429f51d3052909b39486940f644b2fb6dd8b6a37
[mupen64plus-pandora.git] / source / gles2rice / src / RenderBase.cpp
1 /*
2 Copyright (C) 2003 Rice1964
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17
18 */
19
20 #include <cmath>
21 #include <vector>
22
23 #include "osal_preproc.h"
24 #include "float.h"
25 #include "DeviceBuilder.h"
26 #include "VertexShaderConstantDef.h"
27 #include "Render.h"
28 #include "Timing.h"
29
30 extern FiddledVtx * g_pVtxBase;
31
32 #define ENABLE_CLIP_TRI
33 #define X_CLIP_MAX  0x1
34 #define X_CLIP_MIN  0x2
35 #define Y_CLIP_MAX  0x4
36 #define Y_CLIP_MIN  0x8
37 #define Z_CLIP_MAX  0x10
38 #define Z_CLIP_MIN  0x20
39
40 #ifdef ENABLE_CLIP_TRI
41
42 inline void RSP_Vtx_Clipping(int i)
43 {
44     g_clipFlag[i] = 0;
45     g_clipFlag2[i] = 0;
46     if( g_vecProjected[i].w > 0 )
47     {
48         /*
49         if( gRSP.bRejectVtx )
50         {
51             if( g_vecProjected[i].x > 1 )   
52             {
53                 g_clipFlag2[i] |= X_CLIP_MAX;
54                 if( g_vecProjected[i].x > gRSP.real_clip_ratio_posx )   
55                     g_clipFlag[i] |= X_CLIP_MAX;
56             }
57
58             if( g_vecProjected[i].x < -1 )  
59             {
60                 g_clipFlag2[i] |= X_CLIP_MIN;
61                 if( g_vecProjected[i].x < gRSP.real_clip_ratio_negx )   
62                     g_clipFlag[i] |= X_CLIP_MIN;
63             }
64
65             if( g_vecProjected[i].y > 1 )   
66             {
67                 g_clipFlag2[i] |= Y_CLIP_MAX;
68                 if( g_vecProjected[i].y > gRSP.real_clip_ratio_posy )   
69                     g_clipFlag[i] |= Y_CLIP_MAX;
70             }
71
72             if( g_vecProjected[i].y < -1 )  
73             {
74                 g_clipFlag2[i] |= Y_CLIP_MIN;
75                 if( g_vecProjected[i].y < gRSP.real_clip_ratio_negy )   
76                     g_clipFlag[i] |= Y_CLIP_MIN;
77             }
78
79             //if( g_vecProjected[i].z > 1.0f )  
80             //{
81             //  g_clipFlag2[i] |= Z_CLIP_MAX;
82             //  g_clipFlag[i] |= Z_CLIP_MAX;
83             //}
84
85             //if( gRSP.bNearClip && g_vecProjected[i].z < -1.0f )   
86             //{
87             //  g_clipFlag2[i] |= Z_CLIP_MIN;
88             //  g_clipFlag[i] |= Z_CLIP_MIN;
89             //}
90         }
91         else
92         */
93         {
94             if( g_vecProjected[i].x > 1 )   g_clipFlag2[i] |= X_CLIP_MAX;
95             if( g_vecProjected[i].x < -1 )  g_clipFlag2[i] |= X_CLIP_MIN;
96             if( g_vecProjected[i].y > 1 )   g_clipFlag2[i] |= Y_CLIP_MAX;
97             if( g_vecProjected[i].y < -1 )  g_clipFlag2[i] |= Y_CLIP_MIN;
98             //if( g_vecProjected[i].z > 1.0f )  g_clipFlag2[i] |= Z_CLIP_MAX;
99             //if( gRSP.bNearClip && g_vecProjected[i].z < -1.0f )   g_clipFlag2[i] |= Z_CLIP_MIN;
100         }
101
102     }
103 }
104
105 #else
106 inline void RSP_Vtx_Clipping(int i) {}
107 #endif
108
109 /*
110  *  Global variables
111  */
112 ALIGN(16,RSP_Options gRSP)
113 ALIGN(16,RDP_Options gRDP)
114
115 static ALIGN(16,XVECTOR4 g_normal)
116 //static int norms[3];
117
118 ALIGN(16,XVECTOR4 g_vtxNonTransformed[MAX_VERTS])
119 ALIGN(16,XVECTOR4 g_vecProjected[MAX_VERTS])
120 ALIGN(16,XVECTOR4 g_vtxTransformed[MAX_VERTS])
121
122 float       g_vtxProjected5[1000][5];
123 float       g_vtxProjected5Clipped[2000][5];
124
125 //uint32        g_dwVtxFlags[MAX_VERTS];            // Z_POS Z_NEG etc
126 VECTOR2     g_fVtxTxtCoords[MAX_VERTS];
127 uint32      g_dwVtxDifColor[MAX_VERTS];
128 uint32      g_clipFlag[MAX_VERTS];
129 uint32      g_clipFlag2[MAX_VERTS];
130 RenderTexture g_textures[MAX_TEXTURES];
131 float       g_fFogCoord[MAX_VERTS];
132
133 EXTERNAL_VERTEX g_vtxForExternal[MAX_VERTS];
134
135 TLITVERTEX          g_vtxBuffer[1000];
136 TLITVERTEX          g_clippedVtxBuffer[2000];
137 uint8               g_oglVtxColors[1000][4];
138 int                 g_clippedVtxCount=0;
139 TLITVERTEX          g_texRectTVtx[4];
140 unsigned short      g_vtxIndex[1000];
141 unsigned int        g_minIndex, g_maxIndex;
142
143 float               gRSPfFogMin;
144 float               gRSPfFogMax;
145 float               gRSPfFogDivider;
146
147 uint32          gRSPnumLights;
148 Light   gRSPlights[16];
149
150 ALIGN(16,Matrix  gRSPworldProjectTransported)
151 ALIGN(16,Matrix  gRSPworldProject)
152 ALIGN(16,Matrix  gRSPmodelViewTop)
153 ALIGN(16,Matrix  gRSPmodelViewTopTranspose)
154 ALIGN(16,Matrix  dkrMatrixTransposed)
155
156 N64Light        gRSPn64lights[16];
157
158
159 void (*ProcessVertexData)(uint32 dwAddr, uint32 dwV0, uint32 dwNum)=NULL;
160
161 /*
162  *  
163  */
164
165
166 /*n.x = (g_normal.x * matWorld.m00) + (g_normal.y * matWorld.m10) + (g_normal.z * matWorld.m20);
167 n.y = (g_normal.x * matWorld.m01) + (g_normal.y * matWorld.m11) + (g_normal.z * matWorld.m21);
168 n.z = (g_normal.x * matWorld.m02) + (g_normal.y * matWorld.m12) + (g_normal.z * matWorld.m22);*/
169
170 // Multiply (x,y,z,0) by matrix m, then normalize
171 #if defined(__INTEL_COMPILER) && !defined(NO_ASM)
172 #define Vec3TransformNormal(vec, m) __asm                   \
173 {                                       \
174     __asm fld   dword ptr [vec + 0]     \
175     __asm fmul  dword ptr [m + 0]       \ /* x m00*/
176     __asm fld   dword ptr [vec + 0]     \
177     __asm fmul  dword ptr [m + 4]       \ /* x m01  x m00*/
178     __asm fld   dword ptr [vec + 0]     \
179     __asm fmul  dword ptr [m + 8]       \ /* x m02  x m01  x m00*/
180                                         \
181     __asm fld   dword ptr [vec + 4]     \
182     __asm fmul  dword ptr [m + 16]      \ /* y m10  x m02  x m01  x m00*/
183     __asm fld   dword ptr [vec + 4]     \
184     __asm fmul  dword ptr [m + 20]      \ /* y m11  y m10  x m02  x m01  x m00*/
185     __asm fld   dword ptr [vec + 4]     \
186     __asm fmul  dword ptr [m + 24]      \ /* y m12  y m11  y m10  x m02  x m01  x m00*/
187                                         \
188     __asm fxch  st(2)                   \ /* y m10  y m11  y m12  x m02  x m01  x m00*/
189     __asm faddp st(5), st(0)            \ /* y m11  y m12  x m02  x m01  (x m00 + y m10)*/
190     __asm faddp st(3), st(0)            \ /* y m12  x m02  (x m01 + ym11)  (x m00 + y m10)*/
191     __asm faddp st(1), st(0)            \ /* (x m02 + y m12) (x m01 + ym11)  (x m00 + y m10)*/
192                                         \
193     __asm fld   dword ptr [vec + 8]     \
194     __asm fmul  dword ptr [m + 32]      \ /* z m20  (x m02 + y m12) (x m01 + ym11)  (x m00 + y m10)*/
195     __asm fld   dword ptr [vec + 8]     \
196     __asm fmul  dword ptr [m + 36]      \ /* z m21  z m20  (x m02 + y m12) (x m01 + ym11)  (x m00 + y m10)*/
197     __asm fld   dword ptr [vec + 8]     \
198     __asm fmul  dword ptr [m + 40]      \ /* z m22  z m21  z m20  (x m02 + y m12) (x m01 + ym11)  (x m00 + y m10)*/
199                                         \
200     __asm fxch  st(2)                   \ /* z m20  z m21  z m22  (x m02 + y m12) (x m01 + ym11)  (x m00 + y m10)*/
201     __asm faddp st(5), st(0)            \ /* z m21  z m22  (x m02 + y m12) (x m01 + ym11)  (x m00 + y m10 + z m20)*/ 
202     __asm faddp st(3), st(0)            \ /* z m22  (x m02 + y m12) (x m01 + ym11 + z m21)  (x m00 + y m10 + z m20)*/
203     __asm faddp st(1), st(0)            \ /* (x m02 + y m12 + z m 22) (x m01 + ym11 + z m21)  (x m00 + y m10 + z m20)*/
204                                         \
205     __asm fxch  st(2)                   \ /* (x m00 + y m10 + z m20) (x m01 + ym11 + z m21) (x m02 + y m12 + z m 22) */
206                                         \
207     __asm fld1                          \ /* 1 x y z */
208     __asm fld   st(1)                   \ /* x 1 x y z */
209     __asm fmul  st(0),st(0)             \ /* xx 1 x y z */
210     __asm fld   st(3)                   \ /* y xx 1 x y z */
211     __asm fmul  st(0),st(0)             \ /* yy xx 1 x y z */
212     __asm fld   st(5)                   \ /* z yy xx 1 x y z */
213     __asm fmul  st(0),st(0)             \ /* zz yy xx 1 x y z */
214                                         \
215     __asm fxch  st(2)                   \ /* xx yy zz 1 x y z */
216                                         \
217     __asm faddp st(1),st(0)             \ /* (xx+yy) zz 1 x y z */
218     __asm faddp st(1),st(0)             \ /* (xx+yy+zz) 1 x y z */
219                                         \
220     __asm ftst                          \ /* Compare ST to 0  */
221     __asm fstsw ax                      \ /* Store FPU status word in a   */
222     __asm sahf                          \ /* Transfer ax to flags register */
223     __asm jz        l2                  \ /* Skip if length is zero   */
224                                         \
225     __asm fsqrt                         \ /* l 1 x y z */
226                                         \
227     __asm fdivp st(1),st(0)             \ /* (1/l) x y z */
228                                         \
229     __asm fmul  st(3),st(0)             \ /* f x y fz */
230     __asm fmul  st(2),st(0)             \ /* f x fy fz */
231     __asm fmulp st(1),st(0)             \ /* fx fy fz */
232                                         \
233     __asm fstp  dword ptr [vec + 0]     \ /* fy fz*/
234     __asm fstp  dword ptr [vec + 4]     \ /* fz   */
235     __asm fstp  dword ptr [vec + 8]     \ /* done */
236     __asm jmp   l3                      \
237 __asm l2:                               \
238     __asm mov dword ptr [vec + 0], 0    \
239     __asm mov dword ptr [vec + 4], 0    \
240     __asm mov dword ptr [vec + 8], 0    \
241 __asm l3:                               \
242 }                                       \
243
244 #else  // use C code in other cases, this is probably faster anyway
245 #define Vec3TransformNormal(vec, m) \
246    VECTOR3 temp; \
247    temp.x = (vec.x * m._11) + (vec.y * m._21) + (vec.z * m._31); \
248    temp.y = (vec.x * m._12) + (vec.y * m._22) + (vec.z * m._32); \
249    temp.z = (vec.x * m._13) + (vec.y * m._23) + (vec.z * m._33); \
250    float norm = sqrt(temp.x*temp.x+temp.y*temp.y+temp.z*temp.z); \
251    if (norm == 0.0) { vec.x = 0.0; vec.y = 0.0; vec.z = 0.0;} else \
252    { vec.x = temp.x/norm; vec.y = temp.y/norm; vec.z = temp.z/norm; }
253 #endif
254
255
256 #if !defined(__GNUC__) && !defined(NO_ASM)
257 __declspec( naked ) void  __fastcall SSEVec3Transform(int i)
258 {
259     __asm
260     {
261         shl     ecx,4;      // ecx = i
262
263         movaps  xmm1,   DWORD PTR g_vtxNonTransformed [ecx];        // xmm1 as original vector
264
265         movaps  xmm4,   DWORD PTR gRSPworldProjectTransported;          // row1
266         movaps  xmm5,   DWORD PTR gRSPworldProjectTransported[0x10];    // row2
267         movaps  xmm6,   DWORD PTR gRSPworldProjectTransported[0x20];    // row3
268         movaps  xmm7,   DWORD PTR gRSPworldProjectTransported[0x30];    // row4
269
270         mulps   xmm4, xmm1;     // row 1
271         mulps   xmm5, xmm1;     // row 2
272         mulps   xmm6, xmm1;     // row 3
273         mulps   xmm7, xmm1;     // row 4
274
275         movhlps xmm0, xmm4;     // xmm4 high to xmm0 low
276         movlhps xmm0, xmm5;     // xmm5 low to xmm0 high
277
278         addps   xmm4, xmm0;     // result of add are in xmm4 low
279         addps   xmm5, xmm0;     // result of add are in xmm5 high
280
281         shufps  xmm0, xmm4, 0x44;   // move xmm4 low DWORDs to xmm0 high
282         shufps  xmm4, xmm5, 0xe4;   // move xmm5 high DWORS to xmm4
283         movhlps xmm5, xmm0;         // xmm4, xmm5 are mirrored
284
285         shufps  xmm4, xmm4, 0x08;   // move xmm4's 3rd uint32 to its 2nd uint32
286         shufps  xmm5, xmm5, 0x0d;   // move xmm5's 4th uint32 to its 2nd uint32, 
287                                     // and move its 2nd uint32 to its 1st uint32
288         
289         addps   xmm4, xmm5;     // results are in 1st and 2nd uint32
290
291
292         movhlps xmm0, xmm6;     // xmm6 high to xmm0 low
293         movlhps xmm0, xmm7;     // xmm7 low to xmm0 high
294
295         addps   xmm6, xmm0;     // result of add are in xmm6 low
296         addps   xmm7, xmm0;     // result of add are in xmm7 high
297
298         shufps  xmm0, xmm6, 0x44;   // move xmm6 low DWORDs to xmm0 high
299         shufps  xmm6, xmm7, 0xe4;   // move xmm7 high DWORS to xmm6
300         movhlps xmm7, xmm0;         // xmm6, xmm7 are mirrored
301
302         shufps  xmm6, xmm6, 0x08;   // move xmm6's 3rd uint32 to its 2nd uint32
303         shufps  xmm7, xmm7, 0x0d;   // move xmm7's 4th uint32 to its 2nd uint32, 
304                                     // and move its 2nd uint32 to its 1st uint32
305         
306         addps   xmm6, xmm7;     // results are in 1st and 2nd uint32
307         
308         movlhps xmm4, xmm6;     // final result is in xmm4
309         movaps  DWORD PTR g_vtxTransformed [ecx], xmm4;
310
311         movaps  xmm0,xmm4;
312         shufps  xmm0,xmm0,0xff;
313         divps   xmm4,xmm0;
314         rcpps   xmm0,xmm0;
315         movhlps xmm0,xmm4;
316         shufps  xmm0,xmm0,0xe8;
317         movlhps xmm4,xmm0;
318
319         movaps  DWORD PTR g_vecProjected [ecx], xmm4;
320
321         emms;
322         ret;
323     }
324 }
325
326 // Only used by DKR
327 __declspec( naked ) void  __fastcall SSEVec3TransformDKR(XVECTOR4 &pOut, const XVECTOR4 &pV)
328 {
329     __asm
330     {
331         movaps  xmm1,   DWORD PTR [edx];        // xmm1 as original vector
332
333         movaps  xmm4,   DWORD PTR dkrMatrixTransposed;  // row1
334         movaps  xmm5,   DWORD PTR dkrMatrixTransposed[0x10];    // row2
335         movaps  xmm6,   DWORD PTR dkrMatrixTransposed[0x20];    // row3
336         movaps  xmm7,   DWORD PTR dkrMatrixTransposed[0x30];    // row4
337
338         mulps   xmm4, xmm1;     // row 1
339         mulps   xmm5, xmm1;     // row 2
340         mulps   xmm6, xmm1;     // row 3
341         mulps   xmm7, xmm1;     // row 4
342
343         movhlps xmm0, xmm4;     // xmm4 high to xmm0 low
344         movlhps xmm0, xmm5;     // xmm5 low to xmm0 high
345
346         addps   xmm4, xmm0;     // result of add are in xmm4 low
347         addps   xmm5, xmm0;     // result of add are in xmm5 high
348
349         shufps  xmm0, xmm4, 0x44;   // move xmm4 low DWORDs to xmm0 high
350         shufps  xmm4, xmm5, 0xe4;   // move xmm5 high DWORS to xmm4
351         movhlps xmm5, xmm0;         // xmm4, xmm5 are mirrored
352
353         shufps  xmm4, xmm4, 0x08;   // move xmm4's 3rd uint32 to its 2nd uint32
354         shufps  xmm5, xmm5, 0x0d;   // move xmm5's 4th uint32 to its 2nd uint32, 
355         // and move its 2nd uint32 to its 1st uint32
356
357         addps   xmm4, xmm5;     // results are in 1st and 2nd uint32
358
359
360         movhlps xmm0, xmm6;     // xmm6 high to xmm0 low
361         movlhps xmm0, xmm7;     // xmm7 low to xmm0 high
362
363         addps   xmm6, xmm0;     // result of add are in xmm6 low
364         addps   xmm7, xmm0;     // result of add are in xmm7 high
365
366         shufps  xmm0, xmm6, 0x44;   // move xmm6 low DWORDs to xmm0 high
367         shufps  xmm6, xmm7, 0xe4;   // move xmm7 high DWORS to xmm6
368         movhlps xmm7, xmm0;         // xmm6, xmm7 are mirrored
369
370         shufps  xmm6, xmm6, 0x08;   // move xmm6's 3rd uint32 to its 2nd uint32
371         shufps  xmm7, xmm7, 0x0d;   // move xmm7's 4th uint32 to its 2nd uint32, 
372         // and move its 2nd uint32 to its 1st uint32
373
374         addps   xmm6, xmm7;     // results are in 1st and 2nd uint32
375
376         movlhps xmm4, xmm6;     // final result is in xmm4
377         movaps  DWORD PTR [ecx], xmm4;
378
379         emms;
380         ret;
381     }
382 }
383 #elif defined(__GNUC__) && defined(__x86_64__) && !defined(NO_ASM)
384 void SSEVec3Transform(int i)
385 {
386   asm volatile(" shl               $4,      %0   \n"
387                " movslq           %k0,     %q0   \n"
388                " movaps      (%1,%q0),  %%xmm1   \n"
389                " movaps         0(%2),  %%xmm4   \n"
390                " movaps        16(%2),  %%xmm5   \n"
391                " movaps        32(%2),  %%xmm6   \n"
392                " movaps        48(%2),  %%xmm7   \n"
393                " mulps         %%xmm1,  %%xmm4   \n"
394                " mulps         %%xmm1,  %%xmm5   \n"
395                " mulps         %%xmm1,  %%xmm6   \n"
396                " mulps         %%xmm1,  %%xmm7   \n"
397                " movhlps       %%xmm4,  %%xmm0   \n"
398                " movlhps       %%xmm5,  %%xmm0   \n"
399                " addps         %%xmm0,  %%xmm4   \n"
400                " addps         %%xmm0,  %%xmm5   \n"
401                " shufps $0x44, %%xmm4,  %%xmm0   \n"
402                " shufps $0xe4, %%xmm5,  %%xmm4   \n"
403                " movhlps       %%xmm0,  %%xmm5   \n"
404                " shufps $0x08, %%xmm4,  %%xmm4   \n"
405                " shufps $0x0d, %%xmm5,  %%xmm5   \n"
406                " addps         %%xmm5,  %%xmm4   \n"
407                " movhlps       %%xmm6,  %%xmm0   \n"
408                " movlhps       %%xmm7,  %%xmm0   \n"
409                " addps         %%xmm0,  %%xmm6   \n"
410                " addps         %%xmm0,  %%xmm7   \n"
411                " shufps $0x44, %%xmm6,  %%xmm0   \n"
412                " shufps $0xe4, %%xmm7,  %%xmm6   \n"
413                " movhlps       %%xmm0,  %%xmm7   \n"
414                " shufps $0x08, %%xmm6,  %%xmm6   \n"
415                " shufps $0x0d, %%xmm7,  %%xmm7   \n"
416                " addps         %%xmm7,  %%xmm6   \n"
417                " movlhps       %%xmm6,  %%xmm4   \n"
418                " movaps        %%xmm4, (%3,%q0)  \n"
419                " movaps        %%xmm4,  %%xmm0   \n"
420                " shufps $0xff, %%xmm0,  %%xmm0   \n"
421                " divps         %%xmm0,  %%xmm4   \n"
422                " rcpps         %%xmm0,  %%xmm0   \n"
423                " movhlps       %%xmm4,  %%xmm0   \n"
424                " shufps $0xe8, %%xmm0,  %%xmm0   \n"
425                " movlhps       %%xmm0,  %%xmm4   \n"
426                " movaps        %%xmm4, (%4,%q0)  \n"
427                : "+r"(i)
428                : "r"(g_vtxNonTransformed), "r"(&gRSPworldProjectTransported.m[0][0]), "r"(g_vtxTransformed), "r"(g_vecProjected)
429                : "memory", "%xmm0", "%xmm1", "%xmm4", "%xmm5", "%xmm6", "%xmm7"
430                );
431 }
432 #elif !defined(NO_ASM) // 32-bit GCC assumed
433 void SSEVec3Transform(int i)
434 {
435   asm volatile(" shl               $4,      %0   \n"
436                " movaps       (%1,%0),  %%xmm1   \n"
437                " movaps         0(%2),  %%xmm4   \n"
438                " movaps        16(%2),  %%xmm5   \n"
439                " movaps        32(%2),  %%xmm6   \n"
440                " movaps        48(%2),  %%xmm7   \n"
441                " mulps         %%xmm1,  %%xmm4   \n"
442                " mulps         %%xmm1,  %%xmm5   \n"
443                " mulps         %%xmm1,  %%xmm6   \n"
444                " mulps         %%xmm1,  %%xmm7   \n"
445                " movhlps       %%xmm4,  %%xmm0   \n"
446                " movlhps       %%xmm5,  %%xmm0   \n"
447                " addps         %%xmm0,  %%xmm4   \n"
448                " addps         %%xmm0,  %%xmm5   \n"
449                " shufps $0x44, %%xmm4,  %%xmm0   \n"
450                " shufps $0xe4, %%xmm5,  %%xmm4   \n"
451                " movhlps       %%xmm0,  %%xmm5   \n"
452                " shufps $0x08, %%xmm4,  %%xmm4   \n"
453                " shufps $0x0d, %%xmm5,  %%xmm5   \n"
454                " addps         %%xmm5,  %%xmm4   \n"
455                " movhlps       %%xmm6,  %%xmm0   \n"
456                " movlhps       %%xmm7,  %%xmm0   \n"
457                " addps         %%xmm0,  %%xmm6   \n"
458                " addps         %%xmm0,  %%xmm7   \n"
459                " shufps $0x44, %%xmm6,  %%xmm0   \n"
460                " shufps $0xe4, %%xmm7,  %%xmm6   \n"
461                " movhlps       %%xmm0,  %%xmm7   \n"
462                " shufps $0x08, %%xmm6,  %%xmm6   \n"
463                " shufps $0x0d, %%xmm7,  %%xmm7   \n"
464                " addps         %%xmm7,  %%xmm6   \n"
465                " movlhps       %%xmm6,  %%xmm4   \n"
466                " movaps        %%xmm4,  (%3,%0)  \n"
467                " movaps        %%xmm4,  %%xmm0   \n"
468                " shufps $0xff, %%xmm0,  %%xmm0   \n"
469                " divps         %%xmm0,  %%xmm4   \n"
470                " rcpps         %%xmm0,  %%xmm0   \n"
471                " movhlps       %%xmm4,  %%xmm0   \n"
472                " shufps $0xe8, %%xmm0,  %%xmm0   \n"
473                " movlhps       %%xmm0,  %%xmm4   \n"
474                " movaps        %%xmm4,  (%4,%0)  \n"
475                : "+r"(i)
476                : "r"(g_vtxNonTransformed), "r"(&gRSPworldProjectTransported.m[0][0]), "r"(g_vtxTransformed), "r"(g_vecProjected)
477                : "memory", "%xmm0", "%xmm1", "%xmm4", "%xmm5", "%xmm6", "%xmm7"
478                );
479 }
480 #endif
481 float real255 = 255.0f;
482 float real128 = 128.0f;
483
484 #if !defined(__GNUC__) && !defined(NO_ASM)
485 __declspec( naked ) void  __fastcall SSEVec3TransformNormal()
486 {
487     __asm
488     {
489         mov     DWORD PTR [g_normal][12], 0;
490
491         movaps  xmm4,   DWORD PTR gRSPmodelViewTopTranspose;    // row1
492         movaps  xmm5,   DWORD PTR gRSPmodelViewTopTranspose[0x10];  // row2
493         movaps  xmm1,   DWORD PTR [g_normal];       // xmm1 as the normal vector
494         movaps  xmm6,   DWORD PTR gRSPmodelViewTopTranspose[0x20];  // row3
495
496         mulps   xmm4, xmm1;     // row 1
497         mulps   xmm5, xmm1;     // row 2
498         mulps   xmm6, xmm1;     // row 3
499
500         movhlps xmm0, xmm4;     // xmm4 high to xmm0 low
501         movlhps xmm0, xmm5;     // xmm5 low to xmm0 high
502
503         addps   xmm4, xmm0;     // result of add are in xmm4 low
504         addps   xmm5, xmm0;     // result of add are in xmm5 high
505
506         shufps  xmm0, xmm4, 0x44;   // move xmm4 low DWORDs to xmm0 high
507         shufps  xmm4, xmm5, 0xe4;   // move xmm5 high DWORS to xmm4
508         movhlps xmm5, xmm0;         // xmm4, xmm5 are mirrored
509
510         shufps  xmm4, xmm4, 0x08;   // move xmm4's 3rd uint32 to its 2nd uint32
511         shufps  xmm5, xmm5, 0x0d;   // move xmm5's 4th uint32 to its 2nd uint32, 
512
513         addps   xmm4, xmm5;     // results are in 1st and 2nd uint32
514
515         movaps  xmm1,xmm4;
516         mulps   xmm1,xmm1;  //square
517         movlhps xmm7, xmm1;
518         shufps  xmm7, xmm7,0x03;
519         addss   xmm7, xmm1;
520
521         movhlps xmm0, xmm6;     // xmm6 high to xmm0 low
522         addps   xmm6, xmm0;     // result of add are in xmm6 low
523
524         movlhps xmm0, xmm6;
525         shufps  xmm0, xmm0, 0x03;
526         addss   xmm0, xmm6;     // result of add is at xmm0's 1st uint32
527
528         movlhps xmm4, xmm0;
529
530         mulss   xmm0,xmm0;
531         addss   xmm7,xmm0;      // xmm7 1st uint32 is the sum of squares
532
533 #ifdef DEBUGGER
534         movaps  DWORD PTR [g_normal], xmm4;
535         movss  DWORD PTR [g_normal][12], xmm7;
536 #endif
537         xorps   xmm0,xmm0;
538         ucomiss xmm0,xmm7;
539         jz      l2
540
541         rsqrtss xmm7,xmm7;
542         shufps  xmm7,xmm7,0;
543 #ifdef DEBUGGER
544         movss  DWORD PTR [g_normal][12], xmm7;
545 #endif
546         mulps   xmm4,xmm7;
547
548         movaps  DWORD PTR [g_normal], xmm4;     // Normalized
549         mov     DWORD PTR [g_normal][12], 0;
550
551         emms;
552         ret;
553 l2:
554         movss   DWORD PTR [g_normal], xmm0;
555         movss   DWORD PTR [g_normal][12], xmm0;
556         emms;
557         ret;
558     }
559 }
560 #elif defined(__GNUC__) && !defined(NO_ASM)  // this code should compile for both 64-bit and 32-bit architectures
561 void SSEVec3TransformNormal(void)
562 {
563   asm volatile(" movl              $0,  12(%0)    \n"
564            " movaps          (%1),  %%xmm4    \n"
565            " movaps        16(%1),  %%xmm5    \n"
566            " movaps          (%0),  %%xmm1    \n"
567            " movaps        32(%1),  %%xmm6    \n"
568            " mulps         %%xmm1,  %%xmm4    \n"
569            " mulps         %%xmm1,  %%xmm5    \n"
570            " mulps         %%xmm1,  %%xmm6    \n"
571            " movhlps       %%xmm4,  %%xmm0    \n"
572            " movlhps       %%xmm5,  %%xmm0    \n"
573            " addps         %%xmm0,  %%xmm4    \n"
574            " addps         %%xmm0,  %%xmm5    \n"
575            " shufps $0x44, %%xmm4,  %%xmm0    \n"
576            " shufps $0xe4, %%xmm5,  %%xmm4    \n"
577            " movhlps       %%xmm0,  %%xmm5    \n"
578            " shufps $0x08, %%xmm4,  %%xmm4    \n"
579            " shufps $0x0d, %%xmm5,  %%xmm5    \n"
580            " addps         %%xmm5,  %%xmm4    \n"
581            " movaps        %%xmm4,  %%xmm1    \n"
582            " mulps         %%xmm1,  %%xmm1    \n"
583            " movlhps       %%xmm1,  %%xmm7    \n"
584            " shufps $0x03, %%xmm7,  %%xmm7    \n"
585            " addss         %%xmm1,  %%xmm7    \n"
586            " movhlps       %%xmm6,  %%xmm0    \n"
587            " addps         %%xmm0,  %%xmm6    \n"
588            " movlhps       %%xmm6,  %%xmm0    \n"
589            " shufps $0x03, %%xmm0,  %%xmm0    \n"
590            " addss         %%xmm6,  %%xmm0    \n"
591            " movlhps       %%xmm0,  %%xmm4    \n"
592            " mulss         %%xmm0,  %%xmm0    \n"
593            " addss         %%xmm0,  %%xmm7    \n"
594 #ifdef DEBUGGER
595            " movaps        %%xmm4,    (%0)    \n"
596            " movss         %%xmm7,  12(%0)    \n"
597 #endif
598            " xorps         %%xmm0,  %%xmm0    \n"
599            " ucomiss       %%xmm7,  %%xmm0    \n"
600            " jz                0f             \n"
601            " rsqrtss       %%xmm7,  %%xmm7    \n"
602            " shufps $0x00, %%xmm7,  %%xmm7    \n"
603 #ifdef DEBUGGER
604            " movss         %%xmm7,  12(%0)    \n"
605 #endif
606                " mulps         %%xmm7,  %%xmm4    \n"
607                " movaps        %%xmm4,    (%0)    \n"
608                " movl              $0,  12(%0)    \n"
609                " jmp               1f             \n"
610                "0:                                \n"
611                " movss         %%xmm0,    (%0)    \n"
612                " movss         %%xmm0,  12(%0)    \n"
613                "1:                                \n"
614                :
615                : "r"(&g_normal.x), "r"(&gRSPmodelViewTopTranspose.m[0][0])
616                : "memory", "cc", "%xmm0", "%xmm1", "%xmm4", "%xmm5", "%xmm6", "%xmm7"
617                );
618 }
619 #endif
620
621 void NormalizeNormalVec()
622 {
623     float w = 1/sqrtf(g_normal.x*g_normal.x + g_normal.y*g_normal.y + g_normal.z*g_normal.z);
624     g_normal.x *= w;
625     g_normal.y *= w;
626     g_normal.z *= w;
627 }
628
629
630 void InitRenderBase()
631 {
632 #if !defined(NO_ASM)
633     if( status.isSSEEnabled && !g_curRomInfo.bPrimaryDepthHack && options.enableHackForGames != HACK_FOR_NASCAR)
634     {
635         ProcessVertexData = ProcessVertexDataSSE;
636     }
637     else
638 #elif defined(__ARM_NEON__)
639     if( !g_curRomInfo.bPrimaryDepthHack && options.enableHackForGames != HACK_FOR_NASCAR && options.enableHackForGames != HACK_FOR_ZELDA_MM && !options.bWinFrameMode)
640     {
641         ProcessVertexData = ProcessVertexDataNEON;
642     }
643     else
644 #endif
645     {
646         ProcessVertexData = ProcessVertexDataNoSSE;
647     }
648
649     gRSPfFogMin = gRSPfFogMax = 0.0f;
650     windowSetting.fMultX = windowSetting.fMultY = 2.0f;
651     windowSetting.vpLeftW = windowSetting.vpTopW = 0;
652     windowSetting.vpRightW = windowSetting.vpWidthW = 640;
653     windowSetting.vpBottomW = windowSetting.vpHeightW = 480;
654     gRSP.maxZ = 0;
655     gRSP.nVPLeftN = gRSP.nVPTopN = 0;
656     gRSP.nVPRightN = 640;
657     gRSP.nVPBottomN = 640;
658     gRSP.nVPWidthN = 640;
659     gRSP.nVPHeightN = 640;
660     gRDP.scissor.left=gRDP.scissor.top=0;
661     gRDP.scissor.right=gRDP.scissor.bottom=640;
662     
663     gRSP.bLightingEnable = gRSP.bTextureGen = false;
664     gRSP.curTile=gRSPnumLights=gRSP.ambientLightColor=gRSP.ambientLightIndex= 0;
665     gRSP.fAmbientLightR=gRSP.fAmbientLightG=gRSP.fAmbientLightB=0;
666     gRSP.projectionMtxTop = gRSP.modelViewMtxTop = 0;
667     gRDP.fogColor = gRDP.primitiveColor = gRDP.envColor = gRDP.primitiveDepth = gRDP.primLODMin = gRDP.primLODFrac = gRDP.LODFrac = 0;
668     gRDP.fPrimitiveDepth = 0;
669     gRSP.numVertices = 0;
670     gRSP.maxVertexID = 0;
671     gRSP.bCullFront=false;
672     gRSP.bCullBack=true;
673     gRSP.bFogEnabled=gRDP.bFogEnableInBlender=false;
674     gRSP.bZBufferEnabled=true;
675     gRSP.shadeMode=SHADE_SMOOTH;
676     gRDP.keyR=gRDP.keyG=gRDP.keyB=gRDP.keyA=gRDP.keyRGB=gRDP.keyRGBA = 0;
677     gRDP.fKeyA = 0;
678     gRSP.DKRCMatrixIndex = gRSP.dwDKRVtxAddr = gRSP.dwDKRMatrixAddr = 0;
679     gRSP.DKRBillBoard = false;
680
681     gRSP.fTexScaleX = 1/32.0f;
682     gRSP.fTexScaleY = 1/32.0f;
683     gRSP.bTextureEnabled = FALSE;
684
685     gRSP.clip_ratio_left = 0;
686     gRSP.clip_ratio_top = 0;
687     gRSP.clip_ratio_right = 640;
688     gRSP.clip_ratio_bottom = 480;
689     gRSP.clip_ratio_negx = 1;
690     gRSP.clip_ratio_negy = 1;
691     gRSP.clip_ratio_posx = 1;
692     gRSP.clip_ratio_posy = 1;
693     gRSP.real_clip_scissor_left = 0;
694     gRSP.real_clip_scissor_top = 0;
695     gRSP.real_clip_scissor_right = 640;
696     gRSP.real_clip_scissor_bottom = 480;
697     windowSetting.clipping.left = 0;
698     windowSetting.clipping.top = 0;
699     windowSetting.clipping.right = 640;
700     windowSetting.clipping.bottom = 480;
701     windowSetting.clipping.width = 640;
702     windowSetting.clipping.height = 480;
703     windowSetting.clipping.needToClip = false;
704     gRSP.real_clip_ratio_negx = 1;
705     gRSP.real_clip_ratio_negy = 1;
706     gRSP.real_clip_ratio_posx = 1;
707     gRSP.real_clip_ratio_posy = 1;
708
709     gRSP.DKRCMatrixIndex=0;
710     gRSP.DKRVtxCount=0;
711     gRSP.DKRBillBoard = false;
712     gRSP.dwDKRVtxAddr=0;
713     gRSP.dwDKRMatrixAddr=0;
714
715
716     gRDP.geometryMode   = 0;
717     gRDP.otherModeL     = 0;
718     gRDP.otherModeH     = 0;
719     gRDP.fillColor      = 0xFFFFFFFF;
720     gRDP.originalFillColor  =0;
721
722     gRSP.ucode      = 1;
723     gRSP.vertexMult = 10;
724     gRSP.bNearClip  = false;
725     gRSP.bRejectVtx = false;
726
727     gRDP.texturesAreReloaded = false;
728     gRDP.textureIsChanged = false;
729     gRDP.colorsAreReloaded = false;
730
731     memset(&gRDP.otherMode,0,sizeof(RDP_OtherMode));
732     memset(&gRDP.tiles,0,sizeof(Tile)*8);
733
734     for( int i=0; i<MAX_VERTS; i++ )
735     {
736         g_clipFlag[i] = 0;
737         g_vtxNonTransformed[i].w = 1;
738     }
739
740     memset(gRSPn64lights, 0, sizeof(N64Light)*16);
741 }
742
743 void SetFogMinMax(float fMin, float fMax, float fMul, float fOffset)
744 {
745     if( fMin > fMax )
746     {
747         float temp = fMin;
748         fMin = fMax;
749         fMax = temp;
750     }
751
752     {
753         gRSPfFogMin = max(0,fMin/500-1);
754         gRSPfFogMax = fMax/500-1;
755     }
756
757     gRSPfFogDivider = 255/(gRSPfFogMax-gRSPfFogMin);
758     CRender::g_pRender->SetFogMinMax(fMin, fMax);
759 }
760
761 void InitVertexColors()
762 {
763 }
764
765 void InitVertexTextureConstants()
766 {
767     float scaleX;
768     float scaleY;
769
770     RenderTexture &tex0 = g_textures[gRSP.curTile];
771     //CTexture *surf = tex0.m_pCTexture;
772     Tile &tile0 = gRDP.tiles[gRSP.curTile];
773
774     scaleX = gRSP.fTexScaleX;
775     scaleY = gRSP.fTexScaleY;
776
777     gRSP.tex0scaleX = scaleX * tile0.fShiftScaleS/tex0.m_fTexWidth;
778     gRSP.tex0scaleY = scaleY * tile0.fShiftScaleT/tex0.m_fTexHeight;
779
780     gRSP.tex0OffsetX = tile0.fhilite_sl/tex0.m_fTexWidth;
781     gRSP.tex0OffsetY = tile0.fhilite_tl/tex0.m_fTexHeight;
782
783     if( CRender::g_pRender->IsTexel1Enable() )
784     {
785         RenderTexture &tex1 = g_textures[(gRSP.curTile+1)&7];
786         //CTexture *surf = tex1.m_pCTexture;
787         Tile &tile1 = gRDP.tiles[(gRSP.curTile+1)&7];
788
789         gRSP.tex1scaleX = scaleX * tile1.fShiftScaleS/tex1.m_fTexWidth;
790         gRSP.tex1scaleY = scaleY * tile1.fShiftScaleT/tex1.m_fTexHeight;
791
792         gRSP.tex1OffsetX = tile1.fhilite_sl/tex1.m_fTexWidth;
793         gRSP.tex1OffsetY = tile1.fhilite_tl/tex1.m_fTexHeight;
794     }
795
796     gRSP.texGenXRatio = tile0.fShiftScaleS;
797     gRSP.texGenYRatio = gRSP.fTexScaleX/gRSP.fTexScaleY*tex0.m_fTexWidth/tex0.m_fTexHeight*tile0.fShiftScaleT;
798 }
799
800 void TexGen(float &s, float &t)
801 {
802     if (gRDP.geometryMode & G_TEXTURE_GEN_LINEAR)
803     {   
804         s = acosf(g_normal.x) / 3.14159f;
805         t = acosf(g_normal.y) / 3.14159f;
806     }
807     else
808     {
809         s = 0.5f * ( 1.0f + g_normal.x);
810         t = 0.5f * ( 1.0f - g_normal.y);
811     }
812 }
813
814 void ComputeLOD(bool openGL)
815 {
816     TLITVERTEX &v0 = g_vtxBuffer[0];
817     TLITVERTEX &v1 = g_vtxBuffer[1];
818     RenderTexture &tex0 = g_textures[gRSP.curTile];
819
820     float d,dt;
821     if( openGL )
822     {
823         float x = g_vtxProjected5[0][0] / g_vtxProjected5[0][4] - g_vtxProjected5[1][0] / g_vtxProjected5[1][4];
824         float y = g_vtxProjected5[0][1] / g_vtxProjected5[0][4] - g_vtxProjected5[1][1] / g_vtxProjected5[1][4];
825
826         x = windowSetting.vpWidthW*x/windowSetting.fMultX/2;
827         y = windowSetting.vpHeightW*y/windowSetting.fMultY/2;
828         d = sqrtf(x*x+y*y);
829     }
830     else
831     {
832         float x = (v0.x - v1.x)/ windowSetting.fMultX;
833         float y = (v0.y - v1.y)/ windowSetting.fMultY;
834         d = sqrtf(x*x+y*y);
835     }
836
837     float s0 = v0.tcord[0].u * tex0.m_fTexWidth;
838     float t0 = v0.tcord[0].v * tex0.m_fTexHeight;
839     float s1 = v1.tcord[0].u * tex0.m_fTexWidth;
840     float t1 = v1.tcord[0].v * tex0.m_fTexHeight;
841
842     dt = sqrtf((s0-s1)*(s0-s1)+(t0-t1)*(t0-t1));
843
844     float lod = dt/d;
845     float frac = log10f(lod)/log10f(2.0f);
846     //DEBUGGER_IF_DUMP(pauseAtNext,{DebuggerAppendMsg("LOD frac = %f", frac);});
847     frac = (lod / powf(2.0f,floorf(frac)));
848     frac = frac - floorf(frac);
849     //DEBUGGER_IF_DUMP(pauseAtNext,{DebuggerAppendMsg("LOD = %f, frac = %f", lod, frac);});
850     gRDP.LODFrac = (uint32)(frac*255);
851     CRender::g_pRender->SetCombinerAndBlender();
852 }
853
854 bool bHalfTxtScale=false;
855 extern uint32 lastSetTile;
856
857 void InitVertex(uint32 dwV, uint32 vtxIndex, bool bTexture, bool openGL)
858 {
859     VTX_DUMP(TRACE2("Init vertex (%d) to vtx buf[%d]:", dwV, vtxIndex));
860
861     TLITVERTEX &v = g_vtxBuffer[vtxIndex];
862     VTX_DUMP(TRACE4("  Trans: x=%f, y=%f, z=%f, w=%f",  g_vtxTransformed[dwV].x,g_vtxTransformed[dwV].y,g_vtxTransformed[dwV].z,g_vtxTransformed[dwV].w));
863     if( openGL )
864     {
865         g_vtxProjected5[vtxIndex][0] = g_vtxTransformed[dwV].x;
866         g_vtxProjected5[vtxIndex][1] = g_vtxTransformed[dwV].y;
867         g_vtxProjected5[vtxIndex][2] = g_vtxTransformed[dwV].z;
868         g_vtxProjected5[vtxIndex][3] = g_vtxTransformed[dwV].w;
869         g_vtxProjected5[vtxIndex][4] = g_vecProjected[dwV].z;
870
871         if( g_vtxTransformed[dwV].w < 0 )
872             g_vtxProjected5[vtxIndex][4] = 0;
873
874         g_vtxIndex[vtxIndex] = vtxIndex;
875     }
876
877     if( !openGL || options.bOGLVertexClipper == TRUE )
878     {
879         v.x = g_vecProjected[dwV].x*gRSP.vtxXMul+gRSP.vtxXAdd;
880         v.y = g_vecProjected[dwV].y*gRSP.vtxYMul+gRSP.vtxYAdd;
881         v.z = (g_vecProjected[dwV].z + 1.0f) * 0.5f;    // DirectX minZ=0, maxZ=1
882         //v.z = g_vecProjected[dwV].z;  // DirectX minZ=0, maxZ=1
883         v.rhw = g_vecProjected[dwV].w;
884         VTX_DUMP(TRACE4("  Proj : x=%f, y=%f, z=%f, rhw=%f",  v.x,v.y,v.z,v.rhw));
885
886         if( gRSP.bProcessSpecularColor )
887         {
888             v.dcSpecular = CRender::g_pRender->PostProcessSpecularColor();
889             if( gRSP.bFogEnabled )
890             {
891                 v.dcSpecular &= 0x00FFFFFF;
892                 uint32  fogFct = 0xFF-(uint8)((g_fFogCoord[dwV]-gRSPfFogMin)*gRSPfFogDivider);
893                 v.dcSpecular |= (fogFct<<24);
894             }
895         }
896         else if( gRSP.bFogEnabled )
897         {
898             uint32  fogFct = 0xFF-(uint8)((g_fFogCoord[dwV]-gRSPfFogMin)*gRSPfFogDivider);
899             v.dcSpecular = (fogFct<<24);
900         }
901     }
902     VTX_DUMP(TRACE2("  (U,V): %f, %f",  g_fVtxTxtCoords[dwV].x,g_fVtxTxtCoords[dwV].y));
903
904     v.dcDiffuse = g_dwVtxDifColor[dwV];
905     if( gRDP.otherMode.key_en )
906     {
907         v.dcDiffuse &= 0x00FFFFFF;
908         v.dcDiffuse |= (gRDP.keyA<<24);
909     }
910     else if( gRDP.otherMode.aa_en && gRDP.otherMode.clr_on_cvg==0 )
911     {
912         v.dcDiffuse |= 0xFF000000;
913     }
914
915     if( gRSP.bProcessDiffuseColor )
916     {
917         v.dcDiffuse = CRender::g_pRender->PostProcessDiffuseColor(v.dcDiffuse);
918     }
919     if( options.bWinFrameMode )
920     {
921         v.dcDiffuse = g_dwVtxDifColor[dwV];
922     }
923
924     if( openGL )
925     {
926         g_oglVtxColors[vtxIndex][0] = v.r;
927         g_oglVtxColors[vtxIndex][1] = v.g;
928         g_oglVtxColors[vtxIndex][2] = v.b;
929         g_oglVtxColors[vtxIndex][3] = v.a;
930     }
931
932     if( bTexture )
933     {
934         // If the vert is already lit, then there is no normal (and hence we can't generate tex coord)
935         // Only scale if not generated automatically
936         if (gRSP.bTextureGen && gRSP.bLightingEnable)
937         {
938             // Correction for texGen result
939             float u0,u1,v0,v1;
940             RenderTexture &tex0 = g_textures[gRSP.curTile];
941             u0 = g_fVtxTxtCoords[dwV].x * 32 * 1024 * gRSP.fTexScaleX / tex0.m_fTexWidth;
942             v0 = g_fVtxTxtCoords[dwV].y * 32 * 1024 * gRSP.fTexScaleY / tex0.m_fTexHeight;
943             u0 *= (gRDP.tiles[gRSP.curTile].fShiftScaleS);
944             v0 *= (gRDP.tiles[gRSP.curTile].fShiftScaleT);
945
946             if( CRender::g_pRender->IsTexel1Enable() )
947             {
948                 RenderTexture &tex1 = g_textures[(gRSP.curTile+1)&7];
949                 u1 = g_fVtxTxtCoords[dwV].x * 32 * 1024 * gRSP.fTexScaleX / tex1.m_fTexWidth;
950                 v1 = g_fVtxTxtCoords[dwV].y * 32 * 1024 * gRSP.fTexScaleY / tex1.m_fTexHeight;
951                 u1 *= gRDP.tiles[(gRSP.curTile+1)&7].fShiftScaleS;
952                 v1 *= gRDP.tiles[(gRSP.curTile+1)&7].fShiftScaleT;
953                 CRender::g_pRender->SetVertexTextureUVCoord(v, u0, v0, u1, v1);
954             }
955             else
956             {
957                 CRender::g_pRender->SetVertexTextureUVCoord(v, u0, v0);
958             }
959         }
960         else
961         {
962             float tex0u = g_fVtxTxtCoords[dwV].x *gRSP.tex0scaleX - gRSP.tex0OffsetX ;
963             float tex0v = g_fVtxTxtCoords[dwV].y *gRSP.tex0scaleY - gRSP.tex0OffsetY ;
964
965             if( CRender::g_pRender->IsTexel1Enable() )
966             {
967                 float tex1u = g_fVtxTxtCoords[dwV].x *gRSP.tex1scaleX - gRSP.tex1OffsetX ;
968                 float tex1v = g_fVtxTxtCoords[dwV].y *gRSP.tex1scaleY - gRSP.tex1OffsetY ;
969
970                 CRender::g_pRender->SetVertexTextureUVCoord(v, tex0u, tex0v, tex1u, tex1v);
971                 VTX_DUMP(TRACE2("  (tex0): %f, %f",  tex0u,tex0v));
972                 VTX_DUMP(TRACE2("  (tex1): %f, %f",  tex1u,tex1v));
973             }
974             else
975             {
976                 CRender::g_pRender->SetVertexTextureUVCoord(v, tex0u, tex0v);
977                 VTX_DUMP(TRACE2("  (tex0): %f, %f",  tex0u,tex0v));
978             }
979         }
980
981         // Check for txt scale hack
982         if( !bHalfTxtScale && g_curRomInfo.bTextureScaleHack &&
983             (gRDP.tiles[lastSetTile].dwSize == TXT_SIZE_32b || gRDP.tiles[lastSetTile].dwSize == TXT_SIZE_4b ) )
984         {
985             int width = ((gRDP.tiles[lastSetTile].sh-gRDP.tiles[lastSetTile].sl+1)<<1);
986             int height = ((gRDP.tiles[lastSetTile].th-gRDP.tiles[lastSetTile].tl+1)<<1);
987             if( g_fVtxTxtCoords[dwV].x*gRSP.fTexScaleX == width || g_fVtxTxtCoords[dwV].y*gRSP.fTexScaleY == height )
988             {
989                 bHalfTxtScale=true;
990             }
991         }
992     }
993
994     if( g_curRomInfo.bEnableTxtLOD && vtxIndex == 1 && gRDP.otherMode.text_lod )
995     {
996         if( CRender::g_pRender->IsTexel1Enable() && CRender::g_pRender->m_pColorCombiner->m_pDecodedMux->isUsed(MUX_LODFRAC) )
997         {
998             ComputeLOD(openGL);
999         }
1000         else
1001         {
1002             gRDP.LODFrac = 0;
1003         }
1004     }
1005
1006     VTX_DUMP(TRACE2("  DIF(%08X), SPE(%08X)",   v.dcDiffuse, v.dcSpecular));
1007     VTX_DUMP(TRACE0(""));
1008 }
1009
1010 uint32 LightVert(XVECTOR4 & norm, int vidx)
1011 {
1012     float fCosT;
1013
1014     // Do ambient
1015     register float r = gRSP.fAmbientLightR;
1016     register float g = gRSP.fAmbientLightG;
1017     register float b = gRSP.fAmbientLightB;
1018
1019     if( options.enableHackForGames != HACK_FOR_ZELDA_MM )
1020     {
1021         for (register unsigned int l=0; l < gRSPnumLights; l++)
1022         {
1023             fCosT = norm.x*gRSPlights[l].x + norm.y*gRSPlights[l].y + norm.z*gRSPlights[l].z; 
1024
1025             if (fCosT > 0 )
1026             {
1027                 r += gRSPlights[l].fr * fCosT;
1028                 g += gRSPlights[l].fg * fCosT;
1029                 b += gRSPlights[l].fb * fCosT;
1030             }
1031         }
1032     }
1033     else
1034     {
1035         XVECTOR4 v;
1036         bool transformed = false;
1037
1038         for (register unsigned int l=0; l < gRSPnumLights; l++)
1039         {
1040             if( gRSPlights[l].range == 0 )
1041             {
1042                 // Regular directional light
1043                 fCosT = norm.x*gRSPlights[l].x + norm.y*gRSPlights[l].y + norm.z*gRSPlights[l].z; 
1044
1045                 if (fCosT > 0 )
1046                 {
1047                     r += gRSPlights[l].fr * fCosT;
1048                     g += gRSPlights[l].fg * fCosT;
1049                     b += gRSPlights[l].fb * fCosT;
1050                 }
1051             }
1052             else //if( (gRSPlights[l].col&0x00FFFFFF) != 0x00FFFFFF )
1053             {
1054                 // Point light
1055                 if( !transformed )
1056                 {
1057                     Vec3Transform(&v, (XVECTOR3*)&g_vtxNonTransformed[vidx], &gRSPmodelViewTop);    // Convert to w=1
1058                     transformed = true;
1059                 }
1060
1061                 XVECTOR3 dir(gRSPlights[l].x - v.x, gRSPlights[l].y - v.y, gRSPlights[l].z - v.z);
1062                 //XVECTOR3 dir(v.x-gRSPlights[l].x, v.y-gRSPlights[l].y, v.z-gRSPlights[l].z);
1063                 float d2 = sqrtf(dir.x*dir.x+dir.y*dir.y+dir.z*dir.z);
1064                 dir.x /= d2;
1065                 dir.y /= d2;
1066                 dir.z /= d2;
1067
1068                 fCosT = norm.x*dir.x + norm.y*dir.y + norm.z*dir.z; 
1069
1070                 if (fCosT > 0 )
1071                 {
1072                     //float f = d2/gRSPlights[l].range*50;
1073                     float f = d2/15000*50;
1074                     f = 1 - min(f,1);
1075                     fCosT *= f*f;
1076
1077                     r += gRSPlights[l].fr * fCosT;
1078                     g += gRSPlights[l].fg * fCosT;
1079                     b += gRSPlights[l].fb * fCosT;
1080                 }
1081             }
1082         }
1083     }
1084
1085     if (r > 255) r = 255;
1086     if (g > 255) g = 255;
1087     if (b > 255) b = 255;
1088     return ((0xff000000)|(((uint32)r)<<16)|(((uint32)g)<<8)|((uint32)b));
1089 }
1090
1091 uint32 LightVertNew(XVECTOR4 & norm)
1092 {
1093     float fCosT;
1094
1095     // Do ambient
1096     register float r = gRSP.fAmbientLightR;
1097     register float g = gRSP.fAmbientLightG;
1098     register float b = gRSP.fAmbientLightB;
1099
1100
1101     for (register unsigned int l=0; l < gRSPnumLights; l++)
1102     {
1103         fCosT = norm.x*gRSPlights[l].tx + norm.y*gRSPlights[l].ty + norm.z*gRSPlights[l].tz; 
1104
1105         if (fCosT > 0 )
1106         {
1107             r += gRSPlights[l].fr * fCosT;
1108             g += gRSPlights[l].fg * fCosT;
1109             b += gRSPlights[l].fb * fCosT;
1110         }
1111     }
1112
1113     if (r > 255) r = 255;
1114     if (g > 255) g = 255;
1115     if (b > 255) b = 255;
1116     return ((0xff000000)|(((uint32)r)<<16)|(((uint32)g)<<8)|((uint32)b));
1117 }
1118
1119
1120 float zero = 0.0f;
1121 float onef = 1.0f;
1122 float fcosT;
1123
1124 #if !defined(__GNUC__) && !defined(NO_ASM)
1125 __declspec( naked ) uint32  __fastcall SSELightVert()
1126 {
1127     __asm
1128     {
1129         movaps      xmm3, DWORD PTR gRSP;   // loading Ambient colors, xmm3 is the result color
1130         movaps      xmm4, DWORD PTR [g_normal]; // xmm4 is the normal
1131
1132         mov         ecx, 0;
1133 loopback:
1134         cmp         ecx, DWORD PTR gRSPnumLights;
1135         jae         breakout;
1136         mov         eax,ecx;
1137         imul        eax,0x44;
1138         movups      xmm5, DWORD PTR gRSPlights[eax];        // Light Dir
1139         movups      xmm1, DWORD PTR gRSPlights[0x14][eax];  // Light color
1140         mulps       xmm5, xmm4;                 // Lightdir * normals
1141
1142         movhlps     xmm0,xmm5;
1143         addps       xmm0,xmm5;
1144         shufps      xmm5,xmm0,0x01;
1145         addps       xmm0,xmm5;
1146
1147         comiss      xmm0,zero;
1148         jc          endloop
1149
1150         shufps      xmm0,xmm0,0;                    // fcosT
1151         mulps       xmm1,xmm0; 
1152         addps       xmm3,xmm1; 
1153 endloop:
1154         inc         ecx;
1155         jmp         loopback;
1156 breakout:
1157
1158         movss       xmm0,DWORD PTR real255;
1159         shufps      xmm0,xmm0,0;
1160         minps       xmm0,xmm3;
1161
1162         // Without using a memory
1163         cvtss2si    eax,xmm0;       // move the 1st uint32 to eax
1164         shl         eax,10h;
1165         or          eax,0FF000000h;
1166         shufps      xmm0,xmm0,0E5h; // move the 2nd uint32 to the 1st uint32
1167         cvtss2si    ecx,xmm0;       // move the 1st uint32 to ecx
1168         shl         ecx,8;
1169         or          eax,ecx;
1170         shufps      xmm0,xmm0,0E6h; // Move the 3rd uint32 to the 1st uint32
1171         cvtss2si    ecx,xmm0;
1172         or          eax,ecx;
1173
1174         ret;
1175     }
1176 }
1177 #elif defined(__GNUC__) && defined(__x86_64__) && !defined(NO_ASM)
1178 uint32 SSELightVert(void)
1179 {
1180   uint32 rval;
1181   float f255 = 255.0, fZero = 0.0;
1182   
1183   asm volatile(" movaps        %1,  %%xmm3    \n" // xmm3 == gRSP.fAmbientLight{RGBA}
1184            " movaps            %2,  %%xmm4    \n" // xmm4 == g_normal.{xyz}
1185            " xor            %%rcx,   %%rcx    \n"
1186            "0:                                \n"
1187            " cmpl              %3,   %%ecx    \n"
1188            " jae               2f             \n"
1189            " mov            %%rcx,   %%rax    \n"
1190            " imul    $0x44, %%rax,   %%rax    \n"
1191            " movups   (%4,%%rax,),  %%xmm5    \n"  // xmm5 == gRSPlights[l].{xyzr}
1192            " movups 20(%4,%%rax,),  %%xmm1    \n"  // xmm1 == gRSPlights[l].{frfgfbfa}
1193            " mulps         %%xmm4,  %%xmm5    \n"
1194            " movhlps       %%xmm5,  %%xmm0    \n"
1195            " addps         %%xmm5,  %%xmm0    \n"
1196            " shufps $0x01, %%xmm0,  %%xmm5    \n"
1197            " addps         %%xmm5,  %%xmm0    \n"
1198            " comiss            %6,  %%xmm0    \n"
1199            " jc                1f             \n"
1200            " shufps $0x00, %%xmm0,  %%xmm0    \n"
1201            " mulps         %%xmm0,  %%xmm1    \n"
1202            " addps         %%xmm1,  %%xmm3    \n"
1203            "1:                                \n"
1204            " inc            %%rcx             \n"
1205            " jmp               0b             \n"
1206            "2:                                \n"
1207            " movss             %5,  %%xmm0    \n"
1208            " shufps $0x00, %%xmm0,  %%xmm0    \n"
1209            " minps         %%xmm3,  %%xmm0    \n"
1210            " cvtss2si      %%xmm0,   %%eax    \n"
1211            " shll           $0x10,   %%eax    \n"
1212            " orl      $0xff000000,   %%eax    \n"
1213            " shufps $0xe5, %%xmm0,  %%xmm0    \n"
1214            " cvtss2si      %%xmm0,   %%ecx    \n"
1215            " shll              $8,   %%ecx    \n"
1216            " orl            %%ecx,   %%eax    \n"
1217            " shufps $0xe6, %%xmm0,  %%xmm0    \n"
1218            " cvtss2si      %%xmm0,   %%ecx    \n"
1219            " orl            %%ecx,   %%eax    \n"
1220            : "=&a"(rval)
1221            : "m"(gRSP), "m"(g_normal), "m"(gRSPnumLights), "r"(gRSPlights), "m"(f255), "m"(fZero)
1222            : "%rcx", "memory", "cc", "%xmm0", "%xmm1", "%xmm3", "%xmm4", "%xmm5"
1223            );
1224   return rval;
1225 }
1226 #elif !defined(NO_ASM) // 32-bit GCC assumed
1227 uint32 SSELightVert(void)
1228 {
1229   uint32 rval;
1230   float f255 = 255.0, fZero = 0.0;
1231
1232   asm volatile(" movaps            %1,  %%xmm3    \n"
1233                " movaps            %2,  %%xmm4    \n"
1234                " xor            %%ecx,   %%ecx    \n"
1235                "0:                                \n"
1236                " cmpl              %3,   %%ecx    \n"
1237                " jae               2f             \n"
1238                " mov            %%ecx,   %%eax    \n"
1239                " imul    $0x44, %%eax,   %%eax    \n"
1240                " movups   (%4,%%eax,),  %%xmm5    \n"
1241                " movups 20(%4,%%eax,),  %%xmm1    \n"
1242                " mulps         %%xmm4,  %%xmm5    \n"
1243                " movhlps       %%xmm5,  %%xmm0    \n"
1244                " addps         %%xmm5,  %%xmm0    \n"
1245                " shufps $0x01, %%xmm0,  %%xmm5    \n"
1246                " addps         %%xmm5,  %%xmm0    \n"
1247                " comiss            %6,  %%xmm0    \n"
1248                " jc                1f             \n"
1249                " shufps $0x00, %%xmm0,  %%xmm0    \n"
1250                " mulps         %%xmm0,  %%xmm1    \n"
1251                " addps         %%xmm1,  %%xmm3    \n"
1252                "1:                                \n"
1253                " inc            %%ecx             \n"
1254                " jmp               0b             \n"
1255                "2:                                \n"
1256                " movss             %5,  %%xmm0    \n"
1257                " shufps $0x00, %%xmm0,  %%xmm0    \n"
1258                " minps         %%xmm3,  %%xmm0    \n"
1259                " cvtss2si      %%xmm0,   %%eax    \n"
1260                " shll           $0x10,   %%eax    \n"
1261                " orl      $0xff000000,   %%eax    \n"
1262                " shufps $0xe5, %%xmm0,  %%xmm0    \n"
1263                " cvtss2si      %%xmm0,   %%ecx    \n"
1264                " shll              $8,   %%ecx    \n"
1265                " orl            %%ecx,   %%eax    \n"
1266                " shufps $0xe6, %%xmm0,  %%xmm0    \n"
1267                " cvtss2si      %%xmm0,   %%ecx    \n"
1268                " orl            %%ecx,   %%eax    \n"
1269                : "=&a"(rval)
1270                : "m"(gRSP), "m"(g_normal), "m"(gRSPnumLights), "r"(gRSPlights), "m"(f255), "m"(fZero)
1271                : "%rcx", "memory", "cc", "%xmm0", "%xmm1", "%xmm3", "%xmm4", "%xmm5"
1272                );
1273   return rval;
1274 }
1275 #endif
1276
1277 inline void ReplaceAlphaWithFogFactor(int i)
1278 {
1279     if( gRDP.geometryMode & G_FOG )
1280     {
1281         // Use fog factor to replace vertex alpha
1282         if( g_vecProjected[i].z > 1 )
1283             *(((uint8*)&(g_dwVtxDifColor[i]))+3) = 0xFF;
1284         if( g_vecProjected[i].z < 0 )
1285             *(((uint8*)&(g_dwVtxDifColor[i]))+3) = 0;
1286         else
1287             *(((uint8*)&(g_dwVtxDifColor[i]))+3) = (uint8)(g_vecProjected[i].z*255);    
1288     }
1289 }
1290
1291
1292 // Bits
1293 // +-+-+-
1294 // xxyyzz
1295 #define Z_NEG  0x01
1296 #define Z_POS  0x02
1297 #define Y_NEG  0x04
1298 #define Y_POS  0x08
1299 #define X_NEG  0x10
1300 #define X_POS  0x20
1301
1302 // Assumes dwAddr has already been checked! 
1303 // Don't inline - it's too big with the transform macros
1304
1305 #if !defined(NO_ASM)
1306 void ProcessVertexDataSSE(uint32 dwAddr, uint32 dwV0, uint32 dwNum)
1307 {
1308     UpdateCombinedMatrix();
1309
1310     // This function is called upon SPvertex
1311     // - do vertex matrix transform
1312     // - do vertex lighting
1313     // - do texture cooridinate transform if needed
1314     // - calculate normal vector
1315
1316     // Output:  - g_vecProjected[i]             -> transformed vertex x,y,z
1317     //          - g_vecProjected[i].w                       -> saved vertex 1/w
1318     //          - g_dwVtxFlags[i]               -> flags
1319     //          - g_dwVtxDifColor[i]            -> vertex color
1320     //          - g_fVtxTxtCoords[i]                -> vertex texture cooridinates
1321
1322     FiddledVtx * pVtxBase = (FiddledVtx*)(g_pRDRAMu8 + dwAddr);
1323     g_pVtxBase = pVtxBase;
1324
1325     for (uint32 i = dwV0; i < dwV0 + dwNum; i++)
1326     {
1327         SP_Timing(RSP_GBI0_Vtx);
1328
1329         FiddledVtx & vert = pVtxBase[i - dwV0];
1330
1331         g_vtxNonTransformed[i].x = (float)vert.x;
1332         g_vtxNonTransformed[i].y = (float)vert.y;
1333         g_vtxNonTransformed[i].z = (float)vert.z;
1334
1335         SSEVec3Transform(i);
1336
1337         if( gRSP.bFogEnabled )
1338         {
1339             g_fFogCoord[i] = g_vecProjected[i].z;
1340             if( g_vecProjected[i].w < 0 || g_vecProjected[i].z < 0 || g_fFogCoord[i] < gRSPfFogMin )
1341                 g_fFogCoord[i] = gRSPfFogMin;
1342         }
1343
1344         ReplaceAlphaWithFogFactor(i);
1345
1346
1347         VTX_DUMP( 
1348         {
1349             uint32 *dat = (uint32*)(&vert);
1350             DebuggerAppendMsg("vtx %d: %08X %08X %08X %08X", i, dat[0],dat[1],dat[2],dat[3]); 
1351             DebuggerAppendMsg("      : %f, %f, %f, %f", 
1352                 g_vtxTransformed[i].x,g_vtxTransformed[i].y,g_vtxTransformed[i].z,g_vtxTransformed[i].w);
1353             DebuggerAppendMsg("      : %f, %f, %f, %f", 
1354                 g_vecProjected[i].x,g_vecProjected[i].y,g_vecProjected[i].z,g_vecProjected[i].w);
1355         });
1356
1357         RSP_Vtx_Clipping(i);
1358
1359         if( gRSP.bLightingEnable )
1360         {
1361             g_normal.x = (float)vert.norma.nx;
1362             g_normal.y = (float)vert.norma.ny;
1363             g_normal.z = (float)vert.norma.nz;
1364
1365             SSEVec3TransformNormal();
1366             if( options.enableHackForGames != HACK_FOR_ZELDA_MM )
1367                 g_dwVtxDifColor[i] = SSELightVert();
1368             else
1369                 g_dwVtxDifColor[i] = LightVert(g_normal, i);
1370             *(((uint8*)&(g_dwVtxDifColor[i]))+3) = vert.rgba.a; // still use alpha from the vertex
1371         }
1372         else
1373         {
1374             if( (gRDP.geometryMode & G_SHADE) == 0 && gRSP.ucode < 5 )  //Shade is disabled
1375             {
1376                 //FLAT shade
1377                 g_dwVtxDifColor[i] = gRDP.primitiveColor;
1378             }
1379             else
1380             {
1381                 register IColor &color = *(IColor*)&g_dwVtxDifColor[i];
1382                 color.b = vert.rgba.r;
1383                 color.g = vert.rgba.g;
1384                 color.r = vert.rgba.b;
1385                 color.a = vert.rgba.a;
1386             }
1387         }
1388
1389         if( options.bWinFrameMode )
1390         {
1391             g_dwVtxDifColor[i] = COLOR_RGBA(vert.rgba.r, vert.rgba.g, vert.rgba.b, vert.rgba.a);
1392         }
1393
1394         // Update texture coords n.b. need to divide tu/tv by bogus scale on addition to buffer
1395
1396         // If the vert is already lit, then there is no normal (and hence we
1397         // can't generate tex coord)
1398         if (gRSP.bTextureGen && gRSP.bLightingEnable )
1399         {
1400             TexGen(g_fVtxTxtCoords[i].x, g_fVtxTxtCoords[i].y);
1401         }
1402         else
1403         {
1404             g_fVtxTxtCoords[i].x = (float)vert.tu;
1405             g_fVtxTxtCoords[i].y = (float)vert.tv; 
1406         }
1407     }
1408
1409     VTX_DUMP(TRACE2("Setting Vertexes: %d - %d\n", dwV0, dwV0+dwNum-1));
1410     DEBUGGER_PAUSE_AND_DUMP(NEXT_VERTEX_CMD,{TRACE0("Paused at Vertex Cmd");});
1411 }
1412 #endif
1413
1414 void ProcessVertexDataNoSSE(uint32 dwAddr, uint32 dwV0, uint32 dwNum)
1415 {
1416
1417     UpdateCombinedMatrix();
1418
1419     // This function is called upon SPvertex
1420     // - do vertex matrix transform
1421     // - do vertex lighting
1422     // - do texture cooridinate transform if needed
1423     // - calculate normal vector
1424
1425     // Output:  - g_vecProjected[i]             -> transformed vertex x,y,z
1426     //          - g_vecProjected[i].w                       -> saved vertex 1/w
1427     //          - g_dwVtxFlags[i]               -> flags
1428     //          - g_dwVtxDifColor[i]            -> vertex color
1429     //          - g_fVtxTxtCoords[i]                -> vertex texture cooridinates
1430
1431     FiddledVtx * pVtxBase = (FiddledVtx*)(g_pRDRAMu8 + dwAddr);
1432     g_pVtxBase = pVtxBase;
1433
1434     for (uint32 i = dwV0; i < dwV0 + dwNum; i++)
1435     {
1436         SP_Timing(RSP_GBI0_Vtx);
1437
1438         FiddledVtx & vert = pVtxBase[i - dwV0];
1439
1440         g_vtxNonTransformed[i].x = (float)vert.x;
1441         g_vtxNonTransformed[i].y = (float)vert.y;
1442         g_vtxNonTransformed[i].z = (float)vert.z;
1443
1444         Vec3Transform(&g_vtxTransformed[i], (XVECTOR3*)&g_vtxNonTransformed[i], &gRSPworldProject); // Convert to w=1
1445
1446         g_vecProjected[i].w = 1.0f / g_vtxTransformed[i].w;
1447         g_vecProjected[i].x = g_vtxTransformed[i].x * g_vecProjected[i].w;
1448         g_vecProjected[i].y = g_vtxTransformed[i].y * g_vecProjected[i].w;
1449         if ((g_curRomInfo.bPrimaryDepthHack || options.enableHackForGames == HACK_FOR_NASCAR ) && gRDP.otherMode.depth_source )
1450         {
1451             g_vecProjected[i].z = gRDP.fPrimitiveDepth;
1452             g_vtxTransformed[i].z = gRDP.fPrimitiveDepth*g_vtxTransformed[i].w;
1453         }
1454         else
1455         {
1456             g_vecProjected[i].z = g_vtxTransformed[i].z * g_vecProjected[i].w;
1457         }
1458
1459         if( gRSP.bFogEnabled )
1460         {
1461             g_fFogCoord[i] = g_vecProjected[i].z;
1462             if( g_vecProjected[i].w < 0 || g_vecProjected[i].z < 0 || g_fFogCoord[i] < gRSPfFogMin )
1463                 g_fFogCoord[i] = gRSPfFogMin;
1464         }
1465
1466         VTX_DUMP( 
1467         {
1468             uint32 *dat = (uint32*)(&vert);
1469             DebuggerAppendMsg("vtx %d: %08X %08X %08X %08X", i, dat[0],dat[1],dat[2],dat[3]); 
1470             DebuggerAppendMsg("      : %f, %f, %f, %f", 
1471                 g_vtxTransformed[i].x,g_vtxTransformed[i].y,g_vtxTransformed[i].z,g_vtxTransformed[i].w);
1472             DebuggerAppendMsg("      : %f, %f, %f, %f", 
1473                 g_vecProjected[i].x,g_vecProjected[i].y,g_vecProjected[i].z,g_vecProjected[i].w);
1474         });
1475
1476         RSP_Vtx_Clipping(i);
1477
1478         if( gRSP.bLightingEnable )
1479         {
1480             g_normal.x = (float)vert.norma.nx;
1481             g_normal.y = (float)vert.norma.ny;
1482             g_normal.z = (float)vert.norma.nz;
1483
1484             Vec3TransformNormal(g_normal, gRSPmodelViewTop);
1485             g_dwVtxDifColor[i] = LightVert(g_normal, i);
1486             *(((uint8*)&(g_dwVtxDifColor[i]))+3) = vert.rgba.a; // still use alpha from the vertex
1487         }
1488         else
1489         {
1490             if( (gRDP.geometryMode & G_SHADE) == 0 && gRSP.ucode < 5 )  //Shade is disabled
1491             {
1492                 //FLAT shade
1493                 g_dwVtxDifColor[i] = gRDP.primitiveColor;
1494             }
1495             else
1496             {
1497                 register IColor &color = *(IColor*)&g_dwVtxDifColor[i];
1498                 color.b = vert.rgba.r;
1499                 color.g = vert.rgba.g;
1500                 color.r = vert.rgba.b;
1501                 color.a = vert.rgba.a;
1502             }
1503         }
1504
1505         if( options.bWinFrameMode )
1506         {
1507             g_dwVtxDifColor[i] = COLOR_RGBA(vert.rgba.r, vert.rgba.g, vert.rgba.b, vert.rgba.a);
1508         }
1509
1510         ReplaceAlphaWithFogFactor(i);
1511
1512         // Update texture coords n.b. need to divide tu/tv by bogus scale on addition to buffer
1513
1514         // If the vert is already lit, then there is no normal (and hence we
1515         // can't generate tex coord)
1516         if (gRSP.bTextureGen && gRSP.bLightingEnable )
1517         {
1518             TexGen(g_fVtxTxtCoords[i].x, g_fVtxTxtCoords[i].y);
1519         }
1520         else
1521         {
1522             g_fVtxTxtCoords[i].x = (float)vert.tu;
1523             g_fVtxTxtCoords[i].y = (float)vert.tv; 
1524         }
1525     }
1526
1527     VTX_DUMP(TRACE2("Setting Vertexes: %d - %d\n", dwV0, dwV0+dwNum-1));
1528     DEBUGGER_PAUSE_AND_DUMP(NEXT_VERTEX_CMD,{TRACE0("Paused at Vertex Cmd");});
1529 }
1530
1531 /* NEON code */
1532
1533 #include "RenderBase_neon.h"
1534
1535 extern "C" void pv_neon(XVECTOR4 *g_vtxTransformed, XVECTOR4 *g_vecProjected,
1536     uint32 *g_dwVtxDifColor, VECTOR2 *g_fVtxTxtCoords,
1537     float *g_fFogCoord, uint32 *g_clipFlag2,
1538     uint32 dwNum, int neon_state,
1539     const FiddledVtx *vtx,
1540     const Light *gRSPlights, const float *fRSPAmbientLightRGBA,
1541     const XMATRIX *gRSPworldProject, const XMATRIX *gRSPmodelViewTop,
1542     uint32 gRSPnumLights, float gRSPfFogMin,
1543     uint32 primitiveColor, uint32 primitiveColor_);
1544
1545 // debug
1546 //#define DO_CMP
1547 #ifdef DO_CMP
1548 // note: don't forget -fno-associative-math
1549 static XVECTOR4 n_transformed[2], n_projected[2];
1550 static uint32 n_color[2];
1551 static VECTOR2 n_vtxcoords[2];
1552 static float n_fogcoord[2];
1553 static uint32 n_clipflag2[2];
1554
1555 static int do_cmp_f(void *a, void *b, int c)
1556 {
1557     int *ia = (int *)a, *ib = (int *)b;
1558     for (int i = 0; i < c; i++) {
1559         int di = abs(ia[i] - ib[i]);
1560         if (di > 7) {
1561             printf("di: %d\n", di);
1562             return 1;
1563         }
1564     }
1565     return 0;
1566 }
1567
1568 static int do_cmp_c(uint32 a, uint32 b)
1569 {
1570     if (abs(((a >> 0) & 0xff) - ((b >> 0) & 0xff)) > 1)
1571         return 1;
1572     if (abs(((a >> 8) & 0xff) - ((b >> 8) & 0xff)) > 1)
1573         return 1;
1574     if (abs(((a >> 16) & 0xff) - ((b >> 16) & 0xff)) > 1)
1575         return 1;
1576     if (abs(((a >> 24) & 0xff) - ((b >> 24) & 0xff)) > 1)
1577         return 1;
1578
1579     return 0;
1580 }
1581
1582 static void do_cmp(int i, int s, int neon_state)
1583 {
1584     static int ccnt;
1585     int bad = 0;
1586
1587     // if (memcmp(&n_transformed, &g_vtxTransformed[i], sizeof(XVECTOR4)))
1588     if (do_cmp_f(&n_transformed[s], &g_vtxTransformed[i], 4)) {
1589         printf("transformed:\n%13.8e %13.8e %13.8e %13.8e\n"
1590                "%13.8e %13.8e %13.8e %13.8e\n",
1591             n_transformed[s].x, n_transformed[s].y,
1592             n_transformed[s].z, n_transformed[s].w,
1593             g_vtxTransformed[i].x, g_vtxTransformed[i].y,
1594             g_vtxTransformed[i].z, g_vtxTransformed[i].w);
1595         bad = 1;
1596     }
1597     if (do_cmp_f(&n_projected[s], &g_vecProjected[i], 4)) {
1598         printf("projected:\n%13.8e %13.8e %13.8e %13.8e |%08x\n"
1599                "%13.8e %13.8e %13.8e %13.8e |%08x\n",
1600             n_projected[s].x, n_projected[s].y,
1601             n_projected[s].z, n_projected[s].w,
1602             *(uint32 *)&n_projected[s].w,
1603             g_vecProjected[i].x, g_vecProjected[i].y,
1604             g_vecProjected[i].z, g_vecProjected[i].w,
1605             *(uint32 *)&g_vecProjected[i].w);
1606         bad = 1;
1607     }
1608     if (n_vtxcoords[s].x != g_fVtxTxtCoords[i].x
1609         || n_vtxcoords[s].y != g_fVtxTxtCoords[i].y)
1610     {
1611         printf("vtxcoords:\n%13.8e %13.8e\n%13.8e %13.8e\n",
1612             n_vtxcoords[s].x, n_vtxcoords[s].y,
1613             g_fVtxTxtCoords[i].x, g_fVtxTxtCoords[i].y);
1614         bad = 1;
1615     }
1616     if (n_clipflag2[s] != g_clipFlag2[i]) {
1617         printf("clipflag2: %08x %08x\n", n_clipflag2[s], g_clipFlag2[i]);
1618         bad = 1;
1619     }
1620     if (do_cmp_c(n_color[s], g_dwVtxDifColor[i])) {
1621         printf("n_color: %08x %08x\n", n_color[s], g_dwVtxDifColor[i]);
1622         bad = 1;
1623     }
1624     if (!(neon_state & PV_NEON_ENABLE_SHADE))
1625         printf("!ENABLE_SHADE!\n");
1626     if (bad) {
1627         printf("%d s=%d, state %02x\n", ccnt, s, neon_state);
1628         printf(".w %08x %08x\n",
1629             *(uint32 *)&n_projected[s].w, *(uint32 *)&g_vecProjected[i].w);
1630         exit(ccnt);
1631     }
1632     ccnt++;
1633 }
1634 #endif
1635
1636 void ProcessVertexDataNEON(uint32 dwAddr, uint32 dwV0, uint32 dwNum)
1637 {
1638     if (gRSP.bTextureGen && gRSP.bLightingEnable) {
1639         ProcessVertexDataNoSSE(dwAddr, dwV0,dwNum);
1640         return;
1641     }
1642
1643     // assumtions:
1644     // - g_clipFlag is not used at all
1645     // - g_fFogCoord is not used at all
1646     // - g_vtxNonTransformed is not used after ProcessVertexData*() returns
1647     // - g_normal - same
1648
1649     int neon_state = 0;
1650     if ( gRSP.bLightingEnable )
1651         neon_state |= PV_NEON_ENABLE_LIGHT;
1652     if ( (gRDP.geometryMode & G_SHADE) || gRSP.ucode >= 5 )
1653         neon_state |= PV_NEON_ENABLE_SHADE;
1654     if ( gRSP.bFogEnabled )
1655         neon_state |= PV_NEON_ENABLE_FOG;
1656     if ( gRDP.geometryMode & G_FOG )
1657         neon_state |= PV_NEON_FOG_ALPHA;
1658
1659     uint32 i;
1660 #ifdef DO_CMP
1661     uint32 s = 0;
1662 #endif
1663
1664     UpdateCombinedMatrix();
1665
1666     // This function is called upon SPvertex
1667     // - do vertex matrix transform
1668     // - do vertex lighting
1669     // - do texture cooridinate transform if needed
1670     // - calculate normal vector
1671
1672     // Output:  - g_vecProjected[i]             -> transformed vertex x,y,z
1673     //          - g_vecProjected[i].w           -> saved vertex 1/w
1674     //          - g_vtxTransformed[i]
1675     //          - g_dwVtxDifColor[i]            -> vertex color
1676     //          - g_fVtxTxtCoords[i]            -> vertex texture cooridinates
1677     //          - g_fFogCoord[i]                -> unused
1678     //          - g_clipFlag2[i]
1679
1680     const FiddledVtx * pVtxBase = (const FiddledVtx*)(g_pRDRAMu8 + dwAddr);
1681     g_pVtxBase = (FiddledVtx *)pVtxBase;
1682
1683     gRSPmodelViewTop._14 = gRSPmodelViewTop._24 =
1684     gRSPmodelViewTop._34 = 0;
1685
1686     // SP_Timing(RSP_GBI0_Vtx);
1687     status.SPCycleCount += Timing_RSP_GBI0_Vtx * dwNum;
1688
1689 //#define DO_CC
1690 #ifdef DO_CC
1691         asm volatile("mrc p15, 0, %0, c9, c12, 0" : "=r"(i));
1692         i |= 5; // master enable, ccnt reset
1693         i &= ~8; // ccnt divider 0
1694         asm volatile("mcr p15, 0, %0, c9, c12, 0" :: "r"(i));
1695         // enable cycle counter
1696         asm volatile("mcr p15, 0, %0, c9, c12, 1" :: "r"(1<<31));
1697         unsigned int cc_start;
1698         asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(cc_start));
1699 #endif
1700
1701 #if 1
1702     i = dwV0;
1703     pv_neon(&g_vtxTransformed[i], &g_vecProjected[i],
1704             &g_dwVtxDifColor[i], &g_fVtxTxtCoords[i],
1705             &g_fFogCoord[i], &g_clipFlag2[i],
1706             dwNum, neon_state, &pVtxBase[i - dwV0],
1707             gRSPlights, gRSP.fAmbientColors,
1708             &gRSPworldProject, &gRSPmodelViewTop,
1709             gRSPnumLights, gRSPfFogMin,
1710             gRDP.primitiveColor, gRDP.primitiveColor);
1711 #else
1712     for (i = dwV0; i < dwV0 + dwNum; i++)
1713     {
1714 #ifdef DO_CMP
1715         if (!(s & 1))
1716             pv_neon(n_transformed, n_projected,
1717                     n_color, n_vtxcoords,
1718                     n_fogcoord, n_clipflag2,
1719                     1, neon_state, &pVtxBase[i - dwV0],
1720                     gRSPlights, gRSP.fAmbientColors,
1721                     &gRSPworldProject, &gRSPmodelViewTop,
1722                     gRSPnumLights, gRSPfFogMin,
1723                     gRDP.primitiveColor, gRDP.primitiveColor);
1724 #endif
1725
1726         const FiddledVtx & vert = pVtxBase[i - dwV0];
1727         XVECTOR3 vtx_raw; // was g_vtxNonTransformed
1728
1729         vtx_raw.x = (float)vert.x;
1730         vtx_raw.y = (float)vert.y;
1731         vtx_raw.z = (float)vert.z;
1732
1733         Vec3Transform(&g_vtxTransformed[i], &vtx_raw, &gRSPworldProject); // Convert to w=1
1734
1735         g_vecProjected[i].w = 1.0f / g_vtxTransformed[i].w;
1736         g_vecProjected[i].x = g_vtxTransformed[i].x * g_vecProjected[i].w;
1737         g_vecProjected[i].y = g_vtxTransformed[i].y * g_vecProjected[i].w;
1738         g_vecProjected[i].z = g_vtxTransformed[i].z * g_vecProjected[i].w;
1739
1740         // RSP_Vtx_Clipping(i);
1741         g_clipFlag2[i] = 0;
1742         if( g_vecProjected[i].w > 0 )
1743         {
1744             if( g_vecProjected[i].x > 1 )   g_clipFlag2[i] |= X_CLIP_MAX;
1745             if( g_vecProjected[i].x < -1 )  g_clipFlag2[i] |= X_CLIP_MIN;
1746             if( g_vecProjected[i].y > 1 )   g_clipFlag2[i] |= Y_CLIP_MAX;
1747             if( g_vecProjected[i].y < -1 )  g_clipFlag2[i] |= Y_CLIP_MIN;
1748         }
1749
1750         if( neon_state & PV_NEON_ENABLE_LIGHT )
1751         {
1752             XVECTOR3 normal; // was g_normal
1753             float r, g, b;
1754
1755             normal.x = (float)vert.norma.nx;
1756             normal.y = (float)vert.norma.ny;
1757             normal.z = (float)vert.norma.nz;
1758
1759             Vec3TransformNormal(normal, gRSPmodelViewTop);
1760
1761             r = gRSP.fAmbientLightR;
1762             g = gRSP.fAmbientLightG;
1763             b = gRSP.fAmbientLightB;
1764
1765             for (unsigned int l=0; l < gRSPnumLights; l++)
1766             {
1767                 float fCosT = normal.x * gRSPlights[l].x + normal.y * gRSPlights[l].y + normal.z * gRSPlights[l].z; 
1768
1769                 if (fCosT > 0 )
1770                 {
1771                     r += gRSPlights[l].fr * fCosT;
1772                     g += gRSPlights[l].fg * fCosT;
1773                     b += gRSPlights[l].fb * fCosT;
1774                 }
1775             }
1776             if (r > 255) r = 255;
1777             if (g > 255) g = 255;
1778             if (b > 255) b = 255;
1779             g_dwVtxDifColor[i] = ((vert.rgba.a<<24)|(((uint32)r)<<16)|(((uint32)g)<<8)|((uint32)b));
1780         }
1781         else if( neon_state & PV_NEON_ENABLE_SHADE )
1782         {
1783             IColor &color = *(IColor*)&g_dwVtxDifColor[i];
1784             color.b = vert.rgba.r;
1785             color.g = vert.rgba.g;
1786             color.r = vert.rgba.b;
1787             color.a = vert.rgba.a;
1788         }
1789         else
1790             g_dwVtxDifColor[i] = gRDP.primitiveColor; // FLAT shade
1791
1792         // ReplaceAlphaWithFogFactor(i);
1793         if( neon_state & PV_NEON_FOG_ALPHA )
1794         {
1795             // Use fog factor to replace vertex alpha
1796             if( g_vecProjected[i].z > 1 )
1797                 *(((uint8*)&(g_dwVtxDifColor[i]))+3) = 0xFF;
1798             // missing 'else' in original code??
1799             else if( g_vecProjected[i].z < 0 )
1800                 *(((uint8*)&(g_dwVtxDifColor[i]))+3) = 0;
1801             else
1802                 *(((uint8*)&(g_dwVtxDifColor[i]))+3) = (uint8)(g_vecProjected[i].z*255);    
1803         }
1804
1805         g_fVtxTxtCoords[i].x = (float)vert.tu;
1806         g_fVtxTxtCoords[i].y = (float)vert.tv; 
1807 #ifdef DO_CMP
1808         do_cmp(i, s++ & 1, neon_state);
1809 #endif
1810     }
1811 #endif
1812 #ifdef DO_CC
1813     static int total, total_c;
1814         unsigned int cc;
1815         asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(cc));
1816     total += cc - cc_start;
1817     total_c += dwNum;
1818     if (total_c > 20000) {
1819         printf("%.u\n", total / total_c);
1820         total = total_c = 0;
1821     }
1822 #endif
1823 }
1824
1825 bool PrepareTriangle(uint32 dwV0, uint32 dwV1, uint32 dwV2)
1826 {
1827     if( status.isVertexShaderEnabled || status.bUseHW_T_L )
1828     {
1829         g_vtxIndex[gRSP.numVertices++] = dwV0;
1830         g_vtxIndex[gRSP.numVertices++] = dwV1;
1831         g_vtxIndex[gRSP.numVertices++] = dwV2;
1832         status.dwNumTrisRendered++;
1833         gRSP.maxVertexID = max(gRSP.maxVertexID,max(dwV0,max(dwV1,dwV2)));
1834     }
1835     else
1836     {
1837         SP_Timing(SP_Each_Triangle);
1838
1839         bool textureFlag = (CRender::g_pRender->IsTextureEnabled() || gRSP.ucode == 6 );
1840         bool openGL = CDeviceBuilder::m_deviceGeneralType == OGL_DEVICE;
1841
1842         InitVertex(dwV0, gRSP.numVertices, textureFlag, openGL);
1843         InitVertex(dwV1, gRSP.numVertices+1, textureFlag, openGL);
1844         InitVertex(dwV2, gRSP.numVertices+2, textureFlag, openGL);
1845
1846         gRSP.numVertices += 3;
1847         status.dwNumTrisRendered++;
1848     }
1849
1850     return true;
1851 }
1852
1853
1854
1855 // Returns TRUE if it thinks the triangle is visible
1856 // Returns FALSE if it is clipped
1857 bool IsTriangleVisible(uint32 dwV0, uint32 dwV1, uint32 dwV2)
1858 {
1859     //return true;  //fix me
1860
1861     if( status.isVertexShaderEnabled || status.bUseHW_T_L ) return true;    // We won't have access to transformed vertex data
1862
1863     DEBUGGER_ONLY_IF( (!debuggerEnableTestTris || !debuggerEnableCullFace), {return TRUE;});
1864     
1865 #ifdef DEBUGGER
1866     // Check vertices are valid!
1867     if (dwV0 >= MAX_VERTS || dwV1 >= MAX_VERTS || dwV2 >= MAX_VERTS)
1868         return false;
1869 #endif
1870
1871     // Here we AND all the flags. If any of the bits is set for all
1872     // 3 vertices, it means that all three x, y or z lie outside of
1873     // the current viewing volume.
1874     // Currently disabled - still seems a bit dodgy
1875     if ((gRSP.bCullFront || gRSP.bCullBack) && gRDP.otherMode.zmode != 3)
1876     {
1877         XVECTOR4 & v0 = g_vecProjected[dwV0];
1878         XVECTOR4 & v1 = g_vecProjected[dwV1];
1879         XVECTOR4 & v2 = g_vecProjected[dwV2];
1880
1881         // Only try to clip if the tri is onscreen. For some reason, this
1882         // method doesnt' work well when the z value is outside of screenspace
1883         //if (v0.z < 1 && v1.z < 1 && v2.z < 1)
1884         {
1885             float V1 = v2.x - v0.x;
1886             float V2 = v2.y - v0.y;
1887             
1888             float W1 = v2.x - v1.x;
1889             float W2 = v2.y - v1.y;
1890
1891             float fDirection = (V1 * W2) - (V2 * W1);
1892             fDirection = fDirection * v1.w * v2.w * v0.w;
1893             //float fDirection = v0.x*v1.y-v1.x*v0.y+v1.x*v2.y-v2.x*v1.y+v2.x*v0.y-v0.x*v2.y;
1894
1895             if (fDirection < 0 && gRSP.bCullBack)
1896             {
1897                 status.dwNumTrisClipped++;
1898                 return false;
1899             }
1900             else if (fDirection > 0 && gRSP.bCullFront)
1901             {
1902                 status.dwNumTrisClipped++;
1903                 return false;
1904             }
1905         }
1906     }
1907     
1908 #ifdef ENABLE_CLIP_TRI
1909     //if( gRSP.bRejectVtx && (g_clipFlag[dwV0]|g_clipFlag[dwV1]|g_clipFlag[dwV2]) ) 
1910     //  return;
1911     if( g_clipFlag2[dwV0]&g_clipFlag2[dwV1]&g_clipFlag2[dwV2] )
1912     {
1913         //DebuggerAppendMsg("Clipped");
1914         return false;
1915     }
1916 #endif
1917
1918     return true;
1919 }
1920
1921
1922 void SetPrimitiveColor(uint32 dwCol, uint32 LODMin, uint32 LODFrac)
1923 {
1924     gRDP.colorsAreReloaded = true;
1925     gRDP.primitiveColor = dwCol;
1926     gRDP.primLODMin = LODMin;
1927     gRDP.primLODFrac = LODFrac;
1928     if( gRDP.primLODFrac < gRDP.primLODMin )
1929     {
1930         gRDP.primLODFrac = gRDP.primLODMin;
1931     }
1932
1933     gRDP.fvPrimitiveColor[0] = ((dwCol>>16)&0xFF)/255.0f;  //r
1934     gRDP.fvPrimitiveColor[1] = ((dwCol>>8)&0xFF)/255.0f;   //g
1935     gRDP.fvPrimitiveColor[2] = ((dwCol)&0xFF)/255.0f;      //b
1936     gRDP.fvPrimitiveColor[3] = ((dwCol>>24)&0xFF)/255.0f;  //a
1937 }
1938
1939 void SetPrimitiveDepth(uint32 z, uint32 dwDZ)
1940 {
1941     gRDP.primitiveDepth = z & 0x7FFF;
1942     gRDP.fPrimitiveDepth = (float)(gRDP.primitiveDepth)/(float)0x8000;
1943
1944     //gRDP.fPrimitiveDepth = gRDP.fPrimitiveDepth*2-1;  
1945     /*
1946     z=0xFFFF    ->  1   the farest
1947     z=0         ->  -1  the nearest
1948     */
1949
1950     //how to use dwDZ?
1951
1952 #ifdef DEBUGGER
1953     if( (pauseAtNext && (eventToPause == NEXT_VERTEX_CMD || eventToPause == NEXT_FLUSH_TRI )) )//&& logTriangles ) 
1954     {
1955         DebuggerAppendMsg("Set prim Depth: %f, (%08X, %08X)", gRDP.fPrimitiveDepth, z, dwDZ); 
1956     }
1957 #endif
1958 }
1959
1960 void SetVertexXYZ(uint32 vertex, float x, float y, float z)
1961 {
1962     g_vecProjected[vertex].x = x;
1963     g_vecProjected[vertex].y = y;
1964     g_vecProjected[vertex].z = z;
1965
1966     g_vtxTransformed[vertex].x = x*g_vtxTransformed[vertex].w;
1967     g_vtxTransformed[vertex].y = y*g_vtxTransformed[vertex].w;
1968     g_vtxTransformed[vertex].z = z*g_vtxTransformed[vertex].w;
1969 }
1970
1971 void ModifyVertexInfo(uint32 where, uint32 vertex, uint32 val)
1972 {
1973     switch (where)
1974     {
1975     case RSP_MV_WORD_OFFSET_POINT_RGBA:     // Modify RGBA
1976         {
1977             uint32 r = (val>>24)&0xFF;
1978             uint32 g = (val>>16)&0xFF;
1979             uint32 b = (val>>8)&0xFF;
1980             uint32 a = val&0xFF;
1981             g_dwVtxDifColor[vertex] = COLOR_RGBA(r, g, b, a);
1982             LOG_UCODE("Modify vert %d color, 0x%08x", vertex, g_dwVtxDifColor[vertex]);
1983         }
1984         break;
1985     case RSP_MV_WORD_OFFSET_POINT_XYSCREEN:     // Modify X,Y
1986         {
1987             uint16 nX = (uint16)(val>>16);
1988             short x = *((short*)&nX);
1989             x /= 4;
1990
1991             uint16 nY = (uint16)(val&0xFFFF);
1992             short y = *((short*)&nY);
1993             y /= 4;
1994
1995             // Should do viewport transform.
1996
1997
1998             x -= windowSetting.uViWidth/2;
1999             y = windowSetting.uViHeight/2-y;
2000
2001             if( options.bEnableHacks && ((*g_GraphicsInfo.VI_X_SCALE_REG)&0xF) != 0 )
2002             {
2003                 // Tarzan
2004                 // I don't know why Tarzan is different
2005                 SetVertexXYZ(vertex, x/windowSetting.fViWidth, y/windowSetting.fViHeight, g_vecProjected[vertex].z);
2006             }
2007             else
2008             {
2009                 // Toy Story 2 and other games
2010                 SetVertexXYZ(vertex, x*2/windowSetting.fViWidth, y*2/windowSetting.fViHeight, g_vecProjected[vertex].z);
2011             }
2012
2013             LOG_UCODE("Modify vert %d: x=%d, y=%d", vertex, x, y);
2014             VTX_DUMP(TRACE3("Modify vert %d: (%d,%d)", vertex, x, y));
2015         }
2016         break;
2017     case RSP_MV_WORD_OFFSET_POINT_ZSCREEN:      // Modify C
2018         {
2019             int z = val>>16;
2020
2021             SetVertexXYZ(vertex, g_vecProjected[vertex].x, g_vecProjected[vertex].y, (((float)z/0x03FF)+0.5f)/2.0f );
2022             LOG_UCODE("Modify vert %d: z=%d", vertex, z);
2023             VTX_DUMP(TRACE2("Modify vert %d: z=%d", vertex, z));
2024         }
2025         break;
2026     case RSP_MV_WORD_OFFSET_POINT_ST:       // Texture
2027         {
2028             short tu = short(val>>16);
2029             short tv = short(val & 0xFFFF);
2030             float ftu = tu / 32.0f;
2031             float ftv = tv / 32.0f;
2032             LOG_UCODE("      Setting vertex %d tu/tv to %f, %f", vertex, (float)tu, (float)tv);
2033             CRender::g_pRender->SetVtxTextureCoord(vertex, ftu/gRSP.fTexScaleX, ftv/gRSP.fTexScaleY);
2034         }
2035         break;
2036     }
2037     DEBUGGER_PAUSE_AND_DUMP(NEXT_VERTEX_CMD,{TRACE0("Paused at ModVertex Cmd");});
2038 }
2039
2040 void ProcessVertexDataDKR(uint32 dwAddr, uint32 dwV0, uint32 dwNum)
2041 {
2042     UpdateCombinedMatrix();
2043
2044     long long pVtxBase = (long long) (g_pRDRAMu8 + dwAddr);
2045     g_pVtxBase = (FiddledVtx*)pVtxBase;
2046
2047     Matrix &matWorldProject = gRSP.DKRMatrixes[gRSP.DKRCMatrixIndex];
2048
2049     int nOff;
2050
2051     bool addbase=false;
2052     if ((!gRSP.DKRBillBoard) || (gRSP.DKRCMatrixIndex != 2) )
2053         addbase = false;
2054     else
2055         addbase = true;
2056
2057     if( addbase && gRSP.DKRVtxCount == 0 && dwNum > 1 )
2058     {
2059         gRSP.DKRVtxCount++;
2060     }
2061
2062     LOG_UCODE("    ProcessVertexDataDKR, CMatrix = %d, Add base=%s", gRSP.DKRCMatrixIndex, gRSP.DKRBillBoard?"true":"false");
2063     VTX_DUMP(TRACE2("DKR Setting Vertexes\nCMatrix = %d, Add base=%s", gRSP.DKRCMatrixIndex, gRSP.DKRBillBoard?"true":"false"));
2064
2065     nOff = 0;
2066     uint32 end = dwV0 + dwNum;
2067     for (uint32 i = dwV0; i < end; i++)
2068     {
2069         XVECTOR3 w;
2070
2071         g_vtxNonTransformed[i].x = (float)*(short*)((pVtxBase+nOff + 0) ^ 2);
2072         g_vtxNonTransformed[i].y = (float)*(short*)((pVtxBase+nOff + 2) ^ 2);
2073         g_vtxNonTransformed[i].z = (float)*(short*)((pVtxBase+nOff + 4) ^ 2);
2074
2075         //if( status.isSSEEnabled )
2076         //  SSEVec3TransformDKR(g_vtxTransformed[i], g_vtxNonTransformed[i]);
2077         //else
2078             Vec3Transform(&g_vtxTransformed[i], (XVECTOR3*)&g_vtxNonTransformed[i], &matWorldProject);  // Convert to w=1
2079
2080         if( gRSP.DKRVtxCount == 0 && dwNum==1 )
2081         {
2082             gRSP.DKRBaseVec.x = g_vtxTransformed[i].x;
2083             gRSP.DKRBaseVec.y = g_vtxTransformed[i].y;
2084             gRSP.DKRBaseVec.z = g_vtxTransformed[i].z;
2085             gRSP.DKRBaseVec.w = g_vtxTransformed[i].w;
2086         }
2087         else if( addbase )
2088         {
2089             g_vtxTransformed[i].x += gRSP.DKRBaseVec.x;
2090             g_vtxTransformed[i].y += gRSP.DKRBaseVec.y;
2091             g_vtxTransformed[i].z += gRSP.DKRBaseVec.z;
2092             g_vtxTransformed[i].w  = gRSP.DKRBaseVec.w;
2093         }
2094
2095         g_vecProjected[i].w = 1.0f / g_vtxTransformed[i].w;
2096         g_vecProjected[i].x = g_vtxTransformed[i].x * g_vecProjected[i].w;
2097         g_vecProjected[i].y = g_vtxTransformed[i].y * g_vecProjected[i].w;
2098         g_vecProjected[i].z = g_vtxTransformed[i].z * g_vecProjected[i].w;
2099
2100         gRSP.DKRVtxCount++;
2101
2102         VTX_DUMP(TRACE5("vtx %d: %f, %f, %f, %f", i, 
2103             g_vtxTransformed[i].x,g_vtxTransformed[i].y,g_vtxTransformed[i].z,g_vtxTransformed[i].w));
2104
2105         if( gRSP.bFogEnabled )
2106         {
2107             g_fFogCoord[i] = g_vecProjected[i].z;
2108             if( g_vecProjected[i].w < 0 || g_vecProjected[i].z < 0 || g_fFogCoord[i] < gRSPfFogMin )
2109                 g_fFogCoord[i] = gRSPfFogMin;
2110         }
2111
2112         RSP_Vtx_Clipping(i);
2113
2114         short wA = *(short*)((pVtxBase+nOff + 6) ^ 2);
2115         short wB = *(short*)((pVtxBase+nOff + 8) ^ 2);
2116
2117         s8 r = (s8)(wA >> 8);
2118         s8 g = (s8)(wA);
2119         s8 b = (s8)(wB >> 8);
2120         s8 a = (s8)(wB);
2121
2122         if (gRSP.bLightingEnable)
2123         {
2124             g_normal.x = (char)r; //norma.nx;
2125             g_normal.y = (char)g; //norma.ny;
2126             g_normal.z = (char)b; //norma.nz;
2127
2128             Vec3TransformNormal(g_normal, matWorldProject)
2129 #if !defined(NO_ASM)
2130             if( status.isSSEEnabled )
2131                 g_dwVtxDifColor[i] = SSELightVert();
2132             else
2133 #endif
2134                 g_dwVtxDifColor[i] = LightVert(g_normal, i);
2135         }
2136         else
2137         {
2138             int nR, nG, nB, nA;
2139
2140             nR = r;
2141             nG = g;
2142             nB = b;
2143             nA = a;
2144             // Assign true vert colour after lighting/fogging
2145             g_dwVtxDifColor[i] = COLOR_RGBA(nR, nG, nB, nA);
2146         }
2147
2148         ReplaceAlphaWithFogFactor(i);
2149
2150         g_fVtxTxtCoords[i].x = g_fVtxTxtCoords[i].y = 1;
2151
2152         nOff += 10;
2153     }
2154
2155
2156     DEBUGGER_PAUSE_AND_DUMP(NEXT_VERTEX_CMD,{DebuggerAppendMsg("Paused at DKR Vertex Cmd, v0=%d, vn=%d, addr=%08X", dwV0, dwNum, dwAddr);});
2157 }
2158
2159
2160 extern uint32 dwPDCIAddr;
2161 void ProcessVertexDataPD(uint32 dwAddr, uint32 dwV0, uint32 dwNum)
2162 {
2163     UpdateCombinedMatrix();
2164
2165     N64VtxPD * pVtxBase = (N64VtxPD*)(g_pRDRAMu8 + dwAddr);
2166     g_pVtxBase = (FiddledVtx*)pVtxBase; // Fix me
2167
2168     for (uint32 i = dwV0; i < dwV0 + dwNum; i++)
2169     {
2170         N64VtxPD &vert = pVtxBase[i - dwV0];
2171
2172         g_vtxNonTransformed[i].x = (float)vert.x;
2173         g_vtxNonTransformed[i].y = (float)vert.y;
2174         g_vtxNonTransformed[i].z = (float)vert.z;
2175
2176 #if !defined(NO_ASM)
2177         if( status.isSSEEnabled )
2178             SSEVec3Transform(i);
2179         else
2180 #endif
2181         {
2182             Vec3Transform(&g_vtxTransformed[i], (XVECTOR3*)&g_vtxNonTransformed[i], &gRSPworldProject); // Convert to w=1
2183             g_vecProjected[i].w = 1.0f / g_vtxTransformed[i].w;
2184             g_vecProjected[i].x = g_vtxTransformed[i].x * g_vecProjected[i].w;
2185             g_vecProjected[i].y = g_vtxTransformed[i].y * g_vecProjected[i].w;
2186             g_vecProjected[i].z = g_vtxTransformed[i].z * g_vecProjected[i].w;
2187         }
2188
2189         g_fFogCoord[i] = g_vecProjected[i].z;
2190         if( g_vecProjected[i].w < 0 || g_vecProjected[i].z < 0 || g_fFogCoord[i] < gRSPfFogMin )
2191             g_fFogCoord[i] = gRSPfFogMin;
2192
2193         RSP_Vtx_Clipping(i);
2194
2195         uint8 *addr = g_pRDRAMu8+dwPDCIAddr+ (vert.cidx&0xFF);
2196         uint32 a = addr[0];
2197         uint32 r = addr[3];
2198         uint32 g = addr[2];
2199         uint32 b = addr[1];
2200
2201         if( gRSP.bLightingEnable )
2202         {
2203             g_normal.x = (char)r;
2204             g_normal.y = (char)g;
2205             g_normal.z = (char)b;
2206 #if !defined(NO_ASM)
2207             if( status.isSSEEnabled )
2208             {
2209                 SSEVec3TransformNormal();
2210                 g_dwVtxDifColor[i] = SSELightVert();
2211             }
2212             else
2213 #endif
2214             {
2215                 Vec3TransformNormal(g_normal, gRSPmodelViewTop);
2216                 g_dwVtxDifColor[i] = LightVert(g_normal, i);
2217             }
2218             *(((uint8*)&(g_dwVtxDifColor[i]))+3) = (uint8)a;    // still use alpha from the vertex
2219         }
2220         else
2221         {
2222             if( (gRDP.geometryMode & G_SHADE) == 0 && gRSP.ucode < 5 )  //Shade is disabled
2223             {
2224                 g_dwVtxDifColor[i] = gRDP.primitiveColor;
2225             }
2226             else    //FLAT shade
2227             {
2228                 g_dwVtxDifColor[i] = COLOR_RGBA(r, g, b, a);
2229             }
2230         }
2231
2232         if( options.bWinFrameMode )
2233         {
2234             g_dwVtxDifColor[i] = COLOR_RGBA(r, g, b, a);
2235         }
2236
2237         ReplaceAlphaWithFogFactor(i);
2238
2239         VECTOR2 & t = g_fVtxTxtCoords[i];
2240         if (gRSP.bTextureGen && gRSP.bLightingEnable )
2241         {
2242             // Not sure if we should transform the normal here
2243             //Matrix & matWV = gRSP.projectionMtxs[gRSP.projectionMtxTop];
2244             //Vec3TransformNormal(g_normal, matWV);
2245
2246             TexGen(g_fVtxTxtCoords[i].x, g_fVtxTxtCoords[i].y);
2247         }
2248         else
2249         {
2250             t.x = vert.s;
2251             t.y = vert.t; 
2252         }
2253
2254
2255         VTX_DUMP( 
2256         {
2257             DebuggerAppendMsg("vtx %d: %d %d %d", i, vert.x,vert.y,vert.z); 
2258             DebuggerAppendMsg("      : %f, %f, %f, %f", 
2259                 g_vtxTransformed[i].x,g_vtxTransformed[i].y,g_vtxTransformed[i].z,g_vtxTransformed[i].w);
2260             DebuggerAppendMsg("      : %X, %X, %X, %X", r,g,b,a);
2261             DebuggerAppendMsg("      : u=%f, v=%f", t.x, t.y);
2262         });
2263     }
2264
2265     VTX_DUMP(TRACE2("Setting Vertexes: %d - %d\n", dwV0, dwV0+dwNum-1));
2266     DEBUGGER_PAUSE_AND_DUMP(NEXT_VERTEX_CMD,{TRACE0("Paused at Vertex Cmd");});
2267 }
2268
2269 extern uint32 dwConkerVtxZAddr;
2270 void ProcessVertexDataConker(uint32 dwAddr, uint32 dwV0, uint32 dwNum)
2271 {
2272     UpdateCombinedMatrix();
2273
2274     FiddledVtx * pVtxBase = (FiddledVtx*)(g_pRDRAMu8 + dwAddr);
2275     g_pVtxBase = pVtxBase;
2276     //short *vertexColoraddr = (short*)(g_pRDRAMu8+dwConkerVtxZAddr);
2277
2278     for (uint32 i = dwV0; i < dwV0 + dwNum; i++)
2279     {
2280         SP_Timing(RSP_GBI0_Vtx);
2281
2282         FiddledVtx & vert = pVtxBase[i - dwV0];
2283
2284         g_vtxNonTransformed[i].x = (float)vert.x;
2285         g_vtxNonTransformed[i].y = (float)vert.y;
2286         g_vtxNonTransformed[i].z = (float)vert.z;
2287
2288 #if !defined(NO_ASM)
2289         if( status.isSSEEnabled )
2290             SSEVec3Transform(i);
2291         else
2292 #endif
2293         {
2294             Vec3Transform(&g_vtxTransformed[i], (XVECTOR3*)&g_vtxNonTransformed[i], &gRSPworldProject); // Convert to w=1
2295             g_vecProjected[i].w = 1.0f / g_vtxTransformed[i].w;
2296             g_vecProjected[i].x = g_vtxTransformed[i].x * g_vecProjected[i].w;
2297             g_vecProjected[i].y = g_vtxTransformed[i].y * g_vecProjected[i].w;
2298             g_vecProjected[i].z = g_vtxTransformed[i].z * g_vecProjected[i].w;
2299         }
2300
2301         g_fFogCoord[i] = g_vecProjected[i].z;
2302         if( g_vecProjected[i].w < 0 || g_vecProjected[i].z < 0 || g_fFogCoord[i] < gRSPfFogMin )
2303             g_fFogCoord[i] = gRSPfFogMin;
2304
2305         VTX_DUMP( 
2306         {
2307             uint32 *dat = (uint32*)(&vert);
2308             DebuggerAppendMsg("vtx %d: %08X %08X %08X %08X", i, dat[0],dat[1],dat[2],dat[3]); 
2309             DebuggerAppendMsg("      : %f, %f, %f, %f", 
2310                 g_vtxTransformed[i].x,g_vtxTransformed[i].y,g_vtxTransformed[i].z,g_vtxTransformed[i].w);
2311             DebuggerAppendMsg("      : %f, %f, %f, %f", 
2312                 g_vecProjected[i].x,g_vecProjected[i].y,g_vecProjected[i].z,g_vecProjected[i].w);
2313         });
2314
2315         RSP_Vtx_Clipping(i);
2316
2317         if( gRSP.bLightingEnable )
2318         {
2319             {
2320                 uint32 r= ((gRSP.ambientLightColor>>16)&0xFF);
2321                 uint32 g= ((gRSP.ambientLightColor>> 8)&0xFF);
2322                 uint32 b= ((gRSP.ambientLightColor    )&0xFF);
2323                 for( uint32 k=1; k<=gRSPnumLights; k++)
2324                 {
2325                     r += gRSPlights[k].r;
2326                     g += gRSPlights[k].g;
2327                     b += gRSPlights[k].b;
2328                 }
2329                 if( r>255 ) r=255;
2330                 if( g>255 ) g=255;
2331                 if( b>255 ) b=255;
2332                 r *= vert.rgba.r ;
2333                 g *= vert.rgba.g ;
2334                 b *= vert.rgba.b ;
2335                 r >>= 8;
2336                 g >>= 8;
2337                 b >>= 8;
2338                 g_dwVtxDifColor[i] = 0xFF000000;
2339                 g_dwVtxDifColor[i] |= (r<<16);
2340                 g_dwVtxDifColor[i] |= (g<< 8);
2341                 g_dwVtxDifColor[i] |= (b    );          
2342             }
2343
2344             *(((uint8*)&(g_dwVtxDifColor[i]))+3) = vert.rgba.a; // still use alpha from the vertex
2345         }
2346         else
2347         {
2348             if( (gRDP.geometryMode & G_SHADE) == 0 && gRSP.ucode < 5 )  //Shade is disabled
2349             {
2350                 g_dwVtxDifColor[i] = gRDP.primitiveColor;
2351             }
2352             else    //FLAT shade
2353             {
2354                 g_dwVtxDifColor[i] = COLOR_RGBA(vert.rgba.r, vert.rgba.g, vert.rgba.b, vert.rgba.a);
2355             }
2356         }
2357
2358         if( options.bWinFrameMode )
2359         {
2360             //g_vecProjected[i].z = 0;
2361             g_dwVtxDifColor[i] = COLOR_RGBA(vert.rgba.r, vert.rgba.g, vert.rgba.b, vert.rgba.a);
2362         }
2363
2364         ReplaceAlphaWithFogFactor(i);
2365
2366         // Update texture coords n.b. need to divide tu/tv by bogus scale on addition to buffer
2367         //VECTOR2 & t = g_fVtxTxtCoords[i];
2368
2369         // If the vert is already lit, then there is no normal (and hence we
2370         // can't generate tex coord)
2371         if (gRSP.bTextureGen && gRSP.bLightingEnable )
2372         {
2373                 g_normal.x = (float)*(char*)(g_pRDRAMu8+ (((i<<1)+0)^3)+dwConkerVtxZAddr);
2374                 g_normal.y = (float)*(char*)(g_pRDRAMu8+ (((i<<1)+1)^3)+dwConkerVtxZAddr);
2375                 g_normal.z = (float)*(char*)(g_pRDRAMu8+ (((i<<1)+2)^3)+dwConkerVtxZAddr);
2376                 Vec3TransformNormal(g_normal, gRSPmodelViewTop);
2377                 TexGen(g_fVtxTxtCoords[i].x, g_fVtxTxtCoords[i].y);
2378         }
2379         else
2380         {
2381             g_fVtxTxtCoords[i].x = (float)vert.tu;
2382             g_fVtxTxtCoords[i].y = (float)vert.tv; 
2383         }
2384     }
2385
2386     VTX_DUMP(TRACE2("Setting Vertexes: %d - %d\n", dwV0, dwV0+dwNum-1));
2387     DEBUGGER_PAUSE_AND_DUMP(NEXT_VERTEX_CMD,{DebuggerAppendMsg("Paused at Vertex Cmd");});
2388 }
2389
2390
2391 typedef struct{
2392     short y;
2393     short x;
2394     short flag;
2395     short z;
2396 } RS_Vtx_XYZ;
2397
2398 typedef union {
2399     struct {
2400         uint8 a;
2401         uint8 b;
2402         uint8 g;
2403         uint8 r;
2404     };
2405     struct {
2406         char na;    //a
2407         char nz;    //b
2408         char ny;    //g
2409         char nx;    //r
2410     };
2411 } RS_Vtx_Color;
2412
2413
2414 void ProcessVertexData_Rogue_Squadron(uint32 dwXYZAddr, uint32 dwColorAddr, uint32 dwXYZCmd, uint32 dwColorCmd)
2415 {
2416     UpdateCombinedMatrix();
2417
2418     uint32 dwV0 = 0;
2419     uint32 dwNum = (dwXYZCmd&0xFF00)>>10;
2420
2421     RS_Vtx_XYZ * pVtxXYZBase = (RS_Vtx_XYZ*)(g_pRDRAMu8 + dwXYZAddr);
2422     RS_Vtx_Color * pVtxColorBase = (RS_Vtx_Color*)(g_pRDRAMu8 + dwColorAddr);
2423
2424     uint32 i;
2425     for (i = dwV0; i < dwV0 + dwNum; i++)
2426     {
2427         RS_Vtx_XYZ & vertxyz = pVtxXYZBase[i - dwV0];
2428         RS_Vtx_Color & vertcolors = pVtxColorBase[i - dwV0];
2429
2430         g_vtxNonTransformed[i].x = (float)vertxyz.x;
2431         g_vtxNonTransformed[i].y = (float)vertxyz.y;
2432         g_vtxNonTransformed[i].z = (float)vertxyz.z;
2433
2434 #if !defined(NO_ASM)
2435         if( status.isSSEEnabled )
2436             SSEVec3Transform(i);
2437         else
2438 #endif
2439         {
2440             Vec3Transform(&g_vtxTransformed[i], (XVECTOR3*)&g_vtxNonTransformed[i], &gRSPworldProject); // Convert to w=1
2441             g_vecProjected[i].w = 1.0f / g_vtxTransformed[i].w;
2442             g_vecProjected[i].x = g_vtxTransformed[i].x * g_vecProjected[i].w;
2443             g_vecProjected[i].y = g_vtxTransformed[i].y * g_vecProjected[i].w;
2444             g_vecProjected[i].z = g_vtxTransformed[i].z * g_vecProjected[i].w;
2445         }
2446
2447         VTX_DUMP( 
2448         {
2449             DebuggerAppendMsg("      : %f, %f, %f, %f", 
2450                 g_vtxTransformed[i].x,g_vtxTransformed[i].y,g_vtxTransformed[i].z,g_vtxTransformed[i].w);
2451             DebuggerAppendMsg("      : %f, %f, %f, %f", 
2452                 g_vecProjected[i].x,g_vecProjected[i].y,g_vecProjected[i].z,g_vecProjected[i].w);
2453         });
2454
2455         g_fFogCoord[i] = g_vecProjected[i].z;
2456         if( g_vecProjected[i].w < 0 || g_vecProjected[i].z < 0 || g_fFogCoord[i] < gRSPfFogMin )
2457             g_fFogCoord[i] = gRSPfFogMin;
2458
2459         RSP_Vtx_Clipping(i);
2460
2461         if( gRSP.bLightingEnable )
2462         {
2463             g_normal.x = (float)vertcolors.nx;
2464             g_normal.y = (float)vertcolors.ny;
2465             g_normal.z = (float)vertcolors.nz;
2466
2467 #if !defined(NO_ASM)
2468             if( status.isSSEEnabled )
2469             {
2470                 SSEVec3TransformNormal();
2471                 g_dwVtxDifColor[i] = SSELightVert();
2472             }
2473             else
2474 #endif
2475             {
2476                 Vec3TransformNormal(g_normal, gRSPmodelViewTop);
2477                 g_dwVtxDifColor[i] = LightVert(g_normal, i);
2478             }
2479             *(((uint8*)&(g_dwVtxDifColor[i]))+3) = vertcolors.a;    // still use alpha from the vertex
2480         }
2481         else
2482         {
2483             if( (gRDP.geometryMode & G_SHADE) == 0 && gRSP.ucode < 5 )  //Shade is disabled
2484             {
2485                 g_dwVtxDifColor[i] = gRDP.primitiveColor;
2486             }
2487             else    //FLAT shade
2488             {
2489                 g_dwVtxDifColor[i] = COLOR_RGBA(vertcolors.r, vertcolors.g, vertcolors.b, vertcolors.a);
2490             }
2491         }
2492
2493         if( options.bWinFrameMode )
2494         {
2495             g_dwVtxDifColor[i] = COLOR_RGBA(vertcolors.r, vertcolors.g, vertcolors.b, vertcolors.a);
2496         }
2497
2498         ReplaceAlphaWithFogFactor(i);
2499
2500         /*
2501         // Update texture coords n.b. need to divide tu/tv by bogus scale on addition to buffer
2502         VECTOR2 & t = g_fVtxTxtCoords[i];
2503
2504         // If the vert is already lit, then there is no normal (and hence we
2505         // can't generate tex coord)
2506         if (gRSP.bTextureGen && gRSP.bLightingEnable && g_textures[gRSP.curTile].m_bTextureEnable )
2507         {
2508             TexGen(g_fVtxTxtCoords[i].x, g_fVtxTxtCoords[i].y);
2509         }
2510         else
2511         {
2512             t.x = (float)vert.tu;
2513             t.y = (float)vert.tv; 
2514         }
2515         */
2516     }
2517
2518     VTX_DUMP(TRACE2("Setting Vertexes: %d - %d\n", dwV0, dwV0+dwNum-1));
2519     DEBUGGER_PAUSE_AND_DUMP(NEXT_VERTEX_CMD,{TRACE0("Paused at Vertex Cmd");});
2520 }
2521
2522 void SetLightCol(uint32 dwLight, uint32 dwCol)
2523 {
2524     gRSPlights[dwLight].r = (uint8)((dwCol >> 24)&0xFF);
2525     gRSPlights[dwLight].g = (uint8)((dwCol >> 16)&0xFF);
2526     gRSPlights[dwLight].b = (uint8)((dwCol >>  8)&0xFF);
2527     gRSPlights[dwLight].a = 255;    // Ignore light alpha
2528     gRSPlights[dwLight].fr = (float)gRSPlights[dwLight].r;
2529     gRSPlights[dwLight].fg = (float)gRSPlights[dwLight].g;
2530     gRSPlights[dwLight].fb = (float)gRSPlights[dwLight].b;
2531     gRSPlights[dwLight].fa = 255;   // Ignore light alpha
2532
2533     //TRACE1("Set light %d color", dwLight);
2534     LIGHT_DUMP(TRACE2("Set Light %d color: %08X", dwLight, dwCol));
2535 }
2536
2537 void SetLightDirection(uint32 dwLight, float x, float y, float z, float range)
2538 {
2539     //gRSP.bLightIsUpdated = true;
2540
2541     //gRSPlights[dwLight].ox = x;
2542     //gRSPlights[dwLight].oy = y;
2543     //gRSPlights[dwLight].oz = z;
2544
2545     register float w = range == 0 ? (float)sqrt(x*x+y*y+z*z) : 1;
2546
2547     gRSPlights[dwLight].x = x/w;
2548     gRSPlights[dwLight].y = y/w;
2549     gRSPlights[dwLight].z = z/w;
2550     gRSPlights[dwLight].range = range;
2551     DEBUGGER_PAUSE_AND_DUMP(NEXT_SET_LIGHT,TRACE5("Set Light %d dir: %.4f, %.4f, %.4f, %.4f", dwLight, x, y, z, range));
2552 }
2553
2554 static float maxS0, maxT0;
2555 static float maxS1, maxT1;
2556 static bool validS0, validT0;
2557 static bool validS1, validT1;
2558
2559 void LogTextureCoords(float fTex0S, float fTex0T, float fTex1S, float fTex1T)
2560 {
2561     if( validS0 )
2562     {
2563         if( fTex0S<0 || fTex0S>maxS0 )  validS0 = false;
2564     }
2565     if( validT0 )
2566     {
2567         if( fTex0T<0 || fTex0T>maxT0 )  validT0 = false;
2568     }
2569     if( validS1 )
2570     {
2571         if( fTex1S<0 || fTex1S>maxS1 )  validS1 = false;
2572     }
2573     if( validT1 )
2574     {
2575         if( fTex1T<0 || fTex1T>maxT1 )  validT1 = false;
2576     }
2577 }
2578
2579 bool CheckTextureCoords(int tex)
2580 {
2581     if( tex==0 )
2582     {
2583         return validS0&&validT0;
2584     }
2585     else
2586     {
2587         return validS1&&validT1;
2588     }
2589 }
2590
2591 void ResetTextureCoordsLog(float maxs0, float maxt0, float maxs1, float maxt1)
2592 {
2593     maxS0 = maxs0;
2594     maxT0 = maxt0;
2595     maxS1 = maxs1;
2596     maxT1 = maxt1;
2597     validS0 = validT0 = true;
2598     validS1 = validT1 = true;
2599 }
2600
2601 void ForceMainTextureIndex(int dwTile) 
2602 {
2603     if( dwTile == 1 && !(CRender::g_pRender->IsTexel0Enable()) && CRender::g_pRender->IsTexel1Enable() )
2604     {
2605         // Hack
2606         gRSP.curTile = 0;
2607     }
2608     else
2609     {
2610         gRSP.curTile = dwTile;
2611     }
2612 }
2613
2614 float HackZ2(float z)
2615 {
2616     z = (z+9)/10;
2617     return z;
2618 }
2619
2620 float HackZ(float z)
2621 {
2622     return HackZ2(z);
2623
2624     if( z < 0.1 && z >= 0 )
2625         z = (.1f+z)/2;
2626     else if( z < 0 )
2627         //return (10+z)/100;
2628         z = (expf(z)/20);
2629     return z;
2630 }
2631
2632 void HackZ(std::vector<XVECTOR3>& points)
2633 {
2634     int size = points.size();
2635     for( int i=0; i<size; i++)
2636     {
2637         XVECTOR3 &v = points[i];
2638         v.z = (float)HackZ(v.z);
2639     }
2640 }
2641
2642 void HackZAll()
2643 {
2644     if( CDeviceBuilder::m_deviceGeneralType == DIRECTX_DEVICE )
2645     {
2646         for( uint32 i=0; i<gRSP.numVertices; i++)
2647         {
2648             g_vtxBuffer[i].z = HackZ(g_vtxBuffer[i].z);
2649         }
2650     }
2651     else
2652     {
2653         for( uint32 i=0; i<gRSP.numVertices; i++)
2654         {
2655             float w = g_vtxProjected5[i][3];
2656             g_vtxProjected5[i][2] = HackZ(g_vtxProjected5[i][2]/w)*w;
2657         }
2658     }
2659 }
2660
2661
2662 extern XMATRIX reverseXY;
2663 extern XMATRIX reverseY;
2664
2665 void UpdateCombinedMatrix()
2666 {
2667     if( gRSP.bMatrixIsUpdated )
2668     {
2669         gRSPworldProject = gRSP.modelviewMtxs[gRSP.modelViewMtxTop] * gRSP.projectionMtxs[gRSP.projectionMtxTop];
2670         gRSP.bMatrixIsUpdated = false;
2671         gRSP.bCombinedMatrixIsUpdated = true;
2672     }
2673
2674     if( gRSP.bCombinedMatrixIsUpdated )
2675     {
2676         if( options.enableHackForGames == HACK_REVERSE_XY_COOR )
2677         {
2678             gRSPworldProject = gRSPworldProject * reverseXY;
2679         }
2680         if( options.enableHackForGames == HACK_REVERSE_Y_COOR )
2681         {
2682             gRSPworldProject = gRSPworldProject * reverseY;
2683         }
2684 #if !defined(NO_ASM)
2685         if( status.isSSEEnabled )
2686         {
2687             MatrixTranspose(&gRSPworldProjectTransported, &gRSPworldProject);
2688         }
2689 #endif
2690         gRSP.bCombinedMatrixIsUpdated = false;
2691     }
2692
2693     //if( gRSP.bWorldMatrixIsUpdated || gRSP.bLightIsUpdated )
2694     //{
2695     //  // Update lights with transported world matrix
2696     //  for( unsigned int l=0; l<gRSPnumLights; l++)
2697     //  {
2698     //      Vec3TransformCoord(&gRSPlights[l].td, &gRSPlights[l].od, &gRSPmodelViewTopTranspose);
2699     //      Vec3Normalize(&gRSPlights[l].td,&gRSPlights[l].td);
2700     //  }
2701
2702     //  gRSP.bWorldMatrixIsUpdated = false;
2703     //  gRSP.bLightIsUpdated = false;
2704     //}
2705 }
2706