Ejemplo n.º 1
0
void Angelica::listen(const char* stimulus) { //Angelica's ears+eyes
    ifstream stim(stimulus); //open stimulus file
    if(!stim) { //if the file did not open
        clog << "ERROR: Could not open stimulus file." << endl; //error
    } else {  //otherwise continue
        char c;
        int silenceCounter = 0;

        cout << "\nAngelica Says:" << endl;
        while(silenceCounter < SILENCE_LIMIT) { //listen until silence
            if(stim.eof()) {      //if at the end of the input
                silenceCounter++;  //record a round of silence
                b->cycleNet();    //process thought
                t->speak();        //respond to stimulus
            } else {              //otherwise
                stim >> c;         //get simulus
                t->sensor(c);      //see somthing and stimulate brain
                b->cycleNet();    //process thought
                t->speak();        //respond to stimulus
            }
        }

        cout << "\n\n";
    }
    return;
}
//input path: path to image
void ImageSignature::getSignature(Mat &m)
{
	rimage stim( dim, dim );
	//stim.LoadByte(path, 18 );
	stim.loadImage(m);//I added this insted of LoadByte
    PCNN Net ( dim, dim );
    Net.vf = 0;
    stim /= 256;
    stim.UpsideDown( );
	if(testRimage == stim){
		cout << "YES OMG!";
	}else
		cout << "NO\n";
	testRimage = stim;
    int i;
    for( i=0; i<Niters; i++ ) {
		elementType sum =Net.Iterate( stim );//Net.FastIterate(stim);
		//cout << sum <<endl;
		if(i >=  numberofcutsitrs)
		{
		signature[i + start - numberofcutsitrs]= sum;
		//signature += sum + " ";
		//cout<<signature<<endl;
		char * c =new char();
		
		gSignature += _itoa(sum, c,10); 
		//delete c;
		gSignature += " ";
		}
		//cout <<"gSignature = "<< gSignature << endl;
    }
	start += Niters - numberofcutsitrs;
}
Ejemplo n.º 3
0
void CProjectile::FlashbangEffect(const SFlashbangParams *flashbang)
{
	if(!flashbang)
		return;

	const float radius = flashbang->maxRadius;

	if(!gEnv->pAISystem)
		return;

	// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
	EntityId ownerId = m_ownerId;
	IActor *pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);

	if(pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
		ownerId = pActor->GetLinkedVehicle()->GetEntityId();

	SAIStimulus stim(AISTIM_GRENADE, AIGRENADE_FLASH_BANG, ownerId, GetEntityId(),
					 GetEntity()->GetWorldPos(), ZERO, radius);
	gEnv->pAISystem->RegisterStimulus(stim);

	SAIStimulus stimSound(AISTIM_SOUND, AISOUND_WEAPON, ownerId, 0,
						  GetEntity()->GetWorldPos(), ZERO, radius * 3.0f);
	gEnv->pAISystem->RegisterStimulus(stimSound);
}
Ejemplo n.º 4
0
void * worker_thread(void *contract_v){

  
  struct contract *contract = (struct contract*)(contract_v); 
  
  while(contract->fired==0) {//dont exit thread
    
    if(contract->pool_size!=contract->current_job) {

      if(contract->current_job+1==max_queue) {
        contract->current_job=0;
      } else {
        contract->current_job++;
      }

      //work
      stim(&(work_pool[contract->id][contract->current_job]));

      contract->progress+=contract->progress_step;
      
    
    } else{}

    if(contract->pool_size==contract->current_job) {//last job in queue
      //printf("[sleeping]");
      //proc_err("INFO:stimpool.c:worker finished all jobs\n",5);
      usleep(contract->time_to_sleep);
    } else {
      //printf("[overtime(cj/pool)(%d / %d)]", (*contract).current_job ,
      //(*contract).pool_size);
  
    }
  }
}
Ejemplo n.º 5
0
void CSmokeManager::CreateNewSmokeInstance(EntityId grenadeId, EntityId grenadeOwnerId, float fMaxRadius)
{
    IEntity * pGrenade = gEnv->pEntitySystem->GetEntity(grenadeId);

    int iNewSmokeInstanceIndex = m_numActiveSmokeInstances;

    //If all of the smoke instances are used up, get the index of the next one to be deleted
    //	and re-use that instance
    if(iNewSmokeInstanceIndex >= MAX_SMOKE_INSTANCES)
        {
            float fLeastLifeLeft = kSmokeLingerTime;

            iNewSmokeInstanceIndex = 0;

            for(int i = 0; i < iNewSmokeInstanceIndex; i++)
                {
                    SSmokeInstance& smokeInstance = m_smokeInstances[i];
                    if(smokeInstance.fTimer < fLeastLifeLeft)
                        {
                            iNewSmokeInstanceIndex = i;
                            fLeastLifeLeft=smokeInstance.fTimer;
                        }
                }
        }
    else
        {
            m_numActiveSmokeInstances++;
        }

    //Fill out the smoke instance with the new data
    SSmokeInstance& newSmokeInstance = m_smokeInstances[iNewSmokeInstanceIndex];
    newSmokeInstance.state					= eSIS_Active_PhysicsAwake;
    newSmokeInstance.vPositon				= pGrenade->GetPos();
    newSmokeInstance.grenadeId			= grenadeId;
    newSmokeInstance.fMaxRadius			= fMaxRadius;
    newSmokeInstance.fCurrentRadius = 0.1f;
    newSmokeInstance.fTimer					= 0.0f;

    if (!gEnv->bMultiplayer)
        {
            CreateSmokeObstructionObject(newSmokeInstance);

            if (gEnv->pAISystem)
                {
                    // Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
                    EntityId ownerId = grenadeId;
                    IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);
                    IVehicle* pVehicle = pActor ? pActor->GetLinkedVehicle() : NULL;
                    if (pVehicle)
                        {
                            ownerId = pVehicle->GetEntityId();
                        }

                    SAIStimulus stim(AISTIM_GRENADE, AIGRENADE_SMOKE, ownerId, grenadeId, newSmokeInstance.vPositon, ZERO, kMaxSmokeRadius*1.5f);
                    gEnv->pAISystem->RegisterStimulus(stim);
                }
        }
}
Ejemplo n.º 6
0
void TacticalManager::EntityCreated( const EntityInstance &ei )
{
	StimulusPtr stim( new Stimulus );
	stim->mEntity = ei.mEntity;
	stim->mEntInfo = ei.mEntInfo;

	EngineFuncs::EntityPosition( ei.mEntity, stim->mPosition );

	mStimulus[ ei.mEntity.GetIndex() ] = stim;
}
Ejemplo n.º 7
0
    void TestMonodomainSquareWaveStimulus()
    {
        // this parameters are a bit arbitrary, and chosen to get a good spread of voltages
        HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(1.75));
        HeartConfig::Instance()->SetSimulationDuration(2); //ms
        HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements");
        HeartConfig::Instance()->SetOutputDirectory("MonoNeumannSquare");
        HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d");

        ZeroStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory;
        MonodomainProblem<1> monodomain_problem( &cell_factory );

        monodomain_problem.Initialise();
        HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1*1.75/0.0005);

        // create boundary conditions container
        boost::shared_ptr<BoundaryConditionsContainer<1,1,1> > p_bcc(new BoundaryConditionsContainer<1,1,1>);
        SimpleStimulus stim(4*1.75/0.0005, 0.5);
        StimulusBoundaryCondition<1>* p_bc_stim = new StimulusBoundaryCondition<1>(&stim);

        // get mesh
        AbstractTetrahedralMesh<1,1> &mesh = monodomain_problem.rGetMesh();
        // loop over boundary elements
        AbstractTetrahedralMesh<1, 1>::BoundaryElementIterator iter;
        iter = mesh.GetBoundaryElementIteratorBegin();
        while (iter != mesh.GetBoundaryElementIteratorEnd())
        {
            // if the element is on the left of the mesh, add a stimulus to the bcc
            if (((*iter)->GetNodeLocation(0))[0]==0.0)
            {
                p_bcc->AddNeumannBoundaryCondition(*iter, p_bc_stim);
            }
            iter++;
        }

        // pass the bcc to the monodomain problem
        monodomain_problem.SetBoundaryConditionsContainer(p_bcc);

        monodomain_problem.Solve();

        // check some voltages
        ReplicatableVector voltage_replicated(monodomain_problem.GetSolution());
        double atol=8e-3;

        TS_ASSERT_DELTA(voltage_replicated[1], 22.4940, atol);
        TS_ASSERT_DELTA(voltage_replicated[3], 22.6008, atol);
        TS_ASSERT_DELTA(voltage_replicated[5], 23.3054, atol);
        TS_ASSERT_DELTA(voltage_replicated[7], 24.4932, atol);
        TS_ASSERT_DELTA(voltage_replicated[9], 14.5184, atol);
        TS_ASSERT_DELTA(voltage_replicated[10],3.7081, atol);
    }
int sc_main( int argc, char* argv[])
{
   
   // create constants
   const double TIME_RESOLUTION = 1.0;
   const double TOTAL_SIMULATION_TIME = 500.0;
   const double CLOCK_PERIOD = 2.0;

   // set time parameters
   sc_set_time_resolution( TIME_RESOLUTION , SC_NS );
   sc_time simulation_time(TOTAL_SIMULATION_TIME,SC_NS);
   sc_time clock_time(CLOCK_PERIOD,SC_NS);

   // generate clock 
   sc_clock clock("clock",clock_time);

   // create connecting signals from stimulus-->dut
   sc_signal< XY_DATA_TYPE > x_stim,y_stim;
   sc_signal< XY_DATA_TYPE> x_out,y_out;
   sc_signal< Z_DATA_TYPE > z_stim;
   sc_signal< Z_DATA_TYPE > z_out;
   sc_signal< Z_DATA_TYPE > theta_stim;
   sc_signal< RESET_TYPE> reset_stim;

   // create stimulus signal object
   Stimulus stim("stimulus", TOTAL_SIMULATION_TIME);
   stim.reset(reset_stim);
   stim.clock(clock);
   stim.x_in(x_out);
   stim.y_in(y_out);
   stim.z_in(z_out);
   stim.x_out(x_stim);
   stim.y_out(y_stim);
   stim.z_out(z_stim);

   // create cordic_stage object ( DUT )
   CordicStage< XY_DATA_TYPE, Z_DATA_TYPE, RESET_TYPE> cs("cordic_stage", stim.SHIFT);
   cs.xin(x_stim);
   cs.yin(y_stim);
   cs.zin(z_stim);
   cs.reset(reset_stim);
   cs.xout(x_out);
   cs.yout(y_out);
   cs.zout(z_out);
   cs.clock(clock);

   // begin simulation
   sc_start( simulation_time );

   return 0;
}
Ejemplo n.º 9
0
int sc_main(int argc, char *argv[]){

  sc_signal<bool> clock, reset;
  sc_signal<unsigned short int> count_val;
  sc_signal<char> v_hi, v_lo;

  sc_set_time_resolution(1, SC_US);

  stimul stim("stimuli_mod");
  stim.clk(clock);
  stim.res(reset);

  counter count("counter");
  count.clk(clock);
  count.res(reset);
  count.cnt(count_val);


  bcd_decoder bcd("bcd_decode");
  bcd.val(count_val);
  bcd.hi(v_hi);
  bcd.lo(v_lo);

  sc_trace_file *tf = sc_create_vcd_trace_file("traces");  
  sc_trace(tf, reset, "reset");
  sc_trace(tf, clock, "clock");
  sc_trace(tf, count_val, "counter_value");
  sc_trace(tf, v_hi, "BCD_High");
  sc_trace(tf, v_lo, "BCD_low");

  int n_cycles;
  if(argc != 2){
    cout << "default n_cycles = 200\n";
    n_cycles = 200;
  }
  else
    n_cycles = atoi(argv[1]);

  sc_start(n_cycles, SC_US);

  sc_close_vcd_trace_file(tf);

  return 0;

}
Ejemplo n.º 10
0
void testRunGsolve()
{
	double simDt = 0.1;
	// double plotDt = 0.1;
	Shell* s = reinterpret_cast< Shell* >( Id().eref().data() );
	Id kin = makeReacTest();
	double volume = 1e-21;
	Field< double >::set( kin, "volume", volume );
	Field< double >::set( ObjId( "/kinetics/A" ), "concInit", 2 );
	Field< double >::set( ObjId( "/kinetics/e1Pool" ), "concInit", 1 );
	Field< double >::set( ObjId( "/kinetics/e2Pool" ), "concInit", 1 );
	Id e1( "/kinetics/e1Pool/e1" );
	Field< double >::set( e1, "Km", 5 );
	Field< double >::set( e1, "kcat", 1 );
	vector< double > stim( 100, 0.0 );
	for ( unsigned int i = 0; i< 100; ++i ) {
		stim[i] = volume * NA * (1.0 + sin( i * 2.0 * PI / 100.0 ) );
	}
	Field< vector< double > >::set( ObjId( "/kinetics/tab" ), "vector", stim );


	Id gsolve = s->doCreate( "Gsolve", kin, "gsolve", 1 );
	Id stoich = s->doCreate( "Stoich", gsolve, "stoich", 1 );
	Field< Id >::set( stoich, "compartment", kin );
	Field< Id >::set( stoich, "ksolve", gsolve );
	
	Field< string >::set( stoich, "path", "/kinetics/##" );
	s->doUseClock( "/kinetics/gsolve", "process", 4 ); 
	s->doSetClock( 4, simDt );

	s->doReinit();
	s->doStart( 20.0 );
	Id plots( "/kinetics/plots" );
	for ( unsigned int i = 0; i < 7; ++i ) {
		stringstream ss;
		ss << "plot." << i;
		SetGet2< string, string >::set( ObjId( plots, i ), "xplot", 
						"tsr3.plot", ss.str() );
	}
	s->doDelete( kin );
	cout << "." << flush;
}
void CVehicleSeatActionSound::ExecuteTrigger(const TAudioControlID& controlID)
{
	if (controlID == INVALID_AUDIO_CONTROL_ID)
		return;

	if (m_pSeat)
		m_pSeat->ChangedNetworkState(CVehicle::ASPECT_SEAT_ACTION);

	IEntityAudioProxyPtr pIEntityAudioProxy = crycomponent_cast<IEntityAudioProxyPtr>(m_pVehicle->GetEntity()->CreateProxy(ENTITY_PROXY_AUDIO));
	assert(pIEntityAudioProxy.get());

	pIEntityAudioProxy->ExecuteTrigger(controlID, eLSM_None);

	// Report the AI system about the vehicle movement sound.
	if (!gEnv->bMultiplayer && gEnv->pAISystem)
	{
		Vec3 pos = m_pHelper->GetVehicleSpaceTranslation();
		SAIStimulus stim(AISTIM_SOUND, AISOUND_MOVEMENT_LOUD, m_pVehicle->GetEntityId(), 0, pos, ZERO, 200.0f);
		gEnv->pAISystem->RegisterStimulus(stim);
	}

	m_enabled = true;
}
Ejemplo n.º 12
0
//------------------------------------------------------------------------
void CGameRules::ClientExplosion(const ExplosionInfo &explosionInfo)
{
	// let 3D engine know about explosion (will create holes and remove vegetation)
	if (explosionInfo.hole_size > 1.0f && gEnv->p3DEngine->GetIVoxTerrain())
	{
		gEnv->p3DEngine->OnExplosion(explosionInfo.pos, explosionInfo.hole_size, true);
	}

	TExplosionAffectedEntities affectedEntities;

	if (gEnv->bServer)
  {
		CullEntitiesInExplosion(explosionInfo);
		pe_explosion explosion;
		explosion.epicenter = explosionInfo.pos;
		explosion.rmin = explosionInfo.minRadius;
		explosion.rmax = explosionInfo.radius;
		if (explosion.rmax==0)
			explosion.rmax=0.0001f;
		explosion.r = explosion.rmin;
		explosion.impulsivePressureAtR = explosionInfo.pressure;
		explosion.epicenterImp = explosionInfo.pos;
		explosion.explDir = explosionInfo.dir;
		explosion.nGrow = 0;
		explosion.rminOcc = 0.07f;

		// we separate the calls to SimulateExplosion so that we can define different radii for AI and physics bodies
		explosion.holeSize = 0.0f;
		explosion.nOccRes = explosion.rmax>50.0f ? 0:16;




		gEnv->pPhysicalWorld->SimulateExplosion( &explosion, 0, 0, ent_living);

		CreateScriptExplosionInfo(m_scriptExplosionInfo, explosionInfo);
		UpdateAffectedEntitiesSet(affectedEntities, &explosion);

		// check vehicles
		IVehicleSystem *pVehicleSystem = g_pGame->GetIGameFramework()->GetIVehicleSystem();
		uint32 vcount = pVehicleSystem->GetVehicleCount();
		if (vcount > 0)
		{
			IVehicleIteratorPtr iter = g_pGame->GetIGameFramework()->GetIVehicleSystem()->CreateVehicleIterator();
			while (IVehicle* pVehicle = iter->Next())
			{
				if(IEntity *pEntity = pVehicle->GetEntity())
				{
					AABB aabb;
					pEntity->GetWorldBounds(aabb);
					IPhysicalEntity* pEnt = pEntity->GetPhysics();
					if (pEnt && aabb.GetDistanceSqr(explosionInfo.pos) <= explosionInfo.radius*explosionInfo.radius)
					{
						float affected = gEnv->pPhysicalWorld->CalculateExplosionExposure(&explosion, pEnt);
						AddOrUpdateAffectedEntity(affectedEntities, pEntity, affected);
					}
				}
			}
		}

		explosion.rmin = explosionInfo.minPhysRadius;
		explosion.rmax = explosionInfo.physRadius;
		if (explosion.rmax==0)
			explosion.rmax=0.0001f;
		explosion.r = explosion.rmin;
		explosion.holeSize = explosionInfo.hole_size;
		if (explosion.nOccRes>0)
			explosion.nOccRes = -1;	// makes second call re-use occlusion info
		gEnv->pPhysicalWorld->SimulateExplosion( &explosion, 0, 0, ent_rigid|ent_sleeping_rigid|ent_independent|ent_static | ent_delayed_deformations);

		UpdateAffectedEntitiesSet(affectedEntities, &explosion);
		CommitAffectedEntitiesSet(m_scriptExplosionInfo, affectedEntities);

		float fSuitEnergyBeforeExplosion = 0.0f;
		float fHealthBeforeExplosion = 0.0f;
		IActor *pClientActor = g_pGame->GetIGameFramework()->GetClientActor();
		if(pClientActor)
		{
			fHealthBeforeExplosion = (float)pClientActor->GetHealth();
		}
		
		CallScript(m_serverStateScript, "OnExplosion", m_scriptExplosionInfo);    

		if(pClientActor)
		{
			float fDeltaHealth = fHealthBeforeExplosion - static_cast<CPlayer *>(pClientActor)->GetHealth();
			if(fDeltaHealth >= 20.0f)
			{
				SAFE_GAMEAUDIO_SOUNDMOODS_FUNC(AddSoundMood(SOUNDMOOD_EXPLOSION, MIN(fDeltaHealth, 100.0f) ));
			}				
		}		

		// call hit listeners if any
		if (m_hitListeners.empty() == false)
		{
			for (size_t i = 0; i < m_hitListeners.size(); )
			{
				size_t count = m_hitListeners.size();
				m_hitListeners[i]->OnServerExplosion(explosionInfo);
				if (count == m_hitListeners.size())
					i++;
				else
					continue;
			}
		}
  }

	if (gEnv->IsClient())
	{
		if (explosionInfo.pParticleEffect)
			explosionInfo.pParticleEffect->Spawn(true, IParticleEffect::ParticleLoc(explosionInfo.pos, explosionInfo.dir, explosionInfo.effect_scale));

		if (!gEnv->bServer)
		{
			CreateScriptExplosionInfo(m_scriptExplosionInfo, explosionInfo);
		}
		else
		{
			affectedEntities.clear();
			CommitAffectedEntitiesSet(m_scriptExplosionInfo, affectedEntities);
		}
		CallScript(m_clientStateScript, "OnExplosion", m_scriptExplosionInfo);

		// call hit listeners if any
		if (m_hitListeners.empty() == false)
		{
			THitListenerVec::iterator iter = m_hitListeners.begin();
			while (iter != m_hitListeners.end())
			{
				(*iter)->OnExplosion(explosionInfo);
				++iter;
			}
		}
	}

	ProcessClientExplosionScreenFX(explosionInfo);
	ProcessExplosionMaterialFX(explosionInfo);

	if (gEnv->pAISystem && !gEnv->bMultiplayer)
	{
		// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
		EntityId ownerId = explosionInfo.shooterId;
		IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);
		if (pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
			ownerId = pActor->GetLinkedVehicle()->GetEntityId();

		if (ownerId != 0)
		{
			SAIStimulus stim(AISTIM_EXPLOSION, 0, ownerId, 0,
				explosionInfo.pos, ZERO, explosionInfo.radius);
			gEnv->pAISystem->RegisterStimulus(stim);

			SAIStimulus stimSound(AISTIM_SOUND, AISOUND_EXPLOSION, ownerId, 0,
				explosionInfo.pos, ZERO, explosionInfo.radius * 3.0f, AISTIMPROC_FILTER_LINK_WITH_PREVIOUS);
			gEnv->pAISystem->RegisterStimulus(stimSound);
		}
	}

}
    /**
     * Run the same test at different levels of refinement until some convergence criterion is met.
     * @param nameOfTest The name of the convergence test (typically the name in the suite) for use in naming files.
     * \todo This is a scarily long method; could do with some parts extracted?
     */
    void Converge(std::string nameOfTest)
    {
        // Create the meshes on which the test will be based
        const std::string mesh_dir = "ConvergenceMesh";
        OutputFileHandler output_file_handler(mesh_dir);
        ReplicatableVector voltage_replicated;

        unsigned file_num=0;

        // Create a file for storing conduction velocity and AP data and write the header
        OutputFileHandler conv_info_handler("ConvergencePlots"+nameOfTest, false);
        out_stream p_conv_info_file;
        if (PetscTools::AmMaster())
        {
            std::cout << "=========================== Beginning Test...==================================\n";
            p_conv_info_file = conv_info_handler.OpenOutputFile(nameOfTest+"_info.csv");
            (*p_conv_info_file) << "#Abcisa\t"
                                << "l2-norm-full\t"
                                << "l2-norm-onset\t"
                                << "Max absolute err\t"
                                << "APD90_1st_quad\t"
                                << "APD90_3rd_quad\t"
                                << "Conduction velocity (relative diffs)" << std::endl;
        }
        SetInitialConvergenceParameters();

        double prev_apd90_first_qn=0.0;
        double prev_apd90_third_qn=0.0;
        double prev_cond_velocity=0.0;
        std::vector<double> prev_voltage;
        std::vector<double> prev_times;
        PopulateStandardResult(prev_voltage, prev_times);

        do
        {
            CuboidMeshConstructor<DIM> constructor;

            //If the printing time step is too fine, then simulations become I/O bound without much improvement in accuracy
            double printing_step = this->PdeTimeStep;
#define COVERAGE_IGNORE
            while (printing_step < 1.0e-4)
            {
                printing_step *= 2.0;
                std::cout<<"Warning: PrintingTimeStep increased\n";
            }
#undef COVERAGE_IGNORE
            HeartConfig::Instance()->SetOdePdeAndPrintingTimeSteps(this->OdeTimeStep, this->PdeTimeStep, printing_step);
#define COVERAGE_IGNORE
            if (SimulateFullActionPotential)
            {
                HeartConfig::Instance()->SetSimulationDuration(400.0);
            }
            else
            {
                HeartConfig::Instance()->SetSimulationDuration(8.0);
            }
#undef COVERAGE_IGNORE
            HeartConfig::Instance()->SetOutputDirectory("Convergence"+nameOfTest);
            HeartConfig::Instance()->SetOutputFilenamePrefix("Results");

            DistributedTetrahedralMesh<DIM, DIM> mesh;
            constructor.Construct(mesh, this->MeshNum, mMeshWidth);

            unsigned num_ele_across = SmallPow(2u, this->MeshNum+2); // number of elements in each dimension

            AbstractCardiacCellFactory<DIM>* p_cell_factory=NULL;

            switch (this->Stimulus)
            {
                case NEUMANN:
                {
                    p_cell_factory = new ZeroStimulusCellFactory<CELL, DIM>();
                    break;
                }
                case PLANE:
                {
                    if (this->UseAbsoluteStimulus)
                    {
                        #define COVERAGE_IGNORE
                        p_cell_factory = new GeneralPlaneStimulusCellFactory<CELL, DIM>(0, this->AbsoluteStimulus, true);
                        #undef COVERAGE_IGNORE
                    }
                    else
                    {
                        p_cell_factory = new GeneralPlaneStimulusCellFactory<CELL, DIM>(num_ele_across, constructor.GetWidth(), false, this->AbsoluteStimulus);
                    }
                    break;
                }
                case QUARTER:
                {
                    ///\todo consider reducing all stimuli to match this one.
                    p_cell_factory = new RampedQuarterStimulusCellFactory<CELL, DIM>(constructor.GetWidth(), num_ele_across, this->AbsoluteStimulus/10.0);
                    break;
                }
                default:
                    NEVER_REACHED;
            }


            CARDIAC_PROBLEM cardiac_problem(p_cell_factory);
            cardiac_problem.SetMesh(&mesh);

            // Calculate positions of nodes 1/4 and 3/4 through the mesh
            unsigned third_quadrant_node;
            unsigned first_quadrant_node;
            switch(DIM)
            {
                case 1:
                {
                    first_quadrant_node = (unsigned) (0.25*constructor.GetNumElements());
                    third_quadrant_node = (unsigned) (0.75*constructor.GetNumElements());
                    break;
                }
                case 2:
                {
                    unsigned n= SmallPow (2u, this->MeshNum+2);
                    first_quadrant_node =   (n+1)*(n/2)+  n/4 ;
                    third_quadrant_node =   (n+1)*(n/2)+3*n/4 ;
                    break;
                }
                case 3:
                {
                    const unsigned first_quadrant_nodes_3d[5]={61, 362, 2452, 17960, 137296};
                    const unsigned third_quadrant_nodes_3d[5]={63, 366, 2460, 17976, 137328};
                    assert(this->PdeTimeStep<5);
                    first_quadrant_node = first_quadrant_nodes_3d[this->MeshNum];
                    third_quadrant_node = third_quadrant_nodes_3d[this->MeshNum];
                    break;
                }

                default:
                    NEVER_REACHED;
            }

            double mesh_width=constructor.GetWidth();

            // We only need the output of these two nodes
            std::vector<unsigned> nodes_to_be_output;
            nodes_to_be_output.push_back(first_quadrant_node);
            nodes_to_be_output.push_back(third_quadrant_node);
            cardiac_problem.SetOutputNodes(nodes_to_be_output);

            // The results of the tests were originally obtained with the following conductivity
            // values. After implementing fibre orientation the defaults changed. Here we set
            // the former ones to be used.
            SetConductivities(cardiac_problem);

            cardiac_problem.Initialise();

            boost::shared_ptr<BoundaryConditionsContainer<DIM,DIM,PROBLEM_DIM> > p_bcc(new BoundaryConditionsContainer<DIM,DIM,PROBLEM_DIM>);
            SimpleStimulus stim(NeumannStimulus, 0.5);
            if (Stimulus==NEUMANN)
            {

                StimulusBoundaryCondition<DIM>* p_bc_stim = new StimulusBoundaryCondition<DIM>(&stim);

                // get mesh
                AbstractTetrahedralMesh<DIM, DIM> &r_mesh = cardiac_problem.rGetMesh();
                // loop over boundary elements
                typename AbstractTetrahedralMesh<DIM, DIM>::BoundaryElementIterator iter;
                iter = r_mesh.GetBoundaryElementIteratorBegin();
                while (iter != r_mesh.GetBoundaryElementIteratorEnd())
                {
                    double x = ((*iter)->CalculateCentroid())[0];
                    ///\todo remove magic number? (#1884)
                    if (x*x<=1e-10)
                    {
                        p_bcc->AddNeumannBoundaryCondition(*iter, p_bc_stim);
                    }
                    iter++;
                }
                // pass the bcc to the problem
                cardiac_problem.SetBoundaryConditionsContainer(p_bcc);
            }

            DisplayRun();
            Timer::Reset();
            //// use this to get some info printed out
            //cardiac_problem.SetWriteInfo();

            try
            {
                cardiac_problem.Solve();
            }
            catch (Exception e)
            {
                WARNING("This run threw an exception.  Check convergence results\n");
                std::cout << e.GetMessage() << std::endl;
            }

            if (PetscTools::AmMaster())
            {
                std::cout << "Time to solve = " << Timer::GetElapsedTime() << " seconds\n";
            }

            OutputFileHandler results_handler("Convergence"+nameOfTest, false);
            Hdf5DataReader results_reader = cardiac_problem.GetDataReader();

            {
                std::vector<double> transmembrane_potential = results_reader.GetVariableOverTime("V", third_quadrant_node);
                std::vector<double> time_series = results_reader.GetUnlimitedDimensionValues();

                OutputFileHandler plot_file_handler("ConvergencePlots"+nameOfTest, false);
                if (PetscTools::AmMaster())
                {
                    // Write out the time series for the node at third quadrant
                    {
                        std::stringstream plot_file_name_stream;
                        plot_file_name_stream<< nameOfTest << "_Third_quadrant_node_run_"<< file_num << ".csv";
                        out_stream p_plot_file = plot_file_handler.OpenOutputFile(plot_file_name_stream.str());
                        for (unsigned data_point = 0; data_point<time_series.size(); data_point++)
                        {
                            (*p_plot_file) << time_series[data_point] << "\t" << transmembrane_potential[data_point] << "\n";
                        }
                        p_plot_file->close();
                    }
                    // Write time series for first quadrant node
                    {
                        std::vector<double> transmembrane_potential_1qd=results_reader.GetVariableOverTime("V", first_quadrant_node);
                        std::vector<double> time_series_1qd = results_reader.GetUnlimitedDimensionValues();
                        std::stringstream plot_file_name_stream;
                        plot_file_name_stream<< nameOfTest << "_First_quadrant_node_run_"<< file_num << ".csv";
                        out_stream p_plot_file = plot_file_handler.OpenOutputFile(plot_file_name_stream.str());
                        for (unsigned data_point = 0; data_point<time_series.size(); data_point++)
                        {
                            (*p_plot_file) << time_series_1qd[data_point] << "\t" << transmembrane_potential_1qd[data_point] << "\n";
                        }
                        p_plot_file->close();
                    }
                }
                // calculate conduction velocity and APD90 error
                PropagationPropertiesCalculator ppc(&results_reader);

                try
                {
                    #define COVERAGE_IGNORE
                    if (SimulateFullActionPotential)
                    {
                        Apd90FirstQn = ppc.CalculateActionPotentialDuration(90.0, first_quadrant_node);
                        Apd90ThirdQn = ppc.CalculateActionPotentialDuration(90.0, third_quadrant_node);
                    }
                    #undef COVERAGE_IGNORE
                    ConductionVelocity  = ppc.CalculateConductionVelocity(first_quadrant_node,third_quadrant_node,0.5*mesh_width);
                }
                catch (Exception e)
                {
                    #define COVERAGE_IGNORE
                    std::cout << "Warning - this run threw an exception in calculating propagation.  Check convergence results\n";
                    std::cout << e.GetMessage() << std::endl;
                    #undef COVERAGE_IGNORE
                }
                double cond_velocity_error = 1e10;
                double apd90_first_qn_error = 1e10;
                double apd90_third_qn_error = 1e10;

                if (this->PopulatedResult)
                {
                    if (prev_cond_velocity != 0.0)
                    {
                        cond_velocity_error = fabs(ConductionVelocity - prev_cond_velocity) / prev_cond_velocity;
                    }
#define COVERAGE_IGNORE
                    if (prev_apd90_first_qn != 0.0)
                    {
                        apd90_first_qn_error = fabs(Apd90FirstQn - prev_apd90_first_qn) / prev_apd90_first_qn;
                    }
                    if (prev_apd90_third_qn != 0.0)
                    {
                        apd90_third_qn_error = fabs(Apd90ThirdQn - prev_apd90_third_qn) / prev_apd90_third_qn;
                    }
                    if (apd90_first_qn_error == 0.0)
                    {
                        apd90_first_qn_error = DBL_EPSILON; //Avoid log zero on plot
                    }
                    if (apd90_third_qn_error == 0.0)
                    {
                        apd90_third_qn_error = DBL_EPSILON; //Avoid log zero on plot
                    }
#undef COVERAGE_IGNORE
                    if (cond_velocity_error == 0.0)
                    {
                        cond_velocity_error = DBL_EPSILON; //Avoid log zero on plot
                    }
                }

                prev_cond_velocity = ConductionVelocity;
                prev_apd90_first_qn = Apd90FirstQn;
                prev_apd90_third_qn = Apd90ThirdQn;

                // calculate l2norm
                double max_abs_error = 0;
                double sum_sq_abs_error =0;
                double sum_sq_prev_voltage = 0;
                double sum_sq_abs_error_full =0;
                double sum_sq_prev_voltage_full = 0;
                if (this->PopulatedResult)
                {
                    //If the PDE step is varying then we'll have twice as much data now as we use to have

                    unsigned time_factor=(time_series.size()-1) / (prev_times.size()-1);
                    assert (time_factor == 1 || time_factor == 2 || time_factor == 8);
                    //Iterate over the shorter time series data
                    for (unsigned data_point = 0; data_point<prev_times.size(); data_point++)
                    {
                        unsigned this_data_point=time_factor*data_point;

                        assert(time_series[this_data_point] == prev_times[data_point]);
                        double abs_error = fabs(transmembrane_potential[this_data_point]-prev_voltage[data_point]);
                        max_abs_error = (abs_error > max_abs_error) ? abs_error : max_abs_error;
                        //Only do resolve the upstroke...
                        sum_sq_abs_error_full += abs_error*abs_error;
                        sum_sq_prev_voltage_full += prev_voltage[data_point] * prev_voltage[data_point];
                        if (time_series[this_data_point] <= 8.0)
                        {
                            //In most regular cases we always do this, since the simulation stops at ms
                            sum_sq_abs_error += abs_error*abs_error;
                            sum_sq_prev_voltage += prev_voltage[data_point] * prev_voltage[data_point];
                        }
                    }

                }
                if (!this->PopulatedResult || !FixedResult)
                {
                    prev_voltage = transmembrane_potential;
                    prev_times = time_series;
                }

                if (this->PopulatedResult)
                {
                    double l2_norm_upstroke = sqrt(sum_sq_abs_error/sum_sq_prev_voltage);
                    double l2_norm_full = sqrt(sum_sq_abs_error_full/sum_sq_prev_voltage_full);

                    if (PetscTools::AmMaster())
                    {
                        (*p_conv_info_file) << std::setprecision(8)
                                            << Abscissa() << "\t"
                                            << l2_norm_full << "\t"
                                            << l2_norm_upstroke << "\t"
                                            << max_abs_error << "\t"
                                            << Apd90FirstQn <<" "<< apd90_first_qn_error <<""<< "\t"
                                            << Apd90ThirdQn <<" "<< apd90_third_qn_error <<""<< "\t"
                                            << ConductionVelocity <<" "<< cond_velocity_error  <<""<< std::endl;
                    }
                    // convergence criterion
                    this->Converged = l2_norm_full < this->RelativeConvergenceCriterion;
                    this->LastDifference = l2_norm_full;
#define COVERAGE_IGNORE
                    assert (time_series.size() != 1u);
                    if (time_series.back() == 0.0)
                    {
                        std::cout << "Failed after successful convergence - give up this convergence test\n";
                        break;
                    }
#undef COVERAGE_IGNORE

                }

                if ( time_series.back() != 0.0)
                {
                    // Simulation ran to completion
                    this->PopulatedResult=true;

                }
            }

            // Get ready for the next test by halving the time step
            if (!this->Converged)
            {
                UpdateConvergenceParameters();
                file_num++;
            }
            delete p_cell_factory;
        }
        while (!GiveUpConvergence() && !this->Converged);


        if (PetscTools::AmMaster())
        {
            p_conv_info_file->close();

            std::cout << "Results: " << std::endl;
            FileFinder info_finder = conv_info_handler.FindFile(nameOfTest + "_info.csv");
            std::ifstream info_file(info_finder.GetAbsolutePath().c_str());
            if (info_file)
            {
                std::cout << info_file.rdbuf();
                info_file.close();
            }
        }

    }
Ejemplo n.º 14
0
//------------------------------------------------------------------------
void CProjectile::Launch(const Vec3 &pos, const Vec3 &dir, const Vec3 &velocity, float speedScale)
{
	m_destroying = false;

	GetGameObject()->EnablePhysicsEvent(true, eEPE_OnCollisionLogged);

	// Only for bullets
	m_hitPoints = m_pAmmoParams->hitPoints;
	m_hitListener = false;

	if(m_hitPoints>0)
	{
		//Only projectiles with hit points are hit listeners
		g_pGame->GetGameRules()->AddHitListener(this);
		m_hitListener = true;
		m_noBulletHits = m_pAmmoParams->noBulletHits;
	}

	Matrix34 worldTM=Matrix34(Matrix33::CreateRotationVDir(dir.GetNormalizedSafe()));
	worldTM.SetTranslation(pos);
	GetEntity()->SetWorldTM(worldTM);

	//Must set velocity after position, if not velocity could be reseted for PE_RIGID
	SetVelocity(pos, dir, velocity, speedScale);

	m_initial_pos = pos;
	m_initial_dir = dir;
	m_initial_vel = velocity;

	m_last = pos;

	// Attach effect when fired (not first update)
	if(m_trailEffectId<0)
		TrailEffect(true);

	IAIObject *pAI = 0;

	if((pAI = GetEntity()->GetAI()) != NULL && pAI->GetAIType() == AIOBJECT_GRENADE)
	{
		IEntity *pOwnerEntity = gEnv->pEntitySystem->GetEntity(m_ownerId);
		pe_status_dynamics dyn;
		pe_status_dynamics dynProj;

		if(pOwnerEntity->GetPhysics()
				&& pOwnerEntity->GetPhysics()->GetStatus(&dyn)
				&& GetEntity()->GetPhysics()->GetStatus(&dynProj))
		{

//			Vec3 ownerVel(dyn.v);
			Vec3 grenadeDir(dynProj.v.GetNormalizedSafe());

			// Trigger the signal at the predicted landing position.
			Vec3 predictedPos = pos;
			float dummySpeed;

			if(GetWeapon())
				GetWeapon()->PredictProjectileHit(pOwnerEntity->GetPhysics(), pos, dir, velocity, speedScale * m_pAmmoParams->speed, predictedPos, dummySpeed);

			// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
			EntityId ownerId = pOwnerEntity->GetId();
			IActor *pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);

			if(pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
				ownerId = pActor->GetLinkedVehicle()->GetEntityId();

			SAIStimulus stim(AISTIM_GRENADE, AIGRENADE_THROWN, ownerId, GetEntityId(),
							 predictedPos, ZERO, 20.0f);
			gEnv->pAISystem->RegisterStimulus(stim);
		}
	}

}
Ejemplo n.º 15
0
//------------------------------------------------------------------------
void CProjectile::HandleEvent(const SGameObjectEvent &event)
{
	if(m_destroying)
		return;

	FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);

	if(event.event == eGFE_OnCollision)
	{
		EventPhysCollision *pCollision = (EventPhysCollision *)event.ptr;

		if(pCollision == NULL)
			return;

		const SCollisionParams *pCollisionParams = m_pAmmoParams->pCollision;

		if(pCollisionParams)
		{
			if(pCollisionParams->pParticleEffect)
				pCollisionParams->pParticleEffect->Spawn(true, IParticleEffect::ParticleLoc(pCollision->pt, pCollision->n, pCollisionParams->scale));

			if(pCollisionParams->sound)
			{
				_smart_ptr<ISound> pSound = gEnv->pSoundSystem->CreateSound(pCollisionParams->sound, FLAG_SOUND_DEFAULT_3D);

				if(pSound)
				{
					pSound->SetSemantic(eSoundSemantic_Projectile);
					pSound->SetPosition(pCollision->pt);
					pSound->Play();
				}
			}
		}

		// add battledust for bulletimpact
		if(gEnv->bServer && g_pGame->GetGameRules())
		{
			if(CBattleDust *pBD = g_pGame->GetGameRules()->GetBattleDust())
			{
				pBD->RecordEvent(eBDET_ShotImpact, pCollision->pt, GetEntity()->GetClass());
			}
		}

		Ricochet(pCollision);

		//Update damage
		if((m_damageDropPerMeter>0.0001f)&&
				(((pCollision->pt-m_initial_pos).len2()>m_damageDropMinDisSqr)||m_firstDropApplied))
		{

			if(!m_firstDropApplied)
			{
				m_firstDropApplied = true;
				m_initial_pos = m_initial_pos + (m_initial_dir*(sqrt_fast_tpl(m_damageDropMinDisSqr)));
			}

			Vec3 vDiff = pCollision->pt - m_initial_pos;
			float dis  = vDiff.len();

			m_damage -= (int)(floor_tpl(m_damageDropPerMeter * dis));

			//Check m_damage is positive
			if(m_damage<MIN_DAMAGE)
				m_damage=MIN_DAMAGE;

			//Also modify initial position (the projectile could not be destroyed, cause of pirceability)
			m_initial_pos = pCollision->pt;
		}

		// Notify AI system about grenades.
		if(gEnv->pAISystem)
		{
			IAIObject *pAI = 0;

			if((pAI = GetEntity()->GetAI()) != NULL && pAI->GetAIType() == AIOBJECT_GRENADE)
			{
				// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
				EntityId ownerId = m_ownerId;
				IActor *pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);

				if(pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
					ownerId = pActor->GetLinkedVehicle()->GetEntityId();

				SAIStimulus stim(AISTIM_GRENADE, AIGRENADE_COLLISION, ownerId, GetEntityId(),
								 GetEntity()->GetWorldPos(), ZERO, 12.0f);
				gEnv->pAISystem->RegisterStimulus(stim);
			}
		}
	}
}
Ejemplo n.º 16
0
//------------------------------------------------------------------------
void CProjectile::ScaledEffect(const SScaledEffectParams *pScaledEffect)
{
	if(!pScaledEffect)
		return;

	float lifetime = m_pAmmoParams->lifetime;

	IActor *local = gEnv->pGame->GetIGameFramework()->GetClientActor();

	if(local)
	{
		float dist = (GetEntity()->GetWorldPos() - local->GetEntity()->GetWorldPos()).len();

		if(m_totalLifetime < pScaledEffect->delay || pScaledEffect->radius == 0.0f)
			return;

		float fadeInAmt = 1.0f;
		float fadeOutAmt = 1.0f;

		if(pScaledEffect->fadeInTime > 0.0f)
		{
			fadeInAmt = (m_totalLifetime - pScaledEffect->delay) / pScaledEffect->fadeInTime;
			fadeInAmt = min(fadeInAmt, 1.0f);
			fadeOutAmt = 1.0f - (m_totalLifetime - (lifetime - pScaledEffect->fadeOutTime)) / pScaledEffect->fadeOutTime;
			fadeOutAmt = max(fadeOutAmt, 0.0f);
		}

		if(!m_obstructObject && pScaledEffect->aiObstructionRadius != 0.0f)
		{
			pe_params_pos pos;
			pos.scale = 0.1f;
			pos.pos = GetEntity()->GetWorldPos() + Vec3(0,0,pScaledEffect->aiObstructionRadius/4 * pos.scale);
			m_obstructObject = gEnv->pPhysicalWorld->CreatePhysicalEntity(PE_STATIC, &pos);

			if(m_obstructObject)
			{
				primitives::sphere sphere;
				sphere.center = Vec3(0,0,0);
				sphere.r = pScaledEffect->aiObstructionRadius;
				int obstructID = gEnv->p3DEngine->GetMaterialManager()->GetSurfaceTypeIdByName("mat_obstruct");
				IGeometry *pGeom = gEnv->pPhysicalWorld->GetGeomManager()->CreatePrimitive(primitives::sphere::type, &sphere);
				phys_geometry *geometry = gEnv->pPhysicalWorld->GetGeomManager()->RegisterGeometry(pGeom, obstructID);
				pe_geomparams params;
				params.flags = geom_colltype14;
				geometry->nRefCount = 0; // automatically delete geometry
				m_obstructObject->AddGeometry(geometry, &params);
			}
		}
		else
		{
			pe_params_pos pos;
			pos.scale = 0.1f + min(fadeInAmt, fadeOutAmt) * 0.9f;
			pos.pos = GetEntity()->GetWorldPos() + Vec3(0,0, pScaledEffect->aiObstructionRadius/4.0f * pos.scale);
			m_obstructObject->SetParams(&pos);

			// Signal the AI
			if(gEnv->pAISystem && !m_scaledEffectSignaled &&  m_totalLifetime > (pScaledEffect->delay + pScaledEffect->fadeInTime))
			{
				m_scaledEffectSignaled = true;

				// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
				EntityId ownerId = m_ownerId;
				IActor *pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);

				if(pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
					ownerId = pActor->GetLinkedVehicle()->GetEntityId();

				SAIStimulus stim(AISTIM_GRENADE, AIGRENADE_SMOKE, ownerId, GetEntityId(),
								 pos.pos, ZERO, pScaledEffect->aiObstructionRadius*1.5f);
				gEnv->pAISystem->RegisterStimulus(stim);
			}
		}

		if(dist > pScaledEffect->radius)
		{
			gEnv->p3DEngine->SetPostEffectParam(pScaledEffect->ppname, 0.0f);
			return;
		}

		float effectAmt = 1.0f - (dist / pScaledEffect->radius);
		effectAmt = max(effectAmt, 0.0f);
		float effectVal = effectAmt * pScaledEffect->maxValue;
		effectVal *= fadeInAmt;
		m_scaledEffectval = effectVal;

		gEnv->p3DEngine->SetPostEffectParam(pScaledEffect->ppname, effectVal);
	}
}
Ejemplo n.º 17
0
//------------------------------------------
void CC4Projectile::HandleEvent(const SGameObjectEvent &event)
{
	if (CheckAnyProjectileFlags(ePFlag_destroying))
		return;

	CProjectile::HandleEvent(event);

	if (event.event == eGFE_OnCollision)
	{
		EventPhysCollision *pCollision = (EventPhysCollision *)event.ptr;

		if(pCollision && pCollision->pEntity[0]->GetType()==PE_PARTICLE)
		{
			float bouncy, friction;
			uint32 pierceabilityMat;
			gEnv->pPhysicalWorld->GetSurfaceParameters(pCollision->idmat[1], bouncy, friction, pierceabilityMat);
			pierceabilityMat &= sf_pierceable_mask;
			uint32 pierceabilityProj = GetAmmoParams().pParticleParams ? GetAmmoParams().pParticleParams->iPierceability : 13;
			if (pierceabilityMat > pierceabilityProj)
				return;

			if(gEnv->bMultiplayer)
			{
				// Don't stick to weapons.
				if(pCollision->iForeignData[1]==PHYS_FOREIGN_ID_ENTITY)
				{
					if(IEntity* pEntity = (IEntity*)pCollision->pForeignData[1])
					{
						if(IItem* pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pEntity->GetId()))
						{
							if(pItem->GetIWeapon())
							{
								return;
							}
						}
					}
				}
			}

			// Notify AI system about the C4.
			if (gEnv->pAISystem)
			{
				// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
				EntityId ownerId = m_ownerId;
				IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(ownerId);
				if (pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
					ownerId = pActor->GetLinkedVehicle()->GetEntityId();

				SAIStimulus stim(AISTIM_EXPLOSION, 0, ownerId, GetEntityId(),
					GetEntity()->GetWorldPos(), ZERO, 12.0f, AISTIMPROC_ONLY_IF_VISIBLE);
				gEnv->pAISystem->RegisterStimulus(stim);

				SAIStimulus soundStim(AISTIM_SOUND, AISOUND_COLLISION, ownerId, GetEntityId(),
					GetEntity()->GetWorldPos(), ZERO, 8.0f);
				gEnv->pAISystem->RegisterStimulus(soundStim);
			}
		}

		if (gEnv->bServer && !m_stickyProjectile.IsStuck())
			m_stickyProjectile.Stick(
				CStickyProjectile::SStickParams(this, pCollision, CStickyProjectile::eO_AlignToSurface));
	}
}
Ejemplo n.º 18
0
//------------------------------------------------------------------------
tSoundID CItem::PlayAction(const ItemString &actionName, int layer, bool loop, uint32 flags, float speedOverride)
{
	if(!m_enableAnimations || !IsOwnerInGame())
		return (tSoundID)-1;

	TActionMap::iterator it = m_sharedparams->actions.find(CONST_TEMPITEM_STRING(actionName));

	if(it == m_sharedparams->actions.end())
	{
//		GameWarning("Action '%s' not found on item '%s'!", actionName, GetEntity()->GetName());

		for(int i=0; i<eIGS_Last; i++)
		{
			m_animationTime[i]=0;
			m_animationSpeed[i]=1.0f;
			m_animationEnd[i]=0;
		}

		return 0;
	}

	bool fp = m_stats.fp;

	if(m_parentId)
	{
		CItem *pParent=static_cast<CItem *>(m_pItemSystem->GetItem(m_parentId));

		if(pParent)
			fp=pParent->GetStats().fp;
	}

	if(flags&eIPAF_ForceFirstPerson)
		fp = true;

	if(flags&eIPAF_ForceThirdPerson)
		fp = false;

	int sid=fp?eIGS_FirstPerson:eIGS_ThirdPerson;
	SAction &action = it->second;

	tSoundID result = INVALID_SOUNDID;

	if((flags&eIPAF_Sound) && !action.sound[sid].name.empty() && IsSoundEnabled() && g_pGameCVars->i_soundeffects)
	{
		int nSoundFlags = FLAG_SOUND_DEFAULT_3D;
		nSoundFlags |= flags&eIPAF_SoundStartPaused?FLAG_SOUND_START_PAUSED:0;
		IEntitySoundProxy *pSoundProxy = GetSoundProxy(true);

		//GetSound proxy from dualwield master if neccesary
		if(IsDualWieldSlave())
		{
			CItem *pMaster = static_cast<CItem *>(GetDualWieldMaster());

			if(pMaster)
			{
				pSoundProxy = pMaster->GetSoundProxy(true);
			}
		}

		EntityId pSkipEnts[3];
		int nSkipEnts = 0;

		// TODO for Marcio :)
		// check code changes

		// Skip the Item
		pSkipEnts[nSkipEnts] = GetEntity()->GetId();
		++nSkipEnts;

		// Skip the Owner
		if(GetOwner())
		{
			pSkipEnts[nSkipEnts] = GetOwner()->GetId();
			++nSkipEnts;
		}

		if(pSoundProxy)
		{

			TempResourceName name;
			FixResourceName(action.sound[sid].name, name, flags);
			//nSoundFlags = nSoundFlags | (fp?FLAG_SOUND_DEFAULT_3D|FLAG_SOUND_RELATIVE:FLAG_SOUND_DEFAULT_3D);
			Vec3 vOffset(0,0,0);

			if(fp)
				vOffset.x = 0.3f; // offset for first person weapon to the front

			if(!g_pGameCVars->i_staticfiresounds)
			{
				result = pSoundProxy->PlaySoundEx(name, vOffset, FORWARD_DIRECTION, nSoundFlags, 1.0f, 0, 0, eSoundSemantic_Weapon, pSkipEnts, nSkipEnts);
				ISound *pSound = pSoundProxy->GetSound(result);

				if(pSound && action.sound[sid].sphere>0.0f)
					pSound->SetSphereSpec(action.sound[sid].sphere);
			}
			else
			{
				SInstanceAudio *pInstanceAudio=0;

				if(action.sound[sid].isstatic)
				{
					TInstanceActionMap::iterator iit = m_instanceActions.find(CONST_TEMPITEM_STRING(actionName));

					if(iit == m_instanceActions.end())
					{
						std::pair<TInstanceActionMap::iterator, bool> insertion=m_instanceActions.insert(TInstanceActionMap::value_type(actionName, SInstanceAction()));
						pInstanceAudio=&insertion.first->second.sound[sid];
					}
					else
						pInstanceAudio=&iit->second.sound[sid];
				}

				if(pInstanceAudio && (pInstanceAudio->id != INVALID_SOUNDID) && (name != pInstanceAudio->static_name))
					ReleaseStaticSound(pInstanceAudio);

				if(!pInstanceAudio || pInstanceAudio->id == INVALID_SOUNDID)
				{
					result = pSoundProxy->PlaySoundEx(name, vOffset, FORWARD_DIRECTION, nSoundFlags, 1.0f, 0, 0, eSoundSemantic_Weapon, pSkipEnts, nSkipEnts);
					ISound *pSound = pSoundProxy->GetSound(result);

					if(pSound && action.sound[sid].sphere>0.0f)
						pSound->SetSphereSpec(action.sound[sid].sphere);
				}

				if(action.sound[sid].isstatic)
				{
					if(pInstanceAudio->id == INVALID_SOUNDID)
					{
						if(pSoundProxy->SetStaticSound(result, true))
						{
							pInstanceAudio->id = result;
							pInstanceAudio->static_name = name;
							pInstanceAudio->synch = action.sound[sid].issynched;
						}
					}
					else
					{
						ISound *pSound = pSoundProxy->GetSound(pInstanceAudio->id);

						if(pSound)
							pSound->Play(1.0, true, true, pSoundProxy);
					}
				}
			}

			if(gEnv->pAISystem && action.sound[sid].airadius > 0.0f)
			{
				EntityId ownerId = GetOwner() ? GetOwner()->GetId() : 0;

				// associate sound event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
				if(CActor *pOwnerActor = GetOwnerActor())
				{
					IVehicle *pOwnerVehicle = pOwnerActor->GetLinkedVehicle();

					if(pOwnerVehicle && pOwnerVehicle->GetEntityId())
						ownerId = pOwnerVehicle->GetEntityId();
				}

				SAIStimulus stim(AISTIM_SOUND, AISOUND_WEAPON, ownerId?ownerId:GetEntityId() , 0,
								 GetEntity()->GetWorldPos(), ZERO, action.sound[sid].airadius);

				gEnv->pAISystem->RegisterStimulus(stim);
			}
		}
	}


	if(flags&eIPAF_Animation)
	{
		TempResourceName name;
		// generate random number only once per call to allow animations to
		// match across geometry slots (like first person and third person)
		float randomNumber = Random();

		for(int i=0; i<eIGS_Last; i++)
		{
			if(!(flags&(1<<i)))
				continue;

			int nanimations=action.animation[i].size();

			if(nanimations <= 0)
				continue;

			int anim = int(randomNumber * float(nanimations));

			if(action.animation[i][anim].name.empty())
				continue;

			FixResourceName(action.animation[i][anim].name, name, flags);

			if((i == eIGS_Owner) || (i == eIGS_OwnerLooped))
			{
				if(!action.animation[i][anim].name.empty())
				{
					bool looping=(eIGS_OwnerLooped==i);

					CActor *pOwner = GetOwnerActor();

					if(pOwner)
					{
						if(IsDualWield() && !m_sharedparams->params.dual_wield_pose.empty())
							pOwner->PlayAction(name, m_sharedparams->params.dual_wield_pose.c_str(), looping);
						else
							pOwner->PlayAction(name, m_sharedparams->params.pose.c_str(), looping);
					}
				}

				continue;
			}
			else if(i == eIGS_OffHand)
			{
				if(!action.animation[eIGS_OffHand][anim].name.empty())
				{
					CActor *pOwner = GetOwnerActor();

					if(pOwner)
					{
						CItem *pOffHand = pOwner->GetItemByClass(CItem::sOffHandClass);

						if(pOffHand && pOffHand!=this)
						{
							uint32 ohflags=eIPAF_Default;

							if(action.animation[eIGS_OffHand][anim].blend==0.0f)
								ohflags|=eIPAF_NoBlend;

							pOffHand->PlayAction(action.animation[eIGS_OffHand][anim].name, 0, false, ohflags);
						}
					}
				}

				continue;
			}

			SAnimation &animation=action.animation[i][anim];

			if(!animation.name.empty())
			{
				float blend = animation.blend;

				if(flags&eIPAF_NoBlend)
					blend = 0.0f;

				if(speedOverride > 0.0f)
					PlayAnimationEx(name, i, layer, loop, blend, speedOverride, flags);
				else
					PlayAnimationEx(name, i, layer, loop, blend, animation.speed, flags);
			}

			if((m_stats.fp || m_stats.viewmode&eIVM_FirstPerson) && i==eIGS_FirstPerson && !animation.camera_helper.empty())
			{
				m_camerastats.animating=true;
				m_camerastats.helper=animation.camera_helper;
				m_camerastats.position=animation.camera_pos;
				m_camerastats.rotation=animation.camera_rot;
				m_camerastats.follow=animation.camera_follow;
				m_camerastats.reorient=animation.camera_reorient;
			}
			else if(m_camerastats.animating)
				m_camerastats=SCameraAnimationStats();
		}
	}

	if(flags&eIPAF_Effect && !action.effect[sid].name.empty())
	{
		// change this to attach, if needed
		SpawnEffect(sid, action.effect[sid].name.c_str(), action.effect[sid].helper.c_str());
	}

	if(action.children)
	{
		for(TAccessoryMap::iterator ait=m_accessories.begin(); ait!=m_accessories.end(); ait++)
		{
			EntityId aId=(EntityId)ait->second;
			CItem *pAccessory=static_cast<CItem *>(m_pItemSystem->GetItem(aId));

			if(pAccessory)
				pAccessory->PlayAction(actionName, layer, loop, flags, speedOverride);
		}
	}

	return result;
}
Ejemplo n.º 19
0
void statesaver()
{
  static char txtsavemsg[] = "STATE - SAVED.";
  static char txtrrsvmsg[] = "RR STATE - SAVED.";

  static char *txtsavenum = 0;
  static char *txtrrsvnum = 0;

  //Save State code
  #ifdef __UNIXSDL__
  SRAMChdir();
  #endif

  //'Auto increment savestate slot' code
  if (AutoIncSaveSlot)
  {
    if (firstsaveinc) { firstsaveinc = 0; }
    else
    {
      switch (fnamest[statefileloc])
      {
        case 't': // ZST state
        case 'v': // ZMV movie
          fnamest[statefileloc] = '1';
          break;
        case '9':
          fnamest[statefileloc] = 't';
          break;
        default:
          fnamest[statefileloc]++;
      }
    }
  }

  //Get the state number
  INSERT_POSITION_NUMBER(txtsavemsg, txtsavenum);
  INSERT_POSITION_NUMBER(txtrrsvmsg, txtrrsvnum);

  if (MovieProcessing == 2)
  {
    bool mzt_save(char *, bool, bool);
    if (mzt_save((char *)fnamest+1, (cbitmode && !NoPictureSave) ? true : false, false))
    {
      Msgptr = txtrrsvmsg;
      MessageOn = MsgCount;
    }
    return;
  }

  clim();

  if ((fhandle = fopen(fnamest+1,"wb")))
  {
    zst_save(fhandle, (bool)(cbitmode && !NoPictureSave), false);
    fclose(fhandle);

    //Display message onscreen, 'STATE X SAVED.'
    Msgptr = txtsavemsg;
  }
  else
  {
    //Display message onscreen, 'UNABLE TO SAVE.'
    Msgptr = "UNABLE TO SAVE.";
  }

  MessageOn = MsgCount;

  stim();
}
Ejemplo n.º 20
0
//------------------------------------------------------------------------
void CBullet::HandleEvent(const SGameObjectEvent &event)
{
	FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);

	CProjectile::HandleEvent(event);

	if (event.event == eGFE_OnCollision)
	{
		if (m_destroying)
			return;

		EventPhysCollision *pCollision = reinterpret_cast<EventPhysCollision *>(event.ptr);
		if (!pCollision)
			return;
        
		IEntity *pTarget = pCollision->iForeignData[1]==PHYS_FOREIGN_ID_ENTITY ? (IEntity*)pCollision->pForeignData[1]:0;

		//Only process hits that have a target
		if(pTarget)
		{
			Vec3 dir(0, 0, 0);
			if (pCollision->vloc[0].GetLengthSquared() > 1e-6f)
				dir = pCollision->vloc[0].GetNormalized();

			CGameRules *pGameRules = g_pGame->GetGameRules();

			IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(m_ownerId);

			bool ok = true;

			if(!gEnv->bMultiplayer && pActor && pActor->IsPlayer())
			{
				IActor* pAITarget = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pTarget->GetId());
				if(pAITarget && pTarget->GetAI() && pTarget->GetAI()->IsFriendly(pActor->GetEntity()->GetAI(), false))
				{
					pGameRules->SetEntityToIgnore(pTarget->GetId());
					ok = false;
				}
			}

			if(ok)
			{
				HitInfo hitInfo(m_ownerId, pTarget->GetId(), m_weaponId,
					(float)m_damage, 0.0f, pGameRules->GetHitMaterialIdFromSurfaceId(pCollision->idmat[1]), pCollision->partid[1],
					m_hitTypeId, pCollision->pt, dir, pCollision->n);

				hitInfo.remote = IsRemote();
				hitInfo.projectileId = GetEntityId();
				hitInfo.bulletType = m_pAmmoParams->bulletType;

				pGameRules->ClientHit(hitInfo);

				// Notify AI
				if (gEnv->pAISystem && !gEnv->bMultiplayer)
				{
					static int htMelee = pGameRules->GetHitTypeId("melee");
					if (m_ownerId && m_hitTypeId != htMelee)
					{
						ISurfaceType *pSurfaceType = pGameRules->GetHitMaterial(hitInfo.material);
						const ISurfaceType::SSurfaceTypeAIParams* pParams = pSurfaceType ? pSurfaceType->GetAIParams() : 0;
						const float radius = pParams ? pParams->fImpactRadius : 2.5f;
						const float soundRadius = pParams ? pParams->fImpactSoundRadius : 20.0f;
						
						// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
						EntityId ownerId = m_ownerId;
						if (pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
							ownerId = pActor->GetLinkedVehicle()->GetEntityId();

						SAIStimulus stim(AISTIM_BULLET_HIT, 0, ownerId, 0, pCollision->pt, ZERO, radius);
						gEnv->pAISystem->RegisterStimulus(stim);

						SAIStimulus stimSound(AISTIM_SOUND, AISOUND_COLLISION_LOUD, ownerId, 0, pCollision->pt, ZERO, soundRadius, AISTIMPROC_FILTER_LINK_WITH_PREVIOUS);
						gEnv->pAISystem->RegisterStimulus(stimSound);

					}
				}

			}
		}
		else
		{
			// Notify AI
			// The above case only catches entity vs. entity hits, the AI is interested in all hits.
			if (gEnv->pAISystem && !gEnv->bMultiplayer)
			{
				CGameRules *pGameRules = g_pGame->GetGameRules();
				static int htMelee = pGameRules->GetHitTypeId("melee");
				if (m_ownerId && m_hitTypeId != htMelee)
				{
					int material = pGameRules->GetHitMaterialIdFromSurfaceId(pCollision->idmat[1]);
					ISurfaceType *pSurfaceType = pGameRules->GetHitMaterial(material);
					const ISurfaceType::SSurfaceTypeAIParams* pParams = pSurfaceType ? pSurfaceType->GetAIParams() : 0;
					const float radius = pParams ? pParams->fImpactRadius : 2.5f;
					const float soundRadius = pParams ? pParams->fImpactSoundRadius : 20.0f;

					// Associate event with vehicle if the shooter is in a vehicle (tank cannon shot, etc)
					EntityId ownerId = m_ownerId;
					IActor* pActor = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(m_ownerId);
					if (pActor && pActor->GetLinkedVehicle() && pActor->GetLinkedVehicle()->GetEntityId())
						ownerId = pActor->GetLinkedVehicle()->GetEntityId();

					SAIStimulus stim(AISTIM_BULLET_HIT, 0, ownerId, 0, pCollision->pt, ZERO, radius);
					gEnv->pAISystem->RegisterStimulus(stim);

					SAIStimulus stimSound(AISTIM_SOUND, AISOUND_COLLISION_LOUD, ownerId, 0, pCollision->pt, ZERO, soundRadius, AISTIMPROC_FILTER_LINK_WITH_PREVIOUS);
					gEnv->pAISystem->RegisterStimulus(stimSound);

				}
			}
		}


		if (pCollision->pEntity[0]->GetType() == PE_PARTICLE)
		{
			float bouncy, friction;
			uint32	pierceabilityMat;
			gEnv->pPhysicalWorld->GetSurfaceParameters(pCollision->idmat[1], bouncy, friction, pierceabilityMat);
			pierceabilityMat&=sf_pierceable_mask;
			
			pe_params_particle params;
			if(pCollision->pEntity[0]->GetParams(&params)==0)
				SetDefaultParticleParams(&params);

			//Under water trail
			Vec3 pos=pCollision->pt;
			if ((pCollision->idmat[1] == CBullet::m_waterMaterialId) && 
					(pCollision->pEntity[1]!=gEnv->pPhysicalWorld->AddGlobalArea() || !gEnv->p3DEngine->GetVisAreaFromPos(pos)))
			{
				//Reduce drastically bullet velocity (to be able to see the trail effect)
				//pe_params_particle pparams;
				//if(m_pPhysicalEntity->GetParams(&pparams)==0)
					//SetDefaultParticleParams(&pparams);
				//pparams.velocity = 25.0f;

				//m_pPhysicalEntity->SetParams(&pparams);

				if(m_trailUnderWaterId<0)
				{
					//Check terrain/against water level
					float terrainHeight = gEnv->p3DEngine->GetTerrainElevation(pCollision->pt.x,pCollision->pt.y);
					float waterLevel = gEnv->p3DEngine->GetWaterLevel(&(pCollision->pt));
					if(waterLevel>terrainHeight)
					{
						TrailEffect(true,true);
						return;
					}
				}
			}

			if (pierceabilityMat<=params.iPierceability || pCollision->idCollider==-1) //Do not destroy if collides water
				Destroy();
		}
	}
}
Ejemplo n.º 21
0
/**
 * Tab controlled by table
 * A + Tab <===> B
 * A + B -sumtot--> tot1
 * 2B <===> C
 * 
 * C ---e1Pool ---> D
 * D ---e2Pool ----> E
 *
 * All these are created on /kinetics, a cube compartment of vol 1e-18 m^3
 *
 */
Id makeReacTest()
{
	double simDt = 0.1;
	double plotDt = 0.1;
	Shell* s = reinterpret_cast< Shell* >( Id().eref().data() );

	Id pools[10];
	unsigned int i = 0;
	// Make the objects.
	Id kin = s->doCreate( "CubeMesh", Id(), "kinetics", 1 );
	Id tab = s->doCreate( "StimulusTable", kin, "tab", 1 );
	Id T = pools[i++] = s->doCreate( "BufPool", kin, "T", 1 );
	Id A = pools[i++] = s->doCreate( "Pool", kin, "A", 1 );
	Id B = pools[i++] = s->doCreate( "Pool", kin, "B", 1 );
	Id C = pools[i++] = s->doCreate( "Pool", kin, "C", 1 );
	Id D = pools[i++] = s->doCreate( "Pool", kin, "D", 1 );
	Id E = pools[i++] = s->doCreate( "Pool", kin, "E", 1 );
	Id tot1 = pools[i++] = s->doCreate( "BufPool", kin, "tot1", 1 );
	Id sum = s->doCreate( "Function", tot1, "func", 1 ); // Silly that it has to have this name. 
	Id sumInput( sum.value() + 1 );
	Id e1Pool = s->doCreate( "Pool", kin, "e1Pool", 1 );
	Id e2Pool = s->doCreate( "Pool", kin, "e2Pool", 1 );
	Id e1 = s->doCreate( "Enz", e1Pool, "e1", 1 );
	Id cplx = s->doCreate( "Pool", e1, "cplx", 1 );
	Id e2 = s->doCreate( "MMenz", e2Pool, "e2", 1 );
	Id r1 = s->doCreate( "Reac", kin, "r1", 1 );
	Id r2 = s->doCreate( "Reac", kin, "r2", 1 );
	Id plots = s->doCreate( "Table2", kin, "plots", 7 );

	// Connect them up
	s->doAddMsg( "Single", tab, "output", T, "setN" );

	s->doAddMsg( "Single", r1, "sub", T, "reac" );
	s->doAddMsg( "Single", r1, "sub", A, "reac" );
	s->doAddMsg( "Single", r1, "prd", B, "reac" );

	Field< unsigned int >::set( sum, "numVars", 2 );
	s->doAddMsg( "Single", A, "nOut", ObjId( sumInput, 0, 0 ), "input" );
	s->doAddMsg( "Single", B, "nOut", ObjId( sumInput, 0, 1 ), "input" );
	s->doAddMsg( "Single", sum, "valueOut", tot1, "setN" );

	s->doAddMsg( "Single", r2, "sub", B, "reac" );
	s->doAddMsg( "Single", r2, "sub", B, "reac" );
	s->doAddMsg( "Single", r2, "prd", C, "reac" );

	s->doAddMsg( "Single", e1, "sub", C, "reac" );
	s->doAddMsg( "Single", e1, "enz", e1Pool, "reac" );
	s->doAddMsg( "Single", e1, "cplx", cplx, "reac" );
	s->doAddMsg( "Single", e1, "prd", D, "reac" );

	s->doAddMsg( "Single", e2, "sub", D, "reac" );
	s->doAddMsg( "Single", e2Pool, "nOut", e2, "enzDest" );
	s->doAddMsg( "Single", e2, "prd", E, "reac" );

	// Set parameters.
	Field< double >::set( A, "concInit", 2 );
	Field< double >::set( e1Pool, "concInit", 1 );
	Field< double >::set( e2Pool, "concInit", 1 );
	Field< string >::set( sum, "expr", "x0+x1" );
	Field< double >::set( r1, "Kf", 0.2 );
	Field< double >::set( r1, "Kb", 0.1 );
	Field< double >::set( r2, "Kf", 0.1 );
	Field< double >::set( r2, "Kb", 0.0 );
	Field< double >::set( e1, "Km", 5 );
	Field< double >::set( e1, "kcat", 1 );
	Field< double >::set( e1, "ratio", 4 );
	Field< double >::set( e2, "Km", 5 );
	Field< double >::set( e2, "kcat", 1 );
	vector< double > stim( 100, 0.0 );
	double vol = Field< double >::get( kin, "volume" );
	for ( unsigned int i = 0; i< 100; ++i ) {
		stim[i] = vol * NA * (1.0 + sin( i * 2.0 * PI / 100.0 ) );
	}
	Field< vector< double > >::set( tab, "vector", stim );
	Field< double >::set( tab, "stepSize", 0.0 );
	Field< double >::set( tab, "stopTime", 10.0 );
	Field< double >::set( tab, "loopTime", 10.0 );
	Field< bool >::set( tab, "doLoop", true );
	

	// Connect outputs
	for ( unsigned int i = 0; i < 7; ++i )
		s->doAddMsg( "Single", ObjId( plots,i), 
						"requestOut", pools[i], "getConc" );

	// Schedule it.
	for ( unsigned int i = 11; i < 18; ++i )
		s->doSetClock( i, simDt );
	s->doSetClock( 18, plotDt );
	/*
	s->doUseClock( "/kinetics/##[ISA=Reac],/kinetics/##[ISA=EnzBase],/kinetics/##[ISA=SumFunc]",
					"process", 4 );
	s->doUseClock( "/kinetics/##[ISA=PoolBase]", "process", 5 );
	s->doUseClock( "/kinetics/##[ISA=StimulusTable]", 
					"process", 4 );
	s->doUseClock( "/kinetics/##[ISA=Table]", "process", 8 ); 
	s->doSetClock( 4, simDt );
	s->doSetClock( 5, simDt );
	s->doSetClock( 8, plotDt );
	*/
	return kin;
}
Ejemplo n.º 22
0
//------------------------------------------------------------------------
void CCannonBall::HandleEvent(const SGameObjectEvent &event)
{
	FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);

	BaseClass::HandleEvent(event);

	if (event.event == eGFE_OnCollision)
	{
		if (CheckAnyProjectileFlags(ePFlag_destroying))
			return;

		EventPhysCollision *pCollision = reinterpret_cast<EventPhysCollision *>(event.ptr);
		if (!pCollision)
			return;

		float finalDamage = GetFinalDamage(pCollision->pt);
		if (finalDamage <= 0.0f)
			m_alive = false;
        
		IEntity *pTarget = pCollision->iForeignData[1]==PHYS_FOREIGN_ID_ENTITY ? (IEntity*)pCollision->pForeignData[1]:0;
		CGameRules *pGameRules = g_pGame->GetGameRules();
		const int hitMatId = pCollision->idmat[1];

		Vec3 hitDir(ZERO);
		if (pCollision->vloc[0].GetLengthSquared() > 1e-6f)
		{
			hitDir = pCollision->vloc[0].GetNormalized();
		}

		const bool bProcessCollisionEvent = ProcessCollisionEvent(pTarget);
		if (bProcessCollisionEvent)
		{
			//================================= Process Hit =====================================
			//Only process hits that have a target
			if(pTarget)
			{
				if(FilterFriendlyAIHit(pTarget) == false)
				{
					ProcessHit(*pGameRules, *pCollision, *pTarget, finalDamage, hitMatId, hitDir);
				}
			}
			//====================================~ Process Hit ======================================

			//==================================== Notify AI    ======================================
			if (gEnv->pAISystem)
			{
				if (gEnv->pEntitySystem->GetEntity(m_ownerId))
				{
					ISurfaceType *pSurfaceType = gEnv->p3DEngine->GetMaterialManager()->GetSurfaceType(hitMatId);
					const ISurfaceType::SSurfaceTypeAIParams* pParams = pSurfaceType ? pSurfaceType->GetAIParams() : 0;
					const float radius = pParams ? pParams->fImpactRadius : 2.5f;
					const float soundRadius = pParams ? pParams->fImpactSoundRadius : 20.0f;

					SAIStimulus stim(AISTIM_BULLET_HIT, 0, m_ownerId, pTarget ? pTarget->GetId() : 0, pCollision->pt, pCollision->vloc[0].GetNormalizedSafe(ZERO), radius);
					gEnv->pAISystem->RegisterStimulus(stim);

					SAIStimulus stimSound(AISTIM_SOUND, AISTIM_BULLET_HIT, m_ownerId, 0, pCollision->pt, ZERO, soundRadius);
					gEnv->pAISystem->RegisterStimulus(stim);
				}
			}
			//=========================================~ Notify AI ===============================
		}

		//========================================= Surface Pierceability ==============================
		if (pCollision->pEntity[0]->GetType() == PE_PARTICLE)
		{
			const SPierceabilityParams& pierceabilityParams = m_pAmmoParams->pierceabilityParams;

			//If collided water
			if( s_materialLookup.IsMaterial( pCollision->idmat[1], CProjectile::SMaterialLookUp::eType_Water ) )
			{
				if(pierceabilityParams.DestroyOnWaterImpact())
				{
					DestroyAtHitPosition(pCollision->pt);
				}
				else
				{
					EmitUnderwaterTracer(pCollision->pt, pCollision->pt + (pCollision->vloc[0].GetNormalizedSafe() * 100.0f));
				}
			}
			else if (m_pAmmoParams->bounceableBullet == 0)
			{
				float bouncy, friction;
				uint32 pierceabilityMat;
				gEnv->pPhysicalWorld->GetSurfaceParameters(pCollision->idmat[1], bouncy, friction, pierceabilityMat);
				pierceabilityMat &= sf_pierceable_mask;
				
				const bool terrainHit = (pCollision->idCollider == -1);

				bool thouShallNotPass = terrainHit;
				if (!CheckAnyProjectileFlags(ePFlag_ownerIsPlayer))
					thouShallNotPass = thouShallNotPass || pierceabilityParams.DestroyOnImpact(pierceabilityMat);

				if (!thouShallNotPass)
					HandlePierceableSurface(pCollision, pTarget, hitDir, bProcessCollisionEvent);

				const bool destroy = thouShallNotPass || ShouldDestroyCannonBall();
				if (destroy)
				{
					DestroyAtHitPosition(pCollision->pt);
				}
			}
		}
	}
}
Ejemplo n.º 23
0
void CPlayerStateJump::Landed(CPlayer& player, const bool isHeavyWeapon, float fallSpeed)
{
#ifdef STATE_DEBUG
	bool remoteControlled = false;
	IVehicle* pVehicle = player.GetLinkedVehicle();
	if(pVehicle)
	{
		IVehicleSeat* pVehicleSeat = pVehicle->GetSeatForPassenger(player.GetEntityId());
		if(pVehicleSeat && pVehicleSeat->IsRemoteControlled())
		{
			remoteControlled = true;
		}
	}
	CRY_ASSERT_MESSAGE( player.GetLinkedEntity()==NULL || remoteControlled, "Cannot 'land' when you're linked to another entity!" );
#endif

	const SPlayerStats& stats = player.m_stats;

	Vec3 playerPosition = player.GetEntity()->GetWorldPos();
	IPhysicalEntity *phys = player.GetEntity()->GetPhysics();
	IMaterialEffects *mfx = gEnv->pGame->GetIGameFramework()->GetIMaterialEffects();

	const SActorPhysics& actorPhysics = player.GetActorPhysics();
	int matID = actorPhysics.groundMaterialIdx != -1 ? actorPhysics.groundMaterialIdx : mfx->GetDefaultSurfaceIndex();

	const float fHeightofEntity = playerPosition.z;
	const float worldWaterLevel = player.m_playerStateSwim_WaterTestProxy.GetWaterLevel();
	
	TMFXEffectId effectId = mfx->GetEffectId("bodyfall", matID);
	if (effectId != InvalidEffectId)
	{
		SMFXRunTimeEffectParams params;
		Vec3 direction = Vec3(0,0,0);
		if (IMovementController *pMV = player.GetMovementController())
		{
			SMovementState state;
			pMV->GetMovementState(state);
			direction = state.aimDirection;
		}
		params.pos = playerPosition + direction;
		//params.soundSemantic = eSoundSemantic_Player_Foley;

		float landFallParamVal = (float)__fsel( -(fallSpeed - 7.5f), 0.25f, 0.75f);
		params.AddAudioRtpc("landfall", landFallParamVal);

		const float speedParamVal = min(fabsf((actorPhysics.velocity.z * 0.1f)), 1.0f);
		params.AddAudioRtpc("speed", speedParamVal);

		mfx->ExecuteEffect(effectId, params);
	}

	bool heavyLanded = false;

	IItem* pCurrentItem = player.GetCurrentItem();
	CWeapon* pCurrentWeapon = pCurrentItem ? static_cast<CWeapon*>(pCurrentItem->GetIWeapon()) : NULL;

	if (fallSpeed > 0.0f && player.IsPlayer())
	{
		if(!gEnv->bMultiplayer)
		{
			const float verticalSpeed = fabs(fallSpeed);
			const float speedForHeavyLand = g_pGameCVars->pl_health.fallSpeed_HeavyLand;
			if ((verticalSpeed >= speedForHeavyLand) && (player.GetPickAndThrowEntity() == 0) && !player.IsDead())
			{
				if ( !isHeavyWeapon )
				{
					if (pCurrentWeapon)
					{
						pCurrentWeapon->FumbleGrenade();
						pCurrentWeapon->CancelCharge();
					}

					player.StartInteractiveActionByName("HeavyLand", false);
				}
				heavyLanded = true;
			}
		}
	}

	if(player.m_isClient)
	{
		if (fallSpeed > 0.0f)
		{
			const float fallIntensityMultiplier = stats.wasHit ? g_pGameCVars->pl_fall_intensity_hit_multiplier : g_pGameCVars->pl_fall_intensity_multiplier;
			const float fallIntensityMax = g_pGameCVars->pl_fall_intensity_max;
			const float fallTimeMultiplier = g_pGameCVars->pl_fall_time_multiplier;
			const float fallTimeMax = g_pGameCVars->pl_fall_time_max;
			const float zoomMultiplayer = (pCurrentWeapon && pCurrentWeapon->IsZoomed()) ? 0.2f : 1.0f;
			const float direction = ((cry_rand()%2)==0) ? -1.0f : 1.0f;
			const float intensity = clamp_tpl(fallIntensityMultiplier*fallSpeed*zoomMultiplayer, 0.0f, fallIntensityMax);
			const float shakeTime = clamp_tpl(fallTimeMultiplier*fallSpeed*zoomMultiplayer, 0.0f, fallTimeMax);
			const Vec3 rotation = Vec3(-0.5f, 0.15f*direction, 0.05f*direction);

			if (CScreenEffects* pGameScreenEffects = g_pGame->GetScreenEffects())
			{
				pGameScreenEffects->CamShake(rotation*intensity, Vec3(0, 0, 0), shakeTime, shakeTime, 0.05f, CScreenEffects::eCS_GID_Player);
			}

			IForceFeedbackSystem* pForceFeedback = g_pGame->GetIGameFramework()->GetIForceFeedbackSystem();
			assert(pForceFeedback);

			ForceFeedbackFxId fxId = pForceFeedback->GetEffectIdByName("landFF");
			pForceFeedback->PlayForceFeedbackEffect(fxId, SForceFeedbackRuntimeParams(intensity, 0.0f));

			if(fallSpeed > 7.0f)
			{
				player.PlaySound(CPlayer::ESound_Fall_Drop);
			}

			CPlayer::EPlayerSounds playerSound = heavyLanded ? CPlayer::ESound_Gear_HeavyLand : CPlayer::ESound_Gear_Land;
			player.PlaySound(playerSound, true);
		}
		CCCPOINT(PlayerMovement_LocalPlayerLanded);
	}
	
	if( gEnv->pAISystem )
	{
		// Notify AI
		//If silent feet active, ignore here
		const float noiseSupression = 0.0f;
		const float fAISoundRadius = (g_pGameCVars->ai_perception.landed_baseRadius + (g_pGameCVars->ai_perception.landed_speedMultiplier * fallSpeed)) * (1.0f - noiseSupression);
		SAIStimulus stim(AISTIM_SOUND, AISOUND_MOVEMENT_LOUD, player.GetEntityId(), 0,
			player.GetEntity()->GetWorldPos() + player.GetEyeOffset(), ZERO, fAISoundRadius);
		gEnv->pAISystem->RegisterStimulus(stim);
	}

	// Record 'Land' telemetry stats.

	CStatsRecordingMgr::TryTrackEvent(&player, eGSE_Land, fallSpeed);

	if (fallSpeed > 0.0f)
	{
		player.CreateScriptEvent( heavyLanded ? "heavylanded" : "landed",stats.fallSpeed);
	}
}
Ejemplo n.º 24
0
void stateloader (char *statename, unsigned char keycheck, unsigned char xfercheck)
{
  extern unsigned char PauseLoad;

  static char txtloadmsg[] = "STATE - LOADED.";
  static char txtconvmsg[] = "STATE - TOO OLD.";
  static char txtnfndmsg[] = "UNABLE TO LOAD STATE -.";
  static char txtrrldmsg[] = "RR STATE - LOADED.";

  static char *txtloadnum = 0;
  static char *txtconvnum = 0;
  static char *txtnfndnum = 0;
  static char *txtrrldnum = 0;

  //Get the state number
  INSERT_POSITION_NUMBER(txtloadmsg, txtloadnum);
  INSERT_POSITION_NUMBER(txtconvmsg, txtconvnum);
  INSERT_POSITION_NUMBER(txtnfndmsg, txtnfndnum);
  INSERT_POSITION_NUMBER(txtrrldmsg, txtrrldnum);

  #ifdef __UNIXSDL__
  SRAMChdir();
  #endif

  if (keycheck)
  {
    pressed[1] = 0;
    pressed[KeyLoadState] = 2;
    multchange = 1;
    MessageOn = MsgCount;
  }

  switch (MovieProcessing)
  {
    bool mzt_load(char *, bool);

    case 1:
      if (mzt_load(statename, true))
      {
        Msgptr = "CHAPTER LOADED.";
      }
      else
      {
        Msgptr = txtnfndmsg;
      }
      MessageOn = MsgCount;
      return;
    case 2:
      if (mzt_load(statename, false))
      {
        Msgptr = txtrrldmsg;
        MessageOn = MsgCount;

        if (PauseLoad || EMUPause)
        {
          PauseFrameMode = EMUPause = true;
        }
      }
      else
      {
        Msgptr = txtnfndmsg;
      }
      MessageOn = MsgCount;
      return;
  }

  clim();

  //Actual state loading code
  if ((fhandle = fopen(statename,"rb")))
  {
    if (xfercheck)      { Totalbyteloaded = 0; }

    if (zst_load(fhandle, 0))
    {
      Msgptr = txtloadmsg; // 'STATE X LOADED.'

      if (PauseLoad || EMUPause)
      {
        PauseFrameMode = EMUPause = true;
      }
    }
    else
    {
      Msgptr = txtconvmsg; // 'STATE X TOO OLD.' - I don't think this is always accurate -Nach
    }
    fclose(fhandle);
  }
  else
  {
    Msgptr = txtnfndmsg; // 'UNABLE TO LOAD STATE X.'
  }

  Voice0Disable = 1;
  Voice1Disable = 1;
  Voice2Disable = 1;
  Voice3Disable = 1;
  Voice4Disable = 1;
  Voice5Disable = 1;
  Voice6Disable = 1;
  Voice7Disable = 1;

  stim();
}