#pragma On(Align_all_labels)
#pragma On(Align_labels)

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#include <concorde.h>
#include <tomahawk.h>
#include <airforce.h>

extern int *AL_area,AL_ed[4];   /* AL_areaはinitSolidで指定する */
/*   eye[0]  ox        sldp[0]  sx         *
 *   eye[1]  oy        sldp[1]  sy         *
 *   eye[2]  oz        sldp[2]  sz         *
 *   eye[3]  ohead     sldp[3]  shead      *
 *   eye[4]  opitch    sldp[4]  spitch     *
 *   eye[5]  obank     sldp[5]  sbank      */

int  AL_Model(PAGE *drw,int *sld,int *sldp,int *eye,PRJSCRN *pr)
{
	int i,j,pn;
	int *p[128],z[128],*plgn;
	int p1[3],p2[3],pnts[512*3+1],scrn[64*3+1],scut[64*3+1];
	int slds[6],eyes[6];
	int ofsx,ofsy,ofsz,cpz;

	if(AL_area==NULL)return 1;

	ofsx=sldp[0]-eye[0];  ofsy=sldp[1]-eye[1];  ofsz=sldp[2]-eye[2];
	cpz=(*pr).cpz;
	if(sld[4]!=1){ofsx/=100 ; ofsy/=100 ; ofsz/=100 ; cpz/=100;}

	if(sld[7]<3)return 2;
	if(sld[8+sld[7]*3]==0)return 2;

	/* 物体半径･可視最大距離判定略 */

	slds[0]=FxSinHq(sldp[3]);
	slds[1]=FxCosHq(sldp[3]);
	slds[2]=FxSinHq(sldp[4]);
	slds[3]=FxCosHq(sldp[4]);
	slds[4]=FxSinHq(sldp[5]);
	slds[5]=FxCosHq(sldp[5]);

	eyes[0]=FxSinHq(eye[3]);
	eyes[1]=FxCosHq(eye[3]);
	eyes[2]=FxSinHq(eye[4]);
	eyes[3]=FxCosHq(eye[4]);
	eyes[4]=FxSinHq(eye[5]);
	eyes[5]=FxCosHq(eye[5]);


	pn=0;
	z[0]=INT_MIN;
	for(plgn=sld +8 +sld[7]*3  ;  *plgn != 0  ;  plgn += 9 +plgn[8])
	{
		RotVtoGFast(1,p1,plgn+2,slds);
		p1[0]+=ofsx;  p1[1]+=ofsy;  p1[2]+=ofsz;

		RotVtoGFast(1,p2,plgn+5,slds);
		/* RotGtoVFast(1,p2,p2,eyes); */

		if(InnerSgn(p1,p2)>0)continue;

		RotGtoVFast(1,p1,p1,eyes);
		for(j=0   ; p1[2]<=z[j]; j++);
		for(i=pn+1; i>j        ; i--){p[i]=p[i-1]; z[i]=z[i-1];}
		p[j]=plgn ; z[j]=p1[2] ; pn++ ;
	}

	pnts[0]=sld[7];
	RotVtoGFast(sld[7],pnts+1,sld+8,slds);
	p1[0]=ofsx;  p1[1]=ofsy;  p1[2]=ofsz;
	Move3D(sld[7],pnts+1,pnts+1,p1);
	RotGtoVFast(sld[7],pnts+1,pnts+1,eyes);

	for(i=0 ; i<pn ; i++)
	{
		plgn=p[i];
		YGH_color(drw,plgn[1]);
		scrn[0]=plgn[8];
		for(j=0 ; j<plgn[8] ; j++)
		{
			scrn[1+j*3] = pnts[1 + plgn[9+j]*3 ];
			scrn[2+j*3] = pnts[2 + plgn[9+j]*3 ];
			scrn[3+j*3] = pnts[3 + plgn[9+j]*3 ];
		}
		ClipPolyg3D(scut,scrn,cpz);
		Projection(scut[0],scut+1,scut+1,&(*pr).prj);
		if(plgn[8]==3)
		{
			if(!YGH_triangleArea(drw,AL_area,AL_ed,scut))
			{
				YGH_areaPaint(drw,AL_area,AL_ed);
			}
		}
		else
		{
			if(!YGH_polygonArea(drw,AL_area,AL_ed,scut))
			{
				YGH_areaPaint(drw,AL_area,AL_ed);
			}
		}
	}
	return 0;
}
