PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Non-scanline rasterization of triangles

I am currently revisiting the triangle rasterization code that I have in Vincent. The current implementation is more or less based on the ideas out of Chris Hecker's article http://d6.com/users/checker/misctech.htm. The problem with this approach is that it is quite bulky and expensive during triangle setup. In addition, more advanced features like anti-aliasing are *very* difficult to incorporate.

That said I want to experiment with half-space based rasterization, along the lines of Nicolas Capens article http://www.devmaster.net/codespotlight/show.php?id=17.
I believe that many if not most hardware implementations are actually based on this approach nowadays.
Has anyone here actually tried to use this type of rasterizer in a software implementation for textured polygons on a PPC, and what were the experiences?

Also, has anyone experimented with texture swizzling in such a rasterizer etc. to optimize the cache behavior?

Thanks,
HM
hm wrote:
Also, has anyone experimented with texture swizzling in such a rasterizer etc. to optimize the cache behavior?

Thanks,
HM


Yes, it is a little bit slower in the worst case (where the non swizzled texture is read pixel by pixel), and it`s about 3 times faster in the best case I measured (large quad, 90° rotated texture).

On average in my test cases it was something like a 50% speedup over non swizzled textures.

However, filtering becomes a pain to do. It is still faster than without swizzleing, but the innerloop get long and messy (if you write them in assembler).

Nils

btw, I swizzle bitwise, not the 8x8 block fatmap method. I used it before, but bitwise is faster and easier to do.
Regarding the half-space triangle rasterization, near the end of the article's discussion you'll see that efortier implemented the routine with texture mapping for Pocket PC over a year ago. If he still visits PocketMatrix hopefully he'll let us know how it did performance-wise compared to the traditional span based rasterization.

The primary problem is that since it is not span based the various span based occlusion methods cannot be used. However if the performance is drastically better then it may offset the use of a Z-buffer instead. In my case, dynamic lighting is also implemented at the span level, so that would not be applicable to this half space technique either.

Dan East
Dan East wrote:The primary problem is that since it is not span based the various span based occlusion methods cannot be used. [...] In my case, dynamic lighting is also implemented at the span level, so that would not be applicable to this half space technique either.

I see. This would be equivalent to executing the vertex shader only of at least one pixel is acually going to be rendered, right? Or are you doing anything more sophisticated as part of the dynamic lighting calculations?

- HM
torus wrote:
btw, I swizzle bitwise, not the 8x8 block fatmap method. I used it before, but bitwise is faster and easier to do.

Thanks for your reply, Nils. What exactly do you mean by 'bitwise'?

- HM
hm":119pczja]

Say you have your u and v part of the address stored in variables u and v. The fixed point part is alredy chopped of.

The usual way to get the address is most probably 256*(v &255) + (u & 255)

I sort the bits into the final address like this:

address = [u7,v7,u6,v6,u5,v5,u4,v4,u3,v3,u2,v2,u1,v1,u0,v0] (bitwise) So the LSB`s of u and v are stored in the LSB's of the address.. Afterwards the scan direction inside the texture doen't affect the cache anymore.
I plugged the half-space rasterizer into my engine (the-engine-formally-known-as-Varium), and the results are dismal. This is rendering 340 polys, 64x64 texture (when utilized), full screen 240x320 (all pixels rendered to).

[edit]These half space benchmarks are flawed. See my posts below[/edit]
15 FPS: Exact half space C++ implementation as provided (flatshading, q=8 )
10 FPS: Half space with texture mapping q=8
07 FPS: Half space with texture mapping q=16
09 FPS: Half space with texture mapping q=4
51 FPS: My own standard span based rasterization no perspective correction
40 FPS: My own rasterization with gouraud but no perspective correction
32 FPS: My own rasterizer with perspective correction and gouraud shading

The half space test I performed did not include occlusion testing (span based or zbuffer), skybox (which would be completely occluded), or gouraud shading. The tests with my own rasterizers used my C++ implementation (which could use more optimization), and included occlusion testing, as well as a hidden skybox. To make things even worse, that is using my n-gon rasterizer, which is 10-20% slower than the tri rasterizer I used to use. I benchmarked rendering only tris, so my own routines would have performed even better if I were rendering polys with more than 3 sides (which is typical of content generated from MAP files).

The ASM version of my rasterizers achieves another 50% or so over the C++ implementation.

I just don't see how I could pick up 500% performance over his C++ code just by implementing it in ASM. The inner loops are already very tight, so I don't think the performance would even double.

It would be interesting to know exactly why his implementation performs so much worse, considering his code appears to execute substantially fewer instructions than mine. I also have 2-3 function calls per span too. All I can figure is there is some major stalling going on due to the cache.

Dan East
Actually, I just realized what is causing part of the disparity. I'm not testing for polys entirely outside the display, which I do with my own routines.
I'll post another set of benchmarks shortly.

Dan East
Okay, after adding some quick tests to see if the poly is visible at all, as well as to drop out of the loop when the poly is outside the bottom or right side of the display, the flatshading FPS jumped to 47, and with texture mapping it is 33.

An additional optimization would be to jump into the output buffer for polys that are off the top or left sides of the buffer.

So it is 35% slower than my non corrected routine, and that is still not using any occlusion testing with the half space routine.

Dan East
As I suspected, the difference in performance between the two routines converges as the poly count goes up. With my routines the poly setup and span routine overhead start adding up.

1200 tris
17 FPS: half space
16 FPS: my routine

That's without gouraud, but again all my spans are being checked for occlusion, where the half space is just pure rendering. Also, a standard tri rasterizer should still outperform it compared to my ngon routine at that poly count.

Dan East
Dan East wrote:Okay, after adding some quick tests to see if the poly is visible at all, as well as to drop out of the loop when the poly is outside the bottom or right side of the display, the flatshading FPS jumped to 47, and with texture mapping it is 33.

An additional optimization would be to jump into the output buffer for polys that are off the top or left sides of the buffer.

So it is 35% slower than my non corrected routine, and that is still not using any occlusion testing with the half space routine.

Dan East

Thanks for providing these numbers, Dan. Actually, I find those numbers very encouraging, at least for the stuff I am trying to put in. Might also depend on the triangle size. Do you have an idea how many pixels the average triangle in your test is generating?

- HM
Dan East wrote:As I suspected, the difference in performance between the two routines converges as the poly count goes up. With my routines the poly setup and span routine overhead start adding up.

1200 tris
17 FPS: half space
16 FPS: my routine

That's without gouraud, but again all my spans are being checked for occlusion, where the half space is just pure rendering. Also, a standard tri rasterizer should still outperform it compared to my ngon routine at that poly count.

Dan East

Dan,

what device did you use for these numbers? And I am still amazed how quickly you were able to put those benchmarks together; it took me *way* longer to properly integrate the interpolation setup etc. into the code.

- HM

PS: Other than that, I am very pleased with this approach. The code is much simpler, the performance went up, and the library footprint is down to 200k. Looks like finally the lib is starting to get useful.
Well, I'm pretty good at porting code (I ported Quake 2 from scratch to PPC in 2 days). Just getting it to run is easy, because it doesn't require a real knowledge of what the code does. :) In this case there really wasn't much for me to change. Incorporating the texture coord interpolation was the only real work.

My testing was on an Asus a716.

Here's my code. idiv16 is the same ASM integer division approximation routine posted years ago to this forum (16.16 fixed point output).

Code:

//TESTING
//http://www.devmaster.net/codespotlight/show.php?id=17

//TODO: Should round nearest, not to zero
#define iround(n) ((int)(n))
#define min(a,b,c) (a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c))
#define max(a,b,c) (a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c))

#include "fastdiv.h"

void DrawPolyGTn_test(TVxuv *pVerts, int nVerts, TFace *pFace, LIGHT **pLights, TTexture *pTexture) {
if (nVerts!=3) {
//Fall back on standard rasterizer
DrawPolyGTn(pVerts, nVerts, pFace, pLights, pTexture);
return;
}

//Determine texture interpolation values
//Cross product of values we interpolate with x and y
int A = (pVerts[2].u - pVerts[0].u) * (pVerts[1].Vx->y - pVerts[0].Vx->y) -
(pVerts[1].u - pVerts[0].u) * (pVerts[2].Vx->y - pVerts[0].Vx->y);
int B = (pVerts[2].Vx->x - pVerts[0].Vx->x) * (pVerts[1].u - pVerts[0].u) -
(pVerts[1].Vx->x - pVerts[0].Vx->x) * (pVerts[2].u - pVerts[0].u);
int C = (pVerts[1].Vx->x - pVerts[0].Vx->x) * (pVerts[2].Vx->y - pVerts[0].Vx->y) -
(pVerts[2].Vx->x - pVerts[0].Vx->x) * (pVerts[1].Vx->y - pVerts[0].Vx->y);
const int dux=idiv16(-A, C);
const int duy=idiv16(-B, C);
A = (pVerts[2].v - pVerts[0].v) * (pVerts[1].Vx->y - pVerts[0].Vx->y) -
(pVerts[1].v - pVerts[0].v) * (pVerts[2].Vx->y - pVerts[0].Vx->y);
B = (pVerts[2].Vx->x - pVerts[0].Vx->x) * (pVerts[1].v - pVerts[0].v) -
(pVerts[1].Vx->x - pVerts[0].Vx->x) * (pVerts[2].v - pVerts[0].v);
C = (pVerts[1].Vx->x - pVerts[0].Vx->x) * (pVerts[2].Vx->y - pVerts[0].Vx->y) -
(pVerts[2].Vx->x - pVerts[0].Vx->x) * (pVerts[1].Vx->y - pVerts[0].Vx->y);
const int dvx=idiv16(-A, C);
const int dvy=idiv16(-B, C);

COLOR *Tex = pTexture->pData;

//TODO: Hardcoded to 240x320 display for testing
int stride=480;
unsigned short *colorBuffer=VScreen;
unsigned short *maxBuffer=VScreen+240*320;

// 28.4 fixed-point coordinates
const int Y1 = iround(16.0f * pVerts[0].Vx->y);
const int Y2 = iround(16.0f * pVerts[1].Vx->y);
const int Y3 = iround(16.0f * pVerts[2].Vx->y);

const int X1 = iround(16.0f * pVerts[0].Vx->x);
const int X2 = iround(16.0f * pVerts[1].Vx->x);
const int X3 = iround(16.0f * pVerts[2].Vx->x);

// Deltas
const int DX12 = X1 - X2;
const int DX23 = X2 - X3;
const int DX31 = X3 - X1;

const int DY12 = Y1 - Y2;
const int DY23 = Y2 - Y3;
const int DY31 = Y3 - Y1;

// Fixed-point deltas
const int FDX12 = DX12 << 4;
const int FDX23 = DX23 << 4;
const int FDX31 = DX31 << 4;

const int FDY12 = DY12 << 4;
const int FDY23 = DY23 << 4;
const int FDY31 = DY31 << 4;

// Bounding rectangle
int minx = (min(X1, X2, X3) + 0xF) >> 4;
int maxx = (max(X1, X2, X3) + 0xF) >> 4;
int miny = (min(Y1, Y2, Y3) + 0xF) >> 4;
int maxy = (max(Y1, Y2, Y3) + 0xF) >> 4;

if (minx>240 || maxx<0)
return;
if (miny>320 || maxy<0)
return;

// Block size, standard 8x8 (must be power of two)
const int q = 8;

// Start in corner of 8x8 block
minx &= ~(q - 1);
miny &= ~(q - 1);

(char*&)colorBuffer += miny * stride;

// Half-edge constants
int C1 = DY12 * X1 - DX12 * Y1;
int C2 = DY23 * X2 - DX23 * Y2;
int C3 = DY31 * X3 - DX31 * Y3;

// Correct for fill convention
if(DY12 < 0 || (DY12 == 0 && DX12 > 0)) C1++;
if(DY23 < 0 || (DY23 == 0 && DX23 > 0)) C2++;
if(DY31 < 0 || (DY31 == 0 && DX31 > 0)) C3++;

// Loop through blocks
for(int y = miny; y < maxy; y += q)
{
if (y>320)
return;
for(int x = minx; x < maxx; x += q)
{
if (x>240)
continue;
// Corners of block
int x0 = x << 4;
int x1 = (x + q - 1) << 4;
int y0 = y << 4;
int y1 = (y + q - 1) << 4;

// Evaluate half-space functions
bool a00 = C1 + DX12 * y0 - DY12 * x0 > 0;
bool a10 = C1 + DX12 * y0 - DY12 * x1 > 0;
bool a01 = C1 + DX12 * y1 - DY12 * x0 > 0;
bool a11 = C1 + DX12 * y1 - DY12 * x1 > 0;
int a = (a00 << 0) | (a10 << 1) | (a01 << 2) | (a11 << 3);

bool b00 = C2 + DX23 * y0 - DY23 * x0 > 0;
bool b10 = C2 + DX23 * y0 - DY23 * x1 > 0;
bool b01 = C2 + DX23 * y1 - DY23 * x0 > 0;
bool b11 = C2 + DX23 * y1 - DY23 * x1 > 0;
int b = (b00 << 0) | (b10 << 1) | (b01 << 2) | (b11 << 3);

bool c00 = C3 + DX31 * y0 - DY31 * x0 > 0;
bool c10 = C3 + DX31 * y0 - DY31 * x1 > 0;
bool c01 = C3 + DX31 * y1 - DY31 * x0 > 0;
bool c11 = C3 + DX31 * y1 - DY31 * x1 > 0;
int c = (c00 << 0) | (c10 << 1) | (c01 << 2) | (c11 << 3);

// Skip block when outside an edge
if(a == 0x0 || b == 0x0 || c == 0x0) continue;

//Dan East: Texture mapping
int dx=(x)-pVerts[0].Vx->x;
int dy=(y)-pVerts[0].Vx->y;
int U=((int)pVerts[0].u<<16)+dx*dux+(duy*dy);
int V=((int)pVerts[0].v<<16)+dx*dvx+(dvy*dy);
int duystep=duy-dux*q;
int dvystep=dvy-dvx*q;

unsigned short *buffer = colorBuffer;

// Accept whole block when totally covered
if(a == 0xF && b == 0xF && c == 0xF)
{
for(int iy = 0; iy < q; iy++)
{
for(int ix = x; ix < x + q; ix++)
{
//Make sure we are in the output buffer
if (ix>=0 && ix<240 && buffer+ix<maxBuffer && buffer+ix>VScreen)
//buffer[ix]=0x1f00;
buffer[ix] = Tex[((V>>13)&0xfc0)+((U>>19)&0x3f)];
U+=dux;
V+=dvx;
}
U+=duystep;
V+=dvystep;
(char*&)buffer += stride;
}
}
else // Partially covered block
{
int CY1 = C1 + DX12 * y0 - DY12 * x0;
int CY2 = C2 + DX23 * y0 - DY23 * x0;
int CY3 = C3 + DX31 * y0 - DY31 * x0;

for(int iy = y; iy < y + q; iy++)
{
int CX1 = CY1;
int CX2 = CY2;
int CX3 = CY3;

for(int ix = x; ix < x + q; ix++)
{
if(CX1 > 0 && CX2 > 0 && CX3 > 0 &&
ix>=0 && ix<240)
{
if (buffer+ix<maxBuffer && buffer+ix>VScreen)
//buffer[ix]=0x1f00;
buffer[ix] = Tex[((V>>13)&0xfc0)+((U>>19)&0x3f)];
}

U+=dux;
V+=dvx;

CX1 -= FDY12;
CX2 -= FDY23;
CX3 -= FDY31;
}

U+=duystep;
V+=dvystep;

CY1 += FDX12;
CY2 += FDX23;
CY3 += FDX31;

(char*&)buffer += stride;
}
}
}

(char*&)colorBuffer += q * stride;
}
}
Dan East wrote:Well, I'm pretty good at porting code (I ported Quake 2 from scratch to PPC in 2 days). Just getting it to run is easy, because it doesn't require a real knowledge of what the code does. :) In this case there really wasn't much for me to change. Incorporating the texture coord interpolation was the only real work.

My testing was on an Asus a716.

Thanks, Dan.

No wonder you have been so fast; you have been cheating... I know, not really... ;-) but here's my code for comparison; does perspective correct, linear within blocks, separate depth/color path with lazy initialization of interpolation parameters, mipmap selection,... the RasterBlock... functions are replaced by the JIT in release compiles. That's actually what I liked about the approach, it's very cheap to get higher quality/features in there without making things overly complicated.

Code:

// ==========================================================================
//
// RasterizerTraingles.cpp Rasterizer Class for 3D Rendering Library
//
// The rasterizer converts transformed and lit primitives and creates a
// raster image in the current rendering surface.
//
// This files contains the triangle rasterization code, which was
// previously in the Rasterizer.cpp source file.
//
// --------------------------------------------------------------------------
//
// 05-22-2004 Hans-Martin Will initial version
// 02-19-2006 Hans-Martin Will rewrite using edge equations
//
// --------------------------------------------------------------------------
//
// Copyright (c) 2004, Hans-Martin Will. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// ==========================================================================


#include "stdafx.h"
#include "Rasterizer.h"
#include "Surface.h"
#include "Texture.h"
#include "Utils.h"
#include "arm/FunctionCache.h"

using namespace EGL;

#ifdef min
#undef min
#endif

#ifdef max
#undef max
#endif

namespace {
inline I32 min(I32 a, I32 b, I32 c) {
I32 d = (a < b) ? a : b;
return (d < c) ? d : c;
}

inline I32 max(I32 a, I32 b, I32 c) {
I32 d = (a > b) ? a : b;
return (d > c) ? d : c;
}

// 32-bit determinant with 64-bit intermediate
inline I64 det2x2(I32 a00, I32 a01, I32 a10, I32 a11) {
I64 prod1 = static_cast<I64>(a00) * static_cast<I64>(a11);
I64 prod2 = static_cast<I64>(a10) * static_cast<I64>(a01);
return static_cast<I64>(prod1 - prod2);
}

bool HasAlpha(RasterizerState::TextureFormat format) {
switch (format) {
case RasterizerState::TextureFormatAlpha:
case RasterizerState::TextureFormatLuminanceAlpha:
case RasterizerState::TextureFormatRGBA8:
case RasterizerState::TextureFormatRGBA4444:
case RasterizerState::TextureFormatRGBA5551:
return true;

default:
return false;
}
}

inline I32 Mul24(I32 a, I32 b) {
I64 product = static_cast<I64>(a) * static_cast<I64>(b);
return static_cast<I32>((product + 0x400000) >> 23);
}

inline I32 MulRoundShift(I32 a, I32 b, I32 shift) {
I64 product = static_cast<I64>(a) * static_cast<I64>(b);
return static_cast<I32>((product + (1 << (shift - 1))) >> shift);
}

inline I32 Mul(I32 a, I32 b, const I32 shift) {
I64 product = static_cast<I64>(a) * static_cast<I64>(b);
return static_cast<I32>(product >> shift);
}

inline I32 Mul64(I64 a, I32 b, const I32 shift) {
I64 product = a * b;
return static_cast<I32>(product >> shift);
}

inline I32 InvNewtonRaphson4q28(I32 a, I32 x) {
x = EGL_InverseIterQ(a, x, 28);
x = EGL_InverseIterQ(a, x, 28);

return x;
}
}


// ---------------------------------------------------------------------------
// Prepare rasterizer object for triangles
// ---------------------------------------------------------------------------

namespace EGL {
PixelMask RBDepthTestLess(const RasterInfo * rasterInfo,
const Variables * vars,
PixelMask * pixelMask);


PixelMask RBEdgeDepthTestLess(const RasterInfo * rasterInfo,
const Variables * vars,
const Edges * edges,
PixelMask * pixelMask);

void RBTextureReplace(const RasterInfo * rasterInfo,
I32 varying[][2][2],
const PixelMask * pixelMask);

}

void Rasterizer :: PrepareTriangle() {
Prepare();

memset(m_RasterInfo.MipmapLevel, 0, sizeof(m_RasterInfo.MipmapLevel));

// initialize block rasterization here

m_BlockDepthStencilFunction = (BlockDepthStencilFunction *) //&RBDepthTestLess;
m_FunctionCache->GetFunction(FunctionCache::FunctionTypeBlockDepthStencil,
*m_State, &m_VaryingInfo);

m_BlockEdgeDepthStencilFunction = (BlockEdgeDepthStencilFunction *) //&RBEdgeDepthTestLess;
m_FunctionCache->GetFunction(FunctionCache::FunctionTypeBlockEdgeDepthStencil,
*m_State, &m_VaryingInfo);

m_BlockColorAlphaFunction = (BlockColorAlphaFunction *) //&RBTextureReplace;
m_FunctionCache->GetFunction(FunctionCache::FunctionTypeBlockColorAlpha,
*m_State, &m_VaryingInfo);
}

#if !EGL_USE_JIT

PixelMask Rasterizer :: RasterBlockDepthStencil(const Variables * vars,
PixelMask * pixelMask) {

PixelMask * mask = pixelMask, totalMask = 0;
I32 depth0 = vars->Depth.Value;

// initialize surface pointers in local info block
SurfaceInfo surfaceInfo = m_RasterInfo.RasterSurface;

for (I32 iy = 0; iy < EGL_RASTER_BLOCK_SIZE; iy++) {

PixelMask rowMask = 0;

for (I32 ix = 0; ix < EGL_RASTER_BLOCK_SIZE; ix++) {

// test and write depth and stencil
bool written = FragmentDepthStencil(&m_RasterInfo, &surfaceInfo, ix, depth0 >> 4);

rowMask = (rowMask >> 1) | (written ? (1 << (EGL_RASTER_BLOCK_SIZE - 1)) : 0);
depth0 += vars->Depth.dX;
}

*mask++ = rowMask;
totalMask |= rowMask;

depth0 += vars->Depth.dY - (vars->Depth.dX << EGL_LOG_RASTER_BLOCK_SIZE);

surfaceInfo.DepthBuffer += surfaceInfo.Pitch;
surfaceInfo.StencilBuffer += surfaceInfo.Pitch;
}

return totalMask;
}

PixelMask Rasterizer :: RasterBlockEdgeDepthStencil(const Variables * vars,
const Edges * edges,
PixelMask * pixelMask) {

PixelMask * mask = pixelMask, totalMask = 0;
I32 depth0 = vars->Depth.Value;

// initialize surface pointers in local info block
SurfaceInfo surfaceInfo = m_RasterInfo.RasterSurface;

I32 CY1 = edges->edge12.CY;
I32 CY2 = edges->edge23.CY;
I32 CY3 = edges->edge31.CY;

for (I32 iy = 0; iy < EGL_RASTER_BLOCK_SIZE; iy++) {
GLint CX1 = CY1, CX2 = CY2, CX3 = CY3;
I32 depth1 = depth0;
PixelMask rowMask = 0;
bool done = false;

for(I32 ix = 0; ix < EGL_RASTER_BLOCK_SIZE; ix++) {
if (CX1 > 0 && CX2 > 0 && CX3 > 0) {
// test and write depth and stencil
bool written = FragmentDepthStencil(&m_RasterInfo, &surfaceInfo, ix, depth1 >> 4);
rowMask >>= 1;
rowMask |= written ? (1 << (EGL_RASTER_BLOCK_SIZE - 1)) : 0;
done = true;
} else if (done) {
rowMask >>= EGL_RASTER_BLOCK_SIZE - ix;
break;
} else {
rowMask >>= 1;
}

CX1 += edges->edge12.FDY;
CX2 += edges->edge23.FDY;
CX3 += edges->edge31.FDY;
depth1 += vars->Depth.dX;
}

*mask++ = rowMask;
totalMask |= rowMask;

CY1 -= edges->edge12.FDX;
CY2 -= edges->edge23.FDX;
CY3 -= edges->edge31.FDX;

depth0 += vars->Depth.dY;

surfaceInfo.DepthBuffer += surfaceInfo.Pitch;
surfaceInfo.StencilBuffer += surfaceInfo.Pitch;
}

return totalMask;
}

void Rasterizer :: RasterBlockColorAlpha(I32 varying[][2][2],
const PixelMask * pixelMask) {
const PixelMask * mask = pixelMask;

// initialize surface pointers in local info block
SurfaceInfo surfaceInfo = m_RasterInfo.RasterSurface;

for (I32 iy = 0; iy < EGL_RASTER_BLOCK_SIZE; iy++) {

I32 index;
I32 varying0[EGL_MAX_NUM_VARYING][2];
PixelMask rowMask = *mask++;

for (index = 0; index < m_VaryingInfo.numVarying; ++index) {
varying0[index][0] = varying[index][0][0];
varying0[index][1] = (varying[index][1][0] - varying[index][0][0]) >> EGL_LOG_RASTER_BLOCK_SIZE;
}

for (I32 ix = 0; ix < EGL_RASTER_BLOCK_SIZE; ix++) {

if (rowMask & 1) {
I32 tu[EGL_NUM_TEXTURE_UNITS], tv[EGL_NUM_TEXTURE_UNITS];
Color baseColor;
I32 fog;

for (I32 unit = 0; unit < EGL_NUM_TEXTURE_UNITS; ++unit) {
size_t textureBase = m_VaryingInfo.textureBase[unit];

if (textureBase >= 0) {
tu[unit] = varying0[textureBase][0];
tv[unit] = varying0[textureBase + 1][0];
}
}

if (m_VaryingInfo.colorIndex >= 0) {
//baseColor = FractionalColor(varying0 + m_VaryingInfo.colorIndex);
baseColor = FractionalColor(
varying0[m_VaryingInfo.colorIndex][0],
varying0[m_VaryingInfo.colorIndex + 1][0],
varying0[m_VaryingInfo.colorIndex + 2][0],
varying0[m_VaryingInfo.colorIndex + 3][0]);
}

if (m_VaryingInfo.fogIndex >= 0) {
fog = varying0[m_VaryingInfo.fogIndex][0];
}

FragmentColorAlpha(&m_RasterInfo, &surfaceInfo, ix, tu, tv, baseColor, fog);
}

if (!(rowMask >>= 1))
break;

for (index = 0; index < m_VaryingInfo.numVarying; ++index) {
varying0[index][0] += varying0[index][1];
}
}

for (index = 0; index < m_VaryingInfo.numVarying; ++index) {
varying[index][0][0] += varying[index][0][1];
varying[index][1][0] += varying[index][1][1];
}

surfaceInfo.ColorBuffer += surfaceInfo.Pitch;
surfaceInfo.AlphaBuffer += surfaceInfo.Pitch;
}
}

#endif

void Rasterizer :: RasterTriangle(const Vertex& a, const Vertex& b,
const Vertex& c) {

I32 x, y; // block index loop vars
I32 index, unit; // index into varying variable array & texture unit

Variables vars;

Edges edges;

// 16.16 -> 28.4 fixed-point coordinates
const I32 X1 = (a.m_WindowCoords.x + (1 << 11)) >> 12;
const I32 X2 = (b.m_WindowCoords.x + (1 << 11)) >> 12;
const I32 X3 = (c.m_WindowCoords.x + (1 << 11)) >> 12;

// Deltas
const I32 DX12 = X1 - X2;
const I32 DX23 = X2 - X3;
const I32 DX31 = X3 - X1;

// 24.8 Fixed-point deltas
edges.edge12.FDX = DX12 << 4;
edges.edge23.FDX = DX23 << 4;
edges.edge31.FDX = DX31 << 4;

// 16.16 -> 28.4 fixed-point coordinates
const I32 Y1 = (a.m_WindowCoords.y + (1 << 11)) >> 12;
const I32 Y2 = (b.m_WindowCoords.y + (1 << 11)) >> 12;
const I32 Y3 = (c.m_WindowCoords.y + (1 << 11)) >> 12;

const I32 DY12 = Y1 - Y2;
const I32 DY23 = Y2 - Y3;
const I32 DY31 = Y3 - Y1;

edges.edge12.FDY = DY12 << 4;
edges.edge23.FDY = DY23 << 4;
edges.edge31.FDY = DY31 << 4;

// setup of interpolation of varying vars goes here
// area in 24.8
I32 area = DX31 * DY12 - DX12 * DY31;

if (area <= 0xf)
return;

// inv arera as 8.24
I32 invArea = EGL_InverseQ(area, 8);

// Bounding rectangle; round lower bound down to block size
const I32 minx = ((min(X1, X2, X3) + 0x7) >> 4) & ~(EGL_RASTER_BLOCK_SIZE - 1);
const I32 miny = ((min(Y1, Y2, Y3) + 0x7) >> 4) & ~(EGL_RASTER_BLOCK_SIZE - 1);
const I32 maxx = ((max(X1, X2, X3) + 0x8) >> 4) + (EGL_RASTER_BLOCK_SIZE - 1) & ~(EGL_RASTER_BLOCK_SIZE - 1);
const I32 maxy = ((max(Y1, Y2, Y3) + 0x8) >> 4) + (EGL_RASTER_BLOCK_SIZE - 1) & ~(EGL_RASTER_BLOCK_SIZE - 1);
const I32 span = maxx - minx;

m_RasterInfo.Init(m_Surface, miny, minx);
I32 blockStride = EGL_RASTER_BLOCK_SIZE * m_RasterInfo.RasterSurface.Pitch - span;

const U32 numVarying = m_VaryingInfo.numVarying;
U32 usedNumVarying = 0;


// Half-edge constants
I32 C1 = Y2 * X1 - X2 * Y1;
I32 C2 = Y3 * X2 - X3 * Y2;
I32 C3 = Y1 * X3 - X1 * Y3;

// Correct for fill convention
if (DY12 > 0 || (DY12 == 0 && DX12 < 0)) C1++;
if (DY23 > 0 || (DY23 == 0 && DX23 < 0)) C2++;
if (DY31 > 0 || (DY31 == 0 && DX31 < 0)) C3++;

I32 XMin1 = (minx << 4) + (1 << 3) - X1;
I32 YMin1 = (miny << 4) + (1 << 3) - Y1;

// Deltas
const I32 DD12 = (a.m_WindowCoords.depth - b.m_WindowCoords.depth) << 4;
const I32 DD23 = (b.m_WindowCoords.depth - c.m_WindowCoords.depth) << 4;
const I32 DD31 = (c.m_WindowCoords.depth - a.m_WindowCoords.depth) << 4;

vars.Depth.dX = Mul64(det2x2(DY12, DD12, DY31, DD31), invArea, 28);
vars.Depth.dY = -Mul64(det2x2(DX12, DD12, DX31, DD31), invArea, 28);
I32 depthSlope= EGL_Max(EGL_Abs(vars.Depth.dX), EGL_Abs(vars.Depth.dY));
I32 factor = EGL_Mul(depthSlope, m_State->GetPolygonOffsetFactor());
vars.Depth.dBlockLine = vars.Depth.dY * EGL_RASTER_BLOCK_SIZE - vars.Depth.dX * span;
vars.Depth.Value = (a.m_WindowCoords.depth << 4)
+ ((m_State->GetPolygonOffsetUnits() + (1 << 11)) >> 12)
+ factor
+ Mul(XMin1, vars.Depth.dX, 4)
+ Mul(YMin1, vars.Depth.dY, 4);

const I32 DW12 = a.m_WindowCoords.invW - b.m_WindowCoords.invW;
const I32 DW23 = b.m_WindowCoords.invW - c.m_WindowCoords.invW;
const I32 DW31 = c.m_WindowCoords.invW - a.m_WindowCoords.invW;

// dWdX, dWdY is 4.28
vars.InvW.dX = Mul64(det2x2(DY12, DW12, DY31, DW31), invArea, 28);
vars.InvW.dY = -Mul64(det2x2(DX12, DW12, DX31, DW31), invArea, 28);
vars.InvW.dBlockLine = vars.InvW.dY * EGL_RASTER_BLOCK_SIZE - vars.InvW.dX * span;
vars.InvW.Value = a.m_WindowCoords.invW
+ Mul(XMin1, vars.InvW.dX, 4)
+ Mul(YMin1, vars.InvW.dY, 4);

// Loop through blocks
for (y = miny; y < maxy; y += EGL_RASTER_BLOCK_SIZE) {

for (x = minx; x < maxx; x += EGL_RASTER_BLOCK_SIZE) {

// Corners of block as 28.4; move to pixel centers
GLint x0 = (x << 4) | (1 << 3);
GLint y0 = (y << 4) | (1 << 3);

// Evaluate half-space functions
edges.edge12.CY = C1 + DY12 * x0 - DX12 * y0;

GLint pass1 = edges.edge12.CY > 0;
pass1 += edges.edge12.CY + (edges.edge12.FDY << EGL_LOG_RASTER_BLOCK_SIZE) > 0;
pass1 += edges.edge12.CY - (edges.edge12.FDX << EGL_LOG_RASTER_BLOCK_SIZE) > 0;
pass1 += edges.edge12.CY + (edges.edge12.FDY << EGL_LOG_RASTER_BLOCK_SIZE)
- (edges.edge12.FDX << EGL_LOG_RASTER_BLOCK_SIZE) > 0;

edges.edge23.CY = C2 + DY23 * x0 - DX23 * y0;
GLint pass2 = edges.edge23.CY > 0;
pass2 += edges.edge23.CY + (edges.edge23.FDY << EGL_LOG_RASTER_BLOCK_SIZE) > 0;
pass2 += edges.edge23.CY - (edges.edge23.FDX << EGL_LOG_RASTER_BLOCK_SIZE) > 0;
pass2 += edges.edge23.CY + (edges.edge23.FDY << EGL_LOG_RASTER_BLOCK_SIZE)
- (edges.edge23.FDX << EGL_LOG_RASTER_BLOCK_SIZE) > 0;

edges.edge31.CY = C3 + DY31 * x0 - DX31 * y0;
GLint pass3 = edges.edge31.CY > 0;
pass3 += edges.edge31.CY + (edges.edge31.FDY << EGL_LOG_RASTER_BLOCK_SIZE) > 0;
pass3 += edges.edge31.CY - (edges.edge31.FDX << EGL_LOG_RASTER_BLOCK_SIZE) > 0;
pass3 += edges.edge31.CY + (edges.edge31.FDY << EGL_LOG_RASTER_BLOCK_SIZE)
- (edges.edge31.FDX << EGL_LOG_RASTER_BLOCK_SIZE) > 0;

PixelMask pixelMask[EGL_RASTER_BLOCK_SIZE];
PixelMask totalMask;

// Skip block when outside an edge
if (pass1 == 0x0 || pass2 == 0x0 || pass3 == 0x0) {
goto cont;
}

// Accept whole block when totally covered
if (pass1 + pass2 + pass3 == 12) {
#if !EGL_USE_JIT
totalMask = RasterBlockDepthStencil(&vars, pixelMask);
#else
totalMask = m_BlockDepthStencilFunction(&m_RasterInfo, &vars, pixelMask);
//totalMask = RBDepthTestLess(&m_RasterInfo, &vars, pixelMask);
#endif
} else {
// Partially covered block
// initialize surface pointers in local info block
#if !EGL_USE_JIT
totalMask = RasterBlockEdgeDepthStencil(&vars, &edges, pixelMask);
#else
totalMask = m_BlockEdgeDepthStencilFunction(&m_RasterInfo, &vars, &edges, pixelMask);
//totalMask = RBEdgeDepthTestLess(&m_RasterInfo, &vars, &edges, pixelMask);
#endif
}

if (totalMask) {
if (numVarying != usedNumVarying) {
I32 XMin2 = x0 - X1;
I32 YMin2 = y0 - Y1;

usedNumVarying = numVarying;

for (index = usedNumVarying; --index >= 0; ) {
// 4.28
I32 V1OverW = Mul(a.m_Varying[index], a.m_WindowCoords.invW, 16);
I32 V2OverW = Mul(b.m_Varying[index], b.m_WindowCoords.invW, 16);
I32 V3OverW = Mul(c.m_Varying[index], c.m_WindowCoords.invW, 16);

I32 IVW12 = V1OverW - V2OverW;
I32 IVW31 = V3OverW - V1OverW;

// dVaryingDx, dVaryingDy is 4.28
vars.VaryingInvW[index].dX = Mul64(det2x2(DY12, IVW12, DY31, IVW31), invArea, 28);
vars.VaryingInvW[index].dY = -Mul64(det2x2(DX12, IVW12, DX31, IVW31), invArea, 28);
vars.VaryingInvW[index].dBlockLine =
vars.VaryingInvW[index].dY * EGL_RASTER_BLOCK_SIZE - vars.VaryingInvW[index].dX * span;

// varyingStart is 4.28
vars.VaryingInvW[index].Value =
V1OverW
+ Mul(XMin2, vars.VaryingInvW[index].dX, 4)
+ Mul(YMin2, vars.VaryingInvW[index].dY, 4);
}

}

// interpolation values for the four corners
I32 w[2][2]; // w in all four corners of block 4.28 (?)

I32 varying[EGL_MAX_NUM_VARYING][2][2]; //

// compute w in all four corners
w[0][0] = EGL_InverseQ(vars.InvW.Value, 28); // 4.28
w[0][1] = InvNewtonRaphson4q28(vars.InvW.Value + vars.InvW.dX * EGL_RASTER_BLOCK_SIZE, w[0][0]);
w[1][0] = InvNewtonRaphson4q28(vars.InvW.Value + vars.InvW.dY * EGL_RASTER_BLOCK_SIZE, w[0][0]);
w[1][1] = InvNewtonRaphson4q28(vars.InvW.Value + vars.InvW.dX * EGL_RASTER_BLOCK_SIZE
+ vars.InvW.dY * EGL_RASTER_BLOCK_SIZE, w[1][0]);

// compute values of varying at all four corners
for (index = usedNumVarying; --index >= 0; ) {
varying[index][0][0] = Mul(vars.VaryingInvW[index].Value, w[0][0], 16);
varying[index][0][1] =
(Mul(vars.VaryingInvW[index].Value
+ (vars.VaryingInvW[index].dY << EGL_LOG_RASTER_BLOCK_SIZE), w[1][0], 16)
- varying[index][0][0]) >> EGL_LOG_RASTER_BLOCK_SIZE;

varying[index][1][0] =
Mul(vars.VaryingInvW[index].Value
+ (vars.VaryingInvW[index].dX << EGL_LOG_RASTER_BLOCK_SIZE), w[0][1], 16);
varying[index][1][1] =
(Mul(vars.VaryingInvW[index].Value
+ (vars.VaryingInvW[index].dX << EGL_LOG_RASTER_BLOCK_SIZE)
+ (vars.VaryingInvW[index].dY << EGL_LOG_RASTER_BLOCK_SIZE), w[1][1], 16)
- varying[index][1][0]) >> EGL_LOG_RASTER_BLOCK_SIZE;
}

// perform Mipmap selection; initialize local RasterInfo structure
unit = EGL_NUM_TEXTURE_UNITS - 1;
do {
I32 textureBase = m_VaryingInfo.textureBase[unit];

if (textureBase >= 0 && m_UseMipmap[unit]) {
I32 dUdX = ((varying[textureBase][1][0] << 1)
+ (varying[textureBase][1][1] << EGL_LOG_RASTER_BLOCK_SIZE)
- (varying[textureBase][0][0] << 1)
- (varying[textureBase][0][1] << EGL_LOG_RASTER_BLOCK_SIZE))
>> (EGL_LOG_RASTER_BLOCK_SIZE + 1);
I32 dUdY = (varying[textureBase][0][1] + varying[textureBase][1][1]) >> 1;
I32 dVdX = ((varying[textureBase + 1][1][0] << 1)
+ (varying[textureBase + 1][1][1] << EGL_LOG_RASTER_BLOCK_SIZE)
- (varying[textureBase + 1][0][0] << 1)
- (varying[textureBase + 1][0][1] << EGL_LOG_RASTER_BLOCK_SIZE))
>> (EGL_LOG_RASTER_BLOCK_SIZE + 1);
I32 dVdY = (varying[textureBase + 1][0][1] + varying[textureBase + 1][1][1]) >> 1;

I32 maxDu = EGL_Max(EGL_Abs(dUdX), EGL_Abs(dUdY)) >> (16 - m_Texture[unit]->GetTexture(0)->GetLogWidth());
I32 maxDv = EGL_Max(EGL_Abs(dVdX), EGL_Abs(dVdY)) >> (16 - m_Texture[unit]->GetTexture(0)->GetLogHeight());

I32 rho = EGL_Max(maxDu, maxDv);

// we start with nearest/minification only selection; will add LINEAR later
m_RasterInfo.MipmapLevel[unit] = EGL_Min(Log2(rho), m_RasterInfo.MaxMipmapLevel[unit]);
} else {
m_RasterInfo.MipmapLevel[unit] = 0;
}

if (--unit < 0)
break;
} while (true);

#if !EGL_USE_JIT
RasterBlockColorAlpha(varying, pixelMask);
#else
m_BlockColorAlphaFunction(&m_RasterInfo, varying, pixelMask);
//RBTextureReplace(&m_RasterInfo, varying, pixelMask);
#endif
}
cont:
vars.Depth.Value += vars.Depth.dX << EGL_LOG_RASTER_BLOCK_SIZE;
vars.InvW.Value += vars.InvW.dX << EGL_LOG_RASTER_BLOCK_SIZE;

for (index = usedNumVarying; --index >= 0; ) {
vars.VaryingInvW[index].Value += vars.VaryingInvW[index].dX << EGL_LOG_RASTER_BLOCK_SIZE;
}

m_RasterInfo.RasterSurface.ColorBuffer += EGL_RASTER_BLOCK_SIZE;
m_RasterInfo.RasterSurface.DepthBuffer += EGL_RASTER_BLOCK_SIZE;
m_RasterInfo.RasterSurface.AlphaBuffer += EGL_RASTER_BLOCK_SIZE;
m_RasterInfo.RasterSurface.StencilBuffer += EGL_RASTER_BLOCK_SIZE;
}

vars.Depth.Value += vars.Depth.dBlockLine;
vars.InvW.Value += vars.InvW.dBlockLine;

for (index = usedNumVarying; --index >= 0; ) {
vars.VaryingInvW[index].Value += vars.VaryingInvW[index].dBlockLine;
}

m_RasterInfo.RasterSurface.ColorBuffer += blockStride;
m_RasterInfo.RasterSurface.DepthBuffer += blockStride;
m_RasterInfo.RasterSurface.AlphaBuffer += blockStride;
m_RasterInfo.RasterSurface.StencilBuffer += blockStride;
}
}


- HM
I've tried the original simple implementation of this half space rasterizer, but it misses a lot of pixels (holes between triangles)..

I don't know what I am doing wrong, I used the version with fixed point precision and fill convention...
StephC wrote:I've tried the original simple implementation of this half space rasterizer, but it misses a lot of pixels (holes between triangles)..

I don't know what I am doing wrong, I used the version with fixed point precision and fill convention...

No idea. The version I am using seems to work very reliably; at least good enough to run the OpenGL ES conformance test, which has a couple of tests that verify proper lining up of adjacent and/or clipped objects.

- HM