void CMonsterSquad::Attack_AssignTargetDir(ENTITY_VEC &members, const CEntity *enemy)
{
	_elem	first;
	_elem	last;

	lines.clear();

	// сортировать по убыванию расстояния от npc до врага 
	std::sort(members.begin(), members.end(), sort_predicate(enemy));
	if (members.empty()) return;

	float delta_yaw = PI_MUL_2 / members.size();

	// обработать ближний элемент
	first.pE		= members.back();
	first.p_from	= first.pE->Position();
	first.yaw		= 0;
	members.pop_back();

	lines.push_back(first);

	// обработать дальний элемент
	if (!members.empty()) {
		last.pE			= members[0];
		last.p_from		= last.pE->Position();
		last.yaw		= PI;
		members.erase	(members.begin());

		lines.push_back(last);
	}

	Fvector target_pos = enemy->Position();
	float	next_right_yaw	= delta_yaw;
	float	next_left_yaw	= delta_yaw;

	// проходим с конца members в начало (начиная с наименьшего расстояния)
	while (!members.empty()) {
		CEntity *pCur;

		pCur = members.back();
		members.pop_back();

		_elem cur_line;
		cur_line.p_from		= pCur->Position();
		cur_line.pE			= pCur;

		// определить cur_line.yaw

		float h1,p1,h2,p2;
		Fvector dir;
		dir.sub(target_pos, first.p_from);
		dir.getHP(h1,p1);	
		dir.sub(target_pos, cur_line.p_from);
		dir.getHP(h2,p2);

		bool b_add_left = false;

		if (angle_normalize_signed(h2 - h1) > 0)  {		// right
			if ((next_right_yaw < PI) && !fsimilar(next_right_yaw, PI, PI/60.f)) b_add_left = false;
			else b_add_left = true;
		} else {										// left
			if ((next_left_yaw < PI) && !fsimilar(next_left_yaw, PI, PI/60.f)) b_add_left = true;
			else b_add_left = false;
		}

		if (b_add_left) {
			cur_line.yaw = -next_left_yaw;
			next_left_yaw += delta_yaw;
		} else {
			cur_line.yaw = next_right_yaw;
			next_right_yaw += delta_yaw;
		}

		lines.push_back(cur_line);
	}

	// Пройти по всем линиям и заполнить таргеты у npc
	float first_h, first_p;
	Fvector d; d.sub(target_pos,first.p_from);
	d.getHP(first_h, first_p);

	for (u32 i = 0; i < lines.size(); i++){
		SSquadCommand command;
		command.type			= SC_ATTACK;
		command.entity			= enemy;
		command.direction.setHP	(first_h + lines[i].yaw, first_p);
		UpdateCommand(lines[i].pE, command);
	}
}
Beispiel #2
0
void CEnvironment::OnFrame()
{
#ifdef _EDITOR
	SetGameTime				(fGameTime+Device.fTimeDelta*fTimeFactor,fTimeFactor);
    if (fsimilar(ed_to_time,DAY_LENGTH)&&fsimilar(ed_from_time,0.f)){
	    if (fGameTime>DAY_LENGTH)	fGameTime-=DAY_LENGTH;
    }else{
	    if (fGameTime>ed_to_time){	
        	fGameTime=fGameTime-ed_to_time+ed_from_time;
            Current[0]=Current[1]=0;
        }
    	if (fGameTime<ed_from_time){	
        	fGameTime=ed_from_time;
            Current[0]=Current[1]=0;
        }
    }
	if (!psDeviceFlags.is(rsEnvironment))		return;
#else
	if (!g_pGameLevel)		return;
#endif

//	if (pInput->iGetAsyncKeyState(DIK_O))		SetWeatherFX("surge_day"); 

	if (bWFX&&(wfx_time<=0.f)) StopWFX();

	SelectEnvs				(fGameTime);
    VERIFY					(Current[0]&&Current[1]);

	float current_weight	= TimeWeight(fGameTime,Current[0]->exec_time,Current[1]->exec_time);

	// modifiers
	CEnvModifier			EM;
	EM.far_plane			= 0;
	EM.fog_color.set		( 0,0,0 );
	EM.fog_density			= 0;
	EM.ambient.set			( 0,0,0 );
	EM.sky_color.set		( 0,0,0 );
	EM.hemi_color.set		( 0,0,0 );
	Fvector	view			= Device.vCameraPosition;
	float	mpower			= 0;
	for (xr_vector<CEnvModifier>::iterator mit=Modifiers.begin(); mit!=Modifiers.end(); mit++)
		mpower				+= EM.sum(*mit,view);

	// final lerp
	CurrentEnv.lerp				(this,*Current[0],*Current[1],current_weight,EM,mpower);
#ifndef SUN_DIR_NOT_DEBUG
	if(CurrentEnv.sun_dir.y>0)
	{
		Log("CurrentEnv.sun_dir", CurrentEnv.sun_dir);
		Log("current_weight", current_weight);
		Log("mpower", mpower);

		Log("Current[0]->sun_dir", Current[0]->sun_dir);
		Log("Current[1]->sun_dir", Current[1]->sun_dir);

	}
#endif
	VERIFY2						(CurrentEnv.sun_dir.y<0,"Invalid sun direction settings in lerp");

	if (::Render->get_generation()==IRender_interface::GENERATION_R2){
		//. very very ugly hack
		if (HW.Caps.raster_major >= 3 && HW.Caps.geometry.bVTF){
			// tonemapping in VS
			CurrentEnv.sky_r_textures.push_back		(mk_pair(u32(D3DVERTEXTEXTURESAMPLER0),tonemap));	//. hack
			CurrentEnv.sky_r_textures_env.push_back	(mk_pair(u32(D3DVERTEXTEXTURESAMPLER0),tonemap));	//. hack
			CurrentEnv.clouds_r_textures.push_back	(mk_pair(u32(D3DVERTEXTEXTURESAMPLER0),tonemap));	//. hack
		} else {
			// tonemapping in PS
			CurrentEnv.sky_r_textures.push_back		(mk_pair(2,tonemap));								//. hack
			CurrentEnv.sky_r_textures_env.push_back	(mk_pair(2,tonemap));								//. hack
			CurrentEnv.clouds_r_textures.push_back	(mk_pair(2,tonemap));								//. hack
		}
		
	}

	//. Setup skybox textures, somewhat ugly
	IDirect3DBaseTexture9*	e0	= CurrentEnv.sky_r_textures[0].second->surface_get();
	IDirect3DBaseTexture9*	e1	= CurrentEnv.sky_r_textures[1].second->surface_get();
	
	tsky0->surface_set		(e0);	_RELEASE(e0);
	tsky1->surface_set		(e1);	_RELEASE(e1);

	PerlinNoise1D->SetFrequency		(wind_gust_factor*MAX_NOISE_FREQ);
	wind_strength_factor			= clampr(PerlinNoise1D->GetContinious(Device.fTimeGlobal)+0.5f,0.f,1.f); 

    int l_id							=	(current_weight<0.5f)?Current[0]->lens_flare_id:Current[1]->lens_flare_id;
	eff_LensFlare->OnFrame				(l_id);
	int t_id							=	(current_weight<0.5f)?Current[0]->tb_id:Current[1]->tb_id;
    eff_Thunderbolt->OnFrame			(t_id,CurrentEnv.bolt_period,CurrentEnv.bolt_duration);
	eff_Rain->OnFrame					();

	// ******************** Environment params (setting)
	CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGCOLOR,	color_rgba_f(CurrentEnv.fog_color.x,CurrentEnv.fog_color.y,CurrentEnv.fog_color.z,0) )); 
	CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGSTART,	*(u32 *)(&CurrentEnv.fog_near)	));
	CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGEND,	*(u32 *)(&CurrentEnv.fog_far)	));
}
Beispiel #3
0
bool bonesBone::NeedTurn()
{
	if (!fsimilar(params.cur_yaw, params.target_yaw, EPS_L)) return true;
	return false;
}
void msimulator_Simulate( Fvector& result, Fvector& start, Fvector& end, float _radius, float _height)
{
    SCollisionData	cl_data;
    float			half_height	= _height/2;

    // Calc BB
    Fbox			b1,b2,bb;
    create_bb		(b1,start,	_radius,_height);
    create_bb		(b2,end,	_radius,_height);
    bb.merge		(b1,b2);
    bb.grow			(0.05f);

    // Collision query
    Fvector			bbC,bbD;
    bb.get_CD		(bbC,bbD);
    XRC.box_options	(0);
    XRC.box_query	(&Level,bbC,bbD);

    // XForm everything to ellipsoid space
    Fvector			xf;
    xf.set			(1/_radius,1/half_height,1/_radius);

    Fvector			Lposition;
    Lposition.set	(start);
    Lposition.y		+= half_height;
    Lposition.mul	(xf);

    Fvector			target;
    target.set		(end);
    target.y		+= half_height;
    target.mul		(xf);

    Fvector			Lvelocity;
    Lvelocity.sub	(end,start);
    Lvelocity.mul	(xf);

    cl_data.vLastSafePosition.set	(Lposition);

    // Get the data for the triangles in question and scale to ellipsoid space
    int tri_count			= XRC.r_count();
    clContactedT.resize		(tri_count);
    if (tri_count) {
        Fvector vel_dir;
        vel_dir.normalize_safe	(Lvelocity);
        for (int i_t=0; i_t<tri_count; i_t++) {
            cl_tri& T			= clContactedT[i_t];
            CDB::RESULT&		rp = XRC.r_begin()[i_t];
//			CDB::TRI&	O		=
            *(Level.get_tris()+rp.id);

            T.p[0].mul			(rp.verts[0],xf);
            T.p[1].mul			(rp.verts[1],xf);
            T.p[2].mul			(rp.verts[2],xf);
            T.N.mknormal		(T.p[0],T.p[1],T.p[2]);

            T.d = -T.N.dotproduct(T.p[0]);
            T.e10.sub(T.p[1],T.p[0]);
            T.e10s = T.e10.magnitude();
            T.e10.div(T.e10s);
            T.e21.sub(T.p[2],T.p[1]);
            T.e21s = T.e21.magnitude();
            T.e21.div(T.e21s);
            T.e02.sub(T.p[0],T.p[2]);
            T.e02s = T.e02.magnitude();
            T.e02.div(T.e02s);
        }
    }

    // call the recursive collision response function
    Fvector POS;

    for (int i=0; i<3; i++) {
        POS.set(msimulator_CollideWithWorld(cl_data, Lposition, Lvelocity, 0));
        if (fsimilar(POS.x,target.x)&&fsimilar(POS.z,target.z)) break;

        Lposition.set	(POS);
        Lvelocity.sub	(target,POS);
        Lvelocity.y		= 0;
    }

    result.div(POS,xf);
    result.y-=half_height;
}
Beispiel #5
0
void CActor::g_Orientate	(u32 mstate_rl, float dt)
{
	static float fwd_l_strafe_yaw	= deg2rad(pSettings->r_float(ACTOR_ANIM_SECT,	"fwd_l_strafe_yaw"));
	static float back_l_strafe_yaw	= deg2rad(pSettings->r_float(ACTOR_ANIM_SECT,	"back_l_strafe_yaw"));
	static float fwd_r_strafe_yaw	= deg2rad(pSettings->r_float(ACTOR_ANIM_SECT,	"fwd_r_strafe_yaw"));
	static float back_r_strafe_yaw	= deg2rad(pSettings->r_float(ACTOR_ANIM_SECT,	"back_r_strafe_yaw"));
	static float l_strafe_yaw		= deg2rad(pSettings->r_float(ACTOR_ANIM_SECT,	"l_strafe_yaw"));
	static float r_strafe_yaw		= deg2rad(pSettings->r_float(ACTOR_ANIM_SECT,	"r_strafe_yaw"));

	if(!g_Alive())return;
	// visual effect of "fwd+strafe" like motion
	float calc_yaw = 0;
	if(mstate_real&mcClimb)
	{
		if(g_LadderOrient()) return;
	}
	switch(mstate_rl&mcAnyMove)
	{
	case mcFwd+mcLStrafe:
		calc_yaw = +fwd_l_strafe_yaw;//+PI_DIV_4; 
		break;
	case mcBack+mcRStrafe:
		calc_yaw = +back_r_strafe_yaw;//+PI_DIV_4; 
		break;
	case mcFwd+mcRStrafe:
		calc_yaw = -fwd_r_strafe_yaw;//-PI_DIV_4; 
		break;
	case mcBack+mcLStrafe: 
		calc_yaw = -back_l_strafe_yaw;//-PI_DIV_4; 
		break;
	case mcLStrafe:
		calc_yaw = +l_strafe_yaw;//+PI_DIV_3-EPS_L; 
		break;
	case mcRStrafe:
		calc_yaw = -r_strafe_yaw;//-PI_DIV_4+EPS_L; 
		break;
	}

	// lerp angle for "effect" and capture torso data from camera
	angle_lerp		(r_model_yaw_delta,calc_yaw,PI_MUL_4,dt);

	// build matrix
	Fmatrix mXFORM;
	mXFORM.rotateY	(-(r_model_yaw + r_model_yaw_delta));
	mXFORM.c.set	(Position());
	XFORM().set		(mXFORM);

	//-------------------------------------------------

	float tgt_roll		=	0.f;
	if (mstate_rl&mcLookout)
	{
		tgt_roll		=	(mstate_rl&mcLLookout)?-ACTOR_LOOKOUT_ANGLE:ACTOR_LOOKOUT_ANGLE;
		
		if( (mstate_rl&mcLLookout) && (mstate_rl&mcRLookout) )
			tgt_roll	= 0.0f;
	}
	if (!fsimilar(tgt_roll,r_torso_tgt_roll,EPS)){
		angle_lerp		(r_torso_tgt_roll,tgt_roll,PI_MUL_2,dt);
		r_torso_tgt_roll= angle_normalize_signed(r_torso_tgt_roll);
	}
}
void CControlDirection::update_frame()
{
	pitch_correction			();	

	SRotationEventData			event_data;
	event_data.angle			= 0;

	bool heading_similar		= false;
	bool pitch_similar			= false;

	// difference
	float diff = angle_difference(m_pitch.current_angle, m_data.pitch.target_angle) * 4.0f;
	clamp(diff, PI_DIV_6, 5 * PI_DIV_6);

	m_data.pitch.target_speed = m_pitch.current_speed = diff;

	// поправка угловой скорости в соответствии с текущей и таргетовой линейной скоростями
	// heading speed correction
	if (!fis_zero(m_man->movement().velocity_current()) && !fis_zero(m_man->movement().velocity_target()) && m_data.linear_dependency)
		m_heading.current_speed	= m_data.heading.target_speed * m_man->movement().velocity_current() / (m_man->movement().velocity_target() + EPS_L);
	else 
		velocity_lerp			(m_heading.current_speed, m_data.heading.target_speed, m_heading.current_acc, m_object->client_update_fdelta());

	m_heading.current_angle		= angle_normalize(m_heading.current_angle);
	m_data.heading.target_angle	= angle_normalize(m_data.heading.target_angle);
	
	if (fsimilar(m_heading.current_angle, m_data.heading.target_angle)) heading_similar = true;
	angle_lerp(m_heading.current_angle, m_data.heading.target_angle, m_heading.current_speed, m_object->client_update_fdelta());
	if (!heading_similar && fsimilar(m_heading.current_angle, m_data.heading.target_angle)) {
		event_data.angle |= SRotationEventData::eHeading;
	}

	// update pitch
	velocity_lerp				(m_pitch.current_speed, m_data.pitch.target_speed, m_pitch.current_acc, m_object->client_update_fdelta());

	m_pitch.current_angle		= angle_normalize_signed	(m_pitch.current_angle);
	m_data.pitch.target_angle	= angle_normalize_signed	(m_data.pitch.target_angle);

	if (fsimilar(m_pitch.current_angle, m_data.pitch.target_angle)) pitch_similar = true;
	angle_lerp					(m_pitch.current_angle, m_data.pitch.target_angle, m_pitch.current_speed, m_object->client_update_fdelta());
	if (!pitch_similar && fsimilar(m_pitch.current_angle, m_data.pitch.target_angle)) {
		event_data.angle |= SRotationEventData::ePitch;
	}

	// set
	m_man->path_builder().m_body.speed			= m_heading.current_speed;
	m_man->path_builder().m_body.current.yaw	= m_heading.current_angle;
	m_man->path_builder().m_body.target.yaw		= m_heading.current_angle;
	m_man->path_builder().m_body.current.pitch	= m_pitch.current_angle;
	m_man->path_builder().m_body.target.pitch	= m_pitch.current_angle;

	// save object position
	Fvector P					= m_object->Position();
	// set angles
	if(!m_object->animation_movement_controlled())
		m_object->XFORM().setHPB	(-m_man->path_builder().m_body.current.yaw,-m_man->path_builder().m_body.current.pitch,0);
	// restore object position
	m_object->Position()		= P;

	
	// if there is an event
	if (event_data.angle)		m_man->notify(ControlCom::eventRotationEnd, &event_data);
}
Beispiel #7
0
void	CGlow::set_radius		(float R)			{
	if (fsimilar(radius,R))		return;
	radius						= R;
	spatial_move				();
};
Beispiel #8
0
void	light::set_rotation		(const Fvector& D, const Fvector& R)	{ 
	Fvector	old_D		= direction;
	direction.normalize	(D);
	right.normalize(R);
	if (!fsimilar(1.f, old_D.dotproduct(D)))	spatial_move	();
}
Beispiel #9
0
void CWeapon::FireTrace		(const Fvector& P, const Fvector& D)
{
	VERIFY		(m_magazine.size());

	CCartridge &l_cartridge = m_magazine.back();
//	Msg("ammo - %s", l_cartridge.m_ammoSect.c_str());
	VERIFY		(u16(-1) != l_cartridge.bullet_material_idx);
	//-------------------------------------------------------------	
	l_cartridge.m_flags.set				(CCartridge::cfTracer,(m_bHasTracers & !!l_cartridge.m_flags.test(CCartridge::cfTracer)));
	if (m_u8TracerColorID != u8(-1))
		l_cartridge.param_s.u8ColorID	= m_u8TracerColorID;
	//-------------------------------------------------------------
	//повысить изношенность оружия с учетом влияния конкретного патрона
//	float Deterioration = GetWeaponDeterioration();
//	Msg("Deterioration = %f", Deterioration);
	ChangeCondition(-GetWeaponDeterioration()*l_cartridge.param_s.impair);

	
	float fire_disp = 0.f;
	CActor* tmp_actor = NULL;
	if (!IsGameTypeSingle())
	{
		tmp_actor = smart_cast<CActor*>(Level().CurrentControlEntity());
		if (tmp_actor)
		{
			CEntity::SEntityState state;
			tmp_actor->g_State(state);
			if (m_first_bullet_controller.is_bullet_first(state.fVelocity))
			{
				fire_disp = m_first_bullet_controller.get_fire_dispertion();
				m_first_bullet_controller.make_shot();
			}
		}
	}
	if (fsimilar(fire_disp, 0.f))
	{
		//CActor* tmp_actor = smart_cast<CActor*>(Level().CurrentControlEntity());
		if (H_Parent() && (H_Parent() == tmp_actor))
		{
			fire_disp = tmp_actor->GetFireDispertion();
		} else
		{
			fire_disp = GetFireDispersion(true);
		}
	}
	

	bool SendHit = SendHitAllowed(H_Parent());
	//выстерлить пулю (с учетом возможной стрельбы дробью)
	for(int i = 0; i < l_cartridge.param_s.buckShot; ++i) 
	{
		FireBullet(P, D, fire_disp, l_cartridge, H_Parent()->ID(), ID(), SendHit);
	}

	StartShotParticles		();
	
	if(m_bLightShotEnabled) 
		Light_Start			();

	
	// Ammo
	m_magazine.pop_back	();
	--iAmmoElapsed;

	VERIFY((u32)iAmmoElapsed == m_magazine.size());
}
Beispiel #10
0
bool CIKFoot::GetFootStepMatrix( ik_goal_matrix &m, const Fmatrix &g_anim, const  SIKCollideData &cld, bool collide, bool rotation, bool b_make_shift/*=true*/ )const
{
	const Fmatrix global_anim = g_anim;
	Fvector	local_point;		ToePosition( local_point );													//toe position in bone[2] space
	Fvector	global_point;		global_anim.transform_tiny( global_point, local_point );						//non collided toe in global space
	Fvector foot_normal;		FootNormal( foot_normal );
	global_anim.transform_dir( foot_normal );
#ifdef DEBUG
		//if( ph_dbg_draw_mask.test( phDbgDrawIKGoal ) )
		//{
		//	DBG_DrawLine( global_point, Fvector().add( global_point, foot_normal ), D3DCOLOR_XRGB( 0, 255, 255) );
		//}
#endif
	if( cld.m_collide_point == ik_foot_geom::heel || cld.m_collide_point == ik_foot_geom::side )
	{
		Fmatrix foot;ref_bone_to_foot( foot, g_anim );
		Fvector heel;
		HeelPosition( heel );
		foot.transform_tiny(global_point, heel );
#ifdef DEBUG
		if( ph_dbg_draw_mask.test( phDbgDrawIKGoal ) )
			DBG_DrawPoint( global_point, 0.01, D3DCOLOR_XRGB( 0, 255, 255));
#endif
		Fmatrix foot_to_ref;
		ref_bone_to_foot_transform(foot_to_ref).transform_tiny(local_point, heel );
	}

	float	dtoe_tri		=-cld.m_plane.d - cld.m_plane.n.dotproduct( global_point );	
	if(  !cld.collided ||  _abs( dtoe_tri ) > collide_dist )
	{
		m.set( global_anim, ik_goal_matrix::cl_free );
		return false;
	}

	Fplane p = cld.m_plane;
	Fmatrix xm; xm.set( global_anim );
	ik_goal_matrix::e_collide_state cl_state = ik_goal_matrix::cl_undefined;
	if( rotation )//!collide || ik_allign_free_foot
		cl_state = rotate( xm, p, foot_normal, global_point, collide );

	if( b_make_shift && make_shift( xm, local_point, collide, p, cld.m_pick_dir ) )
		switch( cl_state )
		{
			case ik_goal_matrix::cl_aligned		:					break;
			case ik_goal_matrix::cl_undefined	:
			case ik_goal_matrix::cl_free		:
					cl_state = ik_goal_matrix::cl_translational;	break;
			case ik_goal_matrix::cl_rotational:
					cl_state = ik_goal_matrix::cl_mixed;			break;
			default:		NODEFAULT;
			
		}
	else if( cl_state == ik_goal_matrix::cl_undefined )
			cl_state = ik_goal_matrix::cl_free;
	

	VERIFY( _valid( xm ) );
	m.set( xm, cl_state );
#ifdef DEBUG
	if(ph_dbg_draw_mask.test( phDbgDrawIKGoal ))
	{
		DBG_DrawPoint( global_point, 0.03f, D3DCOLOR_RGBA( 255, 0, 0, 255 ) );
	}
	if(!fsimilar( _abs( DET( g_anim ) - 1.f ), _abs( DET( m.get() ) - 1.f ), 0.001f ) )
		Msg("scale g_anim: %f scale m: %f ",  DET( g_anim ) ,  DET( m.get() ) );
#endif

	return true;
}
Beispiel #11
0
void CCar::Init()
{

	CPHCollisionDamageReceiver::Init();

	//get reference wheel radius
	IKinematics* pKinematics=smart_cast<IKinematics*>(Visual());
	CInifile* ini = pKinematics->LL_UserData();
	R_ASSERT2(ini,"Car has no description !!! See ActorEditor Object - UserData");
	///SWheel& ref_wheel=m_wheels_map.find(pKinematics->LL_BoneID(ini->r_string("car_definition","reference_wheel")))->second;

	if(ini->section_exist("air_resistance"))
	{
		PPhysicsShell()->SetAirResistance(default_k_l*ini->r_float("air_resistance","linear_factor"),default_k_w*ini->r_float("air_resistance","angular_factor"));
	}
	if(ini->line_exist("car_definition","steer"))
	{
		
		
		m_bone_steer=pKinematics->LL_BoneID(ini->r_string("car_definition","steer"));
		VERIFY2(fsimilar(DET(pKinematics->LL_GetTransform(m_bone_steer)),1.f,EPS_L),"BBADD MTX");
		pKinematics->LL_GetBoneInstance(m_bone_steer).set_callback(bctPhysics,cb_Steer,this);
	}
	m_steer_angle=0.f;
	//ref_wheel.Init();
	m_ref_radius=ini->r_float("car_definition","reference_radius");//ref_wheel.radius;
	b_exploded						=false;
	b_engine_on						=false;
	b_clutch						=false;
	b_starting						=false;
	b_stalling						=false;
	b_transmission_switching		=false;
	m_root_transform.set(bone_map.find(pKinematics->LL_GetBoneRoot())->second.element->mXFORM);
	m_current_transmission_num=0;
	m_pPhysicsShell->set_DynamicScales(1.f,1.f);
	CDamagableItem::Init(GetfHealth(),3);
	float l_time_to_explosion=READ_IF_EXISTS(ini,r_float,"car_definition","time_to_explosion",120.f);
	CDelayedActionFuse::Initialize(l_time_to_explosion,CDamagableItem::DamageLevelToHealth(2));
	{
		xr_map<u16,SWheel>::iterator i,e;
		i=m_wheels_map.begin();
		e=m_wheels_map.end();
		for(;i!=e;++i)
		{
			i->second.Init();
			i->second.CDamagableHealthItem::Init(100.f,2);
		}
	}

	{
		xr_vector<SWheelDrive>::iterator i,e;
		i=m_driving_wheels.begin();
		e=m_driving_wheels.end();
		for(;i!=e;++i)
			i->Init();
	}

	{
		xr_vector<SWheelBreak>::iterator i,e;
		i=m_breaking_wheels.begin();
		e=m_breaking_wheels.end();
		for(;i!=e;++i)
			i->Init();
	}

	{
		xr_vector<SWheelSteer>::iterator i,e;
		i=m_steering_wheels.begin();
		e=m_steering_wheels.end();
		for(;i!=e;++i)
			i->Init();
	}

	{
		xr_vector<SExhaust>::iterator i,e;
		i=m_exhausts.begin();
		e=m_exhausts.end();
		for(;i!=e;++i)
			i->Init();
	}

	{
		xr_map<u16,SDoor>::iterator i,e;
		i=m_doors.begin();
		e=m_doors.end();
		for(;i!=e;++i)
		{
			i->second.Init();
			i->second.CDamagableHealthItem::Init(100,1);
		}
			
	}

	if(ini->section_exist("damage_items"))
	{
		CInifile::Sect& data		= ini->r_section("damage_items");
		for (CInifile::SectCIt		I=data.Data.begin(); I!=data.Data.end(); I++){
			const CInifile::Item& item	= *I;
			u16 index				= pKinematics->LL_BoneID(*item.first); 
			R_ASSERT3(index != BI_NONE, "Wrong bone name", *item.first);
			xr_map   <u16,SWheel>::iterator i=m_wheels_map.find(index);
			
			if(i!=m_wheels_map.end())
					i->second.CDamagableHealthItem::Init(float(atof(*item.second)),2);
			else 
			{
				xr_map   <u16,SDoor>::iterator i=m_doors.find(index);
				R_ASSERT3(i!=m_doors.end(),"only wheel and doors bones allowed for damage defs",*item.first);
				i->second.CDamagableHealthItem::Init(float(atof(*item.second)),1);
			}

		}
	}
	

	if(ini->section_exist("immunities"))
	{
		LoadImmunities("immunities",ini);
	}

	CDamageManager::reload("car_definition","damage",ini);
	
	HandBreak();
	Transmission(1);

}
Beispiel #12
0
void CEnvironment::OnFrame()
{
#ifdef _EDITOR
    SetGameTime(fGameTime + Device.fTimeDelta*fTimeFactor, fTimeFactor);
    if (fsimilar(ed_to_time, DAY_LENGTH) && fsimilar(ed_from_time, 0.f))
    {
        if (fGameTime > DAY_LENGTH) fGameTime -= DAY_LENGTH;
    }
    else
    {
        if (fGameTime > ed_to_time)
        {
            fGameTime = fGameTime - ed_to_time + ed_from_time;
            Current[0] = Current[1] = 0;
        }
        if (fGameTime < ed_from_time)
        {
            fGameTime = ed_from_time;
            Current[0] = Current[1] = 0;
        }
    }
    if (!psDeviceFlags.is(rsEnvironment)) return;
#else
    if (!g_pGameLevel) return;
#endif

    // if (pInput->iGetAsyncKeyState(DIK_O)) SetWeatherFX("surge_day");
    float current_weight;
    lerp(current_weight);

    // Igor. Dynamic sun position.
    //AVO: allow sun to move as defined in configs
#ifdef DYNAMIC_SUN_MOVEMENT
    if (!::Render->is_sun_static())
        calculate_dynamic_sun_dir();
#endif
    //-AVO

#ifndef MASTER_GOLD
    if (CurrentEnv->sun_dir.y > 0)
    {
        Log("CurrentEnv->sun_dir", CurrentEnv->sun_dir);
        // Log("current_weight", current_weight);
        // Log("mpower", mpower);

        Log("Current[0]->sun_dir", Current[0]->sun_dir);
        Log("Current[1]->sun_dir", Current[1]->sun_dir);

    }
    VERIFY2(CurrentEnv->sun_dir.y < 0, "Invalid sun direction settings in lerp");
#endif // #ifndef MASTER_GOLD

    PerlinNoise1D->SetFrequency(wind_gust_factor*MAX_NOISE_FREQ);
    wind_strength_factor = clampr(PerlinNoise1D->GetContinious(Device.fTimeGlobal) + 0.5f, 0.f, 1.f);

    shared_str l_id = (current_weight < 0.5f) ? Current[0]->lens_flare_id : Current[1]->lens_flare_id;
    eff_LensFlare->OnFrame(l_id);
    shared_str t_id = (current_weight < 0.5f) ? Current[0]->tb_id : Current[1]->tb_id;
    eff_Thunderbolt->OnFrame(t_id, CurrentEnv->bolt_period, CurrentEnv->bolt_duration);
    eff_Rain->OnFrame();

    // ******************** Environment params (setting)
    m_pRender->OnFrame(*this);
}
Beispiel #13
0
void CActorCondition::UpdateCondition()
{
	if(psActorFlags.test(AF_GODMODE_RT))
	{
		UpdateSatiety();
		UpdateBoosters();

		m_fAlcohol		+= m_fV_Alcohol*m_fDeltaTime;
		clamp			(m_fAlcohol,			0.0f,		1.0f);
		if(IsGameTypeSingle())
		{
			CEffectorCam* ce = Actor()->Cameras().GetCamEffector((ECamEffectorType)effAlcohol);
			if(ce)
				RemoveEffector(m_object,effAlcohol);
		}
	}

	if (GodMode())				return;
	if (!object().g_Alive())	return;
	if (!object().Local() && m_object != Level().CurrentViewEntity())		return;	
	
	float base_weight			= object().MaxCarryWeight();
	float cur_weight			= object().inventory().TotalWeight();

	if ((object().mstate_real&mcAnyMove))
	{
		ConditionWalk( cur_weight / base_weight,
			isActorAccelerated( object().mstate_real,object().IsZoomAimingMode() ),
			(object().mstate_real&mcSprint) != 0 );
	}
	else
	{
		ConditionStand( cur_weight / base_weight );
	}
	
	if ( IsGameTypeSingle() )
	{
		float k_max_power = 1.0f;
		if( true )
		{
			k_max_power = 1.0f + _min(cur_weight, base_weight) / base_weight
				+ _max(0.0f, (cur_weight - base_weight) / 10.0f);
		}
		else
		{
			k_max_power = 1.0f;
		}
		SetMaxPower		(GetMaxPower() - m_fPowerLeakSpeed * m_fDeltaTime * k_max_power);
	}


	m_fAlcohol		+= m_fV_Alcohol*m_fDeltaTime;
	clamp			(m_fAlcohol,			0.0f,		1.0f);

	if ( IsGameTypeSingle() )
	{	
		CEffectorCam* ce = Actor()->Cameras().GetCamEffector((ECamEffectorType)effAlcohol);
		if	((m_fAlcohol>0.0001f) ){
			if(!ce){
				AddEffector(m_object,effAlcohol, "effector_alcohol", GET_KOEFF_FUNC(this, &CActorCondition::GetAlcohol));
			}
		}else{
			if(ce)
				RemoveEffector(m_object,effAlcohol);
		}

		
		string512			pp_sect_name;
		shared_str ln		= Level().name();
		if(ln.size())
		{
			CEffectorPP* ppe	= object().Cameras().GetPPEffector((EEffectorPPType)effPsyHealth);
			

			strconcat			(sizeof(pp_sect_name),pp_sect_name, "effector_psy_health", "_", *ln);
			if(!pSettings->section_exist(pp_sect_name))
				xr_strcpy			(pp_sect_name, "effector_psy_health");

			if	( !fsimilar(GetPsyHealth(), 1.0f, 0.05f) )
			{
				if(!ppe)
				{
					AddEffector(m_object,effPsyHealth, pp_sect_name, GET_KOEFF_FUNC(this, &CActorCondition::GetPsy));
				}
			}else
			{
				if(ppe)
					RemoveEffector(m_object,effPsyHealth);
			}
		}
//-		if(fis_zero(GetPsyHealth()))
//-			SetHealth( 0.0f );
	};

	UpdateSatiety();
	UpdateBoosters();

	inherited::UpdateCondition();

	if( IsGameTypeSingle() )
		UpdateTutorialThresholds();

	if(GetHealth()<0.05f && m_death_effector==NULL && IsGameTypeSingle())
	{
		if(pSettings->section_exist("actor_death_effector"))
			m_death_effector = xr_new<CActorDeathEffector>(this, "actor_death_effector");
	}
	if(m_death_effector && m_death_effector->IsActual())
	{
		m_death_effector->UpdateCL	();

		if(!m_death_effector->IsActual())
			m_death_effector->Stop();
	}

	AffectDamage_InjuriousMaterialAndMonstersInfluence();
}
Beispiel #14
0
void	light::set_range		(float R)			{
	float	eps					=	_max	(range*0.1f,EPS_L);
	if (fsimilar(range,R,eps))	return	;
	range						= R		;
	spatial_move				();
};
Beispiel #15
0
void CUIArtefactParams::SetInfo(CGameObject *obj)
{	
	CArtefact *art = smart_cast<CArtefact*> (obj);
	R_ASSERT2(art, "object is not CArtefact");
	const shared_str& af_section = art->cNameSect();
	CActor *pActor = Actor();
	if (!pActor) return;

	string128					_buff;
	float						_h = 0.0f;
	DetachAll					();
	for(u32 i=_item_start; i<_max_item_index; ++i)
	{
		CUIStatic* _s			= m_info_items[i];

		float					_val;
		if(i<_max_item_index1)
		{
#ifdef AF_SHOW_DYNAMIC_PARAMS
			float _actor_val	= pActor->conditions().GetParamByName(af_actor_param_names[i]);			
			float CArtefact::* pRestoreSpeed = af_prop_offsets[i];
			_val = (art->*pRestoreSpeed); // alpet: используется указатель на данные класса
#else
			_val				= pSettings->r_float	(af_section, af_item_sect_names[i]);
			float _actor_val	= pSettings->r_float	("actor_condition", af_actor_param_names[i]);
#endif
			if					(fis_zero(_val))				continue;
			
			_val				= (_val/_actor_val)*100.0f;
		}else
		{
#ifdef AF_SHOW_DYNAMIC_PARAMS			
			u32 idx = i - _max_item_index1;  // absorbation index			 
			_val = art->m_ArtefactHitImmunities.immunities()[idx]; // real absorbation values			
#else
			shared_str _sect	= pSettings->r_string(af_section, "hit_absorbation_sect");
			_val				= pSettings->r_float(_sect, af_item_sect_names[i]);
#endif
			if					(fsimilar(_val, 1.0f))				continue;
			_val				= (1.0f - _val);
			_val				*= 100.0f;

		}
		LPCSTR _sn = "%";
		if(i==_item_radiation_restore_speed || i==_item_power_restore_speed)
		{
			_val				/= 100.0f;
			_sn					= "";
		}

		LPCSTR _color = (_val>0)?"%c[green]":"%c[red]";
		
		if(i==_item_bleeding_restore_speed)
			_val		*=	-1.0f;

		if(i==_item_bleeding_restore_speed || i==_item_radiation_restore_speed)
			_color = (_val>0)?"%c[red]":"%c[green]";


		sprintf_s					(	_buff, "%s %s %+.0f %s", 
									CStringTable().translate(af_item_param_names[i]).c_str(), 
									_color, 
									_val, 
									_sn);
		_s->SetText				(_buff);
		_s->SetWndPos			(_s->GetWndPos().x, _h);
		_h						+= _s->GetWndSize().y;
		AttachChild				(_s);
	}
	SetHeight					(_h);
}
Beispiel #16
0
void	light::set_cone			(float angle)		{
	if (fsimilar(cone,angle))	return	;
	VERIFY						(cone < deg2rad(121.f));	// 120 is hard limit for lights
	cone						= angle;
	spatial_move				();
}
Beispiel #17
0
void SPHNetState::net_Load(IReader &P,const Fvector& min,const Fvector& max)
{
VERIFY( !(fsimilar(min.x,max.x)&&fsimilar(min.y,max.y)&&fsimilar(min.z,max.z)) );
	read(P,min,max);
}
Beispiel #18
0
void CUITrackBar::UpdatePosRelativeToMouse()
{
	float _bkf		= 0.0f;
	int _bki		= 0;
	if(m_b_is_float)
	{
		_bkf = m_f_val; 
	}else
	{
		_bki = m_i_val; 
	}


	float btn_width				= m_pSlider->GetWidth();
	float window_width			= GetWidth();		
	//float fpos					= cursor_pos.x;

	// Start.Real Wolf.06.11.14.
	Fvector2 pos;
	GetAbsolutePos(pos);
	float fpos = GetUICursor()->GetCursorPosition().x - pos.x; 
	// Finish.Real Wolf.06.11.14.

	if( GetInvert() )
		fpos					= window_width - fpos;

	if (fpos < btn_width/2)
		fpos = btn_width/2;
	else 
	if (fpos > window_width - btn_width/2)
		fpos = window_width - btn_width/2;

	float __fval;
	float __fmax	= (m_b_is_float)?m_f_max:(float)m_i_max;
	float __fmin	= (m_b_is_float)?m_f_min:(float)m_i_min;
	float __fstep	= (m_b_is_float)?m_f_step:(float)m_i_step;

	__fval						= (__fmax - __fmin)*(fpos - btn_width/2)/(window_width - btn_width)+ __fmin;
	
	float _d	= (__fval-__fmin);
	
	float _v	= _d/__fstep;
	int _vi		= iFloor(_v);
	float _vf	= __fstep*_vi;
	
	if(_d-_vf>__fstep/2.0f)	
		_vf		+= __fstep;

	__fval		= __fmin+_vf;
	
	clamp		(__fval, __fmin, __fmax);

	if(m_b_is_float)
		m_f_val	= __fval;
	else
		m_i_val	= iFloor(__fval);
	

	bool b_ch = false;
	if(m_b_is_float)
	{
		b_ch  = !fsimilar(_bkf, m_f_val); 
	}else
	{
		b_ch  =  (_bki != m_i_val);
	}

	if(b_ch)
		GetMessageTarget()->SendMessage(this, BUTTON_CLICKED, NULL);

	UpdatePos	();
}
Beispiel #19
0
BOOL CEffectorBobbing::Process		(Fvector &p, Fvector &d, Fvector &n, float& /**fFov/**/, float& /**fFar/**/, float& /**fAspect/**/)
{
	fTime			+= Device.fTimeDelta;
	if (dwMState&ACTOR_DEFS::mcAnyMove){
		if (fReminderFactor<1.f)	fReminderFactor += SPEED_REMINDER*Device.fTimeDelta;
		else						fReminderFactor = 1.f;
	}else{
		if (fReminderFactor>0.f)	fReminderFactor -= SPEED_REMINDER*Device.fTimeDelta;
		else						fReminderFactor = 0.f;
	}
	if (!fsimilar(fReminderFactor,0)){
		Fmatrix		M;
		M.identity	();
		M.j.set		(n);
		M.k.set		(d);
		M.i.crossproduct(n,d);
		M.c.set		(p);
		
		// apply footstep bobbing effect
		Fvector dangle;
		float k		= ((dwMState& ACTOR_DEFS::mcCrouch)?CROUCH_FACTOR:1.f);

		float A, ST;

		if(isActorAccelerated(dwMState, m_bZoomMode))
		{
			A	= m_fAmplitudeRun*k;
			ST	= m_fSpeedRun*fTime*k;
		}
		else if(is_limping)
		{
			A	= m_fAmplitudeLimp*k;
			ST	= m_fSpeedLimp*fTime*k;
		}
		else
		{
			A	= m_fAmplitudeWalk*k;
			ST	= m_fSpeedWalk*fTime*k;
		}
	
		float _sinA	= _abs(_sin(ST)*A)*fReminderFactor;
		float _cosA	= _cos(ST)*A*fReminderFactor;

		p.y			+=	_sinA;
		dangle.x	=	_cosA;
		dangle.z	=	_cosA;
		dangle.y	=	_sinA;

		Fmatrix		R;
		R.setHPB	(dangle.x,dangle.y,dangle.z);

		Fmatrix		mR;
		mR.mul		(M,R);
		
		d.set		(mR.k);
		n.set		(mR.j);
	}
//	else{
//		fTime		= 0;
//	}
	return TRUE;
}
Beispiel #20
0
void CUILines::ParseText() {
    if ( !fsimilar(m_oldWidth, m_wndSize.x) )
    {
        uFlags.set(flNeedReparse, TRUE);
        m_oldWidth = m_wndSize.x;
    }
    if (!uFlags.test(flComplexMode) || !uFlags.test(flNeedReparse))
        return;

    if(NULL == m_pFont)
        return;

    Reset();
    if (!m_text.empty() && NULL == m_pFont)
        R_ASSERT2(false, "can't parse text without font");


    CUILine* line = NULL;
    if (uFlags.test(flColoringMode))
        line = ParseTextToColoredLine(m_text.c_str());
    else
    {
        line = xr_new<CUILine>();
        CUISubLine subline;
        subline.m_text = m_text;
        subline.m_color = GetTextColor();
        line->AddSubLine(&subline);
    }

    BOOL bNewLines = FALSE;

    if (uFlags.test(flRecognizeNewLine))
        if ( m_pFont->IsMultibyte() ) {
            CUILine *ptmp_line = xr_new<CUILine>();
            int vsz = line->m_subLines.size();
            VERIFY( vsz );
            for ( int i = 0 ; i < vsz ; i++ ) {
                char *pszTemp = NULL;
                const u32 tcolor = line->m_subLines[i].m_color;
                char szTempLine[ MAX_MB_CHARS ] , *pszSearch = NULL;
                size_t llen = xr_strlen( line->m_subLines[i].m_text.c_str() );
                VERIFY( llen < MAX_MB_CHARS );
                strcpy( szTempLine , line->m_subLines[i].m_text.c_str() );
                pszSearch = szTempLine;
                while ( ( pszTemp = strstr( pszSearch , "\\n" ) ) != NULL ) {
                    bNewLines = TRUE;
                    *pszTemp = '\0';
                    ptmp_line->AddSubLine( pszSearch , tcolor );
                    pszSearch = pszTemp + 2;
                }
                ptmp_line->AddSubLine( pszSearch , tcolor );
            }
            line->Clear();
            xr_free( line );
            line=ptmp_line;
        } else
            line->ProcessNewLines(); // process "\n"

    if ( m_pFont->IsMultibyte() ) {
#define UBUFFER_SIZE 100
        u16	aMarkers[ UBUFFER_SIZE ];
        CUILine tmp_line;
        char szTempLine[ MAX_MB_CHARS ];
        float fTargetWidth = 1.0f;
        UI()->ClientToScreenScaledWidth( fTargetWidth );
        VERIFY( ( m_wndSize.x > 0 ) && ( fTargetWidth > 0 ) );
        fTargetWidth = m_wndSize.x / fTargetWidth;
        int vsz = line->m_subLines.size();
        VERIFY( vsz );
        if ( ( vsz > 1 ) && ( ! bNewLines ) ) { // only colored line, pizdets
            for ( int i = 0 ; i < vsz ; i++ ) {
                const char *pszText = line->m_subLines[i].m_text.c_str();
                const u32 tcolor = line->m_subLines[i].m_color;
                VERIFY( pszText );
                tmp_line.AddSubLine( pszText , tcolor );
            }
            m_lines.push_back( tmp_line );
            tmp_line.Clear();
        } else {
            for ( int i = 0 ; i < vsz ; i++ ) {
                const char *pszText = line->m_subLines[i].m_text.c_str();
                const u32 tcolor = line->m_subLines[i].m_color;
                u16 uFrom = 0 , uPartLen = 0;
                VERIFY( pszText );
                u16 nMarkers = m_pFont->SplitByWidth( aMarkers , UBUFFER_SIZE , fTargetWidth , pszText );
                for ( u16 j = 0 ; j < nMarkers ; j ++ ) {
                    uPartLen = aMarkers[ j ] - uFrom;
                    VERIFY( ( uPartLen > 0 ) && ( uPartLen < MAX_MB_CHARS ) );
                    strncpy( szTempLine , pszText + uFrom , uPartLen );
                    szTempLine[ uPartLen ] = '\0';
                    tmp_line.AddSubLine( szTempLine , tcolor );
                    m_lines.push_back( tmp_line );
                    tmp_line.Clear();
                    // Compiler bug :)
#pragma warning( disable : 4244 )
                    uFrom += uPartLen;
#pragma warning( default : 4244 )
                }
                strncpy( szTempLine , pszText + uFrom , MAX_MB_CHARS );
                tmp_line.AddSubLine( szTempLine , tcolor );
                m_lines.push_back( tmp_line );
                tmp_line.Clear();
            }
        }
    } else
    {
        float max_width							= m_wndSize.x;
        u32 sbl_cnt								= line->m_subLines.size();
        CUILine									tmp_line;
        string4096								buff;
        float curr_width						= 0.0f;
        bool bnew_line							= false;
        float __eps								= get_str_width(m_pFont,'o');//hack -(
        for(u32 sbl_idx=0; sbl_idx<sbl_cnt; ++sbl_idx)
        {
            bool b_last_subl					= (sbl_idx==sbl_cnt-1);
            CUISubLine& sbl						= line->m_subLines[sbl_idx];
//.			Msg("%s",sbl.m_text.c_str());
            u32 sub_len							= (u32)sbl.m_text.length();
            u32 curr_w_pos						= 0;

            u32 last_space_idx					= 0;
            for(u32 idx=0; idx<sub_len; ++idx)
            {
                bool b_last_ch	= (idx==sub_len-1);

                if(isspace(sbl.m_text[idx]))
                    last_space_idx = idx;

                float w1		= get_str_width(m_pFont, sbl.m_text[idx]);
                bool bOver		= (curr_width+w1+__eps > max_width);

                if(bOver || b_last_ch)
                {
                    if(last_space_idx && !b_last_ch)
                    {
                        idx = last_space_idx;
                        last_space_idx = 0;
                    }

                    strncpy_s			(buff, sizeof(buff), sbl.m_text.c_str()+curr_w_pos, idx-curr_w_pos+1);
//.					Msg					("-%s",buff);
                    tmp_line.AddSubLine	(buff , sbl.m_color);
                    curr_w_pos			= idx+1;
                } else
                    curr_width			+= w1;

                if(bOver || (b_last_ch&&sbl.m_last_in_line) )
                {
                    m_lines.push_back	(tmp_line);
                    tmp_line.Clear		();
                    curr_width			= 0.0f;
                    bnew_line			= false;
                }
            }
            if(b_last_subl && !tmp_line.IsEmpty())
            {
                m_lines.push_back	(tmp_line);
                tmp_line.Clear		();
                curr_width			= 0.0f;
                bnew_line			= false;
            }
        }
    }
//.		while (line->GetSize() > 0 )
//.			m_lines.push_back(*line->CutByLength(m_pFont, m_wndSize.x, uFlags.test(flCutWordsMode)));

    xr_delete(line);
    uFlags.set(flNeedReparse, FALSE);

}
bool CControlDirection::is_turning(float eps_angle)
{
	return (!fsimilar(m_heading.current_angle,m_data.heading.target_angle, eps_angle));
}