• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "Renderer.hpp"
16 
17 #include "Clipper.hpp"
18 #include "Polygon.hpp"
19 #include "Primitive.hpp"
20 #include "Vertex.hpp"
21 #include "Pipeline/Constants.hpp"
22 #include "Pipeline/SpirvShader.hpp"
23 #include "Reactor/Reactor.hpp"
24 #include "System/Debug.hpp"
25 #include "System/Half.hpp"
26 #include "System/Math.hpp"
27 #include "System/Memory.hpp"
28 #include "System/Timer.hpp"
29 #include "Vulkan/VkConfig.hpp"
30 #include "Vulkan/VkDescriptorSet.hpp"
31 #include "Vulkan/VkDevice.hpp"
32 #include "Vulkan/VkFence.hpp"
33 #include "Vulkan/VkImageView.hpp"
34 #include "Vulkan/VkPipelineLayout.hpp"
35 #include "Vulkan/VkQueryPool.hpp"
36 
37 #include "marl/containers.h"
38 #include "marl/defer.h"
39 #include "marl/trace.h"
40 
41 #undef max
42 
43 #ifndef NDEBUG
44 unsigned int minPrimitives = 1;
45 unsigned int maxPrimitives = 1 << 21;
46 #endif
47 
48 namespace sw {
49 
50 template<typename T>
setBatchIndices(unsigned int batch[128][3],VkPrimitiveTopology topology,VkProvokingVertexModeEXT provokingVertexMode,T indices,unsigned int start,unsigned int triangleCount)51 inline bool setBatchIndices(unsigned int batch[128][3], VkPrimitiveTopology topology, VkProvokingVertexModeEXT provokingVertexMode, T indices, unsigned int start, unsigned int triangleCount)
52 {
53 	bool provokeFirst = (provokingVertexMode == VK_PROVOKING_VERTEX_MODE_FIRST_VERTEX_EXT);
54 
55 	switch(topology)
56 	{
57 	case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
58 		{
59 			auto index = start;
60 			auto pointBatch = &(batch[0][0]);
61 			for(unsigned int i = 0; i < triangleCount; i++)
62 			{
63 				*pointBatch++ = indices[index++];
64 			}
65 
66 			// Repeat the last index to allow for SIMD width overrun.
67 			index--;
68 			for(unsigned int i = 0; i < 3; i++)
69 			{
70 				*pointBatch++ = indices[index];
71 			}
72 		}
73 		break;
74 	case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
75 		{
76 			auto index = 2 * start;
77 			for(unsigned int i = 0; i < triangleCount; i++)
78 			{
79 				batch[i][0] = indices[index + (provokeFirst ? 0 : 1)];
80 				batch[i][1] = indices[index + (provokeFirst ? 1 : 0)];
81 				batch[i][2] = indices[index + 1];
82 
83 				index += 2;
84 			}
85 		}
86 		break;
87 	case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
88 		{
89 			auto index = start;
90 			for(unsigned int i = 0; i < triangleCount; i++)
91 			{
92 				batch[i][0] = indices[index + (provokeFirst ? 0 : 1)];
93 				batch[i][1] = indices[index + (provokeFirst ? 1 : 0)];
94 				batch[i][2] = indices[index + 1];
95 
96 				index += 1;
97 			}
98 		}
99 		break;
100 	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
101 		{
102 			auto index = 3 * start;
103 			for(unsigned int i = 0; i < triangleCount; i++)
104 			{
105 				batch[i][0] = indices[index + (provokeFirst ? 0 : 2)];
106 				batch[i][1] = indices[index + (provokeFirst ? 1 : 0)];
107 				batch[i][2] = indices[index + (provokeFirst ? 2 : 1)];
108 
109 				index += 3;
110 			}
111 		}
112 		break;
113 	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
114 		{
115 			auto index = start;
116 			for(unsigned int i = 0; i < triangleCount; i++)
117 			{
118 				batch[i][0] = indices[index + (provokeFirst ? 0 : 2)];
119 				batch[i][1] = indices[index + ((start + i) & 1) + (provokeFirst ? 1 : 0)];
120 				batch[i][2] = indices[index + (~(start + i) & 1) + (provokeFirst ? 1 : 0)];
121 
122 				index += 1;
123 			}
124 		}
125 		break;
126 	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
127 		{
128 			auto index = start + 1;
129 			for(unsigned int i = 0; i < triangleCount; i++)
130 			{
131 				batch[i][provokeFirst ? 0 : 2] = indices[index + 0];
132 				batch[i][provokeFirst ? 1 : 0] = indices[index + 1];
133 				batch[i][provokeFirst ? 2 : 1] = indices[0];
134 
135 				index += 1;
136 			}
137 		}
138 		break;
139 	default:
140 		ASSERT(false);
141 		return false;
142 	}
143 
144 	return true;
145 }
146 
DrawCall()147 DrawCall::DrawCall()
148 {
149 	// TODO(b/140991626): Use allocateUninitialized() instead of allocateZeroOrPoison() to improve startup peformance.
150 	data = (DrawData *)sw::allocateZeroOrPoison(sizeof(DrawData));
151 }
152 
~DrawCall()153 DrawCall::~DrawCall()
154 {
155 	sw::freeMemory(data);
156 }
157 
Renderer(vk::Device * device)158 Renderer::Renderer(vk::Device *device)
159     : device(device)
160 {
161 	vertexProcessor.setRoutineCacheSize(1024);
162 	pixelProcessor.setRoutineCacheSize(1024);
163 	setupProcessor.setRoutineCacheSize(1024);
164 }
165 
~Renderer()166 Renderer::~Renderer()
167 {
168 	drawTickets.take().wait();
169 }
170 
171 // Renderer objects have to be mem aligned to the alignment provided in the class declaration
operator new(size_t size)172 void *Renderer::operator new(size_t size)
173 {
174 	ASSERT(size == sizeof(Renderer));  // This operator can't be called from a derived class
175 	return vk::allocateHostMemory(sizeof(Renderer), alignof(Renderer), vk::NULL_ALLOCATION_CALLBACKS, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
176 }
177 
operator delete(void * mem)178 void Renderer::operator delete(void *mem)
179 {
180 	vk::freeHostMemory(mem, vk::NULL_ALLOCATION_CALLBACKS);
181 }
182 
draw(const vk::GraphicsPipeline * pipeline,const vk::DynamicState & dynamicState,unsigned int count,int baseVertex,CountedEvent * events,int instanceID,int viewID,void * indexBuffer,const VkExtent3D & framebufferExtent,vk::Pipeline::PushConstantStorage const & pushConstants,bool update)183 void Renderer::draw(const vk::GraphicsPipeline *pipeline, const vk::DynamicState &dynamicState, unsigned int count, int baseVertex,
184                     CountedEvent *events, int instanceID, int viewID, void *indexBuffer, const VkExtent3D &framebufferExtent,
185                     vk::Pipeline::PushConstantStorage const &pushConstants, bool update)
186 {
187 	if(count == 0) { return; }
188 
189 	auto id = nextDrawID++;
190 	MARL_SCOPED_EVENT("draw %d", id);
191 
192 	marl::Pool<sw::DrawCall>::Loan draw;
193 	{
194 		MARL_SCOPED_EVENT("drawCallPool.borrow()");
195 		draw = drawCallPool.borrow();
196 	}
197 	draw->id = id;
198 
199 	const vk::GraphicsState &pipelineState = pipeline->getState(dynamicState);
200 	pixelProcessor.setBlendConstant(pipelineState.getBlendConstants());
201 
202 	const vk::Inputs &inputs = pipeline->getInputs();
203 
204 	if(update)
205 	{
206 		MARL_SCOPED_EVENT("update");
207 
208 		const sw::SpirvShader *fragmentShader = pipeline->getShader(VK_SHADER_STAGE_FRAGMENT_BIT).get();
209 		const sw::SpirvShader *vertexShader = pipeline->getShader(VK_SHADER_STAGE_VERTEX_BIT).get();
210 
211 		const vk::Attachments attachments = pipeline->getAttachments();
212 
213 		vertexState = vertexProcessor.update(pipelineState, vertexShader, inputs);
214 		setupState = setupProcessor.update(pipelineState, fragmentShader, vertexShader, attachments);
215 		pixelState = pixelProcessor.update(pipelineState, fragmentShader, vertexShader, attachments, hasOcclusionQuery());
216 
217 		vertexRoutine = vertexProcessor.routine(vertexState, pipelineState.getPipelineLayout(), vertexShader, inputs.getDescriptorSets());
218 		setupRoutine = setupProcessor.routine(setupState);
219 		pixelRoutine = pixelProcessor.routine(pixelState, pipelineState.getPipelineLayout(), fragmentShader, inputs.getDescriptorSets());
220 	}
221 
222 	draw->containsImageWrite = pipeline->containsImageWrite();
223 
224 	DrawCall::SetupFunction setupPrimitives = nullptr;
225 	int ms = pipelineState.getSampleCount();
226 	unsigned int numPrimitivesPerBatch = MaxBatchSize / ms;
227 
228 	if(pipelineState.isDrawTriangle(false))
229 	{
230 		switch(pipelineState.getPolygonMode())
231 		{
232 		case VK_POLYGON_MODE_FILL:
233 			setupPrimitives = &DrawCall::setupSolidTriangles;
234 			break;
235 		case VK_POLYGON_MODE_LINE:
236 			setupPrimitives = &DrawCall::setupWireframeTriangles;
237 			numPrimitivesPerBatch /= 3;
238 			break;
239 		case VK_POLYGON_MODE_POINT:
240 			setupPrimitives = &DrawCall::setupPointTriangles;
241 			numPrimitivesPerBatch /= 3;
242 			break;
243 		default:
244 			UNSUPPORTED("polygon mode: %d", int(pipelineState.getPolygonMode()));
245 			return;
246 		}
247 	}
248 	else if(pipelineState.isDrawLine(false))
249 	{
250 		setupPrimitives = &DrawCall::setupLines;
251 	}
252 	else  // Point primitive topology
253 	{
254 		setupPrimitives = &DrawCall::setupPoints;
255 	}
256 
257 	DrawData *data = draw->data;
258 	draw->occlusionQuery = occlusionQuery;
259 	draw->batchDataPool = &batchDataPool;
260 	draw->numPrimitives = count;
261 	draw->numPrimitivesPerBatch = numPrimitivesPerBatch;
262 	draw->numBatches = (count + draw->numPrimitivesPerBatch - 1) / draw->numPrimitivesPerBatch;
263 	draw->topology = pipelineState.getTopology();
264 	draw->provokingVertexMode = pipelineState.getProvokingVertexMode();
265 	draw->indexType = pipeline->getIndexBuffer().getIndexType();
266 	draw->lineRasterizationMode = pipelineState.getLineRasterizationMode();
267 	draw->descriptorSetObjects = inputs.getDescriptorSetObjects();
268 	draw->pipelineLayout = pipelineState.getPipelineLayout();
269 	draw->depthClipEnable = pipelineState.getDepthClipEnable();
270 
271 	draw->vertexRoutine = vertexRoutine;
272 	draw->setupRoutine = setupRoutine;
273 	draw->pixelRoutine = pixelRoutine;
274 	draw->setupPrimitives = setupPrimitives;
275 	draw->setupState = setupState;
276 
277 	data->descriptorSets = inputs.getDescriptorSets();
278 	data->descriptorDynamicOffsets = inputs.getDescriptorDynamicOffsets();
279 
280 	for(int i = 0; i < MAX_INTERFACE_COMPONENTS / 4; i++)
281 	{
282 		const sw::Stream &stream = inputs.getStream(i);
283 		data->input[i] = stream.buffer;
284 		data->robustnessSize[i] = stream.robustnessSize;
285 		data->stride[i] = stream.vertexStride;
286 	}
287 
288 	data->indices = indexBuffer;
289 	data->viewID = viewID;
290 	data->instanceID = instanceID;
291 	data->baseVertex = baseVertex;
292 
293 	if(pixelState.stencilActive)
294 	{
295 		data->stencil[0].set(pipelineState.getFrontStencil().reference, pipelineState.getFrontStencil().compareMask, pipelineState.getFrontStencil().writeMask);
296 		data->stencil[1].set(pipelineState.getBackStencil().reference, pipelineState.getBackStencil().compareMask, pipelineState.getBackStencil().writeMask);
297 	}
298 
299 	data->lineWidth = pipelineState.getLineWidth();
300 
301 	data->factor = pixelProcessor.factor;
302 
303 	if(pixelState.alphaToCoverage)
304 	{
305 		if(ms == 4)
306 		{
307 			data->a2c0 = float4(0.2f);
308 			data->a2c1 = float4(0.4f);
309 			data->a2c2 = float4(0.6f);
310 			data->a2c3 = float4(0.8f);
311 		}
312 		else if(ms == 2)
313 		{
314 			data->a2c0 = float4(0.25f);
315 			data->a2c1 = float4(0.75f);
316 		}
317 		else if(ms == 1)
318 		{
319 			data->a2c0 = float4(0.5f);
320 		}
321 		else
322 			ASSERT(false);
323 	}
324 
325 	if(pixelState.occlusionEnabled)
326 	{
327 		for(int cluster = 0; cluster < MaxClusterCount; cluster++)
328 		{
329 			data->occlusion[cluster] = 0;
330 		}
331 	}
332 
333 	// Viewport
334 	{
335 		const VkViewport &viewport = pipelineState.getViewport();
336 
337 		float W = 0.5f * viewport.width;
338 		float H = 0.5f * viewport.height;
339 		float X0 = viewport.x + W;
340 		float Y0 = viewport.y + H;
341 		float N = viewport.minDepth;
342 		float F = viewport.maxDepth;
343 		float Z = F - N;
344 		constexpr float subPixF = vk::SUBPIXEL_PRECISION_FACTOR;
345 
346 		data->WxF = float4(W * subPixF);
347 		data->HxF = float4(H * subPixF);
348 		data->X0xF = float4(X0 * subPixF - subPixF / 2);
349 		data->Y0xF = float4(Y0 * subPixF - subPixF / 2);
350 		data->halfPixelX = float4(0.5f / W);
351 		data->halfPixelY = float4(0.5f / H);
352 		data->viewportHeight = abs(viewport.height);
353 		data->depthRange = Z;
354 		data->depthNear = N;
355 		data->constantDepthBias = pipelineState.getConstantDepthBias();
356 		data->slopeDepthBias = pipelineState.getSlopeDepthBias();
357 		data->depthBiasClamp = pipelineState.getDepthBiasClamp();
358 		data->depthClipEnable = pipelineState.getDepthClipEnable();
359 
360 		const vk::Attachments attachments = pipeline->getAttachments();
361 		if(attachments.depthBuffer)
362 		{
363 			switch(attachments.depthBuffer->getFormat(VK_IMAGE_ASPECT_DEPTH_BIT))
364 			{
365 			case VK_FORMAT_D16_UNORM:
366 				data->minimumResolvableDepthDifference = 1.0f / 0xFFFF;
367 				break;
368 			case VK_FORMAT_D32_SFLOAT:
369 				// The minimum resolvable depth difference is determined per-polygon for floating-point depth
370 				// buffers. DrawData::minimumResolvableDepthDifference is unused.
371 				break;
372 			default:
373 				UNSUPPORTED("Depth format: %d", int(attachments.depthBuffer->getFormat(VK_IMAGE_ASPECT_DEPTH_BIT)));
374 			}
375 		}
376 	}
377 
378 	// Target
379 	{
380 		const vk::Attachments attachments = pipeline->getAttachments();
381 
382 		for(int index = 0; index < MAX_COLOR_BUFFERS; index++)
383 		{
384 			draw->colorBuffer[index] = attachments.colorBuffer[index];
385 
386 			if(draw->colorBuffer[index])
387 			{
388 				data->colorBuffer[index] = (unsigned int *)attachments.colorBuffer[index]->getOffsetPointer({ 0, 0, 0 }, VK_IMAGE_ASPECT_COLOR_BIT, 0, data->viewID);
389 				data->colorPitchB[index] = attachments.colorBuffer[index]->rowPitchBytes(VK_IMAGE_ASPECT_COLOR_BIT, 0);
390 				data->colorSliceB[index] = attachments.colorBuffer[index]->slicePitchBytes(VK_IMAGE_ASPECT_COLOR_BIT, 0);
391 			}
392 		}
393 
394 		draw->depthBuffer = attachments.depthBuffer;
395 		draw->stencilBuffer = attachments.stencilBuffer;
396 
397 		if(draw->depthBuffer)
398 		{
399 			data->depthBuffer = (float *)attachments.depthBuffer->getOffsetPointer({ 0, 0, 0 }, VK_IMAGE_ASPECT_DEPTH_BIT, 0, data->viewID);
400 			data->depthPitchB = attachments.depthBuffer->rowPitchBytes(VK_IMAGE_ASPECT_DEPTH_BIT, 0);
401 			data->depthSliceB = attachments.depthBuffer->slicePitchBytes(VK_IMAGE_ASPECT_DEPTH_BIT, 0);
402 		}
403 
404 		if(draw->stencilBuffer)
405 		{
406 			data->stencilBuffer = (unsigned char *)attachments.stencilBuffer->getOffsetPointer({ 0, 0, 0 }, VK_IMAGE_ASPECT_STENCIL_BIT, 0, data->viewID);
407 			data->stencilPitchB = attachments.stencilBuffer->rowPitchBytes(VK_IMAGE_ASPECT_STENCIL_BIT, 0);
408 			data->stencilSliceB = attachments.stencilBuffer->slicePitchBytes(VK_IMAGE_ASPECT_STENCIL_BIT, 0);
409 		}
410 	}
411 
412 	// Scissor
413 	{
414 		const VkRect2D &scissor = pipelineState.getScissor();
415 
416 		data->scissorX0 = clamp<int>(scissor.offset.x, 0, framebufferExtent.width);
417 		data->scissorX1 = clamp<int>(scissor.offset.x + scissor.extent.width, 0, framebufferExtent.width);
418 		data->scissorY0 = clamp<int>(scissor.offset.y, 0, framebufferExtent.height);
419 		data->scissorY1 = clamp<int>(scissor.offset.y + scissor.extent.height, 0, framebufferExtent.height);
420 	}
421 
422 	// Push constants
423 	{
424 		data->pushConstants = pushConstants;
425 	}
426 
427 	draw->events = events;
428 
429 	vk::DescriptorSet::PrepareForSampling(draw->descriptorSetObjects, draw->pipelineLayout, device);
430 
431 	DrawCall::run(device, draw, &drawTickets, clusterQueues);
432 }
433 
setup()434 void DrawCall::setup()
435 {
436 	if(occlusionQuery != nullptr)
437 	{
438 		occlusionQuery->start();
439 	}
440 
441 	if(events)
442 	{
443 		events->add();
444 	}
445 }
446 
teardown(vk::Device * device)447 void DrawCall::teardown(vk::Device *device)
448 {
449 	if(events)
450 	{
451 		events->done();
452 		events = nullptr;
453 	}
454 
455 	if(occlusionQuery != nullptr)
456 	{
457 		for(int cluster = 0; cluster < MaxClusterCount; cluster++)
458 		{
459 			occlusionQuery->add(data->occlusion[cluster]);
460 		}
461 		occlusionQuery->finish();
462 	}
463 
464 	vertexRoutine = {};
465 	setupRoutine = {};
466 	pixelRoutine = {};
467 
468 	for(auto *target : colorBuffer)
469 	{
470 		if(target)
471 		{
472 			target->contentsChanged(vk::Image::DIRECT_MEMORY_ACCESS);
473 		}
474 	}
475 
476 	if(containsImageWrite)
477 	{
478 		vk::DescriptorSet::ContentsChanged(descriptorSetObjects, pipelineLayout, device);
479 	}
480 }
481 
run(vk::Device * device,const marl::Loan<DrawCall> & draw,marl::Ticket::Queue * tickets,marl::Ticket::Queue clusterQueues[MaxClusterCount])482 void DrawCall::run(vk::Device *device, const marl::Loan<DrawCall> &draw, marl::Ticket::Queue *tickets, marl::Ticket::Queue clusterQueues[MaxClusterCount])
483 {
484 	draw->setup();
485 
486 	auto const numPrimitives = draw->numPrimitives;
487 	auto const numPrimitivesPerBatch = draw->numPrimitivesPerBatch;
488 	auto const numBatches = draw->numBatches;
489 
490 	auto ticket = tickets->take();
491 	auto finally = marl::make_shared_finally([device, draw, ticket] {
492 		MARL_SCOPED_EVENT("FINISH draw %d", draw->id);
493 		draw->teardown(device);
494 		ticket.done();
495 	});
496 
497 	for(unsigned int batchId = 0; batchId < numBatches; batchId++)
498 	{
499 		auto batch = draw->batchDataPool->borrow();
500 		batch->id = batchId;
501 		batch->firstPrimitive = batch->id * numPrimitivesPerBatch;
502 		batch->numPrimitives = std::min(batch->firstPrimitive + numPrimitivesPerBatch, numPrimitives) - batch->firstPrimitive;
503 
504 		for(int cluster = 0; cluster < MaxClusterCount; cluster++)
505 		{
506 			batch->clusterTickets[cluster] = std::move(clusterQueues[cluster].take());
507 		}
508 
509 		marl::schedule([device, draw, batch, finally] {
510 			processVertices(device, draw.get(), batch.get());
511 
512 			if(!draw->setupState.rasterizerDiscard)
513 			{
514 				processPrimitives(device, draw.get(), batch.get());
515 
516 				if(batch->numVisible > 0)
517 				{
518 					processPixels(device, draw, batch, finally);
519 					return;
520 				}
521 			}
522 
523 			for(int cluster = 0; cluster < MaxClusterCount; cluster++)
524 			{
525 				batch->clusterTickets[cluster].done();
526 			}
527 		});
528 	}
529 }
530 
processVertices(vk::Device * device,DrawCall * draw,BatchData * batch)531 void DrawCall::processVertices(vk::Device *device, DrawCall *draw, BatchData *batch)
532 {
533 	MARL_SCOPED_EVENT("VERTEX draw %d, batch %d", draw->id, batch->id);
534 
535 	unsigned int triangleIndices[MaxBatchSize + 1][3];  // One extra for SIMD width overrun. TODO: Adjust to dynamic batch size.
536 	{
537 		MARL_SCOPED_EVENT("processPrimitiveVertices");
538 		processPrimitiveVertices(
539 		    triangleIndices,
540 		    draw->data->indices,
541 		    draw->indexType,
542 		    batch->firstPrimitive,
543 		    batch->numPrimitives,
544 		    draw->topology,
545 		    draw->provokingVertexMode);
546 	}
547 
548 	auto &vertexTask = batch->vertexTask;
549 	vertexTask.primitiveStart = batch->firstPrimitive;
550 	// We're only using batch compaction for points, not lines
551 	vertexTask.vertexCount = batch->numPrimitives * ((draw->topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) ? 1 : 3);
552 	if(vertexTask.vertexCache.drawCall != draw->id)
553 	{
554 		vertexTask.vertexCache.clear();
555 		vertexTask.vertexCache.drawCall = draw->id;
556 	}
557 
558 	draw->vertexRoutine(device, &batch->triangles.front().v0, &triangleIndices[0][0], &vertexTask, draw->data);
559 }
560 
processPrimitives(vk::Device * device,DrawCall * draw,BatchData * batch)561 void DrawCall::processPrimitives(vk::Device *device, DrawCall *draw, BatchData *batch)
562 {
563 	MARL_SCOPED_EVENT("PRIMITIVES draw %d batch %d", draw->id, batch->id);
564 	auto triangles = &batch->triangles[0];
565 	auto primitives = &batch->primitives[0];
566 	batch->numVisible = draw->setupPrimitives(device, triangles, primitives, draw, batch->numPrimitives);
567 }
568 
processPixels(vk::Device * device,const marl::Loan<DrawCall> & draw,const marl::Loan<BatchData> & batch,const std::shared_ptr<marl::Finally> & finally)569 void DrawCall::processPixels(vk::Device *device, const marl::Loan<DrawCall> &draw, const marl::Loan<BatchData> &batch, const std::shared_ptr<marl::Finally> &finally)
570 {
571 	struct Data
572 	{
573 		Data(const marl::Loan<DrawCall> &draw, const marl::Loan<BatchData> &batch, const std::shared_ptr<marl::Finally> &finally)
574 		    : draw(draw)
575 		    , batch(batch)
576 		    , finally(finally)
577 		{}
578 		marl::Loan<DrawCall> draw;
579 		marl::Loan<BatchData> batch;
580 		std::shared_ptr<marl::Finally> finally;
581 	};
582 	auto data = std::make_shared<Data>(draw, batch, finally);
583 	for(int cluster = 0; cluster < MaxClusterCount; cluster++)
584 	{
585 		batch->clusterTickets[cluster].onCall([device, data, cluster] {
586 			auto &draw = data->draw;
587 			auto &batch = data->batch;
588 			MARL_SCOPED_EVENT("PIXEL draw %d, batch %d, cluster %d", draw->id, batch->id, cluster);
589 			draw->pixelRoutine(device, &batch->primitives.front(), batch->numVisible, cluster, MaxClusterCount, draw->data);
590 			batch->clusterTickets[cluster].done();
591 		});
592 	}
593 }
594 
synchronize()595 void Renderer::synchronize()
596 {
597 	MARL_SCOPED_EVENT("synchronize");
598 	auto ticket = drawTickets.take();
599 	ticket.wait();
600 	device->updateSamplingRoutineSnapshotCache();
601 	ticket.done();
602 }
603 
processPrimitiveVertices(unsigned int triangleIndicesOut[MaxBatchSize+1][3],const void * primitiveIndices,VkIndexType indexType,unsigned int start,unsigned int triangleCount,VkPrimitiveTopology topology,VkProvokingVertexModeEXT provokingVertexMode)604 void DrawCall::processPrimitiveVertices(
605     unsigned int triangleIndicesOut[MaxBatchSize + 1][3],
606     const void *primitiveIndices,
607     VkIndexType indexType,
608     unsigned int start,
609     unsigned int triangleCount,
610     VkPrimitiveTopology topology,
611     VkProvokingVertexModeEXT provokingVertexMode)
612 {
613 	if(!primitiveIndices)
614 	{
615 		struct LinearIndex
616 		{
617 			unsigned int operator[](unsigned int i) { return i; }
618 		};
619 
620 		if(!setBatchIndices(triangleIndicesOut, topology, provokingVertexMode, LinearIndex(), start, triangleCount))
621 		{
622 			return;
623 		}
624 	}
625 	else
626 	{
627 		switch(indexType)
628 		{
629 		case VK_INDEX_TYPE_UINT16:
630 			if(!setBatchIndices(triangleIndicesOut, topology, provokingVertexMode, static_cast<const uint16_t *>(primitiveIndices), start, triangleCount))
631 			{
632 				return;
633 			}
634 			break;
635 		case VK_INDEX_TYPE_UINT32:
636 			if(!setBatchIndices(triangleIndicesOut, topology, provokingVertexMode, static_cast<const uint32_t *>(primitiveIndices), start, triangleCount))
637 			{
638 				return;
639 			}
640 			break;
641 			break;
642 		default:
643 			ASSERT(false);
644 			return;
645 		}
646 	}
647 
648 	// setBatchIndices() takes care of the point case, since it's different due to the compaction
649 	if(topology != VK_PRIMITIVE_TOPOLOGY_POINT_LIST)
650 	{
651 		// Repeat the last index to allow for SIMD width overrun.
652 		triangleIndicesOut[triangleCount][0] = triangleIndicesOut[triangleCount - 1][2];
653 		triangleIndicesOut[triangleCount][1] = triangleIndicesOut[triangleCount - 1][2];
654 		triangleIndicesOut[triangleCount][2] = triangleIndicesOut[triangleCount - 1][2];
655 	}
656 }
657 
setupSolidTriangles(vk::Device * device,Triangle * triangles,Primitive * primitives,const DrawCall * drawCall,int count)658 int DrawCall::setupSolidTriangles(vk::Device *device, Triangle *triangles, Primitive *primitives, const DrawCall *drawCall, int count)
659 {
660 	auto &state = drawCall->setupState;
661 
662 	int ms = state.multiSampleCount;
663 	const DrawData *data = drawCall->data;
664 	int visible = 0;
665 
666 	for(int i = 0; i < count; i++, triangles++)
667 	{
668 		Vertex &v0 = triangles->v0;
669 		Vertex &v1 = triangles->v1;
670 		Vertex &v2 = triangles->v2;
671 
672 		Polygon polygon(&v0.position, &v1.position, &v2.position);
673 
674 		if((v0.cullMask | v1.cullMask | v2.cullMask) == 0)
675 		{
676 			continue;
677 		}
678 
679 		if((v0.clipFlags & v1.clipFlags & v2.clipFlags) != Clipper::CLIP_FINITE)
680 		{
681 			continue;
682 		}
683 
684 		int clipFlagsOr = v0.clipFlags | v1.clipFlags | v2.clipFlags;
685 		if(clipFlagsOr != Clipper::CLIP_FINITE)
686 		{
687 			if(!Clipper::Clip(polygon, clipFlagsOr, *drawCall))
688 			{
689 				continue;
690 			}
691 		}
692 
693 		if(drawCall->setupRoutine(device, primitives, triangles, &polygon, data))
694 		{
695 			primitives += ms;
696 			visible++;
697 		}
698 	}
699 
700 	return visible;
701 }
702 
setupWireframeTriangles(vk::Device * device,Triangle * triangles,Primitive * primitives,const DrawCall * drawCall,int count)703 int DrawCall::setupWireframeTriangles(vk::Device *device, Triangle *triangles, Primitive *primitives, const DrawCall *drawCall, int count)
704 {
705 	auto &state = drawCall->setupState;
706 
707 	int ms = state.multiSampleCount;
708 	int visible = 0;
709 
710 	for(int i = 0; i < count; i++)
711 	{
712 		const Vertex &v0 = triangles[i].v0;
713 		const Vertex &v1 = triangles[i].v1;
714 		const Vertex &v2 = triangles[i].v2;
715 
716 		float A = ((float)v0.projected.y - (float)v2.projected.y) * (float)v1.projected.x +
717 		          ((float)v2.projected.y - (float)v1.projected.y) * (float)v0.projected.x +
718 		          ((float)v1.projected.y - (float)v0.projected.y) * (float)v2.projected.x;  // Area
719 
720 		int w0w1w2 = bit_cast<int>(v0.w) ^
721 		             bit_cast<int>(v1.w) ^
722 		             bit_cast<int>(v2.w);
723 
724 		A = w0w1w2 < 0 ? -A : A;
725 
726 		bool frontFacing = (state.frontFace == VK_FRONT_FACE_COUNTER_CLOCKWISE) ? (A >= 0.0f) : (A <= 0.0f);
727 
728 		if(state.cullMode & VK_CULL_MODE_FRONT_BIT)
729 		{
730 			if(frontFacing) continue;
731 		}
732 		if(state.cullMode & VK_CULL_MODE_BACK_BIT)
733 		{
734 			if(!frontFacing) continue;
735 		}
736 
737 		Triangle lines[3];
738 		lines[0].v0 = v0;
739 		lines[0].v1 = v1;
740 		lines[1].v0 = v1;
741 		lines[1].v1 = v2;
742 		lines[2].v0 = v2;
743 		lines[2].v1 = v0;
744 
745 		for(int i = 0; i < 3; i++)
746 		{
747 			if(setupLine(device, *primitives, lines[i], *drawCall))
748 			{
749 				primitives += ms;
750 				visible++;
751 			}
752 		}
753 	}
754 
755 	return visible;
756 }
757 
setupPointTriangles(vk::Device * device,Triangle * triangles,Primitive * primitives,const DrawCall * drawCall,int count)758 int DrawCall::setupPointTriangles(vk::Device *device, Triangle *triangles, Primitive *primitives, const DrawCall *drawCall, int count)
759 {
760 	auto &state = drawCall->setupState;
761 
762 	int ms = state.multiSampleCount;
763 	int visible = 0;
764 
765 	for(int i = 0; i < count; i++)
766 	{
767 		const Vertex &v0 = triangles[i].v0;
768 		const Vertex &v1 = triangles[i].v1;
769 		const Vertex &v2 = triangles[i].v2;
770 
771 		float d = (v0.y * v1.x - v0.x * v1.y) * v2.w +
772 		          (v0.x * v2.y - v0.y * v2.x) * v1.w +
773 		          (v2.x * v1.y - v1.x * v2.y) * v0.w;
774 
775 		bool frontFacing = (state.frontFace == VK_FRONT_FACE_COUNTER_CLOCKWISE) ? (d > 0) : (d < 0);
776 		if(state.cullMode & VK_CULL_MODE_FRONT_BIT)
777 		{
778 			if(frontFacing) continue;
779 		}
780 		if(state.cullMode & VK_CULL_MODE_BACK_BIT)
781 		{
782 			if(!frontFacing) continue;
783 		}
784 
785 		Triangle points[3];
786 		points[0].v0 = v0;
787 		points[1].v0 = v1;
788 		points[2].v0 = v2;
789 
790 		for(int i = 0; i < 3; i++)
791 		{
792 			if(setupPoint(device, *primitives, points[i], *drawCall))
793 			{
794 				primitives += ms;
795 				visible++;
796 			}
797 		}
798 	}
799 
800 	return visible;
801 }
802 
setupLines(vk::Device * device,Triangle * triangles,Primitive * primitives,const DrawCall * drawCall,int count)803 int DrawCall::setupLines(vk::Device *device, Triangle *triangles, Primitive *primitives, const DrawCall *drawCall, int count)
804 {
805 	auto &state = drawCall->setupState;
806 
807 	int visible = 0;
808 	int ms = state.multiSampleCount;
809 
810 	for(int i = 0; i < count; i++)
811 	{
812 		if(setupLine(device, *primitives, *triangles, *drawCall))
813 		{
814 			primitives += ms;
815 			visible++;
816 		}
817 
818 		triangles++;
819 	}
820 
821 	return visible;
822 }
823 
setupPoints(vk::Device * device,Triangle * triangles,Primitive * primitives,const DrawCall * drawCall,int count)824 int DrawCall::setupPoints(vk::Device *device, Triangle *triangles, Primitive *primitives, const DrawCall *drawCall, int count)
825 {
826 	auto &state = drawCall->setupState;
827 
828 	int visible = 0;
829 	int ms = state.multiSampleCount;
830 
831 	for(int i = 0; i < count; i++)
832 	{
833 		if(setupPoint(device, *primitives, *triangles, *drawCall))
834 		{
835 			primitives += ms;
836 			visible++;
837 		}
838 
839 		triangles++;
840 	}
841 
842 	return visible;
843 }
844 
setupLine(vk::Device * device,Primitive & primitive,Triangle & triangle,const DrawCall & draw)845 bool DrawCall::setupLine(vk::Device *device, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
846 {
847 	const DrawData &data = *draw.data;
848 
849 	float lineWidth = data.lineWidth;
850 
851 	Vertex &v0 = triangle.v0;
852 	Vertex &v1 = triangle.v1;
853 
854 	if((v0.cullMask | v1.cullMask) == 0)
855 	{
856 		return false;
857 	}
858 
859 	const float4 &P0 = v0.position;
860 	const float4 &P1 = v1.position;
861 
862 	if(P0.w <= 0 && P1.w <= 0)
863 	{
864 		return false;
865 	}
866 
867 	constexpr float subPixF = vk::SUBPIXEL_PRECISION_FACTOR;
868 
869 	const float W = data.WxF[0] * (1.0f / subPixF);
870 	const float H = data.HxF[0] * (1.0f / subPixF);
871 
872 	float dx = W * (P1.x / P1.w - P0.x / P0.w);
873 	float dy = H * (P1.y / P1.w - P0.y / P0.w);
874 
875 	if(dx == 0 && dy == 0)
876 	{
877 		return false;
878 	}
879 
880 	if(draw.lineRasterizationMode != VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT)
881 	{
882 		// Rectangle centered on the line segment
883 
884 		float4 P[4];
885 		int C[4];
886 
887 		P[0] = P0;
888 		P[1] = P1;
889 		P[2] = P1;
890 		P[3] = P0;
891 
892 		float scale = lineWidth * 0.5f / sqrt(dx * dx + dy * dy);
893 
894 		dx *= scale;
895 		dy *= scale;
896 
897 		float dx0h = dx * P0.w / H;
898 		float dy0w = dy * P0.w / W;
899 
900 		float dx1h = dx * P1.w / H;
901 		float dy1w = dy * P1.w / W;
902 
903 		P[0].x += -dy0w;
904 		P[0].y += +dx0h;
905 		C[0] = Clipper::ComputeClipFlags(P[0], draw.depthClipEnable);
906 
907 		P[1].x += -dy1w;
908 		P[1].y += +dx1h;
909 		C[1] = Clipper::ComputeClipFlags(P[1], draw.depthClipEnable);
910 
911 		P[2].x += +dy1w;
912 		P[2].y += -dx1h;
913 		C[2] = Clipper::ComputeClipFlags(P[2], draw.depthClipEnable);
914 
915 		P[3].x += +dy0w;
916 		P[3].y += -dx0h;
917 		C[3] = Clipper::ComputeClipFlags(P[3], draw.depthClipEnable);
918 
919 		if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
920 		{
921 			Polygon polygon(P, 4);
922 
923 			int clipFlagsOr = C[0] | C[1] | C[2] | C[3];
924 
925 			if(clipFlagsOr != Clipper::CLIP_FINITE)
926 			{
927 				if(!Clipper::Clip(polygon, clipFlagsOr, draw))
928 				{
929 					return false;
930 				}
931 			}
932 
933 			return draw.setupRoutine(device, &primitive, &triangle, &polygon, &data);
934 		}
935 	}
936 	else if(false)  // TODO(b/80135519): Deprecate
937 	{
938 		// Connecting diamonds polygon
939 		// This shape satisfies the diamond test convention, except for the exit rule part.
940 		// Line segments with overlapping endpoints have duplicate fragments.
941 		// The ideal algorithm requires half-open line rasterization (b/80135519).
942 
943 		float4 P[8];
944 		int C[8];
945 
946 		P[0] = P0;
947 		P[1] = P0;
948 		P[2] = P0;
949 		P[3] = P0;
950 		P[4] = P1;
951 		P[5] = P1;
952 		P[6] = P1;
953 		P[7] = P1;
954 
955 		float dx0 = lineWidth * 0.5f * P0.w / W;
956 		float dy0 = lineWidth * 0.5f * P0.w / H;
957 
958 		float dx1 = lineWidth * 0.5f * P1.w / W;
959 		float dy1 = lineWidth * 0.5f * P1.w / H;
960 
961 		P[0].x += -dx0;
962 		C[0] = Clipper::ComputeClipFlags(P[0], draw.depthClipEnable);
963 
964 		P[1].y += +dy0;
965 		C[1] = Clipper::ComputeClipFlags(P[1], draw.depthClipEnable);
966 
967 		P[2].x += +dx0;
968 		C[2] = Clipper::ComputeClipFlags(P[2], draw.depthClipEnable);
969 
970 		P[3].y += -dy0;
971 		C[3] = Clipper::ComputeClipFlags(P[3], draw.depthClipEnable);
972 
973 		P[4].x += -dx1;
974 		C[4] = Clipper::ComputeClipFlags(P[4], draw.depthClipEnable);
975 
976 		P[5].y += +dy1;
977 		C[5] = Clipper::ComputeClipFlags(P[5], draw.depthClipEnable);
978 
979 		P[6].x += +dx1;
980 		C[6] = Clipper::ComputeClipFlags(P[6], draw.depthClipEnable);
981 
982 		P[7].y += -dy1;
983 		C[7] = Clipper::ComputeClipFlags(P[7], draw.depthClipEnable);
984 
985 		if((C[0] & C[1] & C[2] & C[3] & C[4] & C[5] & C[6] & C[7]) == Clipper::CLIP_FINITE)
986 		{
987 			float4 L[6];
988 
989 			if(dx > -dy)
990 			{
991 				if(dx > dy)  // Right
992 				{
993 					L[0] = P[0];
994 					L[1] = P[1];
995 					L[2] = P[5];
996 					L[3] = P[6];
997 					L[4] = P[7];
998 					L[5] = P[3];
999 				}
1000 				else  // Down
1001 				{
1002 					L[0] = P[0];
1003 					L[1] = P[4];
1004 					L[2] = P[5];
1005 					L[3] = P[6];
1006 					L[4] = P[2];
1007 					L[5] = P[3];
1008 				}
1009 			}
1010 			else
1011 			{
1012 				if(dx > dy)  // Up
1013 				{
1014 					L[0] = P[0];
1015 					L[1] = P[1];
1016 					L[2] = P[2];
1017 					L[3] = P[6];
1018 					L[4] = P[7];
1019 					L[5] = P[4];
1020 				}
1021 				else  // Left
1022 				{
1023 					L[0] = P[1];
1024 					L[1] = P[2];
1025 					L[2] = P[3];
1026 					L[3] = P[7];
1027 					L[4] = P[4];
1028 					L[5] = P[5];
1029 				}
1030 			}
1031 
1032 			Polygon polygon(L, 6);
1033 
1034 			int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | C[4] | C[5] | C[6] | C[7];
1035 
1036 			if(clipFlagsOr != Clipper::CLIP_FINITE)
1037 			{
1038 				if(!Clipper::Clip(polygon, clipFlagsOr, draw))
1039 				{
1040 					return false;
1041 				}
1042 			}
1043 
1044 			return draw.setupRoutine(device, &primitive, &triangle, &polygon, &data);
1045 		}
1046 	}
1047 	else
1048 	{
1049 		// Parallelogram approximating Bresenham line
1050 		// This algorithm does not satisfy the ideal diamond-exit rule, but does avoid the
1051 		// duplicate fragment rasterization problem and satisfies all of Vulkan's minimum
1052 		// requirements for Bresenham line segment rasterization.
1053 
1054 		float4 P[8];
1055 		P[0] = P0;
1056 		P[1] = P0;
1057 		P[2] = P0;
1058 		P[3] = P0;
1059 		P[4] = P1;
1060 		P[5] = P1;
1061 		P[6] = P1;
1062 		P[7] = P1;
1063 
1064 		float dx0 = lineWidth * 0.5f * P0.w / W;
1065 		float dy0 = lineWidth * 0.5f * P0.w / H;
1066 
1067 		float dx1 = lineWidth * 0.5f * P1.w / W;
1068 		float dy1 = lineWidth * 0.5f * P1.w / H;
1069 
1070 		P[0].x += -dx0;
1071 		P[1].y += +dy0;
1072 		P[2].x += +dx0;
1073 		P[3].y += -dy0;
1074 		P[4].x += -dx1;
1075 		P[5].y += +dy1;
1076 		P[6].x += +dx1;
1077 		P[7].y += -dy1;
1078 
1079 		float4 L[4];
1080 
1081 		if(dx > -dy)
1082 		{
1083 			if(dx > dy)  // Right
1084 			{
1085 				L[0] = P[1];
1086 				L[1] = P[5];
1087 				L[2] = P[7];
1088 				L[3] = P[3];
1089 			}
1090 			else  // Down
1091 			{
1092 				L[0] = P[0];
1093 				L[1] = P[4];
1094 				L[2] = P[6];
1095 				L[3] = P[2];
1096 			}
1097 		}
1098 		else
1099 		{
1100 			if(dx > dy)  // Up
1101 			{
1102 				L[0] = P[0];
1103 				L[1] = P[2];
1104 				L[2] = P[6];
1105 				L[3] = P[4];
1106 			}
1107 			else  // Left
1108 			{
1109 				L[0] = P[1];
1110 				L[1] = P[3];
1111 				L[2] = P[7];
1112 				L[3] = P[5];
1113 			}
1114 		}
1115 
1116 		int C0 = Clipper::ComputeClipFlags(L[0], draw.depthClipEnable);
1117 		int C1 = Clipper::ComputeClipFlags(L[1], draw.depthClipEnable);
1118 		int C2 = Clipper::ComputeClipFlags(L[2], draw.depthClipEnable);
1119 		int C3 = Clipper::ComputeClipFlags(L[3], draw.depthClipEnable);
1120 
1121 		if((C0 & C1 & C2 & C3) == Clipper::CLIP_FINITE)
1122 		{
1123 			Polygon polygon(L, 4);
1124 
1125 			int clipFlagsOr = C0 | C1 | C2 | C3;
1126 
1127 			if(clipFlagsOr != Clipper::CLIP_FINITE)
1128 			{
1129 				if(!Clipper::Clip(polygon, clipFlagsOr, draw))
1130 				{
1131 					return false;
1132 				}
1133 			}
1134 
1135 			return draw.setupRoutine(device, &primitive, &triangle, &polygon, &data);
1136 		}
1137 	}
1138 
1139 	return false;
1140 }
1141 
setupPoint(vk::Device * device,Primitive & primitive,Triangle & triangle,const DrawCall & draw)1142 bool DrawCall::setupPoint(vk::Device *device, Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1143 {
1144 	const DrawData &data = *draw.data;
1145 
1146 	Vertex &v = triangle.v0;
1147 
1148 	if(v.cullMask == 0)
1149 	{
1150 		return false;
1151 	}
1152 
1153 	float pSize = v.pointSize;
1154 
1155 	pSize = clamp(pSize, 1.0f, static_cast<float>(vk::MAX_POINT_SIZE));
1156 
1157 	float4 P[4];
1158 	int C[4];
1159 
1160 	P[0] = v.position;
1161 	P[1] = v.position;
1162 	P[2] = v.position;
1163 	P[3] = v.position;
1164 
1165 	const float X = pSize * P[0].w * data.halfPixelX[0];
1166 	const float Y = pSize * P[0].w * data.halfPixelY[0];
1167 
1168 	P[0].x -= X;
1169 	P[0].y += Y;
1170 	C[0] = Clipper::ComputeClipFlags(P[0], draw.depthClipEnable);
1171 
1172 	P[1].x += X;
1173 	P[1].y += Y;
1174 	C[1] = Clipper::ComputeClipFlags(P[1], draw.depthClipEnable);
1175 
1176 	P[2].x += X;
1177 	P[2].y -= Y;
1178 	C[2] = Clipper::ComputeClipFlags(P[2], draw.depthClipEnable);
1179 
1180 	P[3].x -= X;
1181 	P[3].y -= Y;
1182 	C[3] = Clipper::ComputeClipFlags(P[3], draw.depthClipEnable);
1183 
1184 	Polygon polygon(P, 4);
1185 
1186 	if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1187 	{
1188 		int clipFlagsOr = C[0] | C[1] | C[2] | C[3];
1189 
1190 		if(clipFlagsOr != Clipper::CLIP_FINITE)
1191 		{
1192 			if(!Clipper::Clip(polygon, clipFlagsOr, draw))
1193 			{
1194 				return false;
1195 			}
1196 		}
1197 
1198 		primitive.pointSizeInv = 1.0f / pSize;
1199 
1200 		return draw.setupRoutine(device, &primitive, &triangle, &polygon, &data);
1201 	}
1202 
1203 	return false;
1204 }
1205 
addQuery(vk::Query * query)1206 void Renderer::addQuery(vk::Query *query)
1207 {
1208 	ASSERT(query->getType() == VK_QUERY_TYPE_OCCLUSION);
1209 	ASSERT(!occlusionQuery);
1210 
1211 	occlusionQuery = query;
1212 }
1213 
removeQuery(vk::Query * query)1214 void Renderer::removeQuery(vk::Query *query)
1215 {
1216 	ASSERT(query->getType() == VK_QUERY_TYPE_OCCLUSION);
1217 	ASSERT(occlusionQuery == query);
1218 
1219 	occlusionQuery = nullptr;
1220 }
1221 
1222 }  // namespace sw
1223