/********************************************************************************/
/* Name     : STAINED															*/
/* Title    : KAMUI test program "STAINED" from VL								*/
/* Author   : VideoLogic Carlos Sarria / NEC Software Takeshi Muto				*/
/* Created  : July 1997 by VideoLogic											*/
/* Modified : Novenber 5. 1997 by Takeshi Muto for KAMUI						*/
/*																				*/
/* Description :																*/
/* Copyright : 1997 by VideoLogic Limited. All rights reserved.					*/
/********************************************************************************/
/*
#define		_X86_
*/
/* _X86_ flag for win95 : SET2 */

#define		SPEED			(1.0f)	/* move speed ( 1 to n ) */

#define		_DISPLAY_STRING_
/* if defined then display strings on screen */

#define		_DISP_PERFORMANCE_
/* Display performance : for windows */

/* Set Display Mode */
#define NTSC 1

#include	<math.h>
#include	<stdio.h>
#include	<stdlib.h>
#include	<float.h>

#include	<shinobi.h>

/*--
#include	<io.h>
#include	<FCNTL.H>
#include	<malloc.h>
--*/

#if defined(_X86_)
	#include	<time.h>
	#include	<windows.h>
#endif

#include	"kamui.h"				/* for Kamui Call */
#include	"dispstr.h"				/* for DisplayString */

/*#include <ddraw.h> */

/*#include "sgl.h" */
/*#include "frontend.h" */
#include	"kmstaind.h"			/* This is the file with 3D data */

#if defined(_DISP_PERFORMANCE_)
#if defined(_X86_)
#else
	#include    "QPF.H"                 /* for QueryPerformance */
#endif
#endif

/* Textures */
extern unsigned char stground;
extern unsigned char stlight;
extern unsigned char stpvr;
extern unsigned char stpvr2;

#pragma warning (disable : 4244) /* Disables float to double conversion warning */

/* Texture pixel struct */
typedef struct {
	KMUCHAR8	alpha;
	KMUCHAR8	blue;
	KMUCHAR8	green;
	KMUCHAR8	red;
} KMTEX_PIXEL;

/*#define RGBColour(r, g, b) ((sgl_uint32) (((sgl_uint32)(r&0x000000FF)<<16) | ((sgl_uint32)(g&0x000000FF) << 8) | (sgl_uint32)(b&0x000000FF))) */
#define	RGBColour(r, g, b)	((KMUINT32) (((r) << 16) | ((g) << 8) | (b)))
#define	RGBA(r, g, b, a)	((KMUINT32) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b)))

/* Macros for kamui */
#define		GetRED(col)			((KMFLOAT) ( ((col) & 0x00ff0000) >> 16 ) / 256.0f)
#define		GetGREEN(col)		((KMFLOAT) ( ((col) & 0x0000ff00) >>  8 ) / 256.0f)
#define		GetBLUE(col)		((KMFLOAT) ( ((col) & 0x000000ff)       ) / 256.0f)
#define		GetALPHA(col)		((KMFLOAT) ( ((col) & 0xff000000) >> 24 ) / 256.0f)

/* SGL互換TYPE */
typedef	KMUINT32	sgl_uint32;		/* type of sgl_uint32 */
typedef float		sgl_vector[3];	/* type of sgl_vector */
typedef float		sgl_2d_vec[2];	/* type of sgl_2d_vec */
typedef float		sgl_colour[3];	/* type of sgl_colour */
/* --------- */
/* SGLVERTEX */
/* --------- */
/* This structure is currently physically equivalent to Direct3D's D3DTLVERTEX */
/* (so one can be cast to the other), with the exception that Direct3D's u and */
/* v values must be multiplied by the 1/w value.  RAVE vertices already contain */
/* u/w and v/w. */
typedef struct tagSGLVERTEX
{
	/* Projected screen coordinates: */
	float		fX;		/* 0 <= fX < screen width (up to 1024) */
	float		fY;		/* 0 <= fY < screen height (up to 1024) */
	float		fZ;		/* 0.01 <= fZ <= 1, where 1 is infinite distance away */
	/* 1/w for the perspective projection (should be set to 1.0/fZ; fZ is */
	/* actually ignored): */
	float		fInvW;
	KMUINT32	u32Colour;			/* Material colour (D3DCOLOR format): */
	KMUINT32	u32Specular;		/* Specular colour (D3DCOLOR format): */
	float		fUOverW, fVOverW;	/* Texture coordinates: */
} SGLVERTEX, *PSGLVERTEX;

/****************************************************************************/
/**	Valuables for KAMUI *****************************************************/
/****************************************************************************/
	KMSTATUS			status;					/* return status of KAMUI API */
	KMVERSIONINFO		VersionInfo;			/* KAMUI Version information */
	KMSURFACEDESC		PrimarySurfaceDesc;		/* Primary frame buffer */
	KMSURFACEDESC		BackSurfaceDesc;		/* Back-buffer frame buffer */
	KMSURFACEDESC		Texture[10];			/* texture surface */
	KMVERTEXBUFFDESC	VertexBufferDesc;		/* Vertex-buffer */
	KMVERTEXCONTEXT		VertexContext;			/* Vertex context */

	PKMDWORD			BuffTex;				/* Pointer to texture */

/* 性能測定用変数 */
	int			frame;				/* 画面フレーム */
	int			frame_2 = 0;		/* 画面フレーム上位 */
#if defined(_DISP_PERFORMANCE_)
	int			pcount_f;			/* Hight-resolution counter supported? */
	double		nFPS;				/* 現在の性能(Frame/Second) */
	double		aFPS;				/* 性能の平均値 */
	double		MxFPS;				/* 最高性能 */
	double		MnFPS;				/* 最低性能 */
	__int64 	Time3i;				/* render API 完了時刻 */
	__int64		freqi;				/* カウンタの精度 */
	double		freq;				/* カウンタの精度 */
	double		Time3;				/* render API 完了時刻 */
	double		maxTime = 0.00001;	/* 最高描画時間(msec) */
	double		minTime = 99999;	/* 最低描画時間(msec) */
	double		OldTime3;			/* １フレーム前のrender直後の時間(msec) */
	double		nowTime;			/* 現在の描画時間(msec) */
	double		totalTime	= 0;	/* 累積render時間(msec) */
	double		aveTime;			/* 平均描画時間(msec) */
#if defined(_X86_)
	time_t		start_time;			/* APの開始時間 */
#endif
#endif

/*------------------------------- Global Variables -----------------------------------*/

#define PI	3.1416f

/*int	Device */
int		Init = TRUE;
int		frame;
int		TPos = 280;
int		UpVert=1;
/*int	Texture[100]; */
int		PosX = 10;
int		PosY = 10;
float	Shad[255], GroundSh[1000];
/*float XAng1 = 0.00f,  YAng1 = 0.001f; */
float XAng  = -6.3f,  YAng  =-18.85f;

SGLVERTEX  *TempVert[NUM_MESHES];
/*SGLCONTEXT SGLContext; */
/*sgl_intermediate_map BuffTex[5]; */
sgl_uint32 GroundCo[1000][3], GCo[1000][3], Logo[50][50][3];

void SetupContext   (void);
void SetupTextures  (void);
void InitMeshes     (void);
void DrawAll        (void);
void UpdateVertex   (int Num);
void Shading        (int Num);
void GroundColour   (void);
void CalculateLight (void);
void ShadingGround  (void);
void MoveLamp       (void);

/****************************************************************************/
/**	Check KAMUI function status *********************************************/
/****************************************************************************/
void	Check_Status(KMSTATUS status, char *func)
{
	switch(status) {
	case KMSTATUS_SUCCESS:
		/* No message is displayed when SUCCESS */
		break;
	case KMSTATUS_INVALID_DISPLAY_MODE:
		PRINTOUT(("%s:KMSTATUS_INVALID_DISPLAY_MODE\n",func)); break;
	case KMSTATUS_INVALID_VIDEO_MODE:
		PRINTOUT(("%s:KMSTATUS_INVALID_VIDEO_MODE\n",func)); break;
	case KMSTATUS_NOT_ENOUGH_MEMORY:
		PRINTOUT(("%s:KMSTATUS_NOT_ENOUGH_MEMORY\n",func)); break;
	case KMSTATUS_INVALID_TEXTURE_TYPE:
		PRINTOUT(("%s:KMSTATUS_INVALID_TEXTURE_TYPE\n",func)); break;
	case KMSTATUS_INVALID_MIPMAPED_TEXTURE:
		PRINTOUT(("%s:KMSTATUS_INVALID_MIPMAPED_TEXTURE\n",func)); break;
	case KMSTATUS_CANT_FLIP_SURFACE:
		PRINTOUT(("%s:KMSTATUS_CANT_FLIP_SURFACE\n",func)); break;
	case KMSTATUS_INVALID_ADDRESS:
		PRINTOUT(("%s:KMSTATUS_INVALID_ADDRESS\n",func)); break;
	case KMSTATUS_HARDWARE_NOT_PRESENTED:
		PRINTOUT(("%s:KMSTATUS_HARDWARE_NOT_PRESENTED\n",func)); break;
	case KMSTATUS_INVALID_SETTING:
		PRINTOUT(("%s:KMSTATUS_INVALID_SETTING\n",func)); break;
	case KMSTATUS_INVALID_VERTEX_TYPE:
		PRINTOUT(("%s:KMSTATUS_INVALID_VERTEX_TYPE\n",func)); break;
	case KMSTATUS_NOT_IMPLEMENTED:
		PRINTOUT(("%s:KMSTATUS_NOT_IMPREMENTED\n",func)); break;
	case KMSTATUS_INVALID_PARAMETER:
		PRINTOUT(("%s:KMSTATUS_INVALID_PARAMETER\n",func)); break;
	default:
		PRINTOUT(("%s:???Undefined status : %d\n", func, status));
		break;
	}
}

/****************************************************************************/
/**	Background surface setting **********************************************/
/****************************************************************************/
void	InitBackGround(void)
{
	KMSTATUS			status;
	KMVERTEXCONTEXT		BackVertexContext;		/* Vertex context */
	KMVERTEX_01			BV[3];					/* pointer to Vertex */
	PVOID				pBV[3];					/* pointer to Vertex */

	/* Clear VertexContext */
	memset(&BackVertexContext,0,sizeof(KMVERTEXCONTEXT));

	/* Setup VertexContext */
	BackVertexContext.RenderState	= KM_DEPTHMODE  		| KM_CULLINGMODE				/* ISP/TSP IW */
									| KM_SCREENCOORDINATION	| KM_SHADINGMODE
									| KM_MODIFIER 			| KM_ZWRITEDISABLE				/* TSP CW */
									| KM_SRCBLENDINGMODE
									| KM_SRCSELECT			| KM_DSTSELECT
									| KM_FOGMODE			| KM_USESPECULAR
									| KM_USEALPHA			| KM_IGNORETEXTUREALPHA
									| KM_FLIPUV 			| KM_CLAMPUV 
									| KM_FILTERMODE			| KM_SUPERSAMPLE
									| KM_MIPMAPDADJUST 		| KM_TEXTURESHADINGMODE
									| KM_PARAMTYPE 			| KM_LISTTYPE 					/* Param CW */
									| KM_COLORTYPE			| KM_USESPECULAR
									| KM_UVFORMAT;

	/* for ParameterControlWord  */
	BackVertexContext.ParamType				= KM_POLYGON;
	BackVertexContext.ListType				= KM_OPAQUE_POLYGON;
	BackVertexContext.ColorType				= KM_FLOATINGCOLOR;
	BackVertexContext.bUseSpecular			= FALSE;
	BackVertexContext.UVFormat				= KM_32BITUV;

	/* for ISP/TSP InstructionWord  */
	BackVertexContext.DepthMode				= KM_GREATER;
	BackVertexContext.CullingMode			= KM_NOCULLING;
	BackVertexContext.ScreenCoordination	= KM_SCREEN;
	BackVertexContext.ShadingMode			= KM_NOTEXTUREGOURAUD;
	BackVertexContext.SelectModifier		= KM_NOMODIFIER;
	BackVertexContext.bZWriteDisable		= FALSE;			/* not effective on ARC1 */

	/* for TSP ControlWord  */
	BackVertexContext.SRCBlendingMode		= KM_ONE;
/*	BackVertexContext.DSTBlendingMode		= KM_ZERO;	// must not set this parameter on background plane */
	BackVertexContext.bSRCSel				= FALSE;			/* not effective on ARC1 */
	BackVertexContext.bDSTSel				= FALSE;			/* not effective on ARC1 */
	BackVertexContext.FogMode				= KM_NOFOG;			/* 11 is reserved */
	BackVertexContext.bUseSpecular			= FALSE;
	BackVertexContext.bUseAlpha				= FALSE;
	BackVertexContext.ClampUV				= KM_NOCLAMP;
	BackVertexContext.FilterMode			= KM_POINT_SAMPLE;
	BackVertexContext.bSuperSample			= FALSE;
	BackVertexContext.MipMapAdjust			= 0x00000004;		/* D=1.00 */
	BackVertexContext.TextureShadingMode	= KM_MODULATE;
	
	/* for Texture ControlBit */

	/* No effect on ARC1 */
	BackVertexContext.bColorClamp			= FALSE;
	BackVertexContext.PaletteBank			= 0;

	/* for GlobalColorData */
	BackVertexContext.fFaceColorAlpha		= 1.0f;		/* Face Color Alpha */
	BackVertexContext.fFaceColorRed			= 1.0f;		/* Face Color Red */
	BackVertexContext.fFaceColorGreen		= 1.0f;		/* Face Color Green */
	BackVertexContext.fFaceColorBlue		= 1.0f;		/* Face Color Blue */
	BackVertexContext.fOffsetColorAlpha		= 1.0f;		/* Specular Color Alpha */
	BackVertexContext.fOffsetColorRed		= 1.0f;		/* Specular Color Red */
	BackVertexContext.fOffsetColorGreen		= 1.0f;		/* Specular Color Green */
	BackVertexContext.fOffsetColorBlue		= 1.0f;		/* Specular Color Blue */

	status = kmProcessVertexRenderState(&BackVertexContext);
	Check_Status(status, "kmProcessVertexRenderState");
	status = kmSetBackGroundRenderState(&BackVertexContext);
	Check_Status(status, "kmSetBackGroundRenderState");

	/*----------------------------------------------------------------------------------- */
	/* set VERTEX DATA */

	/* Vertex #1 */
	BV[0].ParamControlWord	= KM_VERTEXPARAM_NORMAL;
	BV[0].fX				=   0.0f;
	BV[0].fY				= 479.0f;
#if defined(_STRICT_UNION_)
	BV[0].u.fZ				=  0.0001f;
#else
	BV[0].fZ				=  0.0001f;
#endif
	BV[0].fBaseAlpha		=   0.0f;
	BV[0].fBaseRed			=   0.3f;
	BV[0].fBaseGreen		=   0.3f;
	BV[0].fBaseBlue			=   0.3f;

	/* Vertex #2 */
	BV[1].ParamControlWord	= KM_VERTEXPARAM_NORMAL;
	BV[1].fX				= 320.0f;
	BV[1].fY				=   0.0f;
#if defined(_STRICT_UNION_)
	BV[1].u.fZ				=  0.0001f;
#else
	BV[1].fZ				=  0.0001f;
#endif
	BV[1].fBaseAlpha		=   0.0f;
	BV[1].fBaseRed			=   0.1f;
	BV[1].fBaseGreen		=   0.1f;
	BV[1].fBaseBlue			=   0.1f;

	/* Vertex #3 */
	BV[2].ParamControlWord	= KM_VERTEXPARAM_ENDOFSTRIP;
	BV[2].fX				= 639.0f;
	BV[2].fY				= 479.0f;
#if defined(_STRICT_UNION_)
	BV[2].u.fZ				=  0.0001f;
#else
	BV[2].fZ				=  0.0001f;
#endif
	BV[2].fBaseAlpha		=   0.0f;
	BV[2].fBaseRed			=   0.3f;
	BV[2].fBaseGreen		=   0.3f;
	BV[2].fBaseBlue			=   0.3f;

	pBV[0] = &BV[0];
	pBV[1] = &BV[1];
	pBV[2] = &BV[2];

	/*----------------------------------------------------------------------------------- */
	/* set VERTEX */
	status = kmSetBackGroundPlane(	pBV,					/* pVertex */
									KM_VERTEXTYPE_01,		/* VertexType */
									sizeof(KMVERTEX_01)		/* StructSize */
									);
	Check_Status(status, "kmSetBackGroundPlane");
}

/****************************************************************************/
/**	kmtri_quads  by T.Hirata ************************************************/
/****************************************************************************/
void 
kmtri_quads (	KMVERTEXBUFFDESC	BufferDesc,
				KMVERTEXCONTEXT		VertexContext,
				int  nNumFaces,
				int  pFaces[][4],
				PSGLVERTEX  pVertices )
{
	KMSTATUS	status;
	int			i;
	KMVERTEX_03	Ver;

	status = kmSetVertexRenderState(&VertexContext);
	Check_Status(status, "kmSetVertexRenderState");

	for(i = 0; i < nNumFaces; i++)
	{
		status = kmStartVertexStrip(&BufferDesc);
		Check_Status(status, "kmStartVertexStrip");

		Ver.ParamControlWord	= KM_VERTEXPARAM_NORMAL;
		Ver.fX					= pVertices[pFaces[i][0]].fX;
		Ver.fY					= pVertices[pFaces[i][0]].fY;
#if defined(_STRICT_UNION_)
		Ver.u.fZ				= pVertices[pFaces[i][0]].fInvW;
#else
		Ver.fZ					= pVertices[pFaces[i][0]].fInvW;
#endif
		Ver.fU					= pVertices[pFaces[i][0]].fUOverW;
		Ver.fV					= pVertices[pFaces[i][0]].fVOverW;
		Ver.uBaseRGB.dwPacked	= pVertices[pFaces[i][0]].u32Colour;
		Ver.uOffsetRGB.dwPacked	= pVertices[pFaces[i][0]].u32Specular;
		status = kmSetVertex(&BufferDesc,&Ver,KM_VERTEXTYPE_03,sizeof(KMVERTEX_03) );
		Check_Status(status, "kmSetVertex");

		Ver.ParamControlWord	= KM_VERTEXPARAM_NORMAL;
		Ver.fX					= pVertices[pFaces[i][1]].fX;
		Ver.fY					= pVertices[pFaces[i][1]].fY;
#if defined(_STRICT_UNION_)
		Ver.u.fZ				= pVertices[pFaces[i][1]].fInvW;
#else
		Ver.fZ					= pVertices[pFaces[i][1]].fInvW;
#endif
		Ver.fU					= pVertices[pFaces[i][1]].fUOverW;
		Ver.fV					= pVertices[pFaces[i][1]].fVOverW;
		Ver.uBaseRGB.dwPacked	= pVertices[pFaces[i][1]].u32Colour;
		Ver.uOffsetRGB.dwPacked	= pVertices[pFaces[i][1]].u32Specular;
		status = kmSetVertex(&BufferDesc,&Ver,KM_VERTEXTYPE_03,sizeof(KMVERTEX_03) );
		Check_Status(status, "kmSetVertex");

		Ver.ParamControlWord	= KM_VERTEXPARAM_NORMAL;
		Ver.fX					= pVertices[pFaces[i][3]].fX;
		Ver.fY					= pVertices[pFaces[i][3]].fY;
#if defined(_STRICT_UNION_)
		Ver.u.fZ				= pVertices[pFaces[i][3]].fInvW;
#else
		Ver.fZ					= pVertices[pFaces[i][3]].fInvW;
#endif
		Ver.fU					= pVertices[pFaces[i][3]].fUOverW;
		Ver.fV					= pVertices[pFaces[i][3]].fVOverW;
		Ver.uBaseRGB.dwPacked	= pVertices[pFaces[i][3]].u32Colour;
		Ver.uOffsetRGB.dwPacked	= pVertices[pFaces[i][3]].u32Specular;
		status = kmSetVertex(&BufferDesc,&Ver,KM_VERTEXTYPE_03,sizeof(KMVERTEX_03) );
		Check_Status(status, "kmSetVertex");

		Ver.ParamControlWord	= KM_VERTEXPARAM_ENDOFSTRIP;
		Ver.fX					= pVertices[pFaces[i][2]].fX;
		Ver.fY					= pVertices[pFaces[i][2]].fY;
#if defined(_STRICT_UNION_)
		Ver.u.fZ				= pVertices[pFaces[i][2]].fInvW;
#else
		Ver.fZ					= pVertices[pFaces[i][2]].fInvW;
#endif
		Ver.fU					= pVertices[pFaces[i][2]].fUOverW;
		Ver.fV					= pVertices[pFaces[i][2]].fVOverW;
		Ver.uBaseRGB.dwPacked	= pVertices[pFaces[i][2]].u32Colour;
		Ver.uOffsetRGB.dwPacked	= pVertices[pFaces[i][2]].u32Specular;
		status = kmSetVertex(&BufferDesc,&Ver,KM_VERTEXTYPE_03,sizeof(KMVERTEX_03) );
		Check_Status(status, "kmSetVertex");
	}
}

/****************************************************************************/
/**	kmtri_triangles  by T.Hirata ********************************************/
/****************************************************************************/
void 
kmtri_triangles ( KMVERTEXBUFFDESC		BufferDesc,
				  KMVERTEXCONTEXT		VertexContext,
				  int  					nNumFaces,
				  int  					pFaces[][3],
				  PSGLVERTEX  			pVertices,
				  int					bTexture)
{
	KMSTATUS	status;
	int			i;
	KMVERTEX_00	Ver00;				/* for NO-TEXTURE-GOURAUD */
	KMVERTEX_03	Ver03;				/* for TEXTURE-GOURAUD */

	status = kmSetVertexRenderState(&VertexContext);
	Check_Status(status, "kmSetVertexRenderState");

	for(i = 0; i < nNumFaces; i++)
	{
		status = kmStartVertexStrip(&BufferDesc);
		Check_Status(status, "kmStartVertexStrip");

		if(bTexture == TRUE) {
			Ver03.ParamControlWord		= KM_VERTEXPARAM_NORMAL;
			Ver03.fX					= pVertices[pFaces[i][0]].fX;
			Ver03.fY					= pVertices[pFaces[i][0]].fY;
#if defined(_STRICT_UNION_)
			Ver03.u.fZ					= pVertices[pFaces[i][0]].fInvW;
#else
			Ver03.fZ					= pVertices[pFaces[i][0]].fInvW;
#endif
			Ver03.fU					= pVertices[pFaces[i][0]].fUOverW;
			Ver03.fV					= pVertices[pFaces[i][0]].fVOverW;
			Ver03.uBaseRGB.dwPacked		= pVertices[pFaces[i][0]].u32Colour;
			Ver03.uOffsetRGB.dwPacked	= pVertices[pFaces[i][0]].u32Specular;
			status = kmSetVertex(&BufferDesc,&Ver03,KM_VERTEXTYPE_03,sizeof(KMVERTEX_03) );
			Check_Status(status, "kmSetVertex");

			Ver03.ParamControlWord		= KM_VERTEXPARAM_NORMAL;
			Ver03.fX					= pVertices[pFaces[i][1]].fX;
			Ver03.fY					= pVertices[pFaces[i][1]].fY;
#if defined(_STRICT_UNION_)
			Ver03.u.fZ					= pVertices[pFaces[i][1]].fInvW;
#else
			Ver03.fZ					= pVertices[pFaces[i][1]].fInvW;
#endif
			Ver03.fU					= pVertices[pFaces[i][1]].fUOverW;
			Ver03.fV					= pVertices[pFaces[i][1]].fVOverW;
			Ver03.uBaseRGB.dwPacked		= pVertices[pFaces[i][1]].u32Colour;
			Ver03.uOffsetRGB.dwPacked	= pVertices[pFaces[i][1]].u32Specular;
			status = kmSetVertex(&BufferDesc,&Ver03,KM_VERTEXTYPE_03,sizeof(KMVERTEX_03) );
			Check_Status(status, "kmSetVertex");

			Ver03.ParamControlWord		= KM_VERTEXPARAM_ENDOFSTRIP;
			Ver03.fX					= pVertices[pFaces[i][2]].fX;
			Ver03.fY					= pVertices[pFaces[i][2]].fY;
#if defined(_STRICT_UNION_)
			Ver03.u.fZ					= pVertices[pFaces[i][2]].fInvW;
#else
			Ver03.fZ					= pVertices[pFaces[i][2]].fInvW;
#endif
			Ver03.fU					= pVertices[pFaces[i][2]].fUOverW;
			Ver03.fV					= pVertices[pFaces[i][2]].fVOverW;
			Ver03.uBaseRGB.dwPacked		= pVertices[pFaces[i][2]].u32Colour;
			Ver03.uOffsetRGB.dwPacked	= pVertices[pFaces[i][2]].u32Specular;
			status = kmSetVertex(&BufferDesc,&Ver03,KM_VERTEXTYPE_03,sizeof(KMVERTEX_03) );
			Check_Status(status, "kmSetVertex");
		}
		else {	/* if(bTexture == TRUE) : NO-TEXTURE */
			Ver00.ParamControlWord	= KM_VERTEXPARAM_NORMAL;
			Ver00.fX				= pVertices[pFaces[i][0]].fX;
			Ver00.fY				= pVertices[pFaces[i][0]].fY;
#if defined(_STRICT_UNION_)
			Ver00.u.fZ				= pVertices[pFaces[i][0]].fInvW;
#else
			Ver00.fZ				= pVertices[pFaces[i][0]].fInvW;
#endif
			Ver00.uBaseRGB.dwPacked	= pVertices[pFaces[i][0]].u32Colour;
			status = kmSetVertex(&BufferDesc,&Ver00,KM_VERTEXTYPE_00,sizeof(KMVERTEX_00) );
			Check_Status(status, "kmSetVertex");

			Ver00.ParamControlWord	= KM_VERTEXPARAM_NORMAL;
			Ver00.fX				= pVertices[pFaces[i][1]].fX;
			Ver00.fY				= pVertices[pFaces[i][1]].fY;
#if defined(_STRICT_UNION_)
			Ver00.u.fZ				= pVertices[pFaces[i][1]].fInvW;
#else
			Ver00.fZ				= pVertices[pFaces[i][1]].fInvW;
#endif
			Ver00.uBaseRGB.dwPacked	= pVertices[pFaces[i][1]].u32Colour;
			status = kmSetVertex(&BufferDesc,&Ver00,KM_VERTEXTYPE_00,sizeof(KMVERTEX_00) );
			Check_Status(status, "kmSetVertex");

			Ver00.ParamControlWord	= KM_VERTEXPARAM_ENDOFSTRIP;
			Ver00.fX				= pVertices[pFaces[i][2]].fX;
			Ver00.fY				= pVertices[pFaces[i][2]].fY;
#if defined(_STRICT_UNION_)
			Ver00.u.fZ				= pVertices[pFaces[i][2]].fInvW;
#else
			Ver00.fZ				= pVertices[pFaces[i][2]].fInvW;
#endif
			Ver00.uBaseRGB.dwPacked	= pVertices[pFaces[i][2]].u32Colour;
			status = kmSetVertex(&BufferDesc,&Ver00,KM_VERTEXTYPE_00,sizeof(KMVERTEX_00) );
			Check_Status(status, "kmSetVertex");
		} /* end of if(bTexture == TRUE) */
	}
}

/****************************************************************************/
/**	Initialize Vertex Context ***********************************************/
/****************************************************************************/
void	InitVertexContext(PKMVERTEXCONTEXT pVertexContext)
{
	/* 頂点CONTEXTの生成 */
	pVertexContext->RenderState	= KM_DEPTHMODE  		| KM_CULLINGMODE
								| KM_SCREENCOORDINATION	| KM_SHADINGMODE
								| KM_MODIFIER 			| KM_ZWRITEDISABLE
								| KM_SRCBLENDINGMODE	| KM_DSTBLENDINGMODE
								| KM_SRCSELECT			| KM_DSTSELECT
								| KM_FOGMODE			| KM_USESPECULAR
								| KM_USEALPHA			| KM_IGNORETEXTUREALPHA
								| KM_FLIPUV 			| KM_CLAMPUV 
								| KM_FILTERMODE			| KM_SUPERSAMPLE
								| KM_MIPMAPDADJUST 		| KM_TEXTURESHADINGMODE
								| KM_PARAMTYPE 			| KM_LISTTYPE
								| KM_COLORTYPE			| KM_USESPECULAR
								| KM_UVFORMAT;

	/* for ParameterControlWord  */
	pVertexContext->ParamType			= KM_POLYGON;
	pVertexContext->ListType			= KM_OPAQUE_POLYGON;
	pVertexContext->ColorType			= KM_PACKEDCOLOR;
	pVertexContext->bUseSpecular		= FALSE;
	pVertexContext->UVFormat			= KM_32BITUV;

	/* for ISP/TSP InstructionWord  */
	pVertexContext->DepthMode			= KM_GREATER;
/*	pVertexContext->CullingMode			= KM_NOCULLING; */
	pVertexContext->CullingMode			= KM_CULLSMALL;
	pVertexContext->ScreenCoordination	= KM_SCREEN;
	pVertexContext->ShadingMode			= KM_NOTEXTUREGOURAUD;
	pVertexContext->SelectModifier		= KM_NOMODIFIER;
	pVertexContext->bZWriteDisable		= FALSE;			/* ARC1にはない */

	/* for TSP ControlWord  */
	pVertexContext->SRCBlendingMode		= KM_ONE;
	pVertexContext->DSTBlendingMode		= KM_ZERO;
	pVertexContext->bSRCSel				= FALSE;			/* ARC1にはない */
	pVertexContext->bDSTSel				= FALSE;			/* ARC1にはない */
	pVertexContext->FogMode				= KM_NOFOG;			/* 11はリザーブ */
	pVertexContext->bUseSpecular		= FALSE;
	pVertexContext->bUseAlpha			= FALSE;
	pVertexContext->FlipUV				= KM_NOFLIP;
	pVertexContext->ClampUV				= KM_NOCLAMP;
/*	pVertexContext->FilterMode			= KM_POINT_SAMPLE; */
	pVertexContext->FilterMode			= KM_BILINEAR;
	pVertexContext->bSuperSample		= FALSE;
	pVertexContext->MipMapAdjust		= 0x00000004;		/* D=1.00 */
	pVertexContext->TextureShadingMode	= KM_MODULATE;
/*	pVertexContext->TextureShadingMode	= KM_MODULATE_ALPHA; */
	
	/* for Texture ControlBit */

	/* No effect on ARC1 */
	pVertexContext->bColorClamp		= FALSE;
	pVertexContext->PaletteBank		= 0;

	/* for GlobalColorData */
	pVertexContext->fFaceColorAlpha		= 1.0f;		/* Face Color Alpha */
	pVertexContext->fFaceColorRed		= 1.0f;		/* Face Color Red */
	pVertexContext->fFaceColorGreen		= 1.0f;		/* Face Color Green */
	pVertexContext->fFaceColorBlue		= 1.0f;		/* Face Color Blue */
	pVertexContext->fOffsetColorAlpha	= 1.0f;		/* Specular Color Alpha */
	pVertexContext->fOffsetColorRed		= 1.0f;		/* Specular Color Red */
	pVertexContext->fOffsetColorGreen	= 1.0f;		/* Specular Color Green */
	pVertexContext->fOffsetColorBlue	= 1.0f;		/* Specular Color Blue */

	kmProcessVertexRenderState(pVertexContext);
}

#if 0
/****************************************************************************/
/**	Load texture ************************************************************/
/****************************************************************************/
PKMDWORD LoadTextureFile(char *filename)
{
	int			hFile;
	long		filelen;
	PKMDWORD	pTexture;

	/* Open input file */
	hFile = _open(filename, _O_RDONLY | _O_BINARY);
	if(hFile != -1) {
		filelen = _filelength(hFile);			/* length of texture file */
		pTexture = (PKMDWORD)malloc(filelen);	/* allocate mainmemory */
		_read(hFile, pTexture, filelen);		/* read in texture file */
		_close(hFile);							/* file close */
		printf("LoadTextureFile: Texture file %s load OK.\n",filename);
	}
	else {
		printf("LoadTextureFile: ??ERROR Can not read texture file %s .\n",filename);
	}
	return pTexture;
}
#endif

/*-------------------------------------------------------------------------------------*/
/*  Function Name   :   SetupScene                                                     */
/*  Inputs          :   None                                                           */
/*  Outputs         :   None                                                           */
/*  Returns         :   Error message or 0                                             */
/*  Globals Used    :   Device                                                         */
/*  Description     :   This routine is used to set SGL device and setup some values.  */
/*                      This routine is called from FRONTEND.C                         */
/*-------------------------------------------------------------------------------------*/
int SetupScene (void)
{
/*	Device = sgl_create_screen_device (0, 640, 480, sgl_device_16bit, TRUE);  */
/*	if (Device<0) return ERR_CREATE_SCREEN_DEVICE; */

/*	sgl_qual_texture_filter (sgl_tf_bilinear); */

	/*-----------------------------------------------------------------------------------*/
	/* Initialize Hardware */

#if NTSC
	sbInitSystem( NJD_RESOLUTION_640x480_NTSCNI, NJD_FRAMEBUFFER_MODE_RGB565, 1 );
#else
	sbInitSystem( NJD_RESOLUTION_VGA, NJD_FRAMEBUFFER_MODE_RGB565, 1 );
#endif

	kmGetVersionInfo(&VersionInfo);
	PRINTOUT(("MajorVersion      0x0%08x\n",VersionInfo.kmMajorVersion));
	PRINTOUT(("LocalVersion      0x0%08x\n",VersionInfo.kmLocalVersion));
	PRINTOUT(("kmFrameBufferSize 0x0%08x\n",VersionInfo.kmFrameBufferSize));

	/*----------------------------------------------------------------------------------- */
	/* Create primary frame buffer surface */
	status = kmCreateFrameBufferSurface(&PrimarySurfaceDesc,	/* pSurfaceDesc */
								640,	/* nWidth */
								480,	/* nHeight */
								FALSE,	/* bStripBuffer */
								FALSE	/* bBufferClear */
								);
	Check_Status(status, "kmCreateFrameBufferSurface(Primary)");

	/*----------------------------------------------------------------------------------- */
	/* Create backbuffer frame buffer surface */
	status = kmCreateFrameBufferSurface(&BackSurfaceDesc,	/* pSurfaceDesc */
								640,	/* nWidth */
								480,	/* nHeight */
								FALSE,	/* bStripBuffer */
								FALSE	/* bBufferClear */
								);
	Check_Status(status, "kmCreateFrameBufferSurface(Back-buffer)");
	/*----------------------------------------------------------------------------------- */
	/* Set Latency Model */
	kmChangeLatencyModel(KM_LATENCYMODEL_2V, KM_VERTEXBUFMODEL_NOBUF_TRANS); 

	/*----------------------------------------------------------------------------------- */
	/* Create vertex buffer */
	status = kmCreateVertexBuffer(&VertexBufferDesc,		/* pBufferDesc */
									131072,					/* Opaque-Polygon 500KB */
									0,						/* Opaque-Modifier */
									131072,					/* Trans-Polygon 500KB */
									0						/* Trans-Modifier */
									);
	Check_Status(status, "kmCreateVertexBuffer");

	/*----------------------------------------------------------------------------------- */
	/* Set Culling Register */
	status = kmSetCullingRegister(1.0f);
	Check_Status(status, "kmSetCullingRegister");

	/*----------------------------------------------------------------------------------- */
	/* set display surface */
	status = kmActivateFrameBuffer(	&PrimarySurfaceDesc,	/* pSurfaceDesc */
									&BackSurfaceDesc,		/* pSurfaceDesc */
									FALSE,					/* bStripBuffer */
									TRUE					/* bWaitVSync */
									);
	Check_Status(status, "kmActivateFrameBuffer");

	/*----------------------------------------------------------------------------------- */
	/* some initializes */
	SetupTextures (); 
	SetupContext  ();

    InitMeshes ();

	txt_InitDisplayString();	/* Initialize DisplayString routine */
	InitBackGround();			/* Setup background plane */

	/*-------------------------------------------------------------------------------- */
	/* 性能測定用各種変数の初期化 */

	frame		= 0;

#if defined(_DISP_PERFORMANCE_)
	totalTime	= 0;

	pcount_f = QueryPerformanceFrequency((LARGE_INTEGER*)&freqi);	/* カウンタの単位の読み出し */
	if(pcount_f) {	/*	QueryPerformanceCounterがサポートされている */
		QueryPerformanceCounter((LARGE_INTEGER*)&Time3i);	/* ダミー値による初期化 */
		freq = 1000.0f / (double)freqi;						/* msec変換用係数の生成 */
		OldTime3 = Time3 = (double)Time3i * freq;			/* countからmsecへ変換 */
	}
	else {	/* QueryPerformanceCounterがサポートされていない */
		Time3 = (double)timeGetTime();						/* ダミー値による初期化 */
	}

	/* Get AP start time ---------------------------------------------*/
#if defined(_X86_)
	 time( &start_time );
#endif
#endif	/* defined(_DISP_PERFORMANCE_) */

    return 0;
}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   :   NextFrame                                                      */
/*  Inputs          :   None                                                           */
/*  Outputs         :   None                                                           */
/*  Returns         :   None                                                           */
/*  Globals Used    :   SGLContext                                                     */
/*  Description     :   Drawing everything and rendering.                              */
/*                      This routine is called from FRONTEND.C                         */
/*-------------------------------------------------------------------------------------*/
void NextFrame()
{
	char		str[256];
#if defined(_X86_)
	time_t		ltime;
#endif

/*	sgltri_startofframe (&SGLContext); */
	 DrawAll ();
/*	sgltri_render   (&SGLContext); */

	txt_SetCursor(0,4);
#if defined(_DISP_PERFORMANCE_)
	/* Write Date & Time on screen ---------------------------------------------*/
#if defined(_X86_)
	 time( &ltime );
    PRINTOUT(("START : %s", ctime( &start_time )));
    PRINTOUT(("NOW   : %s", ctime( &ltime )));
#endif
	/* Write FPS on screen -----------------------------------------------------*/
	PRINTOUT(("FRAME : %06d%06d  Now:%07.3fFPS, Ave:%07.3fFPS\n",frame_2, frame,nFPS,aFPS));
#else
	PRINTOUT(("FRAME : %06d%06d\n",frame_2, frame));
#endif	/* defined(_DISP_PERFORMANCE_) */

	/*-----------------------------------------------------------------------------------*/
	/* Rendering start */
#if defined(_DISPLAY_STRING_)
	txt_DispScreen(VertexBufferDesc);		/* Display screen */
#endif
	status = kmRender();
	Check_Status(status, "kmRender");

	/*----------------------------------------------------------------------------------- */
	/* Flip screen */
	status = kmFlipFrameBuffer();
	Check_Status(status, "kmFlipFrameBuffer");

#if defined(_DISP_PERFORMANCE_)
	/* render終了の時刻 -----------------------------------------------------------------*/
	if(pcount_f) {
		QueryPerformanceCounter((LARGE_INTEGER*)&Time3i);	/* sgltri_render終了の時刻 */
		OldTime3 = Time3; Time3 = (double)Time3i * freq;
	}
	else {
		OldTime3 = Time3; Time3 = (double)timeGetTime();	/* sgltri_render終了の時刻 */
	}

/* 性能計算 ------------------------------------------------------------------*/
	nowTime = Time3 - OldTime3;					/* ただいまのフレームを作成するのにかかった時間 */
	if((nowTime > 1000.0f)||(nowTime < 1.0f)) nowTime = 20.0f;		/* 得られた値が異常であった場合は無視 */
	if(nowTime > maxTime) maxTime = nowTime;	/* もっとも時間がかかった？ */
	if(nowTime < minTime) minTime = nowTime;	/* もっとも早かった？ */

	totalTime += nowTime;										/* 累積時間 */
	aveTime = totalTime / ((double)frame + 1.0f);		/* 今までの平均時間 */

	nFPS  = 1000.0f / (double)nowTime;
	aFPS  = 1000.0f / (double)aveTime;
	MxFPS = 1000.0f / (double)minTime;
	MnFPS = 1000.0f / (double)maxTime;
#endif	/* defined(_DISP_PERFORMANCE_) */

	frame++;
	if(frame > 1000000) {	/* フレームのリセット */
		frame = 0;
#if defined(_DISP_PERFORMANCE_)
		totalTime = 0;
#endif	/* defined(_DISP_PERFORMANCE_) */
		frame_2++;
	}

}

/*-------------------------------------------------------------------------------------*/
/*  Function Name   :   Finish                                                         */
/*  Inputs          :   None                                                           */
/*  Outputs         :   None                                                           */
/*  Returns         :   None                                                           */
/*  Globals Used    :   Device                                                         */
/*  Description     :   Free textures and close device.                                */
/*                      This routine is called from FRONTEND.C                         */
/*-------------------------------------------------------------------------------------*/
void Finish()
{
/*	FreeAllBMPTextures (); */
/*	sgl_delete_device(Device);	 */
  Init = FALSE;
	/*----------------------------------------------------------------------------------- */
	/* Free Texture Surface */
#if 0
	free(BuffTex);
#endif

	/*----------------------------------------------------------------------------------- */
	/* Free vertex buffer */
	status = kmDiscardVertexBuffer(&VertexBufferDesc);
	Check_Status(status, "kmDiscardVertexBuffer");

	/*----------------------------------------------------------------------------------- */
	/* End display */
	status = kmStopDisplayFrameBuffer();
	Check_Status(status, "kmStopDisplayFrameBuffer");
}

/*-------------------------------------------------------------------------------------*/
/*  Function Name   :  DrawAll                                                         */
/*  Inputs          :  None                                                            */
/*  Outputs         :  None                                                            */
/*  Returns         :  None                                                            */
/*  Globals Used    :  XAng, YAng, XAng1, YAng1, SGLContext                            */
/*  Description     :  Updates and draws all the meshes in the model.                  */
/*  Note            :  The definition of Mesh[i] struct is in logo.h                   */
/*-------------------------------------------------------------------------------------*/
void DrawAll()
{
register i;

    MoveLamp();
    GroundColour ();  /* Calculates new colors */

    for (i=0; i<NUM_MESHES; i++){
               
		if(UpVert==1 || i==LIGHT) UpdateVertex (i); /* Only updates vertices if the scene has changed */
        if (i==NUM_MESHES-1) UpVert=0;
      
		/* Updating texture parameters for each mesh of the model */
/*		SGLContext.nTextureName = Texture[Mesh[i].Material]; */
/*		SGLContext.u32Flags     = SGLTT_TEXTURE | SGLTT_GOURAUD | SGLTT_BILINEAR; */
		/* Set shading mode */
		VertexContext.RenderState	|= KM_SHADINGMODE;
		VertexContext.ShadingMode	= KM_TEXTUREGOURAUD;
		/* Set texture surface */
		VertexContext.pTextureSurfaceDesc	= &Texture[Mesh[i].Material];
		/* Process & Set Texture */
		status = kmProcessVertexRenderState(&VertexContext);
		Check_Status(status, "kmProcessVertexRenderState");

        /* Drawing triangles... */
/*		sgltri_triangles (&SGLContext, Mesh[i].NumFaces, (int(*)[3])Mesh[i].Faces, TempVert[i]); */
kmtri_triangles (	VertexBufferDesc,			/* KMVERTEXBUFFDESC	BufferDesc, */
					VertexContext,				/* KMVERTEXCONTEXT		VertexContext, */
					Mesh[i].NumFaces,			/* int  nNumFaces, */
					(int(*)[3])Mesh[i].Faces,	/* int  pFaces[][3], */
					TempVert[i],				/* PSGLVERTEX  pVertices */
					TRUE						/* int	bTexture */
					);

    } 

}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : SetupTextures                                                    */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : NumMaterials, Texture, MatInfo                                   */
/*  Description     : Loads BMP files getting the information from MatInfo struct      */
/*-------------------------------------------------------------------------------------*/
void SetupTextures (void)
{
register i;
	PKMDWORD			pTexture01;				/* Pointer to texture */
	KMTEXTURETYPE		nTextureType;			/* texture type definition */

#if 0
	BuffTex =  LoadTextureFile("stpvr2.pvr");	/* Load KAMUI-BMP texture */
#endif
	BuffTex = (unsigned long *)&stpvr2;

	for (i=0;i<NumMaterials; i++){
         if (*(MatInfo[i].MatFile) == 0) continue;
/*			BuffTex[i] = ConvertBMPtoSGL   (MatInfo[i].MatFile, FALSE); */
/*			Texture[i] = sgl_create_texture( sgl_map_16bit, sgl_map_128x128, */
/*										FALSE, FALSE, &BuffTex[i],  NULL); */
	/*----------------------------------------------------------------------------------- */
	/* Create texture surface */
	nTextureType = KM_TEXTURE_TWIDDLED | KM_TEXTURE_RGB565;	/* Set texture type */
	status = kmCreateTextureSurface(
		&Texture[i],			/* OUT	PKMSURFACEDESC	pSurfaceDesc */
		128,					/*	IN	KMINT32			nWidth  */
		128,					/*	IN	KMINT32			nHeight  */
		nTextureType			/*	IN	KMTEXTURETYPE	nTextureType */
	);
	Check_Status(status, "kmCreateTextureSurface(RGB)");
	/*----------------------------------------------------------------------------------- */
	/* Load and set texture */
#if 0
	pTexture01 =  LoadTextureFile(MatInfo[i].MatFile);	/* Load KAMUI texture */
#endif
	switch(i){
	default:
	case 0:	pTexture01 = (unsigned long *)&stground; break;
	case 1:	pTexture01 = (unsigned long *)&stpvr; break;
	case 2:	pTexture01 = (unsigned long *)&stlight; break;
	}
	status = kmLoadTexture(&Texture[i],			/* PKMSURFACEDESC pSurfaceDesc */
							pTexture01 + (16 / sizeof(KMDWORD)),			/* PKMDWORD pTexture */
							FALSE,				/* KMBOOLEAN bAutoMipMap */
							FALSE				/* KMBOOLEAN bDither */
							);
	Check_Status(status, "kmLoadTexture(ARGB)");
	free(pTexture01);

      }
}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : SetupContext                                                     */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : SGLContext                                                       */
/*  Description     : Sets default values for the render context.                      */
/*-------------------------------------------------------------------------------------*/
void SetupContext (void)
{
/*	SGLContext.bFogOn               = FALSE; */
/*	SGLContext.fFogR                = 0.3f; */
/*	SGLContext.fFogG                = 0.7f; */
/*	SGLContext.fFogB                = 0.7f; */
/*	SGLContext.u32FogDensity        = 5; */
/*	SGLContext.bCullBackfacing      = FALSE; */
/*	SGLContext.u32Flags             = SGLTT_TEXTURE | SGLTT_GOURAUD |SGLTT_BILINEAR; */
/*	SGLContext.nTextureName         = 0; */
/*	SGLContext.bDoClipping          = TRUE; */
/*	SGLContext.cBackgroundColour[0] = 0.0f; */
/*	SGLContext.cBackgroundColour[1] = 0.0f; */
/*	SGLContext.cBackgroundColour[2] = 0.0f; */
/*	SGLContext.eShadowLightVolMode  = ENABLE_SHADOWS; */
/*	SGLContext.bFlipU               = FALSE; */
/*	SGLContext.bFlipV               = FALSE; */
/*	SGLContext.bDoUVTimesInvW       = TRUE; */
/*	SGLContext.RenderRegions        = 0; */
/*	SGLContext.n32MipmapOffset      = 0; */
/*	SGLContext.u32GlobalTrans       = 255; */
/*	SGLContext.eFilterType          = sgl_tf_bilinear; */

	/*-------------------------------------------------------------------------------- */
	/* Initialize Vertex Context */
	/*-------------------------------------------------------------------------------- */
	memset( &VertexContext, 0, sizeof(VertexContext));	/* Crear Context */
	InitVertexContext(&VertexContext);					/* Initialize context */
}

/*-------------------------------------------------------------------------------------*/
/*  Function Name   : InitMeshes                                                       */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : Shad, Mesh, TempVert, TempNormals                                */
/*  Description     : Sets initials values for meshes managing                         */
/*-------------------------------------------------------------------------------------*/
void InitMeshes (void)
{
register i,j, k=0;
#if defined(_X86_)
#else
/* SET4 / SET5 */
int mptr = 0x0c400000;
#endif

    /* This function is in stained.h and creates an array of structures with 3D data */
    CreateMeshesArray ();

	/* Shad is a 255 values array with information for smooth shading */
    for (i=0; i<120; i++) Shad[k++] = (float)(120-i)/480.0;
    for (i=0; i<100; i++) Shad[k++] = (float) i/100.0;
    for (i=0; i<35;  i++) Shad[k++] = 1.0f;

#if defined(_X86_)
	/* Memory allocation for TempVert and TempNormals */ 
	for (i=0; i<NUM_MESHES; i++)
	{
		TempVert[i] = (SGLVERTEX *) malloc (Mesh[i].NumVertex*sizeof(SGLVERTEX));
	}
#else
	for (i=0; i<NUM_MESHES; i++)
	{
		TempVert[i] = (SGLVERTEX *)mptr; mptr += Mesh[i].NumVertex*sizeof(SGLVERTEX);
	}
#endif

	/* Calculate colour array */
    CalculateLight ();
   
	/* Setting UV values for all the meshes */
    for (j=0; j<NUM_MESHES;j++){
		 Shading (j);  /* setting vertices colour just once */
         for (i=0; i<Mesh[j].NumVertex; i++){
            (TempVert[j]+i)->fUOverW    =  (Mesh[j].TexMap==TRUE) ? *(Mesh[j].UV+i*2+0) : 0;
            (TempVert[j]+i)->fVOverW    =  (Mesh[j].TexMap==TRUE) ? *(Mesh[j].UV+i*2+1) : 0; 
       }
    }

}

/*-------------------------------------------------------------------------------------*/
/*  Function Name   : UpdateVertex                                                     */
/*  Inputs          : Num (the mesh in the model)                                      */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : XAng, YAng                                                       */
/*  Description     : Turns vertices around two axes.                                  */
/*-------------------------------------------------------------------------------------*/
void UpdateVertex (int Num)
{
sgl_vector Temp;
int i, j=0, k=0, l=0;
float x, y, z, CosX, SinX, CosY, SinY, CamZ, CamFocus = 500.0f;

CosX = cos(XAng); SinX = sin(XAng);
CosY = cos(YAng); SinY = sin(YAng);

  
    for (i=0; i<Mesh[Num].NumVertex; i++){
 
         x = *(Mesh[Num].Vertex+k++)-GroupCenter[0];
         y = *(Mesh[Num].Vertex+k++)-GroupCenter[1];
         z = *(Mesh[Num].Vertex+k++)-GroupCenter[2];

         /* Temp is the outcome vertex after the rotation */
         Temp[0]  = x * CosY - z * SinY;
         Temp[2]  = z * CosY + x * SinY;

         z        = Temp[2];
         Temp[1]  = y * CosX - z * SinX;
         Temp[2]  = z * CosX + y * SinX + TPos;

         if (Temp[2] <=0.1) Temp[2] = 0.001f;

         /* We store the SGL vertex in TempVert */    
         CamZ = 1.0/(Temp[2]);
    	 (TempVert[Num]+i)->fX    =  CamFocus * CamZ * Temp[0] + 320;
         (TempVert[Num]+i)->fY    = -CamFocus * CamZ * Temp[1] + 240;
	     (TempVert[Num]+i)->fInvW =  CamZ;

   }
}

/*-------------------------------------------------------------------------------------*/
/*  Function Name   : Shading                                                          */
/*  Inputs          : Num                                                              */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : Light1, MatInfo, Mesh, TempVert                                  */
/*  Description     : Shades a mesh.                                                   */
/*-------------------------------------------------------------------------------------*/
void Shading (int Num)
{
float Light1[3] = { 0, 0.5, 1};
float TCo, Dir;
register l=0, i=0, k=0;
float Sh, LTemp[3], x, y, z;
sgl_uint32 Col;

    Dir = sqrt (Light1[0]*Light1[0]+Light1[1]*Light1[1]+Light1[2]*Light1[2]);
    LTemp[0] = Light1[0]/Dir;
	LTemp[1] = Light1[1]/Dir; 
	LTemp[2] = Light1[2]/Dir;

    k = Mesh[Num].Material;

    for (i=0; i<Mesh[Num].NumVertex; i++){
      
        x = *(Mesh[Num].Normals+l++);
        y = *(Mesh[Num].Normals+l++);
        z = *(Mesh[Num].Normals+l++);

		/* Sh is a value from 0.0 to 1.0 depending on the angle between a normal */
		/* and the light direction.                                              */
        Sh = fabs( LTemp[0] * x + LTemp[1] * y + LTemp[2] * z + 1.0);

        TCo = Shad[(int)(127.0*Sh)];
        Col = 255*TCo;

        if (Num==GROUND) GroundSh[i] = TCo; /* Original values */
        if (Num!=WALL) Col =255;
       
       (TempVert[Num]+i)->u32Colour  = RGBColour (Col,Col,Col);
    }

}

/*-------------------------------------------------------------------------------------*/
/*  Function Name   : GroundColour                                                     */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : GroundSh, TempVert, PosX, PosY                                   */
/*  Description     : Sets colours for lighted ground (colouring vertices).            */
/*-------------------------------------------------------------------------------------*/
void GroundColour (void)
{
sgl_uint32 Col[3];
register i, j, cont = 0;

      
      for (j=0; j<31; j++)
	  { 
          for (i=0; i<31; i++)
		  {
			  /* Sets stained glass colours on the ground.   */
			  /* PosX and PosY have been calculated already. */
              if (i > PosX  && i<PosX+10 && j<15+PosY && j> PosY) 
			  {
                  GroundCo[i+j*31][0] = Logo[i-PosX][j-PosY][0];
                  GroundCo[i+j*31][1] = Logo[i-PosX][j-PosY][1];
                  GroundCo[i+j*31][2] = Logo[i-PosX][j-PosY][2];
              }
              else
			  {
				 /* Sets white light colour */
                 if (i>PosX+18) GroundCo[i+j*31][0] = GroundCo[i+j*31][1]= GroundCo[i+j*31][2] = 250.0;
				 /* Set shadow colour */
                 else           GroundCo[i+j*31][0] = GroundCo[i+j*31][1]= GroundCo[i+j*31][2] = 50.0;
              }
         }
     }

      /* Calculates average colour for each vertex */
      for (j=0; j<31; j++)
	  { 
          for (i=0; i<31; i++)
		  {
               GCo[cont][0] = GroundCo[cont][0];
               GCo[cont][1] = GroundCo[cont][1];
               GCo[cont][2] = GroundCo[cont][2];

              if (j>0 && i>0)
			  {
                 GCo[cont][0] =(GroundCo[cont][0]+GroundCo[cont-1][0]+GroundCo[cont+1][0]+GroundCo[cont-31][0]+GroundCo[cont+31][0])/5;
                 GCo[cont][1] =(GroundCo[cont][1]+GroundCo[cont-1][1]+GroundCo[cont+1][1]+GroundCo[cont-31][1]+GroundCo[cont+31][1])/5;
                 GCo[cont][2] =(GroundCo[cont][2]+GroundCo[cont-1][2]+GroundCo[cont+1][2]+GroundCo[cont-31][2]+GroundCo[cont+31][2])/5;
              }
              Col[0] = (int)(GCo[cont][0] * GroundSh[cont]); 
              Col[1] = (int)(GCo[cont][1] * GroundSh[cont]);
              Col[2] = (int)(GCo[cont][2] * GroundSh[cont]);
             
			  /* Sets the colour */
              (TempVert[GROUND]+cont)->u32Colour  = RGBColour (Col[0],Col[1],Col[2]);            
              cont++;
         }
     }
}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : CalculateLight                                                   */
/*  Inputs          : Nune                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : Logo                                                             */
/*  Description     : Creates a 15x10 array with PVR Logo colours.                     */
/*-------------------------------------------------------------------------------------*/
void CalculateLight (void)
{
unsigned long i, j, Pos;
	KMTEX_PIXEL			*pPixel;

  for (j=0; j<15; j++)
  {
    for (i=0; i<10; i++)
	{
		Pos = ((i*128)/10)*128 + ((j*128)/15);  
		/* BuffText[1] is the texture map of the stained glass */
/*		Logo[i][j][0]  = (BuffTex[1].pixels+Pos)->red; */
/*		Logo[i][j][1]  = (BuffTex[1].pixels+Pos)->green; */
/*		Logo[i][j][2]  = (BuffTex[1].pixels+Pos)->blue; */
		pPixel = (KMTEX_PIXEL *)&BuffTex[Pos];	/* Set pointer to the first pixel */
		Logo[i][j][0]  = pPixel->red;
		Logo[i][j][1]  = pPixel->green;
		Logo[i][j][2]  = pPixel->blue;
	}
  }

}
/*-------------------------------------------------------------------------------------*/
/*  Function Name   : MoveLamp                                                         */
/*  Inputs          : None                                                             */
/*  Outputs         : None                                                             */
/*  Returns         : None                                                             */
/*  Globals Used    : frame, Mesh, PosX, PosY                                          */
/*  Description     : Up-down movement of the lamp.                                    */
/*-------------------------------------------------------------------------------------*/
void MoveLamp (void)

{
static float TempL[20][3];
register i;
float LX = 0.0f , LY= 0.0f;

    /* Sets LTemp with the 3D vertices values just once. */
    if ( frame == 0)
	{
      for (i=0; i<Mesh[LIGHT].NumVertex; i++)
	  {
        TempL[i][0] = *(Mesh[LIGHT].Vertex+i*3+0);
        TempL[i][1] = *(Mesh[LIGHT].Vertex+i*3+1)+15;
        TempL[i][2] = *(Mesh[LIGHT].Vertex+i*3+2)+40;
	  }
	}

	/* Calculate light position on the ground and lamp position */
    PosX = (int)(13.0*sin(frame/20.0)+20.0);
    PosY = 7.5;

    LX = 7.5-PosY;
    LY = 15-PosX;

    /* Sets final values for 3D vertices of the lamp. */
    for (i=0; i<Mesh[LIGHT].NumVertex; i++)
	{
      *(Mesh[LIGHT].Vertex+i*3+0)  =  TempL[i][0]+LX;
      *(Mesh[LIGHT].Vertex+i*3+1)  =  TempL[i][1]+LY;
      *(Mesh[LIGHT].Vertex+i*3+2)  =  TempL[i][2];
    }
    
}
/*--------------------------- End of File --------------------------------*/
/****************************************************************************/
/**	main ********************************************************************/
/****************************************************************************/
int	main(void)
{
float	xd	= 0.002f;
float	yd	= 0.008f;

#ifdef __GNUC__
	shinobi_workaround();
#endif

	txt_ClearScreen();	/* Clear text screen */
	PRINTOUT(("** STAINED 2V Latency Trans Direct **\n"));
	SetupScene ();	/* Initialize */
	PRINTOUT(("\n"));

	do {
		NextFrame();	/* Rendering */
		XAng += (xd / SPEED);
		if(XAng > -6.3f) { xd = -xd; XAng = -6.3f; }
		if(XAng < -7.5f) { xd = -xd; XAng = -7.5f; }
		YAng += (yd / SPEED);
		UpVert = 1;
	} while(1);

	Finish();		/* End of render */
	PRINTOUT(("** END STAINED **\n"));
	return 0;
}

/*--------------------------- End of File --------------------------------*/
