void DiInstanceManager::DefragmentBatches(bool optimizeCull, DiVector<DiInstancedModelPtr> &usedEntities,
        InstanceBatchVec &fragmentedBatches)
    {
        auto itor = fragmentedBatches.begin();
        auto end  = fragmentedBatches.end();

        while( itor != end && !usedEntities.empty() )
        {
            if( !(*itor)->IsStatic() )
            {
                (*itor)->DefragmentBatch( optimizeCull, usedEntities );
            }
            ++itor;
        }

        InstanceBatchVec::iterator lastImportantBatch = itor;

        while( itor != end )
        {
            if( !(*itor)->IsStatic() )
            {
                (*itor)->DefragmentBatchDiscard();
                itor->reset();
            }
            else
            {
                *lastImportantBatch++ = *itor;
            }

            ++itor;
        }

        const size_t remainingBatches = end - lastImportantBatch;
        fragmentedBatches.resize( fragmentedBatches.size() - remainingBatches );
    }
    //-----------------------------------------------------------------------
    void InstanceManager::defragmentBatches( bool optimizeCull,
                                                InstanceBatch::InstancedEntityVec &usedEntities,
                                                InstanceBatch::CustomParamsVec &usedParams,
                                                InstanceBatchVec &fragmentedBatches )
    {
        InstanceBatchVec::iterator itor = fragmentedBatches.begin();
        InstanceBatchVec::iterator end  = fragmentedBatches.end();

        while( itor != end && !usedEntities.empty() )
        {
            if( !(*itor)->isStatic() )
                (*itor)->_defragmentBatch( optimizeCull, usedEntities, usedParams );
            ++itor;
        }

        InstanceBatchVec::iterator lastImportantBatch = itor;

        while( itor != end )
        {
            if( !(*itor)->isStatic() )
            {
                //If we get here, this means we hit remaining batches which will be unused.
                //Destroy them
                //Call this to avoid freeing InstancedEntities that were just reparented
                (*itor)->_defragmentBatchDiscard();
                OGRE_DELETE *itor;
            }
            else
            {
                //This isn't a meaningless batch, move it forward so it doesn't get wipe
                //when we resize the container (faster than removing element by element)
                *lastImportantBatch++ = *itor;
            }

            ++itor;
        }

        //Remove remaining batches all at once from the vector
        const size_t remainingBatches = end - lastImportantBatch;
        fragmentedBatches.resize( fragmentedBatches.size() - remainingBatches );
    }