| 1065 | } |
| 1066 | |
| 1067 | void Tr2ParticleSystem::SortParticles() |
| 1068 | { |
| 1069 | USE_MAIN_THREAD_RENDER_CONTEXT(); |
| 1070 | if( !m_bufferDirty && !m_requiresSorting ) |
| 1071 | { |
| 1072 | return; |
| 1073 | } |
| 1074 | |
| 1075 | if( !m_vertexBuffer.IsValid() ) |
| 1076 | { |
| 1077 | return; |
| 1078 | } |
| 1079 | |
| 1080 | XMMATRIX invWorldTransform = m_worldTransform; |
| 1081 | XMVECTOR determinant; |
| 1082 | invWorldTransform = XMMatrixInverse( &determinant, invWorldTransform ); |
| 1083 | |
| 1084 | const float sortingPointEpsilon = 0.001f; |
| 1085 | XMVECTOR sortingReferencePoint = XMVector3TransformCoord( Tr2Renderer::GetViewPosition(), invWorldTransform ); |
| 1086 | XMVECTOR lengthSq = XMVector3LengthSq( XMVectorSubtract( sortingReferencePoint, *m_sortingReferencePoint ) ); |
| 1087 | if( !m_bufferDirty && XMVectorGetX( lengthSq ) < sortingPointEpsilon ) |
| 1088 | { |
| 1089 | return; |
| 1090 | } |
| 1091 | *m_sortingReferencePoint = sortingReferencePoint; |
| 1092 | |
| 1093 | if( m_aliveCount > 0 ) |
| 1094 | { |
| 1095 | if( m_shouldSortVisible && m_sortingAllowed && m_requiresSorting && HasElement( Tr2ParticleElementDeclarationName::POSITION ) ) |
| 1096 | { |
| 1097 | for( unsigned i = 0; i < m_aliveCount; ++i ) |
| 1098 | { |
| 1099 | m_indexes[i] = i; |
| 1100 | } |
| 1101 | |
| 1102 | Tr2ParallelSort( |
| 1103 | m_indexes, |
| 1104 | m_indexes + m_aliveCount, |
| 1105 | [=]( unsigned particle1, unsigned particle2 ) -> bool { |
| 1106 | return CompareParticles( particle1, particle2 ); |
| 1107 | } ); |
| 1108 | |
| 1109 | if( m_vertexBuffer.IsValid() ) |
| 1110 | { |
| 1111 | float* data; |
| 1112 | CR_RETURN( m_vertexBuffer.MapForWriting( data, renderContext ) ); |
| 1113 | ON_BLOCK_EXIT( [&] { m_vertexBuffer.UnmapForWriting( renderContext ); } ); |
| 1114 | for( unsigned i = 0; i < m_aliveCount; ++i ) |
| 1115 | { |
| 1116 | std::copy( |
| 1117 | m_buffers[Tr2ParticleElementData::GPU] + m_indexes[i] * m_vertexSizes[Tr2ParticleElementData::GPU], |
| 1118 | m_buffers[Tr2ParticleElementData::GPU] + ( m_indexes[i] + 1 ) * m_vertexSizes[Tr2ParticleElementData::GPU], |
| 1119 | data + i * m_vertexSizes[Tr2ParticleElementData::GPU] ); |
| 1120 | } |
| 1121 | } |
| 1122 | } |
| 1123 | else if( m_vertexBuffer.IsValid() ) |
| 1124 | { |
no test coverage detected