1 /****************************************************************************
2 * Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
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:
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
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
25 * @brief API implementation
27 ******************************************************************************/
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"
46 #include "common/simdintrin.h"
47 #include "common/os.h"
49 static const SWR_RECT g_MaxScissorRect
= { 0, 0, KNOB_MAX_SCISSOR_X
, KNOB_MAX_SCISSOR_Y
};
51 void SetupDefaultState(SWR_CONTEXT
*pContext
);
53 static INLINE SWR_CONTEXT
* GetContext(HANDLE hContext
)
55 return (SWR_CONTEXT
*)hContext
;
58 void WakeAllThreads(SWR_CONTEXT
*pContext
)
60 pContext
->FifosNotEmpty
.notify_all();
63 //////////////////////////////////////////////////////////////////////////
64 /// @brief Create SWR Context.
65 /// @param pCreateInfo - pointer to creation info.
66 HANDLE
SwrCreateContext(
67 SWR_CREATECONTEXT_INFO
* pCreateInfo
)
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();
76 pContext
->driverType
= pCreateInfo
->driver
;
77 pContext
->privateStateSize
= pCreateInfo
->privateStateSize
;
79 pContext
->dcRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
80 pContext
->dsRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
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);
85 for (uint32_t dc
= 0; dc
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++dc
)
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();
91 pContext
->dsRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
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
;
100 if (pCreateInfo
->pThreadInfo
)
102 pContext
->threadInfo
= *pCreateInfo
->pThreadInfo
;
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();
110 CreateThreadPool(pContext
, &pContext
->threadPool
);
112 pContext
->ppScratch
= new uint8_t*[pContext
->NumWorkerThreads
];
113 pContext
->pStats
= new SWR_STATS
[pContext
->NumWorkerThreads
];
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();
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
)
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
,
131 pContext
->ppScratch
[i
] = (uint8_t*)AlignedMalloc(32 * sizeof(KILOBYTE
), KNOB_SIMD_WIDTH
* 4);
134 // Initialize worker thread context for ArchRast.
135 pContext
->pArContext
[i
] = ArchRast::CreateThreadContext();
138 // State setup AFTER context is fully initialized
139 SetupDefaultState(pContext
);
141 // initialize hot tile manager
142 pContext
->pHotTileMgr
= new HotTileMgr();
144 // initialize function pointer tables
145 InitClearTilesTable();
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
;
155 // pass pointer to bucket manager back to caller
156 #ifdef KNOB_ENABLE_RDTSC
157 pCreateInfo
->pBucketMgr
= &gBucketMgr
;
160 pCreateInfo
->contextSaveSize
= sizeof(API_STATE
);
162 StartThreadPool(pContext
, &pContext
->threadPool
);
164 return (HANDLE
)pContext
;
167 void CopyState(DRAW_STATE
& dst
, const DRAW_STATE
& src
)
169 memcpy(&dst
.state
, &src
.state
, sizeof(API_STATE
));
172 template<bool IsDraw
>
173 void QueueWork(SWR_CONTEXT
*pContext
)
175 DRAW_CONTEXT
* pDC
= pContext
->pCurDrawContext
;
176 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
180 pDC
->pTileMgr
= &pContext
->pMacroTileManagerArray
[dcIndex
];
181 pDC
->pTileMgr
->initialize();
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
;
192 InterlockedIncrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
197 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
);
198 pContext
->dcRing
.Enqueue();
201 if (pContext
->threadInfo
.SINGLE_THREADED
)
203 // flush denormals to 0
204 uint32_t mxcsr
= _mm_getcsr();
205 _mm_setcsr(mxcsr
| _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
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);
215 uint32_t curDispatch
= pContext
->pCurDrawContext
->drawId
;
216 WorkOnCompute(pContext
, 0, curDispatch
);
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) {}
227 AR_API_BEGIN(APIDrawWakeAllThreads
, pDC
->drawId
);
228 WakeAllThreads(pContext
);
229 AR_API_END(APIDrawWakeAllThreads
, 1);
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;
237 INLINE
void QueueDraw(SWR_CONTEXT
* pContext
)
239 QueueWork
<true>(pContext
);
242 INLINE
void QueueDispatch(SWR_CONTEXT
* pContext
)
244 QueueWork
<false>(pContext
);
247 DRAW_CONTEXT
* GetDrawContext(SWR_CONTEXT
*pContext
, bool isSplitDraw
= false)
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)
253 // Need to wait for a free entry.
254 while (pContext
->dcRing
.IsFull())
259 uint64_t curDraw
= pContext
->dcRing
.GetHead();
260 uint32_t dcIndex
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
262 if ((pContext
->frameCount
- pContext
->lastFrameChecked
) > 2 ||
263 (curDraw
- pContext
->lastDrawChecked
) > 0x10000)
265 // Take this opportunity to clean-up old arena allocations
266 pContext
->cachingArenaAllocator
.FreeOldBlocks();
268 pContext
->lastFrameChecked
= pContext
->frameCount
;
269 pContext
->lastDrawChecked
= curDraw
;
272 DRAW_CONTEXT
* pCurDrawContext
= &pContext
->dcRing
[dcIndex
];
273 pContext
->pCurDrawContext
= pCurDrawContext
;
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
];
279 // Copy previous state to current state.
280 if (pContext
->pPrevDrawContext
)
282 DRAW_CONTEXT
* pPrevDrawContext
= pContext
->pPrevDrawContext
;
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)
289 CopyState(*pCurDrawContext
->pState
, *pPrevDrawContext
->pState
);
291 // Should have been cleaned up previously
292 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
294 pCurDrawContext
->pState
->pPrivateState
= nullptr;
296 pContext
->curStateId
++; // Progress state ring index forward.
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);
308 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
309 pContext
->curStateId
++; // Progress state ring index forward.
312 SWR_ASSERT(pCurDrawContext
->pArena
->IsEmpty() == true);
314 pCurDrawContext
->dependent
= false;
315 pCurDrawContext
->pContext
= pContext
;
316 pCurDrawContext
->isCompute
= false; // Dispatch has to set this to true.
318 pCurDrawContext
->doneFE
= false;
319 pCurDrawContext
->FeLock
= 0;
320 pCurDrawContext
->threadsDone
= 0;
321 pCurDrawContext
->retireCallback
.pfnCallbackFunc
= nullptr;
323 pCurDrawContext
->dynState
.Reset(pContext
->NumWorkerThreads
);
325 // Assign unique drawId for this DC
326 pCurDrawContext
->drawId
= pContext
->dcRing
.GetHead();
328 pCurDrawContext
->cleanupState
= true;
332 SWR_ASSERT(isSplitDraw
== false, "Split draw should only be used when obtaining a new DC");
335 AR_API_END(APIGetDrawContext
, 0);
336 return pContext
->pCurDrawContext
;
339 API_STATE
* GetDrawState(SWR_CONTEXT
*pContext
)
341 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
342 SWR_ASSERT(pDC
->pState
!= nullptr);
344 return &pDC
->pState
->state
;
347 void SwrDestroyContext(HANDLE hContext
)
349 SWR_CONTEXT
*pContext
= GetContext(hContext
);
350 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
352 pDC
->FeWork
.type
= SHUTDOWN
;
353 pDC
->FeWork
.pfnWork
= ProcessShutdown
;
358 DestroyThreadPool(pContext
, &pContext
->threadPool
);
361 for (uint32_t i
= 0; i
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++i
)
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();
370 AlignedFree(pContext
->pDispatchQueueArray
);
371 AlignedFree(pContext
->pMacroTileManagerArray
);
373 // Free scratch space.
374 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
377 VirtualFree(pContext
->ppScratch
[i
], 0, MEM_RELEASE
);
379 AlignedFree(pContext
->ppScratch
[i
]);
382 ArchRast::DestroyThreadContext(pContext
->pArContext
[i
]);
385 delete[] pContext
->ppScratch
;
386 delete[] pContext
->pArContext
;
387 delete[] pContext
->pStats
;
389 delete(pContext
->pHotTileMgr
);
391 pContext
->~SWR_CONTEXT();
392 AlignedFree(GetContext(hContext
));
395 void SWR_API
SwrSaveState(
397 void* pOutputStateBlock
,
400 SWR_CONTEXT
*pContext
= GetContext(hContext
);
401 auto pSrc
= GetDrawState(pContext
);
402 SWR_ASSERT(pOutputStateBlock
&& memSize
>= sizeof(*pSrc
));
404 memcpy(pOutputStateBlock
, pSrc
, sizeof(*pSrc
));
407 void SWR_API
SwrRestoreState(
409 const void* pStateBlock
,
412 SWR_CONTEXT
*pContext
= GetContext(hContext
);
413 auto pDst
= GetDrawState(pContext
);
414 SWR_ASSERT(pStateBlock
&& memSize
>= sizeof(*pDst
));
416 memcpy(pDst
, pStateBlock
, sizeof(*pDst
));
419 void SetupDefaultState(SWR_CONTEXT
*pContext
)
421 API_STATE
* pState
= GetDrawState(pContext
);
423 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
424 pState
->rastState
.frontWinding
= SWR_FRONTWINDING_CCW
;
427 void SwrSync(HANDLE hContext
, PFN_CALLBACK_FUNC pfnFunc
, uint64_t userData
, uint64_t userData2
, uint64_t userData3
)
429 SWR_ASSERT(pfnFunc
!= nullptr);
431 SWR_CONTEXT
*pContext
= GetContext(hContext
);
432 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
434 AR_API_BEGIN(APISync
, 0);
436 pDC
->FeWork
.type
= SYNC
;
437 pDC
->FeWork
.pfnWork
= ProcessSync
;
439 // Setup callback function
440 pDC
->retireCallback
.pfnCallbackFunc
= pfnFunc
;
441 pDC
->retireCallback
.userData
= userData
;
442 pDC
->retireCallback
.userData2
= userData2
;
443 pDC
->retireCallback
.userData3
= userData3
;
448 AR_API_END(APISync
, 1);
451 void SwrWaitForIdle(HANDLE hContext
)
453 SWR_CONTEXT
*pContext
= GetContext(hContext
);
455 AR_API_BEGIN(APIWaitForIdle
, 0);
457 while (!pContext
->dcRing
.IsEmpty())
462 AR_API_END(APIWaitForIdle
, 1);
465 void SwrWaitForIdleFE(HANDLE hContext
)
467 SWR_CONTEXT
*pContext
= GetContext(hContext
);
469 AR_API_BEGIN(APIWaitForIdle
, 0);
471 while (pContext
->drawsOutstandingFE
> 0)
476 AR_API_END(APIWaitForIdle
, 1);
479 void SwrSetVertexBuffers(
482 const SWR_VERTEX_BUFFER_STATE
* pVertexBuffers
)
484 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
486 for (uint32_t i
= 0; i
< numBuffers
; ++i
)
488 const SWR_VERTEX_BUFFER_STATE
*pVB
= &pVertexBuffers
[i
];
489 pState
->vertexBuffers
[pVB
->index
] = *pVB
;
493 void SwrSetIndexBuffer(
495 const SWR_INDEX_BUFFER_STATE
* pIndexBuffer
)
497 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
499 pState
->indexBuffer
= *pIndexBuffer
;
502 void SwrSetFetchFunc(
504 PFN_FETCH_FUNC pfnFetchFunc
)
506 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
508 pState
->pfnFetchFunc
= pfnFetchFunc
;
513 PFN_SO_FUNC pfnSoFunc
,
514 uint32_t streamIndex
)
516 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
518 SWR_ASSERT(streamIndex
< MAX_SO_STREAMS
);
520 pState
->pfnSoFunc
[streamIndex
] = pfnSoFunc
;
525 SWR_STREAMOUT_STATE
* pSoState
)
527 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
529 pState
->soState
= *pSoState
;
532 void SwrSetSoBuffers(
534 SWR_STREAMOUT_BUFFER
* pSoBuffer
,
537 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
539 SWR_ASSERT((slot
< 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot
);
541 pState
->soBuffer
[slot
] = *pSoBuffer
;
544 void SwrSetVertexFunc(
546 PFN_VERTEX_FUNC pfnVertexFunc
)
548 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
550 pState
->pfnVertexFunc
= pfnVertexFunc
;
553 void SwrSetFrontendState(
555 SWR_FRONTEND_STATE
*pFEState
)
557 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
558 pState
->frontendState
= *pFEState
;
563 SWR_GS_STATE
*pGSState
)
565 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
566 pState
->gsState
= *pGSState
;
571 PFN_GS_FUNC pfnGsFunc
)
573 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
574 pState
->pfnGsFunc
= pfnGsFunc
;
579 PFN_CS_FUNC pfnCsFunc
,
580 uint32_t totalThreadsInGroup
,
581 uint32_t totalSpillFillSize
)
583 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
584 pState
->pfnCsFunc
= pfnCsFunc
;
585 pState
->totalThreadsInGroup
= totalThreadsInGroup
;
586 pState
->totalSpillFillSize
= totalSpillFillSize
;
591 SWR_TS_STATE
*pState
)
593 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
594 pApiState
->tsState
= *pState
;
601 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
602 pApiState
->pfnHsFunc
= pfnFunc
;
609 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
610 pApiState
->pfnDsFunc
= pfnFunc
;
613 void SwrSetDepthStencilState(
615 SWR_DEPTH_STENCIL_STATE
*pDSState
)
617 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
619 pState
->depthStencilState
= *pDSState
;
622 void SwrSetBackendState(
624 SWR_BACKEND_STATE
*pBEState
)
626 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
628 pState
->backendState
= *pBEState
;
631 void SwrSetPixelShaderState(
633 SWR_PS_STATE
*pPSState
)
635 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
636 pState
->psState
= *pPSState
;
639 void SwrSetBlendState(
641 SWR_BLEND_STATE
*pBlendState
)
643 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
644 memcpy(&pState
->blendState
, pBlendState
, sizeof(SWR_BLEND_STATE
));
647 void SwrSetBlendFunc(
649 uint32_t renderTarget
,
650 PFN_BLEND_JIT_FUNC pfnBlendFunc
)
652 SWR_ASSERT(renderTarget
< SWR_NUM_RENDERTARGETS
);
653 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
654 pState
->pfnBlendFunc
[renderTarget
] = pfnBlendFunc
;
657 // update guardband multipliers for the viewport
658 void updateGuardbands(API_STATE
*pState
)
660 uint32_t numGbs
= pState
->gsState
.emitsRenderTargetArrayIndex
? KNOB_NUM_VIEWPORTS_SCISSORS
: 1;
662 for(uint32_t i
= 0; i
< numGbs
; ++i
)
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
;
672 void SwrSetRastState(
674 const SWR_RASTSTATE
*pRastState
)
676 SWR_CONTEXT
*pContext
= GetContext(hContext
);
677 API_STATE
* pState
= GetDrawState(pContext
);
679 memcpy(&pState
->rastState
, pRastState
, sizeof(SWR_RASTSTATE
));
682 void SwrSetViewports(
684 uint32_t numViewports
,
685 const SWR_VIEWPORT
* pViewports
,
686 const SWR_VIEWPORT_MATRICES
* pMatrices
)
688 SWR_ASSERT(numViewports
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
689 "Invalid number of viewports.");
691 SWR_CONTEXT
*pContext
= GetContext(hContext
);
692 API_STATE
* pState
= GetDrawState(pContext
);
694 memcpy(&pState
->vp
[0], pViewports
, sizeof(SWR_VIEWPORT
) * numViewports
);
696 if (pMatrices
!= nullptr)
698 // @todo Faster to copy portions of the SOA or just copy all of it?
699 memcpy(&pState
->vpMatrices
, pMatrices
, sizeof(SWR_VIEWPORT_MATRICES
));
703 // Compute default viewport transform.
704 for (uint32_t i
= 0; i
< numViewports
; ++i
)
706 if (pContext
->driverType
== DX
)
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
;
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
];
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
);
733 updateGuardbands(pState
);
736 void SwrSetScissorRects(
738 uint32_t numScissors
,
739 const SWR_RECT
* pScissors
)
741 SWR_ASSERT(numScissors
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
742 "Invalid number of scissor rects.");
744 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
745 memcpy(&pState
->scissorRects
[0], pScissors
, numScissors
* sizeof(pScissors
[0]));
748 void SetupMacroTileScissors(DRAW_CONTEXT
*pDC
)
750 API_STATE
*pState
= &pDC
->pState
->state
;
751 uint32_t numScissors
= pState
->gsState
.emitsViewportArrayIndex
? KNOB_NUM_VIEWPORTS_SCISSORS
: 1;
752 pState
->scissorsTileAligned
= true;
754 for (uint32_t index
= 0; index
< numScissors
; ++index
)
756 SWR_RECT
&scissorInFixedPoint
= pState
->scissorsInFixedPoint
[index
];
758 // Set up scissor dimensions based on scissor or viewport
759 if (pState
->rastState
.scissorEnable
)
761 scissorInFixedPoint
= pState
->scissorRects
[index
];
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
);
774 scissorInFixedPoint
&= g_MaxScissorRect
;
776 // Test for tile alignment
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;
783 pState
->scissorsTileAligned
&= tileAligned
;
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
;
791 // Make scissor inclusive
792 scissorInFixedPoint
.xmax
-= 1;
793 scissorInFixedPoint
.ymax
-= 1;
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
)
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;
811 if (psState
.pfnPixelShader
== nullptr)
813 backendFuncs
.pfnBackend
= gBackendNullPs
[pState
->state
.rastState
.sampleCount
];
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;
821 SWR_BARYCENTRICS_MASK barycentricsMask
= (SWR_BARYCENTRICS_MASK
)psState
.barycentricsMask
;
823 // select backend function
824 switch(psState
.shadingRate
)
826 case SWR_SHADING_RATE_PIXEL
:
827 if(bMultisampleEnable
)
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
];
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
];
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
];
847 SWR_ASSERT(0 && "Invalid shading rate");
852 PFN_PROCESS_PRIMS pfnBinner
;
853 switch (pState
->state
.topology
)
856 pState
->pfnProcessPrims
= ClipPoints
;
857 pfnBinner
= BinPoints
;
862 case TOP_LINE_LIST_ADJ
:
863 case TOP_LISTSTRIP_ADJ
:
864 pState
->pfnProcessPrims
= ClipLines
;
865 pfnBinner
= BinLines
;
868 pState
->pfnProcessPrims
= ClipTriangles
;
869 pfnBinner
= GetBinTrianglesFunc((rastState
.conservativeRast
> 0));
873 // disable clipper if viewport transform is disabled
874 if (pState
->state
.frontendState
.vpTransformDisable
)
876 pState
->pfnProcessPrims
= pfnBinner
;
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))
886 pState
->pfnProcessPrims
= nullptr;
889 if (pState
->state
.soState
.rasterizerDisable
== true)
891 pState
->pfnProcessPrims
= nullptr;
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
)
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
)
902 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)backendState
.swizzleMap
[i
].sourceAttrib
+ 1);
907 pState
->state
.feNumAttributes
= pState
->state
.backendState
.numAttributes
;
910 if (pState
->state
.soState
.soEnable
)
912 uint32_t streamMasks
= 0;
913 for (uint32_t i
= 0; i
< 4; ++i
)
915 streamMasks
|= pState
->state
.soState
.streamMasks
[i
];
919 if (_BitScanReverse(&maxAttrib
, streamMasks
))
921 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)(maxAttrib
+ 1));
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;
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;
943 uint32_t numRTs
= pState
->state
.psState
.numRenderTargets
;
944 pState
->state
.colorHottileEnable
= 0;
945 if (psState
.pfnPixelShader
!= nullptr)
947 for (uint32_t rt
= 0; rt
< numRTs
; ++rt
)
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;
957 // Setup depth quantization function
958 if (pState
->state
.depthHottileEnable
)
960 switch (pState
->state
.rastState
.depthFormat
)
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
> ;
972 // set up pass-through quantize if depth isn't enabled
973 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
977 //////////////////////////////////////////////////////////////////////////
979 /// @param pDC - Draw context to initialize for this draw.
984 // We don't need to re-setup the scissors/pipeline state again for split draw.
985 if (isSplitDraw
== false)
987 SetupMacroTileScissors(pDC
);
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(
999 PRIMITIVE_TOPOLOGY topology
)
1001 API_STATE
& state
= pDC
->pState
->state
;
1003 uint32_t vertsPerDraw
= totalVerts
;
1005 if (state
.soState
.soEnable
)
1012 case TOP_POINT_LIST
:
1013 case TOP_TRIANGLE_LIST
:
1014 vertsPerDraw
= KNOB_MAX_PRIMS_PER_DRAW
;
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
)
1051 uint32_t vertsPerPrim
= topology
- TOP_PATCHLIST_BASE
;
1052 vertsPerDraw
= vertsPerPrim
* KNOB_MAX_TESS_PRIMS_PER_DRAW
;
1056 // The Primitive Assembly code can only handle 1 RECT at a time.
1062 // We are not splitting up draws for other topologies.
1066 return vertsPerDraw
;
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)
1080 PRIMITIVE_TOPOLOGY topology
,
1081 uint32_t numVertices
,
1082 uint32_t startVertex
,
1083 uint32_t numInstances
= 1,
1084 uint32_t startInstance
= 0)
1091 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1092 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1094 AR_API_BEGIN(APIDraw
, pDC
->drawId
);
1096 uint32_t maxVertsPerDraw
= MaxVertsPerDraw(pDC
, numVertices
, topology
);
1097 uint32_t primsPerDraw
= GetNumPrims(topology
, maxVertsPerDraw
);
1098 uint32_t remainingVerts
= numVertices
;
1100 API_STATE
*pState
= &pDC
->pState
->state
;
1101 pState
->topology
= topology
;
1102 pState
->forceFront
= false;
1104 // disable culling for points/lines
1105 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1106 if (topology
== TOP_POINT_LIST
)
1108 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1109 pState
->forceFront
= true;
1113 while (remainingVerts
)
1115 uint32_t numVertsForDraw
= (remainingVerts
< maxVertsPerDraw
) ?
1116 remainingVerts
: maxVertsPerDraw
;
1118 bool isSplitDraw
= (draw
> 0) ? true : false;
1119 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
, isSplitDraw
);
1120 InitDraw(pDC
, isSplitDraw
);
1122 pDC
->FeWork
.type
= DRAW
;
1123 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
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
;
1137 pDC
->cleanupState
= (remainingVerts
== numVertsForDraw
);
1140 QueueDraw(pContext
);
1142 remainingVerts
-= numVertsForDraw
;
1146 // restore culling state
1147 pDC
= GetDrawContext(pContext
);
1148 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1150 AR_API_END(APIDraw
, numVertices
* numInstances
);
1153 //////////////////////////////////////////////////////////////////////////
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.
1161 PRIMITIVE_TOPOLOGY topology
,
1162 uint32_t startVertex
,
1163 uint32_t numVertices
)
1165 DrawInstanced(hContext
, topology
, numVertices
, startVertex
);
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(
1178 PRIMITIVE_TOPOLOGY topology
,
1179 uint32_t numVertsPerInstance
,
1180 uint32_t numInstances
,
1181 uint32_t startVertex
,
1182 uint32_t startInstance
1185 DrawInstanced(hContext
, topology
, numVertsPerInstance
, startVertex
, numInstances
, startInstance
);
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(
1199 PRIMITIVE_TOPOLOGY topology
,
1200 uint32_t numIndices
,
1201 uint32_t indexOffset
,
1203 uint32_t numInstances
= 1,
1204 uint32_t startInstance
= 0)
1211 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1212 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1213 API_STATE
* pState
= &pDC
->pState
->state
;
1215 AR_API_BEGIN(APIDrawIndexed
, pDC
->drawId
);
1216 AR_API_EVENT(DrawIndexedInstance(topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
));
1218 uint32_t maxIndicesPerDraw
= MaxVertsPerDraw(pDC
, numIndices
, topology
);
1219 uint32_t primsPerDraw
= GetNumPrims(topology
, maxIndicesPerDraw
);
1220 uint32_t remainingIndices
= numIndices
;
1222 uint32_t indexSize
= 0;
1223 switch (pState
->indexBuffer
.format
)
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;
1233 uint8_t *pIB
= (uint8_t*)pState
->indexBuffer
.pIndices
;
1234 pIB
+= (uint64_t)indexOffset
* (uint64_t)indexSize
;
1236 pState
->topology
= topology
;
1237 pState
->forceFront
= false;
1239 // disable culling for points/lines
1240 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1241 if (topology
== TOP_POINT_LIST
)
1243 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1244 pState
->forceFront
= true;
1247 while (remainingIndices
)
1249 uint32_t numIndicesForDraw
= (remainingIndices
< maxIndicesPerDraw
) ?
1250 remainingIndices
: maxIndicesPerDraw
;
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
);
1257 pDC
->FeWork
.type
= DRAW
;
1258 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
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
;
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
;
1275 pDC
->cleanupState
= (remainingIndices
== numIndicesForDraw
);
1278 QueueDraw(pContext
);
1280 pIB
+= maxIndicesPerDraw
* indexSize
;
1281 remainingIndices
-= numIndicesForDraw
;
1285 // restore culling state
1286 pDC
= GetDrawContext(pContext
);
1287 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1289 AR_API_END(APIDrawIndexed
, numIndices
* numInstances
);
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(
1302 PRIMITIVE_TOPOLOGY topology
,
1303 uint32_t numIndices
,
1304 uint32_t indexOffset
,
1308 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
);
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(
1322 PRIMITIVE_TOPOLOGY topology
,
1323 uint32_t numIndices
,
1324 uint32_t numInstances
,
1325 uint32_t indexOffset
,
1327 uint32_t startInstance
)
1329 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
);
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(
1340 uint32_t attachmentMask
,
1341 const SWR_RECT
& invalidateRect
)
1348 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1349 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
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;
1361 QueueDraw(pContext
);
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
1370 void SWR_API
SwrDiscardRect(
1372 uint32_t attachmentMask
,
1373 const SWR_RECT
& rect
)
1380 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1381 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
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;
1394 QueueDraw(pContext
);
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
1405 uint32_t threadGroupCountX
,
1406 uint32_t threadGroupCountY
,
1407 uint32_t threadGroupCountZ
)
1414 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1415 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1417 AR_API_BEGIN(APIDispatch
, pDC
->drawId
);
1419 pDC
->isCompute
= true; // This is a compute context.
1421 COMPUTE_DESC
* pTaskData
= (COMPUTE_DESC
*)pDC
->pArena
->AllocAligned(sizeof(COMPUTE_DESC
), 64);
1423 pTaskData
->threadGroupCountX
= threadGroupCountX
;
1424 pTaskData
->threadGroupCountY
= threadGroupCountY
;
1425 pTaskData
->threadGroupCountZ
= threadGroupCountZ
;
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
);
1432 QueueDispatch(pContext
);
1433 AR_API_END(APIDispatch
, threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
);
1436 // Deswizzles, converts and stores current contents of the hot tiles to surface
1437 // described by pState
1438 void SWR_API
SwrStoreTiles(
1440 SWR_RENDERTARGET_ATTACHMENT attachment
,
1441 SWR_TILE_STATE postStoreTileState
,
1442 const SWR_RECT
& storeRect
)
1449 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1450 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1452 AR_API_BEGIN(APIStoreTiles
, pDC
->drawId
);
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
;
1462 QueueDraw(pContext
);
1464 AR_API_END(APIStoreTiles
, 1);
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(
1478 const float clearColor
[4],
1481 const SWR_RECT
& clearRect
)
1488 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1489 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1491 AR_API_BEGIN(APIClearRenderTarget
, pDC
->drawId
);
1495 flags
.mask
= clearMask
;
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
;
1510 QueueDraw(pContext
);
1512 AR_API_END(APIClearRenderTarget
, 1);
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
1519 /// SWR is responsible for the allocation of the private context state.
1520 /// @param hContext - Handle passed back from SwrCreateContext
1521 VOID
* SwrGetPrivateContextState(
1524 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1525 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1526 DRAW_STATE
* pState
= pDC
->pState
;
1528 if (pState
->pPrivateState
== nullptr)
1530 pState
->pPrivateState
= pState
->pArena
->AllocAligned(pContext
->privateStateSize
, KNOB_SIMD_WIDTH
*sizeof(float));
1533 return pState
->pPrivateState
;
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(
1549 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1550 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1552 return pDC
->pState
->pArena
->AllocAligned(size
, align
);
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(
1563 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1564 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1566 pDC
->pState
->state
.enableStats
= enable
;
1569 //////////////////////////////////////////////////////////////////////////
1570 /// @brief Mark end of frame - used for performance profiling
1571 /// @param hContext - Handle passed back from SwrCreateContext
1572 void SWR_API
SwrEndFrame(
1576 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1577 pContext
->frameCount
++;