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 void SetupDefaultState(SWR_CONTEXT
*pContext
);
51 static INLINE SWR_CONTEXT
* GetContext(HANDLE hContext
)
53 return (SWR_CONTEXT
*)hContext
;
56 //////////////////////////////////////////////////////////////////////////
57 /// @brief Create SWR Context.
58 /// @param pCreateInfo - pointer to creation info.
59 HANDLE
SwrCreateContext(
60 SWR_CREATECONTEXT_INFO
* pCreateInfo
)
65 void* pContextMem
= AlignedMalloc(sizeof(SWR_CONTEXT
), KNOB_SIMD_WIDTH
* 4);
66 memset(pContextMem
, 0, sizeof(SWR_CONTEXT
));
67 SWR_CONTEXT
*pContext
= new (pContextMem
) SWR_CONTEXT();
69 pContext
->driverType
= pCreateInfo
->driver
;
70 pContext
->privateStateSize
= pCreateInfo
->privateStateSize
;
72 pContext
->dcRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
73 pContext
->dsRing
.Init(KNOB_MAX_DRAWS_IN_FLIGHT
);
75 pContext
->pMacroTileManagerArray
= (MacroTileMgr
*)AlignedMalloc(sizeof(MacroTileMgr
) * KNOB_MAX_DRAWS_IN_FLIGHT
, 64);
76 pContext
->pDispatchQueueArray
= (DispatchQueue
*)AlignedMalloc(sizeof(DispatchQueue
) * KNOB_MAX_DRAWS_IN_FLIGHT
, 64);
78 pContext
->threadInfo
.MAX_WORKER_THREADS
= KNOB_MAX_WORKER_THREADS
;
79 pContext
->threadInfo
.MAX_NUMA_NODES
= KNOB_MAX_NUMA_NODES
;
80 pContext
->threadInfo
.MAX_CORES_PER_NUMA_NODE
= KNOB_MAX_CORES_PER_NUMA_NODE
;
81 pContext
->threadInfo
.MAX_THREADS_PER_CORE
= KNOB_MAX_THREADS_PER_CORE
;
82 pContext
->threadInfo
.SINGLE_THREADED
= KNOB_SINGLE_THREADED
;
84 if (pCreateInfo
->pThreadInfo
)
86 pContext
->threadInfo
= *pCreateInfo
->pThreadInfo
;
89 for (uint32_t dc
= 0; dc
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++dc
)
91 pContext
->dcRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
92 new (&pContext
->pMacroTileManagerArray
[dc
]) MacroTileMgr(*pContext
->dcRing
[dc
].pArena
);
93 new (&pContext
->pDispatchQueueArray
[dc
]) DispatchQueue();
95 pContext
->dsRing
[dc
].pArena
= new CachingArena(pContext
->cachingArenaAllocator
);
98 if (!pContext
->threadInfo
.SINGLE_THREADED
)
100 memset(&pContext
->WaitLock
, 0, sizeof(pContext
->WaitLock
));
101 memset(&pContext
->FifosNotEmpty
, 0, sizeof(pContext
->FifosNotEmpty
));
102 new (&pContext
->WaitLock
) std::mutex();
103 new (&pContext
->FifosNotEmpty
) std::condition_variable();
105 CreateThreadPool(pContext
, &pContext
->threadPool
);
108 // Calling createThreadPool() above can set SINGLE_THREADED
109 if (pContext
->threadInfo
.SINGLE_THREADED
)
111 pContext
->NumWorkerThreads
= 1;
112 pContext
->NumFEThreads
= 1;
113 pContext
->NumBEThreads
= 1;
116 // Allocate scratch space for workers.
117 ///@note We could lazily allocate this but its rather small amount of memory.
118 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
121 uint32_t numaNode
= pContext
->threadPool
.pThreadData
?
122 pContext
->threadPool
.pThreadData
[i
].numaId
: 0;
123 pContext
->pScratch
[i
] = (uint8_t*)VirtualAllocExNuma(
124 GetCurrentProcess(), nullptr, 32 * sizeof(KILOBYTE
),
125 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
,
128 pContext
->pScratch
[i
] = (uint8_t*)AlignedMalloc(32 * sizeof(KILOBYTE
), KNOB_SIMD_WIDTH
* 4);
132 // State setup AFTER context is fully initialized
133 SetupDefaultState(pContext
);
135 // initialize hot tile manager
136 pContext
->pHotTileMgr
= new HotTileMgr();
138 // initialize function pointer tables
139 InitClearTilesTable();
141 // initialize callback functions
142 pContext
->pfnLoadTile
= pCreateInfo
->pfnLoadTile
;
143 pContext
->pfnStoreTile
= pCreateInfo
->pfnStoreTile
;
144 pContext
->pfnClearTile
= pCreateInfo
->pfnClearTile
;
145 pContext
->pfnUpdateSoWriteOffset
= pCreateInfo
->pfnUpdateSoWriteOffset
;
147 // pass pointer to bucket manager back to caller
148 #ifdef KNOB_ENABLE_RDTSC
149 pCreateInfo
->pBucketMgr
= &gBucketMgr
;
152 pCreateInfo
->contextSaveSize
= sizeof(API_STATE
);
154 return (HANDLE
)pContext
;
157 void SwrDestroyContext(HANDLE hContext
)
159 SWR_CONTEXT
*pContext
= GetContext(hContext
);
160 DestroyThreadPool(pContext
, &pContext
->threadPool
);
163 for (uint32_t i
= 0; i
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++i
)
165 delete pContext
->dcRing
[i
].pArena
;
166 delete pContext
->dsRing
[i
].pArena
;
167 pContext
->pMacroTileManagerArray
[i
].~MacroTileMgr();
168 pContext
->pDispatchQueueArray
[i
].~DispatchQueue();
171 AlignedFree(pContext
->pDispatchQueueArray
);
172 AlignedFree(pContext
->pMacroTileManagerArray
);
174 // Free scratch space.
175 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
178 VirtualFree(pContext
->pScratch
[i
], 0, MEM_RELEASE
);
180 AlignedFree(pContext
->pScratch
[i
]);
184 delete(pContext
->pHotTileMgr
);
186 pContext
->~SWR_CONTEXT();
187 AlignedFree(GetContext(hContext
));
190 void CopyState(DRAW_STATE
& dst
, const DRAW_STATE
& src
)
192 memcpy(&dst
.state
, &src
.state
, sizeof(API_STATE
));
195 void WakeAllThreads(SWR_CONTEXT
*pContext
)
197 pContext
->FifosNotEmpty
.notify_all();
200 static TileSet gSingleThreadLockedTiles
;
202 template<bool IsDraw
>
203 void QueueWork(SWR_CONTEXT
*pContext
)
205 DRAW_CONTEXT
* pDC
= pContext
->pCurDrawContext
;
206 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
210 pDC
->pTileMgr
= &pContext
->pMacroTileManagerArray
[dcIndex
];
211 pDC
->pTileMgr
->initialize();
214 // Each worker thread looks at a DC for both FE and BE work at different times and so we
215 // multiply threadDone by 2. When the threadDone counter has reached 0 then all workers
216 // have moved past this DC. (i.e. Each worker has checked this DC for both FE and BE work and
217 // then moved on if all work is done.)
218 pContext
->pCurDrawContext
->threadsDone
= pContext
->NumFEThreads
+ pContext
->NumBEThreads
;
222 InterlockedIncrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
227 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
);
228 pContext
->dcRing
.Enqueue();
231 if (pContext
->threadInfo
.SINGLE_THREADED
)
233 // flush denormals to 0
234 uint32_t mxcsr
= _mm_getcsr();
235 _mm_setcsr(mxcsr
| _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
239 uint32_t curDraw
[2] = { pContext
->pCurDrawContext
->drawId
, pContext
->pCurDrawContext
->drawId
};
240 WorkOnFifoFE(pContext
, 0, curDraw
[0]);
241 WorkOnFifoBE(pContext
, 0, curDraw
[1], gSingleThreadLockedTiles
, 0, 0);
245 uint32_t curDispatch
= pContext
->pCurDrawContext
->drawId
;
246 WorkOnCompute(pContext
, 0, curDispatch
);
249 // Dequeue the work here, if not already done, since we're single threaded (i.e. no workers).
250 while (CompleteDrawContext(pContext
, pContext
->pCurDrawContext
) > 0) {}
257 RDTSC_START(APIDrawWakeAllThreads
);
258 WakeAllThreads(pContext
);
259 RDTSC_STOP(APIDrawWakeAllThreads
, 1, 0);
262 // Set current draw context to NULL so that next state call forces a new draw context to be created and populated.
263 pContext
->pPrevDrawContext
= pContext
->pCurDrawContext
;
264 pContext
->pCurDrawContext
= nullptr;
267 INLINE
void QueueDraw(SWR_CONTEXT
* pContext
)
269 QueueWork
<true>(pContext
);
272 INLINE
void QueueDispatch(SWR_CONTEXT
* pContext
)
274 QueueWork
<false>(pContext
);
277 DRAW_CONTEXT
* GetDrawContext(SWR_CONTEXT
*pContext
, bool isSplitDraw
= false)
279 RDTSC_START(APIGetDrawContext
);
280 // If current draw context is null then need to obtain a new draw context to use from ring.
281 if (pContext
->pCurDrawContext
== nullptr)
283 // Need to wait for a free entry.
284 while (pContext
->dcRing
.IsFull())
289 uint64_t curDraw
= pContext
->dcRing
.GetHead();
290 uint32_t dcIndex
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
292 static uint64_t lastDrawChecked
;
293 static uint32_t lastFrameChecked
;
294 if ((pContext
->frameCount
- lastFrameChecked
) > 2 ||
295 (curDraw
- lastDrawChecked
) > 0x10000)
297 // Take this opportunity to clean-up old arena allocations
298 pContext
->cachingArenaAllocator
.FreeOldBlocks();
300 lastFrameChecked
= pContext
->frameCount
;
301 lastDrawChecked
= curDraw
;
304 DRAW_CONTEXT
* pCurDrawContext
= &pContext
->dcRing
[dcIndex
];
305 pContext
->pCurDrawContext
= pCurDrawContext
;
307 // Assign next available entry in DS ring to this DC.
308 uint32_t dsIndex
= pContext
->curStateId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
309 pCurDrawContext
->pState
= &pContext
->dsRing
[dsIndex
];
311 // Copy previous state to current state.
312 if (pContext
->pPrevDrawContext
)
314 DRAW_CONTEXT
* pPrevDrawContext
= pContext
->pPrevDrawContext
;
316 // If we're splitting our draw then we can just use the same state from the previous
317 // draw. In this case, we won't increment the DS ring index so the next non-split
318 // draw can receive the state.
319 if (isSplitDraw
== false)
321 CopyState(*pCurDrawContext
->pState
, *pPrevDrawContext
->pState
);
323 // Should have been cleaned up previously
324 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
326 pCurDrawContext
->pState
->pPrivateState
= nullptr;
328 pContext
->curStateId
++; // Progress state ring index forward.
332 // If its a split draw then just copy the state pointer over
333 // since its the same draw.
334 pCurDrawContext
->pState
= pPrevDrawContext
->pState
;
335 SWR_ASSERT(pPrevDrawContext
->cleanupState
== false);
340 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
341 pContext
->curStateId
++; // Progress state ring index forward.
344 SWR_ASSERT(pCurDrawContext
->pArena
->IsEmpty() == true);
346 pCurDrawContext
->dependent
= false;
347 pCurDrawContext
->pContext
= pContext
;
348 pCurDrawContext
->isCompute
= false; // Dispatch has to set this to true.
350 pCurDrawContext
->doneFE
= false;
351 pCurDrawContext
->FeLock
= 0;
352 pCurDrawContext
->threadsDone
= 0;
353 pCurDrawContext
->retireCallback
.pfnCallbackFunc
= nullptr;
355 memset(&pCurDrawContext
->dynState
, 0, sizeof(pCurDrawContext
->dynState
));
357 // Assign unique drawId for this DC
358 pCurDrawContext
->drawId
= pContext
->dcRing
.GetHead();
360 pCurDrawContext
->cleanupState
= true;
364 SWR_ASSERT(isSplitDraw
== false, "Split draw should only be used when obtaining a new DC");
367 RDTSC_STOP(APIGetDrawContext
, 0, 0);
368 return pContext
->pCurDrawContext
;
371 API_STATE
* GetDrawState(SWR_CONTEXT
*pContext
)
373 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
374 SWR_ASSERT(pDC
->pState
!= nullptr);
376 return &pDC
->pState
->state
;
379 void SWR_API
SwrSaveState(
381 void* pOutputStateBlock
,
384 SWR_CONTEXT
*pContext
= GetContext(hContext
);
385 auto pSrc
= GetDrawState(pContext
);
386 SWR_ASSERT(pOutputStateBlock
&& memSize
>= sizeof(*pSrc
));
388 memcpy(pOutputStateBlock
, pSrc
, sizeof(*pSrc
));
391 void SWR_API
SwrRestoreState(
393 const void* pStateBlock
,
396 SWR_CONTEXT
*pContext
= GetContext(hContext
);
397 auto pDst
= GetDrawState(pContext
);
398 SWR_ASSERT(pStateBlock
&& memSize
>= sizeof(*pDst
));
400 memcpy(pDst
, pStateBlock
, sizeof(*pDst
));
403 void SetupDefaultState(SWR_CONTEXT
*pContext
)
405 API_STATE
* pState
= GetDrawState(pContext
);
407 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
408 pState
->rastState
.frontWinding
= SWR_FRONTWINDING_CCW
;
411 void SwrSync(HANDLE hContext
, PFN_CALLBACK_FUNC pfnFunc
, uint64_t userData
, uint64_t userData2
, uint64_t userData3
)
413 RDTSC_START(APISync
);
415 SWR_ASSERT(pfnFunc
!= nullptr);
417 SWR_CONTEXT
*pContext
= GetContext(hContext
);
418 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
420 pDC
->FeWork
.type
= SYNC
;
421 pDC
->FeWork
.pfnWork
= ProcessSync
;
423 // Setup callback function
424 pDC
->retireCallback
.pfnCallbackFunc
= pfnFunc
;
425 pDC
->retireCallback
.userData
= userData
;
426 pDC
->retireCallback
.userData2
= userData2
;
427 pDC
->retireCallback
.userData3
= userData3
;
432 RDTSC_STOP(APISync
, 1, 0);
435 void SwrWaitForIdle(HANDLE hContext
)
437 SWR_CONTEXT
*pContext
= GetContext(hContext
);
439 RDTSC_START(APIWaitForIdle
);
441 while (!pContext
->dcRing
.IsEmpty())
446 RDTSC_STOP(APIWaitForIdle
, 1, 0);
449 void SwrWaitForIdleFE(HANDLE hContext
)
451 SWR_CONTEXT
*pContext
= GetContext(hContext
);
453 RDTSC_START(APIWaitForIdle
);
455 while (pContext
->drawsOutstandingFE
> 0)
460 RDTSC_STOP(APIWaitForIdle
, 1, 0);
463 void SwrSetVertexBuffers(
466 const SWR_VERTEX_BUFFER_STATE
* pVertexBuffers
)
468 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
470 for (uint32_t i
= 0; i
< numBuffers
; ++i
)
472 const SWR_VERTEX_BUFFER_STATE
*pVB
= &pVertexBuffers
[i
];
473 pState
->vertexBuffers
[pVB
->index
] = *pVB
;
477 void SwrSetIndexBuffer(
479 const SWR_INDEX_BUFFER_STATE
* pIndexBuffer
)
481 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
483 pState
->indexBuffer
= *pIndexBuffer
;
486 void SwrSetFetchFunc(
488 PFN_FETCH_FUNC pfnFetchFunc
)
490 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
492 pState
->pfnFetchFunc
= pfnFetchFunc
;
497 PFN_SO_FUNC pfnSoFunc
,
498 uint32_t streamIndex
)
500 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
502 SWR_ASSERT(streamIndex
< MAX_SO_STREAMS
);
504 pState
->pfnSoFunc
[streamIndex
] = pfnSoFunc
;
509 SWR_STREAMOUT_STATE
* pSoState
)
511 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
513 pState
->soState
= *pSoState
;
516 void SwrSetSoBuffers(
518 SWR_STREAMOUT_BUFFER
* pSoBuffer
,
521 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
523 SWR_ASSERT((slot
< 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot
);
525 pState
->soBuffer
[slot
] = *pSoBuffer
;
528 void SwrSetVertexFunc(
530 PFN_VERTEX_FUNC pfnVertexFunc
)
532 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
534 pState
->pfnVertexFunc
= pfnVertexFunc
;
537 void SwrSetFrontendState(
539 SWR_FRONTEND_STATE
*pFEState
)
541 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
542 pState
->frontendState
= *pFEState
;
547 SWR_GS_STATE
*pGSState
)
549 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
550 pState
->gsState
= *pGSState
;
555 PFN_GS_FUNC pfnGsFunc
)
557 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
558 pState
->pfnGsFunc
= pfnGsFunc
;
563 PFN_CS_FUNC pfnCsFunc
,
564 uint32_t totalThreadsInGroup
,
565 uint32_t totalSpillFillSize
)
567 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
568 pState
->pfnCsFunc
= pfnCsFunc
;
569 pState
->totalThreadsInGroup
= totalThreadsInGroup
;
570 pState
->totalSpillFillSize
= totalSpillFillSize
;
575 SWR_TS_STATE
*pState
)
577 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
578 pApiState
->tsState
= *pState
;
585 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
586 pApiState
->pfnHsFunc
= pfnFunc
;
593 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
594 pApiState
->pfnDsFunc
= pfnFunc
;
597 void SwrSetDepthStencilState(
599 SWR_DEPTH_STENCIL_STATE
*pDSState
)
601 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
603 pState
->depthStencilState
= *pDSState
;
606 void SwrSetBackendState(
608 SWR_BACKEND_STATE
*pBEState
)
610 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
612 pState
->backendState
= *pBEState
;
615 void SwrSetPixelShaderState(
617 SWR_PS_STATE
*pPSState
)
619 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
620 pState
->psState
= *pPSState
;
623 void SwrSetBlendState(
625 SWR_BLEND_STATE
*pBlendState
)
627 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
628 memcpy(&pState
->blendState
, pBlendState
, sizeof(SWR_BLEND_STATE
));
631 void SwrSetBlendFunc(
633 uint32_t renderTarget
,
634 PFN_BLEND_JIT_FUNC pfnBlendFunc
)
636 SWR_ASSERT(renderTarget
< SWR_NUM_RENDERTARGETS
);
637 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
638 pState
->pfnBlendFunc
[renderTarget
] = pfnBlendFunc
;
641 // update guardband multipliers for the viewport
642 void updateGuardband(API_STATE
*pState
)
644 // guardband center is viewport center
645 pState
->gbState
.left
= KNOB_GUARDBAND_WIDTH
/ pState
->vp
[0].width
;
646 pState
->gbState
.right
= KNOB_GUARDBAND_WIDTH
/ pState
->vp
[0].width
;
647 pState
->gbState
.top
= KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[0].height
;
648 pState
->gbState
.bottom
= KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[0].height
;
651 void SwrSetRastState(
653 const SWR_RASTSTATE
*pRastState
)
655 SWR_CONTEXT
*pContext
= GetContext(hContext
);
656 API_STATE
* pState
= GetDrawState(pContext
);
658 memcpy(&pState
->rastState
, pRastState
, sizeof(SWR_RASTSTATE
));
661 void SwrSetViewports(
663 uint32_t numViewports
,
664 const SWR_VIEWPORT
* pViewports
,
665 const SWR_VIEWPORT_MATRIX
* pMatrices
)
667 SWR_ASSERT(numViewports
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
668 "Invalid number of viewports.");
670 SWR_CONTEXT
*pContext
= GetContext(hContext
);
671 API_STATE
* pState
= GetDrawState(pContext
);
673 memcpy(&pState
->vp
[0], pViewports
, sizeof(SWR_VIEWPORT
) * numViewports
);
675 if (pMatrices
!= nullptr)
677 memcpy(&pState
->vpMatrix
[0], pMatrices
, sizeof(SWR_VIEWPORT_MATRIX
) * numViewports
);
681 // Compute default viewport transform.
682 for (uint32_t i
= 0; i
< numViewports
; ++i
)
684 if (pContext
->driverType
== DX
)
686 pState
->vpMatrix
[i
].m00
= pState
->vp
[i
].width
/ 2.0f
;
687 pState
->vpMatrix
[i
].m11
= -pState
->vp
[i
].height
/ 2.0f
;
688 pState
->vpMatrix
[i
].m22
= pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
;
689 pState
->vpMatrix
[i
].m30
= pState
->vp
[i
].x
+ pState
->vpMatrix
[i
].m00
;
690 pState
->vpMatrix
[i
].m31
= pState
->vp
[i
].y
- pState
->vpMatrix
[i
].m11
;
691 pState
->vpMatrix
[i
].m32
= pState
->vp
[i
].minZ
;
695 // Standard, with the exception that Y is inverted.
696 pState
->vpMatrix
[i
].m00
= (pState
->vp
[i
].width
- pState
->vp
[i
].x
) / 2.0f
;
697 pState
->vpMatrix
[i
].m11
= (pState
->vp
[i
].y
- pState
->vp
[i
].height
) / 2.0f
;
698 pState
->vpMatrix
[i
].m22
= (pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
) / 2.0f
;
699 pState
->vpMatrix
[i
].m30
= pState
->vp
[i
].x
+ pState
->vpMatrix
[i
].m00
;
700 pState
->vpMatrix
[i
].m31
= pState
->vp
[i
].height
+ pState
->vpMatrix
[i
].m11
;
701 pState
->vpMatrix
[i
].m32
= pState
->vp
[i
].minZ
+ pState
->vpMatrix
[i
].m22
;
703 // Now that the matrix is calculated, clip the view coords to screen size.
704 // OpenGL allows for -ve x,y in the viewport.
705 pState
->vp
[i
].x
= std::max(pState
->vp
[i
].x
, 0.0f
);
706 pState
->vp
[i
].y
= std::max(pState
->vp
[i
].y
, 0.0f
);
711 updateGuardband(pState
);
714 void SwrSetScissorRects(
716 uint32_t numScissors
,
717 const BBOX
* pScissors
)
719 SWR_ASSERT(numScissors
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
720 "Invalid number of scissor rects.");
722 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
723 memcpy(&pState
->scissorRects
[0], pScissors
, numScissors
* sizeof(BBOX
));
726 void SetupMacroTileScissors(DRAW_CONTEXT
*pDC
)
728 API_STATE
*pState
= &pDC
->pState
->state
;
729 uint32_t left
, right
, top
, bottom
;
731 // Set up scissor dimensions based on scissor or viewport
732 if (pState
->rastState
.scissorEnable
)
734 // scissor rect right/bottom edge are exclusive, core expects scissor dimensions to be inclusive, so subtract one pixel from right/bottom edges
735 left
= pState
->scissorRects
[0].left
;
736 right
= pState
->scissorRects
[0].right
;
737 top
= pState
->scissorRects
[0].top
;
738 bottom
= pState
->scissorRects
[0].bottom
;
742 // the vp width and height must be added to origin un-rounded then the result round to -inf.
743 // The cast to int works for rounding assuming all [left, right, top, bottom] are positive.
744 left
= (int32_t)pState
->vp
[0].x
;
745 right
= (int32_t)(pState
->vp
[0].x
+ pState
->vp
[0].width
);
746 top
= (int32_t)pState
->vp
[0].y
;
747 bottom
= (int32_t)(pState
->vp
[0].y
+ pState
->vp
[0].height
);
750 right
= std::min
<uint32_t>(right
, KNOB_MAX_SCISSOR_X
);
751 bottom
= std::min
<uint32_t>(bottom
, KNOB_MAX_SCISSOR_Y
);
753 if (left
> KNOB_MAX_SCISSOR_X
|| top
> KNOB_MAX_SCISSOR_Y
)
755 pState
->scissorInFixedPoint
.left
= 0;
756 pState
->scissorInFixedPoint
.right
= 0;
757 pState
->scissorInFixedPoint
.top
= 0;
758 pState
->scissorInFixedPoint
.bottom
= 0;
762 pState
->scissorInFixedPoint
.left
= left
* FIXED_POINT_SCALE
;
763 pState
->scissorInFixedPoint
.right
= right
* FIXED_POINT_SCALE
- 1;
764 pState
->scissorInFixedPoint
.top
= top
* FIXED_POINT_SCALE
;
765 pState
->scissorInFixedPoint
.bottom
= bottom
* FIXED_POINT_SCALE
- 1;
769 // templated backend function tables
770 extern PFN_BACKEND_FUNC gBackendNullPs
[SWR_MULTISAMPLE_TYPE_COUNT
];
771 extern PFN_BACKEND_FUNC gBackendSingleSample
[SWR_INPUT_COVERAGE_COUNT
][2][2];
772 extern PFN_BACKEND_FUNC gBackendPixelRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_MSAA_SAMPLE_PATTERN_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2][2];
773 extern PFN_BACKEND_FUNC gBackendSampleRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2];
774 void SetupPipeline(DRAW_CONTEXT
*pDC
)
776 DRAW_STATE
* pState
= pDC
->pState
;
777 const SWR_RASTSTATE
&rastState
= pState
->state
.rastState
;
778 const SWR_PS_STATE
&psState
= pState
->state
.psState
;
779 BACKEND_FUNCS
& backendFuncs
= pState
->backendFuncs
;
780 const uint32_t forcedSampleCount
= (rastState
.forcedSampleCount
) ? 1 : 0;
783 if (psState
.pfnPixelShader
== nullptr)
785 backendFuncs
.pfnBackend
= gBackendNullPs
[pState
->state
.rastState
.sampleCount
];
789 const bool bMultisampleEnable
= ((rastState
.sampleCount
> SWR_MULTISAMPLE_1X
) || rastState
.forcedSampleCount
) ? 1 : 0;
790 const uint32_t centroid
= ((psState
.barycentricsMask
& SWR_BARYCENTRIC_CENTROID_MASK
) > 0) ? 1 : 0;
791 const uint32_t canEarlyZ
= (psState
.forceEarlyZ
|| (!psState
.writesODepth
&& !psState
.usesSourceDepth
&& !psState
.usesUAV
)) ? 1 : 0;
793 SWR_BARYCENTRICS_MASK barycentricsMask
= (SWR_BARYCENTRICS_MASK
)psState
.barycentricsMask
;
795 // select backend function
796 switch(psState
.shadingRate
)
798 case SWR_SHADING_RATE_PIXEL
:
799 if(bMultisampleEnable
)
801 // always need to generate I & J per sample for Z interpolation
802 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
803 backendFuncs
.pfnBackend
= gBackendPixelRateTable
[rastState
.sampleCount
][rastState
.samplePattern
][psState
.inputCoverage
][centroid
][forcedSampleCount
][canEarlyZ
];
807 // always need to generate I & J per pixel for Z interpolation
808 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_PIXEL_MASK
);
809 backendFuncs
.pfnBackend
= gBackendSingleSample
[psState
.inputCoverage
][centroid
][canEarlyZ
];
812 case SWR_SHADING_RATE_SAMPLE
:
813 SWR_ASSERT(rastState
.samplePattern
== SWR_MSAA_STANDARD_PATTERN
);
814 // always need to generate I & J per sample for Z interpolation
815 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
816 backendFuncs
.pfnBackend
= gBackendSampleRateTable
[rastState
.sampleCount
][psState
.inputCoverage
][centroid
][canEarlyZ
];
819 SWR_ASSERT(0 && "Invalid shading rate");
824 PFN_PROCESS_PRIMS pfnBinner
;
825 switch (pState
->state
.topology
)
828 pState
->pfnProcessPrims
= ClipPoints
;
829 pfnBinner
= BinPoints
;
834 case TOP_LINE_LIST_ADJ
:
835 case TOP_LISTSTRIP_ADJ
:
836 pState
->pfnProcessPrims
= ClipLines
;
837 pfnBinner
= BinLines
;
840 pState
->pfnProcessPrims
= ClipTriangles
;
841 pfnBinner
= GetBinTrianglesFunc((rastState
.conservativeRast
> 0));
845 // disable clipper if viewport transform is disabled
846 if (pState
->state
.frontendState
.vpTransformDisable
)
848 pState
->pfnProcessPrims
= pfnBinner
;
851 if ((pState
->state
.psState
.pfnPixelShader
== nullptr) &&
852 (pState
->state
.depthStencilState
.depthTestEnable
== FALSE
) &&
853 (pState
->state
.depthStencilState
.depthWriteEnable
== FALSE
) &&
854 (pState
->state
.depthStencilState
.stencilTestEnable
== FALSE
) &&
855 (pState
->state
.depthStencilState
.stencilWriteEnable
== FALSE
) &&
856 (pState
->state
.backendState
.numAttributes
== 0))
858 pState
->pfnProcessPrims
= nullptr;
861 if (pState
->state
.soState
.rasterizerDisable
== true)
863 pState
->pfnProcessPrims
= nullptr;
866 // set up the frontend attribute count
867 pState
->state
.feNumAttributes
= 0;
868 const SWR_BACKEND_STATE
& backendState
= pState
->state
.backendState
;
869 if (backendState
.swizzleEnable
)
871 // attribute swizzling is enabled, iterate over the map and record the max attribute used
872 for (uint32_t i
= 0; i
< backendState
.numAttributes
; ++i
)
874 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)backendState
.swizzleMap
[i
].sourceAttrib
+ 1);
879 pState
->state
.feNumAttributes
= pState
->state
.backendState
.numAttributes
;
882 if (pState
->state
.soState
.soEnable
)
884 uint32_t streamMasks
= 0;
885 for (uint32_t i
= 0; i
< 4; ++i
)
887 streamMasks
|= pState
->state
.soState
.streamMasks
[i
];
891 if (_BitScanReverse(&maxAttrib
, streamMasks
))
893 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)(maxAttrib
+ 1));
897 // complicated logic to test for cases where we don't need backing hottile memory for a draw
898 // have to check for the special case where depth/stencil test is enabled but depthwrite is disabled.
899 pState
->state
.depthHottileEnable
= ((!(pState
->state
.depthStencilState
.depthTestEnable
&&
900 !pState
->state
.depthStencilState
.depthWriteEnable
&&
901 pState
->state
.depthStencilState
.depthTestFunc
== ZFUNC_ALWAYS
)) &&
902 (pState
->state
.depthStencilState
.depthTestEnable
||
903 pState
->state
.depthStencilState
.depthWriteEnable
)) ? true : false;
905 pState
->state
.stencilHottileEnable
= (((!(pState
->state
.depthStencilState
.stencilTestEnable
&&
906 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
907 pState
->state
.depthStencilState
.stencilTestFunc
== ZFUNC_ALWAYS
)) ||
908 // for stencil we have to check the double sided state as well
909 (!(pState
->state
.depthStencilState
.doubleSidedStencilTestEnable
&&
910 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
911 pState
->state
.depthStencilState
.backfaceStencilTestFunc
== ZFUNC_ALWAYS
))) &&
912 (pState
->state
.depthStencilState
.stencilTestEnable
||
913 pState
->state
.depthStencilState
.stencilWriteEnable
)) ? true : false;
915 uint32_t numRTs
= pState
->state
.psState
.numRenderTargets
;
916 pState
->state
.colorHottileEnable
= 0;
917 if (psState
.pfnPixelShader
!= nullptr)
919 for (uint32_t rt
= 0; rt
< numRTs
; ++rt
)
921 pState
->state
.colorHottileEnable
|=
922 (!pState
->state
.blendState
.renderTarget
[rt
].writeDisableAlpha
||
923 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableRed
||
924 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableGreen
||
925 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableBlue
) ? (1 << rt
) : 0;
929 // Setup depth quantization function
930 if (pState
->state
.depthHottileEnable
)
932 switch (pState
->state
.rastState
.depthFormat
)
934 case R32_FLOAT_X8X24_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT_X8X24_TYPELESS
> ; break;
935 case R32_FLOAT
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ; break;
936 case R24_UNORM_X8_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R24_UNORM_X8_TYPELESS
> ; break;
937 case R16_UNORM
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R16_UNORM
> ; break;
938 default: SWR_ASSERT(false, "Unsupported depth format for depth quantiztion.");
939 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
944 // set up pass-through quantize if depth isn't enabled
945 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
949 //////////////////////////////////////////////////////////////////////////
951 /// @param pDC - Draw context to initialize for this draw.
956 // We don't need to re-setup the scissors/pipeline state again for split draw.
957 if (isSplitDraw
== false)
959 SetupMacroTileScissors(pDC
);
964 //////////////////////////////////////////////////////////////////////////
965 /// @brief We can split the draw for certain topologies for better performance.
966 /// @param totalVerts - Total vertices for draw
967 /// @param topology - Topology used for draw
968 uint32_t MaxVertsPerDraw(
971 PRIMITIVE_TOPOLOGY topology
)
973 API_STATE
& state
= pDC
->pState
->state
;
975 uint32_t vertsPerDraw
= totalVerts
;
977 if (state
.soState
.soEnable
)
985 case TOP_TRIANGLE_LIST
:
986 vertsPerDraw
= KNOB_MAX_PRIMS_PER_DRAW
;
989 case TOP_PATCHLIST_1
:
990 case TOP_PATCHLIST_2
:
991 case TOP_PATCHLIST_3
:
992 case TOP_PATCHLIST_4
:
993 case TOP_PATCHLIST_5
:
994 case TOP_PATCHLIST_6
:
995 case TOP_PATCHLIST_7
:
996 case TOP_PATCHLIST_8
:
997 case TOP_PATCHLIST_9
:
998 case TOP_PATCHLIST_10
:
999 case TOP_PATCHLIST_11
:
1000 case TOP_PATCHLIST_12
:
1001 case TOP_PATCHLIST_13
:
1002 case TOP_PATCHLIST_14
:
1003 case TOP_PATCHLIST_15
:
1004 case TOP_PATCHLIST_16
:
1005 case TOP_PATCHLIST_17
:
1006 case TOP_PATCHLIST_18
:
1007 case TOP_PATCHLIST_19
:
1008 case TOP_PATCHLIST_20
:
1009 case TOP_PATCHLIST_21
:
1010 case TOP_PATCHLIST_22
:
1011 case TOP_PATCHLIST_23
:
1012 case TOP_PATCHLIST_24
:
1013 case TOP_PATCHLIST_25
:
1014 case TOP_PATCHLIST_26
:
1015 case TOP_PATCHLIST_27
:
1016 case TOP_PATCHLIST_28
:
1017 case TOP_PATCHLIST_29
:
1018 case TOP_PATCHLIST_30
:
1019 case TOP_PATCHLIST_31
:
1020 case TOP_PATCHLIST_32
:
1021 if (pDC
->pState
->state
.tsState
.tsEnable
)
1023 uint32_t vertsPerPrim
= topology
- TOP_PATCHLIST_BASE
;
1024 vertsPerDraw
= vertsPerPrim
* KNOB_MAX_TESS_PRIMS_PER_DRAW
;
1028 // The Primitive Assembly code can only handle 1 RECT at a time.
1034 // We are not splitting up draws for other topologies.
1038 return vertsPerDraw
;
1042 //////////////////////////////////////////////////////////////////////////
1043 /// @brief DrawInstanced
1044 /// @param hContext - Handle passed back from SwrCreateContext
1045 /// @param topology - Specifies topology for draw.
1046 /// @param numVerts - How many vertices to read sequentially from vertex data (per instance).
1047 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1048 /// @param numInstances - How many instances to render.
1049 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1052 PRIMITIVE_TOPOLOGY topology
,
1053 uint32_t numVertices
,
1054 uint32_t startVertex
,
1055 uint32_t numInstances
= 1,
1056 uint32_t startInstance
= 0)
1063 RDTSC_START(APIDraw
);
1065 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1066 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1068 uint32_t maxVertsPerDraw
= MaxVertsPerDraw(pDC
, numVertices
, topology
);
1069 uint32_t primsPerDraw
= GetNumPrims(topology
, maxVertsPerDraw
);
1070 uint32_t remainingVerts
= numVertices
;
1072 API_STATE
*pState
= &pDC
->pState
->state
;
1073 pState
->topology
= topology
;
1074 pState
->forceFront
= false;
1076 // disable culling for points/lines
1077 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1078 if (topology
== TOP_POINT_LIST
)
1080 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1081 pState
->forceFront
= true;
1085 while (remainingVerts
)
1087 uint32_t numVertsForDraw
= (remainingVerts
< maxVertsPerDraw
) ?
1088 remainingVerts
: maxVertsPerDraw
;
1090 bool isSplitDraw
= (draw
> 0) ? true : false;
1091 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
, isSplitDraw
);
1092 InitDraw(pDC
, isSplitDraw
);
1094 pDC
->FeWork
.type
= DRAW
;
1095 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1097 false, // bEnableCutIndex
1098 pState
->tsState
.tsEnable
,
1099 pState
->gsState
.gsEnable
,
1100 pState
->soState
.soEnable
,
1101 pDC
->pState
->pfnProcessPrims
!= nullptr);
1102 pDC
->FeWork
.desc
.draw
.numVerts
= numVertsForDraw
;
1103 pDC
->FeWork
.desc
.draw
.startVertex
= startVertex
;
1104 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1105 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1106 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1107 pDC
->FeWork
.desc
.draw
.startVertexID
= draw
* maxVertsPerDraw
;
1109 pDC
->cleanupState
= (remainingVerts
== numVertsForDraw
);
1112 QueueDraw(pContext
);
1114 remainingVerts
-= numVertsForDraw
;
1118 // restore culling state
1119 pDC
= GetDrawContext(pContext
);
1120 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1122 RDTSC_STOP(APIDraw
, numVertices
* numInstances
, 0);
1125 //////////////////////////////////////////////////////////////////////////
1127 /// @param hContext - Handle passed back from SwrCreateContext
1128 /// @param topology - Specifies topology for draw.
1129 /// @param startVertex - Specifies start vertex in vertex buffer for draw.
1130 /// @param primCount - Number of vertices.
1133 PRIMITIVE_TOPOLOGY topology
,
1134 uint32_t startVertex
,
1135 uint32_t numVertices
)
1137 DrawInstanced(hContext
, topology
, numVertices
, startVertex
);
1140 //////////////////////////////////////////////////////////////////////////
1141 /// @brief SwrDrawInstanced
1142 /// @param hContext - Handle passed back from SwrCreateContext
1143 /// @param topology - Specifies topology for draw.
1144 /// @param numVertsPerInstance - How many vertices to read sequentially from vertex data.
1145 /// @param numInstances - How many instances to render.
1146 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1147 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1148 void SwrDrawInstanced(
1150 PRIMITIVE_TOPOLOGY topology
,
1151 uint32_t numVertsPerInstance
,
1152 uint32_t numInstances
,
1153 uint32_t startVertex
,
1154 uint32_t startInstance
1157 DrawInstanced(hContext
, topology
, numVertsPerInstance
, startVertex
, numInstances
, startInstance
);
1160 //////////////////////////////////////////////////////////////////////////
1161 /// @brief DrawIndexedInstanced
1162 /// @param hContext - Handle passed back from SwrCreateContext
1163 /// @param topology - Specifies topology for draw.
1164 /// @param numIndices - Number of indices to read sequentially from index buffer.
1165 /// @param indexOffset - Starting index into index buffer.
1166 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1167 /// @param numInstances - Number of instances to render.
1168 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1169 void DrawIndexedInstance(
1171 PRIMITIVE_TOPOLOGY topology
,
1172 uint32_t numIndices
,
1173 uint32_t indexOffset
,
1175 uint32_t numInstances
= 1,
1176 uint32_t startInstance
= 0)
1183 RDTSC_START(APIDrawIndexed
);
1185 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1186 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1187 API_STATE
* pState
= &pDC
->pState
->state
;
1189 uint32_t maxIndicesPerDraw
= MaxVertsPerDraw(pDC
, numIndices
, topology
);
1190 uint32_t primsPerDraw
= GetNumPrims(topology
, maxIndicesPerDraw
);
1191 uint32_t remainingIndices
= numIndices
;
1193 uint32_t indexSize
= 0;
1194 switch (pState
->indexBuffer
.format
)
1196 case R32_UINT
: indexSize
= sizeof(uint32_t); break;
1197 case R16_UINT
: indexSize
= sizeof(uint16_t); break;
1198 case R8_UINT
: indexSize
= sizeof(uint8_t); break;
1204 uint8_t *pIB
= (uint8_t*)pState
->indexBuffer
.pIndices
;
1205 pIB
+= (uint64_t)indexOffset
* (uint64_t)indexSize
;
1207 pState
->topology
= topology
;
1208 pState
->forceFront
= false;
1210 // disable culling for points/lines
1211 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1212 if (topology
== TOP_POINT_LIST
)
1214 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1215 pState
->forceFront
= true;
1218 while (remainingIndices
)
1220 uint32_t numIndicesForDraw
= (remainingIndices
< maxIndicesPerDraw
) ?
1221 remainingIndices
: maxIndicesPerDraw
;
1223 // When breaking up draw, we need to obtain new draw context for each iteration.
1224 bool isSplitDraw
= (draw
> 0) ? true : false;
1225 pDC
= GetDrawContext(pContext
, isSplitDraw
);
1226 InitDraw(pDC
, isSplitDraw
);
1228 pDC
->FeWork
.type
= DRAW
;
1229 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1231 pState
->frontendState
.bEnableCutIndex
,
1232 pState
->tsState
.tsEnable
,
1233 pState
->gsState
.gsEnable
,
1234 pState
->soState
.soEnable
,
1235 pDC
->pState
->pfnProcessPrims
!= nullptr);
1236 pDC
->FeWork
.desc
.draw
.pDC
= pDC
;
1237 pDC
->FeWork
.desc
.draw
.numIndices
= numIndicesForDraw
;
1238 pDC
->FeWork
.desc
.draw
.pIB
= (int*)pIB
;
1239 pDC
->FeWork
.desc
.draw
.type
= pDC
->pState
->state
.indexBuffer
.format
;
1241 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1242 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1243 pDC
->FeWork
.desc
.draw
.baseVertex
= baseVertex
;
1244 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1246 pDC
->cleanupState
= (remainingIndices
== numIndicesForDraw
);
1249 QueueDraw(pContext
);
1251 pIB
+= maxIndicesPerDraw
* indexSize
;
1252 remainingIndices
-= numIndicesForDraw
;
1256 // restore culling state
1257 pDC
= GetDrawContext(pContext
);
1258 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1260 RDTSC_STOP(APIDrawIndexed
, numIndices
* numInstances
, 0);
1264 //////////////////////////////////////////////////////////////////////////
1265 /// @brief DrawIndexed
1266 /// @param hContext - Handle passed back from SwrCreateContext
1267 /// @param topology - Specifies topology for draw.
1268 /// @param numIndices - Number of indices to read sequentially from index buffer.
1269 /// @param indexOffset - Starting index into index buffer.
1270 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1271 void SwrDrawIndexed(
1273 PRIMITIVE_TOPOLOGY topology
,
1274 uint32_t numIndices
,
1275 uint32_t indexOffset
,
1279 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
);
1282 //////////////////////////////////////////////////////////////////////////
1283 /// @brief SwrDrawIndexedInstanced
1284 /// @param hContext - Handle passed back from SwrCreateContext
1285 /// @param topology - Specifies topology for draw.
1286 /// @param numIndices - Number of indices to read sequentially from index buffer.
1287 /// @param numInstances - Number of instances to render.
1288 /// @param indexOffset - Starting index into index buffer.
1289 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1290 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1291 void SwrDrawIndexedInstanced(
1293 PRIMITIVE_TOPOLOGY topology
,
1294 uint32_t numIndices
,
1295 uint32_t numInstances
,
1296 uint32_t indexOffset
,
1298 uint32_t startInstance
)
1300 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
);
1303 //////////////////////////////////////////////////////////////////////////
1304 /// @brief SwrInvalidateTiles
1305 /// @param hContext - Handle passed back from SwrCreateContext
1306 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to invalidate.
1307 void SwrInvalidateTiles(
1309 uint32_t attachmentMask
)
1316 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1317 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1319 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1320 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1321 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1322 memset(&pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
, 0, sizeof(SWR_RECT
));
1323 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_INVALID
;
1324 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= false;
1325 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= false;
1328 QueueDraw(pContext
);
1331 //////////////////////////////////////////////////////////////////////////
1332 /// @brief SwrDiscardRect
1333 /// @param hContext - Handle passed back from SwrCreateContext
1334 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to discard.
1335 /// @param rect - if rect is all zeros, the entire attachment surface will be discarded
1336 void SwrDiscardRect(
1338 uint32_t attachmentMask
,
1346 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1347 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1349 // Queue a load to the hottile
1350 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1351 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1352 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1353 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= rect
;
1354 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_RESOLVED
;
1355 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= true;
1356 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= true;
1359 QueueDraw(pContext
);
1362 //////////////////////////////////////////////////////////////////////////
1363 /// @brief SwrDispatch
1364 /// @param hContext - Handle passed back from SwrCreateContext
1365 /// @param threadGroupCountX - Number of thread groups dispatched in X direction
1366 /// @param threadGroupCountY - Number of thread groups dispatched in Y direction
1367 /// @param threadGroupCountZ - Number of thread groups dispatched in Z direction
1370 uint32_t threadGroupCountX
,
1371 uint32_t threadGroupCountY
,
1372 uint32_t threadGroupCountZ
)
1379 RDTSC_START(APIDispatch
);
1380 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1381 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1383 pDC
->isCompute
= true; // This is a compute context.
1385 COMPUTE_DESC
* pTaskData
= (COMPUTE_DESC
*)pDC
->pArena
->AllocAligned(sizeof(COMPUTE_DESC
), 64);
1387 pTaskData
->threadGroupCountX
= threadGroupCountX
;
1388 pTaskData
->threadGroupCountY
= threadGroupCountY
;
1389 pTaskData
->threadGroupCountZ
= threadGroupCountZ
;
1391 uint32_t totalThreadGroups
= threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
;
1392 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
1393 pDC
->pDispatch
= &pContext
->pDispatchQueueArray
[dcIndex
];
1394 pDC
->pDispatch
->initialize(totalThreadGroups
, pTaskData
);
1396 QueueDispatch(pContext
);
1397 RDTSC_STOP(APIDispatch
, threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
, 0);
1400 // Deswizzles, converts and stores current contents of the hot tiles to surface
1401 // described by pState
1404 SWR_RENDERTARGET_ATTACHMENT attachment
,
1405 SWR_TILE_STATE postStoreTileState
)
1412 RDTSC_START(APIStoreTiles
);
1414 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1415 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1417 SetupMacroTileScissors(pDC
);
1419 pDC
->FeWork
.type
= STORETILES
;
1420 pDC
->FeWork
.pfnWork
= ProcessStoreTiles
;
1421 pDC
->FeWork
.desc
.storeTiles
.attachment
= attachment
;
1422 pDC
->FeWork
.desc
.storeTiles
.postStoreTileState
= postStoreTileState
;
1425 QueueDraw(pContext
);
1427 RDTSC_STOP(APIStoreTiles
, 0, 0);
1430 void SwrClearRenderTarget(
1433 const float clearColor
[4],
1442 RDTSC_START(APIClearRenderTarget
);
1444 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1446 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1448 SetupMacroTileScissors(pDC
);
1451 flags
.mask
= clearMask
;
1453 pDC
->FeWork
.type
= CLEAR
;
1454 pDC
->FeWork
.pfnWork
= ProcessClear
;
1455 pDC
->FeWork
.desc
.clear
.flags
= flags
;
1456 pDC
->FeWork
.desc
.clear
.clearDepth
= z
;
1457 pDC
->FeWork
.desc
.clear
.clearRTColor
[0] = clearColor
[0];
1458 pDC
->FeWork
.desc
.clear
.clearRTColor
[1] = clearColor
[1];
1459 pDC
->FeWork
.desc
.clear
.clearRTColor
[2] = clearColor
[2];
1460 pDC
->FeWork
.desc
.clear
.clearRTColor
[3] = clearColor
[3];
1461 pDC
->FeWork
.desc
.clear
.clearStencil
= stencil
;
1464 QueueDraw(pContext
);
1466 RDTSC_STOP(APIClearRenderTarget
, 0, pDC
->drawId
);
1469 //////////////////////////////////////////////////////////////////////////
1470 /// @brief Returns a pointer to the private context state for the current
1471 /// draw operation. This is used for external componets such as the
1473 /// SWR is responsible for the allocation of the private context state.
1474 /// @param hContext - Handle passed back from SwrCreateContext
1475 VOID
* SwrGetPrivateContextState(
1478 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1479 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1480 DRAW_STATE
* pState
= pDC
->pState
;
1482 if (pState
->pPrivateState
== nullptr)
1484 pState
->pPrivateState
= pState
->pArena
->AllocAligned(pContext
->privateStateSize
, KNOB_SIMD_WIDTH
*sizeof(float));
1487 return pState
->pPrivateState
;
1490 //////////////////////////////////////////////////////////////////////////
1491 /// @brief Clients can use this to allocate memory for draw/dispatch
1492 /// operations. The memory will automatically be freed once operation
1493 /// has completed. Client can use this to allocate binding tables,
1494 /// etc. needed for shader execution.
1495 /// @param hContext - Handle passed back from SwrCreateContext
1496 /// @param size - Size of allocation
1497 /// @param align - Alignment needed for allocation.
1498 VOID
* SwrAllocDrawContextMemory(
1503 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1504 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1506 return pDC
->pState
->pArena
->AllocAligned(size
, align
);
1509 //////////////////////////////////////////////////////////////////////////
1510 /// @brief Returns pointer to SWR stats.
1511 /// @note The counters are atomically incremented by multiple threads.
1512 /// When calling this, you need to ensure all previous operations
1514 /// @todo If necessary, add a callback to avoid stalling the pipe to
1515 /// sample the counters.
1516 /// @param hContext - Handle passed back from SwrCreateContext
1517 /// @param pStats - SWR will fill this out for caller.
1522 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1523 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1525 pDC
->FeWork
.type
= QUERYSTATS
;
1526 pDC
->FeWork
.pfnWork
= ProcessQueryStats
;
1527 pDC
->FeWork
.desc
.queryStats
.pStats
= pStats
;
1529 // cannot execute until all previous draws have completed
1530 pDC
->dependent
= true;
1533 QueueDraw(pContext
);
1536 //////////////////////////////////////////////////////////////////////////
1537 /// @brief Enables stats counting
1538 /// @param hContext - Handle passed back from SwrCreateContext
1539 /// @param enable - If true then counts are incremented.
1540 void SwrEnableStats(
1544 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1545 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1547 pDC
->pState
->state
.enableStats
= enable
;
1550 //////////////////////////////////////////////////////////////////////////
1551 /// @brief Mark end of frame - used for performance profiling
1552 /// @param hContext - Handle passed back from SwrCreateContext
1553 void SWR_API
SwrEndFrame(
1557 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1558 pContext
->frameCount
++;