swr: [rasterizer core] implement InnerConservative input coverage
[mesa.git] / src / gallium / drivers / swr / rasterizer / core / context.h
1 /****************************************************************************
2 * Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * @file context.h
24 *
25 * @brief Definitions for SWR_CONTEXT and DRAW_CONTEXT
26 * The SWR_CONTEXT is our global context and contains the DC ring,
27 * thread state, etc.
28 *
29 * The DRAW_CONTEXT contains all state associated with a draw operation.
30 *
31 ******************************************************************************/
32 #pragma once
33
34 #include <condition_variable>
35 #include <algorithm>
36
37 #include "core/api.h"
38 #include "core/utils.h"
39 #include "core/arena.h"
40 #include "core/fifo.hpp"
41 #include "core/knobs.h"
42 #include "common/simdintrin.h"
43 #include "core/threads.h"
44 #include "ringbuffer.h"
45
46 // x.8 fixed point precision values
47 #define FIXED_POINT_SHIFT 8
48 #define FIXED_POINT_SCALE 256
49
50 // x.16 fixed point precision values
51 #define FIXED_POINT16_SHIFT 16
52 #define FIXED_POINT16_SCALE 65536
53
54 struct SWR_CONTEXT;
55 struct DRAW_CONTEXT;
56
57 struct TRI_FLAGS
58 {
59 uint32_t frontFacing : 1;
60 uint32_t yMajor : 1;
61 uint32_t coverageMask : (SIMD_TILE_X_DIM * SIMD_TILE_Y_DIM);
62 uint32_t reserved : 32 - 1 - 1 - (SIMD_TILE_X_DIM * SIMD_TILE_Y_DIM);
63 float pointSize;
64 uint32_t primID;
65 uint32_t renderTargetArrayIndex;
66 };
67
68 //////////////////////////////////////////////////////////////////////////
69 /// SWR_TRIANGLE_DESC
70 /////////////////////////////////////////////////////////////////////////
71 struct SWR_TRIANGLE_DESC
72 {
73 float I[3];
74 float J[3];
75 float Z[3];
76 float OneOverW[3];
77 float recipDet;
78
79 float *pRecipW;
80 float *pAttribs;
81 float *pPerspAttribs;
82 float *pSamplePos;
83 float *pUserClipBuffer;
84
85 uint64_t coverageMask[SWR_MAX_NUM_MULTISAMPLES];
86 uint64_t innerCoverageMask; // Conservative rasterization inner coverage: marked covered if entire pixel is covered
87 uint64_t anyCoveredSamples;
88
89 TRI_FLAGS triFlags;
90 };
91
92 struct TRIANGLE_WORK_DESC
93 {
94 float *pTriBuffer;
95 float *pAttribs;
96 float *pUserClipBuffer;
97 uint32_t numAttribs;
98 TRI_FLAGS triFlags;
99 };
100
101 union CLEAR_FLAGS
102 {
103 struct
104 {
105 uint32_t mask : 3;
106 };
107 uint32_t bits;
108 };
109
110 struct CLEAR_DESC
111 {
112 CLEAR_FLAGS flags;
113 float clearRTColor[4]; // RGBA_32F
114 float clearDepth; // [0..1]
115 uint8_t clearStencil;
116 };
117
118 struct DISCARD_INVALIDATE_TILES_DESC
119 {
120 uint32_t attachmentMask;
121 SWR_RECT rect;
122 SWR_TILE_STATE newTileState;
123 bool createNewTiles;
124 bool fullTilesOnly;
125 };
126
127 struct SYNC_DESC
128 {
129 PFN_CALLBACK_FUNC pfnCallbackFunc;
130 uint64_t userData;
131 uint64_t userData2;
132 uint64_t userData3;
133 };
134
135 struct QUERY_DESC
136 {
137 SWR_STATS* pStats;
138 };
139
140 struct STORE_TILES_DESC
141 {
142 SWR_RENDERTARGET_ATTACHMENT attachment;
143 SWR_TILE_STATE postStoreTileState;
144 };
145
146 struct COMPUTE_DESC
147 {
148 uint32_t threadGroupCountX;
149 uint32_t threadGroupCountY;
150 uint32_t threadGroupCountZ;
151 };
152
153 typedef void(*PFN_WORK_FUNC)(DRAW_CONTEXT* pDC, uint32_t workerId, uint32_t macroTile, void* pDesc);
154
155 enum WORK_TYPE
156 {
157 SYNC,
158 DRAW,
159 CLEAR,
160 DISCARDINVALIDATETILES,
161 STORETILES,
162 QUERYSTATS,
163 };
164
165 struct BE_WORK
166 {
167 WORK_TYPE type;
168 PFN_WORK_FUNC pfnWork;
169 union
170 {
171 SYNC_DESC sync;
172 TRIANGLE_WORK_DESC tri;
173 CLEAR_DESC clear;
174 DISCARD_INVALIDATE_TILES_DESC discardInvalidateTiles;
175 STORE_TILES_DESC storeTiles;
176 QUERY_DESC queryStats;
177 } desc;
178 };
179
180 struct DRAW_WORK
181 {
182 DRAW_CONTEXT* pDC;
183 union
184 {
185 uint32_t numIndices; // DrawIndexed: Number of indices for draw.
186 uint32_t numVerts; // Draw: Number of verts (triangles, lines, etc)
187 };
188 union
189 {
190 const int32_t* pIB; // DrawIndexed: App supplied indices
191 uint32_t startVertex; // Draw: Starting vertex in VB to render from.
192 };
193 int32_t baseVertex;
194 uint32_t numInstances; // Number of instances
195 uint32_t startInstance; // Instance offset
196 uint32_t startPrimID; // starting primitiveID for this draw batch
197 uint32_t startVertexID; // starting VertexID for this draw batch (only needed for non-indexed draws)
198 SWR_FORMAT type; // index buffer type
199 };
200
201 typedef void(*PFN_FE_WORK_FUNC)(SWR_CONTEXT* pContext, DRAW_CONTEXT* pDC, uint32_t workerId, void* pDesc);
202 struct FE_WORK
203 {
204 WORK_TYPE type;
205 PFN_FE_WORK_FUNC pfnWork;
206 union
207 {
208 SYNC_DESC sync;
209 DRAW_WORK draw;
210 CLEAR_DESC clear;
211 DISCARD_INVALIDATE_TILES_DESC discardInvalidateTiles;
212 STORE_TILES_DESC storeTiles;
213 QUERY_DESC queryStats;
214 } desc;
215 };
216
217 struct GUARDBAND
218 {
219 float left, right, top, bottom;
220 };
221
222 struct PA_STATE;
223
224 // function signature for pipeline stages that execute after primitive assembly
225 typedef void(*PFN_PROCESS_PRIMS)(DRAW_CONTEXT *pDC, PA_STATE& pa, uint32_t workerId, simdvector prims[],
226 uint32_t primMask, simdscalari primID);
227
228 OSALIGNLINE(struct) API_STATE
229 {
230 // Vertex Buffers
231 SWR_VERTEX_BUFFER_STATE vertexBuffers[KNOB_NUM_STREAMS];
232
233 // Index Buffer
234 SWR_INDEX_BUFFER_STATE indexBuffer;
235
236 // FS - Fetch Shader State
237 PFN_FETCH_FUNC pfnFetchFunc;
238
239 // VS - Vertex Shader State
240 PFN_VERTEX_FUNC pfnVertexFunc;
241
242 // GS - Geometry Shader State
243 PFN_GS_FUNC pfnGsFunc;
244 SWR_GS_STATE gsState;
245
246 // CS - Compute Shader
247 PFN_CS_FUNC pfnCsFunc;
248 uint32_t totalThreadsInGroup;
249 uint32_t totalSpillFillSize;
250
251 // FE - Frontend State
252 SWR_FRONTEND_STATE frontendState;
253
254 // SOS - Streamout Shader State
255 PFN_SO_FUNC pfnSoFunc[MAX_SO_STREAMS];
256
257 // Streamout state
258 SWR_STREAMOUT_STATE soState;
259 mutable SWR_STREAMOUT_BUFFER soBuffer[MAX_SO_STREAMS];
260
261 // Tessellation State
262 PFN_HS_FUNC pfnHsFunc;
263 PFN_DS_FUNC pfnDsFunc;
264 SWR_TS_STATE tsState;
265
266 // Number of attributes used by the frontend (vs, so, gs)
267 uint32_t feNumAttributes;
268
269 PRIMITIVE_TOPOLOGY topology;
270 bool forceFront;
271
272 // RS - Rasterizer State
273 SWR_RASTSTATE rastState;
274 // floating point multisample offsets
275 float samplePos[SWR_MAX_NUM_MULTISAMPLES * 2];
276
277 GUARDBAND gbState;
278
279 SWR_VIEWPORT vp[KNOB_NUM_VIEWPORTS_SCISSORS];
280 SWR_VIEWPORT_MATRIX vpMatrix[KNOB_NUM_VIEWPORTS_SCISSORS];
281
282 BBOX scissorRects[KNOB_NUM_VIEWPORTS_SCISSORS];
283 BBOX scissorInFixedPoint;
284
285 // Backend state
286 SWR_BACKEND_STATE backendState;
287
288 // PS - Pixel shader state
289 SWR_PS_STATE psState;
290
291 SWR_DEPTH_STENCIL_STATE depthStencilState;
292
293 // OM - Output Merger State
294 SWR_BLEND_STATE blendState;
295 PFN_BLEND_JIT_FUNC pfnBlendFunc[SWR_NUM_RENDERTARGETS];
296
297 // Stats are incremented when this is true.
298 bool enableStats;
299
300 struct
301 {
302 uint32_t colorHottileEnable : 8;
303 uint32_t depthHottileEnable: 1;
304 uint32_t stencilHottileEnable : 1;
305 };
306
307 PFN_QUANTIZE_DEPTH pfnQuantizeDepth;
308 };
309
310 class MacroTileMgr;
311 class DispatchQueue;
312
313 struct RenderOutputBuffers
314 {
315 uint8_t* pColor[SWR_NUM_RENDERTARGETS];
316 uint8_t* pDepth;
317 uint8_t* pStencil;
318 };
319
320 // Plane equation A/B/C coeffs used to evaluate I/J barycentric coords
321 struct BarycentricCoeffs
322 {
323 simdscalar vIa;
324 simdscalar vIb;
325 simdscalar vIc;
326
327 simdscalar vJa;
328 simdscalar vJb;
329 simdscalar vJc;
330
331 simdscalar vZa;
332 simdscalar vZb;
333 simdscalar vZc;
334
335 simdscalar vRecipDet;
336
337 simdscalar vAOneOverW;
338 simdscalar vBOneOverW;
339 simdscalar vCOneOverW;
340 };
341
342 // pipeline function pointer types
343 typedef void(*PFN_BACKEND_FUNC)(DRAW_CONTEXT*, uint32_t, uint32_t, uint32_t, SWR_TRIANGLE_DESC&, RenderOutputBuffers&);
344 typedef void(*PFN_OUTPUT_MERGER)(SWR_PS_CONTEXT &, uint8_t* (&)[SWR_NUM_RENDERTARGETS], uint32_t, const SWR_BLEND_STATE*,
345 const PFN_BLEND_JIT_FUNC (&)[SWR_NUM_RENDERTARGETS], simdscalar&, simdscalar);
346 typedef void(*PFN_CALC_PIXEL_BARYCENTRICS)(const BarycentricCoeffs&, SWR_PS_CONTEXT &);
347 typedef void(*PFN_CALC_SAMPLE_BARYCENTRICS)(const BarycentricCoeffs&, SWR_PS_CONTEXT&);
348 typedef void(*PFN_CALC_CENTROID_BARYCENTRICS)(const BarycentricCoeffs&, SWR_PS_CONTEXT &, const uint64_t *const, const uint32_t,
349 const simdscalar, const simdscalar);
350
351 struct BACKEND_FUNCS
352 {
353 PFN_BACKEND_FUNC pfnBackend;
354 };
355
356 // Draw State
357 struct DRAW_STATE
358 {
359 API_STATE state;
360
361 void* pPrivateState; // Its required the driver sets this up for each draw.
362
363 // pipeline function pointers, filled in by API thread when setting up the draw
364 BACKEND_FUNCS backendFuncs;
365 PFN_PROCESS_PRIMS pfnProcessPrims;
366
367 CachingArena* pArena; // This should only be used by API thread.
368 };
369
370 // Draw Context
371 // The api thread sets up a draw context that exists for the life of the draw.
372 // This draw context maintains all of the state needed for the draw operation.
373 struct DRAW_CONTEXT
374 {
375 SWR_CONTEXT* pContext;
376 union
377 {
378 MacroTileMgr* pTileMgr;
379 DispatchQueue* pDispatch; // Queue for thread groups. (isCompute)
380 };
381 DRAW_STATE* pState;
382 CachingArena* pArena;
383
384 uint32_t drawId;
385 bool dependent;
386 bool isCompute; // Is this DC a compute context?
387 bool cleanupState; // True if this is the last draw using an entry in the state ring.
388 volatile bool doneFE; // Is FE work done for this draw?
389
390 FE_WORK FeWork;
391
392 volatile OSALIGNLINE(uint32_t) FeLock;
393 volatile int64_t threadsDone;
394
395 SYNC_DESC retireCallback; // Call this func when this DC is retired.
396 };
397
398 static_assert((sizeof(DRAW_CONTEXT) & 63) == 0, "Invalid size for DRAW_CONTEXT");
399
400 INLINE const API_STATE& GetApiState(const DRAW_CONTEXT* pDC)
401 {
402 SWR_ASSERT(pDC != nullptr);
403 SWR_ASSERT(pDC->pState != nullptr);
404
405 return pDC->pState->state;
406 }
407
408 INLINE void* GetPrivateState(const DRAW_CONTEXT* pDC)
409 {
410 SWR_ASSERT(pDC != nullptr);
411 SWR_ASSERT(pDC->pState != nullptr);
412
413 return pDC->pState->pPrivateState;
414 }
415
416 class HotTileMgr;
417
418 struct SWR_CONTEXT
419 {
420 // Draw Context Ring
421 // Each draw needs its own state in order to support mulitple draws in flight across multiple threads.
422 // We maintain N draw contexts configured as a ring. The size of the ring limits the maximum number
423 // of draws that can be in flight at any given time.
424 //
425 // Description:
426 // 1. State - When an application first sets state we'll request a new draw context to use.
427 // a. If there are no available draw contexts then we'll have to wait until one becomes free.
428 // b. If one is available then set pCurDrawContext to point to it and mark it in use.
429 // c. All state calls set state on pCurDrawContext.
430 // 2. Draw - Creates submits a work item that is associated with current draw context.
431 // a. Set pPrevDrawContext = pCurDrawContext
432 // b. Set pCurDrawContext to NULL.
433 // 3. State - When an applications sets state after draw
434 // a. Same as step 1.
435 // b. State is copied from prev draw context to current.
436 RingBuffer<DRAW_CONTEXT> dcRing;
437
438 DRAW_CONTEXT *pCurDrawContext; // This points to DC entry in ring for an unsubmitted draw.
439 DRAW_CONTEXT *pPrevDrawContext; // This points to DC entry for the previous context submitted that we can copy state from.
440
441 MacroTileMgr* pMacroTileManagerArray;
442 DispatchQueue* pDispatchQueueArray;
443
444 // Draw State Ring
445 // When draw are very large (lots of primitives) then the API thread will break these up.
446 // These split draws all have identical state. So instead of storing the state directly
447 // in the Draw Context (DC) we instead store it in a Draw State (DS). This allows multiple DCs
448 // to reference a single entry in the DS ring.
449 RingBuffer<DRAW_STATE> dsRing;
450
451 uint32_t curStateId; // Current index to the next available entry in the DS ring.
452
453 uint32_t NumWorkerThreads;
454 uint32_t NumFEThreads;
455 uint32_t NumBEThreads;
456
457 THREAD_POOL threadPool; // Thread pool associated with this context
458
459 std::condition_variable FifosNotEmpty;
460 std::mutex WaitLock;
461
462 DRIVER_TYPE driverType;
463
464 uint32_t privateStateSize;
465
466 HotTileMgr *pHotTileMgr;
467
468 // tile load/store functions, passed in at create context time
469 PFN_LOAD_TILE pfnLoadTile;
470 PFN_STORE_TILE pfnStoreTile;
471 PFN_CLEAR_TILE pfnClearTile;
472
473 // Global Stats
474 SWR_STATS stats[KNOB_MAX_NUM_THREADS];
475
476 // Scratch space for workers.
477 uint8_t* pScratch[KNOB_MAX_NUM_THREADS];
478
479 CachingAllocator cachingArenaAllocator;
480 uint32_t frameCount;
481 };
482
483 void WaitForDependencies(SWR_CONTEXT *pContext, uint64_t drawId);
484 void WakeAllThreads(SWR_CONTEXT *pContext);
485
486 #define UPDATE_STAT(name, count) if (GetApiState(pDC).enableStats) { pContext->stats[workerId].name += count; }
487 #define SET_STAT(name, count) if (GetApiState(pDC).enableStats) { pContext->stats[workerId].name = count; }