diff --git a/62_CAD/CTriangleMesh.cpp b/62_CAD/CTriangleMesh.cpp new file mode 100644 index 000000000..5564c0a51 --- /dev/null +++ b/62_CAD/CTriangleMesh.cpp @@ -0,0 +1 @@ +#include "CTriangleMesh.h" \ No newline at end of file diff --git a/62_CAD/CTriangleMesh.h b/62_CAD/CTriangleMesh.h new file mode 100644 index 000000000..16995c28a --- /dev/null +++ b/62_CAD/CTriangleMesh.h @@ -0,0 +1,131 @@ +#pragma once + +#include +#include +#include "shaders/globals.hlsl" + +using namespace nbl; + +struct DTMHeightShadingInfo +{ + // Height Shading Mode + E_HEIGHT_SHADING_MODE heightShadingMode; + + // Used as fixed interval length for "DISCRETE_FIXED_LENGTH_INTERVALS" shading mode + float intervalLength; + + // Converts an interval index to its corresponding height value + // For example, if this value is 10.0, then an interval index of 2 corresponds to a height of 20.0. + // This computed height is later used to determine the interpolated color for shading. + // It makes sense for this variable to be always equal to `intervalLength` but sometimes it's a different scaling so that last index corresponds to largestHeight + float intervalIndexToHeightMultiplier; + + // Used for "DISCRETE_FIXED_LENGTH_INTERVALS" shading mode + // If `isCenteredShading` is true, the intervals are centered around `minHeight`, meaning the + // first interval spans [minHeight - intervalLength / 2.0, minHeight + intervalLength / 2.0]. + // Otherwise, intervals are aligned from `minHeight` upward, so the first interval spans + // [minHeight, minHeight + intervalLength]. + bool isCenteredShading; + + void addHeightColorMapEntry(float height, float32_t4 color) + { + heightColorSet.emplace(height, color); + } + + bool fillShaderDTMSettingsHeightColorMap(DTMSettings& dtmSettings) const + { + const uint32_t mapSize = heightColorSet.size(); + if (mapSize > DTMSettings::HeightColorMapMaxEntries) + return false; + dtmSettings.heightColorEntryCount = mapSize; + + int index = 0; + for (auto it = heightColorSet.begin(); it != heightColorSet.end(); ++it) + { + dtmSettings.heightColorMapHeights[index] = it->height; + dtmSettings.heightColorMapColors[index] = it->color; + ++index; + } + + return true; + } + +private: + struct HeightColor + { + float height; + float32_t4 color; + + bool operator<(const HeightColor& other) const + { + return height < other.height; + } + }; + + std::set heightColorSet; +}; + +struct DTMContourInfo +{ + LineStyleInfo lineStyleInfo; + + float startHeight; + float endHeight; + float heightInterval; +}; + +struct DTMSettingsInfo +{ + uint32_t mode = 0u; + + DTMHeightShadingInfo heightShadingInfo; + DTMContourInfo contourInfo; + LineStyleInfo outlineStyleInfo; +}; + +class CTriangleMesh final +{ +public: + using index_t = uint32_t; + using vertex_t = TriangleMeshVertex; + + inline void setVertices(core::vector&& vertices) + { + m_vertices = std::move(vertices); + } + inline void setIndices(core::vector&& indices) + { + m_indices = std::move(indices); + } + + inline const core::vector& getVertices() const + { + return m_vertices; + } + inline const core::vector& getIndices() const + { + return m_indices; + } + + inline size_t getVertexBuffByteSize() const + { + return sizeof(vertex_t) * m_vertices.size(); + } + inline size_t getIndexBuffByteSize() const + { + return sizeof(index_t) * m_indices.size(); + } + inline size_t getIndexCount() const + { + return m_indices.size(); + } + + inline void clear() + { + m_vertices.clear(); + m_indices.clear(); + } + + core::vector m_vertices; + core::vector m_indices; +}; \ No newline at end of file diff --git a/62_CAD/DrawResourcesFiller.cpp b/62_CAD/DrawResourcesFiller.cpp index 7cf96d693..a255bc700 100644 --- a/62_CAD/DrawResourcesFiller.cpp +++ b/62_CAD/DrawResourcesFiller.cpp @@ -15,105 +15,20 @@ void DrawResourcesFiller::setSubmitDrawsFunction(const SubmitFunc& func) submitDraws = func; } -void DrawResourcesFiller::allocateIndexBuffer(ILogicalDevice* logicalDevice, uint32_t maxIndices) +void DrawResourcesFiller::allocateResourcesBuffer(ILogicalDevice* logicalDevice, size_t size) { - maxIndexCount = maxIndices; - const size_t indexBufferSize = maxIndices * sizeof(index_buffer_type); - auto indexBuffer = ICPUBuffer::create({ indexBufferSize }); - - index_buffer_type* indices = reinterpret_cast(indexBuffer->getPointer()); - for (uint32_t i = 0u; i < maxIndices / 6u; ++i) - { - index_buffer_type objIndex = i; - indices[i * 6] = objIndex * 4u + 1u; - indices[i * 6 + 1u] = objIndex * 4u + 0u; - indices[i * 6 + 2u] = objIndex * 4u + 2u; - - indices[i * 6 + 3u] = objIndex * 4u + 1u; - indices[i * 6 + 4u] = objIndex * 4u + 2u; - indices[i * 6 + 5u] = objIndex * 4u + 3u; - } - - IGPUBuffer::SCreationParams indexBufferCreationParams = {}; - indexBufferCreationParams.size = indexBufferSize; - indexBufferCreationParams.usage = IGPUBuffer::EUF_INDEX_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT; - - m_utilities->createFilledDeviceLocalBufferOnDedMem(SIntendedSubmitInfo{.queue=m_copyQueue}, std::move(indexBufferCreationParams), indices).move_into(gpuDrawBuffers.indexBuffer); - gpuDrawBuffers.indexBuffer->setObjectDebugName("indexBuffer"); -} - -void DrawResourcesFiller::allocateMainObjectsBuffer(ILogicalDevice* logicalDevice, uint32_t mainObjects) -{ - maxMainObjects = mainObjects; - size_t mainObjectsBufferSize = maxMainObjects * sizeof(MainObject); - - IGPUBuffer::SCreationParams mainObjectsCreationParams = {}; - mainObjectsCreationParams.size = mainObjectsBufferSize; - mainObjectsCreationParams.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT; - gpuDrawBuffers.mainObjectsBuffer = logicalDevice->createBuffer(std::move(mainObjectsCreationParams)); - gpuDrawBuffers.mainObjectsBuffer->setObjectDebugName("mainObjectsBuffer"); - - IDeviceMemoryBacked::SDeviceMemoryRequirements memReq = gpuDrawBuffers.mainObjectsBuffer->getMemoryReqs(); - memReq.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto mainObjectsBufferMem = logicalDevice->allocate(memReq, gpuDrawBuffers.mainObjectsBuffer.get()); - - cpuDrawBuffers.mainObjectsBuffer = ICPUBuffer::create({ mainObjectsBufferSize }); -} - -void DrawResourcesFiller::allocateDrawObjectsBuffer(ILogicalDevice* logicalDevice, uint32_t drawObjects) -{ - maxDrawObjects = drawObjects; - size_t drawObjectsBufferSize = maxDrawObjects * sizeof(DrawObject); - - IGPUBuffer::SCreationParams drawObjectsCreationParams = {}; - drawObjectsCreationParams.size = drawObjectsBufferSize; - drawObjectsCreationParams.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT; - gpuDrawBuffers.drawObjectsBuffer = logicalDevice->createBuffer(std::move(drawObjectsCreationParams)); - gpuDrawBuffers.drawObjectsBuffer->setObjectDebugName("drawObjectsBuffer"); - - IDeviceMemoryBacked::SDeviceMemoryRequirements memReq = gpuDrawBuffers.drawObjectsBuffer->getMemoryReqs(); - memReq.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto drawObjectsBufferMem = logicalDevice->allocate(memReq, gpuDrawBuffers.drawObjectsBuffer.get()); - - cpuDrawBuffers.drawObjectsBuffer = ICPUBuffer::create({ drawObjectsBufferSize }); -} - -void DrawResourcesFiller::allocateGeometryBuffer(ILogicalDevice* logicalDevice, size_t size) -{ - maxGeometryBufferSize = size; - + size = core::alignUp(size, ResourcesMaxNaturalAlignment); + size = core::max(size, getMinimumRequiredResourcesBufferSize()); + // size = 368u; STRESS TEST IGPUBuffer::SCreationParams geometryCreationParams = {}; geometryCreationParams.size = size; - geometryCreationParams.usage = bitflag(IGPUBuffer::EUF_STORAGE_BUFFER_BIT) | IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT; - gpuDrawBuffers.geometryBuffer = logicalDevice->createBuffer(std::move(geometryCreationParams)); - gpuDrawBuffers.geometryBuffer->setObjectDebugName("geometryBuffer"); + geometryCreationParams.usage = bitflag(IGPUBuffer::EUF_SHADER_DEVICE_ADDRESS_BIT) | IGPUBuffer::EUF_TRANSFER_DST_BIT | IGPUBuffer::EUF_INDEX_BUFFER_BIT; + resourcesGPUBuffer = logicalDevice->createBuffer(std::move(geometryCreationParams)); + resourcesGPUBuffer->setObjectDebugName("drawResourcesBuffer"); - IDeviceMemoryBacked::SDeviceMemoryRequirements memReq = gpuDrawBuffers.geometryBuffer->getMemoryReqs(); + IDeviceMemoryBacked::SDeviceMemoryRequirements memReq = resourcesGPUBuffer->getMemoryReqs(); memReq.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto geometryBufferMem = logicalDevice->allocate(memReq, gpuDrawBuffers.geometryBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); - geometryBufferAddress = gpuDrawBuffers.geometryBuffer->getDeviceAddress(); - - cpuDrawBuffers.geometryBuffer = ICPUBuffer::create({ size }); -} - -void DrawResourcesFiller::allocateStylesBuffer(ILogicalDevice* logicalDevice, uint32_t lineStylesCount) -{ - { - maxLineStyles = lineStylesCount; - size_t lineStylesBufferSize = lineStylesCount * sizeof(LineStyle); - - IGPUBuffer::SCreationParams lineStylesCreationParams = {}; - lineStylesCreationParams.size = lineStylesBufferSize; - lineStylesCreationParams.usage = IGPUBuffer::EUF_STORAGE_BUFFER_BIT | IGPUBuffer::EUF_TRANSFER_DST_BIT; - gpuDrawBuffers.lineStylesBuffer = logicalDevice->createBuffer(std::move(lineStylesCreationParams)); - gpuDrawBuffers.lineStylesBuffer->setObjectDebugName("lineStylesBuffer"); - - IDeviceMemoryBacked::SDeviceMemoryRequirements memReq = gpuDrawBuffers.lineStylesBuffer->getMemoryReqs(); - memReq.memoryTypeBits &= logicalDevice->getPhysicalDevice()->getDeviceLocalMemoryTypeBits(); - auto stylesBufferMem = logicalDevice->allocate(memReq, gpuDrawBuffers.lineStylesBuffer.get()); - - cpuDrawBuffers.lineStylesBuffer = ICPUBuffer::create({ lineStylesBufferSize }); - } + auto mem = logicalDevice->allocate(memReq, resourcesGPUBuffer.get(), IDeviceMemoryAllocation::EMAF_DEVICE_ADDRESS_BIT); } void DrawResourcesFiller::allocateMSDFTextures(ILogicalDevice* logicalDevice, uint32_t maxMSDFs, uint32_t2 msdfsExtent) @@ -170,16 +85,17 @@ void DrawResourcesFiller::drawPolyline(const CPolylineBase& polyline, const Line if (!lineStyleInfo.isVisible()) return; - uint32_t styleIdx = addLineStyle_SubmitIfNeeded(lineStyleInfo, intendedNextSubmit); - - uint32_t mainObjIdx = addMainObject_SubmitIfNeeded(styleIdx, intendedNextSubmit); - - drawPolyline(polyline, mainObjIdx, intendedNextSubmit); + setActiveLineStyle(lineStyleInfo); + + beginMainObject(MainObjectType::POLYLINE); + drawPolyline(polyline, intendedNextSubmit); + endMainObject(); } -void DrawResourcesFiller::drawPolyline(const CPolylineBase& polyline, uint32_t polylineMainObjIdx, SIntendedSubmitInfo& intendedNextSubmit) +void DrawResourcesFiller::drawPolyline(const CPolylineBase& polyline, SIntendedSubmitInfo& intendedNextSubmit) { - if (polylineMainObjIdx == InvalidMainObjectIdx) + uint32_t mainObjectIdx = acquireActiveMainObjectIndex_SubmitIfNeeded(intendedNextSubmit); + if (mainObjectIdx == InvalidMainObjectIdx) { // TODO: assert or log error here assert(false); @@ -194,7 +110,7 @@ void DrawResourcesFiller::drawPolyline(const CPolylineBase& polyline, uint32_t p while (currentSectionIdx < sectionsCount) { const auto& currentSection = polyline.getSectionInfoAt(currentSectionIdx); - addPolylineObjects_Internal(polyline, currentSection, currentObjectInSection, polylineMainObjIdx); + addPolylineObjects_Internal(polyline, currentSection, currentObjectInSection, mainObjectIdx); if (currentObjectInSection >= currentSection.count) { @@ -202,7 +118,7 @@ void DrawResourcesFiller::drawPolyline(const CPolylineBase& polyline, uint32_t p currentObjectInSection = 0u; } else - submitCurrentDrawObjectsAndReset(intendedNextSubmit, polylineMainObjIdx); + submitCurrentDrawObjectsAndReset(intendedNextSubmit, mainObjectIdx); } if (!polyline.getConnectors().empty()) @@ -210,14 +126,66 @@ void DrawResourcesFiller::drawPolyline(const CPolylineBase& polyline, uint32_t p uint32_t currentConnectorPolylineObject = 0u; while (currentConnectorPolylineObject < polyline.getConnectors().size()) { - addPolylineConnectors_Internal(polyline, currentConnectorPolylineObject, polylineMainObjIdx); + addPolylineConnectors_Internal(polyline, currentConnectorPolylineObject, mainObjectIdx); if (currentConnectorPolylineObject < polyline.getConnectors().size()) - submitCurrentDrawObjectsAndReset(intendedNextSubmit, polylineMainObjIdx); + submitCurrentDrawObjectsAndReset(intendedNextSubmit, mainObjectIdx); } } } +void DrawResourcesFiller::drawTriangleMesh( + const CTriangleMesh& mesh, + const DTMSettingsInfo& dtmSettingsInfo, + SIntendedSubmitInfo& intendedNextSubmit) +{ + flushDrawObjects(); // flushes draw call construction of any possible draw objects before dtm, because currently we're sepaerating dtm draw calls from drawObj draw calls + + setActiveDTMSettings(dtmSettingsInfo); // TODO !!!! + beginMainObject(MainObjectType::DTM); + + DrawCallData drawCallData = {}; + drawCallData.isDTMRendering = true; + + uint32_t mainObjectIdx = acquireActiveMainObjectIndex_SubmitIfNeeded(intendedNextSubmit); + drawCallData.dtm.triangleMeshMainObjectIndex = mainObjectIdx; + + ICPUBuffer::SCreationParams geometryBuffParams; + + // concatenate the index and vertex buffer into the geometry buffer + const size_t indexBuffByteSize = mesh.getIndexBuffByteSize(); + const size_t vtxBuffByteSize = mesh.getVertexBuffByteSize(); + const size_t dataToAddByteSize = vtxBuffByteSize + indexBuffByteSize; + + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + + // TODO: assert of geometry buffer size, do i need to check if size of objects to be added <= remainingResourcesSize? + // TODO: auto submit instead of assert + assert(dataToAddByteSize <= remainingResourcesSize); + + { + // NOTE[ERFAN]: these push contants will be removed, everything will be accessed by dtmSettings, including where the vertex buffer data resides + + // Copy VertexBuffer + size_t geometryBufferOffset = resourcesCollection.geometryInfo.increaseSizeAndGetOffset(dataToAddByteSize, alignof(CTriangleMesh::vertex_t)); + void* dst = resourcesCollection.geometryInfo.data() + geometryBufferOffset; + // the actual bda address will be determined only after all copies are finalized, later we will do += `baseBDAAddress + geometryInfo.bufferOffset` + drawCallData.dtm.triangleMeshVerticesBaseAddress = geometryBufferOffset; + memcpy(dst, mesh.getVertices().data(), vtxBuffByteSize); + geometryBufferOffset += vtxBuffByteSize; + + // Copy IndexBuffer + dst = resourcesCollection.geometryInfo.data() + geometryBufferOffset; + drawCallData.dtm.indexBufferOffset = geometryBufferOffset; + memcpy(dst, mesh.getIndices().data(), indexBuffByteSize); + geometryBufferOffset += indexBuffByteSize; + } + + drawCallData.dtm.indexCount = mesh.getIndexCount(); + drawCalls.push_back(drawCallData); + endMainObject(); +} + // TODO[Erfan]: Makes more sense if parameters are: solidColor + fillPattern + patternColor void DrawResourcesFiller::drawHatch( const Hatch& hatch, @@ -226,10 +194,8 @@ void DrawResourcesFiller::drawHatch( const HatchFillPattern fillPattern, SIntendedSubmitInfo& intendedNextSubmit) { - // TODO[Optimization Idea]: don't draw hatch twice if both colors are visible: instead do the msdf inside the alpha resolve by detecting mainObj being a hatch - // https://discord.com/channels/593902898015109131/856835291712716820/1228337893366300743 - // TODO: Come back to this idea when doing color resolve for ecws (they don't have mainObj/style Index, instead they have uv into a texture - + // TODO[Optimization Idea]: don't draw hatch twice, we now have color storage buffer and we can treat rendering hatches like a procedural texture (requires 2 colors so no more abusing of linestyle for hatches) + // if backgroundColor is visible drawHatch(hatch, backgroundColor, intendedNextSubmit); // if foregroundColor is visible @@ -251,23 +217,27 @@ void DrawResourcesFiller::drawHatch( MSDFInputInfo msdfInfo = MSDFInputInfo(fillPattern); textureIdx = getMSDFIndexFromInputInfo(msdfInfo, intendedNextSubmit); if (textureIdx == InvalidTextureIdx) - textureIdx = addMSDFTexture(msdfInfo, getHatchFillPatternMSDF(fillPattern), InvalidMainObjectIdx, intendedNextSubmit); + textureIdx = addMSDFTexture(msdfInfo, getHatchFillPatternMSDF(fillPattern), intendedNextSubmit); _NBL_DEBUG_BREAK_IF(textureIdx == InvalidTextureIdx); // probably getHatchFillPatternMSDF returned nullptr } LineStyleInfo lineStyle = {}; lineStyle.color = color; lineStyle.screenSpaceLineWidth = nbl::hlsl::bit_cast(textureIdx); - const uint32_t styleIdx = addLineStyle_SubmitIfNeeded(lineStyle, intendedNextSubmit); - - uint32_t mainObjIdx = addMainObject_SubmitIfNeeded(styleIdx, intendedNextSubmit); - uint32_t currentObjectInSection = 0u; // Object here refers to DrawObject used in vertex shader. You can think of it as a Cage. + + setActiveLineStyle(lineStyle); + beginMainObject(MainObjectType::HATCH); + + uint32_t mainObjectIdx = acquireActiveMainObjectIndex_SubmitIfNeeded(intendedNextSubmit); + uint32_t currentObjectInSection = 0u; // Object here refers to DrawObject. You can think of it as a Cage. while (currentObjectInSection < hatch.getHatchBoxCount()) { - addHatch_Internal(hatch, currentObjectInSection, mainObjIdx); + addHatch_Internal(hatch, currentObjectInSection, mainObjectIdx); if (currentObjectInSection < hatch.getHatchBoxCount()) - submitCurrentDrawObjectsAndReset(intendedNextSubmit, mainObjIdx); + submitCurrentDrawObjectsAndReset(intendedNextSubmit, mainObjectIdx); } + + endMainObject(); } void DrawResourcesFiller::drawHatch(const Hatch& hatch, const float32_t4& color, SIntendedSubmitInfo& intendedNextSubmit) @@ -282,14 +252,16 @@ void DrawResourcesFiller::drawFontGlyph( float32_t2 dirU, float32_t aspectRatio, float32_t2 minUV, - uint32_t mainObjIdx, SIntendedSubmitInfo& intendedNextSubmit) { uint32_t textureIdx = InvalidTextureIdx; const MSDFInputInfo msdfInput = MSDFInputInfo(fontFace->getHash(), glyphIdx); textureIdx = getMSDFIndexFromInputInfo(msdfInput, intendedNextSubmit); if (textureIdx == InvalidTextureIdx) - textureIdx = addMSDFTexture(msdfInput, getGlyphMSDF(fontFace, glyphIdx), mainObjIdx, intendedNextSubmit); + textureIdx = addMSDFTexture(msdfInput, getGlyphMSDF(fontFace, glyphIdx), intendedNextSubmit); + + uint32_t mainObjIdx = acquireActiveMainObjectIndex_SubmitIfNeeded(intendedNextSubmit); + assert(mainObjIdx != InvalidMainObjectIdx); if (textureIdx != InvalidTextureIdx) { @@ -309,147 +281,166 @@ void DrawResourcesFiller::drawFontGlyph( } } +void DrawResourcesFiller::_test_addImageObject(float64_t2 topLeftPos, float32_t2 size, float32_t rotation, SIntendedSubmitInfo& intendedNextSubmit) +{ + auto addImageObject_Internal = [&](const ImageObjectInfo& imageObjectInfo, uint32_t mainObjIdx) -> bool + { + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + + const uint32_t uploadableObjects = (remainingResourcesSize) / (sizeof(ImageObjectInfo) + sizeof(DrawObject) + sizeof(uint32_t) * 6u); + // TODO[ERFAN]: later take into account: our maximum indexable vertex + + if (uploadableObjects <= 0u) + return false; + + // Add Geometry + size_t geometryBufferOffset = resourcesCollection.geometryInfo.increaseSizeAndGetOffset(sizeof(ImageObjectInfo), alignof(ImageObjectInfo)); + void* dst = resourcesCollection.geometryInfo.data() + geometryBufferOffset; + memcpy(dst, &imageObjectInfo, sizeof(ImageObjectInfo)); + + // Push Indices, remove later when compute fills this + uint32_t* indexBufferToBeFilled = resourcesCollection.indexBuffer.increaseCountAndGetPtr(6u * 1u); + const uint32_t startObj = resourcesCollection.drawObjects.getCount(); + uint32_t i = 0u; + indexBufferToBeFilled[i*6] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 1u] = (startObj+i)*4u + 0u; + indexBufferToBeFilled[i*6 + 2u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 3u] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 4u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 5u] = (startObj+i)*4u + 3u; + + // Add DrawObjs + DrawObject* drawObjectsToBeFilled = resourcesCollection.drawObjects.increaseCountAndGetPtr(1u); + DrawObject drawObj = {}; + drawObj.mainObjIndex = mainObjIdx; + drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::IMAGE) | (0 << 16)); // TODO: use custom pack/unpack function + drawObj.geometryAddress = geometryBufferOffset; + drawObjectsToBeFilled[0u] = drawObj; + + return true; + }; + + beginMainObject(MainObjectType::IMAGE); + + uint32_t mainObjIdx = acquireActiveMainObjectIndex_SubmitIfNeeded(intendedNextSubmit); + + ImageObjectInfo info = {}; + info.topLeft = topLeftPos; + info.dirU = float32_t2(size.x * cos(rotation), size.x * sin(rotation)); // + info.aspectRatio = size.y / size.x; + info.textureID = 0u; + if (!addImageObject_Internal(info, mainObjIdx)) + { + // single image object couldn't fit into memory to push to gpu, so we submit rendering current objects and reset geometry buffer and draw objects + submitCurrentDrawObjectsAndReset(intendedNextSubmit, mainObjIdx); + bool success = addImageObject_Internal(info, mainObjIdx); + assert(success); // this should always be true, otherwise it's either bug in code or not enough memory allocated to hold a single image object + } + + endMainObject(); +} + bool DrawResourcesFiller::finalizeAllCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit) { bool success = true; - success &= finalizeMainObjectCopiesToGPU(intendedNextSubmit); - success &= finalizeGeometryCopiesToGPU(intendedNextSubmit); - success &= finalizeLineStyleCopiesToGPU(intendedNextSubmit); + flushDrawObjects(); + success &= finalizeBufferCopies(intendedNextSubmit); success &= finalizeTextureCopies(intendedNextSubmit); return success; } -uint32_t DrawResourcesFiller::addLineStyle_SubmitIfNeeded(const LineStyleInfo& lineStyle, SIntendedSubmitInfo& intendedNextSubmit) +void DrawResourcesFiller::setActiveLineStyle(const LineStyleInfo& lineStyle) { - uint32_t outLineStyleIdx = addLineStyle_Internal(lineStyle); - if (outLineStyleIdx == InvalidStyleIdx) - { - finalizeAllCopiesToGPU(intendedNextSubmit); - submitDraws(intendedNextSubmit); - resetGeometryCounters(); - resetMainObjectCounters(); - resetLineStyleCounters(); - outLineStyleIdx = addLineStyle_Internal(lineStyle); - assert(outLineStyleIdx != InvalidStyleIdx); - } - return outLineStyleIdx; + activeLineStyle = lineStyle; + activeLineStyleIndex = InvalidStyleIdx; } -uint32_t DrawResourcesFiller::addMainObject_SubmitIfNeeded(uint32_t styleIdx, SIntendedSubmitInfo& intendedNextSubmit) +void DrawResourcesFiller::setActiveDTMSettings(const DTMSettingsInfo& dtmSettingsInfo) { - MainObject mainObject = {}; - mainObject.styleIdx = styleIdx; - mainObject.clipProjectionAddress = acquireCurrentClipProjectionAddress(intendedNextSubmit); - uint32_t outMainObjectIdx = addMainObject_Internal(mainObject); - if (outMainObjectIdx == InvalidMainObjectIdx) - { - finalizeAllCopiesToGPU(intendedNextSubmit); - submitDraws(intendedNextSubmit); + activeDTMSettings = dtmSettingsInfo; + activeDTMSettingsIndex = InvalidDTMSettingsIdx; +} - // geometries needs to be reset because they reference draw objects and draw objects reference main objects that are now unavailable and reset - resetGeometryCounters(); - // mainObjects needs to be reset because we submitted every previous main object - resetMainObjectCounters(); - // we shouldn't reset linestyles and clip projections here because it was possibly requested to push to mem before addMainObjects - // but clip projections are reset due to geometry/bda buffer being reset so we need to push again - - // acquireCurrentClipProjectionAddress again here because clip projection should exist in the geometry buffer, and reseting geometry counters will invalidate the current clip proj and requires repush - mainObject.clipProjectionAddress = acquireCurrentClipProjectionAddress(intendedNextSubmit); - outMainObjectIdx = addMainObject_Internal(mainObject); - assert(outMainObjectIdx != InvalidMainObjectIdx); - } - - return outMainObjectIdx; +void DrawResourcesFiller::beginMainObject(MainObjectType type) +{ + activeMainObjectType = type; + activeMainObjectIndex = InvalidMainObjectIdx; +} + +void DrawResourcesFiller::endMainObject() +{ + activeMainObjectType = MainObjectType::NONE; + activeMainObjectIndex = InvalidMainObjectIdx; } void DrawResourcesFiller::pushClipProjectionData(const ClipProjectionData& clipProjectionData) { - clipProjections.push_back(clipProjectionData); - clipProjectionAddresses.push_back(InvalidClipProjectionAddress); + activeClipProjections.push_back(clipProjectionData); + activeClipProjectionIndices.push_back(InvalidClipProjectionIndex); } void DrawResourcesFiller::popClipProjectionData() { - if (clipProjections.empty()) + if (activeClipProjections.empty()) return; - clipProjections.pop_back(); - clipProjectionAddresses.pop_back(); + activeClipProjections.pop_back(); + activeClipProjectionIndices.pop_back(); } -bool DrawResourcesFiller::finalizeMainObjectCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit) +bool DrawResourcesFiller::finalizeBufferCopies(SIntendedSubmitInfo& intendedNextSubmit) { - bool success = true; - // Copy MainObjects - uint32_t remainingMainObjects = currentMainObjectCount - inMemMainObjectCount; - SBufferRange mainObjectsRange = { sizeof(MainObject) * inMemMainObjectCount, sizeof(MainObject) * remainingMainObjects, gpuDrawBuffers.mainObjectsBuffer }; - if (mainObjectsRange.size > 0u) - { - const MainObject* srcMainObjData = reinterpret_cast(cpuDrawBuffers.mainObjectsBuffer->getPointer()) + inMemMainObjectCount; - if (m_utilities->updateBufferRangeViaStagingBuffer(intendedNextSubmit, mainObjectsRange, srcMainObjData)) - inMemMainObjectCount = currentMainObjectCount; - else - { - // TODO: Log - success = false; - } - } - return success; -} + copiedResourcesSize = 0ull; -bool DrawResourcesFiller::finalizeGeometryCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit) -{ - bool success = true; - // Copy DrawObjects - uint32_t remainingDrawObjects = currentDrawObjectCount - inMemDrawObjectCount; - SBufferRange drawObjectsRange = { sizeof(DrawObject) * inMemDrawObjectCount, sizeof(DrawObject) * remainingDrawObjects, gpuDrawBuffers.drawObjectsBuffer }; - if (drawObjectsRange.size > 0u) - { - const DrawObject* srcDrawObjData = reinterpret_cast(cpuDrawBuffers.drawObjectsBuffer->getPointer()) + inMemDrawObjectCount; - if (m_utilities->updateBufferRangeViaStagingBuffer(intendedNextSubmit, drawObjectsRange, srcDrawObjData)) - inMemDrawObjectCount = currentDrawObjectCount; - else - { - // TODO: Log - success = false; - } - } + assert(resourcesCollection.calculateTotalConsumption() <= resourcesGPUBuffer->getSize()); - // Copy GeometryBuffer - uint64_t remainingGeometrySize = currentGeometryBufferSize - inMemGeometryBufferSize; - SBufferRange geomRange = { inMemGeometryBufferSize, remainingGeometrySize, gpuDrawBuffers.geometryBuffer }; - if (geomRange.size > 0u) - { - const uint8_t* srcGeomData = reinterpret_cast(cpuDrawBuffers.geometryBuffer->getPointer()) + inMemGeometryBufferSize; - if (m_utilities->updateBufferRangeViaStagingBuffer(intendedNextSubmit, geomRange, srcGeomData)) - inMemGeometryBufferSize = currentGeometryBufferSize; - else + auto copyCPUFilledDrawBuffer = [&](auto& drawBuffer) -> bool { - // TODO: Log - success = false; - } - } - return success; -} + // drawBuffer must be of type CPUGeneratedResource + SBufferRange copyRange = { copiedResourcesSize, drawBuffer.getStorageSize(), resourcesGPUBuffer}; -bool DrawResourcesFiller::finalizeLineStyleCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit) -{ - bool success = true; - // Copy LineStyles - uint32_t remainingLineStyles = currentLineStylesCount - inMemLineStylesCount; - SBufferRange stylesRange = { sizeof(LineStyle) * inMemLineStylesCount, sizeof(LineStyle) * remainingLineStyles, gpuDrawBuffers.lineStylesBuffer }; - if (stylesRange.size > 0u) - { - const LineStyle* srcLineStylesData = reinterpret_cast(cpuDrawBuffers.lineStylesBuffer->getPointer()) + inMemLineStylesCount; - if (m_utilities->updateBufferRangeViaStagingBuffer(intendedNextSubmit, stylesRange, srcLineStylesData)) - inMemLineStylesCount = currentLineStylesCount; - else + if (copyRange.offset + copyRange.size > resourcesGPUBuffer->getSize()) + { + // TODO: LOG ERROR, this shouldn't happen with correct auto-submission mechanism + assert(false); + return false; + } + + drawBuffer.bufferOffset = copyRange.offset; + if (copyRange.size > 0ull) + { + if (!m_utilities->updateBufferRangeViaStagingBuffer(intendedNextSubmit, copyRange, drawBuffer.vector.data())) + return false; + copiedResourcesSize += drawBuffer.getAlignedStorageSize(); + } + return true; + }; + + auto addComputeReservedFilledDrawBuffer = [&](auto& drawBuffer) -> bool { - // TODO: Log - success = false; - } - } - return success; + // drawBuffer must be of type ReservedComputeResource + SBufferRange copyRange = { copiedResourcesSize, drawBuffer.getStorageSize(), resourcesGPUBuffer}; + + if (copyRange.offset + copyRange.size > resourcesGPUBuffer->getSize()) + { + // TODO: LOG ERROR, this shouldn't happen with correct auto-submission mechanism + assert(false); + return false; + } + + drawBuffer.bufferOffset = copyRange.offset; + copiedResourcesSize += drawBuffer.getAlignedStorageSize(); + }; + + copyCPUFilledDrawBuffer(resourcesCollection.lineStyles); + copyCPUFilledDrawBuffer(resourcesCollection.dtmSettings); + copyCPUFilledDrawBuffer(resourcesCollection.clipProjections); + copyCPUFilledDrawBuffer(resourcesCollection.mainObjects); + copyCPUFilledDrawBuffer(resourcesCollection.drawObjects); + copyCPUFilledDrawBuffer(resourcesCollection.indexBuffer); + copyCPUFilledDrawBuffer(resourcesCollection.geometryInfo); + + return true; } bool DrawResourcesFiller::finalizeTextureCopies(SIntendedSubmitInfo& intendedNextSubmit) @@ -599,131 +590,216 @@ bool DrawResourcesFiller::finalizeTextureCopies(SIntendedSubmitInfo& intendedNex } } -void DrawResourcesFiller::submitCurrentDrawObjectsAndReset(SIntendedSubmitInfo& intendedNextSubmit, uint32_t mainObjectIndex) +const size_t DrawResourcesFiller::calculateRemainingResourcesSize() const +{ + assert(resourcesGPUBuffer->getSize() >= resourcesCollection.calculateTotalConsumption()); + return resourcesGPUBuffer->getSize() - resourcesCollection.calculateTotalConsumption(); +} + +void DrawResourcesFiller::submitCurrentDrawObjectsAndReset(SIntendedSubmitInfo& intendedNextSubmit, uint32_t& mainObjectIndex) { finalizeAllCopiesToGPU(intendedNextSubmit); submitDraws(intendedNextSubmit); + reset(); // resets everything, things referenced through mainObj and other shit will be pushed again through acquireXXX_SubmitIfNeeded + mainObjectIndex = acquireActiveMainObjectIndex_SubmitIfNeeded(intendedNextSubmit); // it will be 0 because it's first mainObjectIndex after reset and invalidation +} - // We reset Geometry Counters (drawObj+geometryInfos) because we're done rendering previous geometry - // We don't reset counters for styles because we will be reusing them - resetGeometryCounters(); - -#if 1 - if (mainObjectIndex < maxMainObjects) - { - // Check if user is following proper usage, mainObjectIndex should be the last mainObj added before an autosubmit, because this is the only mainObj we want to maintain. - // See comments on`addMainObject_SubmitIfNeeded` function - // TODO: consider forcing this by not expose mainObjectIndex to user and keep track of a "currentMainObj" (?) - _NBL_DEBUG_BREAK_IF(mainObjectIndex != (currentMainObjectCount - 1u)); - - // If the clip projection stack is non-empty, then it means we need to re-push the clipProjectionData (because it existed in geometry data and it was erased) - uint64_t newClipProjectionAddress = acquireCurrentClipProjectionAddress(intendedNextSubmit); - // only re-upload mainObjData if it's clipProjectionAddress was changed - if (newClipProjectionAddress != getMainObject(mainObjectIndex)->clipProjectionAddress) - { - // then modify the mainObject data - getMainObject(mainObjectIndex)->clipProjectionAddress = newClipProjectionAddress; - // we need to rewind back inMemMainObjectCount to this mainObjIndex so it re-uploads the current mainObject (because we modified it) - inMemMainObjectCount = core::min(inMemMainObjectCount, mainObjectIndex); - } +uint32_t DrawResourcesFiller::addLineStyle_Internal(const LineStyleInfo& lineStyleInfo) +{ + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + const bool enoughMem = remainingResourcesSize >= sizeof(LineStyle); // enough remaining memory for 1 more linestyle? + if (!enoughMem) + return InvalidStyleIdx; + // TODO: Maybe constraint by a max size? and return InvalidIdx if it would exceed + + LineStyle gpuLineStyle = lineStyleInfo.getAsGPUData(); + _NBL_DEBUG_BREAK_IF(gpuLineStyle.stipplePatternSize > LineStyle::StipplePatternMaxSize); // Oops, even after style normalization the style is too long to be in gpu mem :( + for (uint32_t i = 0u; i < resourcesCollection.lineStyles.vector.size(); ++i) + { + const LineStyle& itr = resourcesCollection.lineStyles.vector[i]; + if (itr == gpuLineStyle) + return i; } - // TODO: Consider resetting MainObjects here as well and addMainObject for the new data again, but account for the fact that mainObjectIndex now changed (either change through uint32_t& or keeping track of "currentMainObj" in drawResourcesFiller -#else - resetMainObjectCounters(); + return resourcesCollection.lineStyles.addAndGetOffset(gpuLineStyle); // this will implicitly increase total resource consumption and reduce remaining size --> no need for mem size trackers +} + +uint32_t DrawResourcesFiller::addDTMSettings_Internal(const DTMSettingsInfo& dtmSettingsInfo, SIntendedSubmitInfo& intendedNextSubmit) +{ + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + const size_t maxMemRequired = sizeof(DTMSettings) + 2 * sizeof(LineStyle); + const bool enoughMem = remainingResourcesSize >= maxMemRequired; // enough remaining memory for 1 more dtm settings with 2 referenced line styles? + + if (!enoughMem) + return InvalidDTMSettingsIdx; + // TODO: Maybe constraint by a max size? and return InvalidIdx if it would exceed - // If there is a mainObject data we need to maintain and keep it's clipProjectionAddr valid - if (mainObjectIndex < maxMainObjects) + DTMSettings dtmSettings; + + ////dtmSettingsInfo.mode = E_DTM_MODE::HEIGHT_SHADING | E_DTM_MODE::CONTOUR | E_DTM_MODE::OUTLINE; + + dtmSettings.mode = dtmSettingsInfo.mode; + if (dtmSettings.mode & E_DTM_MODE::HEIGHT_SHADING) { - MainObject mainObjToMaintain = *getMainObject(mainObjectIndex); + switch (dtmSettingsInfo.heightShadingInfo.heightShadingMode) + { + case E_HEIGHT_SHADING_MODE::DISCRETE_VARIABLE_LENGTH_INTERVALS: + dtmSettings.intervalLength = std::numeric_limits::infinity(); + break; + case E_HEIGHT_SHADING_MODE::DISCRETE_FIXED_LENGTH_INTERVALS: + dtmSettings.intervalLength = dtmSettingsInfo.heightShadingInfo.intervalLength; + break; + case E_HEIGHT_SHADING_MODE::CONTINOUS_INTERVALS: + dtmSettings.intervalLength = 0.0f; + break; + } + dtmSettings.intervalIndexToHeightMultiplier = dtmSettingsInfo.heightShadingInfo.intervalIndexToHeightMultiplier; + dtmSettings.isCenteredShading = static_cast(dtmSettingsInfo.heightShadingInfo.isCenteredShading); + _NBL_DEBUG_BREAK_IF(!dtmSettingsInfo.heightShadingInfo.fillShaderDTMSettingsHeightColorMap(dtmSettings)); + } + if (dtmSettings.mode & E_DTM_MODE::CONTOUR) + { + dtmSettings.contourLinesStartHeight = dtmSettingsInfo.contourInfo.startHeight; + dtmSettings.contourLinesEndHeight = dtmSettingsInfo.contourInfo.endHeight; + dtmSettings.contourLinesHeightInterval = dtmSettingsInfo.contourInfo.heightInterval; + dtmSettings.contourLineStyleIdx = addLineStyle_Internal(dtmSettingsInfo.contourInfo.lineStyleInfo); + } + if (dtmSettings.mode & E_DTM_MODE::OUTLINE) + { + dtmSettings.outlineLineStyleIdx = addLineStyle_Internal(dtmSettingsInfo.outlineStyleInfo); + } - // If the clip projection stack is non-empty, then it means we need to re-push the clipProjectionData (because it exists in geometry data and it was reset) - // `acquireCurrentClipProjectionAddress` shouldn't/won't trigger auto-submit because geometry buffer counters were reset and our geometry buffer is supposed to be larger than a single clipProjectionData - mainObjToMaintain->clipProjectionAddress = acquireCurrentClipProjectionAddress(intendedNextSubmit); - - // We're calling `addMainObject_Internal` instead of safer `addMainObject_SubmitIfNeeded` because we've reset our mainObject and we're sure this won't need an autoSubmit. - addMainObject_Internal(mainObjToMaintain); + for (uint32_t i = 0u; i < resourcesCollection.dtmSettings.vector.size(); ++i) + { + const DTMSettings& itr = resourcesCollection.dtmSettings.vector[i]; + if (itr == dtmSettings) + return i; } -#endif + + return resourcesCollection.dtmSettings.addAndGetOffset(dtmSettings); // this will implicitly increase total resource consumption and reduce remaining size --> no need for mem size trackers } -uint32_t DrawResourcesFiller::addMainObject_Internal(const MainObject& mainObject) +uint32_t DrawResourcesFiller::acquireActiveLineStyleIndex_SubmitIfNeeded(SIntendedSubmitInfo& intendedNextSubmit) { - MainObject* mainObjsArray = reinterpret_cast(cpuDrawBuffers.mainObjectsBuffer->getPointer()); + if (activeLineStyleIndex == InvalidStyleIdx) + activeLineStyleIndex = addLineStyle_SubmitIfNeeded(activeLineStyle, intendedNextSubmit); - if (currentMainObjectCount >= MaxIndexableMainObjects) - return InvalidMainObjectIdx; - if (currentMainObjectCount >= maxMainObjects) - return InvalidMainObjectIdx; - - void* dst = mainObjsArray + currentMainObjectCount; - memcpy(dst, &mainObject, sizeof(MainObject)); - uint32_t ret = currentMainObjectCount; - currentMainObjectCount++; - return ret; + return activeLineStyleIndex; } -uint32_t DrawResourcesFiller::addLineStyle_Internal(const LineStyleInfo& lineStyleInfo) +uint32_t DrawResourcesFiller::acquireActiveDTMSettingsIndex_SubmitIfNeeded(SIntendedSubmitInfo& intendedNextSubmit) { - LineStyle gpuLineStyle = lineStyleInfo.getAsGPUData(); - _NBL_DEBUG_BREAK_IF(gpuLineStyle.stipplePatternSize > LineStyle::StipplePatternMaxSize); // Oops, even after style normalization the style is too long to be in gpu mem :( - LineStyle* stylesArray = reinterpret_cast(cpuDrawBuffers.lineStylesBuffer->getPointer()); - for (uint32_t i = 0u; i < currentLineStylesCount; ++i) - { - const LineStyle& itr = stylesArray[i]; - - if (itr == gpuLineStyle) - return i; - } + if (activeDTMSettingsIndex == InvalidDTMSettingsIdx) + activeDTMSettingsIndex = addDTMSettings_SubmitIfNeeded(activeDTMSettings, intendedNextSubmit); + + return activeDTMSettingsIndex; +} - if (currentLineStylesCount >= maxLineStyles) - return InvalidStyleIdx; +uint32_t DrawResourcesFiller::acquireActiveClipProjectionIndex_SubmitIfNeeded(SIntendedSubmitInfo& intendedNextSubmit) +{ + if (activeClipProjectionIndices.empty()) + return InvalidClipProjectionIndex; - void* dst = stylesArray + currentLineStylesCount; - memcpy(dst, &gpuLineStyle, sizeof(LineStyle)); - return currentLineStylesCount++; + if (activeClipProjectionIndices.back() == InvalidClipProjectionIndex) + activeClipProjectionIndices.back() = addClipProjectionData_SubmitIfNeeded(activeClipProjections.back(), intendedNextSubmit); + + return activeClipProjectionIndices.back(); } -uint64_t DrawResourcesFiller::acquireCurrentClipProjectionAddress(SIntendedSubmitInfo& intendedNextSubmit) +uint32_t DrawResourcesFiller::acquireActiveMainObjectIndex_SubmitIfNeeded(SIntendedSubmitInfo& intendedNextSubmit) { - if (clipProjectionAddresses.empty()) - return InvalidClipProjectionAddress; + if (activeMainObjectIndex != InvalidMainObjectIdx) + return activeMainObjectIndex; + if (activeMainObjectType == MainObjectType::NONE) + { + assert(false); // You're probably trying to acquire mainObjectIndex outside of startMainObject, endMainObject scope + return InvalidMainObjectIdx; + } - if (clipProjectionAddresses.back() == InvalidClipProjectionAddress) - clipProjectionAddresses.back() = addClipProjectionData_SubmitIfNeeded(clipProjections.back(), intendedNextSubmit); + const bool needsLineStyle = + (activeMainObjectType == MainObjectType::POLYLINE) || + (activeMainObjectType == MainObjectType::HATCH) || + (activeMainObjectType == MainObjectType::TEXT); + const bool needsDTMSettings = (activeMainObjectType == MainObjectType::DTM); + const bool needsCustomClipProjection = (!activeClipProjectionIndices.empty()); + + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + // making sure MainObject and everything it references fits into remaining resources mem + size_t memRequired = sizeof(MainObject); + if (needsLineStyle) memRequired += sizeof(LineStyle); + if (needsDTMSettings) memRequired += sizeof(DTMSettings); + if (needsCustomClipProjection) memRequired += sizeof(ClipProjectionData); + + const bool enoughMem = remainingResourcesSize >= memRequired; // enough remaining memory for 1 more dtm settings with 2 referenced line styles? + const bool needToOverflowSubmit = (!enoughMem) || (resourcesCollection.mainObjects.vector.size() >= MaxIndexableMainObjects); + + if (needToOverflowSubmit) + { + // failed to fit into remaining resources mem or exceeded max indexable mainobj + finalizeAllCopiesToGPU(intendedNextSubmit); + submitDraws(intendedNextSubmit); + reset(); // resets everything! be careful! + } - return clipProjectionAddresses.back(); + MainObject mainObject = {}; + // These 3 calls below shouldn't need to Submit because we made sure there is enough memory for all of them. + // if something here triggers a auto-submit it's a possible bug with calculating `memRequired` above, TODO: assert that somehow? + mainObject.styleIdx = (needsLineStyle) ? acquireActiveLineStyleIndex_SubmitIfNeeded(intendedNextSubmit) : InvalidStyleIdx; + mainObject.dtmSettingsIdx = (needsDTMSettings) ? acquireActiveDTMSettingsIndex_SubmitIfNeeded(intendedNextSubmit) : InvalidDTMSettingsIdx; + mainObject.clipProjectionIndex = (needsCustomClipProjection) ? acquireActiveClipProjectionIndex_SubmitIfNeeded(intendedNextSubmit) : InvalidClipProjectionIndex; + activeMainObjectIndex = resourcesCollection.mainObjects.addAndGetOffset(mainObject); + return activeMainObjectIndex; } -uint64_t DrawResourcesFiller::addClipProjectionData_SubmitIfNeeded(const ClipProjectionData& clipProjectionData, SIntendedSubmitInfo& intendedNextSubmit) +uint32_t DrawResourcesFiller::addLineStyle_SubmitIfNeeded(const LineStyleInfo& lineStyle, SIntendedSubmitInfo& intendedNextSubmit) { - uint64_t outClipProjectionAddress = addClipProjectionData_Internal(clipProjectionData); - if (outClipProjectionAddress == InvalidClipProjectionAddress) + uint32_t outLineStyleIdx = addLineStyle_Internal(lineStyle); + if (outLineStyleIdx == InvalidStyleIdx) { + // There wasn't enough resource memory remaining to fit a single LineStyle finalizeAllCopiesToGPU(intendedNextSubmit); submitDraws(intendedNextSubmit); + reset(); // resets everything! be careful! + + outLineStyleIdx = addLineStyle_Internal(lineStyle); + assert(outLineStyleIdx != InvalidStyleIdx); + } - resetGeometryCounters(); - resetMainObjectCounters(); + return outLineStyleIdx; +} - outClipProjectionAddress = addClipProjectionData_Internal(clipProjectionData); - assert(outClipProjectionAddress != InvalidClipProjectionAddress); +uint32_t DrawResourcesFiller::addDTMSettings_SubmitIfNeeded(const DTMSettingsInfo& dtmSettings, SIntendedSubmitInfo& intendedNextSubmit) +{ + // before calling `addDTMSettings_Internal` we have made sute we have enough mem for + uint32_t outDTMSettingIdx = addDTMSettings_Internal(dtmSettings, intendedNextSubmit); + if (outDTMSettingIdx == InvalidDTMSettingsIdx) + { + // There wasn't enough resource memory remaining to fit dtmsettings struct + 2 linestyles structs. + finalizeAllCopiesToGPU(intendedNextSubmit); + submitDraws(intendedNextSubmit); + reset(); // resets everything! be careful! + + outDTMSettingIdx = addDTMSettings_Internal(dtmSettings, intendedNextSubmit); + assert(outDTMSettingIdx != InvalidDTMSettingsIdx); } - return outClipProjectionAddress; + return outDTMSettingIdx; } -uint64_t DrawResourcesFiller::addClipProjectionData_Internal(const ClipProjectionData& clipProjectionData) +uint32_t DrawResourcesFiller::addClipProjectionData_SubmitIfNeeded(const ClipProjectionData& clipProjectionData, SIntendedSubmitInfo& intendedNextSubmit) { - const uint64_t maxGeometryBufferClipProjData = (maxGeometryBufferSize - currentGeometryBufferSize) / sizeof(ClipProjectionData); - if (maxGeometryBufferClipProjData <= 0) - return InvalidClipProjectionAddress; - - void* dst = reinterpret_cast(cpuDrawBuffers.geometryBuffer->getPointer()) + currentGeometryBufferSize; - memcpy(dst, &clipProjectionData, sizeof(ClipProjectionData)); + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + const size_t memRequired = sizeof(ClipProjectionData); + const bool enoughMem = remainingResourcesSize >= memRequired; // enough remaining memory for 1 more dtm settings with 2 referenced line styles? - const uint64_t ret = currentGeometryBufferSize + geometryBufferAddress; - currentGeometryBufferSize += sizeof(ClipProjectionData); - return ret; + if (!enoughMem) + { + finalizeAllCopiesToGPU(intendedNextSubmit); + submitDraws(intendedNextSubmit); + reset(); // resets everything! be careful! + } + + resourcesCollection.clipProjections.vector.push_back(clipProjectionData); // this will implicitly increase total resource consumption and reduce remaining size --> no need for mem size trackers + return resourcesCollection.clipProjections.vector.size() - 1u; } void DrawResourcesFiller::addPolylineObjects_Internal(const CPolylineBase& polyline, const CPolylineBase::SectionInfo& section, uint32_t& currentObjectInSection, uint32_t mainObjIdx) @@ -738,39 +814,49 @@ void DrawResourcesFiller::addPolylineObjects_Internal(const CPolylineBase& polyl void DrawResourcesFiller::addPolylineConnectors_Internal(const CPolylineBase& polyline, uint32_t& currentPolylineConnectorObj, uint32_t mainObjIdx) { - const uint32_t maxGeometryBufferConnectors = static_cast((maxGeometryBufferSize - currentGeometryBufferSize) / sizeof(PolylineConnector)); - - uint32_t uploadableObjects = (maxIndexCount / 6u) - currentDrawObjectCount; - uploadableObjects = core::min(uploadableObjects, maxGeometryBufferConnectors); - uploadableObjects = core::min(uploadableObjects, maxDrawObjects - currentDrawObjectCount); + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + const uint32_t uploadableObjects = (remainingResourcesSize) / (sizeof(PolylineConnector) + sizeof(DrawObject) + sizeof(uint32_t) * 6u); + // TODO[ERFAN]: later take into account: our maximum indexable vertex + const uint32_t connectorCount = static_cast(polyline.getConnectors().size()); const uint32_t remainingObjects = connectorCount - currentPolylineConnectorObj; - const uint32_t objectsToUpload = core::min(uploadableObjects, remainingObjects); + if (objectsToUpload <= 0u) + return; + + // Add Geometry + const auto connectorsByteSize = sizeof(PolylineConnector) * objectsToUpload; + size_t geometryBufferOffset = resourcesCollection.geometryInfo.increaseSizeAndGetOffset(connectorsByteSize, alignof(PolylineConnector)); + void* dst = resourcesCollection.geometryInfo.data() + geometryBufferOffset; + const PolylineConnector& connector = polyline.getConnectors()[currentPolylineConnectorObj]; + memcpy(dst, &connector, connectorsByteSize); + + // Push Indices, remove later when compute fills this + uint32_t* indexBufferToBeFilled = resourcesCollection.indexBuffer.increaseCountAndGetPtr(6u * objectsToUpload); + const uint32_t startObj = resourcesCollection.drawObjects.getCount(); + for (uint32_t i = 0u; i < objectsToUpload; ++i) + { + indexBufferToBeFilled[i*6] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 1u] = (startObj+i)*4u + 0u; + indexBufferToBeFilled[i*6 + 2u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 3u] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 4u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 5u] = (startObj+i)*4u + 3u; + } + // Add DrawObjs + DrawObject* drawObjectsToBeFilled = resourcesCollection.drawObjects.increaseCountAndGetPtr(objectsToUpload); DrawObject drawObj = {}; drawObj.mainObjIndex = mainObjIdx; drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::POLYLINE_CONNECTOR) | 0 << 16); - drawObj.geometryAddress = geometryBufferAddress + currentGeometryBufferSize; + drawObj.geometryAddress = geometryBufferOffset; for (uint32_t i = 0u; i < objectsToUpload; ++i) { - void* dst = reinterpret_cast(cpuDrawBuffers.drawObjectsBuffer->getPointer()) + currentDrawObjectCount; - memcpy(dst, &drawObj, sizeof(DrawObject)); - currentDrawObjectCount += 1u; + drawObjectsToBeFilled[i] = drawObj; drawObj.geometryAddress += sizeof(PolylineConnector); - } - - // Add Geometry - if (objectsToUpload > 0u) - { - const auto connectorsByteSize = sizeof(PolylineConnector) * objectsToUpload; - void* dst = reinterpret_cast(cpuDrawBuffers.geometryBuffer->getPointer()) + currentGeometryBufferSize; - auto& connector = polyline.getConnectors()[currentPolylineConnectorObj]; - memcpy(dst, &connector, connectorsByteSize); - currentGeometryBufferSize += connectorsByteSize; - } + } currentPolylineConnectorObj += objectsToUpload; } @@ -780,154 +866,203 @@ void DrawResourcesFiller::addLines_Internal(const CPolylineBase& polyline, const assert(section.count >= 1u); assert(section.type == ObjectType::LINE); - const uint32_t maxGeometryBufferPoints = static_cast((maxGeometryBufferSize - currentGeometryBufferSize) / sizeof(LinePointInfo)); - const uint32_t maxGeometryBufferLines = (maxGeometryBufferPoints <= 1u) ? 0u : maxGeometryBufferPoints - 1u; - uint32_t uploadableObjects = (maxIndexCount / 6u) - currentDrawObjectCount; - uploadableObjects = core::min(uploadableObjects, maxGeometryBufferLines); - uploadableObjects = core::min(uploadableObjects, maxDrawObjects - currentDrawObjectCount); + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + if (remainingResourcesSize < sizeof(LinePointInfo)) + return; + + // how many lines fit into mem? --> memConsumption = sizeof(LinePointInfo) + sizeof(LinePointInfo)*lineCount + sizeof(DrawObject)*lineCount + sizeof(uint32_t) * 6u * lineCount + const uint32_t uploadableObjects = (remainingResourcesSize - sizeof(LinePointInfo)) / (sizeof(LinePointInfo) + sizeof(DrawObject) + sizeof(uint32_t) * 6u); + // TODO[ERFAN]: later take into account: our maximum indexable vertex const uint32_t lineCount = section.count; const uint32_t remainingObjects = lineCount - currentObjectInSection; - uint32_t objectsToUpload = core::min(uploadableObjects, remainingObjects); + const uint32_t objectsToUpload = core::min(uploadableObjects, remainingObjects); + + if (objectsToUpload <= 0u) + return; + + // Add Geometry + const auto pointsByteSize = sizeof(LinePointInfo) * (objectsToUpload + 1u); + size_t geometryBufferOffset = resourcesCollection.geometryInfo.increaseSizeAndGetOffset(pointsByteSize, alignof(LinePointInfo)); + void* dst = resourcesCollection.geometryInfo.data() + geometryBufferOffset; + const LinePointInfo& linePoint = polyline.getLinePointAt(section.index + currentObjectInSection); + memcpy(dst, &linePoint, pointsByteSize); + + // Push Indices, remove later when compute fills this + uint32_t* indexBufferToBeFilled = resourcesCollection.indexBuffer.increaseCountAndGetPtr(6u * objectsToUpload); + const uint32_t startObj = resourcesCollection.drawObjects.getCount(); + for (uint32_t i = 0u; i < objectsToUpload; ++i) + { + indexBufferToBeFilled[i*6] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 1u] = (startObj+i)*4u + 0u; + indexBufferToBeFilled[i*6 + 2u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 3u] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 4u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 5u] = (startObj+i)*4u + 3u; + } // Add DrawObjs + DrawObject* drawObjectsToBeFilled = resourcesCollection.drawObjects.increaseCountAndGetPtr(objectsToUpload); DrawObject drawObj = {}; drawObj.mainObjIndex = mainObjIdx; drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::LINE) | 0 << 16); - drawObj.geometryAddress = geometryBufferAddress + currentGeometryBufferSize; + drawObj.geometryAddress = geometryBufferOffset; for (uint32_t i = 0u; i < objectsToUpload; ++i) { - void* dst = reinterpret_cast(cpuDrawBuffers.drawObjectsBuffer->getPointer()) + currentDrawObjectCount; - memcpy(dst, &drawObj, sizeof(DrawObject)); - currentDrawObjectCount += 1u; + drawObjectsToBeFilled[i] = drawObj; drawObj.geometryAddress += sizeof(LinePointInfo); - } - - // Add Geometry - if (objectsToUpload > 0u) - { - const auto pointsByteSize = sizeof(LinePointInfo) * (objectsToUpload + 1u); - void* dst = reinterpret_cast(cpuDrawBuffers.geometryBuffer->getPointer()) + currentGeometryBufferSize; - auto& linePoint = polyline.getLinePointAt(section.index + currentObjectInSection); - memcpy(dst, &linePoint, pointsByteSize); - currentGeometryBufferSize += pointsByteSize; - } + } currentObjectInSection += objectsToUpload; } void DrawResourcesFiller::addQuadBeziers_Internal(const CPolylineBase& polyline, const CPolylineBase::SectionInfo& section, uint32_t& currentObjectInSection, uint32_t mainObjIdx) { - constexpr uint32_t CagesPerQuadBezier = getCageCountPerPolylineObject(ObjectType::QUAD_BEZIER); + constexpr uint32_t CagesPerQuadBezier = 3u; // TODO: Break into 3 beziers in compute shader. + assert(section.type == ObjectType::QUAD_BEZIER); - const uint32_t maxGeometryBufferBeziers = static_cast((maxGeometryBufferSize - currentGeometryBufferSize) / sizeof(QuadraticBezierInfo)); + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + // how many quad bezier objects fit into mem? + // memConsumption = quadBezCount * (sizeof(QuadraticBezierInfo) + 3*(sizeof(DrawObject)+6u*sizeof(uint32_t)) + const uint32_t uploadableObjects = (remainingResourcesSize) / (sizeof(QuadraticBezierInfo) + (sizeof(DrawObject) + 6u * sizeof(uint32_t)) * CagesPerQuadBezier); + // TODO[ERFAN]: later take into account: our maximum indexable vertex - uint32_t uploadableObjects = (maxIndexCount / 6u) - currentDrawObjectCount; - uploadableObjects = core::min(uploadableObjects, maxGeometryBufferBeziers); - uploadableObjects = core::min(uploadableObjects, maxDrawObjects - currentDrawObjectCount); - uploadableObjects /= CagesPerQuadBezier; - const uint32_t beziersCount = section.count; const uint32_t remainingObjects = beziersCount - currentObjectInSection; - uint32_t objectsToUpload = core::min(uploadableObjects, remainingObjects); + const uint32_t objectsToUpload = core::min(uploadableObjects, remainingObjects); + const uint32_t cagesCount = objectsToUpload * CagesPerQuadBezier; + + if (objectsToUpload <= 0u) + return; + + // Add Geometry + const auto beziersByteSize = sizeof(QuadraticBezierInfo) * (objectsToUpload); + size_t geometryBufferOffset = resourcesCollection.geometryInfo.increaseSizeAndGetOffset(beziersByteSize, alignof(QuadraticBezierInfo)); + void* dst = resourcesCollection.geometryInfo.data() + geometryBufferOffset; + const QuadraticBezierInfo& quadBezier = polyline.getQuadBezierInfoAt(section.index + currentObjectInSection); + memcpy(dst, &quadBezier, beziersByteSize); + + + // Push Indices, remove later when compute fills this + uint32_t* indexBufferToBeFilled = resourcesCollection.indexBuffer.increaseCountAndGetPtr(6u*cagesCount); + const uint32_t startObj = resourcesCollection.drawObjects.getCount(); + for (uint32_t i = 0u; i < cagesCount; ++i) + { + indexBufferToBeFilled[i*6] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 1u] = (startObj+i)*4u + 0u; + indexBufferToBeFilled[i*6 + 2u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 3u] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 4u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 5u] = (startObj+i)*4u + 3u; + } + // Add DrawObjs + DrawObject* drawObjectsToBeFilled = resourcesCollection.drawObjects.increaseCountAndGetPtr(cagesCount); DrawObject drawObj = {}; drawObj.mainObjIndex = mainObjIdx; - drawObj.geometryAddress = geometryBufferAddress + currentGeometryBufferSize; + drawObj.geometryAddress = geometryBufferOffset; for (uint32_t i = 0u; i < objectsToUpload; ++i) { for (uint16_t subObject = 0; subObject < CagesPerQuadBezier; subObject++) { drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::QUAD_BEZIER) | (subObject << 16)); - void* dst = reinterpret_cast(cpuDrawBuffers.drawObjectsBuffer->getPointer()) + currentDrawObjectCount; - memcpy(dst, &drawObj, sizeof(DrawObject)); - currentDrawObjectCount += 1u; + drawObjectsToBeFilled[i * CagesPerQuadBezier + subObject] = drawObj; } drawObj.geometryAddress += sizeof(QuadraticBezierInfo); } - // Add Geometry - if (objectsToUpload > 0u) - { - const auto beziersByteSize = sizeof(QuadraticBezierInfo) * (objectsToUpload); - void* dst = reinterpret_cast(cpuDrawBuffers.geometryBuffer->getPointer()) + currentGeometryBufferSize; - auto& quadBezier = polyline.getQuadBezierInfoAt(section.index + currentObjectInSection); - memcpy(dst, &quadBezier, beziersByteSize); - currentGeometryBufferSize += beziersByteSize; - } currentObjectInSection += objectsToUpload; } void DrawResourcesFiller::addHatch_Internal(const Hatch& hatch, uint32_t& currentObjectInSection, uint32_t mainObjIndex) { - const uint32_t maxGeometryBufferHatchBoxes = static_cast((maxGeometryBufferSize - currentGeometryBufferSize) / sizeof(Hatch::CurveHatchBox)); - - uint32_t uploadableObjects = (maxIndexCount / 6u) - currentDrawObjectCount; - uploadableObjects = core::min(uploadableObjects, maxDrawObjects - currentDrawObjectCount); - uploadableObjects = core::min(uploadableObjects, maxGeometryBufferHatchBoxes); + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + const uint32_t uploadableObjects = (remainingResourcesSize) / (sizeof(Hatch::CurveHatchBox) + sizeof(DrawObject) + sizeof(uint32_t) * 6u); + // TODO[ERFAN]: later take into account: our maximum indexable vertex + uint32_t remainingObjects = hatch.getHatchBoxCount() - currentObjectInSection; - uploadableObjects = core::min(uploadableObjects, remainingObjects); - - for (uint32_t i = 0; i < uploadableObjects; i++) - { - const Hatch::CurveHatchBox& hatchBox = hatch.getHatchBox(i + currentObjectInSection); + const uint32_t objectsToUpload = core::min(uploadableObjects, remainingObjects); - uint64_t hatchBoxAddress; - { - static_assert(sizeof(CurveBox) == sizeof(Hatch::CurveHatchBox)); - void* dst = reinterpret_cast(cpuDrawBuffers.geometryBuffer->getPointer()) + currentGeometryBufferSize; - memcpy(dst, &hatchBox, sizeof(CurveBox)); - hatchBoxAddress = geometryBufferAddress + currentGeometryBufferSize; - currentGeometryBufferSize += sizeof(CurveBox); - } + if (objectsToUpload <= 0u) + return; - DrawObject drawObj = {}; - drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::CURVE_BOX) | (0 << 16)); - drawObj.mainObjIndex = mainObjIndex; - drawObj.geometryAddress = hatchBoxAddress; - void* dst = reinterpret_cast(cpuDrawBuffers.drawObjectsBuffer->getPointer()) + currentDrawObjectCount + i; - memcpy(dst, &drawObj, sizeof(DrawObject)); + // Add Geometry + static_assert(sizeof(CurveBox) == sizeof(Hatch::CurveHatchBox)); + const auto curveBoxesByteSize = sizeof(Hatch::CurveHatchBox) * objectsToUpload; + size_t geometryBufferOffset = resourcesCollection.geometryInfo.increaseSizeAndGetOffset(curveBoxesByteSize, alignof(Hatch::CurveHatchBox)); + void* dst = resourcesCollection.geometryInfo.data() + geometryBufferOffset; + const Hatch::CurveHatchBox& hatchBox = hatch.getHatchBox(currentObjectInSection); // WARNING: This is assuming hatch boxes are contigous in memory, TODO: maybe make that more obvious through Hatch interface + memcpy(dst, &hatchBox, curveBoxesByteSize); + + // Push Indices, remove later when compute fills this + uint32_t* indexBufferToBeFilled = resourcesCollection.indexBuffer.increaseCountAndGetPtr(6u * objectsToUpload); + const uint32_t startObj = resourcesCollection.drawObjects.getCount(); + for (uint32_t i = 0u; i < objectsToUpload; ++i) + { + indexBufferToBeFilled[i*6] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 1u] = (startObj+i)*4u + 0u; + indexBufferToBeFilled[i*6 + 2u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 3u] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 4u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 5u] = (startObj+i)*4u + 3u; + } + + // Add DrawObjs + DrawObject* drawObjectsToBeFilled = resourcesCollection.drawObjects.increaseCountAndGetPtr(objectsToUpload); + DrawObject drawObj = {}; + drawObj.mainObjIndex = mainObjIndex; + drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::CURVE_BOX) | (0 << 16)); + drawObj.geometryAddress = geometryBufferOffset; + for (uint32_t i = 0u; i < objectsToUpload; ++i) + { + drawObjectsToBeFilled[i] = drawObj; + drawObj.geometryAddress += sizeof(Hatch::CurveHatchBox); } // Add Indices - currentDrawObjectCount += uploadableObjects; currentObjectInSection += uploadableObjects; } bool DrawResourcesFiller::addFontGlyph_Internal(const GlyphInfo& glyphInfo, uint32_t mainObjIdx) { - const uint32_t maxGeometryBufferFontGlyphs = static_cast((maxGeometryBufferSize - currentGeometryBufferSize) / sizeof(GlyphInfo)); + const size_t remainingResourcesSize = calculateRemainingResourcesSize(); + + const uint32_t uploadableObjects = (remainingResourcesSize) / (sizeof(GlyphInfo) + sizeof(DrawObject) + sizeof(uint32_t) * 6u); + // TODO[ERFAN]: later take into account: our maximum indexable vertex - uint32_t uploadableObjects = (maxIndexCount / 6u) - currentDrawObjectCount; - uploadableObjects = core::min(uploadableObjects, maxDrawObjects - currentDrawObjectCount); - uploadableObjects = core::min(uploadableObjects, maxGeometryBufferFontGlyphs); + if (uploadableObjects <= 0u) + return false; - if (uploadableObjects >= 1u) - { - void* geomDst = reinterpret_cast(cpuDrawBuffers.geometryBuffer->getPointer()) + currentGeometryBufferSize; - memcpy(geomDst, &glyphInfo, sizeof(GlyphInfo)); - uint64_t fontGlyphAddr = geometryBufferAddress + currentGeometryBufferSize; - currentGeometryBufferSize += sizeof(GlyphInfo); + // Add Geometry + size_t geometryBufferOffset = resourcesCollection.geometryInfo.increaseSizeAndGetOffset(sizeof(GlyphInfo), alignof(GlyphInfo)); + void* dst = resourcesCollection.geometryInfo.data() + geometryBufferOffset; + memcpy(dst, &glyphInfo, sizeof(GlyphInfo)); + + // Push Indices, remove later when compute fills this + uint32_t* indexBufferToBeFilled = resourcesCollection.indexBuffer.increaseCountAndGetPtr(6u * 1u); + const uint32_t startObj = resourcesCollection.drawObjects.getCount(); + uint32_t i = 0u; + indexBufferToBeFilled[i*6] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 1u] = (startObj+i)*4u + 0u; + indexBufferToBeFilled[i*6 + 2u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 3u] = (startObj+i)*4u + 1u; + indexBufferToBeFilled[i*6 + 4u] = (startObj+i)*4u + 2u; + indexBufferToBeFilled[i*6 + 5u] = (startObj+i)*4u + 3u; - DrawObject drawObj = {}; - drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::FONT_GLYPH) | (0 << 16)); - drawObj.mainObjIndex = mainObjIdx; - drawObj.geometryAddress = fontGlyphAddr; - void* drawObjDst = reinterpret_cast(cpuDrawBuffers.drawObjectsBuffer->getPointer()) + currentDrawObjectCount; - memcpy(drawObjDst, &drawObj, sizeof(DrawObject)); - currentDrawObjectCount += 1u; + // Add DrawObjs + DrawObject* drawObjectsToBeFilled = resourcesCollection.drawObjects.increaseCountAndGetPtr(1u); + DrawObject drawObj = {}; + drawObj.mainObjIndex = mainObjIdx; + drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::FONT_GLYPH) | (0 << 16)); + drawObj.geometryAddress = geometryBufferOffset; + drawObjectsToBeFilled[0u] = drawObj; - return true; - } - else - { - return false; - } + return true; } void DrawResourcesFiller::setGlyphMSDFTextureFunction(const GetGlyphMSDFTextureFunc& func) @@ -940,7 +1075,7 @@ void DrawResourcesFiller::setHatchFillMSDFTextureFunction(const GetHatchFillPatt getHatchFillPatternMSDF = func; } -uint32_t DrawResourcesFiller::addMSDFTexture(const MSDFInputInfo& msdfInput, core::smart_refctd_ptr&& cpuImage, uint32_t mainObjIdx, SIntendedSubmitInfo& intendedNextSubmit) +uint32_t DrawResourcesFiller::addMSDFTexture(const MSDFInputInfo& msdfInput, core::smart_refctd_ptr&& cpuImage, SIntendedSubmitInfo& intendedNextSubmit) { if (!cpuImage) return InvalidTextureIdx; // TODO: Log @@ -961,11 +1096,9 @@ uint32_t DrawResourcesFiller::addMSDFTexture(const MSDFInputInfo& msdfInput, cor { // Dealloc once submission is finished msdfTextureArrayIndexAllocator->multi_deallocate(1u, &evicted.alloc_idx, nextSemaSignal); - - // If we reset main objects will cause an auto submission bug, where adding an msdf texture while constructing glyphs will have wrong main object references (See how SingleLineTexts add Glyphs with a single mainObject) - // for the same reason we don't reset line styles - // `submitCurrentObjectsAndReset` function handles the above + updating clipProjectionData and making sure the mainObjectIdx references to the correct clipProj data after reseting geometry buffer - submitCurrentDrawObjectsAndReset(intendedNextSubmit, mainObjIdx); + finalizeAllCopiesToGPU(intendedNextSubmit); + submitDraws(intendedNextSubmit); + reset(); // resets everything, things referenced through mainObj and other shit will be pushed again through acquireXXX_SubmitIfNeeded } else { diff --git a/62_CAD/DrawResourcesFiller.h b/62_CAD/DrawResourcesFiller.h index e20514651..196ba6885 100644 --- a/62_CAD/DrawResourcesFiller.h +++ b/62_CAD/DrawResourcesFiller.h @@ -1,5 +1,6 @@ #pragma once #include "Polyline.h" +#include "CTriangleMesh.h" #include "Hatch.h" #include "IndexAllocator.h" #include @@ -13,21 +14,10 @@ using namespace nbl::asset; using namespace nbl::ext::TextRendering; static_assert(sizeof(DrawObject) == 16u); -static_assert(sizeof(MainObject) == 16u); -static_assert(sizeof(Globals) == 128u); +static_assert(sizeof(MainObject) == 12u); static_assert(sizeof(LineStyle) == 88u); static_assert(sizeof(ClipProjectionData) == 88u); -template -struct DrawBuffers -{ - smart_refctd_ptr indexBuffer; // only is valid for IGPUBuffer because it's filled at allocation time and never touched again - smart_refctd_ptr mainObjectsBuffer; - smart_refctd_ptr drawObjectsBuffer; - smart_refctd_ptr geometryBuffer; - smart_refctd_ptr lineStylesBuffer; -}; - // ! DrawResourcesFiller // ! This class provides important functionality to manage resources needed for a draw. // ! Drawing new objects (polylines, hatches, etc.) should go through this function. @@ -37,26 +27,113 @@ struct DrawBuffers struct DrawResourcesFiller { public: + + // We pack multiple data types in a single buffer, we need to makes sure each offset starts aligned to avoid mis-aligned accesses + static constexpr size_t ResourcesMaxNaturalAlignment = 8u; - typedef uint32_t index_buffer_type; + /// @brief general parent struct for 1.ReservedCompute and 2.CPUGenerated Resources + struct ResourceBase + { + static constexpr size_t InvalidBufferOffset = ~0u; + size_t bufferOffset = InvalidBufferOffset; // set when copy to gpu buffer is issued + virtual size_t getCount() const = 0; + virtual size_t getStorageSize() const = 0; + virtual size_t getAlignedStorageSize() const { return core::alignUp(getStorageSize(), ResourcesMaxNaturalAlignment); } + }; - DrawResourcesFiller(); + /// @brief ResourceBase reserved for compute shader stages input/output + template + struct ReservedComputeResource : ResourceBase + { + size_t count = 0ull; + size_t getCount() const override { return count; } + size_t getStorageSize() const override { return count * sizeof(T); } + }; - DrawResourcesFiller(smart_refctd_ptr&& utils, IQueue* copyQueue); + /// @brief ResourceBase which is filled by CPU, packed and sent to GPU + template + struct CPUGeneratedResource : ResourceBase + { + core::vector vector; + size_t getCount() const { return vector.size(); } + size_t getStorageSize() const { return vector.size() * sizeof(T); } + + /// @return pointer to start of the data to be filled, up to additionalCount + T* increaseCountAndGetPtr(size_t additionalCount) + { + size_t offset = vector.size(); + vector.resize(offset + additionalCount); + return &vector[offset]; + } - typedef std::function SubmitFunc; - void setSubmitDrawsFunction(const SubmitFunc& func); + /// @brief increases size of general-purpose resources that hold bytes + /// @param alignment: Alignment of the pointer returned to be filled, should be PoT and <= ResourcesMaxNaturalAlignment, only use this if storing raw bytes in vector + /// @return pointer to start of the data to be filled, up to additional size + size_t increaseSizeAndGetOffset(size_t additionalSize, size_t alignment) + { + assert(core::isPoT(alignment) && alignment <= ResourcesMaxNaturalAlignment); + size_t offset = core::alignUp(vector.size(), alignment); + vector.resize(offset + additionalSize); + return offset; + } + + uint32_t addAndGetOffset(const T& val) + { + vector.push_back(val); + return vector.size() - 1u; + } + + T* data() { return vector.data(); } + }; - void allocateIndexBuffer(ILogicalDevice* logicalDevice, uint32_t indices); + /// @brief struct to hold all resources + struct ResourcesCollection + { + // auto-submission level 0 resources (settings that mainObj references) + CPUGeneratedResource lineStyles; + CPUGeneratedResource dtmSettings; + CPUGeneratedResource clipProjections; + + // auto-submission level 1 buffers (mainObj that drawObjs references, if all drawObjs+idxBuffer+geometryInfo doesn't fit into mem this will be broken down into many) + CPUGeneratedResource mainObjects; - void allocateMainObjectsBuffer(ILogicalDevice* logicalDevice, uint32_t mainObjects); + // auto-submission level 2 buffers + CPUGeneratedResource drawObjects; + CPUGeneratedResource indexBuffer; // TODO: this is going to change to ReservedComputeResource where index buffer gets filled by compute shaders + CPUGeneratedResource geometryInfo; // general purpose byte buffer for custom data for geometries (eg. line points, bezier definitions, aabbs) - void allocateDrawObjectsBuffer(ILogicalDevice* logicalDevice, uint32_t drawObjects); + // Get Total memory consumption, If all ResourcesCollection get packed together with ResourcesMaxNaturalAlignment + // used to decide the remaining memory and when to overflow + size_t calculateTotalConsumption() const + { + return + lineStyles.getAlignedStorageSize() + + dtmSettings.getAlignedStorageSize() + + clipProjections.getAlignedStorageSize() + + mainObjects.getAlignedStorageSize() + + drawObjects.getAlignedStorageSize() + + indexBuffer.getAlignedStorageSize() + + geometryInfo.getAlignedStorageSize(); + } + }; + + DrawResourcesFiller(); - void allocateGeometryBuffer(ILogicalDevice* logicalDevice, size_t size); + DrawResourcesFiller(smart_refctd_ptr&& utils, IQueue* copyQueue); - void allocateStylesBuffer(ILogicalDevice* logicalDevice, uint32_t lineStylesCount); + typedef std::function SubmitFunc; + void setSubmitDrawsFunction(const SubmitFunc& func); + /// @brief Get minimum required size for resources buffer (containing objects and geometry info and their settings) + static constexpr size_t getMinimumRequiredResourcesBufferSize() + { + // for auto-submission to work correctly, memory needs to serve at least 2 linestyle, 1 dtm settings, 1 clip proj, 1 main obj, 1 draw obj and 512 bytes of additional mem for geometries and index buffer + // this is the ABSOLUTE MINIMUM (if this value is used rendering will probably be as slow as CPU drawing :D) + return core::alignUp(sizeof(LineStyle) * 2u + sizeof(DTMSettings) + sizeof(ClipProjectionData) + sizeof(MainObject) + sizeof(DrawObject) + 512ull, ResourcesMaxNaturalAlignment); + } + + void allocateResourcesBuffer(ILogicalDevice* logicalDevice, size_t size); + void allocateMSDFTextures(ILogicalDevice* logicalDevice, uint32_t maxMSDFs, uint32_t2 msdfsExtent); // functions that user should set to get MSDF texture if it's not available in cache. @@ -74,8 +151,15 @@ struct DrawResourcesFiller //! this function fills buffers required for drawing a polyline and submits a draw through provided callback when there is not enough memory. void drawPolyline(const CPolylineBase& polyline, const LineStyleInfo& lineStyleInfo, SIntendedSubmitInfo& intendedNextSubmit); - void drawPolyline(const CPolylineBase& polyline, uint32_t polylineMainObjIdx, SIntendedSubmitInfo& intendedNextSubmit); + /// Use this in a begin/endMainObject scope when you want to draw different polylines that should essentially be a single main object (no self-blending between components of a single main object) + /// WARNING: make sure this function is called within begin/endMainObject scope + void drawPolyline(const CPolylineBase& polyline, SIntendedSubmitInfo& intendedNextSubmit); + void drawTriangleMesh( + const CTriangleMesh& mesh, + const DTMSettingsInfo& dtmSettingsInfo, + SIntendedSubmitInfo& intendedNextSubmit); + // ! Convinience function for Hatch with MSDF Pattern and a solid background void drawHatch( const Hatch& hatch, @@ -96,8 +180,9 @@ struct DrawResourcesFiller const Hatch& hatch, const float32_t4& color, SIntendedSubmitInfo& intendedNextSubmit); - - // ! Draw Font Glyph, will auto submit if there is no space + + /// Used by SingleLineText, Issue drawing a font glyph + /// WARNING: make sure this function is called within begin/endMainObject scope void drawFontGlyph( nbl::ext::TextRendering::FontFace* fontFace, uint32_t glyphIdx, @@ -105,113 +190,51 @@ struct DrawResourcesFiller float32_t2 dirU, float32_t aspectRatio, float32_t2 minUV, - uint32_t mainObjIdx, SIntendedSubmitInfo& intendedNextSubmit); void _test_addImageObject( float64_t2 topLeftPos, float32_t2 size, float32_t rotation, - SIntendedSubmitInfo& intendedNextSubmit) - { - auto addImageObject_Internal = [&](const ImageObjectInfo& imageObjectInfo, uint32_t mainObjIdx) -> bool - { - const uint32_t maxGeometryBufferImageObjects = static_cast((maxGeometryBufferSize - currentGeometryBufferSize) / sizeof(ImageObjectInfo)); - uint32_t uploadableObjects = (maxIndexCount / 6u) - currentDrawObjectCount; - uploadableObjects = core::min(uploadableObjects, maxDrawObjects - currentDrawObjectCount); - uploadableObjects = core::min(uploadableObjects, maxGeometryBufferImageObjects); - - if (uploadableObjects >= 1u) - { - void* dstGeom = reinterpret_cast(cpuDrawBuffers.geometryBuffer->getPointer()) + currentGeometryBufferSize; - memcpy(dstGeom, &imageObjectInfo, sizeof(ImageObjectInfo)); - uint64_t geomBufferAddr = geometryBufferAddress + currentGeometryBufferSize; - currentGeometryBufferSize += sizeof(ImageObjectInfo); - - DrawObject drawObj = {}; - drawObj.type_subsectionIdx = uint32_t(static_cast(ObjectType::IMAGE) | (0 << 16)); // TODO: use custom pack/unpack function - drawObj.mainObjIndex = mainObjIdx; - drawObj.geometryAddress = geomBufferAddr; - void* dstDrawObj = reinterpret_cast(cpuDrawBuffers.drawObjectsBuffer->getPointer()) + currentDrawObjectCount; - memcpy(dstDrawObj, &drawObj, sizeof(DrawObject)); - currentDrawObjectCount += 1u; - - return true; - } - else - return false; - }; - - uint32_t mainObjIdx = addMainObject_SubmitIfNeeded(InvalidStyleIdx, intendedNextSubmit); - - ImageObjectInfo info = {}; - info.topLeft = topLeftPos; - info.dirU = float32_t2(size.x * cos(rotation), size.x * sin(rotation)); // - info.aspectRatio = size.y / size.x; - info.textureID = 0u; - if (!addImageObject_Internal(info, mainObjIdx)) - { - // single image object couldn't fit into memory to push to gpu, so we submit rendering current objects and reset geometry buffer and draw objects - submitCurrentDrawObjectsAndReset(intendedNextSubmit, mainObjIdx); - bool success = addImageObject_Internal(info, mainObjIdx); - assert(success); // this should always be true, otherwise it's either bug in code or not enough memory allocated to hold a single image object - } - } + SIntendedSubmitInfo& intendedNextSubmit); + /// @brief call this function before submitting to ensure all resources are copied + /// records copy command into intendedNextSubmit's active command buffer and might possibly submits if fails allocation on staging upload memory. bool finalizeAllCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit); - inline uint32_t getLineStyleCount() const { return currentLineStylesCount; } - - inline uint32_t getDrawObjectCount() const { return currentDrawObjectCount; } - - inline uint32_t getMainObjectCount() const { return currentMainObjectCount; } - - inline size_t getCurrentMainObjectsBufferSize() const + /// @brief resets resources buffers + void reset() { - return sizeof(MainObject) * currentMainObjectCount; + resetDrawObjects(); + resetMainObjects(); + resetCustomClipProjections(); + resetLineStyles(); + resetDTMSettings(); + + drawObjectsFlushedToDrawCalls = 0ull; + drawCalls.clear(); } - inline size_t getCurrentDrawObjectsBufferSize() const - { - return sizeof(DrawObject) * currentDrawObjectCount; - } + /// @brief collection of all the resources that will eventually be reserved or copied to in the resourcesGPUBuffer, will be accessed via individual BDA pointers in shaders + const ResourcesCollection& getResourcesCollection() const { return resourcesCollection; } - inline size_t getCurrentGeometryBufferSize() const - { - return currentGeometryBufferSize; - } + /// @brief buffer containing all non-texture type resources + nbl::core::smart_refctd_ptr getResourcesGPUBuffer() const { return resourcesGPUBuffer; } - inline size_t getCurrentLineStylesBufferSize() const - { - return sizeof(LineStyle) * currentLineStylesCount; - } + /// @return how far resourcesGPUBuffer was copied to by `finalizeAllCopiesToGPU` in `resourcesCollection` + const size_t getCopiedResourcesSize() { return copiedResourcesSize; } - void reset() - { - resetGeometryCounters(); - resetMainObjectCounters(); - resetLineStyleCounters(); - } - - DrawBuffers cpuDrawBuffers; - DrawBuffers gpuDrawBuffers; + // Setting Active Resources: + void setActiveLineStyle(const LineStyleInfo& lineStyle); + void setActiveDTMSettings(const DTMSettingsInfo& dtmSettingsInfo); - uint32_t addLineStyle_SubmitIfNeeded(const LineStyleInfo& lineStyle, SIntendedSubmitInfo& intendedNextSubmit); - - // TODO[Przemek]: Read after reading the fragment shader comments and having a basic understanding of the relationship between "mainObject" and our programmable blending resolve: - // Use `addMainObject_SubmitIfNeeded` to push your single mainObject you'll be using for the enitre triangle mesh (this will ensure overlaps between triangles of the same mesh is resolved correctly) - // Delete comment when you understand this + void beginMainObject(MainObjectType type); + void endMainObject(); - // [ADVANCED] Do not use this function unless you know what you're doing (It may cause auto submit) - // Never call this function multiple times in a row before indexing it in a drawable, because future auto-submits may invalidate mainObjects, so do them one by one, for example: - // Valid: addMainObject1 --> addXXX(mainObj1) ---> addMainObject2 ---> addXXX(mainObj2) .... - // Invalid: addMainObject1 ---> addMainObject2 ---> addXXX(mainObj1) ---> addXXX(mainObj2) .... - uint32_t addMainObject_SubmitIfNeeded(uint32_t styleIdx, SIntendedSubmitInfo& intendedNextSubmit); - - // we need to store the clip projection stack to make sure the front is always available in memory void pushClipProjectionData(const ClipProjectionData& clipProjectionData); void popClipProjectionData(); - const std::deque& getClipProjectionStack() const { return clipProjections; } + + const std::deque& getClipProjectionStack() const { return activeClipProjections; } smart_refctd_ptr getMSDFsTextureArray() { return msdfTextureArray; } @@ -223,6 +246,48 @@ struct DrawResourcesFiller return msdfTextureArray->getCreationParameters().image->getCreationParameters().mipLevels; } + /// For advanced use only, (passed to shaders for them to know if we overflow-submitted in the middle if a main obj + uint32_t getActiveMainObjectIndex() const { return activeMainObjectIndex; } + + // TODO: Remove these later, these are for multiple draw calls instead of a single one. + struct DrawCallData + { + union + { + struct Dtm + { + uint64_t indexBufferOffset; + uint64_t indexCount; + uint64_t triangleMeshVerticesBaseAddress; + uint32_t triangleMeshMainObjectIndex; + } dtm; + struct DrawObj + { + uint64_t drawObjectStart = 0ull; + uint64_t drawObjectCount = 0ull; + } drawObj; + }; + bool isDTMRendering; + }; + + uint64_t drawObjectsFlushedToDrawCalls = 0ull; + + void flushDrawObjects() + { + if (resourcesCollection.drawObjects.getCount() > drawObjectsFlushedToDrawCalls) + { + DrawCallData drawCall = {}; + drawCall.isDTMRendering = false; + drawCall.drawObj.drawObjectStart = drawObjectsFlushedToDrawCalls; + drawCall.drawObj.drawObjectCount = resourcesCollection.drawObjects.getCount() - drawObjectsFlushedToDrawCalls; + drawCalls.push_back(drawCall); + drawObjectsFlushedToDrawCalls = resourcesCollection.drawObjects.getCount(); + } + } + + std::vector drawCalls; // either dtms or objects + + protected: struct MSDFTextureCopy @@ -233,88 +298,99 @@ struct DrawResourcesFiller SubmitFunc submitDraws; - bool finalizeMainObjectCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit); - - bool finalizeGeometryCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit); + bool finalizeBufferCopies(SIntendedSubmitInfo& intendedNextSubmit); - bool finalizeLineStyleCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit); - - bool finalizeCustomClipProjectionCopiesToGPU(SIntendedSubmitInfo& intendedNextSubmit); - bool finalizeTextureCopies(SIntendedSubmitInfo& intendedNextSubmit); - // Internal Function to call whenever we overflow while filling our buffers with geometry (potential limiters: indexBuffer, drawObjectsBuffer or geometryBuffer) - // ! mainObjIdx: is the mainObject the "overflowed" drawObjects belong to. - // mainObjIdx is required to ensure that valid data, especially the `clipProjectionData`, remains linked to the main object. - // This is important because, while other data may change during overflow handling, the main object must persist to maintain consistency throughout rendering all parts of it. (for example all lines and beziers of a single polyline) - // [ADVANCED] If you have not created your mainObject yet, pass `InvalidMainObjectIdx` (See drawHatch) - void submitCurrentDrawObjectsAndReset(SIntendedSubmitInfo& intendedNextSubmit, uint32_t mainObjectIndex); + const size_t calculateRemainingResourcesSize() const; - uint32_t addMainObject_Internal(const MainObject& mainObject); + /// @brief Internal Function to call whenever we overflow when we can't fill all of mainObject's drawObjects + /// @param intendedNextSubmit + /// @param mainObjectIndex: function updates mainObjectIndex after submitting, clearing everything and acquiring mainObjectIndex again. + void submitCurrentDrawObjectsAndReset(SIntendedSubmitInfo& intendedNextSubmit, uint32_t& mainObjectIndex); - uint32_t addLineStyle_Internal(const LineStyleInfo& lineStyleInfo); - - // Gets the current clip projection data (the top of stack) gpu addreess inside the geometryBuffer - // If it's been invalidated then it will request to upload again with a possible auto-submit on low geometry buffer memory. - uint64_t acquireCurrentClipProjectionAddress(SIntendedSubmitInfo& intendedNextSubmit); + // Gets resource index to the active linestyle data from the top of stack + // If it's been invalidated then it will request to add to resources again ( auto-submission happens If there is not enough memory to add again) + uint32_t acquireActiveLineStyleIndex_SubmitIfNeeded(SIntendedSubmitInfo& intendedNextSubmit); - uint64_t addClipProjectionData_SubmitIfNeeded(const ClipProjectionData& clipProjectionData, SIntendedSubmitInfo& intendedNextSubmit); - - uint64_t addClipProjectionData_Internal(const ClipProjectionData& clipProjectionData); + // Gets resource index to the active linestyle data from the top of stack + // If it's been invalidated then it will request to add to resources again ( auto-submission happens If there is not enough memory to add again) + uint32_t acquireActiveDTMSettingsIndex_SubmitIfNeeded(SIntendedSubmitInfo& intendedNextSubmit); - static constexpr uint32_t getCageCountPerPolylineObject(ObjectType type) - { - if (type == ObjectType::LINE) - return 1u; - else if (type == ObjectType::QUAD_BEZIER) - return 3u; - return 0u; - }; + // Gets resource index to the active clip projection data from the top of stack + // If it's been invalidated then it will request to add to resources again ( auto-submission happens If there is not enough memory to add again) + uint32_t acquireActiveClipProjectionIndex_SubmitIfNeeded(SIntendedSubmitInfo& intendedNextSubmit); + + // Gets resource index to the active main object data + // If it's been invalidated then it will request to add to resources again ( auto-submission happens If there is not enough memory to add again) + uint32_t acquireActiveMainObjectIndex_SubmitIfNeeded(SIntendedSubmitInfo& intendedNextSubmit); + /// Attempts to add lineStyle to resources. If it fails to do, due to resource limitations, auto-submits and tries again. + uint32_t addLineStyle_SubmitIfNeeded(const LineStyleInfo& lineStyle, SIntendedSubmitInfo& intendedNextSubmit); + + /// Attempts to add dtmSettings to resources. If it fails to do, due to resource limitations, auto-submits and tries again. + uint32_t addDTMSettings_SubmitIfNeeded(const DTMSettingsInfo& dtmSettings, SIntendedSubmitInfo& intendedNextSubmit); + + /// Attempts to add clipProjection to resources. If it fails to do, due to resource limitations, auto-submits and tries again. + uint32_t addClipProjectionData_SubmitIfNeeded(const ClipProjectionData& clipProjectionData, SIntendedSubmitInfo& intendedNextSubmit); + + /// returns index to added LineStyleInfo, returns Invalid index if it exceeds resource limitations + uint32_t addLineStyle_Internal(const LineStyleInfo& lineStyleInfo); + + /// returns index to added DTMSettingsInfo, returns Invalid index if it exceeds resource limitations + uint32_t addDTMSettings_Internal(const DTMSettingsInfo& dtmSettings, SIntendedSubmitInfo& intendedNextSubmit); + + /// Attempts to upload as many draw objects as possible within the given polyline section considering resource limitations void addPolylineObjects_Internal(const CPolylineBase& polyline, const CPolylineBase::SectionInfo& section, uint32_t& currentObjectInSection, uint32_t mainObjIdx); - + + /// Attempts to upload as many draw objects as possible within the given polyline connectors considering resource limitations void addPolylineConnectors_Internal(const CPolylineBase& polyline, uint32_t& currentPolylineConnectorObj, uint32_t mainObjIdx); - + + /// Attempts to upload as many draw objects as possible within the given polyline section considering resource limitations void addLines_Internal(const CPolylineBase& polyline, const CPolylineBase::SectionInfo& section, uint32_t& currentObjectInSection, uint32_t mainObjIdx); - + + /// Attempts to upload as many draw objects as possible within the given polyline section considering resource limitations void addQuadBeziers_Internal(const CPolylineBase& polyline, const CPolylineBase::SectionInfo& section, uint32_t& currentObjectInSection, uint32_t mainObjIdx); - + + /// Attempts to upload as many draw objects as possible within the given hatch considering resource limitations void addHatch_Internal(const Hatch& hatch, uint32_t& currentObjectInSection, uint32_t mainObjIndex); + /// Attempts to upload a single GlyphInfo considering resource limitations bool addFontGlyph_Internal(const GlyphInfo& glyphInfo, uint32_t mainObjIdx); - void resetMainObjectCounters() + void resetMainObjects() { - inMemMainObjectCount = 0u; - currentMainObjectCount = 0u; + resourcesCollection.mainObjects.vector.clear(); + activeMainObjectIndex = InvalidMainObjectIdx; } - // WARN: If you plan to use this, make sure you either reset the mainObjectCounters as well - // Or if you want to keep your mainObject around, make sure you're using the `submitCurrentObjectsAndReset` function instead of calling this directly - // So that it makes your mainObject point to the correct clipProjectionData (which exists in the geometry buffer) - void resetGeometryCounters() + // these resources are data related to chunks of a whole mainObject + void resetDrawObjects() { - inMemDrawObjectCount = 0u; - currentDrawObjectCount = 0u; - - inMemGeometryBufferSize = 0u; - currentGeometryBufferSize = 0u; + resourcesCollection.drawObjects.vector.clear(); + resourcesCollection.indexBuffer.vector.clear(); + resourcesCollection.geometryInfo.vector.clear(); + } - // Invalidate all the clip projection addresses because geometry buffer got reset - for (auto& clipProjAddr : clipProjectionAddresses) - clipProjAddr = InvalidClipProjectionAddress; + void resetCustomClipProjections() + { + resourcesCollection.clipProjections.vector.clear(); + + // Invalidate all the clip projection addresses because activeClipProjections buffer got reset + for (auto& clipProjAddr : activeClipProjectionIndices) + clipProjAddr = InvalidClipProjectionIndex; } - void resetLineStyleCounters() + void resetLineStyles() { - currentLineStylesCount = 0u; - inMemLineStylesCount = 0u; + resourcesCollection.lineStyles.vector.clear(); + activeLineStyleIndex = InvalidStyleIdx; } - MainObject* getMainObject(uint32_t idx) + void resetDTMSettings() { - MainObject* mainObjsArray = reinterpret_cast(cpuDrawBuffers.mainObjectsBuffer->getPointer()); - return &mainObjsArray[idx]; + resourcesCollection.dtmSettings.vector.clear(); + activeDTMSettingsIndex = InvalidDTMSettingsIdx; } // MSDF Hashing and Caching Internal Functions @@ -405,34 +481,30 @@ struct DrawResourcesFiller // ! mainObjIdx: make sure to pass your mainObjIdx to it if you want it to stay synced/updated if some overflow submit occured which would potentially erase what your mainObject points at. // If you haven't created a mainObject yet, then pass InvalidMainObjectIdx - uint32_t addMSDFTexture(const MSDFInputInfo& msdfInput, core::smart_refctd_ptr&& cpuImage, uint32_t mainObjIdx, SIntendedSubmitInfo& intendedNextSubmit); + uint32_t addMSDFTexture(const MSDFInputInfo& msdfInput, core::smart_refctd_ptr&& cpuImage, SIntendedSubmitInfo& intendedNextSubmit); + // ResourcesCollection and packed into GPUBuffer + ResourcesCollection resourcesCollection; + nbl::core::smart_refctd_ptr resourcesGPUBuffer; + size_t copiedResourcesSize; + // Members smart_refctd_ptr m_utilities; IQueue* m_copyQueue; - uint32_t maxIndexCount; - - uint32_t inMemMainObjectCount = 0u; - uint32_t currentMainObjectCount = 0u; - uint32_t maxMainObjects = 0u; - - uint32_t inMemDrawObjectCount = 0u; - uint32_t currentDrawObjectCount = 0u; - uint32_t maxDrawObjects = 0u; - - uint64_t inMemGeometryBufferSize = 0u; - uint64_t currentGeometryBufferSize = 0u; - uint64_t maxGeometryBufferSize = 0u; + // Active Resources we need to keep track of and push to resources buffer if needed. + LineStyleInfo activeLineStyle; + uint32_t activeLineStyleIndex = InvalidStyleIdx; - uint32_t inMemLineStylesCount = 0u; - uint32_t currentLineStylesCount = 0u; - uint32_t maxLineStyles = 0u; + DTMSettingsInfo activeDTMSettings; + uint32_t activeDTMSettingsIndex = InvalidDTMSettingsIdx; - uint64_t geometryBufferAddress = 0u; // Actual BDA offset 0 of the gpu buffer + MainObjectType activeMainObjectType; + uint32_t activeMainObjectIndex = InvalidMainObjectIdx; - std::deque clipProjections; // stack of clip projectios stored so we can resubmit them if geometry buffer got reset. - std::deque clipProjectionAddresses; // stack of clip projection gpu addresses in geometry buffer. to keep track of them in push/pops + // The ClipProjections are stack, because user can push/pop ClipProjections in any order + std::deque activeClipProjections; // stack of clip projections stored so we can resubmit them if geometry buffer got reset. + std::deque activeClipProjectionIndices; // stack of clip projection gpu addresses in geometry buffer. to keep track of them in push/pops // MSDF GetGlyphMSDFTextureFunc getGlyphMSDF; diff --git a/62_CAD/Polyline.h b/62_CAD/Polyline.h index 03b2f2c30..bee5650c7 100644 --- a/62_CAD/Polyline.h +++ b/62_CAD/Polyline.h @@ -66,8 +66,6 @@ struct LineStyleInfo rigidSegmentIdx = InvalidRigidSegmentIndex; phaseShift = 0.0f; - assert(stipplePatternUnnormalizedRepresentation.size() <= StipplePatternMaxSize); - if (stipplePatternUnnormalizedRepresentation.size() == 0) { stipplePatternSize = 0; @@ -110,6 +108,8 @@ struct LineStyleInfo stipplePatternTransformed[0] += stipplePatternTransformed[stipplePatternTransformed.size() - 1]; stipplePatternTransformed.pop_back(); } + + assert(stipplePatternTransformed.size() <= StipplePatternMaxSize); if (stipplePatternTransformed.size() != 1) { diff --git a/62_CAD/SingleLineText.cpp b/62_CAD/SingleLineText.cpp index 4b41cb628..ea755a2df 100644 --- a/62_CAD/SingleLineText.cpp +++ b/62_CAD/SingleLineText.cpp @@ -63,8 +63,8 @@ void SingleLineText::Draw( lineStyle.color = color; lineStyle.screenSpaceLineWidth = tan(tiltTiltAngle); lineStyle.worldSpaceLineWidth = boldInPixels; - const uint32_t styleIdx = drawResourcesFiller.addLineStyle_SubmitIfNeeded(lineStyle, intendedNextSubmit); - auto glyphObjectIdx = drawResourcesFiller.addMainObject_SubmitIfNeeded(styleIdx, intendedNextSubmit); + drawResourcesFiller.setActiveLineStyle(lineStyle); + drawResourcesFiller.beginMainObject(MainObjectType::TEXT); for (const auto& glyphBox : m_glyphBoxes) { @@ -75,7 +75,8 @@ void SingleLineText::Draw( // float32_t3 xx = float64_t3(0.0, -glyphBox.size.y, 0.0); const float32_t aspectRatio = static_cast(glm::length(dirV) / glm::length(dirU)); // check if you can just do: (glyphBox.size.y * scale.y) / glyphBox.size.x * scale.x) const float32_t2 minUV = face->getUV(float32_t2(0.0f,0.0f), glyphBox.size, drawResourcesFiller.getMSDFResolution(), MSDFPixelRange); - drawResourcesFiller.drawFontGlyph(face, glyphBox.glyphIdx, topLeft, dirU, aspectRatio, minUV, glyphObjectIdx, intendedNextSubmit); + drawResourcesFiller.drawFontGlyph(face, glyphBox.glyphIdx, topLeft, dirU, aspectRatio, minUV, intendedNextSubmit); } + drawResourcesFiller.endMainObject(); } \ No newline at end of file diff --git a/62_CAD/main.cpp b/62_CAD/main.cpp index 637c88eda..6d3a2b431 100644 --- a/62_CAD/main.cpp +++ b/62_CAD/main.cpp @@ -57,6 +57,7 @@ enum class ExampleMode CASE_6, // Custom Clip Projections CASE_7, // Images CASE_8, // MSDF and Text + CASE_9, // DTM CASE_COUNT }; @@ -71,9 +72,10 @@ constexpr std::array cameraExtents = 10.0, // CASE_6 10.0, // CASE_7 600.0, // CASE_8 + 600.0 // CASE_9 }; -constexpr ExampleMode mode = ExampleMode::CASE_4; +constexpr ExampleMode mode = ExampleMode::CASE_9; class Camera2D { @@ -286,18 +288,8 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu { drawResourcesFiller = DrawResourcesFiller(core::smart_refctd_ptr(m_utils), getGraphicsQueue()); - // TODO: move individual allocations to DrawResourcesFiller::allocateResources(memory) - // Issue warning error, if we can't store our largest geomm struct + clip proj data inside geometry buffer along linestyle and mainObject - uint32_t maxIndices = maxObjects * 6u * 2u; - drawResourcesFiller.allocateIndexBuffer(m_device.get(), maxIndices); - drawResourcesFiller.allocateMainObjectsBuffer(m_device.get(), maxObjects); - drawResourcesFiller.allocateDrawObjectsBuffer(m_device.get(), maxObjects * 5u); - drawResourcesFiller.allocateStylesBuffer(m_device.get(), 512u); - - // * 3 because I just assume there is on average 3x beziers per actual object (cause we approximate other curves/arcs with beziers now) - // + 128 ClipProjData - size_t geometryBufferSize = maxObjects * sizeof(QuadraticBezierInfo) * 3 + 128 * sizeof(ClipProjectionData); - drawResourcesFiller.allocateGeometryBuffer(m_device.get(), geometryBufferSize); + size_t bufferSize = 512u * 1024u * 1024u; // 512 MB + drawResourcesFiller.allocateResourcesBuffer(m_device.get(), bufferSize); drawResourcesFiller.allocateMSDFTextures(m_device.get(), 256u, uint32_t2(MSDFSize, MSDFSize)); { @@ -311,14 +303,6 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu auto globalsBufferMem = m_device->allocate(memReq, m_globalsBuffer.get()); } - size_t sumBufferSizes = - drawResourcesFiller.gpuDrawBuffers.drawObjectsBuffer->getSize() + - drawResourcesFiller.gpuDrawBuffers.geometryBuffer->getSize() + - drawResourcesFiller.gpuDrawBuffers.indexBuffer->getSize() + - drawResourcesFiller.gpuDrawBuffers.lineStylesBuffer->getSize() + - drawResourcesFiller.gpuDrawBuffers.mainObjectsBuffer->getSize(); - m_logger->log("Buffers Size = %.2fKB", ILogger::E_LOG_LEVEL::ELL_INFO, sumBufferSizes / 1024.0f); - // pseudoStencil { asset::E_FORMAT pseudoStencilFormat = asset::EF_R32_UINT; @@ -641,6 +625,7 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu double m_timeElapsed = 0.0; std::chrono::steady_clock::time_point lastTime; uint32_t m_hatchDebugStep = 0u; + E_HEIGHT_SHADING_MODE m_shadingModeExample = E_HEIGHT_SHADING_MODE::DISCRETE_VARIABLE_LENGTH_INTERVALS; inline bool onAppInitialized(smart_refctd_ptr&& system) override { @@ -689,41 +674,20 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu }, { .binding = 1u, - .type = asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER, - .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_VERTEX | asset::IShader::E_SHADER_STAGE::ESS_FRAGMENT, - .count = 1u, - }, - { - .binding = 2u, - .type = asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER, - .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_VERTEX | asset::IShader::E_SHADER_STAGE::ESS_FRAGMENT, - .count = 1u, - }, - { - .binding = 3u, - .type = asset::IDescriptor::E_TYPE::ET_STORAGE_BUFFER, - .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, - .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_VERTEX | asset::IShader::E_SHADER_STAGE::ESS_FRAGMENT, - .count = 1u, - }, - { - .binding = 4u, .type = asset::IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_FRAGMENT, .count = 1u, }, { - .binding = 5u, + .binding = 2u, .type = asset::IDescriptor::E_TYPE::ET_SAMPLER, .createFlags = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS::ECF_NONE, .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_FRAGMENT, .count = 1u, }, { - .binding = 6u, + .binding = 3u, .type = asset::IDescriptor::E_TYPE::ET_SAMPLED_IMAGE, .createFlags = bindlessTextureFlags, .stageFlags = asset::IShader::E_SHADER_STAGE::ESS_FRAGMENT, @@ -767,7 +731,7 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu { descriptorSet0 = descriptorPool->createDescriptorSet(smart_refctd_ptr(descriptorSetLayout0)); descriptorSet1 = descriptorPool->createDescriptorSet(smart_refctd_ptr(descriptorSetLayout1)); - constexpr uint32_t DescriptorCountSet0 = 6u; + constexpr uint32_t DescriptorCountSet0 = 3u; video::IGPUDescriptorSet::SDescriptorInfo descriptorInfosSet0[DescriptorCountSet0] = {}; // Descriptors For Set 0: @@ -775,27 +739,15 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu descriptorInfosSet0[0u].info.buffer.size = m_globalsBuffer->getCreationParams().size; descriptorInfosSet0[0u].desc = m_globalsBuffer; - descriptorInfosSet0[1u].info.buffer.offset = 0u; - descriptorInfosSet0[1u].info.buffer.size = drawResourcesFiller.gpuDrawBuffers.drawObjectsBuffer->getCreationParams().size; - descriptorInfosSet0[1u].desc = drawResourcesFiller.gpuDrawBuffers.drawObjectsBuffer; - - descriptorInfosSet0[2u].info.buffer.offset = 0u; - descriptorInfosSet0[2u].info.buffer.size = drawResourcesFiller.gpuDrawBuffers.mainObjectsBuffer->getCreationParams().size; - descriptorInfosSet0[2u].desc = drawResourcesFiller.gpuDrawBuffers.mainObjectsBuffer; - - descriptorInfosSet0[3u].info.buffer.offset = 0u; - descriptorInfosSet0[3u].info.buffer.size = drawResourcesFiller.gpuDrawBuffers.lineStylesBuffer->getCreationParams().size; - descriptorInfosSet0[3u].desc = drawResourcesFiller.gpuDrawBuffers.lineStylesBuffer; - - descriptorInfosSet0[4u].info.combinedImageSampler.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; - descriptorInfosSet0[4u].info.combinedImageSampler.sampler = msdfTextureSampler; - descriptorInfosSet0[4u].desc = drawResourcesFiller.getMSDFsTextureArray(); + descriptorInfosSet0[1u].info.combinedImageSampler.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + descriptorInfosSet0[1u].info.combinedImageSampler.sampler = msdfTextureSampler; + descriptorInfosSet0[1u].desc = drawResourcesFiller.getMSDFsTextureArray(); - descriptorInfosSet0[5u].desc = msdfTextureSampler; // TODO[Erfan]: different sampler and make immutable? + descriptorInfosSet0[2u].desc = msdfTextureSampler; // TODO[Erfan]: different sampler and make immutable? // This is bindless to we write to it later. - // descriptorInfosSet0[6u].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; - // descriptorInfosSet0[6u].desc = drawResourcesFiller.getMSDFsTextureArray(); + // descriptorInfosSet0[3u].info.image.imageLayout = IImage::LAYOUT::READ_ONLY_OPTIMAL; + // descriptorInfosSet0[3u].desc = drawResourcesFiller.getMSDFsTextureArray(); // Descriptors For Set 1: constexpr uint32_t DescriptorCountSet1 = 2u; @@ -812,60 +764,50 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu video::IGPUDescriptorSet::SWriteDescriptorSet descriptorUpdates[DescriptorUpdatesCount] = {}; // Set 0 Updates: + // globals descriptorUpdates[0u].dstSet = descriptorSet0.get(); descriptorUpdates[0u].binding = 0u; descriptorUpdates[0u].arrayElement = 0u; descriptorUpdates[0u].count = 1u; descriptorUpdates[0u].info = &descriptorInfosSet0[0u]; + // mdfs textures descriptorUpdates[1u].dstSet = descriptorSet0.get(); descriptorUpdates[1u].binding = 1u; descriptorUpdates[1u].arrayElement = 0u; descriptorUpdates[1u].count = 1u; descriptorUpdates[1u].info = &descriptorInfosSet0[1u]; - + + // general texture sampler descriptorUpdates[2u].dstSet = descriptorSet0.get(); descriptorUpdates[2u].binding = 2u; descriptorUpdates[2u].arrayElement = 0u; descriptorUpdates[2u].count = 1u; descriptorUpdates[2u].info = &descriptorInfosSet0[2u]; - descriptorUpdates[3u].dstSet = descriptorSet0.get(); - descriptorUpdates[3u].binding = 3u; + // Set 1 Updates: + descriptorUpdates[3u].dstSet = descriptorSet1.get(); + descriptorUpdates[3u].binding = 0u; descriptorUpdates[3u].arrayElement = 0u; descriptorUpdates[3u].count = 1u; - descriptorUpdates[3u].info = &descriptorInfosSet0[3u]; - - descriptorUpdates[4u].dstSet = descriptorSet0.get(); - descriptorUpdates[4u].binding = 4u; + descriptorUpdates[3u].info = &descriptorInfosSet1[0u]; + + descriptorUpdates[4u].dstSet = descriptorSet1.get(); + descriptorUpdates[4u].binding = 1u; descriptorUpdates[4u].arrayElement = 0u; descriptorUpdates[4u].count = 1u; - descriptorUpdates[4u].info = &descriptorInfosSet0[4u]; - - descriptorUpdates[5u].dstSet = descriptorSet0.get(); - descriptorUpdates[5u].binding = 5u; - descriptorUpdates[5u].arrayElement = 0u; - descriptorUpdates[5u].count = 1u; - descriptorUpdates[5u].info = &descriptorInfosSet0[5u]; - - // Set 1 Updates: - descriptorUpdates[6u].dstSet = descriptorSet1.get(); - descriptorUpdates[6u].binding = 0u; - descriptorUpdates[6u].arrayElement = 0u; - descriptorUpdates[6u].count = 1u; - descriptorUpdates[6u].info = &descriptorInfosSet1[0u]; - - descriptorUpdates[7u].dstSet = descriptorSet1.get(); - descriptorUpdates[7u].binding = 1u; - descriptorUpdates[7u].arrayElement = 0u; - descriptorUpdates[7u].count = 1u; - descriptorUpdates[7u].info = &descriptorInfosSet1[1u]; - + descriptorUpdates[4u].info = &descriptorInfosSet1[1u]; m_device->updateDescriptorSets(DescriptorUpdatesCount, descriptorUpdates, 0u, nullptr); } - pipelineLayout = m_device->createPipelineLayout({}, core::smart_refctd_ptr(descriptorSetLayout0), core::smart_refctd_ptr(descriptorSetLayout1), nullptr, nullptr); + const asset::SPushConstantRange range = { + .stageFlags = IShader::E_SHADER_STAGE::ESS_VERTEX | IShader::E_SHADER_STAGE::ESS_FRAGMENT, + .offset = 0, + .size = sizeof(PushConstants) + }; + + pipelineLayout = m_device->createPipelineLayout({ &range,1 }, core::smart_refctd_ptr(descriptorSetLayout0), core::smart_refctd_ptr(descriptorSetLayout1), nullptr, nullptr); } smart_refctd_ptr mainPipelineFragmentShaders = {}; @@ -925,14 +867,14 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu auto mainPipelineFragmentCpuShader = loadCompileShader("../shaders/main_pipeline/fragment.hlsl", IShader::E_SHADER_STAGE::ESS_ALL_OR_LIBRARY); auto mainPipelineVertexCpuShader = loadCompileShader("../shaders/main_pipeline/vertex_shader.hlsl", IShader::E_SHADER_STAGE::ESS_VERTEX); - auto geoTexturePipelineVertCpuShader = loadCompileShader(GeoTextureRenderer::VertexShaderRelativePath, IShader::E_SHADER_STAGE::ESS_VERTEX); - auto geoTexturePipelineFragCpuShader = loadCompileShader(GeoTextureRenderer::FragmentShaderRelativePath, IShader::E_SHADER_STAGE::ESS_FRAGMENT); + // auto geoTexturePipelineVertCpuShader = loadCompileShader(GeoTextureRenderer::VertexShaderRelativePath, IShader::E_SHADER_STAGE::ESS_VERTEX); + // auto geoTexturePipelineFragCpuShader = loadCompileShader(GeoTextureRenderer::FragmentShaderRelativePath, IShader::E_SHADER_STAGE::ESS_FRAGMENT); mainPipelineFragmentCpuShader->setShaderStage(IShader::E_SHADER_STAGE::ESS_FRAGMENT); mainPipelineFragmentShaders = m_device->createShader({ mainPipelineFragmentCpuShader.get(), nullptr, shaderReadCache.get(), shaderWriteCache.get() }); mainPipelineVertexShader = m_device->createShader({ mainPipelineVertexCpuShader.get(), nullptr, shaderReadCache.get(), shaderWriteCache.get() }); - geoTexturePipelineShaders[0] = m_device->createShader({ geoTexturePipelineVertCpuShader.get(), nullptr, shaderReadCache.get(), shaderWriteCache.get() }); - geoTexturePipelineShaders[1] = m_device->createShader({ geoTexturePipelineFragCpuShader.get(), nullptr, shaderReadCache.get(), shaderWriteCache.get() }); + // geoTexturePipelineShaders[0] = m_device->createShader({ geoTexturePipelineVertCpuShader.get(), nullptr, shaderReadCache.get(), shaderWriteCache.get() }); + // geoTexturePipelineShaders[1] = m_device->createShader({ geoTexturePipelineFragCpuShader.get(), nullptr, shaderReadCache.get(), shaderWriteCache.get() }); core::smart_refctd_ptr shaderWriteCacheFile; { @@ -1069,7 +1011,7 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu ); m_geoTextureRenderer = std::unique_ptr(new GeoTextureRenderer(smart_refctd_ptr(m_device), smart_refctd_ptr(m_logger))); - m_geoTextureRenderer->initialize(geoTexturePipelineShaders[0].get(), geoTexturePipelineShaders[1].get(), compatibleRenderPass.get(), m_globalsBuffer); + // m_geoTextureRenderer->initialize(geoTexturePipelineShaders[0].get(), geoTexturePipelineShaders[1].get(), compatibleRenderPass.get(), m_globalsBuffer); // Create the Semaphores m_renderSemaphore = m_device->createSemaphore(0ull); @@ -1129,6 +1071,18 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu { m_hatchDebugStep--; } + if (ev.action == nbl::ui::SKeyboardEvent::E_KEY_ACTION::ECA_PRESSED && ev.keyCode == nbl::ui::E_KEY_CODE::EKC_1) + { + m_shadingModeExample = E_HEIGHT_SHADING_MODE::DISCRETE_VARIABLE_LENGTH_INTERVALS; + } + if (ev.action == nbl::ui::SKeyboardEvent::E_KEY_ACTION::ECA_PRESSED && ev.keyCode == nbl::ui::E_KEY_CODE::EKC_2) + { + m_shadingModeExample = E_HEIGHT_SHADING_MODE::DISCRETE_FIXED_LENGTH_INTERVALS; + } + if (ev.action == nbl::ui::SKeyboardEvent::E_KEY_ACTION::ECA_PRESSED && ev.keyCode == nbl::ui::E_KEY_CODE::EKC_3) + { + m_shadingModeExample = E_HEIGHT_SHADING_MODE::CONTINOUS_INTERVALS; + } } } , m_logger.get()); @@ -1201,23 +1155,6 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu // cb->reset(video::IGPUCommandBuffer::RESET_FLAGS::RELEASE_RESOURCES_BIT); // cb->begin(video::IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT); cb->beginDebugMarker("Frame"); - - float64_t3x3 projectionToNDC; - projectionToNDC = m_Camera.constructViewProjection(); - - Globals globalData = {}; - globalData.antiAliasingFactor = 1.0;// +abs(cos(m_timeElapsed * 0.0008)) * 20.0f; - globalData.resolution = uint32_t2{ m_window->getWidth(), m_window->getHeight() }; - globalData.defaultClipProjection.projectionToNDC = projectionToNDC; - globalData.defaultClipProjection.minClipNDC = float32_t2(-1.0, -1.0); - globalData.defaultClipProjection.maxClipNDC = float32_t2(+1.0, +1.0); - auto screenToWorld = getScreenToWorldRatio(globalData.defaultClipProjection.projectionToNDC, globalData.resolution); - globalData.screenToWorldRatio = screenToWorld; - globalData.worldToScreenRatio = (1.0/screenToWorld); - globalData.miterLimit = 10.0f; - SBufferRange globalBufferUpdateRange = { .offset = 0ull, .size = sizeof(Globals), .buffer = m_globalsBuffer.get() }; - bool updateSuccess = cb->updateBuffer(globalBufferUpdateRange, &globalData); - assert(updateSuccess); nbl::video::IGPUCommandBuffer::SRenderpassBeginInfo beginInfo; auto scRes = static_cast(m_surface->getSwapchainResources()); @@ -1248,10 +1185,46 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu void submitDraws(SIntendedSubmitInfo& intendedSubmitInfo, bool inBetweenSubmit) { + // TODO: Remove this check later + if (inBetweenSubmit) + { + m_logger->log("Temporarily Disabled. Auto-Submission shouldn't happen (for Demo)", ILogger::ELL_ERROR); + assert(!inBetweenSubmit); + } + // Use the current recording command buffer of the intendedSubmitInfos scratchCommandBuffers, it should be in recording state auto* cb = m_currentRecordingCommandBufferInfo->cmdbuf; - auto&r = drawResourcesFiller; + const auto& resources = drawResourcesFiller.getResourcesCollection(); + const auto& resourcesGPUBuffer = drawResourcesFiller.getResourcesGPUBuffer(); + + float64_t3x3 projectionToNDC; + projectionToNDC = m_Camera.constructViewProjection(); + + Globals globalData = {}; + uint64_t baseAddress = resourcesGPUBuffer->getDeviceAddress(); + globalData.pointers = { + .lineStyles = baseAddress + resources.lineStyles.bufferOffset, + .dtmSettings = baseAddress + resources.dtmSettings.bufferOffset, + .customClipProjections = baseAddress + resources.clipProjections.bufferOffset, + .mainObjects = baseAddress + resources.mainObjects.bufferOffset, + .drawObjects = baseAddress + resources.drawObjects.bufferOffset, + .geometryBuffer = baseAddress + resources.geometryInfo.bufferOffset, + }; + globalData.antiAliasingFactor = 1.0;// +abs(cos(m_timeElapsed * 0.0008)) * 20.0f; + globalData.resolution = uint32_t2{ m_window->getWidth(), m_window->getHeight() }; + globalData.defaultClipProjection.projectionToNDC = projectionToNDC; + globalData.defaultClipProjection.minClipNDC = float32_t2(-1.0, -1.0); + globalData.defaultClipProjection.maxClipNDC = float32_t2(+1.0, +1.0); + auto screenToWorld = getScreenToWorldRatio(globalData.defaultClipProjection.projectionToNDC, globalData.resolution); + globalData.screenToWorldRatio = screenToWorld; + globalData.worldToScreenRatio = (1.0/screenToWorld); + globalData.miterLimit = 10.0f; + globalData.currentlyActiveMainObjectIndex = drawResourcesFiller.getActiveMainObjectIndex(); + SBufferRange globalBufferUpdateRange = { .offset = 0ull, .size = sizeof(Globals), .buffer = m_globalsBuffer.get() }; + bool updateSuccess = cb->updateBuffer(globalBufferUpdateRange, &globalData); + assert(updateSuccess); + asset::SViewport vp = { .x = 0u, @@ -1272,25 +1245,12 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu // pipelineBarriersBeforeDraw { - constexpr uint32_t MaxBufferBarriersCount = 6u; + constexpr uint32_t MaxBufferBarriersCount = 2u; uint32_t bufferBarriersCount = 0u; IGPUCommandBuffer::SPipelineBarrierDependencyInfo::buffer_barrier_t bufferBarriers[MaxBufferBarriersCount]; + + const auto& resources = drawResourcesFiller.getResourcesCollection(); - // Index Buffer Copy Barrier -> Only do once at the beginning of the frames - if (m_realFrameIx == 0u) - { - auto& bufferBarrier = bufferBarriers[bufferBarriersCount++]; - bufferBarrier.barrier.dep.srcStageMask = PIPELINE_STAGE_FLAGS::COPY_BIT; - bufferBarrier.barrier.dep.srcAccessMask = ACCESS_FLAGS::TRANSFER_WRITE_BIT; - bufferBarrier.barrier.dep.dstStageMask = PIPELINE_STAGE_FLAGS::VERTEX_INPUT_BITS; - bufferBarrier.barrier.dep.dstAccessMask = ACCESS_FLAGS::INDEX_READ_BIT; - bufferBarrier.range = - { - .offset = 0u, - .size = drawResourcesFiller.gpuDrawBuffers.indexBuffer->getSize(), - .buffer = drawResourcesFiller.gpuDrawBuffers.indexBuffer, - }; - } if (m_globalsBuffer->getSize() > 0u) { auto& bufferBarrier = bufferBarriers[bufferBarriersCount++]; @@ -1305,60 +1265,18 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu .buffer = m_globalsBuffer, }; } - if (drawResourcesFiller.getCurrentDrawObjectsBufferSize() > 0u) - { - auto& bufferBarrier = bufferBarriers[bufferBarriersCount++]; - bufferBarrier.barrier.dep.srcStageMask = PIPELINE_STAGE_FLAGS::COPY_BIT; - bufferBarrier.barrier.dep.srcAccessMask = ACCESS_FLAGS::TRANSFER_WRITE_BIT; - bufferBarrier.barrier.dep.dstStageMask = PIPELINE_STAGE_FLAGS::VERTEX_SHADER_BIT; - bufferBarrier.barrier.dep.dstAccessMask = ACCESS_FLAGS::SHADER_READ_BITS; - bufferBarrier.range = - { - .offset = 0u, - .size = drawResourcesFiller.getCurrentDrawObjectsBufferSize(), - .buffer = drawResourcesFiller.gpuDrawBuffers.drawObjectsBuffer, - }; - } - if (drawResourcesFiller.getCurrentGeometryBufferSize() > 0u) + if (drawResourcesFiller.getCopiedResourcesSize() > 0u) { auto& bufferBarrier = bufferBarriers[bufferBarriersCount++]; bufferBarrier.barrier.dep.srcStageMask = PIPELINE_STAGE_FLAGS::COPY_BIT; bufferBarrier.barrier.dep.srcAccessMask = ACCESS_FLAGS::TRANSFER_WRITE_BIT; - bufferBarrier.barrier.dep.dstStageMask = PIPELINE_STAGE_FLAGS::VERTEX_SHADER_BIT; - bufferBarrier.barrier.dep.dstAccessMask = ACCESS_FLAGS::SHADER_READ_BITS; + bufferBarrier.barrier.dep.dstStageMask = PIPELINE_STAGE_FLAGS::VERTEX_INPUT_BITS | PIPELINE_STAGE_FLAGS::VERTEX_SHADER_BIT | PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT; + bufferBarrier.barrier.dep.dstAccessMask = ACCESS_FLAGS::MEMORY_READ_BITS | ACCESS_FLAGS::MEMORY_WRITE_BITS; bufferBarrier.range = { .offset = 0u, - .size = drawResourcesFiller.getCurrentGeometryBufferSize(), - .buffer = drawResourcesFiller.gpuDrawBuffers.geometryBuffer, - }; - } - if (drawResourcesFiller.getCurrentMainObjectsBufferSize() > 0u) - { - auto& bufferBarrier = bufferBarriers[bufferBarriersCount++]; - bufferBarrier.barrier.dep.srcStageMask = PIPELINE_STAGE_FLAGS::COPY_BIT; - bufferBarrier.barrier.dep.srcAccessMask = ACCESS_FLAGS::TRANSFER_WRITE_BIT; - bufferBarrier.barrier.dep.dstStageMask = PIPELINE_STAGE_FLAGS::VERTEX_SHADER_BIT | PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT; - bufferBarrier.barrier.dep.dstAccessMask = ACCESS_FLAGS::SHADER_READ_BITS; - bufferBarrier.range = - { - .offset = 0u, - .size = drawResourcesFiller.getCurrentMainObjectsBufferSize(), - .buffer = drawResourcesFiller.gpuDrawBuffers.mainObjectsBuffer, - }; - } - if (drawResourcesFiller.getCurrentLineStylesBufferSize() > 0u) - { - auto& bufferBarrier = bufferBarriers[bufferBarriersCount++]; - bufferBarrier.barrier.dep.srcStageMask = PIPELINE_STAGE_FLAGS::COPY_BIT; - bufferBarrier.barrier.dep.srcAccessMask = ACCESS_FLAGS::TRANSFER_WRITE_BIT; - bufferBarrier.barrier.dep.dstStageMask = PIPELINE_STAGE_FLAGS::VERTEX_SHADER_BIT | PIPELINE_STAGE_FLAGS::FRAGMENT_SHADER_BIT; - bufferBarrier.barrier.dep.dstAccessMask = ACCESS_FLAGS::SHADER_READ_BITS; - bufferBarrier.range = - { - .offset = 0u, - .size = drawResourcesFiller.getCurrentLineStylesBufferSize(), - .buffer = drawResourcesFiller.gpuDrawBuffers.lineStylesBuffer, + .size = drawResourcesFiller.getCopiedResourcesSize(), + .buffer = drawResourcesFiller.getResourcesGPUBuffer(), }; } cb->pipelineBarrier(E_DEPENDENCY_FLAGS::EDF_NONE, { .bufBarriers = {bufferBarriers, bufferBarriersCount}, .imgBarriers = {} }); @@ -1383,22 +1301,43 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu }; } cb->beginRenderPass(beginInfo, IGPUCommandBuffer::SUBPASS_CONTENTS::INLINE); - - const uint32_t currentIndexCount = drawResourcesFiller.getDrawObjectCount() * 6u; + IGPUDescriptorSet* descriptorSets[] = { descriptorSet0.get(), descriptorSet1.get() }; cb->bindDescriptorSets(asset::EPBP_GRAPHICS, pipelineLayout.get(), 0u, 2u, descriptorSets); + + cb->bindGraphicsPipeline(graphicsPipeline.get()); - // TODO[Przemek]: based on our call bind index buffer you uploaded to part of the `drawResourcesFiller.gpuDrawBuffers.geometryBuffer` - // Vertices will be pulled based on baseBDAPointer of where you uploaded the vertex + the VertexID in the vertex shader. - cb->bindIndexBuffer({ .offset = 0u, .buffer = drawResourcesFiller.gpuDrawBuffers.indexBuffer.get() }, asset::EIT_32BIT); + for (auto& drawCall : drawResourcesFiller.drawCalls) + { + if (drawCall.isDTMRendering) + { + cb->bindIndexBuffer({ .offset = resources.geometryInfo.bufferOffset + drawCall.dtm.indexBufferOffset, .buffer = drawResourcesFiller.getResourcesGPUBuffer().get()}, asset::EIT_32BIT); - // TODO[Przemek]: binding the same pipelie, no need to change. - cb->bindGraphicsPipeline(graphicsPipeline.get()); - - // TODO[Przemek]: contour settings, height shading settings, base bda pointers will need to be pushed via pushConstants before the draw currently as it's the easiest thing to do. + PushConstants pc = { + .triangleMeshVerticesBaseAddress = drawCall.dtm.triangleMeshVerticesBaseAddress + resourcesGPUBuffer->getDeviceAddress() + resources.geometryInfo.bufferOffset, + .triangleMeshMainObjectIndex = drawCall.dtm.triangleMeshMainObjectIndex, + .isDTMRendering = true + }; + cb->pushConstants(graphicsPipeline->getLayout(), IGPUShader::E_SHADER_STAGE::ESS_VERTEX | IShader::E_SHADER_STAGE::ESS_FRAGMENT, 0, sizeof(PushConstants), &pc); + + cb->drawIndexed(drawCall.dtm.indexCount, 1u, 0u, 0u, 0u); + } + else + { + PushConstants pc = { + .isDTMRendering = false + }; + cb->pushConstants(graphicsPipeline->getLayout(), IGPUShader::E_SHADER_STAGE::ESS_VERTEX | IShader::E_SHADER_STAGE::ESS_FRAGMENT, 0, sizeof(PushConstants), &pc); + + const uint64_t indexOffset = drawCall.drawObj.drawObjectStart * 6u; + const uint64_t indexCount = drawCall.drawObj.drawObjectCount * 6u; + + // assert(currentIndexCount == resources.indexBuffer.getCount()); + cb->bindIndexBuffer({ .offset = resources.indexBuffer.bufferOffset + indexOffset * sizeof(uint32_t), .buffer = resourcesGPUBuffer.get()}, asset::EIT_32BIT); + cb->drawIndexed(indexCount, 1u, 0u, 0u, 0u); + } + } - // TODO[Przemek]: draw parameters needs to reflect the mesh involved - cb->drawIndexed(currentIndexCount, 1u, 0u, 0u, 0u); if (fragmentShaderInterlockEnabled) { cb->bindGraphicsPipeline(resolveAlphaGraphicsPipeline.get()); @@ -1407,10 +1346,11 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu if constexpr (DebugModeWireframe) { + const uint32_t indexCount = resources.drawObjects.getCount() * 6u; cb->bindGraphicsPipeline(debugGraphicsPipeline.get()); - cb->drawIndexed(currentIndexCount, 1u, 0u, 0u, 0u); + cb->drawIndexed(indexCount, 1u, 0u, 0u, 0u); } - + cb->endRenderPass(); if (!inBetweenSubmit) @@ -1482,6 +1422,14 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu retval.fragmentShaderPixelInterlock = FragmentShaderPixelInterlock; return retval; } + + virtual video::SPhysicalDeviceLimits getRequiredDeviceLimits() const override + { + video::SPhysicalDeviceLimits retval = base_t::getRequiredDeviceLimits(); + retval.fragmentShaderBarycentric = true; + + return retval; + } virtual video::IAPIConnection::SFeatures getAPIFeaturesToEnable() override { @@ -1489,14 +1437,13 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu // We only support one swapchain mode, surface, the other one is Display which we have not implemented yet. retval.swapchainMode = video::E_SWAPCHAIN_MODE::ESM_SURFACE; retval.validations = true; - retval.synchronizationValidation = true; + retval.synchronizationValidation = false; return retval; } protected: void addObjects(SIntendedSubmitInfo& intendedNextSubmit) { - // TODO[Przemek]: add your own case, you won't call any other drawResourcesFiller function, only drawMesh with your custom made Mesh (for start it can be a single triangle) // we record upload of our objects and if we failed to allocate we submit everything @@ -1951,8 +1898,8 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu LineStyleInfo style = {}; style.screenSpaceLineWidth = 4.0f; - style.worldSpaceLineWidth = 0.0f; - style.color = float32_t4(0.7f, 0.3f, 0.1f, 0.5f); + style.worldSpaceLineWidth = 2.0f; + style.color = float32_t4(0.7f, 0.3f, 0.1f, 0.1f); LineStyleInfo style2 = {}; style2.screenSpaceLineWidth = 2.0f; @@ -2025,7 +1972,7 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu myCurve.majorAxis = { -10.0, 5.0 }; myCurve.center = { 0, -5.0 }; myCurve.angleBounds = { - nbl::core::PI() * 2.0, + nbl::core::PI() * 1.0, nbl::core::PI() * 0.0 }; myCurve.eccentricity = 1.0; @@ -2053,10 +2000,10 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu } drawResourcesFiller.drawPolyline(originalPolyline, style, intendedNextSubmit); - //CPolyline offsettedPolyline = originalPolyline.generateParallelPolyline(+0.0 - 3.0 * abs(cos(m_timeElapsed * 0.0009))); - //CPolyline offsettedPolyline2 = originalPolyline.generateParallelPolyline(+0.0 + 3.0 * abs(cos(m_timeElapsed * 0.0009))); - //drawResourcesFiller.drawPolyline(offsettedPolyline, style2, intendedNextSubmit); - //drawResourcesFiller.drawPolyline(offsettedPolyline2, style2, intendedNextSubmit); + CPolyline offsettedPolyline = originalPolyline.generateParallelPolyline(+0.0 - 3.0 * abs(cos(10.0 * 0.0009))); + CPolyline offsettedPolyline2 = originalPolyline.generateParallelPolyline(+0.0 + 3.0 * abs(cos(10.0 * 0.0009))); + drawResourcesFiller.drawPolyline(offsettedPolyline, style2, intendedNextSubmit); + drawResourcesFiller.drawPolyline(offsettedPolyline2, style2, intendedNextSubmit); } else if (mode == ExampleMode::CASE_4) { @@ -2912,7 +2859,6 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu default: m_logger->log("Failed to load ICPUImage or ICPUImageView got some other Asset Type, skipping!",ILogger::ELL_ERROR); } - // create matching size gpu image smart_refctd_ptr gpuImg; @@ -2950,7 +2896,7 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu { { .dstSet = descriptorSet0.get(), - .binding = 6u, + .binding = 3u, .arrayElement = 0u, .count = 1u, .info = &dsInfo, @@ -3090,15 +3036,6 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu auto penY = -500.0; auto previous = 0; - uint32_t glyphObjectIdx; - { - LineStyleInfo lineStyle = {}; - lineStyle.color = float32_t4(1.0, 1.0, 1.0, 1.0); - const uint32_t styleIdx = drawResourcesFiller.addLineStyle_SubmitIfNeeded(lineStyle, intendedNextSubmit); - - glyphObjectIdx = drawResourcesFiller.addMainObject_SubmitIfNeeded(styleIdx, intendedNextSubmit); - } - float64_t2 currentBaselineStart = float64_t2(0.0, 0.0); float64_t scale = 1.0 / 64.0; @@ -3231,6 +3168,160 @@ class ComputerAidedDesign final : public examples::SimpleWindowedApplication, pu } } + else if (mode == ExampleMode::CASE_9) + { + // GRID (outdated) + /*core::vector vertices = { + { float32_t2(-200.0f, -200.0f), 10.0f }, + { float32_t2(-50.0f, -200.0f), 50.0f }, + { float32_t2(100.0f, -200.0f), 90.0f }, + { float32_t2(-125.0f, -70.1f), 10.0f }, + { float32_t2(25.0f, -70.1f), 50.0f }, + { float32_t2(175.0f, -70.1f), 90.0f }, + { float32_t2(-200.0f, 59.8f), 10.0f }, + { float32_t2(-50.0f, 59.8f), 50.0f }, + { float32_t2(100.0f, 59.8f), 90.0f }, + { float32_t2(-125.0f, 189.7f), 10.0f }, + { float32_t2(25.0f, 189.7f), 50.0f }, + { float32_t2(175.0f, 189.7f), 90.0f } + }; + + core::vector indices = { + 0, 3, 1, + 1, 3, 4, + 1, 2, 4, + 2, 4, 5, + 3, 4, 6, + 4, 6, 7, + 4, 5, 7, + 5, 7, 8, + 6, 7, 9, + 7, 9, 10, + 7, 8, 10, + 8, 10, 11 + };*/ + + // PYRAMID + core::vector vertices = { + //{ float64_t2(0.0, 0.0), 100.0 }, //0 + //{ float64_t2(-200.0, -200.0), 10.0 }, //1 + //{ float64_t2(200.0, -200.0), 10.0 }, //2 + //{ float64_t2(200.0, 200.0), -20.0 }, //3 + //{ float64_t2(-200.0, 200.0), 10.0 }, //4 + + { float64_t2(0.0, 0.0), 100.0 }, + { float64_t2(-200.0, -200.0), 10.0 }, + { float64_t2(200.0, -100.0), 10.0 }, + { float64_t2(0.0, 0.0), 100.0 }, + { float64_t2(200.0, -100.0), 10.0 }, + { float64_t2(200.0, 200.0), -20.0 }, + { float64_t2(0.0, 0.0), 100.0 }, + { float64_t2(200.0, 200.0), -20.0 }, + { float64_t2(-200.0, 200.0), 10.0 }, + { float64_t2(0.0, 0.0), 100.0 }, + { float64_t2(-200.0, 200.0), 10.0 }, + { float64_t2(-200.0, -200.0), 10.0 }, + }; + + core::vector indices = { + 0, 1, 2, + 3, 4, 5, + 6, 7, 8, + 9, 10, 11 + }; + + // SINGLE TRIANGLE + /*core::vector vertices = { + { float32_t2(0.0, 0.0), -20.0 }, + { float32_t2(200.0, 200.0), 100.0 }, + { float32_t2(200.0, -200.0), 80.0 } + }; + + core::vector indices = { + 0, 1, 2 + };*/ + + CTriangleMesh mesh; + mesh.setVertices(std::move(vertices)); + mesh.setIndices(std::move(indices)); + + DTMSettingsInfo dtmInfo; + dtmInfo.mode = E_DTM_MODE::HEIGHT_SHADING | E_DTM_MODE::CONTOUR | E_DTM_MODE::OUTLINE; + + dtmInfo.outlineStyleInfo.screenSpaceLineWidth = 3.0f; + dtmInfo.outlineStyleInfo.worldSpaceLineWidth = 0.0f; + dtmInfo.outlineStyleInfo.color = float32_t4(0.0f, 0.39f, 0.0f, 1.0f); + std::array outlineStipplePattern = { 0.0f, -5.0f, 20.0f, -5.0f }; + dtmInfo.outlineStyleInfo.setStipplePatternData(outlineStipplePattern); + + dtmInfo.contourInfo.startHeight = 20; + dtmInfo.contourInfo.endHeight = 90; + dtmInfo.contourInfo.heightInterval = 10; + dtmInfo.contourInfo.lineStyleInfo.screenSpaceLineWidth = 0.0f; + dtmInfo.contourInfo.lineStyleInfo.worldSpaceLineWidth = 1.0f; + dtmInfo.contourInfo.lineStyleInfo.color = float32_t4(0.0f, 0.0f, 1.0f, 0.7f); + std::array contourStipplePattern = { 0.0f, -5.0f, 10.0f, -5.0f }; + dtmInfo.contourInfo.lineStyleInfo.setStipplePatternData(contourStipplePattern); + + // PRESS 1, 2, 3 TO SWITCH HEIGHT SHADING MODE + // 1 - DISCRETE_VARIABLE_LENGTH_INTERVALS + // 2 - DISCRETE_FIXED_LENGTH_INTERVALS + // 3 - CONTINOUS_INTERVALS + float animatedAlpha = (std::cos(m_timeElapsed * 0.0005) + 1.0) * 0.5; + switch (m_shadingModeExample) + { + case E_HEIGHT_SHADING_MODE::DISCRETE_VARIABLE_LENGTH_INTERVALS: + { + dtmInfo.heightShadingInfo.heightShadingMode = E_HEIGHT_SHADING_MODE::DISCRETE_VARIABLE_LENGTH_INTERVALS; + + dtmInfo.heightShadingInfo.addHeightColorMapEntry(-10.0f, float32_t4(0.5f, 1.0f, 1.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(20.0f, float32_t4(0.0f, 1.0f, 0.0f, 1.0f)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(25.0f, float32_t4(1.0f, 1.0f, 0.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(70.0f, float32_t4(1.0f, 0.0f, 0.0f, 1.0f)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(90.0f, float32_t4(1.0f, 0.0f, 0.0f, 1.0f)); + + break; + } + case E_HEIGHT_SHADING_MODE::DISCRETE_FIXED_LENGTH_INTERVALS: + { + dtmInfo.heightShadingInfo.intervalLength = 10.0f; + dtmInfo.heightShadingInfo.intervalIndexToHeightMultiplier = dtmInfo.heightShadingInfo.intervalLength; + dtmInfo.heightShadingInfo.isCenteredShading = false; + dtmInfo.heightShadingInfo.heightShadingMode = E_HEIGHT_SHADING_MODE::DISCRETE_FIXED_LENGTH_INTERVALS; + dtmInfo.heightShadingInfo.addHeightColorMapEntry(0.0f, float32_t4(0.0f, 0.0f, 1.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(25.0f, float32_t4(0.0f, 1.0f, 1.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(50.0f, float32_t4(0.0f, 1.0f, 0.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(75.0f, float32_t4(1.0f, 1.0f, 0.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(100.0f, float32_t4(1.0f, 0.0f, 0.0f, animatedAlpha)); + + break; + } + case E_HEIGHT_SHADING_MODE::CONTINOUS_INTERVALS: + { + dtmInfo.heightShadingInfo.heightShadingMode = E_HEIGHT_SHADING_MODE::CONTINOUS_INTERVALS; + dtmInfo.heightShadingInfo.addHeightColorMapEntry(0.0f, float32_t4(0.0f, 0.0f, 1.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(25.0f, float32_t4(0.0f, 1.0f, 1.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(50.0f, float32_t4(0.0f, 1.0f, 0.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(75.0f, float32_t4(1.0f, 1.0f, 0.0f, animatedAlpha)); + dtmInfo.heightShadingInfo.addHeightColorMapEntry(90.0f, float32_t4(1.0f, 0.0f, 0.0f, animatedAlpha)); + + break; + } + } + + drawResourcesFiller.drawTriangleMesh(mesh, dtmInfo, intendedNextSubmit); + + dtmInfo.contourInfo.lineStyleInfo.color = float32_t4(1.0f, 0.39f, 0.0f, 1.0f); + dtmInfo.outlineStyleInfo.color = float32_t4(0.0f, 0.39f, 1.0f, 1.0f); + for (auto& v : mesh.m_vertices) + { + v.pos += float64_t2(450.0, 200.0); + v.height -= 10.0; + } + + drawResourcesFiller.drawTriangleMesh(mesh, dtmInfo, intendedNextSubmit); + } + drawResourcesFiller.finalizeAllCopiesToGPU(intendedNextSubmit); } diff --git a/62_CAD/shaders/geotexture/common.hlsl b/62_CAD/shaders/geotexture/common.hlsl index 82a646319..691cd3d3b 100644 --- a/62_CAD/shaders/geotexture/common.hlsl +++ b/62_CAD/shaders/geotexture/common.hlsl @@ -25,7 +25,7 @@ struct PSInput [[vk::push_constant]] GeoTextureOBB geoTextureOBB; // Set 0 - Scene Data and Globals, buffer bindings don't change the buffers only get updated -[[vk::binding(0, 0)]] ConstantBuffer globals : register(b0); +// [[vk::binding(0, 0)]] ConstantBuffer globals; ---> moved to globals.hlsl // Set 1 - Window dependant data which has higher update frequency due to multiple windows and resize need image recreation and descriptor writes [[vk::binding(0, 1)]] Texture2D geoTexture : register(t0); diff --git a/62_CAD/shaders/globals.hlsl b/62_CAD/shaders/globals.hlsl index 392e796f4..a83acb094 100644 --- a/62_CAD/shaders/globals.hlsl +++ b/62_CAD/shaders/globals.hlsl @@ -18,7 +18,6 @@ using namespace nbl::hlsl; - // because we can't use jit/device_capabilities.hlsl in c++ code #ifdef __HLSL_VERSION using pfloat64_t = portable_float64_t; @@ -32,6 +31,13 @@ using pfloat64_t3 = nbl::hlsl::vector; using pfloat64_t3x3 = portable_matrix_t3x3; +struct PushConstants +{ + uint64_t triangleMeshVerticesBaseAddress; + uint32_t triangleMeshMainObjectIndex; + uint32_t isDTMRendering; +}; + // TODO: Compute this in a compute shader from the world counterparts // because this struct includes NDC coordinates, the values will change based camera zoom and move // of course we could have the clip values to be in world units and also the matrix to transform to world instead of ndc but that requires extra computations(matrix multiplications) per vertex @@ -48,24 +54,33 @@ static_assert(offsetof(ClipProjectionData, minClipNDC) == 72u); static_assert(offsetof(ClipProjectionData, maxClipNDC) == 80u); #endif -struct Globals +struct Pointers { - ClipProjectionData defaultClipProjection; // 88 - pfloat64_t screenToWorldRatio; // 96 - pfloat64_t worldToScreenRatio; // 100 - uint32_t2 resolution; // 108 - float antiAliasingFactor; // 112 - float miterLimit; // 116 - float32_t2 _padding; // 128 + uint64_t lineStyles; + uint64_t dtmSettings; + uint64_t customClipProjections; + uint64_t mainObjects; + uint64_t drawObjects; + uint64_t geometryBuffer; }; +#ifndef __HLSL_VERSION +static_assert(sizeof(Pointers) == 48u); +#endif +struct Globals +{ + Pointers pointers; + ClipProjectionData defaultClipProjection; + pfloat64_t screenToWorldRatio; + pfloat64_t worldToScreenRatio; + uint32_t2 resolution; + float antiAliasingFactor; + uint32_t miterLimit; + uint32_t currentlyActiveMainObjectIndex; // for alpha resolve to skip resolving activeMainObjectIdx and prep it for next submit + float32_t _padding; +}; #ifndef __HLSL_VERSION -static_assert(offsetof(Globals, defaultClipProjection) == 0u); -static_assert(offsetof(Globals, screenToWorldRatio) == 88u); -static_assert(offsetof(Globals, worldToScreenRatio) == 96u); -static_assert(offsetof(Globals, resolution) == 104u); -static_assert(offsetof(Globals, antiAliasingFactor) == 112u); -static_assert(offsetof(Globals, miterLimit) == 116u); +static_assert(sizeof(Globals) == 176u); #endif #ifdef __HLSL_VERSION @@ -100,6 +115,16 @@ pfloat64_t2 transformVectorNdc(NBL_CONST_REF_ARG(pfloat64_t3x3) transformation, } #endif +enum class MainObjectType : uint32_t +{ + NONE = 0u, + POLYLINE, + HATCH, + TEXT, + IMAGE, + DTM, +}; + enum class ObjectType : uint32_t { LINE = 0u, @@ -107,7 +132,8 @@ enum class ObjectType : uint32_t CURVE_BOX = 2u, POLYLINE_CONNECTOR = 3u, FONT_GLYPH = 4u, - IMAGE = 5u + IMAGE = 5u, + TRIANGLE_MESH = 6u }; enum class MajorAxis : uint32_t @@ -120,8 +146,8 @@ enum class MajorAxis : uint32_t struct MainObject { uint32_t styleIdx; - uint32_t pad; // do I even need this on the gpu side? it's stored in structured buffer not bda - uint64_t clipProjectionAddress; + uint32_t dtmSettingsIdx; + uint32_t clipProjectionIndex; }; struct DrawObject @@ -131,6 +157,8 @@ struct DrawObject uint64_t geometryAddress; }; + +// Goes into geometry buffer, needs to be aligned by 8 struct LinePointInfo { pfloat64_t2 p; @@ -138,6 +166,7 @@ struct LinePointInfo float32_t stretchValue; }; +// Goes into geometry buffer, needs to be aligned by 8 struct QuadraticBezierInfo { nbl::hlsl::shapes::QuadraticBezier shape; // 48bytes = 3 (control points) x 16 (float64_t2) @@ -148,6 +177,7 @@ struct QuadraticBezierInfo static_assert(offsetof(QuadraticBezierInfo, phaseShift) == 48u); #endif +// Goes into geometry buffer, needs to be aligned by 8 struct GlyphInfo { pfloat64_t2 topLeft; // 2 * 8 = 16 bytes @@ -192,6 +222,7 @@ struct GlyphInfo } }; +// Goes into geometry buffer, needs to be aligned by 8 struct ImageObjectInfo { pfloat64_t2 topLeft; // 2 * 8 = 16 bytes (16) @@ -241,6 +272,7 @@ struct PolylineConnector }; // NOTE: Don't attempt to pack curveMin/Max to uints because of limited range of values, we need the logarithmic precision of floats (more precision near 0) +// Goes into geometry buffer, needs to be aligned by 8 struct CurveBox { // will get transformed in the vertex shader, and will be calculated on the cpu when generating these boxes @@ -262,9 +294,15 @@ NBL_CONSTEXPR uint32_t InvalidRigidSegmentIndex = 0xffffffff; NBL_CONSTEXPR float InvalidStyleStretchValue = nbl::hlsl::numeric_limits::infinity; -// TODO[Przemek]: we will need something similar to LineStyles but related to heigh shading settings which is user customizable (like LineStyle stipple patterns) and requires upper_bound to figure out the color based on height value. +// TODO[Przemek]: we will need something similar to LineStyles but related to heigh shading settings which is user customizable (like stipple patterns) and requires upper_bound to figure out the color based on height value. // We'll discuss that later or what it will be looking like and how it's gonna get passed to our shaders. +struct TriangleMeshVertex +{ + pfloat64_t2 pos; + pfloat64_t height; +}; + // The color parameter is also used for styling non-curve objects such as text glyphs and hatches with solid color struct LineStyle { @@ -316,6 +354,57 @@ struct LineStyle } }; +enum E_DTM_MODE +{ + OUTLINE = 1 << 0, + CONTOUR = 1 << 1, + HEIGHT_SHADING = 1 << 2, +}; + +enum class E_HEIGHT_SHADING_MODE : uint32_t +{ + DISCRETE_VARIABLE_LENGTH_INTERVALS, + DISCRETE_FIXED_LENGTH_INTERVALS, + CONTINOUS_INTERVALS +}; + +// Documentation and explanation of variables in DTMSettingsInfo +struct DTMSettings +{ + const static uint32_t HeightColorMapMaxEntries = 16u; + uint32_t outlineLineStyleIdx; // index into line styles + uint32_t contourLineStyleIdx; // index into line styles + + uint32_t mode; // E_DTM_MODE + + // contour lines + float contourLinesStartHeight; + float contourLinesEndHeight; + float contourLinesHeightInterval; + + // height-color map + float intervalLength; + float intervalIndexToHeightMultiplier; + int isCenteredShading; + + uint32_t heightColorEntryCount; + float heightColorMapHeights[HeightColorMapMaxEntries]; + float32_t4 heightColorMapColors[HeightColorMapMaxEntries]; + + E_HEIGHT_SHADING_MODE determineHeightShadingMode() + { + if (nbl::hlsl::isinf(intervalLength)) + return E_HEIGHT_SHADING_MODE::DISCRETE_VARIABLE_LENGTH_INTERVALS; + if (intervalLength == 0.0f) + return E_HEIGHT_SHADING_MODE::CONTINOUS_INTERVALS; + return E_HEIGHT_SHADING_MODE::DISCRETE_FIXED_LENGTH_INTERVALS; + } + + bool drawOutlineEnabled() { return (mode & E_DTM_MODE::OUTLINE) != 0u; } + bool drawContourEnabled() { return (mode & E_DTM_MODE::CONTOUR) != 0u; } + bool drawHeightShadingEnabled() { return (mode & E_DTM_MODE::HEIGHT_SHADING) != 0u; } +}; + #ifndef __HLSL_VERSION inline bool operator==(const LineStyle& lhs, const LineStyle& rhs) { @@ -338,22 +427,58 @@ inline bool operator==(const LineStyle& lhs, const LineStyle& rhs) return isStipplePatternArrayEqual; } + +inline bool operator==(const DTMSettings& lhs, const DTMSettings& rhs) +{ + return lhs.outlineLineStyleIdx == rhs.outlineLineStyleIdx && + lhs.contourLineStyleIdx == rhs.contourLineStyleIdx; +} #endif NBL_CONSTEXPR uint32_t MainObjectIdxBits = 24u; // It will be packed next to alpha in a texture NBL_CONSTEXPR uint32_t AlphaBits = 32u - MainObjectIdxBits; NBL_CONSTEXPR uint32_t MaxIndexableMainObjects = (1u << MainObjectIdxBits) - 1u; NBL_CONSTEXPR uint32_t InvalidStyleIdx = nbl::hlsl::numeric_limits::max; +NBL_CONSTEXPR uint32_t InvalidDTMSettingsIdx = nbl::hlsl::numeric_limits::max; NBL_CONSTEXPR uint32_t InvalidMainObjectIdx = MaxIndexableMainObjects; -NBL_CONSTEXPR uint64_t InvalidClipProjectionAddress = nbl::hlsl::numeric_limits::max; +NBL_CONSTEXPR uint32_t InvalidClipProjectionIndex = nbl::hlsl::numeric_limits::max; NBL_CONSTEXPR uint32_t InvalidTextureIdx = nbl::hlsl::numeric_limits::max; + +// Hatches NBL_CONSTEXPR MajorAxis SelectedMajorAxis = MajorAxis::MAJOR_Y; -// TODO: get automatic version working on HLSL NBL_CONSTEXPR MajorAxis SelectedMinorAxis = MajorAxis::MAJOR_X; //(MajorAxis) (1 - (uint32_t) SelectedMajorAxis); + +// Text or MSDF Hatches NBL_CONSTEXPR float MSDFPixelRange = 4.0f; NBL_CONSTEXPR float MSDFPixelRangeHalf = MSDFPixelRange / 2.0f; NBL_CONSTEXPR float MSDFSize = 32.0f; NBL_CONSTEXPR uint32_t MSDFMips = 4; NBL_CONSTEXPR float HatchFillMSDFSceenSpaceSize = 8.0; +#ifdef __HLSL_VERSION +[[vk::binding(0, 0)]] ConstantBuffer globals : register(b0); + +LineStyle loadLineStyle(const uint32_t index) +{ + return vk::RawBufferLoad(globals.pointers.lineStyles + index * sizeof(LineStyle), 8u); +} +DTMSettings loadDTMSettings(const uint32_t index) +{ + return vk::RawBufferLoad(globals.pointers.dtmSettings + index * sizeof(DTMSettings), 8u); +} +ClipProjectionData loadCustomClipProjection(const uint32_t index) +{ + return vk::RawBufferLoad(globals.pointers.customClipProjections + index * sizeof(ClipProjectionData), 8u); +} +MainObject loadMainObject(const uint32_t index) +{ + return vk::RawBufferLoad(globals.pointers.mainObjects + index * sizeof(MainObject), 4u); +} +DrawObject loadDrawObject(const uint32_t index) +{ + return vk::RawBufferLoad(globals.pointers.drawObjects + index * sizeof(DrawObject), 8u); +} +#endif + + #endif diff --git a/62_CAD/shaders/main_pipeline/common.hlsl b/62_CAD/shaders/main_pipeline/common.hlsl index 17c851a19..4327cf7fe 100644 --- a/62_CAD/shaders/main_pipeline/common.hlsl +++ b/62_CAD/shaders/main_pipeline/common.hlsl @@ -74,6 +74,11 @@ struct PSInput [[vk::location(3)]] nointerpolation float4 data4 : COLOR4; // Data segments that need interpolation, mostly for hatches [[vk::location(5)]] float2 interp_data5 : COLOR5; +#ifdef FRAGMENT_SHADER_INPUT + [[vk::location(6)]] [[vk::ext_decorate(/*spv::DecoratePerVertexKHR*/5285)]] float3 vertexScreenSpacePos[3] : COLOR6; +#else + [[vk::location(6)]] float3 vertexScreenSpacePos : COLOR6; +#endif // ArcLenCalculator // Set functions used in vshader, get functions used in fshader @@ -98,7 +103,7 @@ struct PSInput void setCurrentWorldToScreenRatio(float worldToScreen) { interp_data5.y = worldToScreen; } float getCurrentWorldToScreenRatio() { return interp_data5.y; } - + /* LINE */ float2 getLineStart() { return data2.xy; } float2 getLineEnd() { return data2.zw; } @@ -208,19 +213,36 @@ struct PSInput void setImageUV(float2 uv) { interp_data5.xy = uv; } void setImageTextureId(uint32_t textureId) { data2.x = asfloat(textureId); } + + /* TRIANGLE MESH */ + + float getOutlineThickness() { return asfloat(data1.z); } + float getContourLineThickness() { return asfloat(data1.w); } + + void setOutlineThickness(float lineThickness) { data1.z = asuint(lineThickness); } + void setContourLineThickness(float stretch) { data1.w = asuint(stretch); } + + void setHeight(float height) { interp_data5.x = height; } + float getHeight() { return interp_data5.x; } + +#ifndef FRAGMENT_SHADER_INPUT // vertex shader + void setScreenSpaceVertexAttribs(float3 pos) { vertexScreenSpacePos = pos; } +#else // fragment shader + float3 getScreenSpaceVertexAttribs(uint32_t vertexIndex) { return vertexScreenSpacePos[vertexIndex]; } +#endif }; // Set 0 - Scene Data and Globals, buffer bindings don't change the buffers only get updated -[[vk::binding(0, 0)]] ConstantBuffer globals : register(b0); -[[vk::binding(1, 0)]] StructuredBuffer drawObjects : register(t0); -[[vk::binding(2, 0)]] StructuredBuffer mainObjects : register(t1); -[[vk::binding(3, 0)]] StructuredBuffer lineStyles : register(t2); -[[vk::combinedImageSampler]][[vk::binding(4, 0)]] Texture2DArray msdfTextures : register(t3); -[[vk::combinedImageSampler]][[vk::binding(4, 0)]] SamplerState msdfSampler : register(s3); +// [[vk::binding(0, 0)]] ConstantBuffer globals; ---> moved to globals.hlsl + +[[vk::push_constant]] PushConstants pc; + +[[vk::combinedImageSampler]][[vk::binding(1, 0)]] Texture2DArray msdfTextures : register(t4); +[[vk::combinedImageSampler]][[vk::binding(1, 0)]] SamplerState msdfSampler : register(s4); -[[vk::binding(5, 0)]] SamplerState textureSampler : register(s4); -[[vk::binding(6, 0)]] Texture2D textures[128] : register(t4); +[[vk::binding(2, 0)]] SamplerState textureSampler : register(s5); +[[vk::binding(3, 0)]] Texture2D textures[128] : register(t5); // Set 1 - Window dependant data which has higher update frequency due to multiple windows and resize need image recreation and descriptor writes [[vk::binding(0, 1)]] globallycoherent RWTexture2D pseudoStencil : register(u0); diff --git a/62_CAD/shaders/main_pipeline/fragment_shader.hlsl b/62_CAD/shaders/main_pipeline/fragment_shader.hlsl index e850622c3..f9cd52ec3 100644 --- a/62_CAD/shaders/main_pipeline/fragment_shader.hlsl +++ b/62_CAD/shaders/main_pipeline/fragment_shader.hlsl @@ -1,655 +1,1104 @@ -#include "common.hlsl" -#include -#include -#include -#include -#include -#include -#include -#include - -template -struct DefaultClipper -{ - using float_t2 = vector; - NBL_CONSTEXPR_STATIC_INLINE float_t AccuracyThresholdT = 0.0; - - static DefaultClipper construct() - { - DefaultClipper ret; - return ret; - } - - inline float_t2 operator()(const float_t t) - { - const float_t ret = clamp(t, 0.0, 1.0); - return float_t2(ret, ret); - } -}; - -// for usage in upper_bound function -struct StyleAccessor -{ - LineStyle style; - using value_type = float; - - float operator[](const uint32_t ix) - { - return style.getStippleValue(ix); - } -}; - -template -struct StyleClipper -{ - using float_t = typename CurveType::scalar_t; - using float_t2 = typename CurveType::float_t2; - using float_t3 = typename CurveType::float_t3; - NBL_CONSTEXPR_STATIC_INLINE float_t AccuracyThresholdT = 0.000001; - - static StyleClipper construct( - LineStyle style, - CurveType curve, - typename CurveType::ArcLengthCalculator arcLenCalc, - float phaseShift, - float stretch, - float worldToScreenRatio) - { - StyleClipper ret = { style, curve, arcLenCalc, phaseShift, stretch, worldToScreenRatio, 0.0f, 0.0f, 0.0f, 0.0f }; - - // values for non-uniform stretching with a rigid segment - if (style.rigidSegmentIdx != InvalidRigidSegmentIndex && stretch != 1.0f) - { - // rigidSegment info in old non stretched pattern - ret.rigidSegmentStart = (style.rigidSegmentIdx >= 1u) ? style.getStippleValue(style.rigidSegmentIdx - 1u) : 0.0f; - ret.rigidSegmentEnd = (style.rigidSegmentIdx < style.stipplePatternSize) ? style.getStippleValue(style.rigidSegmentIdx) : 1.0f; - ret.rigidSegmentLen = ret.rigidSegmentEnd - ret.rigidSegmentStart; - // stretch value for non rigid segments - ret.nonRigidSegmentStretchValue = (stretch - ret.rigidSegmentLen) / (1.0f - ret.rigidSegmentLen); - // rigidSegment info to new stretched pattern - ret.rigidSegmentStart *= ret.nonRigidSegmentStretchValue / stretch; // get the new normalized rigid segment start - ret.rigidSegmentLen /= stretch; // get the new rigid segment normalized len - ret.rigidSegmentEnd = ret.rigidSegmentStart + ret.rigidSegmentLen; // get the new normalized rigid segment end - } - else - { - ret.nonRigidSegmentStretchValue = stretch; - } - - return ret; - } - - // For non-uniform stretching with a rigid segment (the one segement that shouldn't stretch) the whole pattern changes - // instead of transforming each of the style.stipplePattern values (max 14 of them), we transform the normalized place in pattern - float getRealNormalizedPlaceInPattern(float normalizedPlaceInPattern) - { - if (style.rigidSegmentIdx != InvalidRigidSegmentIndex && stretch != 1.0f) - { - float ret = min(normalizedPlaceInPattern, rigidSegmentStart) / nonRigidSegmentStretchValue; // unstretch parts before rigid segment - ret += max(normalizedPlaceInPattern - rigidSegmentEnd, 0.0f) / nonRigidSegmentStretchValue; // unstretch parts after rigid segment - ret += max(min(rigidSegmentLen, normalizedPlaceInPattern - rigidSegmentStart), 0.0f); // unstretch parts inside rigid segment - ret *= stretch; - return ret; - } - else - { - return normalizedPlaceInPattern; - } - } - - float_t2 operator()(float_t t) - { - // basicaly 0.0 and 1.0 but with a guardband to discard outside the range - const float_t minT = 0.0 - 1.0; - const float_t maxT = 1.0 + 1.0; - - StyleAccessor styleAccessor = { style }; - const float_t reciprocalStretchedStipplePatternLen = style.reciprocalStipplePatternLen / stretch; - const float_t patternLenInScreenSpace = 1.0 / (worldToScreenRatio * style.reciprocalStipplePatternLen); - - const float_t arcLen = arcLenCalc.calcArcLen(t); - const float_t worldSpaceArcLen = arcLen * float_t(worldToScreenRatio); - float_t normalizedPlaceInPattern = frac(worldSpaceArcLen * reciprocalStretchedStipplePatternLen + phaseShift); - normalizedPlaceInPattern = getRealNormalizedPlaceInPattern(normalizedPlaceInPattern); - uint32_t patternIdx = nbl::hlsl::upper_bound(styleAccessor, 0, style.stipplePatternSize, normalizedPlaceInPattern); - - const float_t InvalidT = nbl::hlsl::numeric_limits::infinity; - float_t2 ret = float_t2(InvalidT, InvalidT); - - // odd patternIdx means a "no draw section" and current candidate should split into two nearest draw sections - const bool notInDrawSection = patternIdx & 0x1; - - // TODO[Erfan]: Disable this piece of code after clipping, and comment the reason, that the bezier start and end at 0.0 and 1.0 should be in drawable sections - float_t minDrawT = 0.0; - float_t maxDrawT = 1.0; - { - float_t normalizedPlaceInPatternBegin = frac(phaseShift); - normalizedPlaceInPatternBegin = getRealNormalizedPlaceInPattern(normalizedPlaceInPatternBegin); - uint32_t patternIdxBegin = nbl::hlsl::upper_bound(styleAccessor, 0, style.stipplePatternSize, normalizedPlaceInPatternBegin); - const bool BeginInNonDrawSection = patternIdxBegin & 0x1; - - if (BeginInNonDrawSection) - { - float_t diffToRightDrawableSection = (patternIdxBegin == style.stipplePatternSize) ? 1.0 : styleAccessor[patternIdxBegin]; - diffToRightDrawableSection -= normalizedPlaceInPatternBegin; - float_t scrSpcOffsetToArcLen1 = diffToRightDrawableSection * patternLenInScreenSpace * ((patternIdxBegin != style.rigidSegmentIdx) ? nonRigidSegmentStretchValue : 1.0); - const float_t arcLenForT1 = 0.0 + scrSpcOffsetToArcLen1; - minDrawT = arcLenCalc.calcArcLenInverse(curve, minT, maxT, arcLenForT1, AccuracyThresholdT, 0.0); - } - - // Completely in non-draw section -> clip away: - if (minDrawT >= 1.0) - return ret; - - const float_t arcLenEnd = arcLenCalc.calcArcLen(1.0); - const float_t worldSpaceArcLenEnd = arcLenEnd * float_t(worldToScreenRatio); - float_t normalizedPlaceInPatternEnd = frac(worldSpaceArcLenEnd * reciprocalStretchedStipplePatternLen + phaseShift); - normalizedPlaceInPatternEnd = getRealNormalizedPlaceInPattern(normalizedPlaceInPatternEnd); - uint32_t patternIdxEnd = nbl::hlsl::upper_bound(styleAccessor, 0, style.stipplePatternSize, normalizedPlaceInPatternEnd); - const bool EndInNonDrawSection = patternIdxEnd & 0x1; - - if (EndInNonDrawSection) - { - float_t diffToLeftDrawableSection = (patternIdxEnd == 0) ? 0.0 : styleAccessor[patternIdxEnd - 1]; - diffToLeftDrawableSection -= normalizedPlaceInPatternEnd; - float_t scrSpcOffsetToArcLen0 = diffToLeftDrawableSection * patternLenInScreenSpace * ((patternIdxEnd != style.rigidSegmentIdx) ? nonRigidSegmentStretchValue : 1.0); - const float_t arcLenForT0 = arcLenEnd + scrSpcOffsetToArcLen0; - maxDrawT = arcLenCalc.calcArcLenInverse(curve, minT, maxT, arcLenForT0, AccuracyThresholdT, 1.0); - } - } - - if (notInDrawSection) - { - float toScreenSpaceLen = patternLenInScreenSpace * ((patternIdx != style.rigidSegmentIdx) ? nonRigidSegmentStretchValue : 1.0); - - float_t diffToLeftDrawableSection = (patternIdx == 0) ? 0.0 : styleAccessor[patternIdx - 1]; - diffToLeftDrawableSection -= normalizedPlaceInPattern; - float_t scrSpcOffsetToArcLen0 = diffToLeftDrawableSection * toScreenSpaceLen; - const float_t arcLenForT0 = arcLen + scrSpcOffsetToArcLen0; - float_t t0 = arcLenCalc.calcArcLenInverse(curve, minT, maxT, arcLenForT0, AccuracyThresholdT, t); - t0 = clamp(t0, minDrawT, maxDrawT); - - float_t diffToRightDrawableSection = (patternIdx == style.stipplePatternSize) ? 1.0 : styleAccessor[patternIdx]; - diffToRightDrawableSection -= normalizedPlaceInPattern; - float_t scrSpcOffsetToArcLen1 = diffToRightDrawableSection * toScreenSpaceLen; - const float_t arcLenForT1 = arcLen + scrSpcOffsetToArcLen1; - float_t t1 = arcLenCalc.calcArcLenInverse(curve, minT, maxT, arcLenForT1, AccuracyThresholdT, t); - t1 = clamp(t1, minDrawT, maxDrawT); - - ret = float_t2(t0, t1); - } - else - { - t = clamp(t, minDrawT, maxDrawT); - ret = float_t2(t, t); - } - - return ret; - } - - LineStyle style; - CurveType curve; - typename CurveType::ArcLengthCalculator arcLenCalc; - float phaseShift; - float stretch; - float worldToScreenRatio; - // precomp value for non uniform stretching - float rigidSegmentStart; - float rigidSegmentEnd; - float rigidSegmentLen; - float nonRigidSegmentStretchValue; -}; - -template > -struct ClippedSignedDistance -{ - using float_t = typename CurveType::scalar_t; - using float_t2 = typename CurveType::float_t2; - using float_t3 = typename CurveType::float_t3; - - const static float_t sdf(CurveType curve, float_t2 pos, float_t thickness, bool isRoadStyle, Clipper clipper = DefaultClipper::construct()) - { - typename CurveType::Candidates candidates = curve.getClosestCandidates(pos); - - const float_t InvalidT = nbl::hlsl::numeric_limits::max; - // TODO: Fix and test, we're not working with squared distance anymore - const float_t MAX_DISTANCE_SQUARED = (thickness + 1.0f) * (thickness + 1.0f); // TODO: ' + 1' is too much? - - bool clipped = false; - float_t closestDistanceSquared = MAX_DISTANCE_SQUARED; - float_t closestT = InvalidT; - [[unroll(CurveType::MaxCandidates)]] - for (uint32_t i = 0; i < CurveType::MaxCandidates; i++) - { - const float_t candidateDistanceSquared = length(curve.evaluate(candidates[i]) - pos); - if (candidateDistanceSquared < closestDistanceSquared) - { - float_t2 snappedTs = clipper(candidates[i]); - - if (snappedTs[0] == InvalidT) - { - continue; - } - - if (snappedTs[0] != candidates[i]) - { - // left snapped or clamped - const float_t leftSnappedCandidateDistanceSquared = length(curve.evaluate(snappedTs[0]) - pos); - if (leftSnappedCandidateDistanceSquared < closestDistanceSquared) - { - clipped = true; - closestT = snappedTs[0]; - closestDistanceSquared = leftSnappedCandidateDistanceSquared; - } - - if (snappedTs[0] != snappedTs[1]) - { - // right snapped or clamped - const float_t rightSnappedCandidateDistanceSquared = length(curve.evaluate(snappedTs[1]) - pos); - if (rightSnappedCandidateDistanceSquared < closestDistanceSquared) - { - clipped = true; - closestT = snappedTs[1]; - closestDistanceSquared = rightSnappedCandidateDistanceSquared; - } - } - } - else - { - // no snapping - if (candidateDistanceSquared < closestDistanceSquared) - { - clipped = false; - closestT = candidates[i]; - closestDistanceSquared = candidateDistanceSquared; - } - } - } - } - - - float_t roundedDistance = closestDistanceSquared - thickness; - if(!isRoadStyle) - { - return roundedDistance; - } - else - { - const float_t aaWidth = globals.antiAliasingFactor; - float_t rectCappedDistance = roundedDistance; - - if (clipped) - { - float_t2 q = mul(curve.getLocalCoordinateSpace(closestT), pos - curve.evaluate(closestT)); - rectCappedDistance = capSquare(q, thickness, aaWidth); - } - - return rectCappedDistance; - } - } - - static float capSquare(float_t2 q, float_t th, float_t aaWidth) - { - float_t2 d = abs(q) - float_t2(aaWidth, th); - return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); - } -}; - -// sdf of Isosceles Trapezoid y-aligned by https://iquilezles.org/articles/distfunctions2d/ -float sdTrapezoid(float2 p, float r1, float r2, float he) -{ - float2 k1 = float2(r2, he); - float2 k2 = float2(r2 - r1, 2.0 * he); - - p.x = abs(p.x); - float2 ca = float2(max(0.0, p.x - ((p.y < 0.0) ? r1 : r2)), abs(p.y) - he); - float2 cb = p - k1 + k2 * clamp(dot(k1 - p, k2) / dot(k2,k2), 0.0, 1.0); - - float s = (cb.x < 0.0 && ca.y < 0.0) ? -1.0 : 1.0; - - return s * sqrt(min(dot(ca,ca), dot(cb,cb))); -} - -// line segment sdf which returns the distance vector specialized for usage in hatch box line boundaries -float2 sdLineDstVec(float2 P, float2 A, float2 B) -{ - const float2 PA = P - A; - const float2 BA = B - A; - float h = clamp(dot(PA, BA) / dot(BA, BA), 0.0, 1.0); - return PA - BA * h; -} - -float miterSDF(float2 p, float thickness, float2 a, float2 b, float ra, float rb) -{ - float h = length(b - a) / 2.0; - float2 d = normalize(b - a); - float2x2 rot = float2x2(d.y, -d.x, d.x, d.y); - p = mul(rot, p); - p.y -= h - thickness; - return sdTrapezoid(p, ra, rb, h); -} - -typedef StyleClipper< nbl::hlsl::shapes::Quadratic > BezierStyleClipper; -typedef StyleClipper< nbl::hlsl::shapes::Line > LineStyleClipper; - -// We need to specialize color calculation based on FragmentShaderInterlock feature availability for our transparency algorithm -// because there is no `if constexpr` in hlsl -// @params -// textureColor: color sampled from a texture -// useStyleColor: instead of writing and reading from colorStorage, use main object Idx to find the style color for the object. -template -float32_t4 calculateFinalColor(const uint2 fragCoord, const float localAlpha, const uint32_t currentMainObjectIdx, float3 textureColor, bool colorFromTexture); - -template<> -float32_t4 calculateFinalColor(const uint2 fragCoord, const float localAlpha, const uint32_t currentMainObjectIdx, float3 localTextureColor, bool colorFromTexture) -{ - uint32_t styleIdx = mainObjects[currentMainObjectIdx].styleIdx; - if (!colorFromTexture) - { - float32_t4 col = lineStyles[styleIdx].color; - col.w *= localAlpha; - return float4(col); - } - else - return float4(localTextureColor, localAlpha); -} -template<> -float32_t4 calculateFinalColor(const uint2 fragCoord, const float localAlpha, const uint32_t currentMainObjectIdx, float3 localTextureColor, bool colorFromTexture) -{ - float32_t4 color; - nbl::hlsl::spirv::beginInvocationInterlockEXT(); - - const uint32_t packedData = pseudoStencil[fragCoord]; - - const uint32_t localQuantizedAlpha = (uint32_t)(localAlpha * 255.f); - const uint32_t storedQuantizedAlpha = nbl::hlsl::glsl::bitfieldExtract(packedData,0,AlphaBits); - const uint32_t storedMainObjectIdx = nbl::hlsl::glsl::bitfieldExtract(packedData,AlphaBits,MainObjectIdxBits); - // if geomID has changed, we resolve the SDF alpha (draw using blend), else accumulate - const bool differentMainObject = currentMainObjectIdx != storedMainObjectIdx; // meaning current pixel's main object is different than what is already stored - const bool resolve = differentMainObject && storedMainObjectIdx != InvalidMainObjectIdx; - uint32_t toResolveStyleIdx = InvalidStyleIdx; - - // load from colorStorage only if we want to resolve color from texture instead of style - // sampling from colorStorage needs to happen in critical section because another fragment may also want to store into it at the same time + need to happen before store - if (resolve) - { - toResolveStyleIdx = mainObjects[storedMainObjectIdx].styleIdx; - if (toResolveStyleIdx == InvalidStyleIdx) // if style idx to resolve is invalid, then it means we should resolve from color - color = float32_t4(unpackR11G11B10_UNORM(colorStorage[fragCoord]), 1.0f); - } - - // If current localAlpha is higher than what is already stored in pseudoStencil we will update the value in pseudoStencil or the color in colorStorage, this is equivalent to programmable blending MAX operation. - // OR If previous pixel has a different ID than current's (i.e. previous either empty/invalid or a differnet mainObject), we should update our alpha and color storages. - if (differentMainObject || localQuantizedAlpha > storedQuantizedAlpha) - { - pseudoStencil[fragCoord] = nbl::hlsl::glsl::bitfieldInsert(localQuantizedAlpha,currentMainObjectIdx,AlphaBits,MainObjectIdxBits); - if (colorFromTexture) // writing color from texture - colorStorage[fragCoord] = packR11G11B10_UNORM(localTextureColor); - } - - nbl::hlsl::spirv::endInvocationInterlockEXT(); - - if (!resolve) - discard; - - // draw with previous geometry's style's color or stored in texture buffer :kek: - // we don't need to load the style's color in critical section because we've already retrieved the style index from the stored main obj - if (toResolveStyleIdx != InvalidStyleIdx) // if toResolveStyleIdx is valid then that means our resolved color should come from line style - color = lineStyles[toResolveStyleIdx].color; - color.a *= float(storedQuantizedAlpha) / 255.f; - - return color; -} - -[[vk::spvexecutionmode(spv::ExecutionModePixelInterlockOrderedEXT)]] -[shader("pixel")] -float4 fragMain(PSInput input) : SV_TARGET -{ - float localAlpha = 0.0f; - float3 textureColor = float3(0, 0, 0); // color sampled from a texture - - // TODO[Przemek]: Disable All the object rendering paths if you want. - ObjectType objType = input.getObjType(); - const uint32_t currentMainObjectIdx = input.getMainObjectIdx(); - const MainObject mainObj = mainObjects[currentMainObjectIdx]; - - // figure out local alpha with sdf - if (objType == ObjectType::LINE || objType == ObjectType::QUAD_BEZIER || objType == ObjectType::POLYLINE_CONNECTOR) - { - float distance = nbl::hlsl::numeric_limits::max; - if (objType == ObjectType::LINE) - { - const float2 start = input.getLineStart(); - const float2 end = input.getLineEnd(); - const uint32_t styleIdx = mainObj.styleIdx; - const float thickness = input.getLineThickness(); - const float phaseShift = input.getCurrentPhaseShift(); - const float stretch = input.getPatternStretch(); - const float worldToScreenRatio = input.getCurrentWorldToScreenRatio(); - - nbl::hlsl::shapes::Line lineSegment = nbl::hlsl::shapes::Line::construct(start, end); - nbl::hlsl::shapes::Line::ArcLengthCalculator arcLenCalc = nbl::hlsl::shapes::Line::ArcLengthCalculator::construct(lineSegment); - - LineStyle style = lineStyles[styleIdx]; - - if (!style.hasStipples() || stretch == InvalidStyleStretchValue) - { - distance = ClippedSignedDistance< nbl::hlsl::shapes::Line >::sdf(lineSegment, input.position.xy, thickness, style.isRoadStyleFlag); - } - else - { - LineStyleClipper clipper = LineStyleClipper::construct(lineStyles[styleIdx], lineSegment, arcLenCalc, phaseShift, stretch, worldToScreenRatio); - distance = ClippedSignedDistance, LineStyleClipper>::sdf(lineSegment, input.position.xy, thickness, style.isRoadStyleFlag, clipper); - } - } - else if (objType == ObjectType::QUAD_BEZIER) - { - nbl::hlsl::shapes::Quadratic quadratic = input.getQuadratic(); - nbl::hlsl::shapes::Quadratic::ArcLengthCalculator arcLenCalc = input.getQuadraticArcLengthCalculator(); - - const uint32_t styleIdx = mainObj.styleIdx; - const float thickness = input.getLineThickness(); - const float phaseShift = input.getCurrentPhaseShift(); - const float stretch = input.getPatternStretch(); - const float worldToScreenRatio = input.getCurrentWorldToScreenRatio(); - - LineStyle style = lineStyles[styleIdx]; - if (!style.hasStipples() || stretch == InvalidStyleStretchValue) - { - distance = ClippedSignedDistance< nbl::hlsl::shapes::Quadratic >::sdf(quadratic, input.position.xy, thickness, style.isRoadStyleFlag); - } - else - { - BezierStyleClipper clipper = BezierStyleClipper::construct(lineStyles[styleIdx], quadratic, arcLenCalc, phaseShift, stretch, worldToScreenRatio); - distance = ClippedSignedDistance, BezierStyleClipper>::sdf(quadratic, input.position.xy, thickness, style.isRoadStyleFlag, clipper); - } - } - else if (objType == ObjectType::POLYLINE_CONNECTOR) - { - const float2 P = input.position.xy - input.getPolylineConnectorCircleCenter(); - distance = miterSDF( - P, - input.getLineThickness(), - input.getPolylineConnectorTrapezoidStart(), - input.getPolylineConnectorTrapezoidEnd(), - input.getPolylineConnectorTrapezoidLongBase(), - input.getPolylineConnectorTrapezoidShortBase()); - - } - localAlpha = smoothstep(+globals.antiAliasingFactor, -globals.antiAliasingFactor, distance); - } - else if (objType == ObjectType::CURVE_BOX) - { - const float minorBBoxUV = input.getMinorBBoxUV(); - const float majorBBoxUV = input.getMajorBBoxUV(); - - nbl::hlsl::math::equations::Quadratic curveMinMinor = input.getCurveMinMinor(); - nbl::hlsl::math::equations::Quadratic curveMinMajor = input.getCurveMinMajor(); - nbl::hlsl::math::equations::Quadratic curveMaxMinor = input.getCurveMaxMinor(); - nbl::hlsl::math::equations::Quadratic curveMaxMajor = input.getCurveMaxMajor(); - - // TODO(Optimization): Can we ignore this majorBBoxUV clamp and rely on the t clamp that happens next? then we can pass `PrecomputedRootFinder`s instead of computing the values per pixel. - nbl::hlsl::math::equations::Quadratic minCurveEquation = nbl::hlsl::math::equations::Quadratic::construct(curveMinMajor.a, curveMinMajor.b, curveMinMajor.c - clamp(majorBBoxUV, 0.0, 1.0)); - nbl::hlsl::math::equations::Quadratic maxCurveEquation = nbl::hlsl::math::equations::Quadratic::construct(curveMaxMajor.a, curveMaxMajor.b, curveMaxMajor.c - clamp(majorBBoxUV, 0.0, 1.0)); - - const float minT = clamp(PrecomputedRootFinder::construct(minCurveEquation).computeRoots(), 0.0, 1.0); - const float minEv = curveMinMinor.evaluate(minT); - - const float maxT = clamp(PrecomputedRootFinder::construct(maxCurveEquation).computeRoots(), 0.0, 1.0); - const float maxEv = curveMaxMinor.evaluate(maxT); - - const bool insideMajor = majorBBoxUV >= 0.0 && majorBBoxUV <= 1.0; - const bool insideMinor = minorBBoxUV >= minEv && minorBBoxUV <= maxEv; - - if (insideMinor && insideMajor) - { - localAlpha = 1.0; - } - else - { - // Find the true SDF of a hatch box boundary which is bounded by two curves, It requires knowing the distance from the current UV to the closest point on bounding curves and the limiting lines (in major direction) - // We also keep track of distance vector (minor, major) to convert to screenspace distance for anti-aliasing with screenspace aaFactor - const float InvalidT = nbl::hlsl::numeric_limits::max; - const float MAX_DISTANCE_SQUARED = nbl::hlsl::numeric_limits::max; - - const float2 boxScreenSpaceSize = input.getCurveBoxScreenSpaceSize(); - - - float closestDistanceSquared = MAX_DISTANCE_SQUARED; - const float2 pos = float2(minorBBoxUV, majorBBoxUV) * boxScreenSpaceSize; - - if (minorBBoxUV < minEv) - { - // DO SDF of Min Curve - nbl::hlsl::shapes::Quadratic minCurve = nbl::hlsl::shapes::Quadratic::construct( - float2(curveMinMinor.a, curveMinMajor.a) * boxScreenSpaceSize, - float2(curveMinMinor.b, curveMinMajor.b) * boxScreenSpaceSize, - float2(curveMinMinor.c, curveMinMajor.c) * boxScreenSpaceSize); - - nbl::hlsl::shapes::Quadratic::Candidates candidates = minCurve.getClosestCandidates(pos); - [[unroll(nbl::hlsl::shapes::Quadratic::MaxCandidates)]] - for (uint32_t i = 0; i < nbl::hlsl::shapes::Quadratic::MaxCandidates; i++) - { - candidates[i] = clamp(candidates[i], 0.0, 1.0); - const float2 distVector = minCurve.evaluate(candidates[i]) - pos; - const float candidateDistanceSquared = dot(distVector, distVector); - if (candidateDistanceSquared < closestDistanceSquared) - closestDistanceSquared = candidateDistanceSquared; - } - } - else if (minorBBoxUV > maxEv) - { - // Do SDF of Max Curve - nbl::hlsl::shapes::Quadratic maxCurve = nbl::hlsl::shapes::Quadratic::construct( - float2(curveMaxMinor.a, curveMaxMajor.a) * boxScreenSpaceSize, - float2(curveMaxMinor.b, curveMaxMajor.b) * boxScreenSpaceSize, - float2(curveMaxMinor.c, curveMaxMajor.c) * boxScreenSpaceSize); - nbl::hlsl::shapes::Quadratic::Candidates candidates = maxCurve.getClosestCandidates(pos); - [[unroll(nbl::hlsl::shapes::Quadratic::MaxCandidates)]] - for (uint32_t i = 0; i < nbl::hlsl::shapes::Quadratic::MaxCandidates; i++) - { - candidates[i] = clamp(candidates[i], 0.0, 1.0); - const float2 distVector = maxCurve.evaluate(candidates[i]) - pos; - const float candidateDistanceSquared = dot(distVector, distVector); - if (candidateDistanceSquared < closestDistanceSquared) - closestDistanceSquared = candidateDistanceSquared; - } - } - - if (!insideMajor) - { - const bool minLessThanMax = minEv < maxEv; - float2 majorDistVector = float2(MAX_DISTANCE_SQUARED, MAX_DISTANCE_SQUARED); - if (majorBBoxUV > 1.0) - { - const float2 minCurveEnd = float2(minEv, 1.0) * boxScreenSpaceSize; - if (minLessThanMax) - majorDistVector = sdLineDstVec(pos, minCurveEnd, float2(maxEv, 1.0) * boxScreenSpaceSize); - else - majorDistVector = pos - minCurveEnd; - } - else - { - const float2 minCurveStart = float2(minEv, 0.0) * boxScreenSpaceSize; - if (minLessThanMax) - majorDistVector = sdLineDstVec(pos, minCurveStart, float2(maxEv, 0.0) * boxScreenSpaceSize); - else - majorDistVector = pos - minCurveStart; - } - - const float majorDistSq = dot(majorDistVector, majorDistVector); - if (majorDistSq < closestDistanceSquared) - closestDistanceSquared = majorDistSq; - } - - const float dist = sqrt(closestDistanceSquared); - localAlpha = 1.0f - smoothstep(0.0, globals.antiAliasingFactor, dist); - } - - LineStyle style = lineStyles[mainObj.styleIdx]; - uint32_t textureId = asuint(style.screenSpaceLineWidth); - if (textureId != InvalidTextureIdx) - { - // For Hatch fiils we sample the first mip as we don't fill the others, because they are constant in screenspace and render as expected - // If later on we decided that we can have different sizes here, we should do computations similar to FONT_GLYPH - float3 msdfSample = msdfTextures.SampleLevel(msdfSampler, float3(frac(input.position.xy / HatchFillMSDFSceenSpaceSize), float(textureId)), 0.0).xyz; - float msdf = nbl::hlsl::text::msdfDistance(msdfSample, MSDFPixelRange * HatchFillMSDFSceenSpaceSize / MSDFSize); - localAlpha *= smoothstep(+globals.antiAliasingFactor / 2.0, -globals.antiAliasingFactor / 2.0f, msdf); - } - } - else if (objType == ObjectType::FONT_GLYPH) - { - const float2 uv = input.getFontGlyphUV(); - const uint32_t textureId = input.getFontGlyphTextureId(); - - if (textureId != InvalidTextureIdx) - { - float mipLevel = msdfTextures.CalculateLevelOfDetail(msdfSampler, uv); - float3 msdfSample = msdfTextures.SampleLevel(msdfSampler, float3(uv, float(textureId)), mipLevel); - float msdf = nbl::hlsl::text::msdfDistance(msdfSample, input.getFontGlyphPxRange()); - /* - explaining "*= exp2(max(mipLevel,0.0))" - Each mip level has constant MSDFPixelRange - Which essentially makes the msdfSamples here (Harware Sampled) have different scales per mip - As we go up 1 mip level, the msdf distance should be multiplied by 2.0 - While this makes total sense for NEAREST mip sampling when mipLevel is an integer and only one mip is being sampled. - It's a bit complex when it comes to trilinear filtering (LINEAR mip sampling), but it works in practice! - - Alternatively you can think of it as doing this instead: - localAlpha = smoothstep(+globals.antiAliasingFactor / exp2(max(mipLevel,0.0)), 0.0, msdf); - Which is reducing the aa feathering as we go up the mip levels. - to avoid aa feathering of the MAX_MSDF_DISTANCE_VALUE to be less than aa factor and eventually color it and cause greyed out area around the main glyph - */ - msdf *= exp2(max(mipLevel,0.0)); - - LineStyle style = lineStyles[mainObj.styleIdx]; - const float screenPxRange = input.getFontGlyphPxRange() / MSDFPixelRangeHalf; - const float bolden = style.worldSpaceLineWidth * screenPxRange; // worldSpaceLineWidth is actually boldenInPixels, aliased TextStyle with LineStyle - localAlpha = smoothstep(+globals.antiAliasingFactor / 2.0f + bolden, -globals.antiAliasingFactor / 2.0f + bolden, msdf); - } - } - else if (objType == ObjectType::IMAGE) - { - const float2 uv = input.getImageUV(); - const uint32_t textureId = input.getImageTextureId(); - - if (textureId != InvalidTextureIdx) - { - float4 colorSample = textures[NonUniformResourceIndex(textureId)].Sample(textureSampler, float2(uv.x, uv.y)); - textureColor = colorSample.rgb; - localAlpha = colorSample.a; - } - } - - uint2 fragCoord = uint2(input.position.xy); - - if (localAlpha <= 0) - discard; - - const bool colorFromTexture = objType == ObjectType::IMAGE; - - // TODO[Przemek]: But make sure you're still calling this, correctly calculating alpha and texture color. - // you can add 1 main object and push via DrawResourcesFiller like we already do for other objects (this go in the mainObjects StorageBuffer) and then set the currentMainObjectIdx to 0 here - // having 1 main object temporarily means that all triangle meshes will be treated as a unified object in blending operations. - return calculateFinalColor(fragCoord, localAlpha, currentMainObjectIdx, textureColor, colorFromTexture); -} +#define FRAGMENT_SHADER_INPUT +#include "common.hlsl" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +template +struct DefaultClipper +{ + using float_t2 = vector; + NBL_CONSTEXPR_STATIC_INLINE float_t AccuracyThresholdT = 0.0; + + static DefaultClipper construct() + { + DefaultClipper ret; + return ret; + } + + inline float_t2 operator()(const float_t t) + { + const float_t ret = clamp(t, 0.0, 1.0); + return float_t2(ret, ret); + } +}; + +// for usage in upper_bound function +struct StyleAccessor +{ + LineStyle style; + using value_type = float; + + float operator[](const uint32_t ix) + { + return style.getStippleValue(ix); + } +}; + +template +struct StyleClipper +{ + using float_t = typename CurveType::scalar_t; + using float_t2 = typename CurveType::float_t2; + using float_t3 = typename CurveType::float_t3; + NBL_CONSTEXPR_STATIC_INLINE float_t AccuracyThresholdT = 0.000001; + + static StyleClipper construct( + LineStyle style, + CurveType curve, + typename CurveType::ArcLengthCalculator arcLenCalc, + float phaseShift, + float stretch, + float worldToScreenRatio) + { + StyleClipper ret = { style, curve, arcLenCalc, phaseShift, stretch, worldToScreenRatio, 0.0f, 0.0f, 0.0f, 0.0f }; + + // values for non-uniform stretching with a rigid segment + if (style.rigidSegmentIdx != InvalidRigidSegmentIndex && stretch != 1.0f) + { + // rigidSegment info in old non stretched pattern + ret.rigidSegmentStart = (style.rigidSegmentIdx >= 1u) ? style.getStippleValue(style.rigidSegmentIdx - 1u) : 0.0f; + ret.rigidSegmentEnd = (style.rigidSegmentIdx < style.stipplePatternSize) ? style.getStippleValue(style.rigidSegmentIdx) : 1.0f; + ret.rigidSegmentLen = ret.rigidSegmentEnd - ret.rigidSegmentStart; + // stretch value for non rigid segments + ret.nonRigidSegmentStretchValue = (stretch - ret.rigidSegmentLen) / (1.0f - ret.rigidSegmentLen); + // rigidSegment info to new stretched pattern + ret.rigidSegmentStart *= ret.nonRigidSegmentStretchValue / stretch; // get the new normalized rigid segment start + ret.rigidSegmentLen /= stretch; // get the new rigid segment normalized len + ret.rigidSegmentEnd = ret.rigidSegmentStart + ret.rigidSegmentLen; // get the new normalized rigid segment end + } + else + { + ret.nonRigidSegmentStretchValue = stretch; + } + + return ret; + } + + // For non-uniform stretching with a rigid segment (the one segement that shouldn't stretch) the whole pattern changes + // instead of transforming each of the style.stipplePattern values (max 14 of them), we transform the normalized place in pattern + float getRealNormalizedPlaceInPattern(float normalizedPlaceInPattern) + { + if (style.rigidSegmentIdx != InvalidRigidSegmentIndex && stretch != 1.0f) + { + float ret = min(normalizedPlaceInPattern, rigidSegmentStart) / nonRigidSegmentStretchValue; // unstretch parts before rigid segment + ret += max(normalizedPlaceInPattern - rigidSegmentEnd, 0.0f) / nonRigidSegmentStretchValue; // unstretch parts after rigid segment + ret += max(min(rigidSegmentLen, normalizedPlaceInPattern - rigidSegmentStart), 0.0f); // unstretch parts inside rigid segment + ret *= stretch; + return ret; + } + else + { + return normalizedPlaceInPattern; + } + } + + float_t2 operator()(float_t t) + { + // basicaly 0.0 and 1.0 but with a guardband to discard outside the range + const float_t minT = 0.0 - 1.0; + const float_t maxT = 1.0 + 1.0; + + StyleAccessor styleAccessor = { style }; + const float_t reciprocalStretchedStipplePatternLen = style.reciprocalStipplePatternLen / stretch; + const float_t patternLenInScreenSpace = 1.0 / (worldToScreenRatio * style.reciprocalStipplePatternLen); + + const float_t arcLen = arcLenCalc.calcArcLen(t); + const float_t worldSpaceArcLen = arcLen * float_t(worldToScreenRatio); + float_t normalizedPlaceInPattern = frac(worldSpaceArcLen * reciprocalStretchedStipplePatternLen + phaseShift); + normalizedPlaceInPattern = getRealNormalizedPlaceInPattern(normalizedPlaceInPattern); + uint32_t patternIdx = nbl::hlsl::upper_bound(styleAccessor, 0, style.stipplePatternSize, normalizedPlaceInPattern); + + const float_t InvalidT = nbl::hlsl::numeric_limits::infinity; + float_t2 ret = float_t2(InvalidT, InvalidT); + + // odd patternIdx means a "no draw section" and current candidate should split into two nearest draw sections + const bool notInDrawSection = patternIdx & 0x1; + + // TODO[Erfan]: Disable this piece of code after clipping, and comment the reason, that the bezier start and end at 0.0 and 1.0 should be in drawable sections + float_t minDrawT = 0.0; + float_t maxDrawT = 1.0; + { + float_t normalizedPlaceInPatternBegin = frac(phaseShift); + normalizedPlaceInPatternBegin = getRealNormalizedPlaceInPattern(normalizedPlaceInPatternBegin); + uint32_t patternIdxBegin = nbl::hlsl::upper_bound(styleAccessor, 0, style.stipplePatternSize, normalizedPlaceInPatternBegin); + const bool BeginInNonDrawSection = patternIdxBegin & 0x1; + + if (BeginInNonDrawSection) + { + float_t diffToRightDrawableSection = (patternIdxBegin == style.stipplePatternSize) ? 1.0 : styleAccessor[patternIdxBegin]; + diffToRightDrawableSection -= normalizedPlaceInPatternBegin; + float_t scrSpcOffsetToArcLen1 = diffToRightDrawableSection * patternLenInScreenSpace * ((patternIdxBegin != style.rigidSegmentIdx) ? nonRigidSegmentStretchValue : 1.0); + const float_t arcLenForT1 = 0.0 + scrSpcOffsetToArcLen1; + minDrawT = arcLenCalc.calcArcLenInverse(curve, minT, maxT, arcLenForT1, AccuracyThresholdT, 0.0); + } + + // Completely in non-draw section -> clip away: + if (minDrawT >= 1.0) + return ret; + + const float_t arcLenEnd = arcLenCalc.calcArcLen(1.0); + const float_t worldSpaceArcLenEnd = arcLenEnd * float_t(worldToScreenRatio); + float_t normalizedPlaceInPatternEnd = frac(worldSpaceArcLenEnd * reciprocalStretchedStipplePatternLen + phaseShift); + normalizedPlaceInPatternEnd = getRealNormalizedPlaceInPattern(normalizedPlaceInPatternEnd); + uint32_t patternIdxEnd = nbl::hlsl::upper_bound(styleAccessor, 0, style.stipplePatternSize, normalizedPlaceInPatternEnd); + const bool EndInNonDrawSection = patternIdxEnd & 0x1; + + if (EndInNonDrawSection) + { + float_t diffToLeftDrawableSection = (patternIdxEnd == 0) ? 0.0 : styleAccessor[patternIdxEnd - 1]; + diffToLeftDrawableSection -= normalizedPlaceInPatternEnd; + float_t scrSpcOffsetToArcLen0 = diffToLeftDrawableSection * patternLenInScreenSpace * ((patternIdxEnd != style.rigidSegmentIdx) ? nonRigidSegmentStretchValue : 1.0); + const float_t arcLenForT0 = arcLenEnd + scrSpcOffsetToArcLen0; + maxDrawT = arcLenCalc.calcArcLenInverse(curve, minT, maxT, arcLenForT0, AccuracyThresholdT, 1.0); + } + } + + if (notInDrawSection) + { + float toScreenSpaceLen = patternLenInScreenSpace * ((patternIdx != style.rigidSegmentIdx) ? nonRigidSegmentStretchValue : 1.0); + + float_t diffToLeftDrawableSection = (patternIdx == 0) ? 0.0 : styleAccessor[patternIdx - 1]; + diffToLeftDrawableSection -= normalizedPlaceInPattern; + float_t scrSpcOffsetToArcLen0 = diffToLeftDrawableSection * toScreenSpaceLen; + const float_t arcLenForT0 = arcLen + scrSpcOffsetToArcLen0; + float_t t0 = arcLenCalc.calcArcLenInverse(curve, minT, maxT, arcLenForT0, AccuracyThresholdT, t); + t0 = clamp(t0, minDrawT, maxDrawT); + + float_t diffToRightDrawableSection = (patternIdx == style.stipplePatternSize) ? 1.0 : styleAccessor[patternIdx]; + diffToRightDrawableSection -= normalizedPlaceInPattern; + float_t scrSpcOffsetToArcLen1 = diffToRightDrawableSection * toScreenSpaceLen; + const float_t arcLenForT1 = arcLen + scrSpcOffsetToArcLen1; + float_t t1 = arcLenCalc.calcArcLenInverse(curve, minT, maxT, arcLenForT1, AccuracyThresholdT, t); + t1 = clamp(t1, minDrawT, maxDrawT); + + ret = float_t2(t0, t1); + } + else + { + t = clamp(t, minDrawT, maxDrawT); + ret = float_t2(t, t); + } + + return ret; + } + + LineStyle style; + CurveType curve; + typename CurveType::ArcLengthCalculator arcLenCalc; + float phaseShift; + float stretch; + float worldToScreenRatio; + // precomp value for non uniform stretching + float rigidSegmentStart; + float rigidSegmentEnd; + float rigidSegmentLen; + float nonRigidSegmentStretchValue; +}; + +template > +struct ClippedSignedDistance +{ + using float_t = typename CurveType::scalar_t; + using float_t2 = typename CurveType::float_t2; + using float_t3 = typename CurveType::float_t3; + + const static float_t sdf(CurveType curve, float_t2 pos, float_t thickness, bool isRoadStyle, Clipper clipper = DefaultClipper::construct()) + { + typename CurveType::Candidates candidates = curve.getClosestCandidates(pos); + + const float_t InvalidT = nbl::hlsl::numeric_limits::max; + // TODO: Fix and test, we're not working with squared distance anymore + const float_t MAX_DISTANCE_SQUARED = (thickness + 1.0f) * (thickness + 1.0f); // TODO: ' + 1' is too much? + + bool clipped = false; + float_t closestDistanceSquared = MAX_DISTANCE_SQUARED; + float_t closestT = InvalidT; + [[unroll(CurveType::MaxCandidates)]] + for (uint32_t i = 0; i < CurveType::MaxCandidates; i++) + { + const float_t candidateDistanceSquared = length(curve.evaluate(candidates[i]) - pos); + if (candidateDistanceSquared < closestDistanceSquared) + { + float_t2 snappedTs = clipper(candidates[i]); + + if (snappedTs[0] == InvalidT) + { + continue; + } + + if (snappedTs[0] != candidates[i]) + { + // left snapped or clamped + const float_t leftSnappedCandidateDistanceSquared = length(curve.evaluate(snappedTs[0]) - pos); + if (leftSnappedCandidateDistanceSquared < closestDistanceSquared) + { + clipped = true; + closestT = snappedTs[0]; + closestDistanceSquared = leftSnappedCandidateDistanceSquared; + } + + if (snappedTs[0] != snappedTs[1]) + { + // right snapped or clamped + const float_t rightSnappedCandidateDistanceSquared = length(curve.evaluate(snappedTs[1]) - pos); + if (rightSnappedCandidateDistanceSquared < closestDistanceSquared) + { + clipped = true; + closestT = snappedTs[1]; + closestDistanceSquared = rightSnappedCandidateDistanceSquared; + } + } + } + else + { + // no snapping + if (candidateDistanceSquared < closestDistanceSquared) + { + clipped = false; + closestT = candidates[i]; + closestDistanceSquared = candidateDistanceSquared; + } + } + } + } + + + float_t roundedDistance = closestDistanceSquared - thickness; + if(!isRoadStyle) + { + return roundedDistance; + } + else + { + const float_t aaWidth = globals.antiAliasingFactor; + float_t rectCappedDistance = roundedDistance; + + if (clipped) + { + float_t2 q = mul(curve.getLocalCoordinateSpace(closestT), pos - curve.evaluate(closestT)); + rectCappedDistance = capSquare(q, thickness, aaWidth); + } + + return rectCappedDistance; + } + } + + static float capSquare(float_t2 q, float_t th, float_t aaWidth) + { + float_t2 d = abs(q) - float_t2(aaWidth, th); + return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); + } +}; + +// sdf of Isosceles Trapezoid y-aligned by https://iquilezles.org/articles/distfunctions2d/ +float sdTrapezoid(float2 p, float r1, float r2, float he) +{ + float2 k1 = float2(r2, he); + float2 k2 = float2(r2 - r1, 2.0 * he); + + p.x = abs(p.x); + float2 ca = float2(max(0.0, p.x - ((p.y < 0.0) ? r1 : r2)), abs(p.y) - he); + float2 cb = p - k1 + k2 * clamp(dot(k1 - p, k2) / dot(k2,k2), 0.0, 1.0); + + float s = (cb.x < 0.0 && ca.y < 0.0) ? -1.0 : 1.0; + + return s * sqrt(min(dot(ca,ca), dot(cb,cb))); +} + +// line segment sdf which returns the distance vector specialized for usage in hatch box line boundaries +float2 sdLineDstVec(float2 P, float2 A, float2 B) +{ + const float2 PA = P - A; + const float2 BA = B - A; + float h = clamp(dot(PA, BA) / dot(BA, BA), 0.0, 1.0); + return PA - BA * h; +} + +float miterSDF(float2 p, float thickness, float2 a, float2 b, float ra, float rb) +{ + float h = length(b - a) / 2.0; + float2 d = normalize(b - a); + float2x2 rot = float2x2(d.y, -d.x, d.x, d.y); + p = mul(rot, p); + p.y -= h - thickness; + return sdTrapezoid(p, ra, rb, h); +} + +typedef StyleClipper< nbl::hlsl::shapes::Quadratic > BezierStyleClipper; +typedef StyleClipper< nbl::hlsl::shapes::Line > LineStyleClipper; + +// for usage in upper_bound function +struct DTMSettingsHeightsAccessor +{ + DTMSettings dtmSettings; + using value_type = float; + + float operator[](const uint32_t ix) + { + return dtmSettings.heightColorMapHeights[ix]; + } +}; + +// We need to specialize color calculation based on FragmentShaderInterlock feature availability for our transparency algorithm +// because there is no `if constexpr` in hlsl +// @params +// textureColor: color sampled from a texture +// useStyleColor: instead of writing and reading from colorStorage, use main object Idx to find the style color for the object. +template +float32_t4 calculateFinalColor(const uint2 fragCoord, const float localAlpha, const uint32_t currentMainObjectIdx, float3 textureColor, bool colorFromTexture); + +template<> +float32_t4 calculateFinalColor(const uint2 fragCoord, const float localAlpha, const uint32_t currentMainObjectIdx, float3 localTextureColor, bool colorFromTexture) +{ + uint32_t styleIdx = loadMainObject(currentMainObjectIdx).styleIdx; + if (!colorFromTexture) + { + float32_t4 col = loadLineStyle(styleIdx).color; + col.w *= localAlpha; + return float4(col); + } + else + return float4(localTextureColor, localAlpha); +} +template<> +float32_t4 calculateFinalColor(const uint2 fragCoord, const float localAlpha, const uint32_t currentMainObjectIdx, float3 localTextureColor, bool colorFromTexture) +{ + float32_t4 color; + nbl::hlsl::spirv::beginInvocationInterlockEXT(); + + const uint32_t packedData = pseudoStencil[fragCoord]; + + const uint32_t localQuantizedAlpha = (uint32_t)(localAlpha * 255.f); + const uint32_t storedQuantizedAlpha = nbl::hlsl::glsl::bitfieldExtract(packedData,0,AlphaBits); + const uint32_t storedMainObjectIdx = nbl::hlsl::glsl::bitfieldExtract(packedData,AlphaBits,MainObjectIdxBits); + // if geomID has changed, we resolve the SDF alpha (draw using blend), else accumulate + const bool differentMainObject = currentMainObjectIdx != storedMainObjectIdx; // meaning current pixel's main object is different than what is already stored + const bool resolve = differentMainObject && storedMainObjectIdx != InvalidMainObjectIdx; + uint32_t toResolveStyleIdx = InvalidStyleIdx; + + // load from colorStorage only if we want to resolve color from texture instead of style + // sampling from colorStorage needs to happen in critical section because another fragment may also want to store into it at the same time + need to happen before store + if (resolve) + { + toResolveStyleIdx = loadMainObject(storedMainObjectIdx).styleIdx; + if (toResolveStyleIdx == InvalidStyleIdx) // if style idx to resolve is invalid, then it means we should resolve from color + color = float32_t4(unpackR11G11B10_UNORM(colorStorage[fragCoord]), 1.0f); + } + + // If current localAlpha is higher than what is already stored in pseudoStencil we will update the value in pseudoStencil or the color in colorStorage, this is equivalent to programmable blending MAX operation. + // OR If previous pixel has a different ID than current's (i.e. previous either empty/invalid or a differnet mainObject), we should update our alpha and color storages. + if (differentMainObject || localQuantizedAlpha > storedQuantizedAlpha) + { + pseudoStencil[fragCoord] = nbl::hlsl::glsl::bitfieldInsert(localQuantizedAlpha,currentMainObjectIdx,AlphaBits,MainObjectIdxBits); + if (colorFromTexture) // writing color from texture + colorStorage[fragCoord] = packR11G11B10_UNORM(localTextureColor); + } + + nbl::hlsl::spirv::endInvocationInterlockEXT(); + + if (!resolve) + discard; + + // draw with previous geometry's style's color or stored in texture buffer :kek: + // we don't need to load the style's color in critical section because we've already retrieved the style index from the stored main obj + if (toResolveStyleIdx != InvalidStyleIdx) // if toResolveStyleIdx is valid then that means our resolved color should come from line style + color = loadLineStyle(toResolveStyleIdx).color; + color.a *= float(storedQuantizedAlpha) / 255.f; + + return color; +} + +float dot2(in float2 vec) +{ + return dot(vec, vec); +} + + +// TODO: Later move these functions and structs to dtmSettings.hlsl and a namespace like dtmSettings::height_shading or dtmSettings::contours, etc.. + +struct HeightSegmentTransitionData +{ + float currentHeight; + float4 currentSegmentColor; + float boundaryHeight; + float4 otherSegmentColor; +}; + +// This function interpolates between the current and nearest segment colors based on the +// screen-space distance to the segment boundary. The result is a smoothly blended color +// useful for visualizing discrete height levels without harsh edges. +float4 smoothHeightSegmentTransition(in HeightSegmentTransitionData transitionInfo, in float heightDeriv) +{ + float pxDistanceToNearestSegment = abs((transitionInfo.currentHeight - transitionInfo.boundaryHeight) / heightDeriv); + float nearestSegmentColorCoverage = smoothstep(-globals.antiAliasingFactor, globals.antiAliasingFactor, pxDistanceToNearestSegment); + float4 localHeightColor = lerp(transitionInfo.otherSegmentColor, transitionInfo.currentSegmentColor, nearestSegmentColorCoverage); + return localHeightColor; +} + +// Computes the continuous position of a height value within uniform intervals. +// flooring this value will give the interval index +// +// If `isCenteredShading` is true, the intervals are centered around `minHeight`, meaning the +// first interval spans [minHeight - intervalLength / 2.0, minHeight + intervalLength / 2.0]. +// Otherwise, intervals are aligned from `minHeight` upward, so the first interval spans +// [minHeight, minHeight + intervalLength]. +// +// Parameters: +// - height: The height value to classify. +// - minHeight: The reference starting height for interval calculation. +// - intervalLength: The length of each interval segment. +// - isCenteredShading: Whether to center the shading intervals around minHeight. +// +// Returns: +// - A float representing the continuous position within the interval grid. +float getIntervalPosition(in float height, in float minHeight, in float intervalLength, in bool isCenteredShading) +{ + if (isCenteredShading) + return ( (height - minHeight) / intervalLength + 0.5f); + else + return ( (height - minHeight) / intervalLength ); +} + +void getIntervalHeightAndColor(in int intervalIndex, in DTMSettings dtmSettings, out float4 outIntervalColor, out float outIntervalHeight) +{ + float minShadingHeight = dtmSettings.heightColorMapHeights[0]; + float heightForColor = minShadingHeight + float(intervalIndex) * dtmSettings.intervalIndexToHeightMultiplier; + + if (dtmSettings.isCenteredShading) + outIntervalHeight = minShadingHeight + (float(intervalIndex) - 0.5) * dtmSettings.intervalLength; + else + outIntervalHeight = minShadingHeight + (float(intervalIndex)) * dtmSettings.intervalLength; + + DTMSettingsHeightsAccessor dtmHeightsAccessor = { dtmSettings }; + uint32_t upperBoundHeightIndex = min(nbl::hlsl::upper_bound(dtmHeightsAccessor, 0, dtmSettings.heightColorEntryCount, heightForColor), dtmSettings.heightColorEntryCount-1u); + uint32_t lowerBoundHeightIndex = max(upperBoundHeightIndex - 1, 0); + + float upperBoundHeight = dtmSettings.heightColorMapHeights[upperBoundHeightIndex]; + float lowerBoundHeight = dtmSettings.heightColorMapHeights[lowerBoundHeightIndex]; + + float4 upperBoundColor = dtmSettings.heightColorMapColors[upperBoundHeightIndex]; + float4 lowerBoundColor = dtmSettings.heightColorMapColors[lowerBoundHeightIndex]; + + if (upperBoundHeight == lowerBoundHeight) + { + outIntervalColor = upperBoundColor; + } + else + { + float interpolationVal = (heightForColor - lowerBoundHeight) / (upperBoundHeight - lowerBoundHeight); + outIntervalColor = lerp(lowerBoundColor, upperBoundColor, interpolationVal); + } +} + +float3 calculateDTMTriangleBarycentrics(in float2 v1, in float2 v2, in float2 v3, in float2 p) +{ + float denom = (v2.x - v1.x) * (v3.y - v1.y) - (v3.x - v1.x) * (v2.y - v1.y); + float u = ((v2.y - v3.y) * (p.x - v3.x) + (v3.x - v2.x) * (p.y - v3.y)) / denom; + float v = ((v3.y - v1.y) * (p.x - v3.x) + (v1.x - v3.x) * (p.y - v3.y)) / denom; + float w = 1.0 - u - v; + return float3(u, v, w); +} + +float4 calculateDTMHeightColor(in DTMSettings dtmSettings, in float3 v[3], in float heightDeriv, in float2 fragPos, in float height) +{ + float4 outputColor = float4(0.0f, 0.0f, 0.0f, 1.0f); + + // HEIGHT SHADING + const uint32_t heightMapSize = dtmSettings.heightColorEntryCount; + float minShadingHeight = dtmSettings.heightColorMapHeights[0]; + float maxShadingHeight = dtmSettings.heightColorMapHeights[heightMapSize - 1]; + + if (heightMapSize > 0) + { + // partially based on https://www.shadertoy.com/view/XsXSz4 by Inigo Quilez + float2 e0 = v[1] - v[0]; + float2 e1 = v[2] - v[1]; + float2 e2 = v[0] - v[2]; + + float triangleAreaSign = -sign(e0.x * e2.y - e0.y * e2.x); + float2 v0 = fragPos - v[0]; + float2 v1 = fragPos - v[1]; + float2 v2 = fragPos - v[2]; + + float distanceToLine0 = sqrt(dot2(v0 - e0 * dot(v0, e0) / dot(e0, e0))); + float distanceToLine1 = sqrt(dot2(v1 - e1 * dot(v1, e1) / dot(e1, e1))); + float distanceToLine2 = sqrt(dot2(v2 - e2 * dot(v2, e2) / dot(e2, e2))); + + float line0Sdf = distanceToLine0 * triangleAreaSign * (v0.x * e0.y - v0.y * e0.x); + float line1Sdf = distanceToLine1 * triangleAreaSign * (v1.x * e1.y - v1.y * e1.x); + float line2Sdf = distanceToLine2 * triangleAreaSign * (v2.x * e2.y - v2.y * e2.x); + float line3Sdf = (minShadingHeight - height) / heightDeriv; + float line4Sdf = (height - maxShadingHeight) / heightDeriv; + + float convexPolygonSdf = max(line0Sdf, line1Sdf); + convexPolygonSdf = max(convexPolygonSdf, line2Sdf); + convexPolygonSdf = max(convexPolygonSdf, line3Sdf); + convexPolygonSdf = max(convexPolygonSdf, line4Sdf); + + // TODO: separate + outputColor.a = 1.0f - smoothstep(0.0f, globals.antiAliasingFactor * 2.0f, convexPolygonSdf); + + // calculate height color + E_HEIGHT_SHADING_MODE mode = dtmSettings.determineHeightShadingMode(); + + if (mode == E_HEIGHT_SHADING_MODE::DISCRETE_VARIABLE_LENGTH_INTERVALS) + { + DTMSettingsHeightsAccessor dtmHeightsAccessor = { dtmSettings }; + int upperBoundIndex = nbl::hlsl::upper_bound(dtmHeightsAccessor, 0, heightMapSize, height); + int mapIndex = max(upperBoundIndex - 1, 0); + int mapIndexPrev = max(mapIndex - 1, 0); + int mapIndexNext = min(mapIndex + 1, heightMapSize - 1); + + // logic explainer: if colorIdx is 0.0 then it means blend with next + // if color idx is >= length of the colours array then it means it's also > 0.0 and this blend with prev is true + // if color idx is > 0 and < len - 1, then it depends on the current pixel's height value and two closest height values + bool blendWithPrev = (mapIndex > 0) + && (mapIndex >= heightMapSize - 1 || (height * 2.0 < dtmSettings.heightColorMapHeights[upperBoundIndex] + dtmSettings.heightColorMapHeights[mapIndex])); + + HeightSegmentTransitionData transitionInfo; + transitionInfo.currentHeight = height; + transitionInfo.currentSegmentColor = dtmSettings.heightColorMapColors[mapIndex]; + transitionInfo.boundaryHeight = blendWithPrev ? dtmSettings.heightColorMapHeights[mapIndex] : dtmSettings.heightColorMapHeights[mapIndexNext]; + transitionInfo.otherSegmentColor = blendWithPrev ? dtmSettings.heightColorMapColors[mapIndexPrev] : dtmSettings.heightColorMapColors[mapIndexNext]; + + float4 localHeightColor = smoothHeightSegmentTransition(transitionInfo, heightDeriv); + outputColor.rgb = localHeightColor.rgb; + outputColor.a *= localHeightColor.a; + } + else if (mode == E_HEIGHT_SHADING_MODE::DISCRETE_FIXED_LENGTH_INTERVALS) + { + float intervalPosition = getIntervalPosition(height, minShadingHeight, dtmSettings.intervalLength, dtmSettings.isCenteredShading); + float positionWithinInterval = frac(intervalPosition); + int intervalIndex = nbl::hlsl::_static_cast(intervalPosition); + + float4 currentIntervalColor; + float currentIntervalHeight; + getIntervalHeightAndColor(intervalIndex, dtmSettings, currentIntervalColor, currentIntervalHeight); + + bool blendWithPrev = (positionWithinInterval < 0.5f); + + HeightSegmentTransitionData transitionInfo; + transitionInfo.currentHeight = height; + transitionInfo.currentSegmentColor = currentIntervalColor; + if (blendWithPrev) + { + int prevIntervalIdx = max(intervalIndex - 1, 0); + float prevIntervalHeight; // unused, the currentIntervalHeight is the boundary height between current and prev + getIntervalHeightAndColor(prevIntervalIdx, dtmSettings, transitionInfo.otherSegmentColor, prevIntervalHeight); + transitionInfo.boundaryHeight = currentIntervalHeight; + } + else + { + int nextIntervalIdx = intervalIndex + 1; + getIntervalHeightAndColor(nextIntervalIdx, dtmSettings, transitionInfo.otherSegmentColor, transitionInfo.boundaryHeight); + } + + float4 localHeightColor = smoothHeightSegmentTransition(transitionInfo, heightDeriv); + outputColor.rgb = localHeightColor.rgb; + outputColor.a *= localHeightColor.a; + } + else if (mode == E_HEIGHT_SHADING_MODE::CONTINOUS_INTERVALS) + { + DTMSettingsHeightsAccessor dtmHeightsAccessor = { dtmSettings }; + uint32_t upperBoundHeightIndex = nbl::hlsl::upper_bound(dtmHeightsAccessor, 0, heightMapSize, height); + uint32_t lowerBoundHeightIndex = upperBoundHeightIndex == 0 ? upperBoundHeightIndex : upperBoundHeightIndex - 1; + + float upperBoundHeight = dtmSettings.heightColorMapHeights[upperBoundHeightIndex]; + float lowerBoundHeight = dtmSettings.heightColorMapHeights[lowerBoundHeightIndex]; + + float4 upperBoundColor = dtmSettings.heightColorMapColors[upperBoundHeightIndex]; + float4 lowerBoundColor = dtmSettings.heightColorMapColors[lowerBoundHeightIndex]; + + float interpolationVal; + if (upperBoundHeightIndex == 0) + interpolationVal = 1.0f; + else + interpolationVal = (height - lowerBoundHeight) / (upperBoundHeight - lowerBoundHeight); + + float4 localHeightColor = lerp(lowerBoundColor, upperBoundColor, interpolationVal); + + outputColor.a *= localHeightColor.a; + outputColor.rgb = localHeightColor.rgb * outputColor.a + outputColor.rgb * (1.0f - outputColor.a); + } + } + + return outputColor; +} + +float4 calculateDTMContourColor(in DTMSettings dtmSettings, in float3 v[3], in uint2 edgePoints[3], in PSInput psInput, in float height) +{ + float4 outputColor; + + LineStyle contourStyle = loadLineStyle(dtmSettings.contourLineStyleIdx); + const float contourThickness = psInput.getContourLineThickness(); + float stretch = 1.0f; + float phaseShift = 0.0f; + const float worldToScreenRatio = psInput.getCurrentWorldToScreenRatio(); + + // TODO: move to ubo or push constants + const float startHeight = dtmSettings.contourLinesStartHeight; + const float endHeight = dtmSettings.contourLinesEndHeight; + const float interval = dtmSettings.contourLinesHeightInterval; + + // TODO: can be precomputed + const int maxContourLineIdx = (endHeight - startHeight + 1) / interval; + + // TODO: it actually can output a negative number, fix + int contourLineIdx = nbl::hlsl::_static_cast((height - startHeight + (interval * 0.5f)) / interval); + contourLineIdx = clamp(contourLineIdx, 0, maxContourLineIdx); + float contourLineHeight = startHeight + interval * contourLineIdx; + + int contourLinePointsIdx = 0; + float2 contourLinePoints[2]; + // TODO: case where heights we are looking for are on all three vertices + for (int i = 0; i < 3; ++i) + { + if (contourLinePointsIdx == 2) + break; + + const uint2 currentEdgePoints = edgePoints[i]; + float3 p0 = v[currentEdgePoints[0]]; + float3 p1 = v[currentEdgePoints[1]]; + + if (p1.z < p0.z) + nbl::hlsl::swap(p0, p1); + + float minHeight = p0.z; + float maxHeight = p1.z; + + if (height >= minHeight && height <= maxHeight) + { + float2 edge = float2(p1.x, p1.y) - float2(p0.x, p0.y); + float scale = (contourLineHeight - minHeight) / (maxHeight - minHeight); + + contourLinePoints[contourLinePointsIdx] = scale * edge + float2(p0.x, p0.y); + ++contourLinePointsIdx; + } + } + + if(contourLinePointsIdx == 2) + { + nbl::hlsl::shapes::Line lineSegment = nbl::hlsl::shapes::Line::construct(contourLinePoints[0], contourLinePoints[1]); + + float distance = nbl::hlsl::numeric_limits::max; + if (!contourStyle.hasStipples() || stretch == InvalidStyleStretchValue) + { + distance = ClippedSignedDistance< nbl::hlsl::shapes::Line >::sdf(lineSegment, psInput.position.xy, contourThickness, contourStyle.isRoadStyleFlag); + } + else + { + // TODO: + // It might be beneficial to calculate distance between pixel and contour line to early out some pixels and save yourself from stipple sdf computations! + // where you only compute the complex sdf if abs((height - contourVal) / heightDeriv) <= aaFactor + nbl::hlsl::shapes::Line::ArcLengthCalculator arcLenCalc = nbl::hlsl::shapes::Line::ArcLengthCalculator::construct(lineSegment); + LineStyleClipper clipper = LineStyleClipper::construct(contourStyle, lineSegment, arcLenCalc, phaseShift, stretch, worldToScreenRatio); + distance = ClippedSignedDistance, LineStyleClipper>::sdf(lineSegment, psInput.position.xy, contourThickness, contourStyle.isRoadStyleFlag, clipper); + } + + outputColor.a = smoothstep(+globals.antiAliasingFactor, -globals.antiAliasingFactor, distance) * contourStyle.color.a; + outputColor.rgb = contourStyle.color.rgb; + } + + return outputColor; +} + +float4 calculateDTMOutlineColor(in DTMSettings dtmSettings, in float3 v[3], in uint2 edgePoints[3], in PSInput psInput, in float3 baryCoord, in float height) +{ + float4 outputColor; + + LineStyle outlineStyle = loadLineStyle(dtmSettings.outlineLineStyleIdx); + const float outlineThickness = psInput.getOutlineThickness(); + const float phaseShift = 0.0f; // input.getCurrentPhaseShift(); + const float worldToScreenRatio = psInput.getCurrentWorldToScreenRatio(); + const float stretch = 1.0f; + + // index of vertex opposing an edge, needed for calculation of triangle heights + uint opposingVertexIdx[3]; + opposingVertexIdx[0] = 2; + opposingVertexIdx[1] = 0; + opposingVertexIdx[2] = 1; + + // find sdf of every edge + float triangleAreaTimesTwo; + { + float3 AB = v[0] - v[1]; + float3 AC = v[0] - v[2]; + AB.z = 0.0f; + AC.z = 0.0f; + + // TODO: figure out if there is a faster solution + triangleAreaTimesTwo = length(cross(AB, AC)); + } + + // calculate sdf of every edge as it wasn't stippled + float distances[3]; + for (int i = 0; i < 3; ++i) + { + const uint2 currentEdgePoints = edgePoints[i]; + float3 A = v[currentEdgePoints[0]]; + float3 B = v[currentEdgePoints[1]]; + float3 AB = B - A; + float ABLen = length(AB); + float triangleHeightToOpositeVertex = triangleAreaTimesTwo / ABLen; + + distances[i] = abs(triangleHeightToOpositeVertex * baryCoord[opposingVertexIdx[i]]); + } + + float minDistance = nbl::hlsl::numeric_limits::max; + if (!outlineStyle.hasStipples() || stretch == InvalidStyleStretchValue) + { + for (int i = 0; i < 3; ++i) + { + if (distances[i] > outlineThickness) + continue; + + const uint2 currentEdgePoints = edgePoints[i]; + float3 p0 = v[currentEdgePoints[0]]; + float3 p1 = v[currentEdgePoints[1]]; + + float distance = nbl::hlsl::numeric_limits::max; + nbl::hlsl::shapes::Line lineSegment = nbl::hlsl::shapes::Line::construct(float2(p0.x, p0.y), float2(p1.x, p1.y)); + distance = ClippedSignedDistance >::sdf(lineSegment, psInput.position.xy, outlineThickness, outlineStyle.isRoadStyleFlag); + + minDistance = min(minDistance, distance); + } + } + else + { + for (int i = 0; i < 3; ++i) + { + if (distances[i] > outlineThickness) + continue; + + const uint2 currentEdgePoints = edgePoints[i]; + float3 p0 = v[currentEdgePoints[0]]; + float3 p1 = v[currentEdgePoints[1]]; + + // long story short, in order for stipple patterns to be consistent: + // - point with lesser x coord should be starting point + // - if x coord of both points are equal then point with lesser y value should be starting point + if (p1.x < p0.x) + nbl::hlsl::swap(p0, p1); + else if (p1.x == p0.x && p1.y < p0.y) + nbl::hlsl::swap(p0, p1); + + nbl::hlsl::shapes::Line lineSegment = nbl::hlsl::shapes::Line::construct(float2(p0.x, p0.y), float2(p1.x, p1.y)); + + float distance = nbl::hlsl::numeric_limits::max; + nbl::hlsl::shapes::Line::ArcLengthCalculator arcLenCalc = nbl::hlsl::shapes::Line::ArcLengthCalculator::construct(lineSegment); + LineStyleClipper clipper = LineStyleClipper::construct(outlineStyle, lineSegment, arcLenCalc, phaseShift, stretch, worldToScreenRatio); + distance = ClippedSignedDistance, LineStyleClipper>::sdf(lineSegment, psInput.position.xy, outlineThickness, outlineStyle.isRoadStyleFlag, clipper); + + minDistance = min(minDistance, distance); + } + + } + + outputColor.a = smoothstep(+globals.antiAliasingFactor, -globals.antiAliasingFactor, minDistance) * outlineStyle.color.a; + outputColor.rgb = outlineStyle.color.rgb; + + return outputColor; +} + +float4 blendColorOnTop(in float4 colorBelow, in float4 colorAbove) +{ + float4 outputColor = colorBelow; + outputColor.rgb = colorAbove.rgb * colorAbove.a + outputColor.rgb * outputColor.a * (1.0f - colorAbove.a); + outputColor.a = colorAbove.a + outputColor.a * (1.0f - colorAbove.a); + + return outputColor; +} + +[[vk::spvexecutionmode(spv::ExecutionModePixelInterlockOrderedEXT)]] +[shader("pixel")] +float4 fragMain(PSInput input) : SV_TARGET +{ + float localAlpha = 0.0f; + float3 textureColor = float3(0, 0, 0); // color sampled from a texture + + ObjectType objType = input.getObjType(); + const uint32_t currentMainObjectIdx = input.getMainObjectIdx(); + const MainObject mainObj = loadMainObject(currentMainObjectIdx); + + if (pc.isDTMRendering) + { + DTMSettings dtmSettings = loadDTMSettings(mainObj.dtmSettingsIdx); + + float3 v[3]; + v[0] = input.getScreenSpaceVertexAttribs(0); + v[1] = input.getScreenSpaceVertexAttribs(1); + v[2] = input.getScreenSpaceVertexAttribs(2); + + // indices of points constructing every edge + uint2 edgePoints[3]; + edgePoints[0] = uint2(0, 1); + edgePoints[1] = uint2(1, 2); + edgePoints[2] = uint2(2, 0); + + const float3 baryCoord = calculateDTMTriangleBarycentrics(v[0], v[1], v[2], input.position.xy); + float height = baryCoord.x * v[0].z + baryCoord.y * v[1].z + baryCoord.z * v[2].z; + float heightDeriv = fwidth(height); + + float4 dtmColor = float4(0.0f, 0.0f, 0.0f, 0.0f); + if (dtmSettings.drawHeightShadingEnabled()) + dtmColor = blendColorOnTop(dtmColor, calculateDTMHeightColor(dtmSettings, v, heightDeriv, input.position.xy, height)); + if (dtmSettings.drawContourEnabled()) + dtmColor = blendColorOnTop(dtmColor, calculateDTMContourColor(dtmSettings, v, edgePoints, input, height)); + if (dtmSettings.drawOutlineEnabled()) + dtmColor = blendColorOnTop(dtmColor, calculateDTMOutlineColor(dtmSettings, v, edgePoints, input, baryCoord, height)); + + textureColor = dtmColor.rgb; + localAlpha = dtmColor.a; + + return calculateFinalColor(uint2(input.position.xy), localAlpha, currentMainObjectIdx, textureColor, true); + } + else + { + // figure out local alpha with sdf + if (objType == ObjectType::LINE || objType == ObjectType::QUAD_BEZIER || objType == ObjectType::POLYLINE_CONNECTOR) + { + float distance = nbl::hlsl::numeric_limits::max; + if (objType == ObjectType::LINE) + { + const float2 start = input.getLineStart(); + const float2 end = input.getLineEnd(); + const uint32_t styleIdx = mainObj.styleIdx; + const float thickness = input.getLineThickness(); + const float phaseShift = input.getCurrentPhaseShift(); + const float stretch = input.getPatternStretch(); + const float worldToScreenRatio = input.getCurrentWorldToScreenRatio(); + + nbl::hlsl::shapes::Line lineSegment = nbl::hlsl::shapes::Line::construct(start, end); + + LineStyle style = loadLineStyle(styleIdx); + + if (!style.hasStipples() || stretch == InvalidStyleStretchValue) + { + distance = ClippedSignedDistance< nbl::hlsl::shapes::Line >::sdf(lineSegment, input.position.xy, thickness, style.isRoadStyleFlag); + } + else + { + nbl::hlsl::shapes::Line::ArcLengthCalculator arcLenCalc = nbl::hlsl::shapes::Line::ArcLengthCalculator::construct(lineSegment); + LineStyleClipper clipper = LineStyleClipper::construct(loadLineStyle(styleIdx), lineSegment, arcLenCalc, phaseShift, stretch, worldToScreenRatio); + distance = ClippedSignedDistance, LineStyleClipper>::sdf(lineSegment, input.position.xy, thickness, style.isRoadStyleFlag, clipper); + } + } + else if (objType == ObjectType::QUAD_BEZIER) + { + nbl::hlsl::shapes::Quadratic quadratic = input.getQuadratic(); + nbl::hlsl::shapes::Quadratic::ArcLengthCalculator arcLenCalc = input.getQuadraticArcLengthCalculator(); + + const uint32_t styleIdx = mainObj.styleIdx; + const float thickness = input.getLineThickness(); + const float phaseShift = input.getCurrentPhaseShift(); + const float stretch = input.getPatternStretch(); + const float worldToScreenRatio = input.getCurrentWorldToScreenRatio(); + + LineStyle style = loadLineStyle(styleIdx); + if (!style.hasStipples() || stretch == InvalidStyleStretchValue) + { + distance = ClippedSignedDistance< nbl::hlsl::shapes::Quadratic >::sdf(quadratic, input.position.xy, thickness, style.isRoadStyleFlag); + } + else + { + BezierStyleClipper clipper = BezierStyleClipper::construct(loadLineStyle(styleIdx), quadratic, arcLenCalc, phaseShift, stretch, worldToScreenRatio); + distance = ClippedSignedDistance, BezierStyleClipper>::sdf(quadratic, input.position.xy, thickness, style.isRoadStyleFlag, clipper); + } + } + else if (objType == ObjectType::POLYLINE_CONNECTOR) + { + const float2 P = input.position.xy - input.getPolylineConnectorCircleCenter(); + distance = miterSDF( + P, + input.getLineThickness(), + input.getPolylineConnectorTrapezoidStart(), + input.getPolylineConnectorTrapezoidEnd(), + input.getPolylineConnectorTrapezoidLongBase(), + input.getPolylineConnectorTrapezoidShortBase()); + + } + localAlpha = smoothstep(+globals.antiAliasingFactor, -globals.antiAliasingFactor, distance); + } + else if (objType == ObjectType::CURVE_BOX) + { + const float minorBBoxUV = input.getMinorBBoxUV(); + const float majorBBoxUV = input.getMajorBBoxUV(); + + nbl::hlsl::math::equations::Quadratic curveMinMinor = input.getCurveMinMinor(); + nbl::hlsl::math::equations::Quadratic curveMinMajor = input.getCurveMinMajor(); + nbl::hlsl::math::equations::Quadratic curveMaxMinor = input.getCurveMaxMinor(); + nbl::hlsl::math::equations::Quadratic curveMaxMajor = input.getCurveMaxMajor(); + + // TODO(Optimization): Can we ignore this majorBBoxUV clamp and rely on the t clamp that happens next? then we can pass `PrecomputedRootFinder`s instead of computing the values per pixel. + nbl::hlsl::math::equations::Quadratic minCurveEquation = nbl::hlsl::math::equations::Quadratic::construct(curveMinMajor.a, curveMinMajor.b, curveMinMajor.c - clamp(majorBBoxUV, 0.0, 1.0)); + nbl::hlsl::math::equations::Quadratic maxCurveEquation = nbl::hlsl::math::equations::Quadratic::construct(curveMaxMajor.a, curveMaxMajor.b, curveMaxMajor.c - clamp(majorBBoxUV, 0.0, 1.0)); + + const float minT = clamp(PrecomputedRootFinder::construct(minCurveEquation).computeRoots(), 0.0, 1.0); + const float minEv = curveMinMinor.evaluate(minT); + + const float maxT = clamp(PrecomputedRootFinder::construct(maxCurveEquation).computeRoots(), 0.0, 1.0); + const float maxEv = curveMaxMinor.evaluate(maxT); + + const bool insideMajor = majorBBoxUV >= 0.0 && majorBBoxUV <= 1.0; + const bool insideMinor = minorBBoxUV >= minEv && minorBBoxUV <= maxEv; + + if (insideMinor && insideMajor) + { + localAlpha = 1.0; + } + else + { + // Find the true SDF of a hatch box boundary which is bounded by two curves, It requires knowing the distance from the current UV to the closest point on bounding curves and the limiting lines (in major direction) + // We also keep track of distance vector (minor, major) to convert to screenspace distance for anti-aliasing with screenspace aaFactor + const float InvalidT = nbl::hlsl::numeric_limits::max; + const float MAX_DISTANCE_SQUARED = nbl::hlsl::numeric_limits::max; + + const float2 boxScreenSpaceSize = input.getCurveBoxScreenSpaceSize(); + + + float closestDistanceSquared = MAX_DISTANCE_SQUARED; + const float2 pos = float2(minorBBoxUV, majorBBoxUV) * boxScreenSpaceSize; + + if (minorBBoxUV < minEv) + { + // DO SDF of Min Curve + nbl::hlsl::shapes::Quadratic minCurve = nbl::hlsl::shapes::Quadratic::construct( + float2(curveMinMinor.a, curveMinMajor.a) * boxScreenSpaceSize, + float2(curveMinMinor.b, curveMinMajor.b) * boxScreenSpaceSize, + float2(curveMinMinor.c, curveMinMajor.c) * boxScreenSpaceSize); + + nbl::hlsl::shapes::Quadratic::Candidates candidates = minCurve.getClosestCandidates(pos); + [[unroll(nbl::hlsl::shapes::Quadratic::MaxCandidates)]] + for (uint32_t i = 0; i < nbl::hlsl::shapes::Quadratic::MaxCandidates; i++) + { + candidates[i] = clamp(candidates[i], 0.0, 1.0); + const float2 distVector = minCurve.evaluate(candidates[i]) - pos; + const float candidateDistanceSquared = dot(distVector, distVector); + if (candidateDistanceSquared < closestDistanceSquared) + closestDistanceSquared = candidateDistanceSquared; + } + } + else if (minorBBoxUV > maxEv) + { + // Do SDF of Max Curve + nbl::hlsl::shapes::Quadratic maxCurve = nbl::hlsl::shapes::Quadratic::construct( + float2(curveMaxMinor.a, curveMaxMajor.a) * boxScreenSpaceSize, + float2(curveMaxMinor.b, curveMaxMajor.b) * boxScreenSpaceSize, + float2(curveMaxMinor.c, curveMaxMajor.c) * boxScreenSpaceSize); + nbl::hlsl::shapes::Quadratic::Candidates candidates = maxCurve.getClosestCandidates(pos); + [[unroll(nbl::hlsl::shapes::Quadratic::MaxCandidates)]] + for (uint32_t i = 0; i < nbl::hlsl::shapes::Quadratic::MaxCandidates; i++) + { + candidates[i] = clamp(candidates[i], 0.0, 1.0); + const float2 distVector = maxCurve.evaluate(candidates[i]) - pos; + const float candidateDistanceSquared = dot(distVector, distVector); + if (candidateDistanceSquared < closestDistanceSquared) + closestDistanceSquared = candidateDistanceSquared; + } + } + + if (!insideMajor) + { + const bool minLessThanMax = minEv < maxEv; + float2 majorDistVector = float2(MAX_DISTANCE_SQUARED, MAX_DISTANCE_SQUARED); + if (majorBBoxUV > 1.0) + { + const float2 minCurveEnd = float2(minEv, 1.0) * boxScreenSpaceSize; + if (minLessThanMax) + majorDistVector = sdLineDstVec(pos, minCurveEnd, float2(maxEv, 1.0) * boxScreenSpaceSize); + else + majorDistVector = pos - minCurveEnd; + } + else + { + const float2 minCurveStart = float2(minEv, 0.0) * boxScreenSpaceSize; + if (minLessThanMax) + majorDistVector = sdLineDstVec(pos, minCurveStart, float2(maxEv, 0.0) * boxScreenSpaceSize); + else + majorDistVector = pos - minCurveStart; + } + + const float majorDistSq = dot(majorDistVector, majorDistVector); + if (majorDistSq < closestDistanceSquared) + closestDistanceSquared = majorDistSq; + } + + const float dist = sqrt(closestDistanceSquared); + localAlpha = 1.0f - smoothstep(0.0, globals.antiAliasingFactor, dist); + } + + LineStyle style = loadLineStyle(mainObj.styleIdx); + uint32_t textureId = asuint(style.screenSpaceLineWidth); + if (textureId != InvalidTextureIdx) + { + // For Hatch fiils we sample the first mip as we don't fill the others, because they are constant in screenspace and render as expected + // If later on we decided that we can have different sizes here, we should do computations similar to FONT_GLYPH + float3 msdfSample = msdfTextures.SampleLevel(msdfSampler, float3(frac(input.position.xy / HatchFillMSDFSceenSpaceSize), float(textureId)), 0.0).xyz; + float msdf = nbl::hlsl::text::msdfDistance(msdfSample, MSDFPixelRange * HatchFillMSDFSceenSpaceSize / MSDFSize); + localAlpha *= smoothstep(+globals.antiAliasingFactor / 2.0, -globals.antiAliasingFactor / 2.0f, msdf); + } + } + else if (objType == ObjectType::FONT_GLYPH) + { + const float2 uv = input.getFontGlyphUV(); + const uint32_t textureId = input.getFontGlyphTextureId(); + + if (textureId != InvalidTextureIdx) + { + float mipLevel = msdfTextures.CalculateLevelOfDetail(msdfSampler, uv); + float3 msdfSample = msdfTextures.SampleLevel(msdfSampler, float3(uv, float(textureId)), mipLevel); + float msdf = nbl::hlsl::text::msdfDistance(msdfSample, input.getFontGlyphPxRange()); + /* + explaining "*= exp2(max(mipLevel,0.0))" + Each mip level has constant MSDFPixelRange + Which essentially makes the msdfSamples here (Harware Sampled) have different scales per mip + As we go up 1 mip level, the msdf distance should be multiplied by 2.0 + While this makes total sense for NEAREST mip sampling when mipLevel is an integer and only one mip is being sampled. + It's a bit complex when it comes to trilinear filtering (LINEAR mip sampling), but it works in practice! + + Alternatively you can think of it as doing this instead: + localAlpha = smoothstep(+globals.antiAliasingFactor / exp2(max(mipLevel,0.0)), 0.0, msdf); + Which is reducing the aa feathering as we go up the mip levels. + to avoid aa feathering of the MAX_MSDF_DISTANCE_VALUE to be less than aa factor and eventually color it and cause greyed out area around the main glyph + */ + msdf *= exp2(max(mipLevel,0.0)); + + LineStyle style = loadLineStyle(mainObj.styleIdx); + const float screenPxRange = input.getFontGlyphPxRange() / MSDFPixelRangeHalf; + const float bolden = style.worldSpaceLineWidth * screenPxRange; // worldSpaceLineWidth is actually boldenInPixels, aliased TextStyle with LineStyle + localAlpha = smoothstep(+globals.antiAliasingFactor / 2.0f + bolden, -globals.antiAliasingFactor / 2.0f + bolden, msdf); + } + } + else if (objType == ObjectType::IMAGE) + { + const float2 uv = input.getImageUV(); + const uint32_t textureId = input.getImageTextureId(); + + if (textureId != InvalidTextureIdx) + { + float4 colorSample = textures[NonUniformResourceIndex(textureId)].Sample(textureSampler, float2(uv.x, uv.y)); + textureColor = colorSample.rgb; + localAlpha = colorSample.a; + } + } + + uint2 fragCoord = uint2(input.position.xy); + + if (localAlpha <= 0) + discard; + + const bool colorFromTexture = objType == ObjectType::IMAGE; + + // TODO[Przemek]: But make sure you're still calling this, correctly calculating alpha and texture color. + // you can add 1 main object and push via DrawResourcesFiller like we already do for other objects (this go in the mainObjects StorageBuffer) and then set the currentMainObjectIdx to 0 here + // having 1 main object temporarily means that all triangle meshes will be treated as a unified object in blending operations. + return calculateFinalColor(fragCoord, localAlpha, currentMainObjectIdx, textureColor, colorFromTexture); + } +} diff --git a/62_CAD/shaders/main_pipeline/resolve_alphas.hlsl b/62_CAD/shaders/main_pipeline/resolve_alphas.hlsl index 46c5d28e0..987dd7c29 100644 --- a/62_CAD/shaders/main_pipeline/resolve_alphas.hlsl +++ b/62_CAD/shaders/main_pipeline/resolve_alphas.hlsl @@ -16,26 +16,44 @@ template<> float32_t4 calculateFinalColor(const uint2 fragCoord) { float32_t4 color; - - nbl::hlsl::spirv::beginInvocationInterlockEXT(); + nbl::hlsl::spirv::beginInvocationInterlockEXT(); + + bool resolve = false; + uint32_t toResolveStyleIdx = InvalidStyleIdx; const uint32_t packedData = pseudoStencil[fragCoord]; const uint32_t storedQuantizedAlpha = nbl::hlsl::glsl::bitfieldExtract(packedData,0,AlphaBits); const uint32_t storedMainObjectIdx = nbl::hlsl::glsl::bitfieldExtract(packedData,AlphaBits,MainObjectIdxBits); - pseudoStencil[fragCoord] = nbl::hlsl::glsl::bitfieldInsert(0, InvalidMainObjectIdx, AlphaBits, MainObjectIdxBits); - // if geomID has changed, we resolve the SDF alpha (draw using blend), else accumulate - const bool resolve = storedMainObjectIdx != InvalidMainObjectIdx; - uint32_t toResolveStyleIdx = InvalidStyleIdx; + const bool currentlyActiveMainObj = (storedMainObjectIdx == globals.currentlyActiveMainObjectIndex); + if (!currentlyActiveMainObj) + { + // Normal Scenario, this branch will always be taken if there is no overflow submit in the middle of an active mainObject + //we do the final resolve of the pixel and invalidate the pseudo-stencil + pseudoStencil[fragCoord] = nbl::hlsl::glsl::bitfieldInsert(0, InvalidMainObjectIdx, AlphaBits, MainObjectIdxBits); + + // if geomID has changed, we resolve the SDF alpha (draw using blend), else accumulate + resolve = storedMainObjectIdx != InvalidMainObjectIdx; - // load from colorStorage only if we want to resolve color from texture instead of style - // sampling from colorStorage needs to happen in critical section because another fragment may also want to store into it at the same time + need to happen before store - if (resolve) + // load from colorStorage only if we want to resolve color from texture instead of style + // sampling from colorStorage needs to happen in critical section because another fragment may also want to store into it at the same time + need to happen before store + if (resolve) + { + toResolveStyleIdx = loadMainObject(storedMainObjectIdx).styleIdx; + if (toResolveStyleIdx == InvalidStyleIdx) // if style idx to resolve is invalid, then it means we should resolve from color + color = float32_t4(unpackR11G11B10_UNORM(colorStorage[fragCoord]), 1.0f); + } + } + else if (globals.currentlyActiveMainObjectIndex != InvalidMainObjectIdx) { - toResolveStyleIdx = mainObjects[storedMainObjectIdx].styleIdx; - if (toResolveStyleIdx == InvalidStyleIdx) // if style idx to resolve is invalid, then it means we should resolve from color - color = float32_t4(unpackR11G11B10_UNORM(colorStorage[fragCoord]), 1.0f); + // Being here means there was an overflow submit in the middle of an active main objejct + // We don't want to resolve the active mainObj, because it needs to fully resolved later when the mainObject actually finishes. + // We change the active main object index in our pseudo-stencil to 0u, because that will be it's new index in the next submit. + uint32_t newMainObjectIdx = 0u; + pseudoStencil[fragCoord] = nbl::hlsl::glsl::bitfieldInsert(storedQuantizedAlpha, newMainObjectIdx, AlphaBits, MainObjectIdxBits); + resolve = false; // just to re-iterate that we don't want to resolve this. } + nbl::hlsl::spirv::endInvocationInterlockEXT(); @@ -45,7 +63,7 @@ float32_t4 calculateFinalColor(const uint2 fragCoord) // draw with previous geometry's style's color or stored in texture buffer :kek: // we don't need to load the style's color in critical section because we've already retrieved the style index from the stored main obj if (toResolveStyleIdx != InvalidStyleIdx) // if toResolveStyleIdx is valid then that means our resolved color should come from line style - color = lineStyles[toResolveStyleIdx].color; + color = loadLineStyle(toResolveStyleIdx).color; color.a *= float(storedQuantizedAlpha) / 255.f; return color; diff --git a/62_CAD/shaders/main_pipeline/vertex_shader.hlsl b/62_CAD/shaders/main_pipeline/vertex_shader.hlsl index bff4182f6..f726104b5 100644 --- a/62_CAD/shaders/main_pipeline/vertex_shader.hlsl +++ b/62_CAD/shaders/main_pipeline/vertex_shader.hlsl @@ -25,19 +25,10 @@ float2 QuadraticBezier(float2 p0, float2 p1, float2 p2, float t) ClipProjectionData getClipProjectionData(in MainObject mainObj) { - if (mainObj.clipProjectionAddress != InvalidClipProjectionAddress) - { - ClipProjectionData ret; - ret.projectionToNDC = vk::RawBufferLoad(mainObj.clipProjectionAddress, 8u); - ret.minClipNDC = vk::RawBufferLoad(mainObj.clipProjectionAddress + sizeof(pfloat64_t3x3), 8u); - ret.maxClipNDC = vk::RawBufferLoad(mainObj.clipProjectionAddress + sizeof(pfloat64_t3x3) + sizeof(float32_t2), 8u); - - return ret; - } + if (mainObj.clipProjectionIndex != InvalidClipProjectionIndex) + return loadCustomClipProjection(mainObj.clipProjectionIndex); else - { return globals.defaultClipProjection; - } } float2 transformPointScreenSpace(pfloat64_t3x3 transformation, uint32_t2 resolution, pfloat64_t2 point2d) @@ -91,14 +82,10 @@ PSInput main(uint vertexID : SV_VertexID) // your programmable pulling will use the baseVertexBufferAddress BDA address and `vertexID` to RawBufferLoad it's vertex. // ~~Later, most likely We will require pulling all 3 vertices of the triangle, that's where you need to know which triangle you're currently on, and instead of objectID = vertexID/4 which we currently do, you will do vertexID/3 and pull all 3 of it's vertices.~~ // Ok, brainfart, a vertex can belong to multiple triangles, I was thinking of AA but triangles share vertices, nevermind my comment above. + - const uint vertexIdx = vertexID & 0x3u; - const uint objectID = vertexID >> 2; - - DrawObject drawObj = drawObjects[objectID]; - - ObjectType objType = (ObjectType)(drawObj.type_subsectionIdx & 0x0000FFFF); - uint32_t subsectionIdx = drawObj.type_subsectionIdx >> 16; + ClipProjectionData clipProjectionData; + PSInput outV; // Default Initialize PS Input @@ -108,485 +95,567 @@ PSInput main(uint vertexID : SV_VertexID) outV.data3 = float4(0, 0, 0, 0); outV.data4 = float4(0, 0, 0, 0); outV.interp_data5 = float2(0, 0); - outV.setObjType(objType); - outV.setMainObjectIdx(drawObj.mainObjIndex); - - MainObject mainObj = mainObjects[drawObj.mainObjIndex]; - ClipProjectionData clipProjectionData = getClipProjectionData(mainObj); - // We only need these for Outline type objects like lines and bezier curves - if (objType == ObjectType::LINE || objType == ObjectType::QUAD_BEZIER || objType == ObjectType::POLYLINE_CONNECTOR) + if (pc.isDTMRendering) { - LineStyle lineStyle = lineStyles[mainObj.styleIdx]; + outV.setObjType(ObjectType::TRIANGLE_MESH); + outV.setMainObjectIdx(pc.triangleMeshMainObjectIndex); + + TriangleMeshVertex vtx = vk::RawBufferLoad(pc.triangleMeshVerticesBaseAddress + sizeof(TriangleMeshVertex) * vertexID, 8u); - // Width is on both sides, thickness is one one side of the curve (div by 2.0f) - const float screenSpaceLineWidth = lineStyle.screenSpaceLineWidth + _static_cast(_static_cast(lineStyle.worldSpaceLineWidth) * globals.screenToWorldRatio); - const float antiAliasedLineThickness = screenSpaceLineWidth * 0.5f + globals.antiAliasingFactor; - const float sdfLineThickness = screenSpaceLineWidth / 2.0f; - outV.setLineThickness(sdfLineThickness); - outV.setCurrentWorldToScreenRatio( - _static_cast((_static_cast(2.0f) / - (clipProjectionData.projectionToNDC[0].x * _static_cast(globals.resolution.x)))) - ); + MainObject mainObj = loadMainObject(pc.triangleMeshMainObjectIndex); + clipProjectionData = getClipProjectionData(mainObj); - if (objType == ObjectType::LINE) + // assuming there are 3 * N vertices, number of vertices is equal to number of indices and indices are sequential starting from 0 + float2 transformedOriginalPos; + float2 transformedDilatedPos; { - pfloat64_t2 points[2u]; - points[0u] = vk::RawBufferLoad(drawObj.geometryAddress, 8u); - points[1u] = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(LinePointInfo), 8u); + uint32_t firstVertexOfCurrentTriangleIndex = vertexID - vertexID % 3; + uint32_t currentVertexWithinTriangleIndex = vertexID - firstVertexOfCurrentTriangleIndex; - const float phaseShift = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2), 8u); - const float patternStretch = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float), 8u); - outV.setCurrentPhaseShift(phaseShift); - outV.setPatternStretch(patternStretch); + TriangleMeshVertex triangleVertices[3]; + triangleVertices[0] = vk::RawBufferLoad(pc.triangleMeshVerticesBaseAddress + sizeof(TriangleMeshVertex) * firstVertexOfCurrentTriangleIndex, 8u); + triangleVertices[1] = vk::RawBufferLoad(pc.triangleMeshVerticesBaseAddress + sizeof(TriangleMeshVertex) * (firstVertexOfCurrentTriangleIndex + 1), 8u); + triangleVertices[2] = vk::RawBufferLoad(pc.triangleMeshVerticesBaseAddress + sizeof(TriangleMeshVertex) * (firstVertexOfCurrentTriangleIndex + 2), 8u); + transformedOriginalPos = transformPointScreenSpace(clipProjectionData.projectionToNDC, globals.resolution, triangleVertices[currentVertexWithinTriangleIndex].pos); - float2 transformedPoints[2u]; - for (uint i = 0u; i < 2u; ++i) - { - transformedPoints[i] = transformPointScreenSpace(clipProjectionData.projectionToNDC, globals.resolution, points[i]); - } + pfloat64_t2 triangleCentroid; + triangleCentroid.x = (triangleVertices[0].pos.x + triangleVertices[1].pos.x + triangleVertices[2].pos.x) / _static_cast(3.0f); + triangleCentroid.y = (triangleVertices[0].pos.y + triangleVertices[1].pos.y + triangleVertices[2].pos.y) / _static_cast(3.0f); - const float2 lineVector = normalize(transformedPoints[1u] - transformedPoints[0u]); - const float2 normalToLine = float2(-lineVector.y, lineVector.x); + // move triangles to local space, with centroid at (0, 0) + triangleVertices[0].pos = triangleVertices[0].pos - triangleCentroid; + triangleVertices[1].pos = triangleVertices[1].pos - triangleCentroid; + triangleVertices[2].pos = triangleVertices[2].pos - triangleCentroid; - if (vertexIdx == 0u || vertexIdx == 1u) - { - // work in screen space coordinates because of fixed pixel size - outV.position.xy = transformedPoints[0u] - + normalToLine * (((float)vertexIdx - 0.5f) * 2.0f * antiAliasedLineThickness) - - lineVector * antiAliasedLineThickness; - } - else // if (vertexIdx == 2u || vertexIdx == 3u) - { - // work in screen space coordinates because of fixed pixel size - outV.position.xy = transformedPoints[1u] - + normalToLine * (((float)vertexIdx - 2.5f) * 2.0f * antiAliasedLineThickness) - + lineVector * antiAliasedLineThickness; - } + // TODO: calculate dialation factor + pfloat64_t dialationFactor = _static_cast(2.0f); + pfloat64_t2 dialatedVertex = triangleVertices[currentVertexWithinTriangleIndex].pos * dialationFactor; - outV.setLineStart(transformedPoints[0u]); - outV.setLineEnd(transformedPoints[1u]); + dialatedVertex = dialatedVertex + triangleCentroid; - outV.position.xy = transformFromSreenSpaceToNdc(outV.position.xy, globals.resolution).xy; + transformedDilatedPos = transformPointScreenSpace(clipProjectionData.projectionToNDC, globals.resolution, dialatedVertex); } - else if (objType == ObjectType::QUAD_BEZIER) + + outV.position = transformFromSreenSpaceToNdc(transformedDilatedPos, globals.resolution); + const float heightAsFloat = nbl::hlsl::_static_cast(vtx.height); + outV.setHeight(heightAsFloat); + outV.setScreenSpaceVertexAttribs(float3(transformedOriginalPos, heightAsFloat)); + outV.setCurrentWorldToScreenRatio( + _static_cast((_static_cast(2.0f) / + (clipProjectionData.projectionToNDC[0].x * _static_cast(globals.resolution.x)))) + ); + + DTMSettings dtm = loadDTMSettings(mainObj.dtmSettingsIdx); + LineStyle outlineStyle = loadLineStyle(dtm.outlineLineStyleIdx); + LineStyle contourStyle = loadLineStyle(dtm.contourLineStyleIdx); + // TODO: maybe move to fragment shader since we may have multiple contour styles later + const float screenSpaceOutlineWidth = outlineStyle.screenSpaceLineWidth + _static_cast(_static_cast(outlineStyle.worldSpaceLineWidth) * globals.screenToWorldRatio); + const float sdfOutlineThickness = screenSpaceOutlineWidth * 0.5f; + const float screenSpaceContourLineWidth = contourStyle.screenSpaceLineWidth + _static_cast(_static_cast(contourStyle.worldSpaceLineWidth) * globals.screenToWorldRatio); + const float sdfContourLineThickness = screenSpaceContourLineWidth * 0.5f; + outV.setOutlineThickness(sdfOutlineThickness); + outV.setContourLineThickness(sdfContourLineThickness); + + // full screen triangle (this will destroy outline, contour line and height drawing) +#if 0 + const uint vertexIdx = vertexID % 3; + if(vertexIdx == 0) + outV.position.xy = float2(-1.0f, -1.0f); + else if (vertexIdx == 1) + outV.position.xy = float2(-1.0f, 3.0f); + else if (vertexIdx == 2) + outV.position.xy = float2(3.0f, -1.0f); +#endif + } + else + { + const uint vertexIdx = vertexID & 0x3u; + const uint objectID = vertexID >> 2; + + DrawObject drawObj = loadDrawObject(objectID); + + ObjectType objType = (ObjectType)(drawObj.type_subsectionIdx & 0x0000FFFF); + uint32_t subsectionIdx = drawObj.type_subsectionIdx >> 16; + outV.setObjType(objType); + outV.setMainObjectIdx(drawObj.mainObjIndex); + + + MainObject mainObj = loadMainObject(drawObj.mainObjIndex); + clipProjectionData = getClipProjectionData(mainObj); + + // We only need these for Outline type objects like lines and bezier curves + if (objType == ObjectType::LINE || objType == ObjectType::QUAD_BEZIER || objType == ObjectType::POLYLINE_CONNECTOR) { - pfloat64_t2 points[3u]; - points[0u] = vk::RawBufferLoad(drawObj.geometryAddress, 8u); - points[1u] = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2), 8u); - points[2u] = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) * 2u, 8u); - - const float phaseShift = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) * 3u, 8u); - const float patternStretch = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) * 3u + sizeof(float), 8u); - outV.setCurrentPhaseShift(phaseShift); - outV.setPatternStretch(patternStretch); - - // transform these points into screen space and pass to fragment - float2 transformedPoints[3u]; - for (uint i = 0u; i < 3u; ++i) + LineStyle lineStyle = loadLineStyle(mainObj.styleIdx); + + // Width is on both sides, thickness is one one side of the curve (div by 2.0f) + const float screenSpaceLineWidth = lineStyle.screenSpaceLineWidth + _static_cast(_static_cast(lineStyle.worldSpaceLineWidth) * globals.screenToWorldRatio); + const float antiAliasedLineThickness = screenSpaceLineWidth * 0.5f + globals.antiAliasingFactor; + const float sdfLineThickness = screenSpaceLineWidth / 2.0f; + outV.setLineThickness(sdfLineThickness); + outV.setCurrentWorldToScreenRatio( + _static_cast((_static_cast(2.0f) / + (clipProjectionData.projectionToNDC[0].x * _static_cast(globals.resolution.x)))) + ); + + if (objType == ObjectType::LINE) { - transformedPoints[i] = transformPointScreenSpace(clipProjectionData.projectionToNDC, globals.resolution, points[i]); - } + pfloat64_t2 points[2u]; + points[0u] = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress, 8u); + points[1u] = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(LinePointInfo), 8u); - shapes::QuadraticBezier quadraticBezier = shapes::QuadraticBezier::construct(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u]); - shapes::Quadratic quadratic = shapes::Quadratic::constructFromBezier(quadraticBezier); - shapes::Quadratic::ArcLengthCalculator preCompData = shapes::Quadratic::ArcLengthCalculator::construct(quadratic); - - outV.setQuadratic(quadratic); - outV.setQuadraticPrecomputedArcLenData(preCompData); - - float2 Mid = (transformedPoints[0u] + transformedPoints[2u]) / 2.0f; - float Radius = length(Mid - transformedPoints[0u]) / 2.0f; - - // https://algorithmist.wordpress.com/2010/12/01/quad-bezier-curvature/ - float2 vectorAB = transformedPoints[1u] - transformedPoints[0u]; - float2 vectorAC = transformedPoints[2u] - transformedPoints[1u]; - float area = abs(vectorAB.x * vectorAC.y - vectorAB.y * vectorAC.x) * 0.5; - float MaxCurvature; - if (length(transformedPoints[1u] - lerp(transformedPoints[0u], transformedPoints[2u], 0.25f)) > Radius && length(transformedPoints[1u] - lerp(transformedPoints[0u], transformedPoints[2u], 0.75f)) > Radius) - MaxCurvature = pow(length(transformedPoints[1u] - Mid), 3) / (area * area); - else - MaxCurvature = max(area / pow(length(transformedPoints[0u] - transformedPoints[1u]), 3), area / pow(length(transformedPoints[2u] - transformedPoints[1u]), 3)); - - // We only do this adaptive thing when "MinRadiusOfOsculatingCircle = RadiusOfMaxCurvature < screenSpaceLineWidth/4" OR "MaxCurvature > 4/screenSpaceLineWidth"; - // which means there is a self intersection because of large lineWidth relative to the curvature (in screenspace) - // the reason for division by 4.0f is 1. screenSpaceLineWidth is expanded on both sides and 2. the fact that diameter/2=radius, - const bool noCurvature = abs(dot(normalize(vectorAB), normalize(vectorAC)) - 1.0f) < exp2(-10.0f); - if (MaxCurvature * screenSpaceLineWidth > 4.0f || noCurvature) - { - //OBB Fallback - float2 obbV0; - float2 obbV1; - float2 obbV2; - float2 obbV3; - quadraticBezier.computeOBB(antiAliasedLineThickness, obbV0, obbV1, obbV2, obbV3); - if (subsectionIdx == 0) + const float phaseShift = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2), 8u); + const float patternStretch = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float), 8u); + outV.setCurrentPhaseShift(phaseShift); + outV.setPatternStretch(patternStretch); + + float2 transformedPoints[2u]; + for (uint i = 0u; i < 2u; ++i) { - if (vertexIdx == 0u) - outV.position = float4(obbV0, 0.0, 1.0f); - else if (vertexIdx == 1u) - outV.position = float4(obbV1, 0.0, 1.0f); - else if (vertexIdx == 2u) - outV.position = float4(obbV3, 0.0, 1.0f); - else if (vertexIdx == 3u) - outV.position = float4(obbV2, 0.0, 1.0f); + transformedPoints[i] = transformPointScreenSpace(clipProjectionData.projectionToNDC, globals.resolution, points[i]); } - else - outV.position = float4(0.0f, 0.0f, 0.0f, 0.0f); - } - else - { - // this optimal value is hardcoded based on tests and benchmarks of pixel shader invocation - // this is the place where we use it's tangent in the bezier to form sides the cages - const float optimalT = 0.145f; - - // Whether or not to flip the the interior cage nodes - int flip = cross2D(transformedPoints[0u] - transformedPoints[1u], transformedPoints[2u] - transformedPoints[1u]) > 0.0f ? -1 : 1; - const float middleT = 0.5f; - float2 midPos = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], middleT); - float2 midTangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], middleT)); - float2 midNormal = float2(-midTangent.y, midTangent.x) * flip; - - /* - P1 - + + const float2 lineVector = normalize(transformedPoints[1u] - transformedPoints[0u]); + const float2 normalToLine = float2(-lineVector.y, lineVector.x); + if (vertexIdx == 0u || vertexIdx == 1u) + { + // work in screen space coordinates because of fixed pixel size + outV.position.xy = transformedPoints[0u] + + normalToLine * (((float)vertexIdx - 0.5f) * 2.0f * antiAliasedLineThickness) + - lineVector * antiAliasedLineThickness; + } + else // if (vertexIdx == 2u || vertexIdx == 3u) + { + // work in screen space coordinates because of fixed pixel size + outV.position.xy = transformedPoints[1u] + + normalToLine * (((float)vertexIdx - 2.5f) * 2.0f * antiAliasedLineThickness) + + lineVector * antiAliasedLineThickness; + } - exterior0 exterior1 - ---------------------- - / \- - -/ ---------------- \ - / -/interior0 interior1 - / / \ \- - -/ -/ \- \ - / -/ \ \- - / / \- \ - P0 + \ + P2 - */ + outV.setLineStart(transformedPoints[0u]); + outV.setLineEnd(transformedPoints[1u]); - // Internal cage points - float2 interior0; - float2 interior1; + outV.position.xy = transformFromSreenSpaceToNdc(outV.position.xy, globals.resolution).xy; + } + else if (objType == ObjectType::QUAD_BEZIER) + { + pfloat64_t2 points[3u]; + points[0u] = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress, 8u); + points[1u] = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2), 8u); + points[2u] = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) * 2u, 8u); + + const float phaseShift = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) * 3u, 8u); + const float patternStretch = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) * 3u + sizeof(float), 8u); + outV.setCurrentPhaseShift(phaseShift); + outV.setPatternStretch(patternStretch); + + // transform these points into screen space and pass to fragment + float2 transformedPoints[3u]; + for (uint i = 0u; i < 3u; ++i) + { + transformedPoints[i] = transformPointScreenSpace(clipProjectionData.projectionToNDC, globals.resolution, points[i]); + } - float2 middleExteriorPoint = midPos - midNormal * antiAliasedLineThickness; + shapes::QuadraticBezier quadraticBezier = shapes::QuadraticBezier::construct(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u]); + shapes::Quadratic quadratic = shapes::Quadratic::constructFromBezier(quadraticBezier); + shapes::Quadratic::ArcLengthCalculator preCompData = shapes::Quadratic::ArcLengthCalculator::construct(quadratic); + outV.setQuadratic(quadratic); + outV.setQuadraticPrecomputedArcLenData(preCompData); - float2 leftTangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], optimalT)); - float2 leftNormal = normalize(float2(-leftTangent.y, leftTangent.x)) * flip; - float2 leftExteriorPoint = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], optimalT) - leftNormal * antiAliasedLineThickness; - float2 exterior0 = shapes::util::LineLineIntersection(middleExteriorPoint, midTangent, leftExteriorPoint, leftTangent); + float2 Mid = (transformedPoints[0u] + transformedPoints[2u]) / 2.0f; + float Radius = length(Mid - transformedPoints[0u]) / 2.0f; - float2 rightTangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 1.0f - optimalT)); - float2 rightNormal = normalize(float2(-rightTangent.y, rightTangent.x)) * flip; - float2 rightExteriorPoint = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 1.0f - optimalT) - rightNormal * antiAliasedLineThickness; - float2 exterior1 = shapes::util::LineLineIntersection(middleExteriorPoint, midTangent, rightExteriorPoint, rightTangent); + // https://algorithmist.wordpress.com/2010/12/01/quad-bezier-curvature/ + float2 vectorAB = transformedPoints[1u] - transformedPoints[0u]; + float2 vectorAC = transformedPoints[2u] - transformedPoints[1u]; + float area = abs(vectorAB.x * vectorAC.y - vectorAB.y * vectorAC.x) * 0.5; + float MaxCurvature; + if (length(transformedPoints[1u] - lerp(transformedPoints[0u], transformedPoints[2u], 0.25f)) > Radius && length(transformedPoints[1u] - lerp(transformedPoints[0u], transformedPoints[2u], 0.75f)) > Radius) + MaxCurvature = pow(length(transformedPoints[1u] - Mid), 3) / (area * area); + else + MaxCurvature = max(area / pow(length(transformedPoints[0u] - transformedPoints[1u]), 3), area / pow(length(transformedPoints[2u] - transformedPoints[1u]), 3)); - // Interiors + // We only do this adaptive thing when "MinRadiusOfOsculatingCircle = RadiusOfMaxCurvature < screenSpaceLineWidth/4" OR "MaxCurvature > 4/screenSpaceLineWidth"; + // which means there is a self intersection because of large lineWidth relative to the curvature (in screenspace) + // the reason for division by 4.0f is 1. screenSpaceLineWidth is expanded on both sides and 2. the fact that diameter/2=radius, + const bool noCurvature = abs(dot(normalize(vectorAB), normalize(vectorAC)) - 1.0f) < exp2(-10.0f); + if (MaxCurvature * screenSpaceLineWidth > 4.0f || noCurvature) { - float2 tangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 0.286f)); - float2 normal = normalize(float2(-tangent.y, tangent.x)) * flip; - interior0 = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 0.286) + normal * antiAliasedLineThickness; + //OBB Fallback + float2 obbV0; + float2 obbV1; + float2 obbV2; + float2 obbV3; + quadraticBezier.computeOBB(antiAliasedLineThickness, obbV0, obbV1, obbV2, obbV3); + if (subsectionIdx == 0) + { + if (vertexIdx == 0u) + outV.position = float4(obbV0, 0.0, 1.0f); + else if (vertexIdx == 1u) + outV.position = float4(obbV1, 0.0, 1.0f); + else if (vertexIdx == 2u) + outV.position = float4(obbV3, 0.0, 1.0f); + else if (vertexIdx == 3u) + outV.position = float4(obbV2, 0.0, 1.0f); + } + else + outV.position = float4(0.0f, 0.0f, 0.0f, 0.0f); } + else { - float2 tangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 0.714f)); - float2 normal = normalize(float2(-tangent.y, tangent.x)) * flip; - interior1 = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 0.714f) + normal * antiAliasedLineThickness; + // this optimal value is hardcoded based on tests and benchmarks of pixel shader invocation + // this is the place where we use it's tangent in the bezier to form sides the cages + const float optimalT = 0.145f; + + // Whether or not to flip the the interior cage nodes + int flip = cross2D(transformedPoints[0u] - transformedPoints[1u], transformedPoints[2u] - transformedPoints[1u]) > 0.0f ? -1 : 1; + + const float middleT = 0.5f; + float2 midPos = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], middleT); + float2 midTangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], middleT)); + float2 midNormal = float2(-midTangent.y, midTangent.x) * flip; + + /* + P1 + + + + + exterior0 exterior1 + ---------------------- + / \- + -/ ---------------- \ + / -/interior0 interior1 + / / \ \- + -/ -/ \- \ + / -/ \ \- + / / \- \ + P0 + \ + P2 + */ + + // Internal cage points + float2 interior0; + float2 interior1; + + float2 middleExteriorPoint = midPos - midNormal * antiAliasedLineThickness; + + + float2 leftTangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], optimalT)); + float2 leftNormal = normalize(float2(-leftTangent.y, leftTangent.x)) * flip; + float2 leftExteriorPoint = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], optimalT) - leftNormal * antiAliasedLineThickness; + float2 exterior0 = shapes::util::LineLineIntersection(middleExteriorPoint, midTangent, leftExteriorPoint, leftTangent); + + float2 rightTangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 1.0f - optimalT)); + float2 rightNormal = normalize(float2(-rightTangent.y, rightTangent.x)) * flip; + float2 rightExteriorPoint = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 1.0f - optimalT) - rightNormal * antiAliasedLineThickness; + float2 exterior1 = shapes::util::LineLineIntersection(middleExteriorPoint, midTangent, rightExteriorPoint, rightTangent); + + // Interiors + { + float2 tangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 0.286f)); + float2 normal = normalize(float2(-tangent.y, tangent.x)) * flip; + interior0 = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 0.286) + normal * antiAliasedLineThickness; + } + { + float2 tangent = normalize(BezierTangent(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 0.714f)); + float2 normal = normalize(float2(-tangent.y, tangent.x)) * flip; + interior1 = QuadraticBezier(transformedPoints[0u], transformedPoints[1u], transformedPoints[2u], 0.714f) + normal * antiAliasedLineThickness; + } + + if (subsectionIdx == 0u) + { + float2 endPointTangent = normalize(transformedPoints[1u] - transformedPoints[0u]); + float2 endPointNormal = float2(-endPointTangent.y, endPointTangent.x) * flip; + float2 endPointExterior = transformedPoints[0u] - endPointTangent * antiAliasedLineThickness; + + if (vertexIdx == 0u) + outV.position = float4(shapes::util::LineLineIntersection(leftExteriorPoint, leftTangent, endPointExterior, endPointNormal), 0.0, 1.0f); + else if (vertexIdx == 1u) + outV.position = float4(transformedPoints[0u] + endPointNormal * antiAliasedLineThickness - endPointTangent * antiAliasedLineThickness, 0.0, 1.0f); + else if (vertexIdx == 2u) + outV.position = float4(exterior0, 0.0, 1.0f); + else if (vertexIdx == 3u) + outV.position = float4(interior0, 0.0, 1.0f); + } + else if (subsectionIdx == 1u) + { + if (vertexIdx == 0u) + outV.position = float4(exterior0, 0.0, 1.0f); + else if (vertexIdx == 1u) + outV.position = float4(interior0, 0.0, 1.0f); + else if (vertexIdx == 2u) + outV.position = float4(exterior1, 0.0, 1.0f); + else if (vertexIdx == 3u) + outV.position = float4(interior1, 0.0, 1.0f); + } + else if (subsectionIdx == 2u) + { + float2 endPointTangent = normalize(transformedPoints[2u] - transformedPoints[1u]); + float2 endPointNormal = float2(-endPointTangent.y, endPointTangent.x) * flip; + float2 endPointExterior = transformedPoints[2u] + endPointTangent * antiAliasedLineThickness; + + if (vertexIdx == 0u) + outV.position = float4(shapes::util::LineLineIntersection(rightExteriorPoint, rightTangent, endPointExterior, endPointNormal), 0.0, 1.0f); + else if (vertexIdx == 1u) + outV.position = float4(transformedPoints[2u] + endPointNormal * antiAliasedLineThickness + endPointTangent * antiAliasedLineThickness, 0.0, 1.0f); + else if (vertexIdx == 2u) + outV.position = float4(exterior1, 0.0, 1.0f); + else if (vertexIdx == 3u) + outV.position = float4(interior1, 0.0, 1.0f); + } } - if (subsectionIdx == 0u) - { - float2 endPointTangent = normalize(transformedPoints[1u] - transformedPoints[0u]); - float2 endPointNormal = float2(-endPointTangent.y, endPointTangent.x) * flip; - float2 endPointExterior = transformedPoints[0u] - endPointTangent * antiAliasedLineThickness; + outV.position.xy = (outV.position.xy / globals.resolution) * 2.0f - 1.0f; + } + else if (objType == ObjectType::POLYLINE_CONNECTOR) + { + const float FLOAT_INF = numeric_limits::infinity; + const float4 INVALID_VERTEX = float4(FLOAT_INF, FLOAT_INF, FLOAT_INF, FLOAT_INF); - if (vertexIdx == 0u) - outV.position = float4(shapes::util::LineLineIntersection(leftExteriorPoint, leftTangent, endPointExterior, endPointNormal), 0.0, 1.0f); - else if (vertexIdx == 1u) - outV.position = float4(transformedPoints[0u] + endPointNormal * antiAliasedLineThickness - endPointTangent * antiAliasedLineThickness, 0.0, 1.0f); - else if (vertexIdx == 2u) - outV.position = float4(exterior0, 0.0, 1.0f); - else if (vertexIdx == 3u) - outV.position = float4(interior0, 0.0, 1.0f); - } - else if (subsectionIdx == 1u) + if (lineStyle.isRoadStyleFlag) { - if (vertexIdx == 0u) - outV.position = float4(exterior0, 0.0, 1.0f); - else if (vertexIdx == 1u) - outV.position = float4(interior0, 0.0, 1.0f); - else if (vertexIdx == 2u) - outV.position = float4(exterior1, 0.0, 1.0f); - else if (vertexIdx == 3u) - outV.position = float4(interior1, 0.0, 1.0f); - } - else if (subsectionIdx == 2u) - { - float2 endPointTangent = normalize(transformedPoints[2u] - transformedPoints[1u]); - float2 endPointNormal = float2(-endPointTangent.y, endPointTangent.x) * flip; - float2 endPointExterior = transformedPoints[2u] + endPointTangent * antiAliasedLineThickness; + const pfloat64_t2 circleCenter = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress, 8u); + const float2 v = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2), 8u); + const float cosHalfAngleBetweenNormals = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2), 8u); - if (vertexIdx == 0u) - outV.position = float4(shapes::util::LineLineIntersection(rightExteriorPoint, rightTangent, endPointExterior, endPointNormal), 0.0, 1.0f); - else if (vertexIdx == 1u) - outV.position = float4(transformedPoints[2u] + endPointNormal * antiAliasedLineThickness + endPointTangent * antiAliasedLineThickness, 0.0, 1.0f); - else if (vertexIdx == 2u) - outV.position = float4(exterior1, 0.0, 1.0f); - else if (vertexIdx == 3u) - outV.position = float4(interior1, 0.0, 1.0f); - } - } + const float2 circleCenterScreenSpace = transformPointScreenSpace(clipProjectionData.projectionToNDC, globals.resolution, circleCenter); + outV.setPolylineConnectorCircleCenter(circleCenterScreenSpace); - outV.position.xy = (outV.position.xy / globals.resolution) * 2.0f - 1.0f; - } - else if (objType == ObjectType::POLYLINE_CONNECTOR) - { - const float FLOAT_INF = numeric_limits::infinity; - const float4 INVALID_VERTEX = float4(FLOAT_INF, FLOAT_INF, FLOAT_INF, FLOAT_INF); + // Find other miter vertices + const float sinHalfAngleBetweenNormals = sqrt(1.0f - (cosHalfAngleBetweenNormals * cosHalfAngleBetweenNormals)); + const float32_t2x2 rotationMatrix = float32_t2x2(cosHalfAngleBetweenNormals, -sinHalfAngleBetweenNormals, sinHalfAngleBetweenNormals, cosHalfAngleBetweenNormals); - if (lineStyle.isRoadStyleFlag) - { - const pfloat64_t2 circleCenter = vk::RawBufferLoad(drawObj.geometryAddress, 8u); - const float2 v = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2), 8u); - const float cosHalfAngleBetweenNormals = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2), 8u); + // Pass the precomputed trapezoid values for the sdf + { + float vLen = length(v); + float2 intersectionDirection = v / vLen; - const float2 circleCenterScreenSpace = transformPointScreenSpace(clipProjectionData.projectionToNDC, globals.resolution, circleCenter); - outV.setPolylineConnectorCircleCenter(circleCenterScreenSpace); + float longBase = sinHalfAngleBetweenNormals; + float shortBase = max((vLen - globals.miterLimit) * cosHalfAngleBetweenNormals / sinHalfAngleBetweenNormals, 0.0); + // height of the trapezoid / triangle + float hLen = min(globals.miterLimit, vLen); - // Find other miter vertices - const float sinHalfAngleBetweenNormals = sqrt(1.0f - (cosHalfAngleBetweenNormals * cosHalfAngleBetweenNormals)); - const float32_t2x2 rotationMatrix = float32_t2x2(cosHalfAngleBetweenNormals, -sinHalfAngleBetweenNormals, sinHalfAngleBetweenNormals, cosHalfAngleBetweenNormals); + outV.setPolylineConnectorTrapezoidStart(-1.0 * intersectionDirection * sdfLineThickness); + outV.setPolylineConnectorTrapezoidEnd(intersectionDirection * hLen * sdfLineThickness); + outV.setPolylineConnectorTrapezoidLongBase(sinHalfAngleBetweenNormals * ((1.0 + vLen) / (vLen - cosHalfAngleBetweenNormals)) * sdfLineThickness); + outV.setPolylineConnectorTrapezoidShortBase(shortBase * sdfLineThickness); + } - // Pass the precomputed trapezoid values for the sdf - { - float vLen = length(v); - float2 intersectionDirection = v / vLen; - - float longBase = sinHalfAngleBetweenNormals; - float shortBase = max((vLen - globals.miterLimit) * cosHalfAngleBetweenNormals / sinHalfAngleBetweenNormals, 0.0); - // height of the trapezoid / triangle - float hLen = min(globals.miterLimit, vLen); - - outV.setPolylineConnectorTrapezoidStart(-1.0 * intersectionDirection * sdfLineThickness); - outV.setPolylineConnectorTrapezoidEnd(intersectionDirection * hLen * sdfLineThickness); - outV.setPolylineConnectorTrapezoidLongBase(sinHalfAngleBetweenNormals * ((1.0 + vLen) / (vLen - cosHalfAngleBetweenNormals)) * sdfLineThickness); - outV.setPolylineConnectorTrapezoidShortBase(shortBase * sdfLineThickness); - } + if (vertexIdx == 0u) + { + const float2 V1 = normalize(mul(v, rotationMatrix)) * antiAliasedLineThickness * 2.0f; + const float2 screenSpaceV1 = circleCenterScreenSpace + V1; + outV.position = float4(screenSpaceV1, 0.0f, 1.0f); + } + else if (vertexIdx == 1u) + { + outV.position = float4(circleCenterScreenSpace, 0.0f, 1.0f); + } + else if (vertexIdx == 2u) + { + // find intersection point vertex + float2 intersectionPoint = v * antiAliasedLineThickness * 2.0f; + intersectionPoint += circleCenterScreenSpace; + outV.position = float4(intersectionPoint, 0.0f, 1.0f); + } + else if (vertexIdx == 3u) + { + const float2 V2 = normalize(mul(rotationMatrix, v)) * antiAliasedLineThickness * 2.0f; + const float2 screenSpaceV2 = circleCenterScreenSpace + V2; + outV.position = float4(screenSpaceV2, 0.0f, 1.0f); + } - if (vertexIdx == 0u) - { - const float2 V1 = normalize(mul(v, rotationMatrix)) * antiAliasedLineThickness * 2.0f; - const float2 screenSpaceV1 = circleCenterScreenSpace + V1; - outV.position = float4(screenSpaceV1, 0.0f, 1.0f); - } - else if (vertexIdx == 1u) - { - outV.position = float4(circleCenterScreenSpace, 0.0f, 1.0f); - } - else if (vertexIdx == 2u) - { - // find intersection point vertex - float2 intersectionPoint = v * antiAliasedLineThickness * 2.0f; - intersectionPoint += circleCenterScreenSpace; - outV.position = float4(intersectionPoint, 0.0f, 1.0f); + outV.position.xy = transformFromSreenSpaceToNdc(outV.position.xy, globals.resolution).xy; } - else if (vertexIdx == 3u) + else { - const float2 V2 = normalize(mul(rotationMatrix, v)) * antiAliasedLineThickness * 2.0f; - const float2 screenSpaceV2 = circleCenterScreenSpace + V2; - outV.position = float4(screenSpaceV2, 0.0f, 1.0f); + outV.position = INVALID_VERTEX; } - - outV.position.xy = transformFromSreenSpaceToNdc(outV.position.xy, globals.resolution).xy; - } - else - { - outV.position = INVALID_VERTEX; } } - } - else if (objType == ObjectType::CURVE_BOX) - { - CurveBox curveBox; - curveBox.aabbMin = vk::RawBufferLoad(drawObj.geometryAddress, 8u); - curveBox.aabbMax = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2), 8u); - - for (uint32_t i = 0; i < 3; i ++) + else if (objType == ObjectType::CURVE_BOX) { - curveBox.curveMin[i] = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) * 2 + sizeof(float32_t2) * i, 4u); - curveBox.curveMax[i] = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) * 2 + sizeof(float32_t2) * (3 + i), 4u); - } + CurveBox curveBox; + curveBox.aabbMin = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress, 8u); + curveBox.aabbMax = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2), 8u); - pfloat64_t2 aabbMaxXMinY; - aabbMaxXMinY.x = curveBox.aabbMax.x; - aabbMaxXMinY.y = curveBox.aabbMin.y; + for (uint32_t i = 0; i < 3; i ++) + { + curveBox.curveMin[i] = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) * 2 + sizeof(float32_t2) * i, 4u); + curveBox.curveMax[i] = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) * 2 + sizeof(float32_t2) * (3 + i), 4u); + } - pfloat64_t2 aabbMinXMaxY; - aabbMinXMaxY.x = curveBox.aabbMin.x; - aabbMinXMaxY.y = curveBox.aabbMax.y; + pfloat64_t2 aabbMaxXMinY; + aabbMaxXMinY.x = curveBox.aabbMax.x; + aabbMaxXMinY.y = curveBox.aabbMin.y; - const float2 ndcAxisU = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, aabbMaxXMinY - curveBox.aabbMin)); - const float2 ndcAxisV = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, aabbMinXMaxY - curveBox.aabbMin)); + pfloat64_t2 aabbMinXMaxY; + aabbMinXMaxY.x = curveBox.aabbMin.x; + aabbMinXMaxY.y = curveBox.aabbMax.y; - const float2 screenSpaceAabbExtents = float2(length(ndcAxisU * float2(globals.resolution)) / 2.0, length(ndcAxisV * float2(globals.resolution)) / 2.0); + const float2 ndcAxisU = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, aabbMaxXMinY - curveBox.aabbMin)); + const float2 ndcAxisV = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, aabbMinXMaxY - curveBox.aabbMin)); - // we could use something like this to compute screen space change over minor/major change and avoid ddx(minor), ddy(major) in frag shader (the code below doesn't account for rotation) - outV.setCurveBoxScreenSpaceSize(float2(screenSpaceAabbExtents)); + const float2 screenSpaceAabbExtents = float2(length(ndcAxisU * float2(globals.resolution)) / 2.0, length(ndcAxisV * float2(globals.resolution)) / 2.0); + + // we could use something like this to compute screen space change over minor/major change and avoid ddx(minor), ddy(major) in frag shader (the code below doesn't account for rotation) + outV.setCurveBoxScreenSpaceSize(float2(screenSpaceAabbExtents)); - const float2 undilatedCorner = float2(bool2(vertexIdx & 0x1u, vertexIdx >> 1)); - const pfloat64_t2 undilatedCornerF64 = _static_cast(undilatedCorner); + const float2 undilatedCorner = float2(bool2(vertexIdx & 0x1u, vertexIdx >> 1)); + const pfloat64_t2 undilatedCornerF64 = _static_cast(undilatedCorner); - // We don't dilate on AMD (= no fragShaderInterlock) - const float pixelsToIncreaseOnEachSide = globals.antiAliasingFactor + 1.0; - const float2 dilateRate = pixelsToIncreaseOnEachSide / screenSpaceAabbExtents; // float sufficient to hold the dilate rect? - float2 dilateVec; - float2 dilatedUV; - dilateHatch(dilateVec, dilatedUV, undilatedCorner, dilateRate, ndcAxisU, ndcAxisV); + // We don't dilate on AMD (= no fragShaderInterlock) + const float pixelsToIncreaseOnEachSide = globals.antiAliasingFactor + 1.0; + const float2 dilateRate = pixelsToIncreaseOnEachSide / screenSpaceAabbExtents; // float sufficient to hold the dilate rect? + float2 dilateVec; + float2 dilatedUV; + dilateHatch(dilateVec, dilatedUV, undilatedCorner, dilateRate, ndcAxisU, ndcAxisV); - // doing interpolation this way to ensure correct endpoints and 0 and 1, we can alternatively use branches to set current corner based on vertexIdx - const pfloat64_t2 currentCorner = curveBox.aabbMin * (_static_cast(float2(1.0f, 1.0f)) - undilatedCornerF64) + - curveBox.aabbMax * undilatedCornerF64; + // doing interpolation this way to ensure correct endpoints and 0 and 1, we can alternatively use branches to set current corner based on vertexIdx + const pfloat64_t2 currentCorner = curveBox.aabbMin * (_static_cast(float2(1.0f, 1.0f)) - undilatedCornerF64) + + curveBox.aabbMax * undilatedCornerF64; - const float2 coord = _static_cast(transformPointNdc(clipProjectionData.projectionToNDC, currentCorner) + _static_cast(dilateVec)); + const float2 coord = _static_cast(transformPointNdc(clipProjectionData.projectionToNDC, currentCorner) + _static_cast(dilateVec)); - outV.position = float4(coord, 0.f, 1.f); + outV.position = float4(coord, 0.f, 1.f); - const uint major = (uint)SelectedMajorAxis; - const uint minor = 1-major; - - // A, B & C get converted from unorm to [0, 1] - // A & B get converted from [0,1] to [-2, 2] - shapes::Quadratic curveMin = shapes::Quadratic::construct( - curveBox.curveMin[0], curveBox.curveMin[1], curveBox.curveMin[2]); - shapes::Quadratic curveMax = shapes::Quadratic::construct( - curveBox.curveMax[0], curveBox.curveMax[1], curveBox.curveMax[2]); - - outV.setMinorBBoxUV(dilatedUV[minor]); - outV.setMajorBBoxUV(dilatedUV[major]); - - outV.setCurveMinMinor(math::equations::Quadratic::construct( - curveMin.A[minor], - curveMin.B[minor], - curveMin.C[minor])); - outV.setCurveMinMajor(math::equations::Quadratic::construct( - curveMin.A[major], - curveMin.B[major], - curveMin.C[major])); - - outV.setCurveMaxMinor(math::equations::Quadratic::construct( - curveMax.A[minor], - curveMax.B[minor], - curveMax.C[minor])); - outV.setCurveMaxMajor(math::equations::Quadratic::construct( - curveMax.A[major], - curveMax.B[major], - curveMax.C[major])); - - //math::equations::Quadratic curveMinRootFinding = math::equations::Quadratic::construct( - // curveMin.A[major], - // curveMin.B[major], - // curveMin.C[major] - maxCorner[major]); - //math::equations::Quadratic curveMaxRootFinding = math::equations::Quadratic::construct( - // curveMax.A[major], - // curveMax.B[major], - // curveMax.C[major] - maxCorner[major]); - //outV.setMinCurvePrecomputedRootFinders(PrecomputedRootFinder::construct(curveMinRootFinding)); - //outV.setMaxCurvePrecomputedRootFinders(PrecomputedRootFinder::construct(curveMaxRootFinding)); - } - else if (objType == ObjectType::FONT_GLYPH) - { - LineStyle lineStyle = lineStyles[mainObj.styleIdx]; - const float italicTiltSlope = lineStyle.screenSpaceLineWidth; // aliased text style member with line style + const uint major = (uint)SelectedMajorAxis; + const uint minor = 1-major; + + // A, B & C get converted from unorm to [0, 1] + // A & B get converted from [0,1] to [-2, 2] + shapes::Quadratic curveMin = shapes::Quadratic::construct( + curveBox.curveMin[0], curveBox.curveMin[1], curveBox.curveMin[2]); + shapes::Quadratic curveMax = shapes::Quadratic::construct( + curveBox.curveMax[0], curveBox.curveMax[1], curveBox.curveMax[2]); + + outV.setMinorBBoxUV(dilatedUV[minor]); + outV.setMajorBBoxUV(dilatedUV[major]); + + outV.setCurveMinMinor(math::equations::Quadratic::construct( + curveMin.A[minor], + curveMin.B[minor], + curveMin.C[minor])); + outV.setCurveMinMajor(math::equations::Quadratic::construct( + curveMin.A[major], + curveMin.B[major], + curveMin.C[major])); + + outV.setCurveMaxMinor(math::equations::Quadratic::construct( + curveMax.A[minor], + curveMax.B[minor], + curveMax.C[minor])); + outV.setCurveMaxMajor(math::equations::Quadratic::construct( + curveMax.A[major], + curveMax.B[major], + curveMax.C[major])); + + //math::equations::Quadratic curveMinRootFinding = math::equations::Quadratic::construct( + // curveMin.A[major], + // curveMin.B[major], + // curveMin.C[major] - maxCorner[major]); + //math::equations::Quadratic curveMaxRootFinding = math::equations::Quadratic::construct( + // curveMax.A[major], + // curveMax.B[major], + // curveMax.C[major] - maxCorner[major]); + //outV.setMinCurvePrecomputedRootFinders(PrecomputedRootFinder::construct(curveMinRootFinding)); + //outV.setMaxCurvePrecomputedRootFinders(PrecomputedRootFinder::construct(curveMaxRootFinding)); + } + else if (objType == ObjectType::FONT_GLYPH) + { + LineStyle lineStyle = loadLineStyle(mainObj.styleIdx); + const float italicTiltSlope = lineStyle.screenSpaceLineWidth; // aliased text style member with line style - GlyphInfo glyphInfo; - glyphInfo.topLeft = vk::RawBufferLoad(drawObj.geometryAddress, 8u); - glyphInfo.dirU = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2), 4u); - glyphInfo.aspectRatio = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2), 4u); - glyphInfo.minUV_textureID_packed = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2) + sizeof(float), 4u); - - float32_t2 minUV = glyphInfo.getMinUV(); - uint16_t textureID = glyphInfo.getTextureID(); - - const float32_t2 dirV = float32_t2(glyphInfo.dirU.y, -glyphInfo.dirU.x) * glyphInfo.aspectRatio; - const float2 screenTopLeft = _static_cast(transformPointNdc(clipProjectionData.projectionToNDC, glyphInfo.topLeft)); - const float2 screenDirU = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, _static_cast(glyphInfo.dirU))); - const float2 screenDirV = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, _static_cast(dirV))); - - const float2 corner = float2(bool2(vertexIdx & 0x1u, vertexIdx >> 1)); // corners of square from (0, 0) to (1, 1) - const float2 undilatedCornerNDC = corner * 2.0 - 1.0; // corners of square from (-1, -1) to (1, 1) + GlyphInfo glyphInfo; + glyphInfo.topLeft = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress, 8u); + glyphInfo.dirU = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2), 4u); + glyphInfo.aspectRatio = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2), 4u); + glyphInfo.minUV_textureID_packed = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2) + sizeof(float), 4u); + + float32_t2 minUV = glyphInfo.getMinUV(); + uint16_t textureID = glyphInfo.getTextureID(); + + const float32_t2 dirV = float32_t2(glyphInfo.dirU.y, -glyphInfo.dirU.x) * glyphInfo.aspectRatio; + const float2 screenTopLeft = _static_cast(transformPointNdc(clipProjectionData.projectionToNDC, glyphInfo.topLeft)); + const float2 screenDirU = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, _static_cast(glyphInfo.dirU))); + const float2 screenDirV = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, _static_cast(dirV))); + + const float2 corner = float2(bool2(vertexIdx & 0x1u, vertexIdx >> 1)); // corners of square from (0, 0) to (1, 1) + const float2 undilatedCornerNDC = corner * 2.0 - 1.0; // corners of square from (-1, -1) to (1, 1) - const float2 screenSpaceAabbExtents = float2(length(screenDirU * float2(globals.resolution)) / 2.0, length(screenDirV * float2(globals.resolution)) / 2.0); - const float pixelsToIncreaseOnEachSide = globals.antiAliasingFactor + 1.0; - const float2 dilateRate = (pixelsToIncreaseOnEachSide / screenSpaceAabbExtents); + const float2 screenSpaceAabbExtents = float2(length(screenDirU * float2(globals.resolution)) / 2.0, length(screenDirV * float2(globals.resolution)) / 2.0); + const float pixelsToIncreaseOnEachSide = globals.antiAliasingFactor + 1.0; + const float2 dilateRate = (pixelsToIncreaseOnEachSide / screenSpaceAabbExtents); - const float2 vx = screenDirU * dilateRate.x; - const float2 vy = screenDirV * dilateRate.y; - const float2 offsetVec = vx * undilatedCornerNDC.x + vy * undilatedCornerNDC.y; - float2 coord = screenTopLeft + corner.x * screenDirU + corner.y * screenDirV + offsetVec; + const float2 vx = screenDirU * dilateRate.x; + const float2 vy = screenDirV * dilateRate.y; + const float2 offsetVec = vx * undilatedCornerNDC.x + vy * undilatedCornerNDC.y; + float2 coord = screenTopLeft + corner.x * screenDirU + corner.y * screenDirV + offsetVec; - if (corner.y == 0 && italicTiltSlope > 0.0f) - coord += normalize(screenDirU) * length(screenDirV) * italicTiltSlope * float(globals.resolution.y) / float(globals.resolution.x); + if (corner.y == 0 && italicTiltSlope > 0.0f) + coord += normalize(screenDirU) * length(screenDirV) * italicTiltSlope * float(globals.resolution.y) / float(globals.resolution.x); - // If aspect ratio of the dimensions and glyph inside the texture are the same then screenPxRangeX === screenPxRangeY - // but if the glyph box is stretched in any way then we won't get correct msdf - // in that case we need to take the max(screenPxRangeX, screenPxRangeY) to avoid blur due to underexaggerated distances - // We compute screenPxRange using the ratio of our screenspace extent to the texel space our glyph takes inside the texture - // Our glyph is centered inside the texture, so `maxUV = 1.0 - minUV` and `glyphTexelSize = (1.0-2.0*minUV) * MSDFSize - const float screenPxRangeX = screenSpaceAabbExtents.x / ((1.0 - 2.0 * minUV.x)); // division by MSDFSize happens after max - const float screenPxRangeY = screenSpaceAabbExtents.y / ((1.0 - 2.0 * minUV.y)); // division by MSDFSize happens after max - outV.setFontGlyphPxRange((max(max(screenPxRangeX, screenPxRangeY), 1.0) * MSDFPixelRangeHalf) / MSDFSize); // we premultuply by MSDFPixelRange/2.0, to avoid doing it in frag shader - - // In order to keep the shape scale constant with any dilation values: - // We compute the new dilated minUV that gets us minUV when interpolated on the previous undilated top left - const float2 topLeftInterpolationValue = (dilateRate/(1.0+2.0*dilateRate)); - const float2 dilatedMinUV = (topLeftInterpolationValue - minUV) / (2.0 * topLeftInterpolationValue - 1.0); - const float2 dilatedMaxUV = float2(1.0, 1.0) - dilatedMinUV; + // If aspect ratio of the dimensions and glyph inside the texture are the same then screenPxRangeX === screenPxRangeY + // but if the glyph box is stretched in any way then we won't get correct msdf + // in that case we need to take the max(screenPxRangeX, screenPxRangeY) to avoid blur due to underexaggerated distances + // We compute screenPxRange using the ratio of our screenspace extent to the texel space our glyph takes inside the texture + // Our glyph is centered inside the texture, so `maxUV = 1.0 - minUV` and `glyphTexelSize = (1.0-2.0*minUV) * MSDFSize + const float screenPxRangeX = screenSpaceAabbExtents.x / ((1.0 - 2.0 * minUV.x)); // division by MSDFSize happens after max + const float screenPxRangeY = screenSpaceAabbExtents.y / ((1.0 - 2.0 * minUV.y)); // division by MSDFSize happens after max + outV.setFontGlyphPxRange((max(max(screenPxRangeX, screenPxRangeY), 1.0) * MSDFPixelRangeHalf) / MSDFSize); // we premultuply by MSDFPixelRange/2.0, to avoid doing it in frag shader + + // In order to keep the shape scale constant with any dilation values: + // We compute the new dilated minUV that gets us minUV when interpolated on the previous undilated top left + const float2 topLeftInterpolationValue = (dilateRate/(1.0+2.0*dilateRate)); + const float2 dilatedMinUV = (topLeftInterpolationValue - minUV) / (2.0 * topLeftInterpolationValue - 1.0); + const float2 dilatedMaxUV = float2(1.0, 1.0) - dilatedMinUV; - const float2 uv = dilatedMinUV + corner * (dilatedMaxUV - dilatedMinUV); + const float2 uv = dilatedMinUV + corner * (dilatedMaxUV - dilatedMinUV); - outV.position = float4(coord, 0.f, 1.f); - outV.setFontGlyphUV(uv); - outV.setFontGlyphTextureId(textureID); - } - else if (objType == ObjectType::IMAGE) - { - pfloat64_t2 topLeft = vk::RawBufferLoad(drawObj.geometryAddress, 8u); - float32_t2 dirU = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2), 4u); - float32_t aspectRatio = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2), 4u); - uint32_t textureID = vk::RawBufferLoad(drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2) + sizeof(float), 4u); - - const float32_t2 dirV = float32_t2(dirU.y, -dirU.x) * aspectRatio; - const float2 ndcTopLeft = _static_cast(transformPointNdc(clipProjectionData.projectionToNDC, topLeft)); - const float2 ndcDirU = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, _static_cast(dirU))); - const float2 ndcDirV = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, _static_cast(dirV))); - - float2 corner = float2(bool2(vertexIdx & 0x1u, vertexIdx >> 1)); - float2 uv = corner; // non-dilated + outV.position = float4(coord, 0.f, 1.f); + outV.setFontGlyphUV(uv); + outV.setFontGlyphTextureId(textureID); + } + else if (objType == ObjectType::IMAGE) + { + pfloat64_t2 topLeft = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress, 8u); + float32_t2 dirU = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2), 4u); + float32_t aspectRatio = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2), 4u); + uint32_t textureID = vk::RawBufferLoad(globals.pointers.geometryBuffer + drawObj.geometryAddress + sizeof(pfloat64_t2) + sizeof(float2) + sizeof(float), 4u); + + const float32_t2 dirV = float32_t2(dirU.y, -dirU.x) * aspectRatio; + const float2 ndcTopLeft = _static_cast(transformPointNdc(clipProjectionData.projectionToNDC, topLeft)); + const float2 ndcDirU = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, _static_cast(dirU))); + const float2 ndcDirV = _static_cast(transformVectorNdc(clipProjectionData.projectionToNDC, _static_cast(dirV))); + + float2 corner = float2(bool2(vertexIdx & 0x1u, vertexIdx >> 1)); + float2 uv = corner; // non-dilated - float2 ndcCorner = ndcTopLeft + corner.x * ndcDirU + corner.y * ndcDirV; + float2 ndcCorner = ndcTopLeft + corner.x * ndcDirU + corner.y * ndcDirV; - outV.position = float4(ndcCorner, 0.f, 1.f); - outV.setImageUV(uv); - outV.setImageTextureId(textureID); - } - + outV.position = float4(ndcCorner, 0.f, 1.f); + outV.setImageUV(uv); + outV.setImageTextureId(textureID); + } -// Make the cage fullscreen for testing: + // Make the cage fullscreen for testing: #if 0 - // disabled for object of POLYLINE_CONNECTOR type, since miters would cover whole screen - if(objType != ObjectType::POLYLINE_CONNECTOR) - { - if (vertexIdx == 0u) - outV.position = float4(-1, -1, 0, 1); - else if (vertexIdx == 1u) - outV.position = float4(-1, +1, 0, 1); - else if (vertexIdx == 2u) - outV.position = float4(+1, -1, 0, 1); - else if (vertexIdx == 3u) - outV.position = float4(+1, +1, 0, 1); - } + // disabled for object of POLYLINE_CONNECTOR type, since miters would cover whole screen + if(objType != ObjectType::POLYLINE_CONNECTOR) + { + if (vertexIdx == 0u) + outV.position = float4(-1, -1, 0, 1); + else if (vertexIdx == 1u) + outV.position = float4(-1, +1, 0, 1); + else if (vertexIdx == 2u) + outV.position = float4(+1, -1, 0, 1); + else if (vertexIdx == 3u) + outV.position = float4(+1, +1, 0, 1); + } #endif - + } outV.clip = float4(outV.position.x - clipProjectionData.minClipNDC.x, outV.position.y - clipProjectionData.minClipNDC.y, clipProjectionData.maxClipNDC.x - outV.position.x, clipProjectionData.maxClipNDC.y - outV.position.y); return outV; }