/*
--------------------------------------------------------------------------------

MD3Fix

(c) 2003 Randy Reddig

To compile on Unix: gcc -o md3fix md3fix.c

Quake III Arena MD3 model fixer. Fixes bad shader names, corrupted
vertex normals, and misc other stuff.

Note: this code contains no byte-swapping code, and therefore can only
be run on a little endian architecture.

Portions of this code were borrowed from my PicoModel library, which is
used in GtkRadiant and Q3Map2, licensed under the BSD license.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation.

This file is provided AS IS with no warranties of any kind.  The author
shall have no liability with respect to the infringement of copyrights,
trade secrets or any patents by this file or any part thereof.  In no
event will the author be liable for any lost revenue or profits or
other special, indirect and consequential damages.

--------------------------------------------------------------------------------

PicoModel Library 

Copyright (c) 2002, Randy Reddig & seaw0lf
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

Neither the names of the copyright holders nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

--------------------------------------------------------------------------------
*/



/*
dependencies
*/

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>



/*
macros
*/

#define MD3FIX_VERSION		"0.2"
#define DIR_SEP				'/'



/*
types
*/

/* md3 model format */
#define MD3_MAGIC			"IDP3"
#define MD3_VERSION			15

/* md3 vertex scale */
#define MD3_SCALE		  (1.0f / 64.0f)

/* md3 model frame information */
typedef struct md3Frame_s
{
	float		bounds[ 2 ][ 3 ];
	float		localOrigin[ 3 ];
	float		radius;
	char		creator[ 16 ];
}
md3Frame_t;

/* md3 model tag information */
typedef struct md3Tag_s
{
	char		name[ 64 ];
	float		origin[ 3 ];
	float		axis[ 3 ][ 3 ];
}
md3Tag_t;

/* md3 surface md3 (one object mesh) */
typedef struct md3Surface_s
{
	char		magic[ 4 ];
	char		name[ 64 ];		/* polyset name */
	int			flags;
	int			numFrames;		/* all model surfaces should have the same */
	int			numShaders;		/* all model surfaces should have the same */
	int			numVerts;
	int			numTriangles;
	int			ofsTriangles;
	int			ofsShaders;		/* offset from start of md3Surface_t */
	int			ofsSt;			/* texture coords are common for all frames */
	int			ofsVertexes;	/* numVerts * numFrames */
	int			ofsEnd;			/* next surface follows */
}
md3Surface_t;

typedef struct md3Shader_s
{
	char		name[ 64 ];
	int			shaderIndex;	/* for ingame use */
}
md3Shader_t;

typedef struct md3Triangle_s
{
	int			indexes[ 3 ];
}
md3Triangle_t;

typedef struct md3TexCoord_s
{
	float		st[ 2 ];
}
md3TexCoord_t;

typedef struct md3Vertex_s
{
	short		xyz[ 3 ];
	short		normal;
}
md3Vertex_t;


/* md3 model file md3 structure */
typedef struct md3_s
{
	char		magic[ 4 ];		/* MD3_MAGIC */
	int			version;
	char		name[ 64 ];		/* model name */
	int			flags;
	int			numFrames;
	int			numTags;
	int			numSurfaces;
	int			numSkins;		/* number of skins for the mesh */
	int			ofsFrames;		/* offset for first frame */
	int			ofsTags;		/* numFrames * numTags */
	int			ofsSurfaces;	/* first surface, others follow */
	int			ofsEnd;			/* end of file */
}
md3_t;



/*
code
*/

/*
Usage()
prints usage string and exits
*/

void Usage( int argc, char **argv )
{
	fprintf( stderr, "Fixes a corrupted Quake III Arena MD3 model, including bad shader names and malformed vertex normals.\n" );
	fprintf( stderr, "Usage: %s <in> [<out>]\n", argv[ 0 ] );
	fprintf( stderr, "If no output filename is specified, it will overwrite the original model.\n\n", argv[ 0 ] );
	
	exit( EINVAL );
}



/*
LoadMD3()
loads an md3 model
*/

md3_t *LoadMD3( char *path )
{
	md3_t	*md3;
	FILE	*file;
	int		size;
	
	
	/* open file */
	file = fopen( path, "rb" );
	if( file == NULL )
	{
		fprintf( stderr, "Unable to open %s. Abort.\n", path );
		exit( -1 );
	}
	
	/* get size */
	fseek( file, 0, SEEK_END);
	size = ftell( file );
	fseek( file, 0, SEEK_SET );
	if( size < sizeof( *md3 ) )
	{
		fclose( file );
		fprintf( stderr, "Corrupt/invalid model: %s. Abort.\n", path );
		exit( -1 );
	}
	
	/* allocate buffer */
	md3 = malloc( size );
	if( md3 == NULL )
	{
		fclose( file );
		fprintf( stderr, "Unable to allocate enough memory to load %s. Abort.\n", path );
		exit( -1 );
	}
	
	/* read it in */
	fread( md3, size, 1, file );
	
	/* close */
	fclose( file );
	
	/* check md3 magic */
	if( *((int*) md3->magic) != *((int*) MD3_MAGIC) || md3->version != MD3_VERSION )
	{
		fprintf( stderr, "Corrupt/invalid model: %s. Abort.\n", path );
		exit( -1 );
	}
	
	/* return ok */
	return md3;
}



/*
SaveMD3()
saves an md3 model
fixme: add some error checking to make sure the model got written
*/

void SaveMD3( md3_t *md3, char *path )
{
	FILE	*file;
	
	
	/* open file */
	file = fopen( path, "wb" );
	if( file == NULL )
	{
		fprintf( stderr, "Unable to open %s. Abort.\n", path );
		exit( -1 );
	}
	
	/* write buffer */
	fwrite( md3, md3->ofsEnd, 1, file );
	
	/* close */
	fclose( file );
}



/*
FixMD3()
where the rubber hits the roadkill
*/

void FixMD3( md3_t *md3 )
{
	int				i, j, k, v, lat, lng;
	char			*c;
	md3Frame_t		*frame;
	md3Surface_t	*surface;
	md3Shader_t		*shader;
	md3Vertex_t		*vertexes;
	md3Triangle_t	*triangles;
	float			ilen, xyz[ 3 ][ 3 ], ba[ 3 ], ca[ 3 ], normal[ 3 ];
	float			normals[ 1024 ][ 3 ];
	
	
	/* fix model name */
	printf( "Fixing model name:     %s\n", md3->name );
	for( c = md3->name; *c != '\0'; c++ )
	{
		if( *c == '\\' )
			*c = '/';
	}
	printf( "Done:                  %s\n", md3->name );
	
	/* clear frame bounding boxes */
	for( i = 0; i < md3->numFrames; i++ )
	{
		frame = (md3Frame_t*) ((char*) md3 + md3->ofsFrames + i * sizeof( md3Frame_t ) );
		for( j = 0; j < 3; j++ )
		{
			frame->bounds[ 0 ][ j ] = 999999;	/* mins */
			frame->bounds[ 1 ][ j ] = -999999;	/* maxs */
		}
	}
	
	/* fix surfaces */
	surface = (md3Surface_t*) ((char*) md3 + md3->ofsSurfaces);
	for( i = 0; i < md3->numSurfaces; i++ )
	{
		/* note it */
		printf( "Fixing surface:        %s\n", surface->name );
		
		/* fix shader */
		shader = (md3Shader_t*) ((char*) surface + surface->ofsShaders);
		printf( "Fixing shader:         %s\n", shader->name );
		for( c = shader->name; *c != '\0'; c++ )
		{
			if( *c == '\\' )
				*c = '/';
		}
		if( *(c - 4) == '.' )
			*(c - 4) = '\0';
		printf( "Done:                  %s\n", shader->name );
		
		/* fix normals */
		printf( "Fixing frames/normals: %d frames %d tris %d verts\n", surface->numFrames, surface->numTriangles, surface->numVerts );
		if( surface->numVerts > 1024 )
		{
			fprintf( stderr, "Surface has more than 1024 vertexes. Abort.\n" );
			exit( -1 );
		}
		
		/* setup */
		triangles = (md3Triangle_t*) ((char*) surface + surface->ofsTriangles);
		
		/* walk frames */
		for( j = 0; j < surface->numFrames; j++ )
		{
			/* setup */
			frame = (md3Frame_t*) ((char*) md3 + md3->ofsFrames + j * sizeof( md3Frame_t ) );
			vertexes = (md3Vertex_t*) ((char*) surface + surface->ofsVertexes + j * surface->numVerts);
			memset( normals, 0, sizeof( normals ) );
			
			/* walk triangles */
			for( k = 0; k < surface->numTriangles; k++ )
			{
				/* extract vertex xyz */
				for( v = 0; v < 3; v++ )
				{
					xyz[ v ][ 0 ] = MD3_SCALE * vertexes[ triangles[ k ].indexes[ v ] ].xyz[ 0 ];
					xyz[ v ][ 1 ] = MD3_SCALE * vertexes[ triangles[ k ].indexes[ v ] ].xyz[ 1 ];
					xyz[ v ][ 2 ] = MD3_SCALE * vertexes[ triangles[ k ].indexes[ v ] ].xyz[ 2 ];
				}
				
				/* make a plane */
				for( v = 0; v < 3; v++ )
				{
					ba[ v ] = xyz[ 1 ][ v ] - xyz[ 0 ][ v ];
					ca[ v ] = xyz[ 2 ][ v ] - xyz[ 0 ][ v ];
				}
				normal[ 0 ] = ca[ 1 ] * ba[ 2 ] - ca[ 2 ] * ba[ 1 ];
				normal[ 1 ] = ca[ 2 ] * ba[ 0 ] - ca[ 0 ] * ba[ 2 ];
				normal[ 2 ] = ca[ 0 ] * ba[ 1 ] - ca[ 1 ] * ba[ 0 ];
				ilen = (float) sqrt( normal[ 0 ] * normal[ 0 ] + normal[ 1 ] * normal[ 1 ] + normal[ 2 ] * normal[ 2 ] );
				if( ilen == 0.0f )
					continue;
				ilen = 1.0f / ilen;
				normal[ 0 ] *= ilen;
				normal[ 1 ] *= ilen;
				normal[ 2 ] *= ilen;
				normal[ 3 ] = xyz[ 0 ][ 0 ] * normal[ 0 ] + xyz[ 0 ][ 1 ] * normal[ 1 ] + xyz[ 0 ][ 2 ] * normal[ 2 ];
				
				/* add normal to each of the vertex normals */
				for( v = 0; v < 3; v++ )
				{
					normals[ triangles[ k ].indexes[ v ] ][ 0 ] += normal[ 0 ];
					normals[ triangles[ k ].indexes[ v ] ][ 1 ] += normal[ 1 ];
					normals[ triangles[ k ].indexes[ v ] ][ 2 ] += normal[ 02 ];
				}
			}
			
			/* walk vertexes */
			for( k = 0; k < surface->numVerts; k++ )
			{
				/* expand frame bounding box */
				for( v = 0; v < 3; v++ )
				{
					if( vertexes[ k ].xyz[ v ] < frame->bounds[ 0 ][ v ] )	/* mins */
						frame->bounds[ 0 ][ v ] = vertexes[ k ].xyz[ v ];
					if( vertexes[ k ].xyz[ v ] > frame->bounds[ 1 ][ v ] )	/* maxs */
						frame->bounds[ 1 ][ v ] = vertexes[ k ].xyz[ v ];
				}
				
				/* normalize */
				ilen = (float) sqrt( normals[ k ][ 0 ] * normals[ k ][ 0 ] + normals[ k ][ 1 ] * normals[ k ][ 1 ] + normals[ k ][ 2 ] * normals[ k ][ 2 ] );
					if( ilen == 0.0f )
					continue;
				ilen = 1.0f / ilen;
				normals[ k ][ 0 ] *= ilen;
				normals[ k ][ 1 ] *= ilen;
				normals[ k ][ 2 ] *= ilen;
				
				/* convert to lat/long */
				if( normals[ k ][ 0 ] == 0.0f && normals[ k ][ 1 ] == 0.0f )
				{
					lat = 0;
					if( normals[ k ][ 2 ] > 0.0f )
						lng = 0;
					else
						lng = 128;
				}
				else
				{
					lat = (int) ((double) atan2( normals[ k ][ 1 ], normals[ k ][ 0 ] ) * (180.0 / 3.14159265358979323846) * (255.0 / 360.0));
					lng = (int) ((double) acos( normals[ k ][ 2 ] ) * (180.0 / 3.14159265358979323846) * (255.0 / 360.0));
				}
				
				/* store new normal */
				vertexes[ k ].normal = ((lat & 0xFF) << 8) | (lng & 0xFF);
			}
		}
		
		/* get next surface */
		surface = (md3Surface_t*) ((char*) surface + surface->ofsEnd);
	}
	
	/* clear frame bounding boxes */
	printf( "Fixing frame bounds:   %d frames\n", md3->numFrames );
	for( i = 0; i < md3->numFrames; i++ )
	{
		/* set origin (center of bounding box) */
		frame = (md3Frame_t*) ((char*) md3 + md3->ofsFrames + i * sizeof( md3Frame_t ) );
		frame->localOrigin[ 0 ] = 0.5f * (frame->bounds[ 0 ][ 0 ] + frame->bounds[ 1 ][ 0 ]);
		frame->localOrigin[ 1 ] = 0.5f * (frame->bounds[ 0 ][ 1 ] + frame->bounds[ 1 ][ 1 ]);
		frame->localOrigin[ 2 ] = 0.5f * (frame->bounds[ 0 ][ 2 ] + frame->bounds[ 1 ][ 2 ]);
		
		/* set bounding sphere */
		normal[ 0 ] = frame->bounds[ 1 ][ 0 ] - frame->bounds[ 0 ][ 0 ];
		normal[ 1 ] = frame->bounds[ 1 ][ 1 ] - frame->bounds[ 0 ][ 1 ];
		normal[ 2 ] = frame->bounds[ 1 ][ 2 ] - frame->bounds[ 0 ][ 2 ];
		frame->radius = (float) sqrt( normal[ 0 ] * normal[ 0 ] + normal[ 1 ] * normal[ 1 ] + normal[ 2 ] * normal[ 2 ] );
	}
	
	/* end */
	printf( "Done.\n" );
}



/*
main()
der...
*/

int main( int argc, char **argv )
{
	int		i, len;
	char	src[ 512 ], dest[ 512 ];
	md3_t	*md3;
	
	
	/* note it */
	fprintf( stderr, "MD3Fix %s - Copyright 2003 Randy Reddig\n", MD3FIX_VERSION );

	/* get commandline arguments */
	src[ 0 ] = '\0';
	dest[ 0 ] = '\0';
	if( argc < 2 )
		Usage( argc, argv );
	for( i = 1; i < argc; i++ )
	{
		/* source pname */
		if( src[ 0 ] == '\0' )
		{
			strcpy( src, argv[ i ] );
		}
		
		/* dest pname */
		else if( dest[ 0 ] == '\0' )
		{
			strcpy( dest, argv[ i ] );
		}
		
		/* else busted */
		else
			Usage( argc, argv );
	}
	
	/* create dest pname if necessary */
	len = strlen( dest );
	if( len == 0 )
	{
		strcpy( dest, src );
		len = strlen( dest );
		for( i = len - 1; i >= 0; i-- )
		{
			if( dest[ i ] == '/' || dest[ i ] == '\\' )
				i = -1;
			else if( dest[ i ] == '.' )
			{
				len = i + 1;
				i = -1;
			}
		}
		
		/* append suffix */
		strcpy( &dest[ len ], "md3" );
	}
	
	/* load source md3 */
	md3 = LoadMD3( src );
	
	/* fix it */
	FixMD3( md3 );
	
	/* write destination md3 */
	SaveMD3( md3, dest );
	
	/* free it */
	free( md3 );
	
	/* exit */
	exit( 0 );
}



