summaryrefslogtreecommitdiff
path: root/engine/cmodel_disp.cpp
blob: f805c4ac77269389f3c145bf908340cf5e44af26 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
// $NoKeywords: $
//=============================================================================//

#include <assert.h>
#include <float.h>
#include "cmodel_engine.h"
#include "dispcoll_common.h"
#include "cmodel_private.h"
#include "builddisp.h"
#include "collisionutils.h"
#include "vstdlib/random.h"
#include "tier0/fasttimer.h"
#include "vphysics_interface.h"
#include "vphysics/virtualmesh.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

int g_DispCollTreeCount = 0;
CDispCollTree *g_pDispCollTrees = NULL;
alignedbbox_t *g_pDispBounds = NULL;
class CVirtualTerrain;

//csurface_t dispSurf = { "terrain", 0, 0 };

void CM_PreStab( TraceInfo_t *pTraceInfo, cleaf_t *pLeaf, Vector &vStabDir, int collisionMask, int &contents );
void CM_Stab( TraceInfo_t *pTraceInfo, Vector const &start, Vector const &vStabDir, int contents );
void CM_PostStab( TraceInfo_t *pTraceInfo );

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
static void SetDispTraceSurfaceProps( trace_t *pTrace, CDispCollTree *pDisp )
{
	// use the default surface properties
	pTrace->surface.name = "**displacement**";
	pTrace->surface.flags = 0;
	if ( pTrace->IsDispSurfaceProp2() )
	{
		pTrace->surface.surfaceProps = pDisp->GetSurfaceProps( 1 );
	}
	else
	{
		pTrace->surface.surfaceProps = pDisp->GetSurfaceProps( 0 );
	}
}

class CDispLeafBuilder
{
public:
	CDispLeafBuilder( CCollisionBSPData *pBSPData )
	{
		m_pBSPData = pBSPData;
		// don't want this to resize much, so make the backing buffer large
		m_dispList.EnsureCapacity( MAX_MAP_DISPINFO * 2 );

		// size both of these to the size of the array since there is exactly one per element
		m_leafCount.SetCount( g_DispCollTreeCount );
		m_firstIndex.SetCount( g_DispCollTreeCount );
		for ( int i = 0; i < g_DispCollTreeCount; i++ )
		{
			m_leafCount[i] = 0;
			m_firstIndex[i] = -1;
		}
	}

	void BuildLeafListForDisplacement( int index )
	{
		// get tree and see if it is real (power != 0)
		CDispCollTree *pDispTree = &g_pDispCollTrees[index];
		if( !pDispTree || ( pDispTree->GetPower() == 0 ) )
			return;
		m_firstIndex[index] = m_dispList.Count();
		m_leafCount[index] = 0;
		const int MAX_NODES = 1024;
		int nodeList[MAX_NODES];
		int listRead = 0;
		int listWrite = 1;
		nodeList[0] = m_pBSPData->map_cmodels[0].headnode;
		Vector mins, maxs;
		pDispTree->GetBounds( mins, maxs );

		// UNDONE: The rendering code did this, do we need it?
//		mins -= Vector( 0.5, 0.5, 0.5 );
//		maxs += Vector( 0.5, 0.5, 0.5 );

		while( listRead != listWrite )
		{
			int nodeIndex = nodeList[listRead];
			listRead = (listRead+1)%MAX_NODES;

			// if this is a leaf, add it to the array
			if( nodeIndex < 0 )
			{
				int leafIndex = -1 - nodeIndex;
				m_dispList.AddToTail(leafIndex);
				m_leafCount[index]++;
			}
			else
			{
				//
				// choose side(s) to traverse
				//
				cnode_t *pNode = &m_pBSPData->map_rootnode[nodeIndex];
				cplane_t *pPlane = pNode->plane;

				int sideResult = BOX_ON_PLANE_SIDE( mins, maxs, pPlane );

				// front side
				if( sideResult & 1 )
				{
					nodeList[listWrite] = pNode->children[0];
					listWrite = (listWrite+1)%MAX_NODES;
					Assert(listWrite != listRead);
				}
				// back side
				if( sideResult & 2 )
				{
					nodeList[listWrite] = pNode->children[1];
					listWrite = (listWrite+1)%MAX_NODES;
					Assert(listWrite != listRead);
				}
			}
		}
	}
	int GetDispListCount() { return m_dispList.Count(); }
	void WriteLeafList( unsigned short *pLeafList )
	{
		// clear current count if any
		for ( int i = 0; i < m_pBSPData->numleafs; i++ )
		{
			cleaf_t *pLeaf = &m_pBSPData->map_leafs[i];
			pLeaf->dispCount = 0;
		}
		// compute new count per leaf
		for ( int i = 0; i < m_dispList.Count(); i++ )
		{
			int leafIndex = m_dispList[i];
			cleaf_t *pLeaf = &m_pBSPData->map_leafs[leafIndex];
			pLeaf->dispCount++;
		}
		// point each leaf at the start of it's output range in the output array
		unsigned short firstDispIndex = 0;
		for ( int i = 0; i < m_pBSPData->numleafs; i++ )
		{
			cleaf_t *pLeaf = &m_pBSPData->map_leafs[i];
			pLeaf->dispListStart = firstDispIndex;
			firstDispIndex += pLeaf->dispCount;
			pLeaf->dispCount = 0;
		}
		// now iterate the references in disp order adding to each leaf's (now compact) list
		// for each displacement with leaves
		for ( int i = 0; i < m_leafCount.Count(); i++ )
		{
			// for each leaf in this disp's list
			int count = m_leafCount[i];
			for ( int j = 0; j < count; j++ )
			{
				int listIndex = m_firstIndex[i] + j;					// index to per-disp list
				int leafIndex = m_dispList[listIndex];					// this reference is for one leaf
				cleaf_t *pLeaf = &m_pBSPData->map_leafs[leafIndex];
				int outListIndex = pLeaf->dispListStart + pLeaf->dispCount;	// output position for this leaf
				pLeafList[outListIndex] = i;							// write the reference there
				Assert(outListIndex < GetDispListCount());
				pLeaf->dispCount++;										// move this leaf's output pointer
			}
		}
	}

private:
	CCollisionBSPData *m_pBSPData;
	// this is a list of all of the leaf indices for each displacement
	CUtlVector<unsigned short> m_dispList;
	// this is the first entry into dispList for each displacement
	CUtlVector<int> m_firstIndex;
	// this is the # of leaf entries for each displacement
	CUtlVector<unsigned short> m_leafCount;
};

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CM_DispTreeLeafnum( CCollisionBSPData *pBSPData )
{
	// check to see if there are any displacement trees to push down the bsp tree??
	if( g_DispCollTreeCount == 0 )
		return;

	for ( int i = 0; i < pBSPData->numleafs; i++ )
	{
		pBSPData->map_leafs[i].dispCount = 0;
	}
	//
	// get the number of displacements per leaf
	//
	CDispLeafBuilder leafBuilder( pBSPData );

	for ( int i = 0; i < g_DispCollTreeCount; i++ )
	{
		leafBuilder.BuildLeafListForDisplacement( i );
	}
	int count = leafBuilder.GetDispListCount();
	pBSPData->map_dispList.Attach( count, (unsigned short*)Hunk_Alloc( sizeof(unsigned short) * count, false ) );
	leafBuilder.WriteLeafList( pBSPData->map_dispList.Base() );
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void DispCollTrees_FreeLeafList( CCollisionBSPData *pBSPData )
{
	if ( pBSPData->map_dispList.Base() )
	{
		pBSPData->map_dispList.Detach();
		pBSPData->numdisplist = 0;
	}
}

// Virtual collision models for terrain
class CVirtualTerrain : public IVirtualMeshEvent
{
public:
	CVirtualTerrain()
	{
		m_pDispHullData =  NULL;
	}
	// Fill out the meshlist for this terrain patch
	virtual void GetVirtualMesh( void *userData, virtualmeshlist_t *pList )
	{
		int index = (int)userData;
		Assert(index >= 0 && index < g_DispCollTreeCount );
		g_pDispCollTrees[index].GetVirtualMeshList( pList );
		pList->pHull = NULL;
		if ( m_pDispHullData )
		{
			if ( m_dispHullOffset[index] >= 0 )
			{
				pList->pHull = m_pDispHullData + m_dispHullOffset[index];
			}
		}
	}
	// returns the bounds for the terrain patch
	virtual void GetWorldspaceBounds( void *userData, Vector *pMins, Vector *pMaxs )
	{
		int index = (int)userData;
		*pMins = g_pDispBounds[index].mins;
		*pMaxs = g_pDispBounds[index].maxs;
	}
	// Query against the AABB tree to find the list of triangles for this patch in a sphere
	virtual void GetTrianglesInSphere( void *userData, const Vector &center, float radius, virtualmeshtrianglelist_t *pList )
	{
		int index = (int)userData;
		pList->triangleCount = g_pDispCollTrees[index].AABBTree_GetTrisInSphere( center, radius, pList->triangleIndices, ARRAYSIZE(pList->triangleIndices) );
	}
	void LevelInit( dphysdisp_t *pLump, int lumpSize )
	{
		if ( !pLump )
		{
			m_pDispHullData = NULL;
			return;
		}
		int totalHullData = 0;
		m_dispHullOffset.SetCount(g_DispCollTreeCount);
		Assert(pLump->numDisplacements==g_DispCollTreeCount);
		// count the size of the lump
		unsigned short *pDataSize = (unsigned short *)(pLump+1);
		for ( int i = 0; i < pLump->numDisplacements; i++ )
		{
			if ( pDataSize[i] == (unsigned short)-1 )
			{
				m_dispHullOffset[i] = -1;
				continue;
			}
			m_dispHullOffset[i] = totalHullData;
			totalHullData += pDataSize[i];
		}
		m_pDispHullData = new byte[totalHullData];
		byte *pData = (byte *)(pDataSize + pLump->numDisplacements);
		memcpy( m_pDispHullData, pData, totalHullData );
#if _DEBUG
		int offset = pData - ((byte *)pLump);
		Assert( offset + totalHullData == lumpSize );
#endif
	}
	void LevelShutdown()
	{
		m_dispHullOffset.Purge();
		delete[] m_pDispHullData;
		m_pDispHullData = NULL;
	}

private:
	byte			*m_pDispHullData;
	CUtlVector<int> m_dispHullOffset;
};

// Singleton to implement the callbacks
static CVirtualTerrain g_VirtualTerrain;
// List of terrain collision models for the currently loaded level, indexed by terrain patch index
static CUtlVector<CPhysCollide *> g_TerrainList;

// Find or create virtual terrain collision model.  Note that these will be shared by client & server
CPhysCollide *CM_PhysCollideForDisp( int index )
{
	if ( index < 0 || index >= g_DispCollTreeCount )
		return NULL;

	return g_TerrainList[index];
}

int CM_SurfacepropsForDisp( int index )
{
	return g_pDispCollTrees[index].GetSurfaceProps(0);
}

void CM_CreateDispPhysCollide( dphysdisp_t *pDispLump, int dispLumpSize )
{
	g_VirtualTerrain.LevelInit(pDispLump, dispLumpSize);
	g_TerrainList.SetCount( g_DispCollTreeCount );
	for ( int i = 0; i < g_DispCollTreeCount; i++ )
	{
		// Don't create a physics collision model for displacements that have been tagged as such.
		CDispCollTree *pDispTree = &g_pDispCollTrees[i];
		if ( pDispTree && pDispTree->CheckFlags( CCoreDispInfo::SURF_NOPHYSICS_COLL ) )
		{
			g_TerrainList[i] = NULL;
			continue;
		}
		virtualmeshparams_t params;
		params.pMeshEventHandler = &g_VirtualTerrain;
		params.userData = (void *)i;
		params.buildOuterHull = dispLumpSize > 0 ? false : true;

		g_TerrainList[i] = physcollision->CreateVirtualMesh( params );
	}
}

// End of level, free the collision models
void CM_DestroyDispPhysCollide()
{
	g_VirtualTerrain.LevelShutdown();
	for ( int i = g_TerrainList.Count()-1; i>=0; --i )
	{
		physcollision->DestroyCollide( g_TerrainList[i] );
	}
	g_TerrainList.Purge();
}

//-----------------------------------------------------------------------------
// New Collision!
//-----------------------------------------------------------------------------
void CM_TestInDispTree( TraceInfo_t *pTraceInfo, cleaf_t *pLeaf, const Vector &traceStart,
					   const Vector &boxMin, const Vector &boxMax, int collisionMask, trace_t *pTrace )
{
	bool bIsBox = ( ( boxMin.x != 0.0f ) || ( boxMin.y != 0.0f ) || ( boxMin.z != 0.0f ) ||
		( boxMax.x != 0.0f ) || ( boxMax.y != 0.0f ) || ( boxMax.z != 0.0f ) );

	// box test
	if( bIsBox )
	{
		// Box/Tree intersection test.
		Vector absMins = traceStart + boxMin;
		Vector absMaxs = traceStart + boxMax;

		// Test box against all displacements in the leaf.
		TraceCounter_t *pCounters = pTraceInfo->GetDispCounters();
		int count = pTraceInfo->GetCount();
		for( int i = 0; i < pLeaf->dispCount; i++ )
		{
			int dispIndex = pTraceInfo->m_pBSPData->map_dispList[pLeaf->dispListStart + i];
			alignedbbox_t * RESTRICT pDispBounds = &g_pDispBounds[dispIndex];

			// Respect trace contents
			if( !(pDispBounds->GetContents() & collisionMask) )
				continue;

			if ( !pTraceInfo->Visit( pDispBounds->GetCounter(), count, pCounters ) )
				continue;

			if ( IsBoxIntersectingBox( absMins, absMaxs, pDispBounds->mins, pDispBounds->maxs ) )
			{
				CDispCollTree *pDispTree = &g_pDispCollTrees[dispIndex];
				if( pDispTree->AABBTree_IntersectAABB( absMins, absMaxs ) )
				{
					pTrace->startsolid = true;
					pTrace->allsolid = true;
					pTrace->fraction = 0.0f;
					pTrace->fractionleftsolid = 0.0f;
					pTrace->contents = pDispTree->GetContents();
					return;
				}
			}
		}
	}

	//
	// need to stab if is was a point test or the box test yeilded no intersection
	//
	Vector stabDir;
	int    contents;
	CM_PreStab( pTraceInfo, pLeaf, stabDir, collisionMask, contents );
	CM_Stab( pTraceInfo, traceStart, stabDir, contents );
	CM_PostStab( pTraceInfo );
}


//-----------------------------------------------------------------------------
// New Collision!
//-----------------------------------------------------------------------------
void CM_PreStab( TraceInfo_t *pTraceInfo, cleaf_t *pLeaf, Vector &vStabDir, int collisionMask, int &contents )
{
	if( !pLeaf->dispCount )
		return;

	// if the point wasn't in the bounded area of any of the displacements -- stab in any
	// direction and set contents to "solid"
	int dispIndex = pTraceInfo->m_pBSPData->map_dispList[pLeaf->dispListStart];
	CDispCollTree *pDispTree = &g_pDispCollTrees[dispIndex];
	pDispTree->GetStabDirection( vStabDir );
	contents = CONTENTS_SOLID;

	//
	// if the point is inside a displacement's (in the leaf) bounded area
	// then get the direction to stab from it
	//
	for( int i = 0; i < pLeaf->dispCount; i++ )
	{
		dispIndex = pTraceInfo->m_pBSPData->map_dispList[pLeaf->dispListStart + i];
		pDispTree = &g_pDispCollTrees[dispIndex];

		// Respect trace contents
		if( !(pDispTree->GetContents() & collisionMask) )
			continue;

		if( pDispTree->PointInBounds( pTraceInfo->m_start, pTraceInfo->m_mins, pTraceInfo->m_maxs, pTraceInfo->m_ispoint ) )
		{
			pDispTree->GetStabDirection( vStabDir );
			contents = pDispTree->GetContents();
			return;
		}
	}
}

static Vector InvDelta(const Vector &delta)
{
	Vector vecInvDelta;
	for ( int iAxis = 0; iAxis < 3; ++iAxis )
	{
		if ( delta[iAxis] != 0.0f )
		{
			vecInvDelta[iAxis] = 1.0f / delta[iAxis];
		}
		else
		{
			vecInvDelta[iAxis] = FLT_MAX;
		}
	}
	return vecInvDelta;
}

//-----------------------------------------------------------------------------
// New Collision!
//-----------------------------------------------------------------------------
void CM_Stab( TraceInfo_t *pTraceInfo, const Vector &start, const Vector &vStabDir, int contents )
{
	//
	// initialize the displacement trace parameters
	//
	pTraceInfo->m_trace.fraction = 1.0f;
	pTraceInfo->m_trace.fractionleftsolid = 0.0f;
	pTraceInfo->m_trace.surface = pTraceInfo->m_pBSPData->nullsurface;

	pTraceInfo->m_trace.startsolid = false;
	pTraceInfo->m_trace.allsolid = false;

	pTraceInfo->m_bDispHit = false;
	pTraceInfo->m_DispStabDir = vStabDir;

	Vector end = pTraceInfo->m_end;

	pTraceInfo->m_start = start;
	pTraceInfo->m_end = start + ( vStabDir * /* world extents * 2*/99999.9f );
	pTraceInfo->m_delta = pTraceInfo->m_end - pTraceInfo->m_start;
	pTraceInfo->m_invDelta = InvDelta(pTraceInfo->m_delta);

	// increment the checkcount -- so we can retest objects that may have been tested
	// previous to the stab
	PushTraceVisits( pTraceInfo );

	// increment the stab count -- statistics
#ifdef COUNT_COLLISIONS
	g_CollisionCounts.m_Stabs++;
#endif

	// stab
	CM_RecursiveHullCheck( pTraceInfo, 0 /*root*/, 0.0f, 1.0f );

	PopTraceVisits( pTraceInfo );

	pTraceInfo->m_end = end;
}

//-----------------------------------------------------------------------------
// New Collision!
//-----------------------------------------------------------------------------
void CM_PostStab( TraceInfo_t *pTraceInfo )
{
	//
	// only need to resolve things that impacted against a displacement surface,
	// this is partially resolved in the post trace phase -- so just use that
	// data to determine
	//
	if( pTraceInfo->m_bDispHit && pTraceInfo->m_trace.startsolid )
	{
		pTraceInfo->m_trace.allsolid = true;
		pTraceInfo->m_trace.fraction = 0.0f;
		pTraceInfo->m_trace.fractionleftsolid = 0.0f;
	}
	else
	{
		pTraceInfo->m_trace.startsolid = false;
		pTraceInfo->m_trace.allsolid = false;
		pTraceInfo->m_trace.contents = 0;
		pTraceInfo->m_trace.fraction = 1.0f;
		pTraceInfo->m_trace.fractionleftsolid = 0.0f;
	}
}

//-----------------------------------------------------------------------------
// New Collision!
//-----------------------------------------------------------------------------
void CM_PostTraceToDispTree( TraceInfo_t *pTraceInfo )
{
	// only resolve things that impacted against a displacement surface
	if( !pTraceInfo->m_bDispHit )
		return;

	//
	// determine whether or not we are in solid
	//	
	if( DotProduct( pTraceInfo->m_trace.plane.normal, pTraceInfo->m_delta ) > 0.0f )
	{
		pTraceInfo->m_trace.startsolid = true;
		pTraceInfo->m_trace.allsolid = true;
	}
}

//-----------------------------------------------------------------------------
// New Collision!
//-----------------------------------------------------------------------------
template <bool IS_POINT>
void FASTCALL CM_TraceToDispTree( TraceInfo_t *pTraceInfo, CDispCollTree *pDispTree, float startFrac, float endFrac )
{
	Ray_t ray;
	ray.m_Start = pTraceInfo->m_start;
	ray.m_Delta = pTraceInfo->m_delta;
	ray.m_IsSwept = true;

	trace_t *pTrace = &pTraceInfo->m_trace;

	// ray cast
	if( IS_POINT )
	{
		ray.m_Extents.Init();
		ray.m_IsRay = true;

		if( pDispTree->AABBTree_Ray( ray, pTraceInfo->m_invDelta, pTrace ) )
		{
			pTraceInfo->m_bDispHit = true;
			pTrace->contents = pDispTree->GetContents();
			SetDispTraceSurfaceProps( pTrace, pDispTree );
		}
	}
	// box sweep
	else
	{
		ray.m_Extents = pTraceInfo->m_extents;
		ray.m_IsRay = false;
		if( pDispTree->AABBTree_SweepAABB( ray, pTraceInfo->m_invDelta, pTrace ) )
		{
			pTraceInfo->m_bDispHit = true;
			pTrace->contents = pDispTree->GetContents();
			SetDispTraceSurfaceProps( pTrace, pDispTree );
		}
	}

	//	CM_TraceToDispTreeTest( pDispTree, traceStart, traceEnd, boxMin, boxMax, startFrac, endFrac, pTrace, bRayCast );
}

template void FASTCALL CM_TraceToDispTree<true>( TraceInfo_t *pTraceInfo, CDispCollTree *pDispTree, float startFrac, float endFrac );

template void FASTCALL CM_TraceToDispTree<false>( TraceInfo_t *pTraceInfo, CDispCollTree *pDispTree, float startFrac, float endFrac );