Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "Game/StdAfx.h"
- #include "GS3DStuff.h"
- #include "Core/Tools.h"
- #include "Core/Application.h"
- #include "Core/Managers/SoundManager.h"
- #include "Core/Managers/StringManager.h"
- #include "online/OnlineServiceManager.h"
- #include "grapher/GrapherManager.h"
- #include "grapher/Core/ActorContext.h"
- #include "grapher/Core/DebugConstants.h"
- #include "EventManager/EventManager.h"
- #include "Game/AI/AIController.h"
- #include "Game/AI/BehaviorManager.h"
- #include "Game/AI/WantedLevelManager.h"
- #include "Game/Camera/CameraManager.h"
- #include "Game/Cinematics/CinematicManager.h"
- #include "Game/Cinematics/FadeManager.h"
- #include "Game/ControlHandlers/CControlManager.h"
- #include "Game/Decal/DecalManager.h"
- #include "Game/Events/EvTouchScreen.h"
- #include "Game/Objects/Basic/ShopSpawnPoint.h"
- #include "Game/Gangstar/BulletTraceManager.h"
- #include "Game/Gangstar/daytime.h"
- #include "Game/Gangstar/NPC.h"
- #include "Game/Gangstar/Player.h"
- #include "Game/Gangstar/SpawnGroupManager.h"
- #include "Game/Gangstar/Vehicle/Helicopter.h"
- #include "Game/Gangstar/Vehicle/Moto.h"
- #include "Game/Gangstar/Vehicle/Vehicle.h"
- #include "Game/Gangstar/Vehicle/Boat.h"
- #include "Game/Gangstar/Vehicle/Airplane.h"
- #include "Game/GLitchExtensions/CustomGlitchFeatures.h"
- #include "Game/GLitchExtensions/CCustomIngameSceneManager.h"
- #include "Game/GLitchExtensions/CCustomShopSceneManager.h"
- #include "Game/GLitchExtensions/CCustomSceneManagerTweaker.h"
- #include "Game/GlitchExtensions/CCustomIrrFactory.h"
- #include "Game/PostEffects/PostEffects.h"
- #include "Game/Hud/Elements/Screen.h"
- #include "Game/Lights/LightsManager.h"
- #include "Game/Managers/AbilityManager.h"
- #include "Game/Managers/DialogManager.h"
- #include "Game/Managers/ItemManager.h"
- #include "Game/Managers/VFXManager.h"
- #include "Game/Menus/MapHandler/Map.h"
- #include "Game/Menus/flash_constants_generated.h"
- #include "Game/Menus/MapHandler/MapHandler.h"
- #include "Game/Menus/MenuEventManager.h"
- #include "Game/Menus/SwfManager.h"
- #include "Game/Menus/DownloadingContentMenu.h"
- #include "Game/Objects/SpawnManager.h"
- #include "Game/Objects/basic/Transformation.h"
- #include "Game/Objects/Pickupable/PickupableManager.h"
- #include "Game/Objects/Zones/TriggerZone.h"
- #include "Game/PathFinding/NavMeshManager.h"
- #include "Game/Persistence/Preferences.h"
- #include "Game/Scripts/Mission.h"
- #include "Game/Scripts/Race.h"
- #include "Game/States/GSMain.h"
- #include "Game/States/GSFailure.h"
- #include "Game/States/GSBustedMenu.h"
- #include "Game/Story/StoryManager.h"
- #include "Game/Trail/TrailMgr.h"
- #include "Game/Weapon/Projectile.h"
- #include "Game/Weapon/ProjectileManager.h"
- #include "Game/Managers/WeaponryManager.h"
- #include "Game/Gangstar/Inventory.h"
- #include "Game/Weapon/Weapon.h"
- #include "Game/World/GameObjectManager.h"
- #include "Game/World/StockManager.h"
- #include "Game/World/world.h"
- #include "Utils/CGameFactory.h"
- #include "Utils/GameDataFilesMgr.h"
- #include "Utils/LoadTimeProfiling.h"
- #include "Utils/LoadMemoryProfiling.h"
- #include "Utils/LODSceneNode.h"
- #include "utils/LODProfiler/LODProfiler.h"
- #include "Utils/MemLeakAnnihilator.h"
- #include "glitch/collada/CColladaSceneNode.h"
- #include "glitch/collada/CColladaRootSceneNode.h"
- #include "glitch/scene/CBatchSceneNode.h"
- #include "glitch/scene/CLightSceneNode.h"
- #include <glf/io/archivemanager.h>
- #include "IO/DataStream/DataStream.h"
- #include "IO/Audio/SoundEmitter.h"
- #include "StateMachine/StateMachine.h"
- #include "debug/autoTweak.h"
- #include "Game/Physics/PhysicsWorld.h"
- #ifdef SUN_OCCLUSION
- #include "game/SunOcclusion/SunOcclusionManager.h"
- #endif
- #ifdef IRRADIANCE
- #include <glitch/irradiance/CIrradianceManager.h>
- #endif
- #include "Core/Debug/DebugTweakers.h"
- #include "Core/Debug/GrapherTweakers.h"
- #include "Core/Debug/LocationTweakers.h"
- #include "Core/Debug/MissionTweakers.h"
- #include "Core/Debug/TemplateTweakers.h"
- #include <Game/GlitchExtensions/DynamicMaterialProperties.h>
- #include <Game/GlitchExtensions/DynamicDataValues.h>
- #include "Core/Debug/DynamicMaterialPropertiesTweakers.h"
- #include "Core/Debug/PaletteTweakers.h"
- #include "Game/Objects/SpawnTaskImpl.h" //for Random::GetRandom
- #include "Utils/GlitchDropNodeTask.h"
- #include "Game/Gangstar/CityDomination/CityDominationManager.h"
- #include "Online/GVAdsManager.h"
- #include XMLDATA_INCLUDE(script_constants)
- #include XMLDATA_INCLUDE(common_text_generated)
- #include XMLDATA_INCLUDE(locations_)
- #include XMLDATA_INCLUDE(dialogs_)
- #include XMLDATA_INCLUDE(phone_performance_profiles)
- #include XMLDATA_INCLUDE(shader_constants)
- #include XMLDATA_INCLUDE(giv_loot)
- #include XMLDATA_INCLUDE(giv_spawn_manager)
- #include XMLDATA_INCLUDE(giv_shaders)
- #include XMLDATA_INCLUDE(stock_items_struct)
- #include XMLDATA_INCLUDE(giv_daytime)
- #include XMLDATA_INCLUDE(materials_preload_effects)
- #ifdef OS_IPHONE
- #include<sys/sysctl.h>
- int GetPhysicalMemory()
- {
- int param[] = {CTL_HW, HW_PHYSMEM};
- size_t len = sizeof(int);
- int physicalMemory;
- sysctl(param, 2, &physicalMemory, &len, 0, 0);
- return physicalMemory;
- }
- #endif
- extern bool gGlitchPerfEnable2;
- extern bool gGlitchPerfEnable3;
- extern bool s_SaveLoadDoneIAP;
- //////////////////////////////////////////////////////////////////////////////////////
- // private constants
- namespace
- {
- //update physic dt (used for metro)
- #ifdef PHYSICS_USING_ASYNCHRONOUS_UPDATE
- static const float PHYSIC_UPDATE_RATE = 1.0f/120.0f; // Twice as fast as the physics otherwise the transition is not good
- #else
- #ifdef WIN32
- static const float PHYSIC_UPDATE_RATE = 1.0f/240.0f;
- #else
- static const float PHYSIC_UPDATE_RATE = 1.0f/240.0f;
- #endif
- #endif
- // Number of frame on which I want to spread the sun occlusion update. If 0, only update one object at time
- static const int FRAMES_FOR_COMPLETE_SUN_OCCLUSION_UPDATE = 20;
- // Number of frame on which I want to spread the invisible list update
- static const int FRAMES_FOR_COMPLETE_INVISIBLE_LIST_UPDATE = 3;
- // how many seconds does the havok logo has to be on screen?
- static const int HAVOK_LOGO_DELAY = 3;
- // how many seconds does the GIV logo has to be on screen?
- static const int GIV_LOGO_DELAY = 3;
- static const int EXTRA_LOADING_DURATION = 10;
- static const int FRESH_INSTALL_EXTRA_LOADING_DURATION = 20;
- // test app magic std::string - THIS IS HARDCODED IN PYTHON, please DON'T CHANGE!
- static const char* TEST_OK_STRING = "4b3253bb-5283-4b9b-9a04-8bffdc866dc7: APPLICATION OK";
- }
- ///////////////////////////////////////////////////////////////////////////////////////
- bool gEnableEnvironment = true;
- bool gEnableHDWaterRendering = true;
- bool gPrintShapeCount = false;
- bool gDebugTestRay = false;
- bool gTogglePhysic = true;
- bool gDrawDebugOnMap = false;
- bool gDebugCollisionShape = false;
- float gCollisionInstancingRadius = 500.0f;
- bool gDebugCopPosition = false;
- bool g_debugLookAt = false;
- extern bool g_Loading;
- extern bool gDrawWaterNear;
- bool gIsStreamingEnabled = true;
- #if _WIN32
- extern bool gLodProfiling;
- #endif
- float g_collisionFrontDistance = 75.0f; // default 75cm
- float g_collisionUpperDistance = 125.0f; // default 125cm
- /*
- float g_WaterSpeed = 0.22f;
- float g_WaterWavelength = 0.44f;
- float g_WaterAmplitude = 0.1f;
- float g_WaterSpeed2 = 0.07f;
- float g_WaterWavelength2 = 0.35f;
- float g_WaterAmplitude2 = 0.1f;
- */
- glitch::core::vector4df g_WindParams = glitch::core::vector4df(10.f, 8.f, 4.f, 0.5f);
- glitch::core::vector4df g_WindParams2 = glitch::core::vector4df(1.f, 0.f, -1.f, 0.5f);
- float g_WaveUSpeed = 0.f;
- float g_WaveVSpeed = 0.03f;
- float g_NormalTiling = 30.f;
- float g_WaveUSpeed2 = 0.f;
- float g_WaveVSpeed2 = -0.08f;
- float g_NormalTiling2 = 200.f;
- float g_DistortionFactor = 0.03f;
- glitch::video::SColorf g_DeepWaterColor(0.145f, 0.325f, 0.361f, 1.f);
- float g_DeepWaterDistance = 0.f;
- float g_SpecPower = 50.f;
- float g_SpecFactor = 0.8f;
- float g_WaveUSpeedLow = -0.01f;
- float g_WaveVSpeedLow = 0.f;
- float g_NormalTilingLow = 5.f;
- float g_WaveUSpeed2Low = 0.02f;
- float g_WaveVSpeed2Low = 0.f;
- float g_NormalTiling2Low = 25.f;
- float g_GroundGlossiness = 10.f;
- float g_GroundSpecFactor = 15.0f;
- float g_DetailTiling = 3.f;
- float g_DetailAmount = 0.5f;
- float g_GroundVehicleLightGlowOffset = 200.0f;
- float g_GroundVehicleLightGlowOffsetAnamorphic = 100.0f;
- #ifdef DEBUG_VH_CHAR_COLLISION
- bool gDebugBoundingBoxes = true;
- #else
- bool gDebugBoundingBoxes = false;
- #endif
- glitch::core::vector3df GS3DStuff::s_plStart;
- glitch::core::vector3df GS3DStuff::s_plEnd;
- extern int g_fixedTimeStep;
- extern int g_BulletTimeFactor;
- extern bool gCfgEnableHDWaterSupport;
- template<typename T>
- void RemoveZ(T*& node)
- {
- if(node)
- {
- node->remove();
- node = 0;
- }
- }
- template<typename T>
- void DropZ(boost::intrusive_ptr<T>& node)
- {
- if(node)
- {
- node->remove();
- node.reset();
- }
- }
- typedef glitch::video::SVertexStream::SDataAccessor<glitch::core::vector3df> DataAccessorConstVec3;
- typedef glitch::video::SVertexStream::SDataAccessor<glitch::core::vector3df> DataAccessorVec3;
- typedef glitch::video::CPrimitiveStream::SDataAccessor<glitch::u16> DataAccessorConstIdx;
- using namespace glitch;
- using namespace core;
- using namespace scene;
- using namespace video;
- using namespace io;
- using namespace gui;
- #if defined(WIN32)
- unsigned int GS3DStuff::waiting = 0;
- #endif
- BulletTraceManager* GS3DStuff::s_bulletManager = 0;
- TrailMgr* GS3DStuff::s_TrailMgr = 0;
- DecalManager* GS3DStuff::s_DecalManager = 0;
- GameObjectManager* GS3DStuff::gom;
- unsigned int GS3DStuff::s_dt;
- glitch::scene::ISceneNodePtr GS3DStuff::s_MissionTrailSpline;
- Std<glitch::core::vector3df>::Vector GS3DStuff::BufferedLinePositions;
- Std<glitch::video::SColor>::Vector GS3DStuff::BufferedLineColor;
- Std<unsigned short>::Vector GS3DStuff::BufferedLineIndexes;
- glitch::scene::ISceneNodePtr GS3DStuff::gWaterScene = 0;
- glitch::video::ITexturePtr GS3DStuff::s_roadSpecLut = 0;
- glitch::video::ITexturePtr GS3DStuff::s_carSpecLut = 0;
- float GS3DStuff::s_carGlossiness = 0.f;
- float GS3DStuff::s_carSpecFactor = 0.f;
- TriggerZone* GS3DStuff::s_lastTriggerZone = 0;
- float gTimeAccumulator = 0.f;
- int gNumPhysicIteration = 0;
- int currentLocation = -1;
- static std::string currentLocationXML = "";
- static grapher::ActorContext locationContext("locationContext");
- static int gJustUpdateFrame = 0;
- static int gCheckForDespawnFrame = 0;
- StdString GS3DStuff::s_currentCubeMapName;
- bool GS3DStuff::s_isDayEnvMap = true;
- bool GS3DStuff::s_isLogoHasBeenDisplayedEnough = false;
- #if DLC_FLOW_ENABLED
- static bool s_isProcessingMandatoryDlc = false;
- static bool s_isRetryingDownloadMandatoryDlc = true;
- static std::unique_ptr<DownloadingContentMenu> s_dlcMenu;
- #endif
- int gPhonePerfId = -1;
- bool IsAndroid()
- {
- return strstr(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, sdk), "android") != 0;
- }
- bool IsIos()
- {
- return strstr(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, sdk), "ios") != 0;
- }
- glitch::video::E_ORIENTATION GS3DStuff::s_orientation = GS3DStuff::getDefaultOrientation();
- bool GS3DStuff::b_isAutoOri = true;
- Std<VehicleHandle>::Vector GS3DStuff::s_vehicles;
- Std<NPCHandle>::Vector GS3DStuff::s_npcs;
- int GS3DStuff::s_roundRobinNPCIdx = 0;
- Std<PlayerHandle>::Vector GS3DStuff::s_players;
- glitch::scene::ISceneNode* gMiamiAnimScene = 0;
- int64 GS3DStuff::s_worldEventFlags = 0;
- int GS3DStuff::s_streamingState = SS_NONE;
- int GS3DStuff::s_streamingTimer;
- int GS3DStuff::s_streamingDuration;
- int GS3DStuff::s_streamingElapsed;
- bool GS3DStuff::s_skipFadeIn = false;
- bool GS3DStuff::s_loadingDisplayed = false;
- bool GS3DStuff::s_isIrradianceLoaded = false;
- int GS3DStuff::s_sunOcclusionFrameCounter = 0;
- int GS3DStuff::s_sunOcclusionFrameCycle = 5;
- #ifdef __APPLE__
- #include "Utils/mach_thread_helper.h"
- extern MachThreadPolicyManager g_machThreadPolicyManager;
- #endif
- // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- // Ctors / Dtor
- // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- DEFINE_RTTI(GS3DStuff)
- GS3DStuff::GS3DStuff() :
- m_playingAmbient(false)
- {
- m_drawable = false;
- m_updates = 0;
- flushBufferedLines();
- }
- GS3DStuff::~GS3DStuff()
- {
- EventManager::GetInstance()->detach(Events::TOUCHSCREEN_PRESS, this);
- // it will be set to 0 in unload() when we are really exiting the game
- }
- BulletTraceManager* GS3DStuff::GetBulletManager()
- {
- return GS3DStuff::s_bulletManager;
- }
- TrailMgr* GS3DStuff::GetTrailMgr()
- {
- return GS3DStuff::s_TrailMgr;
- }
- glitch::scene::ISceneNodePtr GS3DStuff::GetMissionTrailSpline()
- {
- return GS3DStuff::s_MissionTrailSpline;
- }
- DecalManager* GS3DStuff::GetDecalManager()
- {
- return GS3DStuff::s_DecalManager;
- }
- void GS3DStuff::SetMissionTrailSpline(const char* dbName)
- {
- if (GS3DStuff::s_MissionTrailSpline)
- {
- GS3DStuff::s_MissionTrailSpline->remove();
- GS3DStuff::s_MissionTrailSpline = 0;
- }
- if (dbName && strlen(dbName) > 0)
- {
- GS3DStuff::s_MissionTrailSpline = CustomConstructScene(dbName, HighlightColladaFactory::getInstance(), false, E_CCS_OH_NONE);
- }
- if (GS3DStuff::s_MissionTrailSpline)
- {
- GET_OBJECT_ROOT()->addChild(GS3DStuff::s_MissionTrailSpline);
- glitch::scene::SSceneNodeArray meshNodeList;
- GS3DStuff::s_MissionTrailSpline->getSceneNodesFromType(glitch::scene::ESNT_COLLADA_MESH, meshNodeList);
- for (glitch::scene::SSceneNodeArray::iterator it = meshNodeList.begin(), end = meshNodeList.end(); it != end; ++it)
- {
- glitch::scene::ISceneNodePtr node = *it;
- node->setRenderingLayer(RenderLayers::ECSRL_TRACK_TRAIL);
- }
- }
- }
- int gNumCallAllStreamingDone = 0;
- bool GS3DStuff::IsAllStreamingDone()
- {
- World* world = World::GetInstance();
- return world->IsAllStreamingDone();
- }
- //-------------------------------------------------------------------------------------------------------------------------------------------------------------
- //-------------------------------------------------------------------------------------------------------------------------------------------------------------
- glitch::video::CMaterialPtr GS3DStuff::CreateMaterial(const char* textureName, glitch::video::E_MATERIAL_TYPE type)
- {
- IVideoDriver* driver = GetVideoDriver();
- glitch::video::CMaterialRendererManager& mrm = driver->getMaterialRendererManager();
- glitch::video::CMaterialPtr materialWithTexture = mrm.createMaterialInstance(driver, type);
- #ifdef GLITCH_COMMAND_QUEUE_BRANCH
- glitch::video::ITexturePtr tex = driver->getTextureManager()->getTexture(driver, textureName);
- #else
- glitch::video::ITexturePtr tex = driver->getTextureManager()->getTexture(textureName);
- #endif
- if(tex)
- {
- glitch::u16 texID = materialWithTexture->getParameterID(glitch::video::ESPT_TEXTURE);
- materialWithTexture->setParameter(texID, tex);
- }
- return materialWithTexture;
- }
- void GS3DStuff::ChangeMaterialType(glitch::collada::CMeshSceneNode* node, int matNumber, glitch::u32 type)
- {
- IVideoDriver* driver = GetVideoDriver();
- glitch::video::CMaterialRendererManager& mrm = driver->getMaterialRendererManager();
- glitch::video::ITexturePtr tex;
- glitch::video::CMaterialPtr mat = node->getMaterial(matNumber);
- if(! mat)
- {
- ASSERT(0);
- return;
- }
- glitch::u16 texID = mat->getParameterID(glitch::video::ESPT_TEXTURE);
- glitch::video::CMaterialPtr newMaterial;
- if(type == glitch::video::EMT_UNLIT_NON_TEXTURED_SOLID)
- {
- //HACK for skybox, force to custom material
- const char* effectFile = "./CustomNonTextured.bdae";
- glitch::collada::CColladaDatabase database(effectFile);
- glitch::video::CMaterialRendererPtr materialRenderer = database.constructEffect(GetVideoDriver(), "Custom Unlit Non Textured", 0);
- newMaterial = glitch::video::CMaterial::allocate(materialRenderer);
- newMaterial->setBaseTechnique(materialRenderer->getTechniqueID("default"));
- }
- else
- {
- newMaterial = glitch::video::CMaterial::allocate(mrm.getMaterialRenderer(type)); //mrm.createMaterialInstance(type);
- }
- if(texID != glitch::u16(-1))
- {
- node->getMaterial(matNumber)->getParameter(texID, tex);
- texID = newMaterial->getParameterID(glitch::video::ESPT_TEXTURE);
- newMaterial->setParameter(texID, tex);
- }
- newMaterial->setParameter(newMaterial->getParameterID(glitch::video::ESPT_DIFFUSE_COLOR), glitch::video::SColor(255,255,255,255));
- node->getMesh()->setMaterial(matNumber, newMaterial, 0);
- }
- void GS3DStuff::ChangeMaterialTexture(glitch::video::CMaterialPtr& mat, glitch::video::ITexture* tex)
- {
- if(!mat || !tex)
- return;
- glitch::u16 texID = mat->getParameterID(glitch::video::ESPT_TEXTURE);
- if(texID != glitch::u16(-1))
- {
- glitch::video::ITexturePtr ptr = tex;
- mat->setParameter(texID, ptr);
- }
- }
- void GS3DStuff::ChangeMaterialTexture(glitch::video::CMaterialPtr& mat, glitch::video::ITexturePtr& tex)
- {
- if(!mat || !tex)
- return;
- glitch::u16 texID = mat->getParameterID(glitch::video::ESPT_TEXTURE);
- if(texID != glitch::u16(-1))
- {
- mat->setParameter(texID, tex);
- }
- }
- glitch::u32 GS3DStuff::CreateMaterialRenderer(const char* rendererName, E_CUSTOM_MATERIAL_TYPE type)
- {
- IVideoDriver* driver = GetVideoDriver();
- glitch::video::CMaterialRendererManager& mrm = driver->getMaterialRendererManager();
- glitch::u32 mrId = glitch::u16(-1);
- mrId = mrm.getMaterialRendererID(rendererName);
- if(mrId != glitch::u16(-1))
- {
- return mrId;
- }
- if(type == ECMT_UNLIT_TEXTURED_ALPHATEST_BACKFACE_CULLING)
- {
- int a = 0;
- }
- #if defined(GLITCH_COMPILE_WITH_OPENGL_FIXED_FAMILY)
- glitch::video::SFixedGLShaderVertexState vertexState;
- if(type == ECMT_UNLIT_NON_TEXTURED_BLEND_NO_DEPTH ||
- type == ECMT_UNLIT_NON_TEXTURED_WIREFRAME ||
- type == ECMT_UNLIT_TEXTURED_ALPHATEST_NO_DEPTH ||
- type == ECMT_UNLIT_TEXTURED_ALPHATEST_BACKFACE_CULLING ||
- type == ECMT_UNLIT_TEXTURED_BACKFACE_CULLING ||
- type == ECMT_UNLIT_NON_TEXTURED_NO_COLORMASK)
- {
- vertexState.setLightCount(0);
- }
- else
- {
- vertexState.setLightCount(1);
- }
- vertexState.setShadeModel(glitch::video::ESM_SMOOTH);
- if(type == ECMT_UNLIT_TEXTURED_ALPHATEST_NO_DEPTH)
- {
- vertexState.setFogMode(glitch::video::EFM_LINEAR);
- }
- glitch::video::SFixedGLShaderFragmentState fragmentState;
- if(type == ECMT_UNLIT_TEXTURED_ALPHATEST_NO_DEPTH ||
- type == ECMT_UNLIT_TEXTURED_ALPHATEST_BACKFACE_CULLING ||
- type == ECMT_LIT_TEXTURED_ALPHATEST)
- {
- fragmentState.setAlphaFunc(glitch::video::ECFN_GREATER);
- fragmentState.setAlphaTestEnable(true);
- fragmentState.setActiveUnitCount(1);
- }
- if(type == ECMT_UNLIT_TEXTURED_BACKFACE_CULLING)
- {
- vertexState.setLightCount(0);
- vertexState.setColorMaterialEnable(true);
- fragmentState.setActiveUnitCount(1);
- }
- else if(type == ECMT_LIT_TEXTURED_BACKFACE_CULLING)
- {
- vertexState.setLightCount(1);
- vertexState.setColorMaterialEnable(true);
- fragmentState.setActiveUnitCount(1);
- }
- glitch::video::CFixedGLShaderManager* shaderManager =
- static_cast<glitch::video::CFixedGLShaderManager*>(
- driver->getShaderManager()
- );
- glitch::video::IShaderPtr shader =
- shaderManager->createShader(glitch::core::randomString(14).c_str(),
- vertexState,
- fragmentState);
- #endif
- glitch::video::SRenderPass::SRenderState renderState;
- /* renderState.setCullFaceEnable(true);
- renderState.setCullFace(video::EFS_BACK);
- */
- if(type == ECMT_UNLIT_NON_TEXTURED_BLEND_NO_DEPTH)
- {
- renderState.setDepthTestEnable(false);
- renderState.setBlendEnable(true);
- renderState.setBlendFunc(glitch::video::EBF_SRC_ALPHA, glitch::video::EBF_ONE);
- }
- else if(type == ECMT_UNLIT_NON_TEXTURED_WIREFRAME)
- {
- renderState.setPolygonModeFront(video::EPM_LINE);
- renderState.setPolygonModeBack(video::EPM_LINE);
- }
- else if(type == ECMT_UNLIT_TEXTURED_ALPHATEST_NO_DEPTH)
- {
- renderState.setDepthTestEnable(false);
- renderState.setBlendEnable(false);
- renderState.setDepthMask(false);
- }
- else if(type == ECMT_UNLIT_NON_TEXTURED_NO_COLORMASK)
- {
- renderState.setColorMask(false,false,false,false);
- }
- else if(type == ECMT_UNLIT_TEXTURED_ALPHATEST_BACKFACE_CULLING)
- {
- renderState.setCullFaceEnable(true);
- renderState.setCullFace(video::EFS_BACK);
- }
- else if(type == ECMT_UNLIT_TEXTURED_BACKFACE_CULLING)
- {
- renderState.setCullFaceEnable(true);
- renderState.setCullFace(video::EFS_BACK);
- }
- // Then we generate a material renderer with the shader
- glitch::video::CMaterialRendererManager::SCreationContext ctx;
- mrId = mrm.beginMaterialRenderer(ctx, driver, rendererName);
- if(mrId)
- {
- ctx.beginTechnique(/*"Technique #1"*/glitch::core::randomString(14).c_str());
- #if defined(GLITCH_COMPILE_WITH_OPENGL_FIXED_FAMILY)
- mrm.addRenderPass(shader, renderState);
- #endif
- if(type == ECMT_UNLIT_TEXTURED_ALPHATEST_NO_DEPTH ||
- type == ECMT_UNLIT_TEXTURED_ALPHATEST_BACKFACE_CULLING ||
- type == ECMT_UNLIT_TEXTURED_BACKFACE_CULLING ||
- type == ECMT_LIT_TEXTURED_BACKFACE_CULLING ||
- type == ECMT_LIT_TEXTURED_ALPHATEST)
- {
- glitch::video::CMaterialRendererManager::STemporaryID paramId = ctx.addParameter("texture", glitch::video::ESPT_TEXTURE, glitch::video::ESPVT_TEXTURE_SAMPLER_2D);
- //ESPT_FOG_DENSITY,
- //ESPT_FOG_START_END,
- //ESPT_FOG_COLOR,
- glitch::video::CMaterialRendererManager::STemporaryID techId = ctx.endTechnique(true, 0 /*max material lights*/);
- #if defined(GLITCH_COMPILE_WITH_OPENGL_FIXED_FAMILY)
- mrm.bindParameter(paramId, techId, shader->getParameterID(glitch::video::ESPT_TEXTURE, glitch::video::ESS_VERTEX));
- #endif
- }
- else
- {
- glitch::video::CMaterialRendererManager::STemporaryID techId = ctx.endTechnique(true, 0 /*max material lights*/);
- }
- //glitch::video::CMaterialRendererManager::STemporaryID techId = mrm.endTechnique(true, 0 /*max material lights*/);
- //if(type == ECMT_UNLIT_TEXTURED_ALPHATEST_NO_DEPTH)
- //{
- // //glitch::video::CMaterialRendererManager::STemporaryID paramId = mrm.addParameter("texture", glitch::video::ESPT_TEXTURE, glitch::video::ESPVT_TEXTURE_SAMPLER_2D);
- // mrm.bindParameter(paramId, techId, shader->getID());
- //}
- mrId = mrm.endMaterialRenderer(ctx);
- }
- else
- {
- mrId = mrm.getMaterialRendererID(rendererName);
- }
- return mrId;
- }
- void GS3DStuff::SetDebugDataVisible(glitch::scene::ISceneNode* node, int flag)
- {
- #ifdef GLITCH_RENDER_DEBUG
- if(node)
- {
- node->setDebugDataVisible(flag);
- glitch::scene::SSceneNodeList::iterator it = node->childrenBegin();
- for(; it != node->childrenEnd(); ++it)
- {
- SetDebugDataVisible(&(*it), flag);
- }
- }
- #endif
- }
- void GS3DStuff::drawNode(glitch::scene::ISceneNode* node)
- {
- if(node)
- {
- GS3DStuff::drawPoint(node->getAbsolutePosition(), 0.0f, 5.0f);
- glitch::scene::SSceneNodeList::iterator it = node->childrenBegin();
- for(; it != node->childrenEnd(); ++it)
- {
- drawNode(&(*it));
- }
- }
- }
- void GS3DStuff::SetAlpha(glitch::scene::ISceneNode* _node, const StdString mat_name, const float alpha)
- {
- glitch::scene::ISceneNode* node = _node;
- GLF_ASSERTMSG(node, "For some reasons GetGlitchSceneNode() is NULL!!! Need to find out why.");
- while (node)
- {
- if(node->getType() == glitch::scene::ESNT_COLLADA_ROOT)
- {
- glitch::video::CMaterialPtr material = static_cast<glitch::collada::CRootSceneNode*>(node)->getMaterial(mat_name.c_str(), GetVideoDriver());
- if(material.get())
- {
- glitch::u16 id = material->getParameterID("Object_Alpha");
- if(id != glitch::u16(-1))
- { material->setParameter(id, alpha); }
- }
- break;
- }
- node = node->getParent();
- }
- }
- bool HasVisibleChildren(glitch::scene::ISceneNode* node)
- {
- glitch::scene::SSceneNodeList::iterator it = node->childrenBegin();
- for(; it != node->childrenEnd(); ++it)
- {
- glitch::scene::ISceneNode* child = &(*it);
- if (child->isVisible())
- {
- return true;
- }
- }
- return false;
- }
- glitch::scene::ISceneNode* GS3DStuff::FindAMesh(glitch::scene::ISceneNode* colmap)
- {
- ProfilerScopeScene("FindAMesh", colmap->getUID());
- colmap->updateAbsolutePosition(true);
- glitch::scene::E_SCENE_NODE_TYPE type = colmap->getType();
- bool isMesh =
- type == glitch::scene::ESNT_COLLADA_MESH ||
- type == glitch::scene::ESNT_COLLADA_SKIN_MESH ||
- type == glitch::scene::ESNT_COLLADA_MODULAR_SKIN_MESH;
- if(isMesh && (strstr(colmap->getUID(), "Plane") == 0) && (strstr(colmap->getUID(), "Jump") == 0) && (strstr(colmap->getUID(), "plane") == 0) && (strstr(colmap->getUID(), "jump") == 0) && !colmap->getSceneNodeFromUID("shadow-mesh"))
- {
- return colmap;
- }
- glitch::scene::ISceneNodePtr result = 0;
- glitch::scene::ISceneNodePtr first = 0;
- #ifndef GLITCH_DISABLE_SCENENODE_MULTITHREAD_CHECK
- //this lock is only to disable the what seems like a false positive require lock.
- //I am in the main thread, why the fuck would I need to lock looping on hierarchy.
- glitch::scene::ScopedSceneNodeReadLock readLock(*colmap);
- #endif
- glitch::scene::E_SCENE_NODE_TYPE types[3] = { glitch::scene::ESNT_COLLADA_MESH, glitch::scene::ESNT_COLLADA_SKIN_MESH, glitch::scene::ESNT_COLLADA_MODULAR_SKIN_MESH };
- for(int i = 0; i < 3; i++)
- {
- glitch::scene::SSceneNodeArray skinNodes;
- colmap->getSceneNodesFromType(types[i], skinNodes);
- for(glitch::scene::SSceneNodeArray::iterator it = skinNodes.begin(); it != skinNodes.end(); ++it)
- {
- glitch::scene::ISceneNodePtr node = *it;
- if ((strstr(node->getUID(), "Plane") == 0) && (strstr(node->getUID(), "Jump") == 0) && (strstr(node->getUID(), "plane") == 0) && (strstr(node->getUID(), "jump") == 0) && !node->getSceneNodeFromUID("shadow-mesh"))
- {
- if (node->isVisible() && HasVisibleChildren(node.get()))
- {
- return node.get();
- }
- }
- }
- }
- return colmap;
- }
- glitch::scene::ISceneNode* GS3DStuff::FindNodeByName(glitch::scene::ISceneNode* node, const char* name)
- {
- if(node == 0)
- {
- return 0;
- }
- if(strstr(node->getUID(), name))
- {
- return node;
- }
- //ScopedSceneNodeWriteLock lock(*node);
- glitch::scene::ISceneNode* result = 0;
- glitch::scene::SSceneNodeList::iterator it = node->childrenBegin();
- for(; it != node->childrenEnd(); ++it)
- {
- result = FindNodeByName(&(*it), name);
- if(result)
- {
- return result;
- }
- }
- return 0;
- }
- glitch::scene::ISceneNode* GS3DStuff::FindNodeByType(glitch::scene::ISceneNode* node, int nodeType)
- {
- if(node == 0)
- {
- return 0;
- }
- if(node->getType() == nodeType)
- {
- return node;
- }
- //ScopedSceneNodeWriteLock lock(*node);
- glitch::scene::ISceneNode* result = 0;
- glitch::scene::SSceneNodeList::iterator it = node->childrenBegin();
- for(; it != node->childrenEnd(); ++it)
- {
- result = FindNodeByType(&(*it), nodeType);
- if(result)
- {
- return result;
- }
- }
- return 0;
- }
- // this helps perfs as it removes about 1/3 of useless nodes for skinned animated mesh
- void GS3DStuff::CleanNode(glitch::scene::ISceneNode* Node)
- {
- if(!Node)
- {
- return;
- }
- {
- #ifndef GLITCH_DISABLE_SCENENODE_MULTITHREAD_CHECK
- //this lock is only to disable the what seems like a false positive require lock. Why would I mutex lock a children traversal
- //on a node that I just created and no one knows it exists yet...
- glitch::scene::ScopedSceneNodeReadLock readLock(*Node);
- #endif
- glitch::scene::SSceneNodeList::iterator it = Node->childrenBegin();
- for(; it != Node->childrenEnd();)
- {
- glitch::scene::ISceneNode* node = &(*it);
- ++it;
- CleanNode(node);
- }
- }
- if(strstr(Node->getName(),"_PIVOT") && Node->getChildren().begin() == Node->getChildren().end())
- {
- Node->remove();
- }
- }
- // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- // Methods (StateBase impl.)
- // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::ctor(const StateMachine* sm)
- {
- CHudManager::GetInstance()->show();
- TouchScreenBase::getInstance().clear();
- }
- extern const char* g_batchFileName;
- bool g_isLoadingBatch = false;
- extern bool g_enableViewportConfig;
- #include "utils/memoryMappedFile.h"
- MemoryMappedFile* gIrradiance = 0;
- namespace LoadingSteps
- {
- enum LS
- {
- First = 0,
- SwfInitialization,
- WaitForMandatoryDlc,
- LoadDownloadedArchives,
- PhysicsWorld,
- GameObjectManager,
- Driver,
- City1,
- GrapherInit,
- GrapherConstants,
- GrapherGenerateXML,
- GrapherFiles,
- GrapherEnd,
- PostEffectsInit,
- VFXManagerInit,
- City3_0,
- City3_1,
- City3_2,
- ItemManager,
- WeaponManager,
- Animations,
- GameObjects,
- SpawnManager,
- PhysicAttributes,
- PlayerStep,
- RegisterGameObjects,
- Managers,
- Scripts,
- Tweakers,
- Misc,
- MenuContent,
- LoadSettings,
- LoadSavegame,
- FinalWait,
- End,
- };
- }
- static const int MAX_LOADSTEP_STRINGSIZE = 64;
- static char s_dbg_current_load_step[MAX_LOADSTEP_STRINGSIZE];
- int s_load_step = 0;
- void DBG_DisplayLoadStep(const char* name, int id)
- {
- //if( IsWin32Build() || GET_DEBUG_SWITCH("DisplayLoadStep") )
- {
- MenuDebug::GetInstance()->SetHardcodedText(name);
- glf::Strcpy_s(s_dbg_current_load_step, MAX_LOADSTEP_STRINGSIZE, name);
- }
- }
- // i'm pretty sure it's doable somehow in pre-processor macro, but I got tired of tried failed synthax
- bool TestLoadDbgSwitch(const char* name, int id)
- {
- #if USE_DEBUG_SWITCHES
- static char buf[128];
- sprintf(buf, "%s_%03d_%s", "SkipLoad", id, name);
- return GET_DEBUG_SWITCH("SkipLoad_All_GS3DStuff") || GET_DEBUG_SWITCH(buf);
- #else
- return false;
- #endif
- }
- #if GANGSTAR_RETAIL_BUILD == 0
- int s_dbg_last_load_step = -1;
- #define LOAD_STEP_FORCE_REFRESH_HACK if(s_dbg_last_load_step != s_load_step) { s_dbg_last_load_step = s_load_step; return false;}
- #else
- #define LOAD_STEP_FORCE_REFRESH_HACK
- #endif
- struct TraceLoadTimeGuard
- {
- TraceLoadTimeGuard()
- {
- }
- ~TraceLoadTimeGuard()
- {
- DebugStepLoadingTime(s_dbg_current_load_step);
- }
- };
- void GS3DStuff::loadDebugConstants()
- {
- #if GANGSTAR_ENABLE_DEBUG_CONSTANTS
- std::vector<std::string> cstNames;
- DataMgr()->GetConstantNames(cstNames);
- for(int i = 0; i < cstNames.size(); i++)
- {
- std::vector<std::string> valueNames;
- DataManager::Constant* cst = DataMgr()->GetConstant(cstNames[i].c_str());
- cst->GetValueNames(valueNames);
- for(int j = 0; j < valueNames.size(); j++)
- {
- int value = cst->GetValue(valueNames[j].c_str());
- grapher::DebugConstants::GetInstance().AddConstant(cstNames[i].c_str(), valueNames[j].c_str(), value);
- }
- }
- //also add array indexes as constants...
- std::vector<std::string> arrayNames;
- DataMgr()->GetArrayNames(arrayNames);
- for(int i = 0; i < arrayNames.size(); i++)
- {
- std::vector<std::string> valueNames;
- DataManager::Array* arr = DataMgr()->GetArray(arrayNames[i].c_str());
- arr->GetEntryNames(valueNames);
- for(int j = 0; j < valueNames.size(); j++)
- {
- int value = arr->GetEntryIdx(valueNames[j].c_str());
- grapher::DebugConstants::GetInstance().AddConstant(arrayNames[i].c_str(), valueNames[j].c_str(), value);
- }
- }
- #endif
- }
- struct TraceMemoryGuard
- {
- TraceMemoryGuard()
- {
- }
- ~TraceMemoryGuard()
- {
- DebugStepLoadingMemory(s_dbg_current_load_step);
- }
- };
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- #define LOAD_STEP(name) \
- case name: \
- {\
- DBG_DisplayLoadStep( #name, name );\
- DEBUG_LOADING_TIMES("GS3DStuff loading" #name); \
- LOAD_STEP_FORCE_REFRESH_HACK \
- checkLoadingLogoSwap(); \
- if(TestLoadDbgSwitch(#name, name) == false)\
- {\
- TraceLoadTimeGuard timer;\
- TraceMemoryGuard memoryGuard;\
- #define END_STEP() \
- }\
- UpdateLoadingProgress(GetPercentBasedOnLoadingStep(), true);\
- break;\
- }\
- #define END_STEP_WITHOUT_LOADING_PROGRESS() \
- } \
- UpdateLoadingProgress(GetPercentBasedOnLoadingStep(), false);\
- break; \
- } \
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::checkLoadingLogoSwap()
- {
- if(!Application::s_isShowingHavokLogo || !Application::s_loadingBackground)
- return;
- // make sure we see at least 3 seconds of Havok
- int diff = static_cast<int>(time(0) - Application::s_backgroundScreenTimer);
- if(diff < HAVOK_LOGO_DELAY)
- {
- return;
- }
- GetVideoDriver()->getTextureManager()->removeTexture(Application::s_loadingBackground);
- Application::s_isShowingHavokLogo = false;
- loadGIVLogo();
- }
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::loadGIVLogo()
- {
- //hack so we enable flash rendering only when we reached the splash screen
- SwfManager::s_isRenderingEnabled = true;
- glitch::video::SScopedDriverOption mipmaps(GetVideoDriver(), glitch::video::EVDO_CREATE_TEXTURE_MIPMAPS, false);
- DEBUG_LOADING_TIMES("Load GIV logo");
- const char* texture = DataByIdx(PhonePerformanceProfiles, gPhonePerfId, LoadingTexture);
- #ifdef GLITCH_COMMAND_QUEUE_BRANCH
- Application::s_loadingBackground = GetVideoDriver()->getTextureManager()->getTexture(GetVideoDriver(), texture);
- #else
- Application::s_loadingBackground = GetVideoDriver()->getTextureManager()->getTexture(texture);
- #endif
- Application::s_backgroundScreenTimer = time(0);
- }
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::loadPreSplashscreenLogo(const std::string& textureName)
- {
- // show havok logo
- Application::s_loadingBackground = GetVideoDriver()->getTextureManager()->getTexture(textureName.c_str());
- Application::s_backgroundScreenTimer = time(0);
- Application::s_isShowingHavokLogo = true;
- }
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- bool GS3DStuff::checkIfLogoHasBeenDisplayedEnough()
- {
- int diff = static_cast<int>(time(0) - Application::s_backgroundScreenTimer);
- if(diff < GIV_LOGO_DELAY)
- {
- return false;
- }
- s_isLogoHasBeenDisplayedEnough = true;
- Application::s_backgroundScreenTimer = time(0);
- return true;
- }
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- bool GS3DStuff::checkIsExtraLoadingLimiterReached()
- {
- int diff = static_cast<int>(time(0) - Application::s_backgroundScreenTimer);
- int loadingDuration = ProfileManager::GetInstance()->HasProfile() ? EXTRA_LOADING_DURATION : FRESH_INSTALL_EXTRA_LOADING_DURATION;
- if (diff < loadingDuration)
- {
- return false;
- }
- return true;
- }
- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void LoadGrapher()
- {
- std::string path1(GetGrapherInitPath());
- std::string path2(GetGrapherAIPath());
- if(IsUsingGrapherBinary())
- {
- GrapherMgr()->SetMode(grapher::BIT_BINARY | grapher::BIT_READ);
- }
- GLFUtils::ToLowerCase(path1);
- GLFUtils::ToLowerCase(path2);
- // if archive, ask the list of files to the archive manager
- if(Application::IsUsingArchives)
- {
- glf::core::FileArchive::FileListing list;
- glf::ArchiveManager::GetInstance()->GetFilesInDirectory(path1.c_str(), list);
- GrapherMgr()->LoadActorsFromFilesList(list , true, path1.c_str());
- list.clear();
- glf::ArchiveManager::GetInstance()->GetFilesInDirectory(path2.c_str(), list);
- GrapherMgr()->LoadActorsFromFilesList(list , true, path2.c_str());
- }
- // else load from file system
- else
- {
- GrapherMgr()->LoadActorsFromFolder(path1.c_str(), true, true);
- GrapherMgr()->LoadActorsFromFolder(path2.c_str(), true, true);
- }
- }
- bool GS3DStuff::isGlobalLoadingDone()
- {
- return s_load_step == LoadingSteps::End;
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- // Returns the next step.
- bool GS3DStuff::load()
- {
- //early escape if someone keeps calling this when we are done loading
- if(s_load_step == LoadingSteps::End)
- {
- return true;
- }
- Application* app = Application::GetInstance();
- IDevice* device = app->GetDevice();
- IVideoDriver* driver = device->getVideoDriver();
- CSceneManager* smgr = device->getSceneManager();
- switch(s_load_step)
- {
- LOAD_STEP(LoadingSteps::First)
- {
- // start the gaia request, it might take some time
- OnlineServiceMgr()->Init();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::SwfInitialization)
- {
- GetMenuEventMgr()->BindToUserInterface(SwfManager::GetInstance()->LoadSWFFile(SwfManager::SWF_MAIN, true), true);
- }
- END_STEP()
- #if DLC_FLOW_ENABLED
- LOAD_STEP(LoadingSteps::WaitForMandatoryDlc)
- {
- if (s_isProcessingMandatoryDlc)
- {
- // Return that DLC processing is not finished yet, continue updates looping
- return false;
- }
- else if (s_isRetryingDownloadMandatoryDlc)
- {
- // Create DLC menu, this will start loading the content
- s_dlcMenu.reset(new DownloadingContentMenu(
- { "global_world" },
- // On finished
- [&] { s_isProcessingMandatoryDlc = false; },
- // On error alert tapped
- [&] { s_isRetryingDownloadMandatoryDlc = true; s_isProcessingMandatoryDlc = false; }
- ));
- s_isProcessingMandatoryDlc = true;
- s_isRetryingDownloadMandatoryDlc = false;
- // Return that DLC processing is not finished yet, continue updates looping
- return false;
- }
- else
- {
- // Release DLC states handler and keep moving
- s_dlcMenu.reset();
- }
- }
- END_STEP_WITHOUT_LOADING_PROGRESS()
- #else
- LOAD_STEP(LoadingSteps::WaitForMandatoryDlc)
- {
- // Stub
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::LoadDownloadedArchives)
- {
- app->LoadArchives(ALS_RAW_CONTENT);
- }
- END_STEP()
- #endif
- LOAD_STEP(LoadingSteps::PhysicsWorld)
- {
- #if DLC_FLOW_ENABLED == 0
- app->LoadArchives(ALS_CITY_PHYSICS);
- #endif
- app->LoadHktArchives();
- #ifdef PHYSICS_UPDATE_IN_THREAD
- if (glf::TaskDirector::GetInstance().GetThreadCount<PHYSICS_UPDATE_CPU_ID>() < 1 &&
- DataByIdx(PhonePerformanceProfiles, gPhonePerfId, havokUpdateThreaded))
- {
- glf::TaskThreadData data;
- data.ptr = (void *)(48 * 1024);
- data.stackSize = 256 * 1024; // Default was 128Kb
- glf::TaskDirector::GetInstance().StartThread<PHYSICS_UPDATE_CPU_ID>(1, data, glf::Thread::PRIORITY_NORM);
- }
- #endif
- #ifdef PHYSICS_USING_ASYNCHRONOUS_UPDATE
- // Initialize physics callback for async update
- if (app->GetApplicationMode() == G4AM_REGULAR)
- {
- extern void _AsyncUpdateGame(const float, const bool, const unsigned long);
- PhysicsWorldCInfo worldInfo;
- worldInfo.m_updateGameCallback = _AsyncUpdateGame;
- worldInfo.m_updateGameParam = 0;
- PhysicsWorld::GetInstance()->Init(worldInfo);
- ProjectileManager::CreateInstance();
- }
- #endif
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::GameObjectManager)
- {
- MLA_SET_CONTEXT("LoadingSteps::GameObjectManager");
- GameObjectManager::GetInstance()->Load();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::GrapherInit)
- {
- GrapherMgr()->Init();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::GrapherConstants)
- {
- loadDebugConstants();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::GrapherGenerateXML)
- {
- #if defined(_WIN32) && DATAMGR_XML_HYBRID_ENABLED == 1
- GrapherMgr()->GenerateXMLTemplate();
- grapher::DebugConstants::GetInstance().Export("./grapher_symbols/cst_symbols.txt");
- #endif
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::GrapherFiles)
- {
- LoadGrapher();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::GrapherEnd)
- {
- GrapherMgr()->LoadingFinish();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::PostEffectsInit)
- {
- MLA_SET_CONTEXT("LoadingSteps::PostEffectsInit");
- static_cast<CCustomIngameSceneManager*>(GetSceneMgr())->GetPostEffects()->Init();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::VFXManagerInit)
- {
- MLA_SET_CONTEXT("LoadingSteps::VFXManagerInit");
- VfxMgr()->Init();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::Driver)
- {
- driver->setOption(glitch::video::EVDO_BATCHING, true);
- driver->setOption(glitch::video::EVDO_CREATE_TEXTURE_MIPMAPS, true);
- driver->getTextureManager()->setFlag(glitch::video::CTextureManager::EF_KEEP_CLIENT_DATA, false);
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::City1)
- {
- MLA_SET_CONTEXT("LoadingSteps::City1");
- #if DLC_FLOW_ENABLED == 0
- app->LoadArchives(ALS_CITY_MESHES);
- #endif
- PreloadEffects(driver);
- World* world = World::GetInstance();
- world->LoadWorldParts();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::City3_0)
- {
- MLA_SET_CONTEXT("LoadingSteps::City3_0");
- CCustomIngameSceneManager* smgr = (CCustomIngameSceneManager*)GetDevice()->getSceneManager();
- smgr->CreateLowResCity("./citylowres_batched.bdae");
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::City3_1)
- {
- MLA_SET_CONTEXT("LoadingSteps::City3_1");
- #ifndef IRRADIANCE_SIMULATION
- s_sunOcclusionFrameCycle = Cst(SunOcclusion, FrameToOmit);
- #ifdef IRRADIANCE
- #ifdef DEBUG_IRRADIANCE_SPHERES
- smgr->InitIrradianceSpheres();
- #endif
- #endif
- CameraManager::GetInstance();
- SetCubeMap("city_cube.tga");
- glitch::video::CGlobalMaterialParameterManager* globalParams = GetVideoDriver()->getGlobalMaterialParameters();
- for (int i = 0; i < DataCount(LUT_list); ++i)
- {
- glitch::u16 id = globalParams->getParameterID(DataByIdx(LUT_list, i, GlobalParameterName));
- if (id != glitch::u16(-1)) // Be sure that getParameterID returns unsigned 16bit
- {
- glitch::video::ITexturePtr tex = GetVideoDriver()->getTextureManager()->getTexture(DataByIdx(LUT_list, i, imageFile));
- GLF_ASSERTMSG(tex, "Could not load LUT file: %s", DataByIdx(LUT_list, i, imageFile));
- if (tex)
- {
- tex->setWrap(static_cast<glitch::video::E_TEXTURE_CLAMP>((int)DataByIdx(LUT_list, i, wrap)));
- if (!static_cast<bool>(DataByIdx(LUT_list, i, usemipmaps)))
- {
- tex->setMinFilter(glitch::video::ETFT_LINEAR);
- }
- globalParams->setParameter(id, tex);
- }
- }
- }
- DayTime::Get().init();
- static_cast<CCustomIngameSceneManager*>(GetSceneMgr())->InitShadowMaps();
- static_cast<CCustomShopSceneManager*>(Application::s_sceneManagerMenu.get())->InitShadowMaps();
- #endif
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::City3_2)
- {
- {
- MLA_SET_CONTEXT("LoadingSteps::City3_2");
- gEnableHDWaterRendering = (bool)DataByIdx(PhonePerformanceProfiles, gPhonePerfId, useHDWaterShaders) && gCfgEnableHDWaterSupport;
- CameraManager::GetInstance();
- if (!DataByIdx(PhonePerformanceProfiles, gPhonePerfId, UseLowResWater))
- {
- gWaterScene = CustomConstructScene("./water.bdae", WaterFadeColladaFactory::getInstance(), true, E_CCS_OH_CHILDREN);
- }
- else
- {
- gWaterScene = CustomConstructScene("./water_lowres.bdae", WaterFadeColladaFactory::getInstance(), true, E_CCS_OH_CHILDREN);
- }
- if (gWaterScene)
- {
- GET_OBJECT_ROOT()->addChild(gWaterScene);
- glitch::scene::SSceneNodeArray waterList;
- gWaterScene->getSceneNodesFromType(glitch::scene::ESNT_COLLADA_MESH, waterList);
- for (size_t i = 0; i < waterList.size(); i++)
- {
- //-150 reserved for objects that must be drawn before HD water
- if (strstr(waterList[i]->getParent()->getName(), "foam"))
- {
- waterList[i]->setRenderingLayer(-151);
- }
- else
- {
- waterList[i]->setRenderingLayer(-150);
- }
- }
- }
- glitch::scene::ISceneNodePtr oceanScene = CustomConstructScene("./ocean.bdae", WaterFadeColladaFactory::getInstance(), true, E_CCS_OH_CHILDREN);
- if (oceanScene)
- {
- oceanScene->setAutomaticCulling(glitch::scene::EAC_FRUSTUM_BOX);
- glitch::scene::SSceneNodeArray oceanList;
- oceanScene->getSceneNodesFromType(glitch::scene::ESNT_COLLADA_MESH, oceanList);
- for (size_t i = 0; i < oceanList.size(); i++)
- {
- oceanList[i]->setRenderingLayer(-1341);
- oceanList[i]->getMaterial(0)->setBaseTechnique(gEnableHDWaterRendering && gCfgEnableHDWaterSupport ? 1 : 0);
- }
- CCustomIngameSceneManager* smgr = static_cast<CCustomIngameSceneManager*>(GetDevice()->getSceneManager());
- smgr->MoveToConjointFrustum(oceanScene);
- }
- InitTreeShaders();
- UpdateTreeShaders();
- }
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::ItemManager)
- {
- MLA_SET_CONTEXT("LoadingSteps::ItemManager");
- ItemMgr();
- }
- END_STEP()
- #ifndef IRRADIANCE_SIMULATION
- LOAD_STEP(LoadingSteps::WeaponManager)
- {
- MLA_SET_CONTEXT("LoadingSteps::WeaponManager");
- WeaponryMgr();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::Animations)
- {
- MLA_SET_CONTEXT("LoadingSteps::Animations");
- Character::loadAnimationFiles();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::GameObjects)
- {
- MLA_SET_CONTEXT("LoadingSteps::GameObjects");
- gom = GameObjectManager::GetInstance();
- World* world = World::GetInstance();
- world->LoadLevelDesignXML();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::SpawnManager)
- {
- MLA_SET_CONTEXT("LoadingSteps::SpawnManager");
- SpawnGroupManager::GetInstance()->Load();
- }
- END_STEP()
- #endif
- LOAD_STEP(LoadingSteps::PhysicAttributes)
- {
- MLA_SET_CONTEXT("LoadingSteps::PhysicAttributes");
- SpawnManager::GetInstance()->Init();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::PlayerStep)
- {
- #ifndef IRRADIANCE_SIMULATION
- MLA_SET_CONTEXT("LoadingSteps::PlayerStep");
- CameraManager::GetInstance()->enterMode(CAMERA_MODES::FOLLOW, Player::GetPlayer(), 0);
- GS3DStuff::SwitchLocation(DataIdx(Locations, City));
- World::GetInstance()->UpdateClippingAndStreamingRange();
- Player* mainPlayer = static_cast<Player*>(GameObjectManager::GetInstance()->GetGameObjectByName("Angel_00"));
- GLF_ASSERTMSG(mainPlayer != 0, "Could not find the player in xml, need something named \"Angel_00\"");
- if (mainPlayer)
- {
- mainPlayer->enable();
- mainPlayer->getAIController()->setBehavior(BehaviorManager::PLAYER);
- Player::s_player = mainPlayer;
- WeaponryMgr()->Init();
- Player::GetPlayer()->addToDebugger();
- Player::GetPlayer()->SetUnlimitedAmmo(false);
- GameObjectManager::GetInstance()->Remove(Player::s_player);
- }
- #endif
- Character::InitInteractionFunctors();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::RegisterGameObjects)
- {
- #ifndef IRRADIANCE_SIMULATION
- MLA_SET_CONTEXT("LoadingSteps::RegisterGameObjects");
- // 3 is the number of queues we have
- for(int i=0; i<3; i++)
- {
- LevelObject* lo = gom->GetFirstLo(i);
- while(lo)
- {
- // this helps perfs as it removes about 1/3 of useless nodes for skinned animated mesh
- CleanNode(lo->GetGlitchSceneNode());
- lo = gom->GetNextLo(lo);
- }
- }
- #endif
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::Scripts)
- {
- MLA_SET_CONTEXT("LoadingSteps::Scripts");
- #ifndef IRRADIANCE_SIMULATION
- // From here, the game is loaded properly so that SaveGames should work
- Application::setGameLoaded(true);
- static bool sAlreadyLoaded = false;
- if(sAlreadyLoaded == false) //i'm gonna burn in hell for this...
- {
- MLA_SET_CONTEXT("LoadingSteps::Scripts");
- StoryManager::GetInstance()->getMission()->load();
- StoryManager::GetInstance()->loadReputationLevels();
- sAlreadyLoaded = true;
- }
- {
- MLA_SET_CONTEXT("LoadingSteps::CameraManager");
- CameraManager::GetInstance();
- }
- {
- MLA_SET_CONTEXT("LoadingSteps::BehaviorManager");
- BehaviorManager::GetInstance()->reset();
- #if USE_BIN_BEHAVIORS
- BehaviorManager::GetInstance()->deserialize(BIN_BEHAVIORS_PATH);
- #endif
- }
- #endif
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::Managers)
- {
- MLA_SET_CONTEXT("LoadingSteps::Managers");
- // add bullet trace manager
- s_bulletManager = gll_new BulletTraceManager();
- s_bulletManager->setAutomaticCulling(EAC_BOX);
- GET_OBJECT_ROOT()->addChild(s_bulletManager);
- s_TrailMgr = gll_new TrailMgr();
- s_TrailMgr->Init(6, 80, 0, DEFAULT_TRAIL_LIFE_FRAMES, DEFAULT_TRAIL_WIDTH);
- #ifdef USE_DECAL_MANAGER
- s_DecalManager = gll_new DecalManager();
- #endif
- WantedMgr(); // this should init the wanted level manager
- AbilityMgr(); // this will init the ability manager.
- StockMgr()->Load();
- Player::GetPlayer()->GetInventory()->InitEquipment();
- ItemMgr();
- CityDominationManager::GetInstance();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::Tweakers)
- {
- MLA_SET_CONTEXT("LoadingSteps::Tweakers");
- #if GANGSTAR_RETAIL_BUILD == 0
- CreateTweakers(GetDevice()); //old tweakers creation from gangstar 3
- GrapherTweakers::GetInstance()->GenerateGUI();
- LocationTweakers::GetInstance()->GenerateGUI();
- DebugTweakers::GetInstance()->GenerateGUI();
- TemplateTweakers::GetInstance()->GenerateGUI();
- DynamicMaterialPropertiesTweakers::GetInstance()->GenerateGUI();
- VfxMgr()->GenerateGUI();
- CCustomSceneManagerTweaker::GetInstance()->GenerateGUI();
- #ifdef WIN32
- PaletteTweakerManager::GetInstance()->GenerateGUI();
- #endif
- MissionTweakers::GetInstance()->GenerateGUI();
- #endif
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::Misc)
- {
- MLA_SET_CONTEXT("LoadingSteps::Misc");
- #ifndef IRRADIANCE_SIMULATION
- app->SetDrawAll(true);
- //set the controller to onFoot
- CControlManager* ctrlMgr = Application::GetInstance()->GetControlManager();
- ctrlMgr->init();
- #endif
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::MenuContent)
- {
- MLA_SET_CONTEXT("LoadingSteps::MenuContent");
- MenuMgr::GetInstance()->Init();
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::LoadSettings)
- {
- //Preferences pref;
- //pref.LoadAndApply(false); // false = don't apply basic preferences. This is the only case
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::LoadSavegame)
- {
- }
- END_STEP()
- LOAD_STEP(LoadingSteps::FinalWait)
- {
- if (!s_isLogoHasBeenDisplayedEnough && !checkIfLogoHasBeenDisplayedEnough())
- {
- return false;
- }
- if ((!OnlineServiceMgr()->IsAnyCRMConfigDispatched() ||
- ProfileManager::GetInstance()->GetStartupProfileStatus() == SPS_RETRIEVING) &&
- OnlineServiceMgr()->GetGaia()->IsInitialized())
- {
- if (!checkIsExtraLoadingLimiterReached())
- {
- return false;
- }
- }
- }
- END_STEP()
- }
- s_load_step++;
- if(s_load_step == LoadingSteps::End)
- {
- MenuDebug::GetInstance()->TakeGlobalRessourceSnapshot();
- TouchScreenBase::getInstance().clear();
- MenuDebug::GetInstance()->SetHardcodedText(0);
- Application::GetInstance()->onGameLoaded();
- Application::GetInstance()->LaunchAlertForPushNotif();
- #if _WIN32
- //This does nothing unless we are in "testapplication" mode but called all the in case we change this to be a proper tool callable command line.
- Application::DoXMLDataCompare();
- // are we testing?
- if(Application::s_isTestingFromCommandLine)
- {
- // test "game loaded callback", call it now
- int result = Tools::applicationLoadedCallback();
- if(result)
- {
- // if return is not zero, it's an error, abort!
- std::cout << "\n" << std::flush;
- ExitProcess(result);
- return true;
- }
- // say that everything is OK - I didn't crash before this.
- std::cout << TEST_OK_STRING << std::endl;
- if(Application::s_isTestingFromCommandLineForcing)
- {
- // if we are forcing, don't rely on the game to quit properly.
- std::cout << "\n" << std::flush;
- ExitProcess(0);
- return true;
- }
- // quit the game properly
- CORE()->Stop();
- return true;
- }
- #endif
- }
- return s_load_step == LoadingSteps::End;
- }
- void GS3DStuff::tearDown()
- {
- StockManager::GetInstance()->Free();
- SpawnManager::GetInstance()->UnInit();
- GET_BACKDROP_ROOT()->removeAll();
- //clear the cube map texture.
- GetVideoDriver()->getGlobalMaterialParameters()->setParameter(
- GetVideoDriver()->getGlobalMaterialParameters()->getParameterID("CubeMapSampler"),
- 0);
- if(gWaterScene)
- {
- gWaterScene->remove();
- gWaterScene = 0;
- }
- s_roadSpecLut = 0;
- s_carSpecLut = 0;
- CameraManager::clean();
- GrapherMgr()->ClearAll();
- ItemManager::GetInstance()->Terminate();
- PickupableManager::GetInstance()->Free();
- ProjectileMgr()->Free();
- GameObjectManager::GetInstance()->purge();
- GameObjectManager::GetInstance()->Clear();
- GlitchUtils::WaitOnAllDropGlitchNode();
- Player::DeletePlayer();
- WeaponryMgr()->Release();
- CameraManager::GetInstance()->Free();
- MenuMgr::GetInstance()->GetMapHandler()->Free();
- Character::unloadAnimationFiles();
- BehaviorManager::tearDown();
- Vehicle::DoorsAndSeats::GetInstance()->Clear();
- DayTime::Get().deinit();
- Character::ClearInteractionFunctors();
- //DropZ(sunNode);
- //DropZ(moonNode);
- //DropZ(sunGlow);
- //DropZ(moonGlow);
- //DropZ(usedLightNode);
- //DropZ(lightNode);
- DropZ(gWaterScene);
- //[batchMeshRemoval] s_batchMesh = 0;
- //ScriptManager::GetInstance()->disable();
- SafeDelete(s_TrailMgr);
- #ifdef USE_DECAL_MANAGER
- SafeDelete(s_DecalManager);
- #endif
- if(s_bulletManager)
- {
- GET_OBJECT_ROOT()->removeChild(s_bulletManager);
- //no need to delete, it a glitch ISceneNode, refcount and it gets deleted as soon as we remove it from the root, since we only have a c style ptr to it. (not refcounted by game)
- //SafeDelete(s_bulletManager);
- }
- //SndMgr()->clear();
- AnimationManager::deleteInstance();
- #ifdef IS_BATCHGENERATOR
- void ClearMapTexMat();
- ClearMapTexMat();
- #endif
- PhysicsWorld::DestroyInstance();
- }
- void GS3DStuff::unload()
- {
- SndMgr()->Execute(eSO_Stop, "sfx");
- }
- void GS3DStuff::dtor(const StateMachine* sm)
- {
- tearDown();
- }
- void GS3DStuff::onEvent(const IEvent* ev, const EventManager* evMgr)
- {
- // SCOPE_TRACE("DBG", "%i\n", ev->getEventID());
- switch(ev->getEventID())
- {
- case Events::TOUCHSCREEN_PRESS:
- // SCOPE_TRACE("DBG", "TOUCHSCREEN_PRESS\n");
- break;
- }
- }
- bool gIsStreaming = false;
- bool gFlushMemoryMap = false;
- int gFlushMemoryMapFrameInterval = -1;
- int gFlushMemoryMapFrameCounter = 0;
- void GS3DStuff::update(StateMachine* sm)
- {
- #ifdef __APPLE__
- if(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, useMachThreadPolicy))
- {
- const bool switchOn = isInGame();
- g_machThreadPolicyManager.Update(switchOn);
- }
- #endif
- Application* app = Application::GetInstance();
- // [ICH] shader global time hack to avoid precision problem
- glitch::video::CGlobalMaterialParameterManager* globalParams = GetVideoDriver()->getGlobalMaterialParameters();
- glitch::u16 timeId = globalParams->getParameterID("MyGlobalTime");
- if (timeId != u16(-1))
- {
- float value = 0;
- globalParams->getParameter(timeId, value);
- value += GS3DStuff::getDT() * MILLISEC_TO_SEC;
- if (value > 240.0f)
- {
- value = 0.0f;
- }
- globalParams->setParameter(timeId, value);
- }
- #if _WIN32
- if(gLodProfiling && Player::GetPlayer())
- {
- if(!LODProfiler::GetInstance()->Update())
- {
- LODProfiler::GetInstance()->PostProcess();
- exit(1);
- }
- }
- if(app->IsRenderingCinematic() && app->IsRenderingCinematicDone())
- {
- exit(1);
- }
- #endif
- glitch::core::dimension2d<s32> size = GetVideoDriver()->getCurrentRenderTarget()->getSize();
- if(gFlushMemoryMapFrameInterval > 0)
- {
- ++gFlushMemoryMapFrameCounter;
- }
- if(gFlushMemoryMap || (gFlushMemoryMapFrameInterval > 0 && gFlushMemoryMapFrameCounter >= gFlushMemoryMapFrameInterval))
- {
- ProfilerScopeScene("flush memory map", NULL);
- gFlushMemoryMap = false;
- gFlushMemoryMapFrameCounter = 0;
- }
- s_dt = StateMachine::GetInstance()->getTimeStamp();
- //unsigned int s_dt_tmp = StateMachine::GetInstance()->getTimeStamp();
- //SCOPE_TRACE("DBG", "%d is not the same as %d\n",s_dt,s_dt_tmp);
- //s_dt = s_dt_tmp;
- if(s_streamingState != SS_NONE)
- {
- ProfilerScopeScene("streaming update", NULL);
- streamingUpdate(s_dt);
- }
- else
- {
- // Just in case, be sure that the loading icon is gone
- Application::GetInstance()->WatchDogForLoadingTime(false);
- }
- //update this asap so hopeful the spawntaskimpl will start WAYYYYYYYYYY before havok.
- SpawnManager::GetInstance()->Update();
- UpdateDayTime();
- if(CHudManager::GetInstance()->getScreen())
- {
- CHudManager::GetInstance()->getScreen()->setupScreenZones();
- }
- UpdateBehaviors();
- UpdateInvisibles();
- UpdateVisibles();
- UpdatePurgeGameObjectAndTriggerZone();
- UpdateCharacters();
- UpdateVehicles();
- UpdatePhysics();
- UpdateCamera();
- UpdateVehicleNodeAndProximity();
- UpdateScripts();
- UpdateWantedAndTrail();
- UpdateAttachDSP();
- UpdateSunOcclusion();
- // the following greatly helps perfs as it pre-cull every dynamic object against the camera AABB
- // the main bottleneck in irrlicht being the number of node flagged as visible going through the animation transformation process
- /* lo = gom->GetFirstLo();
- glitch::core::aabbox3df camBox = CameraManager::GetInstance()->getCamera()->getViewFrustum()->getBoundingBox();
- while(lo)
- {
- //lo->GetGlitchSceneNode()->setVisible(false);
- if (!lo->GetGlitchSceneNode()->getTransformedBoundingBox().intersectsWithBox(camBox))
- lo->GetGlitchSceneNode()->setVisible(false);
- lo = gom->GetNextLo(lo);
- }*/
- if(!m_drawable)
- {
- if(m_updates > 0) //Skip 2 draws
- {
- m_drawable = true;
- EventManager::GetInstance()->attach(Events::TOUCHSCREEN_PRESS, this);
- //CameraManager::GetInstance()->enterMode(CAMERA_MODES::FOLLOW, Player::GetPlayer(), 0.0f);
- }
- m_updates++;
- }
- static bool isFirstFrame = true;
- // set the LOD Ranges mode
- bool useAlternateLodRanges = false;
- if(Player::GetPlayer() && Player::GetPlayer()->isInAVehicle())
- {
- useAlternateLodRanges = true;
- }
- World::GetInstance()->setUseAlternateLodRanges(useAlternateLodRanges);
- const glitch::scene::ICameraSceneNodePtr camera = app->GetDevice()->getSceneManager()->getActiveCamera();
- const glitch::scene::SViewFrustum* frustum = camera->getViewFrustum();
- if(gIsStreamingEnabled)
- {
- glitch::core::vector3df position = camera->getAbsolutePosition();
- World::GetInstance()->UpdateStreaming(position);
- }
- World::GetInstance()->Update(s_dt);
- isFirstFrame = false;
- if(GET_DEBUG_SWITCH("DrawPermanentLine"))
- {
- GS3DStuff::drawLine(s_plStart, s_plEnd, 0.0f, glitch::video::SColor(255, 200, 0 , 0));
- }
- //Order is not that much important for this,
- PickupableManager::GetInstance()->Update(s_dt);
- ProjectileMgr()->Update(s_dt);
- s_sunOcclusionFrameCounter = (s_sunOcclusionFrameCounter + 1) % s_sunOcclusionFrameCycle;
- }
- void GS3DStuff::UpdateMaterialTechniques()
- {
- #ifdef IRRADIANCE
- LevelObject* lo = gom->GetFirstLo(Kst(ObjectFrameActions, UpdateAndDraw));
- while(lo)
- {
- LevelObject* next = gom->GetNextLo(lo);
- if(lo->IsVisible())
- {
- if(GameObjectManager::isCharacter(lo))
- {
- lo->updateShaderTechnique(LightsManager::GetInstance()->IsCurrentLightZoneInterior());
- Character* character = static_cast<Character*>(lo);
- Weapon* weapon = character->getWeapon();
- if(weapon)
- {
- weapon->updateShaderTechnique(LightsManager::GetInstance()->IsCurrentLightZoneInterior());
- }
- }
- }
- lo = next;
- }
- Player::GetPlayer()->updateShaderTechnique(LightsManager::GetInstance()->IsCurrentLightZoneInterior());
- Inventory* inventory = Player::GetPlayer()->GetInventory();
- if (inventory)
- {
- int slot = inventory->GetCurrentWeaponSlot();
- int slot_end = slot;
- do
- {
- Weapon* weapon = inventory->GetWeapon(slot);
- if (weapon)
- {
- weapon->updateShaderTechnique(LightsManager::GetInstance()->IsCurrentLightZoneInterior());
- }
- slot = inventory->GetNextWeaponSlot(1,slot);
- }
- while (slot != slot_end);
- }
- #endif
- }
- void GS3DStuff::pause(const StateMachine* sm)
- {
- if(OnlineServiceMgr()->GetBITracker())
- {
- if(StoryManager::GetInstance()->isInMission())
- {
- OnlineServiceMgr()->GetBITracker()->UpdateMissionTimeSpent(true);
- }
- }
- SndMgr()->Execute(eSO_Pause);
- #ifdef __APPLE__
- if(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, useMachThreadPolicy))
- {
- g_machThreadPolicyManager.Update(false);
- }
- #endif
- }
- void GS3DStuff::resume(const StateMachine* sm)
- {
- if(OnlineServiceMgr()->GetBITracker())
- {
- if(StoryManager::GetInstance()->isInMission())
- {
- OnlineServiceMgr()->GetBITracker()->UpdateMissionTimeSpent(false);
- }
- }
- TouchScreenBase::getInstance().clear();
- SndMgr()->Execute(eSO_Resume);
- }
- void GS3DStuff::wakeup(const StateMachine* sm)
- {
- TouchScreenBase::getInstance().clear();
- }
- void drawBox(const glitch::core::aabbox3df& bbox, const glitch::video::SColor& color)
- {
- glitch::core::vector3df point1(bbox.MaxEdge.getX(), bbox.MaxEdge.getY(), bbox.MaxEdge.getZ());
- glitch::core::vector3df point2(bbox.MaxEdge.getX(), bbox.MaxEdge.getY(), bbox.MinEdge.getZ());
- glitch::core::vector3df point3(bbox.MinEdge.getX(), bbox.MaxEdge.getY(), bbox.MinEdge.getZ());
- glitch::core::vector3df point4(bbox.MinEdge.getX(), bbox.MaxEdge.getY(), bbox.MaxEdge.getZ());
- glitch::core::vector3df point5(bbox.MinEdge.getX(), bbox.MinEdge.getY(), bbox.MinEdge.getZ());
- glitch::core::vector3df point6(bbox.MaxEdge.getX(), bbox.MinEdge.getY(), bbox.MinEdge.getZ());
- glitch::core::vector3df point7(bbox.MaxEdge.getX(), bbox.MinEdge.getY(), bbox.MaxEdge.getZ());
- glitch::core::vector3df point8(bbox.MinEdge.getX(), bbox.MinEdge.getY(), bbox.MaxEdge.getZ());
- GS3DStuff::draw3DLineBuffered(point1, point2, color);
- GS3DStuff::draw3DLineBuffered(point2, point3, color);
- GS3DStuff::draw3DLineBuffered(point3, point4, color);
- GS3DStuff::draw3DLineBuffered(point4, point1, color);
- GS3DStuff::draw3DLineBuffered(point5, point6, color);
- GS3DStuff::draw3DLineBuffered(point6, point7, color);
- GS3DStuff::draw3DLineBuffered(point7, point8, color);
- GS3DStuff::draw3DLineBuffered(point8, point5, color);
- GS3DStuff::draw3DLineBuffered(point1, point7, color);
- GS3DStuff::draw3DLineBuffered(point2, point6, color);
- GS3DStuff::draw3DLineBuffered(point5, point3, color);
- GS3DStuff::draw3DLineBuffered(point4, point8, color);
- }
- void GS3DStuff::drawBox(const glitch::core::vector3df center, const glitch::video::SColor& color)
- {
- glitch::core::vector3df radius(5.0f,5.0f,5.0f);
- const glitch::core::aabbox3df aabb(center-radius, center+radius);
- ::drawBox(aabb, color);
- }
- void drawBox(const glitch::core::aabbox3df& bbox)
- {
- glitch::core::vector3df point1(bbox.MaxEdge.getX(), bbox.MaxEdge.getY(), bbox.MaxEdge.getZ());
- glitch::core::vector3df point2(bbox.MaxEdge.getX(), bbox.MaxEdge.getY(), bbox.MinEdge.getZ());
- glitch::core::vector3df point3(bbox.MinEdge.getX(), bbox.MaxEdge.getY(), bbox.MinEdge.getZ());
- glitch::core::vector3df point4(bbox.MinEdge.getX(), bbox.MaxEdge.getY(), bbox.MaxEdge.getZ());
- glitch::core::vector3df point5(bbox.MinEdge.getX(), bbox.MinEdge.getY(), bbox.MinEdge.getZ());
- glitch::core::vector3df point6(bbox.MaxEdge.getX(), bbox.MinEdge.getY(), bbox.MinEdge.getZ());
- glitch::core::vector3df point7(bbox.MaxEdge.getX(), bbox.MinEdge.getY(), bbox.MaxEdge.getZ());
- glitch::core::vector3df point8(bbox.MinEdge.getX(), bbox.MinEdge.getY(), bbox.MaxEdge.getZ());
- GS3DStuff::draw3DLineBuffered(point1, point2, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point2, point3, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point3, point4, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point4, point1, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point5, point6, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point6, point7, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point7, point8, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point8, point5, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point1, point7, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point2, point6, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point5, point3, glitch::video::SColor(255, 0, 0, 0));
- GS3DStuff::draw3DLineBuffered(point4, point8, glitch::video::SColor(255, 0, 0, 0));
- }
- void GS3DStuff::draw(const StateMachine* sm)
- {
- }
- void drawTurning(glitch::scene::ISceneNode* p);
- void GS3DStuff::drawSkeleton(glitch::scene::ISceneNode* p)
- {
- //glitch::scene::ScopedSceneNodeReadLock readLock(*p);
- glitch::core::vector3df s = p->getAbsolutePosition();
- for(glitch::scene::SSceneNodeList::iterator it = p->childrenBegin(); it != p->childrenEnd(); ++it)
- {
- glitch::scene::ISceneNode* c = &*it;
- //if (c->getType() == glitch::scene::ESNT_EMPTY)
- if((strstr(c->getName(), "root") || strstr(c->getName(), "Bip01")) && !strstr(c->getName(), "Ragdoll"))
- {
- glitch::core::vector3df e = c->getAbsolutePosition();
- GS3DStuff::draw3DLineBuffered(s, e, glitch::video::SColor(0, 0, 255, 0));
- drawSkeleton(c);
- //if(strcmp(c->getName(), "Bip01") == 0)
- //{
- // drawTurning(c);
- //}
- }
- //else if (strstr("char_maincharacter", c->getName()))
- //{
- // c->setVisible(false);
- //}
- }
- }
- void drawTurning(glitch::scene::ISceneNode* p)
- {
- glitch::core::vector3df s = p->getAbsolutePosition();
- glitch::core::vector3df n = Player::GetPlayer()->getNeckNode()->getAbsolutePosition();
- const glitch::core::matrix4& mtx = p->getAbsoluteTransformation();
- glitch::core::quaternion rot = mtx;
- glitch::core::vector3df front = rot * glitch::core::vector3df(0.f, -1.f, 0.f); // GetFront();
- glitch::core::vector3df right = rot * glitch::core::vector3df(-1.f, 0.f, 0.f); // GetRight();
- front.z() = 0.f;
- right.z() = 0.f;
- front.normalize();
- right.normalize();
- GS3DStuff::draw3DLineBuffered(s, s + front * 50.0f, glitch::video::SColor(0, 255, 0, 0));
- GS3DStuff::draw3DLineBuffered(s, s + right * 50.0f, glitch::video::SColor(0, 0, 255, 0));
- if(Player::GetPlayer()->isTurning())
- {
- GS3DStuff::draw3DLineBuffered(s, s + Player::GetPlayer()->m_targetTurningFront * 50.0f, glitch::video::SColor(0, 0, 0, 255));
- GS3DStuff::draw3DLineBuffered(s, s + rot * Player::GetPlayer()->m_paramDir.get() * 50.0f, glitch::video::SColor(0, 255, 255, 255));
- GS3DStuff::draw3DLineBuffered(s, s + rot * Player::GetPlayer()->m_paramDirOut * 50.0f, glitch::video::SColor(0, 255, 0, 255));
- }
- //if (Player::GetPlayer()->isAiming())
- //{
- GS3DStuff::draw3DLineBuffered(n, n + rot * Player::GetPlayer()->m_AimDir.get() * 50.0f, glitch::video::SColor(0, 255, 255, 0));
- GS3DStuff::draw3DLineBuffered(n, n + Player::GetPlayer()->m_aimingStartFront * 50.0f, glitch::video::SColor(0, 255, 255, 255));
- GS3DStuff::draw3DLineBuffered(n, n + rot * Player::GetPlayer()->m_LastParamOut * 50.0f, glitch::video::SColor(0, 255, 0, 255));
- //}
- glitch::core::matrix4 m = Player::GetPlayer()->getMotionNode()->getAbsoluteTransformation();
- GS3DStuff::draw3DLineBuffered(Player::GetPlayer()->getMotionNode()->getAbsolutePosition(), Player::GetPlayer()->getMotionNode()->getAbsolutePosition() + glitch::core::vector3df(m[4], m[5], m[6]) * 50.0f, glitch::video::SColor(0, 255, 0, 0));
- }
- void GS3DStuff::drawBBoxes(glitch::scene::ISceneNode* node)
- {
- GS3DStuff::draw3dAABB(node->getTransformedBoundingBox(), glitch::video::SColor(255, 255, 0, 0));
- for (glitch::scene::SSceneNodeList::iterator it = node->childrenBegin(); it != node->childrenEnd(); ++it)
- {
- glitch::scene::ISceneNode* n = it.operator->();
- drawBBoxes(n);
- }
- }
- void GS3DStuff::draw()
- {
- bool _debug = false;
- #if defined(DEBUG_CAMERA) || defined(DEBUG_PLAYER) || defined(DEBUG_VEHICLE) || defined(DEBUG_PICKABLES) || defined(DEBUG_SIDE_MISSIONS) || defined(DEBUG_HELI) || defined(DEBUG_DUMMIES)
- _debug = true;
- #endif
- if(gDebugCollisionShape || gDebugBoundingBoxes || g_debugLookAt)
- {
- _debug = true;
- }
- glitch::video::IVideoDriver* vd = 0;
- if(_debug)
- {
- vd = GetVideoDriver();
- CMaterialRendererManager& mrm = vd->getMaterialRendererManager();
- vd->setMaterial(mrm.getMaterialInstance(vd, glitch::video::EMT_UNLIT_NON_TEXTURED_SOLID));
- vd->setTransform(glitch::video::ETS_WORLD,glitch::core::matrix4());
- vd->setOption(video::EVDO_RETAIN_BATCH_ON_MISS, true);
- }
- if(gDebugBoundingBoxes)
- {
- GameObjectManager* gom = GameObjectManager::GetInstance();
- LevelObject* lo = gom->GetFirstLo(Kst(ObjectFrameActions, UpdateAndDraw));
- // draw the bounding box of the player
- if(Player::GetPlayer()->IsVisible())
- {
- glitch::core::vector3df center = Player::GetPlayer()->GetPosition() + Player::GetPlayer()->GetFront() * g_collisionFrontDistance +
- glitch::core::vector3df(0, 0, g_collisionUpperDistance);
- glitch::core::aabbox3df centerBox(center - glitch::core::vector3df(10, 10, 10.0f),
- center + glitch::core::vector3df(10, 10, 10.0f));
- ::drawBox(centerBox);
- center = Player::GetPlayer()->GetPosition() + glitch::core::vector3df(0, 0, g_collisionUpperDistance) - Player::GetPlayer()->GetFront() * 30.0f;
- centerBox = glitch::core::aabbox3df(center - glitch::core::vector3df(10, 10, 10.0f),
- center + glitch::core::vector3df(10, 10, 10.0f));
- ::drawBox(centerBox);
- center = Player::GetPlayer()->GetPosition();
- centerBox = glitch::core::aabbox3df(center - glitch::core::vector3df(10, 10, 10.0f),
- center + glitch::core::vector3df(10, 10, 10.0f));
- ::drawBox(centerBox);
- center = Player::GetPlayer()->GetPosition() + glitch::core::vector3df(0, 0, -100);
- centerBox = glitch::core::aabbox3df(center - glitch::core::vector3df(10, 10, 10.0f),
- center + glitch::core::vector3df(10, 10, 10.0f));
- ::drawBox(centerBox);
- ::drawBox(Player::GetPlayer()->getBoundingBox());
- }
- while(lo)
- {
- glitch::core::aabbox3df bbox;
- if(GameObjectManager::isVehicle(lo))
- {
- Vehicle* v = static_cast<Vehicle*>(lo);
- bbox = v->getMesh()->getTransformedBoundingBox();
- }
- ::drawBox(bbox);
- lo = gom->GetNextLo(lo);
- }
- }
- if(g_debugLookAt)
- {
- CameraManager* camMgr = CameraManager::GetInstance();
- glitch::core::vector3df pos = camMgr->getLookAtPosition();
- GS3DStuff::draw3DLineBuffered(pos, pos-camMgr->getLookAtFront()*100, glitch::video::SColor(255, 255, 0, 0));
- GS3DStuff::draw3DLineBuffered(pos, pos+camMgr->getLookAtRight()*100, glitch::video::SColor(255, 0, 255, 0));
- GS3DStuff::draw3DLineBuffered(pos, pos+camMgr->getLookAtUp()*100, glitch::video::SColor(255, 0, 0, 255));
- }
- #define HEX_COLOR(hex) glitch::video::SColor(255, ((hex)>>16)&0xff, ((hex)>>8)&0xff, ((hex)>>0)&0xff)
- if(gDebugCopPosition)
- {
- GameObjectManager* gom = GameObjectManager::GetInstance();
- LevelObject* obj = gom->GetFirstLo(Kst(ObjectFrameActions, UpdateAndDraw));
- while(obj)
- {
- if(obj->IsCop())
- {
- glitch::core::vector3df pA(Player::GetPlayer()->GetPosition());
- glitch::core::vector3df pB(obj->GetPosition());
- pA.setZ(pA.getZ()+100);
- pB.setZ(pB.getZ()+100);
- glitch::video::SColor color(255,0,0,0);
- GS3DStuff::draw3DLineBuffered(pA, pB, color);
- }
- obj = gom->GetNextLo(obj);
- }
- }
- if(GET_DEBUG_SWITCH("DrawSkeleton"))
- {
- Player::GetPlayer()->GetGlitchSceneNode()->updateAbsolutePosition(true);
- drawSkeleton(Player::GetPlayer()->GetGlitchSceneNode());
- drawTurning(Player::GetPlayer()->GetGlitchSceneNode());
- GameObjectManager* gom = GameObjectManager::GetInstance();
- LevelObject* obj = gom->GetFirstLo(Kst(ObjectFrameActions, UpdateAndDraw));
- while(obj)
- {
- if(gom->isCharacter(obj))
- {
- if(obj->GetGlitchSceneNode())
- {
- obj->GetGlitchSceneNode()->updateAbsolutePosition(true);
- drawSkeleton(obj->GetGlitchSceneNode());
- }
- }
- obj = gom->GetNextLo(obj);
- }
- }
- if(gDebugCollisionShape)
- {
- //SCOPE_TRACE("DBG", "Dynamic body count: %d\n", bodyCnt);
- glitch::core::vector3df front = Player::GetPlayer()->GetFront();
- glitch::core::vector3df right = Player::GetPlayer()->GetRight();
- glitch::core::vector3df pos = Player::GetPlayer()->GetPosition();
- glitch::core::vector3df x_start(pos.getX() - 100, pos.getY(), pos.getZ());
- glitch::core::vector3df x_end(pos.getX() + 100, pos.getY(), pos.getZ());
- glitch::core::vector3df y_start(pos.getX(), pos.getY()-100, pos.getZ());
- glitch::core::vector3df y_end(pos.getX(), pos.getY()+100, pos.getZ());
- GS3DStuff::draw3DLineBuffered(x_start, x_end, glitch::video::SColor(255,0,0,0));
- GS3DStuff::draw3DLineBuffered(y_start, y_end, glitch::video::SColor(255,0,0,0));
- pos[2] += 200;
- GS3DStuff::draw3DLineBuffered(pos, pos + front*100, glitch::video::SColor(255,255,0,0));
- GS3DStuff::draw3DLineBuffered(pos, pos + right*100, glitch::video::SColor(255,0,255,0));
- }
- #ifdef DEBUG_DUMMIES
- {
- GameObjectManager* gom = GameObjectManager::GetInstance();
- LevelObject* lo = gom->GetFirstLo(Kst(ObjectFrameActions, UpdateAndDraw));
- while(lo)
- {
- if(gom->isVehicle(lo))
- {
- Vehicle* veh = static_cast<Vehicle*>(lo);
- glitch::scene::ISceneNode* dummy = veh->getLeftDummy();
- glitch::core::vector3df end = dummy->getAbsolutePosition();
- end[2] += 200;
- GS3DStuff::draw3DLineBuffered(dummy->getAbsolutePosition(), end, glitch::video::SColor(255,0,0,255));
- /*
- glitch::core::vector3df dummy_pos = dummy->getAbsolutePosition();
- glitch::core::aabbox3df leftbbox = dummy->getBoundingBox();
- glitch::core::vector3df max = leftbbox.MaxEdge;
- leftbbox.MaxEdge = glitch::core::vector3df(max.getX()+dummy_pos.getX(), max.getY()+dummy_pos.getY(), max.getZ()+dummy_pos.getZ());
- glitch::core::vector3df min = leftbbox.MinEdge;
- leftbbox.MinEdge = glitch::core::vector3df(min.getX()+dummy_pos.getX(), min.getY()+dummy_pos.getY(), min.getZ()+dummy_pos.getZ());
- draw3dAABB(leftbbox, glitch::video::SColor(255,0,128,128));
- */
- dummy = veh->getRightDummy();
- end = dummy->getAbsolutePosition();
- end[2] += 200;
- GS3DStuff::draw3DLineBuffered(dummy->getAbsolutePosition(), end, glitch::video::SColor(255,0,0,255));
- /*
- dummy_pos = dummy->getAbsolutePosition();
- glitch::core::aabbox3df rightbbox = dummy->getBoundingBox();
- max = rightbbox.MaxEdge;
- rightbbox.MaxEdge = glitch::core::vector3df(max.getX()+dummy_pos.getX(), max.getY()+dummy_pos.getY(), max.getZ()+dummy_pos.getZ());
- min = rightbbox.MinEdge;
- rightbbox.MinEdge = glitch::core::vector3df(min.getX()+dummy_pos.getX(), min.getY()+dummy_pos.getY(), min.getZ()+dummy_pos.getZ());
- draw3dAABB(rightbbox, glitch::video::SColor(255,0,128,128));
- */
- }
- lo = GameObjectManager::GetInstance()->GetNextLo(lo);
- }
- }
- #endif
- #ifdef DEBUG_CAMERA
- {
- CameraManager::GetInstance()->debug(vd);
- }
- #endif // DEBUG_CAMERA
- #ifdef DEBUG_PLAYER
- {
- player->debug(vd);
- }
- #endif // DEBUG_PLAYER
- #ifdef DEBUG_VEHICLE
- {
- if(player->getVehicle() != 0)
- {
- player->getVehicle()->debug(vd);
- }
- }
- #endif // DEBUG_VEHICLE
- #ifdef DEBUG_PICKABLES
- {
- GameObjectManager* gom = GameObjectManager::GetInstance();
- LevelObject* lo = gom->GetFirstLo(Kst(ObjectFrameActions, UpdateAndDraw));
- while(lo)
- {
- lo->debug(vd);
- lo = gom->GetNextLo(lo);
- }
- }
- #endif // DEBUG_PICKABLES
- if(vd)
- {
- vd->setOption(video::EVDO_RETAIN_BATCH_ON_MISS, false);
- }
- }
- void GS3DStuff::draw2d(const StateMachine* sm)
- {
- if(s_streamingState != SS_NONE)
- {
- streamingDraw2d();
- }
- }
- Vehicle* GS3DStuff::getClosestVehicle(Character* c)
- {
- Vehicle* vehicle = 0;
- float distance = 0;
- float shortest = 0;
- glitch::scene::ISceneNode* doorNode = 0;
- for(int i = 0; i < s_vehicles.size(); i++)
- {
- Vehicle* v_tmp = s_vehicles[i];
- if (!v_tmp
- || !v_tmp->canBeEntered(c)
- || v_tmp->getDriver() && !v_tmp->canOccupantsCanBeHijacked())
- {
- continue;
- }
- const bool canInteract = c->checkVehicleInteractionAndDistance(v_tmp,distance);
- if (canInteract && distance)
- {
- if(!vehicle || distance < shortest)
- {
- vehicle = v_tmp;
- shortest = distance;
- }
- }
- }
- return vehicle;
- }
- bool GS3DStuff::checkVehicleProximity(Character* c)
- {
- if(Application::getTime() < c->m_lastProximityCheck + 250)
- {
- return false;
- }
- c->m_lastProximityCheck = Application::getTime();
- if(c->canEnterVehicle())
- {
- Vehicle* vehicle = getClosestVehicle(c);
- if(vehicle && vehicle->isAlive())
- {
- c->setClosestVehicle(vehicle);
- return true;
- }
- }
- c->setClosestVehicle(0);
- return false;
- }
- //////////////////////////////////////////////////////////////////////////
- ShopSpawnPoint* GS3DStuff::getClosestShopSpawnPoint(Character* c, Vehicle* v)
- {
- if(!v)
- {
- GLF_ASSERTMSG(false, "GS3DStuff::getClosestShopSpawnPoint() : Vehicle is invalid.\n");
- return 0;
- }
- const bool isBoat = glf::DynamicCast<Boat>(v) != 0;
- const bool isAircraft = glf::DynamicCast<Airplane>(v) != 0 || glf::DynamicCast<Helicopter>(v) != 0;
- int shopSpawnPointType = Cst(ShopSpawnPointTypes, CarAndBike);
- if(isBoat)
- {
- shopSpawnPointType = Cst(ShopSpawnPointTypes, Boat);
- }
- else if(isAircraft)
- {
- shopSpawnPointType = Cst(ShopSpawnPointTypes, HeliAndPlane);
- }
- return getClosestShopSpawnPoint(c, shopSpawnPointType);
- }
- //////////////////////////////////////////////////////////////////////////
- ShopSpawnPoint* GS3DStuff::getClosestShopSpawnPoint(Character* c, int shopSpawnPointType)
- {
- if(!c)
- {
- GLF_ASSERTMSG(false, "GS3DStuff::getClosestShopSpawnPoint() : Character is invalid.\n");
- return 0;
- }
- GameObjectList& objectList = GameObjectManager::GetInstance()->GetObjectList(Kst(ObjectFrameActions, Paused));
- GameObjectList& updObjectList = GameObjectManager::GetInstance()->GetObjectList(Kst(ObjectFrameActions, UpdateAndDraw));
- ShopSpawnPoint* obj = objectList.GetFirst<ShopSpawnPoint>();
- float fClosestDistanceSQ = -1.f;
- ShopSpawnPoint* closest = 0;
- glitch::core::vector3df spawnPos;
- glitch::core::quaternion spawnRot(0.f, 0.f, 0.f, 0.f);
- float minDistVehicleSQ = SQUARE(Cst(SpawnCstCommon, shopMinDistanceToVehicles));
- float minDistPlayerSQ = SQUARE(Cst(SpawnCstCommon, shopMinDistanceToPlayer));
- const glitch::core::vector3df& character_pos = c->GetPosition();
- int numShopSpawnPoint = 0;
- int numShopSpawnPointMatching = 0;
- while(obj)
- {
- numShopSpawnPoint++;
- if(obj->GetShopSpawnPointType() & shopSpawnPointType)
- {
- numShopSpawnPointMatching++;
- float fDistanceSQ = character_pos.getDistanceFromSQ(obj->GetPosition());
- if(!closest || fDistanceSQ < fClosestDistanceSQ && fDistanceSQ >= minDistPlayerSQ)
- {
- // Check for collision with other vehicles
- bool collision = false;
- Vehicle* otherVehicle = updObjectList.GetFirst<Vehicle>();
- while(otherVehicle)
- {
- if(otherVehicle->GetPosition().getDistanceFromSQ(obj->GetPosition()) < minDistVehicleSQ)
- {
- collision = true;
- break;
- }
- otherVehicle = updObjectList.GetNext<Vehicle>(otherVehicle);
- }
- if(!collision)
- {
- fClosestDistanceSQ = fDistanceSQ;
- closest = obj;
- }
- }
- }
- obj = objectList.GetNext<ShopSpawnPoint>(obj);
- }
- if(!closest)
- {
- if(numShopSpawnPointMatching == 0)
- {
- GLF_ASSERTMSG(false, "DATA ERROR : ShopSpawnPointType='ShopSpawnPointTypes.%s' (value=%d)\n But NO primitive of type 'ShopSpawnPoint' with shopSpawnPointType='ShopSpawnPointTypes.%s' was found,\nFound %d ShopSpawnPoint in total.\nPlease double check your ShopSpawnPoint loaded or the StockItem ShopSpawnPointType ...\nShop item will now load IN YOUR FACE THIS IS A BUG.", "unknown"/*DBG_GetEnumName(ShopSpawnPointTypes, m_shopSpawnPointType)*/, shopSpawnPointType, "unknown"/*DBG_GetEnumName(ShopSpawnPointTypes, m_shopSpawnPointType)*/, numShopSpawnPoint);
- }
- else
- {
- GLF_ASSERTMSG(false, "DATA ERROR : found %d matching ShopSpawnPoint but they were all colliding with vehicle with provided radius SpawnCstCommon.shopMinDistanceToVehicles=%d\n!\nStockItem will now spawn IN YOUR FACE\nTHIS IS A BUG\n", numShopSpawnPointMatching, Cst(SpawnCstCommon, shopMinDistanceToVehicles));
- }
- }
- return closest;
- }
- int GS3DStuff::PrintNodeProperties(glitch::scene::ISceneNode* Node, bool recursive, int depth)
- {
- int count = 1;
- if(Node->getType() != glitch::scene::ESNT_EMPTY
- && Node->getType() != glitch::scene::ESNT_COLLADA_NODE
- && Node->getType() != glitch::scene::ESNT_SCENE_MANAGER)
- {
- SCOPE_TRACE("DBG", "Node->getType(): %c%c%c%c\n", (char)(Node->getType()&0xFF),(char)((Node->getType()&0xFF00)>>8),(char)((Node->getType()&0xFF0000)>>16),(char)((Node->getType()&0xFF000000)>>24));
- count = 0;
- }
- if(Node->getChildren().begin() == Node->getChildren().end() && (Node->getType() != glitch::scene::ESNT_COLLADA_MESH && Node->getType() != glitch::scene::ESNT_COLLADA_SKIN_MESH))
- {
- SCOPE_TRACE("DBG", "LEAF: %c%c%c%c\n", (char)(Node->getType()&0xFF),(char)((Node->getType()&0xFF00)>>8),(char)((Node->getType()&0xFF0000)>>16),(char)((Node->getType()&0xFF000000)>>24));
- }
- // add tabs.
- StdString sTabs;
- for(int i = 0; i < depth; ++i)
- {
- sTabs += " ";
- }
- const char* cTabs = sTabs.c_str();
- if(recursive)
- {
- glitch::scene::SSceneNodeList::iterator it = Node->childrenBegin();
- for(; it != Node->childrenEnd(); ++it)
- {
- count += PrintNodeProperties((&(*it)), recursive, depth + 1);
- }
- }
- return count;
- }
- void GS3DStuff::draw3dAABB(const glitch::core::aabbox3df& aabb, glitch::video::SColor color, const glitch::core::matrix4* transform)
- {
- glitch::video::IVideoDriver* vd = GetVideoDriver();
- glitch::core::vector3df max = aabb.MaxEdge;
- glitch::core::vector3df min = aabb.MinEdge;
- glitch::core::vector3df point1(max.getX(), max.getY(), max.getZ());
- glitch::core::vector3df point2(max.getX(), min.getY(), max.getZ());
- glitch::core::vector3df point3(min.getX(), max.getY(), max.getZ());
- glitch::core::vector3df point4(min.getX(), min.getY(), max.getZ());
- glitch::core::vector3df point5(max.getX(), max.getY(), min.getZ());
- glitch::core::vector3df point6(max.getX(), min.getY(), min.getZ());
- glitch::core::vector3df point7(min.getX(), max.getY(), min.getZ());
- glitch::core::vector3df point8(min.getX(), min.getY(), min.getZ());
- if(transform)
- {
- transform->transformVect(point1);
- transform->transformVect(point2);
- transform->transformVect(point3);
- transform->transformVect(point4);
- transform->transformVect(point5);
- transform->transformVect(point6);
- transform->transformVect(point7);
- transform->transformVect(point8);
- }
- GS3DStuff::draw3DLineBuffered(point1, point2, color);
- GS3DStuff::draw3DLineBuffered(point1, point3, color);
- GS3DStuff::draw3DLineBuffered(point1, point5, color);
- GS3DStuff::draw3DLineBuffered(point2, point4, color);
- GS3DStuff::draw3DLineBuffered(point2, point6, color);
- GS3DStuff::draw3DLineBuffered(point3, point7, color);
- GS3DStuff::draw3DLineBuffered(point3, point4, color);
- GS3DStuff::draw3DLineBuffered(point4, point8, color);
- GS3DStuff::draw3DLineBuffered(point5, point6, color);
- GS3DStuff::draw3DLineBuffered(point5, point7, color);
- GS3DStuff::draw3DLineBuffered(point6, point8, color);
- GS3DStuff::draw3DLineBuffered(point7, point8, color);
- }
- void GS3DStuff::drawCircle(const glitch::core::vector3df& center, const float radius, const unsigned int numPoints, const glitch::video::SColor& color)
- {
- glitch::video::IVideoDriver* vd = GetVideoDriver();
- float angle = 0;
- float x = sinf(0);
- float y = cosf(0);
- float interval = glf::TWO_PI/static_cast<float>(numPoints);
- glitch::core::vector3df point01(center.getX() + x*radius, center.getY() + y*radius, center.getZ());
- glitch::core::vector3df point02(center.getX() - x*radius, center.getY() - y*radius, center.getZ());
- glitch::core::vector3df point03(center.getX() + x*radius, center.getY() - y*radius, center.getZ());
- glitch::core::vector3df point04(center.getX() - x*radius, center.getY() + y*radius, center.getZ());
- glitch::core::vector3df point05(center.getX() + y*radius, center.getY() + x*radius, center.getZ());
- glitch::core::vector3df point06(center.getX() - y*radius, center.getY() - x*radius, center.getZ());
- glitch::core::vector3df point07(center.getX() + y*radius, center.getY() - x*radius, center.getZ());
- glitch::core::vector3df point08(center.getX() - y*radius, center.getY() + x*radius, center.getZ());
- while(angle <= glf::PI_2/2)
- {
- angle += interval;
- x = sinf(angle);
- y = cosf(angle);
- glitch::core::vector3df point09(center.getX() + x*radius, center.getY() + y*radius, center.getZ());
- glitch::core::vector3df point10(center.getX() - x*radius, center.getY() - y*radius, center.getZ());
- glitch::core::vector3df point11(center.getX() + x*radius, center.getY() - y*radius, center.getZ());
- glitch::core::vector3df point12(center.getX() - x*radius, center.getY() + y*radius, center.getZ());
- glitch::core::vector3df point13(center.getX() + y*radius, center.getY() + x*radius, center.getZ());
- glitch::core::vector3df point14(center.getX() - y*radius, center.getY() - x*radius, center.getZ());
- glitch::core::vector3df point15(center.getX() + y*radius, center.getY() - x*radius, center.getZ());
- glitch::core::vector3df point16(center.getX() - y*radius, center.getY() + x*radius, center.getZ());
- GS3DStuff::draw3DLineBuffered(point01, point09, color);
- GS3DStuff::draw3DLineBuffered(point02, point10, color);
- GS3DStuff::draw3DLineBuffered(point03, point11, color);
- GS3DStuff::draw3DLineBuffered(point04, point12, color);
- GS3DStuff::draw3DLineBuffered(point05, point13, color);
- GS3DStuff::draw3DLineBuffered(point06, point14, color);
- GS3DStuff::draw3DLineBuffered(point07, point15, color);
- GS3DStuff::draw3DLineBuffered(point08, point16, color);
- point01 = point09;
- point02 = point10;
- point03 = point11;
- point04 = point12;
- point05 = point13;
- point06 = point14;
- point07 = point15;
- point08 = point16;
- }
- }
- void GS3DStuff::drawNormal(const glitch::core::vector3df& start, const glitch::core::vector3df& normal, float zOffset, glitch::video::SColor color)
- {
- const int normalLength = 100.0f;
- glitch::core::vector3df normal2 = normal;
- glitch::core::vector3df from = start;
- from.z() += zOffset;
- normal2.normalize();
- normal2 *= normalLength;
- glitch::core::vector3df to = from + normal2;
- glitch::core::vector3df const0(1.0f, 1.0f, 1.0f);
- glitch::core::vector3df const1(0.0f, 0.0f, 0.0f);
- glitch::core::vector3df ortho;
- {
- // Compute perpendicular vector
- glitch::core::vector3df perpendicular0;
- perpendicular0 = normal2.crossProduct(const0);
- glitch::core::vector3df perpendicular1;
- perpendicular1 = normal2.crossProduct(const1);
- const float l0 = perpendicular0.getLengthSQ();
- const float l1 = perpendicular1.getLengthSQ();
- if(l0 < l1)
- {
- ortho = perpendicular1;
- }
- else
- {
- ortho = perpendicular0;
- }
- }
- ortho.normalize();
- glitch::core::vector3df ortho2;
- ortho2 = normal2.crossProduct(ortho);
- ortho *= normal2.getLength();
- float c0 = 0.85f;
- float c1 = (1.0f - c0);
- glitch::core::vector3df p;
- p = from + normal2 * c0 ;
- glitch::core::vector3df p0;
- p0 = p + (ortho * c1);
- glitch::core::vector3df p1;
- p1 = p + (ortho * -c1);
- glitch::core::vector3df p2;
- p2 = p + (ortho2 * c1);
- glitch::core::vector3df p3;
- p3 = p + (ortho2 * -c1);
- GS3DStuff::draw3DLineBuffered(from, to, color);
- GS3DStuff::draw3DLineBuffered(to, p0, color);
- GS3DStuff::draw3DLineBuffered(to, p1, color);
- GS3DStuff::draw3DLineBuffered(to, p2, color);
- GS3DStuff::draw3DLineBuffered(to, p3, color);
- }
- void GS3DStuff::drawLine(glitch::core::vector3df start, glitch::core::vector3df end, float zOffset, glitch::video::SColor color)
- {
- start[2] += zOffset;
- end[2] += zOffset;
- GS3DStuff::draw3DLineBuffered(start, end, color);
- }
- void GS3DStuff::drawPermanentLine(glitch::core::vector3df start, glitch::core::vector3df end)
- {
- s_plStart = start;
- s_plEnd = end;
- }
- void GS3DStuff::drawPoint(glitch::core::vector3df point, float zOffset, float radius, glitch::video::SColor color)
- {
- glitch::core::vector3df bmin(point.getX() - radius, point.getY() - radius, (point.getZ() + zOffset) - radius);
- glitch::core::vector3df bmax(point.getX() + radius, point.getY() + radius, (point.getZ() + zOffset) + radius);
- glitch::core::aabbox3df box(bmin, bmax);
- glitch::video::IVideoDriver* vd = GetVideoDriver();
- GS3DStuff::draw3DBoxBuffered(box, color);
- }
- void GS3DStuff::draw3DLineBuffered(const glitch::core::vector3df& start, const glitch::core::vector3df& end, glitch::video::SColor color)
- {
- BufferedLinePositions.push_back(start);
- BufferedLinePositions.push_back(end);
- BufferedLineColor.push_back(color);
- BufferedLineColor.push_back(color);
- BufferedLineIndexes.push_back(BufferedLineIndexes.size()%65536);
- BufferedLineIndexes.push_back(BufferedLineIndexes.size()%65536);
- }
- void GS3DStuff::draw3DLineBuffered(const glitch::core::vector3df& start, const glitch::core::vector3df& end, glitch::video::SColor color, glitch::video::SColor color2)
- {
- BufferedLinePositions.push_back(start);
- BufferedLinePositions.push_back(end);
- BufferedLineColor.push_back(color);
- BufferedLineColor.push_back(color2);
- BufferedLineIndexes.push_back(BufferedLineIndexes.size()%65536);
- BufferedLineIndexes.push_back(BufferedLineIndexes.size()%65536);
- }
- void GS3DStuff::draw3DBoxBuffered(const glitch::core::aabbox3d<f32>& box, glitch::video::SColor color)
- {
- glitch::core::vector3df edges[8];
- box.getEdges(edges);
- GS3DStuff::draw3DLineBuffered(edges[0], edges[1], color);
- GS3DStuff::draw3DLineBuffered(edges[0], edges[2], color);
- GS3DStuff::draw3DLineBuffered(edges[0], edges[4], color);
- GS3DStuff::draw3DLineBuffered(edges[1], edges[3], color);
- GS3DStuff::draw3DLineBuffered(edges[1], edges[5], color);
- GS3DStuff::draw3DLineBuffered(edges[2], edges[3], color);
- GS3DStuff::draw3DLineBuffered(edges[2], edges[6], color);
- GS3DStuff::draw3DLineBuffered(edges[3], edges[7], color);
- GS3DStuff::draw3DLineBuffered(edges[4], edges[5], color);
- GS3DStuff::draw3DLineBuffered(edges[4], edges[6], color);
- GS3DStuff::draw3DLineBuffered(edges[5], edges[7], color);
- GS3DStuff::draw3DLineBuffered(edges[6], edges[7], color);
- }
- void GS3DStuff::flushBufferedLines()
- {
- glitch::video::IVideoDriver* vd = GetVideoDriver();
- if(BufferedLineColor.size() > 0)
- {
- vd->clearBuffers(glitch::video::EFB_DEPTH);
- CMaterialRendererManager& mrm = vd->getMaterialRendererManager();
- vd->setMaterial(mrm.getMaterialInstance(vd, glitch::video::EMT_UNLIT_NON_TEXTURED_SOLID));
- int cnt = (BufferedLineIndexes.size()-1)/65536;
- for(int i=0; i<=cnt; i++)
- {
- vd->draw3DLines(
- &BufferedLinePositions[i*65536],
- &BufferedLineIndexes[i*65536],
- &BufferedLineColor[i*65536],
- i != cnt ? 65536 : BufferedLineIndexes.size()%65536,
- (i != cnt ? 65536 : BufferedLineIndexes.size()%65536)/2);
- }
- }
- BufferedLinePositions.resize(0);
- BufferedLineColor.resize(0);
- BufferedLineIndexes.resize(0);
- }
- LODSceneNode* GS3DStuff::parseSceneNodeForLOD(glitch::scene::ISceneNode* nodeToParse, LODSceneNode* LODNode)
- {
- return LODNode;
- }
- bool GS3DStuff::getProperty(const void* userProps, const char* prop, char* buffer)
- {
- if(!userProps)
- {
- return false;
- }
- const char* properties = *((char**)userProps);
- const char* propertyStart = strstr(properties, prop);
- const char* propertyEnd = 0;
- if(!propertyStart)
- {
- return false;
- }
- propertyEnd = strchr(propertyStart, ';');
- if(!propertyEnd)
- {
- propertyEnd = strchr(propertyStart, '\n');
- if(!propertyEnd)
- {
- propertyEnd = properties + strlen(properties);
- }
- }
- propertyStart = strstr(propertyStart, "=") + 1;
- int length = propertyEnd - propertyStart;
- memcpy(buffer, propertyStart, length);
- buffer[length + 1] = '\0';
- return true;
- }
- LevelObject* CheckForDespawnWantedLevel(LevelObject* lo)
- {
- if(!lo)
- {
- return lo;
- }
- if(!Player::GetPlayer())
- {
- return lo;
- }
- bool isCop = lo->IsCop();
- GLF_ASSERTMSG(isCop && WantedMgr()->GetWantedLevel() > 0, "Programmer error : CheckForDespawnWantedLevel should only be called for cops during wanted level\n");
- bool shouldDespawn = false;
- Character* copCharacter = glf::DynamicCast<Character>(lo);
- Vehicle* copCar = glf::DynamicCast<Vehicle>(lo);
- //Quicker Test first : is he dead ?
- // Now testing IsDead is wrong because it becomes true as soon as the HP is zero and the npc starts it's "dying" sequence
- //
- if(lo->isWaitingForDespawn())
- {
- SCOPE_TRACE("WantedLevel", "Despawning %s because cop hes dead, duh ? \n", lo->GetName());
- shouldDespawn = true;
- }
- else
- {
- //Slighly more expensive test (distance related)
- //Distance Related Test.
- glitch::core::vector3df pos = Player::GetPlayer()->GetPosition();
- float distSq = pos.getDistanceFromSQ(lo->GetPosition());
- int presetId;
- if(copCar)
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetCopCar);
- }
- else if(World::GetInstance()->IsInterior())
- {
- presetId = DataByIdx(Locations, GS3DStuff::GetCurrentLocation(), spawnInputsPresetCopInterior);
- }
- else
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetCopNPC);
- }
- const float spawnRadiusMulti = DataByIdx(PhonePerformanceProfiles, gPhonePerfId, spawnInputPresetsMultiplicator);
- float despawn = lo->isVisibleOnScreen(false) ? static_cast<int>(DataByIdx(SpawnInputsPresets, presetId, despawnRadius)) :
- static_cast<int>(DataByIdx(SpawnInputsPresets, presetId, offScreenDespawnRadius));
- despawn *= spawnRadiusMulti;
- float despawnSq = SQUARE(despawn);
- float despawnIfStuckSq = WantedMgr()->GetDespawnIfStuckSq();
- //if we are farther than despawn radius, unspawn cop
- if( distSq >= despawnSq )
- {
- SCOPE_TRACE("WantedLevel", "Despawning %s because cop is outside the curDist=%f >= despawnDist=%f\n",
- lo->GetName()
- ,WantedLevelManager::SqCentimetersToMeters(distSq)
- ,WantedLevelManager::SqCentimetersToMeters(despawnSq));
- shouldDespawn = true;
- }
- else if(distSq >= despawnIfStuckSq)
- {
- shouldDespawn = lo->TestDespawnIfStuckWantedLevel();
- }
- }
- if(shouldDespawn)
- {
- SCOPE_TRACE("WantedLevel", "Despawning cop=%s\n", lo->GetName());
- //Calling this a Vehicle will also disable it's driver so I think it's ok.
- lo = GameObjectManager::GetInstance()->disable(lo);
- }
- //for now, simply NEVER despawn.
- //need better design idea.
- return lo;
- }
- LevelObject* GS3DStuff::checkForDespawn(LevelObject* lo)
- {
- ProfilerScopeGameplay("GS3DStuff::checkForDespawn", NULL);
- bool isSpawned = lo->GetFlag(Kst(GameObjectFlag, Spawned)) && !lo->isActor();
- bool isDead = lo->isDead() && (GameObjectManager::isCharacter(lo) || GameObjectManager::isVehicle(lo) || GameObjectManager::isGameObject(lo));
- bool isToBeReleased = lo->GetFlag(Kst(GameObjectFlag, ToBeReleased));
- Vehicle* veh = glf::DynamicCast<Vehicle>(lo);
- bool isVehicle = veh != 0;
- if(isSpawned || isDead || isToBeReleased)
- {
- Player* player = Player::GetPlayer();
- bool isCop = lo->IsCop();
- NPC* npc = 0;
- if(lo->getType() == Cst(GameObjectType, NPC))
- {
- npc = (NPC*)lo;
- }
- if(npc && !lo->isDead())
- {
- NPC* npc = (NPC*)lo;
- // Leave NPC despawn to the vehicle.
- if(npc->isInAVehicle())
- {
- return lo;
- }
- }
- if(isCop && npc && !GameObjectManager::isHelicopter(npc->getVehicle()) && WantedMgr()->GetWantedLevel() > 0)
- {
- return CheckForDespawnWantedLevel(lo);
- }
- const float spawnRadiusMulti = DataByIdx(PhonePerformanceProfiles, gPhonePerfId, spawnInputPresetsMultiplicator);
- int presetId;
- float radius;
- float radiusSQ;
- // same for cop cars
- if(isVehicle)
- {
- // Can't despawn player vehicle or target vehicle while player is in it
- if(player->isInAVehicle() && lo == player->getVehicle())
- {
- return lo;
- }
- else if(!veh->isDestroyed())
- {
- Player* player = Player::GetPlayer();
- if(veh->hasDriver())
- {
- //Don't despawn an active actor's vehicle.
- if(veh->getDriver()->isActor()&& !veh->getDriver()->GetFlag(Kst(GameObjectFlag, ToBeReleased)))
- {
- return lo;
- }
- //Don't despawn vehicle if driver is interracting with vehicle.
- if(veh->getDriver()->isInteractingWithVehicle() && veh->getDriver()->IsVisible())
- {
- return lo;
- }
- }
- glitch::core::vector3df p1 = Player::GetPlayer()->GetPosition();
- glitch::core::vector3df p2 = veh->GetPosition();
- glitch::core::vector3df dist = player->GetPosition() - veh->GetPosition();
- if(WantedMgr()->GetWantedLevel() > 0)
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetCopCar);
- }
- else
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetVehicle);
- }
- radius = lo->isVisibleOnScreen(false) ? static_cast<int>(DataByIdx(SpawnInputsPresets, presetId, despawnRadius)) :
- static_cast<int>(DataByIdx(SpawnInputsPresets, presetId, offScreenDespawnRadius));
- radius *= spawnRadiusMulti;
- radiusSQ = SQUARE(radius);
- // if this is a cop car and a cop is actually driving...
- if(isCop && veh->getDriver() && dist.getLengthSQ() < radiusSQ)//veh->isChasing() &&
- {
- return lo;
- }
- // Can't despawn player vehicle or target vehicle.
- else if(lo == player->aiGetVehicle() || lo == player->m_closestVehicle || lo == player->m_lastUsedVehicle)
- {
- return lo;
- }
- else if(veh->getViewer() && veh->getViewer()->isEnabled())
- {
- glitch::core::vector3df dist = veh->getViewer()->GetPosition() - veh->GetPosition();
- if(dist.getLengthSQ() < radiusSQ)
- {
- return lo;
- }
- }
- }
- }
- glitch::core::vector3df outerSpawnCenter = Player::GetPlayer()->GetPosition();
- if(World::GetInstance()->IsInterior())
- {
- if(gom->isCharacter(lo) && lo->IsCop() && WantedMgr()->GetWantedLevel() > 0)
- {
- presetId = DataByIdx(Locations, GetCurrentLocation(), spawnInputsPresetCopInterior);
- }
- else
- {
- presetId = DataByIdx(Locations, GetCurrentLocation(), spawnInputsPresetInterior);
- }
- }
- else if(gom->isVehicle(lo))
- {
- if(((Vehicle*)lo)->getDriver())
- {
- if(lo->IsCop() && WantedMgr()->GetWantedLevel() > 0)
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetCopCar);
- }
- else
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetVehicle);
- }
- }
- else
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetParkedVehicle);
- }
- }
- else if(gom->isCharacter(lo))
- {
- if(lo->IsCop() && WantedMgr()->GetWantedLevel() > 0)
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetCopNPC);
- }
- else
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetNPC);
- }
- }
- else
- {
- presetId = Player::GetPlayer()->GetSpawnInputsPreset(Player::SpawnInputsPresetRoadBlock);
- }
- radius = lo->isVisibleOnScreen(false) ? static_cast<int>(DataByIdx(SpawnInputsPresets, presetId, despawnRadius)) :
- static_cast<int>(DataByIdx(SpawnInputsPresets, presetId, offScreenDespawnRadius));
- radius *= spawnRadiusMulti;
- radiusSQ = SQUARE(radius);
- glitch::core::vector3df loPos = lo->GetPosition();
- float centerZ = outerSpawnCenter.getZ();
- float loZ = loPos.getZ();
- const float MAX_Z_OFFSET_TO_STAY_SPAWNED = 500 * M_TO_CM; // (this is huge so it doesnt despawn flying stuff ?!?!? maybe just dont despawn on Z ?)
- // despawn radius is in 2D.
- // we handle Z diff individually...
- loPos.setZ(0);
- outerSpawnCenter.setZ(0);
- float loPosToOuterDistSQ = loPos.getDistanceFromSQ(outerSpawnCenter);
- float despawnRadiusSQ = radiusSQ;
- // [ICH] easy hack just to further the despawn radius of NPCs so that they don't disappear when they die from far at a targetable range
- if (lo->getType() == Cst(GameObjectType, NPC))
- {
- despawnRadiusSQ *= 2.0f;
- if (Player::GetPlayer() && Player::GetPlayer()->isInSnipingHUD())
- {
- despawnRadiusSQ *= 2.0f;
- }
- }
- if(lo->isWaitingForDespawn()
- || std::abs(centerZ - loZ) > MAX_Z_OFFSET_TO_STAY_SPAWNED
- || loPosToOuterDistSQ >= despawnRadiusSQ
- || lo->getType() == Cst(GameObjectType, Projectile))
- {
- ProfilerScopeGameplay("GS3DStuff::checkForDespawn::disable", NULL);
- SCOPE_TRACE("SpawnManager", "Despawning lo=%s,\n\tpos=<%f,%f,%f>,\n\tdespawnCenterPos=<%f,%f,%f>\n\tdist=%f (max=%d)\n"
- , lo->GetName()
- , loPos.getX()
- , loPos.getY()
- , loZ
- , outerSpawnCenter.getX()
- , outerSpawnCenter.getY()
- , centerZ
- , glf::Sqrt(loPosToOuterDistSQ)
- , radius);
- if( GET_DEBUG_SWITCH("DisableSpawnManager") )
- {
- //quick hack, just teleport back that shit closer to player and that's it. this will void all the SpawnManager Shits but keep the "Max number of spawn functional"
- glitch::core::vector3df newPos = Player::GetPlayer()->GetPosition();
- float angle = Random::GetRandom(90, 270);
- float dist = Random::GetRandom(200, 1500);
- glitch::core::vector3df playerR = Player::GetPlayer()->GetFront();
- newPos = newPos + (dist * playerR.rotateXYBy(angle));
- lo->moveTo(newPos, lo->GetRotation());
- lo->SetSnappedToFloor(false);
- }
- else
- {
- if(gom->isVehicle(lo))
- {
- // Remove driver
- Character* driver = static_cast<Vehicle*>(lo)->getDriver();
- if(driver)
- {
- driver->WaitForDespawn();
- }
- }
- lo = gom->disable(lo);
- }
- }
- }
- return lo;
- }
- void GS3DStuff::forceDespawn(int gameObjectType)
- {
- LevelObject* lo = gom->GetFirstLo(Kst(ObjectFrameActions, UpdateAndDraw));
- Player* player = Player::GetPlayer();
- while(lo)
- {
- bool despawned = false;
- if(lo->getType() == gameObjectType
- && ((lo->isActor()
- && lo->GetFlag(Kst(GameObjectFlag, ToBeReleased)))
- || (!lo->isActor()
- && lo->GetFlag(Kst(GameObjectFlag, Spawned) | Kst(GameObjectFlag, ToBeReleased)))))
- {
- if(lo != player->aiGetVehicle() && lo != player->getVehicle() && lo != player->m_closestVehicle && lo != player->m_lastUsedVehicle)
- {
- despawned = true;
- lo = gom->disable(lo);
- }
- }
- if(!despawned)
- {
- lo = gom->GetNextLo(lo);
- }
- }
- }
- // IMPORTANT: Don't call this function directly.
- // To set the orientation, use Application::SetGameOrientation
- void GS3DStuff::SetCurrentOrientation(const glitch::video::E_ORIENTATION new_ori)
- {
- s_orientation = new_ori;
- glitch::video::IVideoDriver* driver = GetVideoDriver();
- #if defined(OS_IPHONE) || defined(OS_ANDROID)
- driver->setOrientation((s_orientation == glitch::video::EO_180) ? glitch::video::EO_180 : glitch::video::EO_0);
- #else
- driver->setOrientation(s_orientation);
- #endif
- };
- #if WIN32
- #include <gl/gl.h>
- #elif defined(OS_IPHONE)
- #include <OpenGLES/ES1/gl.h>
- #elif defined(OS_ANDROID)
- #include <GLES/gl.h>
- #endif
- extern StdString gForcedPhoneProfile;
- void ChoosePerfProfile(glitch::video::IVideoDriver* driver, int idx)
- {
- #if defined(OS_IPHONE) || defined(OS_ANDROID)
- return;
- #endif
- int defaultProfile = 0;
- if (idx < 0)
- {
- const char* glVendor = driver->getVendorInfo(); // Imagination Technologies
- const char* glVersion = driver->getName(); // PowerVR SGX 535
- const char* glRenderer = driver->getRendererInfo();
- //iphone3g OpenGL ES 2.0
- //iphone3gs OpenGL ES 2.0
- //ipad1 OpenGL ES 2.0
- //iphone4 OpenGL ES 2.0 IMGSGX535-48.11.3
- //ipad2 OpenGL ES 2.0 IMGSGX543-58.6
- SCOPE_TRACE("PerfProfile", "glVendor %s\n", glVendor);
- SCOPE_TRACE("PerfProfile", "glVersion %s\n", glVersion);
- SCOPE_TRACE("PerfProfile", "glRenderer %s\n", glRenderer);
- int screenWidth = Application::GetViewportWidth();
- int screenHeight = Application::GetViewportHeight();
- if(screenWidth < screenHeight) //make width bigger than height
- {
- int tmp = screenHeight;
- screenHeight = screenWidth;
- screenWidth = tmp;
- }
- int nbProfiles = DataCount(PhonePerformanceProfiles);
- #if WIN32
- if(GET_DEBUG_SWITCH("IsHighQualityCinematic"))
- {
- gForcedPhoneProfile = StdString("CinematicRenderer");
- }
- for(size_t i = 0; i < nbProfiles; ++i)
- {
- StdString family = (const char*)DataByIdx(PhonePerformanceProfiles, i, deviceFamily);
- if(gForcedPhoneProfile == family)
- {
- gPhonePerfId = i;
- SCOPE_TRACE("PerfProfile", "chosen profile %d -> %s\n", idx, family.c_str());
- return;
- }
- }
- #endif
- for(size_t i = 0; i < nbProfiles; ++i)
- {
- StdString family = (const char*)DataByIdx(PhonePerformanceProfiles, i, deviceFamily);
- if(family == gForcedPhoneProfile)
- {
- idx = i;
- break;
- }
- int numberOfDevices = DataByIdxSize(PhonePerformanceProfiles, i, names);
- for(size_t j = 0; j < numberOfDevices; ++j)
- {
- const char* perfProfileName = DataByIdxN(PhonePerformanceProfiles, i, names, j);
- #if defined(OS_ANDROID)
- if(strstr("ANDROID DEFAULT", perfProfileName))
- {
- #else
- // WIN32 and OS_IPHONE
- if(strstr("DEFAULT", perfProfileName))
- {
- #endif
- defaultProfile = i;
- }
- if(strstr(glVersion, perfProfileName) || strstr(glRenderer, perfProfileName))
- {
- idx = i;
- break;
- }
- }
- if (idx >= 0)
- {
- break;
- }
- }
- }
- if(idx < 0)
- {
- idx = defaultProfile;
- }
- gPhonePerfId = idx;
- SCOPE_TRACE("PerfProfile", "chosen profile %d -> %s\n", idx, static_cast<const char*>(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, deviceFamily)));
- }
- glitch::u32 g_numCapping = 0;
- glitch::u32 g_numSavedCapping = 0;
- glitch::u32 g_numLoadedCapping = 0;
- size_t gSegmentUid = 0;
- int gNumSegments = 0;
- int gIsReallyDoneLoopCount = 0;
- void GS3DStuff::updateStreaming(const glitch::scene::SViewFrustum* frustum, glitch::core::vector3df& pos)
- {
- }
- bool GS3DStuff::isStreaming()
- {
- return s_streamingState != SS_NONE;
- }
- void GS3DStuff::streamingUpdate(int dt)
- {
- static int frameCount = 0;
- s_streamingTimer -= dt;
- World* world = World::GetInstance();
- switch(s_streamingState)
- {
- case SS_FADEOUT:
- {
- if(s_streamingTimer < 0)
- {
- frameCount = 0;
- s_streamingState = SS_STREAMING;
- s_streamingElapsed = 0;
- }
- }
- break;
- case SS_STREAMING:
- {
- frameCount++;
- bool isDone = GS3DStuff::IsAllStreamingDone();
- bool isReallyDone = false;
- g_Loading=true;
- if(isDone)
- {
- isReallyDone = true;
- }
- glf::Thread::Sleep(10);
- glitch::scene::ICameraSceneNodePtr camera = Application::GetInstance()->GetDevice()->getSceneManager()->getActiveCamera();
- glitch::core::vector3df pos = camera->getAbsolutePosition();
- //big ugly hack
- extern bool gFromContinueGame;
- if(isReallyDone)
- {
- bool isTopStateGd3dStuff = StateMachine::GetInstance()->isState<GS3DStuff>() != 0;
- if(gFromContinueGame && isTopStateGd3dStuff && gIsReallyDoneLoopCount < 5)
- {
- gIsReallyDoneLoopCount++;
- extern glitch::core::vector3df gLastStreamedPos;
- glitch::core::vector3df lastStreamedPos = gLastStreamedPos;
- pos = Player::GetPlayer()->GetPosition();
- pos.setZ(0);
- lastStreamedPos.setZ(0);
- float lengthSQ = (pos - lastStreamedPos).getLengthSQ();
- if(lengthSQ > 1500*1500)
- {
- //camera->setPosition(pos);
- //camera->updateAbsolutePosition();
- //CameraManager::GetInstance()->getActiveCamera()->setPosition(pos);
- bool isPlayerVisible = Player::GetPlayer()->GetGlitchSceneNode()->isVisible();
- Player::GetPlayer()->GetGlitchSceneNode()->setVisible(true);
- if (!Player::GetPlayer()->isInAVehicle())
- {
- CameraManager::GetInstance()->enterMode(CAMERA_MODES::FOLLOW, Player::GetPlayer(), 0, 0);
- }
- else
- {
- CameraManager::GetInstance()->enterMode(CAMERA_MODES::VEHICLE, Player::GetPlayer()->getVehicle(), 0, 0);
- }
- CameraManager::GetInstance()->update(1000);
- World::GetInstance()->UpdateStreaming(pos);
- Player::GetPlayer()->GetGlitchSceneNode()->setVisible(isPlayerVisible);
- isReallyDone = false;
- }
- }
- }
- if(isReallyDone)
- {
- gFromContinueGame = false;
- gIsReallyDoneLoopCount = 0;
- g_Loading=false;
- if(s_skipFadeIn)
- {
- s_streamingState = SS_NONE;
- Fade(0);
- s_skipFadeIn = false;
- }
- else
- {
- World::GetInstance()->StreamingEnd();
- s_streamingState = SS_FADEIN;
- s_streamingDuration = s_streamingTimer = 500; // TODO: use constant
- }
- hideLoading();
- CHudManager::GetInstance()->SetEnable(Cst(HudElements, Screen), true);
- CHudManager::GetInstance()->unlock();
- Application::GetInstance()->ResumeScripts();
- }
- else
- {
- frameCount = 0;
- const glitch::scene::SViewFrustum* frustum = Application::GetInstance()->GetDevice()->getSceneManager()->getActiveCamera()->getViewFrustum();
- if(gEnableEnvironment)
- {
- World::GetInstance()->UpdateStreaming(pos);
- }
- ProfilerScopeScene("texture streaming", NULL);
- s_streamingElapsed += dt;
- if(s_streamingElapsed >= 2000)
- {
- showLoading();
- }
- }
- Application::GetInstance()->WatchDogForLoadingTime(true, true);
- }
- break;
- case SS_FADEIN:
- {
- if (s_streamingTimer <= 0)
- {
- s_streamingState = SS_NONE;
- s_streamingElapsed = 0;
- s_streamingDuration = 1;
- s_streamingTimer = 0;
- Fade(0);
- if (OnlineServiceMgr()->GetBITracker())
- {
- OnlineServiceMgr()->GetBITracker()->TrackLoadingTimes(online::tracking::BITracker::MMTOAP, false);
- GVAdsManager::GetInstance()->OnLocationChange("action_phase");
- }
- }
- Application::GetInstance()->WatchDogForLoadingTime(true, false);
- }
- break;
- default:
- break;
- }
- }
- void GS3DStuff::streamingInit()
- {
- s_streamingState = SS_FADEOUT;
- s_streamingTimer = 0;
- s_streamingDuration = 200;
- CHudManager::GetInstance()->SetEnable(Cst(HudElements, Screen), false);
- CHudManager::GetInstance()->lock();
- Application::GetInstance()->PauseScripts();
- World::GetInstance()->StreamingInit();
- }
- void GS3DStuff::Fade(int intensity)
- {
- if (SwfManager::GetInstance() && SwfManager::GetInstance()->GetMenu(SwfManager::SWF_HUD))
- {
- if (s_streamingState == SS_STREAMING)
- {
- intensity = 255;
- }
- SndMgr()->SetGlobalMute((255.0f - (float)intensity) / 255.0f);
- MenuFlashBase* swfHud = SwfManager::GetInstance()->GetMenu(SwfManager::SWF_HUD)->m_renderFX;
- gameswf::CharacterHandle ch = swfHud->find("hudFade_mc");
- ch.gotoAndStop("black");
- ch.setAlpha(intensity / 255.f);
- if (intensity > 0)
- {
- //this hack is needed for streaming only, since the streaming code probably doesnt give time to the flash to render before going in a long loop...
- int screenWidth, screenHeight;
- Application* app = Application::GetInstance();
- glitch::video::C2DDriver* driver = app->GetDevice()->get2DDriver();
- app->GetScreenDimensions(screenWidth, screenHeight);
- driver->draw2DRectangle(glitch::video::SColor(intensity, 0, 0, 0), glitch::core::rect<int>(0, 0, screenWidth, screenHeight));
- ch.setVisible(true);
- }
- else
- {
- ch.setVisible(false);
- }
- }
- }
- void GS3DStuff::streamingDraw2d()
- {
- int intensity = 0;
- switch(s_streamingState)
- {
- case SS_FADEOUT:
- intensity = 255 - s_streamingTimer * 255 / s_streamingDuration;
- break;
- case SS_STREAMING:
- intensity = 255;
- break;
- case SS_FADEIN:
- intensity = s_streamingTimer * 255 / s_streamingDuration;
- break;
- }
- if(intensity > 0)
- {
- Fade(intensity);
- }
- }
- void GS3DStuff::SwitchLocation(int id)
- {
- GLF_ASSERTMSG(id >= 0 && id < DataCount(Locations), "GS3DStuff::SwitchLocation : Cannot switch location because the given location id %i must be in the range of [0;%i[.", id, (int)DataCount(Locations));
- if (id >= 0 && id < DataCount(Locations) && currentLocation != id)
- {
- TRACE_CRASH_LOG("GS3DStuff::SwitchLocation '%s' (%d)\n", DataName(Locations, id), id );
- MapHandler* mapHandler = MenuMgr::GetInstance()->GetMapHandler();
- ASSERT((mapHandler != 0) && "MapHandler cannot be null when switching location.");
- if(mapHandler)
- {
- CHudManager::GetInstance()->setMinimap((int)DataByIdx(Locations, id, MapInfo));
- menu::menuEventMgr::MenuEventManager::Members members;
- GetMenuEventMgr()->DispatchEventAllRoots(flash_constants::events::MapEvent::NEW_LOCATION, members);
- SCOPE_TRACE("MapLocation", "GS3DStuff::SwitchLocation PreviousID(%i) SwitchLocationToID(%i) MapInfoIdx(%i)\n", currentLocation, id, (int)DataByIdx(Locations, id, MapInfo));
- }
- // [ICH]: remove backdrop
- GET_BACKDROP_ROOT()->removeAll();
- const char* backdropFilename = static_cast<const char*>(DataByIdx(Locations, id, backdropFile));
- if (strlen(backdropFilename) > 0)
- {
- glitch::scene::ISceneNodePtr backdropNode = CustomConstructScene(backdropFilename, SkyboxColladaFactory::getInstance(), false, E_CCS_OH_NONE);
- GET_BACKDROP_ROOT()->addChild(backdropNode);
- glitch::core::vector3df position(DataByIdx(Locations, id, backdropPosX), DataByIdx(Locations, id, backdropPosY), DataByIdx(Locations, id, backdropPosZ));
- backdropNode->setPosition(position);
- backdropNode->updateAbsolutePosition(true);
- }
- CCustomIngameSceneManager* smgr = static_cast<CCustomIngameSceneManager*>(GetDevice()->getSceneManager());
- bool shadowAreaEnabled = DataByIdx(Locations, id, UseMandatoryShadowMapArea);
- glitch::core::aabbox3df shadowAABB;
- if (shadowAreaEnabled)
- {
- int valuesCount = DataByIdxSize(Locations, id, MandatoryShadowMapAABB);
- GLF_ASSERTMSG(valuesCount == 6, "There should be six values for MandatoryShadowMapAABB in locations_.xml - minx ^ miny ^ minz ^ maxx ^ maxy ^ maxz");
- float values[6];
- for (int j = 0; j < valuesCount; ++j)
- {
- values[j] = DataByIdxN(Locations, id, MandatoryShadowMapAABB, j);
- }
- shadowAABB.MinEdge = glitch::core::vector3df(values[0], values[1], values[2]);
- shadowAABB.MaxEdge = glitch::core::vector3df(values[3], values[4], values[5]);
- }
- smgr->SetMandatoryShadowMapArea(shadowAreaEnabled, shadowAABB);
- Player::GetPlayer()->toggleFollowersVisibility(DataByIdx(Locations, id, allowFollowers));
- if(Player::GetPlayer()->getTarget())
- {
- Player::GetPlayer()->delockTarget();
- }
- char apex[256] = "gamedata/leveldesign/";
- strcat(apex, DataByIdx(Locations, id, apex));
- if(apex)
- {
- if(currentLocationXML != "")
- {
- GameObjectManager::GetInstance()->UnloadXML(currentLocationXML.c_str());
- }
- GameObjectManager::GetInstance()->LoadFile(apex);
- currentLocationXML = apex;
- }
- const char* entryPoint = DataByIdx(Locations, id, entryPoint);
- if(strlen(entryPoint) != 0)
- {
- LevelObject* entry = GameObjectManager::GetInstance()->GetGameObjectByName(entryPoint);
- ASSERT(entry);
- if(entry)
- {
- Player::GetPlayer()->moveTo(entry);
- }
- }
- const char* grapherScript = DataByIdx(Locations, id, grapher);
- locationContext.Reset();
- GrapherMgr()->FireManualEvent(grapherScript, &locationContext);
- if (id >= 0 && id < DataCount(Locations))
- {
- LightsManager::GetInstance()->LoadLightZone(DataByIdx(Locations, id, lightZone));
- }
- if(currentLocation >= 0 && !DataByIdx(Locations, currentLocation, keepNavMeshLoaded))
- {
- NavMeshManager::GetInstance()->UnloadLocation(currentLocation);
- }
- NavMeshManager::GetInstance()->LoadLocation(id);
- if (currentLocation >= 0)
- {
- int count = DataByIdxSize(Locations, currentLocation, StopSounds);
- if (count > 0)
- {
- for (int i = 0; i < count; ++i)
- {
- std::string sound = (const char*)DataByIdxN(Locations, currentLocation, StopSounds, i);
- SndMgr()->ExecByName(eSO_Stop, sound.c_str());
- }
- }
- }
- #ifdef IRRADIANCE
- if(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, useInteriorIrradiance))
- {
- const char* irradianceFile = DataByIdx(Locations, id, irradianceFile);
- glitch::video::IVideoDriverPtr driver = GetVideoDriver();
- CSceneManager* smgr = GetDevice()->getSceneManager();
- #ifdef GLITCH_ENABLE_IRRADIANCE_SUPPORT
- glitch::CIrradianceManager* irrManager = (glitch::CIrradianceManager*)(driver->getIrradianceManager().get());
- #endif // GLITCH_ENABLE_IRRADIANCE_SUPPORT
- #ifdef GLITCH_ENABLE_INDEXED_IRRADIANCE_SUPPORT
- glitch::indexedIrradiance::CIndexedIrradianceManager* irrManager = (glitch::indexedIrradiance::CIndexedIrradianceManager*)(driver->getIrradianceManager().get());
- #endif // GLITCH_ENABLE_INDEXED_IRRADIANCE_SUPPORT
- irrManager->clear();
- s_isIrradianceLoaded = false;
- if(strlen(irradianceFile) > 0)
- {
- MLA_SET_CONTEXT("ignore");
- //#pragma message("there probably is a way to avoid creating a memory map here")
- //gIrradiance = GameDataFilesMgr::GetInstance()->getFile(GameDataFilesMgr::MMF_IRRADIANCE);
- //if(gIrradiance)
- {
- //gIrradiance.createAndMap("irradiance.bin", 30*1024*1024);
- //MemBlockScope a("irradiance.ird", *gIrradiance);
- irrManager->load(irradianceFile);
- //gIrradiance->flushAll();
- //smgr->InitIrradianceSpheres();
- #ifdef GLITCH_ENABLE_IRRADIANCE_SUPPORT
- irrManager->setOneVolumesSampling(true);
- irrManager->setMultipleVolumesSamplingAdditive(false);
- irrManager->setMultipleVolumesSamplingInterpolate(false);
- irrManager->setSamplingOutsideVolumes(true);
- #endif // GLITCH_ENABLE_IRRADIANCE_SUPPORT
- #ifdef GLITCH_ENABLE_INDEXED_IRRADIANCE_SUPPORT
- irrManager->setSamplingAdditive(false);
- irrManager->setSamplingInterpolate(true);
- irrManager->setSamplingOutsideVolumes(true);
- //irrManager->setMaxVolumeDistance(500.0f);
- #endif // GLITCH_ENABLE_INDEXED_IRRADIANCE_SUPPORT
- s_isIrradianceLoaded = true;
- glitch::video::CGlobalMaterialParameterManager* globalParams = GetVideoDriver()->getGlobalMaterialParameters();
- if(globalParams->getParameterID("IrrAmbientDiffuseMult"))
- {
- glitch::core::vector3df values(0.2f, 2.0f, 0.0f);
- globalParams->setParameter(globalParams->getParameterID("IrrAmbientDiffuseMult"), values);
- }
- }
- }
- else
- {
- // do nothing if there is no irrandiance file or outside.
- }
- GS3DStuff::UpdateMaterialTechniques();
- }
- #endif
- StoryManager::GetInstance()->UpdateMissionTriggers();
- currentLocation = id;
- streamingInit(); // Need to stream the new location.
- }
- }
- int GS3DStuff::GetCurrentLocation()
- {
- return currentLocation;
- }
- void GS3DStuff::InitTreeShaders()
- {
- if(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, removeTreeShaders))
- return;
- int activeTreeConfig = DataIdx(TreeShaderInfos, Normal);
- GLF_ASSERTMSG(activeTreeConfig >= 0, "Did not find find a config TreeShaderInfos.Normal this is used by default by the game engine for the tree shader params init\n");
- if(activeTreeConfig < 0) return;
- g_WindParams[0] = DataByIdx(TreeShaderInfos, activeTreeConfig, strength);
- g_WindParams[1] = DataByIdx(TreeShaderInfos, activeTreeConfig, branch);
- g_WindParams[2] = DataByIdx(TreeShaderInfos, activeTreeConfig, detail);
- g_WindParams[3] = DataByIdx(TreeShaderInfos, activeTreeConfig, freq);
- glitch::core::vector3df dir = DataGetVec3(TreeShaderInfos, activeTreeConfig, direction);
- g_WindParams2[0] = dir.getX();
- g_WindParams2[1] = dir.getY();
- g_WindParams2[2] = dir.getZ();
- g_WindParams2[3] = DataByIdx(TreeShaderInfos, activeTreeConfig, factor);
- UpdateTreeShaders();
- }
- void GS3DStuff::UpdateTreeShaders()
- {
- if(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, removeTreeShaders))
- return;
- GetVideoDriver()->getGlobalMaterialParameters()->setParameter(
- GetVideoDriver()->getGlobalMaterialParameters()->getParameterID("windParams"), g_WindParams);
- glitch::core::vector3df dir = glitch::core::vector3df(g_WindParams2[0], g_WindParams2[1], g_WindParams2[2]);
- dir.normalize();
- GetVideoDriver()->getGlobalMaterialParameters()->setParameter(
- GetVideoDriver()->getGlobalMaterialParameters()->getParameterID("windParams2"), glitch::core::vector4df(dir[0], dir[1], dir[2], g_WindParams2[3]));
- }
- void GS3DStuff::SetFakeFrameBuffer()
- {
- glitch::video::CGlobalMaterialParameterManager* globalParams = GetVideoDriver()->getGlobalMaterialParameters();
- glitch::video::ITexturePtr tex = GetTextureManager()->getTexture("fakeFramebuffer.tga");
- if (globalParams->getParameterID("FrameBuffer") != u16(-1))
- {
- globalParams->setParameter(globalParams->getParameterID("FrameBuffer"), tex);
- }
- }
- void GS3DStuff::SetCubeMap(StdString cubemapName)
- {
- bool isDay = DayTime::Get().isDay();
- SetCubeMap(cubemapName, isDay);
- }
- void GS3DStuff::SetCubeMap(StdString cubemapName, bool isDayEnvMap)
- {
- ProfilerScopeScene("GS3DStuff::SetCubeMap", NULL);
- s_isDayEnvMap = isDayEnvMap;
- if (cubemapName.empty())
- {
- return;
- }
- int startPosPostfixExt = cubemapName.find("_night_cube.tga");
- if (startPosPostfixExt <= 0)
- {
- startPosPostfixExt = cubemapName.find("_cube.tga");
- }
- const StdString keyName = cubemapName.substr(0, startPosPostfixExt);
- const StdString dayName = keyName + "_cube.tga";
- const StdString nightName = keyName + "_night_cube.tga";
- StdString finalName;
- glitch::video::ITexturePtr tex;
- do
- {
- if (!isDayEnvMap)
- {
- if (s_currentCubeMapName == nightName)
- return;
- tex = GetTextureManager()->getTexture(nightName.c_str());
- if (tex)
- {
- finalName = nightName;
- break;
- }
- }
- if (s_currentCubeMapName == dayName)
- return;
- finalName = dayName;
- tex = GetTextureManager()->getTexture(dayName.c_str());
- } while (false);
- if (!tex)
- {
- GLF_ASSERTMSG(false, "Could not load cube map: %s\n\n", dayName.c_str());
- return;
- }
- s_currentCubeMapName = finalName;
- glitch::video::CGlobalMaterialParameterManager* globalParams = GetVideoDriver()->getGlobalMaterialParameters();
- if (globalParams->getParameterID("ReflectionSampler") != u16(-1))
- {
- globalParams->setParameter(globalParams->getParameterID("ReflectionSampler"), tex);
- }
- if (globalParams->getParameterID("CubeMapSampler") != u16(-1))
- {
- globalParams->setParameter(globalParams->getParameterID("CubeMapSampler"), tex);
- }
- }
- void GS3DStuff::UpdateCubeMap()
- {
- bool isDay = DayTime::Get().isDay();
- UpdateCubeMap(isDay);
- }
- void GS3DStuff::UpdateCubeMap(bool isDayEnvMap)
- {
- if (isDayEnvMap != s_isDayEnvMap)
- {
- SetCubeMap(s_currentCubeMapName, isDayEnvMap);
- }
- }
- bool GS3DStuff::isInGame(bool fadeIsInGame)
- {
- return !(CinematicManager::GetInstance()->isInCinematicOrScriptedCutScene()
- || isStreaming()
- || (FadeManager::GetInstance()->IsRenderingFullyOpaque() && !fadeIsInGame)
- || s_loadingDisplayed
- || GS3DStuff::isStreaming());
- }
- // static function
- glitch::video::E_ORIENTATION GS3DStuff::getDefaultOrientation()
- {
- return glitch::video::EO_270;
- }
- void GS3DStuff::showLoading()
- {
- if(!StateMachine::s_isInMainMenu)
- {
- //QUEUE_DIALOG_BY_CONTENT_ID(DefaultDialog, Kst(StrID, INIT_LOADING));
- s_loadingDisplayed = true;
- }
- }
- void GS3DStuff::hideLoading()
- {
- if(!StateMachine::s_isInMainMenu)
- {
- DialogMgr()->CloseDialog(Cst(DialogType, Default));
- s_loadingDisplayed = false;
- }
- }
- //// static function
- //// Transforms the driver's orientation (rotation angle) into the corresponding glf orientation
- //glf::Orientation GS3DStuff::GetCurrentGlfOrientation()
- //{
- // switch (GetCurrentOrientation())
- // {
- // case glitch::video::EO_90 :
- // return glf::ORIENTATION_LANDSCAPE_LEFT;
- //
- // case glitch::video::EO_270 :
- // return glf::ORIENTATION_LANDSCAPE_RIGHT;
- //
- // default:
- // ASSERT(false); // invalid orientation
- // return glf::ORIENTATION_UNDEFINED;
- // }
- //}
- // this is a static function
- glitch::video::E_ORIENTATION GS3DStuff::GetCurrentOrientation()
- {
- #ifdef WIN32
- // on pc, return EO_270 because DrivingControlHandler & FlyingControlHandler expect either EO_270 or EO_90!
- return glitch::video::EO_270;
- #else
- return s_orientation;
- #endif // _WIN32
- }
- void GS3DStuff::DayStateChanged(bool hasTransition /*= true*/)
- {
- char toState[16] = { 0 };
- bool isDay = DayTime::Get().isDay();
- if (isDay)
- {
- if(DayTime::Get().isState(DayTime::Day) || !hasTransition)
- {
- strcpy(toState, flash_constants::events::GameEvent::TIME_DAY);
- }
- }
- else
- {
- if(DayTime::Get().isState(DayTime::Night) || !hasTransition)
- {
- strcpy(toState, flash_constants::events::GameEvent::TIME_NIGHT);
- }
- }
- if(strlen(toState) > 0)
- {
- menu::menuEventMgr::MenuEventManager::Members members;
- gameswf::ASMember toMember;
- toMember.m_name = "toTime";
- toMember.m_value = toState;
- members.push_back(&toMember);
- gameswf::ASMember fromMember;
- if(hasTransition)
- {
- fromMember.m_name = "fromTime";
- fromMember.m_value = isDay ? flash_constants::events::GameEvent::TIME_NIGHT : flash_constants::events::GameEvent::TIME_DAY;
- members.push_back(&fromMember);
- }
- GetMenuEventMgr()->DispatchEvent(SwfManager::SWF_HUD, flash_constants::events::GameEvent::TIME_CHANGE, members);
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateInvisibles()
- {
- ProfilerScopeGameplay("UpdateInvisibles", NULL);
- // !! WARNING !! MC_WRN_INVISIBLE
- // This approach (spreading the update on multiple frames) is not 100% safe because
- // we are using a ->next operator. If the same items are always added and removed every frame, and
- // the item where the iteration stop is one of those, it will always stop there. And since
- // in the next frame the object is not valid anymore, it will restart from scratch at every frame.
- // This will cause any following item on the list to be never updated.
- // As a solution, we can start from a random one instead of the first one, but how will
- // that impact on perfomances? There is no random access with the ->next operator.
- // However this specific condition is probably very unlikely.
- // Last invisible object updated
- static LevelObjectHandle s_lastInvisibleLOUpdate;
- // Size of the block of the invisible objects list that is updated at each frame
- static size_t s_invisibleListBlockSize;
- // m_lastInvisibleLOUpdate is where I stopped at last frame
- const bool isStillValid = (s_lastInvisibleLOUpdate.get_no_assert() != 0);
- LevelObject* lo;
- if(!isStillValid) // item changed or end of list reached
- {
- s_invisibleListBlockSize = ( gom->GetObjectList(Kst(ObjectFrameActions, JustUpdate)).Size() / (float) FRAMES_FOR_COMPLETE_INVISIBLE_LIST_UPDATE ) +1;
- lo = gom->GetFirstLo(Kst(ObjectFrameActions, JustUpdate));
- }
- else
- {
- // continue from here
- lo = s_lastInvisibleLOUpdate.get();
- }
- bool checkForDespawnThisFrame = ((gCheckForDespawnFrame + 2) & 3) == 3;
- // now iterate an appropriate number of times
- for(int i = s_invisibleListBlockSize; i > 0 && lo; --i)
- {
- if(checkForDespawnThisFrame)
- {
- // check for despawns and remove them
- LevelObject* despawned = checkForDespawn(lo);
- if(!despawned)
- {
- break;
- }
- if(despawned != lo)
- {
- lo = despawned;
- continue;
- }
- }
- LevelObject* next = gom->GetNextLo(lo);
- lo->Update(s_dt);
- lo = next;
- }
- s_lastInvisibleLOUpdate = lo;
- }
- void UpdateGameObjectsPerfCounters()
- {
- #if _WIN32 && GLF_ENABLE_DEBUGGER
- GameObjectManager* gom = GameObjectManager::GetInstance();
- static const char* modes[4] = { "updateAndDraw", "justUpdate", "deleted", "paused" };
- static const char* types[4] = { "objectInterface", "levelObject", "transformation", "soundEmitter" };
- for(int i = 0; i < 4; ++i)
- {
- GameObjectInterface* it1 = gom->GetFirst<GameObjectInterface>(i);
- int counts[4] = {0};
- for(GameObjectInterface* goi = gom->GetFirst<GameObjectInterface>(i); goi; goi = gom->GetNext<GameObjectInterface>(goi)) ++counts[0];
- for(LevelObject* lo = gom->GetFirstLo(i); lo; lo = lo->GetNext()) ++counts[1];
- for(Transformation* transf = gom->GetFirst<Transformation>(i); transf; transf = gom->GetNext<Transformation>(transf)) ++counts[2];
- for(SoundEmitter* emm = gom->GetFirst<SoundEmitter>(i); emm; emm = gom->GetNext<SoundEmitter>(emm)) ++counts[3];
- for(int j= 0; j < asizeof(counts); ++j) {
- std::string perfName = std::string(modes[i]) + "." + types[j];
- glf::debugger::PerfCounters::UpdateValue(perfName.c_str(), counts[j]);
- perfName = std::string(types[j]) + "." + modes[i];
- glf::debugger::PerfCounters::UpdateValue(perfName.c_str(), counts[j]);
- }
- }
- #endif
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateVisibles()
- {
- ProfilerScopeGameplay("UpdateVisibles", NULL);
- TriggerZone::SetCurrentTriggerZone(0);
- for (int i = 0; i < s_vehicles.size(); ++i)
- {
- if (s_vehicles[i])
- {
- s_vehicles[i]->SetWasAttackedThisFrame(false);
- }
- }
- for (int i = 0; i < s_npcs.size(); ++i)
- {
- if (s_npcs[i])
- {
- s_npcs[i]->SetWasAttackedThisFrame(false);
- }
- }
- /////////////////////////////////////////////
- // Reset stuff
- Player::GetPlayer()->ResetLastDamageFilter();
- s_vehicles.clear();
- s_npcs.clear();
- s_players.clear();
- //non_vehicles.clear();
- UpdateGameObjectsPerfCounters();
- if(!CinematicManager::GetInstance()->isInBdaeCinematic()) // Prevent the player from being killed when in a cinematic.
- {
- LevelObject* lo = gom->GetFirstLo(Kst(ObjectFrameActions, UpdateAndDraw));
- size_t num = 0;
- bool checkForDespawnThisFrame = (gCheckForDespawnFrame++ & 3) == 3;
- GameObjectManager::DebugStats& dbgStats = GameObjectManager::GetInstance()->GetDebugStats();
- dbgStats.Reset();
- while(lo)
- {
- dbgStats.numObjects++;
- if(checkForDespawnThisFrame)
- {
- // check for despawns and remove them
- LevelObject* despawned = checkForDespawn(lo);
- if(!despawned)
- {
- break;
- }
- if(despawned != lo)
- {
- lo = despawned;
- continue;
- }
- }
- LevelObject* next = gom->GetNextLo(lo);
- #if GANGSTAR_RETAIL_BUILD == 0
- if(GameObjectManager::isVehicle(lo))
- {
- dbgStats.numVehicles++;
- }
- else if(GameObjectManager::isCharacter(lo))
- {
- dbgStats.numCharacters++;
- }
- #endif
- lo->TestForUpdate();
- bool isTriggerZone = glf::DynamicCast<TriggerZone>(lo) != 0;
- if(lo->IsUpdating() && (lo->IsVisible() || (GameObjectManager::isCharacter(lo) || GameObjectManager::isProjectile(lo) || isTriggerZone)))
- {
- SCOPE_TRACE("LOUpdate", "Updating %s...\n", lo->GetName());
- dbgStats.numVisibleObjects++;
- if(GameObjectManager::isVehicle(lo))
- {
- dbgStats.numVisibleVehicles++;
- s_vehicles.push_back(static_cast<Vehicle*>(lo));
- }
- else if(GameObjectManager::isCharacter(lo))
- {
- dbgStats.numVisibleCharacters++;
- if(!static_cast<Character*>(lo)->isPlayer())
- {
- s_npcs.push_back(static_cast<NPC*>(lo));
- }
- else
- {
- s_players.push_back(static_cast<Player*>(lo));
- }
- }
- else
- {
- //ProfilerScope("Update");
- lo->Update(s_dt);
- }
- }
- else
- {
- SCOPE_TRACE("LOUpdate", "Skipping Updating %s...\n", lo->GetName());
- }
- lo = next;//gom->GetNextLo(lo);
- ++num;
- }
- #if GLF_ENABLE_DEBUGGER
- glf::debugger::PerfCounters::UpdateValue("LevelObject.UpdateAndDraw", num);
- #endif
- }
- // Spawned fix. Remove spawned actors silently disabled from paused list if they don't have a owner.
- //size_t num = 0;
- //LevelObject *lo = gom->GetFirstLo(Kst(ObjectFrameActions, Paused));
- //while(lo)
- //{
- // /*if (TEST_FLAG(lo->m_flags, Kst(GameObjectFlag, SilentDisable)))
- // {
- // LevelObject* despawned = checkForDespawn(lo);
- // if(!despawned)
- // {
- // break;
- // }
- // if (despawned != lo)
- // {
- // //SCOPE_TRACE("DBG", "DESPAWNED %s, %s | LO %s, %s\n", despawned->GetName(), gom->GetAlias(despawned), lo->GetName(), gom->GetAlias(lo));
- // lo = despawned;
- // continue;
- // }
- // }*/
- // lo = gom->GetNextLo(lo);
- //}
- #if GLF_ENABLE_DEBUGGER
- //glf::debugger::PerfCounters::UpdateValue("LevelObject.Paused", num);
- #endif
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateDayTime()
- {
- ProfilerScopeGameplay("UpdateDayTime", NULL);
- DayTime& dayTime = DayTime::Get();
- if (dayTime.needsUpdate() || !StoryManager::GetInstance()->isInMission()) // Lock Daytime during mission.
- {
- dayTime.update(s_dt);
- if(dayTime.stateChangedThisFrame())
- {
- DayStateChanged();
- }
- }
- else
- {
- dayTime.UpdateInfo();
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateBehaviors()
- {
- ProfilerScopeGameplay("UpdateBehaviors", NULL);
- if(BehaviorManager::GetInstance()->needReset())
- {
- BehaviorManager::GetInstance()->reset();
- for(int i = 0; i < s_npcs.size(); i++)
- {
- if (s_npcs[i])
- {
- s_npcs[i]->resetBehavior(BehaviorManager::CHARACTER);
- }
- }
- for(int i = 0; i < s_players.size(); i++)
- {
- if (s_npcs[i])
- {
- s_players[i]->resetBehavior(BehaviorManager::PLAYER);
- }
- }
- Player::GetPlayer()->resetBehavior(BehaviorManager::PLAYER);
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateCharacters()
- {
- // [MB] Don't update characters while fading
- if(/*FadeManager::GetInstance()->IsFullyIdle() &&*/ !isStreaming() && !g_Loading)
- {
- ProfilerScopeGameplay("UpdateCharacters", NULL);
- {
- ProfilerScopeGameplay("UpdateNpc", NULL);
- if(s_npcs.size() > 0)
- {
- int forceUpdateNPCIdx = -1;
- for(int i=0; i<s_npcs.size(); i++)
- {
- if(s_npcs[i] && s_npcs[i]->m_forceUpdate)
- {
- s_npcs[i]->m_forceUpdate = false;
- forceUpdateNPCIdx = i;
- break;
- }
- }
- if(forceUpdateNPCIdx < 0)
- {
- s_roundRobinNPCIdx = (s_roundRobinNPCIdx + 1) % s_npcs.size();
- }
- int updateNPCIdx = (forceUpdateNPCIdx < 0 ? s_roundRobinNPCIdx : forceUpdateNPCIdx);
- SCOPE_TRACE("RoundRobin", "*********************************************************************\n");
- SCOPE_TRACE("RoundRobin", "There is %d npcs to update s_roundRobinNPCIdx=%d ... \n", s_npcs.size(), s_roundRobinNPCIdx);
- SCOPE_TRACE("RoundRobin", "*********************************************************************\n");
- for(int i=0; i<s_npcs.size(); i++)
- {
- //This is done here because for now it's a simple "one per frame" round robin for all "skippable" expensive npc update parts.
- //If this becomes more complex, please wrap it correctly.
- //see LevelObject UpdateOptim enum in Level Object, there is a method SetUpdateOptim(int updateOptim) to set only specific update to be skipped...
- //for now : we simply update everything for a single NPC that have the round robin token per frame, so just clear all the flags accordingly.
- bool hasRoundRobinToken = (i == updateNPCIdx);
- if (s_npcs[i])
- {
- // flinch NPCS os being hijacked can't delay their animation updates made by the grapher
- hasRoundRobinToken |= s_npcs[i]->isFlinching() || s_npcs[i]->isInMeleeStrike() || s_npcs[i]->testFlag(IS_HIJACKED);
- hasRoundRobinToken |= Player::GetPlayer()->getTarget() == s_npcs[i];
- s_npcs[i]->SetAllUpdateOptim(hasRoundRobinToken == false);
- SCOPE_TRACE("RoundRobin", "Updating %d==>%s\n", i, s_npcs[i]->GetName());
- s_npcs[i]->Update(s_dt);
- }
- }
- }
- clearWorldEventFlags();
- }
- {
- if(!StateMachine::s_isInMainMenu
- #if _WIN32
- && !gLodProfiling
- #endif
- )
- {
- ProfilerScopeGameplay("UpdatePlayer", NULL);
- Application::GetInstance()->GetControlManager()->update();
- Player::GetPlayer()->Update(s_dt);
- Player::GetPlayer()->updateSunOcclusion();
- }
- }
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateVehicles()
- {
- // [MB] Don't update characters while fading
- if(/*FadeManager::GetInstance()->IsFullyIdle() &&*/ !isStreaming() && !g_Loading)
- {
- ProfilerScopeGameplay("UpdateVehicles", NULL);
- for(int i=0; i<s_vehicles.size(); i++)
- {
- s_vehicles[i]->Update(s_dt);
- }
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdatePhysics()
- {
- int updates = 0;
- gNumPhysicIteration = 0;
- {
- ProfilerScopePhysics("UpdateStaticCollisions", NULL);
- #ifndef PHYSICS_USING_ASYNCHRONOUS_UPDATE
- PhysicsWorld::GetInstance()->Update(s_dt * 0.001f);
- #endif
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateCamera()
- {
- if(gTogglePhysic && FadeManager::GetInstance()->IsFullyIdle() && !isStreaming() && !g_Loading)
- {
- //if(Player::GetPlayer()->isInAVehicle())
- {
- ProfilerScopeScene("UpdateCamera", NULL);
- gTimeAccumulator += (Application::GetInstance()->getSmoothDt() * 0.001f);
- int numberOfConstantFrames = int(gTimeAccumulator / PHYSIC_UPDATE_RATE);
- gTimeAccumulator -= PHYSIC_UPDATE_RATE * numberOfConstantFrames;
- if(numberOfConstantFrames > 240)
- {
- // Maximum X frames
- // Time elapsed is too high, reset and return
- gTimeAccumulator = 0.0f;
- numberOfConstantFrames = 240;
- }
- else if(numberOfConstantFrames <= 0)
- {
- numberOfConstantFrames = 1;
- }
- float cameraTime = Application::GetInstance()->getSmoothDt() * 0.001f / (float)numberOfConstantFrames;
- while(--numberOfConstantFrames >= 0)
- {
- // update the camera in time with the physics updates so we don't get positional jumps
- ProfilerScopeScene("cam", NULL);
- //CameraManager::GetInstance()->update(PHYSIC_UPDATE_RATE);//*1000);
- // Only set listener position once per frame to avoid unnecessary vox calls
- CameraManager::GetInstance()->setListener(numberOfConstantFrames == 0);
- CameraManager::GetInstance()->update(cameraTime);
- }
- }
- }
- else
- {
- CameraManager::GetInstance()->update(Application::GetInstance()->getSmoothDt() * 0.001f);
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateVehicleNodeAndProximity()
- {
- ProfilerScopeGameplay("UpdateVehicleNodeAndProximity", NULL);
- for (int i = 0; i < s_vehicles.size(); i++)
- {
- s_vehicles[i]->updateGlitchNode();
- }
- if(!Player::GetPlayer()->isDead())
- {
- checkVehicleProximity(Player::GetPlayer());
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateScripts()
- {
- ProfilerScopeGameplay("scripts", NULL);
- StoryManager::GetInstance()->Update(s_dt);
- CinematicManager::GetInstance()->update(s_dt);
- //ScriptManager::GetInstance()->update(s_dt);
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateWantedAndTrail()
- {
- ProfilerScopeScene("wanted + trail", NULL);
- //if(!Player::GetPlayer()->isInAVehicle())
- //{ CameraManager::GetInstance()->update(static_cast<float>(s_dt)*0.001f); }
- WantedMgr()->update(s_dt);
- if(s_TrailMgr)
- {
- s_TrailMgr->Update();
- }
- #ifdef USE_DECAL_MANAGER
- if(s_DecalManager)
- {
- s_DecalManager->Update(s_dt);
- }
- #endif
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateAttachDSP()
- {
- ProfilerScopeSounds("attach dsp", NULL);
- if(DataByIdx(PhonePerformanceProfiles, gPhonePerfId, snd_reverb) || GET_DEBUG_SWITCH("EnableReverb"))
- {
- SndMgr()->AttachDSP();
- }
- else
- {
- SndMgr()->DetachDSP();
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdatePurgeGameObjectAndTriggerZone()
- {
- {
- ProfilerScopeScene("GameObjectManager::purge", NULL);
- GameObjectManager::GetInstance()->purge();
- }
- TriggerZone* zone = TriggerZone::GetCurrentTriggerZone();
- if ( zone != s_lastTriggerZone/* || (zone && zone->UseTriggerButton() && !zone->IsTriggerButtonVisible()) */)
- {
- if(zone)
- {
- zone->SetAsCurrentTriggerButton();
- }
- s_lastTriggerZone = zone;
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- void GS3DStuff::UpdateSunOcclusion()
- {
- #ifdef SUN_OCCLUSION
- ProfilerScopeGameplay("UpdateSunOcclusion", NULL);
- if(!CinematicManager::GetInstance()->isInBdaeCinematic())
- {
- // !! WARNING !! MC_WRN_INVISIBLE
- // This approach (spreading the update on multiple frames) is not 100% safe because
- // we are using a ->next operator. If the same items are always added and removed every frame, and
- // the item where the iteration stop is one of those, it will always stop there. And since
- // in the next frame the object is not valid anymore, it will restart from scratch at every frame.
- // This will cause any following item on the list to be never updated.
- // As a solution, we can start from a random one instead of the first one, but how will
- // that impact on perfomances? There is no random access with the ->next operator.
- // However this specific condition is probably very unlikely.
- // Last invisible object updated
- static LevelObjectHandle s_lastSunOcclusionUpdate;
- // Size of the block of the invisible objects list that is updated at each frame
- static size_t s_lastSunOccclusionListBlockSize;
- // s_lastSunOcclusionUpdate is where I stopped at last frame
- const bool isStillValid = (s_lastSunOcclusionUpdate.get_no_assert() != 0);
- LevelObject* lo;
- if(!isStillValid) // item changed or end of list reached
- {
- s_lastSunOccclusionListBlockSize = FRAMES_FOR_COMPLETE_SUN_OCCLUSION_UPDATE ?
- ( gom->GetObjectList(Kst(ObjectFrameActions, UpdateAndDraw)).Size() / (float) FRAMES_FOR_COMPLETE_SUN_OCCLUSION_UPDATE ) +1 // spread over frames
- : 0; // only one object
- lo = gom->GetFirstLo(Kst(ObjectFrameActions, JustUpdate));
- }
- else
- {
- // continue from here
- lo = s_lastSunOcclusionUpdate.get();
- }
- // now iterate an appropriate number of times
- int i = s_lastSunOccclusionListBlockSize;
- while(i > 0 && lo)
- {
- LevelObject* next = gom->GetNextLo(lo);
- if(lo->IsVisible() && lo != Player::GetPlayer()) // player is updated every frame anyway
- {
- lo->updateSunOcclusion();
- --i;
- }
- lo = next;
- }
- s_lastSunOcclusionUpdate = lo;
- }
- #endif
- }
- bool GS3DStuff::OmitOcclusionUpdate(int index)
- {
- return s_sunOcclusionFrameCounter != (index % s_sunOcclusionFrameCycle);
- }
- void GS3DStuff::PreloadEffects(glitch::video::IVideoDriver* driver)
- {
- MLA_SET_CONTEXT("GS3DStuff::PreloadEffects");
- for (int i = 0; i < DataCount(PreloadEffectsList); ++i)
- {
- const char* fileName = DataByIdx(PreloadEffectsList, i, BdaeFile);
- const char* effectName = DataByIdx(PreloadEffectsList, i, Name);
- glitch::collada::CColladaDatabase database(fileName);
- glitch::video::CMaterialRendererPtr materialRenderer = database.constructEffect(driver, effectName, 0);
- }
- }
- float GS3DStuff::GetPercentBasedOnLoadingStep()
- {
- return 100 * (float(s_load_step + 3) / float(LoadingSteps::End));
- }
- void GS3DStuff::UpdateLoadingProgress(float percents, bool isLoadingBarVisible)
- {
- gameswf::ASValue args[2];
- args[0] = (percents > 100.f || percents < 0.f) ? 100.f : percents;
- args[1] = isLoadingBarVisible;
- SwfManager::MenuInfo* topStack = SwfManager::GetInstance()->GetTopMenuInStack();
- if (topStack)
- {
- topStack->m_renderFX->findClass("menus.main", "Splash").invokeStaticMethod("UpdateLoadingProgress", args, 2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement