/*****************************************************************************
* Filter to convert IRIT data files to SCN format.			     *
*									     *
* Made by:  Gershon Elber 						     *
* Modified by:  Antonio Costa				Ver 1.0, Apr 1992    *
*****************************************************************************/

#include <stdio.h>
#include <math.h>
#include <string.h>
#include "irit_sm.h"
#include "iritprsr.h"
#include "allocate.h"
#include "attribut.h"
#include "getarg.h"
#include "genmat.h"
#include "ffcnvrt.h"
#include "ip_cnvrt.h"

#define DIST_EPSILON	2e-4
#define SIZE_EPSILON	1e-5

#ifdef NO_CONCAT_STR
static char *VersionStr =
	"Irit2Scn		Version 4.0,	Antonio Costa,\n\
	 (C) Copyright 1989/90/91/92/93 Gershon Elber, Non commercial use only.";
#else
static char *VersionStr = "Irit2Scn	" VERSION ",	Antonio Costa,	"
	__DATE__ ",   " __TIME__ "\n" COPYRIGHT	", Non commercial use only.";
#endif /* NO_CONCAT_STR */

static char
    *CtrlStr =
"irit2scn l%- 4%- f%-FineNess!d o%-OutName!s g%- T%- z%- DFiles!*s";
static char
    *OutFileName = "irit2scn";

static int
    GlblTalkative = FALSE,
    GlblFineNess = 5,
    GlblDumpOnlyGeometry = FALSE,
    FourPerFlat = FALSE;

static MatrixType CrntViewMat;			/* This is the current view! */

static int TransColorTable[][4] = {
    { /* BLACK		*/ 0,    0,   0,   0 },
    { /* BLUE		*/ 1,    0,   0, 255 },
    { /* GREEN		*/ 2,    0, 255,   0 },
    { /* CYAN		*/ 3,    0, 255, 255 },
    { /* RED		*/ 4,  255,   0,   0 },
    { /* MAGENTA 	*/ 5,  255,   0, 255 },
    { /* BROWN		*/ 6,   50,   0,   0 },
    { /* LIGHTGRAY	*/ 7,  127, 127, 127 },
    { /* DARKGRAY	*/ 8,   63,  63,  63 },
    { /* LIGHTBLUE	*/ 9,    0,   0, 255 },
    { /* LIGHTGREEN	*/ 10,   0, 255,   0 },
    { /* LIGHTCYAN	*/ 11,   0, 255, 255 },
    { /* LIGHTRED	*/ 12, 255,   0,   0 },
    { /* LIGHTMAGENTA	*/ 13, 255,   0, 255 },
    { /* YELLOW		*/ 14, 255, 255,   0 },
    { /* WHITE		*/ 15, 255, 255, 255 },
    { /* BROWN		*/ 20,  50,   0,   0 },
    { /* DARKGRAY	*/ 56,  63,  63,  63 },
    { /* LIGHTBLUE	*/ 57,   0,   0, 255 },
    { /* LIGHTGREEN	*/ 58,   0, 255,   0 },
    { /* LIGHTCYAN	*/ 59,   0, 255, 255 },
    { /* LIGHTRED	*/ 60, 255,   0,   0 },
    { /* LIGHTMAGENTA	*/ 61, 255,   0, 255 },
    { /* YELLOW		*/ 62, 255, 255,   0 },
    { /* WHITE		*/ 63, 255, 255, 255 },
    {			   -1,   0,   0,   0 }
};

static void DumpDataForSCN(IPObjectStruct *PObjects);
static int DumpOneObject(FILE *FScn, FILE *FGeom, IPObjectStruct *PObject);
static int DumpOnePolygon(FILE *f, IPPolygonStruct *PPolygon,
							int IsPolygon);
static RealType *MapPoint(RealType *Pt);
static RealType *MapVector(RealType *Pt, RealType *Vec);
static void Irit2ScnExit(int ExitCode);

/*****************************************************************************
* Main routine - Read Parameter	line and do what you need...		     *
*****************************************************************************/
void main(int argc, char **argv)
{
    int Error,
	FineNessFlag = FALSE,
	LinearOnePolyFlag = FALSE,
	VerFlag = FALSE,
	OutFileFlag = FALSE,
	NumFiles = 0;
    char Line[LINE_LEN_LONG], *p,
	**FileNames = NULL;
    IPObjectStruct *PObjects;

    if ((Error = GAGetArgs (argc, argv, CtrlStr, &LinearOnePolyFlag,
			    &FourPerFlat, &FineNessFlag,
			    &GlblFineNess,  &OutFileFlag,
			    &OutFileName, &GlblDumpOnlyGeometry,
			    &GlblTalkative,
			    &VerFlag, &NumFiles, &FileNames)) != 0) {
	GAPrintErrMsg(Error);
	GAPrintHowTo(CtrlStr);
	Irit2ScnExit(1);
    }

    if (VerFlag) {
	fprintf(stderr, "\n%s\n\n", VersionStr);
	GAPrintHowTo(CtrlStr);
	Irit2ScnExit(0);
    }

    if (LinearOnePolyFlag) {
	fprintf(stderr, "Linear patch side will have a single polygon.\n");
	CagdSetLinear2Poly(CAGD_ONE_POLY_PER_COLIN);
    }
    else
        CagdSetLinear2Poly(CAGD_REG_POLY_PER_LIN);

    fprintf(stderr, "%s triangles per flat will be created.\n",
	    FourPerFlat ? "Four" : "Two");

    if (!NumFiles) {
	fprintf(stderr, "No data file names were given, exit.\n");
	GAPrintHowTo(CtrlStr);
	Irit2ScnExit(1);
    }

    if (!OutFileFlag) {		/* Pick the first input name as output name. */
	strcpy(Line, FileNames[0]);
	if ((p = strrchr(Line, '.')) != NULL)	    /* Remove old file type. */
	    *p = 0;
	OutFileName = IritStrdup(Line);
    }

    /* Get the data files: */
    if ((PObjects = IritPrsrGetDataFiles(FileNames, NumFiles, TRUE, FALSE)) ==
									NULL)
	Irit2ScnExit(1);

    if (IritPrsrWasPrspMat)
	MatMultTwo4by4(CrntViewMat, IritPrsrViewMat, IritPrsrPrspMat);
    else
	GEN_COPY(CrntViewMat, IritPrsrViewMat, sizeof(MatrixType));

    DumpDataForSCN(PObjects);

    Irit2ScnExit(0);
}

/*****************************************************************************
* Routine to convert all surfaces/curves into polylines as follows:	     *
* Curves are converted to single polyline with SamplesPerCurve samples.	     *
* Surface are converted into GlblNumOfIsolines curves in each axes, each     *
* handled as Curves above. The curves and surfaces are then deleted.	     *
*****************************************************************************/
IPObjectStruct *IritPrsrProcessFreeForm(IPObjectStruct *CrvObjs,
					IPObjectStruct *SrfObjs)
{
    int LocalFourPerFlat;
    float RelativeFineNess;
    CagdCrvStruct *Crvs;
    CagdSrfStruct *Srf, *Srfs;
    IPObjectStruct *PObj, *PObjNext;
    IPPolygonStruct *PPolygon, *PPolygonTemp;

    if (CrvObjs == NULL && SrfObjs == NULL)
	return NULL;

    /* Make sure requested format is something reasonable. */
    if (GlblFineNess < 2) {
	GlblFineNess = 2;
	fprintf(stderr, "FineNess is less than 2, 2 picked instead.\n");
    }

    if (CrvObjs) {
	/* Curves are not rendered at this time and they are ignored. */
	for (PObj = CrvObjs; PObj != NULL;) {
	    if (GlblTalkative)
		fprintf(stderr, "Processing curve object \"%s\"\n",
			PObj -> Name);

	    Crvs = PObj -> U.Crvs;
	    CagdCrvFreeList(Crvs);
	    PObjNext = PObj -> Pnext;
	    PObj -> U.Crvs = NULL;
	    IPFreeObject(PObj);
	    PObj = PObjNext;
	}
	CrvObjs = NULL;
    }

    if (SrfObjs) {
	for (PObj = SrfObjs; PObj != NULL; PObj = PObj -> Pnext) {
	    if (GlblTalkative)
		fprintf(stderr, "Processing surface object \"%s\"\n",
			PObj -> Name);

	    Srfs = PObj -> U.Srfs;
	    PObj -> U.Pl = NULL;
	    PObj -> ObjType = IP_OBJ_POLY;
	    IP_SET_POLYGON_OBJ(PObj);

	    LocalFourPerFlat = FourPerFlat;

	    if (AttrGetObjectStrAttrib(PObj, "twoperflat"))
		LocalFourPerFlat = FALSE;
	    if (AttrGetObjectStrAttrib(PObj, "fourperflat"))
		LocalFourPerFlat = TRUE;

	    if ((RelativeFineNess = AttrGetObjectRealAttrib(PObj,
				    "resolution")) > IP_ATTR_BAD_REAL)
		RelativeFineNess = 1.0;

	    for (Srf = Srfs; Srf != NULL; Srf = Srf -> Pnext) {
		PPolygon = PPolygonTemp =
		    IritSurface2Polygons(Srf, LocalFourPerFlat,
			      (int) (RelativeFineNess * GlblFineNess), FALSE);
		while (PPolygonTemp -> Pnext)
		    PPolygonTemp = PPolygonTemp -> Pnext;
		PPolygonTemp -> Pnext = PObj -> U.Pl;
		PObj -> U.Pl = PPolygon;
	    }
	    CagdSrfFreeList(Srfs);

	}
    }

    return SrfObjs;
}

/*****************************************************************************
* Dumps the data for SCN into stdout.					     *
*****************************************************************************/
static void DumpDataForSCN(IPObjectStruct *PObjects)
{
    static char *Header1[] = {
 "%",
 "% This file was automatically created from IRIT solid modeller data",
 "% using Irit2Scn - IRIT to SCN filter.",
 "%",
 "% (c) Copyright 1992 Antonio Costa, Non commercial use only.",
 "%",
 "",
 NULL
    };
    static char *Header2[] = {
	"",
	"eye  0 0 10",
	"look 0 0 0",
	"up   0 1 0",
	"fov 6",
	"",
	"light point 10 30 10",
	"",
	NULL
    };
    int i,
	TotalPolys = 0;
    char Line[128];
    IPObjectStruct *PObj,
	*PObjHead = NULL;
    FILE *FGeom, *FScn;

    sprintf(Line, "%s.scn", OutFileName);
    if (!GlblDumpOnlyGeometry) {
	if ((FScn = fopen(Line, "w")) == NULL) {
	    fprintf(stderr, "Failed to open \"%s\".\n", Line);
	    Irit2ScnExit(2);
	}
    }
    else
	FScn = NULL;

    sprintf(Line, "%s.geom", OutFileName);
    if ((FGeom = fopen(Line, "w")) == NULL) {
#	if defined(OS2GCC) || defined(__WINNT__)
	    sprintf(Line, "%s.geo", OutFileName);
	    if ((FGeom = fopen(Line, "w")) == NULL)
#	endif /* OS2GCC || __WINNT__ */
	    {
		fprintf(stderr, "Failed to open \"%s\".\n", Line);
		Irit2ScnExit(2);
	    }
    }

    if (FScn != NULL)
	for (i = 0; Header1[i] != NULL; i++)
	    fprintf(FScn, "%s\n", Header1[i]);
    for (i = 0; Header1[i] != NULL; i++)
	fprintf(FGeom, "%s\n", Header1[i]);

    /* Reverse object list since it was loaded in reverse by iritprsr module.*/
    while (PObjects != NULL) {
	PObj = PObjects;
	PObjects = PObjects -> Pnext;
	PObj -> Pnext = PObjHead;
	PObjHead = PObj;
    }
    PObjects = PObjHead;

    while (PObjects) {
	TotalPolys += DumpOneObject(FScn, FGeom, PObjects);
	PObjects = PObjects -> Pnext;
    }

    if (FScn != NULL) {
	fprintf(FScn, "#include \"%s\"\n", Line);
	for (i = 0; Header2[i] != NULL; i++)
	    fprintf(FScn, "%s\n", Header2[i]);
	fclose(FScn);
    }

    fclose(FGeom);

    fprintf(stderr, "\nTotal number of polygons - %d\n", TotalPolys);
}

/*****************************************************************************
* Routine to dump one object PObject.					     *
*****************************************************************************/
static int DumpOneObject(FILE *FScn, FILE *FGeom, IPObjectStruct *PObject)
{
    static int
	ObjectSeqNum = 1;
    int i, j, Color, RGBIColor[3],
        PolyCount = 0,
	HasColor = FALSE,
	HasSrfProp = FALSE;
    char *p, Name[LINE_LEN], SrfPropString[LINE_LEN_LONG];
    RealType RGBColor[3];
    IPPolygonStruct *PList;

    if (!IP_IS_POLY_OBJ(PObject))
	return 0;

    PList = PObject -> U.Pl;

    if (strlen(PObject -> Name) == 0)
	sprintf(Name, "Object_%d", ObjectSeqNum);
    else
	strcpy(Name, PObject -> Name);

    fprintf(FGeom, "begin %% %s\n", Name);

    if (AttrGetObjectRGBColor(PObject,
			      &RGBIColor[0], &RGBIColor[1], &RGBIColor[2])) {
	HasColor = TRUE;
	for (i = 0; i < 3; i++)
	    RGBColor[i] = RGBIColor[i];
    }
    else if ((Color = AttrGetObjectColor(PObject)) != IP_ATTR_NO_COLOR) {
	for (i = 0; TransColorTable[i][0] >= 0; i++) {
	    if (TransColorTable[i][0] == Color) {
		HasColor = TRUE;
		for (j = 0; j < 3; j++)
		    RGBColor[j] = TransColorTable[i][j+1];
		break;
	    }
	}
    }

    if ((p = AttrGetObjectStrAttrib(PObject, "SCNsurface")) != NULL) {
	HasSrfProp = TRUE;
	strcpy(SrfPropString, p);
    }

    if (HasColor || HasSrfProp) {
	if (FScn != NULL) {
	    fprintf(FScn, "#define Surface_%s \\\n", Name);
	    if (HasColor && !HasSrfProp) {
		for (i = 0; i < 3; i++)
		    RGBColor[i] /= 255.0;

		fprintf(FScn, "\tsurface matte %g %g %g\n",
			RGBColor[0],
			RGBColor[1],
			RGBColor[2]);
	    }
	    else if (!HasColor && HasSrfProp) {
		fprintf(FScn, "\t%s\n", SrfPropString);
	    }
	    else {
		for (i = 0; i < 3; i++)
		    RGBColor[i] /= 255.0;

		fprintf(FScn, "\t%s\n", SrfPropString);
		fprintf(FScn, "\t%% color %g %g %g\n",
			RGBColor[0],
			RGBColor[1],
			RGBColor[2]);
	    }
	}

	fprintf(FGeom, "Surface_%s\n", Name);
    }

    if ((p = AttrGetObjectStrAttrib(PObject, "SCNrefraction")) != NULL) {
	if (FScn != NULL)
	    fprintf(FScn, "#define Refraction_%s %s\n", Name, p);
    }

    if ((p = AttrGetObjectStrAttrib(PObject, "SCNtexture")) != NULL) {
	if (FScn != NULL) {
	    fprintf(FScn, "#define Texture_%s %s\n", Name, p);
	    fprintf(FGeom, "Texture_%s\n", Name);
	}
    }

    while (PList) {
	PolyCount += DumpOnePolygon(FGeom, PList, IP_IS_POLYGON_OBJ(PObject));
	PList =	PList -> Pnext;
    }
    fprintf(FGeom, "end\n");

    if (GlblTalkative)
	fprintf(stderr, "Converting \"%s\" - %d triangles.\n",
		Name, PolyCount);

    fprintf(FGeom, "\n");
    if (FScn != NULL)
	fprintf(FScn, "\n");

    ObjectSeqNum++;

    return PolyCount;
}

/*****************************************************************************
* Routine to dump one polygon, using global Matrix transform CrntViewMat.    *
*****************************************************************************/
static int DumpOnePolygon(FILE *FGeom, IPPolygonStruct *PPolygon,
							int IsPolygon)
{
    int i,
	TriCount = 0;
    RealType *MappedNormal[3], *MappedPoint[3], Normal[3], Vec1[3], Vec2[3];
    IPVertexStruct *VFirst, *V1, *V2,
	*VList = PPolygon -> PVertex;

    if (VList == NULL)
	return 0;

    if (!IritPrsrIsConvexPolygon(PPolygon)) {
	static int
	    Printed = FALSE;

	if (!Printed) {
	    fprintf(stderr,
		    "\nWARNING: Non convex polygon(s) might be in data (see CONVEX in IRIT),\n\t\t\t\toutput can be wrong as the result!\n");
	    Printed = TRUE;
	}
    }

    if (IsPolygon) {
	VFirst = VList;
	V1 = VFirst -> Pnext;
	V2 = V1 -> Pnext;

	while (V2 != NULL) {
	    MappedPoint[0] = MapPoint(VFirst -> Coord);
	    MappedPoint[1] = MapPoint(V1 -> Coord);
	    MappedPoint[2] = MapPoint(V2 -> Coord);

	    /* Test for two type of degeneracies. Make sure that no two  */
	    /* points in the triangle are the same and that they are     */
	    /* not colinear.					     */
	    if (!PT_APX_EQ(MappedPoint[0], MappedPoint[1]) &&
		!PT_APX_EQ(MappedPoint[0], MappedPoint[2]) &&
		!PT_APX_EQ(MappedPoint[1], MappedPoint[2])) {

		PT_SUB(Vec1, MappedPoint[0], MappedPoint[1]);
		PT_SUB(Vec2, MappedPoint[1], MappedPoint[2]);
		PT_NORMALIZE(Vec1);
		PT_NORMALIZE(Vec2);
		CROSS_PROD(Normal, Vec1, Vec2);

		if (PT_LENGTH(Normal) > SIZE_EPSILON) {
		    PT_NORMALIZE(Normal);

		    MappedNormal[0] =
		        MapVector(VFirst -> Coord, VFirst -> Normal);
		    MappedNormal[1] =
		        MapVector(V1 -> Coord, V1 -> Normal);
		    MappedNormal[2] =
		        MapVector(V2 -> Coord, V2 -> Normal);

		    if (DOT_PROD(Normal, MappedNormal[0]) < -SIZE_EPSILON ||
			DOT_PROD(Normal, MappedNormal[1]) < -SIZE_EPSILON ||
			DOT_PROD(Normal, MappedNormal[2]) < -SIZE_EPSILON) {
			SWAP(RealType *, MappedPoint[1], MappedPoint[2]);
			SWAP(RealType *, MappedNormal[1], MappedNormal[2]);
			PT_SCALE(Normal, -1.0);
		    }

		    /* Make sure all normals are set properly: */
		    if (DOT_PROD(MappedNormal[0],
				 MappedNormal[0]) < SIZE_EPSILON)
		        PT_COPY(MappedNormal[0], Normal);
		    if (DOT_PROD(MappedNormal[1],
				 MappedNormal[1]) < SIZE_EPSILON)
		        PT_COPY(MappedNormal[1], Normal);
		    if (DOT_PROD(MappedNormal[2],
				 MappedNormal[2]) < SIZE_EPSILON)
		        PT_COPY(MappedNormal[2], Normal);

		    TriCount++;

		    for (i = 0; i < 3; i++)
		      fprintf(FGeom,
			"%s %10.7lf %10.7lf %10.7lf  %9.6lf %9.6lf %9.6lf\n",
			i == 0 ? "triangle normal\n\t" : "\t",
				MappedPoint[i][0],
				MappedPoint[i][1],
				MappedPoint[i][2],
				MappedNormal[i][0],
				MappedNormal[i][1],
			        MappedNormal[i][2]);
		}
	    }

	    V1 = V2;
	    V2 = V2 -> Pnext;
	}
    }

    return TriCount;
}

/*****************************************************************************
* Maps the given E3 point using the CrntViewMat.			     *
*****************************************************************************/
static RealType *MapPoint(RealType *Pt)
{
    static int Count = 0;
    static RealType MappedPts[3][3];
    RealType *MappedPt = MappedPts[Count++];

    if (Count >= 3)
	Count = 0;

    MatMultVecby4by4(MappedPt, Pt, CrntViewMat);

    return MappedPt;
}

/*****************************************************************************
* Maps the given E3 vector using the CrntViewMat.			     *
* This routine will return a zero vector if normal is not computable.	     *
*****************************************************************************/
static RealType *MapVector(RealType *Pt, RealType *Vec)
{
    static int
	Count = 0,
	WasWarning = 0;
    static RealType MappedVecs[3][3];
    RealType MappedPt[3], Pt2[3], MappedPt2[3],
	*MappedVec = MappedVecs[Count++];

    if (Count >= 3)
	Count = 0;

    if (DOT_PROD(Vec, Vec) < SIZE_EPSILON) {
	MappedVec[0] = MappedVec[1] = MappedVec[2] = 0.0;
	if (!WasWarning) {
	    WasWarning = 1;
	    fprintf(stderr,
	    "Non computable normals detected. Approximated from geometry.\n");
	}
    }
    else {
    	MatMultVecby4by4(MappedPt, Pt, CrntViewMat);

    	PT_ADD(Pt2, Pt, Vec);
    	MatMultVecby4by4(MappedPt2, Pt2, CrntViewMat);

    	PT_SUB(MappedVec, MappedPt2, MappedPt);
    	PT_NORMALIZE(MappedVec);
    }

    return MappedVec;
}

/*****************************************************************************
* Irit2Scn exit routine.						     *
*****************************************************************************/
static void Irit2ScnExit(int ExitCode)
{
    exit(ExitCode);
}
