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
;
146 pContext
->pfnUpdateStats
= pCreateInfo
->pfnUpdateStats
;
148 // pass pointer to bucket manager back to caller
149 #ifdef KNOB_ENABLE_RDTSC
150 pCreateInfo
->pBucketMgr
= &gBucketMgr
;
153 pCreateInfo
->contextSaveSize
= sizeof(API_STATE
);
155 return (HANDLE
)pContext
;
158 void SwrDestroyContext(HANDLE hContext
)
160 SWR_CONTEXT
*pContext
= GetContext(hContext
);
161 DestroyThreadPool(pContext
, &pContext
->threadPool
);
164 for (uint32_t i
= 0; i
< KNOB_MAX_DRAWS_IN_FLIGHT
; ++i
)
166 delete pContext
->dcRing
[i
].pArena
;
167 delete pContext
->dsRing
[i
].pArena
;
168 pContext
->pMacroTileManagerArray
[i
].~MacroTileMgr();
169 pContext
->pDispatchQueueArray
[i
].~DispatchQueue();
172 AlignedFree(pContext
->pDispatchQueueArray
);
173 AlignedFree(pContext
->pMacroTileManagerArray
);
175 // Free scratch space.
176 for (uint32_t i
= 0; i
< pContext
->NumWorkerThreads
; ++i
)
179 VirtualFree(pContext
->pScratch
[i
], 0, MEM_RELEASE
);
181 AlignedFree(pContext
->pScratch
[i
]);
185 delete(pContext
->pHotTileMgr
);
187 pContext
->~SWR_CONTEXT();
188 AlignedFree(GetContext(hContext
));
191 void CopyState(DRAW_STATE
& dst
, const DRAW_STATE
& src
)
193 memcpy(&dst
.state
, &src
.state
, sizeof(API_STATE
));
196 void WakeAllThreads(SWR_CONTEXT
*pContext
)
198 pContext
->FifosNotEmpty
.notify_all();
201 static TileSet gSingleThreadLockedTiles
;
203 template<bool IsDraw
>
204 void QueueWork(SWR_CONTEXT
*pContext
)
206 DRAW_CONTEXT
* pDC
= pContext
->pCurDrawContext
;
207 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
211 pDC
->pTileMgr
= &pContext
->pMacroTileManagerArray
[dcIndex
];
212 pDC
->pTileMgr
->initialize();
215 // Each worker thread looks at a DC for both FE and BE work at different times and so we
216 // multiply threadDone by 2. When the threadDone counter has reached 0 then all workers
217 // have moved past this DC. (i.e. Each worker has checked this DC for both FE and BE work and
218 // then moved on if all work is done.)
219 pContext
->pCurDrawContext
->threadsDone
= pContext
->NumFEThreads
+ pContext
->NumBEThreads
;
223 InterlockedIncrement((volatile LONG
*)&pContext
->drawsOutstandingFE
);
228 std::unique_lock
<std::mutex
> lock(pContext
->WaitLock
);
229 pContext
->dcRing
.Enqueue();
232 if (pContext
->threadInfo
.SINGLE_THREADED
)
234 // flush denormals to 0
235 uint32_t mxcsr
= _mm_getcsr();
236 _mm_setcsr(mxcsr
| _MM_FLUSH_ZERO_ON
| _MM_DENORMALS_ZERO_ON
);
240 uint32_t curDraw
[2] = { pContext
->pCurDrawContext
->drawId
, pContext
->pCurDrawContext
->drawId
};
241 WorkOnFifoFE(pContext
, 0, curDraw
[0]);
242 WorkOnFifoBE(pContext
, 0, curDraw
[1], gSingleThreadLockedTiles
, 0, 0);
246 uint32_t curDispatch
= pContext
->pCurDrawContext
->drawId
;
247 WorkOnCompute(pContext
, 0, curDispatch
);
250 // Dequeue the work here, if not already done, since we're single threaded (i.e. no workers).
251 while (CompleteDrawContext(pContext
, pContext
->pCurDrawContext
) > 0) {}
258 RDTSC_START(APIDrawWakeAllThreads
);
259 WakeAllThreads(pContext
);
260 RDTSC_STOP(APIDrawWakeAllThreads
, 1, 0);
263 // Set current draw context to NULL so that next state call forces a new draw context to be created and populated.
264 pContext
->pPrevDrawContext
= pContext
->pCurDrawContext
;
265 pContext
->pCurDrawContext
= nullptr;
268 INLINE
void QueueDraw(SWR_CONTEXT
* pContext
)
270 QueueWork
<true>(pContext
);
273 INLINE
void QueueDispatch(SWR_CONTEXT
* pContext
)
275 QueueWork
<false>(pContext
);
278 DRAW_CONTEXT
* GetDrawContext(SWR_CONTEXT
*pContext
, bool isSplitDraw
= false)
280 RDTSC_START(APIGetDrawContext
);
281 // If current draw context is null then need to obtain a new draw context to use from ring.
282 if (pContext
->pCurDrawContext
== nullptr)
284 // Need to wait for a free entry.
285 while (pContext
->dcRing
.IsFull())
290 uint64_t curDraw
= pContext
->dcRing
.GetHead();
291 uint32_t dcIndex
= curDraw
% KNOB_MAX_DRAWS_IN_FLIGHT
;
293 static uint64_t lastDrawChecked
;
294 static uint32_t lastFrameChecked
;
295 if ((pContext
->frameCount
- lastFrameChecked
) > 2 ||
296 (curDraw
- lastDrawChecked
) > 0x10000)
298 // Take this opportunity to clean-up old arena allocations
299 pContext
->cachingArenaAllocator
.FreeOldBlocks();
301 lastFrameChecked
= pContext
->frameCount
;
302 lastDrawChecked
= curDraw
;
305 DRAW_CONTEXT
* pCurDrawContext
= &pContext
->dcRing
[dcIndex
];
306 pContext
->pCurDrawContext
= pCurDrawContext
;
308 // Assign next available entry in DS ring to this DC.
309 uint32_t dsIndex
= pContext
->curStateId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
310 pCurDrawContext
->pState
= &pContext
->dsRing
[dsIndex
];
312 // Copy previous state to current state.
313 if (pContext
->pPrevDrawContext
)
315 DRAW_CONTEXT
* pPrevDrawContext
= pContext
->pPrevDrawContext
;
317 // If we're splitting our draw then we can just use the same state from the previous
318 // draw. In this case, we won't increment the DS ring index so the next non-split
319 // draw can receive the state.
320 if (isSplitDraw
== false)
322 CopyState(*pCurDrawContext
->pState
, *pPrevDrawContext
->pState
);
324 // Should have been cleaned up previously
325 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
327 pCurDrawContext
->pState
->pPrivateState
= nullptr;
329 pContext
->curStateId
++; // Progress state ring index forward.
333 // If its a split draw then just copy the state pointer over
334 // since its the same draw.
335 pCurDrawContext
->pState
= pPrevDrawContext
->pState
;
336 SWR_ASSERT(pPrevDrawContext
->cleanupState
== false);
341 SWR_ASSERT(pCurDrawContext
->pState
->pArena
->IsEmpty() == true);
342 pContext
->curStateId
++; // Progress state ring index forward.
345 SWR_ASSERT(pCurDrawContext
->pArena
->IsEmpty() == true);
347 pCurDrawContext
->dependent
= false;
348 pCurDrawContext
->pContext
= pContext
;
349 pCurDrawContext
->isCompute
= false; // Dispatch has to set this to true.
351 pCurDrawContext
->doneFE
= false;
352 pCurDrawContext
->FeLock
= 0;
353 pCurDrawContext
->threadsDone
= 0;
354 pCurDrawContext
->retireCallback
.pfnCallbackFunc
= nullptr;
356 memset(&pCurDrawContext
->dynState
, 0, sizeof(pCurDrawContext
->dynState
));
358 // Assign unique drawId for this DC
359 pCurDrawContext
->drawId
= pContext
->dcRing
.GetHead();
361 pCurDrawContext
->cleanupState
= true;
365 SWR_ASSERT(isSplitDraw
== false, "Split draw should only be used when obtaining a new DC");
368 RDTSC_STOP(APIGetDrawContext
, 0, 0);
369 return pContext
->pCurDrawContext
;
372 API_STATE
* GetDrawState(SWR_CONTEXT
*pContext
)
374 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
375 SWR_ASSERT(pDC
->pState
!= nullptr);
377 return &pDC
->pState
->state
;
380 void SWR_API
SwrSaveState(
382 void* pOutputStateBlock
,
385 SWR_CONTEXT
*pContext
= GetContext(hContext
);
386 auto pSrc
= GetDrawState(pContext
);
387 SWR_ASSERT(pOutputStateBlock
&& memSize
>= sizeof(*pSrc
));
389 memcpy(pOutputStateBlock
, pSrc
, sizeof(*pSrc
));
392 void SWR_API
SwrRestoreState(
394 const void* pStateBlock
,
397 SWR_CONTEXT
*pContext
= GetContext(hContext
);
398 auto pDst
= GetDrawState(pContext
);
399 SWR_ASSERT(pStateBlock
&& memSize
>= sizeof(*pDst
));
401 memcpy(pDst
, pStateBlock
, sizeof(*pDst
));
404 void SetupDefaultState(SWR_CONTEXT
*pContext
)
406 API_STATE
* pState
= GetDrawState(pContext
);
408 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
409 pState
->rastState
.frontWinding
= SWR_FRONTWINDING_CCW
;
412 void SwrSync(HANDLE hContext
, PFN_CALLBACK_FUNC pfnFunc
, uint64_t userData
, uint64_t userData2
, uint64_t userData3
)
414 RDTSC_START(APISync
);
416 SWR_ASSERT(pfnFunc
!= nullptr);
418 SWR_CONTEXT
*pContext
= GetContext(hContext
);
419 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
421 pDC
->FeWork
.type
= SYNC
;
422 pDC
->FeWork
.pfnWork
= ProcessSync
;
424 // Setup callback function
425 pDC
->retireCallback
.pfnCallbackFunc
= pfnFunc
;
426 pDC
->retireCallback
.userData
= userData
;
427 pDC
->retireCallback
.userData2
= userData2
;
428 pDC
->retireCallback
.userData3
= userData3
;
433 RDTSC_STOP(APISync
, 1, 0);
436 void SwrWaitForIdle(HANDLE hContext
)
438 SWR_CONTEXT
*pContext
= GetContext(hContext
);
440 RDTSC_START(APIWaitForIdle
);
442 while (!pContext
->dcRing
.IsEmpty())
447 RDTSC_STOP(APIWaitForIdle
, 1, 0);
450 void SwrWaitForIdleFE(HANDLE hContext
)
452 SWR_CONTEXT
*pContext
= GetContext(hContext
);
454 RDTSC_START(APIWaitForIdle
);
456 while (pContext
->drawsOutstandingFE
> 0)
461 RDTSC_STOP(APIWaitForIdle
, 1, 0);
464 void SwrSetVertexBuffers(
467 const SWR_VERTEX_BUFFER_STATE
* pVertexBuffers
)
469 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
471 for (uint32_t i
= 0; i
< numBuffers
; ++i
)
473 const SWR_VERTEX_BUFFER_STATE
*pVB
= &pVertexBuffers
[i
];
474 pState
->vertexBuffers
[pVB
->index
] = *pVB
;
478 void SwrSetIndexBuffer(
480 const SWR_INDEX_BUFFER_STATE
* pIndexBuffer
)
482 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
484 pState
->indexBuffer
= *pIndexBuffer
;
487 void SwrSetFetchFunc(
489 PFN_FETCH_FUNC pfnFetchFunc
)
491 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
493 pState
->pfnFetchFunc
= pfnFetchFunc
;
498 PFN_SO_FUNC pfnSoFunc
,
499 uint32_t streamIndex
)
501 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
503 SWR_ASSERT(streamIndex
< MAX_SO_STREAMS
);
505 pState
->pfnSoFunc
[streamIndex
] = pfnSoFunc
;
510 SWR_STREAMOUT_STATE
* pSoState
)
512 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
514 pState
->soState
= *pSoState
;
517 void SwrSetSoBuffers(
519 SWR_STREAMOUT_BUFFER
* pSoBuffer
,
522 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
524 SWR_ASSERT((slot
< 4), "There are only 4 SO buffer slots [0, 3]\nSlot requested: %d", slot
);
526 pState
->soBuffer
[slot
] = *pSoBuffer
;
529 void SwrSetVertexFunc(
531 PFN_VERTEX_FUNC pfnVertexFunc
)
533 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
535 pState
->pfnVertexFunc
= pfnVertexFunc
;
538 void SwrSetFrontendState(
540 SWR_FRONTEND_STATE
*pFEState
)
542 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
543 pState
->frontendState
= *pFEState
;
548 SWR_GS_STATE
*pGSState
)
550 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
551 pState
->gsState
= *pGSState
;
556 PFN_GS_FUNC pfnGsFunc
)
558 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
559 pState
->pfnGsFunc
= pfnGsFunc
;
564 PFN_CS_FUNC pfnCsFunc
,
565 uint32_t totalThreadsInGroup
,
566 uint32_t totalSpillFillSize
)
568 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
569 pState
->pfnCsFunc
= pfnCsFunc
;
570 pState
->totalThreadsInGroup
= totalThreadsInGroup
;
571 pState
->totalSpillFillSize
= totalSpillFillSize
;
576 SWR_TS_STATE
*pState
)
578 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
579 pApiState
->tsState
= *pState
;
586 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
587 pApiState
->pfnHsFunc
= pfnFunc
;
594 API_STATE
* pApiState
= GetDrawState(GetContext(hContext
));
595 pApiState
->pfnDsFunc
= pfnFunc
;
598 void SwrSetDepthStencilState(
600 SWR_DEPTH_STENCIL_STATE
*pDSState
)
602 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
604 pState
->depthStencilState
= *pDSState
;
607 void SwrSetBackendState(
609 SWR_BACKEND_STATE
*pBEState
)
611 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
613 pState
->backendState
= *pBEState
;
616 void SwrSetPixelShaderState(
618 SWR_PS_STATE
*pPSState
)
620 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
621 pState
->psState
= *pPSState
;
624 void SwrSetBlendState(
626 SWR_BLEND_STATE
*pBlendState
)
628 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
629 memcpy(&pState
->blendState
, pBlendState
, sizeof(SWR_BLEND_STATE
));
632 void SwrSetBlendFunc(
634 uint32_t renderTarget
,
635 PFN_BLEND_JIT_FUNC pfnBlendFunc
)
637 SWR_ASSERT(renderTarget
< SWR_NUM_RENDERTARGETS
);
638 API_STATE
*pState
= GetDrawState(GetContext(hContext
));
639 pState
->pfnBlendFunc
[renderTarget
] = pfnBlendFunc
;
642 // update guardband multipliers for the viewport
643 void updateGuardband(API_STATE
*pState
)
645 // guardband center is viewport center
646 pState
->gbState
.left
= KNOB_GUARDBAND_WIDTH
/ pState
->vp
[0].width
;
647 pState
->gbState
.right
= KNOB_GUARDBAND_WIDTH
/ pState
->vp
[0].width
;
648 pState
->gbState
.top
= KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[0].height
;
649 pState
->gbState
.bottom
= KNOB_GUARDBAND_HEIGHT
/ pState
->vp
[0].height
;
652 void SwrSetRastState(
654 const SWR_RASTSTATE
*pRastState
)
656 SWR_CONTEXT
*pContext
= GetContext(hContext
);
657 API_STATE
* pState
= GetDrawState(pContext
);
659 memcpy(&pState
->rastState
, pRastState
, sizeof(SWR_RASTSTATE
));
662 void SwrSetViewports(
664 uint32_t numViewports
,
665 const SWR_VIEWPORT
* pViewports
,
666 const SWR_VIEWPORT_MATRICES
* pMatrices
)
668 SWR_ASSERT(numViewports
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
669 "Invalid number of viewports.");
671 SWR_CONTEXT
*pContext
= GetContext(hContext
);
672 API_STATE
* pState
= GetDrawState(pContext
);
674 memcpy(&pState
->vp
[0], pViewports
, sizeof(SWR_VIEWPORT
) * numViewports
);
676 if (pMatrices
!= nullptr)
678 //memcpy(&pState->vpMatrix[0], pMatrices, sizeof(SWR_VIEWPORT_MATRIX) * numViewports);
679 // @todo Faster to copy portions of the SOA or just copy all of it?
680 memcpy(&pState
->vpMatrices
, pMatrices
, sizeof(SWR_VIEWPORT_MATRICES
));
684 // Compute default viewport transform.
685 for (uint32_t i
= 0; i
< numViewports
; ++i
)
687 if (pContext
->driverType
== DX
)
689 pState
->vpMatrices
.m00
[i
] = pState
->vp
[i
].width
/ 2.0f
;
690 pState
->vpMatrices
.m11
[i
] = -pState
->vp
[i
].height
/ 2.0f
;
691 pState
->vpMatrices
.m22
[i
] = pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
;
692 pState
->vpMatrices
.m30
[i
] = pState
->vp
[i
].x
+ pState
->vpMatrices
.m00
[i
];
693 pState
->vpMatrices
.m31
[i
] = pState
->vp
[i
].y
- pState
->vpMatrices
.m11
[i
];
694 pState
->vpMatrices
.m32
[i
] = pState
->vp
[i
].minZ
;
698 // Standard, with the exception that Y is inverted.
699 pState
->vpMatrices
.m00
[i
] = (pState
->vp
[i
].width
- pState
->vp
[i
].x
) / 2.0f
;
700 pState
->vpMatrices
.m11
[i
] = (pState
->vp
[i
].y
- pState
->vp
[i
].height
) / 2.0f
;
701 pState
->vpMatrices
.m22
[i
] = (pState
->vp
[i
].maxZ
- pState
->vp
[i
].minZ
) / 2.0f
;
702 pState
->vpMatrices
.m30
[i
] = pState
->vp
[i
].x
+ pState
->vpMatrices
.m00
[i
];
703 pState
->vpMatrices
.m31
[i
] = pState
->vp
[i
].height
+ pState
->vpMatrices
.m11
[i
];
704 pState
->vpMatrices
.m32
[i
] = pState
->vp
[i
].minZ
+ pState
->vpMatrices
.m22
[i
];
706 // Now that the matrix is calculated, clip the view coords to screen size.
707 // OpenGL allows for -ve x,y in the viewport.
708 pState
->vp
[i
].x
= std::max(pState
->vp
[i
].x
, 0.0f
);
709 pState
->vp
[i
].y
= std::max(pState
->vp
[i
].y
, 0.0f
);
714 updateGuardband(pState
);
717 void SwrSetScissorRects(
719 uint32_t numScissors
,
720 const BBOX
* pScissors
)
722 SWR_ASSERT(numScissors
<= KNOB_NUM_VIEWPORTS_SCISSORS
,
723 "Invalid number of scissor rects.");
725 API_STATE
* pState
= GetDrawState(GetContext(hContext
));
726 memcpy(&pState
->scissorRects
[0], pScissors
, numScissors
* sizeof(BBOX
));
729 void SetupMacroTileScissors(DRAW_CONTEXT
*pDC
)
731 API_STATE
*pState
= &pDC
->pState
->state
;
732 uint32_t left
, right
, top
, bottom
;
734 // Set up scissor dimensions based on scissor or viewport
735 if (pState
->rastState
.scissorEnable
)
737 // scissor rect right/bottom edge are exclusive, core expects scissor dimensions to be inclusive, so subtract one pixel from right/bottom edges
738 left
= pState
->scissorRects
[0].left
;
739 right
= pState
->scissorRects
[0].right
;
740 top
= pState
->scissorRects
[0].top
;
741 bottom
= pState
->scissorRects
[0].bottom
;
745 // the vp width and height must be added to origin un-rounded then the result round to -inf.
746 // The cast to int works for rounding assuming all [left, right, top, bottom] are positive.
747 left
= (int32_t)pState
->vp
[0].x
;
748 right
= (int32_t)(pState
->vp
[0].x
+ pState
->vp
[0].width
);
749 top
= (int32_t)pState
->vp
[0].y
;
750 bottom
= (int32_t)(pState
->vp
[0].y
+ pState
->vp
[0].height
);
753 right
= std::min
<uint32_t>(right
, KNOB_MAX_SCISSOR_X
);
754 bottom
= std::min
<uint32_t>(bottom
, KNOB_MAX_SCISSOR_Y
);
756 if (left
> KNOB_MAX_SCISSOR_X
|| top
> KNOB_MAX_SCISSOR_Y
)
758 pState
->scissorInFixedPoint
.left
= 0;
759 pState
->scissorInFixedPoint
.right
= 0;
760 pState
->scissorInFixedPoint
.top
= 0;
761 pState
->scissorInFixedPoint
.bottom
= 0;
765 pState
->scissorInFixedPoint
.left
= left
* FIXED_POINT_SCALE
;
766 pState
->scissorInFixedPoint
.right
= right
* FIXED_POINT_SCALE
- 1;
767 pState
->scissorInFixedPoint
.top
= top
* FIXED_POINT_SCALE
;
768 pState
->scissorInFixedPoint
.bottom
= bottom
* FIXED_POINT_SCALE
- 1;
772 // templated backend function tables
773 extern PFN_BACKEND_FUNC gBackendNullPs
[SWR_MULTISAMPLE_TYPE_COUNT
];
774 extern PFN_BACKEND_FUNC gBackendSingleSample
[SWR_INPUT_COVERAGE_COUNT
][2][2];
775 extern PFN_BACKEND_FUNC gBackendPixelRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_MSAA_SAMPLE_PATTERN_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2][2];
776 extern PFN_BACKEND_FUNC gBackendSampleRateTable
[SWR_MULTISAMPLE_TYPE_COUNT
][SWR_INPUT_COVERAGE_COUNT
][2][2];
777 void SetupPipeline(DRAW_CONTEXT
*pDC
)
779 DRAW_STATE
* pState
= pDC
->pState
;
780 const SWR_RASTSTATE
&rastState
= pState
->state
.rastState
;
781 const SWR_PS_STATE
&psState
= pState
->state
.psState
;
782 BACKEND_FUNCS
& backendFuncs
= pState
->backendFuncs
;
783 const uint32_t forcedSampleCount
= (rastState
.forcedSampleCount
) ? 1 : 0;
786 if (psState
.pfnPixelShader
== nullptr)
788 backendFuncs
.pfnBackend
= gBackendNullPs
[pState
->state
.rastState
.sampleCount
];
792 const bool bMultisampleEnable
= ((rastState
.sampleCount
> SWR_MULTISAMPLE_1X
) || rastState
.forcedSampleCount
) ? 1 : 0;
793 const uint32_t centroid
= ((psState
.barycentricsMask
& SWR_BARYCENTRIC_CENTROID_MASK
) > 0) ? 1 : 0;
794 const uint32_t canEarlyZ
= (psState
.forceEarlyZ
|| (!psState
.writesODepth
&& !psState
.usesSourceDepth
&& !psState
.usesUAV
)) ? 1 : 0;
796 SWR_BARYCENTRICS_MASK barycentricsMask
= (SWR_BARYCENTRICS_MASK
)psState
.barycentricsMask
;
798 // select backend function
799 switch(psState
.shadingRate
)
801 case SWR_SHADING_RATE_PIXEL
:
802 if(bMultisampleEnable
)
804 // always need to generate I & J per sample for Z interpolation
805 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
806 backendFuncs
.pfnBackend
= gBackendPixelRateTable
[rastState
.sampleCount
][rastState
.samplePattern
][psState
.inputCoverage
][centroid
][forcedSampleCount
][canEarlyZ
];
810 // always need to generate I & J per pixel for Z interpolation
811 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_PIXEL_MASK
);
812 backendFuncs
.pfnBackend
= gBackendSingleSample
[psState
.inputCoverage
][centroid
][canEarlyZ
];
815 case SWR_SHADING_RATE_SAMPLE
:
816 SWR_ASSERT(rastState
.samplePattern
== SWR_MSAA_STANDARD_PATTERN
);
817 // always need to generate I & J per sample for Z interpolation
818 barycentricsMask
= (SWR_BARYCENTRICS_MASK
)(barycentricsMask
| SWR_BARYCENTRIC_PER_SAMPLE_MASK
);
819 backendFuncs
.pfnBackend
= gBackendSampleRateTable
[rastState
.sampleCount
][psState
.inputCoverage
][centroid
][canEarlyZ
];
822 SWR_ASSERT(0 && "Invalid shading rate");
827 PFN_PROCESS_PRIMS pfnBinner
;
828 switch (pState
->state
.topology
)
831 pState
->pfnProcessPrims
= ClipPoints
;
832 pfnBinner
= BinPoints
;
837 case TOP_LINE_LIST_ADJ
:
838 case TOP_LISTSTRIP_ADJ
:
839 pState
->pfnProcessPrims
= ClipLines
;
840 pfnBinner
= BinLines
;
843 pState
->pfnProcessPrims
= ClipTriangles
;
844 pfnBinner
= GetBinTrianglesFunc((rastState
.conservativeRast
> 0));
848 // disable clipper if viewport transform is disabled
849 if (pState
->state
.frontendState
.vpTransformDisable
)
851 pState
->pfnProcessPrims
= pfnBinner
;
854 if ((pState
->state
.psState
.pfnPixelShader
== nullptr) &&
855 (pState
->state
.depthStencilState
.depthTestEnable
== FALSE
) &&
856 (pState
->state
.depthStencilState
.depthWriteEnable
== FALSE
) &&
857 (pState
->state
.depthStencilState
.stencilTestEnable
== FALSE
) &&
858 (pState
->state
.depthStencilState
.stencilWriteEnable
== FALSE
) &&
859 (pState
->state
.backendState
.numAttributes
== 0))
861 pState
->pfnProcessPrims
= nullptr;
864 if (pState
->state
.soState
.rasterizerDisable
== true)
866 pState
->pfnProcessPrims
= nullptr;
869 // set up the frontend attribute count
870 pState
->state
.feNumAttributes
= 0;
871 const SWR_BACKEND_STATE
& backendState
= pState
->state
.backendState
;
872 if (backendState
.swizzleEnable
)
874 // attribute swizzling is enabled, iterate over the map and record the max attribute used
875 for (uint32_t i
= 0; i
< backendState
.numAttributes
; ++i
)
877 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)backendState
.swizzleMap
[i
].sourceAttrib
+ 1);
882 pState
->state
.feNumAttributes
= pState
->state
.backendState
.numAttributes
;
885 if (pState
->state
.soState
.soEnable
)
887 uint32_t streamMasks
= 0;
888 for (uint32_t i
= 0; i
< 4; ++i
)
890 streamMasks
|= pState
->state
.soState
.streamMasks
[i
];
894 if (_BitScanReverse(&maxAttrib
, streamMasks
))
896 pState
->state
.feNumAttributes
= std::max(pState
->state
.feNumAttributes
, (uint32_t)(maxAttrib
+ 1));
900 // complicated logic to test for cases where we don't need backing hottile memory for a draw
901 // have to check for the special case where depth/stencil test is enabled but depthwrite is disabled.
902 pState
->state
.depthHottileEnable
= ((!(pState
->state
.depthStencilState
.depthTestEnable
&&
903 !pState
->state
.depthStencilState
.depthWriteEnable
&&
904 pState
->state
.depthStencilState
.depthTestFunc
== ZFUNC_ALWAYS
)) &&
905 (pState
->state
.depthStencilState
.depthTestEnable
||
906 pState
->state
.depthStencilState
.depthWriteEnable
)) ? true : false;
908 pState
->state
.stencilHottileEnable
= (((!(pState
->state
.depthStencilState
.stencilTestEnable
&&
909 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
910 pState
->state
.depthStencilState
.stencilTestFunc
== ZFUNC_ALWAYS
)) ||
911 // for stencil we have to check the double sided state as well
912 (!(pState
->state
.depthStencilState
.doubleSidedStencilTestEnable
&&
913 !pState
->state
.depthStencilState
.stencilWriteEnable
&&
914 pState
->state
.depthStencilState
.backfaceStencilTestFunc
== ZFUNC_ALWAYS
))) &&
915 (pState
->state
.depthStencilState
.stencilTestEnable
||
916 pState
->state
.depthStencilState
.stencilWriteEnable
)) ? true : false;
918 uint32_t numRTs
= pState
->state
.psState
.numRenderTargets
;
919 pState
->state
.colorHottileEnable
= 0;
920 if (psState
.pfnPixelShader
!= nullptr)
922 for (uint32_t rt
= 0; rt
< numRTs
; ++rt
)
924 pState
->state
.colorHottileEnable
|=
925 (!pState
->state
.blendState
.renderTarget
[rt
].writeDisableAlpha
||
926 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableRed
||
927 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableGreen
||
928 !pState
->state
.blendState
.renderTarget
[rt
].writeDisableBlue
) ? (1 << rt
) : 0;
932 // Setup depth quantization function
933 if (pState
->state
.depthHottileEnable
)
935 switch (pState
->state
.rastState
.depthFormat
)
937 case R32_FLOAT_X8X24_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT_X8X24_TYPELESS
> ; break;
938 case R32_FLOAT
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ; break;
939 case R24_UNORM_X8_TYPELESS
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R24_UNORM_X8_TYPELESS
> ; break;
940 case R16_UNORM
: pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R16_UNORM
> ; break;
941 default: SWR_ASSERT(false, "Unsupported depth format for depth quantiztion.");
942 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
947 // set up pass-through quantize if depth isn't enabled
948 pState
->state
.pfnQuantizeDepth
= QuantizeDepth
< R32_FLOAT
> ;
952 //////////////////////////////////////////////////////////////////////////
954 /// @param pDC - Draw context to initialize for this draw.
959 // We don't need to re-setup the scissors/pipeline state again for split draw.
960 if (isSplitDraw
== false)
962 SetupMacroTileScissors(pDC
);
967 //////////////////////////////////////////////////////////////////////////
968 /// @brief We can split the draw for certain topologies for better performance.
969 /// @param totalVerts - Total vertices for draw
970 /// @param topology - Topology used for draw
971 uint32_t MaxVertsPerDraw(
974 PRIMITIVE_TOPOLOGY topology
)
976 API_STATE
& state
= pDC
->pState
->state
;
978 uint32_t vertsPerDraw
= totalVerts
;
980 if (state
.soState
.soEnable
)
988 case TOP_TRIANGLE_LIST
:
989 vertsPerDraw
= KNOB_MAX_PRIMS_PER_DRAW
;
992 case TOP_PATCHLIST_1
:
993 case TOP_PATCHLIST_2
:
994 case TOP_PATCHLIST_3
:
995 case TOP_PATCHLIST_4
:
996 case TOP_PATCHLIST_5
:
997 case TOP_PATCHLIST_6
:
998 case TOP_PATCHLIST_7
:
999 case TOP_PATCHLIST_8
:
1000 case TOP_PATCHLIST_9
:
1001 case TOP_PATCHLIST_10
:
1002 case TOP_PATCHLIST_11
:
1003 case TOP_PATCHLIST_12
:
1004 case TOP_PATCHLIST_13
:
1005 case TOP_PATCHLIST_14
:
1006 case TOP_PATCHLIST_15
:
1007 case TOP_PATCHLIST_16
:
1008 case TOP_PATCHLIST_17
:
1009 case TOP_PATCHLIST_18
:
1010 case TOP_PATCHLIST_19
:
1011 case TOP_PATCHLIST_20
:
1012 case TOP_PATCHLIST_21
:
1013 case TOP_PATCHLIST_22
:
1014 case TOP_PATCHLIST_23
:
1015 case TOP_PATCHLIST_24
:
1016 case TOP_PATCHLIST_25
:
1017 case TOP_PATCHLIST_26
:
1018 case TOP_PATCHLIST_27
:
1019 case TOP_PATCHLIST_28
:
1020 case TOP_PATCHLIST_29
:
1021 case TOP_PATCHLIST_30
:
1022 case TOP_PATCHLIST_31
:
1023 case TOP_PATCHLIST_32
:
1024 if (pDC
->pState
->state
.tsState
.tsEnable
)
1026 uint32_t vertsPerPrim
= topology
- TOP_PATCHLIST_BASE
;
1027 vertsPerDraw
= vertsPerPrim
* KNOB_MAX_TESS_PRIMS_PER_DRAW
;
1031 // The Primitive Assembly code can only handle 1 RECT at a time.
1037 // We are not splitting up draws for other topologies.
1041 return vertsPerDraw
;
1045 //////////////////////////////////////////////////////////////////////////
1046 /// @brief DrawInstanced
1047 /// @param hContext - Handle passed back from SwrCreateContext
1048 /// @param topology - Specifies topology for draw.
1049 /// @param numVerts - How many vertices to read sequentially from vertex data (per instance).
1050 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1051 /// @param numInstances - How many instances to render.
1052 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1055 PRIMITIVE_TOPOLOGY topology
,
1056 uint32_t numVertices
,
1057 uint32_t startVertex
,
1058 uint32_t numInstances
= 1,
1059 uint32_t startInstance
= 0)
1066 RDTSC_START(APIDraw
);
1068 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1069 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1071 uint32_t maxVertsPerDraw
= MaxVertsPerDraw(pDC
, numVertices
, topology
);
1072 uint32_t primsPerDraw
= GetNumPrims(topology
, maxVertsPerDraw
);
1073 uint32_t remainingVerts
= numVertices
;
1075 API_STATE
*pState
= &pDC
->pState
->state
;
1076 pState
->topology
= topology
;
1077 pState
->forceFront
= false;
1079 // disable culling for points/lines
1080 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1081 if (topology
== TOP_POINT_LIST
)
1083 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1084 pState
->forceFront
= true;
1088 while (remainingVerts
)
1090 uint32_t numVertsForDraw
= (remainingVerts
< maxVertsPerDraw
) ?
1091 remainingVerts
: maxVertsPerDraw
;
1093 bool isSplitDraw
= (draw
> 0) ? true : false;
1094 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
, isSplitDraw
);
1095 InitDraw(pDC
, isSplitDraw
);
1097 pDC
->FeWork
.type
= DRAW
;
1098 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1100 false, // bEnableCutIndex
1101 pState
->tsState
.tsEnable
,
1102 pState
->gsState
.gsEnable
,
1103 pState
->soState
.soEnable
,
1104 pDC
->pState
->pfnProcessPrims
!= nullptr);
1105 pDC
->FeWork
.desc
.draw
.numVerts
= numVertsForDraw
;
1106 pDC
->FeWork
.desc
.draw
.startVertex
= startVertex
;
1107 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1108 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1109 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1110 pDC
->FeWork
.desc
.draw
.startVertexID
= draw
* maxVertsPerDraw
;
1112 pDC
->cleanupState
= (remainingVerts
== numVertsForDraw
);
1115 QueueDraw(pContext
);
1117 remainingVerts
-= numVertsForDraw
;
1121 // restore culling state
1122 pDC
= GetDrawContext(pContext
);
1123 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1125 RDTSC_STOP(APIDraw
, numVertices
* numInstances
, 0);
1128 //////////////////////////////////////////////////////////////////////////
1130 /// @param hContext - Handle passed back from SwrCreateContext
1131 /// @param topology - Specifies topology for draw.
1132 /// @param startVertex - Specifies start vertex in vertex buffer for draw.
1133 /// @param primCount - Number of vertices.
1136 PRIMITIVE_TOPOLOGY topology
,
1137 uint32_t startVertex
,
1138 uint32_t numVertices
)
1140 DrawInstanced(hContext
, topology
, numVertices
, startVertex
);
1143 //////////////////////////////////////////////////////////////////////////
1144 /// @brief SwrDrawInstanced
1145 /// @param hContext - Handle passed back from SwrCreateContext
1146 /// @param topology - Specifies topology for draw.
1147 /// @param numVertsPerInstance - How many vertices to read sequentially from vertex data.
1148 /// @param numInstances - How many instances to render.
1149 /// @param startVertex - Specifies start vertex for draw. (vertex data)
1150 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1151 void SwrDrawInstanced(
1153 PRIMITIVE_TOPOLOGY topology
,
1154 uint32_t numVertsPerInstance
,
1155 uint32_t numInstances
,
1156 uint32_t startVertex
,
1157 uint32_t startInstance
1160 DrawInstanced(hContext
, topology
, numVertsPerInstance
, startVertex
, numInstances
, startInstance
);
1163 //////////////////////////////////////////////////////////////////////////
1164 /// @brief DrawIndexedInstanced
1165 /// @param hContext - Handle passed back from SwrCreateContext
1166 /// @param topology - Specifies topology for draw.
1167 /// @param numIndices - Number of indices to read sequentially from index buffer.
1168 /// @param indexOffset - Starting index into index buffer.
1169 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1170 /// @param numInstances - Number of instances to render.
1171 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1172 void DrawIndexedInstance(
1174 PRIMITIVE_TOPOLOGY topology
,
1175 uint32_t numIndices
,
1176 uint32_t indexOffset
,
1178 uint32_t numInstances
= 1,
1179 uint32_t startInstance
= 0)
1186 RDTSC_START(APIDrawIndexed
);
1188 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1189 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1190 API_STATE
* pState
= &pDC
->pState
->state
;
1192 uint32_t maxIndicesPerDraw
= MaxVertsPerDraw(pDC
, numIndices
, topology
);
1193 uint32_t primsPerDraw
= GetNumPrims(topology
, maxIndicesPerDraw
);
1194 uint32_t remainingIndices
= numIndices
;
1196 uint32_t indexSize
= 0;
1197 switch (pState
->indexBuffer
.format
)
1199 case R32_UINT
: indexSize
= sizeof(uint32_t); break;
1200 case R16_UINT
: indexSize
= sizeof(uint16_t); break;
1201 case R8_UINT
: indexSize
= sizeof(uint8_t); break;
1207 uint8_t *pIB
= (uint8_t*)pState
->indexBuffer
.pIndices
;
1208 pIB
+= (uint64_t)indexOffset
* (uint64_t)indexSize
;
1210 pState
->topology
= topology
;
1211 pState
->forceFront
= false;
1213 // disable culling for points/lines
1214 uint32_t oldCullMode
= pState
->rastState
.cullMode
;
1215 if (topology
== TOP_POINT_LIST
)
1217 pState
->rastState
.cullMode
= SWR_CULLMODE_NONE
;
1218 pState
->forceFront
= true;
1221 while (remainingIndices
)
1223 uint32_t numIndicesForDraw
= (remainingIndices
< maxIndicesPerDraw
) ?
1224 remainingIndices
: maxIndicesPerDraw
;
1226 // When breaking up draw, we need to obtain new draw context for each iteration.
1227 bool isSplitDraw
= (draw
> 0) ? true : false;
1228 pDC
= GetDrawContext(pContext
, isSplitDraw
);
1229 InitDraw(pDC
, isSplitDraw
);
1231 pDC
->FeWork
.type
= DRAW
;
1232 pDC
->FeWork
.pfnWork
= GetProcessDrawFunc(
1234 pState
->frontendState
.bEnableCutIndex
,
1235 pState
->tsState
.tsEnable
,
1236 pState
->gsState
.gsEnable
,
1237 pState
->soState
.soEnable
,
1238 pDC
->pState
->pfnProcessPrims
!= nullptr);
1239 pDC
->FeWork
.desc
.draw
.pDC
= pDC
;
1240 pDC
->FeWork
.desc
.draw
.numIndices
= numIndicesForDraw
;
1241 pDC
->FeWork
.desc
.draw
.pIB
= (int*)pIB
;
1242 pDC
->FeWork
.desc
.draw
.type
= pDC
->pState
->state
.indexBuffer
.format
;
1244 pDC
->FeWork
.desc
.draw
.numInstances
= numInstances
;
1245 pDC
->FeWork
.desc
.draw
.startInstance
= startInstance
;
1246 pDC
->FeWork
.desc
.draw
.baseVertex
= baseVertex
;
1247 pDC
->FeWork
.desc
.draw
.startPrimID
= draw
* primsPerDraw
;
1249 pDC
->cleanupState
= (remainingIndices
== numIndicesForDraw
);
1252 QueueDraw(pContext
);
1254 pIB
+= maxIndicesPerDraw
* indexSize
;
1255 remainingIndices
-= numIndicesForDraw
;
1259 // restore culling state
1260 pDC
= GetDrawContext(pContext
);
1261 pDC
->pState
->state
.rastState
.cullMode
= oldCullMode
;
1263 RDTSC_STOP(APIDrawIndexed
, numIndices
* numInstances
, 0);
1267 //////////////////////////////////////////////////////////////////////////
1268 /// @brief DrawIndexed
1269 /// @param hContext - Handle passed back from SwrCreateContext
1270 /// @param topology - Specifies topology for draw.
1271 /// @param numIndices - Number of indices to read sequentially from index buffer.
1272 /// @param indexOffset - Starting index into index buffer.
1273 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1274 void SwrDrawIndexed(
1276 PRIMITIVE_TOPOLOGY topology
,
1277 uint32_t numIndices
,
1278 uint32_t indexOffset
,
1282 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
);
1285 //////////////////////////////////////////////////////////////////////////
1286 /// @brief SwrDrawIndexedInstanced
1287 /// @param hContext - Handle passed back from SwrCreateContext
1288 /// @param topology - Specifies topology for draw.
1289 /// @param numIndices - Number of indices to read sequentially from index buffer.
1290 /// @param numInstances - Number of instances to render.
1291 /// @param indexOffset - Starting index into index buffer.
1292 /// @param baseVertex - Vertex in vertex buffer to consider as index "0". Note value is signed.
1293 /// @param startInstance - Which instance to start sequentially fetching from in each buffer (instanced data)
1294 void SwrDrawIndexedInstanced(
1296 PRIMITIVE_TOPOLOGY topology
,
1297 uint32_t numIndices
,
1298 uint32_t numInstances
,
1299 uint32_t indexOffset
,
1301 uint32_t startInstance
)
1303 DrawIndexedInstance(hContext
, topology
, numIndices
, indexOffset
, baseVertex
, numInstances
, startInstance
);
1306 //////////////////////////////////////////////////////////////////////////
1307 /// @brief SwrInvalidateTiles
1308 /// @param hContext - Handle passed back from SwrCreateContext
1309 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to invalidate.
1310 void SwrInvalidateTiles(
1312 uint32_t attachmentMask
)
1319 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1320 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1322 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1323 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1324 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1325 memset(&pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
, 0, sizeof(SWR_RECT
));
1326 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_INVALID
;
1327 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= false;
1328 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= false;
1331 QueueDraw(pContext
);
1334 //////////////////////////////////////////////////////////////////////////
1335 /// @brief SwrDiscardRect
1336 /// @param hContext - Handle passed back from SwrCreateContext
1337 /// @param attachmentMask - The mask specifies which surfaces attached to the hottiles to discard.
1338 /// @param rect - if rect is all zeros, the entire attachment surface will be discarded
1339 void SwrDiscardRect(
1341 uint32_t attachmentMask
,
1349 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1350 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1352 // Queue a load to the hottile
1353 pDC
->FeWork
.type
= DISCARDINVALIDATETILES
;
1354 pDC
->FeWork
.pfnWork
= ProcessDiscardInvalidateTiles
;
1355 pDC
->FeWork
.desc
.discardInvalidateTiles
.attachmentMask
= attachmentMask
;
1356 pDC
->FeWork
.desc
.discardInvalidateTiles
.rect
= rect
;
1357 pDC
->FeWork
.desc
.discardInvalidateTiles
.newTileState
= SWR_TILE_RESOLVED
;
1358 pDC
->FeWork
.desc
.discardInvalidateTiles
.createNewTiles
= true;
1359 pDC
->FeWork
.desc
.discardInvalidateTiles
.fullTilesOnly
= true;
1362 QueueDraw(pContext
);
1365 //////////////////////////////////////////////////////////////////////////
1366 /// @brief SwrDispatch
1367 /// @param hContext - Handle passed back from SwrCreateContext
1368 /// @param threadGroupCountX - Number of thread groups dispatched in X direction
1369 /// @param threadGroupCountY - Number of thread groups dispatched in Y direction
1370 /// @param threadGroupCountZ - Number of thread groups dispatched in Z direction
1373 uint32_t threadGroupCountX
,
1374 uint32_t threadGroupCountY
,
1375 uint32_t threadGroupCountZ
)
1382 RDTSC_START(APIDispatch
);
1383 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1384 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1386 pDC
->isCompute
= true; // This is a compute context.
1388 COMPUTE_DESC
* pTaskData
= (COMPUTE_DESC
*)pDC
->pArena
->AllocAligned(sizeof(COMPUTE_DESC
), 64);
1390 pTaskData
->threadGroupCountX
= threadGroupCountX
;
1391 pTaskData
->threadGroupCountY
= threadGroupCountY
;
1392 pTaskData
->threadGroupCountZ
= threadGroupCountZ
;
1394 uint32_t totalThreadGroups
= threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
;
1395 uint32_t dcIndex
= pDC
->drawId
% KNOB_MAX_DRAWS_IN_FLIGHT
;
1396 pDC
->pDispatch
= &pContext
->pDispatchQueueArray
[dcIndex
];
1397 pDC
->pDispatch
->initialize(totalThreadGroups
, pTaskData
);
1399 QueueDispatch(pContext
);
1400 RDTSC_STOP(APIDispatch
, threadGroupCountX
* threadGroupCountY
* threadGroupCountZ
, 0);
1403 // Deswizzles, converts and stores current contents of the hot tiles to surface
1404 // described by pState
1407 SWR_RENDERTARGET_ATTACHMENT attachment
,
1408 SWR_TILE_STATE postStoreTileState
)
1415 RDTSC_START(APIStoreTiles
);
1417 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1418 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1420 SetupMacroTileScissors(pDC
);
1422 pDC
->FeWork
.type
= STORETILES
;
1423 pDC
->FeWork
.pfnWork
= ProcessStoreTiles
;
1424 pDC
->FeWork
.desc
.storeTiles
.attachment
= attachment
;
1425 pDC
->FeWork
.desc
.storeTiles
.postStoreTileState
= postStoreTileState
;
1428 QueueDraw(pContext
);
1430 RDTSC_STOP(APIStoreTiles
, 0, 0);
1433 void SwrClearRenderTarget(
1436 const float clearColor
[4],
1445 RDTSC_START(APIClearRenderTarget
);
1447 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1449 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1451 SetupMacroTileScissors(pDC
);
1454 flags
.mask
= clearMask
;
1456 pDC
->FeWork
.type
= CLEAR
;
1457 pDC
->FeWork
.pfnWork
= ProcessClear
;
1458 pDC
->FeWork
.desc
.clear
.flags
= flags
;
1459 pDC
->FeWork
.desc
.clear
.clearDepth
= z
;
1460 pDC
->FeWork
.desc
.clear
.clearRTColor
[0] = clearColor
[0];
1461 pDC
->FeWork
.desc
.clear
.clearRTColor
[1] = clearColor
[1];
1462 pDC
->FeWork
.desc
.clear
.clearRTColor
[2] = clearColor
[2];
1463 pDC
->FeWork
.desc
.clear
.clearRTColor
[3] = clearColor
[3];
1464 pDC
->FeWork
.desc
.clear
.clearStencil
= stencil
;
1467 QueueDraw(pContext
);
1469 RDTSC_STOP(APIClearRenderTarget
, 0, pDC
->drawId
);
1472 //////////////////////////////////////////////////////////////////////////
1473 /// @brief Returns a pointer to the private context state for the current
1474 /// draw operation. This is used for external componets such as the
1476 /// SWR is responsible for the allocation of the private context state.
1477 /// @param hContext - Handle passed back from SwrCreateContext
1478 VOID
* SwrGetPrivateContextState(
1481 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1482 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1483 DRAW_STATE
* pState
= pDC
->pState
;
1485 if (pState
->pPrivateState
== nullptr)
1487 pState
->pPrivateState
= pState
->pArena
->AllocAligned(pContext
->privateStateSize
, KNOB_SIMD_WIDTH
*sizeof(float));
1490 return pState
->pPrivateState
;
1493 //////////////////////////////////////////////////////////////////////////
1494 /// @brief Clients can use this to allocate memory for draw/dispatch
1495 /// operations. The memory will automatically be freed once operation
1496 /// has completed. Client can use this to allocate binding tables,
1497 /// etc. needed for shader execution.
1498 /// @param hContext - Handle passed back from SwrCreateContext
1499 /// @param size - Size of allocation
1500 /// @param align - Alignment needed for allocation.
1501 VOID
* SwrAllocDrawContextMemory(
1506 SWR_CONTEXT
* pContext
= GetContext(hContext
);
1507 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1509 return pDC
->pState
->pArena
->AllocAligned(size
, align
);
1512 //////////////////////////////////////////////////////////////////////////
1513 /// @brief Returns pointer to SWR stats.
1514 /// @note The counters are atomically incremented by multiple threads.
1515 /// When calling this, you need to ensure all previous operations
1517 /// @todo If necessary, add a callback to avoid stalling the pipe to
1518 /// sample the counters.
1519 /// @param hContext - Handle passed back from SwrCreateContext
1520 /// @param pStats - SWR will fill this out for caller.
1528 //////////////////////////////////////////////////////////////////////////
1529 /// @brief Enables stats counting
1530 /// @param hContext - Handle passed back from SwrCreateContext
1531 /// @param enable - If true then counts are incremented.
1532 void SwrEnableStats(
1536 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1537 DRAW_CONTEXT
* pDC
= GetDrawContext(pContext
);
1539 pDC
->pState
->state
.enableStats
= enable
;
1542 //////////////////////////////////////////////////////////////////////////
1543 /// @brief Mark end of frame - used for performance profiling
1544 /// @param hContext - Handle passed back from SwrCreateContext
1545 void SWR_API
SwrEndFrame(
1549 SWR_CONTEXT
*pContext
= GetContext(hContext
);
1550 pContext
->frameCount
++;