diff --git a/trinity/CMakeLists.txt b/trinity/CMakeLists.txt index 749f5c35c..9c238506b 100644 --- a/trinity/CMakeLists.txt +++ b/trinity/CMakeLists.txt @@ -315,6 +315,8 @@ set(_SOURCES Eve/SpaceObject/Attachments/EveMeshOverlayEffect.cpp Eve/SpaceObject/Attachments/EveMeshOverlayEffect.h Eve/SpaceObject/Attachments/EveMeshOverlayEffect_Blue.cpp + Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp + Eve/SpaceObject/Attachments/EveDecalTriangleCache.h Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp new file mode 100644 index 000000000..1e4c5f07d --- /dev/null +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -0,0 +1,688 @@ +// Copyright © 2026 CCP ehf. + +#include "StdAfx.h" +#include "EveDecalTriangleCache.h" +#include "Utilities/BoundingBox.h" +#include "Shader/Tr2EffectStateManager.h" +#include "TbbStub.h" +#include +#include + +CCP_STATS_DECLARE( decalTriangleCacheBytes, "Trinity/decalTriangleCacheBytes", false, CST_MEMORY, "Memory of the CPU triangle caches runtime decals build their geometry from." ); + +namespace +{ +// average number of triangles per cell the finest grid level aims for +constexpr float TRIANGLES_PER_CELL = 4.f; +constexpr uint32_t MAX_CELLS_PER_AXIS = 256; +constexpr float MAX_CELLS = float( 1u << 21 ); +// GPU readbacks a frame may start: each holds the main thread for tens of ms on a large mesh, so a +// burst of first hits on new meshes spreads over frames instead of stalling one +constexpr int MAX_READBACKS_PER_FRAME = 1; +// grid builds in flight at once, out of the hardware threads; a mesh asked for beyond that retries later +constexpr unsigned BUILD_THREADS_SHARE = 4; +constexpr int MIN_CONCURRENT_BUILDS = 2; +// after a failed readback, wait this long before the next, doubling up to the cap +constexpr std::chrono::seconds RETRY_BACKOFF_FIRST( 2 ); +constexpr std::chrono::seconds RETRY_BACKOFF_MAX( 60 ); +// A cache unused this long has its triangles freed. Collisions come in bursts: a grind calls Get every +// metre, and a ship bumping around one level piece comes back to it within seconds, so a minute keeps +// those from paying a rebuild (a readback of tens of ms plus about a second of build) while a ship +// that has moved on gives the memory (~30 bytes per triangle) back. +constexpr std::chrono::seconds IDLE_RELEASE( 60 ); +constexpr std::chrono::seconds IDLE_SWEEP_INTERVAL( 1 ); + +// caches built so far, for EndFrame's idle release; main thread only. Weak, so a mesh released with its cache +// leaves no dangling entry, and no mesh is ever reached through it. +std::vector>& GetCacheRegistry() +{ + static std::vector>* registry = new std::vector>(); + return *registry; +} + +struct BuildQueue +{ + Tr2ParallelTaskGroup group; + std::atomic inFlight = 0; + std::atomic shutDown = false; + const int maxInFlight = std::max( MIN_CONCURRENT_BUILDS, int( std::thread::hardware_concurrency() / BUILD_THREADS_SHARE ) ); + // main thread only + int readbacksThisFrame = 0; +}; + +// never destroyed: Shutdown drains it, and tearing a task group down during static destruction is unsafe +BuildQueue& GetBuildQueue() +{ + static BuildQueue* queue = new BuildQueue(); + return *queue; +} + +// Raw copy of one LOD's buffers, taken on the main thread and converted on the worker +struct RawLod +{ + std::vector vertices; + std::vector indices; + uint32_t vertexCount = 0; + uint32_t indexStride = 4; + uint32_t primitiveCount = 0; +}; + +// Reads one LOD back from the GPU. Returns false if the buffers can't be read. +bool CopyLod( const TriGeometryResMeshData& meshData, TriGeometryResLodData& lod, RawLod& out ) +{ + USE_MAIN_THREAD_RENDER_CONTEXT(); + + const unsigned char* vertices = nullptr; + const unsigned char* indices = nullptr; + if( FAILED( lod.m_vertexAllocation.MapForReading( vertices, renderContext ) ) ) + { + return false; + } + ON_BLOCK_EXIT( [&] { lod.m_vertexAllocation.UnmapForReading( renderContext ); } ); + if( FAILED( lod.m_indexAllocation.MapForReading( indices, renderContext ) ) ) + { + return false; + } + ON_BLOCK_EXIT( [&] { lod.m_indexAllocation.UnmapForReading( renderContext ); } ); + + out.vertexCount = meshData.m_bytesPerVertex ? std::min( lod.m_vertexCount, lod.m_vertexAllocation.GetSize() / meshData.m_bytesPerVertex ) : 0; + out.indexStride = lod.m_indexAllocation.GetStride() == 2 ? 2 : 4; + out.primitiveCount = std::min( lod.m_primitiveCount, lod.m_indexAllocation.GetSize() / ( out.indexStride * 3 ) ); + out.vertices.assign( vertices, vertices + size_t( out.vertexCount ) * meshData.m_bytesPerVertex ); + out.indices.assign( indices, indices + size_t( out.primitiveCount ) * 3 * out.indexStride ); + return true; +} + +void ConvertLod( const RawLod& raw, uint32_t bytesPerVertex, bool positionsCompressed, DecalTriangleCache::Lod& out ) +{ + out.positions.resize( raw.vertexCount ); + for( uint32_t v = 0; v < raw.vertexCount; ++v ) + { + const uint8_t* vertex = raw.vertices.data() + size_t( v ) * bytesPerVertex; + if( positionsCompressed ) + { + out.positions[v] = *reinterpret_cast( vertex ); + } + else + { + out.positions[v] = *reinterpret_cast( vertex ); + } + } + + const size_t indexCount = size_t( raw.primitiveCount ) * 3; + out.indices.resize( indexCount ); + for( size_t i = 0; i < indexCount; ++i ) + { + uint32_t index = raw.indexStride == 2 ? reinterpret_cast( raw.indices.data() )[i] : reinterpret_cast( raw.indices.data() )[i]; + out.indices[i] = index < raw.vertexCount ? index : 0; + } +} + +uint32_t CellCoordinate( float value, float origin, float invCellSize, uint32_t dim ) +{ + return uint32_t( std::clamp( ( value - origin ) * invCellSize, 0.f, float( dim - 1 ) ) ); +} + +void BuildGrid( DecalTriangleCache::Lod& lod ) +{ + const size_t triangleCount = lod.indices.size() / 3; + if( triangleCount == 0 || lod.positions.empty() ) + { + lod.levels.assign( 1, {} ); + lod.cellStart.assign( 2, 0 ); + return; + } + + Vector3 minBounds( FLT_MAX, FLT_MAX, FLT_MAX ); + Vector3 maxBounds( -FLT_MAX, -FLT_MAX, -FLT_MAX ); + for( const auto& p : lod.positions ) + { + minBounds = Minimize( minBounds, p ); + maxBounds = Maximize( maxBounds, p ); + } + + // finest level: cells proportional to the extents, aiming for TRIANGLES_PER_CELL triangles per cell; + // every coarser level halves the cell count per axis until one cell covers everything + Vector3 extents = maxBounds - minBounds; + float largest = std::max( { extents.x, extents.y, extents.z, 1e-6f } ); + const float e[3] = { std::max( extents.x, largest * 1e-3f ), std::max( extents.y, largest * 1e-3f ), std::max( extents.z, largest * 1e-3f ) }; + float targetCells = std::clamp( float( triangleCount ) / TRIANGLES_PER_CELL, 1.f, MAX_CELLS ); + float cellEdge = std::cbrt( e[0] * e[1] * e[2] / targetCells ); + uint32_t dims[3]; + for( int a = 0; a < 3; ++a ) + { + dims[a] = std::clamp( uint32_t( std::ceil( e[a] / cellEdge ) ), 1u, MAX_CELLS_PER_AXIS ); + } + lod.levels.clear(); + uint32_t totalCells = 0; + for( ;; ) + { + DecalTriangleCache::Level level; + level.origin = minBounds; + level.cellSize = Vector3( e[0] / dims[0], e[1] / dims[1], e[2] / dims[2] ); + level.invCellSize = Vector3( dims[0] / e[0], dims[1] / e[1], dims[2] / e[2] ); + std::copy( dims, dims + 3, level.dims ); + level.firstCell = totalCells; + totalCells += dims[0] * dims[1] * dims[2]; + lod.levels.push_back( level ); + if( dims[0] == 1 && dims[1] == 1 && dims[2] == 1 ) + { + break; + } + for( auto& d : dims ) + { + d = std::max( 1u, ( d + 1 ) / 2 ); + } + } + // the coarsest level is one cell: make sure it takes any triangle, including degenerate bounds + lod.levels.back().cellSize = Vector3( FLT_MAX, FLT_MAX, FLT_MAX ); + + // each triangle goes to the cell of its centre on the finest level whose cells it fits in + std::vector triangleCell( triangleCount ); + lod.cellStart.assign( size_t( totalCells ) + 1, 0 ); + for( size_t t = 0; t < triangleCount; ++t ) + { + const Vector3& a = lod.positions[lod.indices[t * 3 + 0]]; + const Vector3& b = lod.positions[lod.indices[t * 3 + 1]]; + const Vector3& c = lod.positions[lod.indices[t * 3 + 2]]; + Vector3 lo = Minimize( Minimize( a, b ), c ); + Vector3 hi = Maximize( Maximize( a, b ), c ); + Vector3 size = hi - lo; + Vector3 centre = ( lo + hi ) * 0.5f; + size_t l = 0; + while( size.x > lod.levels[l].cellSize.x || size.y > lod.levels[l].cellSize.y || size.z > lod.levels[l].cellSize.z ) + { + ++l; + } + const auto& level = lod.levels[l]; + uint32_t x = CellCoordinate( centre.x, level.origin.x, level.invCellSize.x, level.dims[0] ); + uint32_t y = CellCoordinate( centre.y, level.origin.y, level.invCellSize.y, level.dims[1] ); + uint32_t z = CellCoordinate( centre.z, level.origin.z, level.invCellSize.z, level.dims[2] ); + uint32_t cell = level.firstCell + ( z * level.dims[1] + y ) * level.dims[0] + x; + triangleCell[t] = cell; + ++lod.cellStart[cell + 1]; + } + for( uint32_t c = 0; c < totalCells; ++c ) + { + lod.cellStart[c + 1] += lod.cellStart[c]; + } + + // counting sort the triangles by cell + std::vector sorted( lod.indices.size() ); + std::vector cursor( lod.cellStart.begin(), lod.cellStart.end() - 1 ); + for( size_t t = 0; t < triangleCount; ++t ) + { + uint32_t to = cursor[triangleCell[t]]++; + std::copy( &lod.indices[t * 3], &lod.indices[t * 3] + 3, &sorted[size_t( to ) * 3] ); + } + lod.indices.swap( sorted ); +} +} + +const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshData ) +{ + if( !meshData ) + { + return nullptr; + } + + auto& cache = meshData->m_decalTriangleCache; + const auto now = std::chrono::steady_clock::now(); + if( cache && cache->failed && now < cache->retryAt ) + { + return nullptr; + } + if( cache && !cache->failed && !cache->released && cache->lodMask == meshData->m_lodMask && cache->lods.size() == meshData->m_lods.size() ) + { + if( !cache->ready.load( std::memory_order_acquire ) ) + { + return nullptr; + } + cache->lastUsed = now; + if( cache->reportedBytes.load() == 0 ) + { + int64_t bytes = int64_t( cache->GetMemoryUsage() ); + cache->reportedBytes.store( bytes ); + CCP_STATS_ADD( decalTriangleCacheBytes, bytes ); + } + return cache.get(); + } + + TRINITY_STATS_ZONE( __FUNCTION__ ); + + BuildQueue& queue = GetBuildQueue(); + if( queue.shutDown.load() || queue.inFlight.load() >= queue.maxInFlight || queue.readbacksThisFrame >= MAX_READBACKS_PER_FRAME ) + { + return nullptr; + } + + for( auto& lod : meshData->m_lods ) + { + if( !lod->m_allocationsValid ) + { + return nullptr; + } + } + + bool positionsCompressed = false; + Tr2VertexDefinition vd; + if( Tr2EffectStateManager::GetVertexDeclarationElements( meshData->m_vertexDeclarationHandle, vd ) ) + { + if( auto pos = vd.Find( vd.POSITION ) ) + { + positionsCompressed = pos->m_dataType == vd.FLOAT16_4; + } + } + + ++queue.readbacksThisFrame; + std::vector raw( meshData->m_lods.size() ); + for( size_t i = 0; i < meshData->m_lods.size(); ++i ) + { + if( !CopyLod( *meshData, *meshData->m_lods[i], raw[i] ) ) + { + // a readback costs tens of ms on a large mesh: don't repeat it every frame + uint32_t failures = cache && cache->failed ? cache->failures + 1 : 1; + auto backoff = std::min( RETRY_BACKOFF_FIRST * ( 1 << std::min( failures - 1, 5u ) ), RETRY_BACKOFF_MAX ); + auto failedCache = std::make_shared(); + failedCache->failed = true; + failedCache->failures = failures; + failedCache->retryAt = now + backoff; + cache = failedCache; + return nullptr; + } + } + + auto newCache = std::make_shared(); + newCache->lodMask = meshData->m_lodMask; + newCache->lods.resize( meshData->m_lods.size() ); + newCache->lastUsed = now; + cache = newCache; + GetCacheRegistry().push_back( newCache ); + + // the task only touches its own copies, so the mesh may be released while it runs + ++queue.inFlight; + queue.group.run( [newCache, raw = std::move( raw ), bytesPerVertex = meshData->m_bytesPerVertex, positionsCompressed, &queue]() { + for( size_t i = 0; i < raw.size() && !queue.shutDown.load(); ++i ) + { + ConvertLod( raw[i], bytesPerVertex, positionsCompressed, newCache->lods[i] ); + BuildGrid( newCache->lods[i] ); + } + if( !queue.shutDown.load() ) + { + newCache->ready.store( true, std::memory_order_release ); + } + --queue.inFlight; + } ); + return nullptr; +} + +bool DecalTriangleCache::IsDeformed( const TriGeometryResMeshData& meshData ) +{ + for( const auto& lod : meshData.m_lods ) + { + for( const auto& area : lod->m_areas ) + { + if( area.m_isSkinned || area.m_isMorphed ) + { + return true; + } + } + } + return false; +} + +void DecalTriangleCache::Shutdown() +{ + BuildQueue& queue = GetBuildQueue(); + queue.shutDown.store( true ); + queue.group.cancel(); + queue.group.wait(); +} + +namespace +{ +// Calls fn( triangle ) for each triangle of lod whose bounds touch [aabbMin, aabbMax]. +template +void ForEachTriangleNear( const DecalTriangleCache::Lod& lod, const Vector3& aabbMin, const Vector3& aabbMax, Fn&& fn ) +{ + for( const auto& level : lod.levels ) + { + // a triangle stored here is no larger than a cell, so its centre is within half a cell of the box + Vector3 margin = Minimize( level.cellSize * 0.5f, Vector3( 1e30f, 1e30f, 1e30f ) ); + Vector3 lo = aabbMin - margin; + Vector3 hi = aabbMax + margin; + uint32_t x0 = CellCoordinate( lo.x, level.origin.x, level.invCellSize.x, level.dims[0] ); + uint32_t y0 = CellCoordinate( lo.y, level.origin.y, level.invCellSize.y, level.dims[1] ); + uint32_t z0 = CellCoordinate( lo.z, level.origin.z, level.invCellSize.z, level.dims[2] ); + uint32_t x1 = CellCoordinate( hi.x, level.origin.x, level.invCellSize.x, level.dims[0] ); + uint32_t y1 = CellCoordinate( hi.y, level.origin.y, level.invCellSize.y, level.dims[1] ); + uint32_t z1 = CellCoordinate( hi.z, level.origin.z, level.invCellSize.z, level.dims[2] ); + for( uint32_t z = z0; z <= z1; ++z ) + { + for( uint32_t y = y0; y <= y1; ++y ) + { + // cells x0..x1 of a row are contiguous, and so are their triangles + uint32_t row = level.firstCell + ( z * level.dims[1] + y ) * level.dims[0]; + for( uint32_t t = lod.cellStart[row + x0]; t < lod.cellStart[row + x1 + 1]; ++t ) + { + const uint32_t* tri = &lod.indices[size_t( t ) * 3]; + const Vector3& v0 = lod.positions[tri[0]]; + const Vector3& v1 = lod.positions[tri[1]]; + const Vector3& v2 = lod.positions[tri[2]]; + // cheap bounds reject before any exact test + if( std::max( { v0.x, v1.x, v2.x } ) < aabbMin.x || std::min( { v0.x, v1.x, v2.x } ) > aabbMax.x || + std::max( { v0.y, v1.y, v2.y } ) < aabbMin.y || std::min( { v0.y, v1.y, v2.y } ) > aabbMax.y || + std::max( { v0.z, v1.z, v2.z } ) < aabbMin.z || std::min( { v0.z, v1.z, v2.z } ) > aabbMax.z ) + { + continue; + } + fn( tri ); + } + } + } + } +} + +// A vertex position rounded to a tenth of a millimetre, so split vertices compare equal +struct VertexKey +{ + int64_t x, y, z; + bool operator==( const VertexKey& other ) const + { + return x == other.x && y == other.y && z == other.z; + } + bool operator<( const VertexKey& other ) const + { + return x != other.x ? x < other.x : y != other.y ? y < other.y : z < other.z; + } +}; + +VertexKey MakeKey( const Vector3& p ) +{ + return { int64_t( std::llround( p.x * 1e4f ) ), int64_t( std::llround( p.y * 1e4f ) ), int64_t( std::llround( p.z * 1e4f ) ) }; +} + +struct EdgeKey +{ + VertexKey a, b; + bool operator==( const EdgeKey& other ) const + { + return a == other.a && b == other.b; + } +}; + +struct EdgeKeyHash +{ + size_t operator()( const EdgeKey& key ) const + { + size_t h = 1469598103934665603ull; + for( int64_t v : { key.a.x, key.a.y, key.a.z, key.b.x, key.b.y, key.b.z } ) + { + h = ( h ^ size_t( v ) ) * 1099511628211ull; + } + return h; + } +}; + +struct EdgeFaces +{ + Vector3 p0, p1; + Vector3 normals[2]; + uint32_t count = 0; +}; + +// Closest point to p on triangle abc (Ericson, Real-Time Collision Detection 5.1.5) +Vector3 ClosestPointOnTriangle( const Vector3& p, const Vector3& a, const Vector3& b, const Vector3& c ) +{ + Vector3 ab = b - a, ac = c - a, ap = p - a; + float d1 = Dot( ab, ap ), d2 = Dot( ac, ap ); + if( d1 <= 0.f && d2 <= 0.f ) + { + return a; + } + Vector3 bp = p - b; + float d3 = Dot( ab, bp ), d4 = Dot( ac, bp ); + if( d3 >= 0.f && d4 <= d3 ) + { + return b; + } + float vc = d1 * d4 - d3 * d2; + if( vc <= 0.f && d1 >= 0.f && d3 <= 0.f ) + { + return a + ab * ( d1 / ( d1 - d3 ) ); + } + Vector3 cp = p - c; + float d5 = Dot( ab, cp ), d6 = Dot( ac, cp ); + if( d6 >= 0.f && d5 <= d6 ) + { + return c; + } + float vb = d5 * d2 - d1 * d6; + if( vb <= 0.f && d2 >= 0.f && d6 <= 0.f ) + { + return a + ac * ( d2 / ( d2 - d6 ) ); + } + float va = d3 * d6 - d5 * d4; + if( va <= 0.f && ( d4 - d3 ) >= 0.f && ( d5 - d6 ) >= 0.f ) + { + return b + ( c - b ) * ( ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ) ); + } + float denom = 1.f / ( va + vb + vc ); + return a + ab * ( vb * denom ) + ac * ( vc * denom ); +} + +Vector3 ClosestPointOnSegment( const Vector3& p, const Vector3& a, const Vector3& b ) +{ + Vector3 ab = b - a; + float lengthSq = Dot( ab, ab ); + float t = lengthSq > 0.f ? std::clamp( Dot( p - a, ab ) / lengthSq, 0.f, 1.f ) : 0.f; + return a + ab * t; +} +} + +void DecalTriangleCache::Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, const Vector3& projectionAxis, float minFacing, std::vector& out ) const +{ + if( lodIndex >= lods.size() ) + { + return; + } + const Lod& lod = lods[lodIndex]; + ForEachTriangleNear( lod, aabbMin, aabbMax, [&]( const uint32_t* tri ) { + const Vector3* v0 = &lod.positions[tri[0]]; + const Vector3* v1 = &lod.positions[tri[1]]; + const Vector3* v2 = &lod.positions[tri[2]]; + if( minFacing > 0.f ) + { + Vector3 faceNormal = Cross( *v1 - *v0, *v2 - *v0 ); + float length = Length( faceNormal ); + if( length < 1e-12f || std::abs( Dot( faceNormal, projectionAxis ) ) < minFacing * length ) + { + return; + } + } + if( IntersectTriangleAABB( v0, v1, v2, aabbMin, aabbMax ) && IntersectTriangleOrientedBox( v0, v1, v2, inverseDecalMatrix ) ) + { + out.insert( out.end(), tri, tri + 3 ); + } + } ); +} + +bool DecalTriangleCache::FindNearestEdge( size_t lodIndex, const Vector3& point, float radius, float sharpCos, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const +{ + if( lodIndex >= lods.size() || radius <= 0.f ) + { + return false; + } + const Lod& lod = lods[lodIndex]; + const Vector3 extent( radius, radius, radius ); + + // Every edge that comes within radius of point lies in this box, and so does every + // triangle on either side of it: an edge's faces are all gathered, so a fold is never + // mistaken for an open edge because its other face was out of the query. + std::unordered_map edges; + ForEachTriangleNear( lod, point - extent, point + extent, [&]( const uint32_t* tri ) { + const Vector3& v0 = lod.positions[tri[0]]; + const Vector3& v1 = lod.positions[tri[1]]; + const Vector3& v2 = lod.positions[tri[2]]; + Vector3 faceNormal = Cross( v1 - v0, v2 - v0 ); + float area = Length( faceNormal ); + if( area < 1e-8f ) + { + return; + } + faceNormal = faceNormal / area; + const Vector3* corners[3] = { &v0, &v1, &v2 }; + for( int i = 0; i < 3; ++i ) + { + const Vector3& a = *corners[i]; + const Vector3& b = *corners[( i + 1 ) % 3]; + VertexKey ka = MakeKey( a ); + VertexKey kb = MakeKey( b ); + if( ka == kb ) + { + continue; + } + EdgeKey key = kb < ka ? EdgeKey{ kb, ka } : EdgeKey{ ka, kb }; + EdgeFaces& faces = edges[key]; + if( faces.count == 0 ) + { + faces.p0 = a; + faces.p1 = b; + } + if( faces.count < 2 ) + { + faces.normals[faces.count] = faceNormal; + } + ++faces.count; + } + } ); + + bool found = false; + float bestDistance = radius; + for( const auto& entry : edges ) + { + const EdgeFaces& faces = entry.second; + Vector3 normal; + if( faces.count == 1 ) + { + normal = faces.normals[0]; + } + else if( faces.count == 2 && Dot( faces.normals[0], faces.normals[1] ) < sharpCos ) + { + normal = faces.normals[0] + faces.normals[1]; + float length = Length( normal ); + // two faces folded flat onto each other (a thin fin): either face will do + normal = length > 1e-4f ? normal / length : faces.normals[0]; + } + else + { + // a smooth fold, or a non-manifold edge shared by more than two triangles + continue; + } + Vector3 closest = ClosestPointOnSegment( point, faces.p0, faces.p1 ); + float distance = Length( closest - point ); + if( distance <= bestDistance ) + { + found = true; + bestDistance = distance; + outPosition = closest; + outNormal = normal; + } + } + outDistance = bestDistance; + return found; +} + +bool DecalTriangleCache::FindNearestSurface( size_t lodIndex, const Vector3& point, float radius, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const +{ + if( lodIndex >= lods.size() || radius <= 0.f ) + { + return false; + } + const Lod& lod = lods[lodIndex]; + const Vector3 extent( radius, radius, radius ); + bool found = false; + float bestDistance = radius; + ForEachTriangleNear( lod, point - extent, point + extent, [&]( const uint32_t* tri ) { + const Vector3& v0 = lod.positions[tri[0]]; + const Vector3& v1 = lod.positions[tri[1]]; + const Vector3& v2 = lod.positions[tri[2]]; + Vector3 faceNormal = Cross( v1 - v0, v2 - v0 ); + float area = Length( faceNormal ); + if( area < 1e-8f ) + { + return; + } + Vector3 closest = ClosestPointOnTriangle( point, v0, v1, v2 ); + float distance = Length( closest - point ); + if( distance <= bestDistance ) + { + found = true; + bestDistance = distance; + outPosition = closest; + faceNormal = faceNormal / area; + // either winding: face the side the query point is on + outNormal = Dot( faceNormal, point - closest ) < 0.f ? -faceNormal : faceNormal; + } + } ); + outDistance = bestDistance; + return found; +} + +void DecalTriangleCache::EndFrame() +{ + GetBuildQueue().readbacksThisFrame = 0; + + static std::chrono::steady_clock::time_point nextSweep; + const auto now = std::chrono::steady_clock::now(); + if( now < nextSweep ) + { + return; + } + nextSweep = now + IDLE_SWEEP_INTERVAL; + + auto& registry = GetCacheRegistry(); + registry.erase( std::remove_if( registry.begin(), registry.end(), [&]( const std::weak_ptr& entry ) { + auto cache = entry.lock(); + if( !cache ) + { + return true; + } + // a cache still building belongs to its task until it is ready: leave it alone + if( !cache->ready.load( std::memory_order_acquire ) || now - cache->lastUsed < IDLE_RELEASE ) + { + return false; + } + std::vector().swap( cache->lods ); + cache->released = true; + cache->ready.store( false, std::memory_order_release ); + if( int64_t bytes = cache->reportedBytes.exchange( 0 ) ) + { + CCP_STATS_ADD( decalTriangleCacheBytes, -bytes ); + } + return true; + } ), + registry.end() ); +} + +DecalTriangleCache::~DecalTriangleCache() +{ + if( int64_t bytes = reportedBytes.load() ) + { + CCP_STATS_ADD( decalTriangleCacheBytes, -bytes ); + } +} + +size_t DecalTriangleCache::GetMemoryUsage() const +{ + size_t bytes = sizeof( *this ); + for( const auto& lod : lods ) + { + bytes += sizeof( lod ); + bytes += lod.positions.capacity() * sizeof( Vector3 ); + bytes += lod.indices.capacity() * sizeof( uint32_t ); + bytes += lod.levels.capacity() * sizeof( Level ); + bytes += lod.cellStart.capacity() * sizeof( uint32_t ); + } + return bytes; +} diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h new file mode 100644 index 000000000..1014e2454 --- /dev/null +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -0,0 +1,120 @@ +// Copyright © 2026 CCP ehf. + +#pragma once + +#include "../../../Resources/TriGeometryRes.h" +#include +#include + +/** + * @brief CPU copy of a mesh's triangles, bucketed in a hierarchical loose grid per LOD, so that a runtime + * decal only tests the triangles near its volume instead of reading back and scanning the whole mesh. + * + * Each triangle is stored once, in the cell of its centre on the finest grid level whose cells are at + * least as large as the triangle; a query looks at every level with its box grown by half a cell there. + * + * The first runtime decal build against a mesh reads the mesh back from the GPU on the main thread and + * builds the grid as a task in a shared task group. A frame does at most one readback (tens of ms on a + * large mesh) and a quarter of the hardware threads (at least two) build at once; until its build + * finishes, Get returns null and the decal tries again on a later frame. The cache is owned by the mesh's TriGeometryResMeshData, + * so it is released together with the geometry (TriGeometryRes::ReleaseResources clears the mesh data on + * release, re-initialization and reload). It is also rebuilt if the mesh's LOD set no longer matches. + * Its memory is reported as Trinity/decalTriangleCacheBytes. A ready cache that Get has not handed out + * for IDLE_RELEASE has its triangles freed by EndFrame; the next Get against the mesh rebuilds it. + */ +struct DecalTriangleCache +{ + struct Level + { + Vector3 origin = Vector3( 0.f, 0.f, 0.f ); + Vector3 cellSize = Vector3( 0.f, 0.f, 0.f ); + Vector3 invCellSize = Vector3( 0.f, 0.f, 0.f ); + uint32_t dims[3] = { 1, 1, 1 }; + // index of this level's first cell in Lod::cellStart + uint32_t firstCell = 0; + }; + + struct Lod + { + std::vector positions; + // 3 per triangle, the LOD's index buffer values, reordered so each cell's triangles are contiguous + std::vector indices; + std::vector levels; + // triangles cellStart[c] .. cellStart[c + 1] (in units of triangles) belong to cell c + std::vector cellStart; + }; + + uint32_t lodMask = 0; + std::vector lods; + // set by the worker thread once lods can be read + std::atomic ready = false; + // the mesh could not be read back: Get does not try again before retryAt + bool failed = false; + uint32_t failures = 0; + std::chrono::steady_clock::time_point retryAt; + // bytes added to the Trinity/decalTriangleCacheBytes statistic, taken off again on destruction + std::atomic reportedBytes = 0; + // when Get last handed this cache out; EndFrame frees the triangles of a cache idle too long + std::chrono::steady_clock::time_point lastUsed; + // EndFrame freed the triangles: Get rebuilds the cache + bool released = false; + + ~DecalTriangleCache(); + + /** + * @brief Returns the cache for meshData, starting to build it if needed. + * @return null while the mesh's buffers or the cache are not ready yet. + */ + static const DecalTriangleCache* Get( TriGeometryResMeshData* meshData ); + + /** + * @brief Whether any area of the mesh is skinned or morphed. Its vertices move away from the + * positions the cache holds, so a decal or a nearest query built on them would land wrong. + */ + static bool IsDeformed( const TriGeometryResMeshData& meshData ); + + /** + * @brief Cancels the builds that have not started and waits for the running ones. Get starts no + * build afterwards. + */ + static void Shutdown(); + + /** + * @brief Called once a frame on the main thread (Tr2Renderer::EndFrame): opens the next frame's + * readback, and at most once a second frees the triangles of every ready cache Get has not handed + * out for IDLE_RELEASE. + */ + static void EndFrame(); + + /** + * @brief Appends the indices of the triangles of LOD lodIndex that intersect the decal volume. + * @param aabbMin, aabbMax Bounds of the decal volume in the mesh's vertex space. + * @param inverseDecalMatrix Maps the mesh's vertex space into decal space (the volume is [-1, 1]^3). + * @param projectionAxis Unit direction the decal projects along, in the mesh's vertex space. + * @param minFacing Triangles whose face normal is closer to perpendicular to projectionAxis than + * this (|cos| of the angle between them) are left out: the decal's texture would smear along + * them. Either winding counts. Pass a value <= 0 to keep every triangle. + */ + void Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, const Vector3& projectionAxis, float minFacing, std::vector& out ) const; + + /** + * @brief Finds the point on a hull edge of LOD lodIndex nearest to point, within radius. + * + * An edge is where two triangles meet at a fold sharper than sharpCos (the cosine of the + * angle between their face normals), or an open edge with a triangle on one side only. + * Vertices are matched by position, so the split vertices of a hard edge still join up. + * @param outNormal The two faces' normals averaged (a face's own on an open edge): a + * decal projected along it wraps over the edge onto both faces. + * @return false if no edge lies within radius. + */ + bool FindNearestEdge( size_t lodIndex, const Vector3& point, float radius, float sharpCos, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const; + + /** + * @brief Finds the point on a triangle of LOD lodIndex nearest to point, within radius. + * @param outNormal The triangle's face normal, turned to the side point is on. + * @return false if no triangle lies within radius. + */ + bool FindNearestSurface( size_t lodIndex, const Vector3& point, float radius, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const; + + size_t GetMemoryUsage() const; +}; diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 52e288c8d..7f4362a0a 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -14,6 +14,8 @@ #include "TriFrustum.h" #include "Tr2InstancedMesh.h" #include "TriSettingsRegistrar.h" +#include "Eve/SpaceObject/Children/EveSpaceObjectChild.h" +#include "EveDecalTriangleCache.h" CCP_STATS_DECLARED_ELSEWHERE( primitiveCount ); @@ -49,7 +51,9 @@ EveSpaceObjectDecal::EveSpaceObjectDecal( IRoot* lockobj ) : m_instanceData( nullptr ), m_minBounds( 0, 0, 0 ), m_maxBounds( 0, 0, 0 ), - m_isGeometryFrozen( false ) + m_isGeometryFrozen( false ), + m_dynamicIndexBuffers( false ), + m_usePartTargets( false ) { // init PrepareResources(); @@ -70,12 +74,43 @@ void EveSpaceObjectDecal::UpdateDecalMatrix() m_decalMatrix = TransformationMatrix( m_scaling, m_rotation, m_position ); // and calc the inverse right away, is needed for intersection m_inverseDecalMatrix = Inverse( m_decalMatrix ); + UpdateDrawDecalMatrix(); +} + +void EveSpaceObjectDecal::UpdateDrawDecalMatrix() +{ + // a grow from 0 must not make the drawn volume singular + constexpr float MIN_GROW = 1e-4f; + Vector3 grow( std::max( m_growScale.x, MIN_GROW ), std::max( m_growScale.y, MIN_GROW ), std::max( m_growScale.z, MIN_GROW ) ); + m_drawDecalMatrix = ScalingMatrix( grow ) * m_decalMatrix; + m_drawInverseDecalMatrix = Inverse( m_drawDecalMatrix ); +} + +namespace +{ +// Whether the volume decalMatrix maps [-1, 1]^3 to lies inside the one builtInverse maps back to it +bool IsVolumeInside( const Matrix& decalMatrix, const Matrix& builtInverse ) +{ + constexpr float SLACK = 1e-3f; + Matrix toBuilt = decalMatrix * builtInverse; + for( int corner = 0; corner < 8; ++corner ) + { + Vector3 p( corner & 1 ? 1.f : -1.f, corner & 2 ? 1.f : -1.f, corner & 4 ? 1.f : -1.f ); + Vector3 q = XMVector3TransformCoord( p, toBuilt ); + if( std::abs( q.x ) > 1.f + SLACK || std::abs( q.y ) > 1.f + SLACK || std::abs( q.z ) > 1.f + SLACK ) + { + return false; + } + } + return true; +} } // ------------------------------------------------------------------------------------------------------ bool EveSpaceObjectDecal::Initialize() { UpdateDecalMatrix(); + m_builtInverseDecalMatrix = m_inverseDecalMatrix; PrepareResources(); @@ -89,15 +124,43 @@ bool EveSpaceObjectDecal::OnModified( Be::Var* value ) { // update the decal matrix UpdateDecalMatrix(); + if( !HasStaticIndexBuffers() && HasBuiltRuntimeGeometry() && IsVolumeInside( m_decalMatrix, m_builtInverseDecalMatrix ) ) + { + // every triangle the new volume touches is in the built geometry already, and the shader + // shows nothing outside the drawn volume: only the drawn matrices change + return true; + } + m_builtInverseDecalMatrix = m_inverseDecalMatrix; // and rebuild the index buffer, cause decal volume has changed size and might hit new triangles if( !HasStaticIndexBuffers() ) { m_decalGeometry = nullptr; } + // the part targets cache the decal volume in part space + m_partTargets.clear(); + m_partsSignature = 0; + } + else if( IsMatch( value, m_growScale ) ) + { + // the geometry stays built for the full volume; only what is drawn of it changes + UpdateDrawDecalMatrix(); } return true; } +bool EveSpaceObjectDecal::HasBuiltRuntimeGeometry() const +{ + if( !m_usePartTargets ) + { + return m_decalGeometry != nullptr; + } + if( m_partTargets.empty() || !m_partsSignature ) + { + return false; + } + return std::all_of( m_partTargets.begin(), m_partTargets.end(), []( const PartTarget& target ) { return target.decalGeometry != nullptr; } ); +} + // ------------------------------------------------------------------------------------------------------ void EveSpaceObjectDecal::ReleaseResources( TriStorage ) { @@ -111,12 +174,22 @@ bool EveSpaceObjectDecal::OnPrepareResources() { m_decalGeometry = nullptr; } + for( auto& target : m_partTargets ) + { + if( target.decalGeometry && !target.decalGeometry->m_indexBuffer.IsValid() ) + { + target.decalGeometry = nullptr; + } + } return true; } void EveSpaceObjectDecal::UpdateVisibility( const EveUpdateContext& updateContext, const IEveSpaceObject2::ParentData* parentData ) { m_isVisible = 0; + m_lastFrustum = updateContext.GetFrustum(); + m_lastInvLodFactor = updateContext.GetInvLodFactor(); + m_hasLastFrustum = true; if( !m_display || !m_decalEffect ) { @@ -181,6 +254,13 @@ void EveSpaceObjectDecal::UpdateVisibility( const EveUpdateContext& updateContex // ------------------------------------------------------------------------------------------------------ void EveSpaceObjectDecal::GetRenderables( std::vector& renderables, DecalMeshCache& meshCache, TriGeometryRes* geomRes, float screensize ) { + if( m_usePartTargets ) + { + m_usePartTargets = false; + m_partTargets.clear(); + m_partsSignature = 0; + } + if( m_isVisible <= 0 || !geomRes ) { return; @@ -201,9 +281,16 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab { CreateStaticIndexBuffers( geomRes ); } + else if( m_dynamicIndexBuffers ) + { + // runtime decal: owned here, never added to the mesh's shared decal cache (that cache only grows) + m_decalGeometry = mesh && geomRes->IsGood() ? BuildDecalGeometryCached( mesh, m_decalMatrix, m_inverseDecalMatrix ) : nullptr; + m_builtInverseDecalMatrix = m_inverseDecalMatrix; + } else if( g_buildDecalBuffers ) { CreateDecalIndexBuffers( geomRes, meshCache ); + m_builtInverseDecalMatrix = m_inverseDecalMatrix; } } @@ -224,6 +311,193 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab renderables.push_back( this ); } +namespace +{ +// A part decal's world matrix is composed on the CPU, while the part itself is drawn through the +// instanced path (instance matrix, then the child's world matrix, on the GPU): the two positions +// differ by rounding, and with no depth write or bias the decal z-fights its own surface. The decal +// is scaled about the eye, which leaves every pixel where it is and moves its depth a fraction of +// its distance towards the eye. That rounding is a few float steps at the largest coordinate in +// the chain (a level instance sits tens of km from its object's origin), so the fraction covers +// PART_DEPTH_ULPS of them at the part's nearest point (no nearer than 2 m), within these bounds. +constexpr float PART_DEPTH_PULL_MIN = 4e-4f; +constexpr float PART_DEPTH_PULL_MAX = 0.005f; +constexpr float PART_DEPTH_ULPS = 2.f; +constexpr float FLOAT_STEP = 1.f / 8388608.f; // 2^-23, a float's relative resolution + +// The LOD the instanced mesh manager draws a part with (EveInstancedMeshManager::GetMeshLod) +int InstancedMeshLod( const TriGeometryResMeshData& meshData, float screenSize ) +{ + const size_t lodCount = meshData.m_lods.size(); + for( size_t lod = 0; lod + 1 < lodCount; ++lod ) + { + if( screenSize > meshData.m_lods[lod + 1]->m_maxScreenSize ) + { + return int( lod ); + } + } + return int( lodCount ) - 1; +} + +// FNV-1a over each part's geometry and transform: equal for the same parts list +uint64_t PartsSignature( const std::vector& parts ) +{ + uint64_t hash = 1469598103934665603ull; + auto mix = [&hash]( const void* data, size_t size ) { + const auto* bytes = static_cast( data ); + for( size_t i = 0; i < size; ++i ) + { + hash = ( hash ^ bytes[i] ) * 1099511628211ull; + } + }; + for( const auto& part : parts ) + { + mix( &part.geometry, sizeof( part.geometry ) ); + mix( &part.childToObject, sizeof( part.childToObject ) ); + } + return hash ? hash : 1; +} + +float MaxAxisScale( const Matrix& m ) +{ + return std::sqrt( std::max( { LengthSq( Vector3( m._11, m._12, m._13 ) ), LengthSq( Vector3( m._21, m._22, m._23 ) ), LengthSq( Vector3( m._31, m._32, m._33 ) ) } ) ); +} +} + +void EveSpaceObjectDecal::GetModularRenderables( std::vector& renderables, const std::vector& parts, float objectScreenSize, float objectRadius, const TriGeometryRes* ownGeometry ) +{ + if( !m_usePartTargets ) + { + // switching from a single mesh parent: drop anything tied to that mesh + m_usePartTargets = true; + m_decalGeometry = nullptr; + m_baseGeometryResource = nullptr; + m_instanceData = nullptr; + m_vertexDeclarationOverride = Tr2EffectStateManager::UNINITIALIZED_DECLARATION; + } + + if( m_isVisible <= 0 ) + { + return; + } + + const uint64_t signature = PartsSignature( parts ); + if( signature != m_partsSignature ) + { + // broad phase: the parts whose bounds the decal volume touches, in object space + Vector3 decalMin( -1.f, -1.f, -1.f ); + Vector3 decalMax( 1.f, 1.f, 1.f ); + BoundingBoxTransform( decalMin, decalMax, m_decalMatrix ); + + std::vector previous = std::move( m_partTargets ); + m_partTargets.clear(); + for( const auto& part : parts ) + { + TriGeometryRes* geometry = part.geometry; + if( !geometry || !geometry->IsGood() || !geometry->GetMeshCount() ) + { + continue; + } + TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); + // a part's decal is drawn with an identity parent bone on its rest-pose triangles: an + // animated part would leave it behind + if( !meshData || DecalTriangleCache::IsDeformed( *meshData ) ) + { + continue; + } + Vector3 partMin = meshData->m_minBounds; + Vector3 partMax = meshData->m_maxBounds; + BoundingBoxTransform( partMin, partMax, part.childToObject ); + if( decalMin.x > partMax.x || decalMax.x < partMin.x || decalMin.y > partMax.y || decalMax.y < partMin.y || decalMin.z > partMax.z || decalMax.z < partMin.z ) + { + continue; + } + + // a part already targeted keeps its built geometry + auto kept = std::find_if( previous.begin(), previous.end(), [&]( const PartTarget& target ) { + return target.geometry == geometry && target.childToObject == part.childToObject; + } ); + if( kept != previous.end() ) + { + m_partTargets.push_back( std::move( *kept ) ); + previous.erase( kept ); + continue; + } + + // built from the current volume: a later volume must fit inside this one to keep the geometry + m_builtInverseDecalMatrix = m_inverseDecalMatrix; + PartTarget target; + target.geometry = geometry; + target.childToObject = part.childToObject; + // part vertices are in part space; the decal volume lives in object space + target.objectToPart = Inverse( part.childToObject ); + target.decalMatrix = m_decalMatrix * target.objectToPart; + target.inverseDecalMatrix = Inverse( target.decalMatrix ); + Vector3 boundsCenter = ( meshData->m_minBounds + meshData->m_maxBounds ) * 0.5f; + target.lodRadius = Length( meshData->m_maxBounds - meshData->m_minBounds ) * 0.5f + Length( boundsCenter ); + // fallback before the first visibility update: scale the object's screen size by the part's size + if( objectRadius > 0.f ) + { + target.screenSizeScale = meshData->m_boundingSphere.w * MaxAxisScale( part.childToObject ) / objectRadius; + } + m_partTargets.push_back( std::move( target ) ); + } + m_partsSignature = signature; + } + + for( auto& target : m_partTargets ) + { + TriGeometryResMeshData* meshData = target.geometry->IsGood() ? target.geometry->GetMeshData( 0 ) : nullptr; + if( meshData && ( !target.decalGeometry || target.decalGeometry->m_lodMask != meshData->m_lodMask ) ) + { + target.decalGeometry = BuildDecalGeometryCached( meshData, target.decalMatrix, target.inverseDecalMatrix ); + } + } + + bool anyVisible = false; + for( auto& target : m_partTargets ) + { + target.lodIndex = -1; + if( !target.decalGeometry || !target.decalGeometry->m_indexBuffer.IsValid() ) + { + continue; + } + int lodIndex = 0; + if( m_isGeometryFrozen ) + { + lodIndex = 0; + } + else if( target.geometry == ownGeometry ) + { + // the object's own mesh draws at the object's screen size + lodIndex = target.geometry->GetLodIndexForScreenSize( 0, objectScreenSize ); + } + else if( m_hasLastFrustum ) + { + // as EveChildInstancedMeshes sizes the instance's sphere and EveInstancedMeshManager picks its LOD + Matrix world = target.childToObject * m_parentData.transform; + float screenSize = m_lastFrustum.GetPixelSizeAccrossEst( world.GetTranslation(), target.lodRadius * MaxAxisScale( world ) ) * m_lastInvLodFactor; + const TriGeometryResMeshData* meshData = target.geometry->GetMeshData( 0 ); + lodIndex = meshData ? InstancedMeshLod( *meshData, screenSize ) : -1; + } + else + { + lodIndex = target.geometry->GetLodIndexForScreenSize( 0, objectScreenSize * target.screenSizeScale ); + } + if( lodIndex < 0 || lodIndex >= int( target.decalGeometry->m_lods.size() ) || !target.decalGeometry->m_lods[lodIndex].m_primitiveCount ) + { + continue; + } + target.lodIndex = lodIndex; + anyVisible = true; + } + + if( anyVisible ) + { + renderables.push_back( this ); + } +} + void EveSpaceObjectDecal::GetInstancedRenderables( std::vector& renderables, DecalMeshCache& meshCache, const Tr2InstancedMesh* instancedMesh, float instanceScreenSize ) { GetRenderables( renderables, meshCache, instancedMesh->GetGeometryResource(), instanceScreenSize ); @@ -257,12 +531,48 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, return; } - if( !m_baseGeometryResource || !m_decalEffect ) + if( !m_decalEffect || !m_display ) { return; } - if( !m_display ) + if( m_usePartTargets ) + { + for( const auto& target : m_partTargets ) + { + if( target.lodIndex < 0 || !target.decalGeometry || !target.decalGeometry->m_indexBuffer.IsValid() || !target.geometry->IsGood() ) + { + continue; + } + const TriGeometryResLodData* lod = target.geometry->GetMeshLod( 0, target.lodIndex ); + if( !lod || !lod->m_allocationsValid ) + { + continue; + } + auto partData = batches->Allocate(); + if( !partData ) + { + return; + } + // draw the part's vertices with the part's world transform and the decal volume in part space + Matrix world = target.childToObject * m_parentData.transform; + if( m_hasLastFrustum ) + { + const Vector3& eye = m_lastFrustum.m_viewPos; + float objectScale = MaxAxisScale( m_parentData.transform ); + // the largest magnitudes the part's vertices pass through on the way to world space + float magnitude = std::max( { Length( target.childToObject.GetTranslation() ) * objectScale, Length( m_parentData.transform.GetTranslation() ), Length( world.GetTranslation() ) } ); + float nearest = std::max( Length( world.GetTranslation() - eye ) - target.lodRadius * MaxAxisScale( world ), 2.f ); + float pull = std::clamp( PART_DEPTH_ULPS * magnitude * FLOAT_STEP / nearest, PART_DEPTH_PULL_MIN, PART_DEPTH_PULL_MAX ); + world = world * TranslationMatrix( -eye ) * ScalingMatrix( 1.f - pull, 1.f - pull, 1.f - pull ) * TranslationMatrix( eye ); + } + FillPerObjectData( *partData, world, m_drawDecalMatrix * target.objectToPart, target.childToObject * m_drawInverseDecalMatrix, IdentityMatrix() ); + CommitBatch( batches, lod, *target.decalGeometry, target.lodIndex, partData ); + } + return; + } + + if( !m_baseGeometryResource ) { return; } @@ -292,11 +602,16 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, return; } + CommitBatch( batches, lod, *m_decalGeometry, m_geometryLodIndex, perObjectData ); +} + +void EveSpaceObjectDecal::CommitBatch( ITriRenderBatchAccumulator* batches, const TriGeometryResLodData* lod, const MeshDecalData& decalGeometry, int lodIndex, const Tr2PerObjectData* perObjectData ) +{ Tr2RenderBatch batch; batch.SetPriority( m_priority ); batch.SetMaterial( m_decalEffect ); auto declaration = m_vertexDeclarationOverride != Tr2EffectStateManager::UNINITIALIZED_DECLARATION ? m_vertexDeclarationOverride : lod->m_mesh->m_vertexDeclarationHandle; - batch.SetGeometry( declaration, lod->m_vertexAllocation, m_decalGeometry->m_indexBuffer ); + batch.SetGeometry( declaration, lod->m_vertexAllocation, decalGeometry.m_indexBuffer ); batch.SetPerObjectData( perObjectData ); @@ -304,9 +619,9 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, { ITr2InstanceData::InstanceData data = m_instanceData->GetInstanceData( 0, std::numeric_limits::max() ); batch.SetDrawIndexedInstanced( - m_decalGeometry->m_lods[m_geometryLodIndex].m_primitiveCount * 3, + decalGeometry.m_lods[lodIndex].m_primitiveCount * 3, data.count, - m_decalGeometry->m_indexBuffer.GetStartIndex() + m_decalGeometry->m_lods[m_geometryLodIndex].m_startIndex, + decalGeometry.m_indexBuffer.GetStartIndex() + decalGeometry.m_lods[lodIndex].m_startIndex, lod->m_vertexAllocation.GetOffset() / lod->m_vertexAllocation.GetStride(), data.offset / data.stride ); batch.m_vertexStreams[1] = &data.buffer; @@ -315,9 +630,9 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, else { batch.SetDrawIndexedInstanced( - m_decalGeometry->m_lods[m_geometryLodIndex].m_primitiveCount * 3, + decalGeometry.m_lods[lodIndex].m_primitiveCount * 3, 1, - m_decalGeometry->m_indexBuffer.GetStartIndex() + m_decalGeometry->m_lods[m_geometryLodIndex].m_startIndex, + decalGeometry.m_indexBuffer.GetStartIndex() + decalGeometry.m_lods[lodIndex].m_startIndex, lod->m_vertexAllocation.GetOffset() / lod->m_vertexAllocation.GetStride(), 0 ); } @@ -352,37 +667,41 @@ Tr2PerObjectData* EveSpaceObjectDecal::GetPerObjectData( ITriRenderBatchAccumula return NULL; } + FillPerObjectData( *perObjectData, m_parentData.transform, m_drawDecalMatrix, m_drawInverseDecalMatrix, m_parentBoneMatrix ); + return perObjectData; +} + +void EveSpaceObjectDecal::FillPerObjectData( EveDecalPerObjectData& data, const Matrix& worldMatrix, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix, const Matrix& parentBoneMatrix ) const +{ // world matrix - perObjectData->m_vsData.m_worldMatrix = Transpose( m_parentData.transform ); + data.m_vsData.m_worldMatrix = Transpose( worldMatrix ); // inv world matrix - perObjectData->m_vsData.m_invWorldMatrix = Inverse( perObjectData->m_vsData.m_worldMatrix ); + data.m_vsData.m_invWorldMatrix = Inverse( data.m_vsData.m_worldMatrix ); // decal matrix (both nrm and inv) - perObjectData->m_vsData.m_decalMatrix = Transpose( m_decalMatrix ); - perObjectData->m_vsData.m_inverseDecalMatrix = Transpose( m_inverseDecalMatrix ); + data.m_vsData.m_decalMatrix = Transpose( decalMatrix ); + data.m_vsData.m_inverseDecalMatrix = Transpose( inverseDecalMatrix ); // matrix from possible bone animation of parent - perObjectData->m_vsData.m_parentBoneMatrix = Transpose( m_parentBoneMatrix ); - perObjectData->m_vsData.m_invParentBoneMatrix = Inverse( Transpose( m_parentBoneMatrix ) ); + data.m_vsData.m_parentBoneMatrix = Transpose( parentBoneMatrix ); + data.m_vsData.m_invParentBoneMatrix = Inverse( Transpose( parentBoneMatrix ) ); // clip sphere data from parent - perObjectData->m_psData.m_shipData = m_parentData.shipData; - perObjectData->m_psData.m_clipData = Vector4( m_parentData.clipSphereCenter, m_parentData.clipRadiusSq ); - perObjectData->m_psData.m_clipRadius2Sq = m_parentData.clipRadius2Sq; + data.m_psData.m_shipData = m_parentData.shipData; + data.m_psData.m_clipData = Vector4( m_parentData.clipSphereCenter, m_parentData.clipRadiusSq ); + data.m_psData.m_clipRadius2Sq = m_parentData.clipRadius2Sq; // display data - perObjectData->m_psData.m_displayData = Vector4( (float)m_parentData.killCount, m_isVisible, 0.f, 0.f ); + data.m_psData.m_displayData = Vector4( (float)m_parentData.killCount, m_isVisible, 0.f, 0.f ); if( m_parentData.shLighting ) { - memcpy( perObjectData->m_psData.m_shLightingCoefficients, m_parentData.shLighting, sizeof( perObjectData->m_psData.m_shLightingCoefficients ) ); + memcpy( data.m_psData.m_shLightingCoefficients, m_parentData.shLighting, sizeof( data.m_psData.m_shLightingCoefficients ) ); } else { - memset( perObjectData->m_psData.m_shLightingCoefficients, 0, sizeof( perObjectData->m_psData.m_shLightingCoefficients ) ); + memset( data.m_psData.m_shLightingCoefficients, 0, sizeof( data.m_psData.m_shLightingCoefficients ) ); } - - return perObjectData; } void EveSpaceObjectDecal::CopyFrom( EveSpaceObjectDecal* object ) @@ -593,8 +912,6 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De { TRINITY_STATS_ZONE( __FUNCTION__ ); - USE_MAIN_THREAD_RENDER_CONTEXT(); - // is loaded and good? if( !geomRes ) { @@ -613,8 +930,6 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De m_decalGeometry = nullptr; - std::vector allIndices; - TriGeometryResMeshData* meshData = geomRes->GetMeshData( 0 ); if( !meshData ) @@ -631,17 +946,60 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De } } + auto newDecal = BuildDecalGeometry( meshData, meshCache, m_decalMatrix, m_inverseDecalMatrix ); + if( !newDecal ) + { + return; + } + + meshData->m_decals.push_back( newDecal ); + m_decalGeometry = newDecal; +} + +// ------------------------------------------------------------------------------------------------------ +std::shared_ptr EveSpaceObjectDecal::BuildDecalGeometry( TriGeometryResMeshData* meshData, DecalMeshCache& meshCache, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ) +{ + TRINITY_STATS_ZONE( __FUNCTION__ ); + + USE_MAIN_THREAD_RENDER_CONTEXT(); + + std::vector allIndices; + std::shared_ptr newDecal = std::make_shared(); - newDecal->m_inverseDecalMatrix = m_inverseDecalMatrix; + newDecal->m_inverseDecalMatrix = inverseDecalMatrix; newDecal->m_lodMask = meshData->m_lodMask; + Vector3 aabbMin( -1.f, -1.f, -1.f ); + Vector3 aabbMax( 1.f, 1.f, 1.f ); + BoundingBoxTransform( aabbMin, aabbMax, decalMatrix ); + + // a decal volume outside the mesh bounds hits nothing: skip reading the buffers back + if( aabbMin.x > meshData->m_maxBounds.x || aabbMax.x < meshData->m_minBounds.x || + aabbMin.y > meshData->m_maxBounds.y || aabbMax.y < meshData->m_minBounds.y || + aabbMin.z > meshData->m_maxBounds.z || aabbMax.z < meshData->m_minBounds.z ) + { + newDecal->m_lods.resize( meshData->m_lods.size() ); + return newDecal; + } + + // is vertex compressed to 16bit floats? + bool vertexPositionCompressed = false; + Tr2VertexDefinition vd; + if( Tr2EffectStateManager::GetVertexDeclarationElements( meshData->m_vertexDeclarationHandle, vd ) ) + { + if( auto pos = vd.Find( vd.POSITION ) ) + { + vertexPositionCompressed = pos->m_dataType == vd.FLOAT16_4; + } + } + for( int i = 0; i < static_cast( meshData->m_lods.size() ); i++ ) { TriGeometryResLodData* lod = meshData->m_lods[i].get(); if( !lod->m_allocationsValid ) { - return; + return nullptr; } // lock existing buffers, we do this only once and it is managed, so this call is ok @@ -660,7 +1018,7 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De { if( FAILED( lod->m_vertexAllocation.MapForReading( originalVertices, renderContext ) ) ) { - return; + return nullptr; } } ON_BLOCK_EXIT( [&] { if( readingBuffers ) lod->m_vertexAllocation.UnmapForReading( renderContext ); } ); @@ -669,7 +1027,7 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De { if( FAILED( lod->m_indexAllocation.MapForReading( originalIndices, renderContext ) ) ) { - return; + return nullptr; } } ON_BLOCK_EXIT( [&] { if( readingBuffers ) lod->m_indexAllocation.UnmapForReading( renderContext ); } ); @@ -687,34 +1045,10 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De // correct source pointers const unsigned int* indices32 = reinterpret_cast( originalIndices ); const unsigned short* indices16 = reinterpret_cast( originalIndices ); - // collect indices for decal geometry - std::vector decalIndices32; - std::vector decalIndices16; bool is16bit = lod->m_indexAllocation.GetStride() == 2; - if( is16bit ) - { - decalIndices16.reserve( lod->m_primitiveCount * 3 ); - } - else - { - decalIndices32.reserve( lod->m_primitiveCount * 3 ); - } - - // is vertex compressed to 16bit floats? - bool vertexPositionCompressed = false; - Tr2VertexDefinition vd; - if( Tr2EffectStateManager::GetVertexDeclarationElements( meshData->m_vertexDeclarationHandle, vd ) ) - { - if( auto pos = vd.Find( vd.POSITION ) ) - { - vertexPositionCompressed = pos->m_dataType == vd.FLOAT16_4; - } - } - - Vector3 aabbMin( -1.f, -1.f, -1.f ); - Vector3 aabbMax( 1.f, 1.f, 1.f ); - BoundingBoxTransform( aabbMin, aabbMax, m_decalMatrix ); + MeshDecalLodData buffer; + buffer.m_startIndex = uint32_t( allIndices.size() ); for( unsigned int t = 0; t < lod->m_primitiveCount; ++t ) { @@ -722,76 +1056,35 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De unsigned int index0 = is16bit ? indices16[0] : indices32[0]; unsigned int index1 = is16bit ? indices16[1] : indices32[1]; unsigned int index2 = is16bit ? indices16[2] : indices32[2]; + // next! + indices16 += 3; + indices32 += 3; + // do real collision detection here + Vector3 pos[3]; if( vertexPositionCompressed ) { - Vector3 pos[3]; pos[0] = *reinterpret_cast( originalVertices + index0 * meshData->m_bytesPerVertex ); pos[1] = *reinterpret_cast( originalVertices + index1 * meshData->m_bytesPerVertex ); pos[2] = *reinterpret_cast( originalVertices + index2 * meshData->m_bytesPerVertex ); - if( IntersectTriangleAABB( pos, pos + 1, pos + 2, aabbMin, aabbMax ) ) - { - if( IntersectTriangleOrientedBox( pos, pos + 1, pos + 2, m_inverseDecalMatrix ) ) - { - if( is16bit ) - { - decalIndices16.push_back( index0 ); - decalIndices16.push_back( index1 ); - decalIndices16.push_back( index2 ); - } - else - { - decalIndices32.push_back( index0 ); - decalIndices32.push_back( index1 ); - decalIndices32.push_back( index2 ); - } - } - } } else { - const Vector3* v0 = reinterpret_cast( originalVertices + index0 * meshData->m_bytesPerVertex ); - const Vector3* v1 = reinterpret_cast( originalVertices + index1 * meshData->m_bytesPerVertex ); - const Vector3* v2 = reinterpret_cast( originalVertices + index2 * meshData->m_bytesPerVertex ); - - if( IntersectTriangleAABB( v0, v1, v2, aabbMin, aabbMax ) ) - { - if( IntersectTriangleOrientedBox( v0, v1, v2, m_inverseDecalMatrix ) ) - { - if( is16bit ) - { - decalIndices16.push_back( index0 ); - decalIndices16.push_back( index1 ); - decalIndices16.push_back( index2 ); - } - else - { - decalIndices32.push_back( index0 ); - decalIndices32.push_back( index1 ); - decalIndices32.push_back( index2 ); - } - } - } + pos[0] = *reinterpret_cast( originalVertices + index0 * meshData->m_bytesPerVertex ); + pos[1] = *reinterpret_cast( originalVertices + index1 * meshData->m_bytesPerVertex ); + pos[2] = *reinterpret_cast( originalVertices + index2 * meshData->m_bytesPerVertex ); + } + if( IntersectTriangleAABB( pos, pos + 1, pos + 2, aabbMin, aabbMax ) && + IntersectTriangleOrientedBox( pos, pos + 1, pos + 2, inverseDecalMatrix ) ) + { + allIndices.push_back( index0 ); + allIndices.push_back( index1 ); + allIndices.push_back( index2 ); } - // next! - indices16 += 3; - indices32 += 3; - } - - // primitive count and index size - MeshDecalLodData buffer; - buffer.m_startIndex = uint32_t( allIndices.size() ); - if( is16bit ) - { - buffer.m_primitiveCount = unsigned( decalIndices16.size() / 3 ); - allIndices.insert( end( allIndices ), begin( decalIndices16 ), end( decalIndices16 ) ); - } - else - { - buffer.m_primitiveCount = unsigned( decalIndices32.size() / 3 ); - allIndices.insert( end( allIndices ), begin( decalIndices32 ), end( decalIndices32 ) ); } + // primitive count; the decal index buffer is always 32 bit + buffer.m_primitiveCount = ( uint32_t( allIndices.size() ) - buffer.m_startIndex ) / 3; newDecal->m_lods.push_back( buffer ); } @@ -800,12 +1093,67 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De { if( !SUCCEEDED( g_sharedBuffer.Allocate( 4, uint32_t( allIndices.size() ), allIndices.data(), renderContext, newDecal->m_indexBuffer ) ) ) { - return; + return nullptr; } } - meshData->m_decals.push_back( newDecal ); - m_decalGeometry = newDecal; + return newDecal; +} + +// ------------------------------------------------------------------------------------------------------ +std::shared_ptr EveSpaceObjectDecal::BuildDecalGeometryCached( TriGeometryResMeshData* meshData, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ) +{ + TRINITY_STATS_ZONE( __FUNCTION__ ); + + std::shared_ptr newDecal = std::make_shared(); + newDecal->m_inverseDecalMatrix = inverseDecalMatrix; + newDecal->m_lodMask = meshData->m_lodMask; + + Vector3 aabbMin( -1.f, -1.f, -1.f ); + Vector3 aabbMax( 1.f, 1.f, 1.f ); + BoundingBoxTransform( aabbMin, aabbMax, decalMatrix ); + + // a decal volume outside the mesh bounds hits nothing: don't build the cache for it + if( aabbMin.x > meshData->m_maxBounds.x || aabbMax.x < meshData->m_minBounds.x || + aabbMin.y > meshData->m_maxBounds.y || aabbMax.y < meshData->m_minBounds.y || + aabbMin.z > meshData->m_maxBounds.z || aabbMax.z < meshData->m_minBounds.z ) + { + newDecal->m_lods.resize( meshData->m_lods.size() ); + return newDecal; + } + + const DecalTriangleCache* cache = DecalTriangleCache::Get( meshData ); + if( !cache ) + { + return nullptr; + } + + // faces more than ~66 degrees off the projection axis would smear the decal's texture across + // them; leaving them out still lets a decal on an edge (45 degrees to each face) wrap it + constexpr float MIN_FACING = 0.4f; + Vector3 projectionAxis( decalMatrix._11, decalMatrix._12, decalMatrix._13 ); + float axisLength = Length( projectionAxis ); + projectionAxis = axisLength > 0.f ? projectionAxis / axisLength : Vector3( 1.f, 0.f, 0.f ); + + std::vector allIndices; + for( size_t i = 0; i < meshData->m_lods.size(); ++i ) + { + MeshDecalLodData lod; + lod.m_startIndex = uint32_t( allIndices.size() ); + cache->Query( i, aabbMin, aabbMax, inverseDecalMatrix, projectionAxis, MIN_FACING, allIndices ); + lod.m_primitiveCount = ( uint32_t( allIndices.size() ) - lod.m_startIndex ) / 3; + newDecal->m_lods.push_back( lod ); + } + + if( !allIndices.empty() ) + { + USE_MAIN_THREAD_RENDER_CONTEXT(); + if( !SUCCEEDED( g_sharedBuffer.Allocate( 4, uint32_t( allIndices.size() ), allIndices.data(), renderContext, newDecal->m_indexBuffer ) ) ) + { + return nullptr; + } + } + return newDecal; } void EveSpaceObjectDecal::SetIndices( const std::vector>& indices ) @@ -928,15 +1276,36 @@ void EveSpaceObjectDecal::GetPickingBatches( ITriRenderBatchAccumulator* batches std::vector EveSpaceObjectDecal::GetDecalPrimitiveCounts() const { std::vector counts; - if( m_decalGeometry ) + if( m_usePartTargets ) + { + // per LOD, summed over all the parts the decal projects onto + for( const auto& target : m_partTargets ) + { + if( !target.decalGeometry ) + { + continue; + } + const auto& lods = target.decalGeometry->m_lods; + if( counts.size() < lods.size() ) + { + counts.resize( lods.size(), 0 ); + } + for( size_t i = 0; i < lods.size(); ++i ) + { + counts[i] += lods[i].m_primitiveCount; + } + } + } + else if( m_decalGeometry ) { for( auto& buffer : m_decalGeometry->m_lods ) { counts.push_back( buffer.m_primitiveCount ); } } - else + else if( m_baseGeometryResource ) { + // no geometry yet: report what the static index buffers hold TriGeometryResMeshData* meshData = m_baseGeometryResource->GetMeshData( 0 ); if( meshData ) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index 6de349978..f832d6d48 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -72,6 +72,8 @@ struct DecalMeshCache std::vector buffers; }; +struct EveChildGeometry; + // -------------------------------------------------------------------------------- // Description: // ToDo @@ -130,6 +132,21 @@ BLUE_CLASS( EveSpaceObjectDecal ) : void UpdateVisibility( const EveUpdateContext& updateContext, const IEveSpaceObject2::ParentData* parentData ); void GetRenderables( std::vector & renderables, DecalMeshCache & meshCache, TriGeometryRes * geomRes, float screensize ); void GetInstancedRenderables( std::vector & renderables, DecalMeshCache & meshCache, const Tr2InstancedMesh* instancedMesh, float instanceScreenSize = std::numeric_limits::max() ); + /** + * @brief Gathers the decal for a parent without a mesh of its own (a modular object), projecting it onto + * every part geometry the decal volume overlaps. Index buffers are built on the CPU from each part + * geometry's DecalTriangleCache and owned by this decal; they are rebuilt when the decal or a part moves. + * @param parts Part geometries of the parent, in the parent's object space (EveSpaceObjectChild::CollectOwnedGeometry). + * @param objectScreenSize Screen size of the whole parent, used to pick a LOD per part. + * @param objectRadius Bounding sphere radius of the whole parent in object space. + */ + void GetModularRenderables( std::vector & renderables, const std::vector& parts, float objectScreenSize, float objectRadius, const TriGeometryRes* ownGeometry ); + + // true if this decal builds its own geometry at runtime (dynamicIndexBuffers) + bool HasDynamicIndexBuffers() const + { + return m_dynamicIndexBuffers; + } // access position etc. const Vector3& GetPosition() const; @@ -161,8 +178,17 @@ BLUE_CLASS( EveSpaceObjectDecal ) : private: // create void CreateDecalIndexBuffers( TriGeometryResPtr geomRes, DecalMeshCache & meshCache ); + // Collects the triangles of every LOD of meshData that intersect the decal volume. Returns null if the + // mesh buffers are not ready yet. inverseDecalMatrix maps the mesh's vertex space into decal space. + static std::shared_ptr BuildDecalGeometry( TriGeometryResMeshData * meshData, DecalMeshCache & meshCache, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ); + // Same result as BuildDecalGeometry, but reads the triangles from the mesh's DecalTriangleCache + // (built once per mesh), so only the triangles near the decal volume are tested. + static std::shared_ptr BuildDecalGeometryCached( TriGeometryResMeshData * meshData, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ); + void FillPerObjectData( EveDecalPerObjectData & data, const Matrix& worldMatrix, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix, const Matrix& parentBoneMatrix ) const; + void CommitBatch( ITriRenderBatchAccumulator * batches, const TriGeometryResLodData* lod, const MeshDecalData& decalGeometry, int lodIndex, const Tr2PerObjectData* perObjectData ); // update void UpdateDecalMatrix(); + void UpdateDrawDecalMatrix(); void CreateStaticIndexBuffers( TriGeometryResPtr geomRes ); bool HasStaticIndexBuffers() const; @@ -193,6 +219,15 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // matrices representing the "volume" of the decal projection Matrix m_decalMatrix; Matrix m_inverseDecalMatrix; + // per-axis share (0..1) of that volume the decal draws in: animating it rebuilds no geometry + Vector3 m_growScale = Vector3( 1.f, 1.f, 1.f ); + // the drawn volume: m_decalMatrix with m_growScale applied in decal space + Matrix m_drawDecalMatrix; + Matrix m_drawInverseDecalMatrix; + // inverse of the volume the runtime geometry was built for: a later volume inside it keeps the geometry + Matrix m_builtInverseDecalMatrix; + // m_decalGeometry or every part target holds geometry built from the decal volume + bool HasBuiltRuntimeGeometry() const; // base mesh geometry TriGeometryResPtr m_baseGeometryResource; @@ -216,6 +251,37 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // the geometry can be frozen bool m_isGeometryFrozen; + + // build the index buffer at runtime even when g_buildDecalBuffers is off; the buffer is then owned by + // this decal instead of being cached on the mesh + bool m_dynamicIndexBuffers; + + // A part of a modular parent that the decal may project onto + struct PartTarget + { + TriGeometryResPtr geometry; + Matrix childToObject; + // the decal volume expressed in the part's vertex space + Matrix decalMatrix; + Matrix inverseDecalMatrix; + Matrix objectToPart; + // owned here rather than cached on the (shared) mesh data: runtime decals come and go + std::shared_ptr decalGeometry; + float screenSizeScale = 1.f; + // radius of the part's bounds about its own origin, as the instanced mesh manager sizes it for LOD + float lodRadius = 0.f; + int lodIndex = -1; + }; + // the parts the decal volume overlaps, from the broad phase of the parts list m_partsSignature names + std::vector m_partTargets; + // hash of the parts list m_partTargets was built from; 0 when they must be rebuilt + uint64_t m_partsSignature = 0; + // the camera of the last visibility update: part LODs and the depth pull are taken from it + TriFrustum m_lastFrustum; + float m_lastInvLodFactor = 1.f; + bool m_hasLastFrustum = false; + // true when the parent has no mesh and the decal renders through m_partTargets + bool m_usePartTargets; }; TYPEDEF_BLUECLASS( EveSpaceObjectDecal ); diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp index 945c4c9b6..ea8a2c93c 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp @@ -21,11 +21,24 @@ const Be::ClassInfo* EveSpaceObjectDecal::ExposeToBlue() MAP_ATTRIBUTE( "position", m_position, "center of decal", Be::READWRITE | Be::NOTIFY | Be::PERSIST ) MAP_ATTRIBUTE( "rotation", m_rotation, "orientation of decal", Be::READWRITE | Be::NOTIFY | Be::PERSIST ); MAP_ATTRIBUTE( "scaling", m_scaling, "size of decal", Be::READWRITE | Be::NOTIFY | Be::PERSIST ); + MAP_ATTRIBUTE( + "growScale", + m_growScale, + "Per-axis share (0..1) of the volume scaling sets that the decal draws in. Animating it costs no geometry " + "rebuild, unlike scaling: the decal's geometry stays built for the full volume and the shader shows nothing " + "outside the drawn one.", + Be::READWRITE | Be::NOTIFY | Be::PERSIST ); MAP_ATTRIBUTE( "parentBoneIndex", m_parentBoneIndex, "the bone index this decal is tight to (-1 to disable)", Be::READWRITE | Be::PERSIST ); MAP_ATTRIBUTE( "minScreenSize", m_minScreenSize, "min size on screen in pixels before the decal is LODed out", Be::READWRITE | Be::PERSIST ) MAP_ATTRIBUTE( "decalEffect", m_decalEffect, "The effect used to draw the decal", Be::READWRITE | Be::PERSIST ) + MAP_ATTRIBUTE( + "dynamicIndexBuffers", + m_dynamicIndexBuffers, + "Build the decal geometry from the parent mesh at runtime, whatever the buildDecalBuffers setting says. " + "For runtime decals (impacts, scratches) that have no baked index buffers; ignored when static index buffers are set.", + Be::READWRITE | Be::PERSIST ) MAP_ATTRIBUTE( "batchType", m_batchType, "Batch type (render pass) used to render the decal", Be::READ ) diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index f046b8701..8ee6ef433 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -35,6 +35,7 @@ #include "Controllers/ITr2Controller.h" #include "Eve/SpaceObject/Children/EveChildInheritProperties.h" #include "Eve/SpaceObject/Children/EveChildMesh.h" +#include "Eve/SpaceObject/Attachments/EveDecalTriangleCache.h" #include "Shader/Tr2Shader.h" #include "../../Tr2RingBuffer.h" @@ -1578,19 +1579,44 @@ void EveSpaceObject2::PushChildrenAndDecalRenderables( std::vectorGetGeometryResource(); - if( geometryRes ) + return; + } + + TriGeometryResPtr geometryRes = m_mesh ? m_mesh->GetGeometryResource() : nullptr; + // geometry the object draws through its children (a modular object's parts, or the + // instanced meshes of level geometry that has only a placeholder mesh of its own) + std::vector parts; + std::vector areas; + for( auto& child : m_effectChildren ) + { + child->CollectOwnedGeometry( TRIBATCHTYPE_OPAQUE, IdentityMatrix(), parts, areas ); + } + if( !parts.empty() && geometryRes ) + { + // a runtime decal goes onto everything the object draws, its own mesh included + EveChildGeometry own; + own.geometry = geometryRes; + own.childToObject = IdentityMatrix(); + parts.insert( parts.begin(), own ); + } + + DecalMeshCache meshCache; + for( auto it = m_decals.begin(); it != m_decals.end(); ++it ) + { + // a baked decal, or one built by the buildDecalBuffers setting, belongs to the object's own mesh + if( parts.empty() || ( geometryRes && !( *it )->HasDynamicIndexBuffers() ) ) { - DecalMeshCache meshCache; - // runn over every decal and update it - for( EveSpaceObjectDecalVector::const_iterator it = m_decals.begin(); it != m_decals.end(); ++it ) + if( geometryRes ) { - // now prep to get the renderables ( *it )->GetRenderables( renderables, meshCache, geometryRes, m_meshScreenSize ); } } + else + { + ( *it )->GetModularRenderables( renderables, parts, m_meshScreenSize, m_boundingSphereRadius, geometryRes ); + } } } @@ -2809,6 +2835,115 @@ bool EveSpaceObject2::GetDamageLocatorBindPosition( int index, Vector3& out ) co return true; } +template +std::pair> EveSpaceObject2::FindNearestOnGeometry( const Vector3& position, float radius, Query&& query ) +{ + std::vector parts; + std::vector areas; + if( m_mesh && m_mesh->GetGeometryResource() ) + { + EveChildGeometry own; + own.geometry = m_mesh->GetGeometryResource(); + own.childToObject = IdentityMatrix(); + parts.push_back( own ); + } + for( auto& child : m_effectChildren ) + { + child->CollectOwnedGeometry( TRIBATCHTYPE_OPAQUE, IdentityMatrix(), parts, areas ); + } + + bool found = false; + bool pending = false; + float bestDistance = radius; + Vector3 bestPosition = position; + Vector3 bestNormal( 0.f, 0.f, 0.f ); + for( const auto& part : parts ) + { + TriGeometryRes* geometry = part.geometry; + if( !geometry || !geometry->IsGood() || !geometry->GetMeshCount() ) + { + pending = pending || ( geometry && !geometry->IsGood() ); + continue; + } + TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); + // the cache holds rest-pose positions, which an animated part moves away from + if( !meshData || DecalTriangleCache::IsDeformed( *meshData ) ) + { + continue; + } + const Matrix& m = part.childToObject; + float scale = std::max( { Length( Vector3( m._11, m._12, m._13 ) ), Length( Vector3( m._21, m._22, m._23 ) ), Length( Vector3( m._31, m._32, m._33 ) ) } ); + if( scale <= 0.f ) + { + continue; + } + Matrix objectToPart = Inverse( m ); + Vector3 local = XMVector3TransformCoord( position, objectToPart ); + float localRadius = bestDistance / scale; + // cheap reject: the part's bounds are further away than the best result so far + if( local.x + localRadius < meshData->m_minBounds.x || local.x - localRadius > meshData->m_maxBounds.x || + local.y + localRadius < meshData->m_minBounds.y || local.y - localRadius > meshData->m_maxBounds.y || + local.z + localRadius < meshData->m_minBounds.z || local.z - localRadius > meshData->m_maxBounds.z ) + { + continue; + } + const DecalTriangleCache* cache = DecalTriangleCache::Get( meshData ); + if( !cache ) + { + pending = true; + continue; + } + Vector3 partPosition, partNormal; + float localDistance; + if( !query( *cache, local, localRadius, partPosition, partNormal, localDistance ) ) + { + continue; + } + Vector3 objectPosition = XMVector3TransformCoord( partPosition, m ); + float distance = Length( objectPosition - position ); + if( distance <= bestDistance ) + { + found = true; + bestDistance = distance; + bestPosition = objectPosition; + // normals take the inverse transpose of the part transform + bestNormal = Normalize( Vector3( XMVector3TransformNormal( partNormal, Transpose( objectToPart ) ) ) ); + } + } + GeometryQueryStatus status = found ? GeometryQueryStatus::FOUND : pending ? GeometryQueryStatus::PENDING : GeometryQueryStatus::NONE; + return std::make_pair( status, std::make_pair( bestPosition, bestNormal ) ); +} + +std::pair> EveSpaceObject2::QueryNearestHullEdge( const Vector3& position, float radius ) +{ + // cosine of the fold, between two faces' normals, that counts as an edge + constexpr float SHARP_EDGE_COS = 0.866f; + auto result = FindNearestOnGeometry( position, radius, [&]( const DecalTriangleCache& cache, const Vector3& point, float r, Vector3& outPosition, Vector3& outNormal, float& outDistance ) { + return cache.FindNearestEdge( 0, point, r, SHARP_EDGE_COS, outPosition, outNormal, outDistance ); + } ); + return std::make_pair( int( result.first ), result.second ); +} + +std::pair> EveSpaceObject2::QueryNearestSurfacePoint( const Vector3& position, float radius ) +{ + auto result = FindNearestOnGeometry( position, radius, [&]( const DecalTriangleCache& cache, const Vector3& point, float r, Vector3& outPosition, Vector3& outNormal, float& outDistance ) { + return cache.FindNearestSurface( 0, point, r, outPosition, outNormal, outDistance ); + } ); + return std::make_pair( int( result.first ), result.second ); +} + +std::pair> EveSpaceObject2::GetNearestHullEdge( const Vector3& position, float radius ) +{ + auto result = QueryNearestHullEdge( position, radius ); + return std::make_pair( result.first == int( GeometryQueryStatus::FOUND ), result.second ); +} + +std::pair> EveSpaceObject2::GetNearestSurfacePoint( const Vector3& position, float radius ) +{ + auto result = QueryNearestSurfacePoint( position, radius ); + return std::make_pair( result.first == int( GeometryQueryStatus::FOUND ), result.second ); +} + Vector3 EveSpaceObject2::GetLocatorPositionFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ) { Vector3 out; diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.h b/trinity/Eve/SpaceObject/EveSpaceObject2.h index b603c40fc..3df4f1522 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.h +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.h @@ -511,6 +511,55 @@ BLUE_CLASS( EveSpaceObject2 ) : int GetClosestLocatorIndex( const Vector3* position, BlueSharedString locatorSetName ); unsigned int GetLocatorCount( BlueSharedString locatorSetName ) const; Vector3 GetLocatorPositionFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ); + + /** + * @brief The point on an edge of the object's own geometry (its mesh, or a modular object's + * parts) nearest to position, and the normal to project a decal along so it wraps the edge. + * @see DecalTriangleCache::FindNearestEdge + * @param position, radius Object space; only edges within radius are considered. + * @return (found, (position, normal)) in object space. Not found while a mesh's triangle + * cache is still being built, which the first call on that mesh starts. + */ + std::pair> GetNearestHullEdge( const Vector3& position, float radius ); + + /** + * @brief The point on the object's own geometry (its mesh, or a modular object's parts) nearest + * to position, and that surface's normal, turned towards position. + * @see DecalTriangleCache::FindNearestSurface + * @param position, radius Object space; only surfaces within radius are considered. + * @return (found, (position, normal)) in object space. Not found while a mesh's triangle + * cache is still being built, which the first call on that mesh starts. + */ + std::pair> GetNearestSurfacePoint( const Vector3& position, float radius ); + + // Status of QueryNearestHullEdge and QueryNearestSurfacePoint + enum class GeometryQueryStatus : int + { + FOUND = 0, + // nothing within the radius, and every part in reach was searched + NONE = 1, + // nothing found yet: a part in reach is still building its triangle cache, ask again later + PENDING = 2, + }; + + /** + * @brief GetNearestHullEdge, telling a part still building its triangle cache from nothing in reach. + * @return (status, (position, normal)), status a GeometryQueryStatus. + */ + std::pair> QueryNearestHullEdge( const Vector3& position, float radius ); + + /** + * @brief GetNearestSurfacePoint, telling a part still building its triangle cache from nothing in reach. + * @return (status, (position, normal)), status a GeometryQueryStatus. + */ + std::pair> QueryNearestSurfacePoint( const Vector3& position, float radius ); + +private: + // The nearest of query( cache, part-space point, part-space radius ) over the object's own geometry + template + std::pair> FindNearestOnGeometry( const Vector3& position, float radius, Query&& query ); + +public: Vector3 GetLocatorRotationFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ); bool GetLocatorPosition( Vector3 * out, int index, bool inWorldSpace, BlueSharedString locatorSetName ); bool GetLocatorDirection( Vector3 * out, int index, bool inWorldSpace, BlueSharedString locatorSetName ); diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp index 350ac1d5c..d24ff77c6 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp @@ -548,6 +548,39 @@ const Be::ClassInfo* EveSpaceObject2::ExposeToBlue() "Get the closest locator in set to target, does not mind about direction of locator.\n" ":param position: position of target\n" ":param locatorSetName: name of locator set \n" ) + MAP_METHOD_AND_WRAP( + "GetNearestHullEdge", + GetNearestHullEdge, + "( position, radius ) -> ( found, ( position, normal ) )\n" + "Nearest point on an edge of the object's geometry (a fold sharper than 30 degrees, or an open edge), " + "in object space, with the normal a decal there should project along to wrap over the edge. " + "Not found while the geometry's triangle cache is still being built.\n" + ":param position: object-space point\n" + ":param radius: search radius in metres\n" ) + MAP_METHOD_AND_WRAP( + "QueryNearestHullEdge", + QueryNearestHullEdge, + "( position, radius ) -> ( status, ( position, normal ) )\n" + "GetNearestHullEdge with a status: 0 found, 1 nothing within radius (every part in reach searched), " + "2 pending (a part in reach is still building its triangle cache; ask again on a later frame).\n" + ":param position: object-space point\n" + ":param radius: search radius in metres\n" ) + MAP_METHOD_AND_WRAP( + "QueryNearestSurfacePoint", + QueryNearestSurfacePoint, + "( position, radius ) -> ( status, ( position, normal ) )\n" + "GetNearestSurfacePoint with a status: 0 found, 1 nothing within radius (every part in reach searched), " + "2 pending (a part in reach is still building its triangle cache; ask again on a later frame).\n" + ":param position: object-space point\n" + ":param radius: search radius in metres\n" ) + MAP_METHOD_AND_WRAP( + "GetNearestSurfacePoint", + GetNearestSurfacePoint, + "( position, radius ) -> ( found, ( position, normal ) )\n" + "Nearest point on the object's geometry, in object space, with that surface's normal turned " + "towards position. Not found while the geometry's triangle cache is still being built.\n" + ":param position: object-space point\n" + ":param radius: search radius in metres\n" ) MAP_METHOD_AND_WRAP( "GetLocatorPositionFromSet", GetLocatorPositionFromSet, diff --git a/trinity/Resources/TriGeometryRes.h b/trinity/Resources/TriGeometryRes.h index 99a465cd9..c88cfb808 100644 --- a/trinity/Resources/TriGeometryRes.h +++ b/trinity/Resources/TriGeometryRes.h @@ -139,6 +139,7 @@ struct MeshDecalData }; struct TriGeometryResMeshData; +struct DecalTriangleCache; extern bool g_eveIsAudioOcclusionGeometryEnabled; @@ -216,6 +217,8 @@ struct TriGeometryResMeshData std::unique_ptr m_audioGeometry; std::vector> m_decals; + // CPU triangles + grid for runtime decals, built on demand (see DecalTriangleCache) + std::shared_ptr m_decalTriangleCache; uint32_t m_lodMask; //A bit mask of which LODs have been loaded. TrackableStdVector> m_lods; diff --git a/trinity/Tr2Renderer.cpp b/trinity/Tr2Renderer.cpp index d1fbc170a..46f823287 100644 --- a/trinity/Tr2Renderer.cpp +++ b/trinity/Tr2Renderer.cpp @@ -10,6 +10,7 @@ #include "TriSettingsRegistrar.h" #include "TriPoolAllocator.h" #include "Resources/TriGeometryRes.h" +#include "Eve/SpaceObject/Attachments/EveDecalTriangleCache.h" using namespace Tr2RenderContextEnum; @@ -357,6 +358,7 @@ bool Tr2Renderer::Initialize() void Tr2Renderer::Shutdown() { + DecalTriangleCache::Shutdown(); GlobalStore().UnregisterVariable( "Time" ); USE_MAIN_THREAD_RENDER_CONTEXT(); //TODO! renderContext.m_esm.Shutdown(); @@ -1055,6 +1057,8 @@ void Tr2Renderer::BeginFrame() void Tr2Renderer::EndFrame() { + DecalTriangleCache::EndFrame(); + if( s_debugTextRenderer ) { s_debugTextRenderer->Clear();