swr: [rasterizer core] allow override of KNOB thread settings
[mesa.git] / src / gallium / drivers / swr / rasterizer / core / api.cpp
1 /****************************************************************************
2 * Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * @file api.cpp
24 *
25 * @brief API implementation
26 *
27 ******************************************************************************/
28
29 #include <cfloat>
30 #include <cmath>
31 #include <cstdio>
32 #include <new>
33
34 #include "core/api.h"
35 #include "core/backend.h"
36 #include "core/context.h"
37 #include "core/depthstencil.h"
38 #include "core/frontend.h"
39 #include "core/rasterizer.h"
40 #include "core/rdtsc_core.h"
41 #include "core/threads.h"
42 #include "core/tilemgr.h"
43 #include "core/clip.h"
44 #include "core/utils.h"
45
46 #include "common/simdintrin.h"
47 #include "common/os.h"
48
49 void SetupDefaultState(SWR_CONTEXT *pContext);
50
51 static INLINE SWR_CONTEXT* GetContext(HANDLE hContext)
52 {
53 return (SWR_CONTEXT*)hContext;
54 }
55
56 //////////////////////////////////////////////////////////////////////////
57 /// @brief Create SWR Context.
58 /// @param pCreateInfo - pointer to creation info.
59 HANDLE SwrCreateContext(
60 SWR_CREATECONTEXT_INFO* pCreateInfo)
61 {
62 RDTSC_RESET();
63 RDTSC_INIT(0);
64
65 void* pContextMem = AlignedMalloc(sizeof(SWR_CONTEXT), KNOB_SIMD_WIDTH * 4);
66 memset(pContextMem, 0, sizeof(SWR_CONTEXT));
67 SWR_CONTEXT *pContext = new (pContextMem) SWR_CONTEXT();
68
69 pContext->driverType = pCreateInfo->driver;
70 pContext->privateStateSize = pCreateInfo->privateStateSize;
71
72 pContext->dcRing.Init(KNOB_MAX_DRAWS_IN_FLIGHT);
73 pContext->dsRing.Init(KNOB_MAX_DRAWS_IN_FLIGHT);
74
75 pContext->pMacroTileManagerArray = (MacroTileMgr*)AlignedMalloc(sizeof(MacroTileMgr) * KNOB_MAX_DRAWS_IN_FLIGHT, 64);
76 pContext->pDispatchQueueArray = (DispatchQueue*)AlignedMalloc(sizeof(DispatchQueue) * KNOB_MAX_DRAWS_IN_FLIGHT, 64);
77
78 pContext->threadInfo.MAX_WORKER_THREADS = KNOB_MAX_WORKER_THREADS;
79 pContext->threadInfo.MAX_NUMA_NODES = KNOB_MAX_NUMA_NODES;
80 pContext->threadInfo.MAX_CORES_PER_NUMA_NODE = KNOB_MAX_CORES_PER_NUMA_NODE;
81 pContext->threadInfo.MAX_THREADS_PER_CORE = KNOB_MAX_THREADS_PER_CORE;
82 pContext->threadInfo.SINGLE_THREADED = KNOB_SINGLE_THREADED;
83
84 if (pCreateInfo->pThreadInfo)
85 {
86 pContext->threadInfo = *pCreateInfo->pThreadInfo;
87 }
88
89 for (uint32_t dc = 0; dc < KNOB_MAX_DRAWS_IN_FLIGHT; ++dc)
90 {
91 pContext->dcRing[dc].pArena = new CachingArena(pContext->cachingArenaAllocator);
92 new (&pContext->pMacroTileManagerArray[dc]) MacroTileMgr(*pContext->dcRing[dc].pArena);
93 new (&pContext->pDispatchQueueArray[dc]) DispatchQueue();
94
95 pContext->dsRing[dc].pArena = new CachingArena(pContext->cachingArenaAllocator);
96 }
97
98 if (!pContext->threadInfo.SINGLE_THREADED)
99 {
100 memset(&pContext->WaitLock, 0, sizeof(pContext->WaitLock));
101 memset(&pContext->FifosNotEmpty, 0, sizeof(pContext->FifosNotEmpty));
102 new (&pContext->WaitLock) std::mutex();
103 new (&pContext->FifosNotEmpty) std::condition_variable();
104
105 CreateThreadPool(pContext, &pContext->threadPool);
106 }
107
108 // Calling createThreadPool() above can set SINGLE_THREADED
109 if (pContext->threadInfo.SINGLE_THREADED)
110 {
111 pContext->NumWorkerThreads = 1;
112 pContext->NumFEThreads = 1;
113 pContext->NumBEThreads = 1;
114 }
115
116 // Allocate scratch space for workers.
117 ///@note We could lazily allocate this but its rather small amount of memory.
118 for (uint32_t i = 0; i < pContext->NumWorkerThreads; ++i)
119 {
120 #if defined(_WIN32)
121 uint32_t numaNode = pContext->threadPool.pThreadData ?
122 pContext->threadPool.pThreadData[i].numaId : 0;
123 pContext->pScratch[i] = (uint8_t*)VirtualAllocExNuma(
124 GetCurrentProcess(), nullptr, 32 * sizeof(KILOBYTE),
125 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE,
126 numaNode);
127 #else
128 pContext->pScratch[i] = (uint8_t*)AlignedMalloc(32 * sizeof(KILOBYTE), KNOB_SIMD_WIDTH * 4);
129 #endif
130 }
131
132 // State setup AFTER context is fully initialized
133 SetupDefaultState(pContext);
134
135 // initialize hot tile manager
136 pContext->pHotTileMgr = new HotTileMgr();
137
138 // initialize function pointer tables
139 InitClearTilesTable();
140
141 // initialize callback functions
142 pContext->pfnLoadTile = pCreateInfo->pfnLoadTile;
143 pContext->pfnStoreTile = pCreateInfo->pfnStoreTile;
144 pContext->pfnClearTile = pCreateInfo->pfnClearTile;
145 pContext->pfnUpdateSoWriteOffset = pCreateInfo->pfnUpdateSoWriteOffset;
146
147 // pass pointer to bucket manager back to caller
148 #ifdef KNOB_ENABLE_RDTSC
149 pCreateInfo->pBucketMgr = &gBucketMgr;
150 #endif
151
152 pCreateInfo->contextSaveSize = sizeof(API_STATE);
153
154 return (HANDLE)pContext;
155 }
156
157 void SwrDestroyContext(HANDLE hContext)
158 {
159 SWR_CONTEXT *pContext = GetContext(hContext);
160 DestroyThreadPool(pContext, &pContext->threadPool);
161
162 // free the fifos
163 for (uint32_t i = 0; i < KNOB_MAX_DRAWS_IN_FLIGHT; ++i)
164 {
165 delete pContext->dcRing[i].pArena;
166 delete pContext->dsRing[i].pArena;
167 pContext->pMacroTileManagerArray[i].~MacroTileMgr();
168 pContext->pDispatchQueueArray[i].~DispatchQueue();
169 }
170
171 AlignedFree(pContext->pDispatchQueueArray);
172 AlignedFree(pContext->pMacroTileManagerArray);
173
174 // Free scratch space.
175 for (uint32_t i = 0; i < pContext->NumWorkerThreads; ++i)
176 {
177 #if defined(_WIN32)
178 VirtualFree(pContext->pScratch[i], 0, MEM_RELEASE);
179 #else
180 AlignedFree(pContext->pScratch[i]);
181 #endif
182 }
183
184 delete(pContext->pHotTileMgr);
185
186 pContext->~SWR_CONTEXT();
187 AlignedFree(GetContext(hContext));
188 }
189
190 void CopyState(DRAW_STATE& dst, const DRAW_STATE& src)
191 {
192 memcpy(&dst.state, &src.state, sizeof(API_STATE));
193 }
194
195 void WakeAllThreads(SWR_CONTEXT *pContext)
196 {
197 pContext->FifosNotEmpty.notify_all();
198 }
199
200 static TileSet gSingleThreadLockedTiles;
201
202 template<bool IsDraw>
203 void QueueWork(SWR_CONTEXT *pContext)
204 {
205 DRAW_CONTEXT* pDC = pContext->pCurDrawContext;
206 uint32_t dcIndex = pDC->drawId % KNOB_MAX_DRAWS_IN_FLIGHT;
207
208 if (IsDraw)
209 {
210 pDC->pTileMgr = &pContext->pMacroTileManagerArray[dcIndex];
211 pDC->pTileMgr->initialize();
212 }
213
214 // Each worker thread looks at a DC for both FE and BE work at different times and so we
215 // multiply threadDone by 2. When the threadDone counter has reached 0 then all workers
216 // have moved past this DC. (i.e. Each worker has checked this DC for both FE and BE work and
217 // then moved on if all work is done.)
218 pContext->pCurDrawContext->threadsDone = pContext->NumFEThreads + pContext->NumBEThreads;
219
220 if (IsDraw)
221 {
222 InterlockedIncrement((volatile LONG*)&pContext->drawsOutstandingFE);
223 }
224
225 _ReadWriteBarrier();
226 {
227 std::unique_lock<std::mutex> lock(pContext->WaitLock);
228 pContext->dcRing.Enqueue();
229 }
230
231 if (pContext->threadInfo.SINGLE_THREADED)
232 {
233 // flush denormals to 0
234 uint32_t mxcsr = _mm_getcsr();
235 _mm_setcsr(mxcsr | _MM_FLUSH_ZERO_ON | _MM_DENORMALS_ZERO_ON);
236
237 if (IsDraw)
238 {
239 uint32_t curDraw[2] = { pContext->pCurDrawContext->drawId, pContext->pCurDrawContext->drawId };
240 WorkOnFifoFE(pContext, 0, curDraw[0]);
241 WorkOnFifoBE(pContext, 0, curDraw[1], gSingleThreadLockedTiles, 0, 0);
242 }
243 else
244 {
245 uint32_t curDispatch = pContext->pCurDrawContext->drawId;
246 WorkOnCompute(pContext, 0, curDispatch);
247 }
248
249 // Dequeue the work here, if not already done, since we're single threaded (i.e. no workers).
250 while (CompleteDrawContext(pContext, pContext->pCurDrawContext) > 0) {}
251
252 // restore csr
253 _mm_setcsr(mxcsr);
254 }
255 else
256 {
257 RDTSC_START(APIDrawWakeAllThreads);
258 WakeAllThreads(pContext);
259 RDTSC_STOP(APIDrawWakeAllThreads, 1, 0);
260 }
261
262 // Set current draw context to NULL so that next state call forces a new draw context to be created and populated.
263 pContext->pPrevDrawContext = pContext->pCurDrawContext;
264 pContext->pCurDrawContext = nullptr;
265 }
266
267 INLINE void QueueDraw(SWR_CONTEXT* pContext)
268 {
269 QueueWork<true>(pContext);
270 }
271
272 INLINE void QueueDispatch(SWR_CONTEXT* pContext)
273 {
274 QueueWork<false>(pContext);
275 }
276
277 DRAW_CONTEXT* GetDrawContext(SWR_CONTEXT *pContext, bool isSplitDraw = false)
278 {
279 RDTSC_START(APIGetDrawContext);
280 // If current draw context is null then need to obtain a new draw context to use from ring.
281 if (pContext->pCurDrawContext == nullptr)
282 {
283 // Need to wait for a free entry.
284 while (pContext->dcRing.IsFull())
285 {
286 _mm_pause();
287 }
288
289 uint64_t curDraw = pContext->dcRing.GetHead();
290 uint32_t dcIndex = curDraw % KNOB_MAX_DRAWS_IN_FLIGHT;
291
292 static uint64_t lastDrawChecked;
293 static uint32_t lastFrameChecked;
294 if ((pContext->frameCount - lastFrameChecked) > 2 ||
295 (curDraw - lastDrawChecked) > 0x10000)
296 {
297 // Take this opportunity to clean-up old arena allocations
298 pContext->cachingArenaAllocator.FreeOldBlocks();
299
300 lastFrameChecked = pContext->frameCount;
301 lastDrawChecked = curDraw;
302 }
303
304 DRAW_CONTEXT* pCurDrawContext = &pContext->dcRing[dcIndex];
305 pContext->pCurDrawContext = pCurDrawContext;
306
307 // Assign next available entry in DS ring to this DC.
308 uint32_t dsIndex = pContext->curStateId % KNOB_MAX_DRAWS_IN_FLIGHT;
309 pCurDrawContext->pState = &pContext->dsRing[dsIndex];
310
311 // Copy previous state to current state.
312 if (pContext->pPrevDrawContext)
313 {
314 DRAW_CONTEXT* pPrevDrawContext = pContext->pPrevDrawContext;
315
316 // If we're splitting our draw then we can just use the same state from the previous
317 // draw. In this case, we won't increment the DS ring index so the next non-split
318 // draw can receive the state.
319 if (isSplitDraw == false)
320 {
321 CopyState(*pCurDrawContext->pState, *pPrevDrawContext->pState);
322
323 // Should have been cleaned up previously
324 SWR_ASSERT(pCurDrawContext->pState->pArena->IsEmpty() == true);
325
326 pCurDrawContext->pState->pPrivateState = nullptr;
327
328 pContext->curStateId++; // Progress state ring index forward.
329 }
330 else
331 {
332 // If its a split draw then just copy the state pointer over
333 // since its the same draw.
334 pCurDrawContext->pState = pPrevDrawContext->pState;
335 SWR_ASSERT(pPrevDrawContext->cleanupState == false);
336 }
337 }
338 else
339 {
340 SWR_ASSERT(pCurDrawContext->pState->pArena->IsEmpty() == true);
341 pContext->curStateId++; // Progress state ring index forward.
342 }
343
344 SWR_ASSERT(pCurDrawContext->pArena->IsEmpty() == true);
345
346 pCurDrawContext->dependent = false;
347 pCurDrawContext->pContext = pContext;
348 pCurDrawContext->isCompute = false; // Dispatch has to set this to true.
349
350 pCurDrawContext->doneFE = false;
351 pCurDrawContext->FeLock = 0;
352 pCurDrawContext->threadsDone = 0;
353 pCurDrawContext->retireCallback.pfnCallbackFunc = nullptr;
354
355 memset(&pCurDrawContext->dynState, 0, sizeof(pCurDrawContext->dynState));
356
357 // Assign unique drawId for this DC
358 pCurDrawContext->drawId = pContext->dcRing.GetHead();
359
360 pCurDrawContext->cleanupState = true;
361 }
362 else
363 {
364 SWR_ASSERT(isSplitDraw == false, "Split draw should only be used when obtaining a new DC");
365 }
366
367 RDTSC_STOP(APIGetDrawContext, 0, 0);
368 return pContext->pCurDrawContext;
369 }
370
371 API_STATE* GetDrawState(SWR_CONTEXT *pContext)
372 {
373 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
374 SWR_ASSERT(pDC->pState != nullptr);
375
376 return &pDC->pState->state;
377 }
378
379 void SWR_API SwrSaveState(
380 HANDLE hContext,
381 void* pOutputStateBlock,
382 size_t memSize)
383 {
384 SWR_CONTEXT *pContext = GetContext(hContext);
385 auto pSrc = GetDrawState(pContext);
386 SWR_ASSERT(pOutputStateBlock && memSize >= sizeof(*pSrc));
387
388 memcpy(pOutputStateBlock, pSrc, sizeof(*pSrc));
389 }
390
391 void SWR_API SwrRestoreState(
392 HANDLE hContext,
393 const void* pStateBlock,
394 size_t memSize)
395 {
396 SWR_CONTEXT *pContext = GetContext(hContext);
397 auto pDst = GetDrawState(pContext);
398 SWR_ASSERT(pStateBlock && memSize >= sizeof(*pDst));
399
400 memcpy(pDst, pStateBlock, sizeof(*pDst));
401 }
402
403 void SetupDefaultState(SWR_CONTEXT *pContext)
404 {
405 API_STATE* pState = GetDrawState(pContext);
406
407 pState->rastState.cullMode = SWR_CULLMODE_NONE;
408 pState->rastState.frontWinding = SWR_FRONTWINDING_CCW;
409 }
410
411 void SwrSync(HANDLE hContext, PFN_CALLBACK_FUNC pfnFunc, uint64_t userData, uint64_t userData2, uint64_t userData3)
412 {
413 RDTSC_START(APISync);
414
415 SWR_ASSERT(pfnFunc != nullptr);
416
417 SWR_CONTEXT *pContext = GetContext(hContext);
418 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
419
420 pDC->FeWork.type = SYNC;
421 pDC->FeWork.pfnWork = ProcessSync;
422
423 // Setup callback function
424 pDC->retireCallback.pfnCallbackFunc = pfnFunc;
425 pDC->retireCallback.userData = userData;
426 pDC->retireCallback.userData2 = userData2;
427 pDC->retireCallback.userData3 = userData3;
428
429 //enqueue
430 QueueDraw(pContext);
431
432 RDTSC_STOP(APISync, 1, 0);
433 }
434
435 void SwrWaitForIdle(HANDLE hContext)
436 {
437 SWR_CONTEXT *pContext = GetContext(hContext);
438
439 RDTSC_START(APIWaitForIdle);
440
441 while (!pContext->dcRing.IsEmpty())
442 {
443 _mm_pause();
444 }
445
446 RDTSC_STOP(APIWaitForIdle, 1, 0);
447 }
448
449 void SwrWaitForIdleFE(HANDLE hContext)
450 {
451 SWR_CONTEXT *pContext = GetContext(hContext);
452
453 RDTSC_START(APIWaitForIdle);
454
455 while (pContext->drawsOutstandingFE > 0)
456 {
457 _mm_pause();
458 }
459
460 RDTSC_STOP(APIWaitForIdle, 1, 0);
461 }
462
463 void SwrSetVertexBuffers(
464 HANDLE hContext,
465 uint32_t numBuffers,
466 const SWR_VERTEX_BUFFER_STATE* pVertexBuffers)
467 {
468 API_STATE* pState = GetDrawState(GetContext(hContext));
469
470 for (uint32_t i = 0; i < numBuffers; ++i)
471 {
472 const SWR_VERTEX_BUFFER_STATE *pVB = &pVertexBuffers[i];
473 pState->vertexBuffers[pVB->index] = *pVB;
474 }
475 }
476
477 void SwrSetIndexBuffer(
478 HANDLE hContext,
479 const SWR_INDEX_BUFFER_STATE* pIndexBuffer)
480 {
481 API_STATE* pState = GetDrawState(GetContext(hContext));
482
483 pState->indexBuffer = *pIndexBuffer;
484 }
485
486 void SwrSetFetchFunc(
487 HANDLE hContext,
488 PFN_FETCH_FUNC pfnFetchFunc)
489 {
490 API_STATE* pState = GetDrawState(GetContext(hContext));
491
492 pState->pfnFetchFunc = pfnFetchFunc;
493 }
494
495 void SwrSetSoFunc(
496 HANDLE hContext,
497 PFN_SO_FUNC pfnSoFunc,
498 uint32_t streamIndex)
499 {
500 API_STATE* pState = GetDrawState(GetContext(hContext));
501
502 SWR_ASSERT(streamIndex < MAX_SO_STREAMS);
503
504 pState->pfnSoFunc[streamIndex] = pfnSoFunc;
505 }
506
507 void SwrSetSoState(
508 HANDLE hContext,
509 SWR_STREAMOUT_STATE* pSoState)
510 {
511 API_STATE* pState = GetDrawState(GetContext(hContext));
512
513 pState->soState = *pSoState;
514 }
515
516 void SwrSetSoBuffers(
517 HANDLE hContext,
518 SWR_STREAMOUT_BUFFER* pSoBuffer,
519 uint32_t slot)
520 {
521 API_STATE* pState = GetDrawState(GetContext(hContext));
522
523 SWR_ASSERT((slot < 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot);
524
525 pState->soBuffer[slot] = *pSoBuffer;
526 }
527
528 void SwrSetVertexFunc(
529 HANDLE hContext,
530 PFN_VERTEX_FUNC pfnVertexFunc)
531 {
532 API_STATE* pState = GetDrawState(GetContext(hContext));
533
534 pState->pfnVertexFunc = pfnVertexFunc;
535 }
536
537 void SwrSetFrontendState(
538 HANDLE hContext,
539 SWR_FRONTEND_STATE *pFEState)
540 {
541 API_STATE* pState = GetDrawState(GetContext(hContext));
542 pState->frontendState = *pFEState;
543 }
544
545 void SwrSetGsState(
546 HANDLE hContext,
547 SWR_GS_STATE *pGSState)
548 {
549 API_STATE* pState = GetDrawState(GetContext(hContext));
550 pState->gsState = *pGSState;
551 }
552
553 void SwrSetGsFunc(
554 HANDLE hContext,
555 PFN_GS_FUNC pfnGsFunc)
556 {
557 API_STATE* pState = GetDrawState(GetContext(hContext));
558 pState->pfnGsFunc = pfnGsFunc;
559 }
560
561 void SwrSetCsFunc(
562 HANDLE hContext,
563 PFN_CS_FUNC pfnCsFunc,
564 uint32_t totalThreadsInGroup,
565 uint32_t totalSpillFillSize)
566 {
567 API_STATE* pState = GetDrawState(GetContext(hContext));
568 pState->pfnCsFunc = pfnCsFunc;
569 pState->totalThreadsInGroup = totalThreadsInGroup;
570 pState->totalSpillFillSize = totalSpillFillSize;
571 }
572
573 void SwrSetTsState(
574 HANDLE hContext,
575 SWR_TS_STATE *pState)
576 {
577 API_STATE* pApiState = GetDrawState(GetContext(hContext));
578 pApiState->tsState = *pState;
579 }
580
581 void SwrSetHsFunc(
582 HANDLE hContext,
583 PFN_HS_FUNC pfnFunc)
584 {
585 API_STATE* pApiState = GetDrawState(GetContext(hContext));
586 pApiState->pfnHsFunc = pfnFunc;
587 }
588
589 void SwrSetDsFunc(
590 HANDLE hContext,
591 PFN_DS_FUNC pfnFunc)
592 {
593 API_STATE* pApiState = GetDrawState(GetContext(hContext));
594 pApiState->pfnDsFunc = pfnFunc;
595 }
596
597 void SwrSetDepthStencilState(
598 HANDLE hContext,
599 SWR_DEPTH_STENCIL_STATE *pDSState)
600 {
601 API_STATE* pState = GetDrawState(GetContext(hContext));
602
603 pState->depthStencilState = *pDSState;
604 }
605
606 void SwrSetBackendState(
607 HANDLE hContext,
608 SWR_BACKEND_STATE *pBEState)
609 {
610 API_STATE* pState = GetDrawState(GetContext(hContext));
611
612 pState->backendState = *pBEState;
613 }
614
615 void SwrSetPixelShaderState(
616 HANDLE hContext,
617 SWR_PS_STATE *pPSState)
618 {
619 API_STATE *pState = GetDrawState(GetContext(hContext));
620 pState->psState = *pPSState;
621 }
622
623 void SwrSetBlendState(
624 HANDLE hContext,
625 SWR_BLEND_STATE *pBlendState)
626 {
627 API_STATE *pState = GetDrawState(GetContext(hContext));
628 memcpy(&pState->blendState, pBlendState, sizeof(SWR_BLEND_STATE));
629 }
630
631 void SwrSetBlendFunc(
632 HANDLE hContext,
633 uint32_t renderTarget,
634 PFN_BLEND_JIT_FUNC pfnBlendFunc)
635 {
636 SWR_ASSERT(renderTarget < SWR_NUM_RENDERTARGETS);
637 API_STATE *pState = GetDrawState(GetContext(hContext));
638 pState->pfnBlendFunc[renderTarget] = pfnBlendFunc;
639 }
640
641 // update guardband multipliers for the viewport
642 void updateGuardband(API_STATE *pState)
643 {
644 // guardband center is viewport center
645 pState->gbState.left = KNOB_GUARDBAND_WIDTH / pState->vp[0].width;
646 pState->gbState.right = KNOB_GUARDBAND_WIDTH / pState->vp[0].width;
647 pState->gbState.top = KNOB_GUARDBAND_HEIGHT / pState->vp[0].height;
648 pState->gbState.bottom = KNOB_GUARDBAND_HEIGHT / pState->vp[0].height;
649 }
650
651 void SwrSetRastState(
652 HANDLE hContext,
653 const SWR_RASTSTATE *pRastState)
654 {
655 SWR_CONTEXT *pContext = GetContext(hContext);
656 API_STATE* pState = GetDrawState(pContext);
657
658 memcpy(&pState->rastState, pRastState, sizeof(SWR_RASTSTATE));
659 }
660
661 void SwrSetViewports(
662 HANDLE hContext,
663 uint32_t numViewports,
664 const SWR_VIEWPORT* pViewports,
665 const SWR_VIEWPORT_MATRIX* pMatrices)
666 {
667 SWR_ASSERT(numViewports <= KNOB_NUM_VIEWPORTS_SCISSORS,
668 "Invalid number of viewports.");
669
670 SWR_CONTEXT *pContext = GetContext(hContext);
671 API_STATE* pState = GetDrawState(pContext);
672
673 memcpy(&pState->vp[0], pViewports, sizeof(SWR_VIEWPORT) * numViewports);
674
675 if (pMatrices != nullptr)
676 {
677 memcpy(&pState->vpMatrix[0], pMatrices, sizeof(SWR_VIEWPORT_MATRIX) * numViewports);
678 }
679 else
680 {
681 // Compute default viewport transform.
682 for (uint32_t i = 0; i < numViewports; ++i)
683 {
684 if (pContext->driverType == DX)
685 {
686 pState->vpMatrix[i].m00 = pState->vp[i].width / 2.0f;
687 pState->vpMatrix[i].m11 = -pState->vp[i].height / 2.0f;
688 pState->vpMatrix[i].m22 = pState->vp[i].maxZ - pState->vp[i].minZ;
689 pState->vpMatrix[i].m30 = pState->vp[i].x + pState->vpMatrix[i].m00;
690 pState->vpMatrix[i].m31 = pState->vp[i].y - pState->vpMatrix[i].m11;
691 pState->vpMatrix[i].m32 = pState->vp[i].minZ;
692 }
693 else
694 {
695 // Standard, with the exception that Y is inverted.
696 pState->vpMatrix[i].m00 = (pState->vp[i].width - pState->vp[i].x) / 2.0f;
697 pState->vpMatrix[i].m11 = (pState->vp[i].y - pState->vp[i].height) / 2.0f;
698 pState->vpMatrix[i].m22 = (pState->vp[i].maxZ - pState->vp[i].minZ) / 2.0f;
699 pState->vpMatrix[i].m30 = pState->vp[i].x + pState->vpMatrix[i].m00;
700 pState->vpMatrix[i].m31 = pState->vp[i].height + pState->vpMatrix[i].m11;
701 pState->vpMatrix[i].m32 = pState->vp[i].minZ + pState->vpMatrix[i].m22;
702
703 // Now that the matrix is calculated, clip the view coords to screen size.
704 // OpenGL allows for -ve x,y in the viewport.
705 pState->vp[i].x = std::max(pState->vp[i].x, 0.0f);
706 pState->vp[i].y = std::max(pState->vp[i].y, 0.0f);
707 }
708 }
709 }
710
711 updateGuardband(pState);
712 }
713
714 void SwrSetScissorRects(
715 HANDLE hContext,
716 uint32_t numScissors,
717 const BBOX* pScissors)
718 {
719 SWR_ASSERT(numScissors <= KNOB_NUM_VIEWPORTS_SCISSORS,
720 "Invalid number of scissor rects.");
721
722 API_STATE* pState = GetDrawState(GetContext(hContext));
723 memcpy(&pState->scissorRects[0], pScissors, numScissors * sizeof(BBOX));
724 };
725
726 void SetupMacroTileScissors(DRAW_CONTEXT *pDC)
727 {
728 API_STATE *pState = &pDC->pState->state;
729 uint32_t left, right, top, bottom;
730
731 // Set up scissor dimensions based on scissor or viewport
732 if (pState->rastState.scissorEnable)
733 {
734 // scissor rect right/bottom edge are exclusive, core expects scissor dimensions to be inclusive, so subtract one pixel from right/bottom edges
735 left = pState->scissorRects[0].left;
736 right = pState->scissorRects[0].right;
737 top = pState->scissorRects[0].top;
738 bottom = pState->scissorRects[0].bottom;
739 }
740 else
741 {
742 // the vp width and height must be added to origin un-rounded then the result round to -inf.
743 // The cast to int works for rounding assuming all [left, right, top, bottom] are positive.
744 left = (int32_t)pState->vp[0].x;
745 right = (int32_t)(pState->vp[0].x + pState->vp[0].width);
746 top = (int32_t)pState->vp[0].y;
747 bottom = (int32_t)(pState->vp[0].y + pState->vp[0].height);
748 }
749
750 right = std::min<uint32_t>(right, KNOB_MAX_SCISSOR_X);
751 bottom = std::min<uint32_t>(bottom, KNOB_MAX_SCISSOR_Y);
752
753 if (left > KNOB_MAX_SCISSOR_X || top > KNOB_MAX_SCISSOR_Y)
754 {
755 pState->scissorInFixedPoint.left = 0;
756 pState->scissorInFixedPoint.right = 0;
757 pState->scissorInFixedPoint.top = 0;
758 pState->scissorInFixedPoint.bottom = 0;
759 }
760 else
761 {
762 pState->scissorInFixedPoint.left = left * FIXED_POINT_SCALE;
763 pState->scissorInFixedPoint.right = right * FIXED_POINT_SCALE - 1;
764 pState->scissorInFixedPoint.top = top * FIXED_POINT_SCALE;
765 pState->scissorInFixedPoint.bottom = bottom * FIXED_POINT_SCALE - 1;
766 }
767 }
768
769 // templated backend function tables
770 extern PFN_BACKEND_FUNC gBackendNullPs[SWR_MULTISAMPLE_TYPE_COUNT];
771 extern PFN_BACKEND_FUNC gBackendSingleSample[SWR_INPUT_COVERAGE_COUNT][2][2];
772 extern PFN_BACKEND_FUNC gBackendPixelRateTable[SWR_MULTISAMPLE_TYPE_COUNT][SWR_MSAA_SAMPLE_PATTERN_COUNT][SWR_INPUT_COVERAGE_COUNT][2][2][2];
773 extern PFN_BACKEND_FUNC gBackendSampleRateTable[SWR_MULTISAMPLE_TYPE_COUNT][SWR_INPUT_COVERAGE_COUNT][2][2];
774 void SetupPipeline(DRAW_CONTEXT *pDC)
775 {
776 DRAW_STATE* pState = pDC->pState;
777 const SWR_RASTSTATE &rastState = pState->state.rastState;
778 const SWR_PS_STATE &psState = pState->state.psState;
779 BACKEND_FUNCS& backendFuncs = pState->backendFuncs;
780 const uint32_t forcedSampleCount = (rastState.forcedSampleCount) ? 1 : 0;
781
782 // setup backend
783 if (psState.pfnPixelShader == nullptr)
784 {
785 backendFuncs.pfnBackend = gBackendNullPs[pState->state.rastState.sampleCount];
786 }
787 else
788 {
789 const bool bMultisampleEnable = ((rastState.sampleCount > SWR_MULTISAMPLE_1X) || rastState.forcedSampleCount) ? 1 : 0;
790 const uint32_t centroid = ((psState.barycentricsMask & SWR_BARYCENTRIC_CENTROID_MASK) > 0) ? 1 : 0;
791 const uint32_t canEarlyZ = (psState.forceEarlyZ || (!psState.writesODepth && !psState.usesSourceDepth && !psState.usesUAV)) ? 1 : 0;
792
793 SWR_BARYCENTRICS_MASK barycentricsMask = (SWR_BARYCENTRICS_MASK)psState.barycentricsMask;
794
795 // select backend function
796 switch(psState.shadingRate)
797 {
798 case SWR_SHADING_RATE_PIXEL:
799 if(bMultisampleEnable)
800 {
801 // always need to generate I & J per sample for Z interpolation
802 barycentricsMask = (SWR_BARYCENTRICS_MASK)(barycentricsMask | SWR_BARYCENTRIC_PER_SAMPLE_MASK);
803 backendFuncs.pfnBackend = gBackendPixelRateTable[rastState.sampleCount][rastState.samplePattern][psState.inputCoverage][centroid][forcedSampleCount][canEarlyZ];
804 }
805 else
806 {
807 // always need to generate I & J per pixel for Z interpolation
808 barycentricsMask = (SWR_BARYCENTRICS_MASK)(barycentricsMask | SWR_BARYCENTRIC_PER_PIXEL_MASK);
809 backendFuncs.pfnBackend = gBackendSingleSample[psState.inputCoverage][centroid][canEarlyZ];
810 }
811 break;
812 case SWR_SHADING_RATE_SAMPLE:
813 SWR_ASSERT(rastState.samplePattern == SWR_MSAA_STANDARD_PATTERN);
814 // always need to generate I & J per sample for Z interpolation
815 barycentricsMask = (SWR_BARYCENTRICS_MASK)(barycentricsMask | SWR_BARYCENTRIC_PER_SAMPLE_MASK);
816 backendFuncs.pfnBackend = gBackendSampleRateTable[rastState.sampleCount][psState.inputCoverage][centroid][canEarlyZ];
817 break;
818 default:
819 SWR_ASSERT(0 && "Invalid shading rate");
820 break;
821 }
822 }
823
824 PFN_PROCESS_PRIMS pfnBinner;
825 switch (pState->state.topology)
826 {
827 case TOP_POINT_LIST:
828 pState->pfnProcessPrims = ClipPoints;
829 pfnBinner = BinPoints;
830 break;
831 case TOP_LINE_LIST:
832 case TOP_LINE_STRIP:
833 case TOP_LINE_LOOP:
834 case TOP_LINE_LIST_ADJ:
835 case TOP_LISTSTRIP_ADJ:
836 pState->pfnProcessPrims = ClipLines;
837 pfnBinner = BinLines;
838 break;
839 default:
840 pState->pfnProcessPrims = ClipTriangles;
841 pfnBinner = GetBinTrianglesFunc((rastState.conservativeRast > 0));
842 break;
843 };
844
845 // disable clipper if viewport transform is disabled
846 if (pState->state.frontendState.vpTransformDisable)
847 {
848 pState->pfnProcessPrims = pfnBinner;
849 }
850
851 if ((pState->state.psState.pfnPixelShader == nullptr) &&
852 (pState->state.depthStencilState.depthTestEnable == FALSE) &&
853 (pState->state.depthStencilState.depthWriteEnable == FALSE) &&
854 (pState->state.depthStencilState.stencilTestEnable == FALSE) &&
855 (pState->state.depthStencilState.stencilWriteEnable == FALSE) &&
856 (pState->state.backendState.numAttributes == 0))
857 {
858 pState->pfnProcessPrims = nullptr;
859 }
860
861 if (pState->state.soState.rasterizerDisable == true)
862 {
863 pState->pfnProcessPrims = nullptr;
864 }
865
866 // set up the frontend attribute count
867 pState->state.feNumAttributes = 0;
868 const SWR_BACKEND_STATE& backendState = pState->state.backendState;
869 if (backendState.swizzleEnable)
870 {
871 // attribute swizzling is enabled, iterate over the map and record the max attribute used
872 for (uint32_t i = 0; i < backendState.numAttributes; ++i)
873 {
874 pState->state.feNumAttributes = std::max(pState->state.feNumAttributes, (uint32_t)backendState.swizzleMap[i].sourceAttrib + 1);
875 }
876 }
877 else
878 {
879 pState->state.feNumAttributes = pState->state.backendState.numAttributes;
880 }
881
882 if (pState->state.soState.soEnable)
883 {
884 uint32_t streamMasks = 0;
885 for (uint32_t i = 0; i < 4; ++i)
886 {
887 streamMasks |= pState->state.soState.streamMasks[i];
888 }
889
890 DWORD maxAttrib;
891 if (_BitScanReverse(&maxAttrib, streamMasks))
892 {
893 pState->state.feNumAttributes = std::max(pState->state.feNumAttributes, (uint32_t)(maxAttrib + 1));
894 }
895 }
896
897 // complicated logic to test for cases where we don't need backing hottile memory for a draw
898 // have to check for the special case where depth/stencil test is enabled but depthwrite is disabled.
899 pState->state.depthHottileEnable = ((!(pState->state.depthStencilState.depthTestEnable &&
900 !pState->state.depthStencilState.depthWriteEnable &&
901 pState->state.depthStencilState.depthTestFunc == ZFUNC_ALWAYS)) &&
902 (pState->state.depthStencilState.depthTestEnable ||
903 pState->state.depthStencilState.depthWriteEnable)) ? true : false;
904
905 pState->state.stencilHottileEnable = (((!(pState->state.depthStencilState.stencilTestEnable &&
906 !pState->state.depthStencilState.stencilWriteEnable &&
907 pState->state.depthStencilState.stencilTestFunc == ZFUNC_ALWAYS)) ||
908 // for stencil we have to check the double sided state as well
909 (!(pState->state.depthStencilState.doubleSidedStencilTestEnable &&
910 !pState->state.depthStencilState.stencilWriteEnable &&
911 pState->state.depthStencilState.backfaceStencilTestFunc == ZFUNC_ALWAYS))) &&
912 (pState->state.depthStencilState.stencilTestEnable ||
913 pState->state.depthStencilState.stencilWriteEnable)) ? true : false;
914
915 uint32_t numRTs = pState->state.psState.numRenderTargets;
916 pState->state.colorHottileEnable = 0;
917 if (psState.pfnPixelShader != nullptr)
918 {
919 for (uint32_t rt = 0; rt < numRTs; ++rt)
920 {
921 pState->state.colorHottileEnable |=
922 (!pState->state.blendState.renderTarget[rt].writeDisableAlpha ||
923 !pState->state.blendState.renderTarget[rt].writeDisableRed ||
924 !pState->state.blendState.renderTarget[rt].writeDisableGreen ||
925 !pState->state.blendState.renderTarget[rt].writeDisableBlue) ? (1 << rt) : 0;
926 }
927 }
928
929 // Setup depth quantization function
930 if (pState->state.depthHottileEnable)
931 {
932 switch (pState->state.rastState.depthFormat)
933 {
934 case R32_FLOAT_X8X24_TYPELESS: pState->state.pfnQuantizeDepth = QuantizeDepth < R32_FLOAT_X8X24_TYPELESS > ; break;
935 case R32_FLOAT: pState->state.pfnQuantizeDepth = QuantizeDepth < R32_FLOAT > ; break;
936 case R24_UNORM_X8_TYPELESS: pState->state.pfnQuantizeDepth = QuantizeDepth < R24_UNORM_X8_TYPELESS > ; break;
937 case R16_UNORM: pState->state.pfnQuantizeDepth = QuantizeDepth < R16_UNORM > ; break;
938 default: SWR_ASSERT(false, "Unsupported depth format for depth quantiztion.");
939 pState->state.pfnQuantizeDepth = QuantizeDepth < R32_FLOAT > ;
940 }
941 }
942 else
943 {
944 // set up pass-through quantize if depth isn't enabled
945 pState->state.pfnQuantizeDepth = QuantizeDepth < R32_FLOAT > ;
946 }
947 }
948
949 //////////////////////////////////////////////////////////////////////////
950 /// @brief InitDraw
951 /// @param pDC - Draw context to initialize for this draw.
952 void InitDraw(
953 DRAW_CONTEXT *pDC,
954 bool isSplitDraw)
955 {
956 // We don't need to re-setup the scissors/pipeline state again for split draw.
957 if (isSplitDraw == false)
958 {
959 SetupMacroTileScissors(pDC);
960 SetupPipeline(pDC);
961 }
962 }
963
964 //////////////////////////////////////////////////////////////////////////
965 /// @brief We can split the draw for certain topologies for better performance.
966 /// @param totalVerts - Total vertices for draw
967 /// @param topology - Topology used for draw
968 uint32_t MaxVertsPerDraw(
969 DRAW_CONTEXT* pDC,
970 uint32_t totalVerts,
971 PRIMITIVE_TOPOLOGY topology)
972 {
973 API_STATE& state = pDC->pState->state;
974
975 uint32_t vertsPerDraw = totalVerts;
976
977 if (state.soState.soEnable)
978 {
979 return totalVerts;
980 }
981
982 switch (topology)
983 {
984 case TOP_POINT_LIST:
985 case TOP_TRIANGLE_LIST:
986 vertsPerDraw = KNOB_MAX_PRIMS_PER_DRAW;
987 break;
988
989 case TOP_PATCHLIST_1:
990 case TOP_PATCHLIST_2:
991 case TOP_PATCHLIST_3:
992 case TOP_PATCHLIST_4:
993 case TOP_PATCHLIST_5:
994 case TOP_PATCHLIST_6:
995 case TOP_PATCHLIST_7:
996 case TOP_PATCHLIST_8:
997 case TOP_PATCHLIST_9:
998 case TOP_PATCHLIST_10:
999 case TOP_PATCHLIST_11:
1000 case TOP_PATCHLIST_12:
1001 case TOP_PATCHLIST_13:
1002 case TOP_PATCHLIST_14:
1003 case TOP_PATCHLIST_15:
1004 case TOP_PATCHLIST_16:
1005 case TOP_PATCHLIST_17:
1006 case TOP_PATCHLIST_18:
1007 case TOP_PATCHLIST_19:
1008 case TOP_PATCHLIST_20:
1009 case TOP_PATCHLIST_21:
1010 case TOP_PATCHLIST_22:
1011 case TOP_PATCHLIST_23:
1012 case TOP_PATCHLIST_24:
1013 case TOP_PATCHLIST_25:
1014 case TOP_PATCHLIST_26:
1015 case TOP_PATCHLIST_27:
1016 case TOP_PATCHLIST_28:
1017 case TOP_PATCHLIST_29:
1018 case TOP_PATCHLIST_30:
1019 case TOP_PATCHLIST_31:
1020 case TOP_PATCHLIST_32:
1021 if (pDC->pState->state.tsState.tsEnable)
1022 {
1023 uint32_t vertsPerPrim = topology - TOP_PATCHLIST_BASE;
1024 vertsPerDraw = vertsPerPrim * KNOB_MAX_TESS_PRIMS_PER_DRAW;
1025 }
1026 break;
1027
1028 // The Primitive Assembly code can only handle 1 RECT at a time.
1029 case TOP_RECT_LIST:
1030 vertsPerDraw = 3;
1031 break;
1032
1033 default:
1034 // We are not splitting up draws for other topologies.
1035 break;
1036 }
1037
1038 return vertsPerDraw;
1039 }
1040
1041
1042 //////////////////////////////////////////////////////////////////////////
1043 /// @brief DrawInstanced
1044 /// @param hContext - Handle passed back from SwrCreateContext
1045 /// @param topology - Specifies topology for draw.
1046 /// @param numVerts - How many vertices to read sequentially from vertex data (per instance).
1047 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1048 /// @param numInstances - How many instances to render.
1049 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1050 void DrawInstanced(
1051 HANDLE hContext,
1052 PRIMITIVE_TOPOLOGY topology,
1053 uint32_t numVertices,
1054 uint32_t startVertex,
1055 uint32_t numInstances = 1,
1056 uint32_t startInstance = 0)
1057 {
1058 if (KNOB_TOSS_DRAW)
1059 {
1060 return;
1061 }
1062
1063 RDTSC_START(APIDraw);
1064
1065 SWR_CONTEXT *pContext = GetContext(hContext);
1066 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1067
1068 uint32_t maxVertsPerDraw = MaxVertsPerDraw(pDC, numVertices, topology);
1069 uint32_t primsPerDraw = GetNumPrims(topology, maxVertsPerDraw);
1070 uint32_t remainingVerts = numVertices;
1071
1072 API_STATE *pState = &pDC->pState->state;
1073 pState->topology = topology;
1074 pState->forceFront = false;
1075
1076 // disable culling for points/lines
1077 uint32_t oldCullMode = pState->rastState.cullMode;
1078 if (topology == TOP_POINT_LIST)
1079 {
1080 pState->rastState.cullMode = SWR_CULLMODE_NONE;
1081 pState->forceFront = true;
1082 }
1083
1084 int draw = 0;
1085 while (remainingVerts)
1086 {
1087 uint32_t numVertsForDraw = (remainingVerts < maxVertsPerDraw) ?
1088 remainingVerts : maxVertsPerDraw;
1089
1090 bool isSplitDraw = (draw > 0) ? true : false;
1091 DRAW_CONTEXT* pDC = GetDrawContext(pContext, isSplitDraw);
1092 InitDraw(pDC, isSplitDraw);
1093
1094 pDC->FeWork.type = DRAW;
1095 pDC->FeWork.pfnWork = GetProcessDrawFunc(
1096 false, // IsIndexed
1097 false, // bEnableCutIndex
1098 pState->tsState.tsEnable,
1099 pState->gsState.gsEnable,
1100 pState->soState.soEnable,
1101 pDC->pState->pfnProcessPrims != nullptr);
1102 pDC->FeWork.desc.draw.numVerts = numVertsForDraw;
1103 pDC->FeWork.desc.draw.startVertex = startVertex;
1104 pDC->FeWork.desc.draw.numInstances = numInstances;
1105 pDC->FeWork.desc.draw.startInstance = startInstance;
1106 pDC->FeWork.desc.draw.startPrimID = draw * primsPerDraw;
1107 pDC->FeWork.desc.draw.startVertexID = draw * maxVertsPerDraw;
1108
1109 pDC->cleanupState = (remainingVerts == numVertsForDraw);
1110
1111 //enqueue DC
1112 QueueDraw(pContext);
1113
1114 remainingVerts -= numVertsForDraw;
1115 draw++;
1116 }
1117
1118 // restore culling state
1119 pDC = GetDrawContext(pContext);
1120 pDC->pState->state.rastState.cullMode = oldCullMode;
1121
1122 RDTSC_STOP(APIDraw, numVertices * numInstances, 0);
1123 }
1124
1125 //////////////////////////////////////////////////////////////////////////
1126 /// @brief SwrDraw
1127 /// @param hContext - Handle passed back from SwrCreateContext
1128 /// @param topology - Specifies topology for draw.
1129 /// @param startVertex - Specifies start vertex in vertex buffer for draw.
1130 /// @param primCount - Number of vertices.
1131 void SwrDraw(
1132 HANDLE hContext,
1133 PRIMITIVE_TOPOLOGY topology,
1134 uint32_t startVertex,
1135 uint32_t numVertices)
1136 {
1137 DrawInstanced(hContext, topology, numVertices, startVertex);
1138 }
1139
1140 //////////////////////////////////////////////////////////////////////////
1141 /// @brief SwrDrawInstanced
1142 /// @param hContext - Handle passed back from SwrCreateContext
1143 /// @param topology - Specifies topology for draw.
1144 /// @param numVertsPerInstance - How many vertices to read sequentially from vertex data.
1145 /// @param numInstances - How many instances to render.
1146 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1147 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1148 void SwrDrawInstanced(
1149 HANDLE hContext,
1150 PRIMITIVE_TOPOLOGY topology,
1151 uint32_t numVertsPerInstance,
1152 uint32_t numInstances,
1153 uint32_t startVertex,
1154 uint32_t startInstance
1155 )
1156 {
1157 DrawInstanced(hContext, topology, numVertsPerInstance, startVertex, numInstances, startInstance);
1158 }
1159
1160 //////////////////////////////////////////////////////////////////////////
1161 /// @brief DrawIndexedInstanced
1162 /// @param hContext - Handle passed back from SwrCreateContext
1163 /// @param topology - Specifies topology for draw.
1164 /// @param numIndices - Number of indices to read sequentially from index buffer.
1165 /// @param indexOffset - Starting index into index buffer.
1166 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1167 /// @param numInstances - Number of instances to render.
1168 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1169 void DrawIndexedInstance(
1170 HANDLE hContext,
1171 PRIMITIVE_TOPOLOGY topology,
1172 uint32_t numIndices,
1173 uint32_t indexOffset,
1174 int32_t baseVertex,
1175 uint32_t numInstances = 1,
1176 uint32_t startInstance = 0)
1177 {
1178 if (KNOB_TOSS_DRAW)
1179 {
1180 return;
1181 }
1182
1183 RDTSC_START(APIDrawIndexed);
1184
1185 SWR_CONTEXT *pContext = GetContext(hContext);
1186 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1187 API_STATE* pState = &pDC->pState->state;
1188
1189 uint32_t maxIndicesPerDraw = MaxVertsPerDraw(pDC, numIndices, topology);
1190 uint32_t primsPerDraw = GetNumPrims(topology, maxIndicesPerDraw);
1191 uint32_t remainingIndices = numIndices;
1192
1193 uint32_t indexSize = 0;
1194 switch (pState->indexBuffer.format)
1195 {
1196 case R32_UINT: indexSize = sizeof(uint32_t); break;
1197 case R16_UINT: indexSize = sizeof(uint16_t); break;
1198 case R8_UINT: indexSize = sizeof(uint8_t); break;
1199 default:
1200 SWR_ASSERT(0);
1201 }
1202
1203 int draw = 0;
1204 uint8_t *pIB = (uint8_t*)pState->indexBuffer.pIndices;
1205 pIB += (uint64_t)indexOffset * (uint64_t)indexSize;
1206
1207 pState->topology = topology;
1208 pState->forceFront = false;
1209
1210 // disable culling for points/lines
1211 uint32_t oldCullMode = pState->rastState.cullMode;
1212 if (topology == TOP_POINT_LIST)
1213 {
1214 pState->rastState.cullMode = SWR_CULLMODE_NONE;
1215 pState->forceFront = true;
1216 }
1217
1218 while (remainingIndices)
1219 {
1220 uint32_t numIndicesForDraw = (remainingIndices < maxIndicesPerDraw) ?
1221 remainingIndices : maxIndicesPerDraw;
1222
1223 // When breaking up draw, we need to obtain new draw context for each iteration.
1224 bool isSplitDraw = (draw > 0) ? true : false;
1225 pDC = GetDrawContext(pContext, isSplitDraw);
1226 InitDraw(pDC, isSplitDraw);
1227
1228 pDC->FeWork.type = DRAW;
1229 pDC->FeWork.pfnWork = GetProcessDrawFunc(
1230 true, // IsIndexed
1231 pState->frontendState.bEnableCutIndex,
1232 pState->tsState.tsEnable,
1233 pState->gsState.gsEnable,
1234 pState->soState.soEnable,
1235 pDC->pState->pfnProcessPrims != nullptr);
1236 pDC->FeWork.desc.draw.pDC = pDC;
1237 pDC->FeWork.desc.draw.numIndices = numIndicesForDraw;
1238 pDC->FeWork.desc.draw.pIB = (int*)pIB;
1239 pDC->FeWork.desc.draw.type = pDC->pState->state.indexBuffer.format;
1240
1241 pDC->FeWork.desc.draw.numInstances = numInstances;
1242 pDC->FeWork.desc.draw.startInstance = startInstance;
1243 pDC->FeWork.desc.draw.baseVertex = baseVertex;
1244 pDC->FeWork.desc.draw.startPrimID = draw * primsPerDraw;
1245
1246 pDC->cleanupState = (remainingIndices == numIndicesForDraw);
1247
1248 //enqueue DC
1249 QueueDraw(pContext);
1250
1251 pIB += maxIndicesPerDraw * indexSize;
1252 remainingIndices -= numIndicesForDraw;
1253 draw++;
1254 }
1255
1256 // restore culling state
1257 pDC = GetDrawContext(pContext);
1258 pDC->pState->state.rastState.cullMode = oldCullMode;
1259
1260 RDTSC_STOP(APIDrawIndexed, numIndices * numInstances, 0);
1261 }
1262
1263
1264 //////////////////////////////////////////////////////////////////////////
1265 /// @brief DrawIndexed
1266 /// @param hContext - Handle passed back from SwrCreateContext
1267 /// @param topology - Specifies topology for draw.
1268 /// @param numIndices - Number of indices to read sequentially from index buffer.
1269 /// @param indexOffset - Starting index into index buffer.
1270 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1271 void SwrDrawIndexed(
1272 HANDLE hContext,
1273 PRIMITIVE_TOPOLOGY topology,
1274 uint32_t numIndices,
1275 uint32_t indexOffset,
1276 int32_t baseVertex
1277 )
1278 {
1279 DrawIndexedInstance(hContext, topology, numIndices, indexOffset, baseVertex);
1280 }
1281
1282 //////////////////////////////////////////////////////////////////////////
1283 /// @brief SwrDrawIndexedInstanced
1284 /// @param hContext - Handle passed back from SwrCreateContext
1285 /// @param topology - Specifies topology for draw.
1286 /// @param numIndices - Number of indices to read sequentially from index buffer.
1287 /// @param numInstances - Number of instances to render.
1288 /// @param indexOffset - Starting index into index buffer.
1289 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1290 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1291 void SwrDrawIndexedInstanced(
1292 HANDLE hContext,
1293 PRIMITIVE_TOPOLOGY topology,
1294 uint32_t numIndices,
1295 uint32_t numInstances,
1296 uint32_t indexOffset,
1297 int32_t baseVertex,
1298 uint32_t startInstance)
1299 {
1300 DrawIndexedInstance(hContext, topology, numIndices, indexOffset, baseVertex, numInstances, startInstance);
1301 }
1302
1303 //////////////////////////////////////////////////////////////////////////
1304 /// @brief SwrInvalidateTiles
1305 /// @param hContext - Handle passed back from SwrCreateContext
1306 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to invalidate.
1307 void SwrInvalidateTiles(
1308 HANDLE hContext,
1309 uint32_t attachmentMask)
1310 {
1311 if (KNOB_TOSS_DRAW)
1312 {
1313 return;
1314 }
1315
1316 SWR_CONTEXT *pContext = GetContext(hContext);
1317 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1318
1319 pDC->FeWork.type = DISCARDINVALIDATETILES;
1320 pDC->FeWork.pfnWork = ProcessDiscardInvalidateTiles;
1321 pDC->FeWork.desc.discardInvalidateTiles.attachmentMask = attachmentMask;
1322 memset(&pDC->FeWork.desc.discardInvalidateTiles.rect, 0, sizeof(SWR_RECT));
1323 pDC->FeWork.desc.discardInvalidateTiles.newTileState = SWR_TILE_INVALID;
1324 pDC->FeWork.desc.discardInvalidateTiles.createNewTiles = false;
1325 pDC->FeWork.desc.discardInvalidateTiles.fullTilesOnly = false;
1326
1327 //enqueue
1328 QueueDraw(pContext);
1329 }
1330
1331 //////////////////////////////////////////////////////////////////////////
1332 /// @brief SwrDiscardRect
1333 /// @param hContext - Handle passed back from SwrCreateContext
1334 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to discard.
1335 /// @param rect - if rect is all zeros, the entire attachment surface will be discarded
1336 void SwrDiscardRect(
1337 HANDLE hContext,
1338 uint32_t attachmentMask,
1339 SWR_RECT rect)
1340 {
1341 if (KNOB_TOSS_DRAW)
1342 {
1343 return;
1344 }
1345
1346 SWR_CONTEXT *pContext = GetContext(hContext);
1347 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1348
1349 // Queue a load to the hottile
1350 pDC->FeWork.type = DISCARDINVALIDATETILES;
1351 pDC->FeWork.pfnWork = ProcessDiscardInvalidateTiles;
1352 pDC->FeWork.desc.discardInvalidateTiles.attachmentMask = attachmentMask;
1353 pDC->FeWork.desc.discardInvalidateTiles.rect = rect;
1354 pDC->FeWork.desc.discardInvalidateTiles.newTileState = SWR_TILE_RESOLVED;
1355 pDC->FeWork.desc.discardInvalidateTiles.createNewTiles = true;
1356 pDC->FeWork.desc.discardInvalidateTiles.fullTilesOnly = true;
1357
1358 //enqueue
1359 QueueDraw(pContext);
1360 }
1361
1362 //////////////////////////////////////////////////////////////////////////
1363 /// @brief SwrDispatch
1364 /// @param hContext - Handle passed back from SwrCreateContext
1365 /// @param threadGroupCountX - Number of thread groups dispatched in X direction
1366 /// @param threadGroupCountY - Number of thread groups dispatched in Y direction
1367 /// @param threadGroupCountZ - Number of thread groups dispatched in Z direction
1368 void SwrDispatch(
1369 HANDLE hContext,
1370 uint32_t threadGroupCountX,
1371 uint32_t threadGroupCountY,
1372 uint32_t threadGroupCountZ)
1373 {
1374 if (KNOB_TOSS_DRAW)
1375 {
1376 return;
1377 }
1378
1379 RDTSC_START(APIDispatch);
1380 SWR_CONTEXT *pContext = GetContext(hContext);
1381 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1382
1383 pDC->isCompute = true; // This is a compute context.
1384
1385 COMPUTE_DESC* pTaskData = (COMPUTE_DESC*)pDC->pArena->AllocAligned(sizeof(COMPUTE_DESC), 64);
1386
1387 pTaskData->threadGroupCountX = threadGroupCountX;
1388 pTaskData->threadGroupCountY = threadGroupCountY;
1389 pTaskData->threadGroupCountZ = threadGroupCountZ;
1390
1391 uint32_t totalThreadGroups = threadGroupCountX * threadGroupCountY * threadGroupCountZ;
1392 uint32_t dcIndex = pDC->drawId % KNOB_MAX_DRAWS_IN_FLIGHT;
1393 pDC->pDispatch = &pContext->pDispatchQueueArray[dcIndex];
1394 pDC->pDispatch->initialize(totalThreadGroups, pTaskData);
1395
1396 QueueDispatch(pContext);
1397 RDTSC_STOP(APIDispatch, threadGroupCountX * threadGroupCountY * threadGroupCountZ, 0);
1398 }
1399
1400 // Deswizzles, converts and stores current contents of the hot tiles to surface
1401 // described by pState
1402 void SwrStoreTiles(
1403 HANDLE hContext,
1404 SWR_RENDERTARGET_ATTACHMENT attachment,
1405 SWR_TILE_STATE postStoreTileState)
1406 {
1407 if (KNOB_TOSS_DRAW)
1408 {
1409 return;
1410 }
1411
1412 RDTSC_START(APIStoreTiles);
1413
1414 SWR_CONTEXT *pContext = GetContext(hContext);
1415 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1416
1417 SetupMacroTileScissors(pDC);
1418
1419 pDC->FeWork.type = STORETILES;
1420 pDC->FeWork.pfnWork = ProcessStoreTiles;
1421 pDC->FeWork.desc.storeTiles.attachment = attachment;
1422 pDC->FeWork.desc.storeTiles.postStoreTileState = postStoreTileState;
1423
1424 //enqueue
1425 QueueDraw(pContext);
1426
1427 RDTSC_STOP(APIStoreTiles, 0, 0);
1428 }
1429
1430 void SwrClearRenderTarget(
1431 HANDLE hContext,
1432 uint32_t clearMask,
1433 const float clearColor[4],
1434 float z,
1435 uint8_t stencil)
1436 {
1437 if (KNOB_TOSS_DRAW)
1438 {
1439 return;
1440 }
1441
1442 RDTSC_START(APIClearRenderTarget);
1443
1444 SWR_CONTEXT *pContext = GetContext(hContext);
1445
1446 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1447
1448 SetupMacroTileScissors(pDC);
1449
1450 CLEAR_FLAGS flags;
1451 flags.mask = clearMask;
1452
1453 pDC->FeWork.type = CLEAR;
1454 pDC->FeWork.pfnWork = ProcessClear;
1455 pDC->FeWork.desc.clear.flags = flags;
1456 pDC->FeWork.desc.clear.clearDepth = z;
1457 pDC->FeWork.desc.clear.clearRTColor[0] = clearColor[0];
1458 pDC->FeWork.desc.clear.clearRTColor[1] = clearColor[1];
1459 pDC->FeWork.desc.clear.clearRTColor[2] = clearColor[2];
1460 pDC->FeWork.desc.clear.clearRTColor[3] = clearColor[3];
1461 pDC->FeWork.desc.clear.clearStencil = stencil;
1462
1463 // enqueue draw
1464 QueueDraw(pContext);
1465
1466 RDTSC_STOP(APIClearRenderTarget, 0, pDC->drawId);
1467 }
1468
1469 //////////////////////////////////////////////////////////////////////////
1470 /// @brief Returns a pointer to the private context state for the current
1471 /// draw operation. This is used for external componets such as the
1472 /// sampler.
1473 /// SWR is responsible for the allocation of the private context state.
1474 /// @param hContext - Handle passed back from SwrCreateContext
1475 VOID* SwrGetPrivateContextState(
1476 HANDLE hContext)
1477 {
1478 SWR_CONTEXT* pContext = GetContext(hContext);
1479 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1480 DRAW_STATE* pState = pDC->pState;
1481
1482 if (pState->pPrivateState == nullptr)
1483 {
1484 pState->pPrivateState = pState->pArena->AllocAligned(pContext->privateStateSize, KNOB_SIMD_WIDTH*sizeof(float));
1485 }
1486
1487 return pState->pPrivateState;
1488 }
1489
1490 //////////////////////////////////////////////////////////////////////////
1491 /// @brief Clients can use this to allocate memory for draw/dispatch
1492 /// operations. The memory will automatically be freed once operation
1493 /// has completed. Client can use this to allocate binding tables,
1494 /// etc. needed for shader execution.
1495 /// @param hContext - Handle passed back from SwrCreateContext
1496 /// @param size - Size of allocation
1497 /// @param align - Alignment needed for allocation.
1498 VOID* SwrAllocDrawContextMemory(
1499 HANDLE hContext,
1500 uint32_t size,
1501 uint32_t align)
1502 {
1503 SWR_CONTEXT* pContext = GetContext(hContext);
1504 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1505
1506 return pDC->pState->pArena->AllocAligned(size, align);
1507 }
1508
1509 //////////////////////////////////////////////////////////////////////////
1510 /// @brief Returns pointer to SWR stats.
1511 /// @note The counters are atomically incremented by multiple threads.
1512 /// When calling this, you need to ensure all previous operations
1513 /// have completed.
1514 /// @todo If necessary, add a callback to avoid stalling the pipe to
1515 /// sample the counters.
1516 /// @param hContext - Handle passed back from SwrCreateContext
1517 /// @param pStats - SWR will fill this out for caller.
1518 void SwrGetStats(
1519 HANDLE hContext,
1520 SWR_STATS* pStats)
1521 {
1522 SWR_CONTEXT *pContext = GetContext(hContext);
1523 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1524
1525 pDC->FeWork.type = QUERYSTATS;
1526 pDC->FeWork.pfnWork = ProcessQueryStats;
1527 pDC->FeWork.desc.queryStats.pStats = pStats;
1528
1529 // cannot execute until all previous draws have completed
1530 pDC->dependent = true;
1531
1532 //enqueue
1533 QueueDraw(pContext);
1534 }
1535
1536 //////////////////////////////////////////////////////////////////////////
1537 /// @brief Enables stats counting
1538 /// @param hContext - Handle passed back from SwrCreateContext
1539 /// @param enable - If true then counts are incremented.
1540 void SwrEnableStats(
1541 HANDLE hContext,
1542 bool enable)
1543 {
1544 SWR_CONTEXT *pContext = GetContext(hContext);
1545 DRAW_CONTEXT* pDC = GetDrawContext(pContext);
1546
1547 pDC->pState->state.enableStats = enable;
1548 }
1549
1550 //////////////////////////////////////////////////////////////////////////
1551 /// @brief Mark end of frame - used for performance profiling
1552 /// @param hContext - Handle passed back from SwrCreateContext
1553 void SWR_API SwrEndFrame(
1554 HANDLE hContext)
1555 {
1556 RDTSC_ENDFRAME();
1557 SWR_CONTEXT *pContext = GetContext(hContext);
1558 pContext->frameCount++;
1559 }