1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #include "Renderer.hpp"
17 #include "Clipper.hpp"
19 #include "FrameBuffer.hpp"
21 #include "Surface.hpp"
23 #include "Primitive.hpp"
24 #include "Polygon.hpp"
25 #include "SwiftConfig.hpp"
26 #include "MutexLock.hpp"
29 #include "Resource.hpp"
30 #include "Constants.hpp"
32 #include "Reactor/Reactor.hpp"
36 bool disableServer = true;
39 unsigned int minPrimitives = 1;
40 unsigned int maxPrimitives = 1 << 21;
45 extern bool halfIntegerCoordinates; // Pixel centers are not at integer coordinates
46 extern bool symmetricNormalizedDepth; // [-1, 1] instead of [0, 1]
47 extern bool booleanFaceRegister;
48 extern bool fullPixelPositionRegister;
49 extern bool leadingVertexFirst; // Flat shading uses first vertex, else last
50 extern bool secondaryColor; // Specular lighting is applied after texturing
52 extern bool forceWindowed;
53 extern bool complementaryDepthBuffer;
54 extern bool postBlendSRGB;
55 extern bool exactColorRounding;
56 extern TransparencyAntialiasing transparencyAntialiasing;
57 extern bool forceClearRegisters;
59 extern bool precacheVertex;
60 extern bool precacheSetup;
61 extern bool precachePixel;
68 TranscendentalPrecision logPrecision = ACCURATE;
69 TranscendentalPrecision expPrecision = ACCURATE;
70 TranscendentalPrecision rcpPrecision = ACCURATE;
71 TranscendentalPrecision rsqPrecision = ACCURATE;
72 bool perspectiveCorrection = true;
84 vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
88 psDirtyConstF = FRAGMENT_UNIFORM_VECTORS;
94 data = (DrawData*)allocate(sizeof(DrawData));
95 data->constants = &constants;
105 Renderer::Renderer(Context *context, Conventions conventions, bool exactColorRounding) : VertexProcessor(context), PixelProcessor(context), SetupProcessor(context), context(context), viewport()
107 sw::halfIntegerCoordinates = conventions.halfIntegerCoordinates;
108 sw::symmetricNormalizedDepth = conventions.symmetricNormalizedDepth;
109 sw::booleanFaceRegister = conventions.booleanFaceRegister;
110 sw::fullPixelPositionRegister = conventions.fullPixelPositionRegister;
111 sw::leadingVertexFirst = conventions.leadingVertexFirst;
112 sw::secondaryColor = conventions.secondaryColor;
113 sw::exactColorRounding = exactColorRounding;
115 setRenderTarget(0, 0);
116 clipper = new Clipper(symmetricNormalizedDepth);
118 updateViewMatrix = true;
119 updateBaseMatrix = true;
120 updateProjectionMatrix = true;
121 updateClipPlanes = true;
127 for(int i = 0; i < 16; i++)
137 resumeApp = new Event();
145 for(int i = 0; i < 16; i++)
147 triangleBatch[i] = 0;
148 primitiveBatch[i] = 0;
151 for(int draw = 0; draw < DRAW_COUNT; draw++)
153 drawCall[draw] = new DrawCall();
154 drawList[draw] = drawCall[draw];
157 for(int unit = 0; unit < 16; unit++)
159 primitiveProgress[unit].init();
162 for(int cluster = 0; cluster < 16; cluster++)
164 pixelProgress[cluster].init();
169 swiftConfig = new SwiftConfig(disableServer);
170 updateConfiguration(true);
172 sync = new Resource(0);
175 Renderer::~Renderer()
185 for(int draw = 0; draw < DRAW_COUNT; draw++)
187 delete drawCall[draw];
193 // This object has to be mem aligned
194 void* Renderer::operator new(size_t size)
\r
196 ASSERT(size == sizeof(Renderer)); // This operator can't be called from a derived class
\r
197 return sw::allocate(sizeof(Renderer), 16);
\r
200 void Renderer::operator delete(void * mem)
\r
202 sw::deallocate(mem);
\r
205 void Renderer::clear(void *pixel, Format format, Surface *dest, const SliceRect &dRect, unsigned int rgbaMask)
207 blitter.clear(pixel, format, dest, dRect, rgbaMask);
210 void Renderer::blit(Surface *source, const SliceRect &sRect, Surface *dest, const SliceRect &dRect, bool filter, bool isStencil)
212 blitter.blit(source, sRect, dest, dRect, filter, isStencil);
215 void Renderer::blit3D(Surface *source, Surface *dest)
217 blitter.blit3D(source, dest);
220 void Renderer::draw(DrawType drawType, unsigned int indexOffset, unsigned int count, bool update)
223 if(count < minPrimitives || count > maxPrimitives)
229 context->drawType = drawType;
231 updateConfiguration();
234 int ss = context->getSuperSampleCount();
235 int ms = context->getMultiSampleCount();
237 for(int q = 0; q < ss; q++)
239 unsigned int oldMultiSampleMask = context->multiSampleMask;
240 context->multiSampleMask = (context->sampleMask >> (ms * q)) & ((unsigned)0xFFFFFFFF >> (32 - ms));
242 if(!context->multiSampleMask)
247 sync->lock(sw::PRIVATE);
249 if(update || oldMultiSampleMask != context->multiSampleMask)
251 vertexState = VertexProcessor::update(drawType);
252 setupState = SetupProcessor::update();
253 pixelState = PixelProcessor::update();
255 vertexRoutine = VertexProcessor::routine(vertexState);
256 setupRoutine = SetupProcessor::routine(setupState);
257 pixelRoutine = PixelProcessor::routine(pixelState);
260 int batch = batchSize / ms;
262 int (Renderer::*setupPrimitives)(int batch, int count);
264 if(context->isDrawTriangle())
266 switch(context->fillMode)
269 setupPrimitives = &Renderer::setupSolidTriangles;
272 setupPrimitives = &Renderer::setupWireframeTriangle;
276 setupPrimitives = &Renderer::setupVertexTriangle;
284 else if(context->isDrawLine())
286 setupPrimitives = &Renderer::setupLines;
290 setupPrimitives = &Renderer::setupPoints;
297 for(int i = 0; i < DRAW_COUNT; i++)
299 if(drawCall[i]->references == -1)
302 drawList[nextDraw % DRAW_COUNT] = draw;
315 DrawData *data = draw->data;
317 if(queries.size() != 0)
319 draw->queries = new std::list<Query*>();
320 bool includePrimitivesWrittenQueries = vertexState.transformFeedbackQueryEnabled && vertexState.transformFeedbackEnabled;
321 for(std::list<Query*>::iterator query = queries.begin(); query != queries.end(); query++)
324 if(includePrimitivesWrittenQueries || (q->type != Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN))
326 atomicIncrement(&(q->reference));
327 draw->queries->push_back(q);
332 draw->drawType = drawType;
333 draw->batchSize = batch;
335 vertexRoutine->bind();
336 setupRoutine->bind();
337 pixelRoutine->bind();
339 draw->vertexRoutine = vertexRoutine;
340 draw->setupRoutine = setupRoutine;
341 draw->pixelRoutine = pixelRoutine;
342 draw->vertexPointer = (VertexProcessor::RoutinePointer)vertexRoutine->getEntry();
343 draw->setupPointer = (SetupProcessor::RoutinePointer)setupRoutine->getEntry();
344 draw->pixelPointer = (PixelProcessor::RoutinePointer)pixelRoutine->getEntry();
345 draw->setupPrimitives = setupPrimitives;
346 draw->setupState = setupState;
348 for(int i = 0; i < MAX_VERTEX_INPUTS; i++)
350 draw->vertexStream[i] = context->input[i].resource;
351 data->input[i] = context->input[i].buffer;
352 data->stride[i] = context->input[i].stride;
354 if(draw->vertexStream[i])
356 draw->vertexStream[i]->lock(PUBLIC, PRIVATE);
360 if(context->indexBuffer)
362 data->indices = (unsigned char*)context->indexBuffer->lock(PUBLIC, PRIVATE) + indexOffset;
365 draw->indexBuffer = context->indexBuffer;
367 for(int sampler = 0; sampler < TOTAL_IMAGE_UNITS; sampler++)
369 draw->texture[sampler] = 0;
372 for(int sampler = 0; sampler < TEXTURE_IMAGE_UNITS; sampler++)
374 if(pixelState.sampler[sampler].textureType != TEXTURE_NULL)
376 draw->texture[sampler] = context->texture[sampler];
377 draw->texture[sampler]->lock(PUBLIC, isReadWriteTexture(sampler) ? MANAGED : PRIVATE); // If the texure is both read and written, use the same read/write lock as render targets
379 data->mipmap[sampler] = context->sampler[sampler].getTextureData();
383 if(context->pixelShader)
385 if(draw->psDirtyConstF)
387 memcpy(&data->ps.cW, PixelProcessor::cW, sizeof(word4) * 4 * (draw->psDirtyConstF < 8 ? draw->psDirtyConstF : 8));
388 memcpy(&data->ps.c, PixelProcessor::c, sizeof(float4) * draw->psDirtyConstF);
389 draw->psDirtyConstF = 0;
392 if(draw->psDirtyConstI)
394 memcpy(&data->ps.i, PixelProcessor::i, sizeof(int4) * draw->psDirtyConstI);
395 draw->psDirtyConstI = 0;
398 if(draw->psDirtyConstB)
400 memcpy(&data->ps.b, PixelProcessor::b, sizeof(bool) * draw->psDirtyConstB);
401 draw->psDirtyConstB = 0;
404 PixelProcessor::lockUniformBuffers(data->ps.u, draw->pUniformBuffers);
408 for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
410 draw->pUniformBuffers[i] = nullptr;
414 if(context->pixelShaderVersion() <= 0x0104)
416 for(int stage = 0; stage < 8; stage++)
418 if(pixelState.textureStage[stage].stageOperation != TextureStage::STAGE_DISABLE || context->pixelShader)
420 data->textureStage[stage] = context->textureStage[stage].uniforms;
426 if(context->vertexShader)
428 if(context->vertexShader->getVersion() >= 0x0300)
430 for(int sampler = 0; sampler < VERTEX_TEXTURE_IMAGE_UNITS; sampler++)
432 if(vertexState.samplerState[sampler].textureType != TEXTURE_NULL)
434 draw->texture[TEXTURE_IMAGE_UNITS + sampler] = context->texture[TEXTURE_IMAGE_UNITS + sampler];
435 draw->texture[TEXTURE_IMAGE_UNITS + sampler]->lock(PUBLIC, PRIVATE);
437 data->mipmap[TEXTURE_IMAGE_UNITS + sampler] = context->sampler[TEXTURE_IMAGE_UNITS + sampler].getTextureData();
442 if(draw->vsDirtyConstF)
444 memcpy(&data->vs.c, VertexProcessor::c, sizeof(float4) * draw->vsDirtyConstF);
445 draw->vsDirtyConstF = 0;
448 if(draw->vsDirtyConstI)
450 memcpy(&data->vs.i, VertexProcessor::i, sizeof(int4) * draw->vsDirtyConstI);
451 draw->vsDirtyConstI = 0;
454 if(draw->vsDirtyConstB)
456 memcpy(&data->vs.b, VertexProcessor::b, sizeof(bool) * draw->vsDirtyConstB);
457 draw->vsDirtyConstB = 0;
460 if(context->vertexShader->isInstanceIdDeclared())
462 data->instanceID = context->instanceID;
465 VertexProcessor::lockUniformBuffers(data->vs.u, draw->vUniformBuffers);
466 VertexProcessor::lockTransformFeedbackBuffers(data->vs.t, data->vs.reg, data->vs.row, data->vs.col, data->vs.str, draw->transformFeedbackBuffers);
472 draw->vsDirtyConstF = VERTEX_UNIFORM_VECTORS + 1;
473 draw->vsDirtyConstI = 16;
474 draw->vsDirtyConstB = 16;
476 for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
478 draw->vUniformBuffers[i] = nullptr;
481 for(int i = 0; i < MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS; i++)
483 draw->transformFeedbackBuffers[i] = nullptr;
487 if(pixelState.stencilActive)
489 data->stencil[0] = stencil;
490 data->stencil[1] = stencilCCW;
493 if(pixelState.fogActive)
498 if(setupState.isDrawPoint)
503 data->lineWidth = context->lineWidth;
505 data->factor = factor;
507 if(pixelState.transparencyAntialiasing == TRANSPARENCY_ALPHA_TO_COVERAGE)
509 float ref = context->alphaReference * (1.0f / 255.0f);
510 float margin = sw::min(ref, 1.0f - ref);
514 data->a2c0 = replicate(ref - margin * 0.6f);
515 data->a2c1 = replicate(ref - margin * 0.2f);
516 data->a2c2 = replicate(ref + margin * 0.2f);
517 data->a2c3 = replicate(ref + margin * 0.6f);
521 data->a2c0 = replicate(ref - margin * 0.3f);
522 data->a2c1 = replicate(ref + margin * 0.3f);
527 if(pixelState.occlusionEnabled)
529 for(int cluster = 0; cluster < clusterCount; cluster++)
531 data->occlusion[cluster] = 0;
536 for(int cluster = 0; cluster < clusterCount; cluster++)
538 for(int i = 0; i < PERF_TIMERS; i++)
540 data->cycles[i][cluster] = 0;
547 float W = 0.5f * viewport.width;
548 float H = 0.5f * viewport.height;
549 float X0 = viewport.x0 + W;
550 float Y0 = viewport.y0 + H;
551 float N = viewport.minZ;
552 float F = viewport.maxZ;
555 if(context->isDrawTriangle(false))
560 if(complementaryDepthBuffer)
566 static const float X[5][16] = // Fragment offsets
568 {+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 1 sample
569 {-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 2 samples
570 {-0.3000f, +0.1000f, +0.3000f, -0.1000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 4 samples
571 {+0.1875f, -0.3125f, +0.3125f, -0.4375f, -0.0625f, +0.4375f, +0.0625f, -0.1875f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 8 samples
572 {+0.2553f, -0.1155f, +0.1661f, -0.1828f, +0.2293f, -0.4132f, -0.1773f, -0.0577f, +0.3891f, -0.4656f, +0.4103f, +0.4248f, -0.2109f, +0.3966f, -0.2664f, -0.3872f} // 16 samples
575 static const float Y[5][16] = // Fragment offsets
577 {+0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 1 sample
578 {-0.2500f, +0.2500f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 2 samples
579 {-0.1000f, -0.3000f, +0.1000f, +0.3000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 4 samples
580 {-0.4375f, -0.3125f, -0.1875f, -0.0625f, +0.0625f, +0.1875f, +0.3125f, +0.4375f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f, +0.0000f}, // 8 samples
581 {-0.4503f, +0.1883f, +0.3684f, -0.4668f, -0.0690f, -0.1315f, +0.4999f, +0.0728f, +0.1070f, -0.3086f, +0.3725f, -0.1547f, -0.1102f, -0.3588f, +0.1789f, +0.0269f} // 16 samples
584 int s = sw::log2(ss);
586 data->Wx16 = replicate(W * 16);
587 data->Hx16 = replicate(H * 16);
588 data->X0x16 = replicate(X0 * 16 - 8);
589 data->Y0x16 = replicate(Y0 * 16 - 8);
590 data->XXXX = replicate(X[s][q] / W);
591 data->YYYY = replicate(Y[s][q] / H);
592 data->halfPixelX = replicate(0.5f / W);
593 data->halfPixelY = replicate(0.5f / H);
594 data->viewportHeight = abs(viewport.height);
595 data->slopeDepthBias = slopeDepthBias;
596 data->depthRange = Z;
598 draw->clipFlags = clipFlags;
602 if(clipFlags & Clipper::CLIP_PLANE0) data->clipPlane[0] = clipPlane[0];
603 if(clipFlags & Clipper::CLIP_PLANE1) data->clipPlane[1] = clipPlane[1];
604 if(clipFlags & Clipper::CLIP_PLANE2) data->clipPlane[2] = clipPlane[2];
605 if(clipFlags & Clipper::CLIP_PLANE3) data->clipPlane[3] = clipPlane[3];
606 if(clipFlags & Clipper::CLIP_PLANE4) data->clipPlane[4] = clipPlane[4];
607 if(clipFlags & Clipper::CLIP_PLANE5) data->clipPlane[5] = clipPlane[5];
613 for(int index = 0; index < RENDERTARGETS; index++)
615 draw->renderTarget[index] = context->renderTarget[index];
617 if(draw->renderTarget[index])
619 data->colorBuffer[index] = (unsigned int*)context->renderTarget[index]->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
620 data->colorPitchB[index] = context->renderTarget[index]->getInternalPitchB();
621 data->colorSliceB[index] = context->renderTarget[index]->getInternalSliceB();
625 draw->depthBuffer = context->depthBuffer;
626 draw->stencilBuffer = context->stencilBuffer;
628 if(draw->depthBuffer)
630 data->depthBuffer = (float*)context->depthBuffer->lockInternal(0, 0, q * ms, LOCK_READWRITE, MANAGED);
631 data->depthPitchB = context->depthBuffer->getInternalPitchB();
632 data->depthSliceB = context->depthBuffer->getInternalSliceB();
635 if(draw->stencilBuffer)
637 data->stencilBuffer = (unsigned char*)context->stencilBuffer->lockStencil(0, 0, q * ms, MANAGED);
638 data->stencilPitchB = context->stencilBuffer->getStencilPitchB();
639 data->stencilSliceB = context->stencilBuffer->getStencilSliceB();
645 data->scissorX0 = scissor.x0;
646 data->scissorX1 = scissor.x1;
647 data->scissorY0 = scissor.y0;
648 data->scissorY1 = scissor.y1;
654 draw->references = (count + batch - 1) / batch;
656 schedulerMutex.lock();
658 schedulerMutex.unlock();
667 task[0].type = Task::RESUME;
672 else // Use main thread for draw execution
675 task[0].type = Task::RESUME;
682 void Renderer::threadFunction(void *parameters)
684 Renderer *renderer = static_cast<Parameters*>(parameters)->renderer;
685 int threadIndex = static_cast<Parameters*>(parameters)->threadIndex;
687 if(logPrecision < IEEE)
689 CPUID::setFlushToZero(true);
690 CPUID::setDenormalsAreZero(true);
693 renderer->threadLoop(threadIndex);
696 void Renderer::threadLoop(int threadIndex)
700 taskLoop(threadIndex);
702 suspend[threadIndex]->signal();
703 resume[threadIndex]->wait();
707 void Renderer::taskLoop(int threadIndex)
709 while(task[threadIndex].type != Task::SUSPEND)
711 scheduleTask(threadIndex);
712 executeTask(threadIndex);
716 void Renderer::findAvailableTasks()
719 for(int cluster = 0; cluster < clusterCount; cluster++)
721 if(!pixelProgress[cluster].executing)
723 for(int unit = 0; unit < unitCount; unit++)
725 if(primitiveProgress[unit].references > 0) // Contains processed primitives
727 if(pixelProgress[cluster].drawCall == primitiveProgress[unit].drawCall)
729 if(pixelProgress[cluster].processedPrimitives == primitiveProgress[unit].firstPrimitive) // Previous primitives have been rendered
731 Task &task = taskQueue[qHead];
732 task.type = Task::PIXELS;
733 task.primitiveUnit = unit;
734 task.pixelCluster = cluster;
736 pixelProgress[cluster].executing = true;
738 // Commit to the task queue
739 qHead = (qHead + 1) % 32;
750 // Find primitive tasks
751 if(currentDraw == nextDraw)
753 return; // No more primitives to process
756 for(int unit = 0; unit < unitCount; unit++)
758 DrawCall *draw = drawList[currentDraw % DRAW_COUNT];
760 if(draw->primitive >= draw->count)
764 if(currentDraw == nextDraw)
766 return; // No more primitives to process
769 draw = drawList[currentDraw % DRAW_COUNT];
772 if(!primitiveProgress[unit].references) // Task not already being executed and not still in use by a pixel unit
774 int primitive = draw->primitive;
775 int count = draw->count;
776 int batch = draw->batchSize;
778 primitiveProgress[unit].drawCall = currentDraw;
779 primitiveProgress[unit].firstPrimitive = primitive;
780 primitiveProgress[unit].primitiveCount = count - primitive >= batch ? batch : count - primitive;
782 draw->primitive += batch;
784 Task &task = taskQueue[qHead];
785 task.type = Task::PRIMITIVES;
786 task.primitiveUnit = unit;
788 primitiveProgress[unit].references = -1;
790 // Commit to the task queue
791 qHead = (qHead + 1) % 32;
797 void Renderer::scheduleTask(int threadIndex)
799 schedulerMutex.lock();
801 if((int)qSize < threadCount - threadsAwake + 1)
803 findAvailableTasks();
808 task[threadIndex] = taskQueue[(qHead - qSize) % 32];
811 if(threadsAwake != threadCount)
813 int wakeup = qSize - threadsAwake + 1;
815 for(int i = 0; i < threadCount && wakeup > 0; i++)
817 if(task[i].type == Task::SUSPEND)
820 task[i].type = Task::RESUME;
831 task[threadIndex].type = Task::SUSPEND;
836 schedulerMutex.unlock();
839 void Renderer::executeTask(int threadIndex)
842 int64_t startTick = Timer::ticks();
845 switch(task[threadIndex].type)
847 case Task::PRIMITIVES:
849 int unit = task[threadIndex].primitiveUnit;
851 int input = primitiveProgress[unit].firstPrimitive;
852 int count = primitiveProgress[unit].primitiveCount;
853 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
854 int (Renderer::*setupPrimitives)(int batch, int count) = draw->setupPrimitives;
856 processPrimitiveVertices(unit, input, count, draw->count, threadIndex);
859 int64_t time = Timer::ticks();
860 vertexTime[threadIndex] += time - startTick;
866 if(!draw->setupState.rasterizerDiscard)
868 visible = (this->*setupPrimitives)(unit, count);
871 primitiveProgress[unit].visible = visible;
872 primitiveProgress[unit].references = clusterCount;
875 setupTime[threadIndex] += Timer::ticks() - startTick;
881 int unit = task[threadIndex].primitiveUnit;
882 int visible = primitiveProgress[unit].visible;
886 int cluster = task[threadIndex].pixelCluster;
887 Primitive *primitive = primitiveBatch[unit];
888 DrawCall *draw = drawList[pixelProgress[cluster].drawCall % DRAW_COUNT];
889 DrawData *data = draw->data;
890 PixelProcessor::RoutinePointer pixelRoutine = draw->pixelPointer;
892 pixelRoutine(primitive, visible, cluster, data);
895 finishRendering(task[threadIndex]);
898 pixelTime[threadIndex] += Timer::ticks() - startTick;
911 void Renderer::synchronize()
913 sync->lock(sw::PUBLIC);
917 void Renderer::finishRendering(Task &pixelTask)
919 int unit = pixelTask.primitiveUnit;
920 int cluster = pixelTask.pixelCluster;
922 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
923 DrawData &data = *draw.data;
924 int primitive = primitiveProgress[unit].firstPrimitive;
925 int count = primitiveProgress[unit].primitiveCount;
926 int processedPrimitives = primitive + count;
928 pixelProgress[cluster].processedPrimitives = processedPrimitives;
930 if(pixelProgress[cluster].processedPrimitives >= draw.count)
932 pixelProgress[cluster].drawCall++;
933 pixelProgress[cluster].processedPrimitives = 0;
936 int ref = atomicDecrement(&primitiveProgress[unit].references);
940 ref = atomicDecrement(&draw.references);
945 for(int cluster = 0; cluster < clusterCount; cluster++)
947 for(int i = 0; i < PERF_TIMERS; i++)
949 profiler.cycles[i] += data.cycles[i][cluster];
956 for(std::list<Query*>::iterator q = draw.queries->begin(); q != draw.queries->end(); q++)
962 case Query::FRAGMENTS_PASSED:
963 for(int cluster = 0; cluster < clusterCount; cluster++)
965 atomicAdd((volatile int*)&query->data, data.occlusion[cluster]);
968 case Query::TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
969 atomicAdd((volatile int*)&query->data, processedPrimitives);
975 atomicDecrement(&query->reference);
982 for(int i = 0; i < RENDERTARGETS; i++)
984 if(draw.renderTarget[i])
986 draw.renderTarget[i]->unlockInternal();
992 draw.depthBuffer->unlockInternal();
995 if(draw.stencilBuffer)
997 draw.stencilBuffer->unlockStencil();
1000 for(int i = 0; i < TOTAL_IMAGE_UNITS; i++)
1004 draw.texture[i]->unlock();
1008 for(int i = 0; i < MAX_VERTEX_INPUTS; i++)
1010 if(draw.vertexStream[i])
1012 draw.vertexStream[i]->unlock();
1016 if(draw.indexBuffer)
1018 draw.indexBuffer->unlock();
1021 for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; i++)
1023 if(draw.pUniformBuffers[i])
1025 draw.pUniformBuffers[i]->unlock();
1027 if(draw.vUniformBuffers[i])
1029 draw.vUniformBuffers[i]->unlock();
1033 for(int i = 0; i < MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS; i++)
1035 if(draw.transformFeedbackBuffers[i])
1037 draw.transformFeedbackBuffers[i]->unlock();
1041 draw.vertexRoutine->unbind();
1042 draw.setupRoutine->unbind();
1043 draw.pixelRoutine->unbind();
1047 draw.references = -1;
1048 resumeApp->signal();
1052 pixelProgress[cluster].executing = false;
1055 void Renderer::processPrimitiveVertices(int unit, unsigned int start, unsigned int triangleCount, unsigned int loop, int thread)
1057 Triangle *triangle = triangleBatch[unit];
1058 DrawCall *draw = drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
1059 DrawData *data = draw->data;
1060 VertexTask *task = vertexTask[thread];
1062 const void *indices = data->indices;
1063 VertexProcessor::RoutinePointer vertexRoutine = draw->vertexPointer;
1065 if(task->vertexCache.drawCall != primitiveProgress[unit].drawCall)
1067 task->vertexCache.clear();
1068 task->vertexCache.drawCall = primitiveProgress[unit].drawCall;
1071 unsigned int batch[128][3]; // FIXME: Adjust to dynamic batch size
1073 switch(draw->drawType)
1075 case DRAW_POINTLIST:
1077 unsigned int index = start;
1079 for(unsigned int i = 0; i < triangleCount; i++)
1081 batch[i][0] = index;
1082 batch[i][1] = index;
1083 batch[i][2] = index;
1091 unsigned int index = 2 * start;
1093 for(unsigned int i = 0; i < triangleCount; i++)
1095 batch[i][0] = index + 0;
1096 batch[i][1] = index + 1;
1097 batch[i][2] = index + 1;
1103 case DRAW_LINESTRIP:
1105 unsigned int index = start;
1107 for(unsigned int i = 0; i < triangleCount; i++)
1109 batch[i][0] = index + 0;
1110 batch[i][1] = index + 1;
1111 batch[i][2] = index + 1;
1119 unsigned int index = start;
1121 for(unsigned int i = 0; i < triangleCount; i++)
1123 batch[i][0] = (index + 0) % loop;
1124 batch[i][1] = (index + 1) % loop;
1125 batch[i][2] = (index + 1) % loop;
1131 case DRAW_TRIANGLELIST:
1133 unsigned int index = 3 * start;
1135 for(unsigned int i = 0; i < triangleCount; i++)
1137 batch[i][0] = index + 0;
1138 batch[i][1] = index + 1;
1139 batch[i][2] = index + 2;
1145 case DRAW_TRIANGLESTRIP:
1147 unsigned int index = start;
1149 for(unsigned int i = 0; i < triangleCount; i++)
1151 batch[i][0] = index + 0;
1152 batch[i][1] = index + (index & 1) + 1;
1153 batch[i][2] = index + (~index & 1) + 1;
1159 case DRAW_TRIANGLEFAN:
1161 unsigned int index = start;
1163 for(unsigned int i = 0; i < triangleCount; i++)
1165 batch[i][0] = index + 1;
1166 batch[i][1] = index + 2;
1173 case DRAW_INDEXEDPOINTLIST8:
1175 const unsigned char *index = (const unsigned char*)indices + start;
1177 for(unsigned int i = 0; i < triangleCount; i++)
1179 batch[i][0] = *index;
1180 batch[i][1] = *index;
1181 batch[i][2] = *index;
1187 case DRAW_INDEXEDPOINTLIST16:
1189 const unsigned short *index = (const unsigned short*)indices + start;
1191 for(unsigned int i = 0; i < triangleCount; i++)
1193 batch[i][0] = *index;
1194 batch[i][1] = *index;
1195 batch[i][2] = *index;
1201 case DRAW_INDEXEDPOINTLIST32:
1203 const unsigned int *index = (const unsigned int*)indices + start;
1205 for(unsigned int i = 0; i < triangleCount; i++)
1207 batch[i][0] = *index;
1208 batch[i][1] = *index;
1209 batch[i][2] = *index;
1215 case DRAW_INDEXEDLINELIST8:
1217 const unsigned char *index = (const unsigned char*)indices + 2 * start;
1219 for(unsigned int i = 0; i < triangleCount; i++)
1221 batch[i][0] = index[0];
1222 batch[i][1] = index[1];
1223 batch[i][2] = index[1];
1229 case DRAW_INDEXEDLINELIST16:
1231 const unsigned short *index = (const unsigned short*)indices + 2 * start;
1233 for(unsigned int i = 0; i < triangleCount; i++)
1235 batch[i][0] = index[0];
1236 batch[i][1] = index[1];
1237 batch[i][2] = index[1];
1243 case DRAW_INDEXEDLINELIST32:
1245 const unsigned int *index = (const unsigned int*)indices + 2 * start;
1247 for(unsigned int i = 0; i < triangleCount; i++)
1249 batch[i][0] = index[0];
1250 batch[i][1] = index[1];
1251 batch[i][2] = index[1];
1257 case DRAW_INDEXEDLINESTRIP8:
1259 const unsigned char *index = (const unsigned char*)indices + start;
1261 for(unsigned int i = 0; i < triangleCount; i++)
1263 batch[i][0] = index[0];
1264 batch[i][1] = index[1];
1265 batch[i][2] = index[1];
1271 case DRAW_INDEXEDLINESTRIP16:
1273 const unsigned short *index = (const unsigned short*)indices + start;
1275 for(unsigned int i = 0; i < triangleCount; i++)
1277 batch[i][0] = index[0];
1278 batch[i][1] = index[1];
1279 batch[i][2] = index[1];
1285 case DRAW_INDEXEDLINESTRIP32:
1287 const unsigned int *index = (const unsigned int*)indices + start;
1289 for(unsigned int i = 0; i < triangleCount; i++)
1291 batch[i][0] = index[0];
1292 batch[i][1] = index[1];
1293 batch[i][2] = index[1];
1299 case DRAW_INDEXEDLINELOOP8:
1301 const unsigned char *index = (const unsigned char*)indices;
1303 for(unsigned int i = 0; i < triangleCount; i++)
1305 batch[i][0] = index[(start + i + 0) % loop];
1306 batch[i][1] = index[(start + i + 1) % loop];
1307 batch[i][2] = index[(start + i + 1) % loop];
1311 case DRAW_INDEXEDLINELOOP16:
1313 const unsigned short *index = (const unsigned short*)indices;
1315 for(unsigned int i = 0; i < triangleCount; i++)
1317 batch[i][0] = index[(start + i + 0) % loop];
1318 batch[i][1] = index[(start + i + 1) % loop];
1319 batch[i][2] = index[(start + i + 1) % loop];
1323 case DRAW_INDEXEDLINELOOP32:
1325 const unsigned int *index = (const unsigned int*)indices;
1327 for(unsigned int i = 0; i < triangleCount; i++)
1329 batch[i][0] = index[(start + i + 0) % loop];
1330 batch[i][1] = index[(start + i + 1) % loop];
1331 batch[i][2] = index[(start + i + 1) % loop];
1335 case DRAW_INDEXEDTRIANGLELIST8:
1337 const unsigned char *index = (const unsigned char*)indices + 3 * start;
1339 for(unsigned int i = 0; i < triangleCount; i++)
1341 batch[i][0] = index[0];
1342 batch[i][1] = index[1];
1343 batch[i][2] = index[2];
1349 case DRAW_INDEXEDTRIANGLELIST16:
1351 const unsigned short *index = (const unsigned short*)indices + 3 * start;
1353 for(unsigned int i = 0; i < triangleCount; i++)
1355 batch[i][0] = index[0];
1356 batch[i][1] = index[1];
1357 batch[i][2] = index[2];
1363 case DRAW_INDEXEDTRIANGLELIST32:
1365 const unsigned int *index = (const unsigned int*)indices + 3 * start;
1367 for(unsigned int i = 0; i < triangleCount; i++)
1369 batch[i][0] = index[0];
1370 batch[i][1] = index[1];
1371 batch[i][2] = index[2];
1377 case DRAW_INDEXEDTRIANGLESTRIP8:
1379 const unsigned char *index = (const unsigned char*)indices + start;
1381 for(unsigned int i = 0; i < triangleCount; i++)
1383 batch[i][0] = index[0];
1384 batch[i][1] = index[((start + i) & 1) + 1];
1385 batch[i][2] = index[(~(start + i) & 1) + 1];
1391 case DRAW_INDEXEDTRIANGLESTRIP16:
1393 const unsigned short *index = (const unsigned short*)indices + start;
1395 for(unsigned int i = 0; i < triangleCount; i++)
1397 batch[i][0] = index[0];
1398 batch[i][1] = index[((start + i) & 1) + 1];
1399 batch[i][2] = index[(~(start + i) & 1) + 1];
1405 case DRAW_INDEXEDTRIANGLESTRIP32:
1407 const unsigned int *index = (const unsigned int*)indices + start;
1409 for(unsigned int i = 0; i < triangleCount; i++)
1411 batch[i][0] = index[0];
1412 batch[i][1] = index[((start + i) & 1) + 1];
1413 batch[i][2] = index[(~(start + i) & 1) + 1];
1419 case DRAW_INDEXEDTRIANGLEFAN8:
1421 const unsigned char *index = (const unsigned char*)indices;
1423 for(unsigned int i = 0; i < triangleCount; i++)
1425 batch[i][0] = index[start + i + 1];
1426 batch[i][1] = index[start + i + 2];
1427 batch[i][2] = index[0];
1431 case DRAW_INDEXEDTRIANGLEFAN16:
1433 const unsigned short *index = (const unsigned short*)indices;
1435 for(unsigned int i = 0; i < triangleCount; i++)
1437 batch[i][0] = index[start + i + 1];
1438 batch[i][1] = index[start + i + 2];
1439 batch[i][2] = index[0];
1443 case DRAW_INDEXEDTRIANGLEFAN32:
1445 const unsigned int *index = (const unsigned int*)indices;
1447 for(unsigned int i = 0; i < triangleCount; i++)
1449 batch[i][0] = index[start + i + 1];
1450 batch[i][1] = index[start + i + 2];
1451 batch[i][2] = index[0];
1457 unsigned int index = 4 * start / 2;
1459 for(unsigned int i = 0; i < triangleCount; i += 2)
1461 batch[i+0][0] = index + 0;
1462 batch[i+0][1] = index + 1;
1463 batch[i+0][2] = index + 2;
1465 batch[i+1][0] = index + 0;
1466 batch[i+1][1] = index + 2;
1467 batch[i+1][2] = index + 3;
1478 task->primitiveStart = start;
1479 task->vertexCount = triangleCount * 3;
1480 vertexRoutine(&triangle->v0, (unsigned int*)&batch, task, data);
1483 int Renderer::setupSolidTriangles(int unit, int count)
1485 Triangle *triangle = triangleBatch[unit];
1486 Primitive *primitive = primitiveBatch[unit];
1488 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
1489 SetupProcessor::State &state = draw.setupState;
1490 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1492 int ms = state.multiSample;
1493 int pos = state.positionRegister;
1494 const DrawData *data = draw.data;
1497 for(int i = 0; i < count; i++, triangle++)
1499 Vertex &v0 = triangle->v0;
1500 Vertex &v1 = triangle->v1;
1501 Vertex &v2 = triangle->v2;
1503 if((v0.clipFlags & v1.clipFlags & v2.clipFlags) == Clipper::CLIP_FINITE)
1505 Polygon polygon(&v0.v[pos], &v1.v[pos], &v2.v[pos]);
1507 int clipFlagsOr = v0.clipFlags | v1.clipFlags | v2.clipFlags | draw.clipFlags;
1509 if(clipFlagsOr != Clipper::CLIP_FINITE)
1511 if(!clipper->clip(polygon, clipFlagsOr, draw))
1517 if(setupRoutine(primitive, triangle, &polygon, data))
1528 int Renderer::setupWireframeTriangle(int unit, int count)
1530 Triangle *triangle = triangleBatch[unit];
1531 Primitive *primitive = primitiveBatch[unit];
1534 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
1535 SetupProcessor::State &state = draw.setupState;
1537 const Vertex &v0 = triangle[0].v0;
1538 const Vertex &v1 = triangle[0].v1;
1539 const Vertex &v2 = triangle[0].v2;
1541 float d = (v0.y * v1.x - v0.x * v1.y) * v2.w + (v0.x * v2.y - v0.y * v2.x) * v1.w + (v2.x * v1.y - v1.x * v2.y) * v0.w;
1543 if(state.cullMode == CULL_CLOCKWISE)
1545 if(d >= 0) return 0;
1547 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1549 if(d <= 0) return 0;
1553 triangle[1].v0 = v1;
1554 triangle[1].v1 = v2;
1555 triangle[2].v0 = v2;
1556 triangle[2].v1 = v0;
1558 if(state.color[0][0].flat) // FIXME
1560 for(int i = 0; i < 2; i++)
1562 triangle[1].v0.C[i] = triangle[0].v0.C[i];
1563 triangle[1].v1.C[i] = triangle[0].v0.C[i];
1564 triangle[2].v0.C[i] = triangle[0].v0.C[i];
1565 triangle[2].v1.C[i] = triangle[0].v0.C[i];
1569 for(int i = 0; i < 3; i++)
1571 if(setupLine(*primitive, *triangle, draw))
1573 primitive->area = 0.5f * d;
1585 int Renderer::setupVertexTriangle(int unit, int count)
1587 Triangle *triangle = triangleBatch[unit];
1588 Primitive *primitive = primitiveBatch[unit];
1591 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
1592 SetupProcessor::State &state = draw.setupState;
1594 const Vertex &v0 = triangle[0].v0;
1595 const Vertex &v1 = triangle[0].v1;
1596 const Vertex &v2 = triangle[0].v2;
1598 float d = (v0.y * v1.x - v0.x * v1.y) * v2.w + (v0.x * v2.y - v0.y * v2.x) * v1.w + (v2.x * v1.y - v1.x * v2.y) * v0.w;
1600 if(state.cullMode == CULL_CLOCKWISE)
1602 if(d >= 0) return 0;
1604 else if(state.cullMode == CULL_COUNTERCLOCKWISE)
1606 if(d <= 0) return 0;
1610 triangle[1].v0 = v1;
1611 triangle[2].v0 = v2;
1613 for(int i = 0; i < 3; i++)
1615 if(setupPoint(*primitive, *triangle, draw))
1617 primitive->area = 0.5f * d;
1629 int Renderer::setupLines(int unit, int count)
1631 Triangle *triangle = triangleBatch[unit];
1632 Primitive *primitive = primitiveBatch[unit];
1635 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
1636 SetupProcessor::State &state = draw.setupState;
1638 int ms = state.multiSample;
1640 for(int i = 0; i < count; i++)
1642 if(setupLine(*primitive, *triangle, draw))
1654 int Renderer::setupPoints(int unit, int count)
1656 Triangle *triangle = triangleBatch[unit];
1657 Primitive *primitive = primitiveBatch[unit];
1660 DrawCall &draw = *drawList[primitiveProgress[unit].drawCall % DRAW_COUNT];
1661 SetupProcessor::State &state = draw.setupState;
1663 int ms = state.multiSample;
1665 for(int i = 0; i < count; i++)
1667 if(setupPoint(*primitive, *triangle, draw))
1679 bool Renderer::setupLine(Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1681 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1682 const SetupProcessor::State &state = draw.setupState;
1683 const DrawData &data = *draw.data;
1685 float lineWidth = data.lineWidth;
1687 Vertex &v0 = triangle.v0;
1688 Vertex &v1 = triangle.v1;
1690 int pos = state.positionRegister;
1692 const float4 &P0 = v0.v[pos];
1693 const float4 &P1 = v1.v[pos];
1695 if(P0.w <= 0 && P1.w <= 0)
1700 const float W = data.Wx16[0] * (1.0f / 16.0f);
1701 const float H = data.Hx16[0] * (1.0f / 16.0f);
1703 float dx = W * (P1.x / P1.w - P0.x / P0.w);
1704 float dy = H * (P1.y / P1.w - P0.y / P0.w);
1706 if(dx == 0 && dy == 0)
1711 if(false) // Rectangle
1721 float scale = lineWidth * 0.5f / sqrt(dx*dx + dy*dy);
1726 float dx0w = dx * P0.w / W;
1727 float dy0h = dy * P0.w / H;
1728 float dx0h = dx * P0.w / H;
1729 float dy0w = dy * P0.w / W;
1731 float dx1w = dx * P1.w / W;
1732 float dy1h = dy * P1.w / H;
1733 float dx1h = dx * P1.w / H;
1734 float dy1w = dy * P1.w / W;
1736 P[0].x += -dy0w + -dx0w;
1737 P[0].y += -dx0h + +dy0h;
1738 C[0] = clipper->computeClipFlags(P[0]);
1740 P[1].x += -dy1w + +dx1w;
1741 P[1].y += -dx1h + +dy1h;
1742 C[1] = clipper->computeClipFlags(P[1]);
1744 P[2].x += +dy1w + +dx1w;
1745 P[2].y += +dx1h + -dy1h;
1746 C[2] = clipper->computeClipFlags(P[2]);
1748 P[3].x += +dy0w + -dx0w;
1749 P[3].y += +dx0h + +dy0h;
1750 C[3] = clipper->computeClipFlags(P[3]);
1752 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1754 Polygon polygon(P, 4);
1756 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1758 if(clipFlagsOr != Clipper::CLIP_FINITE)
1760 if(!clipper->clip(polygon, clipFlagsOr, draw))
1766 return setupRoutine(&primitive, &triangle, &polygon, &data);
1769 else // Diamond test convention
1783 float dx0 = lineWidth * 0.5f * P0.w / W;
1784 float dy0 = lineWidth * 0.5f * P0.w / H;
1786 float dx1 = lineWidth * 0.5f * P1.w / W;
1787 float dy1 = lineWidth * 0.5f * P1.w / H;
1790 C[0] = clipper->computeClipFlags(P[0]);
1793 C[1] = clipper->computeClipFlags(P[1]);
1796 C[2] = clipper->computeClipFlags(P[2]);
1799 C[3] = clipper->computeClipFlags(P[3]);
1802 C[4] = clipper->computeClipFlags(P[4]);
1805 C[5] = clipper->computeClipFlags(P[5]);
1808 C[6] = clipper->computeClipFlags(P[6]);
1811 C[7] = clipper->computeClipFlags(P[7]);
1813 if((C[0] & C[1] & C[2] & C[3] & C[4] & C[5] & C[6] & C[7]) == Clipper::CLIP_FINITE)
1819 if(dx > dy) // Right
1860 Polygon polygon(L, 6);
1862 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | C[4] | C[5] | C[6] | C[7] | draw.clipFlags;
1864 if(clipFlagsOr != Clipper::CLIP_FINITE)
1866 if(!clipper->clip(polygon, clipFlagsOr, draw))
1872 return setupRoutine(&primitive, &triangle, &polygon, &data);
1879 bool Renderer::setupPoint(Primitive &primitive, Triangle &triangle, const DrawCall &draw)
1881 const SetupProcessor::RoutinePointer &setupRoutine = draw.setupPointer;
1882 const SetupProcessor::State &state = draw.setupState;
1883 const DrawData &data = *draw.data;
1885 Vertex &v = triangle.v0;
1889 int pts = state.pointSizeRegister;
1891 if(state.pointSizeRegister != Unused)
1897 pSize = data.point.pointSize[0];
1900 pSize = clamp(pSize, data.point.pointSizeMin, data.point.pointSizeMax);
1905 int pos = state.positionRegister;
1912 const float X = pSize * P[0].w * data.halfPixelX[0];
1913 const float Y = pSize * P[0].w * data.halfPixelY[0];
1917 C[0] = clipper->computeClipFlags(P[0]);
1921 C[1] = clipper->computeClipFlags(P[1]);
1925 C[2] = clipper->computeClipFlags(P[2]);
1929 C[3] = clipper->computeClipFlags(P[3]);
1931 triangle.v1 = triangle.v0;
1932 triangle.v2 = triangle.v0;
1934 triangle.v1.X += iround(16 * 0.5f * pSize);
1935 triangle.v2.Y -= iround(16 * 0.5f * pSize) * (data.Hx16[0] > 0.0f ? 1 : -1); // Both Direct3D and OpenGL expect (0, 0) in the top-left corner
1937 Polygon polygon(P, 4);
1939 if((C[0] & C[1] & C[2] & C[3]) == Clipper::CLIP_FINITE)
1941 int clipFlagsOr = C[0] | C[1] | C[2] | C[3] | draw.clipFlags;
1943 if(clipFlagsOr != Clipper::CLIP_FINITE)
1945 if(!clipper->clip(polygon, clipFlagsOr, draw))
1951 return setupRoutine(&primitive, &triangle, &polygon, &data);
1957 void Renderer::initializeThreads()
1959 unitCount = ceilPow2(threadCount);
1960 clusterCount = ceilPow2(threadCount);
1962 for(int i = 0; i < unitCount; i++)
1964 triangleBatch[i] = (Triangle*)allocate(batchSize * sizeof(Triangle));
1965 primitiveBatch[i] = (Primitive*)allocate(batchSize * sizeof(Primitive));
1968 for(int i = 0; i < threadCount; i++)
1970 vertexTask[i] = (VertexTask*)allocate(sizeof(VertexTask));
1971 vertexTask[i]->vertexCache.drawCall = -1;
1973 task[i].type = Task::SUSPEND;
1975 resume[i] = new Event();
1976 suspend[i] = new Event();
1978 Parameters parameters;
1979 parameters.threadIndex = i;
1980 parameters.renderer = this;
1982 exitThreads = false;
1983 worker[i] = new Thread(threadFunction, ¶meters);
1986 suspend[i]->signal();
1990 void Renderer::terminateThreads()
1992 while(threadsAwake != 0)
1997 for(int thread = 0; thread < threadCount; thread++)
2002 resume[thread]->signal();
2003 worker[thread]->join();
2005 delete worker[thread];
2007 delete resume[thread];
2009 delete suspend[thread];
2010 suspend[thread] = 0;
2013 deallocate(vertexTask[thread]);
2014 vertexTask[thread] = 0;
2017 for(int i = 0; i < 16; i++)
2019 deallocate(triangleBatch[i]);
2020 triangleBatch[i] = 0;
2022 deallocate(primitiveBatch[i]);
2023 primitiveBatch[i] = 0;
2027 void Renderer::loadConstants(const VertexShader *vertexShader)
2029 if(!vertexShader) return;
2031 size_t count = vertexShader->getLength();
2033 for(size_t i = 0; i < count; i++)
2035 const Shader::Instruction *instruction = vertexShader->getInstruction(i);
2037 if(instruction->opcode == Shader::OPCODE_DEF)
2039 int index = instruction->dst.index;
2042 value[0] = instruction->src[0].value[0];
2043 value[1] = instruction->src[0].value[1];
2044 value[2] = instruction->src[0].value[2];
2045 value[3] = instruction->src[0].value[3];
2047 setVertexShaderConstantF(index, value);
2049 else if(instruction->opcode == Shader::OPCODE_DEFI)
2051 int index = instruction->dst.index;
2054 integer[0] = instruction->src[0].integer[0];
2055 integer[1] = instruction->src[0].integer[1];
2056 integer[2] = instruction->src[0].integer[2];
2057 integer[3] = instruction->src[0].integer[3];
2059 setVertexShaderConstantI(index, integer);
2061 else if(instruction->opcode == Shader::OPCODE_DEFB)
2063 int index = instruction->dst.index;
2064 int boolean = instruction->src[0].boolean[0];
2066 setVertexShaderConstantB(index, &boolean);
2071 void Renderer::loadConstants(const PixelShader *pixelShader)
2073 if(!pixelShader) return;
2075 size_t count = pixelShader->getLength();
2077 for(size_t i = 0; i < count; i++)
2079 const Shader::Instruction *instruction = pixelShader->getInstruction(i);
2081 if(instruction->opcode == Shader::OPCODE_DEF)
2083 int index = instruction->dst.index;
2086 value[0] = instruction->src[0].value[0];
2087 value[1] = instruction->src[0].value[1];
2088 value[2] = instruction->src[0].value[2];
2089 value[3] = instruction->src[0].value[3];
2091 setPixelShaderConstantF(index, value);
2093 else if(instruction->opcode == Shader::OPCODE_DEFI)
2095 int index = instruction->dst.index;
2098 integer[0] = instruction->src[0].integer[0];
2099 integer[1] = instruction->src[0].integer[1];
2100 integer[2] = instruction->src[0].integer[2];
2101 integer[3] = instruction->src[0].integer[3];
2103 setPixelShaderConstantI(index, integer);
2105 else if(instruction->opcode == Shader::OPCODE_DEFB)
2107 int index = instruction->dst.index;
2108 int boolean = instruction->src[0].boolean[0];
2110 setPixelShaderConstantB(index, &boolean);
2115 void Renderer::setIndexBuffer(Resource *indexBuffer)
2117 context->indexBuffer = indexBuffer;
2120 void Renderer::setMultiSampleMask(unsigned int mask)
2122 context->sampleMask = mask;
2125 void Renderer::setTransparencyAntialiasing(TransparencyAntialiasing transparencyAntialiasing)
2127 sw::transparencyAntialiasing = transparencyAntialiasing;
2130 bool Renderer::isReadWriteTexture(int sampler)
2132 for(int index = 0; index < RENDERTARGETS; index++)
2134 if(context->renderTarget[index] && context->texture[sampler] == context->renderTarget[index]->getResource())
2140 if(context->depthBuffer && context->texture[sampler] == context->depthBuffer->getResource())
2148 void Renderer::updateClipper()
2150 if(updateClipPlanes)
2152 if(VertexProcessor::isFixedFunction()) // User plane in world space
2154 const Matrix &scissorWorld = getViewTransform();
2156 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = scissorWorld * userPlane[0];
2157 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = scissorWorld * userPlane[1];
2158 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = scissorWorld * userPlane[2];
2159 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = scissorWorld * userPlane[3];
2160 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = scissorWorld * userPlane[4];
2161 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = scissorWorld * userPlane[5];
2163 else // User plane in clip space
2165 if(clipFlags & Clipper::CLIP_PLANE0) clipPlane[0] = userPlane[0];
2166 if(clipFlags & Clipper::CLIP_PLANE1) clipPlane[1] = userPlane[1];
2167 if(clipFlags & Clipper::CLIP_PLANE2) clipPlane[2] = userPlane[2];
2168 if(clipFlags & Clipper::CLIP_PLANE3) clipPlane[3] = userPlane[3];
2169 if(clipFlags & Clipper::CLIP_PLANE4) clipPlane[4] = userPlane[4];
2170 if(clipFlags & Clipper::CLIP_PLANE5) clipPlane[5] = userPlane[5];
2173 updateClipPlanes = false;
2177 void Renderer::setTextureResource(unsigned int sampler, Resource *resource)
2179 ASSERT(sampler < TOTAL_IMAGE_UNITS);
2181 context->texture[sampler] = resource;
2184 void Renderer::setTextureLevel(unsigned int sampler, unsigned int face, unsigned int level, Surface *surface, TextureType type)
2186 ASSERT(sampler < TOTAL_IMAGE_UNITS && face < 6 && level < MIPMAP_LEVELS);
2188 context->sampler[sampler].setTextureLevel(face, level, surface, type);
2191 void Renderer::setTextureFilter(SamplerType type, int sampler, FilterType textureFilter)
2193 if(type == SAMPLER_PIXEL)
2195 PixelProcessor::setTextureFilter(sampler, textureFilter);
2199 VertexProcessor::setTextureFilter(sampler, textureFilter);
2203 void Renderer::setMipmapFilter(SamplerType type, int sampler, MipmapType mipmapFilter)
2205 if(type == SAMPLER_PIXEL)
2207 PixelProcessor::setMipmapFilter(sampler, mipmapFilter);
2211 VertexProcessor::setMipmapFilter(sampler, mipmapFilter);
2215 void Renderer::setGatherEnable(SamplerType type, int sampler, bool enable)
2217 if(type == SAMPLER_PIXEL)
2219 PixelProcessor::setGatherEnable(sampler, enable);
2223 VertexProcessor::setGatherEnable(sampler, enable);
2227 void Renderer::setAddressingModeU(SamplerType type, int sampler, AddressingMode addressMode)
2229 if(type == SAMPLER_PIXEL)
2231 PixelProcessor::setAddressingModeU(sampler, addressMode);
2235 VertexProcessor::setAddressingModeU(sampler, addressMode);
2239 void Renderer::setAddressingModeV(SamplerType type, int sampler, AddressingMode addressMode)
2241 if(type == SAMPLER_PIXEL)
2243 PixelProcessor::setAddressingModeV(sampler, addressMode);
2247 VertexProcessor::setAddressingModeV(sampler, addressMode);
2251 void Renderer::setAddressingModeW(SamplerType type, int sampler, AddressingMode addressMode)
2253 if(type == SAMPLER_PIXEL)
2255 PixelProcessor::setAddressingModeW(sampler, addressMode);
2259 VertexProcessor::setAddressingModeW(sampler, addressMode);
2263 void Renderer::setReadSRGB(SamplerType type, int sampler, bool sRGB)
2265 if(type == SAMPLER_PIXEL)
2267 PixelProcessor::setReadSRGB(sampler, sRGB);
2271 VertexProcessor::setReadSRGB(sampler, sRGB);
2275 void Renderer::setMipmapLOD(SamplerType type, int sampler, float bias)
2277 if(type == SAMPLER_PIXEL)
2279 PixelProcessor::setMipmapLOD(sampler, bias);
2283 VertexProcessor::setMipmapLOD(sampler, bias);
2287 void Renderer::setBorderColor(SamplerType type, int sampler, const Color<float> &borderColor)
2289 if(type == SAMPLER_PIXEL)
2291 PixelProcessor::setBorderColor(sampler, borderColor);
2295 VertexProcessor::setBorderColor(sampler, borderColor);
2299 void Renderer::setMaxAnisotropy(SamplerType type, int sampler, float maxAnisotropy)
2301 if(type == SAMPLER_PIXEL)
2303 PixelProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2307 VertexProcessor::setMaxAnisotropy(sampler, maxAnisotropy);
2311 void Renderer::setSwizzleR(SamplerType type, int sampler, SwizzleType swizzleR)
2313 if(type == SAMPLER_PIXEL)
2315 PixelProcessor::setSwizzleR(sampler, swizzleR);
2319 VertexProcessor::setSwizzleR(sampler, swizzleR);
2323 void Renderer::setSwizzleG(SamplerType type, int sampler, SwizzleType swizzleG)
2325 if(type == SAMPLER_PIXEL)
2327 PixelProcessor::setSwizzleG(sampler, swizzleG);
2331 VertexProcessor::setSwizzleG(sampler, swizzleG);
2335 void Renderer::setSwizzleB(SamplerType type, int sampler, SwizzleType swizzleB)
2337 if(type == SAMPLER_PIXEL)
2339 PixelProcessor::setSwizzleB(sampler, swizzleB);
2343 VertexProcessor::setSwizzleB(sampler, swizzleB);
2347 void Renderer::setSwizzleA(SamplerType type, int sampler, SwizzleType swizzleA)
2349 if(type == SAMPLER_PIXEL)
2351 PixelProcessor::setSwizzleA(sampler, swizzleA);
2355 VertexProcessor::setSwizzleA(sampler, swizzleA);
2359 void Renderer::setBaseLevel(SamplerType type, int sampler, int baseLevel)
2361 if(type == SAMPLER_PIXEL)
2363 PixelProcessor::setBaseLevel(sampler, baseLevel);
2367 VertexProcessor::setBaseLevel(sampler, baseLevel);
2371 void Renderer::setMaxLevel(SamplerType type, int sampler, int maxLevel)
2373 if(type == SAMPLER_PIXEL)
2375 PixelProcessor::setMaxLevel(sampler, maxLevel);
2379 VertexProcessor::setMaxLevel(sampler, maxLevel);
2383 void Renderer::setMinLod(SamplerType type, int sampler, float minLod)
2385 if(type == SAMPLER_PIXEL)
2387 PixelProcessor::setMinLod(sampler, minLod);
2391 VertexProcessor::setMinLod(sampler, minLod);
2395 void Renderer::setMaxLod(SamplerType type, int sampler, float maxLod)
2397 if(type == SAMPLER_PIXEL)
2399 PixelProcessor::setMaxLod(sampler, maxLod);
2403 VertexProcessor::setMaxLod(sampler, maxLod);
2407 void Renderer::setPointSpriteEnable(bool pointSpriteEnable)
2409 context->setPointSpriteEnable(pointSpriteEnable);
2412 void Renderer::setPointScaleEnable(bool pointScaleEnable)
2414 context->setPointScaleEnable(pointScaleEnable);
2417 void Renderer::setLineWidth(float width)
2419 context->lineWidth = width;
2422 void Renderer::setDepthBias(float bias)
2427 void Renderer::setSlopeDepthBias(float slopeBias)
2429 slopeDepthBias = slopeBias;
2432 void Renderer::setRasterizerDiscard(bool rasterizerDiscard)
2434 context->rasterizerDiscard = rasterizerDiscard;
2437 void Renderer::setPixelShader(const PixelShader *shader)
2439 context->pixelShader = shader;
2441 loadConstants(shader);
2444 void Renderer::setVertexShader(const VertexShader *shader)
2446 context->vertexShader = shader;
2448 loadConstants(shader);
2451 void Renderer::setPixelShaderConstantF(int index, const float value[4], int count)
2453 for(int i = 0; i < DRAW_COUNT; i++)
2455 if(drawCall[i]->psDirtyConstF < index + count)
2457 drawCall[i]->psDirtyConstF = index + count;
2461 for(int i = 0; i < count; i++)
2463 PixelProcessor::setFloatConstant(index + i, value);
2468 void Renderer::setPixelShaderConstantI(int index, const int value[4], int count)
2470 for(int i = 0; i < DRAW_COUNT; i++)
2472 if(drawCall[i]->psDirtyConstI < index + count)
2474 drawCall[i]->psDirtyConstI = index + count;
2478 for(int i = 0; i < count; i++)
2480 PixelProcessor::setIntegerConstant(index + i, value);
2485 void Renderer::setPixelShaderConstantB(int index, const int *boolean, int count)
2487 for(int i = 0; i < DRAW_COUNT; i++)
2489 if(drawCall[i]->psDirtyConstB < index + count)
2491 drawCall[i]->psDirtyConstB = index + count;
2495 for(int i = 0; i < count; i++)
2497 PixelProcessor::setBooleanConstant(index + i, *boolean);
2502 void Renderer::setVertexShaderConstantF(int index, const float value[4], int count)
2504 for(int i = 0; i < DRAW_COUNT; i++)
2506 if(drawCall[i]->vsDirtyConstF < index + count)
2508 drawCall[i]->vsDirtyConstF = index + count;
2512 for(int i = 0; i < count; i++)
2514 VertexProcessor::setFloatConstant(index + i, value);
2519 void Renderer::setVertexShaderConstantI(int index, const int value[4], int count)
2521 for(int i = 0; i < DRAW_COUNT; i++)
2523 if(drawCall[i]->vsDirtyConstI < index + count)
2525 drawCall[i]->vsDirtyConstI = index + count;
2529 for(int i = 0; i < count; i++)
2531 VertexProcessor::setIntegerConstant(index + i, value);
2536 void Renderer::setVertexShaderConstantB(int index, const int *boolean, int count)
2538 for(int i = 0; i < DRAW_COUNT; i++)
2540 if(drawCall[i]->vsDirtyConstB < index + count)
2542 drawCall[i]->vsDirtyConstB = index + count;
2546 for(int i = 0; i < count; i++)
2548 VertexProcessor::setBooleanConstant(index + i, *boolean);
2553 void Renderer::setModelMatrix(const Matrix &M, int i)
2555 VertexProcessor::setModelMatrix(M, i);
2558 void Renderer::setViewMatrix(const Matrix &V)
2560 VertexProcessor::setViewMatrix(V);
2561 updateClipPlanes = true;
2564 void Renderer::setBaseMatrix(const Matrix &B)
2566 VertexProcessor::setBaseMatrix(B);
2567 updateClipPlanes = true;
2570 void Renderer::setProjectionMatrix(const Matrix &P)
2572 VertexProcessor::setProjectionMatrix(P);
2573 updateClipPlanes = true;
2576 void Renderer::addQuery(Query *query)
2578 queries.push_back(query);
2581 void Renderer::removeQuery(Query *query)
2583 queries.remove(query);
2587 int Renderer::getThreadCount()
2592 int64_t Renderer::getVertexTime(int thread)
2594 return vertexTime[thread];
2597 int64_t Renderer::getSetupTime(int thread)
2599 return setupTime[thread];
2602 int64_t Renderer::getPixelTime(int thread)
2604 return pixelTime[thread];
2607 void Renderer::resetTimers()
2609 for(int thread = 0; thread < threadCount; thread++)
2611 vertexTime[thread] = 0;
2612 setupTime[thread] = 0;
2613 pixelTime[thread] = 0;
2618 void Renderer::setViewport(const Viewport &viewport)
2620 this->viewport = viewport;
2623 void Renderer::setScissor(const Rect &scissor)
2625 this->scissor = scissor;
2628 void Renderer::setClipFlags(int flags)
2630 clipFlags = flags << 8; // Bottom 8 bits used by legacy frustum
2633 void Renderer::setClipPlane(unsigned int index, const float plane[4])
2635 if(index < MAX_CLIP_PLANES)
2637 userPlane[index] = plane;
2641 updateClipPlanes = true;
2644 void Renderer::updateConfiguration(bool initialUpdate)
2646 bool newConfiguration = swiftConfig->hasNewConfiguration();
2648 if(newConfiguration || initialUpdate)
2652 SwiftConfig::Configuration configuration = {};
2653 swiftConfig->getConfiguration(configuration);
2655 precacheVertex = !newConfiguration && configuration.precache;
2656 precacheSetup = !newConfiguration && configuration.precache;
2657 precachePixel = !newConfiguration && configuration.precache;
2659 VertexProcessor::setRoutineCacheSize(configuration.vertexRoutineCacheSize);
2660 PixelProcessor::setRoutineCacheSize(configuration.pixelRoutineCacheSize);
2661 SetupProcessor::setRoutineCacheSize(configuration.setupRoutineCacheSize);
2663 switch(configuration.textureSampleQuality)
2665 case 0: Sampler::setFilterQuality(FILTER_POINT); break;
2666 case 1: Sampler::setFilterQuality(FILTER_LINEAR); break;
2667 case 2: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2668 default: Sampler::setFilterQuality(FILTER_ANISOTROPIC); break;
2671 switch(configuration.mipmapQuality)
2673 case 0: Sampler::setMipmapQuality(MIPMAP_POINT); break;
2674 case 1: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2675 default: Sampler::setMipmapQuality(MIPMAP_LINEAR); break;
2678 setPerspectiveCorrection(configuration.perspectiveCorrection);
2680 switch(configuration.transcendentalPrecision)
2683 logPrecision = APPROXIMATE;
2684 expPrecision = APPROXIMATE;
2685 rcpPrecision = APPROXIMATE;
2686 rsqPrecision = APPROXIMATE;
2689 logPrecision = PARTIAL;
2690 expPrecision = PARTIAL;
2691 rcpPrecision = PARTIAL;
2692 rsqPrecision = PARTIAL;
2695 logPrecision = ACCURATE;
2696 expPrecision = ACCURATE;
2697 rcpPrecision = ACCURATE;
2698 rsqPrecision = ACCURATE;
2701 logPrecision = WHQL;
2702 expPrecision = WHQL;
2703 rcpPrecision = WHQL;
2704 rsqPrecision = WHQL;
2707 logPrecision = IEEE;
2708 expPrecision = IEEE;
2709 rcpPrecision = IEEE;
2710 rsqPrecision = IEEE;
2713 logPrecision = ACCURATE;
2714 expPrecision = ACCURATE;
2715 rcpPrecision = ACCURATE;
2716 rsqPrecision = ACCURATE;
2720 switch(configuration.transparencyAntialiasing)
2722 case 0: transparencyAntialiasing = TRANSPARENCY_NONE; break;
2723 case 1: transparencyAntialiasing = TRANSPARENCY_ALPHA_TO_COVERAGE; break;
2724 default: transparencyAntialiasing = TRANSPARENCY_NONE; break;
2727 switch(configuration.threadCount)
2729 case -1: threadCount = CPUID::coreCount(); break;
2730 case 0: threadCount = CPUID::processAffinity(); break;
2731 default: threadCount = configuration.threadCount; break;
2734 CPUID::setEnableSSE4_1(configuration.enableSSE4_1);
2735 CPUID::setEnableSSSE3(configuration.enableSSSE3);
2736 CPUID::setEnableSSE3(configuration.enableSSE3);
2737 CPUID::setEnableSSE2(configuration.enableSSE2);
2738 CPUID::setEnableSSE(configuration.enableSSE);
2740 for(int pass = 0; pass < 10; pass++)
2742 optimization[pass] = configuration.optimization[pass];
2745 forceWindowed = configuration.forceWindowed;
2746 complementaryDepthBuffer = configuration.complementaryDepthBuffer;
2747 postBlendSRGB = configuration.postBlendSRGB;
2748 exactColorRounding = configuration.exactColorRounding;
2749 forceClearRegisters = configuration.forceClearRegisters;
2752 minPrimitives = configuration.minPrimitives;
2753 maxPrimitives = configuration.maxPrimitives;
2757 if(!initialUpdate && !worker[0])
2759 initializeThreads();