Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6133 lines
181 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose: static_prop - don't move, don't animate, don't do anything.
  4. // physics_prop - move, take damage, but don't animate
  5. //
  6. //===========================================================================//
  7. #include "cbase.h"
  8. #include "BasePropDoor.h"
  9. #include "ai_basenpc.h"
  10. #include "npcevent.h"
  11. #include "engine/IEngineSound.h"
  12. #include "locksounds.h"
  13. #include "filters.h"
  14. #include "physics.h"
  15. #include "vphysics_interface.h"
  16. #include "entityoutput.h"
  17. #include "vcollide_parse.h"
  18. #include "studio.h"
  19. #include "explode.h"
  20. #include "utlrbtree.h"
  21. #include "tier1/strtools.h"
  22. #include "physics_impact_damage.h"
  23. #include "KeyValues.h"
  24. #include "filesystem.h"
  25. #include "scriptevent.h"
  26. #include "entityblocker.h"
  27. #include "soundent.h"
  28. #include "EntityFlame.h"
  29. #include "game.h"
  30. #include "physics_prop_ragdoll.h"
  31. #include "decals.h"
  32. #include "hierarchy.h"
  33. #include "shareddefs.h"
  34. #include "physobj.h"
  35. #include "physics_npc_solver.h"
  36. #include "SoundEmitterSystem/isoundemittersystembase.h"
  37. #include "datacache/imdlcache.h"
  38. #include "doors.h"
  39. #include "physics_collisionevent.h"
  40. #include "gamestats.h"
  41. #include "vehicle_base.h"
  42. // memdbgon must be the last include file in a .cpp file!!!
  43. #include "tier0/memdbgon.h"
  44. #define DOOR_HARDWARE_GROUP 1
  45. // Any barrel farther away than this is ignited rather than exploded.
  46. #define PROP_EXPLOSION_IGNITE_RADIUS 32.0f
  47. // How many times to remind the player that supply crates can be broken
  48. // (displayed when the supply crate is picked up)
  49. #define NUM_SUPPLY_CRATE_HUD_HINTS 3
  50. extern CBaseEntity *FindPickerEntity( CBasePlayer *pPlayer );
  51. ConVar g_debug_doors( "g_debug_doors", "0" );
  52. ConVar breakable_disable_gib_limit( "breakable_disable_gib_limit", "0" );
  53. ConVar breakable_multiplayer( "breakable_multiplayer", "1" );
  54. // AI Interaction for being hit by a physics object
  55. int g_interactionHitByPlayerThrownPhysObj = 0;
  56. int g_interactionPlayerPuntedHeavyObject = 0;
  57. int g_ActiveGibCount = 0;
  58. ConVar prop_active_gib_limit( "prop_active_gib_limit", "999999" );
  59. ConVar prop_active_gib_max_fade_time( "prop_active_gib_max_fade_time", "999999" );
  60. #define ACTIVE_GIB_LIMIT prop_active_gib_limit.GetInt()
  61. #define ACTIVE_GIB_FADE prop_active_gib_max_fade_time.GetInt()
  62. // Damage type modifiers for breakable objects.
  63. ConVar func_breakdmg_bullet( "func_breakdmg_bullet", "0.5" );
  64. ConVar func_breakdmg_club( "func_breakdmg_club", "1.5" );
  65. ConVar func_breakdmg_explosive( "func_breakdmg_explosive", "1.25" );
  66. ConVar sv_turbophysics( "sv_turbophysics", "0", FCVAR_REPLICATED, "Turns on turbo physics" );
  67. #ifdef HL2_EPISODIC
  68. #define PROP_FLARE_LIFETIME 30.0f
  69. #define PROP_FLARE_IGNITE_SUBSTRACT 5.0f
  70. CBaseEntity *CreateFlare( Vector vOrigin, QAngle Angles, CBaseEntity *pOwner, float flDuration );
  71. void KillFlare( CBaseEntity *pOwnerEntity, CBaseEntity *pEntity, float flKillTime );
  72. #endif
  73. //-----------------------------------------------------------------------------
  74. // Purpose: Breakable objects take different levels of damage based upon the damage type.
  75. // This isn't contained by CBaseProp, because func_breakables use it as well.
  76. //-----------------------------------------------------------------------------
  77. float GetBreakableDamage( const CTakeDamageInfo &inputInfo, IBreakableWithPropData *pProp )
  78. {
  79. float flDamage = inputInfo.GetDamage();
  80. int iDmgType = inputInfo.GetDamageType();
  81. // Bullet damage?
  82. if ( iDmgType & DMG_BULLET )
  83. {
  84. // Buckshot does double damage to breakables
  85. if ( iDmgType & DMG_BUCKSHOT )
  86. {
  87. if ( pProp )
  88. {
  89. flDamage *= (pProp->GetDmgModBullet() * 2);
  90. }
  91. else
  92. {
  93. // Bullets do little damage to breakables
  94. flDamage *= (func_breakdmg_bullet.GetFloat() * 2);
  95. }
  96. }
  97. else
  98. {
  99. if ( pProp )
  100. {
  101. flDamage *= pProp->GetDmgModBullet();
  102. }
  103. else
  104. {
  105. // Bullets do little damage to breakables
  106. flDamage *= func_breakdmg_bullet.GetFloat();
  107. }
  108. }
  109. }
  110. // Club damage?
  111. if ( iDmgType & DMG_CLUB )
  112. {
  113. if ( pProp )
  114. {
  115. flDamage *= pProp->GetDmgModClub();
  116. }
  117. else
  118. {
  119. // Club does extra damage
  120. flDamage *= func_breakdmg_club.GetFloat();
  121. }
  122. }
  123. // Explosive damage?
  124. if ( iDmgType & DMG_BLAST )
  125. {
  126. if ( pProp )
  127. {
  128. flDamage *= pProp->GetDmgModExplosive();
  129. }
  130. else
  131. {
  132. // Explosions do extra damage
  133. flDamage *= func_breakdmg_explosive.GetFloat();
  134. }
  135. }
  136. if ( (iDmgType & DMG_SLASH) && (iDmgType & DMG_CRUSH) )
  137. {
  138. // Cut by a Ravenholm propeller trap
  139. flDamage *= 10.0f;
  140. }
  141. // Poison & other timebased damage types do no damage
  142. if ( g_pGameRules->Damage_IsTimeBased( iDmgType ) )
  143. {
  144. flDamage = 0;
  145. }
  146. return flDamage;
  147. }
  148. //=============================================================================================================
  149. // BASE PROP
  150. //=============================================================================================================
  151. //-----------------------------------------------------------------------------
  152. // Purpose:
  153. //-----------------------------------------------------------------------------
  154. void CBaseProp::Spawn( void )
  155. {
  156. char *szModel = (char *)STRING( GetModelName() );
  157. if (!szModel || !*szModel)
  158. {
  159. Warning( "prop at %.0f %.0f %0.f missing modelname\n", GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z );
  160. UTIL_Remove( this );
  161. return;
  162. }
  163. PrecacheModel( szModel );
  164. Precache();
  165. SetModel( szModel );
  166. // Load this prop's data from the propdata file
  167. int iResult = ParsePropData();
  168. if ( !OverridePropdata() )
  169. {
  170. if ( iResult == PARSE_FAILED_BAD_DATA )
  171. {
  172. DevWarning( "%s at %.0f %.0f %0.f uses model %s, which has an invalid prop_data type. DELETED.\n", GetClassname(), GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z, szModel );
  173. UTIL_Remove( this );
  174. return;
  175. }
  176. else if ( iResult == PARSE_FAILED_NO_DATA )
  177. {
  178. // If we don't have data, but we're a prop_physics, fail
  179. if ( FClassnameIs( this, "prop_physics" ) )
  180. {
  181. DevWarning( "%s at %.0f %.0f %0.f uses model %s, which has no propdata which means it must be used on a prop_static. DELETED.\n", GetClassname(), GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z, szModel );
  182. UTIL_Remove( this );
  183. return;
  184. }
  185. }
  186. else if ( iResult == PARSE_SUCCEEDED )
  187. {
  188. // If we have data, and we're not a physics prop, fail
  189. if ( !dynamic_cast<CPhysicsProp*>(this) )
  190. {
  191. DevWarning( "%s at %.0f %.0f %0.f uses model %s, which has propdata which means that it be used on a prop_physics. DELETED.\n", GetClassname(), GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z, szModel );
  192. UTIL_Remove( this );
  193. return;
  194. }
  195. }
  196. }
  197. SetMoveType( MOVETYPE_PUSH );
  198. m_takedamage = DAMAGE_NO;
  199. SetNextThink( TICK_NEVER_THINK );
  200. m_flAnimTime = gpGlobals->curtime;
  201. m_flPlaybackRate = 0.0;
  202. SetCycle( 0 );
  203. }
  204. //-----------------------------------------------------------------------------
  205. // Purpose:
  206. //-----------------------------------------------------------------------------
  207. void CBaseProp::Precache( void )
  208. {
  209. if ( GetModelName() == NULL_STRING )
  210. {
  211. Msg( "%s at (%.3f, %.3f, %.3f) has no model name!\n", GetClassname(), GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z );
  212. SetModelName( AllocPooledString( "models/error.mdl" ) );
  213. }
  214. PrecacheModel( STRING( GetModelName() ) );
  215. PrecacheScriptSound( "Metal.SawbladeStick" );
  216. PrecacheScriptSound( "PropaneTank.Burst" );
  217. #ifdef HL2_EPISODIC
  218. UTIL_PrecacheOther( "env_flare" );
  219. #endif
  220. BaseClass::Precache();
  221. }
  222. //-----------------------------------------------------------------------------
  223. // Purpose:
  224. //-----------------------------------------------------------------------------
  225. void CBaseProp::Activate( void )
  226. {
  227. BaseClass::Activate();
  228. // Make sure mapmakers haven't used the wrong prop type.
  229. if ( m_takedamage == DAMAGE_NO && m_iHealth != 0 )
  230. {
  231. Warning("%s has a health specified in model '%s'. Use prop_physics or prop_dynamic instead.\n", GetClassname(), STRING(GetModelName()) );
  232. }
  233. }
  234. //-----------------------------------------------------------------------------
  235. // Purpose: Handles keyvalues from the BSP. Called before spawning.
  236. //-----------------------------------------------------------------------------
  237. bool CBaseProp::KeyValue( const char *szKeyName, const char *szValue )
  238. {
  239. if ( FStrEq(szKeyName, "health") )
  240. {
  241. // Only override props are allowed to override health.
  242. if ( FClassnameIs( this, "prop_physics_override" ) || FClassnameIs( this, "prop_dynamic_override" ) )
  243. return BaseClass::KeyValue( szKeyName, szValue );
  244. return true;
  245. }
  246. else
  247. {
  248. return BaseClass::KeyValue( szKeyName, szValue );
  249. }
  250. return true;
  251. }
  252. //-----------------------------------------------------------------------------
  253. // Purpose: Calculate whether this prop should block LOS or not
  254. //-----------------------------------------------------------------------------
  255. void CBaseProp::CalculateBlockLOS( void )
  256. {
  257. // We block LOS if:
  258. // - One of our dimensions is >40
  259. // - Our other 2 dimensions are >30
  260. // By default, entities block LOS, so we only need to detect non-blockage
  261. bool bFoundLarge = false;
  262. Vector vecSize = CollisionProp()->OBBMaxs() - CollisionProp()->OBBMins();
  263. for ( int i = 0; i < 3; i++ )
  264. {
  265. if ( vecSize[i] > 40 )
  266. {
  267. bFoundLarge = true;
  268. }
  269. if ( vecSize[i] > 30 )
  270. continue;
  271. // Dimension smaller than 30.
  272. SetBlocksLOS( false );
  273. return;
  274. }
  275. if ( !bFoundLarge )
  276. {
  277. // No dimension larger than 40
  278. SetBlocksLOS( false );
  279. }
  280. }
  281. //-----------------------------------------------------------------------------
  282. // Purpose: Parse this prop's data from the model, if it has a keyvalues section.
  283. // Returns true only if this prop is using a model that has a prop_data section that's invalid.
  284. //-----------------------------------------------------------------------------
  285. int CBaseProp::ParsePropData( void )
  286. {
  287. KeyValues *modelKeyValues = new KeyValues("");
  288. if ( !modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( GetModel() ), modelinfo->GetModelKeyValueText( GetModel() ) ) )
  289. {
  290. modelKeyValues->deleteThis();
  291. return PARSE_FAILED_NO_DATA;
  292. }
  293. // Do we have a props section?
  294. KeyValues *pkvPropData = modelKeyValues->FindKey("prop_data");
  295. if ( !pkvPropData )
  296. {
  297. modelKeyValues->deleteThis();
  298. return PARSE_FAILED_NO_DATA;
  299. }
  300. int iResult = g_PropDataSystem.ParsePropFromKV( this, pkvPropData, modelKeyValues );
  301. modelKeyValues->deleteThis();
  302. return iResult;
  303. }
  304. //-----------------------------------------------------------------------------
  305. // Purpose:
  306. //-----------------------------------------------------------------------------
  307. void CBaseProp::DrawDebugGeometryOverlays( void )
  308. {
  309. BaseClass::DrawDebugGeometryOverlays();
  310. if ( m_debugOverlays & OVERLAY_PROP_DEBUG )
  311. {
  312. if ( m_takedamage == DAMAGE_NO )
  313. {
  314. NDebugOverlay::EntityBounds(this, 255, 0, 0, 0, 0 );
  315. }
  316. else if ( m_takedamage == DAMAGE_EVENTS_ONLY )
  317. {
  318. NDebugOverlay::EntityBounds(this, 255, 255, 255, 0, 0 );
  319. }
  320. else
  321. {
  322. // Remap health to green brightness
  323. float flG = RemapVal( m_iHealth, 0, 100, 64, 255 );
  324. flG = clamp( flG, 0.f, 255.f );
  325. NDebugOverlay::EntityBounds(this, 0, flG, 0, 0, 0 );
  326. }
  327. }
  328. }
  329. class CEnableMotionFixup : public CBaseEntity
  330. {
  331. DECLARE_CLASS( CEnableMotionFixup, CBaseEntity );
  332. };
  333. LINK_ENTITY_TO_CLASS( point_enable_motion_fixup, CEnableMotionFixup );
  334. static const char *s_pFadeScaleThink = "FadeScaleThink";
  335. static const char *s_pPropAnimateThink = "PropAnimateThink";
  336. void CBreakableProp::SetEnableMotionPosition( const Vector &position, const QAngle &angles )
  337. {
  338. ClearEnableMotionPosition();
  339. CBaseEntity *pFixup = CBaseEntity::Create( "point_enable_motion_fixup", position, angles, this );
  340. if ( pFixup )
  341. {
  342. pFixup->SetParent( this );
  343. }
  344. }
  345. CBaseEntity *CBreakableProp::FindEnableMotionFixup()
  346. {
  347. CUtlVector<CBaseEntity*> list;
  348. GetAllChildren( this, list );
  349. for ( int i = list.Count()-1; i >= 0; --i )
  350. {
  351. if ( FClassnameIs( list[i], "point_enable_motion_fixup" ) )
  352. return list[i];
  353. }
  354. return NULL;
  355. }
  356. bool CBreakableProp::GetEnableMotionPosition( Vector *pPosition, QAngle *pAngles )
  357. {
  358. CBaseEntity *pFixup = FindEnableMotionFixup();
  359. if ( !pFixup )
  360. return false;
  361. *pPosition = pFixup->GetAbsOrigin();
  362. *pAngles = pFixup->GetAbsAngles();
  363. return true;
  364. }
  365. void CBreakableProp::ClearEnableMotionPosition()
  366. {
  367. CBaseEntity *pFixup = FindEnableMotionFixup();
  368. if ( pFixup )
  369. {
  370. UnlinkFromParent( pFixup );
  371. UTIL_Remove( pFixup );
  372. }
  373. }
  374. //-----------------------------------------------------------------------------
  375. //-----------------------------------------------------------------------------
  376. void CBreakableProp::Ignite( float flFlameLifetime, bool bNPCOnly, float flSize, bool bCalledByLevelDesigner )
  377. {
  378. if( IsOnFire() )
  379. return;
  380. if( !HasInteraction( PROPINTER_FIRE_FLAMMABLE ) )
  381. return;
  382. BaseClass::Ignite( flFlameLifetime, bNPCOnly, flSize, bCalledByLevelDesigner );
  383. if ( g_pGameRules->ShouldBurningPropsEmitLight() )
  384. {
  385. GetEffectEntity()->AddEffects( EF_DIMLIGHT );
  386. }
  387. // Frighten AIs, just in case this is an exploding thing.
  388. CSoundEnt::InsertSound( SOUND_DANGER, GetAbsOrigin(), 128.0f, 1.0f, this, SOUNDENT_CHANNEL_REPEATED_DANGER );
  389. }
  390. //-----------------------------------------------------------------------------
  391. //-----------------------------------------------------------------------------
  392. void CBreakableProp::HandleFirstCollisionInteractions( int index, gamevcollisionevent_t *pEvent )
  393. {
  394. if ( pEvent->pEntities[ !index ]->IsWorld() )
  395. {
  396. if ( HasInteraction( PROPINTER_PHYSGUN_WORLD_STICK ) )
  397. {
  398. HandleInteractionStick( index, pEvent );
  399. }
  400. }
  401. if( HasInteraction( PROPINTER_PHYSGUN_FIRST_BREAK ) )
  402. {
  403. // Looks like it's best to break by having the object damage itself.
  404. CTakeDamageInfo info;
  405. info.SetDamage( m_iHealth );
  406. info.SetAttacker( this );
  407. info.SetInflictor( this );
  408. info.SetDamageType( DMG_GENERIC );
  409. Vector vecPosition;
  410. Vector vecVelocity;
  411. VPhysicsGetObject()->GetVelocity( &vecVelocity, NULL );
  412. VPhysicsGetObject()->GetPosition( &vecPosition, NULL );
  413. info.SetDamageForce( vecVelocity );
  414. info.SetDamagePosition( vecPosition );
  415. TakeDamage( info );
  416. return;
  417. }
  418. if( HasInteraction( PROPINTER_PHYSGUN_FIRST_PAINT ) )
  419. {
  420. IPhysicsObject *pObj = VPhysicsGetObject();
  421. Vector vecPos;
  422. pObj->GetPosition( &vecPos, NULL );
  423. Vector vecVelocity = pEvent->preVelocity[0];
  424. VectorNormalize(vecVelocity);
  425. trace_t tr;
  426. UTIL_TraceLine( vecPos, vecPos + (vecVelocity * 64), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
  427. if ( tr.m_pEnt )
  428. {
  429. #ifdef HL2_DLL
  430. // Don't paintsplat friendlies
  431. int iClassify = tr.m_pEnt->Classify();
  432. if ( iClassify != CLASS_PLAYER_ALLY_VITAL && iClassify != CLASS_PLAYER_ALLY &&
  433. iClassify != CLASS_CITIZEN_PASSIVE && iClassify != CLASS_CITIZEN_REBEL )
  434. #endif
  435. {
  436. switch( entindex() % 3 )
  437. {
  438. case 0:
  439. UTIL_DecalTrace( &tr, "PaintSplatBlue" );
  440. break;
  441. case 1:
  442. UTIL_DecalTrace( &tr, "PaintSplatGreen" );
  443. break;
  444. case 2:
  445. UTIL_DecalTrace( &tr, "PaintSplatPink" );
  446. break;
  447. }
  448. }
  449. }
  450. }
  451. if ( HasInteraction( PROPINTER_PHYSGUN_NOTIFY_CHILDREN ) )
  452. {
  453. CUtlVector<CBaseEntity *> children;
  454. GetAllChildren( this, children );
  455. for (int i = 0; i < children.Count(); i++ )
  456. {
  457. CBaseEntity *pent = children.Element( i );
  458. IParentPropInteraction *pPropInter = dynamic_cast<IParentPropInteraction *>( pent );
  459. if ( pPropInter )
  460. {
  461. pPropInter->OnParentCollisionInteraction( COLLISIONINTER_PARENT_FIRST_IMPACT, index, pEvent );
  462. }
  463. }
  464. }
  465. }
  466. void CBreakableProp::CheckRemoveRagdolls()
  467. {
  468. if ( HasSpawnFlags( SF_PHYSPROP_HAS_ATTACHED_RAGDOLLS ) )
  469. {
  470. DetachAttachedRagdollsForEntity( this );
  471. RemoveSpawnFlags( SF_PHYSPROP_HAS_ATTACHED_RAGDOLLS );
  472. }
  473. }
  474. //-----------------------------------------------------------------------------
  475. // Purpose: Handle special physgun interactions
  476. // Input : index -
  477. // *pEvent -
  478. //-----------------------------------------------------------------------------
  479. void CPhysicsProp::HandleAnyCollisionInteractions( int index, gamevcollisionevent_t *pEvent )
  480. {
  481. // If we're supposed to impale, and we've hit an NPC, impale it
  482. if ( HasInteraction( PROPINTER_PHYSGUN_FIRST_IMPALE ) )
  483. {
  484. Vector vel = pEvent->preVelocity[index];
  485. Vector forward;
  486. QAngle angImpaleForward;
  487. if ( GetPropDataAngles( "impale_forward", angImpaleForward ) )
  488. {
  489. Vector vecImpaleForward;
  490. AngleVectors( angImpaleForward, &vecImpaleForward );
  491. VectorRotate( vecImpaleForward, EntityToWorldTransform(), forward );
  492. }
  493. else
  494. {
  495. GetVectors( &forward, NULL, NULL );
  496. }
  497. float speed = DotProduct( forward, vel );
  498. if ( speed < 1000.0f )
  499. {
  500. // not going to stick, so remove any ragdolls we've got
  501. CheckRemoveRagdolls();
  502. return;
  503. }
  504. CBaseEntity *pHitEntity = pEvent->pEntities[!index];
  505. if ( pHitEntity->IsWorld() )
  506. {
  507. Vector normal;
  508. float sign = index ? -1.0f : 1.0f;
  509. pEvent->pInternalData->GetSurfaceNormal( normal );
  510. float dot = DotProduct( forward, normal );
  511. if ( (sign*dot) < DOT_45DEGREE )
  512. return;
  513. // Impale sticks to the wall if we hit end on
  514. HandleInteractionStick( index, pEvent );
  515. }
  516. else if ( pHitEntity->MyNPCPointer() )
  517. {
  518. CAI_BaseNPC *pNPC = pHitEntity->MyNPCPointer();
  519. IPhysicsObject *pObj = VPhysicsGetObject();
  520. // do not impale NPCs if the impaler is friendly
  521. CBasePlayer *pAttacker = HasPhysicsAttacker( 25.0f );
  522. if (pAttacker && pNPC->IRelationType( pAttacker ) == D_LI)
  523. {
  524. return;
  525. }
  526. Vector vecPos;
  527. pObj->GetPosition( &vecPos, NULL );
  528. // Find the bone for the hitbox we hit
  529. trace_t tr;
  530. UTIL_TraceLine( vecPos, vecPos + pEvent->preVelocity[index] * 1.5, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
  531. Vector vecImpalePos = tr.endpos;
  532. int iBone = -1;
  533. if ( tr.hitbox )
  534. {
  535. Vector vecBonePos;
  536. QAngle vecBoneAngles;
  537. iBone = pNPC->GetHitboxBone( tr.hitbox );
  538. pNPC->GetBonePosition( iBone, vecBonePos, vecBoneAngles );
  539. Teleport( &vecBonePos, NULL, NULL );
  540. vecImpalePos = vecBonePos;
  541. }
  542. // Kill the NPC and make an attached ragdoll
  543. pEvent->pInternalData->GetContactPoint( vecImpalePos );
  544. CBaseEntity *pRagdoll = CreateServerRagdollAttached( pNPC, vec3_origin, -1, COLLISION_GROUP_INTERACTIVE_DEBRIS, pObj, this, 0, vecImpalePos, iBone, vec3_origin );
  545. if ( pRagdoll )
  546. {
  547. Vector vecVelocity = pEvent->preVelocity[index] * pObj->GetMass();
  548. PhysCallbackImpulse( pObj, vecVelocity, vec3_origin );
  549. UTIL_Remove( pNPC );
  550. AddSpawnFlags( SF_PHYSPROP_HAS_ATTACHED_RAGDOLLS );
  551. }
  552. }
  553. }
  554. }
  555. void CBreakableProp::StickAtPosition( const Vector &stickPosition, const Vector &savePosition, const QAngle &saveAngles )
  556. {
  557. if ( !VPhysicsGetObject()->IsMotionEnabled() )
  558. return;
  559. EmitSound("Metal.SawbladeStick");
  560. Teleport( &stickPosition, NULL, NULL );
  561. SetEnableMotionPosition( savePosition, saveAngles ); // this uses hierarchy, so it must be set after teleport
  562. VPhysicsGetObject()->EnableMotion( false );
  563. AddSpawnFlags( SF_PHYSPROP_ENABLE_ON_PHYSCANNON );
  564. SetCollisionGroup( COLLISION_GROUP_DEBRIS );
  565. }
  566. //-----------------------------------------------------------------------------
  567. // Purpose:
  568. // Input : index -
  569. // *pEvent -
  570. //-----------------------------------------------------------------------------
  571. void CBreakableProp::HandleInteractionStick( int index, gamevcollisionevent_t *pEvent )
  572. {
  573. Vector vecDir = pEvent->preVelocity[ index ];
  574. float speed = VectorNormalize( vecDir );
  575. // Make sure the object is travelling fast enough to stick.
  576. if( speed > 1000.0f )
  577. {
  578. Vector position;
  579. QAngle angles;
  580. VPhysicsGetObject()->GetPosition( &position, &angles );
  581. Vector vecNormal;
  582. pEvent->pInternalData->GetSurfaceNormal( vecNormal );
  583. // we want the normal that points away from this object
  584. if ( index == 1 )
  585. {
  586. vecNormal *= -1.0f;
  587. }
  588. float flDot = DotProduct( vecDir, vecNormal );
  589. // Make sure the object isn't hitting the world at too sharp an angle.
  590. if( flDot > 0.3 )
  591. {
  592. // Finally, inhibit sticking in metal, grates, sky, or anything else that doesn't make a sound.
  593. const surfacedata_t *psurf = physprops->GetSurfaceData( pEvent->surfaceProps[!index] );
  594. if (psurf->game.material != CHAR_TEX_METAL && psurf->game.material != CHAR_TEX_GRATE && psurf->game.material != 'X' )
  595. {
  596. Vector savePosition = position;
  597. Vector vecEmbed = pEvent->preVelocity[ index ];
  598. VectorNormalize( vecEmbed );
  599. vecEmbed *= 8;
  600. position += vecEmbed;
  601. g_PostSimulationQueue.QueueCall( this, &CBreakableProp::StickAtPosition, position, savePosition, angles );
  602. }
  603. }
  604. }
  605. }
  606. //-----------------------------------------------------------------------------
  607. // Purpose: Turn on prop debugging mode
  608. //-----------------------------------------------------------------------------
  609. void CC_Prop_Debug( void )
  610. {
  611. // Toggle the prop debug bit on all props
  612. for ( CBaseEntity *pEntity = gEntList.FirstEnt(); pEntity != NULL; pEntity = gEntList.NextEnt(pEntity) )
  613. {
  614. CBaseProp *pProp = dynamic_cast<CBaseProp*>(pEntity);
  615. if ( pProp )
  616. {
  617. if ( pProp->m_debugOverlays & OVERLAY_PROP_DEBUG )
  618. {
  619. pProp->m_debugOverlays &= ~OVERLAY_PROP_DEBUG;
  620. }
  621. else
  622. {
  623. pProp->m_debugOverlays |= OVERLAY_PROP_DEBUG;
  624. }
  625. }
  626. }
  627. }
  628. static ConCommand prop_debug("prop_debug", CC_Prop_Debug, "Toggle prop debug mode. If on, props will show colorcoded bounding boxes. Red means ignore all damage. White means respond physically to damage but never break. Green maps health in the range of 100 down to 1.", FCVAR_CHEAT);
  629. //=============================================================================================================
  630. // BREAKABLE PROPS
  631. //=============================================================================================================
  632. IMPLEMENT_SERVERCLASS_ST(CBreakableProp, DT_BreakableProp)
  633. END_SEND_TABLE()
  634. BEGIN_DATADESC( CBreakableProp )
  635. DEFINE_KEYFIELD( m_explodeDamage, FIELD_FLOAT, "ExplodeDamage"),
  636. DEFINE_KEYFIELD( m_explodeRadius, FIELD_FLOAT, "ExplodeRadius"),
  637. DEFINE_KEYFIELD( m_iMinHealthDmg, FIELD_INTEGER, "minhealthdmg" ),
  638. DEFINE_FIELD( m_createTick, FIELD_INTEGER ),
  639. DEFINE_FIELD( m_hBreaker, FIELD_EHANDLE ),
  640. DEFINE_KEYFIELD( m_PerformanceMode, FIELD_INTEGER, "PerformanceMode" ),
  641. DEFINE_KEYFIELD( m_iszBreakModelMessage, FIELD_STRING, "BreakModelMessage" ),
  642. DEFINE_FIELD( m_flDmgModBullet, FIELD_FLOAT ),
  643. DEFINE_FIELD( m_flDmgModClub, FIELD_FLOAT ),
  644. DEFINE_FIELD( m_flDmgModExplosive, FIELD_FLOAT ),
  645. DEFINE_FIELD( m_iszPhysicsDamageTableName, FIELD_STRING ),
  646. DEFINE_FIELD( m_iszBreakableModel, FIELD_STRING ),
  647. DEFINE_FIELD( m_iBreakableSkin, FIELD_INTEGER ),
  648. DEFINE_FIELD( m_iBreakableCount, FIELD_INTEGER ),
  649. DEFINE_FIELD( m_iMaxBreakableSize, FIELD_INTEGER ),
  650. DEFINE_FIELD( m_iszBasePropData, FIELD_STRING ),
  651. DEFINE_FIELD( m_iInteractions, FIELD_INTEGER ),
  652. DEFINE_FIELD( m_iNumBreakableChunks, FIELD_INTEGER ),
  653. DEFINE_FIELD( m_nPhysgunState, FIELD_CHARACTER ),
  654. DEFINE_KEYFIELD( m_iszPuntSound, FIELD_STRING, "puntsound" ),
  655. DEFINE_KEYFIELD( m_flPressureDelay, FIELD_FLOAT, "PressureDelay" ),
  656. DEFINE_FIELD( m_preferredCarryAngles, FIELD_VECTOR ),
  657. DEFINE_FIELD( m_flDefaultFadeScale, FIELD_FLOAT ),
  658. DEFINE_FIELD( m_bUsePuntSound, FIELD_BOOLEAN ),
  659. // DEFINE_FIELD( m_mpBreakMode, mp_break_t ),
  660. // Inputs
  661. DEFINE_INPUTFUNC( FIELD_VOID, "Break", InputBreak ),
  662. DEFINE_INPUTFUNC( FIELD_INTEGER, "SetHealth", InputSetHealth ),
  663. DEFINE_INPUTFUNC( FIELD_INTEGER, "AddHealth", InputAddHealth ),
  664. DEFINE_INPUTFUNC( FIELD_INTEGER, "RemoveHealth", InputRemoveHealth ),
  665. DEFINE_INPUT( m_impactEnergyScale, FIELD_FLOAT, "physdamagescale" ),
  666. DEFINE_INPUTFUNC( FIELD_VOID, "EnablePhyscannonPickup", InputEnablePhyscannonPickup ),
  667. DEFINE_INPUTFUNC( FIELD_VOID, "DisablePhyscannonPickup", InputDisablePhyscannonPickup ),
  668. DEFINE_INPUTFUNC( FIELD_VOID, "EnablePuntSound", InputEnablePuntSound ),
  669. DEFINE_INPUTFUNC( FIELD_VOID, "DisablePuntSound", InputDisablePuntSound ),
  670. // Outputs
  671. DEFINE_OUTPUT( m_OnBreak, "OnBreak" ),
  672. DEFINE_OUTPUT( m_OnHealthChanged, "OnHealthChanged" ),
  673. DEFINE_OUTPUT( m_OnTakeDamage, "OnTakeDamage" ),
  674. DEFINE_OUTPUT( m_OnPhysCannonDetach, "OnPhysCannonDetach" ),
  675. DEFINE_OUTPUT( m_OnPhysCannonAnimatePreStarted, "OnPhysCannonAnimatePreStarted" ),
  676. DEFINE_OUTPUT( m_OnPhysCannonAnimatePullStarted, "OnPhysCannonAnimatePullStarted" ),
  677. DEFINE_OUTPUT( m_OnPhysCannonAnimatePostStarted, "OnPhysCannonAnimatePostStarted" ),
  678. DEFINE_OUTPUT( m_OnPhysCannonPullAnimFinished, "OnPhysCannonPullAnimFinished" ),
  679. // Function Pointers
  680. DEFINE_THINKFUNC( BreakThink ),
  681. DEFINE_THINKFUNC( AnimateThink ),
  682. DEFINE_THINKFUNC( RampToDefaultFadeScale ),
  683. DEFINE_ENTITYFUNC( BreakablePropTouch ),
  684. // Physics Influence
  685. DEFINE_FIELD( m_hPhysicsAttacker, FIELD_EHANDLE ),
  686. DEFINE_FIELD( m_flLastPhysicsInfluenceTime, FIELD_TIME ),
  687. DEFINE_FIELD( m_bOriginalBlockLOS, FIELD_BOOLEAN ),
  688. DEFINE_FIELD( m_bBlockLOSSetByPropData, FIELD_BOOLEAN ),
  689. DEFINE_FIELD( m_bIsWalkableSetByPropData, FIELD_BOOLEAN ),
  690. // Damage
  691. DEFINE_FIELD( m_hLastAttacker, FIELD_EHANDLE ),
  692. DEFINE_FIELD( m_hFlareEnt, FIELD_EHANDLE ),
  693. END_DATADESC()
  694. //-----------------------------------------------------------------------------
  695. // Constructor:
  696. //-----------------------------------------------------------------------------
  697. CBreakableProp::CBreakableProp()
  698. {
  699. m_fadeMinDist = -1;
  700. m_fadeMaxDist = 0;
  701. m_flFadeScale = 1;
  702. m_flDefaultFadeScale = 1;
  703. m_mpBreakMode = MULTIPLAYER_BREAK_DEFAULT;
  704. // This defaults to on. Most times mapmakers won't specify a punt sound to play.
  705. m_bUsePuntSound = true;
  706. }
  707. //-----------------------------------------------------------------------------
  708. // Purpose:
  709. //-----------------------------------------------------------------------------
  710. void CBreakableProp::Spawn()
  711. {
  712. // Starts out as the default fade scale value
  713. m_flDefaultFadeScale = m_flFadeScale;
  714. // Initialize damage modifiers. Must be done before baseclass spawn.
  715. m_flDmgModBullet = 1.0;
  716. m_flDmgModClub = 1.0;
  717. m_flDmgModExplosive = 1.0;
  718. //jmd: I am guessing that the call to Spawn will set any flags that should be set anyway; this
  719. //clears flags we don't want (specifically the FL_ONFIRE for explosive barrels in HL2MP)]
  720. #ifdef HL2MP
  721. ClearFlags();
  722. #endif
  723. BaseClass::Spawn();
  724. if ( IsMarkedForDeletion() )
  725. return;
  726. CStudioHdr *pStudioHdr = GetModelPtr( );
  727. if ( pStudioHdr->flags() & STUDIOHDR_FLAGS_NO_FORCED_FADE )
  728. {
  729. DisableAutoFade();
  730. }
  731. else
  732. {
  733. m_flFadeScale = m_flDefaultFadeScale;
  734. }
  735. // If we have no custom breakable chunks, see if we're breaking into generic ones
  736. if ( !m_iNumBreakableChunks )
  737. {
  738. IBreakableWithPropData *pBreakableInterface = assert_cast<IBreakableWithPropData*>(this);
  739. if ( pBreakableInterface->GetBreakableModel() != NULL_STRING && pBreakableInterface->GetBreakableCount() )
  740. {
  741. m_iNumBreakableChunks = pBreakableInterface->GetBreakableCount();
  742. }
  743. }
  744. // Setup takedamage based upon the health we parsed earlier, and our interactions
  745. if ( ( m_iHealth == 0 ) ||
  746. ( !m_iNumBreakableChunks &&
  747. !HasInteraction( PROPINTER_PHYSGUN_BREAK_EXPLODE ) &&
  748. !HasInteraction( PROPINTER_PHYSGUN_FIRST_BREAK ) &&
  749. !HasInteraction( PROPINTER_FIRE_FLAMMABLE ) &&
  750. !HasInteraction( PROPINTER_FIRE_IGNITE_HALFHEALTH ) &&
  751. !HasInteraction( PROPINTER_FIRE_EXPLOSIVE_RESIST ) ) )
  752. {
  753. m_iHealth = 0;
  754. m_takedamage = DAMAGE_EVENTS_ONLY;
  755. }
  756. else
  757. {
  758. m_takedamage = DAMAGE_YES;
  759. if( g_pGameRules->GetAutoAimMode() == AUTOAIM_ON_CONSOLE )
  760. {
  761. if ( HasInteraction( PROPINTER_PHYSGUN_BREAK_EXPLODE ) ||
  762. HasInteraction( PROPINTER_FIRE_IGNITE_HALFHEALTH ) )
  763. {
  764. // Exploding barrels, exploding gas cans
  765. AddFlag( FL_AIMTARGET );
  766. }
  767. }
  768. }
  769. m_iMaxHealth = ( m_iHealth > 0 ) ? m_iHealth : 1;
  770. m_createTick = gpGlobals->tickcount;
  771. if ( m_impactEnergyScale == 0 )
  772. {
  773. m_impactEnergyScale = 0.1f;
  774. }
  775. m_preferredCarryAngles = QAngle( -5, 0, 0 );
  776. // The presence of this activity causes us to have to detach it before it can be grabbed.
  777. if ( SelectWeightedSequence( ACT_PHYSCANNON_ANIMATE ) != ACTIVITY_NOT_AVAILABLE )
  778. {
  779. m_nPhysgunState = PHYSGUN_ANIMATE_ON_PULL;
  780. }
  781. else if ( SelectWeightedSequence( ACT_PHYSCANNON_DETACH ) != ACTIVITY_NOT_AVAILABLE )
  782. {
  783. m_nPhysgunState = PHYSGUN_MUST_BE_DETACHED;
  784. }
  785. else
  786. {
  787. m_nPhysgunState = PHYSGUN_CAN_BE_GRABBED;
  788. }
  789. m_hLastAttacker = NULL;
  790. m_hBreaker = NULL;
  791. SetTouch( &CBreakableProp::BreakablePropTouch );
  792. }
  793. //-----------------------------------------------------------------------------
  794. // Disable auto fading under dx7 or when level fades are specified
  795. //-----------------------------------------------------------------------------
  796. void CBreakableProp::DisableAutoFade()
  797. {
  798. m_flFadeScale = 0;
  799. m_flDefaultFadeScale = 0;
  800. }
  801. //-----------------------------------------------------------------------------
  802. // Copy fade from another breakable.
  803. //-----------------------------------------------------------------------------
  804. void CBreakableProp::CopyFadeFrom( CBreakableProp *pSource )
  805. {
  806. m_flDefaultFadeScale = pSource->m_flDefaultFadeScale;
  807. m_flFadeScale = pSource->m_flFadeScale;
  808. if ( m_flFadeScale != m_flDefaultFadeScale )
  809. {
  810. float flNextThink = pSource->GetNextThink( s_pFadeScaleThink );
  811. if ( flNextThink < gpGlobals->curtime + TICK_INTERVAL )
  812. {
  813. flNextThink = gpGlobals->curtime + TICK_INTERVAL;
  814. }
  815. SetContextThink( &CBreakableProp::RampToDefaultFadeScale, flNextThink, s_pFadeScaleThink );
  816. }
  817. }
  818. //-----------------------------------------------------------------------------
  819. // Make physcannonable, or not
  820. //-----------------------------------------------------------------------------
  821. void CBreakableProp::InputEnablePhyscannonPickup( inputdata_t &inputdata )
  822. {
  823. RemoveEFlags( EFL_NO_PHYSCANNON_INTERACTION );
  824. }
  825. void CBreakableProp::InputDisablePhyscannonPickup( inputdata_t &inputdata )
  826. {
  827. AddEFlags( EFL_NO_PHYSCANNON_INTERACTION );
  828. }
  829. //-----------------------------------------------------------------------------
  830. // Purpose:
  831. // Input : *pOther -
  832. //-----------------------------------------------------------------------------
  833. void CBreakableProp::BreakablePropTouch( CBaseEntity *pOther )
  834. {
  835. if ( HasSpawnFlags( SF_PHYSPROP_TOUCH ) )
  836. {
  837. // can be broken when run into
  838. float flDamage = pOther->GetSmoothedVelocity().Length() * 0.01;
  839. if ( flDamage >= m_iHealth )
  840. {
  841. // Make sure we can take damage
  842. m_takedamage = DAMAGE_YES;
  843. OnTakeDamage( CTakeDamageInfo( pOther, pOther, flDamage, DMG_CRUSH ) );
  844. // do a little damage to player if we broke glass or computer
  845. CTakeDamageInfo info( pOther, pOther, flDamage/4, DMG_SLASH );
  846. CalculateMeleeDamageForce( &info, (pOther->GetAbsOrigin() - GetAbsOrigin()), GetAbsOrigin() );
  847. pOther->TakeDamage( info );
  848. }
  849. }
  850. if ( HasSpawnFlags( SF_PHYSPROP_PRESSURE ) && pOther->GetGroundEntity() == this )
  851. {
  852. // can be broken when stood upon
  853. // play creaking sound here.
  854. // DamageSound();
  855. m_hBreaker = pOther;
  856. if ( m_pfnThink != (void (CBaseEntity::*)())&CBreakableProp::BreakThink )
  857. {
  858. SetThink( &CBreakableProp::BreakThink );
  859. //SetTouch( NULL );
  860. // Add optional delay
  861. SetNextThink( gpGlobals->curtime + m_flPressureDelay );
  862. }
  863. }
  864. #ifdef HL2_EPISODIC
  865. if ( m_hFlareEnt )
  866. {
  867. CAI_BaseNPC *pNPC = pOther->MyNPCPointer();
  868. if ( pNPC && pNPC->AllowedToIgnite() && pNPC->IsOnFire() == false )
  869. {
  870. pNPC->Ignite( 25.0f );
  871. KillFlare( this, m_hFlareEnt, PROP_FLARE_IGNITE_SUBSTRACT );
  872. IGameEvent *event = gameeventmanager->CreateEvent( "flare_ignite_npc" );
  873. if ( event )
  874. {
  875. event->SetInt( "entindex", pNPC->entindex() );
  876. gameeventmanager->FireEvent( event );
  877. }
  878. }
  879. }
  880. #endif
  881. }
  882. //-----------------------------------------------------------------------------
  883. // UNDONE: Time stamp the object's creation so that an explosion or something doesn't break the parent object
  884. // and then break the children who spawn afterward ?
  885. // Explosions should use entities in box before they start to do damage. Make sure nothing traverses the list
  886. // in a way that would hose this.
  887. int CBreakableProp::OnTakeDamage( const CTakeDamageInfo &inputInfo )
  888. {
  889. CTakeDamageInfo info = inputInfo;
  890. // If attacker can't do at least the min required damage to us, don't take any damage from them
  891. if ( info.GetDamage() < m_iMinHealthDmg )
  892. return 0;
  893. if (!PassesDamageFilter( info ))
  894. {
  895. return 1;
  896. }
  897. if( info.GetAttacker() && info.GetAttacker()->MyCombatCharacterPointer() )
  898. {
  899. m_hLastAttacker.Set( info.GetAttacker() );
  900. }
  901. float flPropDamage = GetBreakableDamage( info, assert_cast<IBreakableWithPropData*>(this) );
  902. info.SetDamage( flPropDamage );
  903. // UNDONE: Do this?
  904. #if 0
  905. // Make a shard noise each time func breakable is hit.
  906. // Don't play shard noise if being burned.
  907. // Don't play shard noise if cbreakable actually died.
  908. if ( ( bitsDamageType & DMG_BURN ) == false )
  909. {
  910. DamageSound();
  911. }
  912. #endif
  913. // don't take damage on the same frame you were created
  914. // (avoids a set of explosions progressively vaporizing a compound breakable)
  915. if ( m_createTick == (unsigned int)gpGlobals->tickcount )
  916. {
  917. int saveFlags = m_takedamage;
  918. m_takedamage = DAMAGE_EVENTS_ONLY;
  919. int ret = BaseClass::OnTakeDamage( info );
  920. m_takedamage = saveFlags;
  921. return ret;
  922. }
  923. // Ignore fire damage from other flames if I'm already on fire.
  924. // (i.e., only let the flames attached to me damage me)
  925. if( IsOnFire() && (inputInfo.GetDamageType() & DMG_BURN) && !(inputInfo.GetDamageType() & DMG_DIRECT) )
  926. {
  927. return 0;
  928. }
  929. bool bDeadly = info.GetDamage() >= m_iHealth;
  930. if( bDeadly && (info.GetDamageType() & DMG_BLAST) && HasInteraction( PROPINTER_FIRE_EXPLOSIVE_RESIST ) && info.GetInflictor() )
  931. {
  932. // This explosion would kill me, but I have a special interaction with explosions.
  933. float flDist = ( WorldSpaceCenter() - info.GetInflictor()->WorldSpaceCenter() ).Length();
  934. // I'm going to burn for a bit instead of exploding right now.
  935. float flBurnTime;
  936. if( flDist >= PROP_EXPLOSION_IGNITE_RADIUS )
  937. {
  938. // I'm far from the blast. Ignite and burn for several seconds.
  939. const float MAX_BLAST_DIST = 256.0f;
  940. // Just clamp distance.
  941. if( flDist > MAX_BLAST_DIST )
  942. flDist = MAX_BLAST_DIST;
  943. float flFactor;
  944. flFactor = flDist / MAX_BLAST_DIST;
  945. const float MAX_BURN_TIME = 5.0f;
  946. flBurnTime = MAX( 0.5, MAX_BURN_TIME * flFactor );
  947. flBurnTime += random->RandomFloat( 0, 0.5 );
  948. }
  949. else
  950. {
  951. // Very near the explosion. explode almost immediately.
  952. flBurnTime = random->RandomFloat( 0.1, 0.2 );
  953. }
  954. // Change my health so that I burn for flBurnTime seconds.
  955. float flIdealHealth = MIN( m_iHealth, FLAME_DIRECT_DAMAGE_PER_SEC * flBurnTime );
  956. float flIdealDamage = m_iHealth - flIdealHealth;
  957. // Scale the damage to do ideal damage.
  958. info.ScaleDamage( flIdealDamage / info.GetDamage() );
  959. // Re-evaluate the deadly
  960. bDeadly = info.GetDamage() >= m_iHealth;
  961. }
  962. if( !bDeadly && (info.GetDamageType() & DMG_BLAST) )
  963. {
  964. Ignite( random->RandomFloat( 10, 15 ), false );
  965. }
  966. else if( !bDeadly && (info.GetDamageType() & DMG_BURN) )
  967. {
  968. // Ignite if burned, and flammable (the Ignite() function takes care of all of this).
  969. Ignite( random->RandomFloat( 10, 15 ), false );
  970. }
  971. else if( !bDeadly && (info.GetDamageType() & DMG_BULLET) )
  972. {
  973. if( HasInteraction( PROPINTER_FIRE_IGNITE_HALFHEALTH ) )
  974. {
  975. if( (m_iHealth - info.GetDamage()) <= m_iMaxHealth / 2 && !IsOnFire() )
  976. {
  977. // Bump back up to full health so it burns longer. Magically getting health back isn't
  978. // a big problem because if this item takes damage again whilst burning, it will break.
  979. m_iHealth = m_iMaxHealth;
  980. Ignite( random->RandomFloat( 10, 15 ), false );
  981. }
  982. else if( IsOnFire() )
  983. {
  984. // Explode right now!
  985. info.ScaleDamage( m_iHealth / info.GetDamage() );
  986. }
  987. }
  988. }
  989. int ret = BaseClass::OnTakeDamage( info );
  990. // Output the new health as a percentage of max health [0..1]
  991. float flRatio = clamp( (float)m_iHealth / (float)m_iMaxHealth, 0.f, 1.f );
  992. m_OnHealthChanged.Set( flRatio, info.GetAttacker(), this );
  993. m_OnTakeDamage.FireOutput( info.GetAttacker(), this );
  994. return ret;
  995. }
  996. //-----------------------------------------------------------------------------
  997. // Purpose:
  998. //-----------------------------------------------------------------------------
  999. void CBreakableProp::Event_Killed( const CTakeDamageInfo &info )
  1000. {
  1001. IPhysicsObject *pPhysics = VPhysicsGetObject();
  1002. if ( pPhysics && !pPhysics->IsMoveable() )
  1003. {
  1004. pPhysics->EnableMotion( true );
  1005. VPhysicsTakeDamage( info );
  1006. }
  1007. Break( info.GetInflictor(), info );
  1008. BaseClass::Event_Killed( info );
  1009. }
  1010. //-----------------------------------------------------------------------------
  1011. // Purpose: Input handler for breaking the breakable immediately.
  1012. //-----------------------------------------------------------------------------
  1013. void CBreakableProp::InputBreak( inputdata_t &inputdata )
  1014. {
  1015. CTakeDamageInfo info;
  1016. info.SetAttacker( this );
  1017. Break( inputdata.pActivator, info );
  1018. }
  1019. //-----------------------------------------------------------------------------
  1020. // Purpose: Input handler for adding to the breakable's health.
  1021. // Input : Integer health points to add.
  1022. //-----------------------------------------------------------------------------
  1023. void CBreakableProp::InputAddHealth( inputdata_t &inputdata )
  1024. {
  1025. UpdateHealth( m_iHealth + inputdata.value.Int(), inputdata.pActivator );
  1026. }
  1027. //-----------------------------------------------------------------------------
  1028. // Purpose: Input handler for removing health from the breakable.
  1029. // Input : Integer health points to remove.
  1030. //-----------------------------------------------------------------------------
  1031. void CBreakableProp::InputRemoveHealth( inputdata_t &inputdata )
  1032. {
  1033. UpdateHealth( m_iHealth - inputdata.value.Int(), inputdata.pActivator );
  1034. }
  1035. //-----------------------------------------------------------------------------
  1036. // Purpose: Input handler for setting the breakable's health.
  1037. //-----------------------------------------------------------------------------
  1038. void CBreakableProp::InputSetHealth( inputdata_t &inputdata )
  1039. {
  1040. UpdateHealth( inputdata.value.Int(), inputdata.pActivator );
  1041. }
  1042. //-----------------------------------------------------------------------------
  1043. // Purpose: Choke point for changes to breakable health. Ensures outputs are fired.
  1044. // Input : iNewHealth -
  1045. // pActivator -
  1046. // Output : Returns true if the breakable survived, false if it died (broke).
  1047. //-----------------------------------------------------------------------------
  1048. bool CBreakableProp::UpdateHealth( int iNewHealth, CBaseEntity *pActivator )
  1049. {
  1050. if ( iNewHealth != m_iHealth )
  1051. {
  1052. m_iHealth = iNewHealth;
  1053. if ( m_iMaxHealth == 0 )
  1054. {
  1055. Assert( false );
  1056. m_iMaxHealth = 1;
  1057. }
  1058. // Output the new health as a percentage of max health [0..1]
  1059. float flRatio = clamp( (float)m_iHealth / (float)m_iMaxHealth, 0.f, 1.f );
  1060. m_OnHealthChanged.Set( flRatio, pActivator, this );
  1061. if ( m_iHealth <= 0 )
  1062. {
  1063. CTakeDamageInfo info;
  1064. info.SetAttacker( this );
  1065. Break( pActivator, info );
  1066. return false;
  1067. }
  1068. }
  1069. return true;
  1070. }
  1071. //-----------------------------------------------------------------------------
  1072. // Purpose: Advance a ripped-off-animation frame
  1073. //-----------------------------------------------------------------------------
  1074. bool CBreakableProp::OnAttemptPhysGunPickup( CBasePlayer *pPhysGunUser, PhysGunPickup_t reason )
  1075. {
  1076. if ( m_nPhysgunState == PHYSGUN_CAN_BE_GRABBED )
  1077. return true;
  1078. if ( m_nPhysgunState == PHYSGUN_ANIMATE_FINISHED )
  1079. return false;
  1080. if ( m_nPhysgunState == PHYSGUN_MUST_BE_DETACHED )
  1081. {
  1082. // A punt advances
  1083. ResetSequence( SelectWeightedSequence( ACT_PHYSCANNON_DETACH ) );
  1084. SetPlaybackRate( 0.0f );
  1085. ResetClientsideFrame();
  1086. m_nPhysgunState = PHYSGUN_IS_DETACHING;
  1087. return false;
  1088. }
  1089. if ( m_nPhysgunState == PHYSGUN_ANIMATE_ON_PULL )
  1090. {
  1091. // Animation-requiring detachments ignore punts
  1092. if ( reason == PUNTED_BY_CANNON )
  1093. return false;
  1094. // Do we have a pre sequence?
  1095. int iSequence = SelectWeightedSequence( ACT_PHYSCANNON_ANIMATE_PRE );
  1096. if ( iSequence != ACTIVITY_NOT_AVAILABLE )
  1097. {
  1098. m_nPhysgunState = PHYSGUN_ANIMATE_IS_PRE_ANIMATING;
  1099. SetContextThink( &CBreakableProp::AnimateThink, gpGlobals->curtime + 0.1, s_pPropAnimateThink );
  1100. m_OnPhysCannonAnimatePreStarted.FireOutput( NULL,this );
  1101. }
  1102. else
  1103. {
  1104. // Go straight to the animate sequence
  1105. iSequence = SelectWeightedSequence( ACT_PHYSCANNON_ANIMATE );
  1106. m_nPhysgunState = PHYSGUN_ANIMATE_IS_ANIMATING;
  1107. m_OnPhysCannonAnimatePullStarted.FireOutput( NULL,this );
  1108. }
  1109. ResetSequence( iSequence );
  1110. SetPlaybackRate( 1.0f );
  1111. ResetClientsideFrame();
  1112. }
  1113. // If we're running PRE or POST ANIMATE sequences, wait for them to be done
  1114. if ( m_nPhysgunState == PHYSGUN_ANIMATE_IS_PRE_ANIMATING ||
  1115. m_nPhysgunState == PHYSGUN_ANIMATE_IS_POST_ANIMATING )
  1116. return false;
  1117. if ( m_nPhysgunState == PHYSGUN_ANIMATE_IS_ANIMATING )
  1118. {
  1119. // Animation-requiring detachments ignore punts
  1120. if ( reason == PUNTED_BY_CANNON )
  1121. return false;
  1122. StudioFrameAdvanceManual( gpGlobals->frametime );
  1123. DispatchAnimEvents( this );
  1124. if ( IsActivityFinished() )
  1125. {
  1126. int iSequence = SelectWeightedSequence( ACT_PHYSCANNON_ANIMATE_POST );
  1127. if ( iSequence != ACTIVITY_NOT_AVAILABLE )
  1128. {
  1129. m_nPhysgunState = PHYSGUN_ANIMATE_IS_POST_ANIMATING;
  1130. SetContextThink( &CBreakableProp::AnimateThink, gpGlobals->curtime + 0.1, s_pPropAnimateThink );
  1131. ResetSequence( iSequence );
  1132. SetPlaybackRate( 1.0f );
  1133. ResetClientsideFrame();
  1134. m_OnPhysCannonAnimatePostStarted.FireOutput( NULL,this );
  1135. }
  1136. else
  1137. {
  1138. m_nPhysgunState = PHYSGUN_ANIMATE_FINISHED;
  1139. m_OnPhysCannonPullAnimFinished.FireOutput( NULL,this );
  1140. }
  1141. }
  1142. }
  1143. else
  1144. {
  1145. // Here, we're grabbing it. If we try to punt it, advance frames by quite a bit.
  1146. StudioFrameAdvanceManual( (reason == PICKED_UP_BY_CANNON) ? gpGlobals->frametime : 0.5f );
  1147. ResetClientsideFrame();
  1148. DispatchAnimEvents( this );
  1149. if ( IsActivityFinished() )
  1150. {
  1151. // We're done, reset the playback rate.
  1152. SetPlaybackRate( 1.0f );
  1153. m_nPhysgunState = PHYSGUN_CAN_BE_GRABBED;
  1154. m_OnPhysCannonDetach.FireOutput( NULL,this );
  1155. }
  1156. }
  1157. return false;
  1158. }
  1159. //-----------------------------------------------------------------------------
  1160. // Physics Attacker
  1161. //-----------------------------------------------------------------------------
  1162. void CBreakableProp::AnimateThink( void )
  1163. {
  1164. if ( m_nPhysgunState == PHYSGUN_ANIMATE_IS_PRE_ANIMATING || m_nPhysgunState == PHYSGUN_ANIMATE_IS_POST_ANIMATING )
  1165. {
  1166. StudioFrameAdvanceManual( 0.1 );
  1167. DispatchAnimEvents( this );
  1168. SetNextThink( gpGlobals->curtime + 0.1, s_pPropAnimateThink );
  1169. if ( IsActivityFinished() )
  1170. {
  1171. if ( m_nPhysgunState == PHYSGUN_ANIMATE_IS_PRE_ANIMATING )
  1172. {
  1173. // Start the animate sequence
  1174. m_nPhysgunState = PHYSGUN_ANIMATE_IS_ANIMATING;
  1175. ResetSequence( SelectWeightedSequence( ACT_PHYSCANNON_ANIMATE ) );
  1176. SetPlaybackRate( 1.0f );
  1177. ResetClientsideFrame();
  1178. m_OnPhysCannonAnimatePullStarted.FireOutput( NULL,this );
  1179. }
  1180. else
  1181. {
  1182. m_nPhysgunState = PHYSGUN_ANIMATE_FINISHED;
  1183. m_OnPhysCannonPullAnimFinished.FireOutput( NULL,this );
  1184. }
  1185. SetContextThink( NULL, 0, s_pPropAnimateThink );
  1186. }
  1187. }
  1188. }
  1189. //-----------------------------------------------------------------------------
  1190. // Physics Attacker
  1191. //-----------------------------------------------------------------------------
  1192. void CBreakableProp::SetPhysicsAttacker( CBasePlayer *pEntity, float flTime )
  1193. {
  1194. m_hPhysicsAttacker = pEntity;
  1195. m_flLastPhysicsInfluenceTime = flTime;
  1196. }
  1197. //-----------------------------------------------------------------------------
  1198. // Prevents fade scale from happening
  1199. //-----------------------------------------------------------------------------
  1200. void CBreakableProp::ForceFadeScaleToAlwaysVisible()
  1201. {
  1202. m_flFadeScale = 0.0f;
  1203. SetContextThink( NULL, gpGlobals->curtime, s_pFadeScaleThink );
  1204. }
  1205. void CBreakableProp::RampToDefaultFadeScale()
  1206. {
  1207. m_flFadeScale += m_flDefaultFadeScale * TICK_INTERVAL / 2.0f;
  1208. if ( m_flFadeScale >= m_flDefaultFadeScale )
  1209. {
  1210. m_flFadeScale = m_flDefaultFadeScale;
  1211. SetContextThink( NULL, gpGlobals->curtime, s_pFadeScaleThink );
  1212. }
  1213. else
  1214. {
  1215. SetContextThink( &CBreakableProp::RampToDefaultFadeScale, gpGlobals->curtime + TICK_INTERVAL, s_pFadeScaleThink );
  1216. }
  1217. }
  1218. //-----------------------------------------------------------------------------
  1219. // Purpose: Keep track of physgun influence
  1220. //-----------------------------------------------------------------------------
  1221. void CBreakableProp::OnPhysGunPickup( CBasePlayer *pPhysGunUser, PhysGunPickup_t reason )
  1222. {
  1223. // Make sure held objects are always visible
  1224. if ( reason == PICKED_UP_BY_CANNON )
  1225. {
  1226. ForceFadeScaleToAlwaysVisible();
  1227. }
  1228. else
  1229. {
  1230. SetContextThink( &CBreakableProp::RampToDefaultFadeScale, gpGlobals->curtime + 2.0f, s_pFadeScaleThink );
  1231. }
  1232. if( reason == PUNTED_BY_CANNON )
  1233. {
  1234. PlayPuntSound();
  1235. }
  1236. if ( IsX360() )
  1237. {
  1238. if( reason != PUNTED_BY_CANNON && (pPhysGunUser->m_nNumCrateHudHints < NUM_SUPPLY_CRATE_HUD_HINTS) )
  1239. {
  1240. if( FClassnameIs( this, "item_item_crate") )
  1241. {
  1242. pPhysGunUser->m_nNumCrateHudHints++;
  1243. UTIL_HudHintText( pPhysGunUser, "#Valve_Hint_Hold_ItemCrate" );
  1244. }
  1245. }
  1246. }
  1247. SetPhysicsAttacker( pPhysGunUser, gpGlobals->curtime );
  1248. // Store original BlockLOS, and disable BlockLOS
  1249. m_bOriginalBlockLOS = BlocksLOS();
  1250. SetBlocksLOS( false );
  1251. #ifdef HL2_EPISODIC
  1252. if ( HasInteraction( PROPINTER_PHYSGUN_CREATE_FLARE ) )
  1253. {
  1254. CreateFlare( PROP_FLARE_LIFETIME );
  1255. }
  1256. #endif
  1257. }
  1258. #ifdef HL2_EPISODIC
  1259. //-----------------------------------------------------------------------------
  1260. // Purpose: Create a flare at the attachment point
  1261. //-----------------------------------------------------------------------------
  1262. void CBreakableProp::CreateFlare( float flLifetime )
  1263. {
  1264. // Create the flare
  1265. CBaseEntity *pFlare = ::CreateFlare( GetAbsOrigin(), GetAbsAngles(), this, flLifetime );
  1266. if ( pFlare )
  1267. {
  1268. int iAttachment = LookupAttachment( "fuse" );
  1269. Vector vOrigin;
  1270. GetAttachment( iAttachment, vOrigin );
  1271. pFlare->SetMoveType( MOVETYPE_NONE );
  1272. pFlare->SetSolid( SOLID_NONE );
  1273. pFlare->SetRenderMode( kRenderTransAlpha );
  1274. pFlare->SetRenderColorA( 1 );
  1275. pFlare->SetLocalOrigin( vOrigin );
  1276. pFlare->SetParent( this, iAttachment );
  1277. RemoveInteraction( PROPINTER_PHYSGUN_CREATE_FLARE );
  1278. m_hFlareEnt = pFlare;
  1279. SetThink( &CBreakable::SUB_FadeOut );
  1280. SetNextThink( gpGlobals->curtime + flLifetime + 5.0f );
  1281. m_nSkin = 1;
  1282. AddEntityToDarknessCheck( pFlare );
  1283. AddEffects( EF_NOSHADOW );
  1284. }
  1285. }
  1286. #endif // HL2_EPISODIC
  1287. //-----------------------------------------------------------------------------
  1288. // Purpose:
  1289. //-----------------------------------------------------------------------------
  1290. void CBreakableProp::OnPhysGunDrop( CBasePlayer *pPhysGunUser, PhysGunDrop_t Reason )
  1291. {
  1292. SetContextThink( &CBreakableProp::RampToDefaultFadeScale, gpGlobals->curtime + 2.0f, s_pFadeScaleThink );
  1293. SetPhysicsAttacker( pPhysGunUser, gpGlobals->curtime );
  1294. if( (int)Reason == (int)PUNTED_BY_CANNON )
  1295. {
  1296. PlayPuntSound();
  1297. }
  1298. // Restore original BlockLOS
  1299. SetBlocksLOS( m_bOriginalBlockLOS );
  1300. }
  1301. //-----------------------------------------------------------------------------
  1302. //-----------------------------------------------------------------------------
  1303. AngularImpulse CBreakableProp::PhysGunLaunchAngularImpulse()
  1304. {
  1305. if( HasInteraction( PROPINTER_PHYSGUN_LAUNCH_SPIN_NONE ) || HasInteraction( PROPINTER_PHYSGUN_LAUNCH_SPIN_Z ) )
  1306. {
  1307. // Don't add in random angular impulse if this object is supposed to spin in a specific way.
  1308. AngularImpulse ang( 0, 0, 0 );
  1309. return ang;
  1310. }
  1311. return CDefaultPlayerPickupVPhysics::PhysGunLaunchAngularImpulse();
  1312. }
  1313. //-----------------------------------------------------------------------------
  1314. //-----------------------------------------------------------------------------
  1315. CBasePlayer *CBreakableProp::HasPhysicsAttacker( float dt )
  1316. {
  1317. if (gpGlobals->curtime - dt <= m_flLastPhysicsInfluenceTime)
  1318. {
  1319. return m_hPhysicsAttacker;
  1320. }
  1321. return NULL;
  1322. }
  1323. //-----------------------------------------------------------------------------
  1324. // Purpose:
  1325. //-----------------------------------------------------------------------------
  1326. void CBreakableProp::BreakThink( void )
  1327. {
  1328. CTakeDamageInfo info;
  1329. info.SetAttacker( this );
  1330. Break( m_hBreaker, info );
  1331. }
  1332. //-----------------------------------------------------------------------------
  1333. // Purpose: Play the sound (if any) that I'm supposed to play when punted.
  1334. //-----------------------------------------------------------------------------
  1335. void CBreakableProp::PlayPuntSound()
  1336. {
  1337. if( !m_bUsePuntSound )
  1338. return;
  1339. if( m_iszPuntSound == NULL_STRING )
  1340. return;
  1341. EmitSound( STRING(m_iszPuntSound) );
  1342. }
  1343. //-----------------------------------------------------------------------------
  1344. // Purpose:
  1345. //-----------------------------------------------------------------------------
  1346. void CBreakableProp::Precache()
  1347. {
  1348. m_iNumBreakableChunks = PropBreakablePrecacheAll( GetModelName() );
  1349. if( m_iszPuntSound != NULL_STRING )
  1350. {
  1351. PrecacheScriptSound( STRING(m_iszPuntSound) );
  1352. }
  1353. BaseClass::Precache();
  1354. }
  1355. // Get the root physics object from which all broken pieces will
  1356. // derive their positions and velocities
  1357. IPhysicsObject *CBreakableProp::GetRootPhysicsObjectForBreak()
  1358. {
  1359. return VPhysicsGetObject();
  1360. }
  1361. void CBreakableProp::Break( CBaseEntity *pBreaker, const CTakeDamageInfo &info )
  1362. {
  1363. const char *pModelName = STRING( GetModelName() );
  1364. if ( pModelName && Q_stristr( pModelName, "crate" ) )
  1365. {
  1366. bool bSmashed = false;
  1367. if ( pBreaker && pBreaker->IsPlayer() )
  1368. {
  1369. bSmashed = true;
  1370. }
  1371. else if ( m_hPhysicsAttacker.Get() && m_hPhysicsAttacker->IsPlayer() )
  1372. {
  1373. bSmashed = true;
  1374. }
  1375. else if ( pBreaker && dynamic_cast< CPropVehicleDriveable * >( pBreaker ) )
  1376. {
  1377. CPropVehicleDriveable *veh = static_cast< CPropVehicleDriveable * >( pBreaker );
  1378. CBaseEntity *driver = veh->GetDriver();
  1379. if ( driver && driver->IsPlayer() )
  1380. {
  1381. bSmashed = true;
  1382. }
  1383. }
  1384. if ( bSmashed )
  1385. {
  1386. gamestats->Event_CrateSmashed();
  1387. }
  1388. }
  1389. IGameEvent * event = gameeventmanager->CreateEvent( "break_prop" );
  1390. if ( event )
  1391. {
  1392. if ( pBreaker && pBreaker->IsPlayer() )
  1393. {
  1394. event->SetInt( "userid", ToBasePlayer( pBreaker )->GetUserID() );
  1395. }
  1396. else
  1397. {
  1398. event->SetInt( "userid", 0 );
  1399. }
  1400. event->SetInt( "entindex", entindex() );
  1401. gameeventmanager->FireEvent( event );
  1402. }
  1403. m_takedamage = DAMAGE_NO;
  1404. m_OnBreak.FireOutput( pBreaker, this );
  1405. Vector velocity;
  1406. AngularImpulse angVelocity;
  1407. IPhysicsObject *pPhysics = GetRootPhysicsObjectForBreak();
  1408. Vector origin;
  1409. QAngle angles;
  1410. AddSolidFlags( FSOLID_NOT_SOLID );
  1411. if ( pPhysics )
  1412. {
  1413. pPhysics->GetVelocity( &velocity, &angVelocity );
  1414. pPhysics->GetPosition( &origin, &angles );
  1415. pPhysics->RecheckCollisionFilter();
  1416. }
  1417. else
  1418. {
  1419. velocity = GetAbsVelocity();
  1420. QAngleToAngularImpulse( GetLocalAngularVelocity(), angVelocity );
  1421. origin = GetAbsOrigin();
  1422. angles = GetAbsAngles();
  1423. }
  1424. PhysBreakSound( this, VPhysicsGetObject(), GetAbsOrigin() );
  1425. bool bExploded = false;
  1426. CBaseEntity *pAttacker = info.GetAttacker();
  1427. if ( m_hLastAttacker )
  1428. {
  1429. // Pass along the person who made this explosive breakable explode.
  1430. // This way the player allies can get immunity from barrels exploded by the player.
  1431. pAttacker = m_hLastAttacker;
  1432. }
  1433. else if( m_hPhysicsAttacker )
  1434. {
  1435. // If I have a physics attacker and was influenced in the last 2 seconds,
  1436. // Make the attacker my physics attacker. This helps protect citizens from dying
  1437. // in the explosion of a physics object that was thrown by the player's physgun
  1438. // and exploded on impact.
  1439. if( gpGlobals->curtime - m_flLastPhysicsInfluenceTime <= 2.0f )
  1440. {
  1441. pAttacker = m_hPhysicsAttacker;
  1442. }
  1443. }
  1444. if ( m_explodeDamage > 0 || m_explodeRadius > 0 )
  1445. {
  1446. if( HasInteraction( PROPINTER_PHYSGUN_BREAK_EXPLODE ) )
  1447. {
  1448. ExplosionCreate( WorldSpaceCenter(), angles, pAttacker, m_explodeDamage, m_explodeRadius,
  1449. SF_ENVEXPLOSION_NOSPARKS | SF_ENVEXPLOSION_NODLIGHTS | SF_ENVEXPLOSION_NOSMOKE | SF_ENVEXPLOSION_SURFACEONLY | SF_ENVEXPLOSION_NOSOUND,
  1450. 0.0f, this );
  1451. EmitSound("PropaneTank.Burst");
  1452. }
  1453. else
  1454. {
  1455. float flScale = GetModelScale();
  1456. ExplosionCreate( WorldSpaceCenter(), angles, pAttacker, m_explodeDamage * flScale, m_explodeRadius * flScale,
  1457. SF_ENVEXPLOSION_NOSPARKS | SF_ENVEXPLOSION_NODLIGHTS | SF_ENVEXPLOSION_NOSMOKE | SF_ENVEXPLOSION_SURFACEONLY,
  1458. 0.0f, this );
  1459. }
  1460. bExploded = true;
  1461. }
  1462. // Allow derived classes to emit special things
  1463. OnBreak( velocity, angVelocity, pBreaker );
  1464. breakablepropparams_t params( origin, angles, velocity, angVelocity );
  1465. params.impactEnergyScale = m_impactEnergyScale;
  1466. params.defCollisionGroup = GetCollisionGroup();
  1467. if ( params.defCollisionGroup == COLLISION_GROUP_NONE )
  1468. {
  1469. // don't automatically make anything COLLISION_GROUP_NONE or it will
  1470. // collide with debris being ejected by breaking
  1471. params.defCollisionGroup = COLLISION_GROUP_INTERACTIVE;
  1472. }
  1473. params.defBurstScale = 100;
  1474. if ( m_iszBreakModelMessage != NULL_STRING )
  1475. {
  1476. CPVSFilter filter( GetAbsOrigin() );
  1477. UserMessageBegin( filter, STRING( m_iszBreakModelMessage ) );
  1478. WRITE_SHORT( GetModelIndex() );
  1479. WRITE_VEC3COORD( GetAbsOrigin() );
  1480. WRITE_ANGLES( GetAbsAngles() );
  1481. MessageEnd();
  1482. #ifndef HL2MP
  1483. UTIL_Remove( this );
  1484. #endif
  1485. return;
  1486. }
  1487. // in multiplayer spawn break models as clientside temp ents
  1488. if ( gpGlobals->maxClients > 1 && breakable_multiplayer.GetBool() )
  1489. {
  1490. CPASFilter filter( WorldSpaceCenter() );
  1491. Vector velocity; velocity.Init();
  1492. if ( pPhysics )
  1493. pPhysics->GetVelocity( &velocity, NULL );
  1494. switch ( GetMultiplayerBreakMode() )
  1495. {
  1496. case MULTIPLAYER_BREAK_DEFAULT: // default is to break client-side
  1497. case MULTIPLAYER_BREAK_CLIENTSIDE:
  1498. te->PhysicsProp( filter, -1, GetModelIndex(), m_nSkin, GetAbsOrigin(), GetAbsAngles(), velocity, true, GetEffects() );
  1499. break;
  1500. case MULTIPLAYER_BREAK_SERVERSIDE: // server-side break
  1501. if ( m_PerformanceMode != PM_NO_GIBS || breakable_disable_gib_limit.GetBool() )
  1502. {
  1503. PropBreakableCreateAll( GetModelIndex(), pPhysics, params, this, -1, ( m_PerformanceMode == PM_FULL_GIBS ), false );
  1504. }
  1505. break;
  1506. case MULTIPLAYER_BREAK_BOTH: // pieces break from both dlls
  1507. te->PhysicsProp( filter, -1, GetModelIndex(), m_nSkin, GetAbsOrigin(), GetAbsAngles(), velocity, true, GetEffects() );
  1508. if ( m_PerformanceMode != PM_NO_GIBS || breakable_disable_gib_limit.GetBool() )
  1509. {
  1510. PropBreakableCreateAll( GetModelIndex(), pPhysics, params, this, -1, ( m_PerformanceMode == PM_FULL_GIBS ), false );
  1511. }
  1512. break;
  1513. }
  1514. }
  1515. // no damage/damage force? set a burst of 100 for some movement
  1516. else if ( m_PerformanceMode != PM_NO_GIBS || breakable_disable_gib_limit.GetBool() )
  1517. {
  1518. PropBreakableCreateAll( GetModelIndex(), pPhysics, params, this, -1, ( m_PerformanceMode == PM_FULL_GIBS ) );
  1519. }
  1520. if( HasInteraction( PROPINTER_PHYSGUN_BREAK_EXPLODE ) )
  1521. {
  1522. if ( bExploded == false )
  1523. {
  1524. ExplosionCreate( origin, angles, pAttacker, 1, m_explodeRadius,
  1525. SF_ENVEXPLOSION_NOSPARKS | SF_ENVEXPLOSION_NODLIGHTS | SF_ENVEXPLOSION_NOSMOKE, 0.0f, this );
  1526. }
  1527. // Find and ignite all NPC's within the radius
  1528. CBaseEntity *pEntity = NULL;
  1529. for ( CEntitySphereQuery sphere( origin, m_explodeRadius ); ( pEntity = sphere.GetCurrentEntity() ) != NULL; sphere.NextEntity() )
  1530. {
  1531. if( pEntity && pEntity->MyCombatCharacterPointer() )
  1532. {
  1533. // Check damage filters so we don't ignite friendlies
  1534. if ( pEntity->PassesDamageFilter( info ) )
  1535. {
  1536. pEntity->MyCombatCharacterPointer()->Ignite( 30 );
  1537. }
  1538. }
  1539. }
  1540. }
  1541. #ifndef HL2MP
  1542. UTIL_Remove( this );
  1543. #endif
  1544. }
  1545. //=============================================================================================================
  1546. // DYNAMIC PROPS
  1547. //=============================================================================================================
  1548. LINK_ENTITY_TO_CLASS( dynamic_prop, CDynamicProp );
  1549. LINK_ENTITY_TO_CLASS( prop_dynamic, CDynamicProp );
  1550. LINK_ENTITY_TO_CLASS( prop_dynamic_override, CDynamicProp );
  1551. IMPLEMENT_AUTO_LIST( IPhysicsPropAutoList );
  1552. BEGIN_DATADESC( CDynamicProp )
  1553. // Fields
  1554. DEFINE_KEYFIELD( m_iszDefaultAnim, FIELD_STRING, "DefaultAnim"),
  1555. DEFINE_FIELD( m_iGoalSequence, FIELD_INTEGER ),
  1556. DEFINE_FIELD( m_iTransitionDirection, FIELD_INTEGER ),
  1557. DEFINE_KEYFIELD( m_bRandomAnimator, FIELD_BOOLEAN, "RandomAnimation"),
  1558. DEFINE_FIELD( m_flNextRandAnim, FIELD_TIME ),
  1559. DEFINE_KEYFIELD( m_flMinRandAnimTime, FIELD_FLOAT, "MinAnimTime"),
  1560. DEFINE_KEYFIELD( m_flMaxRandAnimTime, FIELD_FLOAT, "MaxAnimTime"),
  1561. DEFINE_KEYFIELD( m_bStartDisabled, FIELD_BOOLEAN, "StartDisabled" ),
  1562. DEFINE_KEYFIELD( m_bDisableBoneFollowers, FIELD_BOOLEAN, "DisableBoneFollowers" ),
  1563. DEFINE_FIELD( m_bUseHitboxesForRenderBox, FIELD_BOOLEAN ),
  1564. DEFINE_FIELD( m_nPendingSequence, FIELD_SHORT ),
  1565. // Inputs
  1566. DEFINE_INPUTFUNC( FIELD_STRING, "SetAnimation", InputSetAnimation ),
  1567. DEFINE_INPUTFUNC( FIELD_STRING, "SetDefaultAnimation", InputSetDefaultAnimation ),
  1568. DEFINE_INPUTFUNC( FIELD_VOID, "TurnOn", InputTurnOn ),
  1569. DEFINE_INPUTFUNC( FIELD_VOID, "TurnOff", InputTurnOff ),
  1570. DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputTurnOn ),
  1571. DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputTurnOff ),
  1572. DEFINE_INPUTFUNC( FIELD_VOID, "EnableCollision", InputEnableCollision ),
  1573. DEFINE_INPUTFUNC( FIELD_VOID, "DisableCollision", InputDisableCollision ),
  1574. DEFINE_INPUTFUNC( FIELD_FLOAT, "SetPlaybackRate", InputSetPlaybackRate ),
  1575. // Outputs
  1576. DEFINE_OUTPUT( m_pOutputAnimBegun, "OnAnimationBegun" ),
  1577. DEFINE_OUTPUT( m_pOutputAnimOver, "OnAnimationDone" ),
  1578. // Function Pointers
  1579. DEFINE_THINKFUNC( AnimThink ),
  1580. DEFINE_EMBEDDED( m_BoneFollowerManager ),
  1581. END_DATADESC()
  1582. IMPLEMENT_SERVERCLASS_ST(CDynamicProp, DT_DynamicProp)
  1583. SendPropBool( SENDINFO( m_bUseHitboxesForRenderBox ) ),
  1584. END_SEND_TABLE()
  1585. //-----------------------------------------------------------------------------
  1586. // Purpose:
  1587. //-----------------------------------------------------------------------------
  1588. CDynamicProp::CDynamicProp()
  1589. {
  1590. m_nPendingSequence = -1;
  1591. if ( g_pGameRules->IsMultiplayer() )
  1592. {
  1593. UseClientSideAnimation();
  1594. }
  1595. m_iGoalSequence = -1;
  1596. }
  1597. //------------------------------------------------------------------------------
  1598. // Purpose:
  1599. //------------------------------------------------------------------------------
  1600. void CDynamicProp::Spawn( )
  1601. {
  1602. // Condense classname's to one, except for "prop_dynamic_override"
  1603. if ( FClassnameIs( this, "dynamic_prop" ) )
  1604. {
  1605. SetClassname( "prop_dynamic" );
  1606. }
  1607. // If the prop is not-solid, the bounding box needs to be
  1608. // OBB to correctly surround the prop as it rotates.
  1609. // Check the classname so we don't mess with doors & other derived classes.
  1610. if ( GetSolid() == SOLID_NONE && FClassnameIs( this, "prop_dynamic" ) )
  1611. {
  1612. SetSolid( SOLID_OBB );
  1613. AddSolidFlags( FSOLID_NOT_SOLID );
  1614. }
  1615. BaseClass::Spawn();
  1616. if ( IsMarkedForDeletion() )
  1617. return;
  1618. // Now condense all classnames to one
  1619. if ( FClassnameIs( this, "dynamic_prop" ) || FClassnameIs( this, "prop_dynamic_override" ) )
  1620. {
  1621. SetClassname("prop_dynamic");
  1622. }
  1623. AddFlag( FL_STATICPROP );
  1624. if ( m_bRandomAnimator || ( m_iszDefaultAnim != NULL_STRING ) )
  1625. {
  1626. RemoveFlag( FL_STATICPROP );
  1627. if ( m_bRandomAnimator )
  1628. {
  1629. SetThink( &CDynamicProp::AnimThink );
  1630. m_flNextRandAnim = gpGlobals->curtime + random->RandomFloat( m_flMinRandAnimTime, m_flMaxRandAnimTime );
  1631. SetNextThink( gpGlobals->curtime + m_flNextRandAnim + 0.1 );
  1632. }
  1633. else
  1634. {
  1635. PropSetAnim( STRING( m_iszDefaultAnim ) );
  1636. }
  1637. }
  1638. CreateVPhysics();
  1639. BoneFollowerHierarchyChanged();
  1640. if( m_bStartDisabled )
  1641. {
  1642. AddEffects( EF_NODRAW );
  1643. }
  1644. if ( !PropDataOverrodeBlockLOS() )
  1645. {
  1646. CalculateBlockLOS();
  1647. }
  1648. m_bUseHitboxesForRenderBox = HasSpawnFlags( SF_DYNAMICPROP_USEHITBOX_FOR_RENDERBOX );
  1649. if ( HasSpawnFlags( SF_DYNAMICPROP_DISABLE_COLLISION ) )
  1650. {
  1651. AddSolidFlags( FSOLID_NOT_SOLID );
  1652. }
  1653. //m_debugOverlays |= OVERLAY_ABSBOX_BIT;
  1654. #ifdef TF_DLL
  1655. const char *pszModelName = modelinfo->GetModelName( GetModel() );
  1656. if ( pszModelName && pszModelName[0] )
  1657. {
  1658. if ( FStrEq( pszModelName, "models/bots/boss_bot/carrier_parts.mdl" ) )
  1659. {
  1660. SetModelIndexOverride( VISION_MODE_NONE, modelinfo->GetModelIndex( pszModelName ) );
  1661. SetModelIndexOverride( VISION_MODE_ROME, modelinfo->GetModelIndex( "models/bots/tw2/boss_bot/twcarrier_addon.mdl" ) );
  1662. }
  1663. }
  1664. #endif
  1665. }
  1666. //-----------------------------------------------------------------------------
  1667. // Purpose:
  1668. //-----------------------------------------------------------------------------
  1669. void CDynamicProp::OnRestore( void )
  1670. {
  1671. BaseClass::OnRestore();
  1672. BoneFollowerHierarchyChanged();
  1673. }
  1674. void CDynamicProp::SetParent( CBaseEntity *pNewParent, int iAttachment )
  1675. {
  1676. BaseClass::SetParent(pNewParent, iAttachment);
  1677. BoneFollowerHierarchyChanged();
  1678. }
  1679. // Call this when creating bone followers or changing hierarchy to make sure the bone followers get updated when hierarchy changes
  1680. void CDynamicProp::BoneFollowerHierarchyChanged()
  1681. {
  1682. // If we have bone followers and we're parented to something, we need to constantly update our bone followers
  1683. if ( m_BoneFollowerManager.GetNumBoneFollowers() && GetParent() )
  1684. {
  1685. WatchPositionChanges(this, this);
  1686. }
  1687. }
  1688. //-----------------------------------------------------------------------------
  1689. // Purpose:
  1690. //-----------------------------------------------------------------------------
  1691. bool CDynamicProp::OverridePropdata( void )
  1692. {
  1693. return ( FClassnameIs(this, "prop_dynamic_override" ) );
  1694. }
  1695. //------------------------------------------------------------------------------
  1696. // Purpose:
  1697. //------------------------------------------------------------------------------
  1698. bool CDynamicProp::CreateVPhysics( void )
  1699. {
  1700. if ( GetSolid() == SOLID_NONE || ((GetSolidFlags() & FSOLID_NOT_SOLID) && HasSpawnFlags(SF_DYNAMICPROP_NO_VPHYSICS)))
  1701. return true;
  1702. if ( !m_bDisableBoneFollowers )
  1703. {
  1704. CreateBoneFollowers();
  1705. }
  1706. if ( m_BoneFollowerManager.GetNumBoneFollowers() )
  1707. {
  1708. if ( GetSolidFlags() & FSOLID_NOT_SOLID )
  1709. {
  1710. // Already non-solid? Must need bone followers for some other reason
  1711. // like needing to attach constraints to this object
  1712. for ( int i = 0; i < m_BoneFollowerManager.GetNumBoneFollowers(); i++ )
  1713. {
  1714. CBaseEntity *pFollower = m_BoneFollowerManager.GetBoneFollower(i)->hFollower;
  1715. if ( pFollower )
  1716. {
  1717. pFollower->AddSolidFlags(FSOLID_NOT_SOLID);
  1718. }
  1719. }
  1720. }
  1721. // If our collision is through bone followers, we want to be non-solid
  1722. AddSolidFlags( FSOLID_NOT_SOLID );
  1723. // add these for the client, FSOLID_NOT_SOLID should keep it out of the testCollision code
  1724. // except in the case of TraceEntity() which the client does for impact effects
  1725. AddSolidFlags( FSOLID_CUSTOMRAYTEST | FSOLID_CUSTOMBOXTEST );
  1726. return true;
  1727. }
  1728. else
  1729. {
  1730. VPhysicsInitStatic();
  1731. }
  1732. return true;
  1733. }
  1734. void CDynamicProp::CreateBoneFollowers()
  1735. {
  1736. // already created bone followers? Don't do so again.
  1737. if ( m_BoneFollowerManager.GetNumBoneFollowers() )
  1738. return;
  1739. KeyValues *modelKeyValues = new KeyValues("");
  1740. if ( modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( GetModel() ), modelinfo->GetModelKeyValueText( GetModel() ) ) )
  1741. {
  1742. // Do we have a bone follower section?
  1743. KeyValues *pkvBoneFollowers = modelKeyValues->FindKey("bone_followers");
  1744. if ( pkvBoneFollowers )
  1745. {
  1746. // Loop through the list and create the bone followers
  1747. KeyValues *pBone = pkvBoneFollowers->GetFirstSubKey();
  1748. while ( pBone )
  1749. {
  1750. // Add it to the list
  1751. const char *pBoneName = pBone->GetString();
  1752. m_BoneFollowerManager.AddBoneFollower( this, pBoneName );
  1753. pBone = pBone->GetNextKey();
  1754. }
  1755. }
  1756. modelKeyValues->deleteThis();
  1757. }
  1758. // if we got here, we don't have a bone follower section, but if we have a ragdoll
  1759. // go ahead and create default bone followers for it
  1760. if ( m_BoneFollowerManager.GetNumBoneFollowers() == 0 )
  1761. {
  1762. vcollide_t *pCollide = modelinfo->GetVCollide( GetModelIndex() );
  1763. if ( pCollide && pCollide->solidCount > 1 )
  1764. {
  1765. CreateBoneFollowersFromRagdoll(this, &m_BoneFollowerManager, pCollide);
  1766. }
  1767. }
  1768. }
  1769. bool CDynamicProp::TestCollision( const Ray_t &ray, unsigned int mask, trace_t& trace )
  1770. {
  1771. if ( IsSolidFlagSet(FSOLID_NOT_SOLID) )
  1772. {
  1773. // if this entity is marked non-solid and custom test it must have bone followers
  1774. if ( IsSolidFlagSet( FSOLID_CUSTOMBOXTEST ) && IsSolidFlagSet( FSOLID_CUSTOMRAYTEST ))
  1775. {
  1776. for ( int i = 0; i < m_BoneFollowerManager.GetNumBoneFollowers(); i++ )
  1777. {
  1778. CBaseEntity *pEntity = m_BoneFollowerManager.GetBoneFollower(i)->hFollower;
  1779. if ( pEntity && pEntity->TestCollision(ray, mask, trace) )
  1780. return true;
  1781. }
  1782. }
  1783. }
  1784. return false;
  1785. }
  1786. IPhysicsObject *CDynamicProp::GetRootPhysicsObjectForBreak()
  1787. {
  1788. if ( m_BoneFollowerManager.GetNumBoneFollowers() )
  1789. {
  1790. physfollower_t *pFollower = m_BoneFollowerManager.GetBoneFollower(0);
  1791. CBaseEntity *pFollowerEntity = pFollower->hFollower;
  1792. if ( pFollowerEntity )
  1793. {
  1794. return pFollowerEntity->VPhysicsGetObject();
  1795. }
  1796. }
  1797. return BaseClass::GetRootPhysicsObjectForBreak();
  1798. }
  1799. //-----------------------------------------------------------------------------
  1800. // Purpose:
  1801. //-----------------------------------------------------------------------------
  1802. void CDynamicProp::UpdateOnRemove( void )
  1803. {
  1804. m_BoneFollowerManager.DestroyBoneFollowers();
  1805. BaseClass::UpdateOnRemove();
  1806. }
  1807. //-----------------------------------------------------------------------------
  1808. //-----------------------------------------------------------------------------
  1809. void CDynamicProp::HandleAnimEvent( animevent_t *pEvent )
  1810. {
  1811. switch( pEvent->event )
  1812. {
  1813. case SCRIPT_EVENT_FIRE_INPUT:
  1814. {
  1815. variant_t emptyVariant;
  1816. this->AcceptInput( pEvent->options, this, this, emptyVariant, 0 );
  1817. return;
  1818. }
  1819. case SCRIPT_EVENT_SOUND:
  1820. {
  1821. EmitSound( pEvent->options );
  1822. break;
  1823. }
  1824. default:
  1825. {
  1826. break;
  1827. }
  1828. }
  1829. BaseClass::HandleAnimEvent( pEvent );
  1830. }
  1831. //-----------------------------------------------------------------------------
  1832. // Purpose:
  1833. //-----------------------------------------------------------------------------
  1834. void CDynamicProp::NotifyPositionChanged( CBaseEntity *pEntity )
  1835. {
  1836. Assert(pEntity==this);
  1837. m_BoneFollowerManager.UpdateBoneFollowers(this);
  1838. }
  1839. //------------------------------------------------------------------------------
  1840. // Purpose:
  1841. //------------------------------------------------------------------------------
  1842. void CDynamicProp::AnimThink( void )
  1843. {
  1844. if ( m_nPendingSequence != -1 )
  1845. {
  1846. FinishSetSequence( m_nPendingSequence );
  1847. m_nPendingSequence = -1;
  1848. }
  1849. if ( m_bRandomAnimator && m_flNextRandAnim < gpGlobals->curtime )
  1850. {
  1851. ResetSequence( SelectWeightedSequence( ACT_IDLE ) );
  1852. ResetClientsideFrame();
  1853. // Fire output
  1854. m_pOutputAnimBegun.FireOutput( NULL,this );
  1855. m_flNextRandAnim = gpGlobals->curtime + random->RandomFloat( m_flMinRandAnimTime, m_flMaxRandAnimTime );
  1856. }
  1857. if ( ((m_iTransitionDirection > 0 && GetCycle() >= 0.999f) || (m_iTransitionDirection < 0 && GetCycle() <= 0.0f)) && !SequenceLoops() )
  1858. {
  1859. Assert( m_iGoalSequence >= 0 );
  1860. if (GetSequence() != m_iGoalSequence)
  1861. {
  1862. PropSetSequence( m_iGoalSequence );
  1863. }
  1864. else
  1865. {
  1866. // Fire output
  1867. m_pOutputAnimOver.FireOutput(NULL,this);
  1868. // If I'm a random animator, think again when it's time to change sequence
  1869. if ( m_bRandomAnimator )
  1870. {
  1871. SetNextThink( gpGlobals->curtime + m_flNextRandAnim + 0.1 );
  1872. }
  1873. else
  1874. {
  1875. if (m_iszDefaultAnim != NULL_STRING)
  1876. {
  1877. PropSetAnim( STRING( m_iszDefaultAnim ) );
  1878. }
  1879. }
  1880. }
  1881. }
  1882. else
  1883. {
  1884. SetNextThink( gpGlobals->curtime + 0.1f );
  1885. }
  1886. StudioFrameAdvance();
  1887. DispatchAnimEvents(this);
  1888. m_BoneFollowerManager.UpdateBoneFollowers(this);
  1889. }
  1890. //------------------------------------------------------------------------------
  1891. // Purpose: Sets an animation by sequence name or activity name.
  1892. //------------------------------------------------------------------------------
  1893. void CDynamicProp::PropSetAnim( const char *szAnim )
  1894. {
  1895. if ( !szAnim )
  1896. return;
  1897. int nSequence = LookupSequence( szAnim );
  1898. // Set to the desired anim, or default anim if the desired is not present
  1899. if ( nSequence > ACTIVITY_NOT_AVAILABLE )
  1900. {
  1901. PropSetSequence( nSequence );
  1902. // Fire output
  1903. m_pOutputAnimBegun.FireOutput( NULL,this );
  1904. }
  1905. else
  1906. {
  1907. // Not available try to get default anim
  1908. Warning( "Dynamic prop %s: no sequence named:%s\n", GetDebugName(), szAnim );
  1909. SetSequence( 0 );
  1910. }
  1911. }
  1912. //------------------------------------------------------------------------------
  1913. // Purpose:
  1914. //------------------------------------------------------------------------------
  1915. void CDynamicProp::InputSetAnimation( inputdata_t &inputdata )
  1916. {
  1917. PropSetAnim( inputdata.value.String() );
  1918. }
  1919. //------------------------------------------------------------------------------
  1920. // Purpose:
  1921. //------------------------------------------------------------------------------
  1922. void CDynamicProp::InputSetDefaultAnimation( inputdata_t &inputdata )
  1923. {
  1924. m_iszDefaultAnim = inputdata.value.StringID();
  1925. }
  1926. //-----------------------------------------------------------------------------
  1927. // Purpose:
  1928. //-----------------------------------------------------------------------------
  1929. void CDynamicProp::InputSetPlaybackRate( inputdata_t &inputdata )
  1930. {
  1931. SetPlaybackRate( inputdata.value.Float() );
  1932. }
  1933. //-----------------------------------------------------------------------------
  1934. // Purpose: Helper in case we have to async load the sequence
  1935. // Input : nSequence -
  1936. //-----------------------------------------------------------------------------
  1937. void CDynamicProp::FinishSetSequence( int nSequence )
  1938. {
  1939. // Msg("%.2f CDynamicProp::FinishSetSequence( %d )\n", gpGlobals->curtime, nSequence );
  1940. SetCycle( 0 );
  1941. m_flAnimTime = gpGlobals->curtime;
  1942. ResetSequence( nSequence );
  1943. ResetClientsideFrame();
  1944. RemoveFlag( FL_STATICPROP );
  1945. SetPlaybackRate( m_iTransitionDirection > 0 ? 1.0f : -1.0f );
  1946. SetCycle( m_iTransitionDirection > 0 ? 0.0f : 0.999f );
  1947. }
  1948. //-----------------------------------------------------------------------------
  1949. // Purpose: Sets the sequence and starts thinking.
  1950. // Input : nSequence -
  1951. //-----------------------------------------------------------------------------
  1952. void CDynamicProp::PropSetSequence( int nSequence )
  1953. {
  1954. m_iGoalSequence = nSequence;
  1955. // Msg("%.2f CDynamicProp::PropSetSequence( %d (%d:%.1f:%.3f)\n", gpGlobals->curtime, nSequence, GetSequence(), GetPlaybackRate(), GetCycle() );
  1956. int nNextSequence;
  1957. float nextCycle;
  1958. float flInterval = 0.1f;
  1959. if (GotoSequence( GetSequence(), GetCycle(), GetPlaybackRate(), m_iGoalSequence, nNextSequence, nextCycle, m_iTransitionDirection ))
  1960. {
  1961. FinishSetSequence( nNextSequence );
  1962. }
  1963. SetThink( &CDynamicProp::AnimThink );
  1964. if ( GetNextThink() <= gpGlobals->curtime )
  1965. SetNextThink( gpGlobals->curtime + flInterval );
  1966. }
  1967. // NOTE: To avoid risk, currently these do nothing about collisions, only visually on/off
  1968. void CDynamicProp::InputTurnOn( inputdata_t &inputdata )
  1969. {
  1970. RemoveEffects( EF_NODRAW );
  1971. }
  1972. void CDynamicProp::InputTurnOff( inputdata_t &inputdata )
  1973. {
  1974. AddEffects( EF_NODRAW );
  1975. }
  1976. void CDynamicProp::InputDisableCollision( inputdata_t &inputdata )
  1977. {
  1978. AddSolidFlags( FSOLID_NOT_SOLID );
  1979. }
  1980. void CDynamicProp::InputEnableCollision( inputdata_t &inputdata )
  1981. {
  1982. RemoveSolidFlags( FSOLID_NOT_SOLID );
  1983. }
  1984. //-----------------------------------------------------------------------------
  1985. // Purpose: Ornamental prop that follows a studio
  1986. //-----------------------------------------------------------------------------
  1987. class COrnamentProp : public CDynamicProp
  1988. {
  1989. DECLARE_CLASS( COrnamentProp, CDynamicProp );
  1990. public:
  1991. DECLARE_DATADESC();
  1992. void Spawn();
  1993. void Activate();
  1994. void AttachTo( const char *pAttachEntity, CBaseEntity *pActivator = NULL, CBaseEntity *pCaller = NULL );
  1995. void DetachFromOwner();
  1996. // Input handlers
  1997. void InputSetAttached( inputdata_t &inputdata );
  1998. void InputDetach( inputdata_t &inputdata );
  1999. private:
  2000. string_t m_initialOwner;
  2001. };
  2002. LINK_ENTITY_TO_CLASS( prop_dynamic_ornament, COrnamentProp );
  2003. BEGIN_DATADESC( COrnamentProp )
  2004. DEFINE_KEYFIELD( m_initialOwner, FIELD_STRING, "InitialOwner" ),
  2005. // Inputs
  2006. DEFINE_INPUTFUNC( FIELD_STRING, "SetAttached", InputSetAttached ),
  2007. DEFINE_INPUTFUNC( FIELD_VOID, "Detach", InputDetach ),
  2008. END_DATADESC()
  2009. void COrnamentProp::Spawn()
  2010. {
  2011. BaseClass::Spawn();
  2012. DetachFromOwner();
  2013. }
  2014. void COrnamentProp::DetachFromOwner()
  2015. {
  2016. SetOwnerEntity( NULL );
  2017. AddSolidFlags( FSOLID_NOT_SOLID );
  2018. SetMoveType( MOVETYPE_NONE );
  2019. AddEffects( EF_NODRAW );
  2020. }
  2021. void COrnamentProp::Activate()
  2022. {
  2023. BaseClass::Activate();
  2024. if ( m_initialOwner != NULL_STRING )
  2025. {
  2026. AttachTo( STRING(m_initialOwner) );
  2027. }
  2028. }
  2029. void COrnamentProp::InputSetAttached( inputdata_t &inputdata )
  2030. {
  2031. AttachTo( inputdata.value.String(), inputdata.pActivator, inputdata.pCaller );
  2032. }
  2033. void COrnamentProp::AttachTo( const char *pAttachName, CBaseEntity *pActivator, CBaseEntity *pCaller )
  2034. {
  2035. // find and notify the new parent
  2036. CBaseEntity *pAttach = gEntList.FindEntityByName( NULL, pAttachName, NULL, pActivator, pCaller );
  2037. if ( pAttach )
  2038. {
  2039. RemoveEffects( EF_NODRAW );
  2040. FollowEntity( pAttach );
  2041. }
  2042. }
  2043. void COrnamentProp::InputDetach( inputdata_t &inputdata )
  2044. {
  2045. DetachFromOwner();
  2046. }
  2047. //=============================================================================
  2048. // PHYSICS PROPS
  2049. //=============================================================================
  2050. LINK_ENTITY_TO_CLASS( physics_prop, CPhysicsProp );
  2051. LINK_ENTITY_TO_CLASS( prop_physics, CPhysicsProp );
  2052. LINK_ENTITY_TO_CLASS( prop_physics_override, CPhysicsProp );
  2053. BEGIN_DATADESC( CPhysicsProp )
  2054. DEFINE_INPUTFUNC( FIELD_VOID, "EnableMotion", InputEnableMotion ),
  2055. DEFINE_INPUTFUNC( FIELD_VOID, "DisableMotion", InputDisableMotion ),
  2056. DEFINE_INPUTFUNC( FIELD_VOID, "Wake", InputWake ),
  2057. DEFINE_INPUTFUNC( FIELD_VOID, "Sleep", InputSleep ),
  2058. DEFINE_INPUTFUNC( FIELD_VOID, "DisableFloating", InputDisableFloating ),
  2059. DEFINE_FIELD( m_bAwake, FIELD_BOOLEAN ),
  2060. DEFINE_KEYFIELD( m_massScale, FIELD_FLOAT, "massscale" ),
  2061. DEFINE_KEYFIELD( m_inertiaScale, FIELD_FLOAT, "inertiascale" ),
  2062. DEFINE_KEYFIELD( m_damageType, FIELD_INTEGER, "Damagetype" ),
  2063. DEFINE_KEYFIELD( m_iszOverrideScript, FIELD_STRING, "overridescript" ),
  2064. DEFINE_KEYFIELD( m_damageToEnableMotion, FIELD_INTEGER, "damagetoenablemotion" ),
  2065. DEFINE_KEYFIELD( m_flForceToEnableMotion, FIELD_FLOAT, "forcetoenablemotion" ),
  2066. DEFINE_OUTPUT( m_OnAwakened, "OnAwakened" ),
  2067. DEFINE_OUTPUT( m_MotionEnabled, "OnMotionEnabled" ),
  2068. DEFINE_OUTPUT( m_OnPhysGunPickup, "OnPhysGunPickup" ),
  2069. DEFINE_OUTPUT( m_OnPhysGunOnlyPickup, "OnPhysGunOnlyPickup" ),
  2070. DEFINE_OUTPUT( m_OnPhysGunPunt, "OnPhysGunPunt" ),
  2071. DEFINE_OUTPUT( m_OnPhysGunDrop, "OnPhysGunDrop" ),
  2072. DEFINE_OUTPUT( m_OnPlayerUse, "OnPlayerUse" ),
  2073. DEFINE_OUTPUT( m_OnPlayerPickup, "OnPlayerPickup" ),
  2074. DEFINE_OUTPUT( m_OnOutOfWorld, "OnOutOfWorld" ),
  2075. DEFINE_FIELD( m_bThrownByPlayer, FIELD_BOOLEAN ),
  2076. DEFINE_FIELD( m_bFirstCollisionAfterLaunch, FIELD_BOOLEAN ),
  2077. DEFINE_THINKFUNC( ClearFlagsThink ),
  2078. END_DATADESC()
  2079. IMPLEMENT_SERVERCLASS_ST( CPhysicsProp, DT_PhysicsProp )
  2080. SendPropBool( SENDINFO( m_bAwake ) ),
  2081. END_SEND_TABLE()
  2082. // external function to tell if this entity is a gib physics prop
  2083. bool PropIsGib( CBaseEntity *pEntity )
  2084. {
  2085. if ( FClassnameIs(pEntity, "prop_physics") )
  2086. {
  2087. CPhysicsProp *pProp = static_cast<CPhysicsProp *>(pEntity);
  2088. return pProp->IsGib();
  2089. }
  2090. return false;
  2091. }
  2092. CPhysicsProp::~CPhysicsProp()
  2093. {
  2094. if (HasSpawnFlags(SF_PHYSPROP_IS_GIB))
  2095. {
  2096. g_ActiveGibCount--;
  2097. }
  2098. }
  2099. bool CPhysicsProp::IsGib()
  2100. {
  2101. return (m_spawnflags & SF_PHYSPROP_IS_GIB) ? true : false;
  2102. }
  2103. //-----------------------------------------------------------------------------
  2104. // Purpose: Create a physics object for this prop
  2105. //-----------------------------------------------------------------------------
  2106. void CPhysicsProp::Spawn( )
  2107. {
  2108. if (HasSpawnFlags(SF_PHYSPROP_IS_GIB))
  2109. {
  2110. g_ActiveGibCount++;
  2111. }
  2112. // Condense classname's to one, except for "prop_physics_override"
  2113. if ( FClassnameIs( this, "physics_prop" ) )
  2114. {
  2115. SetClassname( "prop_physics" );
  2116. }
  2117. BaseClass::Spawn();
  2118. if ( IsMarkedForDeletion() )
  2119. return;
  2120. // Now condense all classnames to one
  2121. if ( FClassnameIs( this, "prop_physics_override") )
  2122. {
  2123. SetClassname( "prop_physics" );
  2124. }
  2125. if ( HasSpawnFlags( SF_PHYSPROP_DEBRIS ) || HasInteraction( PROPINTER_PHYSGUN_CREATE_FLARE ) )
  2126. {
  2127. SetCollisionGroup( HasSpawnFlags( SF_PHYSPROP_FORCE_TOUCH_TRIGGERS ) ? COLLISION_GROUP_DEBRIS_TRIGGER : COLLISION_GROUP_DEBRIS );
  2128. }
  2129. if ( HasSpawnFlags( SF_PHYSPROP_NO_ROTORWASH_PUSH ) )
  2130. {
  2131. AddEFlags( EFL_NO_ROTORWASH_PUSH );
  2132. }
  2133. CreateVPhysics();
  2134. if ( !PropDataOverrodeBlockLOS() )
  2135. {
  2136. CalculateBlockLOS();
  2137. }
  2138. //Episode 1 change:
  2139. //Hi, since we're trying to ship this game we'll just go ahead and make all these doors not fade out instead of changing all the levels.
  2140. if ( Q_strcmp( STRING( GetModelName() ), "models/props_c17/door01_left.mdl" ) == 0 )
  2141. {
  2142. SetFadeDistance( -1, 0 );
  2143. DisableAutoFade();
  2144. }
  2145. }
  2146. //-----------------------------------------------------------------------------
  2147. // Purpose:
  2148. //-----------------------------------------------------------------------------
  2149. void CPhysicsProp::Precache( void )
  2150. {
  2151. if ( GetModelName() == NULL_STRING )
  2152. {
  2153. Msg( "%s at (%.3f, %.3f, %.3f) has no model name!\n", GetClassname(), GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z );
  2154. }
  2155. else
  2156. {
  2157. PrecacheModel( STRING( GetModelName() ) );
  2158. BaseClass::Precache();
  2159. }
  2160. }
  2161. //-----------------------------------------------------------------------------
  2162. // Purpose:
  2163. //-----------------------------------------------------------------------------
  2164. bool CPhysicsProp::CreateVPhysics()
  2165. {
  2166. // Create the object in the physics system
  2167. bool asleep = HasSpawnFlags( SF_PHYSPROP_START_ASLEEP ) ? true : false;
  2168. solid_t tmpSolid;
  2169. PhysModelParseSolid( tmpSolid, this, GetModelIndex() );
  2170. if ( m_massScale > 0 )
  2171. {
  2172. tmpSolid.params.mass *= m_massScale;
  2173. }
  2174. if ( m_inertiaScale > 0 )
  2175. {
  2176. tmpSolid.params.inertia *= m_inertiaScale;
  2177. if ( tmpSolid.params.inertia < 0.5 )
  2178. tmpSolid.params.inertia = 0.5;
  2179. }
  2180. PhysGetMassCenterOverride( this, modelinfo->GetVCollide( GetModelIndex() ), tmpSolid );
  2181. if ( HasSpawnFlags(SF_PHYSPROP_NO_COLLISIONS) )
  2182. {
  2183. tmpSolid.params.enableCollisions = false;
  2184. }
  2185. PhysSolidOverride( tmpSolid, m_iszOverrideScript );
  2186. IPhysicsObject *pPhysicsObject = VPhysicsInitNormal( SOLID_VPHYSICS, 0, asleep, &tmpSolid );
  2187. if ( !pPhysicsObject )
  2188. {
  2189. SetSolid( SOLID_NONE );
  2190. SetMoveType( MOVETYPE_NONE );
  2191. Warning("ERROR!: Can't create physics object for %s\n", STRING( GetModelName() ) );
  2192. }
  2193. else
  2194. {
  2195. if ( m_damageType == 1 )
  2196. {
  2197. PhysSetGameFlags( pPhysicsObject, FVPHYSICS_DMG_SLICE );
  2198. }
  2199. if ( HasSpawnFlags( SF_PHYSPROP_MOTIONDISABLED ) || m_damageToEnableMotion > 0 || m_flForceToEnableMotion > 0 )
  2200. {
  2201. pPhysicsObject->EnableMotion( false );
  2202. }
  2203. }
  2204. // fix up any noncompliant blades.
  2205. if( HasInteraction( PROPINTER_PHYSGUN_LAUNCH_SPIN_Z ) )
  2206. {
  2207. if( !(VPhysicsGetObject()->GetGameFlags() & FVPHYSICS_DMG_SLICE) )
  2208. {
  2209. PhysSetGameFlags( pPhysicsObject, FVPHYSICS_DMG_SLICE );
  2210. #if 0
  2211. if( g_pDeveloper->GetInt() )
  2212. {
  2213. // Highlight them in developer mode.
  2214. m_debugOverlays |= (OVERLAY_TEXT_BIT|OVERLAY_BBOX_BIT);
  2215. }
  2216. #endif
  2217. }
  2218. }
  2219. if( HasInteraction( PROPINTER_PHYSGUN_DAMAGE_NONE ) )
  2220. {
  2221. PhysSetGameFlags( pPhysicsObject, FVPHYSICS_NO_IMPACT_DMG );
  2222. }
  2223. if ( HasSpawnFlags(SF_PHYSPROP_PREVENT_PICKUP) )
  2224. {
  2225. PhysSetGameFlags(pPhysicsObject, FVPHYSICS_NO_PLAYER_PICKUP);
  2226. }
  2227. return true;
  2228. }
  2229. //-----------------------------------------------------------------------------
  2230. // Purpose:
  2231. // Output : Returns true on success, false on failure.
  2232. //-----------------------------------------------------------------------------
  2233. bool CPhysicsProp::CanBePickedUpByPhyscannon( void )
  2234. {
  2235. if ( HasSpawnFlags( SF_PHYSPROP_PREVENT_PICKUP ) )
  2236. return false;
  2237. IPhysicsObject *pPhysicsObject = VPhysicsGetObject();
  2238. if ( pPhysicsObject && pPhysicsObject->IsMoveable() == false )
  2239. {
  2240. if ( HasSpawnFlags( SF_PHYSPROP_ENABLE_ON_PHYSCANNON ) == false )
  2241. return false;
  2242. }
  2243. return true;
  2244. }
  2245. //-----------------------------------------------------------------------------
  2246. // Purpose:
  2247. //-----------------------------------------------------------------------------
  2248. bool CPhysicsProp::OverridePropdata( void )
  2249. {
  2250. return ( FClassnameIs(this, "prop_physics_override" ) );
  2251. }
  2252. //-----------------------------------------------------------------------------
  2253. // Purpose: Input handler to start the physics prop simulating.
  2254. //-----------------------------------------------------------------------------
  2255. void CPhysicsProp::InputWake( inputdata_t &inputdata )
  2256. {
  2257. IPhysicsObject *pPhysicsObject = VPhysicsGetObject();
  2258. if ( pPhysicsObject != NULL )
  2259. {
  2260. pPhysicsObject->Wake();
  2261. }
  2262. }
  2263. //-----------------------------------------------------------------------------
  2264. // Purpose: Input handler to stop the physics prop simulating.
  2265. //-----------------------------------------------------------------------------
  2266. void CPhysicsProp::InputSleep( inputdata_t &inputdata )
  2267. {
  2268. IPhysicsObject *pPhysicsObject = VPhysicsGetObject();
  2269. if ( pPhysicsObject != NULL )
  2270. {
  2271. pPhysicsObject->Sleep();
  2272. }
  2273. }
  2274. //-----------------------------------------------------------------------------
  2275. // Purpose: Enable physics motion and collision response (on by default)
  2276. //-----------------------------------------------------------------------------
  2277. void CPhysicsProp::InputEnableMotion( inputdata_t &inputdata )
  2278. {
  2279. EnableMotion();
  2280. }
  2281. //-----------------------------------------------------------------------------
  2282. // Purpose: Disable any physics motion or collision response
  2283. //-----------------------------------------------------------------------------
  2284. void CPhysicsProp::InputDisableMotion( inputdata_t &inputdata )
  2285. {
  2286. IPhysicsObject *pPhysicsObject = VPhysicsGetObject();
  2287. if ( pPhysicsObject != NULL )
  2288. {
  2289. pPhysicsObject->EnableMotion( false );
  2290. }
  2291. }
  2292. // Turn off floating simulation (and cost)
  2293. void CPhysicsProp::InputDisableFloating( inputdata_t &inputdata )
  2294. {
  2295. PhysEnableFloating( VPhysicsGetObject(), false );
  2296. }
  2297. //-----------------------------------------------------------------------------
  2298. // Purpose:
  2299. //-----------------------------------------------------------------------------
  2300. void CPhysicsProp::EnableMotion( void )
  2301. {
  2302. IPhysicsObject *pPhysicsObject = VPhysicsGetObject();
  2303. if ( pPhysicsObject )
  2304. {
  2305. Vector pos;
  2306. QAngle angles;
  2307. if ( GetEnableMotionPosition( &pos, &angles ) )
  2308. {
  2309. ClearEnableMotionPosition();
  2310. //pPhysicsObject->SetPosition( pos, angles, true );
  2311. Teleport( &pos, &angles, NULL );
  2312. }
  2313. pPhysicsObject->EnableMotion( true );
  2314. pPhysicsObject->Wake();
  2315. m_MotionEnabled.FireOutput( this, this, 0 );
  2316. }
  2317. CheckRemoveRagdolls();
  2318. }
  2319. //-----------------------------------------------------------------------------
  2320. // Purpose:
  2321. //-----------------------------------------------------------------------------
  2322. void CPhysicsProp::OnPhysGunPickup( CBasePlayer *pPhysGunUser, PhysGunPickup_t reason )
  2323. {
  2324. BaseClass::OnPhysGunPickup( pPhysGunUser, reason );
  2325. IPhysicsObject *pPhysicsObject = VPhysicsGetObject();
  2326. if ( pPhysicsObject && !pPhysicsObject->IsMoveable() )
  2327. {
  2328. if ( !HasSpawnFlags( SF_PHYSPROP_ENABLE_ON_PHYSCANNON ) )
  2329. return;
  2330. EnableMotion();
  2331. if( HasInteraction( PROPINTER_PHYSGUN_WORLD_STICK ) )
  2332. {
  2333. SetCollisionGroup( COLLISION_GROUP_INTERACTIVE_DEBRIS );
  2334. }
  2335. }
  2336. m_OnPhysGunPickup.FireOutput( pPhysGunUser, this );
  2337. if( reason == PICKED_UP_BY_CANNON )
  2338. {
  2339. m_OnPhysGunOnlyPickup.FireOutput( pPhysGunUser, this );
  2340. }
  2341. if ( reason == PUNTED_BY_CANNON )
  2342. {
  2343. m_OnPhysGunPunt.FireOutput( pPhysGunUser, this );
  2344. }
  2345. if ( reason == PICKED_UP_BY_CANNON || reason == PICKED_UP_BY_PLAYER )
  2346. {
  2347. m_OnPlayerPickup.FireOutput( pPhysGunUser, this );
  2348. }
  2349. CheckRemoveRagdolls();
  2350. }
  2351. //-----------------------------------------------------------------------------
  2352. // Purpose:
  2353. //-----------------------------------------------------------------------------
  2354. void CPhysicsProp::OnPhysGunDrop( CBasePlayer *pPhysGunUser, PhysGunDrop_t Reason )
  2355. {
  2356. BaseClass::OnPhysGunDrop( pPhysGunUser, Reason );
  2357. if ( Reason == LAUNCHED_BY_CANNON )
  2358. {
  2359. if ( HasInteraction( PROPINTER_PHYSGUN_LAUNCH_SPIN_Z ) )
  2360. {
  2361. AngularImpulse angVel( 0, 0, 5000.0 );
  2362. VPhysicsGetObject()->AddVelocity( NULL, &angVel );
  2363. // no angular drag on this object anymore
  2364. float angDrag = 0.0f;
  2365. VPhysicsGetObject()->SetDragCoefficient( NULL, &angDrag );
  2366. }
  2367. PhysSetGameFlags( VPhysicsGetObject(), FVPHYSICS_WAS_THROWN );
  2368. m_bFirstCollisionAfterLaunch = true;
  2369. }
  2370. else if ( Reason == THROWN_BY_PLAYER )
  2371. {
  2372. // Remember the player threw us for NPC response purposes
  2373. m_bThrownByPlayer = true;
  2374. }
  2375. m_OnPhysGunDrop.FireOutput( pPhysGunUser, this );
  2376. if ( HasInteraction( PROPINTER_PHYSGUN_NOTIFY_CHILDREN ) )
  2377. {
  2378. CUtlVector<CBaseEntity *> children;
  2379. GetAllChildren( this, children );
  2380. for (int i = 0; i < children.Count(); i++ )
  2381. {
  2382. CBaseEntity *pent = children.Element( i );
  2383. IParentPropInteraction *pPropInter = dynamic_cast<IParentPropInteraction *>( pent );
  2384. if ( pPropInter )
  2385. {
  2386. pPropInter->OnParentPhysGunDrop( pPhysGunUser, Reason );
  2387. }
  2388. }
  2389. }
  2390. }
  2391. //-----------------------------------------------------------------------------
  2392. // Purpose: Get the specified key's angles for this prop from the QC's physgun_interactions
  2393. //-----------------------------------------------------------------------------
  2394. bool CPhysicsProp::GetPropDataAngles( const char *pKeyName, QAngle &vecAngles )
  2395. {
  2396. KeyValues *modelKeyValues = new KeyValues("");
  2397. if ( modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( GetModel() ), modelinfo->GetModelKeyValueText( GetModel() ) ) )
  2398. {
  2399. KeyValues *pkvPropData = modelKeyValues->FindKey( "physgun_interactions" );
  2400. if ( pkvPropData )
  2401. {
  2402. char const *pszBase = pkvPropData->GetString( pKeyName );
  2403. if ( pszBase && pszBase[0] )
  2404. {
  2405. UTIL_StringToVector( vecAngles.Base(), pszBase );
  2406. modelKeyValues->deleteThis();
  2407. return true;
  2408. }
  2409. }
  2410. }
  2411. modelKeyValues->deleteThis();
  2412. return false;
  2413. }
  2414. //-----------------------------------------------------------------------------
  2415. // Purpose:
  2416. //-----------------------------------------------------------------------------
  2417. float CPhysicsProp::GetCarryDistanceOffset( void )
  2418. {
  2419. KeyValues *modelKeyValues = new KeyValues("");
  2420. if ( modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( GetModel() ), modelinfo->GetModelKeyValueText( GetModel() ) ) )
  2421. {
  2422. KeyValues *pkvPropData = modelKeyValues->FindKey( "physgun_interactions" );
  2423. if ( pkvPropData )
  2424. {
  2425. float flDistance = pkvPropData->GetFloat( "carry_distance_offset", 0 );
  2426. modelKeyValues->deleteThis();
  2427. return flDistance;
  2428. }
  2429. }
  2430. modelKeyValues->deleteThis();
  2431. return 0;
  2432. }
  2433. //-----------------------------------------------------------------------------
  2434. // Purpose:
  2435. //-----------------------------------------------------------------------------
  2436. int CPhysicsProp::ObjectCaps()
  2437. {
  2438. int caps = BaseClass::ObjectCaps() | FCAP_WCEDIT_POSITION;
  2439. if ( HasSpawnFlags( SF_PHYSPROP_ENABLE_PICKUP_OUTPUT ) )
  2440. {
  2441. caps |= FCAP_IMPULSE_USE;
  2442. }
  2443. else if ( CBasePlayer::CanPickupObject( this, 35, 128 ) )
  2444. {
  2445. caps |= FCAP_IMPULSE_USE;
  2446. if( hl2_episodic.GetBool() && HasInteraction( PROPINTER_PHYSGUN_CREATE_FLARE ) )
  2447. {
  2448. caps |= FCAP_USE_IN_RADIUS;
  2449. }
  2450. }
  2451. if( HasSpawnFlags( SF_PHYSPROP_RADIUS_PICKUP ) )
  2452. {
  2453. caps |= FCAP_USE_IN_RADIUS;
  2454. }
  2455. return caps;
  2456. }
  2457. //-----------------------------------------------------------------------------
  2458. // Purpose:
  2459. // Input : *pActivator -
  2460. // *pCaller -
  2461. // useType -
  2462. // value -
  2463. //-----------------------------------------------------------------------------
  2464. void CPhysicsProp::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
  2465. {
  2466. CBasePlayer *pPlayer = ToBasePlayer( pActivator );
  2467. if ( pPlayer )
  2468. {
  2469. if ( HasSpawnFlags( SF_PHYSPROP_ENABLE_PICKUP_OUTPUT ) )
  2470. {
  2471. m_OnPlayerUse.FireOutput( this, this );
  2472. }
  2473. pPlayer->PickupObject( this );
  2474. }
  2475. }
  2476. //-----------------------------------------------------------------------------
  2477. // Purpose:
  2478. // Input : *pPhysics -
  2479. //-----------------------------------------------------------------------------
  2480. void CPhysicsProp::VPhysicsUpdate( IPhysicsObject *pPhysics )
  2481. {
  2482. BaseClass::VPhysicsUpdate( pPhysics );
  2483. m_bAwake = !pPhysics->IsAsleep();
  2484. NetworkStateChanged();
  2485. if ( HasSpawnFlags( SF_PHYSPROP_START_ASLEEP ) )
  2486. {
  2487. if ( m_bAwake )
  2488. {
  2489. m_OnAwakened.FireOutput(this, this);
  2490. RemoveSpawnFlags( SF_PHYSPROP_START_ASLEEP );
  2491. }
  2492. }
  2493. // If we're asleep, clear the player thrown flag
  2494. if ( m_bThrownByPlayer && !m_bAwake )
  2495. {
  2496. m_bThrownByPlayer = false;
  2497. }
  2498. if ( !IsInWorld() )
  2499. {
  2500. m_OnOutOfWorld.FireOutput( this, this );
  2501. }
  2502. }
  2503. //-----------------------------------------------------------------------------
  2504. // Purpose:
  2505. //-----------------------------------------------------------------------------
  2506. void CPhysicsProp::ClearFlagsThink( void )
  2507. {
  2508. // collision may have destroyed the physics object, recheck
  2509. if ( VPhysicsGetObject() )
  2510. {
  2511. PhysClearGameFlags( VPhysicsGetObject(), FVPHYSICS_WAS_THROWN );
  2512. }
  2513. SetContextThink( NULL, 0, "PROP_CLEARFLAGS" );
  2514. }
  2515. //-----------------------------------------------------------------------------
  2516. // Compute impulse to apply to the enabled entity.
  2517. //-----------------------------------------------------------------------------
  2518. void CPhysicsProp::ComputeEnablingImpulse( int index, gamevcollisionevent_t *pEvent )
  2519. {
  2520. // Surface speed of the object that hit us = v + w x r
  2521. // NOTE: w is specified in local space
  2522. Vector vecContactPoint, vecLocalContactPoint;
  2523. pEvent->pInternalData->GetContactPoint( vecContactPoint );
  2524. // Compute the angular component of velocity
  2525. IPhysicsObject *pImpactObject = pEvent->pObjects[!index];
  2526. pImpactObject->WorldToLocal( &vecLocalContactPoint, vecContactPoint );
  2527. vecLocalContactPoint -= pImpactObject->GetMassCenterLocalSpace();
  2528. Vector vecLocalContactVelocity, vecContactVelocity;
  2529. AngularImpulse vecAngularVelocity = pEvent->preAngularVelocity[!index];
  2530. vecAngularVelocity *= M_PI / 180.0f;
  2531. CrossProduct( vecAngularVelocity, vecLocalContactPoint, vecLocalContactVelocity );
  2532. pImpactObject->LocalToWorldVector( &vecContactVelocity, vecLocalContactVelocity );
  2533. // Add in the center-of-mass velocity
  2534. vecContactVelocity += pEvent->preVelocity[!index];
  2535. // Compute the force + torque to apply
  2536. vecContactVelocity *= pImpactObject->GetMass();
  2537. Vector vecForce;
  2538. AngularImpulse vecTorque;
  2539. pEvent->pObjects[index]->CalculateForceOffset( vecContactVelocity, vecContactPoint, &vecForce, &vecTorque );
  2540. PhysCallbackImpulse( pEvent->pObjects[index], vecForce, vecTorque );
  2541. }
  2542. //-----------------------------------------------------------------------------
  2543. // Purpose:
  2544. //-----------------------------------------------------------------------------
  2545. void CPhysicsProp::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent )
  2546. {
  2547. BaseClass::VPhysicsCollision( index, pEvent );
  2548. IPhysicsObject *pPhysObj = pEvent->pObjects[!index];
  2549. if ( m_flForceToEnableMotion )
  2550. {
  2551. CBaseEntity *pOther = static_cast<CBaseEntity *>(pPhysObj->GetGameData());
  2552. // Don't allow the player to bump an object active if we've requested not to
  2553. if ( ( pOther && pOther->IsPlayer() && HasSpawnFlags( SF_PHYSPROP_PREVENT_PLAYER_TOUCH_ENABLE ) ) == false )
  2554. {
  2555. // Large enough to enable motion?
  2556. float flForce = pEvent->collisionSpeed * pPhysObj->GetMass();
  2557. if ( flForce >= m_flForceToEnableMotion )
  2558. {
  2559. ComputeEnablingImpulse( index, pEvent );
  2560. EnableMotion();
  2561. m_flForceToEnableMotion = 0;
  2562. }
  2563. }
  2564. }
  2565. if( m_bFirstCollisionAfterLaunch )
  2566. {
  2567. HandleFirstCollisionInteractions( index, pEvent );
  2568. }
  2569. if ( HasPhysicsAttacker( 2.0f ) )
  2570. {
  2571. HandleAnyCollisionInteractions( index, pEvent );
  2572. }
  2573. if ( !HasSpawnFlags( SF_PHYSPROP_DONT_TAKE_PHYSICS_DAMAGE ) )
  2574. {
  2575. int damageType = 0;
  2576. IBreakableWithPropData *pBreakableInterface = assert_cast<IBreakableWithPropData*>(this);
  2577. float damage = CalculateDefaultPhysicsDamage( index, pEvent, m_impactEnergyScale, true, damageType, pBreakableInterface->GetPhysicsDamageTable() );
  2578. if ( damage > 0 )
  2579. {
  2580. // Take extra damage after we're punted by the physcannon
  2581. if ( m_bFirstCollisionAfterLaunch && !m_bThrownByPlayer )
  2582. {
  2583. damage *= 10;
  2584. }
  2585. CBaseEntity *pHitEntity = pEvent->pEntities[!index];
  2586. if ( !pHitEntity )
  2587. {
  2588. // hit world
  2589. pHitEntity = GetContainingEntity( INDEXENT(0) );
  2590. }
  2591. Vector damagePos;
  2592. pEvent->pInternalData->GetContactPoint( damagePos );
  2593. Vector damageForce = pEvent->postVelocity[index] * pEvent->pObjects[index]->GetMass();
  2594. if ( damageForce == vec3_origin )
  2595. {
  2596. // This can happen if this entity is motion disabled, and can't move.
  2597. // Use the velocity of the entity that hit us instead.
  2598. damageForce = pEvent->postVelocity[!index] * pEvent->pObjects[!index]->GetMass();
  2599. }
  2600. // FIXME: this doesn't pass in who is responsible if some other entity "caused" this collision
  2601. PhysCallbackDamage( this, CTakeDamageInfo( pHitEntity, pHitEntity, damageForce, damagePos, damage, damageType ), *pEvent, index );
  2602. }
  2603. }
  2604. if ( m_bThrownByPlayer || m_bFirstCollisionAfterLaunch )
  2605. {
  2606. // If we were thrown by a player, and we've hit an NPC, let the NPC know
  2607. CBaseEntity *pHitEntity = pEvent->pEntities[!index];
  2608. if ( pHitEntity && pHitEntity->MyNPCPointer() )
  2609. {
  2610. pHitEntity->MyNPCPointer()->DispatchInteraction( g_interactionHitByPlayerThrownPhysObj, this, NULL );
  2611. m_bThrownByPlayer = false;
  2612. }
  2613. }
  2614. if ( m_bFirstCollisionAfterLaunch )
  2615. {
  2616. m_bFirstCollisionAfterLaunch = false;
  2617. // Setup the think function to remove the flags
  2618. RegisterThinkContext( "PROP_CLEARFLAGS" );
  2619. SetContextThink( &CPhysicsProp::ClearFlagsThink, gpGlobals->curtime, "PROP_CLEARFLAGS" );
  2620. }
  2621. }
  2622. //-----------------------------------------------------------------------------
  2623. // Purpose:
  2624. //-----------------------------------------------------------------------------
  2625. int CPhysicsProp::OnTakeDamage( const CTakeDamageInfo &info )
  2626. {
  2627. // note: if motion is disabled, OnTakeDamage can't apply physics force
  2628. int ret = BaseClass::OnTakeDamage( info );
  2629. if( IsOnFire() )
  2630. {
  2631. if( (info.GetDamageType() & DMG_BURN) && (info.GetDamageType() & DMG_DIRECT) )
  2632. {
  2633. // Burning! scare things in my path if I'm moving.
  2634. Vector vel;
  2635. if( VPhysicsGetObject() )
  2636. {
  2637. VPhysicsGetObject()->GetVelocity( &vel, NULL );
  2638. int dangerRadius = 256; // generous radius to begin with
  2639. if( hl2_episodic.GetBool() )
  2640. {
  2641. // In Episodic, burning items (such as destroyed APCs) are making very large
  2642. // danger sounds which frighten NPCs. This danger sound was designed to frighten
  2643. // NPCs away from burning objects that are about to explode (barrels, etc).
  2644. // So if this item has no more health (ie, has died but hasn't exploded),
  2645. // make a smaller danger sound, just to keep NPCs away from the flames.
  2646. // I suspect this problem didn't appear in HL2 simply because we didn't have
  2647. // NPCs in such close proximity to destroyed NPCs. (sjb)
  2648. if( GetHealth() < 1 )
  2649. {
  2650. // This item has no health, but still exists. That means that it may keep
  2651. // burning, but isn't likely to explode, so don't frighten over such a large radius.
  2652. dangerRadius = 120;
  2653. }
  2654. }
  2655. trace_t tr;
  2656. UTIL_TraceLine( WorldSpaceCenter(), WorldSpaceCenter() + vel, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
  2657. CSoundEnt::InsertSound( SOUND_DANGER, tr.endpos, dangerRadius, 1.0, this, SOUNDENT_CHANNEL_REPEATED_DANGER );
  2658. }
  2659. }
  2660. }
  2661. // If we have a force to enable motion, and we're still disabled, check to see if this should enable us
  2662. if ( m_flForceToEnableMotion )
  2663. {
  2664. // Large enough to enable motion?
  2665. float flForce = info.GetDamageForce().Length();
  2666. if ( flForce >= m_flForceToEnableMotion )
  2667. {
  2668. EnableMotion();
  2669. m_flForceToEnableMotion = 0;
  2670. }
  2671. }
  2672. // Check our health against the threshold:
  2673. if( m_damageToEnableMotion > 0 && GetHealth() < m_damageToEnableMotion )
  2674. {
  2675. // only do this once
  2676. m_damageToEnableMotion = 0;
  2677. // The damage that enables motion may have been enough damage to kill me if I'm breakable
  2678. // in which case my physics object is gone.
  2679. if ( VPhysicsGetObject() != NULL )
  2680. {
  2681. EnableMotion();
  2682. VPhysicsTakeDamage( info );
  2683. }
  2684. }
  2685. return ret;
  2686. }
  2687. //-----------------------------------------------------------------------------
  2688. // Mass / mass center
  2689. //-----------------------------------------------------------------------------
  2690. void CPhysicsProp::GetMassCenter( Vector *pMassCenter )
  2691. {
  2692. if ( !VPhysicsGetObject() )
  2693. {
  2694. pMassCenter->Init();
  2695. return;
  2696. }
  2697. Vector vecLocal = VPhysicsGetObject()->GetMassCenterLocalSpace();
  2698. VectorTransform( vecLocal, EntityToWorldTransform(), *pMassCenter );
  2699. }
  2700. float CPhysicsProp::GetMass() const
  2701. {
  2702. return VPhysicsGetObject() ? VPhysicsGetObject()->GetMass() : 1.0f;
  2703. }
  2704. //-----------------------------------------------------------------------------
  2705. // Purpose: Draw any debug text overlays
  2706. // Output : Current text offset from the top
  2707. //-----------------------------------------------------------------------------
  2708. int CPhysicsProp::DrawDebugTextOverlays(void)
  2709. {
  2710. int text_offset = BaseClass::DrawDebugTextOverlays();
  2711. if (m_debugOverlays & OVERLAY_TEXT_BIT)
  2712. {
  2713. if (VPhysicsGetObject())
  2714. {
  2715. char tempstr[512];
  2716. Q_snprintf(tempstr, sizeof(tempstr),"Mass: %.2f kg / %.2f lb (%s)", VPhysicsGetObject()->GetMass(), kg2lbs(VPhysicsGetObject()->GetMass()), GetMassEquivalent(VPhysicsGetObject()->GetMass()));
  2717. EntityText( text_offset, tempstr, 0);
  2718. text_offset++;
  2719. {
  2720. vphysics_objectstress_t stressOut;
  2721. float stress = CalculateObjectStress( VPhysicsGetObject(), this, &stressOut );
  2722. Q_snprintf(tempstr, sizeof(tempstr),"Stress: %.2f (%.2f / %.2f)", stress, stressOut.exertedStress, stressOut.receivedStress );
  2723. EntityText( text_offset, tempstr, 0);
  2724. text_offset++;
  2725. }
  2726. if ( !VPhysicsGetObject()->IsMoveable() )
  2727. {
  2728. Q_snprintf(tempstr, sizeof(tempstr),"Motion Disabled" );
  2729. EntityText( text_offset, tempstr, 0);
  2730. text_offset++;
  2731. }
  2732. if ( m_iszBasePropData != NULL_STRING )
  2733. {
  2734. Q_snprintf(tempstr, sizeof(tempstr),"Base PropData: %s", STRING(m_iszBasePropData) );
  2735. EntityText( text_offset, tempstr, 0);
  2736. text_offset++;
  2737. }
  2738. if ( m_iNumBreakableChunks != 0 )
  2739. {
  2740. IBreakableWithPropData *pBreakableInterface = assert_cast<IBreakableWithPropData*>(this);
  2741. Q_snprintf(tempstr, sizeof(tempstr),"Breakable Chunks: %d (Max Size %d)", m_iNumBreakableChunks, pBreakableInterface->GetMaxBreakableSize() );
  2742. EntityText( text_offset, tempstr, 0);
  2743. text_offset++;
  2744. }
  2745. Q_snprintf(tempstr, sizeof(tempstr),"Skin: %d", m_nSkin.Get() );
  2746. EntityText( text_offset, tempstr, 0);
  2747. text_offset++;
  2748. Q_snprintf(tempstr, sizeof(tempstr),"Health: %d, collision group %d", GetHealth(), GetCollisionGroup() );
  2749. EntityText( text_offset, tempstr, 0);
  2750. text_offset++;
  2751. }
  2752. }
  2753. return text_offset;
  2754. }
  2755. static CBreakableProp *BreakModelCreate_Prop( CBaseEntity *pOwner, breakmodel_t *pModel, const Vector &position, const QAngle &angles, const breakablepropparams_t &params )
  2756. {
  2757. CBreakableProp *pEntity = (CBreakableProp *)CBaseEntity::CreateNoSpawn( "prop_physics", position, angles, pOwner );
  2758. if ( pEntity )
  2759. {
  2760. // UNDONE: Allow .qc to override spawnflags for child pieces
  2761. if ( pOwner )
  2762. {
  2763. pEntity->AddSpawnFlags( pOwner->GetSpawnFlags() );
  2764. // We never want to be motion disabled
  2765. pEntity->RemoveSpawnFlags( SF_PHYSPROP_MOTIONDISABLED );
  2766. }
  2767. pEntity->m_impactEnergyScale = params.impactEnergyScale; // assume the same material
  2768. // Inherit the base object's damage modifiers
  2769. CBreakableProp *pBreakableOwner = dynamic_cast<CBreakableProp *>(pOwner);
  2770. if ( pBreakableOwner )
  2771. {
  2772. pEntity->SetDmgModBullet( pBreakableOwner->GetDmgModBullet() );
  2773. pEntity->SetDmgModClub( pBreakableOwner->GetDmgModClub() );
  2774. pEntity->SetDmgModExplosive( pBreakableOwner->GetDmgModExplosive() );
  2775. // Copy over the dx7 fade too
  2776. pEntity->CopyFadeFrom( pBreakableOwner );
  2777. }
  2778. pEntity->SetModelName( AllocPooledString( pModel->modelName ) );
  2779. pEntity->SetModel( STRING(pEntity->GetModelName()) );
  2780. pEntity->SetCollisionGroup( pModel->collisionGroup );
  2781. if ( pModel->fadeMinDist > 0 && pModel->fadeMaxDist >= pModel->fadeMinDist )
  2782. {
  2783. pEntity->SetFadeDistance( pModel->fadeMinDist, pModel->fadeMaxDist );
  2784. }
  2785. if ( pModel->fadeTime != 0 )
  2786. {
  2787. pEntity->AddSpawnFlags( SF_PHYSPROP_IS_GIB );
  2788. }
  2789. pEntity->Spawn();
  2790. // If we're burning, break into burning pieces
  2791. CBaseAnimating *pAnimating = dynamic_cast<CBreakableProp *>(pOwner);
  2792. if ( pAnimating && pAnimating->IsOnFire() )
  2793. {
  2794. CEntityFlame *pOwnerFlame = dynamic_cast<CEntityFlame*>( pAnimating->GetEffectEntity() );
  2795. if ( pOwnerFlame )
  2796. {
  2797. pEntity->Ignite( pOwnerFlame->GetRemainingLife(), false );
  2798. pEntity->IgniteNumHitboxFires( pOwnerFlame->GetNumHitboxFires() );
  2799. pEntity->IgniteHitboxFireScale( pOwnerFlame->GetHitboxFireScale() );
  2800. }
  2801. else
  2802. {
  2803. // This should never happen
  2804. pEntity->Ignite( random->RandomFloat( 5, 10 ), false );
  2805. }
  2806. }
  2807. }
  2808. return pEntity;
  2809. }
  2810. static CBaseAnimating *BreakModelCreate_Ragdoll( CBaseEntity *pOwner, breakmodel_t *pModel, const Vector &position, const QAngle &angles )
  2811. {
  2812. CBaseAnimating *pAnimating = CreateServerRagdollSubmodel( dynamic_cast<CBaseAnimating *>(pOwner), pModel->modelName, position, angles, pModel->collisionGroup );
  2813. return pAnimating;
  2814. }
  2815. CBaseEntity *BreakModelCreateSingle( CBaseEntity *pOwner, breakmodel_t *pModel, const Vector &position,
  2816. const QAngle &angles, const Vector &velocity, const AngularImpulse &angVelocity, int nSkin, const breakablepropparams_t &params )
  2817. {
  2818. CBaseAnimating *pEntity = NULL;
  2819. // stop creating gibs if too many
  2820. if ( g_ActiveGibCount >= ACTIVE_GIB_LIMIT )
  2821. {
  2822. //DevMsg(1,"Gib limit on %s\n", pModel->modelName );
  2823. return NULL;
  2824. }
  2825. if ( !pModel->isRagdoll )
  2826. {
  2827. pEntity = BreakModelCreate_Prop( pOwner, pModel, position, angles, params );
  2828. }
  2829. else
  2830. {
  2831. pEntity = BreakModelCreate_Ragdoll( pOwner, pModel, position, angles );
  2832. }
  2833. if ( pEntity )
  2834. {
  2835. pEntity->m_nSkin = nSkin;
  2836. pEntity->m_iHealth = pModel->health;
  2837. if ( g_ActiveGibCount >= ACTIVE_GIB_FADE )
  2838. {
  2839. pModel->fadeTime = MIN( 3, pModel->fadeTime );
  2840. }
  2841. if ( pModel->fadeTime )
  2842. {
  2843. pEntity->SUB_StartFadeOut( pModel->fadeTime, false );
  2844. CBreakableProp *pProp = dynamic_cast<CBreakableProp *>(pEntity);
  2845. if ( pProp && !pProp->GetNumBreakableChunks() && pProp->m_takedamage == DAMAGE_YES )
  2846. {
  2847. pProp->m_takedamage = DAMAGE_EVENTS_ONLY;
  2848. }
  2849. }
  2850. IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT];
  2851. int count = pEntity->VPhysicsGetObjectList( pList, ARRAYSIZE(pList) );
  2852. if ( count )
  2853. {
  2854. for ( int i = 0; i < count; i++ )
  2855. {
  2856. pList[i]->SetVelocity( &velocity, &angVelocity );
  2857. }
  2858. }
  2859. else
  2860. {
  2861. // failed to create a physics object
  2862. UTIL_Remove( pEntity );
  2863. return NULL;
  2864. }
  2865. }
  2866. return pEntity;
  2867. }
  2868. class CBreakModelsPrecached : public CAutoGameSystem
  2869. {
  2870. public:
  2871. CBreakModelsPrecached() : CAutoGameSystem( "CBreakModelsPrecached" )
  2872. {
  2873. m_modelList.SetLessFunc( BreakLessFunc );
  2874. }
  2875. struct breakable_precache_t
  2876. {
  2877. string_t iszModelName;
  2878. int iBreakableCount;
  2879. };
  2880. static bool BreakLessFunc( breakable_precache_t const &lhs, breakable_precache_t const &rhs )
  2881. {
  2882. return ( lhs.iszModelName.ToCStr() < rhs.iszModelName.ToCStr() );
  2883. }
  2884. bool IsInList( string_t modelName, int *iBreakableCount )
  2885. {
  2886. breakable_precache_t sEntry;
  2887. sEntry.iszModelName = modelName;
  2888. int iEntry = m_modelList.Find(sEntry);
  2889. if ( iEntry != m_modelList.InvalidIndex() )
  2890. {
  2891. *iBreakableCount = m_modelList[iEntry].iBreakableCount;
  2892. return true;
  2893. }
  2894. return false;
  2895. }
  2896. void AddToList( string_t modelName, int iBreakableCount )
  2897. {
  2898. breakable_precache_t sEntry;
  2899. sEntry.iszModelName = modelName;
  2900. sEntry.iBreakableCount = iBreakableCount;
  2901. m_modelList.Insert( sEntry );
  2902. }
  2903. void LevelShutdownPostEntity()
  2904. {
  2905. m_modelList.RemoveAll();
  2906. }
  2907. private:
  2908. CUtlRBTree<breakable_precache_t> m_modelList;
  2909. };
  2910. static CBreakModelsPrecached g_BreakModelsPrecached;
  2911. int PropBreakablePrecacheAll( string_t modelName )
  2912. {
  2913. int iBreakables = 0;
  2914. if ( g_BreakModelsPrecached.IsInList( modelName, &iBreakables ) )
  2915. return iBreakables;
  2916. if ( modelName == NULL_STRING )
  2917. {
  2918. Msg("Trying to precache breakable prop, but has no model name\n");
  2919. return iBreakables;
  2920. }
  2921. int modelIndex = CBaseEntity::PrecacheModel( STRING(modelName) );
  2922. CUtlVector<breakmodel_t> list;
  2923. BreakModelList( list, modelIndex, COLLISION_GROUP_NONE, 0 );
  2924. iBreakables = list.Count();
  2925. g_BreakModelsPrecached.AddToList( modelName, iBreakables );
  2926. for ( int i = 0; i < iBreakables; i++ )
  2927. {
  2928. string_t breakModelName = AllocPooledString(list[i].modelName);
  2929. if ( modelIndex <= 0 )
  2930. {
  2931. iBreakables--;
  2932. continue;
  2933. }
  2934. PropBreakablePrecacheAll( breakModelName );
  2935. }
  2936. return iBreakables;
  2937. }
  2938. bool PropBreakableCapEdictsOnCreateAll(int modelindex, IPhysicsObject *pPhysics, const breakablepropparams_t &params, CBaseEntity *pEntity, int iPrecomputedBreakableCount = -1 )
  2939. {
  2940. // @Note (toml 10-07-03): this is stop-gap to prevent this function from crashing the engine
  2941. const int BREATHING_ROOM = 64;
  2942. CUtlVector<breakmodel_t> list;
  2943. BreakModelList( list, modelindex, params.defBurstScale, params.defCollisionGroup );
  2944. int numToCreate = 0;
  2945. if ( iPrecomputedBreakableCount != -1 )
  2946. {
  2947. numToCreate = iPrecomputedBreakableCount;
  2948. }
  2949. else
  2950. {
  2951. if ( list.Count() )
  2952. {
  2953. for ( int i = 0; i < list.Count(); i++ )
  2954. {
  2955. int modelIndex = modelinfo->GetModelIndex( list[i].modelName );
  2956. if ( modelIndex <= 0 )
  2957. continue;
  2958. numToCreate++;
  2959. }
  2960. }
  2961. // Then see if the propdata specifies any breakable pieces
  2962. else if ( pEntity )
  2963. {
  2964. IBreakableWithPropData *pBreakableInterface = dynamic_cast<IBreakableWithPropData*>(pEntity);
  2965. if ( pBreakableInterface && pBreakableInterface->GetBreakableModel() != NULL_STRING && pBreakableInterface->GetBreakableCount() )
  2966. {
  2967. numToCreate += pBreakableInterface->GetBreakableCount();
  2968. }
  2969. }
  2970. }
  2971. return ( !numToCreate || ( engine->GetEntityCount() + numToCreate + BREATHING_ROOM < MAX_EDICTS ) );
  2972. }
  2973. //=============================================================================================================
  2974. // BASE PROP DOOR
  2975. //=============================================================================================================
  2976. //
  2977. // Private activities.
  2978. //
  2979. static int ACT_DOOR_OPEN = 0;
  2980. static int ACT_DOOR_LOCKED = 0;
  2981. //
  2982. // Anim events.
  2983. //
  2984. enum
  2985. {
  2986. AE_DOOR_OPEN = 1, // The door should start opening.
  2987. };
  2988. void PlayLockSounds(CBaseEntity *pEdict, locksound_t *pls, int flocked, int fbutton);
  2989. BEGIN_DATADESC_NO_BASE(locksound_t)
  2990. DEFINE_FIELD( sLockedSound, FIELD_STRING),
  2991. DEFINE_FIELD( sLockedSentence, FIELD_STRING ),
  2992. DEFINE_FIELD( sUnlockedSound, FIELD_STRING ),
  2993. DEFINE_FIELD( sUnlockedSentence, FIELD_STRING ),
  2994. DEFINE_FIELD( iLockedSentence, FIELD_INTEGER ),
  2995. DEFINE_FIELD( iUnlockedSentence, FIELD_INTEGER ),
  2996. DEFINE_FIELD( flwaitSound, FIELD_FLOAT ),
  2997. DEFINE_FIELD( flwaitSentence, FIELD_FLOAT ),
  2998. DEFINE_FIELD( bEOFLocked, FIELD_CHARACTER ),
  2999. DEFINE_FIELD( bEOFUnlocked, FIELD_CHARACTER ),
  3000. END_DATADESC()
  3001. BEGIN_DATADESC(CBasePropDoor)
  3002. //DEFINE_FIELD(m_bLockedSentence, FIELD_CHARACTER),
  3003. //DEFINE_FIELD(m_bUnlockedSentence, FIELD_CHARACTER),
  3004. DEFINE_KEYFIELD(m_nHardwareType, FIELD_INTEGER, "hardware"),
  3005. DEFINE_KEYFIELD(m_flAutoReturnDelay, FIELD_FLOAT, "returndelay"),
  3006. DEFINE_FIELD( m_hActivator, FIELD_EHANDLE ),
  3007. DEFINE_KEYFIELD(m_SoundMoving, FIELD_SOUNDNAME, "soundmoveoverride"),
  3008. DEFINE_KEYFIELD(m_SoundOpen, FIELD_SOUNDNAME, "soundopenoverride"),
  3009. DEFINE_KEYFIELD(m_SoundClose, FIELD_SOUNDNAME, "soundcloseoverride"),
  3010. DEFINE_KEYFIELD(m_ls.sLockedSound, FIELD_SOUNDNAME, "soundlockedoverride"),
  3011. DEFINE_KEYFIELD(m_ls.sUnlockedSound, FIELD_SOUNDNAME, "soundunlockedoverride"),
  3012. DEFINE_KEYFIELD(m_SlaveName, FIELD_STRING, "slavename" ),
  3013. DEFINE_FIELD(m_bLocked, FIELD_BOOLEAN),
  3014. //DEFINE_KEYFIELD(m_flBlockDamage, FIELD_FLOAT, "dmg"),
  3015. DEFINE_KEYFIELD( m_bForceClosed, FIELD_BOOLEAN, "forceclosed" ),
  3016. DEFINE_FIELD(m_eDoorState, FIELD_INTEGER),
  3017. DEFINE_FIELD( m_hMaster, FIELD_EHANDLE ),
  3018. DEFINE_FIELD( m_hBlocker, FIELD_EHANDLE ),
  3019. DEFINE_FIELD( m_bFirstBlocked, FIELD_BOOLEAN ),
  3020. //DEFINE_FIELD(m_hDoorList, FIELD_CLASSPTR), // Reconstructed
  3021. DEFINE_INPUTFUNC(FIELD_VOID, "Open", InputOpen),
  3022. DEFINE_INPUTFUNC(FIELD_STRING, "OpenAwayFrom", InputOpenAwayFrom),
  3023. DEFINE_INPUTFUNC(FIELD_VOID, "Close", InputClose),
  3024. DEFINE_INPUTFUNC(FIELD_VOID, "Toggle", InputToggle),
  3025. DEFINE_INPUTFUNC(FIELD_VOID, "Lock", InputLock),
  3026. DEFINE_INPUTFUNC(FIELD_VOID, "Unlock", InputUnlock),
  3027. DEFINE_OUTPUT(m_OnBlockedOpening, "OnBlockedOpening"),
  3028. DEFINE_OUTPUT(m_OnBlockedClosing, "OnBlockedClosing"),
  3029. DEFINE_OUTPUT(m_OnUnblockedOpening, "OnUnblockedOpening"),
  3030. DEFINE_OUTPUT(m_OnUnblockedClosing, "OnUnblockedClosing"),
  3031. DEFINE_OUTPUT(m_OnFullyClosed, "OnFullyClosed"),
  3032. DEFINE_OUTPUT(m_OnFullyOpen, "OnFullyOpen"),
  3033. DEFINE_OUTPUT(m_OnClose, "OnClose"),
  3034. DEFINE_OUTPUT(m_OnOpen, "OnOpen"),
  3035. DEFINE_OUTPUT(m_OnLockedUse, "OnLockedUse" ),
  3036. DEFINE_EMBEDDED( m_ls ),
  3037. // Function Pointers
  3038. DEFINE_THINKFUNC(DoorOpenMoveDone),
  3039. DEFINE_THINKFUNC(DoorCloseMoveDone),
  3040. DEFINE_THINKFUNC(DoorAutoCloseThink),
  3041. END_DATADESC()
  3042. IMPLEMENT_SERVERCLASS_ST(CBasePropDoor, DT_BasePropDoor)
  3043. END_SEND_TABLE()
  3044. CBasePropDoor::CBasePropDoor( void )
  3045. {
  3046. m_hMaster = NULL;
  3047. }
  3048. //-----------------------------------------------------------------------------
  3049. // Purpose:
  3050. //-----------------------------------------------------------------------------
  3051. void CBasePropDoor::Spawn()
  3052. {
  3053. BaseClass::Spawn();
  3054. DisableAutoFade();
  3055. Precache();
  3056. DoorTeleportToSpawnPosition();
  3057. if (HasSpawnFlags(SF_DOOR_LOCKED))
  3058. {
  3059. m_bLocked = true;
  3060. }
  3061. SetMoveType(MOVETYPE_PUSH);
  3062. if (m_flSpeed == 0)
  3063. {
  3064. m_flSpeed = 100;
  3065. }
  3066. RemoveFlag(FL_STATICPROP);
  3067. SetSolid(SOLID_VPHYSICS);
  3068. VPhysicsInitShadow(false, false);
  3069. AddSolidFlags( FSOLID_CUSTOMRAYTEST | FSOLID_CUSTOMBOXTEST );
  3070. SetBodygroup( DOOR_HARDWARE_GROUP, m_nHardwareType );
  3071. if ((m_nHardwareType == 0) && (!HasSpawnFlags(SF_DOOR_LOCKED)))
  3072. {
  3073. // Doors with no hardware must always be locked.
  3074. DevWarning(1, "Unlocked prop_door '%s' at (%.0f %.0f %.0f) has no hardware. All openable doors must have hardware!\n", GetDebugName(), GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z);
  3075. }
  3076. if ( !PropDataOverrodeBlockLOS() )
  3077. {
  3078. CalculateBlockLOS();
  3079. }
  3080. SetDoorBlocker( NULL );
  3081. // Fills out the m_Soundxxx members.
  3082. CalcDoorSounds();
  3083. }
  3084. //-----------------------------------------------------------------------------
  3085. // Purpose: Returns our capabilities mask.
  3086. //-----------------------------------------------------------------------------
  3087. int CBasePropDoor::ObjectCaps()
  3088. {
  3089. return BaseClass::ObjectCaps() | ( HasSpawnFlags( SF_DOOR_IGNORE_USE ) ? 0 : (FCAP_IMPULSE_USE|FCAP_USE_IN_RADIUS) );
  3090. };
  3091. //-----------------------------------------------------------------------------
  3092. // Purpose:
  3093. //-----------------------------------------------------------------------------
  3094. void CBasePropDoor::Precache(void)
  3095. {
  3096. BaseClass::Precache();
  3097. RegisterPrivateActivities();
  3098. }
  3099. //-----------------------------------------------------------------------------
  3100. // Purpose:
  3101. //-----------------------------------------------------------------------------
  3102. void CBasePropDoor::RegisterPrivateActivities(void)
  3103. {
  3104. static bool bRegistered = false;
  3105. if (bRegistered)
  3106. return;
  3107. REGISTER_PRIVATE_ACTIVITY( ACT_DOOR_OPEN );
  3108. REGISTER_PRIVATE_ACTIVITY( ACT_DOOR_LOCKED );
  3109. }
  3110. //-----------------------------------------------------------------------------
  3111. // Purpose:
  3112. //-----------------------------------------------------------------------------
  3113. void CBasePropDoor::Activate( void )
  3114. {
  3115. BaseClass::Activate();
  3116. UpdateAreaPortals( !IsDoorClosed() );
  3117. // If we have a name, we may be linked
  3118. if ( GetEntityName() != NULL_STRING )
  3119. {
  3120. CBaseEntity *pTarget = NULL;
  3121. // Find our slaves.
  3122. // If we have a specified slave name, then use that to find slaves.
  3123. // Otherwise, see if there are any other doors that match our name (Backwards compatability).
  3124. string_t iszSearchName = GetEntityName();
  3125. if ( m_SlaveName != NULL_STRING )
  3126. {
  3127. const char *pSlaveName = STRING(m_SlaveName);
  3128. if ( pSlaveName && pSlaveName[0] )
  3129. {
  3130. iszSearchName = m_SlaveName;
  3131. }
  3132. }
  3133. while ( ( pTarget = gEntList.FindEntityByName( pTarget, iszSearchName ) ) != NULL )
  3134. {
  3135. if ( pTarget != this )
  3136. {
  3137. CBasePropDoor *pDoor = dynamic_cast<CBasePropDoor *>(pTarget);
  3138. if ( pDoor != NULL && pDoor->HasSlaves() == false )
  3139. {
  3140. m_hDoorList.AddToTail( pDoor );
  3141. pDoor->SetMaster( this );
  3142. pDoor->SetOwnerEntity( this );
  3143. }
  3144. }
  3145. }
  3146. }
  3147. }
  3148. //-----------------------------------------------------------------------------
  3149. // Purpose:
  3150. //-----------------------------------------------------------------------------
  3151. void CBasePropDoor::HandleAnimEvent(animevent_t *pEvent)
  3152. {
  3153. // Opening is called here via an animation event if the open sequence has one,
  3154. // otherwise it is called immediately when the open sequence is set.
  3155. if (pEvent->event == AE_DOOR_OPEN)
  3156. {
  3157. DoorActivate();
  3158. }
  3159. }
  3160. // Only overwrite str1 if it's NULL_STRING.
  3161. #define ASSIGN_STRING_IF_NULL( str1, str2 ) \
  3162. if ( ( str1 ) == NULL_STRING ) { ( str1 ) = ( str2 ); }
  3163. //-----------------------------------------------------------------------------
  3164. // Purpose:
  3165. //-----------------------------------------------------------------------------
  3166. void CBasePropDoor::CalcDoorSounds()
  3167. {
  3168. ErrorIfNot( GetModel() != NULL, ( "prop_door with no model at %.2f %.2f %.2f\n", GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z ) );
  3169. string_t strSoundOpen = NULL_STRING;
  3170. string_t strSoundClose = NULL_STRING;
  3171. string_t strSoundMoving = NULL_STRING;
  3172. string_t strSoundLocked = NULL_STRING;
  3173. string_t strSoundUnlocked = NULL_STRING;
  3174. bool bFoundSkin = false;
  3175. // Otherwise, use the sounds specified by the model keyvalues. These are looked up
  3176. // based on skin and hardware.
  3177. KeyValues *modelKeyValues = new KeyValues("");
  3178. if ( modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( GetModel() ), modelinfo->GetModelKeyValueText( GetModel() ) ) )
  3179. {
  3180. KeyValues *pkvDoorSounds = modelKeyValues->FindKey("door_options");
  3181. if ( pkvDoorSounds )
  3182. {
  3183. // Open / close / move sounds are looked up by skin index.
  3184. char szSkin[80];
  3185. int skin = m_nSkin;
  3186. Q_snprintf( szSkin, sizeof( szSkin ), "skin%d", skin );
  3187. KeyValues *pkvSkinData = pkvDoorSounds->FindKey( szSkin );
  3188. if ( pkvSkinData )
  3189. {
  3190. strSoundOpen = AllocPooledString( pkvSkinData->GetString( "open" ) );
  3191. strSoundClose = AllocPooledString( pkvSkinData->GetString( "close" ) );
  3192. strSoundMoving = AllocPooledString( pkvSkinData->GetString( "move" ) );
  3193. const char *pSurfaceprop = pkvSkinData->GetString( "surfaceprop" );
  3194. if ( pSurfaceprop && VPhysicsGetObject() )
  3195. {
  3196. bFoundSkin = true;
  3197. VPhysicsGetObject()->SetMaterialIndex( physprops->GetSurfaceIndex( pSurfaceprop ) );
  3198. }
  3199. }
  3200. // Locked / unlocked sounds are looked up by hardware index.
  3201. char szHardware[80];
  3202. Q_snprintf( szHardware, sizeof( szHardware ), "hardware%d", m_nHardwareType );
  3203. KeyValues *pkvHardwareData = pkvDoorSounds->FindKey( szHardware );
  3204. if ( pkvHardwareData )
  3205. {
  3206. strSoundLocked = AllocPooledString( pkvHardwareData->GetString( "locked" ) );
  3207. strSoundUnlocked = AllocPooledString( pkvHardwareData->GetString( "unlocked" ) );
  3208. }
  3209. // If any sounds were missing, try the "defaults" block.
  3210. if ( ( strSoundOpen == NULL_STRING ) || ( strSoundClose == NULL_STRING ) || ( strSoundMoving == NULL_STRING ) ||
  3211. ( strSoundLocked == NULL_STRING ) || ( strSoundUnlocked == NULL_STRING ) )
  3212. {
  3213. KeyValues *pkvDefaults = pkvDoorSounds->FindKey( "defaults" );
  3214. if ( pkvDefaults )
  3215. {
  3216. ASSIGN_STRING_IF_NULL( strSoundOpen, AllocPooledString( pkvDefaults->GetString( "open" ) ) );
  3217. ASSIGN_STRING_IF_NULL( strSoundClose, AllocPooledString( pkvDefaults->GetString( "close" ) ) );
  3218. ASSIGN_STRING_IF_NULL( strSoundMoving, AllocPooledString( pkvDefaults->GetString( "move" ) ) );
  3219. ASSIGN_STRING_IF_NULL( strSoundLocked, AllocPooledString( pkvDefaults->GetString( "locked" ) ) );
  3220. ASSIGN_STRING_IF_NULL( strSoundUnlocked, AllocPooledString( pkvDefaults->GetString( "unlocked" ) ) );
  3221. // NOTE: No default needed for surfaceprop, it's set by the model
  3222. }
  3223. }
  3224. }
  3225. }
  3226. modelKeyValues->deleteThis();
  3227. modelKeyValues = NULL;
  3228. if ( !bFoundSkin && VPhysicsGetObject() )
  3229. {
  3230. Warning( "%s has Door model (%s) with no door_options! Verify that SKIN is valid, and has a corresponding options block in the model QC file\n", GetDebugName(), modelinfo->GetModelName( GetModel() ) );
  3231. VPhysicsGetObject()->SetMaterialIndex( physprops->GetSurfaceIndex("wood") );
  3232. }
  3233. // Any sound data members that are already filled out were specified as level designer overrides,
  3234. // so they should not be overwritten.
  3235. ASSIGN_STRING_IF_NULL( m_SoundOpen, strSoundOpen );
  3236. ASSIGN_STRING_IF_NULL( m_SoundClose, strSoundClose );
  3237. ASSIGN_STRING_IF_NULL( m_SoundMoving, strSoundMoving );
  3238. ASSIGN_STRING_IF_NULL( m_ls.sLockedSound, strSoundLocked );
  3239. ASSIGN_STRING_IF_NULL( m_ls.sUnlockedSound, strSoundUnlocked );
  3240. // Make sure we have real, precachable sound names in all cases.
  3241. UTIL_ValidateSoundName( m_SoundMoving, "DoorSound.Null" );
  3242. UTIL_ValidateSoundName( m_SoundOpen, "DoorSound.Null" );
  3243. UTIL_ValidateSoundName( m_SoundClose, "DoorSound.Null" );
  3244. UTIL_ValidateSoundName( m_ls.sLockedSound, "DoorSound.Null" );
  3245. UTIL_ValidateSoundName( m_ls.sUnlockedSound, "DoorSound.Null" );
  3246. PrecacheScriptSound( STRING( m_SoundMoving ) );
  3247. PrecacheScriptSound( STRING( m_SoundOpen ) );
  3248. PrecacheScriptSound( STRING( m_SoundClose ) );
  3249. PrecacheScriptSound( STRING( m_ls.sLockedSound ) );
  3250. PrecacheScriptSound( STRING( m_ls.sUnlockedSound ) );
  3251. }
  3252. //-----------------------------------------------------------------------------
  3253. // Purpose:
  3254. // Input : isOpen -
  3255. //-----------------------------------------------------------------------------
  3256. void CBasePropDoor::UpdateAreaPortals(bool isOpen)
  3257. {
  3258. string_t name = GetEntityName();
  3259. if (!name)
  3260. return;
  3261. CBaseEntity *pPortal = NULL;
  3262. while ((pPortal = gEntList.FindEntityByClassname(pPortal, "func_areaportal")) != NULL)
  3263. {
  3264. if (pPortal->HasTarget(name))
  3265. {
  3266. // USE_ON means open the portal, off means close it
  3267. pPortal->Use(this, this, isOpen?USE_ON:USE_OFF, 0);
  3268. }
  3269. }
  3270. }
  3271. //-----------------------------------------------------------------------------
  3272. // Purpose:
  3273. // Input : state -
  3274. //-----------------------------------------------------------------------------
  3275. void CBasePropDoor::SetDoorBlocker( CBaseEntity *pBlocker )
  3276. {
  3277. m_hBlocker = pBlocker;
  3278. if ( m_hBlocker == NULL )
  3279. {
  3280. m_bFirstBlocked = false;
  3281. }
  3282. }
  3283. //-----------------------------------------------------------------------------
  3284. // Purpose: Called when the player uses the door.
  3285. // Input : pActivator -
  3286. // pCaller -
  3287. // useType -
  3288. // value -
  3289. //-----------------------------------------------------------------------------
  3290. void CBasePropDoor::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value)
  3291. {
  3292. if ( GetMaster() != NULL )
  3293. {
  3294. // Tell our owner we've been used
  3295. GetMaster()->Use( pActivator, pCaller, useType, value );
  3296. }
  3297. else
  3298. {
  3299. // Just let it through
  3300. OnUse( pActivator, pCaller, useType, value );
  3301. }
  3302. }
  3303. //-----------------------------------------------------------------------------
  3304. // Purpose:
  3305. // Input : *pActivator -
  3306. // *pCaller -
  3307. // useType -
  3308. // value -
  3309. //-----------------------------------------------------------------------------
  3310. void CBasePropDoor::OnUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
  3311. {
  3312. // If we're blocked while closing, open away from our blocker. This will
  3313. // liberate whatever bit of detritus is stuck in us.
  3314. if ( IsDoorBlocked() && IsDoorClosing() )
  3315. {
  3316. m_hActivator = pActivator;
  3317. DoorOpen( m_hBlocker );
  3318. return;
  3319. }
  3320. if (IsDoorClosed() || (IsDoorOpen() && HasSpawnFlags(SF_DOOR_USE_CLOSES)))
  3321. {
  3322. // Ready to be opened or closed.
  3323. if (m_bLocked)
  3324. {
  3325. PropSetSequence(SelectWeightedSequence((Activity)ACT_DOOR_LOCKED));
  3326. PlayLockSounds(this, &m_ls, TRUE, FALSE);
  3327. m_OnLockedUse.FireOutput( pActivator, pCaller );
  3328. }
  3329. else
  3330. {
  3331. m_hActivator = pActivator;
  3332. PlayLockSounds(this, &m_ls, FALSE, FALSE);
  3333. int nSequence = SelectWeightedSequence((Activity)ACT_DOOR_OPEN);
  3334. PropSetSequence(nSequence);
  3335. if ((nSequence == -1) || !HasAnimEvent(nSequence, AE_DOOR_OPEN))
  3336. {
  3337. // No open anim event, we need to open the door here.
  3338. DoorActivate();
  3339. }
  3340. }
  3341. }
  3342. else if ( IsDoorOpening() && HasSpawnFlags(SF_DOOR_USE_CLOSES) )
  3343. {
  3344. // We've been used while opening, close.
  3345. m_hActivator = pActivator;
  3346. DoorClose();
  3347. }
  3348. else if ( IsDoorClosing() || IsDoorAjar() )
  3349. {
  3350. m_hActivator = pActivator;
  3351. DoorOpen( m_hActivator );
  3352. }
  3353. }
  3354. //-----------------------------------------------------------------------------
  3355. // Purpose: Closes the door if it is not already closed.
  3356. //-----------------------------------------------------------------------------
  3357. void CBasePropDoor::InputClose(inputdata_t &inputdata)
  3358. {
  3359. if (!IsDoorClosed())
  3360. {
  3361. m_OnClose.FireOutput(inputdata.pActivator, this);
  3362. DoorClose();
  3363. }
  3364. }
  3365. //-----------------------------------------------------------------------------
  3366. // Purpose: Input handler that locks the door.
  3367. //-----------------------------------------------------------------------------
  3368. void CBasePropDoor::InputLock(inputdata_t &inputdata)
  3369. {
  3370. Lock();
  3371. }
  3372. //-----------------------------------------------------------------------------
  3373. // Purpose: Opens the door if it is not already open.
  3374. //-----------------------------------------------------------------------------
  3375. void CBasePropDoor::InputOpen(inputdata_t &inputdata)
  3376. {
  3377. OpenIfUnlocked(inputdata.pActivator, NULL);
  3378. }
  3379. //-----------------------------------------------------------------------------
  3380. // Purpose: Opens the door away from a specified entity if it is not already open.
  3381. //-----------------------------------------------------------------------------
  3382. void CBasePropDoor::InputOpenAwayFrom(inputdata_t &inputdata)
  3383. {
  3384. CBaseEntity *pOpenAwayFrom = gEntList.FindEntityByName( NULL, inputdata.value.String(), NULL, inputdata.pActivator, inputdata.pCaller );
  3385. OpenIfUnlocked(inputdata.pActivator, pOpenAwayFrom);
  3386. }
  3387. //-----------------------------------------------------------------------------
  3388. // Purpose:
  3389. //
  3390. // FIXME: This function should be combined with DoorOpen, but doing that
  3391. // could break existing content. Fix after shipping!
  3392. //
  3393. // Input : *pOpenAwayFrom -
  3394. //-----------------------------------------------------------------------------
  3395. void CBasePropDoor::OpenIfUnlocked(CBaseEntity *pActivator, CBaseEntity *pOpenAwayFrom)
  3396. {
  3397. // I'm locked, can't open
  3398. if (m_bLocked)
  3399. return;
  3400. if (!IsDoorOpen() && !IsDoorOpening())
  3401. {
  3402. // Play door unlock sounds.
  3403. PlayLockSounds(this, &m_ls, false, false);
  3404. m_OnOpen.FireOutput(pActivator, this);
  3405. DoorOpen(pOpenAwayFrom);
  3406. }
  3407. }
  3408. //-----------------------------------------------------------------------------
  3409. // Purpose: Opens the door if it is not already open.
  3410. //-----------------------------------------------------------------------------
  3411. void CBasePropDoor::InputToggle(inputdata_t &inputdata)
  3412. {
  3413. if (IsDoorClosed())
  3414. {
  3415. // I'm locked, can't open
  3416. if (m_bLocked)
  3417. return;
  3418. DoorOpen(NULL);
  3419. }
  3420. else if (IsDoorOpen())
  3421. {
  3422. DoorClose();
  3423. }
  3424. }
  3425. //-----------------------------------------------------------------------------
  3426. // Purpose: Input handler that unlocks the door.
  3427. //-----------------------------------------------------------------------------
  3428. void CBasePropDoor::InputUnlock(inputdata_t &inputdata)
  3429. {
  3430. Unlock();
  3431. }
  3432. //-----------------------------------------------------------------------------
  3433. // Purpose: Locks the door so that it cannot be opened.
  3434. //-----------------------------------------------------------------------------
  3435. void CBasePropDoor::Lock(void)
  3436. {
  3437. m_bLocked = true;
  3438. }
  3439. //-----------------------------------------------------------------------------
  3440. // Purpose: Unlocks the door so that it can be opened.
  3441. //-----------------------------------------------------------------------------
  3442. void CBasePropDoor::Unlock(void)
  3443. {
  3444. if (!m_nHardwareType)
  3445. {
  3446. // Doors with no hardware must always be locked.
  3447. DevWarning(1, "Unlocking prop_door '%s' at (%.0f %.0f %.0f) with no hardware. All openable doors must have hardware!\n", GetDebugName(), GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z);
  3448. }
  3449. m_bLocked = false;
  3450. }
  3451. //-----------------------------------------------------------------------------
  3452. // Purpose: Causes the door to "do its thing", i.e. start moving, and cascade activation.
  3453. //-----------------------------------------------------------------------------
  3454. bool CBasePropDoor::DoorActivate( void )
  3455. {
  3456. if ( IsDoorOpen() && DoorCanClose( false ) )
  3457. {
  3458. DoorClose();
  3459. }
  3460. else
  3461. {
  3462. DoorOpen( m_hActivator );
  3463. }
  3464. return true;
  3465. }
  3466. //-----------------------------------------------------------------------------
  3467. // Purpose: Starts the door opening.
  3468. //-----------------------------------------------------------------------------
  3469. void CBasePropDoor::DoorOpen(CBaseEntity *pOpenAwayFrom)
  3470. {
  3471. // Don't bother if we're already doing this
  3472. if ( IsDoorOpen() || IsDoorOpening() )
  3473. return;
  3474. UpdateAreaPortals(true);
  3475. // It could be going-down, if blocked.
  3476. ASSERT( IsDoorClosed() || IsDoorClosing() || IsDoorAjar() );
  3477. // Emit door moving and stop sounds on CHAN_STATIC so that the multicast doesn't
  3478. // filter them out and leave a client stuck with looping door sounds!
  3479. if (!HasSpawnFlags(SF_DOOR_SILENT))
  3480. {
  3481. EmitSound( STRING( m_SoundMoving ) );
  3482. if ( m_hActivator && m_hActivator->IsPlayer() && !HasSpawnFlags( SF_DOOR_SILENT_TO_NPCS ) )
  3483. {
  3484. CSoundEnt::InsertSound( SOUND_PLAYER, GetAbsOrigin(), 512, 0.5, this );//<<TODO>>//magic number
  3485. }
  3486. }
  3487. SetDoorState( DOOR_STATE_OPENING );
  3488. SetMoveDone(&CBasePropDoor::DoorOpenMoveDone);
  3489. // Virtual function that starts the door moving for whatever type of door this is.
  3490. BeginOpening(pOpenAwayFrom);
  3491. m_OnOpen.FireOutput(this, this);
  3492. // Tell all the slaves
  3493. if ( HasSlaves() )
  3494. {
  3495. int numDoors = m_hDoorList.Count();
  3496. CBasePropDoor *pLinkedDoor = NULL;
  3497. // Open all linked doors
  3498. for ( int i = 0; i < numDoors; i++ )
  3499. {
  3500. pLinkedDoor = m_hDoorList[i];
  3501. if ( pLinkedDoor != NULL )
  3502. {
  3503. // If the door isn't already moving, get it moving
  3504. pLinkedDoor->m_hActivator = m_hActivator;
  3505. pLinkedDoor->DoorOpen( pOpenAwayFrom );
  3506. }
  3507. }
  3508. }
  3509. }
  3510. //-----------------------------------------------------------------------------
  3511. // Purpose: The door has reached the open position. Either close automatically
  3512. // or wait for another activation.
  3513. //-----------------------------------------------------------------------------
  3514. void CBasePropDoor::DoorOpenMoveDone(void)
  3515. {
  3516. SetDoorBlocker( NULL );
  3517. if (!HasSpawnFlags(SF_DOOR_SILENT))
  3518. {
  3519. EmitSound( STRING( m_SoundOpen ) );
  3520. }
  3521. ASSERT(IsDoorOpening());
  3522. SetDoorState( DOOR_STATE_OPEN );
  3523. if (WillAutoReturn())
  3524. {
  3525. // In flWait seconds, DoorClose will fire, unless wait is -1, then door stays open
  3526. SetMoveDoneTime(m_flAutoReturnDelay + 0.1);
  3527. SetMoveDone(&CBasePropDoor::DoorAutoCloseThink);
  3528. if (m_flAutoReturnDelay == -1)
  3529. {
  3530. SetNextThink( TICK_NEVER_THINK );
  3531. }
  3532. }
  3533. CAI_BaseNPC *pNPC = dynamic_cast<CAI_BaseNPC *>(m_hActivator.Get());
  3534. if (pNPC)
  3535. {
  3536. // Notify the NPC that opened us.
  3537. pNPC->OnDoorFullyOpen(this);
  3538. }
  3539. m_OnFullyOpen.FireOutput(this, this);
  3540. // Let the leaf class do its thing.
  3541. OnDoorOpened();
  3542. m_hActivator = NULL;
  3543. }
  3544. //-----------------------------------------------------------------------------
  3545. // Purpose: Think function that tries to close the door. Used for autoreturn.
  3546. //-----------------------------------------------------------------------------
  3547. void CBasePropDoor::DoorAutoCloseThink(void)
  3548. {
  3549. // When autoclosing, we check both sides so that we don't close in the player's
  3550. // face, or in an NPC's face for that matter, because they might be shooting
  3551. // through the doorway.
  3552. if ( !DoorCanClose( true ) )
  3553. {
  3554. if (m_flAutoReturnDelay == -1)
  3555. {
  3556. SetNextThink( TICK_NEVER_THINK );
  3557. }
  3558. else
  3559. {
  3560. // In flWait seconds, DoorClose will fire, unless wait is -1, then door stays open
  3561. SetMoveDoneTime(m_flAutoReturnDelay + 0.1);
  3562. SetMoveDone(&CBasePropDoor::DoorAutoCloseThink);
  3563. }
  3564. return;
  3565. }
  3566. DoorClose();
  3567. }
  3568. //-----------------------------------------------------------------------------
  3569. // Purpose: Starts the door closing.
  3570. //-----------------------------------------------------------------------------
  3571. void CBasePropDoor::DoorClose(void)
  3572. {
  3573. // Don't bother if we're already doing this
  3574. if ( IsDoorClosed() || IsDoorClosing() )
  3575. return;
  3576. if (!HasSpawnFlags(SF_DOOR_SILENT))
  3577. {
  3578. EmitSound( STRING( m_SoundMoving ) );
  3579. if ( m_hActivator && m_hActivator->IsPlayer() )
  3580. {
  3581. CSoundEnt::InsertSound( SOUND_PLAYER, GetAbsOrigin(), 512, 0.5, this );//<<TODO>>//magic number
  3582. }
  3583. }
  3584. ASSERT(IsDoorOpen() || IsDoorOpening());
  3585. SetDoorState( DOOR_STATE_CLOSING );
  3586. SetMoveDone(&CBasePropDoor::DoorCloseMoveDone);
  3587. // This will set the movedone time.
  3588. BeginClosing();
  3589. m_OnClose.FireOutput(this, this);
  3590. // Tell all the slaves
  3591. if ( HasSlaves() )
  3592. {
  3593. int numDoors = m_hDoorList.Count();
  3594. CBasePropDoor *pLinkedDoor = NULL;
  3595. // Open all linked doors
  3596. for ( int i = 0; i < numDoors; i++ )
  3597. {
  3598. pLinkedDoor = m_hDoorList[i];
  3599. if ( pLinkedDoor != NULL )
  3600. {
  3601. // If the door isn't already moving, get it moving
  3602. pLinkedDoor->DoorClose();
  3603. }
  3604. }
  3605. }
  3606. }
  3607. //-----------------------------------------------------------------------------
  3608. // Purpose: The door has reached the closed position. Return to quiescence.
  3609. //-----------------------------------------------------------------------------
  3610. void CBasePropDoor::DoorCloseMoveDone(void)
  3611. {
  3612. SetDoorBlocker( NULL );
  3613. if (!HasSpawnFlags(SF_DOOR_SILENT))
  3614. {
  3615. StopSound( STRING( m_SoundMoving ) );
  3616. EmitSound( STRING( m_SoundClose ) );
  3617. }
  3618. ASSERT(IsDoorClosing());
  3619. SetDoorState( DOOR_STATE_CLOSED );
  3620. m_OnFullyClosed.FireOutput(m_hActivator, this);
  3621. UpdateAreaPortals(false);
  3622. // Let the leaf class do its thing.
  3623. OnDoorClosed();
  3624. m_hActivator = NULL;
  3625. }
  3626. //-----------------------------------------------------------------------------
  3627. // Purpose:
  3628. // Input : *pOther -
  3629. //-----------------------------------------------------------------------------
  3630. void CBasePropDoor::MasterStartBlocked( CBaseEntity *pOther )
  3631. {
  3632. if ( HasSlaves() )
  3633. {
  3634. int numDoors = m_hDoorList.Count();
  3635. CBasePropDoor *pLinkedDoor = NULL;
  3636. // Open all linked doors
  3637. for ( int i = 0; i < numDoors; i++ )
  3638. {
  3639. pLinkedDoor = m_hDoorList[i];
  3640. if ( pLinkedDoor != NULL )
  3641. {
  3642. // If the door isn't already moving, get it moving
  3643. pLinkedDoor->OnStartBlocked( pOther );
  3644. }
  3645. }
  3646. }
  3647. // Start ourselves blocked
  3648. OnStartBlocked( pOther );
  3649. }
  3650. //-----------------------------------------------------------------------------
  3651. // Purpose: Called the first frame that the door is blocked while opening or closing.
  3652. // Input : pOther - The blocking entity.
  3653. //-----------------------------------------------------------------------------
  3654. void CBasePropDoor::StartBlocked( CBaseEntity *pOther )
  3655. {
  3656. m_bFirstBlocked = true;
  3657. if ( GetMaster() != NULL )
  3658. {
  3659. GetMaster()->MasterStartBlocked( pOther );
  3660. return;
  3661. }
  3662. // Start ourselves blocked
  3663. OnStartBlocked( pOther );
  3664. }
  3665. //-----------------------------------------------------------------------------
  3666. // Purpose:
  3667. // Input : *pOther -
  3668. //-----------------------------------------------------------------------------
  3669. void CBasePropDoor::OnStartBlocked( CBaseEntity *pOther )
  3670. {
  3671. if ( m_bFirstBlocked == false )
  3672. {
  3673. DoorStop();
  3674. }
  3675. SetDoorBlocker( pOther );
  3676. if (!HasSpawnFlags(SF_DOOR_SILENT))
  3677. {
  3678. StopSound( STRING( m_SoundMoving ) );
  3679. }
  3680. //
  3681. // Fire whatever events we need to due to our blocked state.
  3682. //
  3683. if (IsDoorClosing())
  3684. {
  3685. // Closed into an NPC, open.
  3686. if ( pOther->MyNPCPointer() )
  3687. {
  3688. DoorOpen( pOther );
  3689. }
  3690. m_OnBlockedClosing.FireOutput(pOther, this);
  3691. }
  3692. else
  3693. {
  3694. // Opened into an NPC, close.
  3695. if ( pOther->MyNPCPointer() )
  3696. {
  3697. DoorClose();
  3698. }
  3699. CAI_BaseNPC *pNPC = dynamic_cast<CAI_BaseNPC *>(m_hActivator.Get());
  3700. if ( pNPC != NULL )
  3701. {
  3702. // Notify the NPC that tried to open us.
  3703. pNPC->OnDoorBlocked( this );
  3704. }
  3705. m_OnBlockedOpening.FireOutput( pOther, this );
  3706. }
  3707. }
  3708. //-----------------------------------------------------------------------------
  3709. // Purpose: Called every frame when the door is blocked while opening or closing.
  3710. // Input : pOther - The blocking entity.
  3711. //-----------------------------------------------------------------------------
  3712. void CBasePropDoor::Blocked(CBaseEntity *pOther)
  3713. {
  3714. // dvs: TODO: will prop_door apply any blocking damage?
  3715. // Hurt the blocker a little.
  3716. //if (m_flBlockDamage)
  3717. //{
  3718. // pOther->TakeDamage(CTakeDamageInfo(this, this, m_flBlockDamage, DMG_CRUSH));
  3719. //}
  3720. if ( m_bForceClosed && ( pOther->GetMoveType() == MOVETYPE_VPHYSICS ) &&
  3721. ( pOther->m_takedamage == DAMAGE_NO || pOther->m_takedamage == DAMAGE_EVENTS_ONLY ) )
  3722. {
  3723. EntityPhysics_CreateSolver( this, pOther, true, 4.0f );
  3724. }
  3725. else if ( m_bForceClosed && ( pOther->GetMoveType() == MOVETYPE_VPHYSICS ) && ( pOther->m_takedamage == DAMAGE_YES ) )
  3726. {
  3727. pOther->TakeDamage( CTakeDamageInfo( this, this, pOther->GetHealth(), DMG_CRUSH ) );
  3728. }
  3729. // If we're set to force ourselves closed, keep going
  3730. if ( m_bForceClosed )
  3731. return;
  3732. // If a door has a negative wait, it would never come back if blocked,
  3733. // so let it just squash the object to death real fast.
  3734. // if (m_flAutoReturnDelay >= 0)
  3735. // {
  3736. // if (IsDoorClosing())
  3737. // {
  3738. // DoorOpen();
  3739. // }
  3740. // else
  3741. // {
  3742. // DoorClose();
  3743. // }
  3744. // }
  3745. // Block all door pieces with the same targetname here.
  3746. // if (GetEntityName() != NULL_STRING)
  3747. // {
  3748. // CBaseEntity pTarget = NULL;
  3749. // for (;;)
  3750. // {
  3751. // pTarget = gEntList.FindEntityByName(pTarget, GetEntityName() );
  3752. //
  3753. // if (pTarget != this)
  3754. // {
  3755. // if (!pTarget)
  3756. // break;
  3757. //
  3758. // if (FClassnameIs(pTarget, "prop_door_rotating"))
  3759. // {
  3760. // CPropDoorRotating *pDoor = (CPropDoorRotating *)pTarget;
  3761. //
  3762. // if (pDoor->m_fAutoReturnDelay >= 0)
  3763. // {
  3764. // if (pDoor->GetAbsVelocity() == GetAbsVelocity() && pDoor->GetLocalAngularVelocity() == GetLocalAngularVelocity())
  3765. // {
  3766. // // this is the most hacked, evil, bastardized thing I've ever seen. kjb
  3767. // if (FClassnameIs(pTarget, "prop_door_rotating"))
  3768. // {
  3769. // // set angles to realign rotating doors
  3770. // pDoor->SetLocalAngles(GetLocalAngles());
  3771. // pDoor->SetLocalAngularVelocity(vec3_angle);
  3772. // }
  3773. // else
  3774. // //{
  3775. // // // set origin to realign normal doors
  3776. // // pDoor->SetLocalOrigin(GetLocalOrigin());
  3777. // // pDoor->SetAbsVelocity(vec3_origin);// stop!
  3778. // //}
  3779. // }
  3780. //
  3781. // if (IsDoorClosing())
  3782. // {
  3783. // pDoor->DoorOpen();
  3784. // }
  3785. // else
  3786. // {
  3787. // pDoor->DoorClose();
  3788. // }
  3789. // }
  3790. // }
  3791. // }
  3792. // }
  3793. // }
  3794. }
  3795. //-----------------------------------------------------------------------------
  3796. // Purpose: Called the first frame that the door is unblocked while opening or closing.
  3797. //-----------------------------------------------------------------------------
  3798. void CBasePropDoor::EndBlocked( void )
  3799. {
  3800. if ( GetMaster() != NULL )
  3801. {
  3802. GetMaster()->EndBlocked();
  3803. return;
  3804. }
  3805. if ( HasSlaves() )
  3806. {
  3807. int numDoors = m_hDoorList.Count();
  3808. CBasePropDoor *pLinkedDoor = NULL;
  3809. // Check all links as well
  3810. for ( int i = 0; i < numDoors; i++ )
  3811. {
  3812. pLinkedDoor = m_hDoorList[i];
  3813. if ( pLinkedDoor != NULL )
  3814. {
  3815. // Make sure they can close as well
  3816. pLinkedDoor->OnEndBlocked();
  3817. }
  3818. }
  3819. }
  3820. // Emit door moving and stop sounds on CHAN_STATIC so that the multicast doesn't
  3821. // filter them out and leave a client stuck with looping door sounds!
  3822. if (!HasSpawnFlags(SF_DOOR_SILENT))
  3823. {
  3824. EmitSound( STRING( m_SoundMoving ) );
  3825. }
  3826. //
  3827. // Fire whatever events we need to due to our unblocked state.
  3828. //
  3829. if (IsDoorClosing())
  3830. {
  3831. m_OnUnblockedClosing.FireOutput(this, this);
  3832. }
  3833. else
  3834. {
  3835. m_OnUnblockedOpening.FireOutput(this, this);
  3836. }
  3837. OnEndBlocked();
  3838. }
  3839. //-----------------------------------------------------------------------------
  3840. // Purpose:
  3841. //-----------------------------------------------------------------------------
  3842. void CBasePropDoor::OnEndBlocked( void )
  3843. {
  3844. if ( m_bFirstBlocked )
  3845. return;
  3846. // Restart us going
  3847. DoorResume();
  3848. }
  3849. //-----------------------------------------------------------------------------
  3850. // Purpose:
  3851. // Input : *pNPC -
  3852. //-----------------------------------------------------------------------------
  3853. bool CBasePropDoor::NPCOpenDoor( CAI_BaseNPC *pNPC )
  3854. {
  3855. // dvs: TODO: use activator filter here
  3856. // dvs: TODO: outboard entity containing rules for whether door is operable?
  3857. if ( IsDoorClosed() )
  3858. {
  3859. // Use the door
  3860. Use( pNPC, pNPC, USE_ON, 0 );
  3861. }
  3862. return true;
  3863. }
  3864. bool CBasePropDoor::TestCollision( const Ray_t &ray, unsigned int mask, trace_t& trace )
  3865. {
  3866. if ( !VPhysicsGetObject() )
  3867. return false;
  3868. CStudioHdr *pStudioHdr = GetModelPtr( );
  3869. if (!pStudioHdr)
  3870. return false;
  3871. if ( !( pStudioHdr->contents() & mask ) )
  3872. return false;
  3873. physcollision->TraceBox( ray, VPhysicsGetObject()->GetCollide(), GetAbsOrigin(), GetAbsAngles(), &trace );
  3874. if ( trace.DidHit() )
  3875. {
  3876. trace.surface.surfaceProps = VPhysicsGetObject()->GetMaterialIndex();
  3877. return true;
  3878. }
  3879. return false;
  3880. }
  3881. //-----------------------------------------------------------------------------
  3882. // Custom trace filter for doors
  3883. // Will only test against entities and rejects physics objects below a mass threshold
  3884. //-----------------------------------------------------------------------------
  3885. class CTraceFilterDoor : public CTraceFilterEntitiesOnly
  3886. {
  3887. public:
  3888. // It does have a base, but we'll never network anything below here..
  3889. DECLARE_CLASS_NOBASE( CTraceFilterDoor );
  3890. CTraceFilterDoor( const IHandleEntity *pDoor, const IHandleEntity *passentity, int collisionGroup )
  3891. : m_pDoor(pDoor), m_pPassEnt(passentity), m_collisionGroup(collisionGroup)
  3892. {
  3893. }
  3894. virtual bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
  3895. {
  3896. if ( !StandardFilterRules( pHandleEntity, contentsMask ) )
  3897. return false;
  3898. if ( !PassServerEntityFilter( pHandleEntity, m_pDoor ) )
  3899. return false;
  3900. if ( !PassServerEntityFilter( pHandleEntity, m_pPassEnt ) )
  3901. return false;
  3902. // Don't test if the game code tells us we should ignore this collision...
  3903. CBaseEntity *pEntity = EntityFromEntityHandle( pHandleEntity );
  3904. if ( pEntity )
  3905. {
  3906. if ( !pEntity->ShouldCollide( m_collisionGroup, contentsMask ) )
  3907. return false;
  3908. if ( !g_pGameRules->ShouldCollide( m_collisionGroup, pEntity->GetCollisionGroup() ) )
  3909. return false;
  3910. // If objects are small enough and can move, close on them
  3911. if ( pEntity->GetMoveType() == MOVETYPE_VPHYSICS )
  3912. {
  3913. IPhysicsObject *pPhysics = pEntity->VPhysicsGetObject();
  3914. Assert(pPhysics);
  3915. // Must either be squashable or very light
  3916. if ( pPhysics->IsMoveable() && pPhysics->GetMass() < 32 )
  3917. return false;
  3918. }
  3919. }
  3920. return true;
  3921. }
  3922. private:
  3923. const IHandleEntity *m_pDoor;
  3924. const IHandleEntity *m_pPassEnt;
  3925. int m_collisionGroup;
  3926. };
  3927. inline void TraceHull_Door( const CBasePropDoor *pDoor, const Vector &vecAbsStart, const Vector &vecAbsEnd, const Vector &hullMin,
  3928. const Vector &hullMax, unsigned int mask, const CBaseEntity *ignore,
  3929. int collisionGroup, trace_t *ptr )
  3930. {
  3931. Ray_t ray;
  3932. ray.Init( vecAbsStart, vecAbsEnd, hullMin, hullMax );
  3933. CTraceFilterDoor traceFilter( pDoor, ignore, collisionGroup );
  3934. enginetrace->TraceRay( ray, mask, &traceFilter, ptr );
  3935. }
  3936. // Check directions for door movement
  3937. enum doorCheck_e
  3938. {
  3939. DOOR_CHECK_FORWARD, // Door's forward opening direction
  3940. DOOR_CHECK_BACKWARD, // Door's backward opening direction
  3941. DOOR_CHECK_FULL, // Door's complete movement volume
  3942. };
  3943. enum PropDoorRotatingSpawnPos_t
  3944. {
  3945. DOOR_SPAWN_CLOSED = 0,
  3946. DOOR_SPAWN_OPEN_FORWARD,
  3947. DOOR_SPAWN_OPEN_BACK,
  3948. DOOR_SPAWN_AJAR,
  3949. };
  3950. enum PropDoorRotatingOpenDirection_e
  3951. {
  3952. DOOR_ROTATING_OPEN_BOTH_WAYS = 0,
  3953. DOOR_ROTATING_OPEN_FORWARD,
  3954. DOOR_ROTATING_OPEN_BACKWARD,
  3955. };
  3956. //===============================================
  3957. // Rotating prop door
  3958. //===============================================
  3959. class CPropDoorRotating : public CBasePropDoor
  3960. {
  3961. DECLARE_CLASS( CPropDoorRotating, CBasePropDoor );
  3962. public:
  3963. ~CPropDoorRotating();
  3964. int DrawDebugTextOverlays(void);
  3965. void Spawn( void );
  3966. void MoveDone( void );
  3967. void BeginOpening(CBaseEntity *pOpenAwayFrom);
  3968. void BeginClosing( void );
  3969. void OnRestore( void );
  3970. void DoorTeleportToSpawnPosition();
  3971. void GetNPCOpenData(CAI_BaseNPC *pNPC, opendata_t &opendata);
  3972. void DoorClose( void );
  3973. bool DoorCanClose( bool bAutoClose );
  3974. void DoorOpen( CBaseEntity *pOpenAwayFrom );
  3975. void OnDoorOpened();
  3976. void OnDoorClosed();
  3977. void DoorResume( void );
  3978. void DoorStop( void );
  3979. float GetOpenInterval();
  3980. bool OverridePropdata() { return true; }
  3981. void InputSetSpeed(inputdata_t &inputdata);
  3982. DECLARE_DATADESC();
  3983. private:
  3984. bool IsHingeOnLeft();
  3985. void AngularMove(const QAngle &vecDestAngle, float flSpeed);
  3986. void CalculateDoorVolume( QAngle closedAngles, QAngle openAngles, Vector *destMins, Vector *destMaxs );
  3987. bool CheckDoorClear( doorCheck_e state );
  3988. doorCheck_e GetOpenState( void );
  3989. void InputSetRotationDistance ( inputdata_t &inputdata ); // Set the degree difference between open and closed
  3990. void CalcOpenAngles ( void ); // Subroutine to setup the m_angRotation QAngles based on the m_flDistance variable
  3991. Vector m_vecAxis; // The axis of rotation.
  3992. float m_flDistance; // How many degrees we rotate between open and closed.
  3993. PropDoorRotatingSpawnPos_t m_eSpawnPosition;
  3994. PropDoorRotatingOpenDirection_e m_eOpenDirection;
  3995. QAngle m_angRotationAjar; // Angles to spawn at if we are set to spawn ajar.
  3996. QAngle m_angRotationClosed; // Our angles when we are fully closed.
  3997. QAngle m_angRotationOpenForward; // Our angles when we are fully open towards our forward vector.
  3998. QAngle m_angRotationOpenBack; // Our angles when we are fully open away from our forward vector.
  3999. QAngle m_angGoal;
  4000. Vector m_vecForwardBoundsMin;
  4001. Vector m_vecForwardBoundsMax;
  4002. Vector m_vecBackBoundsMin;
  4003. Vector m_vecBackBoundsMax;
  4004. CHandle<CEntityBlocker> m_hDoorBlocker;
  4005. };
  4006. BEGIN_DATADESC(CPropDoorRotating)
  4007. DEFINE_KEYFIELD(m_eSpawnPosition, FIELD_INTEGER, "spawnpos"),
  4008. DEFINE_KEYFIELD(m_eOpenDirection, FIELD_INTEGER, "opendir" ),
  4009. DEFINE_KEYFIELD(m_vecAxis, FIELD_VECTOR, "axis"),
  4010. DEFINE_KEYFIELD(m_flDistance, FIELD_FLOAT, "distance"),
  4011. DEFINE_KEYFIELD( m_angRotationAjar, FIELD_VECTOR, "ajarangles" ),
  4012. DEFINE_FIELD( m_angRotationClosed, FIELD_VECTOR ),
  4013. DEFINE_FIELD( m_angRotationOpenForward, FIELD_VECTOR ),
  4014. DEFINE_FIELD( m_angRotationOpenBack, FIELD_VECTOR ),
  4015. DEFINE_FIELD( m_angGoal, FIELD_VECTOR ),
  4016. DEFINE_FIELD( m_hDoorBlocker, FIELD_EHANDLE ),
  4017. DEFINE_INPUTFUNC( FIELD_FLOAT, "SetRotationDistance", InputSetRotationDistance ),
  4018. DEFINE_INPUTFUNC( FIELD_FLOAT, "SetSpeed", InputSetSpeed ),
  4019. //m_vecForwardBoundsMin
  4020. //m_vecForwardBoundsMax
  4021. //m_vecBackBoundsMin
  4022. //m_vecBackBoundsMax
  4023. END_DATADESC()
  4024. LINK_ENTITY_TO_CLASS(prop_door_rotating, CPropDoorRotating);
  4025. //-----------------------------------------------------------------------------
  4026. // Destructor
  4027. //-----------------------------------------------------------------------------
  4028. CPropDoorRotating::~CPropDoorRotating( void )
  4029. {
  4030. // Remove our door blocker entity
  4031. if ( m_hDoorBlocker != NULL )
  4032. {
  4033. UTIL_Remove( m_hDoorBlocker );
  4034. }
  4035. }
  4036. //-----------------------------------------------------------------------------
  4037. // Purpose:
  4038. // Input : &mins1 -
  4039. // &maxs1 -
  4040. // &mins2 -
  4041. // &maxs2 -
  4042. // *destMins -
  4043. // *destMaxs -
  4044. //-----------------------------------------------------------------------------
  4045. void UTIL_ComputeAABBForBounds( const Vector &mins1, const Vector &maxs1, const Vector &mins2, const Vector &maxs2, Vector *destMins, Vector *destMaxs )
  4046. {
  4047. // Find the minimum extents
  4048. (*destMins)[0] = MIN( mins1[0], mins2[0] );
  4049. (*destMins)[1] = MIN( mins1[1], mins2[1] );
  4050. (*destMins)[2] = MIN( mins1[2], mins2[2] );
  4051. // Find the maximum extents
  4052. (*destMaxs)[0] = MAX( maxs1[0], maxs2[0] );
  4053. (*destMaxs)[1] = MAX( maxs1[1], maxs2[1] );
  4054. (*destMaxs)[2] = MAX( maxs1[2], maxs2[2] );
  4055. }
  4056. //-----------------------------------------------------------------------------
  4057. // Purpose:
  4058. //-----------------------------------------------------------------------------
  4059. void CPropDoorRotating::Spawn()
  4060. {
  4061. // Doors are built closed, so save the current angles as the closed angles.
  4062. m_angRotationClosed = GetLocalAngles();
  4063. // The axis of rotation must be along the z axis for now.
  4064. // NOTE: If you change this, be sure to change IsHingeOnLeft to account for it!
  4065. m_vecAxis = Vector(0, 0, 1);
  4066. CalcOpenAngles();
  4067. // Call this last! It relies on stuff we calculated above.
  4068. BaseClass::Spawn();
  4069. // We have to call this after we call the base Spawn because it requires
  4070. // that the model already be set.
  4071. if ( IsHingeOnLeft() )
  4072. {
  4073. ::V_swap( m_angRotationOpenForward, m_angRotationOpenBack );
  4074. }
  4075. // Figure out our volumes of movement as this door opens
  4076. CalculateDoorVolume( GetLocalAngles(), m_angRotationOpenForward, &m_vecForwardBoundsMin, &m_vecForwardBoundsMax );
  4077. CalculateDoorVolume( GetLocalAngles(), m_angRotationOpenBack, &m_vecBackBoundsMin, &m_vecBackBoundsMax );
  4078. }
  4079. //-----------------------------------------------------------------------------
  4080. // Purpose: Setup the m_angRotationOpenForward and m_angRotationOpenBack variables based on
  4081. // the m_flDistance variable. Also restricts m_flDistance > 0.
  4082. //-----------------------------------------------------------------------------
  4083. void CPropDoorRotating::CalcOpenAngles()
  4084. {
  4085. // HACK: convert the axis of rotation to dPitch dYaw dRoll
  4086. Vector vecMoveDir(m_vecAxis.y, m_vecAxis.z, m_vecAxis.x);
  4087. if (m_flDistance == 0)
  4088. {
  4089. m_flDistance = 90;
  4090. }
  4091. m_flDistance = fabs(m_flDistance);
  4092. // Calculate our orientation when we are fully open.
  4093. m_angRotationOpenForward.x = m_angRotationClosed.x - (vecMoveDir.x * m_flDistance);
  4094. m_angRotationOpenForward.y = m_angRotationClosed.y - (vecMoveDir.y * m_flDistance);
  4095. m_angRotationOpenForward.z = m_angRotationClosed.z - (vecMoveDir.z * m_flDistance);
  4096. m_angRotationOpenBack.x = m_angRotationClosed.x + (vecMoveDir.x * m_flDistance);
  4097. m_angRotationOpenBack.y = m_angRotationClosed.y + (vecMoveDir.y * m_flDistance);
  4098. m_angRotationOpenBack.z = m_angRotationClosed.z + (vecMoveDir.z * m_flDistance);
  4099. }
  4100. //-----------------------------------------------------------------------------
  4101. // Figures out whether the door's hinge is on its left or its right.
  4102. // Assumes:
  4103. // - that the door is hinged through its origin.
  4104. // - that the origin is at one edge of the door (revolving doors will give
  4105. // a random answer)
  4106. // - that the hinge axis lies along the z axis
  4107. //-----------------------------------------------------------------------------
  4108. bool CPropDoorRotating::IsHingeOnLeft()
  4109. {
  4110. //
  4111. // Find the point farthest from the hinge in 2D.
  4112. //
  4113. Vector vecMins;
  4114. Vector vecMaxs;
  4115. CollisionProp()->WorldSpaceAABB( &vecMins, &vecMaxs );
  4116. vecMins -= GetAbsOrigin();
  4117. vecMaxs -= GetAbsOrigin();
  4118. // Throw out z -- we only care about 2D distance.
  4119. // NOTE: if we allow for arbitrary hinge axes, this needs to change
  4120. vecMins.z = vecMaxs.z = 0;
  4121. Vector vecPointCheck;
  4122. if ( vecMins.LengthSqr() > vecMaxs.LengthSqr() )
  4123. {
  4124. vecPointCheck = vecMins;
  4125. }
  4126. else
  4127. {
  4128. vecPointCheck = vecMaxs;
  4129. }
  4130. //
  4131. // See if the projection of that point lies along our right vector.
  4132. // If it does, the door is hinged on its left.
  4133. //
  4134. Vector vecRight;
  4135. GetVectors( NULL, &vecRight, NULL );
  4136. float flDot = DotProduct( vecPointCheck, vecRight );
  4137. return ( flDot > 0 );
  4138. }
  4139. //-----------------------------------------------------------------------------
  4140. // Purpose:
  4141. // Output : Returns true on success, false on failure.
  4142. //-----------------------------------------------------------------------------
  4143. doorCheck_e CPropDoorRotating::GetOpenState( void )
  4144. {
  4145. return ( m_angGoal == m_angRotationOpenForward ) ? DOOR_CHECK_FORWARD : DOOR_CHECK_BACKWARD;
  4146. }
  4147. //-----------------------------------------------------------------------------
  4148. // Purpose:
  4149. //-----------------------------------------------------------------------------
  4150. void CPropDoorRotating::OnDoorOpened( void )
  4151. {
  4152. if ( m_hDoorBlocker != NULL )
  4153. {
  4154. // Allow passage through this blocker while open
  4155. m_hDoorBlocker->AddSolidFlags( FSOLID_NOT_SOLID );
  4156. if ( g_debug_doors.GetBool() )
  4157. {
  4158. NDebugOverlay::Box( GetAbsOrigin(), m_hDoorBlocker->CollisionProp()->OBBMins(), m_hDoorBlocker->CollisionProp()->OBBMaxs(), 0, 255, 0, true, 1.0f );
  4159. }
  4160. }
  4161. }
  4162. //-----------------------------------------------------------------------------
  4163. // Purpose:
  4164. //-----------------------------------------------------------------------------
  4165. void CPropDoorRotating::OnDoorClosed( void )
  4166. {
  4167. if ( m_hDoorBlocker != NULL )
  4168. {
  4169. // Destroy the blocker that was preventing NPCs from getting in our way.
  4170. UTIL_Remove( m_hDoorBlocker );
  4171. if ( g_debug_doors.GetBool() )
  4172. {
  4173. NDebugOverlay::Box( GetAbsOrigin(), m_hDoorBlocker->CollisionProp()->OBBMins(), m_hDoorBlocker->CollisionProp()->OBBMaxs(), 0, 255, 0, true, 1.0f );
  4174. }
  4175. }
  4176. }
  4177. //-----------------------------------------------------------------------------
  4178. // Purpose: Returns whether the way is clear for the door to close.
  4179. // Input : state - Which sides to check, forward, backward, or both.
  4180. // Output : Returns true if the door can close, false if the way is blocked.
  4181. //-----------------------------------------------------------------------------
  4182. bool CPropDoorRotating::DoorCanClose( bool bAutoClose )
  4183. {
  4184. if ( GetMaster() != NULL )
  4185. return GetMaster()->DoorCanClose( bAutoClose );
  4186. // Check all slaves
  4187. if ( HasSlaves() )
  4188. {
  4189. int numDoors = m_hDoorList.Count();
  4190. CPropDoorRotating *pLinkedDoor = NULL;
  4191. // Check all links as well
  4192. for ( int i = 0; i < numDoors; i++ )
  4193. {
  4194. pLinkedDoor = dynamic_cast<CPropDoorRotating *>((CBasePropDoor *)m_hDoorList[i]);
  4195. if ( pLinkedDoor != NULL )
  4196. {
  4197. if ( !pLinkedDoor->CheckDoorClear( bAutoClose ? DOOR_CHECK_FULL : pLinkedDoor->GetOpenState() ) )
  4198. return false;
  4199. }
  4200. }
  4201. }
  4202. // See if our path of movement is clear to allow us to shut
  4203. return CheckDoorClear( bAutoClose ? DOOR_CHECK_FULL : GetOpenState() );
  4204. }
  4205. //-----------------------------------------------------------------------------
  4206. // Purpose:
  4207. // Input : closedAngles -
  4208. // openAngles -
  4209. // *destMins -
  4210. // *destMaxs -
  4211. //-----------------------------------------------------------------------------
  4212. void CPropDoorRotating::CalculateDoorVolume( QAngle closedAngles, QAngle openAngles, Vector *destMins, Vector *destMaxs )
  4213. {
  4214. // Save our current angles and move to our start angles
  4215. QAngle saveAngles = GetLocalAngles();
  4216. SetLocalAngles( closedAngles );
  4217. // Find our AABB at the closed state
  4218. Vector closedMins, closedMaxs;
  4219. CollisionProp()->WorldSpaceAABB( &closedMins, &closedMaxs );
  4220. SetLocalAngles( openAngles );
  4221. // Find our AABB at the open state
  4222. Vector openMins, openMaxs;
  4223. CollisionProp()->WorldSpaceAABB( &openMins, &openMaxs );
  4224. // Reset our angles to our starting angles
  4225. SetLocalAngles( saveAngles );
  4226. // Find the minimum extents
  4227. UTIL_ComputeAABBForBounds( closedMins, closedMaxs, openMins, openMaxs, destMins, destMaxs );
  4228. // Move this back into local space
  4229. *destMins -= GetAbsOrigin();
  4230. *destMaxs -= GetAbsOrigin();
  4231. }
  4232. //-----------------------------------------------------------------------------
  4233. // Purpose:
  4234. //-----------------------------------------------------------------------------
  4235. void CPropDoorRotating::OnRestore( void )
  4236. {
  4237. BaseClass::OnRestore();
  4238. // Figure out our volumes of movement as this door opens
  4239. CalculateDoorVolume( GetLocalAngles(), m_angRotationOpenForward, &m_vecForwardBoundsMin, &m_vecForwardBoundsMax );
  4240. CalculateDoorVolume( GetLocalAngles(), m_angRotationOpenBack, &m_vecBackBoundsMin, &m_vecBackBoundsMax );
  4241. }
  4242. //-----------------------------------------------------------------------------
  4243. // Purpose:
  4244. // Input : forward -
  4245. // mask -
  4246. // Output : Returns true on success, false on failure.
  4247. //-----------------------------------------------------------------------------
  4248. bool CPropDoorRotating::CheckDoorClear( doorCheck_e state )
  4249. {
  4250. Vector moveMins;
  4251. Vector moveMaxs;
  4252. switch ( state )
  4253. {
  4254. case DOOR_CHECK_FORWARD:
  4255. moveMins = m_vecForwardBoundsMin;
  4256. moveMaxs = m_vecForwardBoundsMax;
  4257. break;
  4258. case DOOR_CHECK_BACKWARD:
  4259. moveMins = m_vecBackBoundsMin;
  4260. moveMaxs = m_vecBackBoundsMax;
  4261. break;
  4262. default:
  4263. case DOOR_CHECK_FULL:
  4264. UTIL_ComputeAABBForBounds( m_vecForwardBoundsMin, m_vecForwardBoundsMax, m_vecBackBoundsMin, m_vecBackBoundsMax, &moveMins, &moveMaxs );
  4265. break;
  4266. }
  4267. // Look for blocking entities, ignoring ourselves and the entity that opened us.
  4268. trace_t tr;
  4269. TraceHull_Door( this, GetAbsOrigin(), GetAbsOrigin(), moveMins, moveMaxs, MASK_SOLID, GetActivator(), COLLISION_GROUP_NONE, &tr );
  4270. if ( tr.allsolid || tr.startsolid )
  4271. {
  4272. if ( g_debug_doors.GetBool() )
  4273. {
  4274. NDebugOverlay::Box( GetAbsOrigin(), moveMins, moveMaxs, 255, 0, 0, true, 10.0f );
  4275. if ( tr.m_pEnt )
  4276. {
  4277. NDebugOverlay::Box( tr.m_pEnt->GetAbsOrigin(), tr.m_pEnt->CollisionProp()->OBBMins(), tr.m_pEnt->CollisionProp()->OBBMaxs(), 220, 220, 0, true, 10.0f );
  4278. }
  4279. }
  4280. return false;
  4281. }
  4282. if ( g_debug_doors.GetBool() )
  4283. {
  4284. NDebugOverlay::Box( GetAbsOrigin(), moveMins, moveMaxs, 0, 255, 0, true, 10.0f );
  4285. }
  4286. return true;
  4287. }
  4288. //-----------------------------------------------------------------------------
  4289. // Purpose: Puts the door in its appropriate position for spawning.
  4290. //-----------------------------------------------------------------------------
  4291. void CPropDoorRotating::DoorTeleportToSpawnPosition()
  4292. {
  4293. QAngle angSpawn;
  4294. // The Start Open spawnflag trumps the choices field
  4295. if ( ( HasSpawnFlags( SF_DOOR_START_OPEN_OBSOLETE ) ) || ( m_eSpawnPosition == DOOR_SPAWN_OPEN_FORWARD ) )
  4296. {
  4297. angSpawn = m_angRotationOpenForward;
  4298. SetDoorState( DOOR_STATE_OPEN );
  4299. }
  4300. else if ( m_eSpawnPosition == DOOR_SPAWN_OPEN_BACK )
  4301. {
  4302. angSpawn = m_angRotationOpenBack;
  4303. SetDoorState( DOOR_STATE_OPEN );
  4304. }
  4305. else if ( m_eSpawnPosition == DOOR_SPAWN_CLOSED )
  4306. {
  4307. angSpawn = m_angRotationClosed;
  4308. SetDoorState( DOOR_STATE_CLOSED );
  4309. }
  4310. else if ( m_eSpawnPosition == DOOR_SPAWN_AJAR )
  4311. {
  4312. angSpawn = m_angRotationAjar;
  4313. SetDoorState( DOOR_STATE_AJAR );
  4314. }
  4315. else
  4316. {
  4317. // Bogus spawn position setting!
  4318. Assert( false );
  4319. angSpawn = m_angRotationClosed;
  4320. SetDoorState( DOOR_STATE_CLOSED );
  4321. }
  4322. SetLocalAngles( angSpawn );
  4323. // Doesn't relink; that's done in Spawn.
  4324. }
  4325. //-----------------------------------------------------------------------------
  4326. // Purpose: After rotating, set angle to exact final angle, call "move done" function.
  4327. //-----------------------------------------------------------------------------
  4328. void CPropDoorRotating::MoveDone()
  4329. {
  4330. SetLocalAngles(m_angGoal);
  4331. SetLocalAngularVelocity(vec3_angle);
  4332. SetMoveDoneTime(-1);
  4333. BaseClass::MoveDone();
  4334. }
  4335. //-----------------------------------------------------------------------------
  4336. // Purpose: Calculate m_vecVelocity and m_flNextThink to reach vecDest from
  4337. // GetLocalOrigin() traveling at flSpeed. Just like LinearMove, but rotational.
  4338. // Input : vecDestAngle -
  4339. // flSpeed -
  4340. //-----------------------------------------------------------------------------
  4341. void CPropDoorRotating::AngularMove(const QAngle &vecDestAngle, float flSpeed)
  4342. {
  4343. ASSERTSZ(flSpeed != 0, "AngularMove: no speed is defined!");
  4344. m_angGoal = vecDestAngle;
  4345. // Already there?
  4346. if (vecDestAngle == GetLocalAngles())
  4347. {
  4348. MoveDone();
  4349. return;
  4350. }
  4351. // Set destdelta to the vector needed to move.
  4352. QAngle vecDestDelta = vecDestAngle - GetLocalAngles();
  4353. // Divide by speed to get time to reach dest
  4354. float flTravelTime = vecDestDelta.Length() / flSpeed;
  4355. // Call MoveDone when destination angles are reached.
  4356. SetMoveDoneTime(flTravelTime);
  4357. // Scale the destdelta vector by the time spent traveling to get velocity.
  4358. SetLocalAngularVelocity(vecDestDelta * (1.0 / flTravelTime));
  4359. }
  4360. //-----------------------------------------------------------------------------
  4361. // Purpose:
  4362. //-----------------------------------------------------------------------------
  4363. void CPropDoorRotating::BeginOpening(CBaseEntity *pOpenAwayFrom)
  4364. {
  4365. // Determine the direction to open.
  4366. QAngle angOpen = m_angRotationOpenForward;
  4367. doorCheck_e eDirCheck = DOOR_CHECK_FORWARD;
  4368. if ( m_eOpenDirection == DOOR_ROTATING_OPEN_FORWARD )
  4369. {
  4370. eDirCheck = DOOR_CHECK_FORWARD;
  4371. angOpen = m_angRotationOpenForward;
  4372. }
  4373. else if ( m_eOpenDirection == DOOR_ROTATING_OPEN_BACKWARD )
  4374. {
  4375. eDirCheck = DOOR_CHECK_BACKWARD;
  4376. angOpen = m_angRotationOpenBack;
  4377. }
  4378. else // Can open either direction, test to see which is appropriate
  4379. {
  4380. if (pOpenAwayFrom != NULL)
  4381. {
  4382. Vector vecForwardDoor;
  4383. GetVectors(&vecForwardDoor, NULL, NULL);
  4384. if (vecForwardDoor.Dot(pOpenAwayFrom->GetAbsOrigin()) > vecForwardDoor.Dot(GetAbsOrigin()))
  4385. {
  4386. angOpen = m_angRotationOpenBack;
  4387. eDirCheck = DOOR_CHECK_BACKWARD;
  4388. }
  4389. }
  4390. // If player is opening us and we're opening away from them, and we'll be
  4391. // blocked if we open away from them, open toward them.
  4392. if (IsPlayerOpening() && (pOpenAwayFrom && pOpenAwayFrom->IsPlayer()) && !CheckDoorClear(eDirCheck))
  4393. {
  4394. if (eDirCheck == DOOR_CHECK_FORWARD)
  4395. {
  4396. angOpen = m_angRotationOpenBack;
  4397. eDirCheck = DOOR_CHECK_BACKWARD;
  4398. }
  4399. else
  4400. {
  4401. angOpen = m_angRotationOpenForward;
  4402. eDirCheck = DOOR_CHECK_FORWARD;
  4403. }
  4404. }
  4405. }
  4406. // Create the door blocker
  4407. Vector mins, maxs;
  4408. if ( eDirCheck == DOOR_CHECK_FORWARD )
  4409. {
  4410. mins = m_vecForwardBoundsMin;
  4411. maxs = m_vecForwardBoundsMax;
  4412. }
  4413. else
  4414. {
  4415. mins = m_vecBackBoundsMin;
  4416. maxs = m_vecBackBoundsMax;
  4417. }
  4418. if ( m_hDoorBlocker != NULL )
  4419. {
  4420. UTIL_Remove( m_hDoorBlocker );
  4421. }
  4422. // Create a blocking entity to keep random entities out of our movement path
  4423. m_hDoorBlocker = CEntityBlocker::Create( GetAbsOrigin(), mins, maxs, pOpenAwayFrom, false );
  4424. Vector volumeCenter = ((mins+maxs) * 0.5f) + GetAbsOrigin();
  4425. // Ignoring the Z
  4426. float volumeRadius = MAX( fabs(mins.x), maxs.x );
  4427. volumeRadius = MAX( volumeRadius, MAX( fabs(mins.y), maxs.y ) );
  4428. // Debug
  4429. if ( g_debug_doors.GetBool() )
  4430. {
  4431. NDebugOverlay::Cross3D( volumeCenter, -Vector(volumeRadius,volumeRadius,volumeRadius), Vector(volumeRadius,volumeRadius,volumeRadius), 255, 0, 0, true, 1.0f );
  4432. }
  4433. // Make respectful entities move away from our path
  4434. if( !HasSpawnFlags(SF_DOOR_SILENT_TO_NPCS) )
  4435. {
  4436. CSoundEnt::InsertSound( SOUND_MOVE_AWAY, volumeCenter, volumeRadius, 0.5f, pOpenAwayFrom );
  4437. }
  4438. // Do final setup
  4439. if ( m_hDoorBlocker != NULL )
  4440. {
  4441. // Only block NPCs
  4442. m_hDoorBlocker->SetCollisionGroup( COLLISION_GROUP_DOOR_BLOCKER );
  4443. // If we hit something while opening, just stay unsolid until we try again
  4444. if ( CheckDoorClear( eDirCheck ) == false )
  4445. {
  4446. m_hDoorBlocker->AddSolidFlags( FSOLID_NOT_SOLID );
  4447. }
  4448. if ( g_debug_doors.GetBool() )
  4449. {
  4450. NDebugOverlay::Box( GetAbsOrigin(), m_hDoorBlocker->CollisionProp()->OBBMins(), m_hDoorBlocker->CollisionProp()->OBBMaxs(), 255, 0, 0, true, 1.0f );
  4451. }
  4452. }
  4453. AngularMove(angOpen, m_flSpeed);
  4454. }
  4455. //-----------------------------------------------------------------------------
  4456. // Purpose:
  4457. //-----------------------------------------------------------------------------
  4458. void CPropDoorRotating::BeginClosing( void )
  4459. {
  4460. if ( m_hDoorBlocker != NULL )
  4461. {
  4462. // Become solid again unless we're already being blocked
  4463. if ( CheckDoorClear( GetOpenState() ) )
  4464. {
  4465. m_hDoorBlocker->RemoveSolidFlags( FSOLID_NOT_SOLID );
  4466. }
  4467. if ( g_debug_doors.GetBool() )
  4468. {
  4469. NDebugOverlay::Box( GetAbsOrigin(), m_hDoorBlocker->CollisionProp()->OBBMins(), m_hDoorBlocker->CollisionProp()->OBBMaxs(), 255, 0, 0, true, 1.0f );
  4470. }
  4471. }
  4472. AngularMove(m_angRotationClosed, m_flSpeed);
  4473. }
  4474. //-----------------------------------------------------------------------------
  4475. // Purpose:
  4476. //-----------------------------------------------------------------------------
  4477. void CPropDoorRotating::DoorStop( void )
  4478. {
  4479. SetLocalAngularVelocity( vec3_angle );
  4480. SetMoveDoneTime( -1 );
  4481. }
  4482. //-----------------------------------------------------------------------------
  4483. // Purpose: Restart a door moving that was temporarily paused
  4484. //-----------------------------------------------------------------------------
  4485. void CPropDoorRotating::DoorResume( void )
  4486. {
  4487. // Restart our angular movement
  4488. AngularMove( m_angGoal, m_flSpeed );
  4489. }
  4490. //-----------------------------------------------------------------------------
  4491. // Purpose:
  4492. // Input : vecMoveDir -
  4493. // opendata -
  4494. //-----------------------------------------------------------------------------
  4495. void CPropDoorRotating::GetNPCOpenData(CAI_BaseNPC *pNPC, opendata_t &opendata)
  4496. {
  4497. // dvs: TODO: finalize open position, direction, activity
  4498. Vector vecForward;
  4499. Vector vecRight;
  4500. AngleVectors(GetAbsAngles(), &vecForward, &vecRight, NULL);
  4501. //
  4502. // Figure out where the NPC should stand to open this door,
  4503. // and what direction they should face.
  4504. //
  4505. opendata.vecStandPos = GetAbsOrigin() - (vecRight * 24);
  4506. opendata.vecStandPos.z -= 54;
  4507. Vector vecNPCOrigin = pNPC->GetAbsOrigin();
  4508. if (pNPC->GetAbsOrigin().Dot(vecForward) > GetAbsOrigin().Dot(vecForward))
  4509. {
  4510. // In front of the door relative to the door's forward vector.
  4511. opendata.vecStandPos += vecForward * 64;
  4512. opendata.vecFaceDir = -vecForward;
  4513. }
  4514. else
  4515. {
  4516. // Behind the door relative to the door's forward vector.
  4517. opendata.vecStandPos -= vecForward * 64;
  4518. opendata.vecFaceDir = vecForward;
  4519. }
  4520. opendata.eActivity = ACT_OPEN_DOOR;
  4521. }
  4522. //-----------------------------------------------------------------------------
  4523. // Purpose: Returns how long it will take this door to open.
  4524. //-----------------------------------------------------------------------------
  4525. float CPropDoorRotating::GetOpenInterval()
  4526. {
  4527. // set destdelta to the vector needed to move
  4528. QAngle vecDestDelta = m_angRotationOpenForward - GetLocalAngles();
  4529. // divide by speed to get time to reach dest
  4530. return vecDestDelta.Length() / m_flSpeed;
  4531. }
  4532. //-----------------------------------------------------------------------------
  4533. // Purpose: Draw any debug text overlays
  4534. // Output : Current text offset from the top
  4535. //-----------------------------------------------------------------------------
  4536. int CPropDoorRotating::DrawDebugTextOverlays(void)
  4537. {
  4538. int text_offset = BaseClass::DrawDebugTextOverlays();
  4539. if (m_debugOverlays & OVERLAY_TEXT_BIT)
  4540. {
  4541. char tempstr[512];
  4542. Q_snprintf(tempstr, sizeof(tempstr),"Avelocity: %.2f %.2f %.2f", GetLocalAngularVelocity().x, GetLocalAngularVelocity().y, GetLocalAngularVelocity().z);
  4543. EntityText( text_offset, tempstr, 0);
  4544. text_offset++;
  4545. if ( IsDoorOpen() )
  4546. {
  4547. Q_strncpy(tempstr, "DOOR STATE: OPEN", sizeof(tempstr));
  4548. }
  4549. else if ( IsDoorClosed() )
  4550. {
  4551. Q_strncpy(tempstr, "DOOR STATE: CLOSED", sizeof(tempstr));
  4552. }
  4553. else if ( IsDoorOpening() )
  4554. {
  4555. Q_strncpy(tempstr, "DOOR STATE: OPENING", sizeof(tempstr));
  4556. }
  4557. else if ( IsDoorClosing() )
  4558. {
  4559. Q_strncpy(tempstr, "DOOR STATE: CLOSING", sizeof(tempstr));
  4560. }
  4561. else if ( IsDoorAjar() )
  4562. {
  4563. Q_strncpy(tempstr, "DOOR STATE: AJAR", sizeof(tempstr));
  4564. }
  4565. EntityText( text_offset, tempstr, 0);
  4566. text_offset++;
  4567. }
  4568. return text_offset;
  4569. }
  4570. //-----------------------------------------------------------------------------
  4571. // Purpose: Change this door's distance (in degrees) between open and closed
  4572. //-----------------------------------------------------------------------------
  4573. void CPropDoorRotating::InputSetRotationDistance( inputdata_t &inputdata )
  4574. {
  4575. m_flDistance = inputdata.value.Float();
  4576. // Recalculate our open volume
  4577. CalcOpenAngles();
  4578. CalculateDoorVolume( GetLocalAngles(), m_angRotationOpenForward, &m_vecForwardBoundsMin, &m_vecForwardBoundsMax );
  4579. CalculateDoorVolume( GetLocalAngles(), m_angRotationOpenBack, &m_vecBackBoundsMin, &m_vecBackBoundsMax );
  4580. }
  4581. // Debug sphere
  4582. class CPhysSphere : public CPhysicsProp
  4583. {
  4584. DECLARE_CLASS( CPhysSphere, CPhysicsProp );
  4585. public:
  4586. virtual bool OverridePropdata() { return true; }
  4587. bool CreateVPhysics()
  4588. {
  4589. SetSolid( SOLID_BBOX );
  4590. SetCollisionBounds( -Vector(12,12,12), Vector(12,12,12) );
  4591. objectparams_t params = g_PhysDefaultObjectParams;
  4592. params.pGameData = static_cast<void *>(this);
  4593. IPhysicsObject *pPhysicsObject = physenv->CreateSphereObject( 12, 0, GetAbsOrigin(), GetAbsAngles(), &params, false );
  4594. if ( pPhysicsObject )
  4595. {
  4596. VPhysicsSetObject( pPhysicsObject );
  4597. SetMoveType( MOVETYPE_VPHYSICS );
  4598. pPhysicsObject->Wake();
  4599. }
  4600. return true;
  4601. }
  4602. };
  4603. void CPropDoorRotating::InputSetSpeed(inputdata_t &inputdata)
  4604. {
  4605. AssertMsg1(inputdata.value.Float() > 0.0f, "InputSetSpeed on %s called with negative parameter!", GetDebugName() );
  4606. m_flSpeed = inputdata.value.Float();
  4607. DoorResume();
  4608. }
  4609. LINK_ENTITY_TO_CLASS( prop_sphere, CPhysSphere );
  4610. // ------------------------------------------------------------------------------------------ //
  4611. // Special version of func_physbox.
  4612. // ------------------------------------------------------------------------------------------ //
  4613. class CPhysBoxMultiplayer : public CPhysBox, public IMultiplayerPhysics
  4614. {
  4615. public:
  4616. DECLARE_CLASS( CPhysBoxMultiplayer, CPhysBox );
  4617. virtual int GetMultiplayerPhysicsMode()
  4618. {
  4619. return m_iPhysicsMode;
  4620. }
  4621. virtual float GetMass()
  4622. {
  4623. return m_fMass;
  4624. }
  4625. virtual bool IsAsleep()
  4626. {
  4627. return VPhysicsGetObject()->IsAsleep();
  4628. }
  4629. CNetworkVar( int, m_iPhysicsMode ); // One of the PHYSICS_MULTIPLAYER_ defines.
  4630. CNetworkVar( float, m_fMass );
  4631. DECLARE_DATADESC();
  4632. DECLARE_SERVERCLASS();
  4633. virtual void Activate()
  4634. {
  4635. BaseClass::Activate();
  4636. SetCollisionGroup( COLLISION_GROUP_PUSHAWAY );
  4637. m_fMass = VPhysicsGetObject()->GetMass();
  4638. }
  4639. };
  4640. LINK_ENTITY_TO_CLASS( func_physbox_multiplayer, CPhysBoxMultiplayer );
  4641. BEGIN_DATADESC( CPhysBoxMultiplayer )
  4642. END_DATADESC()
  4643. IMPLEMENT_SERVERCLASS_ST( CPhysBoxMultiplayer, DT_PhysBoxMultiplayer )
  4644. SendPropInt( SENDINFO( m_iPhysicsMode ), 1, SPROP_UNSIGNED ),
  4645. SendPropFloat( SENDINFO( m_fMass ), 0, SPROP_NOSCALE ),
  4646. END_SEND_TABLE()
  4647. class CPhysicsPropMultiplayer : public CPhysicsProp, public IMultiplayerPhysics
  4648. {
  4649. DECLARE_CLASS( CPhysicsPropMultiplayer, CPhysicsProp );
  4650. CNetworkVar( int, m_iPhysicsMode ); // One of the PHYSICS_MULTIPLAYER_ defines.
  4651. CNetworkVar( float, m_fMass );
  4652. DECLARE_SERVERCLASS();
  4653. DECLARE_DATADESC();
  4654. CPhysicsPropMultiplayer()
  4655. {
  4656. m_iPhysicsMode = PHYSICS_MULTIPLAYER_AUTODETECT;
  4657. m_usingCustomCollisionBounds = false;
  4658. }
  4659. // IBreakableWithPropData:
  4660. void SetPhysicsMode(int iMode)
  4661. {
  4662. m_iPhysicsMode = iMode;
  4663. }
  4664. int GetPhysicsMode() { return m_iPhysicsMode; }
  4665. // IMultiplayerPhysics:
  4666. int GetMultiplayerPhysicsMode() { return m_iPhysicsMode; }
  4667. float GetMass() { return m_fMass; }
  4668. bool IsAsleep() { return !m_bAwake; }
  4669. bool IsDebris( void ) { return ( ( m_spawnflags & SF_PHYSPROP_DEBRIS ) != 0 ); }
  4670. virtual void VPhysicsUpdate( IPhysicsObject *pPhysics )
  4671. {
  4672. BaseClass::VPhysicsUpdate( pPhysics );
  4673. if ( sv_turbophysics.GetBool() )
  4674. {
  4675. // If the object is set to debris, don't let turbo physics change it.
  4676. if ( IsDebris() )
  4677. return;
  4678. if ( m_bAwake )
  4679. {
  4680. SetCollisionGroup( COLLISION_GROUP_PUSHAWAY );
  4681. }
  4682. else if ( m_iPhysicsMode == PHYSICS_MULTIPLAYER_NON_SOLID )
  4683. {
  4684. SetCollisionGroup( COLLISION_GROUP_DEBRIS );
  4685. }
  4686. else
  4687. {
  4688. SetCollisionGroup( COLLISION_GROUP_NONE );
  4689. }
  4690. }
  4691. }
  4692. virtual void Spawn( void )
  4693. {
  4694. BaseClass::Spawn();
  4695. // if no physicsmode was defined by .QC or propdata.txt,
  4696. // use auto detect based on size & mass
  4697. if ( m_iPhysicsMode == PHYSICS_MULTIPLAYER_AUTODETECT )
  4698. {
  4699. if ( VPhysicsGetObject() )
  4700. {
  4701. m_iPhysicsMode = GetAutoMultiplayerPhysicsMode(
  4702. CollisionProp()->OBBSize(), VPhysicsGetObject()->GetMass() );
  4703. }
  4704. else
  4705. {
  4706. UTIL_Remove( this );
  4707. return;
  4708. }
  4709. }
  4710. // check if map maker overrides physics mode to force a server-side entity
  4711. if ( GetSpawnFlags() & SF_PHYSPROP_FORCE_SERVER_SIDE )
  4712. {
  4713. SetPhysicsMode( PHYSICS_MULTIPLAYER_NON_SOLID );
  4714. }
  4715. if ( m_iPhysicsMode == PHYSICS_MULTIPLAYER_CLIENTSIDE )
  4716. {
  4717. if ( engine->IsInEditMode() )
  4718. {
  4719. // in map edit mode always spawn as server phys prop
  4720. SetPhysicsMode( PHYSICS_MULTIPLAYER_NON_SOLID );
  4721. }
  4722. else
  4723. {
  4724. // don't spawn clientside props on server
  4725. UTIL_Remove( this );
  4726. return;
  4727. }
  4728. }
  4729. if ( GetCollisionGroup() == COLLISION_GROUP_NONE )
  4730. SetCollisionGroup( COLLISION_GROUP_PUSHAWAY );
  4731. // Items marked as debris should be set as such.
  4732. if ( IsDebris() )
  4733. {
  4734. SetCollisionGroup( COLLISION_GROUP_DEBRIS );
  4735. }
  4736. m_fMass = VPhysicsGetObject()->GetMass();
  4737. // VPhysicsGetObject() is NULL on the client, which prevents the client from finding a decent
  4738. // AABB surrounding the collision bounds. If we've got a VPhysicsGetObject()->GetCollide(), we'll
  4739. // grab it's unrotated bounds and use it to calculate our collision surrounding bounds. This
  4740. // can end up larger than the CollisionProp() would have calculated on its own, but it'll be
  4741. // identical on the client and the server.
  4742. m_usingCustomCollisionBounds = false;
  4743. if ( ( GetSolid() == SOLID_VPHYSICS ) && ( GetMoveType() == MOVETYPE_VPHYSICS ) )
  4744. {
  4745. IPhysicsObject *pPhysics = VPhysicsGetObject();
  4746. if ( pPhysics && pPhysics->GetCollide() )
  4747. {
  4748. physcollision->CollideGetAABB( &m_collisionMins.GetForModify(), &m_collisionMaxs.GetForModify(), pPhysics->GetCollide(), vec3_origin, vec3_angle );
  4749. CollisionProp()->SetSurroundingBoundsType( USE_GAME_CODE );
  4750. m_usingCustomCollisionBounds = true;
  4751. }
  4752. }
  4753. }
  4754. virtual void ComputeWorldSpaceSurroundingBox( Vector *mins, Vector *maxs )
  4755. {
  4756. Assert( m_usingCustomCollisionBounds );
  4757. Assert( mins != NULL && maxs != NULL );
  4758. if ( !mins || !maxs )
  4759. return;
  4760. // Take our saved collision bounds, and transform into world space
  4761. TransformAABB( EntityToWorldTransform(), m_collisionMins, m_collisionMaxs, *mins, *maxs );
  4762. }
  4763. private:
  4764. bool m_usingCustomCollisionBounds;
  4765. CNetworkVector( m_collisionMins );
  4766. CNetworkVector( m_collisionMaxs );
  4767. };
  4768. LINK_ENTITY_TO_CLASS( prop_physics_multiplayer, CPhysicsPropMultiplayer );
  4769. BEGIN_DATADESC( CPhysicsPropMultiplayer )
  4770. DEFINE_KEYFIELD( m_iPhysicsMode, FIELD_INTEGER, "physicsmode" ),
  4771. DEFINE_FIELD( m_fMass, FIELD_FLOAT ),
  4772. DEFINE_FIELD( m_usingCustomCollisionBounds, FIELD_BOOLEAN ),
  4773. DEFINE_FIELD( m_collisionMins, FIELD_VECTOR ),
  4774. DEFINE_FIELD( m_collisionMaxs, FIELD_VECTOR ),
  4775. END_DATADESC()
  4776. IMPLEMENT_SERVERCLASS_ST( CPhysicsPropMultiplayer, DT_PhysicsPropMultiplayer )
  4777. SendPropInt( SENDINFO( m_iPhysicsMode ), 2, SPROP_UNSIGNED ),
  4778. SendPropFloat( SENDINFO( m_fMass ), 0, SPROP_NOSCALE ),
  4779. SendPropVector( SENDINFO( m_collisionMins ), 0, SPROP_NOSCALE ),
  4780. SendPropVector( SENDINFO( m_collisionMaxs ), 0, SPROP_NOSCALE ),
  4781. END_SEND_TABLE()
  4782. #define RESPAWNABLE_PROP_DEFAULT_TIME 60.0f
  4783. class CPhysicsPropRespawnable : public CPhysicsProp
  4784. {
  4785. DECLARE_CLASS( CPhysicsPropRespawnable, CPhysicsProp );
  4786. DECLARE_DATADESC();
  4787. public:
  4788. CPhysicsPropRespawnable();
  4789. virtual void Spawn( void );
  4790. virtual void Event_Killed( const CTakeDamageInfo &info );
  4791. void Materialize( void );
  4792. private:
  4793. Vector m_vOriginalSpawnOrigin;
  4794. QAngle m_vOriginalSpawnAngles;
  4795. Vector m_vOriginalMins;
  4796. Vector m_vOriginalMaxs;
  4797. float m_flRespawnTime;
  4798. };
  4799. LINK_ENTITY_TO_CLASS( prop_physics_respawnable, CPhysicsPropRespawnable );
  4800. BEGIN_DATADESC( CPhysicsPropRespawnable )
  4801. DEFINE_THINKFUNC( Materialize ),
  4802. DEFINE_KEYFIELD( m_flRespawnTime, FIELD_FLOAT, "RespawnTime" ),
  4803. DEFINE_FIELD( m_vOriginalSpawnOrigin, FIELD_POSITION_VECTOR ),
  4804. DEFINE_FIELD( m_vOriginalSpawnAngles, FIELD_VECTOR ),
  4805. DEFINE_FIELD( m_vOriginalMins, FIELD_VECTOR ),
  4806. DEFINE_FIELD( m_vOriginalMaxs, FIELD_VECTOR ),
  4807. END_DATADESC()
  4808. CPhysicsPropRespawnable::CPhysicsPropRespawnable( void )
  4809. {
  4810. m_flRespawnTime = 0.0f;
  4811. }
  4812. void CPhysicsPropRespawnable::Spawn( void )
  4813. {
  4814. BaseClass::Spawn();
  4815. m_vOriginalSpawnOrigin = GetAbsOrigin();
  4816. m_vOriginalSpawnAngles = GetAbsAngles();
  4817. m_vOriginalMins = CollisionProp()->OBBMins();
  4818. m_vOriginalMaxs = CollisionProp()->OBBMaxs();
  4819. if ( m_flRespawnTime == 0.0f )
  4820. {
  4821. m_flRespawnTime = RESPAWNABLE_PROP_DEFAULT_TIME;
  4822. }
  4823. SetOwnerEntity( NULL );
  4824. }
  4825. void CPhysicsPropRespawnable::Event_Killed( const CTakeDamageInfo &info )
  4826. {
  4827. IPhysicsObject *pPhysics = VPhysicsGetObject();
  4828. if ( pPhysics && !pPhysics->IsMoveable() )
  4829. {
  4830. pPhysics->EnableMotion( true );
  4831. VPhysicsTakeDamage( info );
  4832. }
  4833. Break( info.GetInflictor(), info );
  4834. PhysCleanupFrictionSounds( this );
  4835. VPhysicsDestroyObject();
  4836. CBaseEntity::PhysicsRemoveTouchedList( this );
  4837. CBaseEntity::PhysicsRemoveGroundList( this );
  4838. DestroyAllDataObjects();
  4839. AddEffects( EF_NODRAW );
  4840. if ( IsOnFire() || IsDissolving() )
  4841. {
  4842. UTIL_Remove( GetEffectEntity() );
  4843. }
  4844. Teleport( &m_vOriginalSpawnOrigin, &m_vOriginalSpawnAngles, NULL );
  4845. SetContextThink( NULL, 0, "PROP_CLEARFLAGS" );
  4846. SetThink( &CPhysicsPropRespawnable::Materialize );
  4847. SetNextThink( gpGlobals->curtime + m_flRespawnTime );
  4848. }
  4849. void CPhysicsPropRespawnable::Materialize( void )
  4850. {
  4851. trace_t tr;
  4852. UTIL_TraceHull( m_vOriginalSpawnOrigin, m_vOriginalSpawnOrigin, m_vOriginalMins, m_vOriginalMaxs, MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
  4853. if ( tr.startsolid || tr.allsolid )
  4854. {
  4855. //Try again in a second.
  4856. SetNextThink( gpGlobals->curtime + 1.0f );
  4857. return;
  4858. }
  4859. RemoveEffects( EF_NODRAW );
  4860. Spawn();
  4861. }
  4862. //------------------------------------------------------------------------------
  4863. // Purpose: Create a prop of the given type
  4864. //------------------------------------------------------------------------------
  4865. void CC_Prop_Dynamic_Create( const CCommand &args )
  4866. {
  4867. if ( args.ArgC() != 2 )
  4868. return;
  4869. // Figure out where to place it
  4870. CBasePlayer* pPlayer = UTIL_GetCommandClient();
  4871. Vector forward;
  4872. pPlayer->EyeVectors( &forward );
  4873. trace_t tr;
  4874. UTIL_TraceLine( pPlayer->EyePosition(),
  4875. pPlayer->EyePosition() + forward * MAX_TRACE_LENGTH, MASK_NPCSOLID,
  4876. pPlayer, COLLISION_GROUP_NONE, &tr );
  4877. // No hit? We're done.
  4878. if ( tr.fraction == 1.0 )
  4879. return;
  4880. MDLCACHE_CRITICAL_SECTION();
  4881. char pModelName[512];
  4882. Q_snprintf( pModelName, sizeof(pModelName), "models/%s", args[1] );
  4883. Q_DefaultExtension( pModelName, ".mdl", sizeof(pModelName) );
  4884. MDLHandle_t h = mdlcache->FindMDL( pModelName );
  4885. if ( h == MDLHANDLE_INVALID )
  4886. return;
  4887. bool bAllowPrecache = CBaseEntity::IsPrecacheAllowed();
  4888. CBaseEntity::SetAllowPrecache( true );
  4889. vcollide_t *pVCollide = mdlcache->GetVCollide( h );
  4890. Vector xaxis( 1.0f, 0.0f, 0.0f );
  4891. Vector yaxis;
  4892. CrossProduct( tr.plane.normal, xaxis, yaxis );
  4893. if ( VectorNormalize( yaxis ) < 1e-3 )
  4894. {
  4895. xaxis.Init( 0.0f, 0.0f, 1.0f );
  4896. CrossProduct( tr.plane.normal, xaxis, yaxis );
  4897. VectorNormalize( yaxis );
  4898. }
  4899. CrossProduct( yaxis, tr.plane.normal, xaxis );
  4900. VectorNormalize( xaxis );
  4901. VMatrix entToWorld;
  4902. entToWorld.SetBasisVectors( xaxis, yaxis, tr.plane.normal );
  4903. QAngle angles;
  4904. MatrixToAngles( entToWorld, angles );
  4905. // Try to create entity
  4906. CDynamicProp *pProp = dynamic_cast< CDynamicProp * >( CreateEntityByName( "dynamic_prop" ) );
  4907. if ( pProp )
  4908. {
  4909. char buf[512];
  4910. // Pass in standard key values
  4911. Q_snprintf( buf, sizeof(buf), "%.10f %.10f %.10f", tr.endpos.x, tr.endpos.y, tr.endpos.z );
  4912. pProp->KeyValue( "origin", buf );
  4913. Q_snprintf( buf, sizeof(buf), "%.10f %.10f %.10f", angles.x, angles.y, angles.z );
  4914. pProp->KeyValue( "angles", buf );
  4915. pProp->KeyValue( "model", pModelName );
  4916. pProp->KeyValue( "solid", pVCollide ? "6" : "2" );
  4917. pProp->KeyValue( "fademindist", "-1" );
  4918. pProp->KeyValue( "fademaxdist", "0" );
  4919. pProp->KeyValue( "fadescale", "1" );
  4920. pProp->KeyValue( "MinAnimTime", "5" );
  4921. pProp->KeyValue( "MaxAnimTime", "10" );
  4922. pProp->Precache();
  4923. DispatchSpawn( pProp );
  4924. pProp->Activate();
  4925. }
  4926. CBaseEntity::SetAllowPrecache( bAllowPrecache );
  4927. }
  4928. static ConCommand prop_dynamic_create("prop_dynamic_create", CC_Prop_Dynamic_Create, "Creates a dynamic prop with a specific .mdl aimed away from where the player is looking.\n\tArguments: {.mdl name}", FCVAR_CHEAT);
  4929. //------------------------------------------------------------------------------
  4930. // Purpose: Create a prop of the given type
  4931. //------------------------------------------------------------------------------
  4932. void CC_Prop_Physics_Create( const CCommand &args )
  4933. {
  4934. if ( args.ArgC() != 2 )
  4935. return;
  4936. char pModelName[512];
  4937. Q_snprintf( pModelName, sizeof(pModelName), "models/%s", args[1] );
  4938. Q_DefaultExtension( pModelName, ".mdl", sizeof(pModelName) );
  4939. // Figure out where to place it
  4940. CBasePlayer* pPlayer = UTIL_GetCommandClient();
  4941. Vector forward;
  4942. pPlayer->EyeVectors( &forward );
  4943. CreatePhysicsProp( pModelName, pPlayer->EyePosition(), pPlayer->EyePosition() + forward * MAX_TRACE_LENGTH, pPlayer, true );
  4944. }
  4945. static ConCommand prop_physics_create("prop_physics_create", CC_Prop_Physics_Create, "Creates a physics prop with a specific .mdl aimed away from where the player is looking.\n\tArguments: {.mdl name}", FCVAR_CHEAT);
  4946. CPhysicsProp* CreatePhysicsProp( const char *pModelName, const Vector &vTraceStart, const Vector &vTraceEnd, const IHandleEntity *pTraceIgnore, bool bRequireVCollide, const char *pClassName )
  4947. {
  4948. MDLCACHE_CRITICAL_SECTION();
  4949. MDLHandle_t h = mdlcache->FindMDL( pModelName );
  4950. if ( h == MDLHANDLE_INVALID )
  4951. return NULL;
  4952. // Must have vphysics to place as a physics prop
  4953. studiohdr_t *pStudioHdr = mdlcache->GetStudioHdr( h );
  4954. if ( !pStudioHdr )
  4955. return NULL;
  4956. // Must have vphysics to place as a physics prop
  4957. if ( bRequireVCollide && !mdlcache->GetVCollide( h ) )
  4958. return NULL;
  4959. QAngle angles( 0.0f, 0.0f, 0.0f );
  4960. Vector vecSweepMins = pStudioHdr->hull_min;
  4961. Vector vecSweepMaxs = pStudioHdr->hull_max;
  4962. trace_t tr;
  4963. UTIL_TraceHull( vTraceStart, vTraceEnd,
  4964. vecSweepMins, vecSweepMaxs, MASK_NPCSOLID, pTraceIgnore, COLLISION_GROUP_NONE, &tr );
  4965. // No hit? We're done.
  4966. if ( (tr.fraction == 1.0 && (vTraceEnd-vTraceStart).Length() > 0.01) || tr.allsolid )
  4967. return NULL;
  4968. VectorMA( tr.endpos, 1.0f, tr.plane.normal, tr.endpos );
  4969. bool bAllowPrecache = CBaseEntity::IsPrecacheAllowed();
  4970. CBaseEntity::SetAllowPrecache( true );
  4971. // Try to create entity
  4972. CPhysicsProp *pProp = dynamic_cast< CPhysicsProp * >( CreateEntityByName( pClassName ) );
  4973. if ( pProp )
  4974. {
  4975. char buf[512];
  4976. // Pass in standard key values
  4977. Q_snprintf( buf, sizeof(buf), "%.10f %.10f %.10f", tr.endpos.x, tr.endpos.y, tr.endpos.z );
  4978. pProp->KeyValue( "origin", buf );
  4979. Q_snprintf( buf, sizeof(buf), "%.10f %.10f %.10f", angles.x, angles.y, angles.z );
  4980. pProp->KeyValue( "angles", buf );
  4981. pProp->KeyValue( "model", pModelName );
  4982. pProp->KeyValue( "fademindist", "-1" );
  4983. pProp->KeyValue( "fademaxdist", "0" );
  4984. pProp->KeyValue( "fadescale", "1" );
  4985. pProp->KeyValue( "inertiaScale", "1.0" );
  4986. pProp->KeyValue( "physdamagescale", "0.1" );
  4987. pProp->Precache();
  4988. DispatchSpawn( pProp );
  4989. pProp->Activate();
  4990. }
  4991. CBaseEntity::SetAllowPrecache( bAllowPrecache );
  4992. return pProp;
  4993. }
  4994. //-----------------------------------------------------------------------------
  4995. // Purpose: Scale the object to a new size, taking its render verts and physical verts into account
  4996. //-----------------------------------------------------------------------------
  4997. bool UTIL_CreateScaledPhysObject( CBaseAnimating *pInstance, float flScale )
  4998. {
  4999. // Don't scale NPCs
  5000. if ( pInstance->MyCombatCharacterPointer() )
  5001. return false;
  5002. // FIXME: This needs to work for ragdolls!
  5003. // Get our object
  5004. IPhysicsObject *pObject = pInstance->VPhysicsGetObject();
  5005. if ( pObject == NULL )
  5006. {
  5007. AssertMsg( 0, "UTIL_CreateScaledPhysObject: Failed to scale physics for object-- It has no physics." );
  5008. return false;
  5009. }
  5010. // See if our current physics object is motion disabled
  5011. bool bWasMotionDisabled = ( pObject->IsMotionEnabled() == false );
  5012. bool bWasStatic = ( pObject->IsStatic() );
  5013. vcollide_t *pCollide = modelinfo->GetVCollide( pInstance->GetModelIndex() );
  5014. if ( pCollide == NULL || pCollide->solidCount == 0 )
  5015. return NULL;
  5016. CPhysCollide *pNewCollide = pCollide->solids[0]; // FIXME: Needs to iterate over the solids
  5017. if ( flScale != 1.0f )
  5018. {
  5019. // Create a query to get more information from the collision object
  5020. ICollisionQuery *pQuery = physcollision->CreateQueryModel( pCollide->solids[0] ); // FIXME: This should iterate over all solids!
  5021. if ( pQuery == NULL )
  5022. return false;
  5023. // Create a container to hold all the convexes we'll create
  5024. const int nNumConvex = pQuery->ConvexCount();
  5025. CPhysConvex **pConvexes = (CPhysConvex **) stackalloc( sizeof(CPhysConvex *) * nNumConvex );
  5026. // For each convex, collect the verts and create a convex from it we'll retain for later
  5027. for ( int i = 0; i < nNumConvex; i++ )
  5028. {
  5029. int nNumTris = pQuery->TriangleCount( i );
  5030. int nNumVerts = nNumTris * 3;
  5031. // FIXME: Really? stackalloc?
  5032. Vector *pVerts = (Vector *) stackalloc( sizeof(Vector) * nNumVerts );
  5033. Vector **ppVerts = (Vector **) stackalloc( sizeof(Vector *) * nNumVerts );
  5034. for ( int j = 0; j < nNumTris; j++ )
  5035. {
  5036. // Get all the verts for this triangle and scale them up
  5037. pQuery->GetTriangleVerts( i, j, pVerts+(j*3) );
  5038. *(pVerts+(j*3)) *= flScale;
  5039. *(pVerts+(j*3)+1) *= flScale;
  5040. *(pVerts+(j*3)+2) *= flScale;
  5041. // Setup our pointers (blech!)
  5042. *(ppVerts+(j*3)) = pVerts+(j*3);
  5043. *(ppVerts+(j*3)+1) = pVerts+(j*3)+1;
  5044. *(ppVerts+(j*3)+2) = pVerts+(j*3)+2;
  5045. }
  5046. // Convert it back to a convex
  5047. pConvexes[i] = physcollision->ConvexFromVerts( ppVerts, nNumVerts );
  5048. Assert( pConvexes[i] != NULL );
  5049. if ( pConvexes[i] == NULL )
  5050. return false;
  5051. }
  5052. // Clean up
  5053. physcollision->DestroyQueryModel( pQuery );
  5054. // Create a collision model from all the convexes
  5055. pNewCollide = physcollision->ConvertConvexToCollide( pConvexes, nNumConvex );
  5056. if ( pNewCollide == NULL )
  5057. return false;
  5058. }
  5059. // Get our solid info
  5060. solid_t tmpSolid;
  5061. if ( !PhysModelParseSolidByIndex( tmpSolid, pInstance, pInstance->GetModelIndex(), -1 ) )
  5062. return false;
  5063. // Physprops get keyvalues that effect the mass, this block is to respect those fields when we scale
  5064. CPhysicsProp *pPhysInstance = dynamic_cast<CPhysicsProp*>( pInstance );
  5065. if ( pPhysInstance )
  5066. {
  5067. if ( pPhysInstance->GetMassScale() > 0 )
  5068. {
  5069. tmpSolid.params.mass *= pPhysInstance->GetMassScale();
  5070. }
  5071. PhysSolidOverride( tmpSolid, pPhysInstance->GetPhysOverrideScript() );
  5072. }
  5073. // Scale our mass up as well
  5074. tmpSolid.params.mass *= flScale;
  5075. tmpSolid.params.volume = physcollision->CollideVolume( pNewCollide );
  5076. // Get our surface prop info
  5077. int surfaceProp = -1;
  5078. if ( tmpSolid.surfaceprop[0] )
  5079. {
  5080. surfaceProp = physprops->GetSurfaceIndex( tmpSolid.surfaceprop );
  5081. }
  5082. // Now put it all back (phew!)
  5083. IPhysicsObject *pNewObject = NULL;
  5084. if ( bWasStatic )
  5085. {
  5086. pNewObject = physenv->CreatePolyObjectStatic( pNewCollide, surfaceProp, pInstance->GetAbsOrigin(), pInstance->GetAbsAngles(), &tmpSolid.params );
  5087. }
  5088. else
  5089. {
  5090. pNewObject = physenv->CreatePolyObject( pNewCollide, surfaceProp, pInstance->GetAbsOrigin(), pInstance->GetAbsAngles(), &tmpSolid.params );
  5091. }
  5092. Assert( pNewObject );
  5093. pInstance->VPhysicsDestroyObject();
  5094. pInstance->VPhysicsSetObject( pNewObject );
  5095. // Increase our model bounds
  5096. const model_t *pModel = modelinfo->GetModel( pInstance->GetModelIndex() );
  5097. if ( pModel )
  5098. {
  5099. Vector mins, maxs;
  5100. modelinfo->GetModelBounds( pModel, mins, maxs );
  5101. pInstance->SetCollisionBounds( mins*flScale, maxs*flScale );
  5102. }
  5103. // Scale the base model as well
  5104. pInstance->SetModelScale( flScale );
  5105. if ( pInstance->GetParent() )
  5106. {
  5107. pNewObject->SetShadow( 1e4, 1e4, false, false );
  5108. pNewObject->UpdateShadow( pInstance->GetAbsOrigin(), pInstance->GetAbsAngles(), false, 0 );
  5109. }
  5110. if ( bWasMotionDisabled )
  5111. {
  5112. pNewObject->EnableMotion( false );
  5113. }
  5114. else
  5115. {
  5116. // Make sure we start awake!
  5117. pNewObject->Wake();
  5118. }
  5119. // Blargh
  5120. pInstance->SetScaledPhysics( ( flScale != 1.0f ) ? pNewObject : NULL );
  5121. return true;
  5122. }
  5123. //------------------------------------------------------------------------------
  5124. // Rotates an entity
  5125. //------------------------------------------------------------------------------
  5126. void CC_Ent_Rotate( const CCommand &args )
  5127. {
  5128. CBasePlayer* pPlayer = UTIL_GetCommandClient();
  5129. CBaseEntity* pEntity = FindPickerEntity( pPlayer );
  5130. if ( !pEntity )
  5131. return;
  5132. QAngle angles = pEntity->GetLocalAngles();
  5133. float flAngle = (args.ArgC() == 2) ? atof( args[1] ) : 7.5f;
  5134. VMatrix entToWorld, rot, newEntToWorld;
  5135. MatrixBuildRotateZ( rot, flAngle );
  5136. MatrixFromAngles( angles, entToWorld );
  5137. MatrixMultiply( entToWorld, rot, newEntToWorld );
  5138. MatrixToAngles( newEntToWorld, angles );
  5139. pEntity->SetLocalAngles( angles );
  5140. }
  5141. static ConCommand ent_rotate("ent_rotate", CC_Ent_Rotate, "Rotates an entity by a specified # of degrees", FCVAR_CHEAT);
  5142. // This is a dummy. The entity is entirely clientside.
  5143. LINK_ENTITY_TO_CLASS( func_proprrespawnzone, CBaseEntity );