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
;
426 pState
->depthBoundsState
.depthBoundsTestEnable
= false;
427 pState
->depthBoundsState
.depthBoundsTestMinValue
= 0.0f
;
428 pState
->depthBoundsState
.depthBoundsTestMaxValue
= 1.0f
;
431 void SwrSync(HANDLE hContext
, PFN_CALLBACK_FUNC pfnFunc
, uint64_t userData
, uint64_t userData2
, uint64_t userData3
)
433 SWR_ASSERT(pfnFunc
!= nullptr);
435 SWR_CONTEXT
*pContext
= GetContext(hContext
);
436 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
438 AR_API_BEGIN(APISync
, 0);
440 pDC
->FeWork
.type
= SYNC
;
441 pDC
->FeWork
.pfnWork
= ProcessSync
;
443 // Setup callback function
444 pDC
->retireCallback
.pfnCallbackFunc
= pfnFunc
;
445 pDC
->retireCallback
.userData
= userData
;
446 pDC
->retireCallback
.userData2
= userData2
;
447 pDC
->retireCallback
.userData3
= userData3
;
452 AR_API_END(APISync
, 1);
455 void SwrWaitForIdle(HANDLE hContext
)
457 SWR_CONTEXT
*pContext
= GetContext(hContext
);
459 AR_API_BEGIN(APIWaitForIdle
, 0);
461 while (!pContext
->dcRing
.IsEmpty())
466 AR_API_END(APIWaitForIdle
, 1);
469 void SwrWaitForIdleFE(HANDLE hContext
)
471 SWR_CONTEXT
*pContext
= GetContext(hContext
);
473 AR_API_BEGIN(APIWaitForIdle
, 0);
475 while (pContext
->drawsOutstandingFE
> 0)
480 AR_API_END(APIWaitForIdle
, 1);
483 void SwrSetVertexBuffers(
486 const SWR_VERTEX_BUFFER_STATE
* pVertexBuffers
)
488 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
490 for (uint32_t i
= 0; i
< numBuffers
; ++i
)
492 const SWR_VERTEX_BUFFER_STATE
*pVB
= &pVertexBuffers
[i
];
493 pState
->vertexBuffers
[pVB
->index
] = *pVB
;
497 void SwrSetIndexBuffer(
499 const SWR_INDEX_BUFFER_STATE
* pIndexBuffer
)
501 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
503 pState
->indexBuffer
= *pIndexBuffer
;
506 void SwrSetFetchFunc(
508 PFN_FETCH_FUNC pfnFetchFunc
)
510 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
512 pState
->pfnFetchFunc
= pfnFetchFunc
;
517 PFN_SO_FUNC pfnSoFunc
,
518 uint32_t streamIndex
)
520 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
522 SWR_ASSERT(streamIndex
< MAX_SO_STREAMS
);
524 pState
->pfnSoFunc
[streamIndex
] = pfnSoFunc
;
529 SWR_STREAMOUT_STATE
* pSoState
)
531 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
533 pState
->soState
= *pSoState
;
536 void SwrSetSoBuffers(
538 SWR_STREAMOUT_BUFFER
* pSoBuffer
,
541 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
543 SWR_ASSERT((slot
< 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot
);
545 pState
->soBuffer
[slot
] = *pSoBuffer
;
548 void SwrSetVertexFunc(
550 PFN_VERTEX_FUNC pfnVertexFunc
)
552 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
554 pState
->pfnVertexFunc
= pfnVertexFunc
;
557 void SwrSetFrontendState(
559 SWR_FRONTEND_STATE
*pFEState
)
561 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
562 pState
->frontendState
= *pFEState
;
567 SWR_GS_STATE
*pGSState
)
569 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
570 pState
->gsState
= *pGSState
;
575 PFN_GS_FUNC pfnGsFunc
)
577 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
578 pState
->pfnGsFunc
= pfnGsFunc
;
583 PFN_CS_FUNC pfnCsFunc
,
584 uint32_t totalThreadsInGroup
,
585 uint32_t totalSpillFillSize
)
587 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
588 pState
->pfnCsFunc
= pfnCsFunc
;
589 pState
->totalThreadsInGroup
= totalThreadsInGroup
;
590 pState
->totalSpillFillSize
= totalSpillFillSize
;
595 SWR_TS_STATE
*pState
)
597 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
598 pApiState
->tsState
= *pState
;
605 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
606 pApiState
->pfnHsFunc
= pfnFunc
;
613 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
614 pApiState
->pfnDsFunc
= pfnFunc
;
617 void SwrSetDepthStencilState(
619 SWR_DEPTH_STENCIL_STATE
*pDSState
)
621 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
623 pState
->depthStencilState
= *pDSState
;
626 void SwrSetBackendState(
628 SWR_BACKEND_STATE
*pBEState
)
630 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
632 pState
->backendState
= *pBEState
;
635 void SwrSetDepthBoundsState(
637 SWR_DEPTH_BOUNDS_STATE
*pDBState
)
639 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
641 pState
->depthBoundsState
= *pDBState
;
644 void SwrSetPixelShaderState(
646 SWR_PS_STATE
*pPSState
)
648 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
649 pState
->psState
= *pPSState
;
652 void SwrSetBlendState(
654 SWR_BLEND_STATE
*pBlendState
)
656 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
657 memcpy(&pState
->blendState
, pBlendState
, sizeof(SWR_BLEND_STATE
));
660 void SwrSetBlendFunc(
662 uint32_t renderTarget
,
663 PFN_BLEND_JIT_FUNC pfnBlendFunc
)
665 SWR_ASSERT(renderTarget
< SWR_NUM_RENDERTARGETS
);
666 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
667 pState
->pfnBlendFunc
[renderTarget
] = pfnBlendFunc
;
670 // update guardband multipliers for the viewport
671 void updateGuardbands(API_STATE
*pState
)
673 uint32_t numGbs
= pState
->gsState
.emitsRenderTargetArrayIndex
? KNOB_NUM_VIEWPORTS_SCISSORS
: 1;
675 for(uint32_t i
= 0; i
< numGbs
; ++i
)
677 // guardband center is viewport center
678 pState
->gbState
.left
[i
] = KNOB_GUARDBAND_WIDTH
/ pState
->vp
[i
].width
;
679 pState
->gbState
.right
[i
] = KNOB_GUARDBAND_WIDTH
/ pState
->vp
[i
].width
;
680 pState
->gbState
.top
[i
] = KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[i
].height
;
681 pState
->gbState
.bottom
[i
] = KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[i
].height
;
685 void SwrSetRastState(
687 const SWR_RASTSTATE
*pRastState
)
689 SWR_CONTEXT
*pContext
= GetContext(hContext
);
690 API_STATE
* pState
= GetDrawState(pContext
);
692 memcpy(&pState
->rastState
, pRastState
, sizeof(SWR_RASTSTATE
));
695 void SwrSetViewports(
697 uint32_t numViewports
,
698 const SWR_VIEWPORT
* pViewports
,
699 const SWR_VIEWPORT_MATRICES
* pMatrices
)
701 SWR_ASSERT(numViewports
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
702 "Invalid number of viewports.");
704 SWR_CONTEXT
*pContext
= GetContext(hContext
);
705 API_STATE
* pState
= GetDrawState(pContext
);
707 memcpy(&pState
->vp
[0], pViewports
, sizeof(SWR_VIEWPORT
) * numViewports
);
709 if (pMatrices
!= nullptr)
711 // @todo Faster to copy portions of the SOA or just copy all of it?
712 memcpy(&pState
->vpMatrices
, pMatrices
, sizeof(SWR_VIEWPORT_MATRICES
));
716 // Compute default viewport transform.
717 for (uint32_t i
= 0; i
< numViewports
; ++i
)
719 if (pContext
->driverType
== DX
)
721 pState
->vpMatrices
.m00
[i
] = pState
->vp
[i
].width
/ 2.0f
;
722 pState
->vpMatrices
.m11
[i
] = -pState
->vp
[i
].height
/ 2.0f
;
723 pState
->vpMatrices
.m22
[i
] = pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
;
724 pState
->vpMatrices
.m30
[i
] = pState
->vp
[i
].x
+ pState
->vpMatrices
.m00
[i
];
725 pState
->vpMatrices
.m31
[i
] = pState
->vp
[i
].y
- pState
->vpMatrices
.m11
[i
];
726 pState
->vpMatrices
.m32
[i
] = pState
->vp
[i
].minZ
;
730 // Standard, with the exception that Y is inverted.
731 pState
->vpMatrices
.m00
[i
] = (pState
->vp
[i
].width
- pState
->vp
[i
].x
) / 2.0f
;
732 pState
->vpMatrices
.m11
[i
] = (pState
->vp
[i
].y
- pState
->vp
[i
].height
) / 2.0f
;
733 pState
->vpMatrices
.m22
[i
] = (pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
) / 2.0f
;
734 pState
->vpMatrices
.m30
[i
] = pState
->vp
[i
].x
+ pState
->vpMatrices
.m00
[i
];
735 pState
->vpMatrices
.m31
[i
] = pState
->vp
[i
].height
+ pState
->vpMatrices
.m11
[i
];
736 pState
->vpMatrices
.m32
[i
] = pState
->vp
[i
].minZ
+ pState
->vpMatrices
.m22
[i
];
738 // Now that the matrix is calculated, clip the view coords to screen size.
739 // OpenGL allows for -ve x,y in the viewport.
740 pState
->vp
[i
].x
= std::max(pState
->vp
[i
].x
, 0.0f
);
741 pState
->vp
[i
].y
= std::max(pState
->vp
[i
].y
, 0.0f
);
746 updateGuardbands(pState
);
749 void SwrSetScissorRects(
751 uint32_t numScissors
,
752 const SWR_RECT
* pScissors
)
754 SWR_ASSERT(numScissors
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
755 "Invalid number of scissor rects.");
757 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
758 memcpy(&pState
->scissorRects
[0], pScissors
, numScissors
* sizeof(pScissors
[0]));
761 void SetupMacroTileScissors(DRAW_CONTEXT
*pDC
)
763 API_STATE
*pState
= &pDC
->pState
->state
;
764 uint32_t numScissors
= pState
->gsState
.emitsViewportArrayIndex
? KNOB_NUM_VIEWPORTS_SCISSORS
: 1;
765 pState
->scissorsTileAligned
= true;
767 for (uint32_t index
= 0; index
< numScissors
; ++index
)
769 SWR_RECT
&scissorInFixedPoint
= pState
->scissorsInFixedPoint
[index
];
771 // Set up scissor dimensions based on scissor or viewport
772 if (pState
->rastState
.scissorEnable
)
774 scissorInFixedPoint
= pState
->scissorRects
[index
];
778 // the vp width and height must be added to origin un-rounded then the result round to -inf.
779 // The cast to int works for rounding assuming all [left, right, top, bottom] are positive.
780 scissorInFixedPoint
.xmin
= (int32_t)pState
->vp
[index
].x
;
781 scissorInFixedPoint
.xmax
= (int32_t)(pState
->vp
[index
].x
+ pState
->vp
[index
].width
);
782 scissorInFixedPoint
.ymin
= (int32_t)pState
->vp
[index
].y
;
783 scissorInFixedPoint
.ymax
= (int32_t)(pState
->vp
[index
].y
+ pState
->vp
[index
].height
);
787 scissorInFixedPoint
&= g_MaxScissorRect
;
789 // Test for tile alignment
791 tileAligned
= (scissorInFixedPoint
.xmin
% KNOB_TILE_X_DIM
) == 0;
792 tileAligned
&= (scissorInFixedPoint
.ymin
% KNOB_TILE_Y_DIM
) == 0;
793 tileAligned
&= (scissorInFixedPoint
.xmax
% KNOB_TILE_X_DIM
) == 0;
794 tileAligned
&= (scissorInFixedPoint
.xmax
% KNOB_TILE_Y_DIM
) == 0;
796 pState
->scissorsTileAligned
&= tileAligned
;
798 // Scale to fixed point
799 scissorInFixedPoint
.xmin
*= FIXED_POINT_SCALE
;
800 scissorInFixedPoint
.xmax
*= FIXED_POINT_SCALE
;
801 scissorInFixedPoint
.ymin
*= FIXED_POINT_SCALE
;
802 scissorInFixedPoint
.ymax
*= FIXED_POINT_SCALE
;
804 // Make scissor inclusive
805 scissorInFixedPoint
.xmax
-= 1;
806 scissorInFixedPoint
.ymax
-= 1;
810 // templated backend function tables
811 extern PFN_BACKEND_FUNC gBackendNullPs
[SWR_MULTISAMPLE_TYPE_COUNT
];
812 extern PFN_BACKEND_FUNC gBackendSingleSample
[SWR_INPUT_COVERAGE_COUNT
][2][2];
813 extern PFN_BACKEND_FUNC gBackendPixelRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_MSAA_SAMPLE_PATTERN_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2][2];
814 extern PFN_BACKEND_FUNC gBackendSampleRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2];
815 void SetupPipeline(DRAW_CONTEXT
*pDC
)
817 DRAW_STATE
* pState
= pDC
->pState
;
818 const SWR_RASTSTATE
&rastState
= pState
->state
.rastState
;
819 const SWR_PS_STATE
&psState
= pState
->state
.psState
;
820 BACKEND_FUNCS
& backendFuncs
= pState
->backendFuncs
;
821 const uint32_t forcedSampleCount
= (rastState
.forcedSampleCount
) ? 1 : 0;
824 if (psState
.pfnPixelShader
== nullptr)
826 backendFuncs
.pfnBackend
= gBackendNullPs
[pState
->state
.rastState
.sampleCount
];
830 const bool bMultisampleEnable
= ((rastState
.sampleCount
> SWR_MULTISAMPLE_1X
) || rastState
.forcedSampleCount
) ? 1 : 0;
831 const uint32_t centroid
= ((psState
.barycentricsMask
& SWR_BARYCENTRIC_CENTROID_MASK
) > 0) ? 1 : 0;
832 const uint32_t canEarlyZ
= (psState
.forceEarlyZ
|| (!psState
.writesODepth
&& !psState
.usesSourceDepth
&& !psState
.usesUAV
)) ? 1 : 0;
834 SWR_BARYCENTRICS_MASK barycentricsMask
= (SWR_BARYCENTRICS_MASK
)psState
.barycentricsMask
;
836 // select backend function
837 switch(psState
.shadingRate
)
839 case SWR_SHADING_RATE_PIXEL
:
840 if(bMultisampleEnable
)
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
= gBackendPixelRateTable
[rastState
.sampleCount
][rastState
.samplePattern
][psState
.inputCoverage
][centroid
][forcedSampleCount
][canEarlyZ
];
848 // always need to generate I & J per pixel for Z interpolation
849 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_PIXEL_MASK
);
850 backendFuncs
.pfnBackend
= gBackendSingleSample
[psState
.inputCoverage
][centroid
][canEarlyZ
];
853 case SWR_SHADING_RATE_SAMPLE
:
854 SWR_ASSERT(rastState
.samplePattern
== SWR_MSAA_STANDARD_PATTERN
);
855 // always need to generate I & J per sample for Z interpolation
856 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
857 backendFuncs
.pfnBackend
= gBackendSampleRateTable
[rastState
.sampleCount
][psState
.inputCoverage
][centroid
][canEarlyZ
];
860 SWR_ASSERT(0 && "Invalid shading rate");
865 PFN_PROCESS_PRIMS pfnBinner
;
866 switch (pState
->state
.topology
)
869 pState
->pfnProcessPrims
= ClipPoints
;
870 pfnBinner
= BinPoints
;
875 case TOP_LINE_LIST_ADJ
:
876 case TOP_LISTSTRIP_ADJ
:
877 pState
->pfnProcessPrims
= ClipLines
;
878 pfnBinner
= BinLines
;
881 pState
->pfnProcessPrims
= ClipTriangles
;
882 pfnBinner
= GetBinTrianglesFunc((rastState
.conservativeRast
> 0));
886 // disable clipper if viewport transform is disabled
887 if (pState
->state
.frontendState
.vpTransformDisable
)
889 pState
->pfnProcessPrims
= pfnBinner
;
892 if ((pState
->state
.psState
.pfnPixelShader
== nullptr) &&
893 (pState
->state
.depthStencilState
.depthTestEnable
== FALSE
) &&
894 (pState
->state
.depthStencilState
.depthWriteEnable
== FALSE
) &&
895 (pState
->state
.depthStencilState
.stencilTestEnable
== FALSE
) &&
896 (pState
->state
.depthStencilState
.stencilWriteEnable
== FALSE
) &&
897 (pState
->state
.backendState
.numAttributes
== 0))
899 pState
->pfnProcessPrims
= nullptr;
902 if (pState
->state
.soState
.rasterizerDisable
== true)
904 pState
->pfnProcessPrims
= nullptr;
907 // set up the frontend attribute count
908 pState
->state
.feNumAttributes
= 0;
909 const SWR_BACKEND_STATE
& backendState
= pState
->state
.backendState
;
910 if (backendState
.swizzleEnable
)
912 // attribute swizzling is enabled, iterate over the map and record the max attribute used
913 for (uint32_t i
= 0; i
< backendState
.numAttributes
; ++i
)
915 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)backendState
.swizzleMap
[i
].sourceAttrib
+ 1);
920 pState
->state
.feNumAttributes
= pState
->state
.backendState
.numAttributes
;
923 if (pState
->state
.soState
.soEnable
)
925 uint32_t streamMasks
= 0;
926 for (uint32_t i
= 0; i
< 4; ++i
)
928 streamMasks
|= pState
->state
.soState
.streamMasks
[i
];
932 if (_BitScanReverse(&maxAttrib
, streamMasks
))
934 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)(maxAttrib
+ 1));
938 // complicated logic to test for cases where we don't need backing hottile memory for a draw
939 // have to check for the special case where depth/stencil test is enabled but depthwrite is disabled.
940 pState
->state
.depthHottileEnable
= ((!(pState
->state
.depthStencilState
.depthTestEnable
&&
941 !pState
->state
.depthStencilState
.depthWriteEnable
&&
942 pState
->state
.depthStencilState
.depthTestFunc
== ZFUNC_ALWAYS
)) &&
943 (pState
->state
.depthStencilState
.depthTestEnable
||
944 pState
->state
.depthStencilState
.depthWriteEnable
)) ? true : false;
946 pState
->state
.stencilHottileEnable
= (((!(pState
->state
.depthStencilState
.stencilTestEnable
&&
947 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
948 pState
->state
.depthStencilState
.stencilTestFunc
== ZFUNC_ALWAYS
)) ||
949 // for stencil we have to check the double sided state as well
950 (!(pState
->state
.depthStencilState
.doubleSidedStencilTestEnable
&&
951 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
952 pState
->state
.depthStencilState
.backfaceStencilTestFunc
== ZFUNC_ALWAYS
))) &&
953 (pState
->state
.depthStencilState
.stencilTestEnable
||
954 pState
->state
.depthStencilState
.stencilWriteEnable
)) ? true : false;
956 uint32_t numRTs
= pState
->state
.psState
.numRenderTargets
;
957 pState
->state
.colorHottileEnable
= 0;
958 if (psState
.pfnPixelShader
!= nullptr)
960 for (uint32_t rt
= 0; rt
< numRTs
; ++rt
)
962 pState
->state
.colorHottileEnable
|=
963 (!pState
->state
.blendState
.renderTarget
[rt
].writeDisableAlpha
||
964 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableRed
||
965 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableGreen
||
966 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableBlue
) ? (1 << rt
) : 0;
970 // Setup depth quantization function
971 if (pState
->state
.depthHottileEnable
)
973 switch (pState
->state
.rastState
.depthFormat
)
975 case R32_FLOAT_X8X24_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT_X8X24_TYPELESS
> ; break;
976 case R32_FLOAT
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ; break;
977 case R24_UNORM_X8_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R24_UNORM_X8_TYPELESS
> ; break;
978 case R16_UNORM
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R16_UNORM
> ; break;
979 default: SWR_ASSERT(false, "Unsupported depth format for depth quantiztion.");
980 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
985 // set up pass-through quantize if depth isn't enabled
986 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
990 //////////////////////////////////////////////////////////////////////////
992 /// @param pDC - Draw context to initialize for this draw.
997 // We don't need to re-setup the scissors/pipeline state again for split draw.
998 if (isSplitDraw
== false)
1000 SetupMacroTileScissors(pDC
);
1005 //////////////////////////////////////////////////////////////////////////
1006 /// @brief We can split the draw for certain topologies for better performance.
1007 /// @param totalVerts - Total vertices for draw
1008 /// @param topology - Topology used for draw
1009 uint32_t MaxVertsPerDraw(
1011 uint32_t totalVerts
,
1012 PRIMITIVE_TOPOLOGY topology
)
1014 API_STATE
& state
= pDC
->pState
->state
;
1016 uint32_t vertsPerDraw
= totalVerts
;
1018 if (state
.soState
.soEnable
)
1025 case TOP_POINT_LIST
:
1026 case TOP_TRIANGLE_LIST
:
1027 vertsPerDraw
= KNOB_MAX_PRIMS_PER_DRAW
;
1030 case TOP_PATCHLIST_1
:
1031 case TOP_PATCHLIST_2
:
1032 case TOP_PATCHLIST_3
:
1033 case TOP_PATCHLIST_4
:
1034 case TOP_PATCHLIST_5
:
1035 case TOP_PATCHLIST_6
:
1036 case TOP_PATCHLIST_7
:
1037 case TOP_PATCHLIST_8
:
1038 case TOP_PATCHLIST_9
:
1039 case TOP_PATCHLIST_10
:
1040 case TOP_PATCHLIST_11
:
1041 case TOP_PATCHLIST_12
:
1042 case TOP_PATCHLIST_13
:
1043 case TOP_PATCHLIST_14
:
1044 case TOP_PATCHLIST_15
:
1045 case TOP_PATCHLIST_16
:
1046 case TOP_PATCHLIST_17
:
1047 case TOP_PATCHLIST_18
:
1048 case TOP_PATCHLIST_19
:
1049 case TOP_PATCHLIST_20
:
1050 case TOP_PATCHLIST_21
:
1051 case TOP_PATCHLIST_22
:
1052 case TOP_PATCHLIST_23
:
1053 case TOP_PATCHLIST_24
:
1054 case TOP_PATCHLIST_25
:
1055 case TOP_PATCHLIST_26
:
1056 case TOP_PATCHLIST_27
:
1057 case TOP_PATCHLIST_28
:
1058 case TOP_PATCHLIST_29
:
1059 case TOP_PATCHLIST_30
:
1060 case TOP_PATCHLIST_31
:
1061 case TOP_PATCHLIST_32
:
1062 if (pDC
->pState
->state
.tsState
.tsEnable
)
1064 uint32_t vertsPerPrim
= topology
- TOP_PATCHLIST_BASE
;
1065 vertsPerDraw
= vertsPerPrim
* KNOB_MAX_TESS_PRIMS_PER_DRAW
;
1069 // The Primitive Assembly code can only handle 1 RECT at a time.
1075 // We are not splitting up draws for other topologies.
1079 return vertsPerDraw
;
1083 //////////////////////////////////////////////////////////////////////////
1084 /// @brief DrawInstanced
1085 /// @param hContext - Handle passed back from SwrCreateContext
1086 /// @param topology - Specifies topology for draw.
1087 /// @param numVerts - How many vertices to read sequentially from vertex data (per instance).
1088 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1089 /// @param numInstances - How many instances to render.
1090 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1093 PRIMITIVE_TOPOLOGY topology
,
1094 uint32_t numVertices
,
1095 uint32_t startVertex
,
1096 uint32_t numInstances
= 1,
1097 uint32_t startInstance
= 0)
1104 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1105 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1107 AR_API_BEGIN(APIDraw
, pDC
->drawId
);
1108 AR_API_EVENT(DrawInstancedEvent(pDC
->drawId
, topology
, numVertices
, startVertex
, numInstances
, startInstance
));
1110 uint32_t maxVertsPerDraw
= MaxVertsPerDraw(pDC
, numVertices
, topology
);
1111 uint32_t primsPerDraw
= GetNumPrims(topology
, maxVertsPerDraw
);
1112 uint32_t remainingVerts
= numVertices
;
1114 API_STATE
*pState
= &pDC
->pState
->state
;
1115 pState
->topology
= topology
;
1116 pState
->forceFront
= false;
1118 // disable culling for points/lines
1119 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1120 if (topology
== TOP_POINT_LIST
)
1122 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1123 pState
->forceFront
= true;
1125 else if (topology
== TOP_RECT_LIST
)
1127 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1131 while (remainingVerts
)
1133 uint32_t numVertsForDraw
= (remainingVerts
< maxVertsPerDraw
) ?
1134 remainingVerts
: maxVertsPerDraw
;
1136 bool isSplitDraw
= (draw
> 0) ? true : false;
1137 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
, isSplitDraw
);
1138 InitDraw(pDC
, isSplitDraw
);
1140 pDC
->FeWork
.type
= DRAW
;
1141 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1143 false, // bEnableCutIndex
1144 pState
->tsState
.tsEnable
,
1145 pState
->gsState
.gsEnable
,
1146 pState
->soState
.soEnable
,
1147 pDC
->pState
->pfnProcessPrims
!= nullptr);
1148 pDC
->FeWork
.desc
.draw
.numVerts
= numVertsForDraw
;
1149 pDC
->FeWork
.desc
.draw
.startVertex
= startVertex
;
1150 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1151 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1152 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1153 pDC
->FeWork
.desc
.draw
.startVertexID
= draw
* maxVertsPerDraw
;
1155 pDC
->cleanupState
= (remainingVerts
== numVertsForDraw
);
1158 QueueDraw(pContext
);
1160 remainingVerts
-= numVertsForDraw
;
1164 // restore culling state
1165 pDC
= GetDrawContext(pContext
);
1166 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1168 AR_API_END(APIDraw
, numVertices
* numInstances
);
1171 //////////////////////////////////////////////////////////////////////////
1173 /// @param hContext - Handle passed back from SwrCreateContext
1174 /// @param topology - Specifies topology for draw.
1175 /// @param startVertex - Specifies start vertex in vertex buffer for draw.
1176 /// @param primCount - Number of vertices.
1179 PRIMITIVE_TOPOLOGY topology
,
1180 uint32_t startVertex
,
1181 uint32_t numVertices
)
1183 DrawInstanced(hContext
, topology
, numVertices
, startVertex
);
1186 //////////////////////////////////////////////////////////////////////////
1187 /// @brief SwrDrawInstanced
1188 /// @param hContext - Handle passed back from SwrCreateContext
1189 /// @param topology - Specifies topology for draw.
1190 /// @param numVertsPerInstance - How many vertices to read sequentially from vertex data.
1191 /// @param numInstances - How many instances to render.
1192 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1193 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1194 void SwrDrawInstanced(
1196 PRIMITIVE_TOPOLOGY topology
,
1197 uint32_t numVertsPerInstance
,
1198 uint32_t numInstances
,
1199 uint32_t startVertex
,
1200 uint32_t startInstance
1203 DrawInstanced(hContext
, topology
, numVertsPerInstance
, startVertex
, numInstances
, startInstance
);
1206 //////////////////////////////////////////////////////////////////////////
1207 /// @brief DrawIndexedInstanced
1208 /// @param hContext - Handle passed back from SwrCreateContext
1209 /// @param topology - Specifies topology for draw.
1210 /// @param numIndices - Number of indices to read sequentially from index buffer.
1211 /// @param indexOffset - Starting index into index buffer.
1212 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1213 /// @param numInstances - Number of instances to render.
1214 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1215 void DrawIndexedInstance(
1217 PRIMITIVE_TOPOLOGY topology
,
1218 uint32_t numIndices
,
1219 uint32_t indexOffset
,
1221 uint32_t numInstances
= 1,
1222 uint32_t startInstance
= 0)
1229 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1230 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1231 API_STATE
* pState
= &pDC
->pState
->state
;
1233 AR_API_BEGIN(APIDrawIndexed
, pDC
->drawId
);
1234 AR_API_EVENT(DrawIndexedInstancedEvent(pDC
->drawId
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
));
1236 uint32_t maxIndicesPerDraw
= MaxVertsPerDraw(pDC
, numIndices
, topology
);
1237 uint32_t primsPerDraw
= GetNumPrims(topology
, maxIndicesPerDraw
);
1238 uint32_t remainingIndices
= numIndices
;
1240 uint32_t indexSize
= 0;
1241 switch (pState
->indexBuffer
.format
)
1243 case R32_UINT
: indexSize
= sizeof(uint32_t); break;
1244 case R16_UINT
: indexSize
= sizeof(uint16_t); break;
1245 case R8_UINT
: indexSize
= sizeof(uint8_t); break;
1251 uint8_t *pIB
= (uint8_t*)pState
->indexBuffer
.pIndices
;
1252 pIB
+= (uint64_t)indexOffset
* (uint64_t)indexSize
;
1254 pState
->topology
= topology
;
1255 pState
->forceFront
= false;
1257 // disable culling for points/lines
1258 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1259 if (topology
== TOP_POINT_LIST
)
1261 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1262 pState
->forceFront
= true;
1264 else if (topology
== TOP_RECT_LIST
)
1266 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1269 while (remainingIndices
)
1271 uint32_t numIndicesForDraw
= (remainingIndices
< maxIndicesPerDraw
) ?
1272 remainingIndices
: maxIndicesPerDraw
;
1274 // When breaking up draw, we need to obtain new draw context for each iteration.
1275 bool isSplitDraw
= (draw
> 0) ? true : false;
1276 pDC
= GetDrawContext(pContext
, isSplitDraw
);
1277 InitDraw(pDC
, isSplitDraw
);
1279 pDC
->FeWork
.type
= DRAW
;
1280 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1282 pState
->frontendState
.bEnableCutIndex
,
1283 pState
->tsState
.tsEnable
,
1284 pState
->gsState
.gsEnable
,
1285 pState
->soState
.soEnable
,
1286 pDC
->pState
->pfnProcessPrims
!= nullptr);
1287 pDC
->FeWork
.desc
.draw
.pDC
= pDC
;
1288 pDC
->FeWork
.desc
.draw
.numIndices
= numIndicesForDraw
;
1289 pDC
->FeWork
.desc
.draw
.pIB
= (int*)pIB
;
1290 pDC
->FeWork
.desc
.draw
.type
= pDC
->pState
->state
.indexBuffer
.format
;
1292 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1293 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1294 pDC
->FeWork
.desc
.draw
.baseVertex
= baseVertex
;
1295 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1297 pDC
->cleanupState
= (remainingIndices
== numIndicesForDraw
);
1300 QueueDraw(pContext
);
1302 pIB
+= maxIndicesPerDraw
* indexSize
;
1303 remainingIndices
-= numIndicesForDraw
;
1307 // restore culling state
1308 pDC
= GetDrawContext(pContext
);
1309 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1311 AR_API_END(APIDrawIndexed
, numIndices
* numInstances
);
1315 //////////////////////////////////////////////////////////////////////////
1316 /// @brief DrawIndexed
1317 /// @param hContext - Handle passed back from SwrCreateContext
1318 /// @param topology - Specifies topology for draw.
1319 /// @param numIndices - Number of indices to read sequentially from index buffer.
1320 /// @param indexOffset - Starting index into index buffer.
1321 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1322 void SwrDrawIndexed(
1324 PRIMITIVE_TOPOLOGY topology
,
1325 uint32_t numIndices
,
1326 uint32_t indexOffset
,
1330 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
);
1333 //////////////////////////////////////////////////////////////////////////
1334 /// @brief SwrDrawIndexedInstanced
1335 /// @param hContext - Handle passed back from SwrCreateContext
1336 /// @param topology - Specifies topology for draw.
1337 /// @param numIndices - Number of indices to read sequentially from index buffer.
1338 /// @param numInstances - Number of instances to render.
1339 /// @param indexOffset - Starting index into index buffer.
1340 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1341 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1342 void SwrDrawIndexedInstanced(
1344 PRIMITIVE_TOPOLOGY topology
,
1345 uint32_t numIndices
,
1346 uint32_t numInstances
,
1347 uint32_t indexOffset
,
1349 uint32_t startInstance
)
1351 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
);
1354 //////////////////////////////////////////////////////////////////////////
1355 /// @brief SwrInvalidateTiles
1356 /// @param hContext - Handle passed back from SwrCreateContext
1357 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to invalidate.
1358 /// @param invalidateRect - The pixel-coordinate rectangle to invalidate. This will be expanded to
1359 /// be hottile size-aligned.
1360 void SWR_API
SwrInvalidateTiles(
1362 uint32_t attachmentMask
,
1363 const SWR_RECT
& invalidateRect
)
1370 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1371 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1373 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1374 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1375 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1376 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= invalidateRect
;
1377 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
&= g_MaxScissorRect
;
1378 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_INVALID
;
1379 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= false;
1380 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= false;
1383 QueueDraw(pContext
);
1386 //////////////////////////////////////////////////////////////////////////
1387 /// @brief SwrDiscardRect
1388 /// @param hContext - Handle passed back from SwrCreateContext
1389 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to discard.
1390 /// @param rect - The pixel-coordinate rectangle to discard. Only fully-covered hottiles will be
1392 void SWR_API
SwrDiscardRect(
1394 uint32_t attachmentMask
,
1395 const SWR_RECT
& rect
)
1402 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1403 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1405 // Queue a load to the hottile
1406 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1407 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1408 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1409 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= rect
;
1410 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
&= g_MaxScissorRect
;
1411 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_RESOLVED
;
1412 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= true;
1413 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= true;
1416 QueueDraw(pContext
);
1419 //////////////////////////////////////////////////////////////////////////
1420 /// @brief SwrDispatch
1421 /// @param hContext - Handle passed back from SwrCreateContext
1422 /// @param threadGroupCountX - Number of thread groups dispatched in X direction
1423 /// @param threadGroupCountY - Number of thread groups dispatched in Y direction
1424 /// @param threadGroupCountZ - Number of thread groups dispatched in Z direction
1427 uint32_t threadGroupCountX
,
1428 uint32_t threadGroupCountY
,
1429 uint32_t threadGroupCountZ
)
1436 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1437 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1439 AR_API_BEGIN(APIDispatch
, pDC
->drawId
);
1440 AR_API_EVENT(DispatchEvent(pDC
->drawId
, threadGroupCountX
, threadGroupCountY
, threadGroupCountZ
));
1441 pDC
->isCompute
= true; // This is a compute context.
1443 COMPUTE_DESC
* pTaskData
= (COMPUTE_DESC
*)pDC
->pArena
->AllocAligned(sizeof(COMPUTE_DESC
), 64);
1445 pTaskData
->threadGroupCountX
= threadGroupCountX
;
1446 pTaskData
->threadGroupCountY
= threadGroupCountY
;
1447 pTaskData
->threadGroupCountZ
= threadGroupCountZ
;
1449 uint32_t totalThreadGroups
= threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
;
1450 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
1451 pDC
->pDispatch
= &pContext
->pDispatchQueueArray
[dcIndex
];
1452 pDC
->pDispatch
->initialize(totalThreadGroups
, pTaskData
, &ProcessComputeBE
);
1454 QueueDispatch(pContext
);
1455 AR_API_END(APIDispatch
, threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
);
1458 // Deswizzles, converts and stores current contents of the hot tiles to surface
1459 // described by pState
1460 void SWR_API
SwrStoreTiles(
1462 uint32_t attachmentMask
,
1463 SWR_TILE_STATE postStoreTileState
,
1464 const SWR_RECT
& storeRect
)
1471 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1472 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1474 AR_API_BEGIN(APIStoreTiles
, pDC
->drawId
);
1476 pDC
->FeWork
.type
= STORETILES
;
1477 pDC
->FeWork
.pfnWork
= ProcessStoreTiles
;
1478 pDC
->FeWork
.desc
.storeTiles
.attachmentMask
= attachmentMask
;
1479 pDC
->FeWork
.desc
.storeTiles
.postStoreTileState
= postStoreTileState
;
1480 pDC
->FeWork
.desc
.storeTiles
.rect
= storeRect
;
1481 pDC
->FeWork
.desc
.storeTiles
.rect
&= g_MaxScissorRect
;
1484 QueueDraw(pContext
);
1486 AR_API_END(APIStoreTiles
, 1);
1489 //////////////////////////////////////////////////////////////////////////
1490 /// @brief SwrClearRenderTarget - Clear attached render targets / depth / stencil
1491 /// @param hContext - Handle passed back from SwrCreateContext
1492 /// @param clearMask - combination of SWR_CLEAR_COLOR / SWR_CLEAR_DEPTH / SWR_CLEAR_STENCIL flags (or SWR_CLEAR_NONE)
1493 /// @param clearColor - color use for clearing render targets
1494 /// @param z - depth value use for clearing depth buffer
1495 /// @param stencil - stencil value used for clearing stencil buffer
1496 /// @param clearRect - The pixel-coordinate rectangle to clear in all cleared buffers
1497 void SWR_API
SwrClearRenderTarget(
1500 const float clearColor
[4],
1503 const SWR_RECT
& clearRect
)
1510 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1511 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1513 AR_API_BEGIN(APIClearRenderTarget
, pDC
->drawId
);
1517 flags
.mask
= clearMask
;
1519 pDC
->FeWork
.type
= CLEAR
;
1520 pDC
->FeWork
.pfnWork
= ProcessClear
;
1521 pDC
->FeWork
.desc
.clear
.rect
= clearRect
;
1522 pDC
->FeWork
.desc
.clear
.rect
&= g_MaxScissorRect
;
1523 pDC
->FeWork
.desc
.clear
.flags
= flags
;
1524 pDC
->FeWork
.desc
.clear
.clearDepth
= z
;
1525 pDC
->FeWork
.desc
.clear
.clearRTColor
[0] = clearColor
[0];
1526 pDC
->FeWork
.desc
.clear
.clearRTColor
[1] = clearColor
[1];
1527 pDC
->FeWork
.desc
.clear
.clearRTColor
[2] = clearColor
[2];
1528 pDC
->FeWork
.desc
.clear
.clearRTColor
[3] = clearColor
[3];
1529 pDC
->FeWork
.desc
.clear
.clearStencil
= stencil
;
1532 QueueDraw(pContext
);
1534 AR_API_END(APIClearRenderTarget
, 1);
1537 //////////////////////////////////////////////////////////////////////////
1538 /// @brief Returns a pointer to the private context state for the current
1539 /// draw operation. This is used for external componets such as the
1541 /// SWR is responsible for the allocation of the private context state.
1542 /// @param hContext - Handle passed back from SwrCreateContext
1543 VOID
* SwrGetPrivateContextState(
1546 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1547 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1548 DRAW_STATE
* pState
= pDC
->pState
;
1550 if (pState
->pPrivateState
== nullptr)
1552 pState
->pPrivateState
= pState
->pArena
->AllocAligned(pContext
->privateStateSize
, KNOB_SIMD_WIDTH
*sizeof(float));
1555 return pState
->pPrivateState
;
1558 //////////////////////////////////////////////////////////////////////////
1559 /// @brief Clients can use this to allocate memory for draw/dispatch
1560 /// operations. The memory will automatically be freed once operation
1561 /// has completed. Client can use this to allocate binding tables,
1562 /// etc. needed for shader execution.
1563 /// @param hContext - Handle passed back from SwrCreateContext
1564 /// @param size - Size of allocation
1565 /// @param align - Alignment needed for allocation.
1566 VOID
* SwrAllocDrawContextMemory(
1571 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1572 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1574 return pDC
->pState
->pArena
->AllocAligned(size
, align
);
1577 //////////////////////////////////////////////////////////////////////////
1578 /// @brief Enables stats counting
1579 /// @param hContext - Handle passed back from SwrCreateContext
1580 /// @param enable - If true then counts are incremented.
1581 void SwrEnableStats(
1585 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1586 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1588 pDC
->pState
->state
.enableStats
= enable
;
1591 //////////////////////////////////////////////////////////////////////////
1592 /// @brief Mark end of frame - used for performance profiling
1593 /// @param hContext - Handle passed back from SwrCreateContext
1594 void SWR_API
SwrEndFrame(
1597 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1598 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1601 AR_API_EVENT(FrameEndEvent(pContext
->frameCount
, pDC
->drawId
));
1603 pContext
->frameCount
++;