Source

ogre / OgreMain / src / OgreInstanceBatch.cpp

Full commit
  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
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2012 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreInstanceManager.h"
#include "OgreInstanceBatch.h"
#include "OgreSubMesh.h"
#include "OgreRenderOperation.h"
#include "OgreInstancedEntity.h"
#include "OgreSceneNode.h"
#include "OgreCamera.h"
#include "OgreLodStrategy.h"
#include "OgreException.h"

namespace Ogre
{
	InstanceBatch::InstanceBatch( InstanceManager *creator, MeshPtr &meshReference,
									const MaterialPtr &material, size_t instancesPerBatch,
									const Mesh::IndexMap *indexToBoneMap, const String &batchName ) :
				Renderable(),
                MovableObject(),
				mInstancesPerBatch( instancesPerBatch ),
				mCreator( creator ),
				mMaterial( material ),
				mMeshReference( meshReference ),
				mIndexToBoneMap( indexToBoneMap ),
				mBoundingRadius( 0 ),
				mBoundsDirty( false ),
				mBoundsUpdated( false ),
				mCurrentCamera( 0 ),
				mMaterialLodIndex( 0 ),
				mTechnSupportsSkeletal( true ),
				mCachedCamera( 0 ),
				mTransformSharingDirty(true),
				mRemoveOwnVertexData(false),
				mRemoveOwnIndexData(false)
	{
		assert( mInstancesPerBatch );

		//Force batch visibility to be always visible. The instanced entities
		//have individual visibility flags. If none matches the scene's current,
		//then this batch won't rendered.
		mVisibilityFlags = std::numeric_limits<Ogre::uint32>::max();

		if( indexToBoneMap )
		{
			assert( !(meshReference->hasSkeleton() && indexToBoneMap->empty()) );
		}

		mFullBoundingBox.setExtents( -Vector3::ZERO, Vector3::ZERO );

		mName = batchName;
	}

	InstanceBatch::~InstanceBatch()
	{
		deleteAllInstancedEntities();

		//Remove the parent scene node automatically
		SceneNode *sceneNode = getParentSceneNode();
		if( sceneNode )
		{
			sceneNode->detachAllObjects();
			sceneNode->getParentSceneNode()->removeAndDestroyChild( sceneNode->getName() );
		}

		if( mRemoveOwnVertexData )
			OGRE_DELETE mRenderOperation.vertexData;
		if( mRemoveOwnIndexData )
			OGRE_DELETE mRenderOperation.indexData;

	}

	void InstanceBatch::_setInstancesPerBatch( size_t instancesPerBatch )
	{
		if( !mInstancedEntities.empty() )
		{
			OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Instances per batch can only be changed before"
						" building the batch.", "InstanceBatch::_setInstancesPerBatch");
		}

		mInstancesPerBatch = instancesPerBatch;
	}
	//-----------------------------------------------------------------------
	bool InstanceBatch::checkSubMeshCompatibility( const SubMesh* baseSubMesh )
	{
		if( baseSubMesh->operationType != RenderOperation::OT_TRIANGLE_LIST )
		{
			OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Only meshes with OT_TRIANGLE_LIST are supported",
						"InstanceBatch::checkSubMeshCompatibility");
		}

		return true;
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::_updateBounds(void)
	{
		mFullBoundingBox.setNull();

		InstancedEntityVec::const_iterator itor = mInstancedEntities.begin();
		InstancedEntityVec::const_iterator end  = mInstancedEntities.end();

		Real maxScale = 0;
		while( itor != end )
		{
			InstancedEntity* ent = (*itor);
			//Only increase the bounding box for those objects we know are in the scene
			if( ent->isInScene() )
			{
				maxScale = std::max(maxScale, ent->getMaxScaleCoef());
				mFullBoundingBox.merge( ent->_getDerivedPosition() );
			}

			++itor;
		}

		Real addToBound = maxScale * _getMeshReference()->getBoundingSphereRadius();
		mFullBoundingBox.setMaximum(mFullBoundingBox.getMaximum() + addToBound);
		mFullBoundingBox.setMinimum(mFullBoundingBox.getMinimum() - addToBound);


		mBoundingRadius = Math::boundingRadiusFromAABB( mFullBoundingBox );

		//Tell the SceneManager our bounds have changed
		getParentSceneNode()->needUpdate(true);

		mBoundsDirty	= false;
		mBoundsUpdated	= true;
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::updateVisibility(void)
	{
		mVisible = false;

		InstancedEntityVec::const_iterator itor = mInstancedEntities.begin();
		InstancedEntityVec::const_iterator end  = mInstancedEntities.end();

		while( itor != end && !mVisible )
		{
			//Trick to force Ogre not to render us if none of our instances is visible
			//Because we do Camera::isVisible(), it is better if the SceneNode from the
			//InstancedEntity is not part of the scene graph (i.e. ultimate parent is root node)
			//to avoid unnecessary wasteful calculations
			mVisible |= (*itor)->findVisible( mCurrentCamera );
			++itor;
		}
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::createAllInstancedEntities()
	{
		mInstancedEntities.reserve( mInstancesPerBatch );
		mUnusedEntities.reserve( mInstancesPerBatch );

		for( size_t i=0; i<mInstancesPerBatch; ++i )
		{
			InstancedEntity *instance = generateInstancedEntity(i);
			mInstancedEntities.push_back( instance );
			mUnusedEntities.push_back( instance );
		}
	}
	//-----------------------------------------------------------------------
	InstancedEntity* InstanceBatch::generateInstancedEntity(size_t num)
	{
		return OGRE_NEW InstancedEntity( this, num);
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::deleteAllInstancedEntities()
	{
		InstancedEntityVec::const_iterator itor = mInstancedEntities.begin();
		InstancedEntityVec::const_iterator end  = mInstancedEntities.end();

		while( itor != end )
		{
			if( (*itor)->getParentSceneNode() )
				(*itor)->getParentSceneNode()->detachObject( (*itor) );

			OGRE_DELETE *itor++;
		}
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::deleteUnusedInstancedEntities()
	{
		InstancedEntityVec::const_iterator itor = mUnusedEntities.begin();
		InstancedEntityVec::const_iterator end  = mUnusedEntities.end();

		while( itor != end )
			OGRE_DELETE *itor++;

		mUnusedEntities.clear();
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::makeMatrixCameraRelative3x4( float *mat3x4, size_t numFloats )
	{
		const Vector3 &cameraRelativePosition = mCurrentCamera->getDerivedPosition();

		for( size_t i=0; i<numFloats >> 2; i += 3 )
		{
			const Vector3 worldTrans( mat3x4[(i+0) * 4 + 3], mat3x4[(i+1) * 4 + 3],
										mat3x4[(i+2) * 4 + 3] );
			const Vector3 newPos( worldTrans - cameraRelativePosition );

			mat3x4[(i+0) * 4 + 3] = (float)newPos.x;
			mat3x4[(i+1) * 4 + 3] = (float)newPos.y;
			mat3x4[(i+2) * 4 + 3] = (float)newPos.z;
		}
	}
	//-----------------------------------------------------------------------
	RenderOperation InstanceBatch::build( const SubMesh* baseSubMesh )
	{
		if( checkSubMeshCompatibility( baseSubMesh ) )
		{
			//Only triangle list at the moment
			mRenderOperation.operationType	= RenderOperation::OT_TRIANGLE_LIST;
			mRenderOperation.srcRenderable	= this;
			mRenderOperation.useIndexes	= true;
			setupVertices( baseSubMesh );
			setupIndices( baseSubMesh );

			createAllInstancedEntities();
		}

		return mRenderOperation;
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation )
	{
		mRenderOperation = renderOperation;
		createAllInstancedEntities();
	}
	//-----------------------------------------------------------------------
	InstancedEntity* InstanceBatch::createInstancedEntity()
	{
		InstancedEntity *retVal = 0;

		if( !mUnusedEntities.empty() )
		{
			retVal = mUnusedEntities.back();
			mUnusedEntities.pop_back();

			retVal->setInUse(true);
		}

		return retVal;
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::removeInstancedEntity( InstancedEntity *instancedEntity )
	{
		if( instancedEntity->mBatchOwner != this )
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
						"Trying to remove an InstancedEntity from scene created"
						" with a different InstanceBatch",
						"InstanceBatch::removeInstancedEntity()");
		}
		if( !instancedEntity->isInUse() )
		{
			OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
						"Trying to remove an InstancedEntity that is already removed!",
						"InstanceBatch::removeInstancedEntity()");
		}

		if( instancedEntity->getParentSceneNode() )
			instancedEntity->getParentSceneNode()->detachObject( instancedEntity );

		instancedEntity->setInUse(false);
		instancedEntity->stopSharingTransform();

		//Put it back into the queue
		mUnusedEntities.push_back( instancedEntity );
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::getInstancedEntitiesInUse( InstancedEntityVec &outEntities )
	{
		InstancedEntityVec::const_iterator itor = mInstancedEntities.begin();
		InstancedEntityVec::const_iterator end  = mInstancedEntities.end();

		while( itor != end )
		{
			if( (*itor)->isInUse() )
				outEntities.push_back( *itor );
			++itor;
		}
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::defragmentBatchNoCull( InstancedEntityVec &usedEntities )
	{
		const size_t maxInstancesToCopy = std::min( mInstancesPerBatch, usedEntities.size() );
		InstancedEntityVec::iterator first = usedEntities.end() - maxInstancesToCopy;

		//Copy from the back to front, into m_instancedEntities
		mInstancedEntities.insert( mInstancedEntities.begin(), first, usedEntities.end() );
		//Remove them from the array
		usedEntities.resize( usedEntities.size() - maxInstancesToCopy );	
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::defragmentBatchDoCull( InstancedEntityVec &usedEntities )
	{
		//Get the the entity closest to the minimum bbox edge and put into "first"
		InstancedEntityVec::const_iterator itor   = usedEntities.begin();
		InstancedEntityVec::const_iterator end   = usedEntities.end();

		Vector3 vMinPos = Vector3::ZERO, firstPos = Vector3::ZERO;
		InstancedEntity *first = 0;

		if( !usedEntities.empty() )
		{
			first      = *usedEntities.begin();
			firstPos   = first->_getDerivedPosition();
			vMinPos      = first->_getDerivedPosition();
		}

		while( itor != end )
		{
			const Vector3 &vPos      = (*itor)->_getDerivedPosition();

			vMinPos.x = std::min( vMinPos.x, vPos.x );
			vMinPos.y = std::min( vMinPos.y, vPos.y );
			vMinPos.z = std::min( vMinPos.z, vPos.z );

			if( vMinPos.squaredDistance( vPos ) < vMinPos.squaredDistance( firstPos ) )
			{
				firstPos   = vPos;
			}

			++itor;
		}

		//Now collect entities closest to 'first'
		while( !usedEntities.empty() && mInstancedEntities.size() < mInstancesPerBatch )
		{
			InstancedEntityVec::iterator closest   = usedEntities.begin();
			InstancedEntityVec::iterator it         = usedEntities.begin();
			InstancedEntityVec::iterator e          = usedEntities.end();

			Vector3 closestPos;
			closestPos = (*closest)->_getDerivedPosition();

			while( it != e )
			{
				const Vector3 &vPos   = (*it)->_getDerivedPosition();

				if( firstPos.squaredDistance( vPos ) < firstPos.squaredDistance( closestPos ) )
				{
					closest      = it;
					closestPos   = vPos;
				}

				++it;
			}

			mInstancedEntities.push_back( *closest );

			//Remove 'closest' from usedEntities using swap and pop_back trick
			*closest = *(usedEntities.end() - 1);
			usedEntities.pop_back();
		}
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::_defragmentBatch( bool optimizeCulling, InstancedEntityVec &usedEntities )
	{
		//Remove and clear what we don't need
		mInstancedEntities.clear();
		deleteUnusedInstancedEntities();

		if( !optimizeCulling )
			defragmentBatchNoCull( usedEntities );
		else
			defragmentBatchDoCull( usedEntities );

		//Reassign instance IDs and tell we're the new parent
		uint32 instanceId = 0;
		InstancedEntityVec::const_iterator itor = mInstancedEntities.begin();
		InstancedEntityVec::const_iterator end  = mInstancedEntities.end();

		while( itor != end )
		{
			(*itor)->mInstanceId = instanceId++;
			(*itor)->mBatchOwner = this;
			++itor;
		}

		//Recreate unused entities, if there's left space in our container
		assert( (signed)(mInstancesPerBatch) - (signed)(mInstancedEntities.size()) >= 0 );
		mInstancedEntities.reserve( mInstancesPerBatch );
		mUnusedEntities.reserve( mInstancesPerBatch );
		for( size_t i=mInstancedEntities.size(); i<mInstancesPerBatch; ++i )
		{
			InstancedEntity *instance = generateInstancedEntity(i);
			mInstancedEntities.push_back( instance );
			mUnusedEntities.push_back( instance );
		}

		//We've potentially changed our bounds
		if( !isBatchUnused() )
			_boundsDirty();
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::_defragmentBatchDiscard(void)
	{
		//Remove and clear what we don't need
		mInstancedEntities.clear();
		deleteUnusedInstancedEntities();
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::_boundsDirty(void)
	{
		if( mCreator && !mBoundsDirty ) 
			mCreator->_addDirtyBatch( this );
		mBoundsDirty = true;
	}
	//-----------------------------------------------------------------------
	const String& InstanceBatch::getMovableType(void) const
	{
		static String sType = "InstanceBatch";
		return sType;
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::_notifyCurrentCamera( Camera* cam )
	{
		mCurrentCamera = cam;

		//See DistanceLodStrategy::getValueImpl()
		//We use our own because our SceneNode is just filled with zeroes, and updating it
		//with real values is expensive, plus we would need to make sure it doesn't get to
		//the shader
		Real depth = Math::Sqrt( getSquaredViewDepth(cam) ) -
					 mMeshReference->getBoundingSphereRadius();
        depth = std::max( depth, Real(0) );
        Real lodValue = depth * cam->_getLodBiasInverse();

		//Now calculate Material LOD
        /*const LodStrategy *materialStrategy = m_material->getLodStrategy();
        
        //Calculate lod value for given strategy
        Real lodValue = materialStrategy->getValue( this, cam );*/

        //Get the index at this depth
        unsigned short idx = mMaterial->getLodIndex( lodValue );

		//TODO: Replace subEntity for MovableObject
        // Construct event object
        /*EntityMaterialLodChangedEvent subEntEvt;
        subEntEvt.subEntity = this;
        subEntEvt.camera = cam;
        subEntEvt.lodValue = lodValue;
        subEntEvt.previousLodIndex = m_materialLodIndex;
        subEntEvt.newLodIndex = idx;

        //Notify lod event listeners
        cam->getSceneManager()->_notifyEntityMaterialLodChanged(subEntEvt);*/

        //Change lod index
        mMaterialLodIndex = idx;

		MovableObject::_notifyCurrentCamera( cam );
	}
	//-----------------------------------------------------------------------
	const AxisAlignedBox& InstanceBatch::getBoundingBox(void) const
	{
		return mFullBoundingBox;
	}
	//-----------------------------------------------------------------------
	Real InstanceBatch::getBoundingRadius(void) const
	{
		return mBoundingRadius;
	}
	//-----------------------------------------------------------------------
	Real InstanceBatch::getSquaredViewDepth( const Camera* cam ) const
	{
		if( mCachedCamera != cam )
		{
			mCachedCameraDist = std::numeric_limits<Real>::infinity();

			InstancedEntityVec::const_iterator itor = mInstancedEntities.begin();
			InstancedEntityVec::const_iterator end  = mInstancedEntities.end();

			while( itor != end )
			{
				if( (*itor)->isVisible() )
					mCachedCameraDist = std::min( mCachedCameraDist, (*itor)->getSquaredViewDepth( cam ) );
				++itor;
			}

			mCachedCamera = cam;
		}

        return mCachedCameraDist;
	}
	//-----------------------------------------------------------------------
	const LightList& InstanceBatch::getLights( void ) const
	{
		return queryLights();
	}
	//-----------------------------------------------------------------------
	Technique* InstanceBatch::getTechnique( void ) const
	{
		return mMaterial->getBestTechnique( mMaterialLodIndex, this );
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::_updateRenderQueue( RenderQueue* queue )
	{
		/*if( m_boundsDirty )
			_updateBounds();*/

		mDirtyAnimation = false;

		//Is at least one object in the scene?
		updateVisibility();

		if( mVisible )
		{
			if( mMeshReference->hasSkeleton() )
			{
				InstancedEntityVec::const_iterator itor = mInstancedEntities.begin();
				InstancedEntityVec::const_iterator end  = mInstancedEntities.end();

				while( itor != end )	
				{
					mDirtyAnimation |= (*itor)->_updateAnimation();
					++itor;
				}
			}

			queue->addRenderable( this, mRenderQueueID, mRenderQueuePriority );
		}

		//Reset visibility once we skipped addRenderable (which saves GPU time), because OGRE for some
		//reason stops updating our render queue afterwards, preventing us to recalculate visibility
		mVisible = true;
	}
	//-----------------------------------------------------------------------
	void InstanceBatch::visitRenderables( Renderable::Visitor* visitor, bool debugRenderables )
	{
		visitor->visit( this, 0, false );
	}
}