• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2021 The Khronos Group Inc.
6  * Copyright (c) 2021 Valve Corporation.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  *//*!
21  * \file
22  * \brief Mesh Shader Synchronization Tests
23  *//*--------------------------------------------------------------------*/
24 
25 #include "vktMeshShaderSyncTests.hpp"
26 #include "vktTestCase.hpp"
27 
28 #include "vkDefs.hpp"
29 #include "vkTypeUtil.hpp"
30 #include "vkImageWithMemory.hpp"
31 #include "vkBufferWithMemory.hpp"
32 #include "vkObjUtil.hpp"
33 #include "vkBuilderUtil.hpp"
34 #include "vkCmdUtil.hpp"
35 #include "vkBarrierUtil.hpp"
36 #include "vkImageUtil.hpp"
37 
38 #include "deUniquePtr.hpp"
39 
40 #include <iostream>
41 #include <sstream>
42 #include <vector>
43 
44 namespace vkt
45 {
46 namespace MeshShader
47 {
48 
49 namespace
50 {
51 
52 using GroupPtr = de::MovePtr<tcu::TestCaseGroup>;
53 
54 using namespace vk;
55 
56 // Stages that will be used in these tests.
57 enum class Stage
58 {
59 	HOST = 0,
60 	TRANSFER,
61 	TASK,
62 	MESH,
63 	FRAG,
64 };
65 
operator <<(std::ostream & stream,Stage stage)66 std::ostream& operator<< (std::ostream& stream, Stage stage)
67 {
68 	switch (stage)
69 	{
70 	case Stage::HOST:		stream << "host";		break;
71 	case Stage::TRANSFER:	stream << "transfer";	break;
72 	case Stage::TASK:		stream << "task";		break;
73 	case Stage::MESH:		stream << "mesh";		break;
74 	case Stage::FRAG:		stream << "frag";		break;
75 	default: DE_ASSERT(false); break;
76 	}
77 
78 	return stream;
79 }
80 
isShaderStage(Stage stage)81 bool isShaderStage (Stage stage)
82 {
83 	return (stage == Stage::TASK || stage == Stage::MESH || stage == Stage::FRAG);
84 }
85 
stageToFlags(Stage stage)86 VkPipelineStageFlags stageToFlags (Stage stage)
87 {
88 	switch (stage)
89 	{
90 	case Stage::HOST:		return VK_PIPELINE_STAGE_HOST_BIT;
91 	case Stage::TRANSFER:	return VK_PIPELINE_STAGE_TRANSFER_BIT;
92 	case Stage::TASK:		return VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV;
93 	case Stage::MESH:		return VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV;
94 	case Stage::FRAG:		return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
95 	default:				DE_ASSERT(false); break;
96 	}
97 
98 	// Unreachable.
99 	DE_ASSERT(false);
100 	return 0u;
101 }
102 
getImageFormat()103 VkFormat getImageFormat ()
104 {
105 	return VK_FORMAT_R32_UINT;
106 }
107 
getImageExtent()108 VkExtent3D getImageExtent ()
109 {
110 	return makeExtent3D(1u, 1u, 1u);
111 }
112 
113 // Types of resources we will use.
114 enum class ResourceType
115 {
116 	UNIFORM_BUFFER = 0,
117 	STORAGE_BUFFER,
118 	STORAGE_IMAGE,
119 	SAMPLED_IMAGE,
120 };
121 
resourceTypeToDescriptor(ResourceType resType)122 VkDescriptorType resourceTypeToDescriptor (ResourceType resType)
123 {
124 	switch (resType)
125 	{
126 	case ResourceType::UNIFORM_BUFFER:	return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
127 	case ResourceType::STORAGE_BUFFER:	return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
128 	case ResourceType::STORAGE_IMAGE:	return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
129 	case ResourceType::SAMPLED_IMAGE:	return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
130 	default:							DE_ASSERT(false); break;
131 	}
132 
133 	// Unreachable.
134 	DE_ASSERT(false);
135 	return VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
136 }
137 
138 // Will the test use a specific barrier or a general memory barrier?
139 enum class BarrierType
140 {
141 	GENERAL = 0,
142 	SPECIFIC,
143 	DEPENDENCY,
144 };
145 
146 // Types of writes we will use.
147 enum class WriteAccess
148 {
149 	HOST_WRITE = 0,
150 	TRANSFER_WRITE,
151 	SHADER_WRITE,
152 };
153 
writeAccessToFlags(WriteAccess access)154 VkAccessFlags writeAccessToFlags (WriteAccess access)
155 {
156 	switch (access)
157 	{
158 	case WriteAccess::HOST_WRITE:		return VK_ACCESS_HOST_WRITE_BIT;
159 	case WriteAccess::TRANSFER_WRITE:	return VK_ACCESS_TRANSFER_WRITE_BIT;
160 	case WriteAccess::SHADER_WRITE:		return VK_ACCESS_SHADER_WRITE_BIT;
161 	default:							DE_ASSERT(false); break;
162 	}
163 
164 	// Unreachable.
165 	DE_ASSERT(false);
166 	return 0u;
167 }
168 
169 // Types of reads we will use.
170 enum class ReadAccess
171 {
172 	HOST_READ = 0,
173 	TRANSFER_READ,
174 	SHADER_READ,
175 	UNIFORM_READ,
176 };
177 
readAccessToFlags(ReadAccess access)178 VkAccessFlags readAccessToFlags (ReadAccess access)
179 {
180 	switch (access)
181 	{
182 	case ReadAccess::HOST_READ:			return VK_ACCESS_HOST_READ_BIT;
183 	case ReadAccess::TRANSFER_READ:		return VK_ACCESS_TRANSFER_READ_BIT;
184 	case ReadAccess::SHADER_READ:		return VK_ACCESS_SHADER_READ_BIT;
185 	case ReadAccess::UNIFORM_READ:		return VK_ACCESS_UNIFORM_READ_BIT;
186 	default:							DE_ASSERT(false); break;
187 	}
188 
189 	// Unreachable.
190 	DE_ASSERT(false);
191 	return 0u;
192 }
193 
194 // Auxiliary functions to verify certain combinations are possible.
195 
196 // Check if the writing stage can use the specified write access.
canWriteFromStageAsAccess(Stage writeStage,WriteAccess access)197 bool canWriteFromStageAsAccess (Stage writeStage, WriteAccess access)
198 {
199 	switch (writeStage)
200 	{
201 	case Stage::HOST:		return (access == WriteAccess::HOST_WRITE);
202 	case Stage::TRANSFER:	return (access == WriteAccess::TRANSFER_WRITE);
203 	case Stage::TASK:		// fallthrough
204 	case Stage::MESH:		// fallthrough
205 	case Stage::FRAG:		return (access == WriteAccess::SHADER_WRITE);
206 	default:				DE_ASSERT(false); break;
207 	}
208 
209 	return false;
210 }
211 
212 // Check if the reading stage can use the specified read access.
canReadFromStageAsAccess(Stage readStage,ReadAccess access)213 bool canReadFromStageAsAccess (Stage readStage, ReadAccess access)
214 {
215 	switch (readStage)
216 	{
217 	case Stage::HOST:		return (access == ReadAccess::HOST_READ);
218 	case Stage::TRANSFER:	return (access == ReadAccess::TRANSFER_READ);
219 	case Stage::TASK:		// fallthrough
220 	case Stage::MESH:		// fallthrough
221 	case Stage::FRAG:		return (access == ReadAccess::SHADER_READ || access == ReadAccess::UNIFORM_READ);
222 	default:				DE_ASSERT(false); break;
223 	}
224 
225 	return false;
226 }
227 
228 // Check if reading the given resource type is possible with the given type of read access.
canReadResourceAsAccess(ResourceType resType,ReadAccess access)229 bool canReadResourceAsAccess (ResourceType resType, ReadAccess access)
230 {
231 	if (access == ReadAccess::UNIFORM_READ)
232 		return (resType == ResourceType::UNIFORM_BUFFER);
233 	return true;
234 }
235 
236 // Check if writing to the given resource type is possible with the given type of write access.
canWriteResourceAsAccess(ResourceType resType,WriteAccess access)237 bool canWriteResourceAsAccess (ResourceType resType, WriteAccess access)
238 {
239 	if (resType == ResourceType::UNIFORM_BUFFER)
240 		return (access != WriteAccess::SHADER_WRITE);
241 	return true;
242 }
243 
244 // Check if the given stage can write to the given resource type.
canWriteTo(Stage stage,ResourceType resType)245 bool canWriteTo (Stage stage, ResourceType resType)
246 {
247 	switch (stage)
248 	{
249 	case Stage::HOST:		return (resType == ResourceType::UNIFORM_BUFFER || resType == ResourceType::STORAGE_BUFFER);
250 	case Stage::TRANSFER:	return true;
251 	case Stage::TASK:		// fallthrough
252 	case Stage::MESH:		return (resType == ResourceType::STORAGE_BUFFER || resType == ResourceType::STORAGE_IMAGE);
253 	default:				DE_ASSERT(false); break;
254 	}
255 
256 	return false;
257 }
258 
259 // Check if the given stage can read from the given resource type.
canReadFrom(Stage stage,ResourceType resType)260 bool canReadFrom (Stage stage, ResourceType resType)
261 {
262 	switch (stage)
263 	{
264 	case Stage::HOST:		return (resType == ResourceType::UNIFORM_BUFFER || resType == ResourceType::STORAGE_BUFFER);
265 	case Stage::TRANSFER:	// fallthrough
266 	case Stage::TASK:		// fallthrough
267 	case Stage::MESH:
268 	case Stage::FRAG:		return true;
269 	default:				DE_ASSERT(false); break;
270 	}
271 
272 	return false;
273 }
274 
275 // Will we need to store the test value in an auxiliar buffer to be read?
needsAuxiliarSourceBuffer(Stage fromStage,Stage toStage)276 bool needsAuxiliarSourceBuffer (Stage fromStage, Stage toStage)
277 {
278 	DE_UNREF(toStage);
279 	return (fromStage == Stage::TRANSFER);
280 }
281 
282 // Will we need to store the read operation result into an auxiliar buffer to be checked?
needsAuxiliarDestBuffer(Stage fromStage,Stage toStage)283 bool needsAuxiliarDestBuffer (Stage fromStage, Stage toStage)
284 {
285 	DE_UNREF(fromStage);
286 	return (toStage == Stage::TRANSFER);
287 }
288 
289 // Needs any auxiliar buffer for any case?
needsAuxiliarBuffer(Stage fromStage,Stage toStage)290 bool needsAuxiliarBuffer (Stage fromStage, Stage toStage)
291 {
292 	return (needsAuxiliarSourceBuffer(fromStage, toStage) || needsAuxiliarDestBuffer(fromStage, toStage));
293 }
294 
295 // Will the final value be stored in the auxiliar destination buffer?
valueInAuxiliarDestBuffer(Stage toStage)296 bool valueInAuxiliarDestBuffer (Stage toStage)
297 {
298 	return (toStage == Stage::TRANSFER);
299 }
300 
301 // Will the final value be stored in the resource buffer itself?
valueInResourceBuffer(Stage toStage)302 bool valueInResourceBuffer (Stage toStage)
303 {
304 	return (toStage == Stage::HOST);
305 }
306 
307 // Will the final value be stored in the color buffer?
valueInColorBuffer(Stage toStage)308 bool valueInColorBuffer (Stage toStage)
309 {
310 	return (!valueInAuxiliarDestBuffer(toStage) && !valueInResourceBuffer(toStage));
311 }
312 
313 // Image usage flags for the image resource.
resourceImageUsageFlags(ResourceType resourceType)314 VkImageUsageFlags resourceImageUsageFlags (ResourceType resourceType)
315 {
316 	VkImageUsageFlags flags = (VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
317 
318 	switch (resourceType)
319 	{
320 	case ResourceType::STORAGE_IMAGE:	flags |= VK_IMAGE_USAGE_STORAGE_BIT;	break;
321 	case ResourceType::SAMPLED_IMAGE:	flags |= VK_IMAGE_USAGE_SAMPLED_BIT;	break;
322 	default: DE_ASSERT(false); break;
323 	}
324 
325 	return flags;
326 }
327 
328 // Buffer usage flags for the buffer resource.
resourceBufferUsageFlags(ResourceType resourceType)329 VkBufferUsageFlags resourceBufferUsageFlags (ResourceType resourceType)
330 {
331 	VkBufferUsageFlags flags = (VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
332 
333 	switch (resourceType)
334 	{
335 	case ResourceType::UNIFORM_BUFFER:	flags |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;	break;
336 	case ResourceType::STORAGE_BUFFER:	flags |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;	break;
337 	default: DE_ASSERT(false); break;
338 	}
339 
340 	return flags;
341 }
342 
343 // A subpass dependency is needed if both the source and destination stages are shader stages.
needsSubpassDependency(Stage fromStage,Stage toStage)344 bool needsSubpassDependency (Stage fromStage, Stage toStage)
345 {
346 	return (isShaderStage(fromStage) && isShaderStage(toStage));
347 }
348 
349 struct TestParams
350 {
351 	Stage			fromStage;
352 	Stage			toStage;
353 	ResourceType	resourceType;
354 	BarrierType		barrierType;
355 	WriteAccess		writeAccess;
356 	ReadAccess		readAccess;
357 	uint32_t		testValue;
358 
359 protected:
readsOrWritesInvkt::MeshShader::__anon79afff990111::TestParams360 	bool readsOrWritesIn (Stage stage) const
361 	{
362 		DE_ASSERT(fromStage != toStage);
363 		return (fromStage == stage || toStage == stage);
364 	}
365 
366 public:
needsTaskvkt::MeshShader::__anon79afff990111::TestParams367 	bool needsTask () const
368 	{
369 		return readsOrWritesIn(Stage::TASK);
370 	}
371 
readsOrWritesInMeshvkt::MeshShader::__anon79afff990111::TestParams372 	bool readsOrWritesInMesh () const
373 	{
374 		return readsOrWritesIn(Stage::MESH);
375 	}
376 
getResourceDeclvkt::MeshShader::__anon79afff990111::TestParams377 	std::string getResourceDecl () const
378 	{
379 		const auto			imgFormat		= ((resourceType == ResourceType::STORAGE_IMAGE) ? ", r32ui" : "");
380 		const auto			storagePrefix	= ((writeAccess == WriteAccess::SHADER_WRITE) ? "" : "readonly ");
381 		std::ostringstream	decl;
382 
383 		decl << "layout (set=0, binding=0" << imgFormat << ") ";
384 		switch (resourceType)
385 		{
386 		case ResourceType::UNIFORM_BUFFER:	decl << "uniform UniformBuffer { uint value; } ub;";					break;
387 		case ResourceType::STORAGE_BUFFER:	decl << storagePrefix << "buffer StorageBuffer { uint value; } sb;";	break;
388 		case ResourceType::STORAGE_IMAGE:	decl << storagePrefix << "uniform uimage2D si;";						break;
389 		case ResourceType::SAMPLED_IMAGE:	decl << "uniform usampler2D sampled;";									break;
390 		default:							DE_ASSERT(false);														break;
391 		}
392 
393 		decl << "\n";
394 		return decl.str();
395 	}
396 
getReadStatementvkt::MeshShader::__anon79afff990111::TestParams397 	std::string getReadStatement (const std::string& outName) const
398 	{
399 		std::ostringstream statement;
400 		statement << "    " << outName << " = ";
401 
402 		switch (resourceType)
403 		{
404 		case ResourceType::UNIFORM_BUFFER:	statement << "ub.value";							break;
405 		case ResourceType::STORAGE_BUFFER:	statement << "sb.value";							break;
406 		case ResourceType::STORAGE_IMAGE:	statement << "imageLoad(si, ivec2(0, 0)).x";		break;
407 		case ResourceType::SAMPLED_IMAGE:	statement << "texture(sampled, vec2(0.5, 0.5)).x";	break;
408 		default:							DE_ASSERT(false); break;
409 		}
410 
411 		statement << ";\n";
412 		return statement.str();
413 	}
414 
getWriteStatementvkt::MeshShader::__anon79afff990111::TestParams415 	std::string getWriteStatement (const std::string& valueName) const
416 	{
417 		std::ostringstream statement;
418 		statement << "    ";
419 
420 		switch (resourceType)
421 		{
422 		case ResourceType::STORAGE_BUFFER:	statement << "sb.value = " << valueName;											break;
423 		case ResourceType::STORAGE_IMAGE:	statement << "imageStore(si, ivec2(0, 0), uvec4(" << valueName << ", 0, 0, 0))";	break;
424 		case ResourceType::UNIFORM_BUFFER:	// fallthrough
425 		case ResourceType::SAMPLED_IMAGE:	// fallthrough
426 		default:							DE_ASSERT(false); break;
427 		}
428 
429 		statement << ";\n";
430 		return statement.str();
431 	}
432 
getResourceShaderStagesvkt::MeshShader::__anon79afff990111::TestParams433 	VkShaderStageFlags getResourceShaderStages () const
434 	{
435 		VkShaderStageFlags flags = 0u;
436 
437 		if (fromStage == Stage::TASK || toStage == Stage::TASK)	flags |= VK_SHADER_STAGE_TASK_BIT_NV;
438 		if (fromStage == Stage::MESH || toStage == Stage::MESH)	flags |= VK_SHADER_STAGE_MESH_BIT_NV;
439 		if (fromStage == Stage::FRAG || toStage == Stage::FRAG)	flags |= VK_SHADER_STAGE_FRAGMENT_BIT;
440 
441 		// We assume at least something must be done either on the task or mesh shaders for the tests to be interesting.
442 		DE_ASSERT((flags & (VK_SHADER_STAGE_TASK_BIT_NV | VK_SHADER_STAGE_MESH_BIT_NV)) != 0u);
443 		return flags;
444 	}
445 
446 	// We'll prefer to keep the image in the general layout if it will be written to from a shader stage or if the barrier is going to be a generic memory barrier.
preferGeneralLayoutvkt::MeshShader::__anon79afff990111::TestParams447 	bool preferGeneralLayout () const
448 	{
449 		return (isShaderStage(fromStage) || (barrierType == BarrierType::GENERAL) || (resourceType == ResourceType::STORAGE_IMAGE));
450 	}
451 };
452 
453 class MeshShaderSyncCase : public vkt::TestCase
454 {
455 public:
MeshShaderSyncCase(tcu::TestContext & testCtx,const std::string & name,const std::string & description,const TestParams & params)456 					MeshShaderSyncCase		(tcu::TestContext& testCtx, const std::string& name, const std::string& description, const TestParams& params)
457 						: vkt::TestCase (testCtx, name, description), m_params (params)
458 						{}
459 
~MeshShaderSyncCase(void)460 	virtual			~MeshShaderSyncCase		(void) {}
461 
462 	void			checkSupport			(Context& context) const override;
463 	void			initPrograms			(vk::SourceCollections& programCollection) const override;
464 	TestInstance*	createInstance			(Context& context) const override;
465 
466 protected:
467 	TestParams		m_params;
468 };
469 
470 class MeshShaderSyncInstance : public vkt::TestInstance
471 {
472 public:
MeshShaderSyncInstance(Context & context,const TestParams & params)473 						MeshShaderSyncInstance	(Context& context, const TestParams& params) : vkt::TestInstance(context), m_params(params) {}
~MeshShaderSyncInstance(void)474 	virtual				~MeshShaderSyncInstance	(void) {}
475 
476 	tcu::TestStatus		iterate					(void) override;
477 
478 protected:
479 	TestParams			m_params;
480 };
481 
checkSupport(Context & context) const482 void MeshShaderSyncCase::checkSupport (Context& context) const
483 {
484 	context.requireDeviceFunctionality("VK_NV_mesh_shader");
485 
486 	const auto& meshFeatures = context.getMeshShaderFeatures();
487 
488 	if (!meshFeatures.meshShader)
489 		TCU_THROW(NotSupportedError, "Mesh shaders not supported");
490 
491 	if (m_params.needsTask() && !meshFeatures.taskShader)
492 		TCU_THROW(NotSupportedError, "Task shaders not supported");
493 
494 	if (m_params.writeAccess == WriteAccess::SHADER_WRITE)
495 	{
496 		const auto& features = context.getDeviceFeatures();
497 		if (!features.vertexPipelineStoresAndAtomics)
498 			TCU_THROW(NotSupportedError, "Vertex pipeline stores not supported");
499 	}
500 }
501 
initPrograms(vk::SourceCollections & programCollection) const502 void MeshShaderSyncCase::initPrograms (vk::SourceCollections& programCollection) const
503 {
504 	const bool	needsTaskShader	= m_params.needsTask();
505 	const auto	valueStr		= de::toString(m_params.testValue);
506 	const auto	resourceDecl	= m_params.getResourceDecl();
507 
508 	if (needsTaskShader)
509 	{
510 
511 		std::ostringstream task;
512 		task
513 			<< "#version 450\n"
514 			<< "#extension GL_NV_mesh_shader : enable\n"
515 			<< "\n"
516 			<< "layout(local_size_x=1) in;\n"
517 			<< "\n"
518 			<< "out taskNV TaskData { uint value; } td;\n"
519 			<< "\n"
520 			<< resourceDecl
521 			<< "\n"
522 			<< "void main ()\n"
523 			<< "{\n"
524 			<< "    gl_TaskCountNV = 1u;\n"
525 			<< "    td.value = 0u;\n"
526 			<< ((m_params.fromStage == Stage::TASK)	? m_params.getWriteStatement(valueStr)	: "")
527 			<< ((m_params.toStage == Stage::TASK)	? m_params.getReadStatement("td.value")	: "")
528 			<< "}\n"
529 			;
530 		programCollection.glslSources.add("task") << glu::TaskSource(task.str());
531 	}
532 
533 	{
534 		std::ostringstream mesh;
535 		mesh
536 			<< "#version 450\n"
537 			<< "#extension GL_NV_mesh_shader : enable\n"
538 			<< "\n"
539 			<< "layout(local_size_x=1) in;\n"
540 			<< "layout(triangles) out;\n"
541 			<< "layout(max_vertices=3, max_primitives=1) out;\n"
542 			<< "\n"
543 			<< (needsTaskShader ? "in taskNV TaskData { uint value; } td;\n" : "")
544 			<< "layout (location=0) out perprimitiveNV uint primitiveValue[];\n"
545 			<< "\n"
546 			<< (m_params.readsOrWritesInMesh() ? resourceDecl : "")
547 			<< "\n"
548 			<< "void main ()\n"
549 			<< "{\n"
550 			<< "    gl_PrimitiveCountNV = 1u;\n"
551 			<< (needsTaskShader ? "    primitiveValue[0] = td.value;\n" : "")
552 			<< ((m_params.fromStage == Stage::MESH)	? m_params.getWriteStatement(valueStr)				: "")
553 			<< ((m_params.toStage == Stage::MESH)	? m_params.getReadStatement("primitiveValue[0]")	: "")
554 			<< "\n"
555 			<< "    gl_MeshVerticesNV[0].gl_Position = vec4(-1.0, -1.0, 0.0, 1.0);\n"
556 			<< "    gl_MeshVerticesNV[1].gl_Position = vec4(-1.0,  3.0, 0.0, 1.0);\n"
557 			<< "    gl_MeshVerticesNV[2].gl_Position = vec4( 3.0, -1.0, 0.0, 1.0);\n"
558 			<< "    gl_PrimitiveIndicesNV[0] = 0;\n"
559 			<< "    gl_PrimitiveIndicesNV[1] = 1;\n"
560 			<< "    gl_PrimitiveIndicesNV[2] = 2;\n"
561 			<< "}\n"
562 			;
563 		programCollection.glslSources.add("mesh") << glu::MeshSource(mesh.str());
564 	}
565 
566 	{
567 		const bool			readFromFrag = (m_params.toStage == Stage::FRAG);
568 		std::ostringstream	frag;
569 
570 		frag
571 			<< "#version 450\n"
572 			<< "#extension GL_NV_mesh_shader : enable\n"
573 			<< "\n"
574 			<< "layout (location=0) in perprimitiveNV flat uint primitiveValue;\n"
575 			<< "layout (location=0) out uvec4 outColor;\n"
576 			<< "\n"
577 			<< (readFromFrag ? resourceDecl : "")
578 			<< "\n"
579 			<< "void main ()\n"
580 			<< "{\n"
581 			<< "	outColor = uvec4(primitiveValue, 0, 0, 0);\n"
582 			<< (readFromFrag ? m_params.getReadStatement("const uint readVal")	: "")
583 			<< (readFromFrag ? "    outColor = uvec4(readVal, 0, 0, 0);\n"		: "")
584 			<< "}\n"
585 			;
586 		programCollection.glslSources.add("frag") << glu::FragmentSource(frag.str());
587 	}
588 }
589 
createInstance(Context & context) const590 TestInstance* MeshShaderSyncCase::createInstance (Context& context) const
591 {
592 	return new MeshShaderSyncInstance(context, m_params);
593 }
594 
595 // General description behind these tests.
596 //
597 //	From				To
598 //	==============================
599 //	HOST				TASK			Prepare buffer from host. Only valid for uniform and storage buffers. Read value from task into td.value. Verify color buffer.
600 //	HOST				MESH			Same situation. Read value from mesh into primitiveValue[0]. Verify color buffer.
601 //	TRANSFER			TASK			Prepare auxiliary host-coherent source buffer from host. Copy buffer to buffer or buffer to image. Read from task into td.value. Verify color buffer.
602 //	TRANSFER			MESH			Same initial steps. Read from mesh into primitiveValue[0]. Verify color buffer.
603 //	TASK				MESH			Write value to buffer or image from task shader. Only valid for storage buffers and images. Read from mesh into primitiveValue[0]. Verify color buffer.
604 //	TASK				FRAG			Same write procedure and restrictions. Read from frag into outColor. Verify color buffer.
605 //	TASK				TRANSFER		Same write procedure and restrictions. Prepare auxiliary host-coherent read buffer and copy buffer to buffer or image to buffer. Verify auxiliary buffer.
606 //	TASK				HOST			Due to From/To restrictions, only valid for storage buffers. Same write procedure. Read and verify buffer directly.
607 //	MESH				FRAG			Same as task to frag but the write instructions need to be in the mesh shader.
608 //	MESH				TRANSFER		Same as task to transfer but the write instructions need to be in the mesh shader.
609 //	MESH				HOST			Same as task to host but the write instructions need to be in the mesh shader.
610 //
611 
createCustomRenderPass(const DeviceInterface & vkd,VkDevice device,VkFormat colorFormat,const TestParams & params)612 Move<VkRenderPass> createCustomRenderPass (const DeviceInterface& vkd, VkDevice device, VkFormat colorFormat, const TestParams& params)
613 {
614 	const std::vector<VkAttachmentDescription> attachmentDescs =
615 	{
616 		{
617 			0u,											//	VkAttachmentDescriptionFlags	flags;
618 			colorFormat,								//	VkFormat						format;
619 			VK_SAMPLE_COUNT_1_BIT,						//	VkSampleCountFlagBits			samples;
620 			VK_ATTACHMENT_LOAD_OP_CLEAR,				//	VkAttachmentLoadOp				loadOp;
621 			VK_ATTACHMENT_STORE_OP_STORE,				//	VkAttachmentStoreOp				storeOp;
622 			VK_ATTACHMENT_LOAD_OP_DONT_CARE,			//	VkAttachmentLoadOp				stencilLoadOp;
623 			VK_ATTACHMENT_STORE_OP_DONT_CARE,			//	VkAttachmentStoreOp				stencilStoreOp;
624 			VK_IMAGE_LAYOUT_UNDEFINED,					//	VkImageLayout					initialLayout;
625 			VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,	//	VkImageLayout					finalLayout;
626 		}
627 	};
628 
629 	const std::vector<VkAttachmentReference> attachmentRefs = { { 0u, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL } };
630 
631 	const std::vector<VkSubpassDescription> subpassDescs =
632 	{
633 		{
634 			0u,												//	VkSubpassDescriptionFlags		flags;
635 			VK_PIPELINE_BIND_POINT_GRAPHICS,				//	VkPipelineBindPoint				pipelineBindPoint;
636 			0u,												//	uint32_t						inputAttachmentCount;
637 			nullptr,										//	const VkAttachmentReference*	pInputAttachments;
638 			static_cast<uint32_t>(attachmentRefs.size()),	//	uint32_t						colorAttachmentCount;
639 			de::dataOrNull(attachmentRefs),					//	const VkAttachmentReference*	pColorAttachments;
640 			nullptr,										//	const VkAttachmentReference*	pResolveAttachments;
641 			nullptr,										//	const VkAttachmentReference*	pDepthStencilAttachment;
642 			0u,												//	uint32_t						preserveAttachmentCount;
643 			nullptr,										//	const uint32_t*					pPreserveAttachments;
644 		}
645 	};
646 
647 	// When both stages are shader stages, the dependency will be expressed as a subpass dependency.
648 	std::vector<VkSubpassDependency> dependencies;
649 	if (needsSubpassDependency(params.fromStage, params.toStage))
650 	{
651 		const VkSubpassDependency dependency =
652 		{
653 			0u,											//	uint32_t				srcSubpass;
654 			0u,											//	uint32_t				dstSubpass;
655 			stageToFlags(params.fromStage),				//	VkPipelineStageFlags	srcStageMask;
656 			stageToFlags(params.toStage),				//	VkPipelineStageFlags	dstStageMask;
657 			writeAccessToFlags(params.writeAccess),		//	VkAccessFlags			srcAccessMask;
658 			readAccessToFlags(params.readAccess),		//	VkAccessFlags			dstAccessMask;
659 			0u,											//	VkDependencyFlags		dependencyFlags;
660 		};
661 		dependencies.push_back(dependency);
662 	}
663 
664 	const VkRenderPassCreateInfo createInfo =
665 	{
666 		VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,		//	VkStructureType					sType;
667 		nullptr,										//	const void*						pNext;
668 		0u,												//	VkRenderPassCreateFlags			flags;
669 		static_cast<uint32_t>(attachmentDescs.size()),	//	uint32_t						attachmentCount;
670 		de::dataOrNull(attachmentDescs),				//	const VkAttachmentDescription*	pAttachments;
671 		static_cast<uint32_t>(subpassDescs.size()),		//	uint32_t						subpassCount;
672 		de::dataOrNull(subpassDescs),					//	const VkSubpassDescription*		pSubpasses;
673 		static_cast<uint32_t>(dependencies.size()),		//	uint32_t						dependencyCount;
674 		de::dataOrNull(dependencies),					//	const VkSubpassDependency*		pDependencies;
675 	};
676 
677 	return createRenderPass(vkd, device, &createInfo);
678 }
679 
hostToTransferMemoryBarrier(const DeviceInterface & vkd,VkCommandBuffer cmdBuffer)680 void hostToTransferMemoryBarrier (const DeviceInterface& vkd, VkCommandBuffer cmdBuffer)
681 {
682 	const auto barrier = makeMemoryBarrier(VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
683 	vkd.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 1u, &barrier, 0u, nullptr, 0u, nullptr);
684 }
685 
transferToHostMemoryBarrier(const DeviceInterface & vkd,VkCommandBuffer cmdBuffer)686 void transferToHostMemoryBarrier (const DeviceInterface& vkd, VkCommandBuffer cmdBuffer)
687 {
688 	const auto barrier = makeMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT);
689 	vkd.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 1u, &barrier, 0u, nullptr, 0u, nullptr);
690 }
691 
iterate(void)692 tcu::TestStatus MeshShaderSyncInstance::iterate (void)
693 {
694 	const auto&	vkd						= m_context.getDeviceInterface();
695 	const auto	device					= m_context.getDevice();
696 	auto&		alloc					= m_context.getDefaultAllocator();
697 	const auto	queueIndex				= m_context.getUniversalQueueFamilyIndex();
698 	const auto	queue					= m_context.getUniversalQueue();
699 
700 	const auto	imageFormat				= getImageFormat();
701 	const auto	imageExtent				= getImageExtent();
702 	const auto	colorBufferUsage		= (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
703 	const auto	colorSRR				= makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
704 	const auto	colorSRL				= makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, 1u);
705 	const auto	bufferSize				= static_cast<VkDeviceSize>(sizeof(m_params.testValue));
706 	const auto	descriptorType			= resourceTypeToDescriptor(m_params.resourceType);
707 	const auto	resourceStages			= m_params.getResourceShaderStages();
708 	const auto	auxiliarBufferUsage		= (VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
709 	const auto	useGeneralLayout		= m_params.preferGeneralLayout();
710 
711 	const auto	writeAccessFlags		= writeAccessToFlags(m_params.writeAccess);
712 	const auto	readAccessFlags			= readAccessToFlags(m_params.readAccess);
713 	const auto	fromStageFlags			= stageToFlags(m_params.fromStage);
714 	const auto	toStageFlags			= stageToFlags(m_params.toStage);
715 
716 	// Prepare color buffer.
717 	const VkImageCreateInfo colorBufferCreateInfo =
718 	{
719 		VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,	//	VkStructureType			sType;
720 		nullptr,								//	const void*				pNext;
721 		0u,										//	VkImageCreateFlags		flags;
722 		VK_IMAGE_TYPE_2D,						//	VkImageType				imageType;
723 		imageFormat,							//	VkFormat				format;
724 		imageExtent,							//	VkExtent3D				extent;
725 		1u,										//	uint32_t				mipLevels;
726 		1u,										//	uint32_t				arrayLayers;
727 		VK_SAMPLE_COUNT_1_BIT,					//	VkSampleCountFlagBits	samples;
728 		VK_IMAGE_TILING_OPTIMAL,				//	VkImageTiling			tiling;
729 		colorBufferUsage,						//	VkImageUsageFlags		usage;
730 		VK_SHARING_MODE_EXCLUSIVE,				//	VkSharingMode			sharingMode;
731 		0u,										//	uint32_t				queueFamilyIndexCount;
732 		nullptr,								//	const uint32_t*			pQueueFamilyIndices;
733 		VK_IMAGE_LAYOUT_UNDEFINED,				//	VkImageLayout			initialLayout;
734 	};
735 	ImageWithMemory	colorBuffer		(vkd, device, alloc, colorBufferCreateInfo, MemoryRequirement::Any);
736 	const auto		colorBufferView	= makeImageView(vkd, device, colorBuffer.get(), VK_IMAGE_VIEW_TYPE_2D, imageFormat, colorSRR);
737 
738 	// Main resource.
739 	using ImageWithMemoryPtr	= de::MovePtr<ImageWithMemory>;
740 	using BufferWithMemoryPtr	= de::MovePtr<BufferWithMemory>;
741 
742 	ImageWithMemoryPtr	imageResource;
743 	Move<VkImageView>	imageResourceView;
744 	VkImageLayout		imageDescriptorLayout	= (useGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
745 	VkImageLayout		currentLayout			= VK_IMAGE_LAYOUT_UNDEFINED;
746 	BufferWithMemoryPtr	bufferResource;
747 
748 	bool useImageResource	= false;
749 	bool useBufferResource	= false;
750 
751 	switch (m_params.resourceType)
752 	{
753 	case ResourceType::UNIFORM_BUFFER:
754 	case ResourceType::STORAGE_BUFFER:
755 		useBufferResource = true;
756 		break;
757 	case ResourceType::STORAGE_IMAGE:
758 	case ResourceType::SAMPLED_IMAGE:
759 		useImageResource = true;
760 		break;
761 	default:
762 		DE_ASSERT(false);
763 		break;
764 	}
765 
766 	// One resource needed.
767 	DE_ASSERT(useImageResource != useBufferResource);
768 
769 	if (useImageResource)
770 	{
771 		const auto resourceImageUsage = resourceImageUsageFlags(m_params.resourceType);
772 
773 		const VkImageCreateInfo resourceCreateInfo =
774 		{
775 			VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,	//	VkStructureType			sType;
776 			nullptr,								//	const void*				pNext;
777 			0u,										//	VkImageCreateFlags		flags;
778 			VK_IMAGE_TYPE_2D,						//	VkImageType				imageType;
779 			imageFormat,							//	VkFormat				format;
780 			imageExtent,							//	VkExtent3D				extent;
781 			1u,										//	uint32_t				mipLevels;
782 			1u,										//	uint32_t				arrayLayers;
783 			VK_SAMPLE_COUNT_1_BIT,					//	VkSampleCountFlagBits	samples;
784 			VK_IMAGE_TILING_OPTIMAL,				//	VkImageTiling			tiling;
785 			resourceImageUsage,						//	VkImageUsageFlags		usage;
786 			VK_SHARING_MODE_EXCLUSIVE,				//	VkSharingMode			sharingMode;
787 			0u,										//	uint32_t				queueFamilyIndexCount;
788 			nullptr,								//	const uint32_t*			pQueueFamilyIndices;
789 			VK_IMAGE_LAYOUT_UNDEFINED,				//	VkImageLayout			initialLayout;
790 		};
791 		imageResource		= ImageWithMemoryPtr(new ImageWithMemory(vkd, device, alloc, resourceCreateInfo, MemoryRequirement::Any));
792 		imageResourceView	= makeImageView(vkd, device, imageResource->get(), VK_IMAGE_VIEW_TYPE_2D, imageFormat, colorSRR);
793 	}
794 	else
795 	{
796 		const auto resourceBufferUsage		= resourceBufferUsageFlags(m_params.resourceType);
797 		const auto resourceBufferCreateInfo	= makeBufferCreateInfo(bufferSize, resourceBufferUsage);
798 		bufferResource = BufferWithMemoryPtr(new BufferWithMemory(vkd, device, alloc, resourceBufferCreateInfo, MemoryRequirement::HostVisible));
799 	}
800 
801 	Move<VkSampler> sampler;
802 	if (descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
803 	{
804 		const VkSamplerCreateInfo samplerCreateInfo =
805 		{
806 			VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,	//	VkStructureType			sType;
807 			nullptr,								//	const void*				pNext;
808 			0u,										//	VkSamplerCreateFlags	flags;
809 			VK_FILTER_NEAREST,						//	VkFilter				magFilter;
810 			VK_FILTER_NEAREST,						//	VkFilter				minFilter;
811 			VK_SAMPLER_MIPMAP_MODE_NEAREST,			//	VkSamplerMipmapMode		mipmapMode;
812 			VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,	//	VkSamplerAddressMode	addressModeU;
813 			VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,	//	VkSamplerAddressMode	addressModeV;
814 			VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,	//	VkSamplerAddressMode	addressModeW;
815 			0.0f,									//	float					mipLodBias;
816 			VK_FALSE,								//	VkBool32				anisotropyEnable;
817 			1.0f,									//	float					maxAnisotropy;
818 			VK_FALSE,								//	VkBool32				compareEnable;
819 			VK_COMPARE_OP_NEVER,					//	VkCompareOp				compareOp;
820 			0.0f,									//	float					minLod;
821 			0.0f,									//	float					maxLod;
822 			VK_BORDER_COLOR_INT_TRANSPARENT_BLACK,	//	VkBorderColor			borderColor;
823 			VK_FALSE,								//	VkBool32				unnormalizedCoordinates;
824 		};
825 		sampler = createSampler(vkd, device, &samplerCreateInfo);
826 	}
827 
828 	// Auxiliary host-coherent buffer for some cases. Being host-coherent lets us avoid extra barriers that would "pollute" synchronization tests.
829 	BufferWithMemoryPtr hostCoherentBuffer;
830 	void*				hostCoherentDataPtr = nullptr;
831 	if (needsAuxiliarBuffer(m_params.fromStage, m_params.toStage))
832 	{
833 		const auto auxiliarBufferCreateInfo = makeBufferCreateInfo(bufferSize, auxiliarBufferUsage);
834 		hostCoherentBuffer	= BufferWithMemoryPtr(new BufferWithMemory(vkd, device, alloc, auxiliarBufferCreateInfo, (MemoryRequirement::HostVisible | MemoryRequirement::Coherent)));
835 		hostCoherentDataPtr	= hostCoherentBuffer->getAllocation().getHostPtr();
836 	}
837 
838 	// Descriptor pool.
839 	Move<VkDescriptorPool> descriptorPool;
840 	{
841 		DescriptorPoolBuilder poolBuilder;
842 		poolBuilder.addType(descriptorType);
843 		descriptorPool = poolBuilder.build(vkd, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
844 	}
845 
846 	// Descriptor set layout.
847 	Move<VkDescriptorSetLayout> setLayout;
848 	{
849 		DescriptorSetLayoutBuilder layoutBuilder;
850 		layoutBuilder.addSingleBinding(descriptorType, resourceStages);
851 		setLayout = layoutBuilder.build(vkd, device);
852 	}
853 
854 	// Descriptor set.
855 	const auto descriptorSet = makeDescriptorSet(vkd, device, descriptorPool.get(), setLayout.get());
856 
857 	// Update descriptor set.
858 	{
859 		DescriptorSetUpdateBuilder	updateBuilder;
860 		const auto					location = DescriptorSetUpdateBuilder::Location::binding(0u);
861 
862 		switch (descriptorType)
863 		{
864 		case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
865 		case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
866 			{
867 				const auto bufferInfo = makeDescriptorBufferInfo(bufferResource->get(), 0ull, bufferSize);
868 				updateBuilder.writeSingle(descriptorSet.get(), location, descriptorType, &bufferInfo);
869 			}
870 			break;
871 		case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
872 		case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
873 			{
874 				auto descriptorImageInfo = makeDescriptorImageInfo(sampler.get(), imageResourceView.get(), imageDescriptorLayout);
875 				updateBuilder.writeSingle(descriptorSet.get(), location, descriptorType, &descriptorImageInfo);
876 			}
877 			break;
878 		default:
879 			DE_ASSERT(false); break;
880 		}
881 
882 		updateBuilder.update(vkd, device);
883 	}
884 
885 	// Shader modules.
886 	Move<VkShaderModule> taskShader;
887 	Move<VkShaderModule> meshShader;
888 	Move<VkShaderModule> fragShader;
889 
890 	const auto& binaries = m_context.getBinaryCollection();
891 
892 	if (m_params.needsTask())
893 		taskShader = createShaderModule(vkd, device, binaries.get("task"), 0u);
894 	meshShader = createShaderModule(vkd, device, binaries.get("mesh"), 0u);
895 	fragShader = createShaderModule(vkd, device, binaries.get("frag"), 0u);
896 
897 	// Pipeline layout, render pass, framebuffer.
898 	const auto pipelineLayout	= makePipelineLayout(vkd, device, setLayout.get());
899 	const auto renderPass		= createCustomRenderPass(vkd, device, imageFormat, m_params);
900 	const auto framebuffer		= makeFramebuffer(vkd, device, renderPass.get(), colorBufferView.get(), imageExtent.width, imageExtent.height);
901 
902 	// Pipeline.
903 	std::vector<VkViewport>	viewports	(1u, makeViewport(imageExtent));
904 	std::vector<VkRect2D>	scissors	(1u, makeRect2D(imageExtent));
905 	const auto				pipeline	= makeGraphicsPipeline(vkd, device, pipelineLayout.get(), taskShader.get(), meshShader.get(), fragShader.get(), renderPass.get(), viewports, scissors);
906 
907 	// Command pool and buffer.
908 	const auto cmdPool		= makeCommandPool(vkd, device, queueIndex);
909 	const auto cmdBufferPtr	= allocateCommandBuffer(vkd, device, cmdPool.get(), VK_COMMAND_BUFFER_LEVEL_PRIMARY);
910 	const auto cmdBuffer	= cmdBufferPtr.get();
911 
912 	beginCommandBuffer(vkd, cmdBuffer);
913 
914 	if (m_params.fromStage == Stage::HOST)
915 	{
916 		// Prepare buffer from host when the source stage is the host.
917 		DE_ASSERT(useBufferResource);
918 
919 		auto& resourceBufferAlloc	= bufferResource->getAllocation();
920 		void* resourceBufferDataPtr	= resourceBufferAlloc.getHostPtr();
921 
922 		deMemcpy(resourceBufferDataPtr, &m_params.testValue, sizeof(m_params.testValue));
923 		flushAlloc(vkd, device, resourceBufferAlloc);
924 	}
925 	else if (m_params.fromStage == Stage::TRANSFER)
926 	{
927 		// Put value in host-coherent buffer and transfer it to the resource buffer or image.
928 		deMemcpy(hostCoherentDataPtr, &m_params.testValue, sizeof(m_params.testValue));
929 		hostToTransferMemoryBarrier(vkd, cmdBuffer);
930 
931 		if (useBufferResource)
932 		{
933 			const auto copyRegion = makeBufferCopy(0ull, 0ull, bufferSize);
934 			vkd.cmdCopyBuffer(cmdBuffer, hostCoherentBuffer->get(), bufferResource->get(), 1u, &copyRegion);
935 		}
936 		else
937 		{
938 			// Move image to the right layout for transfer.
939 			const auto newLayout = (useGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
940 			if (newLayout != currentLayout)
941 			{
942 				const auto preCopyBarrier = makeImageMemoryBarrier(0u, VK_ACCESS_TRANSFER_WRITE_BIT, currentLayout, newLayout, imageResource->get(), colorSRR);
943 				vkd.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, nullptr, 0u, nullptr, 1u, &preCopyBarrier);
944 				currentLayout = newLayout;
945 			}
946 			const auto copyRegion = makeBufferImageCopy(imageExtent, colorSRL);
947 			vkd.cmdCopyBufferToImage(cmdBuffer, hostCoherentBuffer->get(), imageResource->get(), currentLayout, 1u, &copyRegion);
948 		}
949 	}
950 	else if (m_params.fromStage == Stage::TASK || m_params.fromStage == Stage::MESH)
951 	{
952 		// The image or buffer will be written to from shaders. Images need to be in the right layout.
953 		if (useImageResource)
954 		{
955 			const auto newLayout = VK_IMAGE_LAYOUT_GENERAL;
956 			if (newLayout != currentLayout)
957 			{
958 				const auto preWriteBarrier = makeImageMemoryBarrier(0u, (VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT), currentLayout, newLayout, imageResource->get(), colorSRR);
959 				vkd.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, fromStageFlags, 0u, 0u, nullptr, 0u, nullptr, 1u, &preWriteBarrier);
960 				currentLayout = newLayout;
961 			}
962 		}
963 	}
964 	else
965 	{
966 		DE_ASSERT(false);
967 	}
968 
969 	// If the resource is going to be read from shaders, we'll insert the main barrier before running the pipeline.
970 	if (isShaderStage(m_params.toStage))
971 	{
972 		if (m_params.barrierType == BarrierType::GENERAL)
973 		{
974 			const auto memoryBarrier = makeMemoryBarrier(writeAccessFlags, readAccessFlags);
975 			vkd.cmdPipelineBarrier(cmdBuffer, fromStageFlags, toStageFlags, 0u, 1u, &memoryBarrier, 0u, nullptr, 0u, nullptr);
976 		}
977 		else if (m_params.barrierType == BarrierType::SPECIFIC)
978 		{
979 			if (useBufferResource)
980 			{
981 				const auto bufferBarrier = makeBufferMemoryBarrier(writeAccessFlags, readAccessFlags, bufferResource->get(), 0ull, bufferSize);
982 				vkd.cmdPipelineBarrier(cmdBuffer, fromStageFlags, toStageFlags, 0u, 0u, nullptr, 1u, &bufferBarrier, 0u, nullptr);
983 			}
984 			else
985 			{
986 				const auto newLayout	= (useGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
987 				const auto imageBarrier	= makeImageMemoryBarrier(writeAccessFlags, readAccessFlags, currentLayout, newLayout, imageResource->get(), colorSRR);
988 
989 				vkd.cmdPipelineBarrier(cmdBuffer, fromStageFlags, toStageFlags, 0u, 0u, nullptr, 0u, nullptr, 1u, &imageBarrier);
990 				currentLayout = newLayout;
991 			}
992 		}
993 		// For subpass dependencies, they have already been included in the render pass.
994 	}
995 
996 	// Run the pipeline.
997 	beginRenderPass(vkd, cmdBuffer, renderPass.get(), framebuffer.get(), scissors.at(0), tcu::UVec4(0u));
998 	vkd.cmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout.get(), 0u, 1u, &descriptorSet.get(), 0u, nullptr);
999 	vkd.cmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.get());
1000 	vkd.cmdDrawMeshTasksNV(cmdBuffer, 1u, 0u);
1001 	endRenderPass(vkd, cmdBuffer);
1002 
1003 	// If the resource was written to from the shaders, insert the main barrier after running the pipeline.
1004 	if (isShaderStage(m_params.fromStage))
1005 	{
1006 		if (m_params.barrierType == BarrierType::GENERAL)
1007 		{
1008 			const auto memoryBarrier = makeMemoryBarrier(writeAccessFlags, readAccessFlags);
1009 			vkd.cmdPipelineBarrier(cmdBuffer, fromStageFlags, toStageFlags, 0u, 1u, &memoryBarrier, 0u, nullptr, 0u, nullptr);
1010 		}
1011 		else if (m_params.barrierType == BarrierType::SPECIFIC)
1012 		{
1013 			if (useBufferResource)
1014 			{
1015 				const auto bufferBarrier = makeBufferMemoryBarrier(writeAccessFlags, readAccessFlags, bufferResource->get(), 0ull, bufferSize);
1016 				vkd.cmdPipelineBarrier(cmdBuffer, fromStageFlags, toStageFlags, 0u, 0u, nullptr, 1u, &bufferBarrier, 0u, nullptr);
1017 			}
1018 			else
1019 			{
1020 				// Note: the image will only be read from shader stages (which is covered in BarrierType::DEPENDENCY) or from the transfer stage.
1021 				const auto newLayout	= (useGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
1022 				const auto imageBarrier	= makeImageMemoryBarrier(writeAccessFlags, readAccessFlags, currentLayout, newLayout, imageResource->get(), colorSRR);
1023 
1024 				vkd.cmdPipelineBarrier(cmdBuffer, fromStageFlags, toStageFlags, 0u, 0u, nullptr, 0u, nullptr, 1u, &imageBarrier);
1025 				currentLayout = newLayout;
1026 			}
1027 		}
1028 		// For subpass dependencies, they have already been included in the render pass.
1029 	}
1030 
1031 	// Read resource from the destination stage if needed.
1032 	if (m_params.toStage == Stage::HOST)
1033 	{
1034 		// Nothing to do. The test value should be in the resource buffer already, which is host-visible.
1035 	}
1036 	else if (m_params.toStage == Stage::TRANSFER)
1037 	{
1038 		// Copy value from resource to host-coherent buffer to be verified later.
1039 		if (useBufferResource)
1040 		{
1041 			const auto copyRegion = makeBufferCopy(0ull, 0ull, bufferSize);
1042 			vkd.cmdCopyBuffer(cmdBuffer, bufferResource->get(), hostCoherentBuffer->get(), 1u, &copyRegion);
1043 		}
1044 		else
1045 		{
1046 			const auto copyRegion = makeBufferImageCopy(imageExtent, colorSRL);
1047 			vkd.cmdCopyImageToBuffer(cmdBuffer, imageResource->get(), currentLayout, hostCoherentBuffer->get(), 1u, &copyRegion);
1048 		}
1049 
1050 		transferToHostMemoryBarrier(vkd, cmdBuffer);
1051 	}
1052 
1053 	// If the output value will be available in the color buffer, take the chance to transfer its contents to a host-coherent buffer.
1054 	BufferWithMemoryPtr colorVerificationBuffer;
1055 	void*				colorVerificationDataPtr = nullptr;
1056 
1057 	if (valueInColorBuffer(m_params.toStage))
1058 	{
1059 		const auto auxiliarBufferCreateInfo = makeBufferCreateInfo(bufferSize, auxiliarBufferUsage);
1060 		colorVerificationBuffer		= BufferWithMemoryPtr(new BufferWithMemory(vkd, device, alloc, auxiliarBufferCreateInfo, (MemoryRequirement::HostVisible | MemoryRequirement::Coherent)));
1061 		colorVerificationDataPtr	= colorVerificationBuffer->getAllocation().getHostPtr();
1062 
1063 		const auto srcAccess	= (VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
1064 		const auto dstAccess	= VK_ACCESS_TRANSFER_READ_BIT;
1065 		const auto colorBarrier	= makeImageMemoryBarrier(srcAccess, dstAccess, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, colorBuffer.get(), colorSRR);
1066 		vkd.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, nullptr, 0u, nullptr, 1u, &colorBarrier);
1067 
1068 		const auto copyRegion = makeBufferImageCopy(imageExtent, colorSRL);
1069 		vkd.cmdCopyImageToBuffer(cmdBuffer, colorBuffer.get(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, colorVerificationBuffer->get(), 1u, &copyRegion);
1070 
1071 		transferToHostMemoryBarrier(vkd, cmdBuffer);
1072 	}
1073 
1074 
1075 	endCommandBuffer(vkd, cmdBuffer);
1076 	submitCommandsAndWait(vkd, device, queue, cmdBuffer);
1077 
1078 	// Verify output resources as needed.
1079 
1080 	if (valueInAuxiliarDestBuffer(m_params.toStage))
1081 	{
1082 		uint32_t bufferValue;
1083 		deMemcpy(&bufferValue, hostCoherentDataPtr, sizeof(bufferValue));
1084 
1085 		if (bufferValue != m_params.testValue)
1086 		{
1087 			std::ostringstream msg;
1088 			msg << "Unexpected value in auxiliar host-coherent buffer: found " << bufferValue << " and expected " << m_params.testValue;
1089 			TCU_FAIL(msg.str());
1090 		}
1091 	}
1092 
1093 	if (valueInResourceBuffer(m_params.toStage))
1094 	{
1095 		auto&		resourceBufferAlloc		= bufferResource->getAllocation();
1096 		void*		resourceBufferDataPtr	= resourceBufferAlloc.getHostPtr();
1097 		uint32_t	bufferValue;
1098 
1099 		invalidateAlloc(vkd, device, resourceBufferAlloc);
1100 		deMemcpy(&bufferValue, resourceBufferDataPtr, sizeof(bufferValue));
1101 
1102 		if (bufferValue != m_params.testValue)
1103 		{
1104 			std::ostringstream msg;
1105 			msg << "Unexpected value in resource buffer: found " << bufferValue << " and expected " << m_params.testValue;
1106 			TCU_FAIL(msg.str());
1107 		}
1108 	}
1109 
1110 	if (valueInColorBuffer(m_params.toStage))
1111 	{
1112 		uint32_t bufferValue;
1113 		deMemcpy(&bufferValue, colorVerificationDataPtr, sizeof(bufferValue));
1114 
1115 		if (bufferValue != m_params.testValue)
1116 		{
1117 			std::ostringstream msg;
1118 			msg << "Unexpected value in color verification buffer: found " << bufferValue << " and expected " << m_params.testValue;
1119 			TCU_FAIL(msg.str());
1120 		}
1121 	}
1122 
1123 	return tcu::TestStatus::pass("Pass");
1124 }
1125 
1126 } // anonymous
1127 
createMeshShaderSyncTests(tcu::TestContext & testCtx)1128 tcu::TestCaseGroup* createMeshShaderSyncTests (tcu::TestContext& testCtx)
1129 {
1130 	const struct
1131 	{
1132 		Stage		fromStage;
1133 		Stage		toStage;
1134 	} stageCombinations[] =
1135 	{
1136 		// Combinations where the source and destination stages involve mesh shaders.
1137 		// Note: this could be tested procedurally.
1138 		{	Stage::HOST,		Stage::TASK			},
1139 		{	Stage::HOST,		Stage::MESH			},
1140 		{	Stage::TRANSFER,	Stage::TASK			},
1141 		{	Stage::TRANSFER,	Stage::MESH			},
1142 		{	Stage::TASK,		Stage::MESH			},
1143 		{	Stage::TASK,		Stage::FRAG			},
1144 		{	Stage::TASK,		Stage::TRANSFER		},
1145 		{	Stage::TASK,		Stage::HOST			},
1146 		{	Stage::MESH,		Stage::FRAG			},
1147 		{	Stage::MESH,		Stage::TRANSFER		},
1148 		{	Stage::MESH,		Stage::HOST			},
1149 	};
1150 
1151 	const struct
1152 	{
1153 		ResourceType	resourceType;
1154 		const char*		name;
1155 	} resourceTypes[] =
1156 	{
1157 		{ ResourceType::UNIFORM_BUFFER,	"uniform_buffer"	},
1158 		{ ResourceType::STORAGE_BUFFER,	"storage_buffer"	},
1159 		{ ResourceType::STORAGE_IMAGE,	"storage_image"		},
1160 		{ ResourceType::SAMPLED_IMAGE,	"sampled_image"		},
1161 	};
1162 
1163 	const struct
1164 	{
1165 		BarrierType		barrierType;
1166 		const char*		name;
1167 	} barrierTypes[] =
1168 	{
1169 		{	BarrierType::GENERAL,		"memory_barrier"		},
1170 		{	BarrierType::SPECIFIC,		"specific_barrier"		},
1171 		{	BarrierType::DEPENDENCY,	"subpass_dependency"	},
1172 	};
1173 
1174 	const struct
1175 	{
1176 		WriteAccess		writeAccess;
1177 		const char*		name;
1178 	} writeAccesses[] =
1179 	{
1180 		{	WriteAccess::HOST_WRITE,		"host_write"		},
1181 		{	WriteAccess::TRANSFER_WRITE,	"transfer_write"	},
1182 		{	WriteAccess::SHADER_WRITE,		"shader_write"		},
1183 	};
1184 
1185 	const struct
1186 	{
1187 		ReadAccess		readAccess;
1188 		const char*		name;
1189 	} readAccesses[] =
1190 	{
1191 		{	ReadAccess::HOST_READ,		"host_read"		},
1192 		{	ReadAccess::TRANSFER_READ,	"transfer_read"	},
1193 		{	ReadAccess::SHADER_READ,	"shader_read"	},
1194 		{	ReadAccess::UNIFORM_READ,	"uniform_read"	},
1195 	};
1196 
1197 	uint32_t testValue = 1628510124u;
1198 
1199 	GroupPtr mainGroup (new tcu::TestCaseGroup(testCtx, "synchronization", "Mesh Shader synchronization tests"));
1200 
1201 	for (const auto& stageCombination : stageCombinations)
1202 	{
1203 		const std::string	combinationName		= de::toString(stageCombination.fromStage) + "_to_" + de::toString(stageCombination.toStage);
1204 		GroupPtr			combinationGroup	(new tcu::TestCaseGroup(testCtx, combinationName.c_str(), ""));
1205 
1206 		for (const auto& resourceCase : resourceTypes)
1207 		{
1208 			if (!canWriteTo(stageCombination.fromStage, resourceCase.resourceType))
1209 				continue;
1210 
1211 			if (!canReadFrom(stageCombination.toStage, resourceCase.resourceType))
1212 				continue;
1213 
1214 			GroupPtr resourceGroup (new tcu::TestCaseGroup(testCtx, resourceCase.name, ""));
1215 
1216 			for (const auto& barrierCase : barrierTypes)
1217 			{
1218 				const auto subpassDependencyNeeded	= needsSubpassDependency(stageCombination.fromStage, stageCombination.toStage);
1219 				const auto barrierIsDependency		= (barrierCase.barrierType == BarrierType::DEPENDENCY);
1220 
1221 				// Subpass dependencies must be used if, and only if, they are needed.
1222 				if (subpassDependencyNeeded != barrierIsDependency)
1223 					continue;
1224 
1225 				GroupPtr barrierGroup (new tcu::TestCaseGroup(testCtx, barrierCase.name, ""));
1226 
1227 				for (const auto& writeCase	: writeAccesses)
1228 				for (const auto& readCase	: readAccesses)
1229 				{
1230 					if (!canReadResourceAsAccess(resourceCase.resourceType, readCase.readAccess))
1231 						continue;
1232 					if (!canWriteResourceAsAccess(resourceCase.resourceType, writeCase.writeAccess))
1233 						continue;
1234 					if (!canReadFromStageAsAccess(stageCombination.toStage, readCase.readAccess))
1235 						continue;
1236 					if (!canWriteFromStageAsAccess(stageCombination.fromStage, writeCase.writeAccess))
1237 						continue;
1238 
1239 					const std::string accessCaseName = writeCase.name + std::string("_") + readCase.name;
1240 
1241 					const TestParams testParams =
1242 					{
1243 						stageCombination.fromStage,	//	Stage			fromStage;
1244 						stageCombination.toStage,	//	Stage			toStage;
1245 						resourceCase.resourceType,	//	ResourceType	resourceType;
1246 						barrierCase.barrierType,	//	BarrierType		barrierType;
1247 						writeCase.writeAccess,		//	WriteAccess		writeAccess;
1248 						readCase.readAccess,		//	ReadAccess		readAccess;
1249 						testValue++,				//	uint32_t		testValue;
1250 					};
1251 
1252 					barrierGroup->addChild(new MeshShaderSyncCase(testCtx, accessCaseName, "", testParams));
1253 				}
1254 
1255 				resourceGroup->addChild(barrierGroup.release());
1256 			}
1257 
1258 			combinationGroup->addChild(resourceGroup.release());
1259 		}
1260 
1261 		mainGroup->addChild(combinationGroup.release());
1262 	}
1263 
1264 	return mainGroup.release();
1265 }
1266 
1267 } // MeshShader
1268 } // vkt
1269