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