diff options
| author | Steven Fuller <relnev@icculus.org> | 2001-07-01 00:55:22 +0000 |
|---|---|---|
| committer | Patryk Obara <dreamer.tan@gmail.com> | 2019-08-20 02:09:04 +0200 |
| commit | 2186d5f3f95cd74a070a490d899291648d58667a (patch) | |
| tree | 55241a1afa3e1a22e0b6593a8dead0b703800f44 /3dc/win95 | |
| parent | 218ca90543758a20ac326e444ca0643174ca7384 (diff) | |
Initial revision
Diffstat (limited to '3dc/win95')
138 files changed, 0 insertions, 74272 deletions
diff --git a/3dc/win95/ANIMCHNK.CPP b/3dc/win95/ANIMCHNK.CPP deleted file mode 100644 index 3f5d87a..0000000 --- a/3dc/win95/ANIMCHNK.CPP +++ /dev/null @@ -1,270 +0,0 @@ -#include "animchnk.hpp" - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(animchnk) - -RIF_IMPLEMENT_DYNCREATE("TEXTANIM",Animation_Chunk) - -Animation_Chunk::Animation_Chunk(Chunk_With_Children* parent) -: Chunk(parent, "TEXTANIM") -{ - NumPolys=0; - AnimList=0; -} -Animation_Chunk::Animation_Chunk(Chunk_With_Children* parent,const char* data,size_t /*datasize*/) -: Chunk(parent, "TEXTANIM") -{ - NumPolys=*((int*)data); - data+=4; - if(NumPolys) - { - AnimList=(TEXANIM**)malloc(NumPolys*sizeof(TEXANIM*)); - for(int i=0;i<NumPolys;i++) - { - AnimList[i]=new TEXANIM; - TEXANIM* ta=AnimList[i]; - ta->poly=*((int*)data); - data+=4; - ta->ID=*((int*)data); - data+=4; - ta->NumSeq=*((int*)data); - data+=4; - ta->NumVerts=*((int*)data); - data+=4; - ta->AnimFlags=*((int*)data); - data+=4; - ta->Identifier=*((int*)data); - data+=4; - ta->CurSeq=0; - ta->Seq=new FrameList*[ta->NumSeq]; - for(int j=0;j<ta->NumSeq;j++) - { - ta->Seq[j]=new FrameList(ta); - FrameList* fl=ta->Seq[j]; - fl->Speed=*((int*)data); - data+=4; - fl->Flags=*((int*)data); - data+=4; - - fl->NumFrames=*((int*)data); - data+=4; - fl->spare1=*((int*)data); - data+=4; - fl->spare2=*((int*)data); - data+=4; - fl->CurFrame=0; - - fl->Textures=new int[fl->NumFrames]; - fl->UVCoords=new int[(2*ta->NumVerts)*fl->NumFrames]; - for(int k=0;k<fl->NumFrames;k++) - { - fl->Textures[k]=*((int*)data); - data+=4; - } - for(k=0;k<(2*ta->NumVerts)*fl->NumFrames;k++) - { - fl->UVCoords[k]=*((int*)data); - data+=4; - } - } - - } - } - else - AnimList=0; - -} - -Animation_Chunk::~Animation_Chunk() -{ - for(int i=0;i<NumPolys;i++) - { - delete AnimList[i]; - } - free(AnimList); -} - - -size_t Animation_Chunk::size_chunk() -{ - chunk_size=12+4; - for(int i=0;i<NumPolys;i++) - { - chunk_size+=24; - TEXANIM* ta=AnimList[i]; - for(int j=0;j<ta->NumSeq;j++) - { - chunk_size+=20; - chunk_size+=4*(1+2*ta->NumVerts)*ta->Seq[j]->NumFrames; - } - } - return chunk_size; -} - -BOOL Animation_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -void Animation_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=NumPolys; - data_start+=4; - for(int i=0;i<NumPolys;i++) - { - TEXANIM* ta=AnimList[i]; - *(int*)data_start=ta->poly; - data_start+=4; - *(int*)data_start=ta->ID; - data_start+=4; - *(int*)data_start=ta->NumSeq; - data_start+=4; - *(int*)data_start=ta->NumVerts; - data_start+=4; - *(int*)data_start=ta->AnimFlags; - data_start+=4; - *(int*)data_start=ta->Identifier; - data_start+=4; - - for(int j=0;j<ta->NumSeq;j++) - { - FrameList* fl=ta->Seq[j]; - *(int*)data_start=fl->Speed; - data_start+=4; - *(int*)data_start=fl->Flags; - data_start+=4; - *(int*)data_start=fl->NumFrames; - data_start+=4; - *(int*)data_start=fl->spare1; - data_start+=4; - *(int*)data_start=fl->spare2; - data_start+=4; - for(int k=0;k<fl->NumFrames;k++) - { - *(int*)data_start=fl->Textures[k]; - data_start+=4; - } - for(k=0;k<(2*ta->NumVerts)*fl->NumFrames;k++) - { - *(int*)data_start=fl->UVCoords[k]; - data_start+=4; - } - } - - } -} - -FrameList::FrameList(TEXANIM* p) -{ - Speed=65536; - Flags=0; - NumFrames=0; - CurFrame=-1; - parent=p; - Textures=0; - UVCoords=0; - spare1=spare2=0; -} -FrameList::FrameList(TEXANIM* p,FrameList* fl,int* conv) -{ - Speed=fl->Speed; - Flags=fl->Flags; - NumFrames=fl->NumFrames; - parent=p; - Textures=new int[NumFrames]; - UVCoords=new int[NumFrames*2*p->NumVerts]; - spare1=fl->spare1; - spare2=fl->spare2; - if(conv) - { - for(int i=0;i<NumFrames;i++) - { - Textures[i]=conv[fl->Textures[i]]; - } - } - else - { - for(int i=0;i<NumFrames;i++) - { - Textures[i]=fl->Textures[i]; - } - } - for(int i=0;i<NumFrames*2*p->NumVerts;i++) - { - UVCoords[i]=fl->UVCoords[i]; - } - CurFrame=0; -} -FrameList::~FrameList() -{ - delete [] Textures; - delete UVCoords; -} - -TEXANIM::TEXANIM() -{ - shape=0; - NumSeq=0; - CurSeq=-1; - Seq=0; - NumVerts=3; - AnimFlags=Identifier=0; -} -TEXANIM::TEXANIM(TEXANIM* ta) -{ - shape=0; - NumSeq=0; - CurSeq=-1; - Seq=0; - NumVerts=3; - AnimFlags=Identifier=0; - CopyAnimData(ta,0); -} - -TEXANIM::~TEXANIM() -{ - for(int i=0;i<NumSeq;i++) - { - delete Seq[i]; - } - delete [] Seq; -} - -void TEXANIM::CopyAnimData(TEXANIM* ta,int*conv) -{ - shape=ta->shape; - poly=ta->poly; - ID=ta->ID; - NumSeq=ta->NumSeq; - CurSeq=0; - Seq=new FrameList*[NumSeq]; - NumVerts=ta->NumVerts; - AnimFlags=ta->AnimFlags; - Identifier=ta->Identifier; - for(int i=0;i<NumSeq;i++) - { - Seq[i]=new FrameList(this,ta->Seq[i],conv); - } - -} - diff --git a/3dc/win95/ANIMCHNK.HPP b/3dc/win95/ANIMCHNK.HPP deleted file mode 100644 index 9c30cbc..0000000 --- a/3dc/win95/ANIMCHNK.HPP +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef _animchnk_hpp -#define _animchnk_hpp -#include "chunk.hpp" -#include "Chnktype.hpp" - -struct TEXANIM; - - -class Animation_Chunk : public Chunk -{ -public : - Animation_Chunk(Chunk_With_Children* parent,const char*,size_t); - Animation_Chunk(Chunk_With_Children* parent); - ~Animation_Chunk(); - - virtual BOOL output_chunk (HANDLE &hand); - - virtual size_t size_chunk(); - - virtual void fill_data_block(char* data_start); - - int NumPolys; //with animation in this shape - TEXANIM** AnimList; - -}; - -#define txa_flag_nointerptofirst 0x80000000 - -struct FrameList -{ - ~FrameList(); - FrameList(TEXANIM*); - #if InterfaceEngine - FrameList(TEXANIM* p,FrameList* templ); - #endif - FrameList(TEXANIM* p,FrameList* fl,int* conv); - int Speed; - int Flags; - - int NumFrames; - int CurFrame; - TEXANIM* parent; - - int* Textures; - int* UVCoords; - int spare1,spare2; - - - #if InterfaceEngine - void CopyToSID(int shape,int poly); - void CopyFromSID(int shape,int poly); - void AddFrame(); - void RemoveFrame(); - #endif -}; - -#define AnimFlag_NotPlaying 0x00000001 -struct TEXANIM -{ - TEXANIM(TEXANIM*); - TEXANIM(); - ~TEXANIM(); - - #if InterfaceEngine - TEXANIM(int s,int p,int id); - //construct a TEXANIM using templ as a template. - TEXANIM(int s,int p,TEXANIM* templ); - #endif - int shape; - int poly; - int NumVerts; - int ID; - int NumSeq;//number of sequences - int CurSeq; - int AnimFlags; - int Identifier; - FrameList** Seq; - - #if InterfaceEngine - void ChangeFrame(int newseq,int newframe); - void AddSeq(); - void RemoveSeq(); - void CopySeq(int seq_num); - #endif - void CopyAnimData(TEXANIM* ta,int* conv); -}; - -#endif diff --git a/3dc/win95/BMPNAMES.CPP b/3dc/win95/BMPNAMES.CPP deleted file mode 100644 index 1918033..0000000 --- a/3dc/win95/BMPNAMES.CPP +++ /dev/null @@ -1,964 +0,0 @@ -#include <string.h> -#include "bmpnames.hpp" -#include "mishchnk.hpp" - -#if engine -#define UseLocalAssert No -#include "ourasert.h" -#define assert(x) GLOBALASSERT(x) -#else -#if cencon -#include "ccassert.h" -#else -#include <assert.h> -#endif -#endif - -#ifdef cencon -#define new my_new -#endif - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(bmpnames) - - -BMP_Name::BMP_Name (const char * fname, int const gbnc_version) -: flags((BMPN_Flags)DEFAULT_BMPN_FLAGS), index(0), version_num (gbnc_version << BMPNAME_PARENT_VER_SHIFT), priority (DEFAULT_BMPN_PRIORITY), transparency_colour_union(0), enum_id(0) -#if cencon -, md5val(0) -#endif -{ - filename = new char [strlen(fname)+1]; - strcpy (filename, fname); -} - -BMP_Name::BMP_Name (const char * fname) -: flags((BMPN_Flags)DEFAULT_BMPN_FLAGS), index(0), version_num (0), priority (DEFAULT_BMPN_PRIORITY), transparency_colour_union(0), enum_id(0) -#if cencon -, md5val(0) -#endif -{ - filename = new char [strlen(fname)+1]; - strcpy (filename, fname); -} - -BMP_Name::~BMP_Name () -{ - if (filename) - delete [] filename; -} - -BMP_Name::BMP_Name (const BMP_Name & bn) -{ - if (&bn == this) return; - - filename = new char [strlen(bn.filename)+1]; - strcpy (filename, bn.filename); - flags = bn.flags; - index = bn.index; - version_num = bn.version_num; - enum_id = bn.enum_id; - priority = bn.priority; - transparency_colour_union = bn.transparency_colour_union; - #if cencon - md5val = bn.md5val; - #endif -} - -void BMP_Name::Validate(void) -{ - if (flags & ChunkBMPFlag_PriorityAndTransparencyAreValid) return; - - priority = DEFAULT_BMPN_PRIORITY; - flags = (BMPN_Flags)(flags | DEFAULT_BMPN_FLAGS); -} - -const BMP_Name & BMP_Name::operator=(const BMP_Name & bn) -{ - if (&bn == this) return(*this); - - if (filename) - delete [] filename; - - filename = new char [strlen(bn.filename)+1]; - strcpy (filename, bn.filename); - flags = bn.flags; - index = bn.index; - version_num = bn.version_num; - enum_id = bn.enum_id; - priority = bn.priority; - transparency_colour_union = bn.transparency_colour_union; - #if cencon - md5val = bn.md5val; - #endif - - return(*this); - - -} - - - -BOOL operator==(const BMP_Name &o1, const BMP_Name &o2) -{ - if (o1.filename && o2.filename) return _stricmp(o1.filename,o2.filename) ? FALSE : TRUE; - else return &o1 == &o2; -} - -BOOL operator!=(const BMP_Name &o1, const BMP_Name &o2) -{ - if (o1.filename && o2.filename) return _stricmp(o1.filename,o2.filename) ? TRUE : FALSE; - else return &o1 != &o2; -} - - -/////////////////////////////////////// - -// Class Chunk_With_BMPs functions - - - -Chunk_With_BMPs::Chunk_With_BMPs (Chunk_With_Children * parent, const char * const ident, const char * bdata, size_t /*bsize*/) -: Chunk (parent, ident), max_index (0) -{ - int temp = *(int *)bdata; - - int num = temp & 0xffff; - - int ver_num = temp >> 16 & 0xffff; // the remains of a previous mistake - not really necessary anymore - - bdata += 4; - - for (int i=0; i<num; i++) - { - int f,i,d1,d2,d3; - - f = *((int *)bdata); - bdata += 4; - i = *((int *)bdata); - bdata += 4; - d1 = *((int *)bdata); - bdata += 4; - d2 = *((int *)bdata); - bdata += 4; - d3 = *((int *)bdata); - bdata += 4; - - BMP_Name bn (bdata); - bdata += (4-strlen(bn.filename)%4) + strlen(bn.filename); - - bn.flags = (BMPN_Flags)f; - bn.index = i; - bn.version_num = d1 & BMPNAME_VERSION_NUM_MASK; - bn.enum_id = (int)((unsigned int)d1 >> BMPNAME_ENUMID_SHIFT); - bn.priority = d2; - bn.transparency_colour_union = d3; - - max_index = max (bn.index, max_index); - - bmps.add_entry (bn); - } - - if (ver_num) - { - set_version_num(ver_num); - } -} - - -size_t Chunk_With_BMPs::size_chunk () -{ - int sz = 12 + 4; - - for (LIF<BMP_Name> bl(&bmps); !bl.done(); bl.next()) - { - sz += (4-strlen(bl().filename)%4) + strlen(bl().filename) + 20; - } - - chunk_size = sz; - - return (chunk_size); - -} - -void Chunk_With_BMPs::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = bmps.size(); - - data_start += 4; - - for (LIF<BMP_Name> bl(&bmps); !bl.done(); bl.next()) - { - *((int *) data_start) = bl().flags; - data_start += 4; - *((int *) data_start) = bl().index; - data_start += 4; - *((int *) data_start) = bl().version_num & BMPNAME_VERSION_NUM_MASK | bl().enum_id << BMPNAME_ENUMID_SHIFT; - data_start += 4; - *((int *) data_start) = bl().priority; - data_start += 4; - *((int *) data_start) = bl().transparency_colour_union; - data_start += 4; - - strcpy (data_start, bl().filename); - data_start += (4-strlen(bl().filename)%4) + strlen(bl().filename); - } - -} - -int Chunk_With_BMPs::get_version_num(void) -{ - if (parent) - { - List<Chunk *> verlist; - parent->lookup_child("BMNAMVER",verlist); - while (verlist.size()>1) - { - Chunk * v1 = verlist.first_entry(); - Chunk * v2 = verlist[1]; - if (((BMP_Names_Version_Chunk *)v1)->version_num > ((BMP_Names_Version_Chunk *)v2)->version_num) - { - delete verlist.last_entry(); - verlist.delete_last_entry(); - } - else - { - delete v1; - verlist.delete_first_entry(); - } - } - if (verlist.size()) - { - int rv = ((BMP_Names_Version_Chunk *)verlist.first_entry())->version_num; - return rv; - } - } - return 0; -} - -void Chunk_With_BMPs::set_version_num(int v) -{ - if (parent) - { - List<Chunk *> verlist; - parent->lookup_child("BMNAMVER",verlist); - while (verlist.size()>1) - { - Chunk * v1 = verlist.first_entry(); - Chunk * v2 = verlist[1]; - if (((BMP_Names_Version_Chunk *)v1)->version_num > ((BMP_Names_Version_Chunk *)v2)->version_num) - { - delete verlist.last_entry(); - verlist.delete_last_entry(); - } - else - { - delete v1; - verlist.delete_first_entry(); - } - } - if (verlist.size()) - { - ((BMP_Names_Version_Chunk *)verlist.first_entry())->version_num = v; - return; - } - - (new BMP_Names_Version_Chunk(parent))->version_num = v; - } -} - -void Chunk_With_BMPs::inc_version_num(void) -{ - if (parent) - { - List<Chunk *> verlist; - parent->lookup_child("BMNAMVER",verlist); - while (verlist.size()>1) - { - Chunk * v1 = verlist.first_entry(); - Chunk * v2 = verlist[1]; - if (((BMP_Names_Version_Chunk *)v1)->version_num > ((BMP_Names_Version_Chunk *)v2)->version_num) - { - delete verlist.last_entry(); - verlist.delete_last_entry(); - } - else - { - delete v1; - verlist.delete_first_entry(); - } - } - if (verlist.size()) - { - ((BMP_Names_Version_Chunk *)verlist.first_entry())->version_num ++; - return; - } - - (new BMP_Names_Version_Chunk(parent))->version_num ++; - } -} - -BMP_Names_ExtraData * Chunk_With_BMPs::GetExtendedData(void) -{ - if (parent) - { - List<Chunk *> verlist; - parent->lookup_child("BMNAMEXT",verlist); - if (verlist.size()) - { - return (BMP_Names_ExtraData_Chunk *) verlist.first_entry(); - } - return new BMP_Names_ExtraData_Chunk(parent); - } - return 0; -} - -int const * Chunk_With_BMPs::GetMD5Val(BMP_Name const & rcbmp) -{ - Bitmap_MD5_Chunk * md5c = GetMD5Chunk(rcbmp.filename); - if (md5c) - if (rcbmp.version_num == md5c->version_num) - return md5c->md5_val; - return 0; -} - -void Chunk_With_BMPs::RemoveMD5Val(char const * bname) -{ - Bitmap_MD5_Chunk * md5c = GetMD5Chunk(bname); - if (md5c) - delete md5c; -} - -void Chunk_With_BMPs::SetMD5Val(BMP_Name const & rcbmp, int const * md5id) -{ - Bitmap_MD5_Chunk * md5c = GetMD5Chunk(rcbmp.filename); - if (md5c) - { - if (rcbmp.version_num == md5c->version_num) - { - memcpy(md5c->md5_val,md5id,16); - return; - } - else - delete md5c; - } - CreateMD5Chunk(rcbmp,md5id); -} - - -///////////////////////////////////// -// Global_BMP_Name_Chunk -///////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("BMPNAMES",Global_BMP_Name_Chunk) - -Bitmap_MD5_Chunk * Global_BMP_Name_Chunk::GetMD5Chunk(char const * bname) -{ - List<Chunk *> chlst; - parent->lookup_child("BMPMD5ID",chlst); - - for (LIF<Chunk *> i_chlst(&chlst); !i_chlst.done(); i_chlst.next()) - { - Bitmap_MD5_Chunk * md5c = (Bitmap_MD5_Chunk *)i_chlst(); - - if (!strcmp(md5c->bmpname,bname)) - if (!(md5c->rifname ? *md5c->rifname : 1) && !(md5c->shapename ? *md5c->shapename : 1)) - return md5c; - } - - return 0; -} - -void Global_BMP_Name_Chunk::CreateMD5Chunk(BMP_Name const & rcbmp, int const * md5id) -{ - new Bitmap_MD5_Chunk(parent,md5id,rcbmp); -} - -///////////////////////////////////// -// Bitmap_List_Store_Chunk -///////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("BMPLSTST",Bitmap_List_Store_Chunk) - -Bitmap_MD5_Chunk * Bitmap_List_Store_Chunk::GetMD5Chunk(char const * bname) -{ - List<Chunk *> chlst; - parent->lookup_child("BMPMD5ID",chlst); - - List<Chunk *> rnlst; - parent->lookup_child("RIFFNAME",rnlst); - char const * rname = 0; - if (rnlst.size()) - { - rname = ((RIF_Name_Chunk *)rnlst.first_entry())->rif_name; - } - - for (LIF<Chunk *> i_chlst(&chlst); !i_chlst.done(); i_chlst.next()) - { - Bitmap_MD5_Chunk * md5c = (Bitmap_MD5_Chunk *)i_chlst(); - - if (!strcmp(md5c->bmpname,bname)) - if (!(md5c->rifname ? rname ? strcmp(rname,md5c->rifname) : *md5c->rifname : rname ? *rname : 0) && - !(md5c->shapename ? *md5c->shapename : 1)) - return md5c; - } - - return 0; -} - -void Bitmap_List_Store_Chunk::CreateMD5Chunk(BMP_Name const & rcbmp, int const * md5id) -{ - List<Chunk *> rnlst; - parent->lookup_child("RIFFNAME",rnlst); - char const * rname = 0; - if (rnlst.size()) - { - rname = ((RIF_Name_Chunk *)rnlst.first_entry())->rif_name; - } - new Bitmap_MD5_Chunk(parent,md5id,rcbmp,rname); -} - - - -/////////////////////////////////////// - -// Class BMP_Names_Version_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("BMNAMVER",BMP_Names_Version_Chunk) - - -size_t BMP_Names_Version_Chunk::size_chunk () -{ - chunk_size = 12+4; - - return (chunk_size); - -} - -void BMP_Names_Version_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = version_num; - -} - - - -/////////////////////////////////////// - -// Class BMP_Names_ExtraData_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("BMNAMEXT",BMP_Names_ExtraData_Chunk) - - -size_t BMP_Names_ExtraData_Chunk::size_chunk () -{ - chunk_size = 12+52; - - return (chunk_size); - -} - -void BMP_Names_ExtraData_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - - *((int *) data_start) = chunk_size; - data_start += 4; - - *((int *) data_start) = flags; - data_start += 4; - - for (int i=0; i<12; ++i, data_start+=4) - { - *(int *)data_start = reserved[i]; - } - -} - -/////////////////////////////////////// - -// Class External_Shape_BMPs_Store_Chunk functions -RIF_IMPLEMENT_DYNCREATE("SHBMPNAM",External_Shape_BMPs_Store_Chunk) - -External_Shape_BMPs_Store_Chunk::External_Shape_BMPs_Store_Chunk (Chunk_With_Children * parent, char const * rifn, char const * shapen) -: Chunk_With_BMPs (parent, "SHBMPNAM"), rifname(0), shapename(0), version_num(0) -{ - for (int i=0; i<12; ++i) - reserved[i] = 0; - - flags = GBF_NONE; - - if (rifn) - { - rifname = new char [strlen(rifn)+1]; - strcpy(rifname,rifn); - } - if (shapen) - { - shapename = new char [strlen(shapen)+1]; - strcpy(shapename,shapen); - } -} - -External_Shape_BMPs_Store_Chunk::~External_Shape_BMPs_Store_Chunk() -{ - if (rifname) delete[] rifname; - if (shapename) delete[] shapename; -} - -void External_Shape_BMPs_Store_Chunk::fill_data_block(char * data_start) -{ - Chunk_With_BMPs::fill_data_block(data_start); - data_start += Chunk_With_BMPs::size_chunk(); - size_chunk(); // resize it just in case - - strcpy(data_start,rifname ? rifname : ""); - unsigned int const l1 = rifname ? strlen(rifname)+1 : 1; - - strcpy(data_start+l1,shapename ? shapename : ""); - unsigned int const l2 = shapename ? strlen(shapename)+1 : 1; - - data_start += l1+l2 +3&~3; - - *(int *)data_start = flags; - data_start+=4; - - *(int *)data_start = version_num; - data_start+=4; - - for (int i=0; i<12; ++i, data_start+=4) - *(int *)data_start = reserved[i]; -} - -External_Shape_BMPs_Store_Chunk::External_Shape_BMPs_Store_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize) -: Chunk_With_BMPs (parent, "SHBMPNAM", sdata, ssize) -{ - sdata += Chunk_With_BMPs::size_chunk() -12; - unsigned int const l1 = strlen(sdata)+1; - rifname = new char [l1]; - strcpy(rifname,sdata); - unsigned int const l2 = strlen(sdata+l1)+1; - shapename = new char [l2]; - strcpy(shapename,sdata+l1); - - sdata += l1+l2 +3&~3; - - flags = (GlobalBMPFlags)(*(int *)sdata & GBF_MASK); - sdata+=4; - - version_num = *(int *)sdata; - sdata+=4; - - for (int i=0; i<12; ++i, sdata+=4) - reserved[i] = *(int *)sdata; -} - - -Bitmap_MD5_Chunk * External_Shape_BMPs_Store_Chunk::GetMD5Chunk(char const * bname) -{ - List<Chunk *> chlst; - parent->lookup_child("BMPMD5ID",chlst); - - for (LIF<Chunk *> i_chlst(&chlst); !i_chlst.done(); i_chlst.next()) - { - Bitmap_MD5_Chunk * md5c = (Bitmap_MD5_Chunk *)i_chlst(); - - if (!strcmp(md5c->bmpname,bname)) - if (!(md5c->rifname ? rifname ? strcmp(rifname,md5c->rifname) : *md5c->rifname : rifname ? *rifname : 0) && - !(md5c->shapename ? shapename ? strcmp(shapename,md5c->shapename) : *md5c->shapename : shapename ? *shapename : 0) && - (flags & GBF_SPRITE && md5c->flags & BMD5F_SPRITE || !(flags & GBF_SPRITE) && !(md5c->flags & BMD5F_SPRITE))) - - return md5c; - } - - return 0; -} - -void External_Shape_BMPs_Store_Chunk::CreateMD5Chunk(BMP_Name const & rcbmp, int const * md5id) -{ - Bitmap_MD5_Chunk * md5c = new Bitmap_MD5_Chunk(parent,md5id,rcbmp,rifname,shapename); - md5c->flags = flags & GBF_SPRITE ? BMD5F_SPRITE : BMD5F_0; -} - - -/*************************/ -/* matching images stuff */ -/*************************/ - -// class ImageDescriptor -// --------------------- -ImageDescriptor::ImageDescriptor() -: filename(0) -, rifname(0) -, fixrifname(0) -{ -} - -ImageDescriptor::ImageDescriptor(ImageDescriptor const & id2) -: flags(id2.flags) -, filename(0) -, rifname(0) -, fixrifname(0) -{ - spares[0] = id2.spares[0]; - spares[1] = id2.spares[1]; - spares[2] = id2.spares[2]; - - if (id2.filename) - { - filename = new char [strlen(id2.filename)+1]; - strcpy(filename,id2.filename); - } - if (id2.rifname) - { - rifname = new char [strlen(id2.rifname)+1]; - strcpy(rifname,id2.rifname); - } - if (id2.fixrifname) - { - fixrifname = new char [strlen(id2.fixrifname)+1]; - strcpy(fixrifname,id2.fixrifname); - } -} - -ImageDescriptor::ImageDescriptor(IDscFlags idscf, char const * fname, char const * rname, char const * xname) -: flags(idscf) -, filename(0) -, rifname(0) -, fixrifname(0) -{ - spares[0] = 0; - spares[1] = 0; - spares[2] = 0; - - if (fname) - { - filename = new char [strlen(fname)+1]; - strcpy(filename,fname); - } - if (rname) - { - rifname = new char [strlen(rname)+1]; - strcpy(rifname,rname); - } - if (xname) - { - fixrifname = new char [strlen(xname)+1]; - strcpy(fixrifname,xname); - } -} - -ImageDescriptor::~ImageDescriptor() -{ - if (filename) delete[] filename; - if (rifname) delete[] rifname; - if (fixrifname) delete[] fixrifname; -} - -ImageDescriptor & ImageDescriptor::operator = (ImageDescriptor const & id2) -{ - if (&id2 != this) - { - flags = id2.flags; - spares[0] = id2.spares[0]; - spares[1] = id2.spares[1]; - spares[2] = id2.spares[2]; - - if (filename) - { - delete[] filename; - filename = 0; - } - if (rifname) - { - delete[] rifname; - rifname = 0; - } - if (fixrifname) - { - delete[] fixrifname; - fixrifname = 0; - } - - if (id2.filename) - { - filename = new char [strlen(id2.filename)+1]; - strcpy(filename,id2.filename); - } - if (id2.rifname) - { - rifname = new char [strlen(id2.rifname)+1]; - strcpy(rifname,id2.rifname); - } - if (id2.fixrifname) - { - fixrifname = new char [strlen(id2.fixrifname)+1]; - strcpy(fixrifname,id2.fixrifname); - } - } - return *this; -} - - -// I/O -ImageDescriptor::ImageDescriptor(char const * datablock) -: flags((IDscFlags)(*(int const *)datablock & IDSCF_MASK)) -{ - spares[0] = *(int const *)(datablock+4); - spares[1] = *(int const *)(datablock+8); - spares[2] = *(int const *)(datablock+12); - datablock += 16; - - size_t len = strlen(datablock)+1; - filename = new char[len]; - strcpy(filename,datablock); - datablock += len; - - len = strlen(datablock)+1; - rifname = new char[len]; - strcpy(rifname,datablock); - datablock += len; - - len = strlen(datablock)+1; - fixrifname = new char[len]; - strcpy(fixrifname,datablock); -} - -size_t ImageDescriptor::Size() const -{ - return 16 - + (filename ? strlen(filename) : 0) - + (rifname ? strlen(rifname) : 0) - + (fixrifname ? strlen(fixrifname) : 0) - + 3 - +3&~3; -} - -void ImageDescriptor::WriteData(char * datablock) const -{ - *(int *)datablock = flags; - *(int *)(datablock+4) = spares[0]; - *(int *)(datablock+8) = spares[1]; - *(int *)(datablock+12) = spares[2]; - datablock+=16; - - strcpy(datablock,filename ? filename : ""); - datablock += strlen(datablock)+1; - - strcpy(datablock,rifname ? rifname : ""); - datablock += strlen(datablock)+1; - - strcpy(datablock,fixrifname ? fixrifname : ""); -} - -// operators -BOOL ImageDescriptor::operator == (ImageDescriptor const & id2) const -{ - if (flags!=id2.flags) return FALSE; - if (_stricmp(filename ? filename : "",id2.filename ? id2.filename : "")) return FALSE; - if (_stricmp(rifname ? rifname : "",id2.rifname ? id2.rifname : "")) return FALSE; - if (_stricmp(fixrifname ? fixrifname : "",id2.fixrifname ? id2.fixrifname : "")) return FALSE; - return TRUE; -} - -// class MatchingImages -// -------------------- - -// constructos; -MatchingImages::MatchingImages(ImageDescriptor const & _load, ImageDescriptor const & _insteadof) -: load(_load) -, insteadof(_insteadof) -{ - spares[0] = 0; - spares[1] = 0; - spares[2] = 0; -} - -// I/O -MatchingImages::MatchingImages(char const * datablock) -: load(datablock+12) -, insteadof(datablock+12+load.Size()) -{ - spares[0] = *(int const *)datablock; - spares[1] = *(int const *)(datablock+4); - spares[2] = *(int const *)(datablock+8); -} - -size_t MatchingImages::Size() const -{ - return 12 + load.Size() + insteadof.Size(); -} - -void MatchingImages::WriteData(char * datablock) const -{ - *(int *)datablock = spares[0]; - *(int *)(datablock+4) = spares[1]; - *(int *)(datablock+8) = spares[2]; - - load.WriteData(datablock+12); - insteadof.WriteData(datablock+12+load.Size()); -} - - -// class Matching_Images_Chunk : public Chunk -// ------------------------------------------ -RIF_IMPLEMENT_DYNCREATE("MATCHIMG",Matching_Images_Chunk) - -// I/O -Matching_Images_Chunk::Matching_Images_Chunk(Chunk_With_Children * parent, char const * datablock, size_t size) -: Chunk(parent,"MATCHIMG") -, flags ((MICFlags)(*(int *)(datablock+8) & MICF_MASK)) -{ - char const * datastart = datablock; - - spares[0] = *(int *)datablock; - spares[1] = *(int *)(datablock+4); - - int listsize = *(int *)(datablock+12); - datablock += 16; - - for (;listsize; --listsize) - { - mlist.add_entry_end(datablock); - datablock += mlist.last_entry().Size(); - } - - assert(datastart + size == datablock); -} - -size_t Matching_Images_Chunk::size_chunk() -{ - chunk_size = 28; // 2dw spares, 1dw flags, 1dw list size, 12b header - - for (LIF<MatchingImages> mlit(&mlist); !mlit.done(); mlit.next()) - { - chunk_size += mlit().Size(); - } - - return chunk_size; -} - -void Matching_Images_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *(int *) data_start = chunk_size; - data_start += 4; - - *(int *)data_start = spares[0]; - *(int *)(data_start+4) = spares[1]; - *(int *)(data_start+8) = flags; - - *(int *)(data_start+12) = mlist.size(); - - data_start += 16; - - for (LIF<MatchingImages> mlit(&mlist); !mlit.done(); mlit.next()) - { - mlit().WriteData(data_start); - data_start += mlit().Size(); - } -} - -ImageDescriptor const & Matching_Images_Chunk::GetLoadImage(ImageDescriptor const & _insteadof) -{ - for (LIF<MatchingImages> mlit(&mlist); !mlit.done(); mlit.next()) - { - if (_insteadof == mlit().insteadof) return mlit().load; - } - return _insteadof; -} - -// Bitmap MD5 Chunk -RIF_IMPLEMENT_DYNCREATE("BMPMD5ID",Bitmap_MD5_Chunk) - -Bitmap_MD5_Chunk::Bitmap_MD5_Chunk(Chunk_With_Children * parent, int const * md5id, BMP_Name const & rcbmp, char const * rname, char const * sname) -: Chunk(parent,"BMPMD5ID"), spare(0), flags(BMD5F_0), version_num(rcbmp.version_num) -{ - memcpy(md5_val,md5id,16); - - char const * bname = rcbmp.filename; - if (!bname) bname = ""; - bmpname = new char[strlen(bname)+1]; - strcpy(bmpname,bname); - - if (!rname) rname = ""; - rifname = new char[strlen(rname)+1]; - strcpy(rifname,rname); - - if (!sname) sname = ""; - shapename = new char[strlen(sname)+1]; - strcpy(shapename,sname); -} - -Bitmap_MD5_Chunk::Bitmap_MD5_Chunk(Chunk_With_Children * parent, char const * datablock, size_t) -: Chunk(parent,"BMPMD5ID"), spare(*(int *)datablock), flags((BMPMD5_Flags)(*(int *)(datablock+4) & BMD5F_MASK)), version_num(*(int *)(datablock+8)) -{ - memcpy(md5_val,datablock+12,16); - datablock += 28; - unsigned int const blen = strlen(datablock)+1; - bmpname = new char [blen]; - strcpy(bmpname,datablock); - datablock += blen; - unsigned int const rlen = strlen(datablock)+1; - rifname = new char [rlen]; - strcpy(rifname,datablock); - datablock += rlen; - unsigned int const slen = strlen(datablock)+1; - shapename = new char [slen]; - strcpy(shapename,datablock); -} - -Bitmap_MD5_Chunk::~Bitmap_MD5_Chunk() -{ - delete [] bmpname; - delete [] rifname; - delete [] shapename; -} - -void Bitmap_MD5_Chunk::fill_data_block(char * datastart) -{ - strncpy (datastart, identifier, 8); - datastart += 8; - *((int *) datastart) = chunk_size; - datastart += 4; - - *(int *)datastart = spare; - *(int *)(datastart+4) = flags; - *(int *)(datastart+8) = version_num; - memcpy(datastart+12,md5_val,16); - datastart += 28; - strcpy(datastart,bmpname ? bmpname : ""); - datastart += strlen(datastart)+1; - strcpy(datastart,rifname ? rifname : ""); - datastart += strlen(datastart)+1; - strcpy(datastart,shapename ? shapename : ""); -} - -size_t Bitmap_MD5_Chunk::size_chunk() -{ - return chunk_size = 12+28 - +(bmpname ? strlen(bmpname) : 0) - +(rifname ? strlen(rifname) : 0) - +(shapename ? strlen(shapename) : 0) - +3 +3&~3; -} - - - - diff --git a/3dc/win95/BMPNAMES.HPP b/3dc/win95/BMPNAMES.HPP deleted file mode 100644 index 5616b12..0000000 --- a/3dc/win95/BMPNAMES.HPP +++ /dev/null @@ -1,727 +0,0 @@ -#ifndef _bmpnames_hpp_ -#define _bmpnames_hpp_ - -#include "chunk.hpp" - -// for assert -#if engine - -#define UseLocalAssert No -#include "ourasert.h" -#define assert(x) GLOBALASSERT(x) - -#else - -#if cencon -#include "ccassert.h" -#else -#include <assert.h> -#endif - -#endif - -enum BMPN_Flags -{ - ChunkBMPFlag_Null = 0x00000000, // all flags reset - ChunkBMPFlag_NotInShape = 0x00000001, // not a texture map, maybe a sprite or hud graphic - ChunkBMPFlag_UsesTransparency = 0x00000002, // transparency_colour defines invisible pixels - ChunkBMPFlag_RequireGameMipMaps = 0x00000004, // mip maps are required for the game - ChunkBMPFlag_RequireToolsMipMaps = 0x00000008, // mip maps are required for the interface engine - ChunkBMPFlag_MipMapsExist = 0x00000010, // internal mip maps are up to date - ChunkBMPFlag_NotLit = 0x00000020, // not light sourced (eg. hud, iflag_nolight), so do not put darker colours into palette - ChunkBMPFlag_FixedPalette = 0x00000040, // will be quantized once only to a fixed sub-palette of each main palette - ChunkBMPFlag_Quantized = 0x00000080, // .PG0 exists which corresponds to the palette - // See below 0x00000100 - ChunkBMPFlag_MipMapsQuantized = 0x00000200, // .PG1-.PG6 exist which correspond to the palette and are mip maps - ChunkBMPFlag_PP0Exists = 0x00000400, // internal .PP0 exists - ChunkBMPFlag_NotInPC = 0x00000800, // for reduced memory, reduced features on some platforms - ChunkBMPFlag_NotInSaturn = 0x00001000, // for reduced memory, reduced features on some platforms - ChunkBMPFlag_NotInPlaystation = 0x00002000, // for reduced memory, reduced features on some platforms - ChunkBMPFlag_BM0Exists = 0x00004000, // 256 colour palettized texture for hw accelerators exists - ChunkBMPFlag_BMnsExist = 0x00008000, // mip mapped versions of 256 colour palettized texture exist - ChunkBMP_Dither = 0x00070000, // - ChunkBMP_DitherFloyd = 0x00010000, // - ChunkBMP_DitherFloydDamp1 = 0x00020000, // - ChunkBMP_DitherFloydDamp2 = 0x00030000, // 3 bits to control the type of error diffusion (if any) - ChunkBMP_DitherJarvis = 0x00040000, // - ChunkBMP_DitherJarvisDamp1 = 0x00050000, // - ChunkBMP_DitherJarvisDamp2 = 0x00060000, // - ChunkBMPFlag_RqQuantLUV = 0x00080000, // Remap in LUV colour space - ChunkBMPFlag_HistogramExists = 0x00100000, // used by cencon in palette generation - help by outputting .HST files - ChunkBMPFlag_HistogramV2Exists = 0x00200000, // used by cencon in palette generation - help by outputting .HS2 files (non-lit histograms for lit bitmaps with conceptual tlt palette) - ChunkBMPFlag_CopiedGenMipMaps = 0x00400000, // mip map HW generic textures have been copied to final dest - ChunkBMPFlag_CopiedGenBaseTex = 0x00800000, // base (non-mip) HW generic textures have been copied to final dest - - ChunkBMPFlag_IFF = 0x01000000, // a very important flag indeed: - // when this flag is set, the file is an IFF file and the filename stores a - // full relative path from the 'textures-root' directory for the project - // all other flags are complete bollocks when this flag is set - // (except for the NotIn.... flags) - // all this data will be in the file itself (transparency data anyway,,,) - // the file can be updated without the use of cencon, so for this reason - // I'll store the widths and heights where the transparent colour used - // to be. I'll also provide member-access functions to access this data - // which will check the flag is correct - -// This flag will be set on newer RIF files, because older ones will have priorities of 0 which is not ideal! -// When a chunk with these flag not set is detected, default values are filled in and the old values are not used. - ChunkBMPFlag_PriorityAndTransparencyAreValid = 0x00000100 - -}; - -//I have removed transparency from the default flags at the request of the artists - -// default flags for new bitmaps -#define DEFAULT_BMPN_FLAGS ((BMPN_Flags) ( \ - ChunkBMPFlag_PriorityAndTransparencyAreValid | \ - ChunkBMPFlag_RequireToolsMipMaps | /* test */ \ - ChunkBMPFlag_RequireGameMipMaps )) - -// user flags that should correspond for corresponding bitmaps -#define COPY_BMPN_FLAGS ((BMPN_Flags) ( \ - ChunkBMPFlag_NotInShape | \ - ChunkBMPFlag_UsesTransparency | \ - ChunkBMPFlag_RequireToolsMipMaps | \ - ChunkBMPFlag_RequireGameMipMaps | \ - ChunkBMPFlag_MipMapsExist | \ - ChunkBMPFlag_BMnsExist | \ - ChunkBMPFlag_BM0Exists | \ - ChunkBMPFlag_PP0Exists | \ - ChunkBMPFlag_NotLit | \ - ChunkBMPFlag_FixedPalette | \ - ChunkBMPFlag_NotInPC | \ - ChunkBMPFlag_NotInSaturn | \ - ChunkBMPFlag_NotInPlaystation | \ - ChunkBMP_Dither | \ - ChunkBMPFlag_RqQuantLUV | \ - ChunkBMPFlag_IFF)) - -// flags that when changed require requantizing -#define CHECKMODIFY_BMPN_FLAGS ((BMPN_Flags) ( \ - ChunkBMPFlag_UsesTransparency | \ - ChunkBMPFlag_FixedPalette /* not sure */ | \ - ChunkBMP_Dither | \ - ChunkBMPFlag_RqQuantLUV )) - -// flags to reset if a bitmap needs requantizing -#define QUANTIZED_BMPN_FLAGS ((BMPN_Flags) ( \ - ChunkBMPFlag_Quantized | \ - ChunkBMPFlag_MipMapsQuantized )) - -#define COMPLETED_BMPN_FLAGS ((BMPN_Flags) ( \ - ChunkBMPFlag_CopiedGenBaseTex | \ - ChunkBMPFlag_CopiedGenMipMaps | \ - QUANTIZED_BMPN_FLAGS )) - -#define DEFAULT_BMPN_PRIORITY 6 - - -extern void Palette_Outdated(Chunk_With_Children * parent); // decalred here, defined in chunkpal to avoid extra compiler dependencies -extern void FixedPalette_Outdated(Chunk_With_Children * parent); // decalred here, defined in chunkpal to avoid extra compiler dependencies -extern BOOL IsFixedPalette(Chunk_With_Children * parent); - - -class BMP_Name -{ -public: - - BMP_Name(const char * fname, int const gbnc_version); - ~BMP_Name(); - - BMP_Name(const BMP_Name &); - const BMP_Name & operator=(const BMP_Name &); - - char * filename; - - BMPN_Flags flags; - int index; - int version_num; - int enum_id; - #define BMPNAME_PARENT_VER_SHIFT 8 - // version num contains bmp version num (incremental on update) - // and Global_BMP_Name_Chunk version (at the time of creation) num shifted up - // This is so that if a bitmap is removed and then added, its - // version num will still be greater than that of the removed version - #define BMPNAME_VERSION_NUM_MASK 0x000fffff - #define BMPNAME_ENUMID_SHIFT 20 - // the top 12 bits of the previously spare data item (data1) - // contain an enumeration constant (max 4095) - // and the bottom 20 bits are available for version numbers - // a bit cramped and not ideal, but we are running out of storage space - // there are still two bytes free(0) in the priority data - - #define MAX_PC_PRIORITY 0xff - #define MAX_PSX_PRIORITY 0xff - inline int get_pc_priority(void) const { return priority & 0xff; } - inline int get_psx_priority(void) const { return priority >> 8 & 0xff; } - inline void set_pc_priority(int const p) { priority &= ~0xff; priority |= p & 0xff; } - inline void set_psx_priority(int const p) { priority &= ~0xff00; priority |= (p & 0xff) << 8; } - - friend BOOL operator==(const BMP_Name &o1, const BMP_Name &o2); - friend BOOL operator!=(const BMP_Name &o1, const BMP_Name &o2); - - BMP_Name() - : filename(0), flags((BMPN_Flags)DEFAULT_BMPN_FLAGS), index(0), version_num (0), priority (DEFAULT_BMPN_PRIORITY), transparency_colour_union(0) {} - - void Validate(void); - - #if cencon - int const * md5val; // space to put a pointer - - void DeleteAssociatedFiles() const; - void DeleteAssociatedMipFiles() const; - // changes the filename member, returns FALSE on failure - BOOL Rename(char const * newname); - - // use these to prevent DeleteAssociatedMipFiles & DeleteAssociatedFiles - // from deleting specific files - static void PreventDeleteFile(char const * pszFileName); - static void ReallowDeleteFile(char const * pszFileName); - private: - static List<char *> ms_listFilesCantDelete; - static void DeleteFileProt(char const * pszFileName); - public: - #endif - - unsigned GetTranspRedVal() const; - unsigned GetTranspGreenVal() const; - unsigned GetTranspBlueVal() const; - unsigned GetWidth() const; - unsigned GetHeight() const; - - void SetTranspRedVal(unsigned); - void SetTranspGreenVal(unsigned); - void SetTranspBlueVal(unsigned); - void SetWidth(unsigned); - void SetHeight(unsigned); - - // copy all data - void CopyUnionDataFrom(BMP_Name const & rBmp); - bool DifferentTransparencyColour(BMP_Name const & rBmp) const; - - enum - { - MAXVAL_RGB = 0xff, - MAXVAL_WH = 0xffff - }; - -private: - - int priority; // contains pc palettized mode palette generating priority as well as 16/256 colour priority for attahced palettes - - enum - { - SHIFT_R = 22, - SHIFT_G = 12, - SHIFT_B = 2, - - SHIFT_W = 0, - SHIFT_H = 16 - }; - - unsigned transparency_colour_union; // == r<<22 + g<<12 + b << 2 ; r,g,b <- [0..255], but don't assume this'll always be the case - // or H<<16 + W - - BMP_Name(const char * fname); - // initial part of constructor from buffer. - // GBNC and BLSC loaders find the rest of the data - // and put it into the BMP_Name object constructed with this constructor - - friend class Chunk_With_BMPs; - friend class BMP_Flags; -}; - -// functions to access the union transparency_colour_union which isn't a real C/C++ union -// they will check that you're performing valid accesses (ie. using the right part of the union) -// if you're a friend class, please ensure you use these access functions or know what you're doing -inline unsigned BMP_Name::GetTranspRedVal() const -{ - assert(!(flags & ChunkBMPFlag_IFF)); // not available for IFF files - it's in the file - return transparency_colour_union >> SHIFT_R & MAXVAL_RGB; -} - -inline unsigned BMP_Name::GetTranspGreenVal() const -{ - assert(!(flags & ChunkBMPFlag_IFF)); // not available for IFF files - it's in the file - return transparency_colour_union >> SHIFT_G & MAXVAL_RGB; -} - -inline unsigned BMP_Name::GetTranspBlueVal() const -{ - assert(!(flags & ChunkBMPFlag_IFF)); // not available for IFF files - it's in the file - return transparency_colour_union >> SHIFT_B & MAXVAL_RGB; -} - -inline unsigned BMP_Name::GetWidth() const -{ - assert(flags & ChunkBMPFlag_IFF); // only available for IFF files - required since they can be modified externally - return transparency_colour_union >> SHIFT_W & MAXVAL_WH; -} - -inline unsigned BMP_Name::GetHeight() const -{ - assert(flags & ChunkBMPFlag_IFF); // only available for IFF files - required since they can be modified externally - return transparency_colour_union >> SHIFT_H & MAXVAL_WH; -} - -inline void BMP_Name::SetTranspRedVal(unsigned v) -{ - assert(!(flags & ChunkBMPFlag_IFF)); // not available for IFF files - it's in the file - assert(v<=MAXVAL_RGB); // sensible value - - transparency_colour_union &= ~(MAXVAL_RGB << SHIFT_R); - transparency_colour_union |= v << SHIFT_R; -} - -inline void BMP_Name::SetTranspGreenVal(unsigned v) -{ - assert(!(flags & ChunkBMPFlag_IFF)); // not available for IFF files - it's in the file - assert(v<=MAXVAL_RGB); // sensible value - - transparency_colour_union &= ~(MAXVAL_RGB << SHIFT_G); - transparency_colour_union |= v << SHIFT_G; -} - -inline void BMP_Name::SetTranspBlueVal(unsigned v) -{ - assert(!(flags & ChunkBMPFlag_IFF)); // not available for IFF files - it's in the file - assert(v<=MAXVAL_RGB); // sensible value - - transparency_colour_union &= ~(MAXVAL_RGB << SHIFT_B); - transparency_colour_union |= v << SHIFT_B; -} - -inline void BMP_Name::SetWidth(unsigned v) -{ - assert(flags & ChunkBMPFlag_IFF); // only available for IFF files - required since they can be modified externally - assert(v<=MAXVAL_WH); // sensible value - - transparency_colour_union &= ~(MAXVAL_WH << SHIFT_W); - transparency_colour_union |= v << SHIFT_W; -} - -inline void BMP_Name::SetHeight(unsigned v) -{ - assert(flags & ChunkBMPFlag_IFF); // only available for IFF files - required since they can be modified externally - assert(v<=MAXVAL_WH); // sensible value - - transparency_colour_union &= ~(MAXVAL_WH << SHIFT_H); - transparency_colour_union |= v << SHIFT_H; -} - -inline void BMP_Name::CopyUnionDataFrom(BMP_Name const & rBmp) -{ - assert((flags & ChunkBMPFlag_IFF)==(rBmp.flags & ChunkBMPFlag_IFF)); - - transparency_colour_union = rBmp.transparency_colour_union; -} - -inline bool BMP_Name::DifferentTransparencyColour(BMP_Name const & rBmp) const -{ - assert(!(flags & ChunkBMPFlag_IFF) && !(rBmp.flags & ChunkBMPFlag_IFF)); - - return transparency_colour_union != rBmp.transparency_colour_union; -} - - -/////////////////////////////////////////////// - -class BMP_Names_ExtraData; -class Bitmap_MD5_Chunk; - -class Chunk_With_BMPs : public Chunk -{ -public: - - int max_index; - - List<BMP_Name> bmps; - - virtual int get_version_num(void); - virtual void set_version_num(int); - virtual void inc_version_num(void); - virtual BMP_Names_ExtraData * GetExtendedData(void); - - virtual int const * GetMD5Val(BMP_Name const & rcbmp); - virtual void SetMD5Val(BMP_Name const & rcbmp, int const * md5id); - virtual void RemoveMD5Val(char const * bname); - - friend class BMP_Group; // for cencon - friend class BMP_Info; // for cencon - -protected: - virtual Bitmap_MD5_Chunk * GetMD5Chunk(char const * bname) = 0; - virtual void CreateMD5Chunk(BMP_Name const & rcbmp, int const * md5id) = 0; - - virtual size_t size_chunk (); - virtual void fill_data_block (char * data_start); - - Chunk_With_BMPs (Chunk_With_Children * parent, const char * const ident) : Chunk(parent,ident), max_index(0) {} - Chunk_With_BMPs (Chunk_With_Children * parent, const char * const ident, const char * sdata, size_t ssize); - -}; - - -class Global_BMP_Name_Chunk : public Chunk_With_BMPs -{ -public: - - Global_BMP_Name_Chunk (Chunk_With_Children * parent) - : Chunk_With_BMPs (parent, "BMPNAMES") - {} - // constructor from buffer - Global_BMP_Name_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize) - : Chunk_With_BMPs (parent, "BMPNAMES", sdata, ssize) {} -private: - virtual Bitmap_MD5_Chunk * GetMD5Chunk(char const * bname); - virtual void CreateMD5Chunk(BMP_Name const & rcbmp, int const * md5id); - - friend class Environment_Data_Chunk; - - - - -}; - - -class Bitmap_List_Store_Chunk : public Chunk_With_BMPs -{ -public: - - Bitmap_List_Store_Chunk (Chunk_With_Children * parent) - : Chunk_With_BMPs (parent, "BMPLSTST") - {} - - // constructor from buffer - // not private, so that it is easy to get to - Bitmap_List_Store_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize) - : Chunk_With_BMPs (parent, "BMPLSTST", sdata, ssize) {} - -private: - virtual Bitmap_MD5_Chunk * GetMD5Chunk(char const * bname); - virtual void CreateMD5Chunk(BMP_Name const & rcbmp, int const * md5id); - - friend class Shape_External_File_Chunk; - -}; - - - -class BMP_Names_Version_Chunk : public Chunk -{ -public: - - BMP_Names_Version_Chunk (Chunk_With_Children * parent) - : Chunk (parent, "BMNAMVER"), version_num (0) - {} - // constructor from buffer - BMP_Names_Version_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/) - : Chunk (parent, "BMNAMVER"), version_num(*(int *)sdata) - {} - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - -private: - - int version_num; - - friend class Environment_Data_Chunk; - friend class Chunk_With_BMPs; - friend class Shape_External_File_Chunk; - friend class Sprite_Header_Chunk; - - -}; - -enum GlobalBMPFlags -{ - GBF_FIXEDPALETTE = 0x00000001, - GBF_SPRITE = 0x00000002, - GBF_HISTOGRAMEXISTS = 0x00000004, - GBF_HISTOGRAMV2EXISTS = 0x00000008, - - GBF_NONE = 0, - - // IMPORTANT - // since enums are not guaranteed to assume any particular - // storage class, code compiled on different compilers or - // with different settings may result in enums to be written - // to the data block as a char and read back in as an int, - // with the three most significant bytes containing junk. - // THIS MASK MUST BE KEPT UP TO DATE AS THE ENUM IS EXTENDED; - // ALSO ENSURE THAT NEW FILES LOADED INTO OLD SOFTWARE WILL - // NOT HAVE THEIR ENUM VALUE OVER-MASKED; THE MASK IS ONLY - // HERE TO ATTEMPT TO REMOVE PROBLEMS FROM FILES MADE - // PRIOR TO ITS INTRODUCTION - GBF_MASK = 0x000000ff -}; - -class BMP_Names_ExtraData -{ -public: - GlobalBMPFlags flags; -protected: - int reserved[12]; -}; - - -class BMP_Names_ExtraData_Chunk : public Chunk, public BMP_Names_ExtraData -{ -public: - - BMP_Names_ExtraData_Chunk (Chunk_With_Children * parent) - : Chunk (parent, "BMNAMEXT") - { - for (int i=0; i<12; ++i) reserved[i] = 0; - flags = GBF_NONE; - } - - // constructor from buffer - BMP_Names_ExtraData_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/) - : Chunk (parent, "BMNAMEXT") - { - flags = (GlobalBMPFlags)(*(int *)sdata & GBF_MASK); - sdata += 4; - for (int i=0; i<12; ++i, sdata+=4) reserved[i] = *(int *)sdata; - } - -private: - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - friend class Environment_Data_Chunk; - friend class Shape_External_File_Chunk; - friend class Sprite_Header_Chunk; - - -}; - - -class External_Shape_BMPs_Store_Chunk : public Chunk_With_BMPs, protected BMP_Names_ExtraData -{ -public: - char * rifname; // to match one in RIF_Child_Chunk - char * shapename; // matches rif name of original shape - - External_Shape_BMPs_Store_Chunk (Chunk_With_Children * parent, char const * rifn, char const * shapen); - External_Shape_BMPs_Store_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize); - ~External_Shape_BMPs_Store_Chunk(); - - virtual int get_version_num(void) { return version_num; } - virtual void set_version_num(int v) { version_num = v; } - virtual void inc_version_num(void) { ++version_num; } - virtual BMP_Names_ExtraData * GetExtendedData(void) { return this; } - -private: - virtual Bitmap_MD5_Chunk * GetMD5Chunk(char const * bname); - virtual void CreateMD5Chunk(BMP_Name const & rcbmp, int const * md5id); - - int version_num; - - virtual size_t size_chunk() - { - return chunk_size = Chunk_With_BMPs::size_chunk() + ((rifname ? strlen(rifname) : 0) + (shapename ? strlen(shapename) : 0)+2 +3&~3) + 56; - } - - virtual void fill_data_block(char * data_start); - - - - friend class Environment_Game_Mode_Chunk; -}; - - -// for dealing with matching images - -enum IDscFlags -{ - IDSCF_SPRITE = 0x00000001, // image is in a sprite - IDSCF_INCLUDED = 0x00000002, // image is from another rif file - IDSCF_FIXEDPALETTE = 0x00000004, // image has pgms for fixed palette - IDSCF_SUBSHAPE = 0x00000008, // image for shape included from another file - - IDSCF_0 = 0, - - // IMPORTANT - // since enums are not guaranteed to assume any particular - // storage class, code compiled on different compilers or - // with different settings may result in enums to be written - // to the data block as a char and read back in as an int, - // with the three most significant bytes containing junk. - // THIS MASK MUST BE KEPT UP TO DATE AS THE ENUM IS EXTENDED; - // ALSO ENSURE THAT NEW FILES LOADED INTO OLD SOFTWARE WILL - // NOT HAVE THEIR ENUM VALUE OVER-MASKED; THE MASK IS ONLY - // HERE TO ATTEMPT TO REMOVE PROBLEMS FROM FILES MADE - // PRIOR TO ITS INTRODUCTION - IDSCF_MASK = 0x000000ff -}; - -class ImageDescriptor -{ -public: - // constructos; - ImageDescriptor(); - ImageDescriptor(ImageDescriptor const &); - ImageDescriptor(IDscFlags, char const * fname, char const * rname = 0, char const * xname = 0); - ~ImageDescriptor(); - ImageDescriptor & operator = (ImageDescriptor const &); - - // operators - BOOL operator == (ImageDescriptor const &) const; - inline BOOL operator != (ImageDescriptor const & id2) const - { return ! operator == (id2); } - - // members - IDscFlags flags; - - char * filename; // name.bmp - char * rifname; // only if IDSCF_INCLUDED is set - char * fixrifname; // only if IDSCF_FIXEDPALETTE is set - -private: - // I/O - ImageDescriptor(char const * datablock); - size_t Size() const; - void WriteData(char * datablock) const; - - friend class MatchingImages; - - int spares[3]; -}; - -class MatchingImages -{ -public: - // constructos; - MatchingImages() {} - MatchingImages(ImageDescriptor const & _load, ImageDescriptor const & _insteadof); - - // operators - inline BOOL operator == (MatchingImages const & m2) - { return load == m2.load && insteadof == m2.insteadof; } - inline BOOL operator != (MatchingImages const & m2) - { return load != m2.load || insteadof != m2.insteadof; } - - // members - ImageDescriptor load; - ImageDescriptor insteadof; - -private: - - // I/O - MatchingImages(char const * datablock); - size_t Size() const; - void WriteData(char * datablock) const; - - friend class Matching_Images_Chunk; - - int spares[3]; - -}; - -enum MICFlags -{ - MICF_0 = 0, - - MICF_FIXEDPALETTE = 0x00000001, - - // IMPORTANT - // since enums are not guaranteed to assume any particular - // storage class, code compiled on different compilers or - // with different settings may result in enums to be written - // to the data block as a char and read back in as an int, - // with the three most significant bytes containing junk. - // THIS MASK MUST BE KEPT UP TO DATE AS THE ENUM IS EXTENDED; - // ALSO ENSURE THAT NEW FILES LOADED INTO OLD SOFTWARE WILL - // NOT HAVE THEIR ENUM VALUE OVER-MASKED; THE MASK IS ONLY - // HERE TO ATTEMPT TO REMOVE PROBLEMS FROM FILES MADE - // PRIOR TO ITS INTRODUCTION - MICF_MASK = 0x000000ff -}; - -class Matching_Images_Chunk : public Chunk -{ -public: - // constructors - Matching_Images_Chunk(Chunk_With_Children * parent) : Chunk(parent,"MATCHIMG"), flags(MICF_0) - { spares[0]=0; spares[1]=0; } // empty list - // I/O - Matching_Images_Chunk(Chunk_With_Children * parent, char const * datablock, size_t); - // members - List<MatchingImages> mlist; - - MICFlags flags; - - // methods - ImageDescriptor const & GetLoadImage(ImageDescriptor const &); - -private: - int spares[2]; - - - virtual size_t size_chunk(); - virtual void fill_data_block(char * data_start); - - friend class Environment_Data_Chunk; - friend class Environment_Game_Mode_Chunk; -}; - -enum BMPMD5_Flags -{ - BMD5F_0 = 0, - - BMD5F_SPRITE = 0x00000001, - - // IMPORTANT - // since enums are not guaranteed to assume any particular - // storage class, code compiled on different compilers or - // with different settings may result in enums to be written - // to the data block as a char and read back in as an int, - // with the three most significant bytes containing junk. - // THIS MASK MUST BE KEPT UP TO DATE AS THE ENUM IS EXTENDED; - // ALSO ENSURE THAT NEW FILES LOADED INTO OLD SOFTWARE WILL - // NOT HAVE THEIR ENUM VALUE OVER-MASKED; THE MASK IS ONLY - // HERE TO ATTEMPT TO REMOVE PROBLEMS FROM FILES MADE - // PRIOR TO ITS INTRODUCTION - BMD5F_MASK = 0x000000ff -}; - -class Bitmap_MD5_Chunk : public Chunk -{ -public : - Bitmap_MD5_Chunk(Chunk_With_Children * parent, char const * datablock, size_t); -private: - Bitmap_MD5_Chunk(Chunk_With_Children * parent, int const * md5id, BMP_Name const & rcbmp, char const * rname = 0, char const * sname = 0); - ~Bitmap_MD5_Chunk(); - int md5_val[4]; - char * bmpname; - char * rifname; - char * shapename; - BMPMD5_Flags flags; - int version_num; - - int spare; - - virtual size_t size_chunk(); - virtual void fill_data_block(char * data_start); - - // your parents are your friends - friend class Environment_Data_Chunk; - friend class Environment_Game_Mode_Chunk; - friend class Shape_External_File_Chunk; - friend class Sprite_Header_Chunk; - // some of your siblings are friends as well - friend class Chunk_With_BMPs; - friend class Global_BMP_Name_Chunk; - friend class Bitmap_List_Store_Chunk; - friend class External_Shape_BMPs_Store_Chunk; - friend class RIF_Child_Chunk; -}; - - - -#endif
\ No newline at end of file diff --git a/3dc/win95/CD_player.c b/3dc/win95/CD_player.c deleted file mode 100644 index f6e2861..0000000 --- a/3dc/win95/CD_player.c +++ /dev/null @@ -1,602 +0,0 @@ -#include "3dc.h" -#include "inline.h" -#include "psndplat.h" -#include "cd_player.h" - -#define UseLocalAssert Yes -#include "ourasert.h" - -/* KJL 12:40:35 07/05/98 - This is code derived from Patrick's original stuff & -moved into it's own file. */ - -/* Patrick 10/6/97 ------------------------------------------------------------- - CDDA Support - ----------------------------------------------------------------------------*/ -#define NO_DEVICE -1 -int cdDeviceID = NO_DEVICE; -int cdAuxDeviceID = NO_DEVICE; - -/* Patrick 9/6/97 ------------------------------------------------------------- - ---------------------------------------------------------------------------- - CDDA Support - ----------------------------------------------------------------------------- - -----------------------------------------------------------------------------*/ -static int CDDASwitchedOn = 0; -static int CDDAIsInitialised = 0; -static int CDDAVolume = CDDA_VOLUME_DEFAULT; -CDOPERATIONSTATES CDDAState; - -static DWORD PreGameCDVolume;//windows cd volume before the game started - -static CDTRACKID TrackBeingPlayed; -static enum CDCOMMANDID LastCommandGiven; - -extern HWND hWndMain; - -int CDPlayerVolume; // volume control from menus - -int CDTrackMax=-1; //highest track number on cd - -void CDDA_Start(void) -{ - CDDAVolume = CDDA_VOLUME_DEFAULT; - CDPlayerVolume = CDDAVolume; - CDDAState = CDOp_Idle; - CDDAIsInitialised = 0; - if(PlatStartCDDA()!=SOUND_PLATFORMERROR) - { - CDDAIsInitialised = 1; - CDDA_SwitchOn(); - CDDA_ChangeVolume(CDDAVolume); /* init the volume */ - CDDA_CheckNumberOfTracks(); - } - LastCommandGiven = CDCOMMANDID_Start; -} - -void CDDA_End(void) -{ - if(!CDDAIsInitialised) return; - - CDDA_Stop(); - PlatChangeCDDAVolume(CDDA_VOLUME_RESTOREPREGAMEVALUE); - PlatEndCDDA(); - CDDA_SwitchOff(); - CDDAIsInitialised = 0; - - LastCommandGiven = CDCOMMANDID_End; -} - -void CDDA_Management(void) -{ - if(!CDDASwitchedOn) return; /* CDDA is off */ - if(CDDAState==CDOp_Playing) return; /* already playing */ - PlatCDDAManagement(); -} - -void CDDA_Play(int CDDATrack) -{ - int ok; - - if(!CDDASwitchedOn) return; /* CDDA is off */ - if(CDDAState==CDOp_Playing) return; /* already playing */ - if((CDDATrack<=0)||(CDDATrack>=CDTrackMax)) return; /* no such track */ - - ok = PlatPlayCDDA((int)CDDATrack); - if(ok!=SOUND_PLATFORMERROR) - { - CDDAState=CDOp_Playing; - LastCommandGiven = CDCOMMANDID_Play; - TrackBeingPlayed = CDDATrack; - } -} -void CDDA_PlayLoop(int CDDATrack) -{ - int ok; - - if(!CDDASwitchedOn) return; /* CDDA is off */ - if(CDDAState==CDOp_Playing) return; /* already playing */ - if((CDDATrack<=0)||(CDDATrack>=CDTrackMax)) return; /* no such track */ - - ok = PlatPlayCDDA((int)CDDATrack); - if(ok!=SOUND_PLATFORMERROR) - { - CDDAState=CDOp_Playing; - LastCommandGiven = CDCOMMANDID_PlayLoop; - TrackBeingPlayed = CDDATrack; - } -} - -extern void CheckCDVolume(void) -{ - if (CDDAVolume != CDPlayerVolume) - { - CDDA_ChangeVolume(CDPlayerVolume); - } -} -void CDDA_ChangeVolume(int volume) -{ - if(!CDDASwitchedOn) return; /* CDDA is off */ - if(volume<CDDA_VOLUME_MIN) return; - if(volume>CDDA_VOLUME_MAX) return; - - if(CDDA_IsOn()) - { - if(PlatChangeCDDAVolume(volume)) - { - CDDAVolume=volume; - CDPlayerVolume = volume; - LastCommandGiven = CDCOMMANDID_ChangeVolume; - } - } -} - -int CDDA_GetCurrentVolumeSetting(void) -{ - return CDDAVolume; -} - -void CDDA_Stop() -{ - int ok; - if(!CDDASwitchedOn) return; /* CDDA is off */ - if(CDDAState!=CDOp_Playing) return; /* nothing playing */ - ok = PlatStopCDDA(); - CDDAState=CDOp_Idle; - LastCommandGiven = CDCOMMANDID_Stop; -} - -void CDDA_SwitchOn() -{ - LOCALASSERT(!CDDA_IsPlaying()); - if(CDDAIsInitialised) CDDASwitchedOn = 1; -} - -void CDDA_SwitchOff() -{ - if(!CDDASwitchedOn) return; /* CDDA is off already */ - if(CDDA_IsPlaying()) CDDA_Stop(); - CDDASwitchedOn = 0; -} - -int CDDA_IsOn() -{ - return CDDASwitchedOn; -} - -int CDDA_IsPlaying() -{ - if(CDDAState==CDOp_Playing) - { - LOCALASSERT(CDDASwitchedOn); - return 1; - } - return 0; -} - -int CDDA_CheckNumberOfTracks() -{ - int numTracks=0; - - if(CDDA_IsOn()) - { - PlatGetNumberOfCDTracks(&numTracks); - - //if there is only one track , then it probably can't be used anyway - if(numTracks==1) numTracks=0; - - //store the maximum allowed track number - CDTrackMax=numTracks; - } - return numTracks; -} - - - -/* win95 specific */ - -int PlatStartCDDA(void) -{ - static void PlatGetCDDAVolumeControl(void); - DWORD dwReturn; - MCI_OPEN_PARMS mciOpenParms; - - /* Initialise device handles */ - cdDeviceID = NO_DEVICE; - cdAuxDeviceID = NO_DEVICE; - - /* try to open mci cd-audio device */ - mciOpenParms.lpstrDeviceType = (LPCSTR) MCI_DEVTYPE_CD_AUDIO; - dwReturn = mciSendCommand(NULL,MCI_OPEN,MCI_OPEN_TYPE|MCI_OPEN_TYPE_ID,(DWORD)(LPVOID)&mciOpenParms); - if(dwReturn) - { - /* error */ - cdDeviceID = NO_DEVICE; - return SOUND_PLATFORMERROR; - } - cdDeviceID = mciOpenParms.wDeviceID; - - /* now try to get the cd volume control, by obtaining the auxiliary device id for - the cd-audio player*/ - PlatGetCDDAVolumeControl(); - return 0; -} - -/* this is a support function for PlatStartCDDA() */ -#if 0 -static void PlatGetCDDAVolumeControl(void) -{ - MMRESULT mmres; - unsigned int numAuxDevs,i; - - numAuxDevs = auxGetNumDevs(); - /* search the auxilary device list for the cd player */ - for(i=0;i<numAuxDevs;i++) - { - AUXCAPS devCaps; - mmres = auxGetDevCaps(i,&devCaps,sizeof(AUXCAPS)); - if(mmres==MMSYSERR_NOERROR) - { - if((devCaps.wTechnology&AUXCAPS_CDAUDIO)&&(devCaps.dwSupport&AUXCAPS_VOLUME)) - { - cdAuxDeviceID = i; - } - } - } -} -#else -static void PlatGetCDDAVolumeControl(void) -{ - int i; - int numDev = mixerGetNumDevs(); - - - //go through the mixer devices searching for one that can deal with the cd volume - for(i=0;i<numDev;i++) - { - HMIXER handle; - if(mixerOpen(&handle,i,0,0,MIXER_OBJECTF_MIXER ) == MMSYSERR_NOERROR ) - { - - //try to get the compact disc mixer line - MIXERLINE line; - line.cbStruct=sizeof(MIXERLINE); - line.dwComponentType=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; - - if(mixerGetLineInfo(handle,&line,MIXER_GETLINEINFOF_COMPONENTTYPE) == MMSYSERR_NOERROR) - { - MIXERLINECONTROLS lineControls; - MIXERCONTROL control; - - - lineControls.cbStruct=sizeof(MIXERLINECONTROLS); - lineControls.dwLineID=line.dwLineID; - lineControls.pamxctrl=&control; - lineControls.dwControlType=MIXERCONTROL_CONTROLTYPE_VOLUME ; - lineControls.cControls=1; - lineControls.cbmxctrl=sizeof(MIXERCONTROL); - - control.cbStruct=sizeof(MIXERCONTROL); - - - //try to get the volume control - if(mixerGetLineControls(handle,&lineControls,MIXER_GETLINECONTROLSF_ONEBYTYPE)==MMSYSERR_NOERROR) - { - - MIXERCONTROLDETAILS details; - MIXERCONTROLDETAILS_UNSIGNED detailValue; - - details.cbStruct=sizeof(MIXERCONTROLDETAILS); - details.dwControlID=control.dwControlID; - details.cChannels=1; - details.cMultipleItems=0; - details.cbDetails=sizeof(MIXERCONTROLDETAILS_UNSIGNED); - details.paDetails=&detailValue; - - //get the current volume so that we can restore it later - if(mixerGetControlDetails(handle,&details,MIXER_GETCONTROLDETAILSF_VALUE)==MMSYSERR_NOERROR) - { - PreGameCDVolume = detailValue.dwValue; - mixerClose(handle); - - return; //success - } - } - } - - - mixerClose(handle); - } - - } - - return; -} -#endif - - -void PlatEndCDDA(void) -{ - DWORD dwReturn; - - /* check the cdDeviceId */ - if(cdDeviceID==NO_DEVICE) return; - - dwReturn = mciSendCommand((UINT)cdDeviceID,MCI_CLOSE,MCI_WAIT,NULL); - cdDeviceID=NO_DEVICE; - - /* reset the auxilary device handle */ - cdAuxDeviceID = NO_DEVICE; -} - -int PlatPlayCDDA(int track) -{ - DWORD dwReturn; - MCI_SET_PARMS mciSetParms = {0,0,0}; - MCI_PLAY_PARMS mciPlayParms = {0,0,0}; - MCI_STATUS_PARMS mciStatusParms = {0,0,0,0}; - - /* check the cdDeviceId */ - if(cdDeviceID==NO_DEVICE) return SOUND_PLATFORMERROR; - - /* set the time format */ - mciSetParms.dwTimeFormat = MCI_FORMAT_MSF; - dwReturn = mciSendCommand((UINT)cdDeviceID,MCI_SET,MCI_SET_TIME_FORMAT,(DWORD)(LPVOID) &mciSetParms); - if(dwReturn) - { -// NewOnScreenMessage("CD ERROR - TIME FORMAT"); - /* error */ - return SOUND_PLATFORMERROR; - } - - /* find the length of the track... */ - mciStatusParms.dwItem = MCI_STATUS_LENGTH; - mciStatusParms.dwTrack = track; - dwReturn = mciSendCommand((UINT)cdDeviceID,MCI_STATUS,MCI_STATUS_ITEM|MCI_TRACK,(DWORD)(LPVOID)&mciStatusParms); - if(dwReturn) - { - /* error */ -// NewOnScreenMessage("CD ERROR - GET LENGTH"); - return SOUND_PLATFORMERROR; - } - - /* set the time format */ - mciSetParms.dwTimeFormat = MCI_FORMAT_TMSF; - dwReturn = mciSendCommand((UINT)cdDeviceID,MCI_SET,MCI_SET_TIME_FORMAT,(DWORD)(LPVOID) &mciSetParms); - if(dwReturn) - { - /* error */ -// NewOnScreenMessage("CD ERROR - TIME FORMAT"); - return SOUND_PLATFORMERROR; - } - - /* play the track: set up for notification when track finishes, or an error occurs */ - mciPlayParms.dwFrom=MCI_MAKE_TMSF(track,0,0,0); - mciPlayParms.dwTo=MCI_MAKE_TMSF(track, MCI_MSF_MINUTE(mciStatusParms.dwReturn), - MCI_MSF_SECOND(mciStatusParms.dwReturn), - MCI_MSF_FRAME(mciStatusParms.dwReturn)); - mciPlayParms.dwCallback=(DWORD)hWndMain; - dwReturn = mciSendCommand((UINT)cdDeviceID,MCI_PLAY,MCI_FROM|MCI_TO|MCI_NOTIFY,(DWORD)(LPVOID)&mciPlayParms); - if(dwReturn) - { - /* error */ -// NewOnScreenMessage("CD ERROR - PLAY"); - return SOUND_PLATFORMERROR; - } - return 0; -} - -int PlatGetNumberOfCDTracks(int* numTracks) -{ - DWORD dwReturn; - MCI_STATUS_PARMS mciStatusParms = {0,0,0,0}; - - /* check the cdDeviceId */ - if(cdDeviceID==NO_DEVICE) return SOUND_PLATFORMERROR; - if(!numTracks) return SOUND_PLATFORMERROR; - - - /* find the number tracks... */ - mciStatusParms.dwItem = MCI_STATUS_NUMBER_OF_TRACKS ; - dwReturn = mciSendCommand((UINT)cdDeviceID,MCI_STATUS,MCI_STATUS_ITEM ,(DWORD)(LPVOID)&mciStatusParms); - if(dwReturn) - { - /* error */ - return SOUND_PLATFORMERROR; - } - - //number of tracks is in the dwReturn member - *numTracks=mciStatusParms.dwReturn; - - - return 0; - -} - -int PlatStopCDDA(void) -{ - DWORD dwReturn; - - /* check the cdDeviceId */ - if(cdDeviceID==NO_DEVICE) - { - return SOUND_PLATFORMERROR; - } - - /* stop the cd player */ - dwReturn = mciSendCommand((UINT)cdDeviceID,MCI_STOP,MCI_WAIT,NULL); - if(dwReturn) - { - /* error */ - return SOUND_PLATFORMERROR; - } - return 0; -} -#if 0 -int PlatChangeCDDAVolume(int volume) -{ - MMRESULT mmres; - unsigned int newVolume; - - /* check the cdDeviceId */ - if(cdDeviceID==NO_DEVICE) return SOUND_PLATFORMERROR; - /* check the mixer device id */ - if(cdAuxDeviceID==NO_DEVICE) return SOUND_PLATFORMERROR; - - /* scale and set the new volume */ - { - int channelVolume; - channelVolume = VOLUME_CDDA_MINPLAT + WideMulNarrowDiv(volume, - (VOLUME_CDDA_MAXPLAT-VOLUME_CDDA_MINPLAT), (CDDA_VOLUME_MAX-CDDA_VOLUME_MIN)); - if(channelVolume < VOLUME_CDDA_MINPLAT) channelVolume = VOLUME_CDDA_MINPLAT; - if(channelVolume > VOLUME_CDDA_MAXPLAT) channelVolume = VOLUME_CDDA_MAXPLAT; - - /* set left and right channels (if there is only one channel, - should still work ok)*/ - newVolume = channelVolume|(channelVolume<<16); - } - PlatGetCDDAVolumeControl(); - - mmres = auxSetVolume((UINT)cdAuxDeviceID,(DWORD)newVolume); - if(mmres==MMSYSERR_NOERROR) return 1; - else return SOUND_PLATFORMERROR; -} -#else -int PlatChangeCDDAVolume(int volume) -{ - MMRESULT mmres; - unsigned int newVolume; - int i; - int numDev = mixerGetNumDevs(); - - /* check the cdDeviceId */ - if(cdDeviceID==NO_DEVICE) return SOUND_PLATFORMERROR; - - //go through the mixer devices searching for one that can deal with the cd volume - for(i=0;i<numDev;i++) - { - HMIXER handle; - if(mixerOpen(&handle,i,0,0,MIXER_OBJECTF_MIXER ) == MMSYSERR_NOERROR ) - { - - //try to get the compact disc mixer line - MIXERLINE line; - line.cbStruct=sizeof(MIXERLINE); - line.dwComponentType=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; - - if(mixerGetLineInfo(handle,&line,MIXER_GETLINEINFOF_COMPONENTTYPE) == MMSYSERR_NOERROR) - { - MIXERLINECONTROLS lineControls; - MIXERCONTROL control; - - - lineControls.cbStruct=sizeof(MIXERLINECONTROLS); - lineControls.dwLineID=line.dwLineID; - lineControls.pamxctrl=&control; - lineControls.dwControlType=MIXERCONTROL_CONTROLTYPE_VOLUME ; - lineControls.cControls=1; - lineControls.cbmxctrl=sizeof(MIXERCONTROL); - - control.cbStruct=sizeof(MIXERCONTROL); - - - //try to get the volume control - if(mixerGetLineControls(handle,&lineControls,MIXER_GETLINECONTROLSF_ONEBYTYPE)==MMSYSERR_NOERROR) - { - - MIXERCONTROLDETAILS details; - MIXERCONTROLDETAILS_UNSIGNED detailValue; - - details.cbStruct=sizeof(MIXERCONTROLDETAILS); - details.dwControlID=control.dwControlID; - details.cChannels=1; - details.cMultipleItems=0; - details.cbDetails=sizeof(MIXERCONTROLDETAILS_UNSIGNED); - details.paDetails=&detailValue; - - - if(volume==CDDA_VOLUME_RESTOREPREGAMEVALUE) - { - //set the volume to what it was before the game started - newVolume=PreGameCDVolume; - } - else - { - //scale the volume - newVolume = control.Bounds.dwMinimum + WideMulNarrowDiv(volume, - (control.Bounds.dwMaximum-control.Bounds.dwMinimum), (CDDA_VOLUME_MAX-CDDA_VOLUME_MIN)); - - if(newVolume<control.Bounds.dwMinimum) newVolume=control.Bounds.dwMinimum; - if(newVolume>control.Bounds.dwMaximum) newVolume=control.Bounds.dwMaximum; - } - //fill in the volume in the control details structure - detailValue.dwValue=newVolume; - - - mmres = mixerSetControlDetails(handle,&details,MIXER_SETCONTROLDETAILSF_VALUE); - mixerClose(handle); - - if(mmres==MMSYSERR_NOERROR) return 1; - else return SOUND_PLATFORMERROR; - - } - } - - - mixerClose(handle); - } - - } - - return SOUND_PLATFORMERROR; -} - -#endif - - - - -void PlatCDDAManagement(void) -{ - /* does nothing for Win95: use call back instead */ -} - -void PlatCDDAManagementCallBack(WPARAM flags, LONG deviceId) -{ - extern CDOPERATIONSTATES CDDAState; - - /* check the cdDeviceId */ - if(cdDeviceID==NO_DEVICE) return; - /* compare with the passed device id */ - if((UINT)deviceId!=(UINT)cdDeviceID) return; - - if(flags&MCI_NOTIFY_SUCCESSFUL) - { - CDDAState = CDOp_Idle; - //NewOnScreenMessage("CD COMMAND RETURNED WITH SUCCESSFUL"); - /* Play it again, sam */ - if (LastCommandGiven == CDCOMMANDID_PlayLoop) - { - CDDA_PlayLoop(TrackBeingPlayed); - } - } - else if(flags&MCI_NOTIFY_FAILURE) - { - /* error while playing: abnormal termination */ - //NewOnScreenMessage("CD COMMAND FAILED"); - CDDAState = CDOp_Idle; - } - else if(flags&MCI_NOTIFY_SUPERSEDED) - { - //NewOnScreenMessage("CD COMMAND SUPERSEDED"); - } - else if(flags&MCI_NOTIFY_ABORTED) - { - /* aborted or superceeded: try and stop the device */ - //NewOnScreenMessage("CD COMMAND ABORTED(?)"); - // CDDA_Stop(); - } - else - { - //NewOnScreenMessage("CD COMMAND RETURNED WITH UNKNOWN MESSAGE"); - } -} diff --git a/3dc/win95/CD_player.h b/3dc/win95/CD_player.h deleted file mode 100644 index 70e8a2e..0000000 --- a/3dc/win95/CD_player.h +++ /dev/null @@ -1,110 +0,0 @@ -/* KJL 12:40:35 07/05/98 - This is code derived from Patrick's original stuff & -moved into it's own file. */ - - -/* Patrick 10/6/97 -------------------------------------------------------------- - SUPPORT FOR CDDA SYSTEM - -----------------------------------------------------------------------------*/ - -/* Patrick 10/6/97 -------------------------------------------------------------- - Some Volume defines - -----------------------------------------------------------------------------*/ -#define CDDA_VOLUME_MAX (127) -#define CDDA_VOLUME_MIN (0) -#define CDDA_VOLUME_DEFAULT (127) -#define CDDA_VOLUME_RESTOREPREGAMEVALUE (-100) - -/* Patrick 10/6/97 -------------------------------------------------------------- - Enumeration of CD player states - -----------------------------------------------------------------------------*/ -typedef enum cdoperationstates -{ - CDOp_Idle, - CDOp_Playing, -} -CDOPERATIONSTATES; - -/* Patrick 10/6/97 -------------------------------------------------------------- - CDDA_Start/End are used to initialise and de-initialise the CDDA system. - No CDDA operations have any effect until the system has been initialised. - -----------------------------------------------------------------------------*/ -extern void CDDA_Start(void); -extern void CDDA_End(void); -/* Patrick 10/6/97 -------------------------------------------------------------- - This is provided to allow platform specific polling/management of the CD device - whilst playing. It should be called during the main game loop. - -----------------------------------------------------------------------------*/ -extern void CDDA_Management(void); -/* Patrick 10/6/97 -------------------------------------------------------------- - Play , change volume, and stop are the basic CDDA operations provided. An - enumeration of tracks should be provided in the platform header. - -----------------------------------------------------------------------------*/ -extern void CDDA_Play(int CDDATrack); -extern void CDDA_PlayLoop(int CDDATrack); -extern void CDDA_ChangeVolume(int volume); -extern void CDDA_Stop(void); -extern int CDDA_CheckNumberOfTracks(void); -/* Patrick 23/6/97 -------------------------------------------------------------- - Returns the current CDDA volume setting. NB if the cd player has not been - initialised the volume setting can still be obtained by calling this function, - though it may not be changed using CDDA_ChangeVolume(). - -----------------------------------------------------------------------------*/ -extern int CDDA_GetCurrentVolumeSetting(void); -/* Patrick 10/6/97 -------------------------------------------------------------- - Switch on and switch off may be used to stop and start the CDDA system after - initialisation. They are provided to allow the user to stop and start CDDA - during a game. - -----------------------------------------------------------------------------*/ -extern void CDDA_SwitchOn(void); -extern void CDDA_SwitchOff(void); -/* Patrick 10/6/97 -------------------------------------------------------------- - These are provided to interrogate the state of the CDDA system. - -----------------------------------------------------------------------------*/ -extern int CDDA_IsOn(void); -extern int CDDA_IsPlaying(void); - - - -enum CDCOMMANDID -{ - CDCOMMANDID_Start, - CDCOMMANDID_End, - CDCOMMANDID_Play, - CDCOMMANDID_PlayLoop, - CDCOMMANDID_ChangeVolume, - CDCOMMANDID_Stop, -}; - -/* CDDA SUPPORT */ - -#define VOLUME_CDDA_MAXPLAT (65535) -#define VOLUME_CDDA_MINPLAT (0) - -/* Patrick 10/6/97 ------------------------------------------------------------- - Start and end functions provide any platform specific initialisation for - the CD player. The start function returns SOUND_PLATFORM error if unsucessful, - or zero otherwise. - ----------------------------------------------------------------------------*/ -extern int PlatStartCDDA(void); -extern void PlatEndCDDA(void); -/* Patrick 10/6/97 ------------------------------------------------------------- - Platform specific play, stop, and change volume functions. NB the volume - is scaled to the platform limits defined above. - These functions return SOUND_PLATFORM error if unsucessful, or 0 otherwise. - ----------------------------------------------------------------------------*/ -extern int PlatPlayCDDA(int track); -extern int PlatStopCDDA(void); -extern int PlatChangeCDDAVolume(int volume); -int PlatGetNumberOfCDTracks(int* numTracks); -/* Patrick 10/6/97 ------------------------------------------------------------- - Management functions are provided for platform specific detection of changes - in the cd player state (ie finishing a track, or an error). The basic - management function is provided for consoles, who need to poll the device, - whilst the call back is provided for intercepting WIN95 MCI call backs. - ----------------------------------------------------------------------------*/ -extern void PlatCDDAManagement(void); -extern void PlatCDDAManagementCallBack(WPARAM flags, LONG deviceId); - - - -extern int CDPlayerVolume;
\ No newline at end of file diff --git a/3dc/win95/CHNKIMAG.CPP b/3dc/win95/CHNKIMAG.CPP deleted file mode 100644 index a2f703a..0000000 --- a/3dc/win95/CHNKIMAG.CPP +++ /dev/null @@ -1,699 +0,0 @@ -#include <string.h> - -#define TRY_OLD_DIRS 0 // obsolete -#define ALLOW_LOAD_ORIGINAL 0 - -#if TRY_OLD_DIRS // temporary until all textures go into subshps directory -#include "ffstdio.h" -#endif - -#include "chnkimag.hpp" - -#include "list_tem.hpp" -#include "envchunk.hpp" -#include "chunkpal.hpp" -#include "bmpnames.hpp" - -#include "chnkload.hpp" - -char const * CL_RIFFImage::game_mode = 0; - -// useful filename handling functions - -// returns pointer into string pointing to filename without dirname -template <class C> // C can be char or char const -static C * strip_path(C * n) -{ - C * rm = strrchr(n,':'); - if (rm) n = rm+1; - rm = strrchr(n,'/'); - if (rm) n = rm+1; - rm = strrchr(n,'\\'); - if (rm) n = rm+1; - - return n; -} - -// removes any .extension from filename by inserting null character -static void strip_file_extension(char * n) -{ - char * dotpos = strrchr(n,'.'); - if (dotpos) *dotpos = 0; -} - -static char * strip_file_extension(char const * n) -{ - char * nn = new char[strlen(n)+1]; - strcpy(nn,n); - strip_file_extension(nn); - return nn; -} - -//////////////////////// -// -// riff file interface -// -//////////////////////// - - -// get the directory associated with the riff - free with delete[] -static char * riff_basename(Chunk_With_Children * envd) -{ - RIF_Name_Chunk * rnc = 0; - - List<Chunk *> chlst = envd->lookup_child("RIFFNAME"); - - if (chlst.size()) - { - rnc = (RIF_Name_Chunk *)chlst.first_entry(); - const char * rif_name = strip_path(rnc->rif_name); - - char * basename = new char[strlen(rif_name)+1]; - strcpy(basename,rif_name); - strip_file_extension(basename); - - return basename; - } - const char * deflt = "empty"; - char * basename = new char [strlen(deflt)+1]; - strcpy(basename,deflt); - - return basename; -} - -#if OUTPUT_LOG -#define _LOGID CL_LogFile.lprintf("%s:%d :: ",__FILE__,__LINE__) -#define _LOGPUT(s) _LOGID,CL_LogFile.lputs(s) -#define _LOGPRINT(args) _LOGID,CL_LogFile.lprintf args -#else -#define _LOGPUT(s) (void)0 -#define _LOGPRINT(args) (void)0 -#endif - -void CL_RIFFImage::GetPath(ImageDescriptor const & idsc, Environment_Data_Chunk * envd, BMPN_Flags bflags) -{ - if (fname) delete[] fname; - fname = 0; - - // set the name - if (name) delete[] name; - char * nptr = strip_path(idsc.filename); - name = new char[strlen(nptr)+1]; - strcpy(name,nptr); - #if 0 - char orig_ext[32]; - char const * oeP = strrchr(name,'.'); - if (!oeP) eoP = ""; - strcpy(orig_ext,oeP); - #endif - strip_file_extension(name); - - // load this image - char const * pg0ext = ".PG0"; - switch (imode) - { - case CLM_16BIT: - case CLM_24BIT: - case CLM_32BIT: - #if ALLOW_LOAD_ORIGINAL - { - char const * dir2 = idsc.flags & IDSCF_SPRITE ? "Sprites\\" : ""; - char * riffname = riff_basename(envd); - char const * dir3 = idsc.flags & IDSCF_INCLUDED ? idsc.rifname : riffname; - fname = new char[strlen(ToolsTex_Directory)+strlen(dir2)+strlen(dir3)+1+strlen(name)+5]; - strcpy(fname,ToolsTex_Directory); - strcat(fname,dir2); - strcat(fname,dir3); - strcat(fname,"\\"); - strcat(fname,name); - strcat(fname,".PP0"); - delete[] riffname; - break; - } - #endif - case CLM_ATTACHEDPALETTE: - { - char const * dir2 = idsc.flags & IDSCF_SPRITE ? "Sprites\\" : idsc.flags & IDSCF_SUBSHAPE ? "SubShps\\All\\" : ""; - char * riffname = riff_basename(envd); - char const * dir3 = idsc.flags & IDSCF_INCLUDED ? idsc.rifname : riffname; - fname = new char[strlen(GenTex_Directory)+strlen(dir2)+strlen(dir3)+1+strlen(name)+5]; - strcpy(fname,GenTex_Directory); - strcat(fname,dir2); - strcat(fname,dir3); - strcat(fname,"\\"); - strcat(fname,name); - strcat(fname,".BM0"); - delete[] riffname; - #if TRY_OLD_DIRS // temporary until all textures go into subshps directory - FFILE * ftest = ffopen(fname,"rb"); - if (ftest) ffclose(ftest); - else - { - _LOGPUT("WARNING! Not found in SubShps directory\n"); - char const * dir2 = idsc.flags & IDSCF_SPRITE ? "Sprites\\" : ""; - char * riffname = riff_basename(envd); - char const * dir3 = idsc.flags & IDSCF_INCLUDED ? idsc.rifname : riffname; - delete[] fname; - fname = new char[strlen(GenTex_Directory)+strlen(dir2)+strlen(dir3)+1+strlen(name)+5]; - strcpy(fname,GenTex_Directory); - strcat(fname,dir2); - strcat(fname,dir3); - strcat(fname,"\\"); - strcat(fname,name); - strcat(fname,".BM0"); - delete[] riffname; - } - #endif - break; - } - case CLM_TLTPALETTE: - if (!(bflags & ChunkBMPFlag_NotLit)) - { - pg0ext = ".PW0"; - flags.tltpalette = 1; - } - case CLM_GLOBALPALETTE: - { - if (idsc.flags & IDSCF_FIXEDPALETTE) - { - char const * dir2 = idsc.fixrifname ? *idsc.fixrifname ? idsc.fixrifname : 0 : 0; - char const * dir3 = idsc.flags & IDSCF_SPRITE ? "Sprites\\" : ""; - char * riffname = riff_basename(envd); - char const * dir4 = idsc.flags & IDSCF_INCLUDED ? idsc.rifname : riffname; - fname = new char[strlen(FixTex_Directory)+(dir2 ? strlen(dir2)+1 : 0)+strlen(dir3)+strlen(dir4)+1+strlen(name)+5]; - strcpy(fname,FixTex_Directory); - if (dir2) - { - strcat(fname,dir2); - strcat(fname,"\\"); - } - strcat(fname,dir3); - strcat(fname,dir4); - strcat(fname,"\\"); - strcat(fname,name); - strcat(fname,pg0ext); - delete[] riffname; - } - else - { - char const * dir1 = game_mode ? GameTex_Directory : ToolsTex_Directory; - char * dir2 = riff_basename(envd); - char const * dir4 = idsc.flags & IDSCF_SPRITE ? "Sprites\\" : ""; - char const * dir5 = idsc.flags & IDSCF_INCLUDED ? idsc.rifname : 0; - fname = new char[strlen(dir1)+strlen(dir2)+1+(game_mode ? strlen(game_mode)+1 : 0)+strlen(dir4)+(dir5 ? strlen(dir5)+1 : 0)+strlen(name)+5]; - strcpy(fname,dir1); - strcat(fname,dir2); - strcat(fname,"\\"); - if (game_mode) - { - strcat(fname,game_mode); - strcat(fname,"\\"); - } - strcat(fname,dir4); - if (dir5) - { - strcat(fname,dir5); - strcat(fname,"\\"); - } - strcat(fname,name); - strcat(fname,pg0ext); - delete[] dir2; - } - break; - } - } - - if (!fname) - { - _LOGPUT("WARNING! GetPath returning NULL pointer\n"); - } - else - _LOGPRINT(("file expected to be %s\n",fname)); -} - - -CL_Error CL_RIFFImage::Locate(char const * iname, int const enum_id) -{ - _LOGPRINT(("RIF File image finder called for %s, id %d\n",iname,enum_id)); - - if (!Env_Chunk) - _LOGPUT("WARNING! no .RIF file loaded\n"); - - if (!Env_Chunk) return CLE_RIFFERROR; - - switch (imode) - { - case CLM_ATTACHEDPALETTE: - case CLM_16BIT: - case CLM_24BIT: - case CLM_32BIT: - case CLM_GLOBALPALETTE: - case CLM_TLTPALETTE: - break; - default: - _LOGPUT("WARNING! undefined video mode\n"); - return CLE_INVALIDDXMODE; - } - - // remove projectsubdirectory from start of image name if it is there - unsigned int const psdirlen = strlen(projectsubdirectory); - if (!strncmp(projectsubdirectory,iname,psdirlen)) - iname += psdirlen; - - List<Chunk *> envdl (Env_Chunk->lookup_child("REBENVDT")); - - if (!envdl.size()) - { - _LOGPUT("WARNING! no environment data chunk\n"); - return CLE_RIFFERROR; - } - - Environment_Data_Chunk * envd = (Environment_Data_Chunk *) envdl.first_entry(); - - CL_Error retval = CLE_OK; - Environment_Game_Mode_Chunk * egmc = 0; - if (game_mode) - { - if (*game_mode) - { - List<Chunk *> egmcl (envd->lookup_child("GAMEMODE")); - - for (LIF<Chunk *> egmci(&egmcl); !egmci.done(); egmci.next()) - { - Environment_Game_Mode_Chunk * egmcm = (Environment_Game_Mode_Chunk *) egmci(); - if (egmcm->id_equals(game_mode)) - { - egmc = egmcm; - break; - } - } - - if (!egmc) retval = CLE_INVALIDGAMEMODE; - // only returns this error if the game mode cannot be found *and* the image is not listed - } - } - - if (name) - { - delete[] name; - name = 0; - } - if (iname) name = strip_file_extension(strip_path(iname)); - - char * rcname = 0; - if (iname) - { - if (strchr(iname,'\\')) - { - rcname = new char[strlen(iname)+1]; - strcpy(rcname,iname); - *strchr(rcname,'\\')=0; - } - else if (strchr(iname,'/')) - { - rcname = new char[strlen(iname)+1]; - strcpy(rcname,iname); - *strchr(rcname,'/')=0; - } - } - - if (egmc) - { - int shapefoundingm = rcname ? 0 : 1; - // Get the matching image 'Processor' chunk - List<Chunk *> micl = egmc->lookup_child("MATCHIMG"); - - Matching_Images_Chunk * mic = 0; - if (micl.size()) mic = (Matching_Images_Chunk *)micl.first_entry(); - - List<Chunk *> rcl = egmc->lookup_child("RIFCHILD"); - - for (LIF<Chunk *> rci(&rcl); !rci.done(); rci.next()) - { - RIF_Child_Chunk * rcm = (RIF_Child_Chunk *) rci(); - - if (rcname) - { - if (_stricmp(rcname,rcm->rifname) && (*rcname || *rcm->filename)) - continue; - shapefoundingm = 1; - } - - for (LIF<BMP_Flags> bmpfi(&rcm->bmps); !bmpfi.done(); bmpfi.next()) - { - BMP_Flags bmpft(bmpfi()); - strip_file_extension(bmpft.filename); - - if (iname ? !_stricmp(name,strip_path(bmpft.filename)) : enum_id == bmpft.enum_id) - { - // select image descriptor - ImageDescriptor const idsc - ( - *rcm->filename ? - (IDscFlags)((bmpft.flags & ChunkBMPFlag_FixedPalette ? - IDSCF_FIXEDPALETTE - : - IDSCF_0) - |IDSCF_INCLUDED) - : - IDSCF_0, - bmpfi().filename, - *rcm->filename ? rcm->rifname : 0 - ); - ImageDescriptor const * p_idsc = &idsc; - - if (mic) p_idsc = &mic->GetLoadImage(idsc); - else _LOGPRINT(("WARNING! no rule to find matching images in game mode %s\n",egmc->header->mode_identifier)); - - // load this image - GetPath(*p_idsc,envd,bmpft.flags); - - if (fname) - { - if (rcname) - { - delete[] rcname; - rcname = 0; - } - flags.located = 1; - return CLE_OK; - } - } - } - } - - List<Chunk *> ssc = egmc->lookup_child("SHBMPNAM"); - - for (LIF<Chunk *> ssi(&ssc); !ssi.done(); ssi.next()) - { - External_Shape_BMPs_Store_Chunk * ss = (External_Shape_BMPs_Store_Chunk *) ssi(); - - if (rcname) - if (_stricmp(rcname,ss->shapename) && *rcname) - continue; - - for (LIF<BMP_Name> bmpfi(&ss->bmps); !bmpfi.done(); bmpfi.next()) - { - BMP_Name bmpft(bmpfi()); - strip_file_extension(bmpft.filename); - - if (iname ? !_stricmp(name,strip_path(bmpft.filename)) : enum_id == bmpft.enum_id) - { - - // select image descriptor - ImageDescriptor const idsc - ( - (IDscFlags)((bmpft.flags & ChunkBMPFlag_FixedPalette ? - IDSCF_FIXEDPALETTE - : - IDSCF_0) - |(ss->GetExtendedData()->flags & GBF_SPRITE ? - IDSCF_SPRITE - : - IDSCF_SUBSHAPE) - |IDSCF_INCLUDED), - bmpfi().filename, - ss->shapename, - bmpft.flags & ChunkBMPFlag_FixedPalette ? ss->rifname : 0 - ); - ImageDescriptor const * p_idsc = &idsc; - - if (mic) p_idsc = &mic->GetLoadImage(idsc); - else _LOGPRINT(("WARNING! no rule to find matching images in game mode %s\n",egmc->header->mode_identifier)); - - #if TRY_OLD_DIRS // temporary until all textures move to SubShps/All directory - if (*p_idsc == idsc) - { - // select image descriptor - ImageDescriptor const idsc2 - ( - (IDscFlags)((bmpft.flags & ChunkBMPFlag_FixedPalette ? - IDSCF_FIXEDPALETTE - : - IDSCF_0) - |(ss->GetExtendedData()->flags & GBF_SPRITE ? - IDSCF_SPRITE - : - IDSCF_0) - |IDSCF_INCLUDED), - bmpfi().filename, - ss->shapename, - bmpft.flags & ChunkBMPFlag_FixedPalette ? ss->rifname : 0 - ); - ImageDescriptor const * p_idsc2 = &idsc2; - - if (mic) p_idsc2 = &mic->GetLoadImage(idsc2); - else _LOGPRINT(("WARNING! no rule to find matching images in game mode %s\n",egmc->header->mode_identifier)); - - if (*p_idsc2 != idsc2) - { - _LOGPUT("WARNING! Not listed as in SubShps directory\n"); - p_idsc = p_idsc2; - } - } - #endif - - // load this image - GetPath(*p_idsc,envd,bmpft.flags); - - if (fname) - { - if (rcname) - { - delete[] rcname; - rcname = 0; - } - flags.located = 1; - return CLE_OK; - } - } - } - } - - if (rcname) - { - if (!shapefoundingm) - _LOGPRINT(("WARNING! shape/sprite %s not found in this RIF file\n",rcname)); - else - _LOGPRINT(("WARNING! shape/sprite %s does not appear to list %s\n",rcname,name)); - } - - } - - List<Chunk *> micl = envd->lookup_child("MATCHIMG"); - - Matching_Images_Chunk * mic_fix = 0; - Matching_Images_Chunk * mic_nrm = 0; - - for (LIF<Chunk *> mici(&micl); !mici.done(); mici.next()) - { - Matching_Images_Chunk * mic = (Matching_Images_Chunk *)mici(); - if (mic->flags & MICF_FIXEDPALETTE) - mic_fix = mic; - else - mic_nrm = mic; - } - - List<Chunk_With_Children *> shapesandsprites; - - List<Chunk *> shlst = Env_Chunk->lookup_child("REBSHAPE"); - for (LIF<Chunk *> shLIF(&shlst); !shLIF.done(); shLIF.next()) - { - List<Chunk *> shxflst = ((Shape_Chunk *)shLIF())->lookup_child("SHPEXTFL"); - if (shxflst.size()) - { - shapesandsprites.add_entry( (Shape_External_File_Chunk *)shxflst.first_entry() ); - } - } - shlst = Env_Chunk->lookup_child("RSPRITES"); - if (shlst.size()) - { - List<Chunk *> splst = ((Chunk_With_Children *)shlst.first_entry())->lookup_child("SPRIHEAD"); - - for (LIF<Chunk *> spLIF(&splst); !spLIF.done(); spLIF.next()) - { - shapesandsprites.add_entry( (Chunk_With_Children *)spLIF() ); - } - } - - int shapefound = rcname ? 0 : 1; - - for (LIF<Chunk_With_Children *> sasLIF(&shapesandsprites); !sasLIF.done(); sasLIF.next()) - { - char * subrifname = riff_basename(sasLIF()); - - if (rcname) - { - if (_stricmp(subrifname,rcname)) // must match shapes name exactly - { - delete[] subrifname; - continue; - } - shapefound = 1; - } - - List<Chunk *> blsclst = sasLIF()->lookup_child("BMPLSTST"); - if (blsclst.size()) - { - Bitmap_List_Store_Chunk * gbnc = (Bitmap_List_Store_Chunk *) blsclst.first_entry(); - - for (LIF<BMP_Name> bmpni(&gbnc->bmps); !bmpni.done(); bmpni.next()) - { - BMP_Name bmpnt(bmpni()); - strip_file_extension(bmpnt.filename); - - if (iname ? !_stricmp(name,strip_path(bmpnt.filename)) : enum_id == bmpnt.enum_id) - { - - // select image descriptor - char * riffname = riff_basename(envd); - ImageDescriptor const idsc - ( - (IDscFlags)((bmpnt.flags & ChunkBMPFlag_FixedPalette ? - IDSCF_FIXEDPALETTE - : - IDSCF_0) - |(gbnc->GetExtendedData()->flags & GBF_SPRITE ? - IDSCF_SPRITE - : - IDSCF_SUBSHAPE) - |IDSCF_INCLUDED), - bmpni().filename, - subrifname, - bmpnt.flags & ChunkBMPFlag_FixedPalette ? riffname : 0 - ); - ImageDescriptor const * p_idsc = &idsc; - delete[] riffname; - - if (bmpnt.flags & ChunkBMPFlag_FixedPalette) - { - if (mic_fix) p_idsc = &mic_fix->GetLoadImage(idsc); - else _LOGPUT("WARNING! no rule to find fixed palette matching images in environment data\n"); - } - else - { - if (mic_nrm) p_idsc = &mic_nrm->GetLoadImage(idsc); - else _LOGPUT("WARNING! no rule to find matching images in environment data (interface engine?)\n"); - } - - #if TRY_OLD_DIRS // temporary until all textures move to SubShps/All directory - if (*p_idsc == idsc) - { - // select image descriptor - char * riffname = riff_basename(envd); - ImageDescriptor const idsc2 - ( - (IDscFlags)((bmpnt.flags & ChunkBMPFlag_FixedPalette ? - IDSCF_FIXEDPALETTE - : - IDSCF_0) - |(gbnc->GetExtendedData()->flags & GBF_SPRITE ? - IDSCF_SPRITE - : - IDSCF_0) - |IDSCF_INCLUDED), - bmpni().filename, - subrifname, - bmpnt.flags & ChunkBMPFlag_FixedPalette ? riffname : 0 - ); - ImageDescriptor const * p_idsc2 = &idsc2; - delete[] riffname; - - if (bmpnt.flags & ChunkBMPFlag_FixedPalette) - { - if (mic_fix) p_idsc2 = &mic_fix->GetLoadImage(idsc2); - else _LOGPUT("WARNING! no rule to find fixed palette matching images in environment data\n"); - } - else - { - if (mic_nrm) p_idsc2 = &mic_nrm->GetLoadImage(idsc2); - else _LOGPUT("WARNING! no rule to find matching images in environment data (interface engine?)\n"); - } - if (*p_idsc2 != idsc2) - { - _LOGPUT("WARNING! Not listed as in SubShps directory\n"); - p_idsc = p_idsc2; - } - } - #endif - - // load this image - GetPath(*p_idsc,envd,bmpnt.flags); - - if (fname) - { - delete[] subrifname; - if (rcname) - { - delete[] rcname; - rcname = 0; - } - flags.located = 1; - return CLE_OK; - } - } - } - } - delete[] subrifname; - } - - if (rcname) - { - if (!shapefound) - _LOGPRINT(("WARNING! shape/sprite %s not found in this RIF file\n",rcname)); - else - _LOGPRINT(("WARNING! shape/sprite %s does not appear to list %s\n",rcname,name)); - delete[] rcname; - rcname = 0; - } - - // not found in game textures, so look in default - - else // but only if there is no virtual shape directory - { - List<Chunk *> gbncl = envd->lookup_child("BMPNAMES"); - if (gbncl.size()) - { - Global_BMP_Name_Chunk * gbnc = (Global_BMP_Name_Chunk *) gbncl.first_entry(); - - for (LIF<BMP_Name> bmpni(&gbnc->bmps); !bmpni.done(); bmpni.next()) - { - BMP_Name bmpnt(bmpni()); - strip_file_extension(bmpnt.filename); - - if (iname ? !_stricmp(name,strip_path(bmpnt.filename)) : enum_id == bmpnt.enum_id) - { - // select image descriptor - ImageDescriptor const idsc (bmpnt.flags & ChunkBMPFlag_FixedPalette ? IDSCF_FIXEDPALETTE : IDSCF_0, bmpni().filename); - ImageDescriptor const * p_idsc = &idsc; - - if (bmpnt.flags & ChunkBMPFlag_FixedPalette) - { - if (mic_fix) p_idsc = &mic_fix->GetLoadImage(idsc); - else _LOGPUT("WARNING! no rule to find fixed palette matching images in environment data\n"); - } - else - { - if (mic_nrm) p_idsc = &mic_nrm->GetLoadImage(idsc); - else _LOGPUT("WARNING! no rule to find matching images in environment data (interface engine?)\n"); - } - - // load this image - GetPath(*p_idsc,envd,bmpnt.flags); - - if (fname) - { - flags.located = 1; - return CLE_OK; - } - } - } - } - } - - if (retval != CLE_OK) return retval; - return CLE_FINDERROR; -} - - - diff --git a/3dc/win95/CHNKIMAG.HPP b/3dc/win95/CHNKIMAG.HPP deleted file mode 100644 index df0dc62..0000000 --- a/3dc/win95/CHNKIMAG.HPP +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef _included__chnkimag_hpp_ -#define _included__chnkimag_hpp_ - -#error "This file is obsolete" - -#include <stdio.h> - -#include "d3_image.hpp" -#include "mishchnk.hpp" -#include "bmpnames.hpp" - -extern "C" extern char projectsubdirectory[]; - -extern char const * GameTex_Directory; -extern char const * GenTex_Directory; -extern char const * FixTex_Directory; -extern char const * ToolsTex_Directory; - -struct CL_RIFFImage : public CL_Image -{ -public: - static char const * game_mode; // game mode defines palette and set of graphics - can be null or "" for default - - CL_RIFFImage() : CL_Image() {} - CL_RIFFImage(CL_Image const & base) : CL_Image(base) {} - -private: - virtual CL_Error Locate(char const * iname, int const enum_id); - - void GetPath(ImageDescriptor const & idsc, Environment_Data_Chunk * envd, BMPN_Flags bflags); -}; - -#endif // !_included__chnkimag_hpp_ diff --git a/3dc/win95/CHNKLOAD.H b/3dc/win95/CHNKLOAD.H deleted file mode 100644 index 55fd754..0000000 --- a/3dc/win95/CHNKLOAD.H +++ /dev/null @@ -1,233 +0,0 @@ -#ifndef _chnkload_h_ -#define _chnkload_h_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "system.h" -#include "equates.h" -#include "platform.h" -#include "shape.h" -#include "prototyp.h" -#include "module.h" - -extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; - -#define GLS_NOTINLIST (-1) - -/////////////////// -// RIF Loading, etc -/////////////////// - -typedef struct _RifHandle * RIFFHANDLE; -#define INVALID_RIFFHANDLE 0 - -// flags - project specific ones start at lsb -// - generic ones to start from msb - -#define CCF_NOMORPH 0x80000000 - -typedef enum UVCoordType -{ - UVC_SPRITE_U, - UVC_SPRITE_V, - UVC_POLY_U, - UVC_POLY_V, - -} UVCOORDTYPE; - -// Note: for aesthetic reasons, macros enable one to have all one's fuctions in lower case or captialized, to suit one's style! - -// For clarity, functions which are to be defined in project specific files -// are here declared with extern - -///////////////////////////////////////// -// Functions which operate on RIFFHANDLEs -///////////////////////////////////////// - -// load a rif file into memory -RIFFHANDLE load_rif (const char * fname); -RIFFHANDLE load_rif_non_env (const char * fname); -#define LoadRIF(s) load_rif(s) - -// deallocate the shapes, unload the rif, close the handle -void undo_rif_load (RIFFHANDLE); -#define UndoRIFLoad(h) undo_rif_load(h) - -// deallocate the shapes copied from the rif -void deallocate_loaded_shapes (RIFFHANDLE); -#define DeallocateLoadedShapes(h) deallocate_loaded_shapes(h) - -// unloads the rif but keeps the handle and associated copied shapes -void unload_rif (RIFFHANDLE); -#define UnloadRIF(h) unload_rif(h); - -// close the handle - performs tidying up and memory deallocation -void close_rif_handle (RIFFHANDLE); -#define CloseRIFHandle(h) close_rif_handle(h) - -// load textures for environment -BOOL load_rif_bitmaps (RIFFHANDLE, int flags); -#define LoadRIFBitmaps(h,f) load_rif_bitmaps(h,f) - -// set the quantization event depending on CL_RIFFImage::game_mode -BOOL set_quantization_event(RIFFHANDLE, int flags); -#define SetQuantizationEvent(h,f) set_quantization_event(h,f) - -// copy palette -BOOL copy_rif_palette (RIFFHANDLE, int flags); -#define CopyRIFPalette(h,f) copy_rif_palette(h,f) - -// copy texture lighting table -BOOL copy_rif_tlt (RIFFHANDLE, int flags); -#define CopyRIFTLT(h,f) copy_rif_tlt(h,f) - -// copy palette remap table (15-bit) - post_process_shape may use it -BOOL get_rif_palette_remap_table (RIFFHANDLE, int flags); -#define GetRIFPaletteRemapTable(h,f) get_rif_palette_remap_table(h,f) - -// copy one named shape or sprite; does not put in main shape list, needs deallocating -SHAPEHEADER * CopyNamedShapePtr (RIFFHANDLE, char const * shapename); -#define copy_named_shape_ptr(h,s) CopyNamedShapePtr(h,s) - -// copy one named shape or sprite; put it in the main shape list -int CopyNamedShapeMSL (RIFFHANDLE, char const * shapename); -#define copy_named_shape_msl(h,s) CopyNamedShapeMSL(h,s) - -//////////////////////////////////////////////////////////////////////// -// Functions which do not operate on RIFFHANDLEs and may become obsolete -//////////////////////////////////////////////////////////////////////// - -// these functions work on the current rif; they only remain for historical reasons -extern RIFFHANDLE current_rif_handle; -// returns NULL on fail; does not put it in the mainshapelist -SHAPEHEADER * CopyNamedShape (char const * shapename); - -///////////////////////////////////////////// -// Functions for handling the main shape list -///////////////////////////////////////////// - -// reserves the next avaialbe position in the main shape list and returns it -extern int GetMSLPos(void); -#define get_msl_pos() GetMSLPos() - -// frees a position in the main shape list -extern void FreeMSLPos(int); -#define free_msl_pos(i) FreeMSLPos(i) - -//////////////////////////////////////////////// -// Functions retrieving data about loaded shapes -//////////////////////////////////////////////// - -// gets the main shape list position of a shape loaded into the msl -int GetLoadedShapeMSL(char const * shapename); -#define get_loaded_shape_msl(s) GetLoadedShapeMSL(s) -// ditto, but returns a pointer; the shape need not be in the msl -SHAPEHEADER * GetLoadedShapePtr(char const * shapename); -#define get_loaded_shape_ptr(s) GetLoadedShapePtr(s) - -// gets name of shape from msl pos -char const * GetMSLLoadedShapeName(int listpos); -#define get_msl_loaded_shape_name(i) GetMSLLoadedShapeName(i) -// gets name of shape from pointer; the shape need not be in msl -char const * GetPtrLoadedShapeName(SHAPEHEADER *); -#define get_ptr_loaded_shape_name(p) GetPtrLoadedShapeName(p) - -// free a reference to a named shape if it exists - not necessary since these are all tidied up -void FreeShapeNameReference(SHAPEHEADER * shptr); -#define free_shape_name_reference(p) FreeShapeNameReference(p) - -////////////////////////////////////////////////////////////////////////////// -// Initializing, deallocating of shapes, mainly hooks for project specific fns -////////////////////////////////////////////////////////////////////////////// - -// perform initial post processing on shape just after loading -// note that the copy named shape functions will not call this -extern void post_process_shape (SHAPEHEADER *); -#define PostProcessShape(p) post_process_shape(p) - -// hook to perhaps scale the uv coordinates - should return new value -extern int ProcessUVCoord(RIFFHANDLE,UVCOORDTYPE,int uv_value,int image_num); -#define process_uv_coord(h,t,u,i) ProcessUVCoord(h,t,u,i) - -// delete a shape by the shapeheader -void DeallocateLoadedShapePtr(SHAPEHEADER *); -#define deallocate_loaded_shape_ptr(h,p) DeallocateLoadedShapePtr(h,p) - -// delete a shape by the shape list number -void DeallocateLoadedShapeMSL(RIFFHANDLE, int); -#define deallocate_loaded_shape_msl(h,i) DeallocateLoadedShapeMSL(h,i) - -// your function could perform any extra tidying up you need -extern void DeallocateLoadedShapeheader(SHAPEHEADER *); -#define deallocate_loaded_shapeheader(p) DeallocateLoadedShapeHeader(p) - -// your function should call this function which undoes the allocation done when copied from rif data -void DeallocateRifLoadedShapeheader(SHAPEHEADER *); -#define deallocate_rif_loaded_shapeheader(p) DeallocateRifLoadedShapeHeader(p) - -/////// -// Misc -/////// - -// return TRUE if the poly item type corresponds to a textured polygon -BOOL is_textured(int); -#define IsTextured(i) is_textured(i) - -///////////////////// -// Rif loader globals -///////////////////// - -extern unsigned char const * PaletteMapTable; - -///////////////// -// Engine globals -///////////////// - -extern int start_of_loaded_shapes; - -extern unsigned char *TextureLightingTable; - -#if defined(InterfaceEngine) && InterfaceEngine -// this is of crucial importance!! -extern SHAPEHEADER * mainshapelist[]; -#else -extern SHAPEHEADER ** mainshapelist; -#endif - -extern MAPHEADER Map[]; - -extern MAPBLOCK8 Player_and_Camera_Type8[]; -extern MAPBLOCK6 Empty_Landscape_Type6; -extern MAPBLOCK6 Empty_Object_Type6; -extern MAPBLOCK6 Term_Type6; - -extern unsigned char TestPalette[]; - -extern unsigned char LPTestPalette[]; /* to cast to lp*/ - -#if 0 -extern int NumImages; /* # current images */ -extern IMAGEHEADER *ImageHeaderPtrs[]; /* Ptrs to Image Header Blocks */ -extern IMAGEHEADER ImageHeaderArray[]; /* Array of Image Headers */ -extern IMAGEHEADER *NextFreeImageHeaderPtr; -#endif - -#if SupportModules - -extern SCENEMODULE MainScene; -extern MODULE Empty_Module; -extern MODULE Term_Module; - -extern MODULEMAPBLOCK Empty_Module_Map; - -#endif - -#ifdef __cplusplus - -} - -#endif - -#endif diff --git a/3dc/win95/CHNKLOAD.HPP b/3dc/win95/CHNKLOAD.HPP deleted file mode 100644 index 19325dc..0000000 --- a/3dc/win95/CHNKLOAD.HPP +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef _chnkload_hpp -#define _chnkload_hpp 1 - -#include "chnkload.h" - -#ifdef __cplusplus - -#include "chunk.hpp" -#include "shpchunk.hpp" -#include "obchunk.hpp" -#include "bmpnames.hpp" -#include "projload.hpp" - -#if 0 -extern BOOL copy_to_mainshpl (Shape_Chunk *shape, int list_pos); -extern BOOL copy_to_mainshpl (Shape_Sub_Shape_Chunk *shape, int list_pos); -#endif - -extern void copy_to_module (Object_Chunk * ob, int mod_pos, int shplst_pos); - -extern BOOL copy_to_shapeheader ( - RIFFHANDLE, - ChunkShape const & cshp, - SHAPEHEADER *& shphd, - Chunk_With_Children * shape, - int flags, - int local_max_index, - int * local_tex_index_nos, - int listpos = GLS_NOTINLIST, - const ChunkObject* object=0 //object used so that conversion from float to int can be done in world coordinates - ); -extern BOOL copy_preprocessed_to_shapeheader ( - RIFFHANDLE, - Shape_Preprocessed_Data_Chunk*, - SHAPEHEADER *& shphd, - Chunk_With_Children * shape, - int flags, - int local_max_index, - int * local_tex_index_nos, - int listpos = GLS_NOTINLIST, - const ChunkObject* object=0 //object used so that conversion from float to int can be done in world coordinates - ); - -extern BOOL copy_sprite_to_shapeheader (RIFFHANDLE, SHAPEHEADER *& shphd,Sprite_Header_Chunk* shc, int listpos = GLS_NOTINLIST); - - -extern BOOL copy_to_map6(Object_Chunk *,MAPBLOCK6*, int shplst_pos); - -extern void merge_polygons_in_chunkshape (ChunkShape & shp, Shape_Merge_Data_Chunk * smdc); - -extern File_Chunk * Env_Chunk; - -extern double local_scale; - -// copies shape to msl -#if SupportMorphing && LOAD_MORPH_SHAPES -typedef struct -{ - int start_list_pos; - int main_list_pos; - MORPHCTRL * mc; - -} CTM_ReturnType; -#else -typedef int CTM_ReturnType; -#endif - -CTM_ReturnType copy_to_mainshapelist(RIFFHANDLE, Shape_Chunk *, int flags,const ChunkObject* object=0); -#define CopyToMainshapelist(h,r,p,f) copy_to_mainshapelist(h,r,p,f) - -// copies sprite to msl -int copy_sprite_to_mainshapelist(RIFFHANDLE, Sprite_Header_Chunk *, int flags); -#define CopySpriteToMainshapelist(h,p,f) copy_sprite_to_mainshapelist(h,p,f) - -// hook to load a bitmap - so you can load them from test directories, etc. should return tex index -extern int load_rif_bitmap (char const * fname, BMPN_Flags flags); -#define LoadRIFBitmap(s,f) load_rif_bitmap(s,f) - -// project specific shape pre processing - usually merge polys -extern void pre_process_shape (RIFFHANDLE, ChunkShape &, Chunk_With_Children * shape_chunk, int flags); -#define PreProcessShape(h,r,p,f) pre_process_shape(h,r,p,f) - - -struct _RifHandle : Project_RifHandle -{ - File_Chunk * fc; - Environment_Data_Chunk * envd; - Chunk_With_Children * palparent; - List<int> shape_nums; - int max_index; - int * tex_index_nos; - - ~_RifHandle() - {} - _RifHandle() - : fc(0) - , envd(0) - , max_index(0) - , tex_index_nos(0) - , palparent(0) - {} -}; - -#endif - -#endif diff --git a/3dc/win95/CHNKTEXI.CPP b/3dc/win95/CHNKTEXI.CPP deleted file mode 100644 index 640f011..0000000 --- a/3dc/win95/CHNKTEXI.CPP +++ /dev/null @@ -1,940 +0,0 @@ -#include <windows.h> -#include <string.h> -#include <string.hpp> -#ifndef DB_LEVEL - #define DB_LEVEL 4 -#endif -#include "db.h" -#include "awTexLd.h" -#include "chnkload.hpp" -#include "chunkpal.hpp" - -#ifndef CL_SUPPORT_FASTFILE - #error "Please #define CL_SUPPORT_FASTFILE to 0 or 1 in projload.hpp" -#endif -#if CL_SUPPORT_FASTFILE - #include "ffstdio.h" -#endif - -#ifndef CL_SUPPORT_ALTTAB - #error "Please #define CL_SUPPORT_ALTTAB to 0 or 1 in projload.hpp" -#endif -#if CL_SUPPORT_ALTTAB - #include "alt_tab.h" -#endif - -#include "chnktexi.h" - -#if !defined(NDEBUG) && defined(_CPPRTTI) - #include <typeinfo.h> -#else - #define dynamic_cast static_cast -#endif - -char const * cl_pszGameMode = NULL; - -// used to determine if the display is palettized -// currently assuming that if this is <= 8 then all -// surfaces et. except d3d textures have a global palette -extern "C" extern int VideoModeColourDepth; - -// useful filename handling functions - -// returns pointer into string pointing to filename without dirname -template <class C> // C can be char or char const -static C * StripPath(C * n) -{ - C * rm = strrchr(n,':'); - if (rm) n = rm+1; - rm = strrchr(n,'/'); - if (rm) n = rm+1; - rm = strrchr(n,'\\'); - if (rm) n = rm+1; - - return n; -} - -// removes any .extension from filename by inserting null character -static void StripFileExtension(char * n) -{ - char * dotpos = strrchr(n,'.'); - if (dotpos) *dotpos = 0; -} - -static char * StripFileExtension(char const * n) -{ - char * nn = new char[strlen(n)+1]; - strcpy(nn,n); - StripFileExtension(nn); - return nn; -} - -// get the directory associated with the riff - free with delete[] -static char * RiffBasename(Chunk_With_Children * pEnvDataChunk) -{ - Chunk * pChunk = pEnvDataChunk->lookup_single_child("RIFFNAME"); - - if (pChunk) - { - RIF_Name_Chunk * pRifNameChunk = dynamic_cast<RIF_Name_Chunk *>(pChunk); - - const char * pszRifName = StripPath(pRifNameChunk->rif_name); - - char * pszBaseName = new char[strlen(pszRifName)+1]; - strcpy(pszBaseName,pszRifName); - StripFileExtension(pszBaseName); - - return pszBaseName; - } - const char * pszDefault = "empty"; - char * pszBaseName = new char [strlen(pszDefault)+1]; - strcpy(pszBaseName,pszDefault); - - return pszBaseName; -} - -#if CL_SUPPORT_FASTFILE -static inline bool IsFileInFastFile(char const * pszFileName) -{ - unsigned nLen; - return ffreadbuf(pszFileName,&nLen) ? true : false; -} -#endif - -static bool DoesFileExist(char const * pszFileName) -{ - DWORD dwFileAttributes = GetFileAttributes(pszFileName); - - if (0xffffffff == dwFileAttributes || dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - return false; - else - return true; -} - -static char * GetPath(char * pszFileNameBuf, unsigned nBufSize, ImageDescriptor const & idsc, Chunk_With_Children * pEnvDataChunk, bool bGloballyPalettized) -{ - // set the name - char const * pszRawName = StripPath(idsc.filename); - char * pszName = new char[strlen(pszRawName)+1]; - strcpy(pszName,pszRawName); - StripFileExtension(pszName); - - // load this image - char const * pg0ext = ".PG0"; - - if (!bGloballyPalettized) - { - char const * dir2 = idsc.flags & IDSCF_SPRITE ? "Sprites\\" : idsc.flags & IDSCF_SUBSHAPE ? SubShps_Directory : ""; - char * riffname = RiffBasename(pEnvDataChunk); - char const * dir3 = idsc.flags & IDSCF_INCLUDED ? idsc.rifname : riffname; - if (nBufSize < strlen(GenTex_Directory)+strlen(dir2)+strlen(dir3)+1+strlen(pszName)+5) - { - db_log1("CL_LoadImageOnce(): ERROR: buffer not big enough for filename"); - pszFileNameBuf = NULL; - } - else - { - strcpy(pszFileNameBuf,GenTex_Directory); - strcat(pszFileNameBuf,dir2); - strcat(pszFileNameBuf,dir3); - strcat(pszFileNameBuf,"\\"); - strcat(pszFileNameBuf,pszName); - strcat(pszFileNameBuf,".BM0"); - } - delete[] riffname; - } - else - { - if (idsc.flags & IDSCF_FIXEDPALETTE) - { - char const * dir2 = idsc.fixrifname ? *idsc.fixrifname ? idsc.fixrifname : 0 : 0; - char const * dir3 = idsc.flags & IDSCF_SPRITE ? "Sprites\\" : ""; - char * riffname = RiffBasename(pEnvDataChunk); - char const * dir4 = idsc.flags & IDSCF_INCLUDED ? idsc.rifname : riffname; - if (nBufSize < strlen(FixTex_Directory)+(dir2 ? strlen(dir2)+1 : 0)+strlen(dir3)+strlen(dir4)+1+strlen(pszName)+5) - { - db_log1("CL_LoadImageOnce(): ERROR: buffer not big enough for filename"); - pszFileNameBuf = NULL; - } - else - { - strcpy(pszFileNameBuf,FixTex_Directory); - if (dir2) - { - strcat(pszFileNameBuf,dir2); - strcat(pszFileNameBuf,"\\"); - } - strcat(pszFileNameBuf,dir3); - strcat(pszFileNameBuf,dir4); - strcat(pszFileNameBuf,"\\"); - strcat(pszFileNameBuf,pszName); - strcat(pszFileNameBuf,pg0ext); - } - delete[] riffname; - } - else - { - char const * dir1 = cl_pszGameMode ? GameTex_Directory : ToolsTex_Directory; - char * dir2 = RiffBasename(pEnvDataChunk); - char const * dir4 = idsc.flags & IDSCF_SPRITE ? "Sprites\\" : ""; - char const * dir5 = idsc.flags & IDSCF_INCLUDED ? idsc.rifname : 0; - if (nBufSize < strlen(dir1)+strlen(dir2)+1+(cl_pszGameMode ? strlen(cl_pszGameMode)+1 : 0)+strlen(dir4)+(dir5 ? strlen(dir5)+1 : 0)+strlen(pszName)+5) - { - db_log1("CL_LoadImageOnce(): ERROR: buffer not big enough for filename"); - pszFileNameBuf = NULL; - } - else - { - strcpy(pszFileNameBuf,dir1); - strcat(pszFileNameBuf,dir2); - strcat(pszFileNameBuf,"\\"); - if (cl_pszGameMode) - { - strcat(pszFileNameBuf,cl_pszGameMode); - strcat(pszFileNameBuf,"\\"); - } - strcat(pszFileNameBuf,dir4); - if (dir5) - { - strcat(pszFileNameBuf,dir5); - strcat(pszFileNameBuf,"\\"); - } - strcat(pszFileNameBuf,pszName); - strcat(pszFileNameBuf,pg0ext); - } - delete[] dir2; - } - } - - if (pszFileNameBuf) - db_logf4(("\tfile expected to be '%s'",pszFileNameBuf)); - - delete[] pszName; - - return pszFileNameBuf; -} - -char * CL_GetImageFileName(char * pszDestBuf, unsigned nBufSize, char const * pszFileName, unsigned fFlagsEtc) -{ - db_assert1(pszFileName); - db_assert1(pszDestBuf); - db_assert1(nBufSize>0); - db_logf4(("CL_LoadImageOnce(): Getting the full pathname for %s",pszFileName)); - switch (fFlagsEtc & _LIO_PATHTYPEMASK) - { - case LIO_ABSOLUTEPATH: - db_log4("\t(which is an absolute path)"); - if (strlen(pszFileName)<nBufSize) - { - strcpy(pszDestBuf,pszFileName); - return pszDestBuf; - } - else - { - db_log1("CL_LoadImageOnce(): ERROR: buffer not large enough to hold filename"); - return NULL; - } - case LIO_RELATIVEPATH: - db_logf4(("\t(which is a path relative to %s or %s)", - FirstTex_Directory ? FirstTex_Directory : "<not-specified>", - SecondTex_Directory ? SecondTex_Directory : "<not-specified>")); - #define _GET_RELATIVE_PATH(pszDirectory,fnDoesExist) \ - if (pszDirectory) { \ - String str = pszDirectory; \ - if (str.length()) { \ - int chLast = str.get_at(str.length()-1); \ - if (chLast != '\\' && chLast != '/') \ - str += '\\'; \ - str += pszFileName; \ - if (fnDoesExist(str)) { \ - if (str.length() < nBufSize) { \ - strcpy(pszDestBuf,str); \ - return pszDestBuf; \ - } else { \ - db_log1("CL_LoadImageOnce(): ERROR: buffer not large enough to hold filename"); \ - return NULL; /* fail because the buffer isnt big enough */ \ - } } } } - - #if CL_SUPPORT_FASTFILE - _GET_RELATIVE_PATH(FirstTex_Directory,IsFileInFastFile) - _GET_RELATIVE_PATH(SecondTex_Directory,IsFileInFastFile) - #endif - #if !defined(CL_SUPPORTONLY_FASTFILE) || !CL_SUPPORTONLY_FASTFILE - _GET_RELATIVE_PATH(FirstTex_Directory,DoesFileExist) - _GET_RELATIVE_PATH(SecondTex_Directory,DoesFileExist) - #endif - db_log1("CL_LoadImageOnce(): ERROR: file not found in relative path"); - return NULL; - case LIO_RIFFPATH: - { - int enum_id = -1; // may be supported at a later date, valid when pszFileName is NULL - - bool bGloballyPalettized = VideoModeColourDepth <= 8 && (fFlagsEtc & _LIO_SURFTYPEMASK) != LIO_D3DTEXTURE; - - db_log4("\t(whose path is determined by the current .RIF file)"); - if (!Env_Chunk) - { - db_log1("CL_LoadImageOnce(): ERROR: no RIF file"); - return NULL; - } - Chunk * pChunk = Env_Chunk->lookup_single_child("REBENVDT"); - if (!pChunk) - { - db_log1("CL_LoadImageOnce(): ERROR: no environment data chunk"); - return NULL; - } - Chunk_With_Children * pEnvDataChunk = dynamic_cast<Chunk_With_Children *>(pChunk); - db_assert1(pEnvDataChunk); - - Environment_Game_Mode_Chunk * pGameModeChunk = NULL; - if (cl_pszGameMode) - { - if (*cl_pszGameMode) - { - List<Chunk *> listGmChunks; - pEnvDataChunk->lookup_child("GAMEMODE",listGmChunks); - - for (LIF<Chunk *> itGmChunks(&listGmChunks); !itGmChunks.done(); itGmChunks.next()) - { - Environment_Game_Mode_Chunk * pGmChunk = dynamic_cast<Environment_Game_Mode_Chunk *>(itGmChunks()); - db_assert1(pGmChunk); - if (pGmChunk->id_equals(cl_pszGameMode)) - { - pGameModeChunk = pGmChunk; - break; - } - } - - if (!pGameModeChunk) - db_logf3(("CL_LoadImageOnce(): WARNING: Game Mode '%s' not found",cl_pszGameMode)); - } - } - - char * pszName = StripFileExtension(StripPath(pszFileName)); - - char * pszSubName = 0; - if (pszFileName) - { - if (strchr(pszFileName,'\\')) - { - pszSubName = new char[strlen(pszFileName)+1]; - strcpy(pszSubName,pszFileName); - *strchr(pszSubName,'\\')=0; - } - else if (strchr(pszFileName,'/')) - { - pszSubName = new char[strlen(pszFileName)+1]; - strcpy(pszSubName,pszFileName); - *strchr(pszSubName,'/')=0; - } - } - - if (pGameModeChunk) - { - bool bShapeInGm = pszSubName ? false : true; - // Get the matching image 'Processor' chunk - Chunk * pMiChunk = pGameModeChunk->lookup_single_child("MATCHIMG"); - Matching_Images_Chunk * pMatchImageChunk = NULL; - - if (pMiChunk) - { - pMatchImageChunk = dynamic_cast<Matching_Images_Chunk *>(pMiChunk); - db_assert1(pMatchImageChunk); - } - - List<Chunk *> listRifChildChunks; - pGameModeChunk->lookup_child("RIFCHILD",listRifChildChunks); - - for (LIF<Chunk *> itRifChildChunks(&listRifChildChunks); !itRifChildChunks.done(); itRifChildChunks.next()) - { - RIF_Child_Chunk * pRifChildChunk = dynamic_cast<RIF_Child_Chunk *>(itRifChildChunks()); - db_assert1(pRifChildChunk); - - if (pszSubName) - { - if (_stricmp(pszSubName,pRifChildChunk->rifname) && (*pszSubName || *pRifChildChunk->filename)) - continue; - bShapeInGm = true; - } - - for (LIF<BMP_Flags> itBmpFlags(&pRifChildChunk->bmps); !itBmpFlags.done(); itBmpFlags.next()) - { - BMP_Flags bmpfTemp(itBmpFlags()); - StripFileExtension(bmpfTemp.filename); - - if (pszFileName ? !_stricmp(pszName,StripPath(bmpfTemp.filename)) : enum_id == bmpfTemp.enum_id) - { - // select image descriptor - ImageDescriptor const idsc - ( - *pRifChildChunk->filename ? - (IDscFlags)((bmpfTemp.flags & ChunkBMPFlag_FixedPalette ? - IDSCF_FIXEDPALETTE - : - IDSCF_0) - |IDSCF_INCLUDED) - : - IDSCF_0, - itBmpFlags().filename, - *pRifChildChunk->filename ? pRifChildChunk->rifname : 0 - ); - ImageDescriptor const * pIdsc = &idsc; - - if (pMatchImageChunk) pIdsc = &pMatchImageChunk->GetLoadImage(idsc); - else db_logf3(("CL_LoadImageOnce(): WARNING! no rule to find matching images in game mode '%s'\n",pGameModeChunk->header->mode_identifier)); - - // load this image - if (GetPath(pszDestBuf,nBufSize,*pIdsc,pEnvDataChunk,bGloballyPalettized)) - { - if (pszSubName) - { - delete[] pszSubName; - } - delete[] pszName; - return pszDestBuf; - } - } - } - } - - List<Chunk *> listExtShapes; - pGameModeChunk->lookup_child("SHBMPNAM",listExtShapes); - - for (LIF<Chunk *> itExtShapes(&listExtShapes); !itExtShapes.done(); itExtShapes.next()) - { - External_Shape_BMPs_Store_Chunk * pShapeBmpsChunk = dynamic_cast<External_Shape_BMPs_Store_Chunk *>(itExtShapes()); - db_assert1(pShapeBmpsChunk); - - if (pszSubName) - if (_stricmp(pszSubName,pShapeBmpsChunk->shapename) && *pszSubName) - continue; - - for (LIF<BMP_Name> itBmpNames(&pShapeBmpsChunk->bmps); !itBmpNames.done(); itBmpNames.next()) - { - BMP_Name bmpnTemp(itBmpNames()); - StripFileExtension(bmpnTemp.filename); - - if (pszFileName ? !_stricmp(pszName,StripPath(bmpnTemp.filename)) : enum_id == bmpnTemp.enum_id) - { - - // select image descriptor - ImageDescriptor const idsc - ( - (IDscFlags)((bmpnTemp.flags & ChunkBMPFlag_FixedPalette ? - IDSCF_FIXEDPALETTE - : - IDSCF_0) - |(pShapeBmpsChunk->GetExtendedData()->flags & GBF_SPRITE ? - IDSCF_SPRITE - : - IDSCF_SUBSHAPE) - |IDSCF_INCLUDED), - itBmpNames().filename, - pShapeBmpsChunk->shapename, - bmpnTemp.flags & ChunkBMPFlag_FixedPalette ? pShapeBmpsChunk->rifname : 0 - ); - ImageDescriptor const * pIdsc = &idsc; - - if (pMatchImageChunk) pIdsc = &pMatchImageChunk->GetLoadImage(idsc); - else db_logf3(("WARNING! no rule to find matching images in game mode %s\n",pGameModeChunk->header->mode_identifier)); - - // load this image - if (GetPath(pszDestBuf,nBufSize,*pIdsc,pEnvDataChunk,bGloballyPalettized)) - { - if (pszSubName) - { - delete[] pszSubName; - } - delete[] pszName; - return pszDestBuf; - } - } - } - } - - if (pszSubName) - { - if (!bShapeInGm) - db_logf3(("CL_LoadImageOnce(): WARNING! shape/sprite %s not found in this RIF file\n",pszSubName)); - else - db_logf3(("CL_LoadImageOnce(): WARNING! shape/sprite %s does not appear to list %s\n",pszSubName,pszName)); - } - - } - - List<Chunk *> listMatchImageChunk; - pEnvDataChunk->lookup_child("MATCHIMG",listMatchImageChunk); - - Matching_Images_Chunk * pMicFix = NULL; - Matching_Images_Chunk * pMicNorm = NULL; - - for (LIF<Chunk *> itMatchImageChunk(&listMatchImageChunk); !itMatchImageChunk.done(); itMatchImageChunk.next()) - { - Matching_Images_Chunk * pMatchImageChunk = dynamic_cast<Matching_Images_Chunk *>(itMatchImageChunk()); - db_assert1(pMatchImageChunk); - if (pMatchImageChunk->flags & MICF_FIXEDPALETTE) - pMicFix = pMatchImageChunk; - else - pMicNorm = pMatchImageChunk; - } - - List<Chunk_With_Children *> listShapesSprites; - - List<Chunk *> listShapes; - Env_Chunk->lookup_child("REBSHAPE",listShapes); - for (LIF<Chunk *> itShapes(&listShapes); !itShapes.done(); itShapes.next()) - { - Shape_Chunk * pShapeChunk = dynamic_cast<Shape_Chunk *>(itShapes()); - db_assert1(pShapeChunk); - Chunk * pSxfnChunk = pShapeChunk->lookup_single_child("SHPEXTFL"); - if (pSxfnChunk) - { - Shape_External_File_Chunk * pShpExtFnameChunk = dynamic_cast<Shape_External_File_Chunk *>(pSxfnChunk); - db_assert1(pShpExtFnameChunk); - listShapesSprites.add_entry(pShpExtFnameChunk); - } - } - Chunk * pSprChunk = Env_Chunk->lookup_single_child("RSPRITES"); - if (pSprChunk) - { - Chunk_With_Children * pSpritesChunk = dynamic_cast<Chunk_With_Children *>(pSprChunk); - db_assert1(pSpritesChunk); - - List<Chunk *> listSprHeadChunks; - pSpritesChunk->lookup_child("SPRIHEAD",listSprHeadChunks); - - for (LIF<Chunk *> itSprites(&listSprHeadChunks); !itSprites.done(); itSprites.next()) - { - Chunk_With_Children * pSpriteHead = dynamic_cast<Chunk_With_Children *>(itSprites()); - db_assert1(pSpriteHead); - listShapesSprites.add_entry(pSpriteHead); - } - } - - int bShapeFound = pszSubName ? false : true; - - for (LIF<Chunk_With_Children *> itShapesSprites(&listShapesSprites); !itShapesSprites.done(); itShapesSprites.next()) - { - char * pszSubRifName = RiffBasename(itShapesSprites()); - - if (pszSubName) - { - if (_stricmp(pszSubRifName,pszSubName)) // must match shapes name exactly - { - delete[] pszSubRifName; - continue; - } - bShapeFound = true; - } - - Chunk * pBmpLstStChunk = itShapesSprites()->lookup_single_child("BMPLSTST"); - if (pBmpLstStChunk) - { - Bitmap_List_Store_Chunk * pBmpListStoreChunk = dynamic_cast<Bitmap_List_Store_Chunk *>(pBmpLstStChunk); - db_assert1(pBmpListStoreChunk); - - for (LIF<BMP_Name> itBmpName(&pBmpListStoreChunk->bmps); !itBmpName.done(); itBmpName.next()) - { - BMP_Name bmpnTemp(itBmpName()); - StripFileExtension(bmpnTemp.filename); - - if (pszFileName ? !_stricmp(pszName,StripPath(bmpnTemp.filename)) : enum_id == bmpnTemp.enum_id) - { - - // select image descriptor - char * pszRifName = RiffBasename(pEnvDataChunk); - ImageDescriptor const idsc - ( - (IDscFlags)((bmpnTemp.flags & ChunkBMPFlag_FixedPalette ? - IDSCF_FIXEDPALETTE - : - IDSCF_0) - |(pBmpListStoreChunk->GetExtendedData()->flags & GBF_SPRITE ? - IDSCF_SPRITE - : - IDSCF_SUBSHAPE) - |IDSCF_INCLUDED), - itBmpName().filename, - pszSubRifName, - bmpnTemp.flags & ChunkBMPFlag_FixedPalette ? pszRifName : 0 - ); - ImageDescriptor const * pIdsc = &idsc; - delete[] pszRifName; - - if (bmpnTemp.flags & ChunkBMPFlag_FixedPalette) - { - if (pMicFix) pIdsc = &pMicFix->GetLoadImage(idsc); - else db_log3("CL_LoadImageOnce(): WARNING! no rule to find fixed palette matching images in environment data\n"); - } - else - { - if (pMicNorm) pIdsc = &pMicNorm->GetLoadImage(idsc); - else db_log3("CL_LoadImageOnce(): WARNING! no rule to find matching images in environment data (interface engine?)\n"); - } - - // load this image - if (GetPath(pszDestBuf,nBufSize,*pIdsc,pEnvDataChunk,bGloballyPalettized)) - { - delete[] pszSubRifName; - if (pszSubName) - { - delete[] pszSubName; - } - delete[] pszName; - return pszDestBuf; - } - } - } - } - delete[] pszSubRifName; - } - - if (pszSubName) - { - if (!bShapeFound) - db_logf3(("CL_LoadImageOnce(): WARNING! shape/sprite %s not found in this RIF file\n",pszSubName)); - else - db_logf3(("CL_LoadImageOnce(): WARNING! shape/sprite %s does not appear to list %s\n",pszSubName,pszName)); - delete[] pszSubName; - } - - // not found in game textures, so look in default - - else // but only if there is no virtual shape directory - { - Chunk * pBmpNames = pEnvDataChunk->lookup_single_child("BMPNAMES"); - if (pBmpNames) - { - Global_BMP_Name_Chunk * pGbnc = dynamic_cast<Global_BMP_Name_Chunk *>(pBmpNames); - db_assert1(pGbnc); - - for (LIF<BMP_Name> itBmpName(&pGbnc->bmps); !itBmpName.done(); itBmpName.next()) - { - BMP_Name bmpnTemp(itBmpName()); - StripFileExtension(bmpnTemp.filename); - - if (pszFileName ? !_stricmp(pszName,StripPath(bmpnTemp.filename)) : enum_id == bmpnTemp.enum_id) - { - // select image descriptor - ImageDescriptor const idsc (bmpnTemp.flags & ChunkBMPFlag_FixedPalette ? IDSCF_FIXEDPALETTE : IDSCF_0, itBmpName().filename); - ImageDescriptor const * pIdsc = &idsc; - - if (bmpnTemp.flags & ChunkBMPFlag_FixedPalette) - { - if (pMicFix) pIdsc = &pMicFix->GetLoadImage(idsc); - else db_log3("CL_LoadImageOnce(): WARNING! no rule to find fixed palette matching images in environment data\n"); - } - else - { - if (pMicNorm) pIdsc = &pMicNorm->GetLoadImage(idsc); - else db_log3("CL_LoadImageOnce(): WARNING! no rule to find matching images in environment data (interface engine?)\n"); - } - - // load this image - if (GetPath(pszDestBuf,nBufSize,*pIdsc,pEnvDataChunk,bGloballyPalettized)) - { - delete[] pszName; - return pszDestBuf; - } - } - } - } - } - delete[] pszName; - return NULL; - } - default: // invalid arguments - db_log1("CL_LoadImageOnce(): ERROR: invalid parameter passed to CL_GetImageFileName()"); - return NULL; - } -} - -extern "C" extern void CheckForWindowsMessages(void); - -int CL_LoadImageOnce(char const * pszFileName, unsigned fFlagsEtc) -{ - // safe to handle windows messages at this point (I think - JCWH) - CheckForWindowsMessages(); - - // get the filename - char szBuf[MAX_PATH]; - if (!CL_GetImageFileName(szBuf,sizeof szBuf/sizeof szBuf[0],pszFileName,fFlagsEtc)) - { - db_log1("CL_LoadImageOnce(): ERROR: unable to determine path of file"); - return GEI_NOTLOADED; - } - - db_logf4(("\tLoading '%s'",szBuf)); - - // already loaded ? - int iExistingImage = GetExistingImageNum(szBuf); - if (GEI_NOTLOADED != iExistingImage) - { - db_logf4(("\tImage already loaded to image number %d",iExistingImage)); - return iExistingImage; - } - - // what flags do we want? - unsigned fAwLoad = AW_TLF_DEFAULT; - if (fFlagsEtc & LIO_VIDMEM) - fAwLoad |= AW_TLF_VIDMEM; - if (fFlagsEtc & LIO_TRANSPARENT) - fAwLoad |= AW_TLF_TRANSP; - if (fFlagsEtc & LIO_CHROMAKEY) - fAwLoad |= AW_TLF_CHROMAKEY; - if (fFlagsEtc & LIO_LOADMIPMAPS) - db_log1("CL_LoadImageOnce(): WARNING: mip maps not supported yet - will not be created/loaded"); - - // what are we loading into ? - switch (fFlagsEtc & _LIO_SURFTYPEMASK) - { - case LIO_CHIMAGE: - { - db_log1("CL_LoadImageOnce(): WARNING: having to call LoadImageCH()"); - IMAGEHEADER * pImageHdr = GetImageHeader(); - db_assert1(pImageHdr); - memset(pImageHdr,0,sizeof(IMAGEHEADER)); - if (LoadImageCH(szBuf,pImageHdr)) - return NumImages-1; - else - { - db_log1("CL_LoadImageOnce(): ERROR: LoadImageCH() failed"); - return GEI_NOTLOADED; - } - } - case LIO_DDSURFACE: - { - #if CL_SUPPORT_FASTFILE - unsigned nFastFileLen; - void const * pFastFileData = ffreadbuf(szBuf,&nFastFileLen); - if (pFastFileData) - { - db_log4("\tfile is in a fast file"); - unsigned nWidth, nHeight; - AW_BACKUPTEXTUREHANDLE hBackup = NULL; - DDSurface * pSurface = - AwCreateSurface - ( - fFlagsEtc & LIO_RESTORABLE ? "pxfXYB" : "pxfXY", - pFastFileData, - nFastFileLen, - fAwLoad, - &nWidth, - &nHeight, - &hBackup - ); - if (pSurface) - { - IMAGEHEADER * pImageHdr = GetImageHeader(); - db_assert1(pImageHdr); - memset(pImageHdr,0,sizeof(IMAGEHEADER)); - pImageHdr->ImageWidth = nWidth; - pImageHdr->ImageHeight = nHeight; - db_assert1(sizeof pImageHdr->ImageName / sizeof pImageHdr->ImageName[0] > strlen(szBuf)); - strcpy(pImageHdr->ImageName,szBuf); - pImageHdr->DDSurface = pSurface; - pImageHdr->hBackup = hBackup; - db_logf4(("\tloaded to image number %d",NumImages-1)); - #if CL_SUPPORT_ALTTAB - if (fFlagsEtc & LIO_RESTORABLE) - #ifdef NDEBUG - ATIncludeSurface(pSurface,hBackup); - #else - { - char szDbInf[512]; - sprintf(szDbInf,"Name \"%s\" Number %d",szBuf,NumImages-1); - ATIncludeSurfaceDb(pSurface,hBackup,szDbInf); - } - #endif - #endif // CL_SUPPORT_ALTTAB - return NumImages-1; - } - else - { - db_log1("CL_LoadImageOnce(): ERROR copying data to surface"); - return GEI_NOTLOADED; - } - } - else - #endif // CL_SUPPORT_FASTFILE - { - #if !defined(CL_SUPPORTONLY_FASTFILE) || !CL_SUPPORTONLY_FASTFILE - db_log4("\tloading the actual file"); - unsigned nWidth, nHeight; - AW_BACKUPTEXTUREHANDLE hBackup = NULL; - DDSurface * pSurface = - AwCreateSurface - ( - fFlagsEtc & LIO_RESTORABLE ? "sfXYB" : "sfXY", - &szBuf[0], - fAwLoad, - &nWidth, - &nHeight, - &hBackup - ); - if (pSurface) - { - IMAGEHEADER * pImageHdr = GetImageHeader(); - db_assert1(pImageHdr); - memset(pImageHdr,0,sizeof(IMAGEHEADER)); - pImageHdr->ImageWidth = nWidth; - pImageHdr->ImageHeight = nHeight; - db_assert1(sizeof pImageHdr->ImageName / sizeof pImageHdr->ImageName[0] > strlen(szBuf)); - strcpy(pImageHdr->ImageName,szBuf); - pImageHdr->DDSurface = pSurface; - pImageHdr->hBackup = hBackup; - db_logf4(("\tloaded to image number %d",NumImages-1)); - db_logf4(("\t\tsurface:%p",pSurface)); - #if CL_SUPPORT_ALTTAB - if (fFlagsEtc & LIO_RESTORABLE) - #ifdef NDEBUG - ATIncludeSurface(pSurface,hBackup); - #else - { - char szDbInf[512]; - sprintf(szDbInf,"Name \"%s\" Number %d",szBuf,NumImages-1); - ATIncludeSurfaceDb(pSurface,hBackup,szDbInf); - } - #endif - #endif // CL_SUPPORT_ALTTAB - return NumImages-1; - } - else - { - db_log1("CL_LoadImageOnce(): ERROR copying data to surface"); - return GEI_NOTLOADED; - } - #elif !CL_SUPPORT_FASTFILE - #error "CL_SUPPORTONLY_FASTFILE set but CL_SUPPORT_FASTFILE not set" - #endif // !CL_SUPPORTONLY_FASTFILE - } - //db_msg1("THIS CODE SHOULD BE UNREACHABLE"); - } - case LIO_D3DTEXTURE: - { - fAwLoad |= AW_TLF_COMPRESS; // required on some cards!! - #if CL_SUPPORT_FASTFILE - unsigned nFastFileLen; - void const * pFastFileData = ffreadbuf(szBuf,&nFastFileLen); - if (pFastFileData) - { - db_log4("\tfile is in a fast file"); - unsigned nWidth, nHeight; - AW_BACKUPTEXTUREHANDLE hBackup = NULL; - D3DTexture * pTexture = - AwCreateTexture - ( - fFlagsEtc & LIO_RESTORABLE ? "pxfWHB" : "pxfWH", - pFastFileData, - nFastFileLen, - fAwLoad, - &nWidth, - &nHeight, - &hBackup - ); - if (pTexture) - { - IMAGEHEADER * pImageHdr = GetImageHeader(); - db_assert1(pImageHdr); - memset(pImageHdr,0,sizeof(IMAGEHEADER)); - pImageHdr->ImageWidth = nWidth; - pImageHdr->ImageHeight = nHeight; - db_assert1(sizeof pImageHdr->ImageName / sizeof pImageHdr->ImageName[0] > strlen(szBuf)); - strcpy(pImageHdr->ImageName,szBuf); - pImageHdr->D3DTexture = pTexture; - pImageHdr->hBackup = hBackup; - db_logf4(("\tloaded to image number %d",NumImages-1)); - - /* KJL 16:05:50 26/02/98 - attempt to get a texture handle */ - { - int gotTextureHandle = GetTextureHandle(pImageHdr); - db_assert1(gotTextureHandle==TRUE); - } - - #if CL_SUPPORT_ALTTAB - if (fFlagsEtc & LIO_RESTORABLE) - #ifdef NDEBUG - ATIncludeTexture(pTexture,hBackup); - #else - { - char szDbInf[512]; - sprintf(szDbInf,"Name \"%s\" Number %d",szBuf,NumImages-1); - ATIncludeTextureDb(pTexture,hBackup,szDbInf); - } - #endif - #endif // CL_SUPPORT_ALTTAB - return NumImages-1; - } - else - { - db_log1("CL_LoadImageOnce(): ERROR copying data to texture"); - return GEI_NOTLOADED; - } - } - else - #endif // CL_SUPPORT_FASTFILE - { - #if !defined(CL_SUPPORTONLY_FASTFILE) || !CL_SUPPORTONLY_FASTFILE - db_log4("\tloading the actual file"); - unsigned nWidth, nHeight; - AW_BACKUPTEXTUREHANDLE hBackup = NULL; - D3DTexture * pTexture = - AwCreateTexture - ( - fFlagsEtc & LIO_RESTORABLE ? "sfWHB" : "sfWH", - &szBuf[0], - fAwLoad, - &nWidth, - &nHeight, - &hBackup - ); - if (pTexture) - { - IMAGEHEADER * pImageHdr = GetImageHeader(); - db_assert1(pImageHdr); - memset(pImageHdr,0,sizeof(IMAGEHEADER)); - pImageHdr->ImageWidth = nWidth; - pImageHdr->ImageHeight = nHeight; - db_assert1(sizeof pImageHdr->ImageName / sizeof pImageHdr->ImageName[0] > strlen(szBuf)); - strcpy(pImageHdr->ImageName,szBuf); - pImageHdr->D3DTexture = pTexture; - pImageHdr->hBackup = hBackup; - db_logf4(("\tloaded to image number %d",NumImages-1)); - - /* KJL 16:05:50 26/02/98 - attempt to get a texture handle */ - { - int gotTextureHandle = GetTextureHandle(pImageHdr); - db_assert1(gotTextureHandle==TRUE); - } - - #if CL_SUPPORT_ALTTAB - if (fFlagsEtc & LIO_RESTORABLE) - #ifdef NDEBUG - ATIncludeTexture(pTexture,hBackup); - #else - { - char szDbInf[512]; - sprintf(szDbInf,"Name \"%s\" Number %d",szBuf,NumImages-1); - ATIncludeTextureDb(pTexture,hBackup,szDbInf); - } - #endif - #endif // CL_SUPPORT_ALTTAB - return NumImages-1; - } - else - { - db_log1("CL_LoadImageOnce(): ERROR copying data to texture"); - return GEI_NOTLOADED; - } - #elif !CL_SUPPORT_FASTFILE - #error "CL_SUPPORTONLY_FASTFILE set but CL_SUPPORT_FASTFILE not set" - #endif // !CL_SUPPORTONLY_FASTFILE - } - //db_msg1("THIS CODE SHOULD BE UNREACHABLE"); - } - default: - db_log1("CL_LoadImageOnce(): ERROR: Invalid destination surface specification"); - return GEI_NOTLOADED; - } -} - diff --git a/3dc/win95/CHNKTEXI.H b/3dc/win95/CHNKTEXI.H deleted file mode 100644 index 88a6b7e..0000000 --- a/3dc/win95/CHNKTEXI.H +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef _INCLUDED_CHNKTEXI_H_ -#define _INCLUDED_CHNKTEXI_H_ - -#ifdef __cplusplus - extern "C" { -#endif /* __cplusplus */ - -/* image number for already loaded image - really an internal function */ -#define GEI_NOTLOADED (-1) -extern int GetExistingImageNum(char const * pszActualFileName); - -enum /* flags, etc */ -{ - /* destination surface type */ - LIO_CHIMAGE = 0x00000000U, /* Chris Humphries texture */ - LIO_DDSURFACE = 0x00000001U, /* Direct Draw Surface */ - LIO_D3DTEXTURE = 0x00000002U, /* Direct 3D Texture */ - _LIO_SURFTYPEMASK= 0x00000003U, - /* target memory type for DDSURFACE only - D3DTextures dest depends on driver */ - LIO_SYSMEM = 0x00000000U, /* system memory */ - LIO_VIDMEM = 0x00000004U, /* video memory */ - /* transparency flags - unless specified in the file */ - LIO_NONTRANSP = 0x00000000U, /* no transparency */ - LIO_TRANSPARENT = 0x00000008U, /* has transparency */ - /* alpha or chroma key? */ - LIO_USEALPHA = 0x00000000U, /* use alpha mask if available instead of chroma keying */ - LIO_CHROMAKEY = 0x00000010U, /* use chroma key even if surface has alpha channel */ - /* path flags */ - LIO_ABSOLUTEPATH = 0x00000000U, /* path is correct */ - LIO_RELATIVEPATH = 0x00000020U, /* path is relative to a textures directory */ - LIO_RIFFPATH = 0x00000040U, /* current RIF file used to build path and extension */ - _LIO_PATHTYPEMASK= 0x00000060U, - /* mip maps? */ - LIO_NOMIPMAPS = 0x00000000U, /* no mip maps */ - LIO_LOADMIPMAPS = 0x00000080U, /* load mip maps if available */ - /* restorable ? */ - LIO_NORESTORE = 0x00000000U, /* not going to be restorable */ - LIO_RESTORABLE = 0x00000100U, /* put something in imageheader to allow restoring */ -}; - -/* CL_LoadImageOnce relies on this value to be 1 greater - than the index of the last loaded image */ -extern int NumImages; - -/* directories used with the LIO_RIFFPATH flag */ -extern char const * GameTex_Directory; -extern char const * SubShps_Directory; -extern char const * GenTex_Directory; -extern char const * FixTex_Directory; -extern char const * ToolsTex_Directory; - -/* game mode for use with the above */ -extern char const * cl_pszGameMode; - -/* directories used with the LIO_RELATIVEPATH flag - these are searched in order*/ -extern char const * FirstTex_Directory; -extern char const * SecondTex_Directory; - -/* returns GEI_NOTLOADED on failure */ -extern int CL_LoadImageOnce(char const * pszFileName, unsigned fFlagsEtc); - -/* returns NULL on failure, or pointer to pszDestBuf on success, nBufSize includes nul terminator */ -extern char * CL_GetImageFileName(char * pszDestBuf, unsigned nBufSize, char const * pszFileName, unsigned fFlagsEtc); - -#ifdef __cplusplus - } -#endif /* __cplusplus */ - -#endif /* !_INCLUDED_CHNKTEXI_H_ */ diff --git a/3dc/win95/CHNKTYPE.CPP b/3dc/win95/CHNKTYPE.CPP deleted file mode 100644 index bddaaae..0000000 --- a/3dc/win95/CHNKTYPE.CPP +++ /dev/null @@ -1,1221 +0,0 @@ -#include "chunk.hpp" -#include <math.h> -#include "chnktype.hpp" - -#if engine - -#define UseLocalAssert No -#include "ourasert.h" -#define assert(x) GLOBALASSERT(x) - -#else - -#if cencon -#include "ccassert.h" -#else -#include <assert.h> -#endif - -#endif - -#ifdef cencon -#define new my_new -#endif - -// misc data structures functions -BOOL operator==(const obinfile &o1, const obinfile &o2) -{ - return (&o1 == &o2); -} -BOOL operator!=(const obinfile &o1, const obinfile &o2) -{ - return (&o1 != &o2); -} - -BOOL operator==(const shpinfile &s1, const shpinfile &s2) -{ - return (&s1 == &s2); -} -BOOL operator!=(const shpinfile &s1, const shpinfile &s2) -{ - return (&s1 != &s2); -} - -BOOL operator== (const ChunkUV_List &c1, const ChunkUV_List &c2) -{ - return(&c1 == &c2); -} - -BOOL operator!= (const ChunkUV_List &c1, const ChunkUV_List &c2) -{ - return(&c1 != &c2); -} - -BOOL operator== (const ObjectID &o1, const ObjectID &o2) -{ - return((o1.id1==o2.id1) && (o1.id2==o2.id2)); -} - -BOOL operator!= (const ObjectID &o1, const ObjectID &o2) -{ - return((o1.id1!=o2.id1) || (o1.id2!=o2.id2)); -} - -ObjectID Minimum(const ObjectID &o1,const ObjectID &o2) -{ - if(o1.id1<o2.id1) return o1; - if(o1.id1>o2.id1) return o2; - if(o1.id2<o2.id2) return o1; - return o2; -} -////////////////////////////////////////////// -#define CHUNK_MAX_UVINDEX ((1<<20)-1) -#define CHUNK_MAX_TEXTUREINDEX ((1<<12)-1) - -#define CHUNK_UVINDEX_MASK 0xfffff000 -#define CHUNK_TEXTUREINDEX_MASK 0xfff -#define CHUNK_NEWUVINDEX_BITS 0x0000f000 - -unsigned int ChunkPoly::GetUVIndex() -{ - if(colour & CHUNK_NEWUVINDEX_BITS) - { - unsigned int uv_index; - uv_index=(colour & CHUNK_NEWUVINDEX_BITS) << 4; - uv_index|= (colour >> 16); - - return uv_index; - } - else - { - //uvindex is just in the top 16 bits - return (colour >> 16); - } - -} - -unsigned int ChunkPoly::GetTextureIndex() -{ - return (colour & CHUNK_TEXTUREINDEX_MASK); -} - -void ChunkPoly::SetUVIndex(unsigned int uv_index) -{ - assert(uv_index<=CHUNK_MAX_UVINDEX); - //clear the old uvindex - colour &=~CHUNK_UVINDEX_MASK; - - if(uv_index<65536) - { - //fit uv index into the top 16 bits if it will fit , to maintain compatibility with - //old chunk loaders - colour |= (uv_index<<16); - } - else - { - //put the bottom 16 bits of the uv_index in the top 16 bits of the colour - colour |= (uv_index & 0xffff) << 16; - //put the next 4 bits of the uv_index in the lower middle 4 bits of the colour - uv_index>>=16; - colour |= (uv_index <<12); - } - -} - -void ChunkPoly::SetTextureIndex(unsigned int texture_index) -{ - assert(texture_index<=CHUNK_MAX_TEXTUREINDEX); - - colour &=~ CHUNK_TEXTUREINDEX_MASK; - colour |= texture_index; -} - - - -////////////////////////////////////////////// - -ChunkVector operator+(const ChunkVector& a, const ChunkVector& b) -{ - ChunkVector v; - v.x=a.x+b.x; - v.y=a.y+b.y; - v.z=a.z+b.z; - return v; -} - - -ChunkVector operator-(const ChunkVector& a, const ChunkVector& b) -{ - ChunkVector v; - v.x=a.x-b.x; - v.y=a.y-b.y; - v.z=a.z-b.z; - return v; -} - -ChunkVector& ChunkVector::operator+=(const ChunkVector& a) -{ - x += a.x; - y += a.y; - z += a.z; - - return *this; -} - - - -ChunkVector& ChunkVector::operator-=(const ChunkVector& a) -{ - x -= a.x; - y -= a.y; - z -= a.z; - - return *this; -} - - - -#if engine -ChunkVector::operator VECTORCH () const -{ - VECTORCH v; - v.vx = x; - v.vy = y; - v.vz = z; - - return(v); -} -#endif -ChunkVector::operator ChunkVectorInt () const -{ - ChunkVectorInt v; - v.x = (int)x; - v.y = (int)y; - v.z = (int)z; - - return(v); -} -ChunkVector::operator ChunkVectorFloat () const -{ - ChunkVectorFloat v; - v.x = (float)x; - v.y = (float)y; - v.z = (float)z; - - return(v); -} - -ChunkVector operator*(const ChunkVector & a, const double s) -{ - ChunkVector v; - v.x = a.x * s; - v.y = a.y * s; - v.z = a.z * s; - return(v); - -} - -ChunkVector operator/(const ChunkVector & a, const double s) -{ - ChunkVector v; - v.x = a.x / s; - v.y = a.y / s; - v.z = a.z / s; - return(v); -} - -ChunkVector operator*(const ChunkVector& a, const ChunkVector& b) -{ - ChunkVector v; - v.x=a.y*b.z - a.z*b.y; - v.y=a.z*b.x - a.x*b.z; - v.z=a.x*b.y - a.y*b.x; - return v; -} - - -double dot(const ChunkVector& a, const ChunkVector& b) -{ - return(a.x*b.x + a.y*b.y + a.z*b.z); -} - -double mod(const ChunkVector& a) -{ - return(sqrt(dot(a,a))); -} - -int ChunkVector::norm() -{ - double modulos = mod(*this); - - if(modulos == 0)return(0); - - x /=modulos; - y /= modulos; - z /= modulos; - - return(1); - -} -////////////////////////////////////////////// -ChunkVectorInt operator+(const ChunkVectorInt& a, const ChunkVectorInt& b) -{ - ChunkVectorInt v; - v.x=a.x+b.x; - v.y=a.y+b.y; - v.z=a.z+b.z; - return v; -} - - -ChunkVectorInt operator-(const ChunkVectorInt& a, const ChunkVectorInt& b) -{ - ChunkVectorInt v; - v.x=a.x-b.x; - v.y=a.y-b.y; - v.z=a.z-b.z; - return v; -} - -ChunkVectorInt& ChunkVectorInt::operator+=(const ChunkVectorInt& a) -{ - x += a.x; - y += a.y; - z += a.z; - - return *this; -} - - - -ChunkVectorInt& ChunkVectorInt::operator-=(const ChunkVectorInt& a) -{ - x -= a.x; - y -= a.y; - z -= a.z; - - return *this; -} - - - -#if engine -ChunkVectorInt::operator VECTORCH () const -{ - VECTORCH v; - v.vx = x; - v.vy = y; - v.vz = z; - - return(v); -} -#endif - -ChunkVectorInt operator*(const ChunkVectorInt & a, const double s) -{ - ChunkVectorInt v; - v.x =(int) (a.x * s); - v.y =(int) (a.y * s); - v.z =(int) (a.z * s); - return(v); - -} - -ChunkVectorInt operator/(const ChunkVectorInt & a, const double s) -{ - ChunkVectorInt v; - v.x =(int) (a.x / s); - v.y =(int) (a.y / s); - v.z =(int) (a.z / s); - return(v); -} - -double mod(const ChunkVectorInt& a) -{ - return(sqrt((double)a.x*(double)a.x+(double)a.y*(double)a.y+(double)a.z*(double)a.z)); -} - -int ChunkVectorInt::norm() -{ - double modulos = mod(*this) /65536.0; - - if(modulos == 0)return(0); - - x =(int) (x/modulos); - y =(int) (y/modulos); - z =(int) (z/modulos); - - return(1); - -} -//////////////////////////////////////////////////////// -ChunkVectorFloat operator+(const ChunkVectorFloat& a, const ChunkVectorFloat& b) -{ - ChunkVectorFloat v; - v.x=a.x+b.x; - v.y=a.y+b.y; - v.z=a.z+b.z; - return v; -} - - -ChunkVectorFloat operator-(const ChunkVectorFloat& a, const ChunkVectorFloat& b) -{ - ChunkVectorFloat v; - v.x=a.x-b.x; - v.y=a.y-b.y; - v.z=a.z-b.z; - return v; -} - -ChunkVectorFloat& ChunkVectorFloat::operator+=(const ChunkVectorFloat& a) -{ - x += a.x; - y += a.y; - z += a.z; - - return *this; -} - - - -ChunkVectorFloat& ChunkVectorFloat::operator-=(const ChunkVectorFloat& a) -{ - x -= a.x; - y -= a.y; - z -= a.z; - - return *this; -} - -ChunkVectorFloat operator*(const ChunkVectorFloat & a, const double s) -{ - ChunkVectorFloat v; - v.x =(float) (a.x * s); - v.y =(float) (a.y * s); - v.z =(float) (a.z * s); - return(v); - -} - -ChunkVectorFloat operator/(const ChunkVectorFloat & a, const double s) -{ - ChunkVectorFloat v; - v.x =(float) (a.x / s); - v.y =(float) (a.y / s); - v.z =(float) (a.z / s); - return(v); -} - -#if engine -ChunkVectorFloat::operator VECTORCH () const -{ - VECTORCH v; - v.vx =(int) (x*65536); - v.vy =(int) (y*65536); - v.vz =(int) (z*65536); - - return(v); -} -#endif -int ChunkVectorFloat::norm() -{ - float modulos =(float) mod(*this); - - if(modulos == 0)return(0); - - x /= modulos; - y /= modulos; - z /= modulos; - - return(1); -} -double mod(const ChunkVectorFloat& a) -{ - return(sqrt((double)a.x*(double)a.x+(double)a.y*(double)a.y+(double)a.z*(double)a.z)); -} -//////////////////////////////////////////////////////// -ChunkShape::~ChunkShape() -{ - - if (v_list) delete [] v_list; - if (v_normal_list) delete [] v_normal_list; - if (p_normal_list) delete [] p_normal_list; - if (poly_list) delete [] poly_list; - if (uv_list) delete [] uv_list; - if (texture_fns) - for (int i = 0; i<num_texfiles; i++) - if (texture_fns[i]) delete texture_fns[i]; - - #if UseOldChunkLoader - if(float_v_list) delete float_v_list; - #endif -} - -ChunkShape::ChunkShape() -{ - num_polys = 0; - num_verts = 0; - num_uvs = 0; - num_texfiles = 0; - - v_list = 0; - v_normal_list = 0; - p_normal_list = 0; - poly_list = 0; - uv_list = 0; - texture_fns = 0; - - radius_about_centre=0; - - #if UseOldChunkLoader - float_v_list=0; - #endif -} - - -ChunkShape::ChunkShape(const ChunkShape &shp) -{ - int i; - - radius = shp.radius; - max = shp.max; - min = shp.min; - num_polys = shp.num_polys; - num_verts = shp.num_verts; - num_uvs = shp.num_uvs; - num_texfiles = shp.num_texfiles; - - if (shp.v_list) { - v_list = new ChunkVectorInt [num_verts]; - for (i=0; i<num_verts; i++) - v_list[i] = shp.v_list[i]; - } - else v_list = 0; - - if (shp.v_normal_list) { - v_normal_list = new ChunkVectorFloat [num_verts]; - for (i=0; i<num_verts; i++) - v_normal_list[i] = shp.v_normal_list[i]; - } - else v_normal_list = 0; - - if (shp.p_normal_list) { - p_normal_list = new ChunkVectorFloat [num_polys]; - for (i=0; i<num_polys; i++) - p_normal_list[i] = shp.p_normal_list[i]; - } - else p_normal_list = 0; - - if (shp.poly_list) { - poly_list = new ChunkPoly [num_polys]; - for (i=0; i<num_polys; i++) - poly_list[i] = shp.poly_list[i]; - } - else poly_list = 0; - - if (shp.uv_list) { - uv_list = new ChunkUV_List [num_uvs]; - for (i=0; i<num_uvs; i++) - uv_list[i] = shp.uv_list[i]; - } - else uv_list = 0; - - if (shp.texture_fns) { - texture_fns = new char * [num_texfiles]; - for (i=0; i<num_texfiles; i++) { - texture_fns[i] = new char [strlen (shp.texture_fns[i]) + 1]; - strcpy (texture_fns[i], shp.texture_fns[i]); - } - } - else texture_fns = 0; - - centre=shp.centre; - radius_about_centre=shp.radius_about_centre; - - #if UseOldChunkLoader - float_v_list=0; - #endif -} - -ChunkShape& ChunkShape::operator=(const ChunkShape &shp) -{ - int i; - - if (v_list) delete [] v_list; - if (v_normal_list) delete [] v_normal_list; - if (p_normal_list) delete [] p_normal_list; - if (poly_list) delete [] poly_list; - if (uv_list) delete [] uv_list; - if (texture_fns) - for (int i = 0; i<num_texfiles; i++) - if (texture_fns[i]) delete texture_fns[i]; - - radius = shp.radius; - max = shp.max; - min = shp.min; - num_polys = shp.num_polys; - num_verts = shp.num_verts; - num_uvs = shp.num_uvs; - num_texfiles = shp.num_texfiles; - - - - if (shp.v_list) { - v_list = new ChunkVectorInt [num_verts]; - for (i=0; i<num_verts; i++) - v_list[i] = shp.v_list[i]; - } - else v_list = 0; - - if (shp.v_normal_list) { - v_normal_list = new ChunkVectorFloat [num_verts]; - for (i=0; i<num_verts; i++) - v_normal_list[i] = shp.v_normal_list[i]; - } - else v_normal_list = 0; - - if (shp.p_normal_list) { - p_normal_list = new ChunkVectorFloat [num_polys]; - for (i=0; i<num_polys; i++) - p_normal_list[i] = shp.p_normal_list[i]; - } - else p_normal_list = 0; - - if (shp.poly_list) { - poly_list = new ChunkPoly [num_polys]; - for (i=0; i<num_polys; i++) - poly_list[i] = shp.poly_list[i]; - } - else poly_list = 0; - - if (shp.uv_list) { - uv_list = new ChunkUV_List [num_uvs]; - for (i=0; i<num_uvs; i++) - uv_list[i] = shp.uv_list[i]; - } - else uv_list = 0; - - if (shp.texture_fns) { - texture_fns = new char * [num_texfiles]; - for (i=0; i<num_texfiles; i++) { - texture_fns[i] = new char [strlen (shp.texture_fns[i]) + 1]; - strcpy (texture_fns[i], shp.texture_fns[i]); - } - } - else texture_fns = 0; - - centre=shp.centre; - radius_about_centre=shp.radius_about_centre; - - #if UseOldChunkLoader - if(float_v_list) delete float_v_list; - float_v_list=0; - #endif - - return *this; - -} - -void ChunkShape::rescale (double scale) -{ - int i; - - if (v_list) - { - for (i=0; i<num_verts; i++) - { - v_list[i].x =(int) (v_list[i].x*scale); - v_list[i].y =(int) (v_list[i].y*scale); - v_list[i].z =(int) (v_list[i].z*scale); - } - } - - radius =(float) (radius*scale); - max.x =(int) (max.x*scale); - max.y =(int) (max.y*scale); - max.z =(int) (max.z*scale); - - min.x =(int) (min.x*scale); - min.y =(int) (min.y*scale); - min.z =(int) (min.z*scale); - - centre=centre*scale; - radius_about_centre=(float) (radius_about_centre*scale); - -} - - -VMod_Arr_Item::VMod_Arr_Item() -{ - #if UseOldChunkLoader - o_name = 0; - #endif -} - -VMod_Arr_Item::~VMod_Arr_Item() -{ - #if UseOldChunkLoader - if (o_name) - delete o_name; - #endif -} - -VMod_Arr_Item::VMod_Arr_Item(const VMod_Arr_Item & vma) -{ - #if UseOldChunkLoader - if (vma.o_name) - { - o_name = new char [strlen(vma.o_name)+1]; - strcpy (o_name, vma.o_name); - } - else - { - o_name = 0; - } - #endif - - branch_no = vma.branch_no; - flags = vma.flags; - spare = vma.spare; - object_index=vma.object_index; -} - -VMod_Arr_Item& VMod_Arr_Item::operator=(const VMod_Arr_Item & vma) -{ - if (&vma == this) return(*this); - - #if UseOldChunkLoader - if (o_name) - delete o_name; - - if (vma.o_name) - { - o_name = new char [strlen(vma.o_name)+1]; - strcpy (o_name, vma.o_name); - } - else - { - o_name = 0; - } - #endif - - branch_no = vma.branch_no; - flags = vma.flags; - spare = vma.spare; - object_index=vma.object_index; - - return(*this); - -} - -BOOL operator==(const VMod_Arr_Item & vm1, const VMod_Arr_Item & vm2) -{ - return(&vm1 == &vm2); - -} - -BOOL operator!=(const VMod_Arr_Item & vm1, const VMod_Arr_Item & vm2) -{ - return(&vm1 != &vm2); - -} - -/////////////////////////////////////// - -Adjacent_Module::Adjacent_Module() -{ - flags = 0; - #if UseOldChunkLoader - o_name = 0; - #endif - entry_point.x=0; - entry_point.y=0; - entry_point.z=0; -} - -Adjacent_Module::~Adjacent_Module() -{ - #if UseOldChunkLoader - if (o_name) - delete o_name; - #endif -} - -Adjacent_Module::Adjacent_Module(const Adjacent_Module & am) -{ - #if UseOldChunkLoader - if (am.o_name) - { - o_name = new char [strlen(am.o_name)+1]; - strcpy (o_name, am.o_name); - } - else - { - o_name = 0; - } - #endif - object_index=am.object_index; - flags = am.flags; - entry_point = am.entry_point; -} - -Adjacent_Module& Adjacent_Module::operator=(const Adjacent_Module & am) -{ - if (&am == this) return(*this); - - #if UseOldChunkLoader - if (o_name) - delete o_name; - - if (am.o_name) - { - o_name = new char [strlen(am.o_name)+1]; - strcpy (o_name, am.o_name); - } - else - { - o_name = 0; - } - #endif - - object_index=am.object_index; - flags = am.flags; - entry_point = am.entry_point; - - return(*this); - -} - -BOOL operator==(const Adjacent_Module & am1, const Adjacent_Module & am2) -{ - return(&am1 == &am2); -} - -BOOL operator!=(const Adjacent_Module & am1, const Adjacent_Module & am2) -{ - return(&am1 != &am2); -} - - -/////////////////////////////////////// - -BOOL operator==(poly_change_info const &f1, poly_change_info const &f2) -{ - return(&f1 == &f2); -} - -BOOL operator!=(poly_change_info const &f1, poly_change_info const &f2) -{ - return(&f1 != &f2); -} - - -////////////////////////////////////////////// -ChunkAnimFrame::~ChunkAnimFrame() -{ - if(name) delete [] name; - if(v_list) delete [] v_list; - if(p_normal_list) delete [] p_normal_list; - -} - -ChunkAnimFrame::ChunkAnimFrame() -{ - name=0; - num_polys=0; - num_verts=0; - v_list=0; - p_normal_list=0; - flags=num_interp_frames=pad3=pad4=0; -} - -ChunkAnimFrame::ChunkAnimFrame(const ChunkAnimFrame & frm) -{ - - if(frm.name) - { - name=new char[strlen(frm.name)+1]; - strcpy(name,frm.name); - } - else - name=0; - - num_polys=frm.num_polys; - num_verts=frm.num_verts; - - if(num_polys) - { - p_normal_list=new ChunkVectorFloat[num_polys]; - for(int i=0;i<num_polys;i++) - { - p_normal_list[i]=frm.p_normal_list[i]; - } - } - else - p_normal_list=0; - - if(num_verts) - { - v_list=new ChunkVectorInt[num_verts]; - for(int i=0;i<num_verts;i++) - { - v_list[i]=frm.v_list[i]; - } - } - else - v_list=0; - flags=frm.flags; - num_interp_frames=frm.num_interp_frames; - pad3=frm.pad3; - pad4=frm.pad4; -} -/* -ChunkAnimFrame::ChunkAnimFrame(ChunkAnimFrame* startframe,ChunkAnimFrame* endframe,int startwt,int endwt,ChunkShape const *cs) -{ - name=0; - num_polys=startframe->num_polys; - num_verts=startframe->num_verts; - flags=startframe->flags|animframeflag_interpolated_frame; - num_interp_frames=0; - pad3=0; - pad4=0; - - v_list=new ChunkVector[num_verts]; - p_normal_list=new ChunkVector[num_polys]; - - double start_mult=startwt/(double)(startwt+endwt); - double end_mult=endwt/(double)(startwt+endwt); - - for(int i=0;i<num_verts;i++) - { - v_list[i].x=startframe->v_list[i].x*start_mult+endframe->v_list[i].x*end_mult; - v_list[i].y=startframe->v_list[i].y*start_mult+endframe->v_list[i].y*end_mult; - v_list[i].z=startframe->v_list[i].z*start_mult+endframe->v_list[i].z*end_mult; - } - - for(i=0;i<num_polys;i++) - { - ChunkVector v1=cs->v_list[cs->poly_list[i].vert_ind[1]]-cs->v_list[cs->poly_list[i].vert_ind[0]]; - ChunkVector v2=cs->v_list[cs->poly_list[i].vert_ind[2]]-cs->v_list[cs->poly_list[i].vert_ind[0]]; - ChunkVector norm; - norm.x=v1.y*v2.z-v1.z*v2.y; - norm.y=v1.z*v2.x-v1.x*v2.z; - norm.z=v1.x*v2.y-v1.y*v2.x; - double length=sqrt(norm.x*norm.x+norm.y*norm.y+norm.z*norm.z); - cs->p_normal_list[i]=norm*(1/length); - } - -} -*/ -ChunkAnimFrame& ChunkAnimFrame::operator=(const ChunkAnimFrame &frm) -{ - - if(name) delete [] name; - if(v_list) delete [] v_list; - if(p_normal_list) delete [] p_normal_list; - - - if(frm.name) - { - name=new char[strlen(frm.name)+1]; - strcpy(name,frm.name); - } - else - name=0; - - num_polys=frm.num_polys; - num_verts=frm.num_verts; - - if(num_polys) - { - p_normal_list=new ChunkVectorFloat[num_polys]; - for(int i=0;i<num_polys;i++) - { - p_normal_list[i]=frm.p_normal_list[i]; - } - } - else - p_normal_list=0; - - if(num_verts) - { - v_list=new ChunkVectorInt[num_verts]; - for(int i=0;i<num_verts;i++) - { - v_list[i]=frm.v_list[i]; - } - } - else - v_list=0; - flags=frm.flags; - num_interp_frames=frm.num_interp_frames; - pad3=frm.pad3; - pad4=frm.pad4; - return *this; -} - - -ChunkAnimSequence::~ChunkAnimSequence() -{ - if(name) delete [] name; - for(int i=0;i<NumFrames;i++) - { - if(Frames[i])delete Frames[i]; - } - if(Frames) delete [] Frames; - if(v_normal_list) delete [] v_normal_list; -} - -ChunkAnimSequence::ChunkAnimSequence() -{ - SequenceNum=-1; - name=0; - NumFrames=0; - Frames=0; - flags=pad2=pad3=pad4=0; - - num_verts=0; - v_normal_list=0; - min.x=min.y=min.z=0; - max.x=max.y=max.z=0; - radius=0; - -} -ChunkAnimSequence::ChunkAnimSequence(const ChunkAnimSequence & seq) -{ - SequenceNum=seq.SequenceNum; - - if(seq.name) - { - name=new char[strlen(seq.name)+1]; - strcpy(name,seq.name); - - } - else - name=0; - - NumFrames=seq.NumFrames; - if(NumFrames) - { - Frames=new ChunkAnimFrame*[NumFrames]; - for(int i=0;i<NumFrames;i++) - { - Frames[i]=new ChunkAnimFrame(*seq.Frames[i]); - } - } - else - Frames=0; - - flags=seq.flags; - pad2=seq.pad2; - pad3=seq.pad3; - pad4=seq.pad4; - - num_verts=seq.num_verts; - if(num_verts) - { - v_normal_list=new ChunkVectorFloat[num_verts]; - for(int i=0;i<num_verts;i++) - { - v_normal_list[i]=seq.v_normal_list[i]; - } - } - else v_normal_list=0; - min=seq.min; - max=seq.max; - radius=seq.radius; -} - -ChunkAnimSequence& ChunkAnimSequence::operator=(const ChunkAnimSequence &seq) -{ - if(name) delete [] name; - if(Frames) delete [] Frames; - if(v_normal_list) delete [] v_normal_list; - SequenceNum=seq.SequenceNum; - - if(seq.name) - { - name=new char[strlen(seq.name)+1]; - strcpy(name,seq.name); - - } - else - name=0; - - NumFrames=seq.NumFrames; - if(NumFrames) - { - Frames=new ChunkAnimFrame*[NumFrames]; - for(int i=0;i<NumFrames;i++) - { - Frames[i]=new ChunkAnimFrame(*seq.Frames[i]); - } - } - else - Frames=0; - - flags=seq.flags; - pad2=seq.pad2; - pad3=seq.pad3; - pad4=seq.pad4; - - num_verts=seq.num_verts; - if(num_verts) - { - v_normal_list=new ChunkVectorFloat[num_verts]; - for(int i=0;i<num_verts;i++) - { - v_normal_list[i]=seq.v_normal_list[i]; - } - } - else v_normal_list=0; - min=seq.min; - max=seq.max; - radius=seq.radius; - return *this; -} - - -void ChunkAnimSequence::UpdateNormalsAndExtents(ChunkShape const * cs,List<int>* poly_not_in_bb) -{ - if(!cs) return; - num_verts=cs->num_verts; - if(!v_normal_list)v_normal_list=new ChunkVectorFloat[cs->num_verts]; - for(int i=0;i<num_verts;i++) - { - v_normal_list[i].x=0; - v_normal_list[i].y=0; - v_normal_list[i].z=0; - } - for(i=0;i<cs->num_polys;i++) - { - const ChunkPoly* cp=&cs->poly_list[i]; - for(int j=0;j<cp->num_verts;j++) - { - int vi=cp->vert_ind[j]; - for(int k=0;k<NumFrames;k++) - { - v_normal_list[vi]+=Frames[k]->p_normal_list[i]; - } - } - } - for(i=0;i<num_verts;i++) - { - double length=mod(v_normal_list[i]); - if(length) - { - v_normal_list[i]=v_normal_list[i]/length; - } - else - { - v_normal_list[i].x=1; - v_normal_list[i].y=0; - v_normal_list[i].z=0; - } - } - - - max.x = -2000000000; - max.y = -2000000000; - max.z = -2000000000; - - min.x = 2000000000; - min.y = 2000000000; - min.z = 2000000000; - - radius = 0; - - int* vert_in_bb=0; - if(poly_not_in_bb) - { - vert_in_bb=new int[cs->num_verts]; - for(i=0;i<cs->num_verts;i++) - { - vert_in_bb[i]=0; - } - for(i=0;i<cs->num_polys;i++) - { - if(poly_not_in_bb->contains(i))continue; - const ChunkPoly* cp=&cs->poly_list[i]; - for(int j=0;j<cp->num_verts;j++) - { - vert_in_bb[cp->vert_ind[j]]=1; - } - - } - } - for(i=0;i<NumFrames;i++) - { - ChunkAnimFrame* caf=Frames[i]; - for (int j=0; j<caf->num_verts; j++) - { - if(vert_in_bb && !vert_in_bb[j]) continue; - max.x = max(max.x, caf->v_list[j].x); - max.y = max(max.y, caf->v_list[j].y); - max.z = max(max.z, caf->v_list[j].z); - - min.x = min(min.x, caf->v_list[j].x); - min.y = min(min.y, caf->v_list[j].y); - min.z = min(min.z, caf->v_list[j].z); - - double temp_rad = mod(caf->v_list[j]); - - radius = max (radius, (float)temp_rad); - } - } - if(vert_in_bb) delete [] vert_in_bb; -} - -void ChunkAnimSequence::DeleteInterpolatedFrames() -{ - int NewNumFrames=NumFrames; - for(int i=0;i<NumFrames;i++) - { - if(Frames[i]->flags & animframeflag_interpolated_frame)NewNumFrames--; - } - if(NewNumFrames==NumFrames)return; - - int framepos=0; - for(i=0;i<NumFrames;i++) - { - if(Frames[i]->flags & animframeflag_interpolated_frame) continue; - Frames[framepos++]=Frames[i]; - } - NumFrames=NewNumFrames; - Frames=(ChunkAnimFrame**)realloc(Frames,sizeof(ChunkAnimFrame*)*NumFrames); - -} - -void ChunkAnimSequence::GenerateInterpolatedFrames(ChunkShape const *cs) -{ - DeleteInterpolatedFrames(); - /* - int NewNumFrames=NumFrames; - for(int i=0;i<NumFrames;i++) - { - NewNumFrames+=Frames[i]->num_interp_frames; - } - if(NewNumFrames==NumFrames) return; - - ChunkAnimFrame** NewFrames=new ChunkAnimFrame*[NewNumFrames]; - - int framepos=0; - for( i=0;i<NumFrames;i++ ) - { - NewFrames[framepos++]=Frames[i]; - if(Frames[i]->num_interp_frames==0)continue; - - ChunkAnimFrame* startframe=Frames[i]; - ChunkAnimFrame* endframe=Frames[(i+1)%NumFrames]; - - for(int j=0;j<startframe->num_interp_frames;j++) - { - NewFrames[framepos++]=new ChunkAnimFrame(startframe,endframe,startframe->num_interp_frames-j,j+1,cs); - } - } - delete [] Frames; - Frames=NewFrames; - NumFrames=NewNumFrames; - */ -}
\ No newline at end of file diff --git a/3dc/win95/CHNKTYPE.HPP b/3dc/win95/CHNKTYPE.HPP deleted file mode 100644 index 9a3a57d..0000000 --- a/3dc/win95/CHNKTYPE.HPP +++ /dev/null @@ -1,396 +0,0 @@ -#ifndef _chnktype_hpp -#define _chnktype_hpp 1 - -#if engine -#include "3dc.h" -#endif -#include "list_tem.hpp" - -struct ChunkVectorInt; -struct ChunkVectorFloat; - -struct ChunkVector -{ - - double x; - double y; - double z; - - - ChunkVector friend operator+(const ChunkVector&, const ChunkVector&); - ChunkVector friend operator-(const ChunkVector&, const ChunkVector&); - ChunkVector& operator+=(const ChunkVector&); - ChunkVector& operator-=(const ChunkVector&); - - ChunkVector friend operator*(const ChunkVector&, const double); - ChunkVector friend operator/(const ChunkVector&, const double); - - ChunkVector friend operator*(const ChunkVector&, const ChunkVector&); //cross prod - - - - #if engine - operator VECTORCH () const; - #endif - operator ChunkVectorInt () const; - operator ChunkVectorFloat () const; - - friend double dot(const ChunkVector&, const ChunkVector&);//dot product - friend double mod(const ChunkVector&);//magnitude of vector - int norm(); //normalize -}; - -struct ChunkVectorInt -{ - - int x; - int y; - int z; - - - ChunkVectorInt friend operator+(const ChunkVectorInt&, const ChunkVectorInt&); - ChunkVectorInt friend operator-(const ChunkVectorInt&, const ChunkVectorInt&); - ChunkVectorInt& operator+=(const ChunkVectorInt&); - ChunkVectorInt& operator-=(const ChunkVectorInt&); - - ChunkVectorInt friend operator*(const ChunkVectorInt&, const double); - ChunkVectorInt friend operator/(const ChunkVectorInt&, const double); - - //ChunkVectorInt friend operator*(const ChunkVectorInt&, const ChunkVectorInt&); //cross prod - - - - #if engine - operator VECTORCH () const; - #endif - - //friend double dot(const ChunkVector&, const ChunkVector&);//dot product - friend double mod(const ChunkVectorInt&);//magnitude of vector - int norm(); //normalize to 65536 -}; -struct ChunkVectorFloat -{ - - float x; - float y; - float z; - - ChunkVectorFloat friend operator+(const ChunkVectorFloat&, const ChunkVectorFloat&); - ChunkVectorFloat friend operator-(const ChunkVectorFloat&, const ChunkVectorFloat&); - ChunkVectorFloat& operator+=(const ChunkVectorFloat&); - ChunkVectorFloat& operator-=(const ChunkVectorFloat&); - - ChunkVectorFloat friend operator*(const ChunkVectorFloat&, const double); - ChunkVectorFloat friend operator/(const ChunkVectorFloat&, const double); - - //ChunkVectorInt friend operator*(const ChunkVectorInt&, const ChunkVectorInt&); //cross prod - #if engine - operator VECTORCH () const; - #endif - - //friend double dot(const ChunkVector&, const ChunkVector&);//dot product - friend double mod(const ChunkVectorFloat&);//magnitude of vector - int norm(); //normalize to 1 -}; - -struct ChunkUV -{ - - float u; - float v; - -}; - -// in integers I suppose - -struct ChunkMatrix -{ - - int mat11; - int mat12; - int mat13; - - int mat21; - int mat22; - int mat23; - - int mat31; - int mat32; - int mat33; - -}; - - -struct ChunkUV_List -{ - int num_verts; - ChunkUV vert[4]; - - // for list iterator - friend BOOL operator== (const ChunkUV_List &, const ChunkUV_List &); - friend BOOL operator!= (const ChunkUV_List &, const ChunkUV_List &); - -}; - -class ChunkPoly -{ -public: - - int engine_type; - int normal_index; - int flags; - unsigned int colour; - - int num_verts; - - int vert_ind[4]; - - - //functions for gettings and setting texture and uv indeces in the colour - unsigned int GetUVIndex(); - unsigned int GetTextureIndex(); - - void SetUVIndex(unsigned int uv_index); - void SetTextureIndex(unsigned int texture_index); - - -}; - - -struct ChunkShape -{ - ChunkShape(); - ~ChunkShape(); - - ChunkShape (const ChunkShape &); - ChunkShape& operator=(const ChunkShape &); - - - float radius; //radius of points about 0,0,0 - - ChunkVectorInt max; - ChunkVectorInt min; - - ChunkVectorInt centre; //average of min and max - float radius_about_centre; - - int num_verts; - ChunkVectorInt * v_list; - - #if UseOldChunkLoader - ChunkVector * float_v_list; - #endif - - //int num_vert_normals; //I don't think num_vert_normals is ever used - ChunkVectorFloat * v_normal_list; - - int num_polys; - ChunkPoly * poly_list; - ChunkVectorFloat * p_normal_list; - - int num_uvs; - ChunkUV_List * uv_list; - - int num_texfiles; - char ** texture_fns; - - void rescale (double); - -}; - -struct ChunkQuat -{ - float x,y,z,w; -}; - - -struct ObjectID -{ - int id1; - int id2; - - friend BOOL operator== (const ObjectID &, const ObjectID &); - friend BOOL operator!= (const ObjectID &, const ObjectID &); - friend ObjectID Minimum(const ObjectID &,const ObjectID &); - -}; - -struct ChunkObject -{ - - ChunkVectorInt location; - - #if UseOldChunkLoader - ChunkVector float_location; - #endif - - ChunkQuat orientation; - - BOOL is_base_object; - - char o_name[50]; - - int index_num; //this won't get changed by update_my_chunkobject - - ObjectID ID; - -}; - - -struct VMod_Arr_Item -{ - VMod_Arr_Item(); - ~VMod_Arr_Item(); - - VMod_Arr_Item(const VMod_Arr_Item & vma); - VMod_Arr_Item & operator=(const VMod_Arr_Item & vma); - - int branch_no; - int flags; - int spare; - int object_index; - - #if UseOldChunkLoader - char * o_name; //replaced by object_index - #endif - - friend BOOL operator==(const VMod_Arr_Item &, const VMod_Arr_Item &); - friend BOOL operator!=(const VMod_Arr_Item &, const VMod_Arr_Item &); - -}; - -struct Adjacent_Module -{ - Adjacent_Module(); - ~Adjacent_Module(); - - Adjacent_Module(const Adjacent_Module & vma); - Adjacent_Module & operator=(const Adjacent_Module & vma); - - int flags; - ChunkVectorInt entry_point; - int object_index; - - #if UseOldChunkLoader - char * o_name; - #endif - - friend BOOL operator==(const Adjacent_Module & am1, const Adjacent_Module & am2); - friend BOOL operator!=(const Adjacent_Module & am1, const Adjacent_Module & am2); - -}; - -class Shape_Chunk; -class Shape_Sub_Shape_Chunk; - -struct a_frame -{ - a_frame() - : shape1a (0), shape1b(0), shape2a(0), shape2b(0) - {} - - Shape_Sub_Shape_Chunk * shape1a; - Shape_Chunk * shape1b; - Shape_Sub_Shape_Chunk * shape2a; - Shape_Chunk * shape2b; - int spare; -}; - - -// Data structures for bits and pieces - -struct obinfile -{ - int filepos; - char name[50]; - size_t length; - - friend BOOL operator==(const obinfile &o1, const obinfile &o2); - friend BOOL operator!=(const obinfile &o1, const obinfile &o2); -}; - -struct shpinfile -{ - int filepos; - int id; - size_t length; - - friend BOOL operator==(const shpinfile &s1, const shpinfile &s2); - friend BOOL operator!=(const shpinfile &s1, const shpinfile &s2); -}; - - -struct poly_change_info -{ - int poly_num; - int vert_num_before; - int vert_num_after; - - friend BOOL operator==(poly_change_info const &f1, poly_change_info const &f2); - friend BOOL operator!=(poly_change_info const &f1, poly_change_info const &f2); -}; - - - -#define animframeflag_not_in_psx 0x00000001 -#define animframeflag_not_in_saturn 0x00000002 -#define animframeflag_interpolated_frame 0x00000004 -struct ChunkAnimFrame -{ - ChunkAnimFrame(); - ~ChunkAnimFrame(); - - ChunkAnimFrame(const ChunkAnimFrame &); - //constructor for interpolated frame - //ChunkAnimFrame(ChunkAnimFrame* startframe,ChunkAnimFrame* endframe,int startwt,int endwt,ChunkShape const *cs); - ChunkAnimFrame& operator=(const ChunkAnimFrame &); - - - char* name; - - int num_polys; - int num_verts; - - ChunkVectorInt * v_list; - ChunkVectorFloat * p_normal_list; - - int flags; - int num_interp_frames; - int pad3,pad4; -}; - - -#define animseqflag_not_in_psx 0x00000001 -#define animseqflag_not_in_saturn 0x00000002 - - -struct ChunkAnimSequence -{ - ChunkAnimSequence(); - ~ChunkAnimSequence(); - - ChunkAnimSequence (const ChunkAnimSequence &); - ChunkAnimSequence& operator=(const ChunkAnimSequence &); - - void DeleteInterpolatedFrames(); - void GenerateInterpolatedFrames(ChunkShape const *cs); - - void UpdateNormalsAndExtents(ChunkShape const *cs,List<int>* poly_not_in_bb=0); - - int SequenceNum; - char* name; - - int NumFrames; - ChunkAnimFrame** Frames; - - int flags; - int pad2,pad3,pad4; - - ChunkVectorInt min; - ChunkVectorInt max; - float radius; - - int num_verts; - ChunkVectorFloat* v_normal_list; -}; -#endif
\ No newline at end of file diff --git a/3dc/win95/CHUNKPAL.CPP b/3dc/win95/CHUNKPAL.CPP deleted file mode 100644 index 0cf1185..0000000 --- a/3dc/win95/CHUNKPAL.CPP +++ /dev/null @@ -1,1007 +0,0 @@ -#include "chunkpal.hpp" -#include "mishchnk.hpp" - -#if engine - -#ifndef UseLocalAssert -#define UseLocalAssert 1 -#endif -#include "ourasert.h" -#define assert(x) GLOBALASSERT(x) - -#else - -#if cencon -#include "ccassert.h" -#else -#include <assert.h> -#endif - -#endif -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(chunkpal) - -/////////////////////////////////////// - -// Class Environment_Palette_Chunk functions - - -void Palette_Outdated(Chunk_With_Children * parent) -{ - if (parent) - { - List<Chunk *> plist; - parent->lookup_child("ENVPALET",plist); - for (LIF<Chunk *> plit(&plist); !plit.done(); plit.next()) - { - ((Environment_Palette_Chunk *)plit())->flags &= ~EnvPalFlag_UpToDate; - } - } -} - -void FixedPalette_Outdated(Chunk_With_Children * parent) -{ - if (parent) - { - List<Chunk *> plist; - parent->lookup_child("PRSETPAL",plist); - for (LIF<Chunk *> plit(&plist); !plit.done(); plit.next()) - { - for (LIF<Preset_Palette> findconst(&((Preset_Palette_Chunk *)plit())->pplist); !findconst.done(); findconst.next()) - { - Preset_Palette temp = findconst(); - if (temp.flags & PrePalFlag_Reserved) - { - temp.flags &= ~PrePalFlag_UpToDate; - findconst.change_current(temp); - } - } - } - } -} - -BOOL IsFixedPalette(Chunk_With_Children * parent) -{ - if (parent) - { - List<Chunk *> plist; - parent->lookup_child("PRSETPAL",plist); - for (LIF<Chunk *> plit(&plist); !plit.done(); plit.next()) - { - for (LIF<Preset_Palette> findconst(&((Preset_Palette_Chunk *)plit())->pplist); !findconst.done(); findconst.next()) - { - if (findconst().flags & PrePalFlag_Reserved) - { - return TRUE; - } - } - } - parent->lookup_child("SETPALST",plist); - for (plit = LIF<Chunk *> (&plist); !plit.done(); plit.next()) - { - for (LIF<Preset_Palette> findconst(&((Preset_Palette_Store_Chunk *)plit())->pplist); !findconst.done(); findconst.next()) - { - if (findconst().flags & PrePalFlag_Reserved) - { - return TRUE; - } - } - } - } - return FALSE; -} - -RIF_IMPLEMENT_DYNCREATE("ENVPALET",Environment_Palette_Chunk) - -Environment_Palette_Chunk::~Environment_Palette_Chunk () -{ - if (pixel_data) - { - unsigned char * temp_pd = (unsigned char *)pixel_data; - delete [] temp_pd; - } -} - -size_t Environment_Palette_Chunk::size_chunk() -{ - chunk_size = 12 + 8 + (width * height * 3 + 3 & ~3); - return chunk_size; -} - -void Environment_Palette_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int*)data_start) = width * height; - *((int*)(data_start+4)) = flags; - - data_start += 8; - - for (int i=0; i<(width*height*3); i++) - { - data_start[i] = pixel_data[i]; - } - -} - - -/////////////////////////////////////// - -// Class Preset_Palette_Chunk functions - - -Preset_Palette::~Preset_Palette () -{ - if (pixel_data) - { - unsigned char * temp_pd = (unsigned char *)pixel_data; - delete [] temp_pd; - } - if (name) delete[] name; -} - -Preset_Palette::Preset_Palette (Preset_Palette const & c) -: size(c.size) -, flags(c.flags) -, reserved1(c.reserved1) -, reserved2(c.reserved2) -, startpos(c.startpos) -, pixel_data(grab_pixel_data(c.size, c.pixel_data)) -, name(0) -{ - if (c.name) - { - name = new char[strlen(c.name)+1]; - strcpy(name,c.name); - } -} - -Preset_Palette & Preset_Palette::operator = (Preset_Palette const & c) -{ - if (pixel_data) - { - unsigned char * temp_pd = (unsigned char *)pixel_data; - delete [] temp_pd; - } - if (name) - { - delete[] name; - name = 0; - } - if (c.name) - { - name = new char[strlen(c.name)+1]; - strcpy(name,c.name); - } - - *(int *)&size = c.size; - *(int *)&flags = c.flags; - *(int *)&reserved1 = c.reserved1; - *(int *)&reserved2 = c.reserved2; - *(int *)&startpos = c.startpos; - - *(const unsigned char * *)&pixel_data = grab_pixel_data(c.size,c.pixel_data); - - return *this; -} - - - -size_t Preset_Palette::size_chunk() const -{ - return 20 + (size * 3 + (name ? strlen(name)+1 : 8) +3 &~3); -} - -void Preset_Palette::fill_data_block (char * data_start) -{ - *(int*)data_start = size; - *(int*)(data_start+4) = flags; - *(int*)(data_start+8) = reserved1; - *(int*)(data_start+12) = reserved2; - *(int*)(data_start+16) = startpos; - - data_start += 20; - - unsigned char const * sptr = pixel_data; - - for (int i=size*3; i; --i, ++sptr, ++data_start) - { - *data_start = *sptr; - } - strcpy(data_start,name ? name : "unnamed"); -} - -RIF_IMPLEMENT_DYNCREATE("PRSETPAL",Preset_Palette_Chunk) - -Preset_Palette_Chunk::Preset_Palette_Chunk(Chunk_With_Children * const parent, char const * sdata, size_t const /*ssize*/) -: Chunk(parent,"PRSETPAL") -, version_num(*(int *)sdata) -, flags(*(int *)(sdata+4)) -, reserved1(*(int *)(sdata+8)) -, reserved2(*(int *)(sdata+12)) -, reserved3(*(int *)(sdata+16)) -{ - int const pplistsize = *(int *)(sdata+20); - sdata += 24; - - for (int i = pplistsize; i; --i) - { - Preset_Palette current(sdata); - sdata += current.size_chunk(); - pplist.add_entry(current); - } -} - - -size_t Preset_Palette_Chunk::size_chunk () -{ - chunk_size = 12 + 24; - - for (LIF<Preset_Palette> li(&pplist); !li.done(); li.next()) - { - chunk_size += li().size_chunk(); - } - - return chunk_size; -} - -void Preset_Palette_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *(int *) data_start = chunk_size; - - data_start += 4; - - *(int*)data_start = version_num; - *(int*)(data_start+4) = flags; - *(int*)(data_start+8) = reserved1; - *(int*)(data_start+12) = reserved2; - *(int*)(data_start+16) = reserved3; - *(int*)(data_start+20) = pplist.size(); - - data_start += 24; - - for (LIF<Preset_Palette> li(&pplist); !li.done(); li.next()) - { - Preset_Palette current(li()); - - current.fill_data_block(data_start); - data_start += current.size_chunk(); - } -} - - -/////////////////////////////////////// - -// Class Environment_TLT_Chunk functions - - -RIF_IMPLEMENT_DYNCREATE("ENVTXLIT",Environment_TLT_Chunk) - -Environment_TLT_Chunk::Environment_TLT_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize) -: Chunk (parent, "ENVTXLIT"), width (*((int*)(sdata))), - num_levels (*((int*)(sdata+4))), flags(*(int *)(sdata+28)), table (0), filename(0) -{ - for (int i=0; i<ChunkTLT_NumReserved; ++i) reserved[i] = *(int *)(sdata+8+(i<<2)); - - if (flags & ChunkTLTFlag_ExternalFile) - { - filename = new char[strlen(sdata+32)+1]; - strcpy(filename,sdata+32); - } - else if ((signed) ssize >= 32 + width*num_levels) - { - table = new unsigned char [width*num_levels]; - unsigned char * tableptr = table; - unsigned char const * sdataptr = (unsigned char *)(sdata+32); - for (i=width*num_levels; i; --i) - { - *tableptr++ = *sdataptr++; - } - } - -} - -Environment_TLT_Chunk::~Environment_TLT_Chunk () -{ - if (table) delete[] table; - if (filename) delete[] filename; -} - -size_t Environment_TLT_Chunk::size_chunk() -{ - if (flags & ChunkTLTFlag_ExternalFile) - { - if (filename) - { - chunk_size = 12 + 32 + (strlen(filename)+4 & ~3); - } - else - { - chunk_size = 12 + 32 + 4; - } - } - else - { - chunk_size = 12 + 32 + width * num_levels; - } - return(chunk_size); - -} - -void Environment_TLT_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int*)data_start) = width; - *((int*)(data_start+4)) = num_levels; - - data_start += 8; - - for (int i=0; i < ChunkTLT_NumReserved ; ++i, data_start+=4) - *((int *)data_start) = reserved[i]; - - *(int *)data_start = flags; - data_start+=4; - - if (flags & ChunkTLTFlag_ExternalFile) - { - if (filename) - strcpy(data_start,filename); - else - *data_start = 0; - } - else - { - if (table) - { - unsigned char * tableptr = table; - - for (i=width*num_levels; i; --i) - { - *data_start++ = *tableptr++; - } - } - else - { - for (i=width*num_levels; i; --i) - { - *data_start++ = 0; - } - } - } -} - - -/////////////////////////////////////// - -// Class TLT_Config_Chunk functions - -TLTCC_Flags::TLTCC_Flags(unsigned int data) -: allow_v2 (data & 0x00000001 ? 1 : 0) -, nodefault (data & 0x00000002 ? 1 : 0) -{ -} - -TLTCC_Flags::operator unsigned int () const -{ - return - allow_v2 * 0x00000001 + - nodefault * 0x00000002 ; -} - -RIF_IMPLEMENT_DYNCREATE("TLTCONFG",TLT_Config_Chunk) - -TLT_Config_Chunk::TLT_Config_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize) -: Chunk (parent, "TLTCONFG") -, num_shades_white(*(unsigned int const *)sdata) -, table_size(*(unsigned int const *)(sdata+4)) -, flags(*(unsigned int const *)(sdata+8)) -, palette_size(*(unsigned int const *)(sdata+12)) -{ - if (!table_size) table_size = 256; - - sdata+=16; - - for (int i=0; i<3; ++i, sdata+=4) reserved[i] = *(int *)sdata; - - unsigned int const len = strlen(sdata)+4&~3; - srcrifname = new char[len]; - memcpy(srcrifname,sdata,len); - sdata += len; - - unsigned int listsize = *(int *)sdata; - sdata += 4; - - while (listsize) - { - TLTConfigBlock block(sdata); - sdata += block.Size(); - blocks.add_entry_end(block); - listsize--; - } - - // hmm, size_chunk was wrong so allow sizes which were wrong in that way to pass - assert (ssize + 12 == size_chunk() || ssize + 12 + (44+strlen(srcrifname)+4&~3) - (44+strlen(srcrifname)+4&~4) == size_chunk()); -} - -size_t TLT_Config_Chunk::size_chunk() -{ - chunk_size = 44 + (srcrifname ? strlen(srcrifname) : 0) + 4 &~3; - for (LIF<TLTConfigBlock> tbli(&blocks); !tbli.done(); tbli.next()) - { - chunk_size += tbli().Size(); - } - return chunk_size; -} - -void TLT_Config_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - - *((int *) data_start) = chunk_size; - data_start += 4; - - *(unsigned int *)data_start = num_shades_white; - data_start += 4; - - *(unsigned int *)data_start = table_size; - data_start += 4; - - *(unsigned int *)data_start = flags; - data_start += 4; - - *(unsigned int *)data_start = palette_size; - data_start += 4; - - for (int i=0; i<3 ; ++i, data_start+=4) - *(int *)data_start = reserved[i]; - - strcpy(data_start,srcrifname ? srcrifname : ""); - - data_start += strlen(data_start) + 4 &~3; - - *(int *)data_start = blocks.size(); - data_start+=4; - - for (LIF<TLTConfigBlock> tbli(&blocks); !tbli.done(); tbli.next()) - { - tbli().WriteData(data_start); - data_start += tbli().Size(); - } -} - - -/////////////////////////////////////// - -// Class Environment_Data_Chunk functions - -// constructor from buffer - -RIF_IMPLEMENT_DYNCREATE("GAMEMODE",Environment_Game_Mode_Chunk) - -/* -Children For Environment_Game_Mode_Chunk : - - -"GMODHEAD" Environment_Game_Mode_Header_Chunk -"ENVPALET" Environment_Palette_Chunk -"ENVTXLIT" Environment_TLT_Chunk -"TLTCONFG" TLT_Config_Chunk -"CLRLOOKP" Coloured_Polygons_Lookup_Chunk -"MATCHIMG" Matching_Images_Chunk -"SHBMPNAM" External_Shape_BMPs_Store_Chunk -"RIFCHILD" RIF_Child_Chunk -"SETPALST" Preset_Palette_Store_Chunk -"BMPMD5ID" Bitmap_MD5_Chunk -*/ - - -Environment_Game_Mode_Chunk::Environment_Game_Mode_Chunk(Chunk_With_Children* const parent,const char* data,size_t const size) -:Chunk_With_Children(parent,"GAMEMODE") , envd_parent((Environment_Data_Chunk *)parent) -{ - const char * buffer_ptr = data; - while ((data-buffer_ptr)< (signed) size) { - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed) size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(data); - data += *(int *)(data + 8); - } -} - -char * Environment_Game_Mode_Chunk::ExpandedIdentifier() const -{ - char const * full_fname = header->flags & GameModeFlag_Editable ? ((File_Chunk *)GetRootChunk())->filename : header->get_safe_source(); - char const * skip = strrchr(full_fname,'\\'); - if (skip) full_fname = skip+1; - skip = strrchr(full_fname,'/'); - if (skip) full_fname = skip+1; - skip = strrchr(full_fname,':'); - if (skip) full_fname = skip+1; - char * retp = new char[strlen(full_fname)+strlen(header->mode_identifier)+3]; - strcpy(retp,full_fname); - char * dotpos = strrchr(retp,'.'); - if (dotpos) *dotpos = 0; - strcat(retp,"::"); - strcat(retp,header->mode_identifier); - return retp; -} - -// header chunk -RIF_IMPLEMENT_DYNCREATE("GMODHEAD",Environment_Game_Mode_Header_Chunk) - -Environment_Game_Mode_Header_Chunk::Environment_Game_Mode_Header_Chunk(Chunk_With_Children * const parent, const char * pdata, size_t const /*psize*/) -: Chunk (parent, "GMODHEAD"), flags(0), rif_files() -{ - flags = *((int *) pdata); - - pdata+=4; - - for (int i=0; i<ChunkGMod_NumReserved; i++, pdata+=4) - { - reserved[i] = *((int *) pdata); - } - - version_num = *(int *)pdata; - pdata+=4; - - mode_identifier = new char[strlen(pdata)+1]; - - strcpy (mode_identifier, (pdata)); - - pdata += strlen(mode_identifier) + 1; - - while (*pdata) - { - unsigned int len = strlen(pdata)+1; - - char * riffn = new char[len]; - strcpy(riffn,pdata); - rif_files.add_entry(riffn); - - pdata += len; - } - - ((Environment_Game_Mode_Chunk*)parent)->header = this; -} - - -Environment_Game_Mode_Header_Chunk::~Environment_Game_Mode_Header_Chunk() -{ - if (mode_identifier) delete[] mode_identifier; - - while (rif_files.size()) - { - delete [] rif_files.first_entry(); - rif_files.delete_first_entry(); - } -} - - - -void Environment_Game_Mode_Header_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = flags; - data_start+=4; - - for (int i=0; i<ChunkGMod_NumReserved; i++, data_start+=4) - { - *((int *) data_start) = reserved[i]; - } - *(int *)data_start = version_num; - data_start+=4; - - strcpy ((data_start), mode_identifier); - - data_start += strlen(mode_identifier) + 1; - - for (LIF<char *> li(&rif_files); !li.done(); li.next()) - { - strcpy(data_start,li()); - - data_start += strlen(li())+1; - } - - *data_start = 0; // double 0-byte terminator -} - - -size_t Environment_Game_Mode_Header_Chunk::size_chunk () -{ - chunk_size = 12+20+(strlen(mode_identifier)+1); - - for (LIF<char *> li(&rif_files); !li.done(); li.next()) - { - chunk_size += strlen(li())+1; - } - - chunk_size += 4; // 1 byte terminator, 3(max) to pad - chunk_size &= ~3; - return chunk_size; -} - - - -//////////////////////////////////////// - -// Class RIF_Child_Chunk - for RIFs in game modes containing graphics -RIF_IMPLEMENT_DYNCREATE("RIFCHILD",RIF_Child_Chunk) - -RIF_Child_Chunk::~RIF_Child_Chunk() -{ - if (filename) delete[] filename; - if (rifname) delete[] rifname; -} - -size_t RIF_Child_Chunk::size_chunk() -{ - chunk_size = 12 + 12 + (strlen(rifname)+1 +3 &~3) + 4 + (strlen(filename)+1 +3 &~3) + 4; - - for (LIF<BMP_Flags> li(&bmps); !li.done(); li.next()) - { - chunk_size += 8 + strlen(li().filename)+1 +3 & ~3; - } - - return chunk_size; -} - -void RIF_Child_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - for (int i=0; i<ChunkRIFChild_NumReserved; i++, data_start+=4) - { - *((int *) data_start) = reserved[i]; - } - - *(RCC_Flags *)data_start = flags; - data_start += 4; - - strcpy(data_start,rifname); - data_start += strlen(rifname)+1 +3 &~3; - - *((int *) data_start) = version_num; - - data_start += 4; - - strcpy(data_start,filename); - data_start += strlen(filename)+1 +3 &~3; - - *((int *) data_start) = bmps.size(); - data_start += 4; - - for (LIF<BMP_Flags> li(&bmps); !li.done(); li.next()) - { - *((int *) data_start) = li().flags; - data_start += 4; - *((int *) data_start) = li().version_num & BMPFLAGS_VERSION_NUM_MASK | li().enum_id << BMPFLAGS_ENUMID_SHIFT; - data_start += 4; - - strcpy(data_start, li().filename); - data_start += strlen(li().filename)+1 +3 &~3; - } - -} - -int const * RIF_Child_Chunk::GetMD5Val(BMP_Flags const & rcbmp) -{ - Bitmap_MD5_Chunk * md5c = GetMD5Chunk(rcbmp.filename); - if (md5c) - if (rcbmp.version_num == md5c->version_num) - return md5c->md5_val; - return 0; -} - -void RIF_Child_Chunk::RemoveMD5Val(char const * bname) -{ - Bitmap_MD5_Chunk * md5c = GetMD5Chunk(bname); - if (md5c) - delete md5c; -} - -void RIF_Child_Chunk::SetMD5Val(BMP_Flags const & rcbmp, int const * md5id) -{ - Bitmap_MD5_Chunk * md5c = GetMD5Chunk(rcbmp.filename); - if (md5c) - { - if (rcbmp.version_num == md5c->version_num) - { - memcpy(md5c->md5_val,md5id,16); - return; - } - else - delete md5c; - } - CreateMD5Chunk(rcbmp,md5id); -} - -Bitmap_MD5_Chunk * RIF_Child_Chunk::GetMD5Chunk(char const * bname) -{ - List<Chunk *> chlst; - parent->lookup_child("BMPMD5ID",chlst); - - for (LIF<Chunk *> i_chlst(&chlst); !i_chlst.done(); i_chlst.next()) - { - Bitmap_MD5_Chunk * md5c = (Bitmap_MD5_Chunk *)i_chlst(); - - if (!strcmp(md5c->bmpname,bname)) - if (!(md5c->rifname ? rifname ? strcmp(rifname,md5c->rifname) : *md5c->rifname : rifname ? *rifname : 0) && - !(md5c->shapename ? *md5c->shapename : 1)) - return md5c; - } - - return 0; -} - -void RIF_Child_Chunk::CreateMD5Chunk(BMP_Flags const & rcbmp, int const * md5id) -{ - new Bitmap_MD5_Chunk(parent,md5id,rcbmp,rifname); -} - -RIF_Child_Chunk::RIF_Child_Chunk (Chunk_With_Children * const parent, const char * sdata, size_t const /*ssize*/) -: Chunk(parent,"RIFCHILD"), egm_parent((Environment_Game_Mode_Chunk * const)parent) -{ - for (int i=0; i<ChunkRIFChild_NumReserved; i++, sdata+=4) - { - reserved[i] = *((int *) sdata); - } - flags = *(RCC_Flags *)sdata; - sdata += 4; - - unsigned int len = strlen(sdata)+1; - rifname = new char[len]; - strcpy(rifname,sdata); - sdata += len+3 &~3; - - version_num = *(int *)sdata; - sdata += 4; - - len = strlen(sdata)+1; - filename = new char[len]; - strcpy(filename,sdata); - sdata += len+3 &~3; - - int listsize = *(int *)sdata; - sdata+=4; - - for (i = listsize; i; --i) - { - BMP_Flags temp; - temp.flags = *(BMPN_Flags *)sdata; - sdata += 4; - temp.enum_id = (int)(*(unsigned int *)sdata >> BMPFLAGS_ENUMID_SHIFT); - temp.version_num = *(int *)sdata & BMPFLAGS_VERSION_NUM_MASK; - sdata += 4; - - len = strlen(sdata)+1; - temp.filename = new char[len]; - strcpy(temp.filename,sdata); - sdata += len+3 &~3; - - bmps.add_entry(temp); - } - -} - -///////////////////////////////// -// Preset_Palette_Store_Chunk -// ties in with RIF_Child_Chunk -// the filenames (-dirname) should match - -RIF_IMPLEMENT_DYNCREATE("SETPALST",Preset_Palette_Store_Chunk) - -Preset_Palette_Store_Chunk::Preset_Palette_Store_Chunk(Chunk_With_Children * const parent, char const * sdata, size_t const /*ssize*/) -: Chunk(parent,"SETPALST") -, version_num(*(int *)sdata) -, flags(*(int *)(sdata+4)) -, reserved1(*(int *)(sdata+8)) -, reserved2(*(int *)(sdata+12)) -, reserved3(*(int *)(sdata+16)) -{ - sdata += 20; - - unsigned int const len = strlen(sdata)+1; - rifname = new char[len]; - strcpy(rifname,sdata); - sdata += len + 3 &~3; - - int const pplistsize = *(int *)sdata; - sdata += 4; - - for (int i = pplistsize; i; --i) - { - Preset_Palette current(sdata); - sdata += current.size_chunk(); - pplist.add_entry(current); - } -} - - -size_t Preset_Palette_Store_Chunk::size_chunk () -{ - chunk_size = 12 + 24 + strlen(rifname)+1+3 &~3; - - for (LIF<Preset_Palette> li(&pplist); !li.done(); li.next()) - { - chunk_size += li().size_chunk(); - } - - return chunk_size; -} - -void Preset_Palette_Store_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *(int *) data_start = chunk_size; - - data_start += 4; - - *(int*)data_start = version_num; - *(int*)(data_start+4) = flags; - *(int*)(data_start+8) = reserved1; - *(int*)(data_start+12) = reserved2; - *(int*)(data_start+16) = reserved3; - data_start += 20; - - strcpy(data_start,rifname); - data_start+=strlen(rifname)+1+3 &~3; - - *(int*)(data_start) = pplist.size(); - data_start += 4; - - for (LIF<Preset_Palette> li(&pplist); !li.done(); li.next()) - { - Preset_Palette current(li()); - - current.fill_data_block(data_start); - data_start += current.size_chunk(); - } -} - - - - - -/////////////////////////////////////// - -// Class Coloured_Polygons_Lookup_Chunk functions - -// simple 32K tables for palettes to quickly map coloured -// polygons to the right palette colour on loading, with 15-bit definition - - -RIF_IMPLEMENT_DYNCREATE("CLRLOOKP",Coloured_Polygons_Lookup_Chunk) - -Coloured_Polygons_Lookup_Chunk::Coloured_Polygons_Lookup_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/) -: Chunk (parent, "CLRLOOKP"), flags (*((int*)(sdata))), - filename(0), table (0) -{ - for (int i=0; i<ChunkCPLU_NumReserved; ++i) reserved[i] = *(int *)(sdata+4+(i<<2)); - - if (flags & ChunkCPLUFlag_ExternalFile) - { - filename = new char[strlen(sdata+32)+1]; - strcpy(filename,sdata+32); - } - else - { - table = new unsigned char [1<<15]; - unsigned char * tableptr = table; - unsigned char const * sdataptr = (unsigned char *)(sdata+32); - for (i=1<<15; i; --i) - { - *tableptr++ = *sdataptr++; - } - } - -} - -Coloured_Polygons_Lookup_Chunk::~Coloured_Polygons_Lookup_Chunk () -{ - if (table) delete [] table; - if (filename) delete [] filename; -} - -size_t Coloured_Polygons_Lookup_Chunk::size_chunk() -{ - if (flags & ChunkCPLUFlag_ExternalFile) - { - if (filename) - { - chunk_size = 12 + 32 + (strlen(filename)+4 & ~3); - } - else - { - chunk_size = 12 + 32 + 4; - } - } - else - { - chunk_size = 12 + 32 + (1<<15); - } - return(chunk_size); - -} - -void Coloured_Polygons_Lookup_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int*)data_start) = flags; - - data_start += 4; - - for (int i=0; i < ChunkCPLU_NumReserved ; ++i, data_start+=4) - *((int *)data_start) = reserved[i]; - - if (flags & ChunkCPLUFlag_ExternalFile) - { - if (filename) - strcpy(data_start,filename); - else // escape - *data_start = 0; - } - else - { - if (table) - { - unsigned char * tableptr = table; - - for (i=1<<15; i; --i) - { - *data_start++ = *tableptr++; - } - } - else // escape - { - for (i=1<<15; i; --i) - { - *data_start++ = 0; - } - } - } -} - - diff --git a/3dc/win95/CHUNKPAL.HPP b/3dc/win95/CHUNKPAL.HPP deleted file mode 100644 index 5a51c6d..0000000 --- a/3dc/win95/CHUNKPAL.HPP +++ /dev/null @@ -1,1044 +0,0 @@ -#ifndef _included_chunkpal_hpp_ -#define _included_chunkpal_hpp_ - -#include "chunk.hpp" -#include "bmpnames.hpp" -#if cencon -#include "palette.h" -#endif - -static const unsigned char * grab_pixel_data(int ssize, unsigned char const * sdata) -{ - if (!ssize) return 0; - ssize *= 3; - - unsigned char * pixels = new unsigned char[ssize]; - - unsigned char * ddata = pixels; - - for (int cnt = ssize; cnt; --cnt, ++ddata, ++sdata) *ddata = *sdata; - - return pixels; -} - - - -class Environment_Palette_Chunk : public Chunk -{ - -public: - -#if cencon - // constructor from data - defined in genpal - Environment_Palette_Chunk (Chunk_With_Children * const parent, PPM_Header const * const palette); -#endif - // constructor from buffer - Environment_Palette_Chunk (Chunk_With_Children * const parent, const char * sdata, size_t const /*ssize*/) - : Chunk (parent, "ENVPALET") - , width (*(int *)sdata) - , height (1) - , flags (*(int *)(sdata+4)) - , pixel_data (grab_pixel_data(*(int *)sdata,(unsigned char *)(sdata+8))) - {} - ~Environment_Palette_Chunk (); - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - const int width; - const int height; - int flags; // was width, but width was always 1 - // do not use as a flag 0x00000001 - #define EnvPalFlag_UpToDate 0x00000002 // make flag - #define EnvPalFlag_Lit 0x00000004 // uses darken flag when generating palette - #define EnvPalFlag_V2 0x00000008 // flagged to distinguish between big tlt palette & normal palette - #define DEFAULT_ENV_PAL_FLAGS EnvPalFlag_Lit - - const unsigned char * const pixel_data; - -private: - - friend class Environment_Data_Chunk; - friend class Environment_Game_Mode_Chunk; - - -}; - - - -class Preset_Palette_Chunk; - -class Preset_Palette -{ -public: - -#if cencon - // constructor from data - defined in genpal - Preset_Palette (PPM_Header const * const palette); - - // update by generating from bmps chunk - void update(Global_BMP_Name_Chunk * gbnc, Preset_Palette_Chunk * ppc, class Environment * e, Environment_Data_Chunk * envd, BOOL bDoSoftwareTex); - -#if 0 - Preset_Palette (const char * iname) - : size(0) - , flags(0) - , reserved1(0) - , reserved2(0) - , startpos(0) - , pixel_data(0) - , name(0) - { - if (iname) - { - name = new char[strlen(iname)+1]; - strcpy(name,iname); - } - } -#endif -#endif - - Preset_Palette () - : size(0) - , flags(0) - , reserved1(0) - , reserved2(0) - , startpos(0) - , pixel_data(0) - , name(0) - {} - - // copy constructor - Preset_Palette (Preset_Palette const & c); - - ~Preset_Palette (); - - Preset_Palette & operator = (Preset_Palette const & c); - - const int size; - int flags; - #define PrePalFlag_Reserved 0x00000001 // preset palette defines contant entries in palette for graphics which are not reloaded - #define PrePalFlag_UpToDate 0x00000002 - #define PrePalFlag_V2 0x00000004 // calculated fixed palette using wide palette, tlt and lit textures - - const int reserved1; - const int reserved2; - int startpos; - - char * name; - - const unsigned char * const pixel_data; - - // for the list template - inline BOOL operator == (Preset_Palette const & c) const { return !_stricmp(name,c.name); } - inline BOOL operator != (Preset_Palette const & c) const { return _stricmp(name,c.name); } - inline BOOL operator < (Preset_Palette const & c) const { return startpos < c.startpos; } - -private: - - friend class Preset_Palette_Chunk; - friend class Preset_Palette_Store_Chunk; - - size_t size_chunk () const; - - void fill_data_block (char * data_start); - - // constructor from buffer - Preset_Palette (char const * sdata) - : size (*(int *)sdata) - , flags (*(int *)(sdata+4)) - , reserved1 (*(int *)(sdata+8)) - , reserved2 (*(int *)(sdata+12)) - , startpos (*(int *)(sdata+16)) - , pixel_data (grab_pixel_data(*(int *)sdata,(unsigned char *)(sdata+20))) - { - sdata += 20+size*3; - name = new char[strlen(sdata)+1]; - strcpy(name,sdata); - } -}; - - -class Preset_Palette_Chunk : public Chunk -{ -public: - -#if cencon - // empty constructor - Preset_Palette_Chunk (Chunk_With_Children * const parent) - : Chunk (parent,"PRSETPAL") - , flags(0) - , version_num(0) - , reserved1(0) - , reserved2(0) - , reserved3(0) - {} - -#endif - // constructor from buffer - Preset_Palette_Chunk (Chunk_With_Children * const parent, char const * sdata, size_t const ssize); - ~Preset_Palette_Chunk () {}; - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - int flags; - int version_num; - - const int reserved1; - const int reserved2; - const int reserved3; - - List<Preset_Palette> pplist; - - -private: - - friend class Environment_Data_Chunk; - - -}; - - - - -class Environment_TLT_Chunk : public Chunk -{ - -public: - -#if cencon - // constructor using palette - defined in genpal - Environment_TLT_Chunk (Chunk_With_Children * parent, PPM_Header * palette, PPM_Header * tlt_palette, Lighting_Style const * ls); -#endif - // constructor from buffer - Environment_TLT_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize); - - ~Environment_TLT_Chunk (); - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - int width; // should be == palette size, though may well have to be 256 due to the way 3dc lookup works - int num_levels; // usually 256, for 256 "different" shades of each colour - - #define ChunkTLT_NumReserved 5 - int reserved[ ChunkTLT_NumReserved ]; - - int flags; // either expect filename or table - #define ChunkTLTFlag_ExternalFile 0x00000001 - #define ChunkTLTFlag_OptionsChanged 0x00000002 - #define ChunkTLTFlag_V2 0x00000004 // version 2: may have width != 256, flagged so we can distinguish between two tables in chunk - - char * filename; // either a filename - - unsigned char * table; // or an actual table in memory - -private: - - friend class Environment_Data_Chunk; - friend class Environment_Game_Mode_Chunk; - - - -}; - - -class TLTConfigBlock -{ -public: - // constructos; - TLTConfigBlock() - { - spares[0]=0; - spares[1]=0; - spares[2]=0; - spares[3]=0; - } - - TLTConfigBlock(double const & iistart, double const & oistart, double const & iiend, double const & oiend) - : input_intensity_start(iistart) - , output_intensity_start(oistart) - , input_intensity_end(iiend) - , output_intensity_end(oiend) - { - spares[0]=0; - spares[1]=0; - spares[2]=0; - spares[3]=0; - } - - // I/O - TLTConfigBlock(char const * datablock) - : input_intensity_start(*(double *)datablock) - , output_intensity_start(*(double *)(datablock+8)) - , input_intensity_end(*(double *)(datablock+16)) - , output_intensity_end(*(double *)(datablock+24)) - { - memcpy(spares,datablock+32,16); - } - inline size_t Size() const { return 48; } - inline void WriteData(char * datablock) const - { - *(double *)datablock = input_intensity_start; - datablock += 8; - *(double *)datablock = output_intensity_start; - datablock += 8; - *(double *)datablock = input_intensity_end; - datablock += 8; - *(double *)datablock = output_intensity_end; - datablock += 8; - memcpy(datablock,spares,16); - } - - // operators - inline BOOL operator == (TLTConfigBlock const & tcb2) const - { - return input_intensity_start == tcb2.input_intensity_start - && output_intensity_start == tcb2.output_intensity_start - && input_intensity_end == tcb2.input_intensity_end - && output_intensity_end == tcb2.output_intensity_end; - } - inline BOOL operator != (TLTConfigBlock const & tcb2) const - { return ! operator == (tcb2); } - - // members - double input_intensity_start; - double output_intensity_start; - double input_intensity_end; - double output_intensity_end; - -private: - - int spares[4]; - -}; - -struct TLTCC_Flags -{ - TLTCC_Flags(unsigned int data = 0); - - operator unsigned int () const; - - unsigned int allow_v2 : 1; // palette size refers to bigger size table - unsigned int nodefault : 1; // suppress normal 256 colour tlts -}; - -class TLT_Config_Chunk : public Chunk -{ - -public: - -#if cencon - // constructor for default - TLT_Config_Chunk (Chunk_With_Children * parent, char const * rifname = 0) - : Chunk (parent, "TLTCONFG") - , num_shades_white(16) - , srcrifname(rifname ? new char [strlen(rifname)+1] : 0) - , blocks(TLTConfigBlock(0,0,1,1)) - , table_size(256) - , palette_size(0) - { - for (int i=0; i<3; ++i) reserved[i]=0; - if (rifname) strcpy(srcrifname,rifname); - } -#endif - // constructor from buffer - TLT_Config_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize); - - ~TLT_Config_Chunk() - { if (srcrifname) delete[] srcrifname; } - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - char * srcrifname; - - unsigned int num_shades_white; - - unsigned int table_size; - - List<TLTConfigBlock> blocks; - - unsigned int palette_size; // for version 2 palettes and big tlt - - TLTCC_Flags flags; - - inline BOOL operator == (TLT_Config_Chunk const & tcc2) const - { return blocks == tcc2.blocks && num_shades_white == tcc2.num_shades_white && table_size == tcc2.table_size && flags == tcc2.flags && (!flags.allow_v2 || palette_size == tcc2.palette_size); } - inline BOOL operator != (TLT_Config_Chunk const & tcc2) const - { return ! operator == (tcc2); } - inline BOOL NeedFullRemake(TLT_Config_Chunk const & tcc_old) const - { return blocks != tcc_old.blocks || num_shades_white != tcc_old.num_shades_white; } - inline BOOL NeedNewTLTPalette(TLT_Config_Chunk const & tcc_old) const - { return flags != tcc_old.flags || flags.allow_v2 && palette_size != tcc_old.palette_size; } - -private: - int reserved[3]; - - friend class Environment_Data_Chunk; - friend class Environment_Game_Mode_Chunk; - - - -}; - -#if cencon -extern TLT_Config_Chunk Default_TLT_Config_Chunk; -#endif - - - - -// Multi-Palettes for one environment - -// Coloured polygons will be set on load-up -// If 15 bit is good-enough, we can use a 32K -// lookup table for the coloured polygons, -// otherwise we'll have to do the slower -// distance comparisons - -// We need a new chunk which is a child of the REBENVDT environment data chunk - -// this will be a GAMEMODE chunk with children, and there may be more than one -// in the case where there are several palettes available for the environment - -// there will be an identifying string in the gamepalette chunk. -// the "REBENVDT"->lookup_child("GAMPALET") will return a list of these chunks, -// so you can look through them to find the one you want -// There should be some sort of convention/restriction/communication -// about the - -// most of the information will be in its children, which can be any of the following - -// ENVPALET - -// RIFCHILD(s) - the name of RIF file(s) -// this is basically a RIF_Name_Chunk, but named differently so as to distinguish it from its own file's name -// which should have a REBENVDT chunk with BMPNAMES and/or RIFCHILD(s) (even more RIFs) -// specifying what non-environment specific bitmaps are used, and probably much more data, -// - they could be sprites, etc. -// then all the data could be automatically included (but not loaded) by the inclusion of one file - -// ENVTXLIT - texture lighting table, -// but maybe this should a filename to load if required - -// CLRLOOKP - 15-bit r;g;b lookup table to get palette entries for coloured polygons on load -// can have a table or a reference file - -// other relevant chunks to be added later -// we may need some sort of BMPNAMES chunk, for flags about which bmps are quantized, etc. - - -// HOW TO USE - example (supplied without warranty) -// ---------- - -/* -File_Chunk * environment = $current environment$; - -List<Chunk *> envdatalist = environment->lookup_child("REBENVDT"); - -if (envdatalist.size()) -{ - Environment_Data_Chunk * envdata = (Environment_Data_Chunk *)envdatalist.first_entry(); - - List<Chunk *> gamemodelist = envdata->lookup_child("GAMEMODE"); - - Environment_Game_Mode_Chunk * selected = 0; - - for(LIF<Chunk *> li(&gamemodelist); !li.done(); li.next()) - { - Environment_Game_Mode_Chunk * try_this = (Environment_Game_Mode_Chunk *) li(); - if (try_this->id_equals((const char *)$your identifier$)) - { - selected = try_this; - break; - } - } - - if (selected) - { - List<Chunk *> bmpgrouplist = selected->lookup_child("RIFCHILD"); - - String subdir; - - List<Chunk *> rifnamechunk = envdata->lookup_child("RIFFNAME"); - if (rifnamechunk.size()) - subdir = ((RIF_Name_Chunk *) rifnamechunk.first_entry())->rif_name; - else - subdir = "empty"; - - // load graphics loop - for (LIF<Chunk *> g(&bmpgrouplist); !g.done(); g.next()) - { - RIF_Child_Chunk * current = (RIF_Child_Chunk *)g(); - - const char * mipmap_0; - const char * mipmap_n; - String dir; - - if ($loading pgms$) - { - dir = (String)"Game-Textures\\" + subdir + "\\" + (String)$your identifier$ + "\\"; - if (*current->filename) - { - dir += (String)current->rifname + "\\"; - } - mipmap_0 = ".pg0"; - mipmap_n = ".pg%1d"; - } - else // loading bm0 to bm6 - { - dir = (String)"Generic-Textures\\" + current->rifname + "\\"; - mipmap_0 = ".pg0"; - mipmap_n = ".pg%1d"; - } - - // load graphics-set loop - for (LIF<BMP_Flags> img(¤t->bmps); !img.done(); img.next()) - { - BMP_Flags bmp = img(); - - char * imname = new char[strlen(bmp.filename)+5]; - strcpy(imname,bmp.filename); - char * dotpos = strrchr(imname,'.'); - if (!dotpos) dotpos = imname + strlen(imname); - strcpy(dotpos,mipmap_0); - - String filename = dir + imname; - - $load image$(filename) - - if (bmp.flags & ChunkBMPFlag_MipMapsQuantized) - { - // load mipmaps loop - for (int i = 1 ; i<=6 ; ++i) - { - sprintf(dotpos,mipmap_n,i); - filename = dir + imname; - $load image$(filename) - } - } - delete [] imname; - } - } - } - else - { - // your identifier is not valid - } -} -else -{ - // no data -} - - - -*/ - - -#define GameModeFlag_Editable 0x00000001 // game modes are not editable if they are included from another RIF -#define GameModeFlag_Deleted 0x00000002 // so you can click on cancel and invisibly no updating will be done -#define GameModeFlag_Added 0x00000004 // ditto - -class Environment_Game_Mode_Chunk; -class Environment_Game_Mode_Header_Chunk; - - - -class Environment_Game_Mode_Chunk : public Chunk_With_Children -{ - -public: - -#if cencon - // constructor from data - Environment_Game_Mode_Chunk (Environment_Data_Chunk * const parent, const char * _mode_id); - - // defined in gmodlink - void remove(class CWnd * const pWnd); // update this copy by finding its original - void update(class CWnd * const pWnd, BOOL bDoSoftwareTex); // update this copy by finding its original - void been_updated(class CWnd * const pWnd, BOOL bDoSoftwareTex); // find and update copies from this original - void definite_update(Environment_Game_Mode_Chunk const * const src, class CWnd * const pWnd, Environment_Data_Chunk * envd, BOOL bDoSoftwareTex); - -#endif - // constructor from buffer - Environment_Game_Mode_Chunk (Chunk_With_Children * const parent, const char * sdata, size_t const ssize); - - ~Environment_Game_Mode_Chunk(){} - - Environment_Game_Mode_Header_Chunk * header; - Environment_Data_Chunk * const envd_parent; - - char * ExpandedIdentifier() const; // must delete return value - - inline BOOL operator == (Environment_Game_Mode_Chunk const & m) const; - inline BOOL operator != (Environment_Game_Mode_Chunk const & m) const; - // public function for people to check if they have the game mode they want - inline BOOL id_equals(const char * s) const; - -private: - - friend class Environment_Data_Chunk; - - - -}; - -class Environment_Game_Mode_Chunk_Pointer -{ -private: - Environment_Game_Mode_Chunk * p; - // poor lonely thing has no friends and never will -- aaaahh - -private: - inline Environment_Game_Mode_Chunk_Pointer(void) : p(0) {}; - friend struct List_Member<Environment_Game_Mode_Chunk_Pointer>; - -public: - // copy constructor from another of this type - //inline Environment_Game_Mode_Chunk_Pointer(Environment_Game_Mode_Chunk_Pointer const & cp) : p(cp.p) {}; - // cast constructor from C pointer - inline Environment_Game_Mode_Chunk_Pointer(Environment_Game_Mode_Chunk * const cp) : p(cp) {}; - // cast to C pointer operator - inline operator Environment_Game_Mode_Chunk * (void) const { return p; } - // no empty constructor -- p must always be valid - - // equavalence based on contents of pointer, not addresses being the same - inline BOOL operator == (Environment_Game_Mode_Chunk_Pointer const m) const - { - if (!p || !m.p) return 0; - return *p == *m.p; - } - inline BOOL operator != (Environment_Game_Mode_Chunk_Pointer const m) const - { - if (!p || !m.p) return 1; - return *p != *m.p; - } - -}; - - -/////////////////////////////////////////////// - - - - -class Environment_Game_Mode_Header_Chunk : public Chunk -{ -public: - // constructor from buffer - Environment_Game_Mode_Header_Chunk (Chunk_With_Children * const parent, const char * pdata, size_t const psize); - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - inline BOOL id_equals(const char * s) - { - if (_stricmp(s,mode_identifier)) - return FALSE; - else - return TRUE; - } - - int flags; - char * mode_identifier; - - inline void add_rif_entry(char const * f) - { - char * n = new char[strlen(f)+1]; - strcpy(n,f); - rif_files.add_entry(n); - } - inline const char * get_safe_source(void) - { - if (flags & GameModeFlag_Editable) - return "this.rif"; - if (!rif_files.size()) - return "unknown.rif"; - return rif_files.first_entry(); - } - -private: - - friend class Environment_Game_Mode_Chunk; - friend class Cwm_GAMEMODEDlg; - friend class Cwm_GAMEMODClicked116Dlg; - friend class GameModeDlg; - friend class GameModeRifDlg; - - List<char *> rif_files; // where the game mode goes to or comes from - - #define ChunkGMod_NumReserved 3 - int reserved[ChunkGMod_NumReserved]; - - int version_num; - - - #if cencon - // constructor from parent - Environment_Game_Mode_Header_Chunk (Environment_Game_Mode_Chunk * const parent, const char * const _mode_id) - : Chunk (parent, "GMODHEAD"), version_num(0), - flags (0), rif_files() - { - for (int i=0; i<ChunkGMod_NumReserved; i++) - { - reserved[i] = 0; - } - mode_identifier = new char[strlen(_mode_id)+1]; - strcpy(mode_identifier,_mode_id); - - parent->header = this; - } - - inline Environment_Game_Mode_Header_Chunk const & operator = (Environment_Game_Mode_Header_Chunk & s) - { - flags = s.flags; - while (rif_files.size()) - { - delete[] rif_files.first_entry(); - rif_files.delete_first_entry(); - } - if (mode_identifier) delete[] mode_identifier; - - mode_identifier = new char[strlen(s.mode_identifier)+1]; - strcpy(mode_identifier,s.mode_identifier); - - for (LIF<char *> src(&s.rif_files); !src.done(); src.next()) - { - add_rif_entry(src()); - } - - version_num = s.version_num; - - return *this; - - } - #endif - - // deconstructor - ~Environment_Game_Mode_Header_Chunk(); - - - -}; - -////////////////// - -inline BOOL Environment_Game_Mode_Chunk::operator == (Environment_Game_Mode_Chunk const & m) const -{ - if ((header->flags | m.header->flags) & GameModeFlag_Deleted) return FALSE; - return !_stricmp(header->mode_identifier,m.header->mode_identifier); -} -inline BOOL Environment_Game_Mode_Chunk::operator != (Environment_Game_Mode_Chunk const & m) const -{ - if ((header->flags | m.header->flags) & GameModeFlag_Deleted) return TRUE; - return _stricmp(header->mode_identifier,m.header->mode_identifier); -} -inline BOOL Environment_Game_Mode_Chunk::id_equals(const char * s) const -{ - return header->id_equals(s); -} - - -/////////////////////////////////////////////// - - -class RIF_Child_Chunk; - -class BMP_Flags -{ -public: - BMP_Flags(void) : filename(0), enum_id(0), version_num(0), flags((BMPN_Flags)0){} - BMP_Flags(const char * const fname) : enum_id(0), version_num(0), flags((BMPN_Flags)0), filename(0) - { - if (fname) - { - filename = new char[strlen(fname)+1]; - strcpy(filename,fname); - } - } - BMP_Flags(BMP_Name const & bn) : enum_id(bn.enum_id), version_num(bn.version_num), flags((BMPN_Flags)(bn.flags & COPY_BMPN_FLAGS)), filename(0) - { - if (bn.filename) - { - filename = new char[strlen(bn.filename)+1]; - strcpy(filename,bn.filename); - } - } - BMP_Flags(BMP_Flags const & c) : filename(0), enum_id(c.enum_id), version_num(c.version_num), flags(c.flags) - { - if (c.filename) - { - filename = new char[strlen(c.filename)+1]; - strcpy(filename,c.filename); - } - } - operator BMP_Name () const - { - BMP_Name cast(filename); - cast.flags = flags; - cast.version_num = version_num; - cast.enum_id = enum_id; - return cast; - } - ~BMP_Flags() - { - if (filename) delete[] filename; - } - - BMP_Flags & operator = (BMP_Flags const & c) - { - if (filename) delete[] filename; - if (c.filename) - { - filename = new char[strlen(c.filename)+1]; - strcpy(filename,c.filename); - } - else - filename = 0; - flags = c.flags; - version_num = c.version_num; - enum_id = c.enum_id; - return *this; - } - - - char * filename; - BMPN_Flags flags; - #define BMPFLAGS_VERSION_NUM_MASK 0x000fffff - #define BMPFLAGS_ENUMID_SHIFT 20 - int version_num; - int enum_id; - - inline BOOL operator == (BMP_Flags const & c) const - { - return !_stricmp(filename,c.filename); - } - inline BOOL operator != (BMP_Flags const & c) const - { - return _stricmp(filename,c.filename); - } - - #if cencon - void DeleteAssociatedFiles(RIF_Child_Chunk const *, Environment_Data_Chunk *) const; - #endif -}; - -enum RCC_Flags { - RCCF_EXTERNSHAPE = 0x00000001, // bitmaps from shape which is in game mode solely because it was an external shape added to the environment with this game mode - RCCF_FIXEDPALETTE = 0x00000002, // pgms are quantized with a fixed constant palette - RCCF_HISTOGRAMEXISTS = 0x00000004, - RCCF_HISTOGRAMV2EXISTS = 0x00000008, - - RCCF_DEFAULT = 0 -}; - -class RIF_Child_Chunk : public Chunk -{ -public: - -#if cencon - RIF_Child_Chunk(Environment_Game_Mode_Chunk * const parent, const char * fname, class CWnd * const pWnd, BOOL bDoSoftwareTex); - - void update(class CWnd * const, BOOL bDoSoftwareTex); - void update(class Environment * e, BOOL bDoSoftwareTex); // for where the environment is already loaded - void DeleteAssociatedFiles(Environment_Data_Chunk *) const; -#endif -// constructor from buffer - RIF_Child_Chunk (Chunk_With_Children * const parent, const char * sdata, size_t const ssize); - ~RIF_Child_Chunk(); - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - int const * GetMD5Val(BMP_Flags const & rcbmp); - void SetMD5Val(BMP_Flags const & rcbmp, int const * md5id); - void RemoveMD5Val(char const * bname); - Bitmap_MD5_Chunk * GetMD5Chunk(char const * bname); - void CreateMD5Chunk(BMP_Flags const & rcbmp, int const * md5id); - - Environment_Game_Mode_Chunk * const egm_parent; - - int version_num; - - char * filename; - char * rifname; - - inline BOOL operator == (RIF_Child_Chunk const & c) const - { - return !strcmp(rifname,c.rifname); - } - inline BOOL operator != (RIF_Child_Chunk const & c) const - { - return strcmp(rifname,c.rifname); - } - - List<BMP_Flags> bmps; - - RCC_Flags flags; - - #define ChunkRIFChild_NumReserved 2 - int reserved[ChunkRIFChild_NumReserved]; - - -private: - - friend class Environment_Game_Mode_Chunk; - - -}; - - - -class Preset_Palette_Store_Chunk : public Chunk -{ -public: - -#if cencon - // constructor from Preset_Palette_Chunk - Preset_Palette_Store_Chunk (Chunk_With_Children * const parent, Preset_Palette_Chunk const * const schunk, const char * const srname) - : Chunk (parent,"SETPALST") - , flags(schunk->flags) - , version_num(schunk->version_num) - , reserved1(schunk->reserved1) - , reserved2(schunk->reserved2) - , reserved3(schunk->reserved3) - , rifname(new char[strlen(srname)+1]) - , pplist(schunk->pplist) - { - strcpy(rifname,srname); - } - - // empty constructor - Preset_Palette_Store_Chunk (Chunk_With_Children * const parent, const char * const srname) - : Chunk (parent,"SETPALST") - , flags(0) - , version_num(0) - , reserved1(0) - , reserved2(0) - , reserved3(0) - , rifname(new char[strlen(srname)+1]) - { - strcpy(rifname,srname); - } - -#endif - // constructor from buffer - Preset_Palette_Store_Chunk (Chunk_With_Children * const parent, char const * sdata, size_t const ssize); - ~Preset_Palette_Store_Chunk () - { - if (rifname) delete[] rifname; - } - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - int flags; - int version_num; - - const int reserved1; - const int reserved2; - const int reserved3; - - char * rifname; - - inline BOOL operator == (Preset_Palette_Store_Chunk const & c) const - { - return !strcmp(rifname,c.rifname); - } - inline BOOL operator != (Preset_Palette_Store_Chunk const & c) const - { - return strcmp(rifname,c.rifname); - } - - List<Preset_Palette> pplist; - - -private: - - friend class Environment_Game_Mode_Chunk; - - -}; - - - - - -/////////////////////////////////////////////// - - - -class Coloured_Polygons_Lookup_Chunk : public Chunk -{ -public: - -#if cencon - // constructor from data - defined in cencon - Coloured_Polygons_Lookup_Chunk (Chunk_With_Children * parent, PPM_Header * const palette); -#endif - // constructor from buffer - Coloured_Polygons_Lookup_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize); - - ~Coloured_Polygons_Lookup_Chunk (); - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - int flags; - #define ChunkCPLUFlag_ExternalFile 0x00000001 - - #define ChunkCPLU_NumReserved 7 - int reserved[ ChunkCPLU_NumReserved ]; - - char * filename; - unsigned char * table; - -private: - - friend class Environment_Game_Mode_Chunk; - friend class Environment_Data_Chunk; - - -}; - - - - - -#endif // !included - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/3dc/win95/CL_INIT.CPP b/3dc/win95/CL_INIT.CPP deleted file mode 100644 index beab242..0000000 --- a/3dc/win95/CL_INIT.CPP +++ /dev/null @@ -1,34 +0,0 @@ -#include "cl_init.h" -#include "system.h" // because the 3dc header files don't automatically include the ones they need -#include "equates.h" // because the 3dc header files don't automatically include the ones they need -#include "platform.h" // for VideoModeTypes -#include "shape.h" // because the 3dc header files don't automatically include the ones they need -#include "prototyp.h" // for SDB -#include "d3_image.hpp" // for init functions - -extern "C" extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; - -void CL_Init_All(void) -{ - switch (VideoModeTypeScreen) - { - case VideoModeType_8: - if (ScreenDescriptorBlock.SDB_Flags & SDB_Flag_TLTPalette) - CL_Init_DirectDrawMode(CLV_8TLT); - else - CL_Init_DirectDrawMode(CLV_8); - break; - case VideoModeType_15: - CL_Init_DirectDrawMode(CLV_15); - break; - case VideoModeType_24: - CL_Init_DirectDrawMode(CLV_24); - break; - case VideoModeType_8T: - CL_Init_DirectDrawMode(CLV_8T); - break; - } - - if (ScanDrawDirectDraw != ScanDrawMode) - CL_Init_D3DMode(&(d3d.TextureFormat[d3d.CurrentTextureFormat].ddsd)); -} diff --git a/3dc/win95/CL_INIT.H b/3dc/win95/CL_INIT.H deleted file mode 100644 index 79cfba2..0000000 --- a/3dc/win95/CL_INIT.H +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _included_cl_init_h_ -#define _included_cl_init_h_ - -#error "This file is obsolete" - -#ifdef __cplusplus -extern "C" { -#endif - -#include "d3d.h" // required by d3_func.hpp -#include "d3_func.h" // for D3DINFO definition - -extern int VideoModeTypeScreen; -extern int ScanDrawMode; -extern D3DINFO d3d; - -void CL_Init_All(void); - -#ifdef __cplusplus -}; -#endif - -#endif // !_included_cl_init_h_
\ No newline at end of file diff --git a/3dc/win95/Chunk.cpp b/3dc/win95/Chunk.cpp deleted file mode 100644 index a123ba0..0000000 --- a/3dc/win95/Chunk.cpp +++ /dev/null @@ -1,599 +0,0 @@ -#include <string.h> - -#include "chunk.hpp" - -#if engine - -#define UseLocalAssert No -#include "ourasert.h" -#define assert(x) GLOBALASSERT(x) - -#else - -#if cencon -#include "ccassert.h" -#else -#include <assert.h> -#endif - -#endif - - -#if cencon -#include "environs.hpp" -#else -#define twprintf printf - -#ifdef cencon -#define new my_new -#endif - -char * users_name = "Player"; -#endif - -#include "hash_tem.hpp" -Chunk * Parent_File; - -// Non class functions ( only one as yet ) - -void list_chunks_in_file(List<int> * pList, HANDLE hand, char const * chunk_id) -{ - unsigned long bytes_read; - - char buffer[8]; - BOOL ok = TRUE; - - while (pList->size()) - pList->delete_first_entry(); - - // assuming we start at the front of a parent chunk, - // containing the child chunk specified - - int init_file_pos = SetFilePointer (hand,0,0,FILE_CURRENT); - int file_pos; - int file_length = GetFileSize(hand, 0); - - SetFilePointer (hand,8,0,FILE_CURRENT); - - int chunk_length; - int sub_chunk_ln; - - ReadFile (hand, (long *) &chunk_length, 4, &bytes_read, 0); - - if ((init_file_pos + chunk_length) > file_length) return; - - while ((file_pos = SetFilePointer (hand,0,0,FILE_CURRENT)) - < (init_file_pos + chunk_length) && ok) { - - ok = ReadFile (hand, (long *) buffer, 8, &bytes_read, 0); - if (strncmp(buffer, chunk_id, 8) == 0) - pList->add_entry(file_pos); - - ok = ReadFile (hand, (long *) &sub_chunk_ln, 4, &bytes_read, 0); - - SetFilePointer (hand,sub_chunk_ln-12,0,FILE_CURRENT); - } -} - -#ifndef RIFF_OPTIMIZE -List<int> list_chunks_in_file (HANDLE & hand, const char * chunk_id) -{ - - List<int> chunk_list; - - list_chunks_in_file(&chunk_list, hand, chunk_id); - - return chunk_list; -} -#endif - -////////////////////////////////////////////// - - -// Class Chunk functions - -Chunk::~Chunk() -{ - if (parent) { - if (parent->children == this) { - parent->children = next; - if (next) - next->previous = previous; - } - else { - if (previous) - previous->next = next; - if (next) - next->previous = previous; - } - } -} - -Chunk::Chunk(Chunk_With_Children * _parent, const char * _identifier) -: error_code(0) -{ - strncpy (identifier_store, _identifier, 8); - identifier_store[8] = 0; - identifier = identifier_store; - parent = _parent; - next = NULL; - previous = NULL; - - if (parent){ - if (parent->children) { - Chunk * pTail = parent->children; - while (pTail->next) - pTail = pTail->next; - pTail->next = this; - previous = pTail; - } - else - parent->children = this; - } -} - -BOOL Chunk::output_chunk (HANDLE & hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = make_data_block_from_chunk(); - - if (data_block) - { - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - delete [] data_block; - - if (!ok) return FALSE; - } - else if (chunk_size) - { - return(FALSE); - } - return TRUE; -} - - - -char * Chunk::make_data_block_from_chunk () -{ - char * data_block; - size_t block_size; - - block_size = size_chunk(); - - if (!chunk_size) - { - return(0); - } - - data_block = new char [block_size]; - - this->fill_data_block(data_block); - - return data_block; -} - -char * Chunk::make_data_block_for_process () -{ - char * data_block; - size_t block_size; - - block_size = size_chunk_for_process(); - - if (!chunk_size) - { - return(0); - } - - data_block = new char [block_size]; - - fill_data_block_for_process(data_block); - - return data_block; -} - - -size_t Chunk::size_chunk_for_process() -{ - return size_chunk(); -} - - -void Chunk::fill_data_block_for_process(char * data_start) -{ - fill_data_block(data_start); -} - -Chunk_With_Children * Chunk::GetRootChunk(void) -{ - Chunk * retp = this; - - while (retp->parent) retp = retp->parent; - - return (Chunk_With_Children *) retp; -} - -Chunk_With_Children const * Chunk::GetRootChunk(void) const -{ - Chunk const * retp = this; - - while (retp->parent) retp = retp->parent; - - return (Chunk_With_Children const *) retp; -} - - -/////////////////////////////////////// - -// Class Miscellaneous_Chunk functions - -Miscellaneous_Chunk::Miscellaneous_Chunk (Chunk_With_Children * parent, const char * identifier, - const char * _data, size_t _data_size) -: Chunk (parent, identifier), -data(NULL), data_size (_data_size) -{ - if (data_size) - { - data_store = new char [data_size]; - - *((char **) &data) = data_store; - - for (int i = 0; i < (signed)data_size; i++) - data_store[i] = _data[i]; - } - else - { - data_store = NULL; - } - -} - -void Miscellaneous_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - for (int i = 0; i<(signed)(chunk_size-12); i++) - data_start[i] = data[i]; -} - -Miscellaneous_Chunk::~Miscellaneous_Chunk () -{ - delete [] data_store; -} - -/////////////////////////////////////// - -// Class Chunk_With_Children functions - -Chunk_With_Children::~Chunk_With_Children() -{ - while (children) - delete children; -} - -size_t Chunk_With_Children::size_chunk () -{ - Chunk * child_ptr = children; - - chunk_size = 12; // identifier + length - - if (children) - while (child_ptr != NULL) { - chunk_size += child_ptr->size_chunk(); - child_ptr = child_ptr->next; - } - - return chunk_size; - -} - -BOOL Chunk_With_Children::output_chunk (HANDLE &hand) -{ - unsigned long junk; - Chunk * child_ptr = children; - BOOL ok; - - ok = WriteFile (hand, (long *) identifier, 8, &junk, 0); - - if (!ok) return FALSE; - - ok = WriteFile (hand, (long *) &chunk_size, 4, &junk, 0); - - if (!ok) return FALSE; - - if (children) - while (child_ptr != NULL && ok){ - ok = child_ptr->output_chunk(hand); - child_ptr = child_ptr->next; - } - - if (!ok) return FALSE; - - return TRUE; - - -} - - -size_t Chunk_With_Children::size_chunk_for_process() -{ - Chunk * child_ptr = children; - - chunk_size = 12; // identifier + length - - if (children) - while (child_ptr != NULL) { - chunk_size += child_ptr->size_chunk_for_process(); - child_ptr = child_ptr->next; - } - - return chunk_size; - -} - - -void Chunk_With_Children::fill_data_block_for_process(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - Chunk * child_ptr = children; - - if (children) - while (child_ptr != NULL) { - child_ptr->fill_data_block_for_process (data_start); - data_start += child_ptr->chunk_size; - child_ptr = child_ptr->next; - } - -} - - - -void Chunk_With_Children::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - Chunk * child_ptr = children; - - if (children) - while (child_ptr != NULL) { - child_ptr->fill_data_block (data_start); - data_start += child_ptr->chunk_size; - child_ptr = child_ptr->next; - } - -} - -#ifndef RIFF_OPTIMIZE -List<Chunk *> Chunk_With_Children::lookup_child (const char * class_ident) const -{ - List<Chunk *> child_list; - - lookup_child(class_ident,child_list); - - return child_list; -} -#endif - -void Chunk_With_Children::lookup_child (const char * class_ident,List<Chunk*>& child_list) const -{ - //make sure the list is empty first - while(child_list.size()) - { - child_list.delete_first_entry(); - } - - Chunk * child_ptr = children; - - if (children) - while (child_ptr != NULL) { - if (strncmp (class_ident, child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - child_list.add_entry(child_ptr); - } - child_ptr = child_ptr->next; - } - - -} - -unsigned Chunk_With_Children::count_children (char const * class_ident) const -{ - unsigned nChildren = 0; - - Chunk * child_ptr = children; - - if (children) - while (child_ptr != NULL) { - if (strncmp (class_ident, child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - ++ nChildren; - } - child_ptr = child_ptr->next; - } - - return nChildren; -} - -Chunk* Chunk_With_Children::lookup_single_child (const char * class_ident) const -{ - #if debug - //if debug make sure there is at most one of the required chunk type - Chunk * child_ptr = children; - Chunk * chunk_found=0; - if (children) - while (child_ptr != NULL) { - if (strncmp (class_ident, child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - assert(!chunk_found); - chunk_found=child_ptr; - } - child_ptr = child_ptr->next; - } - return chunk_found; - #else - Chunk * child_ptr = children; - - if (children) - while (child_ptr != NULL) { - if (strncmp (class_ident, child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - return child_ptr; - } - child_ptr = child_ptr->next; - } - return 0; - #endif - - - -} - -void Chunk_With_Children::prepare_for_output() -{ - Chunk * child_ptr = children; - if (children) - while (child_ptr != NULL){ - child_ptr->prepare_for_output (); - child_ptr = child_ptr->next; - } -} - -void Chunk_With_Children::post_input_processing() -{ - Chunk * child_ptr = children; - if (children) - while (child_ptr != NULL){ - child_ptr->post_input_processing (); - child_ptr = child_ptr->next; - } -} - -/////////////////////////////////////////////////// -//Chunk registering stuff - - -class RifRegEntry -{ - public: - int chunk_id_1; - int chunk_id_2; - int parent_id_1; - int parent_id_2; - Chunk * (* m_pfnCreate) (Chunk_With_Children* parent,const char* data); - - - /* - For two members of this class to be considered similar there chunk_is members must match. - If both parent_id members are zero for one of the objects being compared , then they are considered - equal regardless of the parent_id members of the other object. - Otherwise the parent_id members of the two objects must match. - (This is done because not all of the constructors insist on a given parent) - */ - inline bool operator == (RifRegEntry const & rEntry) const - { - if(chunk_id_1 != rEntry.chunk_id_1 || chunk_id_2 != rEntry.chunk_id_2) return FALSE; - if(parent_id_1 == 0 && parent_id_2 == 0) return TRUE; - if(rEntry.parent_id_1 == 0 && rEntry.parent_id_2 == 0) return TRUE; - return parent_id_1 == rEntry.parent_id_1 && parent_id_2 == rEntry.parent_id_2; - } - inline bool operator != (RifRegEntry const & rEntry) const - { - return ! operator == (rEntry); - } -}; - -inline unsigned HashFunction(RifRegEntry const & rEntry) -{ - return HashFunction(rEntry.chunk_id_1 + rEntry.chunk_id_2); -} - -static HashTable<RifRegEntry> * g_pRifRegister = NULL; - -void Chunk::Register(const char* idChunk,const char* idParent, Chunk * (* pfnCreate) (Chunk_With_Children* parent,const char* data) ) -{ - static HashTable<RifRegEntry> reg; - char temp_id[8]; - - g_pRifRegister = ® - - RifRegEntry entry; - - strncpy(temp_id,idChunk,8); - entry.chunk_id_1 = *(int*) &temp_id[0]; - entry.chunk_id_2 = *(int*) &temp_id[4]; - entry.m_pfnCreate = pfnCreate; - - if(idParent) - { - strncpy(temp_id,idParent,8); - entry.parent_id_1 = *(int*) &temp_id[0]; - entry.parent_id_2 = *(int*) &temp_id[4]; - } - else - { - entry.parent_id_1 = 0; - entry.parent_id_2 = 0; - } - - reg.AddAsserted(entry); -} - -Chunk* Chunk_With_Children::DynCreate(const char* data) -{ - /* - Look in hash tables for a constructor for this block - If none exists , create a Miscellaneous_Chunk - */ - if (g_pRifRegister) - { - RifRegEntry test; - test.chunk_id_1 = *(int*) data; - test.chunk_id_2 = *(int*) &data[4]; - test.parent_id_1 = *(int*) identifier; - test.parent_id_2 = *(int*) &identifier[4]; - test.m_pfnCreate = NULL; - - RifRegEntry const * pEntry = g_pRifRegister->Contains(test); - if (pEntry) - { - return pEntry->m_pfnCreate(this,data); - } - } - return new Miscellaneous_Chunk(this,data,(data + 12), (*(int *) (data + 8))-12); -} - - - - - - - - - - - diff --git a/3dc/win95/Chunk.hpp b/3dc/win95/Chunk.hpp deleted file mode 100644 index e7afcb4..0000000 --- a/3dc/win95/Chunk.hpp +++ /dev/null @@ -1,687 +0,0 @@ -// Chunk library - -#ifndef _chunk_hpp -#define _chunk_hpp 1 - - -#if engine - - #include "3dc.h" - #include "mem3dc.h" // for debug new and delete - - - #include "inline.h" - -#if SupportModules - - #include "module.h" - -#endif - - #include "list_tem.hpp" - - -#endif - -#if cencon - -#include "AFXWIN.H" - -#ifdef _DEBUG -#undef new -#define new DEBUG_NEW -#define my_new DEBUG_NEW -#else -#define my_new new -#endif - -#include "list_tem.hpp" - -#endif - -#if objedit || sprite_edit || ANIMEXP -#include "StdAfx.h" -#include "list_tem.hpp" -#endif - -#if shpedit -#include "stdafx.h" -#include "list_tem.hpp" -#endif - -#if standard -#include "advwin32.h" -#include <windows.h> -#include "list_tem.hpp" -#endif - - -#define CHUNK_FAILED_ON_LOAD -1 -#define CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED -2 -#define CHUNK_FAILED_ON_WRITE -3 -#define CHECK_FAILED_NOT_OPEN -4 - -#define DisableLock 1 - -#define GENERAL_FLAG_LOCKED 0x0000001 - -// Non class functions ( only one as yet ) - -// The function will return a list of file pointers -// for the starting position of each chunk within a chunk -// File pointers are offset from the start of the file. - -// we start at the header of the chunk we are in -// so that we can stop at the end of the chunk - -#if cencon -extern char users_name[]; -#endif - -#ifndef RIFF_OPTIMIZE // define this to get compiler errors where you are calling the old slow functions -extern List<int> list_chunks_in_file (HANDLE &, const char * chunk_id); -#endif -extern void list_chunks_in_file (List<int> * pList, HANDLE, const char * chunk_id); - -// Structures for interfacing with the outside application -// these are going to be basically very C-ee so that C -// functions can also read them - - - -// The basic chunk class structure is as follows -// -// Base_Chunk -// | | -// Chunk_With_Children Data Chunks -// | -// File_Chunk -// - -// Most chunk classes are either derived from the Chunk -// class or the Chunk_With_Children class. - -// A chunk with data is derived from the Chunk class as follows - -// class Sample_Data_Chunk : public Chunk -// { -// public: -// -// // Constructors are placed either here or may be private -// // The constructors for most shape data chunks are private -// // as only the Shape_Chunk can call them. This is because -// // the shape chunk deals with the data. -// // -// // Any constuctor should initialise class chunk with the -// // correct identifier for the current chunk. -// // -// // There are normally two constructors - one for constructing -// // from interface data one for constructing from raw data. -// // -// // A destructor can also be placed here or may not be needed -// // -// // Any variables that are made available for the user should also -// // be placed here. -// // -// // The next three functions are vital for the io functions -// // -// virtual BOOL output_chunk (HANDLE &hand); -// // This function will write the chunk data to the file specified -// // by the windows file handle - hand. -// // -// virtual size_t size_chunk (); -// // This function will return the size of the chunk (including the header). -// // IT MUST SET the variable chunk_size to the size it returns -// // -// virtual fill_data_block (char * data_start); -// // This function will fill a data block with data. The data will be -// // the same as the file data. The data is assumed to be pre-allocated -// // with the size given by the size_chunk function. -// // -// } - -// A chunk with children is derived from the Chunk_With_Children class -// as follows -// -// class Sample_Chunk_With_Children : public Chunk -// { -// public: -// -// // Constructors may be used to construct child chunks from -// // interface data. A parsing constructor should be used for -// // constructing from raw data (look at Shape_Chunk). -// // -// // Any constructor should initialise class Chunk_With_Children with -// // the correct identifier for the current chunk. -// // -// // The Destructor does not need to destroy child chunks as the -// // Chunk_With_Children destructor will automatically do this. -// // -// // The three functions (size_chunk, output_chunk and fill_data_block) -// // are not needed as Chunk_With_Children can deal with these - but may -// // be put in. -// // -// } - -// -// - - -// The logic behind the locking is as follows. - -// There are two functions for locking and unlocking chunks -// these are currently only in the shape and object chunks - -// lock_chunk(File_Chunk &) -// will lock a chunk, this must only be called once -// and will return false if it tries to lock a chunk -// that has already been locked by anyone. - -// unlock_chunk (File_Chunk &, BOOL updatedyn) -// will unlock the chunk locally and in the file if it is not to be updated -// If it is to be updated, it will set the updated flag and -// the chunk can only be locked again once it is written to a file. - -// The user may call File_Chunk::update_file() whenever -// (either after every chunk update, or once a minute) -// Note that this fully unlocks locally locked chunks -// that are being written to the file. - -// Another function File_Chunk::update_chunks_from_file() -// will reload those chunks that have been externally upadted -// This must be done with care!! - -// The objects are associated with shapes primarily -// When a shape is being edited, a list of objects will -// be with that shape in the header. These objects will be locked -// also. - - - -/////////////////////////////////////////////// - -class Chunk -{ -public: - - //destructor - virtual ~Chunk (); - - // constructors - Chunk (class Chunk_With_Children * parent, const char * ident); - - virtual size_t size_chunk () = 0; - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start) = 0; - - // this function is virtual, but will probably not be used elsewhere - virtual char * make_data_block_from_chunk (); - - - // Selective output functions, these are similar to the normal ones - // and will normally call the equivalents. - // special chunks will have there own functions which will only respond - // if they have a flag set - - virtual char * make_data_block_for_process(); - - virtual size_t size_chunk_for_process(); - - virtual void fill_data_block_for_process(char * data_start); - - // these functions are virtual, but will only be used sparingly - - virtual void prepare_for_output() - {} - - virtual void post_input_processing() - {} - - const char * identifier; - - int error_code; - - // this allows chunks with children to trap miscellaneous chunks - // that shouldn't be miscellaneous !!! - virtual BOOL r_u_miscellaneous() - { return FALSE; } - - static void Register(const char* idChunk,const char* idParent ,Chunk * (* pfnCreate) (Chunk_With_Children* parent,const char* data) ); - -private: - - // copy - private to stop chunks - // from being copied - Chunk (const Chunk &); - // ditto - void operator=(const Chunk &); - - // pointers to siblings - - friend class Chunk_With_Children; - friend class Sprite_Header_Chunk; // sprite updating needs to scan through all child chunks - friend class File_Chunk; - friend class RIF_File_Chunk; - friend class Shape_Chunk; - - Chunk * next; - Chunk * previous; - - // identifier store - - char identifier_store[9]; - -protected: - - size_t chunk_size; - - // pointer to parent - class Chunk_With_Children * parent; - -public : - - class Chunk_With_Children * GetRootChunk(void); - class Chunk_With_Children const * GetRootChunk(void) const; - -}; - - -/////////////////////////////////////////////// - -class Miscellaneous_Chunk : public Chunk -{ -public: - - Miscellaneous_Chunk (Chunk_With_Children * parent, const char * identifier, - const char * _data, size_t _data_size); - - - virtual ~Miscellaneous_Chunk (); - - virtual size_t size_chunk () - { - return (chunk_size = (data_size + 12)); - } - - virtual void fill_data_block (char * data_start); - - const size_t data_size; - const char * const data; - - // this allows chunks with children to trap miscellaneous chunks - // that shouldn't be miscellaneous !!! - virtual BOOL r_u_miscellaneous() - { return TRUE; } - -private: - - char * data_store; - -}; - - -/////////////////////////////////////////////// - -class Chunk_With_Children : public Chunk -{ - -public: - - virtual ~Chunk_With_Children(); - - Chunk_With_Children (Chunk_With_Children * parent, const char * identifier) - : Chunk (parent, identifier), children (NULL) {} - - virtual size_t size_chunk (); - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - virtual void prepare_for_output(); - - virtual void post_input_processing(); - - // look for child chunk(s) - #ifndef RIFF_OPTIMIZE // define this to get compiler errors where you are calling the old slow functions - List<Chunk *> lookup_child (const char *) const; - #endif - void lookup_child (const char *,List<Chunk*>&) const; - Chunk* lookup_single_child(const char*) const; - unsigned count_children(char const *) const; - - // Selective output functions, these are similar to the normal ones - // and will normally call the equivalents. - // special chunks will have there own functions which will only respond - // if they have a flag set - - virtual size_t size_chunk_for_process(); - - virtual void fill_data_block_for_process(char * data_start); - - - Chunk* Chunk_With_Children::DynCreate(const char* data); - -protected: - - friend class Chunk; - friend class File_Chunk; - - // points to a doubly linked list - Chunk * children; - -}; - -///////////////////////////////////////////// -// macros to save typing for chunk with children loader - -extern Chunk * Parent_File; - -#define CHUNK_WITH_CHILDREN_LOADER_PARENT __parent - -#define CHUNK_WITH_CHILDREN_LOADER_INIT_PT1(id,chunkclass) \ -chunkclass::chunkclass(Chunk_With_Children * const CHUNK_WITH_CHILDREN_LOADER_PARENT, char const * __data, size_t const __size) \ -:Chunk_With_Children(CHUNK_WITH_CHILDREN_LOADER_PARENT,id) - -#define CHUNK_WITH_CHILDREN_LOADER_INIT_PT2 { \ - const char * const __buffer_ptr = __data; \ - while (__data - __buffer_ptr < (signed)__size){ \ - if (*(int *)(__data + 8) + (__data-__buffer_ptr) > (signed)__size){ \ - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; \ - break;} - -#define LOCKABLE_CHUNK_WITH_CHILDREN_LOADER_INIT_PT1(id,chunkclass) \ -chunkclass::chunkclass(Chunk_With_Children * const CHUNK_WITH_CHILDREN_LOADER_PARENT, char const * __data, size_t const __size) \ -:Lockable_Chunk_With_Children(CHUNK_WITH_CHILDREN_LOADER_PARENT,id) - -#define LOCKABLE_CHUNK_WITH_CHILDREN_LOADER_INIT_PT2 { \ - const char * const __buffer_ptr = __data; \ - while (__data - __buffer_ptr < (signed) __size){ \ - if (*(int *)(__data + 8) + (__data-__buffer_ptr) > (signed) __size){ \ - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; \ - break;} - -#define CHUNK_WITH_CHILDREN_LOADER_INIT(id,chunkclass) \ - CHUNK_WITH_CHILDREN_LOADER_INIT_PT1(id,chunkclass) \ - CHUNK_WITH_CHILDREN_LOADER_INIT_PT2 - -#define LOCKABLE_CHUNK_WITH_CHILDREN_LOADER_INIT(id,chunkclass) \ - LOCKABLE_CHUNK_WITH_CHILDREN_LOADER_INIT_PT1(id,chunkclass) \ - LOCKABLE_CHUNK_WITH_CHILDREN_LOADER_INIT_PT2 - -#define CHUNK_WITH_CHILDREN_LOADER_FOR(id,chunkclass) \ - else if (!strncmp(__data,id,8)){ \ - new chunkclass(this,__data+12,*(int *)(__data+8)-12); \ - __data += *(int *)(__data+8);} - -#define CHUNK_WITH_CHILDREN_LOADER_END \ - else { \ - new Miscellaneous_Chunk (this, __data, (__data + 12), (*(int *) (__data + 8)) -12 ); \ - __data += *(int *)(__data + 8);}}} - -// example: -// -// CHUNK_WITH_CHILDREN_LOADER_INIT("GAMEMODE",Environment_Game_Mode_Chunk) -// CHUNK_WITH_CHILDREN_LOADER_FOR("ENVPALET",Environment_Palette_Chunk) -// CHUNK_WITH_CHILDREN_LOADER_FOR("ENVTXLIT",Environment_TLT_Chunk) -// CHUNK_WITH_CHILDREN_LOADER_FOR("CLRLOOKP",Coloured_Polygons_Lookup_Chunk) -// CHUNK_WITH_CHILDREN_LOADER_FOR("RIFCHILD",RIF_Name_Chunk) -// CHUNK_WITH_CHILDREN_LOADER_END - -/////////////////////////////////////////////// -//macros for use in chunk construction from buffer, assume buffer is called data - -//read variable of type 'type' -#define CHUNK_EXTRACT(var,type) \ - var=*(type*)data; \ - data+=sizeof(type); - -//read 4 byte aligned string -#define CHUNK_EXTRACT_STRING(var) { \ - int __length=strlen(data); \ - if(__length) \ - { \ - var=new char[__length+1]; \ - strcpy(var,data); \ - } \ - else var=0; \ - data+=(__length+4) &~3 ;} - -//read array -//length is an int (filled in by macro) -//pointer is a pointer of type 'type' -#define CHUNK_EXTRACT_ARRAY(length,pointer,type){\ - CHUNK_EXTRACT(length,int) \ - if(length) \ - { \ - pointer=new type[length]; \ - for(int __i=0;__i<length;__i++) \ - { \ - CHUNK_EXTRACT(pointer[__i],type) \ - } \ - } \ - else pointer=0;} - - -//macros for use in fill_data_block - -#define CHUNK_FILL_START \ - strncpy (data, identifier, 8); \ - data += 8; \ - *(int *) data = chunk_size; \ - data += 4; - - -//write variable of type 'type' -#define CHUNK_FILL(var,type) \ - *(type*)data=var; \ - data+=sizeof(type); - -//write 4 byte aligned string -#define CHUNK_FILL_STRING(var) \ - if(var) strcpy(data,var); \ - else *data=0; \ - data+=(strlen(data)+4)&~3; - -#define CHUNK_FILL_ARRAY(length,pointer,type){\ - CHUNK_FILL(length,int) \ - for(int __i=0;__i<length;__i++) \ - { \ - CHUNK_FILL(pointer[__i],type); \ - } \ -} - -//macros for use in size_chunk - -#define CHUNK_SIZE_START \ - chunk_size = 12 - - -//size of variable of type 'type' -#define CHUNK_SIZE(var,type) \ - + sizeof(type) - -//size of 4 byte aligned string -#define CHUNK_SIZE_STRING(string) \ - + (string ? (strlen(string)+4)&~3 : 4) - -#define CHUNK_SIZE_ARRAY(length,pointer,type) \ - + sizeof(int) \ - + (length * sizeof(type)) - -#define CHUNK_SIZE_END ; - -/////////////////////////////////////////////// - -class GodFather_Chunk : public Chunk_With_Children -{ -public: - - GodFather_Chunk () - : Chunk_With_Children (NULL, "REBINFF2") - {} - - GodFather_Chunk (char * buffer, size_t size); -}; - - -/////////////////////////////////////////////// - -/* -Macro for adding chunk class to list of that can be created using DynCreate -Chunks registered this way can be created as a child of any chunk -*/ - -#define RIF_IMPLEMENT_DYNCREATE(idChunk,tokenClassName) _RIF_IMPLEMENT_DYNCREATE_LINE_EX(idChunk,tokenClassName,__LINE__) -#define _RIF_IMPLEMENT_DYNCREATE_LINE_EX(idChunk,tokenClassName,nLine) _RIF_IMPLEMENT_DYNCREATE_LINE(idChunk,tokenClassName,nLine) - -#define _RIF_IMPLEMENT_DYNCREATE_LINE(idChunk,tokenClassName,nLine) \ -static Chunk * RifCreateClassObject ## tokenClassName ##_## nLine (Chunk_With_Children* parent,const char* data) { \ - Chunk * pChunk = new tokenClassName(parent,data+12,(*(int *) (data + 8))-12); \ - return pChunk; \ -} \ - class RegisterRifChunkClass ## tokenClassName ##_## nLine { \ - public: RegisterRifChunkClass ## tokenClassName ##_## nLine () { \ - Chunk::Register(idChunk ,0,RifCreateClassObject ## tokenClassName ##_## nLine); \ - } \ -} rifcc ## tokenClassName ##_## nLine; - -/* -Macro for adding chunk class to list of that can be created using DynCreate. -Chunks registered this way will only be created as children of the parent named -*/ - - -#define RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT(idChunk,tokenClassName,idParent,parentClassName) _RIF_IMPLEMENT_DYNCREATE_PARENT_LINE_EX(idChunk,tokenClassName,idParent,parentClassName,__LINE__) -#define _RIF_IMPLEMENT_DYNCREATE_PARENT_LINE_EX(idChunk,tokenClassName,idParent,parentClassName,nLine) _RIF_IMPLEMENT_DYNCREATE_PARENT_LINE(idChunk,tokenClassName,idParent,parentClassName,nLine) - -#define _RIF_IMPLEMENT_DYNCREATE_PARENT_LINE(idChunk,tokenClassName,idParent,parentClassName,nLine) \ -static Chunk * RifCreateClassObject ## tokenClassName ##_## nLine (Chunk_With_Children* parent,const char* data) { \ - Chunk * pChunk = new tokenClassName((parentClassName*)parent,data+12,(*(int *) (data + 8))-12); \ - return pChunk; \ -} \ - class RegisterRifChunkClass ## tokenClassName ##_## nLine { \ - public: RegisterRifChunkClass ## tokenClassName ##_## nLine () { \ - Chunk::Register(idChunk ,idParent,RifCreateClassObject ## tokenClassName ##_## nLine); \ - } \ -} rifcc ## tokenClassName ##_## nLine; - - -/* -Load from buffer function for standard Chunk_With_Children -*/ - -#define CHUNK_WITH_CHILDREN_LOADER(id,chunk_class) \ -chunk_class::chunk_class(Chunk_With_Children * const parent,char const * __data, size_t const __size)\ -:Chunk_With_Children(parent,id)\ -{\ - const char * __buffer_ptr = __data;\ - while ((__data-__buffer_ptr)< (signed) __size) {\ - if ((*(int *)(__data + 8)) + (__data-__buffer_ptr) > (signed) __size) {\ - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;\ - break;\ - }\ - \ - DynCreate(__data);\ - __data += *(int *)(__data + 8);\ - }\ -} -/* -Load from buffer function for standard Lockable_Chunk_With_Children -*/ - -#define LOCKABLE_CHUNK_WITH_CHILDREN_LOADER(id,chunk_class) \ -chunk_class::chunk_class(Chunk_With_Children * const parent,char const * __data, size_t const __size)\ -:Lockable_Chunk_With_Children(parent,id)\ -{\ - const char * __buffer_ptr = __data;\ - while ((__data-__buffer_ptr)< (signed) __size) {\ - if ((*(int *)(__data + 8)) + (__data-__buffer_ptr) > (signed) __size) {\ - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;\ - break;\ - }\ - \ - DynCreate(__data);\ - __data += *(int *)(__data + 8);\ - }\ -} - - -//macros for forcing inclusion of chunk files from a library -#define FORCE_CHUNK_INCLUDE_START //not needed anymore - -#define FORCE_CHUNK_INCLUDE(filename)\ - extern int __Chunk_Include_##filename;\ - int* p__Chunk_Include_##filename =& __Chunk_Include_##filename; - -#define FORCE_CHUNK_INCLUDE_END //not needed anymore - - -#define FORCE_CHUNK_INCLUDE_IMPLEMENT(filename) int __Chunk_Include_##filename; - -/* -//eg. -FORCE_CHUNK_INCLUDE_START -FORCE_CHUNK_INCLUDE(mishchnk) -FORCE_CHUNK_INCLUDE(shpchunk) -FORCE_CHUNK_INCLUDE(obchunk) -FORCE_CHUNK_INCLUDE(envchunk) -FORCE_CHUNK_INCLUDE(animchnk) -FORCE_CHUNK_INCLUDE(hierchnk) -FORCE_CHUNK_INCLUDE(animobs) -FORCE_CHUNK_INCLUDE(sndchunk) -FORCE_CHUNK_INCLUDE(avpchunk) -FORCE_CHUNK_INCLUDE(bmpnames) -FORCE_CHUNK_INCLUDE(chunkpal) -FORCE_CHUNK_INCLUDE(dummyobjectchunk) -FORCE_CHUNK_INCLUDE(enumchnk) -FORCE_CHUNK_INCLUDE(enumsch) -FORCE_CHUNK_INCLUDE(fragchnk) -FORCE_CHUNK_INCLUDE(gsprchnk) -FORCE_CHUNK_INCLUDE(hierplace) -FORCE_CHUNK_INCLUDE(ltchunk) -FORCE_CHUNK_INCLUDE(oechunk) -FORCE_CHUNK_INCLUDE(pathchnk) -FORCE_CHUNK_INCLUDE(sprchunk) -FORCE_CHUNK_INCLUDE(strachnk) -FORCE_CHUNK_INCLUDE(toolchnk) -FORCE_CHUNK_INCLUDE(wpchunk) -FORCE_CHUNK_INCLUDE_END -*/ - -#endif // !included - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/3dc/win95/D3_IMAGE.CPP b/3dc/win95/D3_IMAGE.CPP deleted file mode 100644 index c068b82..0000000 --- a/3dc/win95/D3_IMAGE.CPP +++ /dev/null @@ -1,2491 +0,0 @@ -#include <stdlib.h> -#include <string.h> - -#include "d3_image.hpp" -#include "platform.h" - -// define = 1 if you dont have pre-quantized images to load into palettized D3D texture surfaces -#define QUANTISE_ON_LOAD 0 - -#if debug -#define DEBUG_TRANSPARENCY 1 -#else -#define DEBUG_TRANSPARENCY 0 -#endif - -// image loader stuff - -#if OUTPUT_LOG -#include "debuglog.hpp" -LogFile CL_LogFile("DB_IMLD.LOG"); -#endif - -#if TIME_LOADS -unsigned int OpenTime; -unsigned int CloseTime; -unsigned int ReadTime; -#endif - -static inline unsigned long read_le_dword(D3I_FILE * f) -{ - unsigned char d1,d2,d3,d4; - d3i_fread(&d1,1,1,f); - d3i_fread(&d2,1,1,f); - d3i_fread(&d3,1,1,f); - d3i_fread(&d4,1,1,f); - - return (unsigned long)d1 | (unsigned long)d2<<8 | (unsigned long)d3<<16 | (unsigned long)d4<<24; -} - -static inline unsigned short read_le_word(D3I_FILE * f) -{ - unsigned char d1,d2; - d3i_fread(&d1,1,1,f); - d3i_fread(&d2,1,1,f); - - return (unsigned short)d1 | (unsigned short)((unsigned short)d2<<8); -} - -// some default globals -CL_ImageMode CL_Image::imode = CLM_GLOBALPALETTE; -CL_ImageMode CL_Image::imode_d3d = CLM_ATTACHEDPALETTE; -CL_ImageMode CL_Image::imode_ddraw = CLM_GLOBALPALETTE; -LPDDSURFACEDESC CL_Image::format = 0; -unsigned int CL_Image::bitsperpixel; -unsigned int CL_Image::bitsperpixel_d3d; -unsigned int CL_Image::bitsperpixel_ddraw; -CL_LoadMode CL_Image::lmode = CLL_DDSURFACE; - -CL_DX_Format CL_Pixel_32::f; -CL_DX_Format CL_Pixel_32::f_d3d; -CL_DX_Format CL_Pixel_32::f_ddraw; -CL_DX_Format CL_Pixel_16::f; -CL_DX_Format CL_Pixel_16::f_d3d; -CL_DX_Format CL_Pixel_16::f_ddraw; - - -void CL_Image::DeleteNotMips(void) -{ - if (im24) - { - delete[] *im24; - delete[] im24; - im24 = 0; - } - if (im16) - { - delete[] *im16; - delete[] im16; - im16 = 0; - } - if (im8) - { - delete[] *im8; - delete[] im8; - im8 = 0; - } - if (palette) - { - delete[] palette; - palette = 0; - palette_size = 0; - } - flags.loaded = 0; - flags.raw16bit = 0; -} - -void CL_Image::Delete(void) -{ - DeleteNotMips(); - while (mipmaps.size()) - { - delete mipmaps.last_entry(); - mipmaps.delete_last_entry(); - } -} - - -void CL_Image::Copy(CL_Image const & i2) -{ - if (i2.im24) - { - im24 = new CL_Pixel_24 * [height]; - *im24 = new CL_Pixel_24 [size]; - - CL_Pixel_24 const * sptr = *i2.im24; - CL_Pixel_24 * dptr = *im24; - - for (int i=size; i; --i) - { - *dptr++ = *sptr++; - } - - CL_Pixel_24 const * * dptrptr = (CL_Pixel_24 const * *) im24; - CL_Pixel_24 const * aptr = *im24; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - - if (i2.im16) - { - im16 = new CL_Pixel_16 * [height]; - *im16 = new CL_Pixel_16 [size]; - - CL_Pixel_16 const * sptr = *i2.im16; - CL_Pixel_16 * dptr = *im16; - - for (int i=size; i; --i) - { - *dptr++ = *sptr++; - } - - CL_Pixel_16 const * * dptrptr = (CL_Pixel_16 const * *) im16; - CL_Pixel_16 const * aptr = *im16; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - - if (i2.im8) - { - im8 = new unsigned char * [height]; - *im8 = new unsigned char [size]; - - unsigned char const * sptr = *i2.im8; - unsigned char * dptr = *im8; - - for (int i=size; i; --i) - { - *dptr++ = *sptr++; - } - - unsigned char const * * dptrptr = (unsigned char const * *) im8; - unsigned char const * aptr = *im8; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - - if (i2.palette) - { - palette = new CL_Pixel_24 [palette_size]; - - CL_Pixel_24 const * sptr = i2.palette; - CL_Pixel_24 * dptr = palette; - - for (int i=palette_size; i; --i) - { - *dptr++ = *sptr; - } - } - - if (i2.name) - { - name = new char [strlen(i2.name)+1]; - strcpy(name,i2.name); - } - - if (i2.fname) - { - fname = new char [strlen(i2.fname)+1]; - strcpy(fname,i2.fname); - } - - for (CLIF<CL_Image *> i_mip(&i2.mipmaps); !i_mip.done(); i_mip.next()) - { - mipmaps.add_entry_end(new CL_Image(*i_mip())); - } -} - - -CL_Image::~CL_Image() -{ - Delete(); - if (fname) delete[] fname; - if (name) delete[] name; -} - - -CL_Image::CL_Image(CL_Image const & i2) -: width(i2.width) -, height(i2.height) -, size(i2.size) -, im24(0) -, im16(0) -, im8(0) -, palette(0) -, palette_size(i2.palette_size) -, fname(0) -, name(0) -, flags(i2.flags) -{ - Copy(i2); -} - - -CL_Image & CL_Image::operator = (CL_Image const & i2) -{ - if (&i2 != this) - { - Delete(); - if (fname) delete[] fname; - if (name) delete[] name; - - width = i2.width; - height = i2.height; - size = i2.size; - palette_size = i2.palette_size; - - fname = 0; - name = 0; - - flags = i2.flags; - - Copy(i2); - } - return *this; -} - - -CL_Error CL_Image::Make(int const _width, int const _height) -{ - Delete(); - - width = _width; - height = _height; - palette_size = 0; - size = width*height; - - switch (imode) - { - case CLM_ATTACHEDPALETTE: - { - palette_size = 256; - palette = new CL_Pixel_24 [palette_size]; - } - case CLM_GLOBALPALETTE: - case CLM_TLTPALETTE: - { - im8 = new unsigned char * [height]; - *im8 = new unsigned char [size]; - - unsigned char const * * dptrptr = (unsigned char const * *) im8; - unsigned char * dptr = *im8; - for (int i=height; i; --i, dptr+=width) - { - *dptrptr++ = dptr; - } - - break; - } - case CLM_24BIT: - { - im24 = new CL_Pixel_24 * [height]; - *im24 = new CL_Pixel_24 [size]; - - CL_Pixel_24 const * * dptrptr = (CL_Pixel_24 const * *) im24; - CL_Pixel_24 const * aptr = *im24; - for (int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - break; - } - case CLM_16BIT: - { - im16 = new CL_Pixel_16 * [height]; - *im16 = new CL_Pixel_16 [size]; - - CL_Pixel_16 const * * dptrptr = (CL_Pixel_16 const * *) im16; - CL_Pixel_16 const * aptr = *im16; - for (int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - break; - } - case CLM_32BIT: - { - im32 = new CL_Pixel_32 * [height]; - *im32 = new CL_Pixel_32 [size]; - - CL_Pixel_32 const * * dptrptr = (CL_Pixel_32 const * *) im32; - CL_Pixel_32 const * aptr = *im32; - for (int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - break; - } - default: - return CLE_INVALIDDXMODE; - } - - flags.loaded = 1; - return CLE_OK; -} - - -CL_Error CL_Image::MakeRandom(int const _width, int const _height, int const seed) -{ - Delete(); - - if (-1!=seed) srand((unsigned int)seed); - - width = _width; - height = _height; - size = width*height; - palette_size = 0; - - switch (imode) - { - case CLM_ATTACHEDPALETTE: - { - palette_size = 256; - palette = new CL_Pixel_24 [palette_size]; - CL_Pixel_24 * palP = palette; - for (int i=palette_size; i; --i, ++palP) - { - *palP = CL_Pixel_24(rand()&255,rand()&255,rand()&255); - } - } - case CLM_GLOBALPALETTE: - case CLM_TLTPALETTE: - { - im8 = new unsigned char * [height]; - *im8 = new unsigned char [size]; - - unsigned char const * * dptrptr = (unsigned char const * *) im8; - unsigned char * dptr = *im8; - for (int i=height; i; --i) - { - *dptrptr++ = dptr; - for (int j=width; j; --j, ++dptr) - *dptr = (unsigned char)(rand()&(palette_size-1)); - } - - break; - } - case CLM_24BIT: - { - im24 = new CL_Pixel_24 * [height]; - *im24 = new CL_Pixel_24 [size]; - - CL_Pixel_24 const * * dptrptr = (CL_Pixel_24 const * *) im24; - CL_Pixel_24 * aptr = *im24; - for (int i=height; i; --i) - { - *dptrptr++ = aptr; - for (int j=width; j; --j, ++aptr) - *aptr = CL_Pixel_24(rand()&255,rand()&255,rand()&255); - } - - break; - } - case CLM_16BIT: - { - im16 = new CL_Pixel_16 * [height]; - *im16 = new CL_Pixel_16 [size]; - - CL_Pixel_16 const * * dptrptr = (CL_Pixel_16 const * *) im16; - CL_Pixel_16 * aptr = *im16; - for (int i=height; i; --i) - { - *dptrptr++ = aptr; - for (int j=width; j; --j, ++aptr) - *aptr = CL_Pixel_24(rand()&255,rand()&255,rand()&255); - } - - break; - } - case CLM_32BIT: - { - im32 = new CL_Pixel_32 * [height]; - *im32 = new CL_Pixel_32 [size]; - - CL_Pixel_32 const * * dptrptr = (CL_Pixel_32 const * *) im32; - CL_Pixel_32 * aptr = *im32; - for (int i=height; i; --i) - { - *dptrptr++ = aptr; - for (int j=width; j; --j, ++aptr) - *aptr = CL_Pixel_24(rand()&255,rand()&255,rand()&255); - } - - break; - } - default: - return CLE_INVALIDDXMODE; - } - - flags.loaded = 1; - return CLE_OK; -} - - -CL_Error CL_Image::Load_BMP(D3I_FILE * f) -{ - if (!f) return CLE_OPENERROR; - - DeleteNotMips(); - - switch (imode) - { - case CLM_ATTACHEDPALETTE: - case CLM_24BIT: - case CLM_16BIT: - case CLM_32BIT: - break; - default: - return CLE_INVALIDDXMODE; - } - - d3i_fseek(f,0,SEEK_SET); - unsigned short magic; - d3i_fread(&magic,2,1,f); - if (magic != *(unsigned short const *)"BM") return CLE_LOADERROR; - - size_t filesize = read_le_dword(f); - d3i_fseek(f,4,SEEK_CUR); - size_t offset = read_le_dword(f); - size_t headsize = read_le_dword(f); - - unsigned short bitdepth; - - if (12 == headsize) // OS/2 1.x - { - width = read_le_word(f); - height = read_le_word(f); - size = width * height; - if (!width || !height) return CLE_LOADERROR; - unsigned short planes = read_le_word(f); - if (1 != planes) return CLE_LOADERROR; - bitdepth = read_le_word(f); - - if (bitdepth != 24) - { - palette_size = 1<<bitdepth; - palette = new CL_Pixel_24 [palette_size]; - CL_Pixel_24 * rptr = palette; - for (int i=palette_size; i; --i) - { - rptr++->Read(f,CLF_BGR); - } - } - } - else if (40 == headsize || 64 == headsize) // Windows 3.x || OS/2 2.x - { - width = read_le_dword(f); - height = read_le_dword(f); - unsigned short planes = read_le_word(f); - if (1 != planes) return CLE_LOADERROR; - bitdepth = read_le_word(f); - - if (read_le_dword(f)) return CLE_LOADERROR; // compressed bmps not supported - - size = read_le_dword(f); - - d3i_fseek(f,8,SEEK_CUR); - palette_size = read_le_dword(f); - if (!palette_size && bitdepth != 24) palette_size = 1<<bitdepth; - - if (palette_size) - { - d3i_fseek(f,headsize+14,SEEK_SET); - palette = new CL_Pixel_24 [palette_size]; - CL_Pixel_24 * rptr = palette; - for (int i=palette_size; i; --i) - { - rptr++->Read(f,CLF_BGRX); - } - } - } - else return CLE_LOADERROR; - - d3i_fseek(f,offset,SEEK_SET); - - if (palette_size) - { - if (bitdepth < 4) - { - delete[] palette; - palette_size = 0; - return CLE_LOADERROR; - } - - im8 = new unsigned char * [height]; - *im8 = new unsigned char [size]; - - unsigned char const * * dptrptr = (unsigned char const * *) im8; - unsigned char * dptr = *im8; - for (int i=height; i; --i, dptr+=width) - { - *dptrptr++ = dptr; - } - - #if DEBUG_TRANSPARENCY - int num_tps=0; - #endif - for (i=height-1; i>=0; --i) - { - dptr = im8[i]; - - if (4==bitdepth) - { - for (int i=width>>1; i; --i) - { - unsigned char byte; - d3i_fread(&byte,1,1,f); - #if DEBUG_TRANSPARENCY - *dptr = (unsigned char)(byte >> 4 & 0xf); - if (!*dptr) num_tps++; - *++dptr = (unsigned char)(byte & 0xf); - if (!*dptr) num_tps++; - ++dptr; - #else - *dptr++ = (unsigned char)(byte >> 4 & 0xf); - *dptr++ = (unsigned char)(byte & 0xf); - #endif - } - if (width & 1) - { - d3i_fread(dptr,1,1,f); - *dptr &= 0xf; - #if DEBUG_TRANSPARENCY - if (!*dptr) num_tps++; - #endif - } - - d3i_fseek(f,(~(width-1) & 7)>>1,SEEK_CUR); - } - else - { - for (int i=width; i; --i) - { - #if DEBUG_TRANSPARENCY - d3i_fread(dptr,1,1,f); - if (!*dptr) num_tps++; - dptr++; - #else - d3i_fread(dptr++,1,1,f); - #endif - } - d3i_fseek(f,~(width-1) & 3,SEEK_CUR); - } - } - #if DEBUG_TRANSPARENCY - if (num_tps) CL_LogFile.lprintf("-- %d TRANSPARENT PIXELS FOUND\n",num_tps); - #endif - } - else if (CLM_16BIT == imode) - { - im16 = new CL_Pixel_16 * [height]; - *im16 = new CL_Pixel_16 [size]; - - CL_Pixel_16 const * * dptrptr = (CL_Pixel_16 const * *) im16; - CL_Pixel_16 const * aptr = *im16; - for (int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - for (i=height-1; i>=0; --i) - { - CL_Pixel_16 * dptr = im16[i]; - - for (int i=width; i; --i) - { - dptr++->Read(f,CLF_BGR); - } - d3i_fseek(f,~(width*3-1) & 3,SEEK_CUR); - } - - } - else if (CLM_32BIT == imode) - { - im32 = new CL_Pixel_32 * [height]; - *im32 = new CL_Pixel_32 [size]; - - CL_Pixel_32 const * * dptrptr = (CL_Pixel_32 const * *) im32; - CL_Pixel_32 const * aptr = *im32; - for (int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - for (i=height-1; i>=0; --i) - { - CL_Pixel_32 * dptr = im32[i]; - - for (int i=width; i; --i) - { - dptr++->Read(f,CLF_BGR); - } - d3i_fseek(f,~(width*3-1) & 3,SEEK_CUR); - } - - } - else if (CLM_24BIT == imode) - { - im24 = new CL_Pixel_24 * [height]; - *im24 = new CL_Pixel_24 [size]; - - CL_Pixel_24 const * * dptrptr = (CL_Pixel_24 const * *) im24; - CL_Pixel_24 const * aptr = *im24; - for (int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - for (i=height-1; i>=0; --i) - { - CL_Pixel_24 * dptr = im24[i]; - - for (int i=width; i; --i) - { - dptr++->Read(f,CLF_BGR); - } - d3i_fseek(f,~(width*3-1) & 3,SEEK_CUR); - } - - } - else return CLE_INVALIDDXMODE; - - if (palette_size && CLM_ATTACHEDPALETTE != imode) - { - if (CLM_16BIT == imode) - { - im16 = new CL_Pixel_16 * [height]; - *im16 = new CL_Pixel_16 [size]; - - unsigned char const * sptr = *im8; - CL_Pixel_16 * dptr = *im16; - - for (int i=size; i; --i, ++dptr,++sptr) - { - if (*sptr && !palette[*sptr]) - *dptr = dptr->f.dx_black; - else - *dptr = palette[*sptr]; - } - - CL_Pixel_16 const * * dptrptr = (CL_Pixel_16 const * *) im16; - CL_Pixel_16 const * aptr = *im16; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - else if (CLM_32BIT == imode) - { - im32 = new CL_Pixel_32 * [height]; - *im32 = new CL_Pixel_32 [size]; - - unsigned char const * sptr = *im8; - CL_Pixel_32 * dptr = *im32; - - for (int i=size; i; --i, ++dptr,++sptr) - { - if (*sptr && !palette[*sptr]) - *dptr = dptr->f.dx_black; - else - *dptr = palette[*sptr]; - } - - CL_Pixel_32 const * * dptrptr = (CL_Pixel_32 const * *) im32; - CL_Pixel_32 const * aptr = *im32; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - else - { - im24 = new CL_Pixel_24 * [height]; - *im24 = new CL_Pixel_24 [size]; - - unsigned char const * sptr = *im8; - CL_Pixel_24 * dptr = *im24; - - for (int i=size; i; --i, ++dptr,++sptr) - { - if (*sptr && !palette[*sptr]) - *dptr = CL_Pixel_24(0,1,0); - else - *dptr = palette[*sptr]; - } - - CL_Pixel_24 const * * dptrptr = (CL_Pixel_24 const * *) im24; - CL_Pixel_24 const * aptr = *im24; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - - delete[] palette; - palette = 0; - palette_size = 0; - delete[] *im8; - delete[] im8; - im8 = 0; - } - - if (d3i_ferror(f) || d3i_feof(f)) - { - DeleteNotMips(); - return CLE_LOADERROR; - } - - flags.loaded = 1; - return CLE_OK; -} - - -CL_Error CL_Image::Load_PPM(D3I_FILE * f) -{ - if (!f) return CLE_OPENERROR; - - DeleteNotMips(); - - switch (imode) - { - case CLM_24BIT: - case CLM_16BIT: - case CLM_32BIT: - break; - default: - return CLE_INVALIDDXMODE; - } - - d3i_fseek(f,0,SEEK_SET); - unsigned short magic; - d3i_fread(&magic,2,1,f); - if (magic != *(unsigned short const *)"P6") return CLE_LOADERROR; - - d3i_fseek(f,1,SEEK_CUR); - char buf[256]; - char * bufptr = buf; - unsigned int fields[5]; - unsigned int fields_read = 0; - while (fields_read < 3 && bufptr) - { - do bufptr = d3i_fgets(buf, sizeof buf, f); - while ('#'==buf[0] && bufptr); - - int num_fields_read = sscanf(buf,"%u %u %u",&fields[fields_read],&fields[fields_read+1],&fields[fields_read+2]); - if (EOF != num_fields_read) fields_read += num_fields_read; - } - if (fields_read < 3) return CLE_LOADERROR; - width = fields[0]; - height = fields[1]; - unsigned int maxval = fields[2]; - if (maxval > 255) return CLE_LOADERROR; - - size = width * height; - - if (CLM_16BIT == imode) - { - im16 = new CL_Pixel_16 * [height]; - *im16 = new CL_Pixel_16 [size]; - - CL_Pixel_16 * rptr = *im16; - for (int i=size; i; --i) - { - rptr++->Read(f,CLF_RGB,maxval); - } - - CL_Pixel_16 const * * dptrptr = (CL_Pixel_16 const * *) im16; - CL_Pixel_16 const * aptr = *im16; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - else if (CLM_32BIT == imode) - { - im32 = new CL_Pixel_32 * [height]; - *im32 = new CL_Pixel_32 [size]; - - CL_Pixel_32 * rptr = *im32; - for (int i=size; i; --i) - { - rptr++->Read(f,CLF_RGB,maxval); - } - - CL_Pixel_32 const * * dptrptr = (CL_Pixel_32 const * *) im32; - CL_Pixel_32 const * aptr = *im32; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - else - { - im24 = new CL_Pixel_24 * [height]; - *im24 = new CL_Pixel_24 [size]; - - CL_Pixel_24 * rptr = *im24; - for (int i=size; i; --i) - { - rptr++->Read(f,CLF_RGB,maxval); - } - - CL_Pixel_24 const * * dptrptr = (CL_Pixel_24 const * *) im24; - CL_Pixel_24 const * aptr = *im24; - for (i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - } - - if (d3i_ferror(f) || d3i_feof(f)) - { - DeleteNotMips(); - return CLE_LOADERROR; - } - - flags.loaded = 1; - return CLE_OK; -} - - -CL_Error CL_Image::Load_PGM(D3I_FILE * f) -{ - if (!f) return CLE_OPENERROR; - - DeleteNotMips(); - - switch (imode) - { - case CLM_GLOBALPALETTE: - case CLM_TLTPALETTE: - break; - default: - return CLE_INVALIDDXMODE; - } - - d3i_fseek(f,0,SEEK_SET); - unsigned short magic; - d3i_fread(&magic,2,1,f); - if (magic != *(unsigned short const *)"P5") return CLE_LOADERROR; - - d3i_fseek(f,1,SEEK_CUR); - char buf[256]; - char * bufptr = buf; - unsigned int fields[5]; - unsigned int fields_read = 0; - while (fields_read < 3 && bufptr) - { - do bufptr = d3i_fgets(buf, sizeof buf, f); - while ('#'==buf[0] && bufptr); - - int num_fields_read = sscanf(buf,"%u %u %u",&fields[fields_read],&fields[fields_read+1],&fields[fields_read+2]); - if (EOF != num_fields_read) fields_read += num_fields_read; - } - if (fields_read < 3) return CLE_LOADERROR; - width = fields[0]; - height = fields[1]; - unsigned int maxval = fields[2]; - if (maxval > 255) return CLE_LOADERROR; - - size = width * height; - - im8 = new unsigned char * [height]; - *im8 = new unsigned char [size]; - - d3i_fread(*im8,1,size,f); - - unsigned char const * * dptrptr = (unsigned char const * *) im8; - unsigned char const * aptr = *im8; - for (int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - if (d3i_ferror(f) || d3i_feof(f)) - { - DeleteNotMips(); - return CLE_LOADERROR; - } - - flags.loaded = 1; - return CLE_OK; -} - - -CL_Error CL_Image::Load_PWM(D3I_FILE * f) -{ - if (!f) return CLE_OPENERROR; - - DeleteNotMips(); - - switch (imode) - { - case CLM_TLTPALETTE: - break; - default: - return CLE_INVALIDDXMODE; - } - - d3i_fseek(f,0,SEEK_SET); - unsigned short magic; - d3i_fread(&magic,2,1,f); - if (magic != *(unsigned short const *)"P8") return CLE_LOADERROR; - - d3i_fseek(f,1,SEEK_CUR); - char buf[256]; - char * bufptr = buf; - unsigned int fields[5]; - unsigned int fields_read = 0; - while (fields_read < 3 && bufptr) - { - do bufptr = d3i_fgets(buf, sizeof buf, f); - while ('#'==buf[0] && bufptr); - - int num_fields_read = sscanf(buf,"%u %u %u",&fields[fields_read],&fields[fields_read+1],&fields[fields_read+2]); - if (EOF != num_fields_read) fields_read += num_fields_read; - } - if (fields_read < 3) return CLE_LOADERROR; - width = fields[0]; - height = fields[1]; - unsigned int maxval = fields[2]; - if (maxval > 65535) return CLE_LOADERROR; - - size = width * height; - - im16raw = new unsigned short * [height]; - *im16raw = new unsigned short [size]; - - d3i_fread(*im16raw,2,size,f); - - unsigned short const * * dptrptr = (unsigned short const * *) im16raw; - unsigned short const * aptr = *im16raw; - for (int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - if (d3i_ferror(f) || d3i_feof(f)) - { - DeleteNotMips(); - return CLE_LOADERROR; - } - - flags.loaded = 1; - flags.raw16bit = 1; - return CLE_OK; -} - - - -CL_Error CL_Image::GetBitsPerPixel(unsigned int* bpp) -{ - *bpp = bitsperpixel; - return CLE_OK; -} - -CL_Error CL_Image::Load_Image(D3I_FILE * f) -{ - if (!f) return CLE_OPENERROR; - - CL_Error retval = CLE_LOADERROR; - - START_TIMER - - d3i_fseek(f,0,SEEK_SET); - unsigned short magic; - d3i_fread(&magic,2,1,f); - - if ( *(unsigned short const *)"BM" == magic) - retval = Load_BMP(f); - else if ( *(unsigned short const *)"P6" == magic) - retval = Load_PPM(f); - else if ( *(unsigned short const *)"P5" == magic) - retval = Load_PGM(f); - else if ( *(unsigned short const *)"P8" == magic) - retval = Load_PWM(f); - #if OUTPUT_LOG - else CL_LogFile.lputs("** ERROR: Not a recognized file format\n"); - #endif - - END_TIMER(ReadTime) - - #if OUTPUT_LOG - #if TIME_LOADS - CL_LogFile.lprintf("-- Timer Stats (ms): Open %d Read %d Close %d\n",OpenTime,ReadTime,CloseTime); - #endif - #endif - - return retval; -} - - -void CL_Image::PadTo(int const width_unit,int const height_unit) -{ - if (!flags.loaded) return; - - unsigned int const owidth = width; - unsigned int const oheight = height; - - width += width_unit-1; - width &= ~(width_unit-1); - height += height_unit-1; - height &= ~(height_unit-1); - - if (width == owidth && height == oheight) return; // already in spec - - size = width * height; - - CL_Pixel_32 * * const oim32 = im32; - CL_Pixel_16 * * const oim16 = im16; - unsigned char * * const oim8 = im8; - - if (oim32) - { - im32 = new CL_Pixel_32 * [height]; - *im32 = new CL_Pixel_32 [size]; - - CL_Pixel_32 const * * dptrptr = (CL_Pixel_32 const * *) im32; - CL_Pixel_32 const * aptr = *im32; - for (unsigned int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - for (unsigned int y = 0; y < oheight; ++y) - { - CL_Pixel_32 const * sptr = oim32[y]; - CL_Pixel_32 * dptr = im32[y]; - - for (unsigned int x = 0; x < owidth; ++x, ++dptr, ++sptr) - *dptr = *sptr; - - for (; x < width; ++x, ++dptr) - *dptr = CL_Pixel_24(0,0,0); - } - - for (; y < height; ++y) - { - CL_Pixel_32 * dptr = im32[y]; - for (unsigned int x = 0; x < width; ++x, ++dptr) - *dptr = CL_Pixel_24(0,0,0); - } - - delete[] *oim32; - delete[] oim32; - } - - if (oim16) - { - im16 = new CL_Pixel_16 * [height]; - *im16 = new CL_Pixel_16 [size]; - - CL_Pixel_16 const * * dptrptr = (CL_Pixel_16 const * *) im16; - CL_Pixel_16 const * aptr = *im16; - for (unsigned int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - for (unsigned int y = 0; y < oheight; ++y) - { - CL_Pixel_16 const * sptr = oim16[y]; - CL_Pixel_16 * dptr = im16[y]; - - for (unsigned int x = 0; x < owidth; ++x, ++dptr, ++sptr) - *dptr = *sptr; - - for (; x < width; ++x, ++dptr) - *dptr = CL_Pixel_24(0,0,0); - } - - for (; y < height; ++y) - { - CL_Pixel_16 * dptr = im16[y]; - for (unsigned int x = 0; x < width; ++x, ++dptr) - *dptr = CL_Pixel_24(0,0,0); - } - - delete[] *oim16; - delete[] oim16; - } - - if (oim8) - { - im8 = new unsigned char * [height]; - *im8 = new unsigned char [size]; - - unsigned char const * * dptrptr = (unsigned char const * *) im8; - unsigned char const * aptr = *im8; - for (unsigned int i=height; i; --i, aptr+=width) - { - *dptrptr++ = aptr; - } - - for (unsigned int y = 0; y < oheight; ++y) - { - unsigned char const * sptr = oim8[y]; - unsigned char * dptr = im8[y]; - - for (unsigned int x = 0; x < owidth; ++x, ++dptr, ++sptr) - *dptr = *sptr; - - for (; x < width; ++x, ++dptr) - *dptr = 0; - } - - for (; y < height; ++y) - { - unsigned char * dptr = im8[y]; - for (unsigned int x = 0; x < width; ++x, ++dptr) - *dptr = 0; - } - - delete[] *oim8; - delete[] oim8; - } -} - -// implementation of the 'popularity algorithm' for reducing palette - -unsigned int CL_Pixel_24::FVD_Distance(CL_Pixel_24 const & p2) const -{ - unsigned int dg = g > p2.g ? g - p2.g : p2.g - g; - unsigned int db = b > p2.b ? b - p2.b : p2.b - b; - - unsigned int dgb = dg + db + ((dg > db ? dg : db)<<1); - - unsigned int dr = r > p2.r ? r - p2.r : p2.r - r; - dr += dr<<1; // *= 3 - - return dr + dgb + ((dr > dgb ? dr : dgb)<<1); -} - -struct _CL_palpixcnt -{ - unsigned int cnt; - unsigned int palpos; -}; - -int _CL_cmp_palpixcnt(void const * e1, void const * e2) -{ - return ((_CL_palpixcnt *)e2)->cnt - ((_CL_palpixcnt *)e1)->cnt; -} - -CL_Error CL_Image::ReducePalette(unsigned int const num_colours) -{ - if (!flags.loaded) return CLE_LOADERROR; - - if (!palette) return CLE_INVALIDDXMODE; - if (!im8) return CLE_INVALIDDXMODE; - - if (palette_size <= num_colours) return CLE_OK; - - _CL_palpixcnt * const sortarray = new _CL_palpixcnt[palette_size]; - - for (unsigned int i=0; i<palette_size; ++i) - { - sortarray[i].cnt = 0; - sortarray[i].palpos = i; - } - - for (unsigned int y=0; y<height; ++y) - { - unsigned char const * sptr = im8[y]; - - for (unsigned int x=width; x; --x, ++sptr) - ++ sortarray[*sptr].cnt; - } - - unsigned int const palstart = CL_Pixel_24(0,0,0) == palette[0] ? 1 : 0; - qsort(sortarray + palstart, palette_size - palstart, sizeof(_CL_palpixcnt), _CL_cmp_palpixcnt); - - CL_Pixel_24 * const opalette = palette; - unsigned int const opalette_size = palette_size; - palette = new CL_Pixel_24[num_colours]; - palette_size = num_colours; - - for (i=0; i<palette_size; ++i) - palette[i] = opalette[sortarray[i].palpos]; - - delete[] sortarray; - - // umm - if theres black thats not transparent, make sure it doesnt become colour 0 in palette - for (unsigned int pswap=1; pswap<palette_size && 0==palstart && CL_Pixel_24(0,0,0)==palette[0]; ++pswap) - { - palette[0]=palette[pswap]; - palette[pswap]=CL_Pixel_24(0,0,0); - } - - // emergency? - if (0==palstart && CL_Pixel_24(0,0,0)==palette[0]) - palette[0] = CL_Pixel_24(1,1,1); - - unsigned int * const palmaps = new unsigned int [opalette_size]; - palmaps[0] = 0; - for (i=palstart; i<opalette_size; ++i) - { - unsigned int closest = palstart; - unsigned int distance = opalette[i].FVD_Distance(palette[palstart]); - - for (unsigned int j = palstart+1; j<palette_size; ++j) - { - unsigned int thisdist = opalette[i].FVD_Distance(palette[j]); - if (thisdist < distance) - { - distance = thisdist; - closest = j; - } - } - - palmaps[i] = closest; - } - - delete[] opalette; - - for (y=0; y<height; ++y) - { - unsigned char * sptr = im8[y]; - - for (unsigned int x=width; x; --x, ++sptr) - *sptr = (unsigned char)palmaps[*sptr]; - } - - delete[] palmaps; - - return CLE_OK; -} - -// useful filename handling functions - -// returns pointer into string pointing to filename without dirname -static char const * strip_path(char const * n) -{ - char const * rm = strrchr(n,':'); - if (rm) n = rm+1; - rm = strrchr(n,'/'); - if (rm) n = rm+1; - rm = strrchr(n,'\\'); - if (rm) n = rm+1; - - return n; -} - -#if 0 -static char * strip_path(char * n) -{ - char * rm = strrchr(n,':'); - if (rm) n = rm+1; - rm = strrchr(n,'/'); - if (rm) n = rm+1; - rm = strrchr(n,'\\'); - if (rm) n = rm+1; - - return n; -} -#endif - -// removes any .extension from filename by inserting null character -static void strip_file_extension(char * n) -{ - char * dotpos = strrchr(n,'.'); - if (dotpos) *dotpos = 0; -} - -static char * strip_file_extension(char const * n) -{ - char * nn = new char[strlen(n)+1]; - strcpy(nn,n); - strip_file_extension(nn); - return nn; -} - -// CL_Image functions - -CL_Error CL_Image::Locate(char const * iname, int const /* enum_id */) -{ - if (!iname) return CLE_RIFFERROR; - - if (name) - delete[] name; - name = strip_file_extension(strip_path(iname)); - - if (fname) - delete[] fname; - fname = new char[strlen(iname)+1]; - strcpy(fname,iname); - - flags.located = 1; - return CLE_OK; -} - -CL_Error CL_Image::Load(char const * const iname, int const enum_id) -{ - if (iname || CL_EID_INVALID != enum_id || !flags.located) - { - CL_Error locate_err = Locate(iname,enum_id); - - if (locate_err != CLE_OK) - { - EXITONLOCATEFAIL(locate_err,iname,enum_id) - return locate_err; - } - } - - #if OUTPUT_LOG - char const * texformat; - unsigned int redbits = 8; - unsigned int greenbits = 8; - unsigned int bluebits = 8; - switch (imode) - { - case CLM_GLOBALPALETTE: - texformat = "Palettized Display"; - break; - case CLM_TLTPALETTE: - texformat = "Palettized Display with Abstract TLT Palette"; - break; - case CLM_ATTACHEDPALETTE: - texformat = "Palettized Textures"; - break; - case CLM_32BIT: - texformat = "32BIT DX"; - redbits += CL_Pixel_32::f.red_bits_gt8; - redbits -= CL_Pixel_32::f.red_bits_lt8; - greenbits += CL_Pixel_32::f.green_bits_gt8; - greenbits -= CL_Pixel_32::f.green_bits_lt8; - bluebits += CL_Pixel_32::f.blue_bits_gt8; - bluebits -= CL_Pixel_32::f.blue_bits_lt8; - break; - case CLM_24BIT: - texformat = "24-bit for runtime conversion"; - break; - case CLM_16BIT: - texformat = "16BIT DX"; - redbits += CL_Pixel_16::f.red_bits_gt8; - redbits -= CL_Pixel_16::f.red_bits_lt8; - greenbits += CL_Pixel_16::f.green_bits_gt8; - greenbits -= CL_Pixel_16::f.green_bits_lt8; - bluebits += CL_Pixel_16::f.blue_bits_gt8; - bluebits -= CL_Pixel_16::f.blue_bits_lt8; - break; - } - CL_LogFile.lprintf("--%s %s (%u-bit, %u-%u-%u)\n",fname,texformat,bitsperpixel,redbits,greenbits,bluebits); - #endif - - START_TIMER - D3I_FILE * fp = d3i_fopen(fname,"rb"); - END_TIMER(OpenTime) - - if (fp) - { - CL_Error retval = Load_Image(fp); - START_TIMER - d3i_fclose(fp); - END_TIMER(CloseTime) - if (CLE_OK != retval) - { - #if OUTPUT_LOG - CL_LogFile.lputs("** ERROR: unable to read\n"); - #endif - EXITONREADFAIL(fname) - } - return retval; - } - - #if OUTPUT_LOG - CL_LogFile.lputs("** ERROR: unable to open\n"); - #endif - EXITONLOADFAIL(fname) - return CLE_OPENERROR; -} - -CL_Error CL_Image::PreLoad(char const * const iname, int const enum_id) -{ - CL_Error locate_err = Locate(iname,enum_id); - - if (locate_err != CLE_OK) - { - return locate_err; - } - - return CLE_OK; -} - -CL_Error CL_Image::LoadMipMaps(int const n_mips) // assumes locating has been done (ie. PreLoad or Load has been called) -{ - if (!flags.located) return CLE_FINDERROR; - - while (mipmaps.size()) - { - delete mipmaps.last_entry(); - mipmaps.delete_last_entry(); - } - - for (int mip_idx = 1; mip_idx < n_mips; ++mip_idx) - { - CL_Image * mip_n = new CL_Image; - - mip_n->name = new char[strlen(name)+1]; - mip_n->fname = new char[strlen(fname)+1]; - strcpy(mip_n->name,name); - strcpy(mip_n->fname,fname); - - char * dotpos = strrchr(mip_n->fname,'.'); - if (!dotpos) - { - delete mip_n; - break; - } - sprintf(dotpos+3,"%1d",mip_idx); - - mip_n->flags.located = 1; - - if (CLE_OK!=mip_n->Load()) - { - delete mip_n; - break; - } - - if (mip_n->width << mip_idx < width || mip_n->height << mip_idx < height) - { - delete mip_n; - #if OUTPUT_LOG - CL_LogFile.lputs("** Warning: less than half size\n"); - #endif - break; - } - - mipmaps.add_entry_end(mip_n); - } - return CLE_OK; -} - -void CL_Select_Mode(CL_LoadMode const lmode) -{ - switch (lmode) - { - case CLL_D3DTEXTURE: - CL_Image::imode = CL_Image::imode_d3d; - CL_Image::bitsperpixel = CL_Image::bitsperpixel_d3d; - CL_Pixel_16::f = CL_Pixel_16::f_d3d; - CL_Pixel_32::f = CL_Pixel_32::f_d3d; - break; - case CLL_DDSURFACE: - CL_Image::imode = CL_Image::imode_ddraw; - CL_Image::bitsperpixel = CL_Image::bitsperpixel_ddraw; - CL_Pixel_16::f = CL_Pixel_16::f_ddraw; - CL_Pixel_32::f = CL_Pixel_32::f_ddraw; - break; - } - CL_Image::lmode = lmode; -} - -// 3DC interface - -void CL_Init_DirectDrawMode(CL_VideoMode const vmode) -{ - switch (vmode) - { - case CLV_8: - CL_Image::bitsperpixel_ddraw = 8; - CL_Image::imode_ddraw = CLM_GLOBALPALETTE; - break; - case CLV_8TLT: - CL_Image::bitsperpixel_ddraw = 8; - CL_Image::imode_ddraw = CLM_TLTPALETTE; - break; - case CLV_15: - CL_Image::bitsperpixel_ddraw = 16; - CL_Image::imode_ddraw = CLM_16BIT; - CL_Pixel_16::f_ddraw.Init - ( - DisplayPixelFormat.dwRBitMask, - DisplayPixelFormat.dwGBitMask, - DisplayPixelFormat.dwBBitMask - ); - break; - case CLV_24: - CL_Image::bitsperpixel_ddraw = DisplayPixelFormat.dwRGBBitCount; - if (24 == CL_Image::bitsperpixel_ddraw) - CL_Image::imode_ddraw = CLM_24BIT; - else - { - CL_Image::imode_ddraw = CLM_32BIT; - CL_Pixel_32::f_ddraw.Init - ( - DisplayPixelFormat.dwRBitMask, - DisplayPixelFormat.dwGBitMask, - DisplayPixelFormat.dwBBitMask - ); - } - break; - case CLV_8T: - CL_Image::bitsperpixel_ddraw = 8; - CL_Image::imode_ddraw = CLM_16BIT; - CL_Pixel_16::f_ddraw.Init(7<<5,7<<2,3); - break; - } - CL_Select_Mode(CLL_DDSURFACE); -} - - -CL_Error CL_Image::CopyToScanDrawTexture(unsigned char * * const ImagePtrA [], unsigned int n_mips_max) -{ - if (!flags.loaded) return CLE_LOADERROR; - - if (CLL_DDSURFACE != lmode) CL_Select_Mode(CLL_DDSURFACE); - - if (n_mips_max > mipmaps.size()+1) n_mips_max = mipmaps.size()+1; - - if (!*ImagePtrA[0]) - { - if (flags.raw16bit) - { - if (n_mips_max>1) - *ImagePtrA[0] = (unsigned char *) AllocateMem((2*width+1)*(2*height+1)*2/3+(n_mips_max-3)*2); // slightly more than 4/3 w*h*bytedepth - else - *ImagePtrA[0] = (unsigned char *) AllocateMem(width*height*2); - } - else - { - if (n_mips_max>1) - *ImagePtrA[0] = (unsigned char *) AllocateMem((2*width+1)*(2*height+1)*bitsperpixel/24+(n_mips_max-3)*(bitsperpixel/8)); // slightly more than 4/3 w*h*bytedepth - else - *ImagePtrA[0] = (unsigned char *) AllocateMem(width*height*(bitsperpixel>>3)); - } - } - if (!*ImagePtrA[0]) - return CLE_ALLOCFAIL; - - unsigned int my_bitsperpixel = bitsperpixel; - - switch (imode) - { - unsigned char * tptr; - unsigned short * tSptr; - unsigned long * tLptr; - - case CLM_GLOBALPALETTE: - case CLM_TLTPALETTE: - if (flags.raw16bit) - { - my_bitsperpixel = 16; - tSptr = (unsigned short *)*ImagePtrA[0]; - if (tSptr) - { - for (int i=0; i<height; ++i) - { - memcpy(tSptr,im16raw[i],width*sizeof(unsigned short)); - tSptr += width; - } - } - } - else - { - tptr = *ImagePtrA[0]; - if (tptr) - { - for (int i=0; i<height; ++i) - { - memcpy(tptr,im8[i],width); - tptr += width; - } - } - } - break; - case CLM_16BIT: - switch (bitsperpixel) - { - case 8: - tptr = *ImagePtrA[0]; - if (tptr) - { - for (int i=0; i<height; ++i) - { - unsigned char const * i8ptr = im8[i]; - for (int j=width; j; --j) - { - *tptr++ = *i8ptr++; - } - } - } - break; - case 16: - tSptr = (unsigned short *)*ImagePtrA[0]; - if (tSptr) - { - for (int i=0; i<height; ++i) - { - CL_Pixel_16 const * i16ptr = im16[i]; - for (int j=width; j; --j) - { - *tSptr++ = *i16ptr++; - } - } - } - break; - } - break; - case CLM_24BIT: - switch (bitsperpixel) - { - case 24: - tptr = *ImagePtrA[0]; - if (tptr) - { - for (int i=0; i<height; ++i) - { - CL_Pixel_24 const * i24ptr = im24[i]; - for (int j=width; j; --j) - { - *tptr++ = i24ptr->b; - *tptr++ = i24ptr->g; - *tptr++ = i24ptr->r; - i24ptr++; - } - } - } - break; - case 32: - tLptr = (unsigned long *)*ImagePtrA[0]; - if (tLptr) - { - for (int i=0; i<height; ++i) - { - CL_Pixel_32 const * i32ptr = im32[i]; - for (int j=width; j; --j) - { - *tLptr++ = *i32ptr++; - } - } - } - break; - } - break; - default: - return CLE_INVALIDDXMODE; - } - - // now do mipmaps if avail - - CL_Image * last_mipP = this; - - LIF<CL_Image *> i_mip(&mipmaps); - for (int i=1; i<n_mips_max && !i_mip.done(); ++i, i_mip.next()) - { - *ImagePtrA[i] = *ImagePtrA[i-1] + last_mipP->width*last_mipP->height*(my_bitsperpixel>>3); - CL_Error thismipmaperror = i_mip()->CopyToScanDrawTexture(&ImagePtrA[i],1); - if (CLE_OK != thismipmaperror) return thismipmaperror; - last_mipP = i_mip(); - } - return CLE_OK; -} - - - -// Direct X interface - -void CL_Init_D3DMode(LPDDSURFACEDESC const format) -{ - CL_Image::format = format; - - if (format->ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED8) - { - #if QUANTISE_ON_LOAD - CL_Image::imode_d3d = CLM_24BIT; - #else - CL_Image::imode_d3d = CLM_ATTACHEDPALETTE; - #endif - CL_Image::bitsperpixel_d3d = 8; - } - else if (format->ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED4) - { - #if QUANTISE_ON_LOAD - CL_Image::imode_d3d = CLM_24BIT; - #else - CL_Image::imode_d3d = CLM_ATTACHEDPALETTE; - #endif - CL_Image::bitsperpixel_d3d = 4; - } - else if (format->ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED2) - { - #if QUANTISE_ON_LOAD - CL_Image::imode_d3d = CLM_24BIT; - #else - CL_Image::imode_d3d = CLM_ATTACHEDPALETTE; - #endif - CL_Image::bitsperpixel_d3d = 2; - } - else if (format->ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED1) - { - #if QUANTISE_ON_LOAD - CL_Image::imode_d3d = CLM_24BIT; - #else - CL_Image::imode_d3d = CLM_ATTACHEDPALETTE; - #endif - CL_Image::bitsperpixel_d3d = 1; - } - else - { - CL_Image::bitsperpixel_d3d = format->ddpfPixelFormat.dwRGBBitCount; - if (format->ddpfPixelFormat.dwRGBBitCount > 16) - { - CL_Image::imode_d3d = CLM_32BIT; - CL_Pixel_32::f_d3d.Init - ( - format->ddpfPixelFormat.dwRBitMask, - format->ddpfPixelFormat.dwGBitMask, - format->ddpfPixelFormat.dwBBitMask - ); - } - else - { - CL_Image::imode_d3d = CLM_16BIT; - CL_Pixel_16::f_d3d.Init - ( - format->ddpfPixelFormat.dwRBitMask, - format->ddpfPixelFormat.dwGBitMask, - format->ddpfPixelFormat.dwBBitMask - ); - } - } - CL_Select_Mode(CLL_D3DTEXTURE); -} - - -CL_Error CL_Image::CopyToD3DTexture(LPDIRECTDRAWSURFACE * const DDPtrA [], LPVOID * const DDSurfaceA [], int const MemoryType, unsigned int n_mips_max) -{ - if (!flags.loaded) return CLE_LOADERROR; - - WaitForVRamReady(VWS_D3DTEXCREATE); - - if (CLL_D3DTEXTURE != lmode) CL_Select_Mode(CLL_D3DTEXTURE); - - LPDIRECTDRAWSURFACE lpDDS; - DDSURFACEDESC ddsd; - HRESULT ddrval; - - // Check for image being 4 byte aligned - // and fail if it is not - if (width & 3 || height & 3) - { - // return error code - return CLE_DXERROR; - } - - - // Set up the surface description. starting - // with the passed texture format and then - // incorporating the information read from the - // ppm. - memcpy(&ddsd, format, sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddsd.dwFlags = (DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT); - ddsd.ddsCaps.dwCaps = (DDSCAPS_TEXTURE | MemoryType); - ddsd.dwHeight = height; - ddsd.dwWidth = width; - - if (n_mips_max > mipmaps.size()+1) n_mips_max = mipmaps.size()+1; - - if (n_mips_max>1) - { - ddsd.dwFlags |= DDSD_MIPMAPCOUNT; - ddsd.ddsCaps.dwCaps |= DDSCAPS_MIPMAP | DDSCAPS_COMPLEX; - ddsd.dwMipMapCount = n_mips_max; - } - - // Create the surface - ddrval = lpDD->CreateSurface(&ddsd, &lpDDS, NULL); - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return CLE_DXERROR; - #endif - } - - - // now do mipmaps if avail - - if (n_mips_max>1) - { - // We must now traverse the mip-map chain from highest to lowest - // resolutions, For each surface AFTER the first one, we must - // load a new file, using a name obtained from the mip map number - - int MipMapNum = 0; - LPDIRECTDRAWSURFACE lpThisMipMap, lpNextMipMap; - DDSCAPS ddsCaps; - - - lpThisMipMap = lpDDS; - // Component Object Model, increase reference count on - // mip-map surface by one. - lpThisMipMap->AddRef(); - ddsCaps.dwCaps = (DDSCAPS_TEXTURE | DDSCAPS_MIPMAP); - ddrval = DD_OK; - - LIF<CL_Image *> i_mip(&mipmaps); - - CL_Image * last_mipP = this; - - while ((ddrval == DD_OK) && (MipMapNum < n_mips_max)) // both tests in case... - { - // Call LoadPPMIntoDDSurface with lpThisMipMap, new file name, and - // other values. - - *DDSurfaceA[MipMapNum] = last_mipP->CopyToDDSurface(lpThisMipMap); - - // Death trap - if (!*DDSurfaceA[MipMapNum]) - { - return CLE_DXERROR; - } - *DDPtrA[MipMapNum] = lpThisMipMap; - - // Proceed to the next level. - // Collect bonus rings. - ddrval = lpThisMipMap->GetAttachedSurface(&ddsCaps, &lpNextMipMap); - // Necessary to match the manual increment of the reference count on the - // COM texture. I think. - lpThisMipMap->Release(); - // ?? lpNextMipMap = lpThisMipMap; - lpThisMipMap = lpNextMipMap; - - MipMapNum++; - if (!i_mip.done()) - { - last_mipP = i_mip(); - i_mip.next(); - } - } - } - else - { - *DDSurfaceA[0] = CopyToDDSurface(lpDDS); - - if (!*DDSurfaceA[0]) return CLE_DXERROR; - - *DDPtrA[0] = lpDDS; - } - - return CLE_OK; -} - - -CL_Error CL_Image::CopyToDirectDrawSurface(LPDIRECTDRAWSURFACE * const DDPtrA [], LPVOID * const DDSurfaceA [], int const MemoryType, unsigned int n_mips_max) -{ - if (!flags.loaded) return CLE_LOADERROR; - - WaitForVRamReady(VWS_DDCREATE); - - if (CLL_DDSURFACE != lmode) CL_Select_Mode(CLL_DDSURFACE); - - LPDIRECTDRAWSURFACE lpDDS; - DDSURFACEDESC ddsd; - HRESULT ddrval; - - // Check for image being 4 byte aligned - // and fail if it is not - if (width & 3 || height & 3) - { - // return error code - return CLE_DXERROR; - } - - if (n_mips_max > mipmaps.size()+1) n_mips_max = mipmaps.size()+1; - - // Set up the surface description. starting - // with the passed texture format and then - // incorporating the information read from the - // ppm. - memset(&ddsd, 0, sizeof ddsd); - ddsd.dwSize = sizeof ddsd; - ddsd.dwFlags = (DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT); - // Ensure that created surface has same pixel desription - // as primary - memcpy(&ddsd.ddpfPixelFormat, &DisplayPixelFormat, sizeof(DDPIXELFORMAT)); - ddsd.ddsCaps.dwCaps = (DDSCAPS_OFFSCREENPLAIN | MemoryType); - ddsd.dwHeight = height; - ddsd.dwWidth = width; - - if (n_mips_max>1) - { - ddsd.dwFlags |= DDSD_MIPMAPCOUNT; - ddsd.ddsCaps.dwCaps |= DDSCAPS_MIPMAP | DDSCAPS_COMPLEX; - ddsd.dwMipMapCount = n_mips_max; - } - - // Create the surface - ddrval = lpDD->CreateSurface(&ddsd, &lpDDS, NULL); - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return CLE_DXERROR; - #endif - } - - DDCOLORKEY set_zero = {0,0}; - ddrval = lpDDS->SetColorKey(DDCKEY_SRCBLT, &set_zero); - - LOGDXERR(ddrval); - if(ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return CLE_DXERROR; - #endif - } - - - // now do mipmaps if avail - - if (n_mips_max>1) - { - // We must now traverse the mip-map chain from highest to lowest - // resolutions, For each surface AFTER the first one, we must - // load a new file, using a name obtained from the mip map number - - int MipMapNum = 0; - LPDIRECTDRAWSURFACE lpThisMipMap, lpNextMipMap; - DDSCAPS ddsCaps; - - - lpThisMipMap = lpDDS; - // Component Object Model, increase reference count on - // mip-map surface by one. - lpThisMipMap->AddRef(); - ddsCaps.dwCaps = (DDSCAPS_TEXTURE | DDSCAPS_MIPMAP); - ddrval = DD_OK; - - LIF<CL_Image *> i_mip(&mipmaps); - - CL_Image * last_mipP = this; - - while ((ddrval == DD_OK) && (MipMapNum < n_mips_max)) // both tests in case... - { - // Call LoadPPMIntoDDSurface with lpThisMipMap, new file name, and - // other values. - - *DDSurfaceA[MipMapNum] = last_mipP->CopyToDDSurface(lpThisMipMap); - - // Death trap - if (!*DDSurfaceA[MipMapNum]) - { - return CLE_DXERROR; - } - *DDPtrA[MipMapNum] = lpThisMipMap; - - // Proceed to the next level. - // Collect bonus rings. - ddrval = lpThisMipMap->GetAttachedSurface(&ddsCaps, &lpNextMipMap); - // Necessary to match the manual increment of the reference count on the - // COM texture. I think. - lpThisMipMap->Release(); - // ?? lpNextMipMap = lpThisMipMap; - lpThisMipMap = lpNextMipMap; - - MipMapNum++; - if (!i_mip.done()) - { - last_mipP = i_mip(); - i_mip.next(); - } - } - } - else - { - *DDSurfaceA[0] = CopyToDDSurface(lpDDS); - - if (!*DDSurfaceA[0]) return CLE_DXERROR; - - *DDPtrA[0] = lpDDS; - } - - return CLE_OK; -} - - -LPVOID CL_Image::CopyToDDSurface(LPDIRECTDRAWSURFACE lpDDS) -{ - if (!flags.loaded) return 0; - - LPDIRECTDRAWPALETTE lpDDPPMPal; - PALETTEENTRY ppe[256]; - DDSURFACEDESC ddsd; - #if QUANTISE_ON_LOAD - D3DCOLOR colors[256]; - D3DCOLOR c; - int color_count; - #endif - int psize; - char *lpC; - HRESULT ddrval; - unsigned int i, j; - unsigned int pcaps; - - // Lock the surface so it can be filled with the PPM file - - memset(&ddsd, 0, sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddrval = lpDDS->Lock(NULL, &ddsd, 0, NULL); - - if (!ddsd.lpSurface) - { - lpDDS->Unlock(NULL); - lpDDS->Release(); - LOGDXSTR("No surface"); - return 0; - } - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return 0; - #endif - } - - // The method of loading depends on the pixel format of the dest surface - - switch (imode) - { - case CLM_32BIT: - switch (bitsperpixel) - { - case 32: - for (j = 0; j < height; j++) - { - // Point to next row in texture surface - unsigned long * lpLP = (unsigned long*)((char*)ddsd.lpSurface - + ddsd.lPitch * j); - CL_Pixel_32 * lpP32 = im32[j]; - for (i = width; i; --i) - { - *lpLP++ = *lpP32++; - } - } - break; - case 24: - for (j = 0; j < height; j++) - { - // Point to next row in texture surface - unsigned char * lpCP = (unsigned char*)ddsd.lpSurface - + ddsd.lPitch * j; - CL_Pixel_32 * lpP32 = im32[j]; - for (i = width; i; --i) - { - unsigned long lv = *lpP32++; - unsigned char const * lpSrcCP = (unsigned char const *)&lv; - // dodgy - makes assumtions about 24-bit values... - *lpCP++ = *lpSrcCP++; - *lpCP++ = *lpSrcCP++; - *lpCP++ = *lpSrcCP++; - } - } - break; - default: - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Unlock(NULL); - lpDDS->Release(); - return 0; - #endif - } - lpDDS->Unlock(NULL); - break; - case CLM_16BIT: - switch (bitsperpixel) - { - case 16: - for (j = 0; j < height; j++) - { - // Point to next row in texture surface - unsigned short * lpSP = (unsigned short*)((char*)ddsd.lpSurface - + ddsd.lPitch * j); - CL_Pixel_16 * lpP16 = im16[j]; - for (i = width; i; --i) - { - *lpSP++ = *lpP16++; - } - } - break; - case 8: - for (j = 0; j < height; j++) - { - // Point to next row in texture surface - unsigned char * lpCP = (unsigned char*)ddsd.lpSurface - + ddsd.lPitch * j; - CL_Pixel_16 * lpP16 = im16[j]; - for (i = width; i; --i) - { - *lpCP++ = *lpP16++; - } - } - break; - default: - // Everything's gone pear-shaped... - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Unlock(NULL); - lpDDS->Release(); - return 0; - #endif - } - lpDDS->Unlock(NULL); - break; - case CLM_24BIT: - if (24==bitsperpixel) - { - for (j = 0; j < height; j++) - { - // Point to next row in surface - unsigned char * lpCP = ((unsigned char*)ddsd.lpSurface) + ddsd.lPitch * j; - CL_Pixel_24 * lpP24 = im24[j]; - for (i = 0; i < width; i++) - { - // making an assumption about the ordering of r,g,b on the video card - *lpCP++ = lpP24->b; - *lpCP++ = lpP24->g; - *lpCP++ = lpP24->r; - lpP24++; - } - } - lpDDS->Unlock(NULL); - } - else - { - #if QUANTISE_ON_LOAD // Neal's quantize on load stuff - - // Paletted target texture surface - psize = 1<<bitsperpixel; - color_count = 0; // number of colors in the texture - for (j = 0; j < height; j++) - { - // Point to next row in surface - lpC = ((char*)ddsd.lpSurface) + ddsd.lPitch * j; - CL_Pixel_24 * lpP24 = im24[j]; - for (i = 0; i < width; i++, lpP24++) - { - int k; - // Get the next red, green and blue values and turn them into a - // D3DCOLOR. - c = RGB_MAKE(lpP24->r, lpP24->g, lpP24->b); - // Search for this color in a table of colors in this texture - for (k = 0; k < color_count; k++) - if (c == colors[k]) break; - if (k == color_count) - { - // This is a new color, so add it to the list - color_count++; - // More than 256 and we fail (8-bit) - if (color_count > psize) - { - color_count--; - k = color_count - 1; - } - colors[k] = c; - } - // Set the "pixel" value on the surface to be the index into the - // color table - if (psize<256) - { - unsigned int bitmask; - switch (psize) - { - default: - bitmask = 1; - break; - case 4: - bitmask = 3; - break; - case 2: - bitmask = 7; - break; - } - if ((i & bitmask) == 0) - *lpC = (char)(k & (psize-1)); - else - *lpC |= (char)((k & (psize-1)) << (i & (psize-1))); - if ((~i & bitmask) == 0) - lpC++; - } - else - { - *lpC = (char)k; - lpC++; - } - } - } - - // Close the file and unlock the surface - - lpDDS->Unlock(NULL); - - if (color_count > psize) - { - // If there are more than 256 colors, we overran our palette - #if debug - ReleaseDirect3D(); - exit(0x321123); - #else - lpDDS->Release(); - return 0; - #endif - } - - // Create a palette with the colors in our color table - - memset(ppe, 0, sizeof(PALETTEENTRY) * 256); - for (i = 0; i < color_count; i++) - { - ppe[i].peRed = (unsigned char)RGB_GETRED(colors[i]); - ppe[i].peGreen = (unsigned char)RGB_GETGREEN(colors[i]); - ppe[i].peBlue = (unsigned char)RGB_GETBLUE(colors[i]); - } - - // Set all remaining entry flags to D3DPAL_RESERVED, which are ignored by - // the renderer. - - for (; i < 256; i++) - ppe[i].peFlags = D3DPAL_RESERVED; - - // Create the palette with the DDPCAPS_ALLOW256 flag because we want to - // have access to all entries. - - switch (bitsperpixel) - { - default: - pcaps = DDPCAPS_8BIT | DDPCAPS_ALLOW256; - break; - case 4: - pcaps = DDPCAPS_4BIT; - break; - case 2: - pcaps = DDPCAPS_2BIT; - break; - case 1: - pcaps = DDPCAPS_1BIT; - break; - } - - ddrval = lpDD->CreatePalette - (DDPCAPS_INITIALIZE | pcaps, - ppe, &lpDDPPMPal, NULL); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return 0; - #endif - } - - // Finally, bind the palette to the surface - - ddrval = lpDDS->SetPalette(lpDDPPMPal); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - lpDDPPMPal->Release(); - return 0; - #endif - } - - lpDDPPMPal->Release(); - } - break; - #else - // Everything's gone pear-shaped... - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Unlock(NULL); - lpDDS->Release(); - return 0; - #endif - } - break; - case CLM_ATTACHEDPALETTE: - #endif - case CLM_GLOBALPALETTE: - case CLM_TLTPALETTE: - // Paletted target texture surface - - psize = 1<<bitsperpixel; - ReducePalette(psize); // will do nothing if palette is already small enough - // ignore returned error code, because I don't care if it failed - for (j = 0; j < height; j++) - { - // Point to next row in surface - lpC = ((char*)ddsd.lpSurface) + ddsd.lPitch * j; - unsigned char * lpP8 = im8[j]; - - if (psize<256) - { - unsigned int bitmask; - unsigned int nextpixelshift; - switch (psize) - { - default: - nextpixelshift = 2; - break; - case 4: - nextpixelshift = 1; - break; - case 2: - nextpixelshift = 0; - break; - } - bitmask = 7 >> nextpixelshift; - for (i = 0; i < width; i++) - { - unsigned char k = *lpP8++; - // Set the "pixel" value on the surface to be the index into the - // color table - if ((i & bitmask) == 0) - *lpC = (char) (k & (psize-1)); - else - *lpC |= (char) ((k & (psize-1)) << ((i & bitmask)<<nextpixelshift)); - if ((~i & bitmask) == 0) - lpC++; - } - } - else - { - memcpy(lpC,lpP8,width); - } - } - - // Close the file and unlock the surface - - lpDDS->Unlock(NULL); - - // Create a palette with the colors in our color table - - memset(ppe, 0, sizeof(PALETTEENTRY) * 256); - for (i = 0; i < palette_size; i++) - { - ppe[i].peRed = palette[i].r; - ppe[i].peGreen = palette[i].g; - ppe[i].peBlue = palette[i].b; - } - - // Set all remaining entry flags to D3DPAL_RESERVED, which are ignored by - // the renderer. - - for (; i < 256; i++) - ppe[i].peFlags = D3DPAL_RESERVED; - - // Create the palette with the DDPCAPS_ALLOW256 flag because we want to - // have access to all entries. - - switch (bitsperpixel) - { - default: - pcaps = DDPCAPS_8BIT | DDPCAPS_ALLOW256; - break; - case 4: - pcaps = DDPCAPS_4BIT; - break; - case 2: - pcaps = DDPCAPS_2BIT; - break; - case 1: - pcaps = DDPCAPS_1BIT; - break; - } - - ddrval = lpDD->CreatePalette - (DDPCAPS_INITIALIZE | pcaps, - ppe, &lpDDPPMPal, NULL); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return 0; - #endif - } - - // Finally, bind the palette to the surface - - ddrval = lpDDS->SetPalette(lpDDPPMPal); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - lpDDPPMPal->Release(); - return 0; - #endif - } - - lpDDPPMPal->Release(); - break; - default: - // Everything's gone pear-shaped... - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Unlock(NULL); - lpDDS->Release(); - return 0; - #endif - - - } - - return ddsd.lpSurface; -} - - diff --git a/3dc/win95/D3_IMAGE.HPP b/3dc/win95/D3_IMAGE.HPP deleted file mode 100644 index a2bc639..0000000 --- a/3dc/win95/D3_IMAGE.HPP +++ /dev/null @@ -1,1223 +0,0 @@ -#ifndef _included__d3_image_hpp_ -#define _included__d3_image_hpp_ - -#error "This file is obsolete" - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include "list_tem.hpp" - -#include "ddraw.h" -#include "d3d.h" -#include "vramtime.h" - -#include "system.h" -#include "mem3dc.h" - -#include "dxlog.h" -// define = 1 if you want an output log file of all texture files loaded and for which DD surface format -#if debug -#define OUTPUT_LOG 1 -#else -#define OUTPUT_LOG 0 -#endif - -// define = 1 to use fast files for loading (will still try normal files if fastfile doesn't contain correct data) -#define USE_FASTFILE 1 - -#if USE_FASTFILE - -#include "ffstdio.h" -#define D3I_FILE FFILE -#define d3i_fpos_t ffpos_t -#define d3i_fclearerr ffclearerr -#define d3i_fclose ffclose -#define d3i_fcloseall ffcloseall -#define d3i_feof ffeof -#define d3i_ferror fferror -#define d3i_fgetc ffgetc -#define d3i_fgetpos ffgetpos -#define d3i_fgets ffgets -#define d3i_flook fflook -#define d3i_flookb fflookb -#define d3i_fopen ffopen -#define d3i_fread ffread -#define d3i_freadb ffreadb -#define d3i_fseek ffseek -#define d3i_fsetpos ffsetpos -#define d3i_ftell fftell - -#else - -#define D3I_FILE FILE -#define d3i_fpos_t fpos_t -#define d3i_fclearerr fclearerr -#define d3i_fclose fclose -#define d3i_fcloseall fcloseall -#define d3i_feof feof -#define d3i_ferror ferror -#define d3i_fgetc fgetc -#define d3i_fgetpos fgetpos -#define d3i_fgets fgets -#define d3i_fopen fopen -#define d3i_fread fread -#define d3i_fseek fseek -#define d3i_fsetpos fsetpos -#define d3i_ftell ftell - -#endif - - -// define = 1 if you do not want to handle the error return codes, and require a load failure to cause an exit -#define EXIT_ON_LOAD_FAIL 0 - -// define = 1 if you are locating images through rif files and expect this to always succeed -// works like EXIT_ON_LOAD_FAIL, and only if EXIT_ON_LOAD_FAIL is set, but most failures are handled -// by assuming the given name to be a complete path and filename -#define EXIT_ON_LOCATE_FAIL 0 - -// define = 1 to time file opens, file closes and file reads -#define TIME_LOADS 0 - -// I tested the times with a typically complex set of images from AVP, -// loaded over a nework. -// Opening took 16secs, Reading 38secs and Closing 2secs for approx -// for about 500 images (including mip maps) - -#if TIME_LOADS -#include <time.h> -#define START_TIMER {clock_t __stime = clock(); -#define END_TIMER(__var) __var += (unsigned int) ((clock() - __stime) * 1000 / CLOCKS_PER_SEC);} -#else -#define START_TIMER -#define END_TIMER(__var) -#endif - -#if TIME_LOADS -extern unsigned int OpenTime; -extern unsigned int CloseTime; -extern unsigned int ReadTime; -#endif - -#if OUTPUT_LOG -#include "debuglog.hpp" -extern LogFile CL_LogFile; -#endif - -// externs for 3dc things -extern "C" { - extern LPDIRECTDRAW lpDD; - extern DDPIXELFORMAT DisplayPixelFormat; -}; - -enum CL_RGBFormat // for loading from files -{ - CLF_RGB, CLF_BGR, CLF_BGRX -}; - -struct CL_Pixel_24 -{ - union - { - struct - { - unsigned char r,g,b; - unsigned char xx; - }; - unsigned long l; - }; - - CL_Pixel_24() : l(0) {} - CL_Pixel_24(unsigned char const r,unsigned char const g,unsigned char const b) : r(r),g(g),b(b),xx(0) {} - CL_Pixel_24(CL_Pixel_24 const & p24) : l(p24.l) {} - CL_Pixel_24(unsigned long const i) : l(i) {} - - operator unsigned long (void) const { return l; } - - inline void Read (D3I_FILE * const f, CL_RGBFormat const t) - { - switch(t) - { - case CLF_RGB: - d3i_fread(&r,1,1,f); - d3i_fread(&g,1,1,f); - d3i_fread(&b,1,1,f); - break; - case CLF_BGR: - d3i_fread(&b,1,1,f); - d3i_fread(&g,1,1,f); - d3i_fread(&r,1,1,f); - break; - case CLF_BGRX: - d3i_fread(&b,1,1,f); - d3i_fread(&g,1,1,f); - d3i_fread(&r,1,1,f); - d3i_fseek(f,1,SEEK_CUR); - default: - break; - } - } - - inline void Read (D3I_FILE * const f, CL_RGBFormat const t, unsigned int const maxval) - { - Read(f,t); - if (maxval != 255) - { - r = (unsigned char) ( ((unsigned int)r << 8) / (maxval+1) ); - g = (unsigned char) ( ((unsigned int)g << 8) / (maxval+1) ); - b = (unsigned char) ( ((unsigned int)b << 8) / (maxval+1) ); - } - } - - unsigned int FVD_Distance(CL_Pixel_24 const & p2) const; -}; - - -struct CL_DX_Format -{ - unsigned int - red_mask, - red_shift, - red_bits, - red_bits_gt8, - red_bits_lt8, - blue_mask, - blue_shift, - blue_bits, - blue_bits_gt8, - blue_bits_lt8, - green_mask, - green_shift, - green_bits, - green_bits_gt8, - green_bits_lt8; - - CL_Pixel_24 dx_black; - - inline void Init(unsigned int rmask,unsigned int gmask,unsigned int bmask) - { - red_mask = rmask; - blue_mask = bmask; - green_mask = gmask; - for (red_shift = 0; !(rmask & 1); red_shift++, rmask>>=1); - for (green_shift = 0; !(gmask & 1); green_shift++, gmask>>=1); - for (blue_shift = 0; !(bmask & 1); blue_shift++, bmask>>=1); - for (red_bits = 0; rmask; red_bits++, rmask>>=1); - for (green_bits = 0; gmask; green_bits++, gmask>>=1); - for (blue_bits = 0; bmask; blue_bits++, bmask>>=1); - if (blue_bits >= green_bits && blue_bits >= red_bits) - { - dx_black = CL_Pixel_24(0,0,1); - } - else if (red_bits >= green_bits) - { - dx_black = CL_Pixel_24(1,0,0); - } - else - { - dx_black = CL_Pixel_24(0,1,0); - } - if (red_bits >= 8) - { - red_bits_gt8 = red_bits-8; - red_bits_lt8 = 0; - } - else - { - red_bits_lt8 = 8-red_bits; - red_bits_gt8 = 0; - } - if (green_bits >= 8) - { - green_bits_gt8 = green_bits-8; - green_bits_lt8 = 0; - } - else - { - green_bits_lt8 = 8-green_bits; - green_bits_gt8 = 0; - } - if (blue_bits >= 8) - { - blue_bits_gt8 = blue_bits-8; - blue_bits_lt8 = 0; - } - else - { - blue_bits_lt8 = 8-blue_bits; - blue_bits_gt8 = 0; - } - } -}; - - -// for 32 bit and 24 bit DirectX formats -template <class S> -struct CL_Pixel_T -{ - static CL_DX_Format f; - static CL_DX_Format f_d3d; - static CL_DX_Format f_ddraw; - - S p; - - inline S r(void) const { return (S)((p & f.red_mask)>>f.red_shift); } - inline S g(void) const { return (S)((p & f.green_mask)>>f.green_shift); } - inline S b(void) const { return (S)((p & f.blue_mask)>>f.blue_shift); } - - CL_Pixel_T() {} - CL_Pixel_T(CL_Pixel_T<S> const & p32) : p(p32.p) {} - CL_Pixel_T(CL_Pixel_24 const & p24) - : p((S)( - (S)p24.r>>f.red_bits_lt8<<f.red_shift+f.red_bits_gt8 | - (S)p24.g>>f.green_bits_lt8<<f.green_shift+f.green_bits_gt8 | - (S)p24.b>>f.blue_bits_lt8<<f.blue_shift+f.blue_bits_gt8 )) - { - // make the 32bit pixel non-black to avoid transparency problems - if (!p && p24.l) // if the 24bit pixel is not black and the 32 bit pixel is black - { - // choose which of r,g or b to make non-zero - try and get as close to black as poss - if ((1<<f.blue_bits_lt8)-p24.b <= (1<<f.red_bits_lt8)-p24.r && (1<<f.blue_bits_lt8)-p24.b <= (1<<f.green_bits_lt8)-p24.g) - p = (S)(1<<f.blue_shift); - else if ((1<<f.red_bits_lt8)-p24.r <= (1<<f.green_bits_lt8)-p24.g) - p = (S)(1<<f.red_shift); - else - p = (S)(1<<f.green_shift); - } - } - - inline operator CL_Pixel_24 (void) const - { - S rr = (S)(r()>>f.red_bits_gt8<<f.red_bits_lt8); - S gg = (S)(g()>>f.green_bits_gt8<<f.green_bits_lt8); - S bb = (S)(b()>>f.blue_bits_gt8<<f.blue_bits_lt8); - - if (!(rr|gg|bb) && p) - { - if (b()<<f.red_bits>=r()<<f.blue_bits && b()<<f.green_bits>=g()<<f.blue_bits) // make the 16bit pixel non-black to avoid transparency problems - bb = 1; - else if (r()<<f.green_bits>=g()<<f.red_bits) - rr = 1; - else - gg = 1; - } - - return CL_Pixel_24((unsigned char)rr,(unsigned char)gg,(unsigned char)bb); - }; - operator S (void) const { return p; } - - inline void Read (D3I_FILE * const f, CL_RGBFormat const t) - { - CL_Pixel_24 p24; - p24.Read(f,t); - *this = (CL_Pixel_T<S>)p24; - } - - inline void Read (D3I_FILE * const f, CL_RGBFormat const t, unsigned int const maxval) - { - CL_Pixel_24 p24; - p24.Read(f,t,maxval); - *this = (CL_Pixel_T<S>)p24; - } -}; - - -typedef CL_Pixel_T<unsigned long> CL_Pixel_32; -typedef CL_Pixel_T<unsigned short> CL_Pixel_16; - - -enum CL_Error -{ - CLE_OK, - CLE_LOADERROR, // file cannot be loaded - format is wrong - CLE_OPENERROR, // file cannot be opened - does not exist? - CLE_FINDERROR, // file cannot be found - not listed in .RIF file - CLE_RIFFERROR, // rif file not loaded, or invalid - CLE_INVALIDGAMEMODE, // specified game mode does not exist - CLE_INVALIDDXMODE, // video mode is invalid - CLE_DXERROR, // other direct X related error - CLE_ALLOCFAIL // failed memory allocation -}; - - -enum CL_ImageMode { - - CLM_GLOBALPALETTE, // image shares a global palette in a palettized mode - CLM_TLTPALETTE, // images may also share an abstract palette which remaps via a tlt to a global display palette - CLM_ATTACHEDPALETTE, // 256 colour image with attached palette - CLM_16BIT, // 16 bit in specified RGB format - CLM_32BIT, // 32 bit in specified RGB format - CLM_24BIT // 24 bit truecolour image in 888 format -}; -// Note: -// currently 24-bit and 16-bit image formats are not output. -// If the desired format is 24-bit or 16-bit then 256 colour BMPs are loaded -// and 'unquantized' to generate the required format. - - -enum CL_LoadMode { - - CLL_D3DTEXTURE, - CLL_DDSURFACE -}; - -void CL_Select_Mode(CL_LoadMode const lmode); - - -void CL_Init_D3DMode(LPDDSURFACEDESC const format); - -enum CL_VideoMode { - - CLV_8, - CLV_15, - CLV_24, - CLV_8T, - CLV_8TLT -}; - -void CL_Init_DirectDrawMode(CL_VideoMode const vmode); - - - -// test!!! -#if HwTextureHack -static int craptest = 0; -#endif - -#if EXIT_ON_LOAD_FAIL - extern "C" - { - #include "3dc.h" - } - #if EXIT_ON_LOCATE_FAIL - #define EXITONLOCATEFAIL(__errcode,__iname,__enum_id) \ - if (CLE_RIFFERROR != __errcode) { \ - if (__iname) textprint("Cannot figure path for:\n%s\n",__iname); \ - else textprint("Cannot figure path for:\nImage ID %d\n",__enum_id); \ - WaitForReturn(); \ - ExitSystem(); \ - exit(0x10cafa11); \ - } - #else - #define EXITONLOCATEFAIL(__errcode,__iname,__enum_id) - #endif - #define EXITONLOADFAIL(__iname) \ - { \ - textprint("Cannot open:\n%s\n",__iname); \ - WaitForReturn(); \ - ExitSystem(); \ - exit(0x10adfa11); \ - } - #define EXITONREADFAIL(__iname) \ - { \ - textprint("Cannot read:\n%s\n",__iname); \ - WaitForReturn(); \ - ExitSystem(); \ - exit(0x10adfa11); \ - } -#else - #define EXITONLOCATEFAIL(__errcode,__iname,__enum_id) - #define EXITONLOADFAIL(__iname) - #define EXITONREADFAIL(__iname) -#endif - -struct CL_Flags -{ - unsigned int loaded : 1; - unsigned int located : 1; - unsigned int raw16bit : 1; - unsigned int tltpalette : 1; - - CL_Flags() - : loaded(0) - , located(0) - , tltpalette(0) - , raw16bit(0) - {} -}; - -#define CL_EID_INVALID (-1) - - -#if 0 -template <class I> -class CL_MIP_Image -{ -public: - unsigned int num_mipmaps; - I * * mipmaps; // array of CL_Image pointers of decreasing image size - - unsigned int width; // == mipmaps[0]->width - unsigned int height; // == mipmaps[0]->height - unsigned int size; // == mipmaps[0]->size - - char * fname; // full filename (including directory/path) of mipmap with index 0 - char * name; // name of image without directory/path or extension - - CL_MIP_Image() : mipmaps(0), num_mipmaps(0), fname(0), name(0) {} - ~CL_MIP_Image() { Delete(); } - - CL_MIP_Image(CL_MIP_Image<I> const & i2) - : width (i2.width) - , height (i2.height) - , size (i2.size) - , num_mipmaps (i2.num_mipmaps) - { Copy(i2); } - - CL_MIP_Image<I> & operator = (CL_MIP_Image<I> const & i2) - { - if (&i2 != this) - { - Delete(); - - width = i2.width; - height = i2.height; - size = i2.size; - num_mipmaps = i2.num_mipmaps; - - Copy(i2); - } - return *this; - } - -private: - void Copy(CL_MIP_Image<I> const & i2) - { - if (i2.mipmaps) - { - mipmaps = new I * [num_mipmaps]; - for (int i=0; i<num_mipmaps; ++i) - { - mipmaps[i] = new I(*i2.mipmaps[i]); - } - } - - if (i2.fname) - { - fname = new char[strlen(i2.fname)+1]; - strcpy(fname,i2.fname); - } - - if (i2.name) - { - name = new char[strlen(i2.name)+1]; - strcpy(name,i2.name); - } - } - void Delete(void) - { - if (mipmaps) - { - for (int i=0; i<num_mipmaps; ++i) delete mipmaps[i]; - delete[] mipmaps; - mipmaps = 0; - } - - if (name) - { - delete[] name; - name = 0; - } - - if (fname) - { - delete[] fname; - fname = 0; - } - } - - CL_Flags flags; - -public: - inline CL_Error Load(int const enum_id) - { - return Load(0,enum_id); - } - inline CL_Error Load(char const * const iname) - { - return Load(iname,CL_EID_INVALID); - } - inline CL_Error Load() - { - return Load(0,CL_EID_INVALID); - } - - inline CL_Error PreLoad(int const enum_id) - { - return PreLoad(0,enum_id); - } - inline CL_Error PreLoad(char const * const iname) - { - return PreLoad(iname,CL_EID_INVALID); - } - - CL_Error CopyToScanDrawTexture(unsigned char * * const ImagePtrA [], unsigned int maxnummips) - { - if (!flags.loaded) return CLE_LOADERROR; - - if (CLL_DDSURFACE != I::lmode) CL_Select_Mode(CLL_DDSURFACE); - - if (num_mipmaps < maxnummips) maxnummips = num_mipmaps; - if (!maxnummips) return CLE_ALLOCFAIL; - - if (!*ImagePtrA[0]) *ImagePtrA[0] = (unsigned char *) AllocateMem((2*width+1)*(2*height+1)*I::bitsperpixel/24+(maxnummips-3)*I::bitsperpixel/8); // slightly more than 4/3 w*h*bytedepth - - for (int i=0; i<maxnummips; ++i) - { - if (i) *ImagePtrA[i] = *ImagePtrA[i-1] + mipmaps[i-1]->width*mipmaps[i-1]->height*(I::bitsperpixel>>3); - CL_Error thismipmaperror = mipmaps[i]->CopyToScanDrawTexture(ImagePtrA[i]); - if (CLE_OK != thismipmaperror) return thismipmaperror; - } - return CLE_OK; - } - - CL_Error CopyToD3DTexture(LPDIRECTDRAWSURFACE * const DDPtrA [], LPVOID * const DDSurfaceA [], unsigned int maxnummips, int const MemoryType) - { - if (!flags.loaded) return CLE_LOADERROR; - - WaitForVRamReady(VWS_D3DTEXCREATE); - - if (CLL_D3DTEXTURE != I::lmode) CL_Select_Mode(CLL_D3DTEXTURE); - - LPDIRECTDRAWSURFACE lpDDS; - DDSURFACEDESC ddsd; - HRESULT ddrval; - - if (width & 3 || height & 3) - { - // return error code - return CLE_DXERROR; - } - - /* test !!! */ - { - #if HwTextureHack - craptest++; - if (craptest > 10) - return CLE_DXERROR; - #endif - } - - - if (num_mipmaps < maxnummips) maxnummips = num_mipmaps; - // Set up the mip-mapped surface description. starting - // with the passed texture format and then - // incorporating the information read from the - // ppm. - memcpy(&ddsd, I::format, sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddsd.dwFlags = (DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT - | DDSD_MIPMAPCOUNT); - ddsd.dwMipMapCount = maxnummips; // engine standard, primary plus six mip-maps - ddsd.ddsCaps.dwCaps = (DDSCAPS_TEXTURE | DDSCAPS_MIPMAP - | DDSCAPS_COMPLEX | MemoryType); - ddsd.dwHeight = height; - ddsd.dwWidth = width; - - - // Create the surface - ddrval = lpDD->CreateSurface(&ddsd, &lpDDS, NULL); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return CLE_DXERROR; - #endif - } - - // We must now traverse the mip-map chain from highest to lowest - // resolutions, For each surface AFTER the first one, we must - // load a new file, using a name obtained from the mip map number - - int MipMapNum = 0; - LPDIRECTDRAWSURFACE lpThisMipMap, lpNextMipMap; - DDSCAPS ddsCaps; - - - lpThisMipMap = lpDDS; - // Component Object Model, increase reference count on - // mip-map surface by one. - lpThisMipMap->AddRef(); - ddsCaps.dwCaps = (DDSCAPS_TEXTURE | DDSCAPS_MIPMAP); - ddrval = DD_OK; - - while ((ddrval == DD_OK) && (MipMapNum < maxnummips)) // both tests in case... - { - // Call LoadPPMIntoDDSurface with lpThisMipMap, new file name, and - // other values. - - *DDSurfaceA[MipMapNum] = mipmaps[MipMapNum]->CopyToDDSurface(lpThisMipMap); - - // Death trap - if (!*DDSurfaceA[MipMapNum]) - { - return CLE_DXERROR; - } - *DDPtrA[MipMapNum] = lpThisMipMap; - - // Proceed to the next level. - // Collect bonus rings. - ddrval = lpThisMipMap->GetAttachedSurface(&ddsCaps, &lpNextMipMap); - // Necessary to match the manual increment of the reference count on the - // COM texture. I think. - lpThisMipMap->Release(); - // ?? lpNextMipMap = lpThisMipMap; - lpThisMipMap = lpNextMipMap; - - MipMapNum++; - } - - return CLE_OK; - - } - - CL_Error CopyToDirectDrawSurface(LPDIRECTDRAWSURFACE * const DDPtrA [], LPVOID * const DDSurfaceA [], unsigned int maxnummips, int const MemoryType) - { - if (!flags.loaded) return CLE_LOADERROR; - - WaitForVRamReady(VWS_DDCREATE); - - if (CLL_DDSURFACE != I::lmode) CL_Select_Mode(CLL_DDSURFACE); - - LPDIRECTDRAWSURFACE lpDDS; - DDSURFACEDESC ddsd; - HRESULT ddrval; - - if (width & 3 || height & 3) - { - // return error code - return CLE_DXERROR; - } - - if (num_mipmaps < maxnummips) maxnummips = num_mipmaps; - // Set up the mip-mapped surface description. starting - // with the passed texture format and then - // incorporating the information read from the - // ppm. - memset(&ddsd, 0, sizeof ddsd); - ddsd.dwSize = sizeof ddsd; - ddsd.dwFlags = (DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT - | DDSD_MIPMAPCOUNT); - ddsd.dwMipMapCount = maxnummips; // engine standard, primary plus six mip-maps - ddsd.ddsCaps.dwCaps = (DDSCAPS_OFFSCREENPLAIN | DDSCAPS_MIPMAP - | DDSCAPS_COMPLEX | MemoryType); - ddsd.dwHeight = height; - ddsd.dwWidth = width; - - - // Create the surface - ddrval = lpDD->CreateSurface(&ddsd, &lpDDS, NULL); - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return CLE_DXERROR; - #endif - } - - DDCOLORKEY set_zero = {0,0}; - ddrval = lpDDS->SetColorKey(DDCKEY_SRCBLT, &set_zero); - - LOGDXERR(ddrval); - if(ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - lpDDS->Release(); - return CLE_DXERROR; - #endif - } - - // We must now traverse the mip-map chain from highest to lowest - // resolutions, For each surface AFTER the first one, we must - // load a new file, using a name obtained from the mip map number - - int MipMapNum = 0; - LPDIRECTDRAWSURFACE lpThisMipMap, lpNextMipMap; - DDSCAPS ddsCaps; - - - lpThisMipMap = lpDDS; - // Component Object Model, increase reference count on - // mip-map surface by one. - lpThisMipMap->AddRef(); - ddsCaps.dwCaps = (DDSCAPS_TEXTURE | DDSCAPS_MIPMAP); - ddrval = DD_OK; - - while ((ddrval == DD_OK) && (MipMapNum < maxnummips)) // both tests in case... - { - // Call LoadPPMIntoDDSurface with lpThisMipMap, new file name, and - // other values. - - *DDSurfaceA[MipMapNum] = mipmaps[MipMapNum]->CopyToDDSurface(lpThisMipMap); - - // Death trap - if (!*DDSurfaceA[MipMapNum]) - { - return CLE_DXERROR; - } - *DDPtrA[MipMapNum] = lpThisMipMap; - - // Proceed to the next level. - // Collect bonus rings. - ddrval = lpThisMipMap->GetAttachedSurface(&ddsCaps, &lpNextMipMap); - // Necessary to match the manual increment of the reference count on the - // COM texture. I think. - lpThisMipMap->Release(); - // ?? lpNextMipMap = lpThisMipMap; - lpThisMipMap = lpNextMipMap; - - MipMapNum++; - } - - return CLE_OK; - - } - -private: - // I was using Dan's list template for this, - // but since it is not a standard part of 3DC, - // I have had to write a specific simple list handler - struct TempListMember - { - I * mip; - TempListMember * next; - TempListMember(I * data) : mip(data), next(0) {} - //TempListMember() : next(0) {} - ~TempListMember() { if (next) delete next; } - }; - struct TempList - { - unsigned int n_entries; - TempListMember * first; - TempListMember * last; - TempList(I * data) : first(new TempListMember(data)), n_entries(1) { last = first; } - TempList & operator += (I * data) - { - if (!first) - { - first = new TempListMember(data); - last = first; - } - else - { - last->next = new TempListMember(data); - last = last->next; - } - ++ n_entries; - return *this; - } - ~TempList() - { - if (first) delete first; - } - }; - - CL_Error Load(char const * const iname, int const enum_id) - { - if (iname || CL_EID_INVALID != enum_id) flags.located = 0; - - I * mip0; - - if (flags.located && mipmaps) - { - mip0 = mipmaps[0]; - // we have grabbed the previously allocated pointer - // it will now be treated as if it were allocated here, - // so we must remove it from the class, in case the - // deconstructor tries to deallocate it - delete[] mipmaps; - mipmaps = 0; - } - else - { - mip0 = new I; - - CL_Error locate_err = mip0->Locate(iname,enum_id); - - if (locate_err != CLE_OK) - { - delete mip0; - EXITONLOCATEFAIL(locate_err,iname,enum_id) - return locate_err; - } - } - - #if OUTPUT_LOG - char const * texformat; - unsigned int redbits = 8; - unsigned int greenbits = 8; - unsigned int bluebits = 8; - switch (I::imode) - { - case CLM_GLOBALPALETTE: - case CLM_TLTPALETTE: - texformat = "Palettized Display"; - break; - case CLM_ATTACHEDPALETTE: - texformat = "Palettized Textures"; - break; - case CLM_32BIT: - texformat = "32BIT DX"; - redbits += CL_Pixel_32::f.red_bits_gt8; - redbits -= CL_Pixel_32::f.red_bits_lt8; - greenbits += CL_Pixel_32::f.green_bits_gt8; - greenbits -= CL_Pixel_32::f.green_bits_lt8; - bluebits += CL_Pixel_32::f.blue_bits_gt8; - bluebits -= CL_Pixel_32::f.blue_bits_lt8; - break; - case CLM_24BIT: - texformat = "24-bit for runtime conversion"; - break; - case CLM_16BIT: - texformat = "16BIT DX"; - redbits += CL_Pixel_16::f.red_bits_gt8; - redbits -= CL_Pixel_16::f.red_bits_lt8; - greenbits += CL_Pixel_16::f.green_bits_gt8; - greenbits -= CL_Pixel_16::f.green_bits_lt8; - bluebits += CL_Pixel_16::f.blue_bits_gt8; - bluebits -= CL_Pixel_16::f.blue_bits_lt8; - break; - } - CL_LogFile.lprintf("--%s %s (%u-bit, %u-%u-%u)\n",mip0->fname,texformat,I::bitsperpixel,redbits,greenbits,bluebits); - #endif - - START_TIMER - D3I_FILE * fp = d3i_fopen(mip0->fname,"rb"); - END_TIMER(OpenTime) - - if (!fp) - { - #if OUTPUT_LOG - CL_LogFile.lputs("** ERROR: unable to open\n"); - #endif - EXITONLOADFAIL(mip0->fname) - delete mip0; - return CLE_OPENERROR; - } - - CL_Error load_err = mip0->Load_Image(fp); - START_TIMER - d3i_fclose(fp); - END_TIMER(CloseTime) - - if (load_err != CLE_OK) - { - if (!flags.located) delete mip0; - #if OUTPUT_LOG - CL_LogFile.lputs("** ERROR: unable to read\n"); - #endif - EXITONREADFAIL(mip0->fname) - return load_err; - } - - TempList miplist(mip0); - - width = mip0->width; - height = mip0->height; - size = mip0->size; - - if (!flags.located) - { - if (fname) delete[] fname; - if (name) delete[] name; - fname = new char[strlen(mip0->fname)+1]; - name = new char[strlen(mip0->name)+1]; - strcpy(fname,mip0->fname); - strcpy(name,mip0->name); - } - - for (int mip_idx = 1; mip_idx < 7; ++mip_idx) - { - I * mip_n; - - mip_n = new I; - mip_n->name = new char[strlen(name)+1]; - mip_n->fname = new char[strlen(fname)+1]; - strcpy(mip_n->name,name); - strcpy(mip_n->fname,fname); - - char * dotpos = strrchr(mip_n->fname,'.'); - if (!dotpos) - { - delete mip_n; - break; - } - sprintf(dotpos+3,"%1d",mip_idx); - - #if OUTPUT_LOG - char const * texformat; - unsigned int redbits = 8; - unsigned int greenbits = 8; - unsigned int bluebits = 8; - switch (I::imode) - { - case CLM_GLOBALPALETTE: - case CLM_TLTPALETTE: - texformat = "Palettized Display"; - break; - case CLM_ATTACHEDPALETTE: - texformat = "Palettized Textures"; - break; - case CLM_32BIT: - texformat = "32BIT DX"; - redbits += CL_Pixel_32::f.red_bits_gt8; - redbits -= CL_Pixel_32::f.red_bits_lt8; - greenbits += CL_Pixel_32::f.green_bits_gt8; - greenbits -= CL_Pixel_32::f.green_bits_lt8; - bluebits += CL_Pixel_32::f.blue_bits_gt8; - bluebits -= CL_Pixel_32::f.blue_bits_lt8; - break; - case CLM_24BIT: - texformat = "24-bit for runtime conversion"; - break; - case CLM_16BIT: - texformat = "16BIT DX"; - redbits += CL_Pixel_16::f.red_bits_gt8; - redbits -= CL_Pixel_16::f.red_bits_lt8; - greenbits += CL_Pixel_16::f.green_bits_gt8; - greenbits -= CL_Pixel_16::f.green_bits_lt8; - bluebits += CL_Pixel_16::f.blue_bits_gt8; - bluebits -= CL_Pixel_16::f.blue_bits_lt8; - break; - } - CL_LogFile.lprintf("--%s %s (%u-bit, %u-%u-%u)\n",mip_n->fname,texformat,I::bitsperpixel,redbits,greenbits,bluebits); - #endif - - START_TIMER - fp = d3i_fopen(mip_n->fname,"rb"); - END_TIMER(OpenTime) - - if (!fp) - { - delete mip_n; - #if OUTPUT_LOG - CL_LogFile.lputs("** Warning: unable to open\n"); - #endif - break; - } - - load_err = mip_n->Load_Image(fp); - START_TIMER - d3i_fclose(fp); - END_TIMER(CloseTime) - - if (load_err != CLE_OK) - { - delete mip_n; - #if OUTPUT_LOG - CL_LogFile.lputs("** Warning: unable to read\n"); - #endif - break; - } - - if (mip_n->width << mip_idx < width || mip_n->height << mip_idx < height) - { - delete mip_n; - #if OUTPUT_LOG - CL_LogFile.lputs("** Warning: less than half size\n"); - #endif - break; - } - - miplist += mip_n; - } - - if (mipmaps) - { - for (int i = 0; i<num_mipmaps; ++i) delete mipmaps[i]; - delete[] mipmaps; - } - - num_mipmaps = miplist.n_entries; - mipmaps = new I * [num_mipmaps]; - - TempListMember * listP = miplist.first; - for (int i=0; i<num_mipmaps; ++i) - { - mipmaps[i] = listP->mip; - listP = listP->next; - } - - flags.loaded = 1; - flags.located = 1; - return CLE_OK; - } - - CL_Error PreLoad(char const * const iname, int const enum_id) - { - I * mip0 = new I; - - CL_Error locate_err = mip0->Locate(iname,enum_id); - - if (locate_err != CLE_OK) - { - delete mip0; - return locate_err; - } - - if (fname) delete[] fname; - if (name) delete[] name; - fname = new char[strlen(mip0->fname)+1]; - name = new char[strlen(mip0->name)+1]; - strcpy(fname,mip0->fname); - strcpy(name,mip0->name); - - if (mipmaps) - { - for (int i=0; i<num_mipmaps; ++i) delete mipmaps[i]; - delete[] mipmaps; - } - - num_mipmaps = 1; - mipmaps = new I * [1]; - *mipmaps = mip0; - - flags.loaded = 0; - flags.located = 1; - - return CLE_OK; - } -}; -#endif - -struct CL_Image -{ -public: - static CL_ImageMode imode; // video mode defines which format images should be loaded - static CL_ImageMode imode_d3d; // video mode defines which format images should be loaded - static CL_ImageMode imode_ddraw; // video mode defines which format images should be loaded - static LPDDSURFACEDESC format; - static unsigned int bitsperpixel; - static unsigned int bitsperpixel_d3d; - static unsigned int bitsperpixel_ddraw; - static CL_LoadMode lmode; - - // any one of these 3 may be valid - union - { // array of 24 bit or 32 bit pixels - CL_Pixel_24 * * im24; // array of 24 bit pixels - CL_Pixel_32 * * im32; // array of 32 bit pixels - // the data storage sizes of CL_Pixel_24 and CL_Pixel_32 must match - }; - union - { - CL_Pixel_16 * * im16; // array of 16 bit pixels - unsigned short * * im16raw; // raw double-byte pixel data - }; - unsigned char * * im8; // array of entrys into CLUT - - unsigned int palette_size; - CL_Pixel_24 * palette; // CLUT (applicable only if 'im8' is valid) - - unsigned int width; - unsigned int height; - unsigned int size; // width * height - - char * fname; // full name of image including directory/path and extension - char * name; // name of image without directory/path or extension - - List<CL_Image *> mipmaps; - - CL_Image() : im8(0),im16(0),im24(0),palette(0),palette_size(0),fname(0),name(0) {} - virtual ~CL_Image(); - - CL_Image(CL_Image const &); - CL_Image & operator = (CL_Image const &); - - inline CL_Error Load(char const * const iname) // looks at rif file and video mode to determine which file to load - { - return Load(iname,CL_EID_INVALID); - } - inline CL_Error Load(int const enum_id) // looks at rif file and video mode to determine which file to load - { - return Load(0,enum_id); - } - inline CL_Error Load() // assumes preload has been called - { - return Load(0,CL_EID_INVALID); - } - - inline CL_Error PreLoad(char const * const iname) // looks at rif file and video mode to determine which file to load - { - return PreLoad(iname,CL_EID_INVALID); - } - inline CL_Error PreLoad(int const enum_id) // looks at rif file and video mode to determine which file to load - { - return PreLoad(0,enum_id); - } - - CL_Error LoadMipMaps(int const n_mips = 7); // assumes locating has been done (ie. PreLoad or Load has been called) - - CL_Error Load_BMP(D3I_FILE * f); // videomode != CLM_GLOBALPALETTE - CL_Error Load_PPM(D3I_FILE * f); // videomode == CLM_16BIT || CLM_24BIT - CL_Error Load_PGM(D3I_FILE * f); // videomode == CLM_GLOBALPALETTE - CL_Error Load_PWM(D3I_FILE * f); // videomode == CLM_GLOBALPALETTE - - CL_Error Load_Image(D3I_FILE * f); // calls one of the above if correct format - - CL_Error GetBitsPerPixel(unsigned int* bpp); //returns bitsperpixel; - - // needs CL_Init_D3DMode((LPDDSURFACEDESC)format) to have been called - inline CL_Error CopyToD3DTexture(LPDIRECTDRAWSURFACE * const DDPtrA, LPVOID * const DDSurfaceA, int const MemoryType) - { - return CopyToD3DTexture(&DDPtrA,&DDSurfaceA,MemoryType); - } - CL_Error CopyToD3DTexture(LPDIRECTDRAWSURFACE * const DDPtrA [], LPVOID * const DDSurfaceA [], int const MemoryType, unsigned int n_mips_max = 1); - // needs CL_Init_ScanDrawMode((CL_VideoMode) videomode) to have been called - inline CL_Error CopyToDirectDrawSurface(LPDIRECTDRAWSURFACE * const DDPtrA, LPVOID * const DDSurfaceA, int const MemoryType) - { - return CopyToDirectDrawSurface(&DDPtrA,&DDSurfaceA,MemoryType); - } - CL_Error CopyToDirectDrawSurface(LPDIRECTDRAWSURFACE * const DDPtrA [], LPVOID * const DDSurfaceA [], int const MemoryType, unsigned int n_mips_max = 1); - // needs CL_Init_ScanDrawMode((CL_VideoMode) videomode) to have been called - inline CL_Error CopyToScanDrawTexture(unsigned char * * const ImagePtrA) - { - return CopyToScanDrawTexture(&ImagePtrA); - } - CL_Error CopyToScanDrawTexture(unsigned char * * const ImagePtrA [], unsigned int n_mips_max = 1); - // create an empty image for user manipulation - CL_Error Make(int const _width,int const _height); - // create an empty random image for user manipulation - CL_Error MakeRandom(int const _width,int const _height,int const seed = -1); - // ensure with and height are multiples of given units - void PadTo(int const width_unit,int const height_unit); - - inline CL_Flags const & GetFlags() const - { - return flags; - } -protected: - CL_Flags flags; - - virtual CL_Error Locate(char const * iname, int const enum_id); - CL_Error Load(char const * const iname, int const enum_id); - CL_Error PreLoad(char const * const iname, int const enum_id); - - CL_Error ReducePalette(unsigned int const num_colours); - - // returns DDSURFACEDESC.lpSurface - // does what LoadPPMIntoDDSurface did - LPVOID CopyToDDSurface(LPDIRECTDRAWSURFACE lpDDS); - -private: - void Copy(CL_Image const &); - void Delete(void); - void DeleteNotMips(void); -}; - -#endif // !_included__d3_image_hpp_ diff --git a/3dc/win95/DB.H b/3dc/win95/DB.H deleted file mode 100644 index 10e5d4d..0000000 --- a/3dc/win95/DB.H +++ /dev/null @@ -1,363 +0,0 @@ -/* ******************************************************************** * - * * - * DB.H - Header for debugging functions and macros. * - * * - * By: Garry Lancaster Version: 2.0 * - * * - * ******************************************************************** */ - -/* N O T E S ********************************************************** */ - -/* Define NDEBUG here to switch off all debugging. */ - -/* Set the DB_LEVEL here or before this file is included. Most db macros - * have a level from 1 to 5. They - * will only compile to code if the DB_LEVEL is at or greater than their - * level, otherwise they will be translated to ((void) 0) (i.e. no - * code.). The levels should be used as follows: - * - * 1 - Very low cost debugging. Negligible speed penalty. Could easily - * be left in a finished game. - * 2 - Low cost debugging. Small speed penalty. Use during development - * for well-tested code. - * 3 - Medium cost debugging. Obvious but tolerable speed penalty. Use - * during development most of the time. - * 4 - High cost debugging. Large speed penalty. Use during development - * when actively bug hunting. - * 5 - Very high cost debugging. Massive speed penalty. Use when trying - * to track down one of THOSE bugs. - * - * The level of a macro is part of its name e.g. to code a db_assert - * that fires at level 3 or above, use db_assert3(). - */ - -#pragma once - -/* If you do not set the DB_LEVEL, it is set for you: to 3 */ -#ifndef DB_LEVEL - #define DB_LEVEL 3 -#endif - -/* N.B. If NDEBUG is set, it over-rides DB_LEVEL and switches off all - * debugging. - */ -#ifdef NDEBUG - #undef DB_LEVEL - #define DB_LEVEL 0 -#endif - -/* Some db macros can be made optional dependent on the setting of the - * global variable db_option by appending _opt e.g. db_assert_opt(). The - * only code that is executed for any _opt macro if db_option is zero is - * - * if(db_option) - * - * However, this is still more than the macros controlled by the DB_LEVEL - * - if they are above the current DB_LEVEL they cause no code execution - * whatsoever. Therefore, avoid using _opt type macros inside extremely - * time critical code - use macros contolled by the DB_LEVEL instead, - * unless you are prepared to put up with the speed penalty. - * The only time that _opt type macros generate no code is when NDEBUG is - * defined. - */ - -/* S T A R T W R A P P E R ****************************************** */ - -/* Avoid multiple inclusions of this file in a single source file. */ -#ifndef DB_H_INCLUDED -#define DB_H_INCLUDED - -/* I N C L U D E D S ************************************************** */ -#include "advwin32.h" -#ifndef DB_NOWINDOWS - #include <windows.h> - #include "advwin32.h" -#endif - -/* Permit use in a C++ source file. */ -#ifdef __cplusplus -extern "C" { -#endif - -/* ******************************************************************** * - * * - * I N T E R F A C E - both internal and external. * - * * - * ******************************************************************** */ - -/* C O N S T A N T S ************************************************** */ - -/* Possible values for the global variable, db_display_type. */ -#define DB_DOS 0 -#define DB_WINDOWS 1 -#define DB_DIRECTDRAW 2 - -/* Possible values for the bltOrFlip field of db_dd_mode_tag structure. */ -#define DB_FLIP 0 -#define DB_BLT 1 - -/* M A C R O S ******************************************************** */ - -#if (!defined(DB_NOASSUME)) && defined(_MSC_VER) && (_MSC_VER >= 1200) - #define _db_assume(x) __assume(x) -#else - #define _db_assume(x) ((void)0) -#endif - -#if DB_LEVEL >= 1 - /* Fn like macro. */ - #define db_set_mode(md, miP) db_set_mode_ex(md, miP, NULL) - #define db_set_log_file(strP) db_set_log_file_ex(strP) -#else - #define db_set_mode(md, miP) ((void) 0) - #define db_set_log_file(strP) ((void) 0) -#endif - -/* Final use macros after testing of DB_LEVEL / db_option. */ -#define db_assert_final(expr) \ - ((expr) ? ((void) 0) : db_assert_fail(#expr, __FILE__, __LINE__)) - -/* Macros whose compilation is conditional on the value of DB_LEVEL. */ -#if DB_LEVEL >= 1 - #define db_assert1(expr) db_assert_final(expr) - #define db_onlyassert1(expr) db_assert_final(expr) - #define db_verify1(expr) db_assert_final(expr) - #define db_print1(x, y, strP) db_print_fired(x, y, strP) - #define db_msg1(strP) db_msg_fired(strP) - #define db_log1(strP) db_log_fired(strP) - #define db_code1(code) code - #define db_printf1(params) db_printf_fired params - #define db_msgf1(params) db_msgf_fired params - #define db_logf1(params) db_logf_fired params -#else - #define db_assert1(expr) _db_assume(expr) - #define db_onlyassert1(__ignore) ((void) 0) - #define db_verify1(expr) (expr) - #define db_print1(x, y, __ignore) ((void) 0) - #define db_msg1(__ignore) _db_assume(0) - #define db_log1(__ignore) ((void) 0) - #define db_code1(__ignore) - #define db_printf1(x, y, __ignore) ((void) 0) - #define db_msgf1(__ignore) _db_assume(0) - #define db_logf1(__ignore) ((void) 0) -#endif -#if DB_LEVEL >= 2 - #define db_assert2(expr) db_assert_final(expr) - #define db_onlyassert2(expr) db_assert_final(expr) - #define db_verify2(expr) db_assert_final(expr) - #define db_print2(x, y, strP) db_print_fired(x, y, strP) - #define db_msg2(strP) db_msg_fired(strP) - #define db_log2(strP) db_log_fired(strP) - #define db_code2(code) code - #define db_printf2(params) db_printf_fired params - #define db_msgf2(params) db_msgf_fired params - #define db_logf2(params) db_logf_fired params -#else - #define db_assert2(expr) _db_assume(expr) - #define db_onlyassert2(__ignore) ((void) 0) - #define db_verify2(expr) (expr) - #define db_print2(x, y, __ignore) ((void) 0) - #define db_msg2(__ignore) _db_assume(0) - #define db_log2(__ignore) ((void) 0) - #define db_code2(__ignore) - #define db_printf2(x, y, __ignore) ((void) 0) - #define db_msgf2(__ignore) _db_assume(0) - #define db_logf2(__ignore) ((void) 0) -#endif -#if DB_LEVEL >= 3 - #define db_assert3(expr) db_assert_final(expr) - #define db_onlyassert3(expr) db_assert_final(expr) - #define db_verify3(expr) db_assert_final(expr) - #define db_print3(x, y, strP) db_print_fired(x, y, strP) - #define db_msg3(strP) db_msg_fired(strP) - #define db_log3(strP) db_log_fired(strP) - #define db_code3(code) code - #define db_printf3(params) db_printf_fired params - #define db_msgf3(params) db_msgf_fired params - #define db_logf3(params) db_logf_fired params -#else - #define db_assert3(expr) _db_assume(expr) - #define db_onlyassert3(__ignore) ((void) 0) - #define db_verify3(expr) (expr) - #define db_print3(x, y, __ignore) ((void) 0) - #define db_msg3(__ignore) _db_assume(0) - #define db_log3(__ignore) ((void) 0) - #define db_code3(__ignore) - #define db_printf3(x, y, __ignore) ((void) 0) - #define db_msgf3(__ignore) _db_assume(0) - #define db_logf3(__ignore) ((void) 0) -#endif -#if DB_LEVEL >= 4 - #define db_assert4(expr) db_assert_final(expr) - #define db_onlyassert4(expr) db_assert_final(expr) - #define db_verify4(expr) db_assert_final(expr) - #define db_print4(x, y, strP) db_print_fired(x, y, strP) - #define db_msg4(strP) db_msg_fired(strP) - #define db_log4(strP) db_log_fired(strP) - #define db_code4(code) code - #define db_printf4(params) db_printf_fired params - #define db_msgf4(params) db_msgf_fired params - #define db_logf4(params) db_logf_fired params -#else - #define db_assert4(expr) _db_assume(expr) - #define db_onlyassert4(__ignore) ((void) 0) - #define db_verify4(expr) (expr) - #define db_print4(x, y, __ignore) ((void) 0) - #define db_msg4(__ignore) _db_assume(0) - #define db_log4(__ignore) ((void) 0) - #define db_code4(__ignore) - #define db_printf4(x, y, __ignore) ((void) 0) - #define db_msgf4(__ignore) _db_assume(0) - #define db_logf4(__ignore) ((void) 0) -#endif -#if DB_LEVEL >= 5 - #define db_assert5(expr) db_assert_final(expr) - #define db_onlyassert5(expr) db_assert_final(expr) - #define db_verify5(expr) db_assert_final(expr) - #define db_print5(x, y, strP) db_print_fired(x, y, strP) - #define db_msg5(strP) db_msg_fired(strP) - #define db_log5(strP) db_log_fired(strP) - #define db_code5(code) code - #define db_printf5(params) db_printf_fired params - #define db_msgf5(params) db_msgf_fired params - #define db_logf5(params) db_logf_fired params -#else - #define db_assert5(expr) _db_assume(expr) - #define db_onlyassert5(__ignore) ((void) 0) - #define db_verify5(expr) (expr) - #define db_print5(x, y, __ignore) ((void) 0) - #define db_msg5(__ignore) _db_assume(0) - #define db_log5(__ignore) ((void) 0) - #define db_code5(__ignore) - #define db_printf5(x, y, __ignore) ((void) 0) - #define db_msgf5(__ignore) _db_assume(0) - #define db_logf5(__ignore) ((void) 0) -#endif - -/* Macros which fire if db_option is non-zero (and NDEBUG is not - * defined). - */ -#ifndef NDEBUG - #define db_assert_opt(expr) if(db_option) db_assert_final(expr) - #define db_onlyassert_opt(expr) if(db_option) db_assert_final(expr) - #define db_verify_opt(expr) ((db_option) ? db_assert_final(expr) : (expr)) - #define db_print_opt(x, y, strP) if(db_option) db_print_fired(x, y, strP) - #define db_msg_opt(strP) if(db_option) db_msg_fired(strP) - #define db_log_opt(strP) if(db_option) db_log_fired(strP) - #define db_code_opt(code) if(db_option) code - #define db_printf_opt(params) if(db_option) db_printf_fired params - #define db_msgf_opt(params) if(db_option) db_msgf_fired params - #define db_logf_opt(params) if(db_option) db_logf_fired params -#else - #define db_assert_opt(expr) _db_assume(expr) - #define db_onlyassert_opt(__ignore) ((void) 0) - #define db_verify_opt(expr) (expr) - #define db_print_opt(x,y,__ignore) ((void) 0) - #define db_msg_opt(__ignore) _db_assume(0) - #define db_log_opt(__ignore) ((void) 0) - #define db_code_opt(code) - #define db_printf_opt(params) ((void) 0) - #define db_msgf_opt(params) _db_assume(0) - #define db_logf_opt(params) ((void) 0) -#endif - -/* Macros for setting and getting db_option. */ -#ifndef NDEBUG - #define db_option_set(status) db_option = (status) - #define db_option_on() db_option = 1 - #define db_option_off() db_option = 0 - #define db_option_get() (db_option) -#else - #define db_option_set(__ignore) ((void) 0) - #define db_option_on() ((void) 0) - #define db_option_off() ((void) 0) - #define db_option_get() (0) -#endif - -/* T Y P E S ********************************************************** */ - -struct db_dd_mode_tag -{ - void *directDrawP; - void *visibleSurfaceP; - void *drawSurfaceP; - int width, height, bitsPerPixel; - unsigned short foreCol, backCol; - int bltOrFlip; - int bltXOffset, bltYOffset; -}; - -/* P R O T O S ******************************************************** */ - -/* Don't prototype anything or declare globals if NDEBUG is defined. */ -#ifndef NDEBUG - -/* New formatted debugging fns. */ -extern void __cdecl db_logf_fired(const char *fmtStrP, ...); -extern void __cdecl db_printf_fired(int x, int y, const char *fmtStrP, ...); -extern void __cdecl db_msgf_fired(const char *fmtStrP, ...); - -/* Called whenever an assertion fails. */ -extern void db_assert_fail(const char *exprP, const char *fileP, int line); - -/* Displays a message and has the program pause until the user responds - * to it. - */ -extern void db_msg_fired(const char *strP); - -/* Displays a message (on platforms that support positioning, at (x, y)) - * and continues program execution immediately. - */ -extern void db_print_fired(int x, int y, const char *strP); - -/* Writes a message to a log file. */ -extern void db_log_fired(const char *strP); - -/* Deletes the old log file, so that the log file only contains messages - * saved from this point on. Use ONCE at the start of any program that - * uses any of the db_log macros. - */ -extern void db_log_init(void); - -/* Gets the current infomation needed for the display mode. Used to enable - * other code to use the same debugging stuff. The return value is modeInfoP - */ -extern int db_get_mode(void **modeInfoPP, void **FontPP); - -/* Changes the log file name */ -extern void db_set_log_file_ex(const char *strP); - -/* Sets the display mode for the debugging functions to use. mode must - * be one of DB_DOS, DB_WINDOWS or DB_DIRECTDRAW. The modeInfoP parameter - * is NULL except for Direct Draw. The Last parameter can be NULL. - */ -extern void db_set_mode_ex(int mode, void *modeInfoP, void *newFontP); - -/* Called to set whether exceptions or brakepoints are called. */ -extern void DbUseBrakepoints(BOOL use_brakepoints); - -/* Call this to de-allocate memory used to store the debugging font. This - * fn does nothing unless you are in DirectDraw mode, since this is the - * only mode which loads its own font. Calling this fn is not strictly - * necessary since the OS will de-allocate a process' outstanding dynamic - * memory allocations when it ends anyway. However, calling this fn is - * cleaner and avoids BoundsChecker hits. - */ -extern void db_uninit(void); - - /* G L O B A L S ****************************************************** */ - -/* Should we expand _opt type macros? */ -extern int db_option; - -#endif /* of #ifndef NDEBUG */ - -/* E N D W R A P P E R ********************************************** */ - -/* Permit use in a C++ source file. */ -#ifdef __cplusplus -} -#endif - -/* Avoid multiple inclusions of this file in a single source file. */ -#endif diff --git a/3dc/win95/DD_FUNC.CPP b/3dc/win95/DD_FUNC.CPP deleted file mode 100644 index 3be2188..0000000 --- a/3dc/win95/DD_FUNC.CPP +++ /dev/null @@ -1,2260 +0,0 @@ -extern "C" { - -#include "3dc.h" -#include "vramtime.h" -#include "dxlog.h" -#include "inline.h" -#include "scrshot.hpp" -#include "awTexLd.h" // to set the surface format for Aw gfx dd surface loads - -#define UseLocalAssert No -#include "ourasert.h" - - -// for 640x480x8 experiment -#define InterlaceExperiment No - - -// In as separate define to debug because we -// might want to leave it even in a published -// game. -#define AllowReboot Yes - -// In as #define since there is no -// obvious good behaviour on failure -#define CheckForModeXInSubWindow No - -// Temporary hack! -#define NoPalette No -extern void TimeStampedMessage(char *s); - -// Nasty hack to try and fix non-appearance of font -// on some machines, probably due to there not being -// enough video memory for the font and BltFast -// not working outside display memory. -// According to Roxby, source colour keying won't work -// on Blt in the Beta 3, so expect a grotty font with this on. -// PS Source colour keying works, but the font -// still doesn't appear on my machine in SubWindow -// mode... Ho hum... -#define NoBltFastOnFont No - - -// Check to see if video mode is valid -// and rewrite it if it isn't reported - -#define CheckVideoMode No - -/* - Globals -*/ - -LPDIRECTDRAW lpDD; // DirectDraw object -LPDIRECTDRAWSURFACE lpDDSPrimary; // DirectDraw primary surface -LPDIRECTDRAWSURFACE lpDDSBack; // DirectDraw back surface -LPDIRECTDRAWSURFACE lpDDSHiddenBack; // for system memory rendering target, stable configuration -LPDIRECTDRAWPALETTE lpDDPal[MaxPalettes]; // DirectDraw palette -#if debug || PreBeta -LPDIRECTDRAWSURFACE lpDDDbgFont; // Debugging font, specific to current video mode -#endif -// For SubWindow mode -LPDIRECTDRAWCLIPPER lpDDClipper; -// DirectDraw gdi surface -LPDIRECTDRAWSURFACE lpDDGDI; -int VideoModeColourDepth; -long BackBufferPitch; -// To describe available video hardware -int TotalVideoMemory; -int NumAvailableVideoModes; -VIDEOMODEINFO AvailableVideoModes[MaxAvailableVideoModes]; -// Must be kept up to date with jump table!!!! -VIDEOMODEINFO EngineVideoModes[] = { - // Mode 320x200x8 - 320, // width - 200, // height - 8, // colour depth (bits per pixel) - // Mode 320x200x8T - 320, // width - 200, // height - 8, // colour depth (bits per pixel) - // Mode 320x200x15 - 320, // width - 200, // height - 16, // colour depth (bits per pixel) - // Mode 320x240x8 - 320, // width - 240, // height - 8, // colour depth (bits per pixel) - // Mode 640x480x8 - 640, // width - 480, // height - 8, // colour depth (bits per pixel) - // Mode 640x480x8T - 640, // width - 480, // height - 8, // colour depth (bits per pixel) - // Mode 640x480x15 - 640, // width - 480, // height - 16, // colour depth (bits per pixel) - // Mode 640x480x24 - 640, // width - 480, // height - 24 // colour depth (bits per pixel) - }; - -// Flag for backdrop composition - -// for 640x480x8 experiment -#if InterlaceExperiment -int oddDraw; -#endif - - -// Surface for Backdrop composition -LPDIRECTDRAWSURFACE lpDDBackdrop; -// Pointer into Backdrop DD surface -unsigned char* BackScreenBuffer; -// Pitch on auxilliary backdrop surface -static long BackScreenPitch; -DDPIXELFORMAT DisplayPixelFormat; - -// For locking against other processes, e.g. -// mouse pointer display -unsigned char GlobalFlipLock = No; - -/* Externs */ - -extern int VideoMode; -extern int VideoModeTypeScreen; -extern int VideoModeType; -extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; -extern unsigned char *ScreenBuffer; -extern HWND hWndMain; -extern unsigned char LPTestPalette[]; -extern unsigned char TestPalette[]; -extern int WindowMode; -extern WINSCALEXY TopLeftSubWindow; -extern WINSCALEXY ExtentXYSubWindow; -extern int WinWidth; -extern int WinHeight; -extern int WinLeftX; -extern int WinTopY; -extern int WinRightX; -extern int WinBotY; -extern int DXMemoryMode; -extern int RasterisationRequestMode; -extern int DXMemoryRequestMode; -extern int WindowRequestMode; -extern int VideoRequestMode; -extern int ZBufferRequestMode; -extern int SoftwareScanDrawRequestMode; -extern unsigned char AttemptVideoModeRestart; -extern VIDEORESTARTMODES VideoRestartMode; -extern BOOL MMXAvailable; -extern BOOL D3DHardwareAvailable; -extern int cosine[]; -extern int sine[]; - -BOOL really_32_bit = 0; - -void GenerateDirectDrawSurface() - -{ - - DDCAPS ddcaps; - HRESULT ddrval; - DDSURFACEDESC ddsd; - DDSCAPS ddscaps; - unsigned char Mode8T; - - // Check for combination of a MODEX type mode - // and SubWindowing - - #if AllowReboot - // THIS MAY NOT WORK!!! - if (WindowMode == WindowModeSubWindow) - ddrval = lpDD->SetCooperativeLevel(hWndMain, - DDSCL_NORMAL); - else - ddrval = lpDD->SetCooperativeLevel(hWndMain, - DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_ALLOWREBOOT ); - - LOGDXERR(ddrval); - #else - // More stable even if crashes cannot be booted - // out of? - if (WindowMode == WindowModeSubWindow) - ddrval = lpDD->SetCooperativeLevel(hWndMain, - DDSCL_NORMAL); - else - ddrval = lpDD->SetCooperativeLevel(hWndMain, - DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_ALLOWMODEX); - LOGDXERR(ddrval); - #endif - - TimeStampedMessage("Allow reboot thingy"); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x2); - } - #else - return; - #endif - - switch (ScreenDescriptorBlock.SDB_ScreenDepth) - { - case VideoModeType_8: - VideoModeColourDepth = 8; - Mode8T = No; - break; - case VideoModeType_15: - VideoModeColourDepth = 16; - Mode8T = No; - break; - case VideoModeType_24: - if (really_32_bit) - VideoModeColourDepth = 32; - else - VideoModeColourDepth = 24; - Mode8T = No; - break; - case VideoModeType_8T: - VideoModeColourDepth = 8; - Mode8T = Yes; - break; - default: - VideoModeColourDepth = 16; // default is 16 bit colour - break; - } - - // Note that SetDisplayMode is now technically part - // of the DirectDraw2 COM interface, not DirectDraw. - // However, as long as we do not wish to change - // monitor refresh rates we do not need to use the - // DirectDraw2 version or set up a separate secondary - // DD interface object, which be just plain fiddly. - - // MAY NOT WORK LIKE THIS IN SUBWINDOW MODE!!!! - if (WindowMode == WindowModeFullScreen) - { - ddrval = lpDD->SetDisplayMode(ScreenDescriptorBlock.SDB_Width, - ScreenDescriptorBlock.SDB_Height, VideoModeColourDepth); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - { - if ((ddrval == DDERR_INVALIDMODE) || - (ddrval == DDERR_GENERIC) || - (ddrval == DDERR_INVALIDPIXELFORMAT)) - { - AttemptVideoModeRestart = Yes; - VideoRestartMode = RestartDisplayModeNotAvailable; - } - return; - } - #endif - } - TimeStampedMessage("after SetDisplayMode"); - - // Create primary surface and back buffer - // IMPORTANT!!! Currently no support for triple - // buffering in SubWindow mode!!! - - if (WindowMode == WindowModeSubWindow) - { - // Create primary - memset(&ddsd,0,sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddsd.dwFlags = DDSD_CAPS; - - // Request a 3D capable device so that - // Direct3D accesses will work - // note primary must be in video memory - ddsd.ddsCaps.dwCaps = (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE); - - ddrval = lpDD->CreateSurface(&ddsd, &lpDDSPrimary, NULL); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x41); - } - #else - return; - #endif - - // Create back buffer - memset(&ddsd,0,sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS; - ddsd.dwHeight = ScreenDescriptorBlock.SDB_Height; - ddsd.dwWidth = ScreenDescriptorBlock.SDB_Width; - - // Request a 3D capable device so that - // Direct3D accesses will work - if (DXMemoryMode == SystemMemoryPreferred) - ddsd.ddsCaps.dwCaps = (DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY | DDSCAPS_3DDEVICE); - else // video memory if possible - ddsd.ddsCaps.dwCaps= (DDSCAPS_OFFSCREENPLAIN | DDSCAPS_3DDEVICE); - - ddrval = lpDD->CreateSurface(&ddsd, &lpDDSBack, NULL); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x5); - } - #else - return; - #endif - - // Create clipper objects - ddrval = lpDD->CreateClipper(0, &lpDDClipper, NULL); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x55); - } - #else - return; - #endif - - ddrval = lpDDClipper->SetHWnd(0, hWndMain); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x51); - } - #else - return; - #endif - - ddrval = lpDDSPrimary->SetClipper(lpDDClipper); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x52); - } - #else - return; - #endif - } - else // default to FullScreen... - { - TimeStampedMessage("after 'default to FullScreen'"); - if (DXMemoryMode == VideoMemoryPreferred) - { - ddcaps.dwSize = sizeof (ddcaps); - memset (&ddsd, 0, sizeof (ddsd)); - ddsd.dwSize = sizeof (ddsd); - ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; - - // Request a 3D capable device so that - // Direct3D accesses will work - ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | - DDSCAPS_FLIP | - DDSCAPS_COMPLEX | - DDSCAPS_3DDEVICE; - - ddsd.dwBackBufferCount = 1; - - ddrval = lpDD->CreateSurface(&ddsd, &lpDDSPrimary, NULL); - LOGDXERR(ddrval); - TimeStampedMessage("after vm CreateSurface"); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x41); - } - #else - { - // For dubious modex emulation - // problem fix and dubious driver - // cannot change to different bit depths - // fix. - // Note that this must be kept up to date!!!! - if ((ddrval == DDERR_OUTOFVIDEOMEMORY) && - ((VideoMode == VideoMode_DX_320x200x8) || - (VideoMode == VideoMode_DX_320x200x8T) || - (VideoMode == VideoMode_DX_320x240x8) || - (VideoMode == VideoMode_DX_320x200x15))) - { - AttemptVideoModeRestart = Yes; - VideoRestartMode = RestartOutOfVidMemForPrimary; - } - else if ((ddrval == DDERR_INVALIDMODE) || - (ddrval == DDERR_GENERIC) || - (ddrval == DDERR_INVALIDPIXELFORMAT)) - { - AttemptVideoModeRestart = Yes; - VideoRestartMode = RestartDisplayModeNotAvailable; - } - - return; - } - #endif - - // get a pointer to the back buffer - // DO I NEED TO SET A SIZE FIELD HERE?? - // SEEMS I _CAN'T_, ANYWAY... - ddscaps.dwCaps = DDSCAPS_BACKBUFFER; - - ddrval = lpDDSPrimary->GetAttachedSurface(&ddscaps,&lpDDSBack); - LOGDXERR(ddrval); - TimeStampedMessage("after vm GetAttachedSurface"); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x5); - } - #else - return; - #endif - } - // assume we want a system memory - // rendering target, e.g. for MMX - else - { - DDPIXELFORMAT TempPixelFormat; - - // Make primary, with back buffer in video memory - ddcaps.dwSize = sizeof (ddcaps); - memset (&ddsd, 0, sizeof (ddsd)); - ddsd.dwSize = sizeof (ddsd); - ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; - - // Request a 3D capable device so that - // Direct3D accesses will work - ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | - DDSCAPS_FLIP | - DDSCAPS_COMPLEX | - DDSCAPS_3DDEVICE; - - ddsd.dwBackBufferCount = 1; - - ddrval = lpDD->CreateSurface(&ddsd, &lpDDSPrimary, NULL); - LOGDXERR(ddrval); - TimeStampedMessage("after vm CreateSurface"); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - { - return; - } - #endif - - // get a pointer to the back buffer - // Note that in this configuration the back - // buffer is hidden from the rendering system, - // since other configurations do not seem to be - // stable in ModeX emulation modes - ddscaps.dwCaps = DDSCAPS_BACKBUFFER; - - ddrval = lpDDSPrimary->GetAttachedSurface( - &ddscaps, - &lpDDSHiddenBack); - LOGDXERR(ddrval); - TimeStampedMessage("after vm GetAttachedSurface"); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - return; - #endif - - // Save pixel format of primary - memcpy(&TempPixelFormat, &ddsd.ddpfPixelFormat, - sizeof(DDPIXELFORMAT)); - TimeStampedMessage("after memcpy 1"); - - // Create rendering target - memset(&ddsd,0,sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS; - ddsd.dwHeight = ScreenDescriptorBlock.SDB_Height; - ddsd.dwWidth = ScreenDescriptorBlock.SDB_Width; - - // Ensure rendering target has same format as primary - memcpy(&ddsd.ddpfPixelFormat, &TempPixelFormat, - sizeof(DDPIXELFORMAT)); - TimeStampedMessage("after memcpy 2"); - - // Request a 3D capable device so that - // Direct3D accesses will work - ddsd.ddsCaps.dwCaps = (DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY | DDSCAPS_3DDEVICE); - - ddrval = lpDD->CreateSurface(&ddsd, &lpDDSBack, NULL); - TimeStampedMessage("after CreateSurface"); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - return; - #endif - } - } - - // Set the Colour Palette (paletted modes only) - #if NoPalette - #else - if (VideoModeColourDepth == 8) - { - - TimeStampedMessage("SHOULD NEVER GET HERE"); - - if (WindowMode == WindowModeSubWindow) - // Use system palette in a SubWindow case - { - // Standard windows RGB + flags palette - // structure prototyped in various versions - // (Though not, apparently, others) of objbase.h - PALETTEENTRY SystemPalette[256]; - // Get system palette via GDI device context - HDC hdc = GetDC(NULL); - GetSystemPaletteEntries(hdc, 0, (1 << 8), SystemPalette); - // Restrict system to two palette entries only. - SetSystemPaletteUse(hdc, SYSPAL_NOSTATIC); - ReleaseDC(NULL, hdc); - - // Flag system palette entries - // Will this work? - // I sure hope so... - { - int i; - // Take all but 20 basic entries for our - // greedy little sod of a game window - for (i=0; i<1; i++) - SystemPalette[i].peFlags = PC_EXPLICIT; - for (i=1; i<(256-1); i++) - { - SystemPalette[i].peRed = LPTestPalette[i*4]; - SystemPalette[i].peGreen = LPTestPalette[(i*4)+1]; - SystemPalette[i].peBlue = LPTestPalette[(i*4)+2]; - SystemPalette[i].peFlags = PC_RESERVED; - } - for (i=(256-1); i<256; i++) - SystemPalette[i].peFlags = PC_EXPLICIT; - } - - // Create the palette within DirectDraw, using - // DD palette initialisation rather than ours - ddrval = lpDD->CreatePalette(DDPCAPS_8BIT | DDPCAPS_ALLOW256, - SystemPalette, &lpDDPal[0], NULL); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x7); - } - #else - return; - #endif - - // Set palette on both buffers - ddrval = lpDDSBack->SetPalette(lpDDPal[0]); - LOGDXERR(ddrval); - ddrval = lpDDSPrimary->SetPalette(lpDDPal[0]); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - return; - #endif - // Save palette in internal format for - // use later - // Out because it causes problems with - // window mode swapping. - // ConvertDDToInternalPalette((unsigned char*) SystemPalette, TestPalette, 256); - } - else // default to FullScreen - { - if ((ScreenDescriptorBlock.SDB_Flags - & SDB_Flag_Raw256) || (Mode8T))// full 256 colours - ddrval = lpDD->CreatePalette((DDPCAPS_8BIT | DDPCAPS_ALLOW256), - (LPPALETTEENTRY)(LPTestPalette), - &lpDDPal[0], - NULL); - else // default is 222 - ddrval = lpDD->CreatePalette((DDPCAPS_8BIT), - (LPPALETTEENTRY)(LPTestPalette), - &lpDDPal[0], - NULL); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x7); - } - #else - return; - #endif - - ddrval = lpDDSPrimary->SetPalette(lpDDPal[0]); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x8); - } - #else - return; - #endif - -// Set palette on BOTH buffers to work around -// bug in Direct3D initialisation!!! - ddrval = lpDDSBack->SetPalette(lpDDPal[0]); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(0x8); - } - #else - return; - #endif - } - } - #endif // for NoPalette - - // Get the surface desc for AW DDSurface loads - - memset(&ddsd,0,sizeof ddsd); - ddsd.dwSize = sizeof ddsd; - ddrval = lpDDSPrimary->GetSurfaceDesc(&ddsd); - LOGDXERR(ddrval); - GLOBALASSERT(DD_OK==ddrval); - TimeStampedMessage("after memset"); - AwSetSurfaceFormat(&ddsd); - TimeStampedMessage("after AwSetSurfaceFormat"); - - // Do an initial lock and unlock on the back buffer - // to pull out vital information such as the - // surface description - LockSurfaceAndGetBufferPointer(); - UnlockSurface(); - TimeStampedMessage("after Lock & Unlock"); - -} - -// Lock back buffer and get screen pointer - -void LockSurfaceAndGetBufferPointer() -{ - DDSURFACEDESC ddsdback; - HRESULT ddrval; - int count = 0; - - #if optimiseblit - while (lpDDSBack->GetBltStatus(DDGBS_ISBLTDONE) != DD_OK); - #endif - - memset(&ddsdback, 0, sizeof(ddsdback)); - ddsdback.dwSize = sizeof(ddsdback); - - // DDLOCK_WAIT is another safety option that - // should in theory be removable by using - // the GetBltStatus call above. - // Or of course the while loop... - while ((ddrval = lpDDSBack->Lock(NULL, &ddsdback, DDLOCK_WAIT, NULL)) == DDERR_WASSTILLDRAWING) - { - count++; - if (count>1) // was 10000, for test purposes ONLY!!! - { - LOGDXERR(ddrval); - ReleaseDirect3D(); - exit(0x2001); - } - } - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - return; - #endif - } - - /* ddsdback now contains my lpSurface)*/ - - ScreenBuffer = (unsigned char *)ddsdback.lpSurface; - BackBufferPitch = ddsdback.lPitch; - - // Get pixel format description of - // rendering target - memcpy(&DisplayPixelFormat, &ddsdback.ddpfPixelFormat, - sizeof(DDPIXELFORMAT)); -} - -void UnlockSurface(void) -{ - HRESULT ddrval; - - ddrval = lpDDSBack->Unlock((LPVOID)ScreenBuffer); - LOGDXERR(ddrval); - - #if debug - if (ddrval != DD_OK) - { - ReleaseDirect3D(); - exit(ddrval); - } - #endif -} - -void FlipBuffers(void) -{ - HRESULT ddrval; - - // for locking against other draw processes, - // e.g. mouse pointer - GlobalFlipLock = Yes; - - // IMPORTANT!!! OptimiseFlip, Blit are - // not supported in SubWindow mode!!! - - if (WindowMode == WindowModeSubWindow) - { - RECT dest; - - // For SubWindow mode, we cannot flip, but - // must instead do a (stretched, in principle) - // blit to the front buffer to combine with GDI - // surfaces. - // The whole back buffer should be taken. - dest.left = WinLeftX; - dest.top = WinTopY; - dest.right = WinRightX; - dest.bottom = WinBotY; - ddrval = lpDDSPrimary->Blt(&dest, lpDDSBack, - NULL, DDBLT_WAIT, NULL); - } - else // default to FullScreen - { - // we hope to flip, and flip to hope - // we are the tumbling jongleurs... - if (DXMemoryMode == VideoMemoryPreferred) - { - #if optimiseflip - while (lpDDSBack->GetFlipStatus(DDGFS_ISFLIPDONE) == DDERR_WASSTILLDRAWING) - ProcessProjectWhileWaitingToBeFlippable(); - #endif - - // we are going to flip with DDFLIP_WAIT on - // even if optimiseflip is set. - // IT'S THE ONLY WAY TO BE SURE. - ddrval = lpDDSPrimary->Flip(NULL, DDFLIP_WAIT); - - while(1) - { - if (ddrval == DD_OK) - break; - if (ddrval == DDERR_SURFACELOST) - { - ddrval = lpDDSPrimary->Restore(); - if (ddrval != DD_OK) - break; - } - if (ddrval != DDERR_WASSTILLDRAWING) - break; - } - } - else // assume system memory rendering target - { - // Take rendering target to back buffer - // Rendering target should map fully onto back buffer - ddrval = lpDDSHiddenBack->Blt(NULL, lpDDSBack, - NULL, DDBLT_WAIT, NULL); - - // And now do a standard flip - #if optimiseflip - while (lpDDSBack->GetFlipStatus(DDGFS_ISFLIPDONE) == DDERR_WASSTILLDRAWING) - ProcessProjectWhileWaitingToBeFlippable(); - #endif - - // we are going to flip with DDFLIP_WAIT on - // even if optimiseflip is set. - // IT'S THE ONLY WAY TO BE SURE. - ddrval = lpDDSPrimary->Flip(NULL, DDFLIP_WAIT); - - while(1) - { - if (ddrval == DD_OK) - break; - if (ddrval == DDERR_SURFACELOST) - { - ddrval = lpDDSPrimary->Restore(); - if (ddrval != DD_OK) - break; - } - if (ddrval != DDERR_WASSTILLDRAWING) - break; - } - } - } - - GlobalFlipLock = No; - - ProjectSpecificBufferFlipPostProcessing(); - - HandleScreenShot(); - - #if InterlaceExperiment - oddDraw ^= 1; - #endif -} - -void InGameFlipBuffers(void) -{ - FlipBuffers(); - return; - HRESULT ddrval; - - // for locking against other draw processes, - // e.g. mouse pointer - GlobalFlipLock = Yes; - - // IMPORTANT!!! OptimiseFlip, Blit are - // not supported in SubWindow mode!!! - - if (WindowMode == WindowModeSubWindow) - { - RECT dest; - - // For SubWindow mode, we cannot flip, but - // must instead do a (stretched, in principle) - // blit to the front buffer to combine with GDI - // surfaces. - // The whole back buffer should be taken. - dest.left = WinLeftX; - dest.top = WinTopY; - dest.right = WinRightX; - dest.bottom = WinBotY; - ddrval = lpDDSPrimary->Blt(&dest, lpDDSBack, - NULL, DDBLT_WAIT, NULL); - } - else // default to FullScreen - { - // we hope to flip, and flip to hope - // we are the tumbling jongleurs... - if (DXMemoryMode == VideoMemoryPreferred) - { - #if optimiseflip - while (lpDDSBack->GetFlipStatus(DDGFS_ISFLIPDONE) == DDERR_WASSTILLDRAWING) - ProcessProjectWhileWaitingToBeFlippable(); - #endif - - // we are going to flip with DDFLIP_WAIT on - // even if optimiseflip is set. - // IT'S THE ONLY WAY TO BE SURE. - ddrval = lpDDSPrimary->Flip(NULL, 0); - - while(0) - { - if (ddrval == DD_OK) - break; - if (ddrval == DDERR_SURFACELOST) - { - ddrval = lpDDSPrimary->Restore(); - if (ddrval != DD_OK) - break; - } - if (ddrval != DDERR_WASSTILLDRAWING) - break; - } - } - else // assume system memory rendering target - { - LOCALASSERT(0); - // Take rendering target to back buffer - // Rendering target should map fully onto back buffer - ddrval = lpDDSHiddenBack->Blt(NULL, lpDDSBack, - NULL, DDBLT_WAIT, NULL); - - // And now do a standard flip - #if optimiseflip - while (lpDDSBack->GetFlipStatus(DDGFS_ISFLIPDONE) == DDERR_WASSTILLDRAWING) - ProcessProjectWhileWaitingToBeFlippable(); - #endif - - // we are going to flip with DDFLIP_WAIT on - // even if optimiseflip is set. - // IT'S THE ONLY WAY TO BE SURE. - ddrval = lpDDSPrimary->Flip(NULL, DDFLIP_WAIT); - - while(1) - { - if (ddrval == DD_OK) - break; - if (ddrval == DDERR_SURFACELOST) - { - ddrval = lpDDSPrimary->Restore(); - if (ddrval != DD_OK) - break; - } - if (ddrval != DDERR_WASSTILLDRAWING) - break; - } - } - } - - GlobalFlipLock = No; - - ProjectSpecificBufferFlipPostProcessing(); - - HandleScreenShot(); - - #if InterlaceExperiment - oddDraw ^= 1; - #endif -} - -// As of 29/4/96, slightly later in the day, -// it now deallocates NOTHING explcitly, but -// just calls Release on the entire DD object, -// which seems a better approach. Ho hum. - -// This function is now OBSOLETE (25 / 7 / 96) -// CALL RELEASEDIRECT3D INSTEAD!!! - -void finiObjects(void) -{ - if (lpDD != NULL) - { - lpDD->Release(); - lpDD = NULL; - } -} - -// Release ONE direct draw surface, to be used -// when replacing images via imageheader array, -// e.g. in LoadBackdrop. - -void ReleaseDDSurface(void* DDSurface) - -{ - LPDIRECTDRAWSURFACE lpSurface; - - WaitForVRamReady(VWS_DDRELEASE); - - lpSurface = (LPDIRECTDRAWSURFACE) DDSurface; - - if (lpSurface != NULL) - { - lpSurface->Release(); - lpSurface = NULL; - } -} - - -// Blt member is used rather BltFast because BltFast does not -// allow a colour fill - -void ColourFillBackBuffer(int FillColour) - -{ - HRESULT ddrval; - DDBLTFX ddbltfx; - - memset(&ddbltfx, 0, sizeof(ddbltfx)); - ddbltfx.dwSize = sizeof(ddbltfx); - ddbltfx.dwFillColor = FillColour; - - /* lets blt a color to the surface*/ - #if optimiseblit - while (lpDDSBack->GetBltStatus(DDGBS_CANBLT) != DD_OK); - #endif - - #if optimiseblit - ddrval = lpDDSBack->Blt(NULL, NULL, NULL, DDBLT_COLORFILL | DDBLT_ASYNC, &ddbltfx); - - if (ddrval == DDERR_WASSTILLDRAWING) - ddrval = lpDDSBack->Blt(NULL, NULL, NULL, DDBLT_COLORFILL | DDBLT_WAIT, - &ddbltfx); - #else - ddrval = lpDDSBack->Blt(NULL, NULL, NULL, DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx); - #endif - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - return; - #endif - } -} - -// Blt member is used rather BltFast because BltFast does not -// allow a colour fill - -void ColourFillBackBufferQuad(int FillColour, int LeftX, - int TopY, int RightX, int BotY) - -{ - HRESULT ddrval; - DDBLTFX ddbltfx; - RECT destRect; - - destRect.left = LeftX; - destRect.top = TopY; - destRect.right = RightX; - destRect.bottom = BotY; - - memset(&ddbltfx, 0, sizeof(ddbltfx)); - ddbltfx.dwSize = sizeof(ddbltfx); - ddbltfx.dwFillColor = FillColour; - - /* lets blt a color to the surface*/ - #if optimiseblit - while (lpDDSBack->GetBltStatus(DDGBS_CANBLT) != DD_OK); - #endif - - #if optimiseblit - ddrval = lpDDSBack->Blt(&destRect, NULL, NULL, DDBLT_COLORFILL | DDBLT_ASYNC, &ddbltfx); - - if (ddrval == DDERR_WASSTILLDRAWING) - ddrval = lpDDSBack->Blt(&destRect, NULL, NULL, DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx); - #else - ddrval = lpDDSBack->Blt(&destRect, NULL, NULL, DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx); - #endif - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - return; - #endif - } -} - -// Note Blt is used rather than BltFast because BltFast will -// always attempt to invoke an asynchronous blit and this appears -// to be unstable at present (cf. problems with optimiseblit) -// CHECK THIS -- WITH DDBLTFASTWAIT??? -// COMMENT ABOVE NOW OBSOLETE... - -void BlitToBackBuffer(void* lpBackground, RECT* destRectPtr, RECT* srcRectPtr) - -{ - HRESULT ddrval; - - #if optimiseblit - while (lpDDSBack->GetBltStatus(DDGBS_CANBLT) != DD_OK); - #endif - - #if optimiseblit - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_ASYNC, NULL); - - if (ddrval == DDERR_WASSTILLDRAWING) - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_WAIT, NULL); - #else - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_WAIT, NULL); - #endif - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - return; - #endif - } -} - -// Note Blt is used rather than BltFast because BltFast does not -// support DDBLTFX and therefore cannot be used to attempt to -// prevent tearing - -void BlitToBackBufferWithoutTearing(void* lpBackground, RECT* destRectPtr, RECT* srcRectPtr) - -{ - HRESULT ddrval; - DDBLTFX ddbltfx; - - memset(&ddbltfx, 0, sizeof(ddbltfx)); - ddbltfx.dwSize = sizeof(ddbltfx); - ddbltfx.dwDDFX = DDBLTFX_NOTEARING; - - #if optimiseblit - while (lpDDSBack->GetBltStatus(DDGBS_CANBLT) != DD_OK); - #endif - - #if optimiseblit - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_ASYNC | DDBLT_DDFX, &ddbltfx); - - if (ddrval == DDERR_WASSTILLDRAWING) - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_WAIT | DDBLT_DDFX, &ddbltfx); - #else - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_WAIT | DDBLT_DDFX, &ddbltfx); - #endif - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - return; - #endif - } -} - -#if 0 - -// Note Blt is used rather than BltFast because BltFast does -// not support the DDBLTFX structure and therefore cannot accept -// a rotated blit - -void RotatedBlitToBackBuffer(void* lpBackground, RECT* destRectPtr, RECT* srcRectPtr, int RollZ) - -{ - HRESULT ddrval; - DDBLTFX ddbltfx; - - memset(&ddbltfx, 0, sizeof(ddbltfx)); - ddbltfx.dwSize = sizeof(ddbltfx); - ddbltfx.dwRotationAngle = RollZ; - - #if optimiseblit - while (lpDDSBack->GetBltStatus(DDGBS_CANBLT) != DD_OK); - #endif - - #if optimiseblit - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_ASYNC | DDBLT_ROTATIONANGLE, &ddbltfx); - - if (ddrval == DDERR_WASSTILLDRAWING) - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_WAIT | DDBLT_ROTATIONANGLE, &ddbltfx); - #else - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_WAIT | DDBLT_ROTATIONANGLE, &ddbltfx); - #endif - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - return; - #endif - } -} - -// Note Blt is used rather than BltFast because BltFast does not -// support DDBLTFX and therefore cannot be used to attempt to -// prevent tearing - -void RotatedBlitToBackBufferWithoutTearing(void* lpBackground, RECT* destRectPtr, RECT* srcRectPtr, int RollZ) - -{ - HRESULT ddrval; - DDBLTFX ddbltfx; - - memset(&ddbltfx, 0, sizeof(ddbltfx)); - ddbltfx.dwSize = sizeof(ddbltfx); - ddbltfx.dwDDFX = DDBLTFX_NOTEARING; - ddbltfx.dwRotationAngle = RollZ; - - #if optimiseblit - while (lpDDSBack->GetBltStatus(DDGBS_CANBLT) != DD_OK); - #endif - - #if optimiseblit - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_ASYNC | DDBLT_DDFX | DDBLT_ROTATIONANGLE, &ddbltfx); - - if (ddrval == DDERR_WASSTILLDRAWING) - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_WAIT | DDBLT_DDFX | DDBLT_ROTATIONANGLE, &ddbltfx); - #else - ddrval = lpDDSBack->Blt(destRectPtr, (LPDIRECTDRAWSURFACE) lpBackground, - srcRectPtr, DDBLT_WAIT | DDBLT_DDFX | DDBLT_ROTATIONANGLE, &ddbltfx); - #endif - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - return; - #endif - } -} - -#endif - - -// Note x, y are assumed to be TOP LEFT of character -// BltFast is used here, partially as an experiment (ahem...) - -// THIS FUNCTION ASSUMES A VERTICAL FONT BRUSH!!! - -// FIXME!!! This function does not always seem to -// produce visible text in SubWindow mode; i.e. -// as of 29/4/96 it works on Roxby's and fails on -// mine. I suspect this is because we are using -// BltFast, which 'works only on display memory', -// and there isn't enough video RAM on my card -// to put the debug font in video memory in SubWindow -// mode. Or something. -// At present I have done nothing about this, since Roxby -// claims that as of Beta 3 he can't get source colour -// keying working on the blitter without using BltFast, and -// we need source colour keying to get the font to -// look right. -// Will have to be looked at at some stage, 'tho. - -#if debug || PreBeta -void BlitWin95Char(int x, int y, unsigned char toprint) - -{ - static int bltwin95char_ok=1; - if (!bltwin95char_ok) return; - - int FontIndex; - RECT source; - HRESULT ddrval; - #if NoBltFastOnFont - RECT destination; - #endif - - // Check for data out of range for font - if ((toprint < FontStart) || (toprint > FontEnd)) - return; - - // Check for character being on screen - if ((x < ScreenDescriptorBlock.SDB_ClipLeft) || - ((x + CharWidth) > ScreenDescriptorBlock.SDB_ClipRight) || - (y < ScreenDescriptorBlock.SDB_ClipUp) || - ((y + CharHeight) > ScreenDescriptorBlock.SDB_ClipDown)) - return; - - // Generate font index and source rectangle - // Assumes vertical brush - FontIndex = (toprint - FontStart); - - source.left = 0; - source.top = (FontIndex * CharHeight); - source.right = CharWidth; - source.bottom = ((FontIndex + 1) * CharHeight); - - // Do blit - #if NoBltFastOnFont - destination.left = x; - destination.top = y; - destination.right = (x+CharWidth); - destination.bottom = (y+CharHeight); - ddrval = lpDDSBack->Blt(&destination, lpDDDbgFont, - &source, DDBLT_WAIT | DDBLT_KEYSRC, NULL); - #else - ddrval = lpDDSBack->BltFast(x, y, - lpDDDbgFont, &source, - DDBLTFAST_WAIT | DDBLTFAST_SRCCOLORKEY); - #endif - - LOGDXERR(ddrval); - if (ddrval != DD_OK) - #if debug && 0 - { - ReleaseDirect3D(); - exit(0x11); - } - #else - bltwin95char_ok = 0; - return; - #endif -} - -#else -void BlitWin95Char(int x, int y, unsigned char toprint) -{ -} -#endif - -// IMPORTANT!!! FIXME!!!! - -// This function has been hacked to FORCE images into -// system memory due to what appears to be a bug in -// DirectDraw's defaulting to system memory... - -// Has HOPEFULLY now been fixed to deal with non 8 bit -// images... but I wouldn't count on it... - -// If SysMem is TRUE, the image should go into system memory. If it is -// FALSE, we will try for video memory. And may God walk at our side in -// the valley of the shadow. - - - -// This callback enumerates all the DirectDraw -// devices present on a system searching for one -// with hardware 3D support available. If such -// a device is present, it will always be selected. -// Otherwise, no valid device will be returned. - -static BOOL bHardwareDDObj = FALSE; -static BOOL bNoHardwareDD = FALSE; - - -BOOL FAR PASCAL EnumDDObjectsCallback(GUID FAR* lpGUID, LPSTR lpDriverDesc, - LPSTR lpDriverName, LPVOID lpContext) -{ - LPDIRECTDRAW lpDDTest; - DDCAPS DriverCaps, HELCaps; - HRESULT ddrval; - - /* - A NULL GUID* indicates the DirectDraw HEL which we are not interested - in at the moment, because we are cruel and heartless and really - really nasty people, after all. - */ - - if (lpGUID) - { - // Create the DirectDraw device using this driver. If it fails, - // just move on to the next driver. - - ddrval = DirectDrawCreate(lpGUID, &lpDDTest, NULL); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - return DDENUMRET_OK; - - // Get the capabilities of this DirectDraw driver. If it fails, - // just move on to the next driver. - - memset(&DriverCaps, 0, sizeof(DDCAPS)); - DriverCaps.dwSize = sizeof(DDCAPS); - memset(&HELCaps, 0, sizeof(DDCAPS)); - HELCaps.dwSize = sizeof(DDCAPS); - - ddrval = lpDDTest->GetCaps(&DriverCaps, &HELCaps); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - lpDDTest->Release(); - return DDENUMRET_OK; - } - - // JH - changed so that debugging in a window works if you've got two cards or something - if (DriverCaps.dwCaps & DDCAPS_3D && WindowRequestMode != WindowModeSubWindow) - { - // We have found a 3d hardware device. Return the DD object - // and stop enumeration. - // This assumes that 3d capable DD hardware - // drivers cannot operate in a window. - // True? CHECKME!!! - WindowMode = WindowModeFullScreen; - *(LPDIRECTDRAW*)lpContext = lpDDTest; - return DDENUMRET_CANCEL; - } - lpDDTest->Release(); - } - return DDENUMRET_OK; -} - - -// Set up the DirectDraw object for the -// system. Using this we can determine the -// system capabilities. The DirectDraw object -// in question should never be released until -// ExitSystem, even if window or video modes -// are changed. Note that as well as checking -// for valid video modes etc, this function will -// also search for hardware DirectDraw objects -// and use one if appropriate. - -// Note that GenerateDirectDrawSurface and -// SetVideoMode now just set a video mode, -// rather than (as previously) initialising the -// DirectDraw model. - -// This function should be called -// during InitialiseSystem, so that we can -// be sure that SetVideoMode (called later) -// will be setting a valid mode. The function -// must be called after InitialVideoMode (which -// sets the mode it validates) and before -// InitialiseWindowsSystem, since in the -// current version that needs to know the -// WindowMode, not the VideoMode. Note that -// InitialiseWindowsSystem itself must be called -// after InitialVideoMode (it is currently -// called at the start of InitialiseSystem). - -DDCAPS direct_draw_caps; - -BOOL InitialiseDirectDrawObject(void) - -{ - HRESULT ddrval; - LPDIRECTDRAW lpDDHardware = NULL; - - // Set up DirectDraw object. - - // If we are not in emulation only mode, - // search for a hardware 3D capable DirectDraw - // driver and use it. If this fails, or if we - // are in emulation, go straight for the HEL. - if (RasterisationRequestMode != RequestSoftwareRasterisation) - { - ddrval = DirectDrawEnumerate(EnumDDObjectsCallback, &lpDDHardware); - LOGDXERR(ddrval); - if (ddrval != DD_OK) - { - #if debug - ReleaseDirect3D(); - exit(ddrval); - #else - return FALSE; - #endif - } - } - - // If we don't have a hardware driver, either - // because there wasn't one or because we are in - // HEL... then make one. - - if (!lpDDHardware) - { - if (RasterisationRequestMode != RequestSoftwareRasterisation) - bNoHardwareDD = TRUE; - bHardwareDDObj = FALSE; - ddrval = DirectDrawCreate(NULL, &lpDD, NULL); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - { - ReleaseDirect3D(); // for safety - return FALSE; - } - #endif - } - else - { - bHardwareDDObj = TRUE; - lpDD = lpDDHardware; - } - - AwSetDDObject(lpDD); - - // Get caps for hardware DD driver/HEL layer - memset(&direct_draw_caps, 0, sizeof(direct_draw_caps)); - direct_draw_caps.dwSize = sizeof(direct_draw_caps); - ddrval = lpDD->GetCaps(&direct_draw_caps, NULL); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - { - ReleaseDirect3D(); // for safety - return FALSE; - } - #endif - - // Put statistics into globals - TotalVideoMemory = (int) (direct_draw_caps.dwVidMemTotal); - // At some stage, we should set up a proper - // structure here with the general system - // capabilities in it. - // Notably, we may need to check DD surface - // alignment values and the stride. - - // NOTE THAT AS GARRY HAS POINTED OUT, TOTAL - // FREE VIDMEM CAN CHANGE AFTER SETTING THE - // VIDEO MODE OR COOPERATIVE LEVEL, SO WE - // SHOULD REALLY BE RUNNING THIS GETCAPS MEMBER - // ON THE DDOBJECT AGAIN AFTER GENERATESURFACE, OR - // POSSIBLY WHENEVER THE USER WANTS. - // ***FIXME!!!*** - - // Run the display modes enumerator - // Note that NULL in the second entry - // means enumerate all available display - // modes on the driver. - NumAvailableVideoModes = 0; - ddrval = lpDD->EnumDisplayModes(0, NULL, 0, EnumDisplayModesCallback); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - { - ReleaseDirect3D(); // for safety - return FALSE; - } - #endif - - // Check that the video mode asked - // for (initially at least in - // InitialVideoMode) is actually - // available. If it is not, attempt to - // default to 640x480x8 and 640x480x15 - // (liable to be the most common modes) - // and if that fails, exit altogether - // with a failure code. - - // Note!!! This only matters in FullScreen - // mode. In SubWindow mode we must use the - // Windows display mode anyway. Obviously - // initialisation of the video mode will fail - // in SubWindow mode if the colour depth of - // the Windows display is different to the - // VideoMode colour depth, but I have not bothered - // to check for this since SubWindow mode is - // only intended for debugging and the failure - // case exits with an appropriate DirectDraw - // error anyway. - #if CheckVideoMode - if (WindowMode == WindowModeFullScreen) - { - if (!(CheckForVideoModes(VideoMode))) - { - VideoMode = VideoMode_DX_640x480x8; - if (!(CheckForVideoModes(VideoMode))) - { - VideoMode = VideoMode_DX_640x480x15; - if (!(CheckForVideoModes(VideoMode))) - { - ReleaseDirect3D(); // for safety - return FALSE; - } - } - } - } - #endif // for CheckVideoMode - - return TRUE; // Successful completion -} - - -// return TRUE on success - -static BOOL ReallyChangeDDObj(void) -{ - finiObjects(); - - if (InitialiseDirectDrawObject() - == FALSE) - /* - If we cannot get a video mode, - fail. No point in a non debugging option - for this. - */ - { - #if debug - ReleaseDirect3D(); - exit(0x997798); - #else - return FALSE; - #endif - } - - /* - Initialise global to say whether - we think there is an onboard 3D - acceleration card / motherboard - built-in - */ - #if 0 - TestInitD3DObject(); - -/* - This is (HOPEFULLY!!) now the right - place to put this call. Note that it is - not absolutely certain that we can do test - blits from DirectDraw without setting - a cooperative level, however... And note also - that MMX works better with the back buffer in - system memory... -*/ - TestMemoryAccess(); - #endif - return TRUE; -} - -int SelectDirectDrawObject(LPGUID pGUID) -{ - HRESULT ddrval; - LPDIRECTDRAW lpDDHardware = NULL; - - // Set up DirectDraw object. - bNoHardwareDD = TRUE; - bHardwareDDObj = FALSE; - ddrval = DirectDrawCreate(pGUID, &lpDD, NULL); - - AwSetDDObject(lpDD); - - // Get caps for hardware DD driver/HEL layer - memset(&direct_draw_caps, 0, sizeof(direct_draw_caps)); - direct_draw_caps.dwSize = sizeof(direct_draw_caps); - ddrval = lpDD->GetCaps(&direct_draw_caps, NULL); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - { - ReleaseDirect3D(); // for safety - return FALSE; - } - #endif - - // Put statistics into globals - TotalVideoMemory = (int) (direct_draw_caps.dwVidMemTotal); - // At some stage, we should set up a proper - // structure here with the general system - // capabilities in it. - // Notably, we may need to check DD surface - // alignment values and the stride. - - // NOTE THAT AS GARRY HAS POINTED OUT, TOTAL - // FREE VIDMEM CAN CHANGE AFTER SETTING THE - // VIDEO MODE OR COOPERATIVE LEVEL, SO WE - // SHOULD REALLY BE RUNNING THIS GETCAPS MEMBER - // ON THE DDOBJECT AGAIN AFTER GENERATESURFACE, OR - // POSSIBLY WHENEVER THE USER WANTS. - // ***FIXME!!!*** - - // Run the display modes enumerator - // Note that NULL in the second entry - // means enumerate all available display - // modes on the driver. - NumAvailableVideoModes = 0; - ddrval = lpDD->EnumDisplayModes(0, NULL, 0, EnumDisplayModesCallback); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - { - ReleaseDirect3D(); // for safety - return FALSE; - } - #endif - - // Check that the video mode asked - // for (initially at least in - // InitialVideoMode) is actually - // available. If it is not, attempt to - // default to 640x480x8 and 640x480x15 - // (liable to be the most common modes) - // and if that fails, exit altogether - // with a failure code. - - // Note!!! This only matters in FullScreen - // mode. In SubWindow mode we must use the - // Windows display mode anyway. Obviously - // initialisation of the video mode will fail - // in SubWindow mode if the colour depth of - // the Windows display is different to the - // VideoMode colour depth, but I have not bothered - // to check for this since SubWindow mode is - // only intended for debugging and the failure - // case exits with an appropriate DirectDraw - // error anyway. - #if CheckVideoMode - if (WindowMode == WindowModeFullScreen) - { - if (!(CheckForVideoModes(VideoMode))) - { - VideoMode = VideoMode_DX_640x480x8; - if (!(CheckForVideoModes(VideoMode))) - { - VideoMode = VideoMode_DX_640x480x15; - if (!(CheckForVideoModes(VideoMode))) - { - ReleaseDirect3D(); // for safety - return FALSE; - } - } - } - } - #endif // for CheckVideoMode - - return TRUE; // Successful completion -} - - - -BOOL ChangeDirectDrawObject(void) -{ - if (RequestSoftwareRasterisation==RasterisationRequestMode) - { - // software modes required - if (bHardwareDDObj) - { - // but was previously hardware DD - return ReallyChangeDDObj(); - } - } - else - { - // hardware modes requested if available - if (!bHardwareDDObj && !bNoHardwareDD) - { - // but was previously software DD and - // we haven't established that hardware isn't available - return ReallyChangeDDObj(); - } - } - - return TRUE; -} - - - -BOOL CheckForVideoModes(int TestVideoMode) - -{ - int i=0; - BOOL EarlyExit = FALSE; - - do - { - if ((EngineVideoModes[TestVideoMode].Width - == AvailableVideoModes[i].Width) && - (EngineVideoModes[TestVideoMode].Height - == AvailableVideoModes[i].Height) && - (EngineVideoModes[TestVideoMode].ColourDepth - == AvailableVideoModes[i].ColourDepth)) - EarlyExit = TRUE; - else - i++; - } - while ((i < NumAvailableVideoModes) && - (!EarlyExit)); - - return(EarlyExit); -} - -HRESULT CALLBACK EnumDisplayModesCallback(LPDDSURFACEDESC pddsd, LPVOID Context) -{ - AvailableVideoModes[NumAvailableVideoModes].Width = pddsd->dwWidth; - AvailableVideoModes[NumAvailableVideoModes].Height = pddsd->dwHeight; - AvailableVideoModes[NumAvailableVideoModes].ColourDepth = pddsd->ddpfPixelFormat.dwRGBBitCount; - NumAvailableVideoModes++; - - if (NumAvailableVideoModes < MaxAvailableVideoModes) - return DDENUMRET_OK; - else - return DDENUMRET_CANCEL; -} - -// Deallocate all objects except the basic -// DirectDraw objects, which we want to do -// before shifting display modes or window -// mode. Note that ExitWindowsSystem must be -// called separately. Note also that ExitSystem -// should be called for a full system shutdown. - -// FIXME!!! BACKDROPS?!?!? -- done in -// DeallocateAllImages (called from ReleaseDirect3D -// and ReleaseDirect3DNotDD) - -// Note that getting the right sequence for releases -// here is CRUCIAL. Note also that the font surface -// is NOT explicitly deallocated; hopefully it will just -// go when we kill the primary (as an offscreen surface). -// Could this cause problems for DeallocateAllImages?? -// Um, err, I sure hope not... - - -void finiObjectsExceptDD(void) -{ - if (WindowMode == WindowModeSubWindow) - { - if (lpDDClipper != NULL) - { - lpDDClipper->Release(); - lpDDClipper = NULL; - } - } - - if (lpDDPal[0] != NULL) // should be killed neway??? - { - lpDDPal[0]->Release(); - lpDDPal[0] = NULL; - } - - if (lpDDSBack != NULL) - { - lpDDSBack->Release(); - lpDDSBack = NULL; - } - - if (lpDDSPrimary != NULL) - { - lpDDSPrimary->Release(); - lpDDSPrimary = NULL; - } -} - - -// This will hopefully allow us to change -// the palette at runtime, assuming that -// we are in a palettised mode. It will -// wait for vertical blank to make it work -// on all video cards (I hope). Note that -// the palette should be passed in engine -// internal format, i.e. 6 bits, and will be -// converted to the DirectDraw format internally. - -// Note we assume entry 0 in the lpDDPal array!!! - -// Note for 222 mode we set the FIRST 64 entries!!! -// Not certain that's right, actually... - -int ChangePalette (unsigned char* NewPalette) - -{ - unsigned char DDPalette[1024]; // 256 colours, 4 bytes each - int NumEntries; - - // Check for palettised mode - // Note we must use VideoModeTypeScreen - // due to nature of Direct3D ramp driver - // interface. - - if ((VideoModeTypeScreen != VideoModeType_8) && - (VideoModeTypeScreen != VideoModeType_8T)) - return No; - - // Check for FullScreen mode - // if (WindowMode != WindowModeFullScreen) - // return No; - - // Set up number of entries to change - if (ScreenDescriptorBlock.SDB_Flags & SDB_Flag_222) - NumEntries = 256; // actually, this seems to be right... - else if ((ScreenDescriptorBlock.SDB_Flags & SDB_Flag_Raw256) - || (VideoModeTypeScreen == VideoModeType_8T)) - NumEntries = 256; - else - return No; // undefined behaviour - - // Convert to DirectDraw 4 bytes, 8 bit format - // with all flag entries set to zero - - ConvertToDDPalette(NewPalette, DDPalette, NumEntries, 0); - - // Wait for beginning of next vertical - // blanking interval - lpDD->WaitForVerticalBlank(DDWAITVB_BLOCKBEGIN, NULL); - - // Set all entries in palette to new values - lpDDPal[0]->SetEntries(0,0,NumEntries,(LPPALETTEENTRY) - DDPalette); - - return Yes; -} - -// At some stage it may be worth expanding this function -// to get more than video memory, or replacing it -// with one that uses GetCaps to fill out a general -// structure. - -int GetAvailableVideoMemory(void) -{ - DDCAPS ddcaps; - HRESULT ddrval; - - // Get caps for DirectDraw object - memset(&ddcaps, 0, sizeof(ddcaps)); - ddcaps.dwSize = sizeof(ddcaps); - ddrval = lpDD->GetCaps(&ddcaps, NULL); - LOGDXERR(ddrval); - - if (ddrval != DD_OK) - #if debug - { - ReleaseDirect3D(); - exit(ddrval); - } - #else - return -1; - #endif - - return (int) (ddcaps.dwVidMemFree); -} - -/* - This is designed to allow for ModeX - emulation failures where the system - boots up in a low memory cost mode - which actually takes up much more than - a high cost mode because GDI cannot be - evicted. Note that the VideoMode reset - done here is in any case a last ditch - measure, since the higher res version will - be much slower as well as (normally) more - costly in terms of memory. - - It will also now do start errors due to the - driver not being able to change to a mode of - a different colour depth, and this not being reported - by the DirectDraw object's enum display modes - callback. Hopefully. - - NOTE THAT THIS MUST BE CALLED FROM YOUR WINMAIN - AFTER SETVIDEOMODE IF IT IS TO WORK. - - NOTE ALSO THAT THE ACTIVATION CODE FOR THIS IS - IN GENERATEDIRECTDRAWSURFACE AND WILL NOT BE TURNED - ON UNLESS -->DEBUG<-- IS -->OFF<--. -*/ - -void HandleVideoModeRestarts(HINSTANCE hInstance, int nCmdShow) -{ - if (AttemptVideoModeRestart) - { - switch (VideoRestartMode) - { - case RestartDisplayModeNotAvailable: - { - // Rewrite mode as equivalent resolution, - // different bit depth, before trying again. - // Note this must be kept up to date!!! - switch (VideoMode) - { - case VideoMode_DX_320x200x8: - { - ReleaseDirect3D(); - exit(0xfedd); - } - VideoMode = VideoMode_DX_320x200x15; - break; - - case VideoMode_DX_320x200x8T: - VideoMode = VideoMode_DX_320x200x15; - break; - - case VideoMode_DX_320x200x15: - VideoMode = VideoMode_DX_320x200x8T; - break; - - case VideoMode_DX_320x240x8: - VideoMode = VideoMode_DX_320x200x15; - break; - - case VideoMode_DX_640x480x8: - VideoMode = VideoMode_DX_640x480x15; - break; - - case VideoMode_DX_640x480x8T: - VideoMode = VideoMode_DX_640x480x15; - break; - - case VideoMode_DX_640x480x15: - VideoMode = VideoMode_DX_640x480x8T; - break; - - case VideoMode_DX_640x480x24: - VideoMode = VideoMode_DX_640x480x15; - break; - - default: // hmm... - break; - } - - // Clear variables - AttemptVideoModeRestart = No; - VideoRestartMode = NoRestartRequired; - - ChangeDisplayModes(hInstance, nCmdShow, - VideoMode, WindowRequestMode, - ZBufferRequestMode, RasterisationRequestMode, - SoftwareScanDrawRequestMode, DXMemoryRequestMode); - } - break; - - case RestartOutOfVidMemForPrimary: - { - // Guess mode reset - // Note this must be kept up to date!!! - if ((VideoMode == VideoMode_DX_320x200x8) || - (VideoMode == VideoMode_DX_320x200x8T) || - (VideoMode == VideoMode_DX_320x240x8)) - VideoMode = VideoMode_DX_640x480x8; - else if (VideoMode == VideoMode_DX_320x200x15) - VideoMode = VideoMode_DX_640x480x15; - - // Clear variables - AttemptVideoModeRestart = No; - VideoRestartMode = NoRestartRequired; - - ChangeDisplayModes(hInstance, nCmdShow, - VideoMode, WindowRequestMode, - ZBufferRequestMode, RasterisationRequestMode, - SoftwareScanDrawRequestMode, DXMemoryRequestMode); - } - break; - - default: // err... - break; - } - } -} - - -// Take a 24 bit RGB colour and return it in the -// correct format for the current primary surface -// We will assume that the primary is NOT in a -// palettised mode, since the mapping if we have -// already set a palette is undefined. - -int GetSingleColourForPrimary(int Colour) - -{ - unsigned long m; - int s; - int red_shift, red_scale; - int green_shift, green_scale; - int blue_shift, blue_scale; - int RetVal = 0; - int r, g ,b; - - // Fail for palettised modes - if ((VideoModeTypeScreen == VideoModeType_8) - || (VideoModeTypeScreen == VideoModeType_8T)) - return -1; - - // Extra! check for palettised modes - if ((DisplayPixelFormat.dwFlags & DDPF_PALETTEINDEXED8) - || (DisplayPixelFormat.dwFlags & DDPF_PALETTEINDEXED4)) - return -1; - - // Determine r, g, b masks and scale - for (s = 0, m = DisplayPixelFormat.dwRBitMask; - !(m & 1); s++, m >>= 1); - - red_shift = s; - red_scale = 255 / (DisplayPixelFormat.dwRBitMask >> s); - - for (s = 0, m = DisplayPixelFormat.dwGBitMask; - !(m & 1); s++, m >>= 1); - - green_shift = s; - green_scale = 255 / (DisplayPixelFormat.dwGBitMask >> s); - - for (s = 0, m = DisplayPixelFormat.dwBBitMask; - !(m & 1); s++, m >>= 1); - - blue_shift = s; - blue_scale = 255 / (DisplayPixelFormat.dwBBitMask >> s); - - // Extract r,g,b components from input colour - r = (Colour >> 16) & 0xff; - g = (Colour >> 8) & 0xff; - b = Colour & 0xff; - - // Scale and shift each value - r /= red_scale; - g /= green_scale; - b /= blue_scale; - RetVal = (r << red_shift) | (g << green_shift) - | (b << blue_shift); - - return(RetVal); -} - -#if triplebuffer -// NOTE TRIPLE BUFFERING SUPPORT HAS BEEN -->REMOVED<-- -// ON THE GROUNDS THAT THE SECOND BACK BUFFER TAKES UP -// EXTRA MEMORY AND IT'S NOT GOING TO GO ANY FASTER -// ANYWAY UNLESS YOUR VIDEO CARD FLIPS IN HARDWARE AND -// TAKES MORE THAN ABOUT 10 MILLISECONDS TO DO IT. -// WHICH I CERTAINLY HOPE ISN'T TRUE... - -// NOTE ALSO: THIS FUNCTION DOESN'T WORK! (DESPITE -// THE DOCUMENTATION). YOU NEED TO USE GETATTACHEDSURFACE -// TWICE INSTEAD. SEE ARSEWIPE CODE FOR A WORKING -// EXAMPLE (NOTE THAT TRIPLE BUFFERING CAN BE OPTIMAL -// IN ARSEWIPE BECAUSE IT'S 2D, AND THE TIME TO THE NEXT -// SURFACE LOCK IN A RENDERING CYCLE CAN THUS BE MUCH LESS -// THAN IN 3DC). - -// defines this function as FAR PASCAL, i.e. -// using Windows standard parameter passing convention, -// which will be neecessary for all callbacks - -HRESULT WINAPI InitTripleBuffers(LPDIRECTDRAWSURFACE lpdd, - LPDDSURFACEDESC lpsd, LPVOID lpc) -{ - if ((lpsd->ddsCaps.dwCaps & DDSCAPS_FLIP) && - (!(lpsd->ddsCaps.dwCaps & DDSCAPS_FRONTBUFFER)) - && (BackBufferEnum < MaxBackBuffers)) - lpDDSBack[BackBufferEnum++] = lpdd; - - if (BackBufferEnum == MaxBackBuffers) - return(DDENUMRET_CANCEL); - else - return(DDENUMRET_OK); -} -#endif - - - -/* new versions of these functions, provided by neil */ -static GDIObjectReferenceCount = 0; -BOOL GetGDISurface(void) -{ - HRESULT hr = DD_OK; - - if(WindowMode == WindowModeSubWindow) return TRUE; - - if(!lpDDGDI) - { - hr = lpDD->GetGDISurface(&lpDDGDI); - if(hr != DD_OK) - { - ReleaseDirect3D(); - exit(hr); - } - } - - // flip the buffer to the GDI surface - hr = lpDD->FlipToGDISurface(); - if(hr != DD_OK) - { - ReleaseDirect3D(); - exit(hr); - } - - GDIObjectReferenceCount++; - - // release windows palette entries - - // whenever we flip to the GDI surface, - // we will want the full palette. - - if (VideoModeColourDepth == 8) - { - HDC hdc = GetDC(NULL); - SetSystemPaletteUse(hdc, SYSPAL_STATIC); - ReleaseDC(NULL, hdc); - } - - return TRUE; -} - - -BOOL LeaveGDISurface(void) -{ - HRESULT hr = DD_OK; - - if(WindowMode == WindowModeSubWindow) return TRUE; - - if (GDIObjectReferenceCount <= 1) - { - ReleaseDDSurface(lpDDGDI); - } - - // recapture system static palette - // entries (see note above in - // GetGDISurface... ) - - if (VideoModeColourDepth == 8) - { - HDC hdc = GetDC(NULL); - SetSystemPaletteUse(hdc, SYSPAL_NOSTATIC); - ReleaseDC(NULL, hdc); - } - - return TRUE; -} - -/************ for extern "C"*****************/ - -}; - diff --git a/3dc/win95/DEBUGLOG.CPP b/3dc/win95/DEBUGLOG.CPP deleted file mode 100644 index 2e76b9f..0000000 --- a/3dc/win95/DEBUGLOG.CPP +++ /dev/null @@ -1,122 +0,0 @@ -#include <string.h> -#include <stdlib.h> -#include <windows.h> -#include "debuglog.hpp" - -LogFile::LogFile(char const * const _fname) : fname(0) , ever_written(0) -{ - FILE * fp = fopen(_fname,"w"); - if (fp) - { - fclose(fp); - fname = new char[strlen(_fname)+1]; - strcpy(fname,_fname); - return; - } - char const * path = getenv("TEMP"); - if (!path) path = getenv("TMP"); - if (!path) return; - fname = new char[strlen(path)+1+strlen(_fname)+1]; - strcpy(fname,path); - strncat(fname,"\\",1); - strcat(fname,_fname); - fp = fopen(fname,"w"); - if (fp) - fclose(fp); - else - { - delete[] fname; - fname = 0; - } -} - -LogFile::~LogFile() -{ - if (unwritten.size()) - { - FILE * fp = fopen(fname,"a"); - for (int attempt=0; !fp && attempt<10; ++attempt) - { - Sleep(100); - fp = fopen(fname,"a"); - } - if (fp) - { - FlushOut(fp); - fclose(fp); - } - } - if (fname) delete[] fname; -} - -LogFile & LogFile::operator = (LogFile const & l) -{ - if (&l != this) - { - if (fname) delete[] fname; - if (l.fname) - { - fname = new char[strlen(l.fname)+1]; - strcpy(fname,l.fname); - } - else - fname = 0; - - unwritten = l.unwritten; - ever_written = l.ever_written; - } - return *this; -} - -LogFile::LogFile(LogFile const & l) -: unwritten(l.unwritten) -, ever_written(l.ever_written) -{ - if (l.fname) - { - fname = new char[strlen(l.fname)+1]; - strcpy(fname,l.fname); - } - else - fname = 0; -} - -void LogFile::FlushOut(FILE * fp) -{ - while (unwritten.size()) - { - char * str = unwritten.first_entry(); - unwritten.delete_first_entry(); - fputs(str,fp); - delete[] str; - } -} - -int vlfprintf(LOGFILE * lfp, char const * format, va_list args ) -{ - return lfp->vlprintf(format,args); -} - -int lfprintf(LOGFILE * lfp, char const * format, ... ) -{ - va_list ap; - va_start(ap, format); - int rv = lfp->vlprintf(format,ap); - va_end(ap); - return rv; -} - -int lfputs(LOGFILE * lfp, char const * str) -{ - return lfp->lputs(str); -} - -LOGFILE * lfopen(char const * fname) -{ - return new LogFile(fname); -} - -void lfclose(LOGFILE * lfp) -{ - delete lfp; -} diff --git a/3dc/win95/DEBUGLOG.H b/3dc/win95/DEBUGLOG.H deleted file mode 100644 index 2079406..0000000 --- a/3dc/win95/DEBUGLOG.H +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef _included_debuglog_h_ -#define _included_debuglog_h_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include <stdarg.h> - -typedef struct LogFile LOGFILE; - -int vlfprintf(LOGFILE * lfp, char const * format, va_list args ); - -int lfprintf(LOGFILE * lfp, char const * format, ... ); - -int lfputs(LOGFILE * lfp, char const * str); - -LOGFILE * lfopen(char const * fname); - -void lfclose(LOGFILE * lfp); - -#ifdef __cplusplus -} -#endif - -#endif /* ! _included_debuglog_h_ */ diff --git a/3dc/win95/DEBUGLOG.HPP b/3dc/win95/DEBUGLOG.HPP deleted file mode 100644 index 5a0087e..0000000 --- a/3dc/win95/DEBUGLOG.HPP +++ /dev/null @@ -1,179 +0,0 @@ -#ifndef _included_debuglog_hpp_ -#define _included_debuglog_hpp_ - -#include <stdio.h> -#include "debuglog.h" -#include "list_tem.hpp" - -/* Changed 27/1/98 by DHM: - ----------------------- - - Made LogFile derived from R_DumpContext rather than being a base class. - - This is in order to give a clean interface for debug dumps to e.g. the - screen, with the same interface as to a log file. This base class will - perform an analagous role to the class CDumpContext in the Microsoft - Foundation Class library. - - The virtual functions dputs(), dprintf() and vdprintf() will eventually replace - lputs(), lprintf() and vlprintf(). - - For the moment I've copied and pasted the implementations of both. I would prefer - in the short term to make one call the other, but this isn't easy with variable - arguments. In the long term I want to eliminate the l* functions (lputs() etc) - but can't because of heritage code (and heritage libraries). -*/ - - #ifndef _dcontext_hpp - #include "dcontext.hpp" - #endif - -struct LogFile : public R_DumpContext -{ -private: - char * fname; - List<char *> unwritten; - int ever_written; - void FlushOut(FILE * fp); - -public: - LogFile(char const * const _fname); - virtual ~LogFile(); - LogFile & operator = (LogFile const & l); - LogFile(LogFile const & l); - - // {{{ Virtual dump implementations: - inline int dputs(char const * const buf) - { - if (!fname) return EOF; - FILE * fp = fopen(fname,"a"); - if (!fp) - { - if (!ever_written) return EOF; - char * newtxt = new char [strlen(buf)+1]; - strcpy(newtxt,buf); - unwritten.add_entry_end(newtxt); - return 0; - } - if (unwritten.size()) FlushOut(fp); - ever_written = 1; - int rv = fputs(buf,fp); - fclose(fp); - return rv; - } - - inline int dprintf(char const * format, ... ) - { - if (!fname) return -1; - FILE * fp = fopen(fname,"a"); - if (!fp && !ever_written) return -1; - va_list ap; - va_start(ap, format); - int rv; - if (fp) - { - if (unwritten.size()) FlushOut(fp); - rv = vfprintf(fp,format,ap); - ever_written = 1; - } - else - { - char buf[4096]; - rv = vsprintf(buf,format,ap); - char * newtxt = new char [strlen(buf)+1]; - strcpy(newtxt,buf); - unwritten.add_entry_end(newtxt); - } - va_end(ap); - if (fp) fclose(fp); - return rv; - } - - inline int vdprintf(char const * format, va_list ap) - { - if (!fname) return -1; - FILE * fp = fopen(fname,"a"); - if (!fp && !ever_written) return -1; - - int rv; - if (fp) - { - if (unwritten.size()) FlushOut(fp); - rv = vfprintf(fp,format,ap); - ever_written = 1; - fclose(fp); - } - else - { - char buf[4096]; - rv = vsprintf(buf,format,ap); - char * newtxt = new char [strlen(buf)+1]; - strcpy(newtxt,buf); - unwritten.add_entry_end(newtxt); - } - return rv; - } - // }}} - - // {{{ Deprecated logging functions: - inline int lputs(char const * const buf) - { - return dputs(buf); - } - - inline int lprintf(char const * format, ... ) - { - if (!fname) return -1; - FILE * fp = fopen(fname,"a"); - if (!fp && !ever_written) return -1; - va_list ap; - va_start(ap, format); - int rv; - if (fp) - { - if (unwritten.size()) FlushOut(fp); - rv = vfprintf(fp,format,ap); - ever_written = 1; - } - else - { - char buf[4096]; - rv = vsprintf(buf,format,ap); - char * newtxt = new char [strlen(buf)+1]; - strcpy(newtxt,buf); - unwritten.add_entry_end(newtxt); - } - va_end(ap); - if (fp) fclose(fp); - return rv; - } - - inline int vlprintf(char const * format, va_list ap) - { - if (!fname) return -1; - FILE * fp = fopen(fname,"a"); - if (!fp && !ever_written) return -1; - - int rv; - if (fp) - { - if (unwritten.size()) FlushOut(fp); - rv = vfprintf(fp,format,ap); - ever_written = 1; - fclose(fp); - } - else - { - char buf[4096]; - rv = vsprintf(buf,format,ap); - char * newtxt = new char [strlen(buf)+1]; - strcpy(newtxt,buf); - unwritten.add_entry_end(newtxt); - } - return rv; - } - // }}} - -}; - -#endif // ! _included_debuglog_hpp_ diff --git a/3dc/win95/DXLOG.C b/3dc/win95/DXLOG.C deleted file mode 100644 index d95bd51..0000000 --- a/3dc/win95/DXLOG.C +++ /dev/null @@ -1,389 +0,0 @@ -#include "3dc.h" - -#if debug - -#include "ourasert.h" -#include "dxlog.h" -#include "debuglog.h" - -/* - * D3DAppErrorToString - */ -static char* -D3DAppErrorToString(HRESULT error) -{ - switch(error) { - case DD_OK: - return "No error.\0"; - case DDERR_ALREADYINITIALIZED: - return "This object is already initialized.\0"; - case DDERR_BLTFASTCANTCLIP: - return "Return if a clipper object is attached to the source surface passed into a BltFast call.\0"; - case DDERR_CANNOTATTACHSURFACE: - return "This surface can not be attached to the requested surface.\0"; - case DDERR_CANNOTDETACHSURFACE: - return "This surface can not be detached from the requested surface.\0"; - case DDERR_CANTCREATEDC: - return "Windows can not create any more DCs.\0"; - case DDERR_CANTDUPLICATE: - return "Can't duplicate primary & 3D surfaces, or surfaces that are implicitly created.\0"; - case DDERR_CLIPPERISUSINGHWND: - return "An attempt was made to set a cliplist for a clipper object that is already monitoring an hwnd.\0"; - case DDERR_COLORKEYNOTSET: - return "No src color key specified for this operation.\0"; - case DDERR_CURRENTLYNOTAVAIL: - return "Support is currently not available.\0"; - case DDERR_DIRECTDRAWALREADYCREATED: - return "A DirectDraw object representing this driver has already been created for this process.\0"; - case DDERR_EXCEPTION: - return "An exception was encountered while performing the requested operation.\0"; - case DDERR_EXCLUSIVEMODEALREADYSET: - return "An attempt was made to set the cooperative level when it was already set to exclusive.\0"; - case DDERR_GENERIC: - return "Generic failure.\0"; - case DDERR_HEIGHTALIGN: - return "Height of rectangle provided is not a multiple of reqd alignment.\0"; - case DDERR_HWNDALREADYSET: - return "The CooperativeLevel HWND has already been set. It can not be reset while the process has surfaces or palettes created.\0"; - case DDERR_HWNDSUBCLASSED: - return "HWND used by DirectDraw CooperativeLevel has been subclassed, this prevents DirectDraw from restoring state.\0"; - case DDERR_IMPLICITLYCREATED: - return "This surface can not be restored because it is an implicitly created surface.\0"; - case DDERR_INCOMPATIBLEPRIMARY: - return "Unable to match primary surface creation request with existing primary surface.\0"; - case DDERR_INVALIDCAPS: - return "One or more of the caps bits passed to the callback are incorrect.\0"; - case DDERR_INVALIDCLIPLIST: - return "DirectDraw does not support the provided cliplist.\0"; - case DDERR_INVALIDDIRECTDRAWGUID: - return "The GUID passed to DirectDrawCreate is not a valid DirectDraw driver identifier.\0"; - case DDERR_INVALIDMODE: - return "DirectDraw does not support the requested mode.\0"; - case DDERR_INVALIDOBJECT: - return "DirectDraw received a pointer that was an invalid DIRECTDRAW object.\0"; - case DDERR_INVALIDPARAMS: - return "One or more of the parameters passed to the function are incorrect.\0"; - case DDERR_INVALIDPIXELFORMAT: - return "The pixel format was invalid as specified.\0"; - case DDERR_INVALIDPOSITION: - return "Returned when the position of the overlay on the destination is no longer legal for that destination.\0"; - case DDERR_INVALIDRECT: - return "Rectangle provided was invalid.\0"; - case DDERR_LOCKEDSURFACES: - return "Operation could not be carried out because one or more surfaces are locked.\0"; - case DDERR_NO3D: - return "There is no 3D present.\0"; - case DDERR_NOALPHAHW: - return "Operation could not be carried out because there is no alpha accleration hardware present or available.\0"; - case DDERR_NOBLTHW: - return "No blitter hardware present.\0"; - case DDERR_NOCLIPLIST: - return "No cliplist available.\0"; - case DDERR_NOCLIPPERATTACHED: - return "No clipper object attached to surface object.\0"; - case DDERR_NOCOLORCONVHW: - return "Operation could not be carried out because there is no color conversion hardware present or available.\0"; - case DDERR_NOCOLORKEY: - return "Surface doesn't currently have a color key\0"; - case DDERR_NOCOLORKEYHW: - return "Operation could not be carried out because there is no hardware support of the destination color key.\0"; - case DDERR_NOCOOPERATIVELEVELSET: - return "Create function called without DirectDraw object method SetCooperativeLevel being called.\0"; - case DDERR_NODC: - return "No DC was ever created for this surface.\0"; - case DDERR_NODDROPSHW: - return "No DirectDraw ROP hardware.\0"; - case DDERR_NODIRECTDRAWHW: - return "A hardware-only DirectDraw object creation was attempted but the driver did not support any hardware.\0"; - case DDERR_NOEMULATION: - return "Software emulation not available.\0"; - case DDERR_NOEXCLUSIVEMODE: - return "Operation requires the application to have exclusive mode but the application does not have exclusive mode.\0"; - case DDERR_NOFLIPHW: - return "Flipping visible surfaces is not supported.\0"; - case DDERR_NOGDI: - return "There is no GDI present.\0"; - case DDERR_NOHWND: - return "Clipper notification requires an HWND or no HWND has previously been set as the CooperativeLevel HWND.\0"; - case DDERR_NOMIRRORHW: - return "Operation could not be carried out because there is no hardware present or available.\0"; - case DDERR_NOOVERLAYDEST: - return "Returned when GetOverlayPosition is called on an overlay that UpdateOverlay has never been called on to establish a destination.\0"; - case DDERR_NOOVERLAYHW: - return "Operation could not be carried out because there is no overlay hardware present or available.\0"; - case DDERR_NOPALETTEATTACHED: - return "No palette object attached to this surface.\0"; - case DDERR_NOPALETTEHW: - return "No hardware support for 16 or 256 color palettes.\0"; - case DDERR_NORASTEROPHW: - return "Operation could not be carried out because there is no appropriate raster op hardware present or available.\0"; - case DDERR_NOROTATIONHW: - return "Operation could not be carried out because there is no rotation hardware present or available.\0"; - case DDERR_NOSTRETCHHW: - return "Operation could not be carried out because there is no hardware support for stretching.\0"; - case DDERR_NOT4BITCOLOR: - return "DirectDrawSurface is not in 4 bit color palette and the requested operation requires 4 bit color palette.\0"; - case DDERR_NOT4BITCOLORINDEX: - return "DirectDrawSurface is not in 4 bit color index palette and the requested operation requires 4 bit color index palette.\0"; - case DDERR_NOT8BITCOLOR: - return "DirectDrawSurface is not in 8 bit color mode and the requested operation requires 8 bit color.\0"; - case DDERR_NOTAOVERLAYSURFACE: - return "Returned when an overlay member is called for a non-overlay surface.\0"; - case DDERR_NOTEXTUREHW: - return "Operation could not be carried out because there is no texture mapping hardware present or available.\0"; - case DDERR_NOTFLIPPABLE: - return "An attempt has been made to flip a surface that is not flippable.\0"; - case DDERR_NOTFOUND: - return "Requested item was not found.\0"; - case DDERR_NOTLOCKED: - return "Surface was not locked. An attempt to unlock a surface that was not locked at all, or by this process, has been attempted.\0"; - case DDERR_NOTPALETTIZED: - return "The surface being used is not a palette-based surface.\0"; - case DDERR_NOVSYNCHW: - return "Operation could not be carried out because there is no hardware support for vertical blank synchronized operations.\0"; - case DDERR_NOZBUFFERHW: - return "Operation could not be carried out because there is no hardware support for zbuffer blitting.\0"; - case DDERR_NOZOVERLAYHW: - return "Overlay surfaces could not be z layered based on their BltOrder because the hardware does not support z layering of overlays.\0"; - case DDERR_OUTOFCAPS: - return "The hardware needed for the requested operation has already been allocated.\0"; - case DDERR_OUTOFMEMORY: - return "DirectDraw does not have enough memory to perform the operation.\0"; - case DDERR_OUTOFVIDEOMEMORY: - return "DirectDraw does not have enough video memory to perform the operation.\0"; - case DDERR_OVERLAYCANTCLIP: - return "The hardware does not support clipped overlays.\0"; - case DDERR_OVERLAYCOLORKEYONLYONEACTIVE: - return "Can only have ony color key active at one time for overlays.\0"; - case DDERR_OVERLAYNOTVISIBLE: - return "Returned when GetOverlayPosition is called on a hidden overlay.\0"; - case DDERR_PALETTEBUSY: - return "Access to this palette is being refused because the palette is already locked by another thread.\0"; - case DDERR_PRIMARYSURFACEALREADYEXISTS: - return "This process already has created a primary surface.\0"; - case DDERR_REGIONTOOSMALL: - return "Region passed to Clipper::GetClipList is too small.\0"; - case DDERR_SURFACEALREADYATTACHED: - return "This surface is already attached to the surface it is being attached to.\0"; - case DDERR_SURFACEALREADYDEPENDENT: - return "This surface is already a dependency of the surface it is being made a dependency of.\0"; - case DDERR_SURFACEBUSY: - return "Access to this surface is being refused because the surface is already locked by another thread.\0"; - case DDERR_SURFACEISOBSCURED: - return "Access to surface refused because the surface is obscured.\0"; - case DDERR_SURFACELOST: - return "Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.\0"; - case DDERR_SURFACENOTATTACHED: - return "The requested surface is not attached.\0"; - case DDERR_TOOBIGHEIGHT: - return "Height requested by DirectDraw is too large.\0"; - case DDERR_TOOBIGSIZE: - return "Size requested by DirectDraw is too large, but the individual height and width are OK.\0"; - case DDERR_TOOBIGWIDTH: - return "Width requested by DirectDraw is too large.\0"; - case DDERR_UNSUPPORTED: - return "Action not supported.\0"; - case DDERR_UNSUPPORTEDFORMAT: - return "FOURCC format requested is unsupported by DirectDraw.\0"; - case DDERR_UNSUPPORTEDMASK: - return "Bitmask in the pixel format requested is unsupported by DirectDraw.\0"; - case DDERR_VERTICALBLANKINPROGRESS: - return "Vertical blank is in progress.\0"; - case DDERR_WASSTILLDRAWING: - return "Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.\0"; - case DDERR_WRONGMODE: - return "This surface can not be restored because it was created in a different mode.\0"; - case DDERR_XALIGN: - return "Rectangle provided was not horizontally aligned on required boundary.\0"; - case D3DERR_BADMAJORVERSION: - return "D3DERR_BADMAJORVERSION\0"; - case D3DERR_BADMINORVERSION: - return "D3DERR_BADMINORVERSION\0"; - case D3DERR_EXECUTE_LOCKED: - return "D3DERR_EXECUTE_LOCKED\0"; - case D3DERR_EXECUTE_NOT_LOCKED: - return "D3DERR_EXECUTE_NOT_LOCKED\0"; - case D3DERR_EXECUTE_CREATE_FAILED: - return "D3DERR_EXECUTE_CREATE_FAILED\0"; - case D3DERR_EXECUTE_DESTROY_FAILED: - return "D3DERR_EXECUTE_DESTROY_FAILED\0"; - case D3DERR_EXECUTE_LOCK_FAILED: - return "D3DERR_EXECUTE_LOCK_FAILED\0"; - case D3DERR_EXECUTE_UNLOCK_FAILED: - return "D3DERR_EXECUTE_UNLOCK_FAILED\0"; - case D3DERR_EXECUTE_FAILED: - return "D3DERR_EXECUTE_FAILED\0"; - case D3DERR_EXECUTE_CLIPPED_FAILED: - return "D3DERR_EXECUTE_CLIPPED_FAILED\0"; - case D3DERR_TEXTURE_NO_SUPPORT: - return "D3DERR_TEXTURE_NO_SUPPORT\0"; - case D3DERR_TEXTURE_NOT_LOCKED: - return "D3DERR_TEXTURE_NOT_LOCKED\0"; - case D3DERR_TEXTURE_LOCKED: - return "D3DERR_TEXTURELOCKED\0"; - case D3DERR_TEXTURE_CREATE_FAILED: - return "D3DERR_TEXTURE_CREATE_FAILED\0"; - case D3DERR_TEXTURE_DESTROY_FAILED: - return "D3DERR_TEXTURE_DESTROY_FAILED\0"; - case D3DERR_TEXTURE_LOCK_FAILED: - return "D3DERR_TEXTURE_LOCK_FAILED\0"; - case D3DERR_TEXTURE_UNLOCK_FAILED: - return "D3DERR_TEXTURE_UNLOCK_FAILED\0"; - case D3DERR_TEXTURE_LOAD_FAILED: - return "D3DERR_TEXTURE_LOAD_FAILED\0"; - case D3DERR_MATRIX_CREATE_FAILED: - return "D3DERR_MATRIX_CREATE_FAILED\0"; - case D3DERR_MATRIX_DESTROY_FAILED: - return "D3DERR_MATRIX_DESTROY_FAILED\0"; - case D3DERR_MATRIX_SETDATA_FAILED: - return "D3DERR_MATRIX_SETDATA_FAILED\0"; - case D3DERR_SETVIEWPORTDATA_FAILED: - return "D3DERR_SETVIEWPORTDATA_FAILED\0"; - case D3DERR_MATERIAL_CREATE_FAILED: - return "D3DERR_MATERIAL_CREATE_FAILED\0"; - case D3DERR_MATERIAL_DESTROY_FAILED: - return "D3DERR_MATERIAL_DESTROY_FAILED\0"; - case D3DERR_MATERIAL_SETDATA_FAILED: - return "D3DERR_MATERIAL_SETDATA_FAILED\0"; - case D3DERR_LIGHT_SET_FAILED: - return "D3DERR_LIGHT_SET_FAILED\0"; - case D3DRMERR_BADOBJECT: - return "D3DRMERR_BADOBJECT\0"; - case D3DRMERR_BADTYPE: - return "D3DRMERR_BADTYPE\0"; - case D3DRMERR_BADALLOC: - return "D3DRMERR_BADALLOC\0"; - case D3DRMERR_FACEUSED: - return "D3DRMERR_FACEUSED\0"; - case D3DRMERR_NOTFOUND: - return "D3DRMERR_NOTFOUND\0"; - case D3DRMERR_NOTDONEYET: - return "D3DRMERR_NOTDONEYET\0"; - case D3DRMERR_FILENOTFOUND: - return "The file was not found.\0"; - case D3DRMERR_BADFILE: - return "D3DRMERR_BADFILE\0"; - case D3DRMERR_BADDEVICE: - return "D3DRMERR_BADDEVICE\0"; - case D3DRMERR_BADVALUE: - return "D3DRMERR_BADVALUE\0"; - case D3DRMERR_BADMAJORVERSION: - return "D3DRMERR_BADMAJORVERSION\0"; - case D3DRMERR_BADMINORVERSION: - return "D3DRMERR_BADMINORVERSION\0"; - case D3DRMERR_UNABLETOEXECUTE: - return "D3DRMERR_UNABLETOEXECUTE\0"; - default: - return "Unrecognized error value.\0"; - } -} - -#ifdef __WATCOMC__ - #define LOGFILE_NAME "dx_error.log" -#else - #define LOGFILE_NAME "dx_errorM.log" -#endif - -static LOGFILE * dxlog = 0; -static int closed_once = 0; - -void dx_err_log(HRESULT error, int line, char const * file) -{ - if (DD_OK==error) return; - if (closed_once) return; - - - if (!dxlog) dxlog = lfopen(LOGFILE_NAME); - - lfprintf(dxlog,"Line %d of %s:\n%s\n\n",line,file,D3DAppErrorToString(error)); -} - -void dx_str_log(char const * str, int line, char const * file) -{ - if (closed_once) return; - if (!dxlog) dxlog = lfopen(LOGFILE_NAME); - - lfprintf(dxlog,"Line %d of %s:\n%s\n\n",line,file,str); -} - -void dx_line_log(int line, char const * file) -{ - if (closed_once) return; - if (!dxlog) dxlog = lfopen(LOGFILE_NAME); - - lfprintf(dxlog,"Line %d of %s:\n",line,file); -} - -void dx_strf_log(char const * fmt, ... ) -{ - if (closed_once) return; - if (!dxlog) dxlog = lfopen(LOGFILE_NAME); - { - va_list ap; - va_start(ap, fmt); - vlfprintf(dxlog,fmt,ap); - va_end(ap); - } - lfputs(dxlog,"\n\n"); -} - -#undef exit -int GlobalAssertFired(char * Filename, int LineNum,char * Condition) -{ - extern void exit_break_point_fucntion (); - exit_break_point_fucntion(); - if (closed_once) return 0; - if (!dxlog) dxlog = lfopen(LOGFILE_NAME); - - lfprintf(dxlog,"Line %d of %s:\nGAF: %s\n",LineNum,Filename,Condition); - lfclose(dxlog); - closed_once = 1; - textprint("Line %d of %s:\nGAF: %s\n",LineNum,Filename,Condition); - WaitForReturn(); - - ExitSystem(); - exit(0xffff); -} - -int LocalAssertFired(char * Filename, int LineNum,char * Condition) -{ - extern void exit_break_point_fucntion (); - exit_break_point_fucntion(); - if (closed_once) return 0; - if (!dxlog) dxlog = lfopen(LOGFILE_NAME); - - lfprintf(dxlog,"Line %d of %s:\nLAF: %s\n",LineNum,Filename,Condition); - lfclose(dxlog); - closed_once = 1; - textprint("Line %d of %s:\nLAF: %s\n",LineNum,Filename,Condition); - WaitForReturn(); - - ExitSystem(); - exit(0xfffe); -} - - -void DXLOGHandleCompilerWarningMessage(void) -{ - int temp; - - temp = D3DRMMAP_PERSPCORRECT; - temp = D3DRMMAP_WRAPU; - temp = D3DRMMAP_WRAPV; - temp = D3DRMGROUP_ALLGROUPS; -} - -void ExitFired(char* Filename, int LineNum, int ExitCode) -{ - extern void exit_break_point_fucntion (); - exit_break_point_fucntion(); - if (closed_once) return ; - if (!dxlog) dxlog = lfopen(LOGFILE_NAME); - - lfprintf(dxlog,"Line %d of %s:\nExit: %x\n",LineNum,Filename,ExitCode); - lfclose(dxlog); - closed_once = 1; - - exit(ExitCode); -} -#endif diff --git a/3dc/win95/DXLOG.H b/3dc/win95/DXLOG.H deleted file mode 100644 index d67b57c..0000000 --- a/3dc/win95/DXLOG.H +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef _included_dxlog_h_ -#define _included_dxlog_h_ - -#include "system.h" -#include "ddraw.h" -#include "d3d.h" -#include "d3drm.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if debug - -void dx_err_log(HRESULT error, int line, char const * file); -void dx_str_log(char const * str, int line, char const * file); -void dx_line_log(int line, char const * file); -void dx_strf_log(char const * fmt, ...); - -#define LOGDXERR(error) dx_err_log(error,__LINE__,__FILE__) -#define LOGDXSTR(str) dx_str_log(str,__LINE__,__FILE__) -#define LOGDXFMT(args) (dx_line_log(__LINE__,__FILE__),dx_strf_log args) - -#else - -#define LOGDXERR(error) (void)0 -#define LOGDXSTR(str) (void)0 -#define LOGDXFMT(args) (void)0 - -#endif - - -#ifdef __cplusplus -} -#endif - -#endif /* ! _included_dxlog_h_ */ diff --git a/3dc/win95/Di_func.cpp b/3dc/win95/Di_func.cpp deleted file mode 100644 index c29b4c1..0000000 --- a/3dc/win95/Di_func.cpp +++ /dev/null @@ -1,1344 +0,0 @@ -// Interface functions (written in C++) for -// Direct3D immediate mode system - -// Must link to C code in main engine system - -extern "C" { - -// Note: INITGUID has NOT been defined here, -// since the definition in d3_func.cpp is amply -// sufficient. - -#include "3dc.h" -#include "module.h" -#include "inline.h" -#include "stratdef.h" -#include "gamedef.h" -#include "gameplat.h" -#include "usr_io.h" -extern "C++"{ -#include "iofocus.h" -}; - -#include "showcmds.h" - -// DirectInput key down value -#define DikOn 0x80 - -// Internal DirectInput driver -// buffer Size for direct mouse read -#define DMouse_BufferSize 128 - -// Maximum number of buffered events retrievable -// from a mouse data acquisition -#define DMouse_RetrieveSize 128 - -/* - These are (hopefully) temporary #defines, - introduced as a hack because the curious - FIELD_OFFSET macros in the dinput.h header - don't appear to compile, at least in Watcom 10.6. - They will obviously have to be kept up to date - with changes in the DIMOUSESTATE structure manually. -*/ - -#define DIMouseXOffset 0 - -#define DIMouseYOffset 4 -#define DIMouseZOffset 8 - -#define DIMouseButton0Offset 12 - -#define DIMouseButton1Offset 13 - -#define DIMouseButton2Offset 14 - -#define DIMouseButton3Offset 15 - - -/* - Globals -*/ - - -static LPDIRECTINPUT lpdi; // DirectInput interface -static LPDIRECTINPUTDEVICE lpdiKeyboard; // keyboard device interface -static LPDIRECTINPUTDEVICE lpdiMouse; // mouse device interface -static BOOL DIKeyboardOkay; // Is the keyboard acquired? - -static IDirectInputDevice* g_pJoystick = NULL; -static IDirectInputDevice2* g_pJoystickDevice2 = NULL; // needed to poll joystick - - static char bGravePressed = No; - // added 14/1/98 by DHM as a temporary hack to debounce the GRAVE key - -/* - Externs for input communication -*/ - -extern HINSTANCE hInst; -extern HWND hWndMain; - -int GotMouse; -unsigned int MouseButton; -int MouseVelX; -int MouseVelY; -int MouseVelZ; -int MouseX; -int MouseY; -int MouseZ; - -extern unsigned char KeyboardInput[]; -extern unsigned char GotAnyKey; -static unsigned char LastGotAnyKey; -unsigned char DebouncedGotAnyKey; - -int GotJoystick; -JOYCAPS JoystickCaps; -JOYINFOEX JoystickData; -int JoystickEnabled; - -DIJOYSTATE JoystickState; // DirectInput joystick state - - -/* - 8/4/98 DHM: A new array, analagous to KeyboardInput, except it's debounced -*/ -extern "C" -{ - unsigned char DebouncedKeyboardInput[MAX_NUMBER_OF_INPUT_KEYS]; -} - -// Implementation of the debounced KeyboardInput -// There's probably a more efficient way of getting it direct from DirectInput -// but it's getting late and I can't face reading any more Microsoft documentation... -static unsigned char LastFramesKeyboardInput[MAX_NUMBER_OF_INPUT_KEYS]; - - -extern int NormalFrameTime; - -static char IngameKeyboardInput[256]; -extern IngameKeyboardInput_KeyDown(unsigned char key); -extern IngameKeyboardInput_KeyUp(unsigned char key); -extern IngameKeyboardInput_ClearBuffer(void); - -/* - - Create DirectInput via CoCreateInstance - -*/ - - -BOOL InitialiseDirectInput(void) - -{ - // try to create di object - if (DirectInputCreate(hInst, DIRECTINPUT_VERSION, &lpdi, NULL) != DI_OK) - { - #if debug - ReleaseDirect3D(); - exit(0x4111); - #else - return FALSE; - #endif - } - - return TRUE; -} - -/* - - Release DirectInput object - -*/ - - -void ReleaseDirectInput(void) - -{ - if (lpdi!= NULL) - { - lpdi->Release(); - lpdi = NULL; - } -} - - - - -// see comments below - -#define UseForegroundKeyboard No - -GUID guid = GUID_SysKeyboard; -BOOL InitialiseDirectKeyboard() - -{ - HRESULT hRes; - - // try to create keyboard device - if (lpdi->CreateDevice(guid, &lpdiKeyboard, NULL) !=DI_OK) - { - #if debug - ReleaseDirect3D(); - exit(0x4112); - #else - return FALSE; - #endif - } - - // Tell DirectInput that we want to receive data in keyboard format - if (lpdiKeyboard->SetDataFormat(&c_dfDIKeyboard) != DI_OK) - { - #if debug - ReleaseDirect3D(); - exit(0x4113); - #else - return FALSE; - #endif - } - - // set cooperative level - // this level is the most likely to work across - // multiple hardware targets - // (i.e. this is probably best for a production - // release) - #if UseForegroundKeyboard - if (lpdiKeyboard->SetCooperativeLevel(hWndMain, - DISCL_NONEXCLUSIVE | DISCL_FOREGROUND) != DI_OK) - #else - // this level makes alt-tabbing multiple instances in - // SunWindow mode possible without receiving lots - // of false inputs - if (lpdiKeyboard->SetCooperativeLevel(hWndMain, - DISCL_NONEXCLUSIVE | DISCL_BACKGROUND) != DI_OK) - #endif - { - #if debug - ReleaseDirect3D(); - exit(0x4114); - #else - return FALSE; - #endif - } - - // try to acquire the keyboard - hRes = lpdiKeyboard->Acquire(); - if (hRes == DI_OK) - { - // keyboard was acquired - DIKeyboardOkay = TRUE; - } - else - { - // keyboard was NOT acquired - DIKeyboardOkay = FALSE; - } - - // if we get here, all objects were created successfully - return TRUE; -} - - - -/* - - Use DirectInput to read keyboard - - PS: I know this function involves an - apparently unnecessary layer of translation - between one keyboard array and another one. - This is to allow people to swap from a windows - procedure keyboard handler to a DirectInput one - without having to change their IDemand functions. - - I can't think of a faster way to do the translation - below, but given that it only runs once per frame - it shouldn't be too bad. BUT NOTE THAT IT DOES - ONLY RUN ONCE PER FRAME (FROM READUSERINPUT) AND - SO YOU MUST HAVE A DECENT FRAME RATE IF KEYS ARE NOT - TO BE MISSED. - - NOTE ALSO THAT IF YOU ARE USING THIS SYSTEM YOU CAN - ACCESS THE KEYBOARD ARRAY IN A TIGHT LOOP WHILE CALLING - READUSERINPUT BUT -->NOT<-- CHECKWINDOWSMESSAGES (AS REQUIRED - FOR THE WINPROC HANDLER). BUT CHECKFORWINDOWSMESSAGES WON'T DO - ANY HARM. -*/ - -void DirectReadKeyboard(void) -{ - // Local array for map of all 256 characters on - // keyboard - BYTE DiKeybd[256]; - HRESULT hRes; - - // Get keyboard state - hRes = lpdiKeyboard->GetDeviceState(sizeof(DiKeybd), DiKeybd); - if (hRes != DI_OK) - { - if (hRes == DIERR_INPUTLOST) - { - // keyboard control lost; try to reacquire - DIKeyboardOkay = FALSE; - hRes = lpdiKeyboard->Acquire(); - if (hRes == DI_OK) - DIKeyboardOkay = TRUE; - } - } - - // Check for error values on routine exit - if (hRes != DI_OK) - { - // failed to read the keyboard - #if debug - ReleaseDirect3D(); - exit(0x999774); - #else - return; - #endif - } - - // Take a copy of last frame's inputs: - memcpy((void*)LastFramesKeyboardInput, (void*)KeyboardInput, MAX_NUMBER_OF_INPUT_KEYS); - LastGotAnyKey=GotAnyKey; - - // Zero current inputs (i.e. set all keys to FALSE, - // or not pressed) - memset((void*)KeyboardInput, FALSE, MAX_NUMBER_OF_INPUT_KEYS); - GotAnyKey = FALSE; - - #if 1 - { - int c; - - for (c='a'; c<='z'; c++) - { - if (IngameKeyboardInput[c]) - { - KeyboardInput[KEY_A + c - 'a'] = TRUE; - GotAnyKey = TRUE; - } - } - if (IngameKeyboardInput[246]) - { - KeyboardInput[KEY_O_UMLAUT] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[228]) - { - KeyboardInput[KEY_A_UMLAUT] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[252]) - { - KeyboardInput[KEY_U_UMLAUT] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[223]) - { - KeyboardInput[KEY_BETA] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['+']) - { - KeyboardInput[KEY_PLUS] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['#']) - { - KeyboardInput[KEY_HASH] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[161]) - { - KeyboardInput[KEY_UPSIDEDOWNEXCLAMATION] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[231]) - { - KeyboardInput[KEY_C_CEDILLA] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[241]) - { - KeyboardInput[KEY_N_TILDE] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[')']) - { - KeyboardInput[KEY_RIGHTBRACKET] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['*']) - { - KeyboardInput[KEY_ASTERISK] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['$']) - { - KeyboardInput[KEY_DOLLAR] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[249]) - { - KeyboardInput[KEY_U_GRAVE] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['!']) - { - KeyboardInput[KEY_EXCLAMATION] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[':']) - { - KeyboardInput[KEY_COLON] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[96]) - { - KeyboardInput[KEY_DIACRITIC_GRAVE] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[180]) - { - KeyboardInput[KEY_DIACRITIC_ACUTE] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[94]) - { - KeyboardInput[KEY_DIACRITIC_CARET] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[168]) - { - KeyboardInput[KEY_DIACRITIC_UMLAUT] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['<']) - { - KeyboardInput[KEY_LESSTHAN] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[176]) - { - KeyboardInput[KEY_ORDINAL] = TRUE; - GotAnyKey = TRUE; - } - - - if (IngameKeyboardInput['[']) - { - KeyboardInput[KEY_LBRACKET] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[']']) - { - KeyboardInput[KEY_RBRACKET] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[';']) - { - KeyboardInput[KEY_SEMICOLON] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['\'']) - { - KeyboardInput[KEY_APOSTROPHE] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['\\']) - { - KeyboardInput[KEY_BACKSLASH] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['/']) - { - KeyboardInput[KEY_SLASH] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['-']) - { - KeyboardInput[KEY_MINUS] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['=']) - { - KeyboardInput[KEY_EQUALS] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput[',']) - { - KeyboardInput[KEY_COMMA] = TRUE; - GotAnyKey = TRUE; - } - if (IngameKeyboardInput['.']) - { - KeyboardInput[KEY_FSTOP] = TRUE; - GotAnyKey = TRUE; - } - - } - - #endif - - // Check and set keyboard array - // (test checks only for the moment) - if (DiKeybd[DIK_LEFT] & DikOn) - { - KeyboardInput[KEY_LEFT] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_RIGHT] & DikOn) - { - KeyboardInput[KEY_RIGHT] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_UP] & DikOn) - { - KeyboardInput[KEY_UP] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_DOWN] & DikOn) - { - KeyboardInput[KEY_DOWN] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_ESCAPE] & DikOn) - { - KeyboardInput[KEY_ESCAPE] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_RETURN] & DikOn) - { - KeyboardInput[KEY_CR] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_TAB] & DikOn) - { - KeyboardInput[KEY_TAB] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F1] & DikOn) - { - KeyboardInput[KEY_F1] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F2] & DikOn) - { - KeyboardInput[KEY_F2] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F3] & DikOn) - { - KeyboardInput[KEY_F3] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F4] & DikOn) - { - KeyboardInput[KEY_F4] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F5] & DikOn) - { - KeyboardInput[KEY_F5] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F6] & DikOn) - { - KeyboardInput[KEY_F6] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F7] & DikOn) - { - KeyboardInput[KEY_F7] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F8] & DikOn) - { - KeyboardInput[KEY_F8] = TRUE; -/* KJL 14:51:38 21/04/98 - F8 does screen shots, and so this is a hack -to make F8 not count in a 'press any key' situation */ -// GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F9] & DikOn) - { - KeyboardInput[KEY_F9] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F10] & DikOn) - { - KeyboardInput[KEY_F10] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F11] & DikOn) - { - KeyboardInput[KEY_F11] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_F12] & DikOn) - { - KeyboardInput[KEY_F12] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_INSERT] & DikOn) - { - KeyboardInput[KEY_INS] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_DELETE] & DikOn) - { - KeyboardInput[KEY_DEL] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_END] & DikOn) - { - KeyboardInput[KEY_END] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_HOME] & DikOn) - { - KeyboardInput[KEY_HOME] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_PRIOR] & DikOn) - { - KeyboardInput[KEY_PAGEUP] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_NEXT] & DikOn) - { - KeyboardInput[KEY_PAGEDOWN] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_BACK] & DikOn) - { - KeyboardInput[KEY_BACKSPACE] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_SPACE] & DikOn) - { - KeyboardInput[KEY_SPACE] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_LSHIFT] & DikOn) - { - KeyboardInput[KEY_LEFTSHIFT] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_RSHIFT] & DikOn) - { - KeyboardInput[KEY_RIGHTSHIFT] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_LCONTROL] & DikOn) - { - KeyboardInput[KEY_LEFTCTRL] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_RCONTROL] & DikOn) - { - KeyboardInput[KEY_RIGHTCTRL] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_CAPSLOCK] & DikOn) - { - KeyboardInput[KEY_CAPS] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_NUMLOCK] & DikOn) - { - KeyboardInput[KEY_NUMLOCK] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_SCROLL] & DikOn) - { - KeyboardInput[KEY_SCROLLOK] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_LMENU] & DikOn) - { - KeyboardInput[KEY_LEFTALT] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_RMENU] & DikOn) - { - KeyboardInput[KEY_RIGHTALT] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_0] & DikOn) - { - KeyboardInput[KEY_0] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_1] & DikOn) - { - KeyboardInput[KEY_1] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_2] & DikOn) - { - KeyboardInput[KEY_2] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_3] & DikOn) - { - KeyboardInput[KEY_3] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_4] & DikOn) - { - KeyboardInput[KEY_4] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_5] & DikOn) - { - KeyboardInput[KEY_5] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_6] & DikOn) - { - KeyboardInput[KEY_6] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_7] & DikOn) - { - KeyboardInput[KEY_7] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_8] & DikOn) - { - KeyboardInput[KEY_8] = TRUE; - GotAnyKey = TRUE; - } - - if (DiKeybd[DIK_9] & DikOn) - { - KeyboardInput[KEY_9] = TRUE; - GotAnyKey = TRUE; - } - - - /* KJL 16:12:19 05/11/97 - numeric pad follows */ - if (DiKeybd[DIK_NUMPAD7] & DikOn) - { - KeyboardInput[KEY_NUMPAD7] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD8] & DikOn) - { - KeyboardInput[KEY_NUMPAD8] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD9] & DikOn) - { - KeyboardInput[KEY_NUMPAD9] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_SUBTRACT] & DikOn) - { - KeyboardInput[KEY_NUMPADSUB] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD4] & DikOn) - { - KeyboardInput[KEY_NUMPAD4] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD5] & DikOn) - { - KeyboardInput[KEY_NUMPAD5] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD6] & DikOn) - { - KeyboardInput[KEY_NUMPAD6] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_ADD] & DikOn) - { - KeyboardInput[KEY_NUMPADADD] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD1] & DikOn) - { - KeyboardInput[KEY_NUMPAD1] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD2] & DikOn) - { - KeyboardInput[KEY_NUMPAD2] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD3] & DikOn) - { - KeyboardInput[KEY_NUMPAD3] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPAD0] & DikOn) - { - KeyboardInput[KEY_NUMPAD0] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_DECIMAL] & DikOn) - { - KeyboardInput[KEY_NUMPADDEL] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_NUMPADENTER] & DikOn) - { - KeyboardInput[KEY_NUMPADENTER] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_DIVIDE] & DikOn) - { - KeyboardInput[KEY_NUMPADDIVIDE] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_MULTIPLY] & DikOn) - { - KeyboardInput[KEY_NUMPADMULTIPLY] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_CAPITAL] & DikOn) - { - KeyboardInput[KEY_CAPITAL] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_LWIN] & DikOn) - { - KeyboardInput[KEY_LWIN] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_RWIN] & DikOn) - { - KeyboardInput[KEY_RWIN] = TRUE; - GotAnyKey = TRUE; - } - if (DiKeybd[DIK_APPS] & DikOn) - { - KeyboardInput[KEY_APPS] = TRUE; - GotAnyKey = TRUE; - } - - - #if 0 - // Added 14/1/98 by DHM: Process the grave key (known to some as the tilde key) - // Done this way as a bit of a hack to avoid touching PLATFORM.H - // which would force big recompiles - if (DiKeybd[DIK_GRAVE] & DikOn) - { - if ( !bGravePressed ) - { - IOFOCUS_Toggle(); - } - - bGravePressed = Yes; - - GotAnyKey = TRUE; - } - else - { - bGravePressed = No; - } - #else - if (DiKeybd[DIK_GRAVE] & DikOn) - { - KeyboardInput[KEY_GRAVE] = TRUE; - } - #endif - - /* mouse keys */ - if (MouseButton & LeftButton) - { - KeyboardInput[KEY_LMOUSE] = TRUE; - GotAnyKey = TRUE; - } - if (MouseButton & MiddleButton) - { - KeyboardInput[KEY_MMOUSE] = TRUE; - GotAnyKey = TRUE; - } - if (MouseButton & RightButton) - { - KeyboardInput[KEY_RMOUSE] = TRUE; - GotAnyKey = TRUE; - } - - /* mouse wheel - read using windows messages */ - { - extern signed int MouseWheelStatus; - if (MouseWheelStatus>0) - { - KeyboardInput[KEY_MOUSEWHEELUP] = TRUE; - GotAnyKey = TRUE; - } - else if (MouseWheelStatus<0) - { - KeyboardInput[KEY_MOUSEWHEELDOWN] = TRUE; - GotAnyKey = TRUE; - } - } - - - /* joystick buttons */ - if (GotJoystick) - { - unsigned int n,bit; - - for (n=0,bit=1; n<16; n++,bit*=2) - { - if(JoystickData.dwButtons&bit) - { - KeyboardInput[KEY_JOYSTICK_BUTTON_1+n]=TRUE; - GotAnyKey = TRUE; - } - } - - } - - - /* update debounced keys array */ - { - for (int i=0;i<MAX_NUMBER_OF_INPUT_KEYS;i++) - { - DebouncedKeyboardInput[i] = - ( - KeyboardInput[i] && !LastFramesKeyboardInput[i] - ); - } - DebouncedGotAnyKey = GotAnyKey && !LastGotAnyKey; - } - - -} -/* - - Clean up direct keyboard objects - -*/ - -void ReleaseDirectKeyboard(void) -{ - if (DIKeyboardOkay) - { - lpdiKeyboard->Unacquire(); - DIKeyboardOkay = FALSE; - } - - if (lpdiKeyboard != NULL) - { - lpdiKeyboard->Release(); - lpdiKeyboard = NULL; - } -} - - -BOOL InitialiseDirectMouse() - -{ - GUID guid = GUID_SysMouse; - HRESULT hres; - - //MouseButton = 0; - - // Obtain an interface to the system mouse device. - hres = lpdi->CreateDevice(guid, &lpdiMouse, NULL); - if (hres != DI_OK) return FALSE; - - // Set the data format to "mouse format". - hres = lpdiMouse->SetDataFormat(&c_dfDIMouse); - if (hres != DI_OK) return FALSE; - - // Set the cooperativity level. - - #if debug - // This level should allow the debugger to actually work - // not to mention drop 'n' drag in sub-window mode - hres = lpdiMouse->SetCooperativeLevel(hWndMain, - DISCL_NONEXCLUSIVE | DISCL_FOREGROUND); - #else - // this level is the most likely to work across - // multiple mouse drivers - hres = lpdiMouse->SetCooperativeLevel(hWndMain, - DISCL_EXCLUSIVE | DISCL_FOREGROUND); - #endif - if (hres != DI_OK) return FALSE; - - // Set the buffer size for reading the mouse to - // DMouse_BufferSize elements - // mouse-type should be relative by default, so there - // is no need to change axis mode. - DIPROPDWORD dipdw = - { - { - sizeof(DIPROPDWORD), // diph.dwSize - sizeof(DIPROPHEADER), // diph.dwHeaderSize - 0, // diph.dwObj - DIPH_DEVICE, // diph.dwHow - }, - DMouse_BufferSize, // dwData - }; - - hres = lpdiMouse->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph); - - if (hres != DI_OK) return FALSE; - - // try to acquire the mouse - hres = lpdiMouse->Acquire(); - - return TRUE; -} - -void DirectReadMouse(void) -{ - DIDEVICEOBJECTDATA od[DMouse_RetrieveSize]; - DWORD dwElements = DMouse_RetrieveSize; - HRESULT hres; - int OldMouseX, OldMouseY, OldMouseZ; - - GotMouse = No; - MouseVelX = 0; - MouseVelY = 0; - MouseVelZ = 0; - - hres = lpdiMouse->GetDeviceData(sizeof(DIDEVICEOBJECTDATA),&od[0],&dwElements, 0); - - - if (hres == DIERR_INPUTLOST || hres==DIERR_NOTACQUIRED) - { - // We had acquisition, but lost it. Try to reacquire it. - hres = lpdiMouse->Acquire(); - // No data this time - return; - } - - // Unable to read data - if (hres != DI_OK) return; - - // Check for any data being picked up - GotMouse = Yes; - if (dwElements == 0) return; - - // Save mouse x and y for velocity determination - OldMouseX = MouseX; - OldMouseY = MouseY; - OldMouseZ = MouseZ; - - // Process all recovered elements and - // make appropriate modifications to mouse - // status variables. - - int i; - - for (i=0; i<dwElements; i++) - { - // Look at the element to see what happened - - switch (od[i].dwOfs) - { - // DIMOFS_X: Mouse horizontal motion - case DIMouseXOffset: - MouseX += od[i].dwData; - break; - - // DIMOFS_Y: Mouse vertical motion - case DIMouseYOffset: - MouseY += od[i].dwData; - break; - - case DIMouseZOffset: - MouseZ += od[i].dwData; - textprint("z info received %d\n",MouseZ); - break; - - // DIMOFS_BUTTON0: Button 0 pressed or released - case DIMouseButton0Offset: - if (od[i].dwData & DikOn) - // Button pressed - MouseButton |= LeftButton; - else - // Button released - MouseButton &= ~LeftButton; - break; - - // DIMOFS_BUTTON1: Button 1 pressed or released - case DIMouseButton1Offset: - if (od[i].dwData & DikOn) - // Button pressed - MouseButton |= RightButton; - else - // Button released - MouseButton &= ~RightButton; - break; - - case DIMouseButton2Offset: - case DIMouseButton3Offset: - if (od[i].dwData & DikOn) - // Button pressed - MouseButton |= MiddleButton; - else - // Button released - MouseButton &= ~MiddleButton; - break; - - default: - break; - } - } - - MouseVelX = DIV_FIXED(MouseX-OldMouseX,NormalFrameTime); - MouseVelY = DIV_FIXED(MouseY-OldMouseY,NormalFrameTime); - //MouseVelZ = DIV_FIXED(MouseZ-OldMouseZ,NormalFrameTime); - - - #if 0 - textprint("MouseNormalFrameTime %d\n",MouseNormalFrameTime); - textprint("Got Mouse %d\n", GotMouse); - textprint("Vel X %d\n", MouseVelX); - textprint("Vel Y %d\n", MouseVelY); - #endif -} - -void ReleaseDirectMouse(void) - -{ - if (lpdiMouse != NULL) - { - lpdiMouse->Release(); - lpdiMouse = NULL; - } -} - - - -/*KJL**************************************************************** -* * -* JOYSTICK SUPPORT - I've moved all joystick support to here. * -* * -****************************************************************KJL*/ - - -/* KJL 11:32:46 04/30/97 - - - Okay, this has been changed for the sake of AvP. I know that this - isn't in AvP\win95\..., but moving this file probably isn't worth - the trouble. - - This code is designed to read only one joystick. - -*/ - - -/* - Decide which (if any) joysticks - exist, access capabilities, - initialise internal variables. -*/ -#if 1 -void InitJoysticks(void) -{ - JoystickData.dwFlags = (JOY_RETURNALL | JOY_RETURNCENTERED | JOY_USEDEADZONE); - JoystickData.dwSize = sizeof(JoystickData); - - GotJoystick = CheckForJoystick(); -} - -void ReadJoysticks(void) -{ - GotJoystick = ReadJoystick(); -} - -int ReadJoystick(void) -{ - MMRESULT joyreturn; - - if(!JoystickControlMethods.JoystickEnabled) return No; - - joyreturn = joyGetPosEx(JOYSTICKID1,&JoystickData); - - if (joyreturn == JOYERR_NOERROR) return Yes; - - return No; -} - -int CheckForJoystick(void) -{ - MMRESULT joyreturn; - - joyreturn = joyGetDevCaps(JOYSTICKID1, - &JoystickCaps, - sizeof(JOYCAPS)); - - if (joyreturn == JOYERR_NOERROR) return Yes; - - return No; -} -#else -// Eleventh hour rewrite of joystick code, to support PantherXL trackerball. -// Typical. KJL, 99/5/1 -BOOL CALLBACK EnumJoysticksCallback( LPCDIDEVICEINSTANCE pInst, LPVOID lpvContext ); - - -void InitJoysticks(void) -{ - HRESULT hr; - GotJoystick = No; - g_pJoystick = NULL; - - hr = lpdi->EnumDevices(DIDEVTYPE_JOYSTICK, EnumJoysticksCallback, NULL, DIEDFL_ATTACHEDONLY); - if ( FAILED(hr) ) return; - - hr = g_pJoystick->SetDataFormat( &c_dfDIJoystick ); - if ( FAILED(hr) ) return; - - hr = g_pJoystick->SetCooperativeLevel( hWndMain, DISCL_EXCLUSIVE | DISCL_FOREGROUND); - if ( FAILED(hr) ) return; - - GotJoystick = Yes; -} - -void ReadJoysticks(void) -{ - - GotJoystick = No; - - if(!JoystickControlMethods.JoystickEnabled || g_pJoystick==NULL) - { - return; - } - - HRESULT hr = DIERR_INPUTLOST; - - // if input is lost then acquire and keep trying - while ( DIERR_INPUTLOST == hr ) - { - // poll the joystick to read the current state - hr = g_pJoystickDevice2->Poll(); - if ( FAILED(hr) ) return; - - // get the input's device state, and put the state in dims - hr = g_pJoystick->GetDeviceState( sizeof(DIJOYSTATE), &JoystickState ); - - if ( hr == DIERR_INPUTLOST ) - { - // DirectInput is telling us that the input stream has - // been interrupted. We aren't tracking any state - // between polls, so we don't have any special reset - // that needs to be done. We just re-acquire and - // try again. - hr = g_pJoystick->Acquire(); - if ( FAILED(hr) ) return; - } - } - - if ( FAILED(hr) ) return; - - GotJoystick = Yes; - PrintDebuggingText("%d %d\n",JoystickState.rglSlider[0],JoystickState.rglSlider[1]); - -} -//----------------------------------------------------------------------------- -// Function: EnumJoysticksCallback -// -// Description: -// Called once for each enumerated joystick. If we find one, -// create a device interface on it so we can play with it. -// -//----------------------------------------------------------------------------- -BOOL CALLBACK EnumJoysticksCallback( LPCDIDEVICEINSTANCE pInst, - LPVOID lpvContext ) -{ - HRESULT hr; - LPDIRECTINPUTDEVICE pDevice; - - // obtain an interface to the enumerated force feedback joystick. - hr = lpdi->CreateDevice( pInst->guidInstance, &pDevice, NULL ); - - // if it failed, then we can't use this joystick for some - // bizarre reason. (Maybe the user unplugged it while we - // were in the middle of enumerating it.) So continue enumerating - if ( FAILED(hr) ) - return DIENUM_CONTINUE; - - // we successfully created an IDirectInputDevice. So stop looking - // for another one. - g_pJoystick = pDevice; - - // query for IDirectInputDevice2 - we need this to poll the joystick - pDevice->QueryInterface( IID_IDirectInputDevice2, (LPVOID *)&g_pJoystickDevice2 ); - - return DIENUM_STOP; -} -#endif - - -extern IngameKeyboardInput_KeyDown(unsigned char key) -{ - IngameKeyboardInput[key] = 1; -} - -extern IngameKeyboardInput_KeyUp(unsigned char key) -{ - IngameKeyboardInput[key] = 0; -} - -extern IngameKeyboardInput_ClearBuffer(void) -{ - int i; - - for (i=0; i<=255; i++) - { - IngameKeyboardInput[i] = 0; - } -} - -// For extern "C" -}; - - - diff --git a/3dc/win95/DummyObjectChunk.cpp b/3dc/win95/DummyObjectChunk.cpp deleted file mode 100644 index 7fa86c9..0000000 --- a/3dc/win95/DummyObjectChunk.cpp +++ /dev/null @@ -1,181 +0,0 @@ -#include "DummyObjectChunk.hpp" - -#ifdef cencon -#define new my_new -#endif - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(dummyobjectchunk) - - -RIF_IMPLEMENT_DYNCREATE("DUMMYOBJ",Dummy_Object_Chunk) - -CHUNK_WITH_CHILDREN_LOADER("DUMMYOBJ",Dummy_Object_Chunk) -/* -Children for Dummy_Object_Chunk : - -"DUMOBJDT" Dummy_Object_Data_Chunk -"DUMOBJTX" Dummy_Object_Text_Chunk -*/ - - - -Dummy_Object_Chunk::Dummy_Object_Chunk(Chunk_With_Children* parent,const char* _name,ChunkVectorInt& _location,ChunkVectorInt& min ,ChunkVectorInt& max ,ChunkQuat& orient) -:Chunk_With_Children(parent,"DUMMYOBJ") -{ - new Dummy_Object_Data_Chunk(this,_name,_location,min,max,orient); -} - -Dummy_Object_Data_Chunk* Dummy_Object_Chunk::get_data_chunk() -{ - return (Dummy_Object_Data_Chunk*) lookup_single_child("DUMOBJDT"); -} - - -const char* Dummy_Object_Chunk::get_text() -{ - //find the text - Dummy_Object_Text_Chunk* text_chunk = (Dummy_Object_Text_Chunk*) lookup_single_child("DUMOBJTX"); - if(!text_chunk) - { - //no text - return NULL; - } - - return text_chunk->get_text(); -} - -void Dummy_Object_Chunk::set_text(const char* text) -{ - //find the text chunk - Dummy_Object_Text_Chunk* text_chunk = (Dummy_Object_Text_Chunk*) lookup_single_child("DUMOBJTX"); - - if(!text || strlen(text)==0) - { - //delete the text chunk if it exists - delete text_chunk; - } - else - { - if(text_chunk) - { - //alter the existing text - text_chunk->set_text(text); - } - else - { - //create a new text chunk - new Dummy_Object_Text_Chunk(this,text); - } - } -} - - -//////////////////////////////Dummy_Object_Data_Chunk//////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("DUMOBJDT",Dummy_Object_Data_Chunk) - -Dummy_Object_Data_Chunk::Dummy_Object_Data_Chunk(Dummy_Object_Chunk* parent,const char* _name ,ChunkVectorInt& _location,ChunkVectorInt& min ,ChunkVectorInt& max ,ChunkQuat& orient) -:Chunk(parent,"DUMOBJDT") -{ - location=_location; - min_extents=min; - max_extents=max; - orientation=orient; - - name=new char[strlen(_name)+1]; - strcpy(name,_name); -} - - -Dummy_Object_Data_Chunk::Dummy_Object_Data_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"DUMOBJDT") -{ - CHUNK_EXTRACT(location,ChunkVectorInt) - CHUNK_EXTRACT(min_extents,ChunkVectorInt) - CHUNK_EXTRACT(max_extents,ChunkVectorInt) - CHUNK_EXTRACT(orientation,ChunkQuat) - CHUNK_EXTRACT_STRING(name) -} - - -Dummy_Object_Data_Chunk::~Dummy_Object_Data_Chunk() -{ - if(name) delete [] name; -} - - -void Dummy_Object_Data_Chunk::fill_data_block(char* data) -{ - CHUNK_FILL_START - - CHUNK_FILL(location,ChunkVectorInt) - CHUNK_FILL(min_extents,ChunkVectorInt) - CHUNK_FILL(max_extents,ChunkVectorInt) - CHUNK_FILL(orientation,ChunkQuat) - CHUNK_FILL_STRING(name) - -} - - -size_t Dummy_Object_Data_Chunk::size_chunk() -{ - chunk_size=12+3*sizeof(ChunkVectorInt)+sizeof(ChunkQuat); - chunk_size+=(strlen(name)+4)&~3; - return chunk_size; -} - -///////////////////////////////////////////////////////////////////////////////////// -//////////////////////////////Dummy_Object_Text_Chunk//////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("DUMOBJTX",Dummy_Object_Text_Chunk) - -Dummy_Object_Text_Chunk::Dummy_Object_Text_Chunk(Dummy_Object_Chunk* parent,const char* _text) -:Chunk(parent,"DUMOBJTX"),text(NULL) -{ - set_text(_text); -} - -Dummy_Object_Text_Chunk::Dummy_Object_Text_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"DUMOBJTX") -{ - CHUNK_EXTRACT_STRING(text) -} - - -Dummy_Object_Text_Chunk::~Dummy_Object_Text_Chunk() -{ - delete [] text; -} - -void Dummy_Object_Text_Chunk::fill_data_block(char* data) -{ - CHUNK_FILL_START - - CHUNK_FILL_STRING(text) -} - -void Dummy_Object_Text_Chunk::set_text(const char* _text) -{ - char* new_text = NULL; - if(_text) - { - new_text = new char[strlen(_text)+1]; - strcpy(new_text,_text); - } - - delete [] text; - text = new_text; - -} - - -size_t Dummy_Object_Text_Chunk::size_chunk() -{ - chunk_size=12; - if(text) - chunk_size+=(strlen(text)+4)&~3; - else - chunk_size+=4; - return chunk_size; -} diff --git a/3dc/win95/DummyObjectChunk.hpp b/3dc/win95/DummyObjectChunk.hpp deleted file mode 100644 index adb3a93..0000000 --- a/3dc/win95/DummyObjectChunk.hpp +++ /dev/null @@ -1,81 +0,0 @@ - -#ifndef _DummyObjectChunk_hpp -#define _DummyObjectChunk_hpp 1 - -#include "chunk.hpp" -#include "list_tem.hpp" -#include "chnktype.hpp" - -class Dummy_Object_Data_Chunk; - -class Dummy_Object_Chunk : public Chunk_With_Children -{ -public: - - Dummy_Object_Chunk(Chunk_With_Children* parent,const char* _name ,ChunkVectorInt& _location,ChunkVectorInt& min ,ChunkVectorInt& max ,ChunkQuat& orient); - - // constructor from buffer - Dummy_Object_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - - Dummy_Object_Data_Chunk * get_data_chunk();//gets data chunk (name and location) - - const char* get_text(); //get text attached to a dummy object - void set_text(const char* text); //change the text attached to a dummy object - -}; - -//chunk containing name and location of dummy object -class Dummy_Object_Data_Chunk : public Chunk -{ -public : - Dummy_Object_Data_Chunk(Dummy_Object_Chunk* parent,const char* _name ,ChunkVectorInt& _location,ChunkVectorInt& min ,ChunkVectorInt& max ,ChunkQuat& orient); - Dummy_Object_Data_Chunk (Chunk_With_Children * parent, const char * data, size_t ); - ~Dummy_Object_Data_Chunk(); - - -/*------------------------** -** Main dummy object data ** -**------------------------*/ - char* name; - - ChunkVectorInt location; - ChunkQuat orientation; - - ChunkVectorInt min_extents; - ChunkVectorInt max_extents; -/*------------------------** -** Main dummy object data ** -**------------------------*/ - - size_t size_chunk(); - void fill_data_block (char * data); - -private : - - friend class Dummy_Object_Chunk; - -}; - - -//contains the 'user text' from 3dsmax -class Dummy_Object_Text_Chunk : public Chunk -{ -public : - Dummy_Object_Text_Chunk(Dummy_Object_Chunk* parent,const char* _text); - Dummy_Object_Text_Chunk(Chunk_With_Children * parent, const char * data, size_t ); - ~Dummy_Object_Text_Chunk(); - - size_t size_chunk(); - void fill_data_block (char * data); - - - const char* get_text() {return text;} - void set_text(const char* _text); - -private : - char* text; - -}; - - -#endif
\ No newline at end of file diff --git a/3dc/win95/ENUMCHNK.CPP b/3dc/win95/ENUMCHNK.CPP deleted file mode 100644 index 6b6a3e7..0000000 --- a/3dc/win95/ENUMCHNK.CPP +++ /dev/null @@ -1,131 +0,0 @@ -#include "enumchnk.hpp" -//#include "enumsch.hpp" - -#ifdef cencon -#define new my_new -#endif - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(enumchnk) - -// Class Enum_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("REBENUMS",Enum_Chunk) -// constructor from buffer -LOCKABLE_CHUNK_WITH_CHILDREN_LOADER("REBENUMS",Enum_Chunk) -/* -Children for Enum_Chunk : - -"ENUMHEAD" Enum_Header_Chunk -"BMPENUMS" BMP_Enums_Chunk -*/ - - - -// empty constructor -Enum_Chunk::Enum_Chunk (Chunk_With_Children * parent) -:Lockable_Chunk_With_Children (parent, "REBENUMS") -{ - // as necessary, generated automatically - new Enum_Header_Chunk (this); -} - - -BOOL Enum_Chunk::file_equals (HANDLE & /*rif_file*/) -{ - return(TRUE); -} - -Enum_Header_Chunk * Enum_Chunk::get_header() -{ - - return (Enum_Header_Chunk *) this->lookup_single_child ("ENUMHEAD"); -} - -const char * Enum_Chunk::get_head_id() -{ - Enum_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return (0); - - return(hdptr->identifier); - -} - -void Enum_Chunk::set_lock_user (char * user) -{ - Enum_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return; - - strncpy (hdptr->lock_user, user,16); - - hdptr->lock_user[16] = 0; -} - -void Enum_Chunk::post_input_processing() -{ - if (get_header()) - if (get_header()->flags & GENERAL_FLAG_LOCKED) - external_lock = TRUE; - - Chunk_With_Children::post_input_processing(); - -} - -/////////////////////////////////////// - -// Class Enum_Header_Chunk functions -RIF_IMPLEMENT_DYNCREATE("ENUMHEAD",Enum_Header_Chunk) - -// from buffer -Enum_Header_Chunk::Enum_Header_Chunk (Chunk_With_Children * parent, const char * hdata, size_t /*hsize*/) - : Chunk (parent, "ENUMHEAD"), - flags (0), version_no (0) -{ - flags = *((int *) hdata); - - strncpy (lock_user, (hdata + 4), 16); - lock_user[16] = '\0'; - - version_no = *((int *) (hdata + 20)); -} - -BOOL Enum_Header_Chunk::output_chunk (HANDLE & hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -void Enum_Header_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = flags; - strncpy ((data_start + 4), lock_user, 16); - - *((int *) (data_start+20)) = version_no; -} - -void Enum_Header_Chunk::prepare_for_output() -{ - version_no ++; -} - diff --git a/3dc/win95/ENUMCHNK.HPP b/3dc/win95/ENUMCHNK.HPP deleted file mode 100644 index a29bf16..0000000 --- a/3dc/win95/ENUMCHNK.HPP +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef _included_enumchnk_hpp_ -#define _included_enumchnk_hpp_ - -#include "chunk.hpp" -#include "mishchnk.hpp" - -class Enum_Header_Chunk; - -class Enum_Chunk : public Lockable_Chunk_With_Children -{ -public: - - // empty constructor - Enum_Chunk (Chunk_With_Children * parent); - - // constructor from buffer - Enum_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - - Enum_Header_Chunk * get_header(); - - // functions for the locking functionality - - BOOL file_equals (HANDLE &); - const char * get_head_id(); - void set_lock_user(char *); - - void post_input_processing(); - -private: - - friend class File_Chunk; - friend class GodFather_Chunk; - - - - -}; - -/////////////////////////////////////////////// - -class Enum_Header_Chunk : public Chunk -{ -public: - // constructor from buffer - Enum_Header_Chunk (Chunk_With_Children * parent, const char * pdata, size_t psize); - - virtual size_t size_chunk () - { - chunk_size = 36; - return chunk_size; - } - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - void prepare_for_output(); - -private: - - friend class Enum_Chunk; - friend class File_Chunk; - - int flags; - - int version_no; - - char lock_user[17]; - - - // constructor from parent - Enum_Header_Chunk (Enum_Chunk * parent) - : Chunk (parent, "ENUMHEAD"), - flags (0), version_no (0) - {} - -}; - - - - -#endif // _included_enumchnk_hpp_
\ No newline at end of file diff --git a/3dc/win95/ENUMSCH.CPP b/3dc/win95/ENUMSCH.CPP deleted file mode 100644 index 0138cab..0000000 --- a/3dc/win95/ENUMSCH.CPP +++ /dev/null @@ -1,163 +0,0 @@ -#include <string.h> - -#include "enumsch.hpp" - -#ifdef cencon -#define new my_new -#endif - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(enumsch) - -Enum_Constant::Enum_Constant(char const * const _cname, int const _value) : cname(0), value(_value), reserved(0) -{ - if (_cname) - { - cname = new char[strlen(_cname)+1]; - strcpy(cname,_cname); - } -} - -Enum_Constant::Enum_Constant(Enum_Constant const & ec2) : reserved(ec2.reserved), value(ec2.value), cname(0) -{ - if (ec2.cname) - { - cname = new char[strlen(ec2.cname)+1]; - strcpy(cname,ec2.cname); - } -} - -Enum_Constant & Enum_Constant::operator = (Enum_Constant const & ec2) -{ - if (cname) delete[] cname; - cname = 0; - value = ec2.value; - reserved = ec2.reserved; - if (ec2.cname) - { - cname = new char[strlen(ec2.cname)+1]; - strcpy(cname,ec2.cname); - } - - return *this; -} - -BOOL Enum_Constant::operator == (Enum_Constant const & ec2) const -{ - if (cname && ec2.cname) - if (!strcmp(cname,ec2.cname)) return TRUE; - return FALSE; -} - -BOOL Enum_Constant::operator != (Enum_Constant const & ec2) const -{ - if (cname && ec2.cname) - if (!strcmp(cname,ec2.cname)) return FALSE; - return TRUE; -} - -BOOL Enum_Constant::operator < (Enum_Constant const & ec2) const -{ - if (cname && ec2.cname) - if (strcmp(cname,ec2.cname)<0) return TRUE; - return FALSE; -} - - -Enum_Constant::Enum_Constant(char const * sdata) -: value(*(int *)sdata), reserved(*(int *)(sdata+4)), cname(0) -{ - sdata+=8; - if (*sdata) - { - cname = new char[strlen(sdata)+1]; - strcpy(cname,sdata); - } -} - -size_t Enum_Constant::size_chunk() const -{ - return 8 + ((cname ? strlen(cname)+1 : 1) +3 &~3); -} - -void Enum_Constant::fill_data_block (char * data_start) -{ - *(int*)data_start = value; - *(int*)(data_start+4) = reserved; - - data_start += 8; - - strcpy(data_start,cname ? cname : ""); -} - - -/////// -RIF_IMPLEMENT_DYNCREATE("BMPENUMS",BMP_Enums_Chunk) - -BMP_Enums_Chunk::BMP_Enums_Chunk(Chunk_With_Children * const parent, char const * sdata, size_t const /*ssize*/) -: Chunk(parent,"BMPENUMS") -, reserved1(*(int *)sdata) -, reserved2(*(int *)(sdata+4)) -, ctype(0) -{ - sdata+=8; - unsigned int const len = strlen(sdata)+1; - - if (len>1) - { - ctype = new char[len]; - strcpy(ctype,sdata); - } - - sdata += len + 3 &~3; - - unsigned int const enlistsize = *(int *)sdata; - sdata += 4; - - for (unsigned int i = enlistsize; i; --i) - { - Enum_Constant current(sdata); - sdata += current.size_chunk(); - enums.add_entry(current); - } -} - -size_t BMP_Enums_Chunk::size_chunk () -{ - chunk_size = 12 + 8 + (ctype ? strlen(ctype)+1 : 1) + 4 +3 &~3; - - for (LIF<Enum_Constant> li(&enums); !li.done(); li.next()) - { - chunk_size += li().size_chunk(); - } - return chunk_size; -} - -void BMP_Enums_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - - *(int *) data_start = chunk_size; - data_start += 4; - - *(int*)data_start = reserved1; - *(int*)(data_start+4) = reserved2; - data_start += 8; - - strcpy(data_start,ctype ? ctype : ""); - data_start += strlen(data_start)+1 +3 &~3; - - *(int *)data_start = enums.size(); - data_start += 4; - - for (LIF<Enum_Constant> li(&enums); !li.done(); li.next()) - { - Enum_Constant current(li()); - - current.fill_data_block(data_start); - data_start += current.size_chunk(); - } - -} - diff --git a/3dc/win95/ENUMSCH.HPP b/3dc/win95/ENUMSCH.HPP deleted file mode 100644 index a332b84..0000000 --- a/3dc/win95/ENUMSCH.HPP +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef _included_enumsch_hpp_ -#define _included_enumsch_hpp_ - -#include "chunk.hpp" - -class Enum_Constant -{ -public: - char * cname; - int value; - int reserved; - - Enum_Constant() : cname(0), value(0), reserved(0) {} - - ~Enum_Constant() - { - if (cname) delete[] cname; - } - - Enum_Constant(char const * const _cname, int const _value); - Enum_Constant(Enum_Constant const & ec2); - - Enum_Constant & operator = (Enum_Constant const & ec2); - - BOOL operator == (Enum_Constant const & ec2) const; - BOOL operator != (Enum_Constant const & ec2) const; - BOOL operator < (Enum_Constant const & ec2) const; - -private: - - friend class BMP_Enums_Chunk; - - // constructor from buffer - Enum_Constant(char const * sdata); - - size_t size_chunk() const; - - void fill_data_block(char * data_start); -}; - - -class Enum_Const_List -{ -public: - List<Enum_Constant> enums; - - virtual ~Enum_Const_List(){} -#if cencon - int lowest_free_index(void); - void Sort_By_Name(void); -#endif -}; - - -class BMP_Enums_Chunk : public Chunk, public Enum_Const_List -{ -public: - // constructor from buffer - BMP_Enums_Chunk (Chunk_With_Children * const parent, char const * sdata, size_t const ssize); - -#if cencon - // empty constructor - BMP_Enums_Chunk (Chunk_With_Children * const parent) - : Chunk(parent,"BMPENUMS") - , ctype(0) - , reserved1(0) - , reserved2(0) - {} -#endif - - ~BMP_Enums_Chunk () - { - if (ctype) delete[] ctype; - } - - virtual size_t size_chunk (); - virtual void fill_data_block (char * data_start); - - char * ctype; - int reserved1; - int reserved2; - // List<Enum_Constant> enums; - -private: - - friend class Enum_Chunk; - -}; - - -#endif // !_included_enumsch_hpp_ diff --git a/3dc/win95/ENVCHUNK.CPP b/3dc/win95/ENVCHUNK.CPP deleted file mode 100644 index 04cc292..0000000 --- a/3dc/win95/ENVCHUNK.CPP +++ /dev/null @@ -1,325 +0,0 @@ -#include "chunk.hpp" -#include "envchunk.hpp" - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(envchunk) - -// Class Environment_Data_Chunk functions -RIF_IMPLEMENT_DYNCREATE("REBENVDT",Environment_Data_Chunk) - -// constructor from buffer -LOCKABLE_CHUNK_WITH_CHILDREN_LOADER("REBENVDT",Environment_Data_Chunk) -/* -Children for Enviornment_Data_Chunk : - -"ENVSDSCL" Environment_Scale_Chunk -"GAMEMODE" Environment_Game_Mode_Chunk -"ENVPALET" Environment_Palette_Chunk -"ENVTXLIT" Environment_TLT_Chunk -"TLTCONFG" TLT_Config_Chunk -"CLRLOOKP" Coloured_Polygons_Lookup_Chunk -"MATCHIMG" Matching_Images_Chunk -"BMPNAMES" Global_BMP_Name_Chunk -"BMNAMVER" BMP_Names_Version_Chunk -"BMNAMEXT" BMP_Names_ExtraData_Chunk -"RIFFNAME" RIF_Name_Chunk -"ENDTHEAD" Environment_Data_Header_Chunk -"LIGHTSET" Light_Set_Chunk -"PRSETPAL" Preset_Palette_Chunk -"SPECLOBJ" Special_Objects_Chunk -"AVPEXSTR" AVP_External_Strategy_Chunk -"BMPMD5ID" Bitmap_MD5_Chunk -"GLOGENDC" Global_Generator_Data_Chunk -"FRAGTYPE" Fragment_Type_Chunk -"ENVACOUS" Environment_Acoustics_Chunk -"AVPENVIR" AVP_Environment_Settings_Chunk -"SOUNDDIR" Sound_Directory_Chunk -"RANTEXID" Random_Texture_ID_Chunk -*/ - - - - -// empty constructor -Environment_Data_Chunk::Environment_Data_Chunk (Chunk_With_Children * parent) -:Lockable_Chunk_With_Children (parent, "REBENVDT") -{ - // as necessary, generated automatically - new Environment_Data_Header_Chunk (this); -} - - -BOOL Environment_Data_Chunk::file_equals (HANDLE & /*rif_file*/) -{ - return(TRUE); -} - -Environment_Data_Header_Chunk * Environment_Data_Chunk::get_header() -{ - return (Environment_Data_Header_Chunk *) this->lookup_single_child ("ENDTHEAD"); -} - -const char * Environment_Data_Chunk::get_head_id() -{ - Environment_Data_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return (0); - - return(hdptr->identifier); - -} - -void Environment_Data_Chunk::set_lock_user (char * user) -{ - Environment_Data_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return; - - strncpy (hdptr->lock_user, user,16); - - hdptr->lock_user[16] = 0; -} - -void Environment_Data_Chunk::post_input_processing() -{ - if (get_header()) - if (get_header()->flags & GENERAL_FLAG_LOCKED) - external_lock = TRUE; - - Chunk_With_Children::post_input_processing(); - -} - -/////////////////////////////////////// - -// Class Environment_Data_Header_Chunk functions -RIF_IMPLEMENT_DYNCREATE("ENDTHEAD",Environment_Data_Header_Chunk) - -// from buffer -Environment_Data_Header_Chunk::Environment_Data_Header_Chunk (Chunk_With_Children * parent, const char * hdata, size_t /*hsize*/) - : Chunk (parent, "ENDTHEAD"), - flags (0), version_no (0) -{ - flags = *((int *) hdata); - - strncpy (lock_user, (hdata + 4), 16); - lock_user[16] = '\0'; - - version_no = *((int *) (hdata + 20)); -} - -BOOL Environment_Data_Header_Chunk::output_chunk (HANDLE & hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -void Environment_Data_Header_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = flags; - strncpy ((data_start + 4), lock_user, 16); - - *((int *) (data_start+20)) = version_no; -} - -void Environment_Data_Header_Chunk::prepare_for_output() -{ - version_no ++; -} - -/////////////////////////////////////// - -// Class Environment_Scale_Chunk functions -RIF_IMPLEMENT_DYNCREATE("ENVSDSCL",Environment_Scale_Chunk) - -void Environment_Scale_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((double *) data_start) = scale; -} - -/////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("ENVACOUS",Environment_Acoustics_Chunk) - -Environment_Acoustics_Chunk::Environment_Acoustics_Chunk(Environment_Data_Chunk* parent) -:Chunk(parent,"ENVACOUS") -{ - env_index=0; - reverb=2; - spare=0; -} - -Environment_Acoustics_Chunk::Environment_Acoustics_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"ENVACOUS") -{ - env_index=*(int*)data; - data+=4; - reverb=*(float*)data; - data+=4; - spare=*(int*)data; -} - -void Environment_Acoustics_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=env_index; - data_start+=4; - *(float*)data_start=reverb; - data_start+=4; - *(int*)data_start=spare; - -} -/////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("SOUNDDIR",Sound_Directory_Chunk) - -Sound_Directory_Chunk::Sound_Directory_Chunk(Environment_Data_Chunk* parent,const char* dir) -:Chunk(parent,"SOUNDDIR") -{ - directory=new char[strlen(dir)+1]; - strcpy(directory,dir); -} - -Sound_Directory_Chunk::Sound_Directory_Chunk(Chunk_With_Children * const parent, const char* data, size_t const ) -:Chunk(parent,"SOUNDDIR") -{ - directory=new char[strlen(data)+1]; - strcpy(directory,data); -} - -Sound_Directory_Chunk::~Sound_Directory_Chunk() -{ - delete [] directory; -} - -void Sound_Directory_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - strcpy(data_start,directory); -} - - -/////////////////////////////////////// -/////////////////////Available shape set collections//////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("RANTEXID",Random_Texture_ID_Chunk) - -Random_Texture_ID_Chunk::Random_Texture_ID_Chunk(Chunk_With_Children* parent,const char* _name) -:Chunk(parent,"RANTEXID") -{ - name=new char[strlen(_name)+1]; - strcpy(name,_name); - spare1=spare2=0; -} - - -Random_Texture_ID_Chunk::Random_Texture_ID_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"RANTEXID") -{ - CHUNK_EXTRACT_STRING(name); - - int num_types,type; - CHUNK_EXTRACT(num_types,int); - for(int i=0;i<num_types;i++) - { - CHUNK_EXTRACT(type,int); - random_types.add_entry(type); - } - CHUNK_EXTRACT(spare1,int); - CHUNK_EXTRACT(spare2,int); - -} - -Random_Texture_ID_Chunk::~Random_Texture_ID_Chunk() -{ - delete [] name; -} - -void Random_Texture_ID_Chunk::fill_data_block(char* data) -{ - CHUNK_FILL_START - - CHUNK_FILL_STRING(name) - - CHUNK_FILL(random_types.size(),int); - for(LIF<int> rlif(&random_types);!rlif.done();rlif.next()) - { - CHUNK_FILL(rlif(),int) - } - - CHUNK_FILL(spare1,int) - CHUNK_FILL(spare2,int) - -} - -size_t Random_Texture_ID_Chunk::size_chunk() -{ - chunk_size=12+12+random_types.size()*4; - chunk_size+=(strlen(name)+4)&~3; - return chunk_size; -} -/////////////////////////////////////// - - - - -//Class Special_Objects_Chunk : -RIF_IMPLEMENT_DYNCREATE("SPECLOBJ",Special_Objects_Chunk) - -CHUNK_WITH_CHILDREN_LOADER("SPECLOBJ",Special_Objects_Chunk) -/* -Children for Special_Objects_Chunk : -"AVPGENER" AVP_Generator_Chunk -"SOUNDOB2" Sound_Object_Chunk -"VIOBJECT" Virtual_Object_Chunk -"AVPCABLE" AVP_Power_Cable_Chunk -"AVPSTART" AVP_Player_Start_Chunk -"AVPPATH2" AVP_Path_Chunk -"AVPGENEX" AVP_Generator_Extra_Data_Chunk -"SOUNDEXD" Sound_Object_Extra_Data_Chunk -"PARGENER" AVP_Particle_Generator_Chunk -"PLACHIER" Placed_Hierarchy_Chunk -"CAMORIGN" Camera_Origin_Chunk -"AVPDECAL" AVP_Decal_Chunk -"R6WAYPNT" R6_Waypoint_Chunk - -*/ - - diff --git a/3dc/win95/ENVCHUNK.HPP b/3dc/win95/ENVCHUNK.HPP deleted file mode 100644 index ee4b578..0000000 --- a/3dc/win95/ENVCHUNK.HPP +++ /dev/null @@ -1,201 +0,0 @@ -#ifndef _envchunk_hpp -#define _envchunk_hpp 1 - -#include "chunk.hpp" -#include "chnktype.hpp" -#include "mishchnk.hpp" - - -class Environment_Data_Header_Chunk; - -class Environment_Data_Chunk : public Lockable_Chunk_With_Children -{ -public: - - // empty constructor - Environment_Data_Chunk (Chunk_With_Children * parent); - // constructor from buffer - Environment_Data_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - - Environment_Data_Header_Chunk * get_header(); - - // functions for the locking functionality - - BOOL file_equals (HANDLE &); - const char * get_head_id(); - void set_lock_user(char *); - - void post_input_processing(); - -private: - - friend class File_Chunk; - friend class GodFather_Chunk; - friend class RIF_File_Chunk; - - - - -}; - -/////////////////////////////////////////////// - -class Environment_Data_Header_Chunk : public Chunk -{ -public: - // constructor from buffer - Environment_Data_Header_Chunk (Chunk_With_Children * parent, const char * pdata, size_t psize); - - virtual size_t size_chunk () - { - chunk_size = 36; - return chunk_size; - } - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - void prepare_for_output(); - -private: - - friend class Environment_Data_Chunk; - friend class File_Chunk; - - int flags; - - int version_no; - - char lock_user[17]; - - - // constructor from parent - Environment_Data_Header_Chunk (Environment_Data_Chunk * parent) - : Chunk (parent, "ENDTHEAD"), - flags (0), version_no (0) - {} - -}; - -/////////////////////////////////////////////// - -class Environment_Scale_Chunk : public Chunk -{ - -public: - - // constructor from data - Environment_Scale_Chunk (Environment_Data_Chunk * parent, double _scale) - : Chunk (parent, "ENVSDSCL"), - scale (_scale) - {} - - // constructor from buffer - Environment_Scale_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/) - : Chunk (parent, "ENVSDSCL"), - scale ( *((double *) sdata) ) - {} - - virtual size_t size_chunk () - { - chunk_size = 20; - return chunk_size; - } - - virtual void fill_data_block (char * data_start); - - const double scale; - -private: - - friend class Environment_Data_Chunk; - - - - -}; - -/////////////////////////////////////////////// - -class Special_Objects_Chunk : public Chunk_With_Children -{ - -public: - - Special_Objects_Chunk(Chunk_With_Children * parent) - : Chunk_With_Children (parent, "SPECLOBJ") - {} - // constructor from buffer - Special_Objects_Chunk (Chunk_With_Children * const parent,const char *, size_t const); -private: - - friend class Environment_Data_Chunk; - friend class AVP_Generator_Chunk; - - - -}; - -/////////////////////////////////////////////// -class Environment_Acoustics_Chunk : public Chunk -{ -public: - Environment_Acoustics_Chunk(Environment_Data_Chunk * parent); - Environment_Acoustics_Chunk(Chunk_With_Children* parent, const char * data, size_t ); - virtual void fill_data_block(char*); - virtual size_t size_chunk() - {return chunk_size=24;} - - int env_index; - float reverb; - int spare; -private: - friend class Environment_Data_Chunk; - - - -}; -/////////////////////////////////////////////// -class Sound_Directory_Chunk : public Chunk -{ -public : - Sound_Directory_Chunk(Environment_Data_Chunk* parent,const char* dir); - ~Sound_Directory_Chunk(); - // constructor from buffer - Sound_Directory_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - char* directory; - - size_t size_chunk() - { - return (chunk_size =12 + ((strlen (directory)+4)&~3)); - } - - void fill_data_block(char* data_start); - -private: - - friend class Environment_Data_Chunk; - - - -}; - -/////////////////////Available shape set collections//////////////////////////////////////// -class Random_Texture_ID_Chunk : public Chunk -{ -public : - Random_Texture_ID_Chunk(Chunk_With_Children* parent,const char* _name); - Random_Texture_ID_Chunk(Chunk_With_Children* parent,const char* data, size_t); - ~Random_Texture_ID_Chunk(); - - void fill_data_block(char* data); - size_t size_chunk(); - - char* name; - List<int> random_types; - - int spare1,spare2; - -}; -#endif
\ No newline at end of file diff --git a/3dc/win95/GSPRCHNK.CPP b/3dc/win95/GSPRCHNK.CPP deleted file mode 100644 index b20293f..0000000 --- a/3dc/win95/GSPRCHNK.CPP +++ /dev/null @@ -1,130 +0,0 @@ -#include "gsprchnk.hpp" - -#ifdef cencon -#define new my_new -#endif - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(gsprchnk) - -// Class AllSprites_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("RSPRITES",AllSprites_Chunk) -// constructor from buffer -LOCKABLE_CHUNK_WITH_CHILDREN_LOADER("RSPRITES",AllSprites_Chunk) - -/* -Children for AllSprites_Chunk : - -"ASPRHEAD" AllSprites_Header_Chunk -"SPRIHEAD" Sprite_Header_Chunk -*/ - - - -// empty constructor -AllSprites_Chunk::AllSprites_Chunk (Chunk_With_Children * parent) -:Lockable_Chunk_With_Children (parent, "RSPRITES") -{ - // as necessary, generated automatically - new AllSprites_Header_Chunk (this); -} - - -BOOL AllSprites_Chunk::file_equals (HANDLE & /*rif_file*/) -{ - return(TRUE); -} - -AllSprites_Header_Chunk * AllSprites_Chunk::get_header() -{ - return (AllSprites_Header_Chunk *) this->lookup_single_child ("ASPRHEAD"); -} - -const char * AllSprites_Chunk::get_head_id() -{ - AllSprites_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return (0); - - return(hdptr->identifier); - -} - -void AllSprites_Chunk::set_lock_user (char * user) -{ - AllSprites_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return; - - strncpy (hdptr->lock_user, user,16); - - hdptr->lock_user[16] = 0; -} - -void AllSprites_Chunk::post_input_processing() -{ - if (get_header()) - if (get_header()->flags & GENERAL_FLAG_LOCKED) - external_lock = TRUE; - - Chunk_With_Children::post_input_processing(); - -} - -/////////////////////////////////////// - -// Class AllSprites_Header_Chunk functions -RIF_IMPLEMENT_DYNCREATE("ASPRHEAD",AllSprites_Header_Chunk) - -// from buffer -AllSprites_Header_Chunk::AllSprites_Header_Chunk (Chunk_With_Children * parent, const char * hdata, size_t /*hsize*/) - : Chunk (parent, "ASPRHEAD"), - flags (0), version_no (0) -{ - flags = *((int *) hdata); - - strncpy (lock_user, (hdata + 4), 16); - lock_user[16] = '\0'; - - version_no = *((int *) (hdata + 20)); -} - -BOOL AllSprites_Header_Chunk::output_chunk (HANDLE & hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -void AllSprites_Header_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = flags; - strncpy ((data_start + 4), lock_user, 16); - - *((int *) (data_start+20)) = version_no; -} - -void AllSprites_Header_Chunk::prepare_for_output() -{ - version_no ++; -} - diff --git a/3dc/win95/GSPRCHNK.HPP b/3dc/win95/GSPRCHNK.HPP deleted file mode 100644 index ede6395..0000000 --- a/3dc/win95/GSPRCHNK.HPP +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef _included_gsprchnk_hpp_ -#define _included_gsprchnk_hpp_ - -#include "chunk.hpp" -#include "mishchnk.hpp" - -class AllSprites_Header_Chunk; - -class AllSprites_Chunk : public Lockable_Chunk_With_Children -{ -public: - - // empty constructor - AllSprites_Chunk (Chunk_With_Children * parent); - // constructor from buffer - AllSprites_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - - AllSprites_Header_Chunk * get_header(); - - // functions for the locking functionality - - BOOL file_equals (HANDLE &); - const char * get_head_id(); - void set_lock_user(char *); - - void post_input_processing(); - -private: - - friend class File_Chunk; - friend class GodFather_Chunk; - - - - -}; - -/////////////////////////////////////////////// - -class AllSprites_Header_Chunk : public Chunk -{ -public: - // constructor from buffer - AllSprites_Header_Chunk (Chunk_With_Children * parent, const char * pdata, size_t psize); - - virtual size_t size_chunk () - { - chunk_size = 36; - return chunk_size; - } - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - void prepare_for_output(); - -private: - - friend class AllSprites_Chunk; - friend class File_Chunk; - - int flags; - - int version_no; - - char lock_user[17]; - - - - // constructor from parent - AllSprites_Header_Chunk (AllSprites_Chunk * parent) - : Chunk (parent, "ASPRHEAD"), - flags (0), version_no (0) - {} - -}; - - - - -#endif // _included_gsprchnk_hpp_
\ No newline at end of file diff --git a/3dc/win95/Hash_tem.hpp b/3dc/win95/Hash_tem.hpp deleted file mode 100644 index 279c65d..0000000 --- a/3dc/win95/Hash_tem.hpp +++ /dev/null @@ -1,882 +0,0 @@ -/********************************************************/ -/* Hash Table template class - v1.2 */ -/* */ -/* Author: Jake Hotson */ -/* */ -/* construct a hash table for objects of type TYPE */ -/* */ -/* HashTable<TYPE>(unsigned initialTableSizeShift */ -/* = HT_DEFAULTTABLESIZESHIFT); */ -/* */ -/* TYPE must have boolean operator == defined, and */ -/* there must be an overload of the function */ -/* HashFunction() which acts as a hash */ -/* function for the TYPE, taking an argument of type */ -/* TYPE or a suitable conversion thereof, and returning */ -/* unsigned */ -/* Also, if a==b then HashFunction(a)==HashFunction(b) */ -/* Additionally, TYPE must have valid assignment */ -/* operator and copy constructor */ -/****************************************************Jake*/ - -/************************************************************/ -/* */ -/* v1.0 public classes and functions and macros */ -/* */ -/* HASH_TEMPLATE_VERSION */ -/* */ -/* major version * 100 + minor version */ -/* in this version (1.0) the value is 100 */ -/* */ -/* HT_NODEFAULTFNS */ -/* */ -/* #define to not compile default hash functions */ -/* */ -/* HT_DEFAULTABLESIZESHIFT */ -/* */ -/* #define to override default table size shift */ -/* of 6 (which gives a default table size of 64) */ -/* */ -/* HT_FAIL(sP) */ -/* */ -/* this macro should expand to a function (which */ -/* takes a char const * parameter) to be called */ -/* in the event of an error */ -/* */ -/* HashFunction(unsigned) */ -/* */ -/* default hash function for integers */ -/* */ -/* HashFunction(void const *) */ -/* */ -/* default hash function for pointers */ -/* */ -/* HashFunction(char const *) */ -/* */ -/* default hash function for strings */ -/* */ -/* class HashTable<TYPE> */ -/* */ -/* hash table template class */ -/* TYPE should have == operator defined and an */ -/* overloaded HashFunction() defined which can */ -/* take an argument type TYPE or suitable */ -/* conversion thereof */ -/* */ -/* HashTable::HashTable() */ -/* */ -/* constructs an empty table with default table */ -/* size */ -/* */ -/* HashTable::HashTable(unsigned) */ -/* */ -/* constructs an empty table with specific */ -/* table size determined by 2^arg */ -/* */ -/* bool HashTable::AddChecked(TYPE) */ -/* */ -/* adds object to hash table unless it already */ -/* contains it. Returns non-zero if object was */ -/* added, and zero if it was already contained */ -/* */ -/* void HashTable::AddRegardless(TYPE) */ -/* */ -/* adds object to hash table but does not check */ -/* if it already exists, so duplicates could */ -/* occur */ -/* */ -/* void HashTable::AddAsserted(TYPE) */ -/* */ -/* adds object to hash table but throws a failure if it */ -/* already exists unless NDEBUG is defined in which case */ -/* this function is identical to AddRegardless */ -/* */ -/* TYPE const * HashTable::Contains(TYPE) const */ -/* */ -/* returns pointer to equivalent entry in table, */ -/* or NULL, if none exists */ -/* */ -/* bool HashTable::Remove(TYPE) */ -/* */ -/* removes object from table if it exists. */ -/* Returns non-zero if object was removed, or */ -/* zero if object was not contained */ -/* */ -/* void HashTable::RemoveAll() */ -/* */ -/* empties the table */ -/* */ -/* void HashTable::RemoveAsserted(TYPE) */ -/* */ -/* removes object from table, but throws a */ -/* failure if object was not contained */ -/* */ -/* unsigned HashTable::Size() const */ -/* */ -/* returns number of objects in table */ -/* */ -/* class HashTable<TYPE>::ConstIterator */ -/* */ -/* class for iterating through objects contained */ -/* in hash table, without modifying the contents */ -/* of the table */ -/* */ -/* HashTable::ConstIterator::ConstIterator(HashTable const) */ -/* */ -/* constructs an iterator linked to a table, */ -/* ready for a Get() */ -/* */ -/* TYPE const & HashTable::ConstIterator::Get() const */ -/* HashTable::ConstIterator::operator TYPE const & () const */ -/* */ -/* gets a constant reference to the object in */ -/* the table pointed to by the iterator object */ -/* */ -/* bool HashTable::ConstIterator::Done() const */ -/* */ -/* returns non-zero only if there is no more */ -/* iterating to do */ -/* */ -/* void HashTable::ConstIterator::Next() */ -/* */ -/* moves iterator to a fresh entry in the table */ -/* */ -/* class HashTable<TYPE>::Iterator */ -/* */ -/* class for iterating through objects contained */ -/* in hash table, allowing their removal */ -/* */ -/* HashTable::Iterator::Iterator(HashTable) */ -/* */ -/* constructs an iterator linked to a table, */ -/* ready for a Get() */ -/* */ -/* HashTable::Iterator::Remove() */ -/* */ -/* removes the current object pointed to by the */ -/* iterator from the table, and advances the */ -/* iterator to the next entry */ -/* */ -/*******************************************************Jake*/ - -/************************************************************/ -/* */ -/* v1.1 - v1.11 extended functionality */ -/* */ -/* class HashTable<TYPE>::Node */ -/* */ -/* this is the internal class for nodes in the table */ -/* */ -/* TYPE HashTable::Node::d */ -/* */ -/* this is the value of a node's data */ -/* */ -/* Node * HashTable::NewNode() */ -/* */ -/* allocates a node without inserting it into the table; */ -/* you are expected to set Node::d to the required value */ -/* to be added to the table, and call one of these methods */ -/* to link the node into the table */ -/* */ -/* void HashTable::AddAsserted(Node *) */ -/* */ -/* like AddAsserted(TYPE const &) but takes a Node * */ -/* created with NewNode(); do not use the Node * pointer */ -/* after calling this method */ -/* */ -/* void HashTable::AddRegardless(Node *) */ -/* */ -/* like AddRegardless(TYPE const &) but takes a Node * */ -/* created with NewNode(); do not use the Node * pointer */ -/* after calling this method */ -/* */ -/* bool HashTable::AddChecked(Node *) */ -/* */ -/* like AddChecked(TYPE const &) but takes a Node * */ -/* created with NewNode(); do not use the Node * pointer */ -/* after calling this method if it returns true, but if it */ -/* returns false (i.e. the Node was not added, then you */ -/* can re-use the Node or use the following function to */ -/* delete it. */ -/* */ -/* void HashTable::DeleteNode(Node *) */ -/* */ -/* destroys a Node created with NewNode. Use this only if */ -/* the node created was not added to the hash table */ -/* */ -/*******************************************************Jake*/ - -/************************************************************/ -/* */ -/* v1.2 */ -/* */ -/* HashTable::Iterator::Restart() */ -/* restarts the iterator */ -/* */ -/* HashTable::HashTable(HashTable<TYPE>) */ -/* copy constructor */ -/* */ -/* HashTable::ValueIterator(unsigned) */ -/* iterate through all entries of a specific hashvalue */ -/* */ -/*******************************************************Alex*/ - -#ifndef HASH_TEMPLATE_VERSION -#define HASH_TEMPLATE_VERSION 12 // v1.2 - -#include <stddef.h> -#include <ctype.h>// for toupper - -// v1,0 Default Hash Functions defined: -// HashFunction(unsigned), HashFunction(void const *), HashFunction(char const *) -// you can disable the default hash functions by defining HT_NODEFAULTFNS - -#ifndef HT_NODEFAULTFNS - // a hash function for integral (unsigned) values - inline unsigned HashFunction(unsigned const _i) - { - return _i ^ _i>>4 ^ _i>>9 ^ _i>>15 ^ _i>>22; - } - - // a hash function for pointers - inline unsigned HashFunction(void const * const _vP) - { - // treat as integer - return HashFunction(reinterpret_cast<unsigned>(_vP)); - } - - // a hash function for strings - inline unsigned HashFunction(char const * _sP) - { - unsigned rv = 0; - while (*_sP) rv += toupper(*_sP++); - return rv; - } -#endif - -// v1,0 Default (initial) table size (log2 of) -// Define this to another value if you like, -// or just override in the constructor. -// in v1.0, the table is not self-expanding, -// but if this feature is implememted, then -// this value will become the log2(initial table size), -// and if table becomes is self-contracting, -// this value will also give the minimum table size - -#ifndef HT_DEFAULTTABLESIZESHIFT - #define HT_DEFAULTTABLESIZESHIFT 6 -#endif - -// for asserted functions, define HT_FAIL to be your function -// to be triggered upon a failure, eg. -// #define HT_FAIL(strP) fprintf(stderr,"%s\n",strP) -#ifndef HT_FAIL - #define HT_FAIL(strP) ((void)0) -#endif - -template <class TYPE, class ARG_TYPE, class CMP_ARG_TYPE> -class _base_HashTable -{ - public: - class Iterator; - class ConstIterator; - class ValueIterator; - class Node; - - public: - // V1.0 Functionality - - // empty constructor, with argument specifying initial table size (log2 of) - _base_HashTable(unsigned = HT_DEFAULTTABLESIZESHIFT); - - // destructor - ~_base_HashTable(); - - // copy constructor and assignment not provided in v1.0 - _base_HashTable(_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> const &); - _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> & operator = (_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> const &); - - // add, checking that an equivalent entry does not already exist - // returns non-zero if entry was added - bool AddChecked(ARG_TYPE); - - // add, regardless of whether an equivalent entry already exists - void AddRegardless(ARG_TYPE); - - // add, checking that an equivalent entry does not already exist - // triggering fail function if one does - void AddAsserted(ARG_TYPE); - - // see if entry exists, get pointer to it if it does - TYPE const * Contains(CMP_ARG_TYPE) const; - - // remove an entry (once only in the case of equivalent entries listed multiple times) - // returns non-zero if entry existed and was removed - bool Remove(CMP_ARG_TYPE); - - // remove an entry (once only in the case of equivalent entries listed multiple times) - // triggers fail function if no entry existed to remove - void RemoveAsserted(CMP_ARG_TYPE); - - // empty the table - void RemoveAll(); - - // return num entries in table - unsigned Size() const; - - // a _base_HashTable const iterator - class ConstIterator - { - // Nested class functions apparently have to be declared here for MSVC compatability - public: - // construct from const hash table - ConstIterator(_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> const & tableR) - : chainPP(tableR.chainPA) - , nChainsRemaining(tableR.tableSize) - , nEntriesRemaining(tableR.nEntries) - { - if (nEntriesRemaining) - { - while (!*chainPP) - { - ++ chainPP; - -- nChainsRemaining; - } - nodePP = chainPP; - } - } - - // returns non-zero if there are no more entries to get - inline bool Done() const - { - return ! nEntriesRemaining; - } - - inline void Restart(_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> const & tableR) - { - chainPP = tableR.chainPA; - nChainsRemaining = tableR.tableSize; - nEntriesRemaining = tableR.nEntries; - - if (nEntriesRemaining) - { - while (!*chainPP) - { - ++ chainPP; - -- nChainsRemaining; - } - nodePP = chainPP; - } - } - - // get the current entry pointed to, either with Get() or cast operator - inline operator ARG_TYPE () const - { - return Get(); - } - inline ARG_TYPE Get() const - { - if( Done() ) - { - HT_FAIL("HTT: Tried to Get() from an iterator which was Done()"); - } - return (*nodePP)->d; - } - - // advance to the next entry - void Next() - { - if (!nEntriesRemaining) - { - HT_FAIL("HTT: Tried to do Next() on an iterator which was Done()"); - } - if ((*nodePP)->nextP) - { - nodePP = &(*nodePP)->nextP; - } - else - { - do - { - ++ chainPP; - -- nChainsRemaining; - } - while (nChainsRemaining && !*chainPP); - nodePP = chainPP; - } - -- nEntriesRemaining; - } - - private: - - Node * * chainPP; - Node * * nodePP; - unsigned nChainsRemaining; - unsigned nEntriesRemaining; - - friend class Iterator; - }; - - // a _base_HashTable non-const iterator - can remove entry pointed to - class Iterator : public ConstIterator - { - // Nested class functions apparently have to be declared here for MSVC compatability - public: - // construct from hash table - inline Iterator(_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> & tableR) - : ConstIterator(tableR) - , tableNEntriesP(&tableR.nEntries) - { - } - - // remove the current entry pointed to, advancing to the next - void Remove() - { - if (!nEntriesRemaining) - { - HT_FAIL("HTT: Tried to Remove() via an iterator which was Done()"); - } - Node * oldP = *nodePP; - *nodePP = oldP->nextP; - delete oldP; - if (!*nodePP) - { - do - { - ++ chainPP; - -- nChainsRemaining; - } - while (nChainsRemaining && !*chainPP); - nodePP = chainPP; - } - -- nEntriesRemaining; - -- *tableNEntriesP; - } - - private: - unsigned * tableNEntriesP; - }; - - // v1.2 extended functionality - // a _base_HashTable iterator through a specific hash value - class ValueIterator - { - // Nested class functions apparently have to be declared here for MSVC compatability - public: - // construct from const hash table - ValueIterator(_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> & tableR, unsigned value) - : chainPP(tableR.chainPA) - , value(value) - , tableNEntriesP(&tableR.nEntries) - { - chainPP += (value & tableR.tableSizeMask); - nodePP = chainPP; - } - - // returns non-zero if there are no more entries to get - inline bool Done() const - { - return( !(*nodePP) ); - } - - inline operator ARG_TYPE () const - { - return Get(); - } - inline ARG_TYPE Get() const - { - if( Done() ) - { - HT_FAIL("HTT: Tried to Get() from an iterator which was Done()"); - } - return (*nodePP)->d; - } - - inline void Restart(_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> const & tableR) - { - chainPP = tableR.chainPA + (value & tableR.tableSizeMask); - nodePP = chainPP; - } - - // advance to the next entry - void Next() - { - if( *nodePP ) - { - nodePP = &(*nodePP)->nextP; // even if it's NULL for ValueIterator - } - else - { - HT_FAIL("HTT: Tried to do Next() on a Value iterator which was Done()"); - } - } - - // remove the current entry pointed to, advancing to the next - void Remove() - { - if( *nodePP ) - { - Node * oldP = *nodePP; - *nodePP = oldP->nextP; - delete oldP; - -- *tableNEntriesP; - } - else - { - HT_FAIL("HTT: Tried to Remove() via an iterator which was Done()"); - } - } - - private: - - Node * * chainPP; - Node * * nodePP; - - unsigned value; - unsigned * tableNEntriesP; - }; - - // V1.1 extended functionality - // allow user to create nodes, change - // the data using this pointer, - // then insert the node into the - // correct chain, without having - // to create a copy of the data to - // be added on the stack - virtual Node * NewNode(); - // add, checking that an equivalent entry does not already exist - // triggering fail function if one does - void AddAsserted(Node *); - // add, regardless of whether an equivalent entry already exists - void AddRegardless(Node *); - // V1.11 allows AddChecked for the Node-adding interface - bool AddChecked(Node *); - // if add checked fails, you should avoid the memory leak with this function - virtual void DeleteNode(Node *); - - class Node - { - public: - TYPE d; - private: - Node * nextP; - // Nested class functions apparently have to be declared here for MSVC compatability - inline Node(ARG_TYPE _dataR,Node * _nextP) - : d(_dataR) - , nextP(_nextP) - { - } - inline Node() - { - } - inline ~Node() - { - } - void DeleteChain() - { - if (nextP) nextP->DeleteChain(); - delete this; - } - - friend class ConstIterator; - friend class Iterator; - friend class ValueIterator; - friend class _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>; - }; - - private: - // virtual functions for future expansion - virtual Node * NewNode(ARG_TYPE,Node *); - - unsigned nEntries; - unsigned tableSize; - unsigned tableSizeMask; - Node * * chainPA; - - friend class ConstIterator; - friend class Iterator; - friend class ValueIterator; - - inline void Xx(){} -}; - -/*******************/ -/* Defined to Fail */ -/**************Jake*/ - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> & _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::operator = (_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> const &) -{ - HT_FAIL("HTT: assignment operator not allowed in this version"); - return *this; -} - -/*******************************/ -/* Inline Function Definitions */ -/**************************Jake*/ - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::AddRegardless(ARG_TYPE _dataR) -{ - Node * & chainPR = chainPA[HashFunction(_dataR) & tableSizeMask]; - chainPR = new Node(_dataR,chainPR); - ++ nEntries; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::AddRegardless(Node * _nodeP) -{ - Node * & chainPR = chainPA[HashFunction(_nodeP->d) & tableSizeMask]; - _nodeP->nextP = chainPR; - chainPR = _nodeP; - ++ nEntries; -} - -// with NDEBUG on these functions evaluate to be identical to AddRegardless -#ifdef NDEBUG -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::AddAsserted(ARG_TYPE _dataR) -{ - AddRegardless(_dataR); -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::AddAsserted(Node * _nodeP) -{ - AddRegardless(_nodeP); -} -#endif - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline TYPE const * _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::Contains(CMP_ARG_TYPE _dataR) const -{ - for (Node const * nodeP = chainPA[HashFunction(_dataR) & tableSizeMask]; nodeP; nodeP = nodeP->nextP) - { - if (nodeP->d == _dataR) return &nodeP->d; - } - return NULL; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline unsigned _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::Size() const -{ - return nEntries; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::RemoveAll() -{ - for (unsigned i=0; i<tableSize; ++i) - if (chainPA[i]) - { - chainPA[i]->DeleteChain(); - chainPA[i] = NULL; - } - nEntries = 0; -} - -/*************************************************************/ -/* Non inlines declared here since neither Watcom nor */ -/* MS Visual C will link if they're in their own source file */ -/********************************************************Jake*/ - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::_base_HashTable(unsigned _initialTableSizeShift) - : nEntries(0) - , tableSize(1<<_initialTableSizeShift) - , tableSizeMask(tableSize-1) - , chainPA(new Node * [tableSize]) -{ - for (unsigned i=0; i<tableSize; ++i) - chainPA[i] = NULL; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -inline _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::_base_HashTable(_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE> const & ht) - : nEntries(0) - , tableSize(ht.tableSize) - , tableSizeMask(tableSize-1) - , chainPA(new Node * [tableSize]) -{ - for (unsigned i=0; i<tableSize; ++i) { chainPA[i] = NULL; } - - for( HashTable<TYPE>::ConstIterator it(ht); !it.Done(); it.Next() ) - { - AddRegardless( it.Get() ); - } -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::~_base_HashTable() -{ - for (unsigned i=0; i<tableSize; ++i) - if (chainPA[i]) - chainPA[i]->DeleteChain(); - delete[] chainPA; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -bool _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::AddChecked(ARG_TYPE _dataR) -{ - Node * & chainPR = chainPA[HashFunction(_dataR) & tableSizeMask]; - for (Node const * nodeP = chainPR; nodeP; nodeP = nodeP->nextP) - { - if (nodeP->d == _dataR) return false; - } - chainPR = new Node(_dataR,chainPR); - ++ nEntries; - return true; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -bool _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::AddChecked(Node * _nodeP) -{ - Node * & chainPR = chainPA[HashFunction(_nodeP->d) & tableSizeMask]; - for (Node const * nodeP = chainPR; nodeP; nodeP = nodeP->nextP) - { - if (nodeP->d == _nodeP->d) return false; - } - _nodeP->nextP = chainPR; - chainPR = _nodeP; - ++ nEntries; - return true; -} - -// with NDEBUG on these functions evaluate to be identical to AddRegardless -#ifndef NDEBUG -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::AddAsserted(ARG_TYPE _dataR) -{ - Node * & chainPR = chainPA[HashFunction(_dataR) & tableSizeMask]; - for (Node const * nodeP = chainPR; nodeP; nodeP = nodeP->nextP) - { - if (nodeP->d == _dataR) - { - HT_FAIL("HTT: Tried to add entry which was already contained in table"); - } - } - chainPR = new Node(_dataR,chainPR); - ++ nEntries; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::AddAsserted(Node * _nodeP) -{ - Node * & chainPR = chainPA[HashFunction(_nodeP->d) & tableSizeMask]; - for (Node const * nodeP = chainPR; nodeP; nodeP = nodeP->nextP) - { - if (nodeP->d == _nodeP->d) - { - HT_FAIL("HTT: Tried to add entry which was already contained in table"); - } - } - _nodeP->nextP = chainPR; - chainPR = _nodeP; - ++ nEntries; -} -#endif - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -bool _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::Remove(CMP_ARG_TYPE _dataR) -{ - for (Node * * nodePP = &chainPA[HashFunction(_dataR) & tableSizeMask]; (*nodePP); nodePP = &(*nodePP)->nextP) - { - if ((*nodePP)->d == _dataR) - { - Node * oldP = *nodePP; - *nodePP = oldP->nextP; - delete oldP; - -- nEntries; - return true; - } - } - return false; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::RemoveAsserted(CMP_ARG_TYPE _dataR) -{ - for (Node * * nodePP = &chainPA[HashFunction(_dataR) & tableSizeMask]; (*nodePP); nodePP = &(*nodePP)->nextP) - { - if ((*nodePP)->d == _dataR) - { - Node * oldP = *nodePP; - *nodePP = oldP->nextP; - delete oldP; - -- nEntries; - return; - } - } - HT_FAIL("HTT: Tried to remove entry which was not contained in table"); -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::Node * _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::NewNode(ARG_TYPE _dataR,Node * _nextP) -{ - return new Node(_dataR,_nextP); -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -_base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::Node * _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::NewNode() -{ - return new Node; -} - -template <class TYPE,class ARG_TYPE,class CMP_ARG_TYPE> -void _base_HashTable<TYPE,ARG_TYPE,CMP_ARG_TYPE>::DeleteNode(Node * _nodeP) -{ - delete _nodeP; -} - -template <class TYPE> class HashTable; - -#define HT_DEFINITION(T1,T2,T3) \ - : public _base_HashTable<T1,T2,T3> { public: HashTable(unsigned _initialTableSizeShift = HT_DEFAULTTABLESIZESHIFT) : _base_HashTable<T1,T2,T3>(_initialTableSizeShift){} }; - -// for simple types -#define HT_WATCOM_DEFINE_FOR_SIMPLE_TYPE(TYPE) \ - class HashTable<TYPE> HT_DEFINITION(TYPE,TYPE,TYPE) - -#ifdef __WATCOMC__ - -//watcom generartes errors if template<> is added to the start of the line - Richard. -#define HT_DEFINE_FOR_SIMPLE_TYPE(SIMPLE_TYPE) HT_WATCOM_DEFINE_FOR_SIMPLE_TYPE(SIMPLE_TYPE) - -#else - -#define HT_DEFINE_FOR_SIMPLE_TYPE(SIMPLE_TYPE) template<> HT_WATCOM_DEFINE_FOR_SIMPLE_TYPE(SIMPLE_TYPE) - -#endif - -HT_DEFINE_FOR_SIMPLE_TYPE(unsigned long) -HT_DEFINE_FOR_SIMPLE_TYPE(signed long) -HT_DEFINE_FOR_SIMPLE_TYPE(unsigned) -HT_DEFINE_FOR_SIMPLE_TYPE(signed) -HT_DEFINE_FOR_SIMPLE_TYPE(unsigned short) -HT_DEFINE_FOR_SIMPLE_TYPE(signed short) -HT_DEFINE_FOR_SIMPLE_TYPE(unsigned char) -HT_DEFINE_FOR_SIMPLE_TYPE(signed char) -HT_DEFINE_FOR_SIMPLE_TYPE(char) -HT_DEFINE_FOR_SIMPLE_TYPE(float) - -#undef HT_DEFINE_FOR_SIMPLE_TYPE -#undef HT_WATCOM_DEFINE_FOR_SIMPLE_TYPE - -// for pointer types -#if 0 // doesnt't compile!! -template <class TYPE> -class HashTable<TYPE *> HT_DEFINITION(TYPE *, TYPE *, TYPE const *) - -template <class TYPE> -class HashTable<TYPE const *> HT_DEFINITION(TYPE const *, TYPE const *, TYPE const *) -#endif - -// for other types -template <class TYPE> -class HashTable HT_DEFINITION(TYPE,TYPE const &, TYPE const &) - -//template <class TYPE *> class HashTable : public _base_HashTable<TYPE *,TYPE *,TYPE const *> {}; - -#undef HT_DEFINITION - -#endif // ! HASH_TEMPLATE_VERSION diff --git a/3dc/win95/ILBM_ext.cpp b/3dc/win95/ILBM_ext.cpp deleted file mode 100644 index e1d8a4d..0000000 --- a/3dc/win95/ILBM_ext.cpp +++ /dev/null @@ -1,87 +0,0 @@ -#include "ILBM_ext.hpp" - -IFF_IMPLEMENT_DYNCREATE("ILBM","TRAN",IlbmTranChunk) -IFF_IMPLEMENT_DYNCREATE("ILBM","ALPH",IlbmAlphChunk) -IFF_IMPLEMENT_DYNCREATE("MIPM","CONT",MipmContChunk) -IFF_IMPLEMENT_DYNCREATE("ILBM","S3TC",IlbmS3tcChunk) -IFF_IMPLEMENT_DYNCREATE("MIPM","FLAG",MipmFlagChunk) - -namespace IFF -{ - void IlbmTranChunk::Serialize(Archive * pArchv) - { - pArchv->Transfer(eTransType); - pArchv->Transfer(xPos); - pArchv->Transfer(yPos); - pArchv->Transfer(rgb); - } - - void IlbmAlphChunk::Serialize(Archive * pArchv) - { - pArchv->Transfer(width); - pArchv->Transfer(height); - pArchv->Transfer(nBitPlanes); - pArchv->Transfer(eCompression); - - IlbmBodyChunk::Serialize(pArchv); - } - - bool IlbmAlphChunk::GetHeaderInfo() const - { - IlbmBodyChunk::nWidth = width; - IlbmBodyChunk::eCompression = eCompression; - IlbmBodyChunk::nBitPlanes = nBitPlanes; - return true; - } - - void MipmContChunk::Serialize(Archive * pArchv) - { - pArchv->Transfer(nMipMaps); - pArchv->Transfer(eFilter); - } - - void MipmFlagChunk::Serialize(Archive * pArchv) - { - pArchv->Transfer(flags); - } - - IlbmS3tcChunk::IlbmS3tcChunk() - { - m_idCk = "S3TC"; - - pData = NULL; - dataSize = 0; - } - - IlbmS3tcChunk::~IlbmS3tcChunk() - { - if(pData) delete [] pData; - pData = NULL; - } - - void IlbmS3tcChunk::Serialize(Archive * pArchv) - { - pArchv->Transfer(flags); - pArchv->Transfer(fourCC); - pArchv->Transfer(redWeight); - pArchv->Transfer(blueWeight); - pArchv->Transfer(greenWeight); - pArchv->Transfer(width); - pArchv->Transfer(height); - - pArchv->Transfer(dataSize); - - if (pArchv->m_bIsLoading) - { - if(pData) delete [] pData; - pData = new UBYTE[dataSize]; - } - - UBYTE *pDataPos = pData; - for(unsigned i=0;i<dataSize;i++) - { - pArchv->Transfer(*pDataPos++); - } - } - -}
\ No newline at end of file diff --git a/3dc/win95/ILBM_ext.hpp b/3dc/win95/ILBM_ext.hpp deleted file mode 100644 index 3aefce7..0000000 --- a/3dc/win95/ILBM_ext.hpp +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef _INCLUDED_ILBM_EXT_HPP_ -#define _INCLUDED_ILBM_EXT_HPP_ - -#include "iff.hpp" -#include "iff_ILBM.hpp" - -namespace IFF -{ - class IlbmTranChunk : public Chunk - { - public: - enum - { - TRANS_NONE = 0, - TRANS_TOPLEFT = 1, - TRANS_BOTTOMLEFT = 2, - TRANS_TOPRIGHT = 3, - TRANS_BOTTOMRIGHT = 4, - TRANS_XY = 5, - TRANS_RGB = 6 - }; - UBYTE eTransType; - UINT16 xPos; - UINT16 yPos; - RGBTriple rgb; - - IlbmTranChunk() { m_idCk = "TRAN"; } - - protected: - virtual void Serialize(Archive * pArchv); - }; - - class IlbmAlphChunk : public IlbmBodyChunk // uses same encoding methodology - { - public: - UINT16 width; - UINT16 height; - UBYTE nBitPlanes; - UBYTE eCompression; - - IlbmAlphChunk() - { m_idCk = "ALPH"; } - - protected: - virtual void Serialize(Archive * pArchv); - - virtual bool GetHeaderInfo() const; - }; - - class IlbmS3tcChunk : public Chunk - { - public: - IlbmS3tcChunk(); - virtual ~IlbmS3tcChunk(); - - - - UINT32 flags; // none at the moment - UINT32 fourCC; //the fourcc code 'DXT1' - 'DXT5' - - UINT16 redWeight; //weighting values used in compression - UINT16 blueWeight; - UINT16 greenWeight; - - UINT16 width; - UINT16 height; - - UINT32 dataSize; - UBYTE* pData; //the compressed texture itself - - protected: - virtual void Serialize(Archive * pArchv); - }; - - - class MipmContChunk : public Chunk - { - public: - enum - { - FILTER_DEFAULT = 0, - FILTER_BOX = 1, - FILTER_TRIANGLE = 2, - FILTER_BELL = 3, - FILTER_BSPLINE = 4, - FILTER_LANCZOS3 = 5, - FILTER_MITCHELL = 6 - }; - UBYTE nMipMaps; - UBYTE eFilter; - - MipmContChunk() - { m_idCk = "CONT"; } - - protected: - virtual void Serialize(Archive * pArchv); - }; - - class MipmFlagChunk : public Chunk - { - public: - enum - { - FLAG_MANUAL_MIPS = 0x00000001,//some of the mip maps have been set by hand - }; - UINT32 flags; - - MipmFlagChunk() - { m_idCk = "FLAG"; flags = 0;} - - protected: - virtual void Serialize(Archive * pArchv); - }; - -} - -#endif diff --git a/3dc/win95/INLINE.H b/3dc/win95/INLINE.H deleted file mode 100644 index fdc5c60..0000000 --- a/3dc/win95/INLINE.H +++ /dev/null @@ -1,1246 +0,0 @@ -#ifndef INLINE_INCLUDED - -#if SUPPORT_MMX -#include "mmx_math.h" -#endif - -/* - - - Watcom PC Inline Functions. - - Watcom Standard C does not support the C++ "inline" directive, so these - functions have been written as inline assembler instead. - -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - Standard macros. Note that FIXED_TO_INT - and INT_TO_FIXED are very suboptimal in - this version!!! - Also, MUL_INT and ISR are ONLY intended - to be used in Win95 so that Saturn versions - of the same code can be compiled using calls - to hand optimised assembler functions, i.e. - for code that is never intended to be run on - a Saturn they are unnecessary. -*/ - -#define OUR_ABS(x) (((x) < 0) ? -(x) : (x)) -#define OUR_SIGN(x) (((x) < 0) ? -1 : +1) -#define OUR_INT_TO_FIXED(x) (int) ((x) * (65536)) -#define OUR_FIXED_TO_INT(x) (int) ((x) / (65536)) -#define OUR_MUL_INT(a, b) ((a) * (b)) -#define OUR_ISR(a, shift) ((a) >> (shift)) - - -/* - - win95\item.c functions - -*/ - -void InitialiseTriangleArrayData(void); -void* AllocateTriangleArrayData(int tasize); - - -/* - - General Triangle Array Handler Null Case / Error - -*/ - -void TriangleArrayNullOrError(TRIANGLEARRAY *tarr); - - -/* - - Item Polygon Triangle Array Functions - -*/ - -void Item_Polygon_PrepareTriangleArray_3(TRIANGLEARRAY *qarr); -void Item_Polygon_PrepareTriangleArray_4(TRIANGLEARRAY *qarr); -void Item_Polygon_PrepareTriangleArray_5(TRIANGLEARRAY *qarr); -void Item_Polygon_PrepareTriangleArray_6(TRIANGLEARRAY *qarr); -void Item_Polygon_PrepareTriangleArray_7(TRIANGLEARRAY *qarr); -void Item_Polygon_PrepareTriangleArray_8(TRIANGLEARRAY *qarr); -void Item_Polygon_PrepareTriangleArray_9(TRIANGLEARRAY *qarr); - - -/* - - Item Gouraud Polygon Triangle Array Functions - -*/ - -void Item_GouraudPolygon_PrepareTriangleArray_3(TRIANGLEARRAY *qarr); -void Item_GouraudPolygon_PrepareTriangleArray_4(TRIANGLEARRAY *qarr); -void Item_GouraudPolygon_PrepareTriangleArray_5(TRIANGLEARRAY *qarr); -void Item_GouraudPolygon_PrepareTriangleArray_6(TRIANGLEARRAY *qarr); -void Item_GouraudPolygon_PrepareTriangleArray_7(TRIANGLEARRAY *qarr); -void Item_GouraudPolygon_PrepareTriangleArray_8(TRIANGLEARRAY *qarr); -void Item_GouraudPolygon_PrepareTriangleArray_9(TRIANGLEARRAY *qarr); - -/* - - Item 2d Textured Polygon Triangle Array Functions - -*/ - -void Item_2dTexturedPolygon_PrepareTriangleArray_3(TRIANGLEARRAY *qarr); -void Item_2dTexturedPolygon_PrepareTriangleArray_4(TRIANGLEARRAY *qarr); -void Item_2dTexturedPolygon_PrepareTriangleArray_5(TRIANGLEARRAY *qarr); -void Item_2dTexturedPolygon_PrepareTriangleArray_6(TRIANGLEARRAY *qarr); -void Item_2dTexturedPolygon_PrepareTriangleArray_7(TRIANGLEARRAY *qarr); -void Item_2dTexturedPolygon_PrepareTriangleArray_8(TRIANGLEARRAY *qarr); -void Item_2dTexturedPolygon_PrepareTriangleArray_9(TRIANGLEARRAY *qarr); - -/* - - Item Gouraud 2d Textured Polygon Triangle Array Functions - -*/ - -void Item_Gouraud2dTexturedPolygon_PrepareTriangleArray_3(TRIANGLEARRAY *qarr); -void Item_Gouraud2dTexturedPolygon_PrepareTriangleArray_4(TRIANGLEARRAY *qarr); -void Item_Gouraud2dTexturedPolygon_PrepareTriangleArray_5(TRIANGLEARRAY *qarr); -void Item_Gouraud2dTexturedPolygon_PrepareTriangleArray_6(TRIANGLEARRAY *qarr); -void Item_Gouraud2dTexturedPolygon_PrepareTriangleArray_7(TRIANGLEARRAY *qarr); -void Item_Gouraud2dTexturedPolygon_PrepareTriangleArray_8(TRIANGLEARRAY *qarr); -void Item_Gouraud2dTexturedPolygon_PrepareTriangleArray_9(TRIANGLEARRAY *qarr); - - -/* - - Item 3d Textured Polygon Triangle Array Functions - -*/ - -void Item_3dTexturedPolygon_PrepareTriangleArray_3(TRIANGLEARRAY *qarr); -void Item_3dTexturedPolygon_PrepareTriangleArray_4(TRIANGLEARRAY *qarr); -void Item_3dTexturedPolygon_PrepareTriangleArray_5(TRIANGLEARRAY *qarr); -void Item_3dTexturedPolygon_PrepareTriangleArray_6(TRIANGLEARRAY *qarr); -void Item_3dTexturedPolygon_PrepareTriangleArray_7(TRIANGLEARRAY *qarr); -void Item_3dTexturedPolygon_PrepareTriangleArray_8(TRIANGLEARRAY *qarr); -void Item_3dTexturedPolygon_PrepareTriangleArray_9(TRIANGLEARRAY *qarr); - -/* - - Item Gouraud 3d Textured Polygon Triangle Array Functions - -*/ - -void Item_Gouraud3dTexturedPolygon_PrepareTriangleArray_3(TRIANGLEARRAY *qarr); -void Item_Gouraud3dTexturedPolygon_PrepareTriangleArray_4(TRIANGLEARRAY *qarr); -void Item_Gouraud3dTexturedPolygon_PrepareTriangleArray_5(TRIANGLEARRAY *qarr); -void Item_Gouraud3dTexturedPolygon_PrepareTriangleArray_6(TRIANGLEARRAY *qarr); -void Item_Gouraud3dTexturedPolygon_PrepareTriangleArray_7(TRIANGLEARRAY *qarr); -void Item_Gouraud3dTexturedPolygon_PrepareTriangleArray_8(TRIANGLEARRAY *qarr); -void Item_Gouraud3dTexturedPolygon_PrepareTriangleArray_9(TRIANGLEARRAY *qarr); - -/* - - Platform Specific 64-Bit Operator Functions - - Not all compilers support 64-bit operations, and some platforms may not - even support 64-bit numbers. Support for 64-bit operations is therefore - provided in the platform specific fucntions below. - - For C++ a mew class could be defined. However the current system is not - compiled as C++ and the Cygnus GNU C++ is not currently working. - -*/ - - -/* - These functions have been checked for suitability for - a Pentium and look as if they would pair up okay. - Might be worth a more detailed look at optimising - them though. - Obviously there is a problem with values not being - loaded into registers for these functions, but this - may be unavoidable for 64 bit values on a Watcom - platform. -*/ - - -#ifdef __WATCOMC__ /* inline assember for the Watcom compiler */ - -/* ADD */ - -void ADD_LL(LONGLONGCH *a, LONGLONGCH *b, LONGLONGCH *c); -# pragma aux ADD_LL = \ -"mov eax,[esi]" \ -"mov edx,[esi+4]" \ -"add eax,[edi]" \ -"adc edx,[edi+4]" \ -"mov [ebx],eax" \ -"mov [ebx+4],edx" \ -parm[esi] [edi] [ebx] \ -modify[eax edx]; - - -/* ADD ++ */ - -void ADD_LL_PP(LONGLONGCH *c, LONGLONGCH *a); -# pragma aux ADD_LL_PP = \ -"mov eax,[esi]" \ -"mov edx,[esi+4]" \ -"add [edi],eax" \ -"adc [edi+4],edx" \ -parm[edi] [esi] \ -modify[eax edx]; - - -/* SUB */ - -void SUB_LL(LONGLONGCH *a, LONGLONGCH *b, LONGLONGCH *c); -# pragma aux SUB_LL = \ -"mov eax,[esi]" \ -"mov edx,[esi+4]" \ -"sub eax,[edi]" \ -"sbb edx,[edi+4]" \ -"mov [ebx],eax" \ -"mov [ebx+4],edx" \ -parm[esi] [edi] [ebx] \ -modify[eax edx]; - - - -/* SUB -- */ - -void SUB_LL_MM(LONGLONGCH *c, LONGLONGCH *a); -# pragma aux SUB_LL_MM = \ -"mov eax,[esi]" \ -"mov edx,[esi+4]" \ -"sub [edi],eax" \ -"sbb [edi+4],edx" \ -parm[edi] [esi] \ -modify[eax edx]; - - -/* - - MUL - - This is the multiply we use, the 32 x 32 = 64 widening version - -*/ - -void MUL_I_WIDE(int a, int b, LONGLONGCH *c); -# pragma aux MUL_I_WIDE = \ -"imul edx"\ -"mov [ebx],eax" \ -"mov [ebx+4],edx" \ -parm[eax] [edx] [ebx] \ -modify[eax edx]; - - - -/* - - CMP - - This substitutes for ==, >, <, >=, <= - -*/ - -int CMP_LL(LONGLONGCH *a, LONGLONGCH *b); -# pragma aux CMP_LL = \ -"mov eax,[ebx]" \ -"mov edx,[ebx+4]" \ -"sub eax,[ecx]" \ -"sbb edx,[ecx+4]" \ -"and edx,edx" \ -"jne llnz" \ -"and eax,eax" \ -"jne llnz" \ -"xor eax,eax" \ -"jmp llgs" \ -"llnz:" \ -"mov eax,1" \ -"and edx,edx" \ -"jge llgs" \ -"neg eax" \ -"llgs:" \ -parm[ebx] [ecx] \ -value[eax] \ -modify[edx]; - - - - -/* EQUALS */ - -void EQUALS_LL(LONGLONGCH *a, LONGLONGCH *b); -# pragma aux EQUALS_LL = \ -"mov eax,[esi]" \ -"mov edx,[esi+4]" \ -"mov [edi],eax" \ -"mov [edi+4],edx" \ -parm[edi] [esi] \ -modify[eax edx]; - - -/* NEGATE */ - -void NEG_LL(LONGLONGCH *a); -# pragma aux NEG_LL = \ -"not dword ptr[esi]" \ -"not dword ptr[esi+4]" \ -"add dword ptr[esi],1" \ -"adc dword ptr[esi+4],0" \ -parm[esi]; - - -/* ASR */ - -void ASR_LL(LONGLONGCH *a, int shift); -# pragma aux ASR_LL = \ -"and eax,eax" \ -"jle asrdn" \ -"asrlp:" \ -"sar dword ptr[esi+4],1" \ -"rcr dword ptr[esi],1" \ -"dec eax" \ -"jne asrlp" \ -"asrdn:" \ -parm[esi] [eax]; - - -/* Convert int to LONGLONGCH */ - -void IntToLL(LONGLONGCH *a, int *b); -# pragma aux IntToLL = \ -"mov eax,[esi]" \ -"cdq" \ -"mov [edi],eax" \ -"mov [edi+4],edx" \ -parm[edi] [esi] \ -modify[eax edx]; - - - - - - - - - -/* - - Fixed Point Multiply. - - - 16.16 * 16.16 -> 16.16 - or - 16.16 * 0.32 -> 0.32 - - A proper version of this function ought to read - 16.16 * 16.16 -> 32.16 - but this would require a long long result - - Algorithm: - - Take the mid 32 bits of the 64 bit result - -*/ - -/* - These functions have been checked for suitability for - a Pentium and look as if they would work adequately. - Might be worth a more detailed look at optimising - them though. -*/ - -#if 0 - -int MUL_FIXED(int a, int b); -# pragma aux MUL_FIXED = \ -"imul edx" \ -"mov ax,dx" \ -"rol eax,16" \ -parm[eax] [edx] \ -value[eax] \ -modify[edx]; - -#else - -int MUL_FIXED(int a, int b); -# pragma aux MUL_FIXED = \ -"imul edx" \ -"shrd eax,edx,16" \ -parm[eax] [edx] \ -value[eax] \ -modify[edx]; - -#endif - - -/* - - Fixed Point Divide - returns a / b - -*/ - -int DIV_FIXED(int a, int b); -# pragma aux DIV_FIXED = \ -"cdq" \ -"rol eax,16" \ -"mov dx,ax" \ -"xor ax,ax" \ -"idiv ebx" \ -parm[eax] [ebx] \ -value[eax] \ -modify[edx]; - - - - -/* - - Multiply and Divide Functions. - -*/ - - -/* - - 32/32 division - - This macro is a function on some other platforms - -*/ - -#define DIV_INT(a, b) ((a) / (b)) - - - - -/* - - A Narrowing 64/32 Division - -*/ - -int NarrowDivide(LONGLONGCH *a, int b); -# pragma aux NarrowDivide = \ -"mov eax,[esi]" \ -"mov edx,[esi+4]" \ -"idiv ebx" \ -parm[esi] [ebx] \ -value[eax] \ -modify[edx]; - - - -/* - - This function performs a Widening Multiply followed by a Narrowing Divide. - - a = (a * b) / c - -*/ - -int WideMulNarrowDiv(int a, int b, int c); -# pragma aux WideMulNarrowDiv = \ -"imul edx"\ -"idiv ebx" \ -parm[eax] [edx] [ebx] \ -value[eax]; - - - -/* - - Function to rotate a VECTORCH using a MATRIXCH - - This is the C function - - x = MUL_FIXED(m->mat11, v->vx); - x += MUL_FIXED(m->mat21, v->vy); - x += MUL_FIXED(m->mat31, v->vz); - - y = MUL_FIXED(m->mat12, v->vx); - y += MUL_FIXED(m->mat22, v->vy); - y += MUL_FIXED(m->mat32, v->vz); - - z = MUL_FIXED(m->mat13, v->vx); - z += MUL_FIXED(m->mat23, v->vy); - z += MUL_FIXED(m->mat33, v->vz); - - v->vx = x; - v->vy = y; - v->vz = z; - - This is the MUL_FIXED inline assembler function - - imul edx - shrd eax,edx,16 - - -typedef struct matrixch { - - int mat11; 0 - int mat12; 4 - int mat13; 8 - - int mat21; 12 - int mat22; 16 - int mat23; 20 - - int mat31; 24 - int mat32; 28 - int mat33; 32 - -} MATRIXCH; - -*/ - -void RotateVector_ASM(VECTORCH *v, MATRIXCH *m); -# pragma aux RotateVector_ASM = \ -\ -"push eax" \ -"push ebx" \ -"push ecx" \ -"push edx" \ -"push ebp" \ -\ -"mov eax,[edi + 0]" \ -"imul DWORD PTR [esi + 0]" \ -"shrd eax,edx,16" \ -"mov ecx,eax"\ -"mov eax,[edi + 12]" \ -"imul DWORD PTR [esi + 4]" \ -"shrd eax,edx,16" \ -"add ecx,eax" \ -"mov eax,[edi + 24]" \ -"imul DWORD PTR [esi + 8]" \ -"shrd eax,edx,16" \ -"add ecx,eax" \ -\ -"mov eax,[edi + 4]" \ -"imul DWORD PTR [esi + 0]" \ -"shrd eax,edx,16" \ -"mov ebx,eax"\ -"mov eax,[edi + 16]" \ -"imul DWORD PTR [esi + 4]" \ -"shrd eax,edx,16" \ -"add ebx,eax" \ -"mov eax,[edi + 28]" \ -"imul DWORD PTR [esi + 8]" \ -"shrd eax,edx,16" \ -"add ebx,eax" \ -\ -"mov eax,[edi + 8]" \ -"imul DWORD PTR [esi + 0]" \ -"shrd eax,edx,16" \ -"mov ebp,eax"\ -"mov eax,[edi + 20]" \ -"imul DWORD PTR [esi + 4]" \ -"shrd eax,edx,16" \ -"add ebp,eax" \ -"mov eax,[edi + 32]" \ -"imul DWORD PTR [esi + 8]" \ -"shrd eax,edx,16" \ -"add ebp,eax" \ -\ -"mov [esi + 0],ecx" \ -"mov [esi + 4],ebx" \ -"mov [esi + 8],ebp" \ -\ -"pop ebp" \ -"pop edx" \ -"pop ecx" \ -"pop ebx" \ -"pop eax" \ -\ -parm[esi] [edi]; - - -/* - - Here is the same function, this time copying the result to a second vector - -*/ - -void RotateAndCopyVector_ASM(VECTORCH *v1, VECTORCH *v2, MATRIXCH *m); -# pragma aux RotateAndCopyVector_ASM = \ -\ -"push eax" \ -"push ebx" \ -"push ecx" \ -"push ebp" \ -\ -"push edx" \ -"mov eax,[edi + 0]" \ -"imul DWORD PTR [esi + 0]" \ -"shrd eax,edx,16" \ -"mov ecx,eax"\ -"mov eax,[edi + 12]" \ -"imul DWORD PTR [esi + 4]" \ -"shrd eax,edx,16" \ -"add ecx,eax" \ -"mov eax,[edi + 24]" \ -"imul DWORD PTR [esi + 8]" \ -"shrd eax,edx,16" \ -"add ecx,eax" \ -\ -"mov eax,[edi + 4]" \ -"imul DWORD PTR [esi + 0]" \ -"shrd eax,edx,16" \ -"mov ebx,eax"\ -"mov eax,[edi + 16]" \ -"imul DWORD PTR [esi + 4]" \ -"shrd eax,edx,16" \ -"add ebx,eax" \ -"mov eax,[edi + 28]" \ -"imul DWORD PTR [esi + 8]" \ -"shrd eax,edx,16" \ -"add ebx,eax" \ -\ -"mov eax,[edi + 8]" \ -"imul DWORD PTR [esi + 0]" \ -"shrd eax,edx,16" \ -"mov ebp,eax"\ -"mov eax,[edi + 20]" \ -"imul DWORD PTR [esi + 4]" \ -"shrd eax,edx,16" \ -"add ebp,eax" \ -"mov eax,[edi + 32]" \ -"imul DWORD PTR [esi + 8]" \ -"shrd eax,edx,16" \ -"add ebp,eax" \ -\ -"pop edx" \ -"mov [edx + 0],ecx" \ -"mov [edx + 4],ebx" \ -"mov [edx + 8],ebp" \ -\ -"pop ebp" \ -"pop ecx" \ -"pop ebx" \ -"pop eax" \ -\ -parm[esi] [edx] [edi]; - - - - -#if (SupportFPMathsFunctions || SupportFPSquareRoot) - -/* - - Square Root - - Returns the Square Root of a 32-bit number - -*/ - -static long temp; -static long temp2; - -int SqRoot32(int A); -# pragma aux SqRoot32 = \ -"finit" \ -"mov temp,eax" \ -"fild temp" \ -"fsqrt" \ -"fistp temp2" \ -"fwait" \ -"mov eax,temp2" \ -parm[eax] \ -value[eax]; - -#endif - - -/* - - This may look ugly (it is) but it is a MUCH faster way to convert "float" into "int" than - the function call "CHP" used by the WATCOM compiler. - -*/ - -static float fptmp; -static int itmp; - -void FloatToInt(void); -# pragma aux FloatToInt = \ -"fld fptmp" \ -"fistp itmp"; - -/* - - This macro makes usage of the above function easier and more elegant - -*/ - -#define f2i(a, b) { \ -fptmp = (b); \ -FloatToInt(); \ -a = itmp;} - -#elif defined(_MSC_VER) /* inline assember for the Microsoft compiler */ - -/* ADD */ - -static void ADD_LL(LONGLONGCH *a, LONGLONGCH *b, LONGLONGCH *c) -{ - _asm - { - mov esi,a - mov edi,b - mov ebx,c - mov eax,[esi] - mov edx,[esi+4] - add eax,[edi] - adc edx,[edi+4] - mov [ebx],eax - mov [ebx+4],edx - } -} - -/* ADD ++ */ - -static void ADD_LL_PP(LONGLONGCH *c, LONGLONGCH *a) -{ - _asm - { - mov edi,c - mov esi,a - mov eax,[esi] - mov edx,[esi+4] - add [edi],eax - adc [edi+4],edx - } -} - -/* SUB */ - -static void SUB_LL(LONGLONGCH *a, LONGLONGCH *b, LONGLONGCH *c) -{ - _asm - { - mov esi,a - mov edi,b - mov ebx,c - mov eax,[esi] - mov edx,[esi+4] - sub eax,[edi] - sbb edx,[edi+4] - mov [ebx],eax - mov [ebx+4],edx - } -} - -/* SUB -- */ - -static void SUB_LL_MM(LONGLONGCH *c, LONGLONGCH *a) -{ - _asm - { - mov edi,c - mov esi,a - mov eax,[esi] - mov edx,[esi+4] - sub [edi],eax - sbb [edi+4],edx - } -} - -/* - - MUL - - This is the multiply we use, the 32 x 32 = 64 widening version - -*/ - -static void MUL_I_WIDE(int a, int b, LONGLONGCH *c) -{ - _asm - { - mov eax,a - mov ebx,c - imul b - mov [ebx],eax - mov [ebx+4],edx - } -} - -/* - - CMP - - This substitutes for ==, >, <, >=, <= - -*/ - -static int CMP_LL(LONGLONGCH *a, LONGLONGCH *b) -{ - int retval = 0; - _asm - { - mov ebx,a - mov ecx,b - mov eax,[ebx] - mov edx,[ebx+4] - sub eax,[ecx] - sbb edx,[ecx+4] - and edx,edx - jne llnz - and eax,eax - je llgs - llnz: - mov retval,1 - and edx,edx - jge llgs - neg retval - llgs: - } - return retval; -} - -/* EQUALS */ - -static void EQUALS_LL(LONGLONGCH *a, LONGLONGCH *b) -{ - _asm - { - mov edi,a - mov esi,b - mov eax,[esi] - mov edx,[esi+4] - mov [edi],eax - mov [edi+4],edx - } -} - -/* NEGATE */ - -static void NEG_LL(LONGLONGCH *a) -{ - _asm - { - mov esi,a - not dword ptr[esi] - not dword ptr[esi+4] - add dword ptr[esi],1 - adc dword ptr[esi+4],0 - } -} - -/* ASR */ - -static void ASR_LL(LONGLONGCH *a, int shift) -{ - _asm - { - mov esi,a - mov eax,shift - and eax,eax - jle asrdn - asrlp: - sar dword ptr[esi+4],1 - rcr dword ptr[esi],1 - dec eax - jne asrlp - asrdn: - } -} - -/* Convert int to LONGLONGCH */ - -static void IntToLL(LONGLONGCH *a, int *b) -{ - _asm - { - mov esi,b - mov edi,a - mov eax,[esi] - cdq - mov [edi],eax - mov [edi+4],edx - } -} - -/* - - Fixed Point Multiply. - - - 16.16 * 16.16 -> 16.16 - or - 16.16 * 0.32 -> 0.32 - - A proper version of this function ought to read - 16.16 * 16.16 -> 32.16 - but this would require a long long result - - Algorithm: - - Take the mid 32 bits of the 64 bit result - -*/ - -/* - These functions have been checked for suitability for - a Pentium and look as if they would work adequately. - Might be worth a more detailed look at optimising - them though. -*/ - -static int MUL_FIXED(int a, int b) -{ - int retval; - _asm - { - mov eax,a - imul b - shrd eax,edx,16 - mov retval,eax - } - return retval; -} - -/* - - Fixed Point Divide - returns a / b - -*/ - -static int DIV_FIXED(int a, int b) -{ - int retval; - _asm - { - mov eax,a - cdq - rol eax,16 - mov dx,ax - xor ax,ax - idiv b - mov retval,eax - } - return retval; -} - -/* - - Multiply and Divide Functions. - -*/ - - -/* - - 32/32 division - - This macro is a function on some other platforms - -*/ - -#define DIV_INT(a, b) ((a) / (b)) - -/* - - A Narrowing 64/32 Division - -*/ - -static int NarrowDivide(LONGLONGCH *a, int b) -{ - int retval; - _asm - { - mov esi,a - mov eax,[esi] - mov edx,[esi+4] - idiv b - mov retval,eax - } - return retval; -} - -/* - - This function performs a Widening Multiply followed by a Narrowing Divide. - - a = (a * b) / c - -*/ - -static int WideMulNarrowDiv(int a, int b, int c) -{ - int retval; - _asm - { - mov eax,a - imul b - idiv c - mov retval,eax - } - return retval; -} - -/* - - Function to rotate a VECTORCH using a MATRIXCH - - This is the C function - - x = MUL_FIXED(m->mat11, v->vx); - x += MUL_FIXED(m->mat21, v->vy); - x += MUL_FIXED(m->mat31, v->vz); - - y = MUL_FIXED(m->mat12, v->vx); - y += MUL_FIXED(m->mat22, v->vy); - y += MUL_FIXED(m->mat32, v->vz); - - z = MUL_FIXED(m->mat13, v->vx); - z += MUL_FIXED(m->mat23, v->vy); - z += MUL_FIXED(m->mat33, v->vz); - - v->vx = x; - v->vy = y; - v->vz = z; - - This is the MUL_FIXED inline assembler function - - imul edx - shrd eax,edx,16 - - -typedef struct matrixch { - - int mat11; 0 - int mat12; 4 - int mat13; 8 - - int mat21; 12 - int mat22; 16 - int mat23; 20 - - int mat31; 24 - int mat32; 28 - int mat33; 32 - -} MATRIXCH; - -*/ - -static void RotateVector_ASM(VECTORCH *v, MATRIXCH *m) -{ - _asm - { - mov esi,v - mov edi,m - - mov eax,[edi + 0] - imul DWORD PTR [esi + 0] - shrd eax,edx,16 - mov ecx,eax - mov eax,[edi + 12] - imul DWORD PTR [esi + 4] - shrd eax,edx,16 - add ecx,eax - mov eax,[edi + 24] - imul DWORD PTR [esi + 8] - shrd eax,edx,16 - add ecx,eax - - mov eax,[edi + 4] - imul DWORD PTR [esi + 0] - shrd eax,edx,16 - mov ebx,eax - mov eax,[edi + 16] - imul DWORD PTR [esi + 4] - shrd eax,edx,16 - add ebx,eax - mov eax,[edi + 28] - imul DWORD PTR [esi + 8] - shrd eax,edx,16 - add ebx,eax - - mov eax,[edi + 8] - imul DWORD PTR [esi + 0] - shrd eax,edx,16 - mov ebp,eax - mov eax,[edi + 20] - imul DWORD PTR [esi + 4] - shrd eax,edx,16 - add ebp,eax - mov eax,[edi + 32] - imul DWORD PTR [esi + 8] - shrd eax,edx,16 - add ebp,eax - - mov [esi + 0],ecx - mov [esi + 4],ebx - mov [esi + 8],ebp - } -} - -/* - - Here is the same function, this time copying the result to a second vector - -*/ - -static void RotateAndCopyVector_ASM(VECTORCH *v1, VECTORCH *v2, MATRIXCH *m) -{ - _asm - { - mov esi,v1 - mov edi,m - - mov eax,[edi + 0] - imul DWORD PTR [esi + 0] - shrd eax,edx,16 - mov ecx,eax - mov eax,[edi + 12] - imul DWORD PTR [esi + 4] - shrd eax,edx,16 - add ecx,eax - mov eax,[edi + 24] - imul DWORD PTR [esi + 8] - shrd eax,edx,16 - add ecx,eax - - mov eax,[edi + 4] - imul DWORD PTR [esi + 0] - shrd eax,edx,16 - mov ebx,eax - mov eax,[edi + 16] - imul DWORD PTR [esi + 4] - shrd eax,edx,16 - add ebx,eax - mov eax,[edi + 28] - imul DWORD PTR [esi + 8] - shrd eax,edx,16 - add ebx,eax - - mov eax,[edi + 8] - imul DWORD PTR [esi + 0] - shrd eax,edx,16 - mov ebp,eax - mov eax,[edi + 20] - imul DWORD PTR [esi + 4] - shrd eax,edx,16 - add ebp,eax - mov eax,[edi + 32] - imul DWORD PTR [esi + 8] - shrd eax,edx,16 - add ebp,eax - - mov edx,v2 - mov [edx + 0],ecx - mov [edx + 4],ebx - mov [edx + 8],ebp - } -} - -#if (SupportFPMathsFunctions || SupportFPSquareRoot) - -/* - - Square Root - - Returns the Square Root of a 32-bit number - -*/ - -static long temp; -static long temp2; - -static int SqRoot32(int A) -{ - _asm - { - finit - fild A - fsqrt - fistp temp2 - fwait - } - return (int)temp2; -} - -#endif - - -/* - - This may look ugly (it is) but it is a MUCH faster way to convert "float" into "int" than - the function call "CHP" used by the WATCOM compiler. - -*/ - -static float fptmp; -static int itmp; - -static void FloatToInt(void) -{ - _asm - { - fld fptmp - fistp itmp - } -} - -/* - - This macro makes usage of the above function easier and more elegant - -*/ - -#define f2i(a, b) { \ -fptmp = (b); \ -FloatToInt(); \ -a = itmp;} - -#else /* other compiler ? */ - -#error "Unknown compiler" - -#endif - - -/* These functions are in plspecfn.c */ - -int WideMul2NarrowDiv(int a, int b, int c, int d, int e); -int _Dot(VECTORCH *vptr1, VECTORCH *vptr2); -void MakeV(VECTORCH *v1, VECTORCH *v2, VECTORCH *v3); -void AddV(VECTORCH *v1, VECTORCH *v2); -void RotVect(VECTORCH *v, MATRIXCH *m); -void CopyClipPoint(CLIP_POINT *cp1, CLIP_POINT *cp2); - -#if SUPPORT_MMX - -#define RotateVector(v,m) (use_mmx_math ? MMX_VectorTransform((v),(m)) : _RotateVector((v),(m))) -#define RotateAndCopyVector(v_in,v_out,m) (use_mmx_math ? MMX_VectorTransformed((v_out),(v_in),(m)) : _RotateAndCopyVector((v_in),(v_out),(m))) -#define Dot(v1,v2) (use_mmx_math ? MMXInline_VectorDot((v1),(v2)) : _Dot((v1),(v2))) -#define DotProduct(v1,v2) (use_mmx_math ? MMX_VectorDot((v1),(v2)) : _DotProduct((v1),(v2))) - -#else /* ! SUPPORT_MMX */ - -#define RotateVector(v,m) (_RotateVector((v),(m))) -#define RotateAndCopyVector(v_in,v_out,m) (_RotateAndCopyVector((v_in),(v_out),(m))) -#define Dot(v1,v2) (_Dot((v1),(v2))) -#define DotProduct(v1,v2) (_DotProduct((v1),(v2))) - -#endif /* ? SUPPORT_MMX */ - -#ifdef __cplusplus -} -#endif - -#define INLINE_INCLUDED -#endif - diff --git a/3dc/win95/KRENDER.H b/3dc/win95/KRENDER.H deleted file mode 100644 index ebd5dc1..0000000 --- a/3dc/win95/KRENDER.H +++ /dev/null @@ -1,55 +0,0 @@ -/* If this define is set to a non-zero value then the new scandraws will be used */ -#define KRENDER_ON 1 - -/* prototypes of the replacement scandraw functions */ -extern void KR_ScanDraw_Item_2dTexturePolygon_VideoModeType_8(int *itemptr); -extern void KR_ScanDraw_Item_Gouraud2dTexturePolygon_VideoModeType_8(int *itemptr); -extern void KR_ScanDraw_Item_Gouraud3dTexturePolygon_Linear_S_VideoModeType_8(int *itemptr); -extern void MotionTrackerRotateBlit(void); -extern void MotionTrackerRotateBlit8(void); - - -/*KJL***************************************************** -* Palette fading; a value of 65536 corresponds to normal * -* palette, 0 is completely other (eg. all white). * -*****************************************************KJL*/ -extern void SetPaletteFadeLevel(int fadeLevel); -extern void FadeBetweenPalettes(unsigned char *palPtr, int fadeLevel); -extern void FadePaletteToWhite(unsigned char *palPtr,int fadeLevel); - -/*KJL********************************************* -* Fill the screen with black & flip then repeat. * -*********************************************KJL*/ -extern void BlankScreen(void); - - -/* KJL 16:06:24 04/04/97 - To choose between laced and full screen modes */ -extern int KRenderDrawMode; - - - - - - -extern void KDraw_Item_GouraudPolygon(int *itemptr); -extern void KDraw_Item_2dTexturePolygon(int *itemptr); -extern void KDraw_Item_Gouraud2dTexturePolygon(int *itemptr); -extern void KDraw_Item_Gouraud3dTexturePolygon(int *itemptr); - - - - - - - - - - - - -extern void MakeViewingWindowSmaller(void); -extern void MakeViewingWindowLarger(void); - -/* routines to draw a star filled sky */ -extern void CreateStarArray(void); -extern void DrawStarfilledSky(void);
\ No newline at end of file diff --git a/3dc/win95/Krender.c b/3dc/win95/Krender.c deleted file mode 100644 index a52c1d5..0000000 --- a/3dc/win95/Krender.c +++ /dev/null @@ -1,2830 +0,0 @@ -/*KJL********************************************************************* -* krender.c - Kevin's scandrawing code. (New render, new danger.) * -* * -* The new scandraws are called by patching the functions below into the * -* jumptables used in item.c. If the KRENDER_ON flag in krender.h is zero * -* then the old scandraws will be used. * -*********************************************************************KJL*/ - -/* this file is a bit messy at the moment, but I'll be back later... */ -#include "3dc.h" -#include "inline.h" -#include "module.h" -#include "gamedef.h" -#include "krender.h" -#include "vision.h" - -#define UseLocalAssert Yes -#include "ourasert.h" - -#define PENTIUM_PROFILING_ON 0 -#if PENTIUM_PROFILING_ON -#include "pentime.h" -#else -#define ProfileStart(); -#define ProfileStop(x); -#endif - -int ReciprocalTable[321]; -#if 1 -#define DIVIDE(a,b) ((a)/(b)) -#else -#define DIVIDE(a,b) (MUL_FIXED((a),ReciprocalTable[(b)])) -#endif - - -int Transparent; - -/* assembler fns */ -extern void ScanDraw2D_Gouraud(void); -extern void ScanDraw2D_GouraudTransparent(void); -extern void ScanDraw2D_VAlignedTransparent(void); -extern void ScanDraw2D_VAlignedOpaque(void); -extern void ScanDraw2D_Transparent(void); -extern void ScanDraw2D_TransparentLit(void); -extern void ScanDraw2D_Opaque(void); -extern void ScanDraw_GouraudScan(void); -extern void ScanDrawF3D_Gouraud(void); - -/* globals accessed by the assembler routines */ -unsigned char *SCASM_Lighting; -unsigned char *SCASM_Destination; -unsigned char *SCASM_Bitmap; -int SCASM_StartU; -int SCASM_StartV; -int SCASM_StartI; -int SCASM_DeltaU; -int SCASM_DeltaV; -int SCASM_DeltaI; -int SCASM_ScanLength; -int SCASM_ShadingTableSize; -int SCASM_TextureDeltaScan; - -/* things from item.c */ -extern int NumScans; -extern int ItemColour; -extern IMAGEHEADER *ImageHeaderPtrs[MaxImages]; -extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; -extern unsigned char *TextureLightingTable; -extern int MIP_Index; -extern int ScanData[maxpolys*maxscansize]; -extern unsigned char *ScreenBuffer; -extern long BackBufferPitch; - -void Draw_Gouraud3dTexture_Spans(int *itemptr); - -int KRenderDrawMode = 0; - -/***********/ - -void KR_ScanDraw_Item_Gouraud2dTexturePolygon_VideoModeType_8(int *itemptr) -{ - POLYHEADER *pheader = (POLYHEADER *) itemptr; - I_GOURAUD2DTEXTUREPOLYGON_SCAN *sptr; - - if(NumScans) - { - int y = NumScans; - /* Get the Image Data required for the Draw */ - { - IMAGEHEADER *ImageHdr; - { - int TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - } - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - TEXTURE **TxImagePtr = &ImageHdr->ImagePtr; - SCASM_Bitmap = TxImagePtr[MIP_Index]; - GLOBALASSERT(SCASM_Bitmap); - SCASM_TextureDeltaScan = ImageHdr->ImageWidth >> MIP_Index; - #if MIP_ROUNDUP - if (ImageHdr->ImageWidth & (1<<MIP_Index)-1) ++SCASM_TextureDeltaScan; - #endif - - - } - else - { - SCASM_TextureDeltaScan = ImageHdr->ImageWidth; - SCASM_Bitmap = ImageHdr->ImagePtr; - GLOBALASSERT(SCASM_Bitmap); - } - } - SCASM_Lighting = TextureLightingTable; - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_Raw256) SCASM_ShadingTableSize = 256; - else SCASM_ShadingTableSize = 64; - - sptr = (I_GOURAUD2DTEXTUREPOLYGON_SCAN *) ScanData; - do - { - int dx = sptr->ig2s_x2 - sptr->ig2s_x1; - if (dx>0 && !(sptr->ig2s_y & KRenderDrawMode) ) - { - /* Fixed Point U for Interpolation */ - { - int StartU = sptr->ig2s_u1; - SCASM_DeltaU = DIVIDE((sptr->ig2s_u2 - StartU),dx); - SCASM_StartU = StartU; - } - - /* Fixed Point V for Interpolation */ - { - int StartV = sptr->ig2s_v1; - SCASM_DeltaV = DIVIDE((sptr->ig2s_v2 - StartV),dx); - SCASM_StartV = StartV; - } - /* Fixed Point I for Interpolation */ - { - int StartI = sptr->ig2s_c1; - SCASM_DeltaI = DIVIDE((sptr->ig2s_c2 - StartI),dx); - SCASM_StartI = StartI; - } - /* Draw the Gouraud 2d Texture Scan */ - - SCASM_Destination = ScreenBuffer + (sptr->ig2s_y * BackBufferPitch) + sptr->ig2s_x1; - SCASM_ScanLength = dx; - - if(pheader->PolyFlags & iflag_ignore0) - { - ScanDraw2D_GouraudTransparent(); - } - else - { - ScanDraw2D_Gouraud(); - } - } - sptr++; - y--; - } - while(y); - } - -} - -void Draw3DScan(I_GOURAUD3DTEXTUREPOLYGON_SCAN *scanPtr, POLYHEADER *pheader) -{ - int dx = scanPtr->ig3s_x2 - scanPtr->ig3s_x1; - - if(dx > 0) - { - float uf; - float vf; - float uf2; - float vf2; - /* Get start and end UVs */ - { - float ooz1; - ooz1 = 65536.0 / scanPtr->ig3s_z1; - uf = scanPtr->ig3s_u1 * ooz1; - vf = scanPtr->ig3s_v1 * ooz1; - } - { - float ooz2; - ooz2 = 65536.0 / scanPtr->ig3s_z2; - uf2 = scanPtr->ig3s_u2 * ooz2; - vf2 = scanPtr->ig3s_v2 * ooz2; - } - if ( (uf>16700000.0) - ||(uf<0.0) - ||(vf>16700000.0) - ||(vf<0.0) ) - { - textprint("WARNING: UV coords invalid\n"); - // LOCALASSERT(0); - return; - } - if ( (uf2>16700000.0) - ||(uf2<0.0) - ||(vf2>16700000.0) - ||(vf2<0.0) ) - { - textprint("WARNING: UV coords invalid\n"); - // LOCALASSERT(0); - return; - } - /* For UV interpolation */ - f2i(SCASM_StartU,uf); - f2i(SCASM_StartV,vf); - { - int EndU,EndV; - f2i(EndU,uf2); - f2i(EndV,vf2); - SCASM_DeltaU =(EndU-SCASM_StartU)/dx; - SCASM_DeltaV =(EndV-SCASM_StartV)/dx; - } - - /* Fixed Point I for Interpolation */ - { - int StartI = scanPtr->ig3s_c1; - SCASM_DeltaI = (scanPtr->ig3s_c2 - StartI)/dx; - SCASM_StartI = StartI; - } - - /* Draw the 3d Texture Scan */ - SCASM_Destination = ScreenBuffer + (scanPtr->ig3s_y * BackBufferPitch) + scanPtr->ig3s_x1; - SCASM_ScanLength = dx; - - if(pheader->PolyFlags & iflag_ignore0) - { - ScanDraw2D_GouraudTransparent(); - } - else - { - ScanDraw2D_Gouraud(); - } - } -} - - -void KR_ScanDraw_Item_Gouraud3dTexturePolygon_Linear_S_VideoModeType_8(int *itemptr) -{ - POLYHEADER *pheader = (POLYHEADER *) itemptr; - - int num_scans_s; - I_GOURAUD3DTEXTUREPOLYGON_SCAN *sptr_array_ptr; - I_GOURAUD3DTEXTUREPOLYGON_SCAN *next_free_sptr; - I_GOURAUD3DTEXTUREPOLYGON_SCAN sptr_array[lin_s_max + 1]; - int StillSubdividing; - int i; - - - if(NumScans) - { - I_GOURAUD3DTEXTUREPOLYGON_SCAN *sptr; - int y; - /* Get the Image Data required for the Draw */ - { - IMAGEHEADER *ImageHdr; - { - int TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - } - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - TEXTURE **TxImagePtr = &ImageHdr->ImagePtr; - SCASM_Bitmap = TxImagePtr[MIP_Index]; - GLOBALASSERT(SCASM_Bitmap); - SCASM_TextureDeltaScan = ImageHdr->ImageWidth >> MIP_Index; - #if MIP_ROUNDUP - if (ImageHdr->ImageWidth & (1<<MIP_Index)-1) ++SCASM_TextureDeltaScan; - #endif - - } - else - { - SCASM_TextureDeltaScan = ImageHdr->ImageWidth; - SCASM_Bitmap = ImageHdr->ImagePtr; - GLOBALASSERT(SCASM_Bitmap); - } - } - SCASM_Lighting = TextureLightingTable; - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_Raw256) SCASM_ShadingTableSize = 256; - else SCASM_ShadingTableSize = 64; - - - sptr = (I_GOURAUD3DTEXTUREPOLYGON_SCAN *) ScanData; - - for(y = NumScans; y!=0; y--) - { - int dx = sptr->ig3s_x2 - sptr->ig3s_x1; - if (dx>0 && !(sptr->ig3s_y & KRenderDrawMode) ) - { - float zmax, zmin, z_ratio; - - /* Have a look at the z-ratio */ - if(sptr->ig3s_z1 > sptr->ig3s_z2) - { - zmax = sptr->ig3s_z1; - zmin = sptr->ig3s_z2; - } - else - { - zmax = sptr->ig3s_z2; - zmin = sptr->ig3s_z1; - } - z_ratio = (zmax * 256); - - - /* Draw if the z ratio is inside the threshold */ - if(z_ratio < lin_s_zthr*zmin) - { - Draw3DScan(sptr,pheader); - } - /* Else subdivide until scan segments are inside threshold */ - else - { - /* Copy the current scan to the subdivision array */ - sptr_array_ptr = sptr_array; - num_scans_s = 1; - - sptr_array_ptr->ig3s_u1 = sptr->ig3s_u1; - sptr_array_ptr->ig3s_v1 = sptr->ig3s_v1; - sptr_array_ptr->ig3s_z1 = sptr->ig3s_z1; - sptr_array_ptr->ig3s_c1 = sptr->ig3s_c1; - - sptr_array_ptr->ig3s_u2 = sptr->ig3s_u2; - sptr_array_ptr->ig3s_v2 = sptr->ig3s_v2; - sptr_array_ptr->ig3s_z2 = sptr->ig3s_z2; - sptr_array_ptr->ig3s_c2 = sptr->ig3s_c2; - - sptr_array_ptr->ig3s_x1 = sptr->ig3s_x1; - sptr_array_ptr->ig3s_x2 = sptr->ig3s_x2; - - sptr_array_ptr->ig3s_y = sptr->ig3s_y; - - - /* Subdivide until no further divisions are needed */ - - next_free_sptr = sptr_array_ptr + 1; - do - { - sptr_array_ptr = sptr_array; - - StillSubdividing = No; /* Assume not */ - - for(i = num_scans_s; i!=0; i--) - { - #if 0 - /* z ratio of this scan */ - if(sptr_array_ptr->ig3s_z1 > sptr_array_ptr->ig3s_z2) - { - z_ratio = (sptr_array_ptr->ig3s_z1 * 256) / - sptr_array_ptr->ig3s_z2; - } - else - { - z_ratio = (sptr_array_ptr->ig3s_z2 * 256) / - sptr_array_ptr->ig3s_z1; - } - /* Is it within the threshold? */ - if(z_ratio > lin_s_zthr && num_scans_s < lin_s_max) - #endif - int overThreshold=0; - /* z ratio of this scan */ - if(sptr_array_ptr->ig3s_z1 > sptr_array_ptr->ig3s_z2) - { - if ( (sptr_array_ptr->ig3s_z1 * 256) > (lin_s_zthr*sptr_array_ptr->ig3s_z2)) - overThreshold=1; - } - else - { - if ( (sptr_array_ptr->ig3s_z2 * 256) > (lin_s_zthr*sptr_array_ptr->ig3s_z1)) - overThreshold=1; - } - /* Is it within the threshold? */ - if(overThreshold && num_scans_s < lin_s_max) - { - int mid_x, mid_c; - float mid_u, mid_v, mid_z; - /* No - subdivide */ - StillSubdividing = Yes; - - mid_u = (sptr_array_ptr->ig3s_u1 + sptr_array_ptr->ig3s_u2) / 2; - - mid_v = (sptr_array_ptr->ig3s_v1 + sptr_array_ptr->ig3s_v2) / 2; - - mid_z = (sptr_array_ptr->ig3s_z1 + sptr_array_ptr->ig3s_z2) / 2; - - mid_c = (sptr_array_ptr->ig3s_c1 + sptr_array_ptr->ig3s_c2) / 2; - - mid_x = (sptr_array_ptr->ig3s_x1 + sptr_array_ptr->ig3s_x2) / 2; - - /* Create new scan */ - - next_free_sptr->ig3s_u1 = mid_u; - next_free_sptr->ig3s_v1 = mid_v; - next_free_sptr->ig3s_z1 = mid_z; - next_free_sptr->ig3s_c1 = mid_c; - next_free_sptr->ig3s_x1 = mid_x; - next_free_sptr->ig3s_u2 = sptr_array_ptr->ig3s_u2; - next_free_sptr->ig3s_v2 = sptr_array_ptr->ig3s_v2; - next_free_sptr->ig3s_z2 = sptr_array_ptr->ig3s_z2; - next_free_sptr->ig3s_c2 = sptr_array_ptr->ig3s_c2; - next_free_sptr->ig3s_x2 = sptr_array_ptr->ig3s_x2; - next_free_sptr->ig3s_y = sptr_array_ptr->ig3s_y; - /* Redefine old scan */ - - sptr_array_ptr->ig3s_u2 = mid_u; - sptr_array_ptr->ig3s_v2 = mid_v; - sptr_array_ptr->ig3s_z2 = mid_z; - sptr_array_ptr->ig3s_c2 = mid_c; - sptr_array_ptr->ig3s_x2 = mid_x; - - /* Update pointer and counter */ - - next_free_sptr++; - num_scans_s++; - - } - sptr_array_ptr++; - } - - } - while(StillSubdividing); - - /* Draw the scan array */ - sptr_array_ptr = sptr_array; - for(i = num_scans_s; i!=0; i--) - { - Draw3DScan(sptr_array_ptr,pheader); - sptr_array_ptr++; - } - } - } - sptr++; - } - } -} - - - -void KR_ScanDraw_Item_2dTexturePolygon_VideoModeType_8(int *itemptr) -{ - POLYHEADER *pheader = (POLYHEADER *) itemptr; - if(NumScans) - { - if(pheader->PolyFlags & iflag_nolight) - { - int y; - I_2DTEXTUREPOLYGON_SCAN *sptr = (I_2DTEXTUREPOLYGON_SCAN *) ScanData; - - /* Offset in Screen Buffer */ - { - IMAGEHEADER *ImageHdr; - { - int TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - } - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - TEXTURE **TxImagePtr = &ImageHdr->ImagePtr; - SCASM_Bitmap = TxImagePtr[MIP_Index]; - GLOBALASSERT(SCASM_Bitmap); - SCASM_TextureDeltaScan = ImageHdr->ImageWidth >> MIP_Index; - #if MIP_ROUNDUP - if (ImageHdr->ImageWidth & (1<<MIP_Index)-1) ++SCASM_TextureDeltaScan; - #endif - } - else - { - SCASM_TextureDeltaScan = ImageHdr->ImageWidth; - SCASM_Bitmap = ImageHdr->ImagePtr; - GLOBALASSERT(SCASM_Bitmap); - } - } - - /* Get the Image Data required for the Draw */ - for(y=NumScans; y!=0; y--) - { - int dx = sptr->i2s_x2 - sptr->i2s_x1; - - if (dx>0 && !(sptr->i2s_y & KRenderDrawMode) ) - { - /* Fixed Point U for Interpolation */ - { - int StartU = sptr->i2s_u1; - SCASM_DeltaU = (sptr->i2s_u2 - StartU)/dx; - SCASM_StartU = StartU; - } - - /* Fixed Point V for Interpolation */ - { - int StartV = sptr->i2s_v1; - SCASM_DeltaV = (sptr->i2s_v2 - StartV)/dx; - SCASM_StartV = StartV; - } - - SCASM_Destination = ScreenBuffer + (sptr->i2s_y * BackBufferPitch) + sptr->i2s_x1; - SCASM_ScanLength = dx; - - - /* Is VDelta = 0? */ - if(SCASM_DeltaV == 0) - { - if(pheader->PolyFlags & iflag_ignore0) - { - ScanDraw2D_VAlignedTransparent(); - } - else - { - ScanDraw2D_VAlignedOpaque(); - } - - } - else - { - if(pheader->PolyFlags & iflag_ignore0) - { - ScanDraw2D_Transparent(); - } - else - { - ScanDraw2D_Opaque(); - } - } - } - sptr++; - } - } - #if 1 - else - { - int y; - I_2DTEXTUREPOLYGON_SCAN *sptr = (I_2DTEXTUREPOLYGON_SCAN *) ScanData; - /* Offset in Screen Buffer */ - { - IMAGEHEADER *ImageHdr; - { - int TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - } - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - TEXTURE **TxImagePtr = &ImageHdr->ImagePtr; - SCASM_Bitmap = TxImagePtr[MIP_Index]; - GLOBALASSERT(SCASM_Bitmap); - SCASM_TextureDeltaScan = ImageHdr->ImageWidth >> MIP_Index; - #if MIP_ROUNDUP - if (ImageHdr->ImageWidth & (1<<MIP_Index)-1) ++SCASM_TextureDeltaScan; - #endif - } - else - { - SCASM_TextureDeltaScan = ImageHdr->ImageWidth; - SCASM_Bitmap = ImageHdr->ImagePtr; - GLOBALASSERT(SCASM_Bitmap); - } - } - SCASM_StartI = ItemColour >> TxDefn; - - SCASM_Lighting = TextureLightingTable; - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_Raw256) SCASM_ShadingTableSize = 256; - else SCASM_ShadingTableSize = 64; - - - /* Get the Image Data required for the Draw */ - for(y=NumScans; y!=0; y--) - { - int dx = sptr->i2s_x2 - sptr->i2s_x1; - if (dx>0 && !(sptr->i2s_y & KRenderDrawMode) ) - { - /* Fixed Point U for Interpolation */ - { - int StartU = sptr->i2s_u1; - SCASM_DeltaU = (sptr->i2s_u2 - StartU)/dx; - SCASM_StartU = StartU; - } - - /* Fixed Point V for Interpolation */ - { - int StartV = sptr->i2s_v1; - SCASM_DeltaV = (sptr->i2s_v2 - StartV)/dx; - SCASM_StartV = StartV; - } - - SCASM_Destination = ScreenBuffer + (sptr->i2s_y * BackBufferPitch) + sptr->i2s_x1; - SCASM_ScanLength = dx; - - ScanDraw2D_TransparentLit(); - // PredatorScanDraw(); - } - sptr++; - } - - - } - #endif - } - -} -unsigned char LighterTable[255]; -int predatorTimer = 0; -void ScanDraw_CloakedScan(void) -{ - unsigned char *screen = SCASM_Destination; - int x = SCASM_ScanLength; - - unsigned char buffer[1000]; - do - { - buffer[x] = *screen++; - } - while(--x); - - screen = SCASM_Destination; - x = SCASM_ScanLength; - - if (FastRandom()&3==3 && x>2) - { - x--; - screen++; - } - if (FastRandom()&3==3 && x>2) - { - x--; - } - - do - { - { - extern sine[]; - extern cosine[]; - unsigned char colour; - int offset = (GetCos( ((x*2047)/SCASM_ScanLength + predatorTimer)&4095 )+65536)/2; - offset = MUL_FIXED(offset,offset); - colour = (buffer[SCASM_ScanLength-x+1]); - // colour = (buffer[x]); - #if 0 - int i; - for (i=0; i<=255;i++) - { - if (colour==*(TextureLightingTable + 256*200 + i)) break; - } - #endif - colour=*(TextureLightingTable + 256*(60+MUL_FIXED(4,GetCos(predatorTimer&4095)) ) + colour); - *screen++ = colour; - - } - } - while(--x); - -} -#if 0 -void PredatorScanDraw(void) -{ - unsigned char *screen = SCASM_Destination; - unsigned char *source; - - do - { - source = SCASM_Bitmap+ (SCASM_StartU>>16) + (SCASM_StartV>>16)*SCASM_TextureDeltaScan; - - *screen++ = *source++; - - SCASM_StartU += SCASM_DeltaU; - SCASM_StartV += SCASM_DeltaV; - } - while(--SCASM_ScanLength); - -} -#else -void PredatorScanDraw(void) -{ - unsigned char *screen = SCASM_Destination; - unsigned char *source; - int x = SCASM_ScanLength; - do - { - source = SCASM_Bitmap+ (SCASM_StartU>>16) + (SCASM_StartV>>16)*SCASM_TextureDeltaScan; - - if (*source) - { - extern sine[]; - extern cosine[]; - unsigned char colour = *(screen); - *screen = LighterTable[colour]; - } - screen++; - SCASM_StartU += SCASM_DeltaU; - SCASM_StartV += SCASM_DeltaV; - } - while(--x); - -} -#endif - -void Draw_Item_CloakedPolygon(int *itemptr) -{ - POLYHEADER *pheader = (POLYHEADER *)itemptr; - int minYVertex = 0; - int maxYVertex = 0; - int maxVertexNum = 0; - - { - I_GOURAUDPOLYGON_PT *vertexPtr = (I_GOURAUDPOLYGON_PT*)&pheader->Poly1stPt; - int minY = vertexPtr->i_y; - int maxY = vertexPtr->i_y; - vertexPtr++; - - do - { - maxVertexNum++; - - if (minY > vertexPtr->i_y) - { - minY = vertexPtr->i_y; - minYVertex = maxVertexNum; - } - else if (maxY < vertexPtr->i_y) - { - maxY = vertexPtr->i_y; - maxYVertex = maxVertexNum; - } - vertexPtr++; - } - while(vertexPtr->i_x != Term); - - } - - - /* Initialise the Scan Data Buffer */ - { - I_GOURAUDPOLYGON_PT *vertexPtr = (I_GOURAUDPOLYGON_PT*)&pheader->Poly1stPt; - I_GOURAUDPOLYGON_SCAN *polyScan; - int curVertex; - int SecondOpinion=0; - - NumScans=0; - /* scan out the right edge */ - polyScan = (I_GOURAUDPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - int i,x,y; - int deltaX,deltaI; - - int nextVertex = curVertex-1; - if (nextVertex<0) nextVertex = maxVertexNum; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_int - vertexPtr[curVertex].i_int; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_int; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->igs_x2 = x>>16; - x+=deltaX; - polyScan->igs_c2 = i; - i+=deltaI; - - polyScan->igs_y = y; - NumScans++; - polyScan++; - } - } - curVertex--; - if (curVertex<0) curVertex = maxVertexNum; - - } - while(curVertex!=maxYVertex); - - /* scan out the left edge */ - polyScan = (I_GOURAUDPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - int i,x,y; - int deltaX,deltaI; - - int nextVertex = curVertex+1; - if (nextVertex>maxVertexNum) nextVertex = 0; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_int - vertexPtr[curVertex].i_int; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_int; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->igs_x1 = x>>16; - x+=deltaX; - polyScan->igs_c1 = i; - i+=deltaI; - - SecondOpinion++; - polyScan++; - } - } - curVertex++; - if (curVertex>maxVertexNum) curVertex = 0; - - } - while(curVertex!=maxYVertex); - - if (SecondOpinion<NumScans) - { - textprint("WARNING: Rasterization error\n"); - NumScans = SecondOpinion; -// LOCALASSERT(0); - return; - } - - } - - //draw 'em - - { - unsigned char colour= pheader->PolyColour; - I_GOURAUDPOLYGON_SCAN *polyScan; - polyScan = (I_GOURAUDPOLYGON_SCAN*)ScanData; - SCASM_Lighting = TextureLightingTable+colour; - SCASM_ShadingTableSize = 256; - - while(NumScans) - { - int dx = polyScan->igs_x2 - polyScan->igs_x1; - if (dx>0) - { - SCASM_Destination = ScreenBuffer+(polyScan->igs_y * BackBufferPitch) + polyScan->igs_x1; - SCASM_ScanLength = dx; - SCASM_DeltaI = (polyScan->igs_c2-polyScan->igs_c1)/dx; - SCASM_StartI = polyScan->igs_c1; - ScanDraw_CloakedScan(); - } - NumScans--; - polyScan++; - } - } -} -#if 1 -void KDraw_Item_GouraudPolygon(int *itemptr) -{ - POLYHEADER *pheader = (POLYHEADER *)itemptr; - int minYVertex = 0; - int maxYVertex = 0; - int maxVertexNum = 0; - - { - I_GOURAUDPOLYGON_PT *vertexPtr = (I_GOURAUDPOLYGON_PT*)&pheader->Poly1stPt; - int minY = vertexPtr->i_y; - int maxY = vertexPtr->i_y; - vertexPtr++; - - do - { - maxVertexNum++; - - if (minY > vertexPtr->i_y) - { - minY = vertexPtr->i_y; - minYVertex = maxVertexNum; - } - else if (maxY < vertexPtr->i_y) - { - maxY = vertexPtr->i_y; - maxYVertex = maxVertexNum; - } - vertexPtr++; - } - while(vertexPtr->i_x != Term); - - } - - - /* Initialise the Scan Data Buffer */ - { - I_GOURAUDPOLYGON_PT *vertexPtr = (I_GOURAUDPOLYGON_PT*)&pheader->Poly1stPt; - I_GOURAUDPOLYGON_SCAN *polyScan; - int curVertex; - int SecondOpinion=0; - - NumScans=0; - /* scan out the right edge */ - polyScan = (I_GOURAUDPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - int i,x,y; - int deltaX,deltaI; - - int nextVertex = curVertex-1; - if (nextVertex<0) nextVertex = maxVertexNum; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_int - vertexPtr[curVertex].i_int; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_int; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->igs_x2 = x>>16; - x+=deltaX; - polyScan->igs_c2 = i; - i+=deltaI; - - polyScan->igs_y = y; - NumScans++; - polyScan++; - } - } - curVertex--; - if (curVertex<0) curVertex = maxVertexNum; - - } - while(curVertex!=maxYVertex); - - /* scan out the left edge */ - polyScan = (I_GOURAUDPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - int i,x,y; - int deltaX,deltaI; - - int nextVertex = curVertex+1; - if (nextVertex>maxVertexNum) nextVertex = 0; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_int - vertexPtr[curVertex].i_int; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_int; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->igs_x1 = x>>16; - x+=deltaX; - polyScan->igs_c1 = i; - i+=deltaI; - - SecondOpinion++; - polyScan++; - } - } - curVertex++; - if (curVertex>maxVertexNum) curVertex = 0; - - } - while(curVertex!=maxYVertex); - - if (SecondOpinion<NumScans) - { - textprint("WARNING: Rasterization error\n"); - NumScans = SecondOpinion; -// LOCALASSERT(0); - return; - } - - } - - //draw 'em - - { - unsigned char colour= pheader->PolyColour; - I_GOURAUDPOLYGON_SCAN *polyScan; - polyScan = (I_GOURAUDPOLYGON_SCAN*)ScanData; - SCASM_Lighting = TextureLightingTable+colour; - SCASM_ShadingTableSize = 256; - - while(NumScans) - { - int dx = polyScan->igs_x2 - polyScan->igs_x1; - if (dx>0) - { - SCASM_Destination = ScreenBuffer+(polyScan->igs_y * BackBufferPitch) + polyScan->igs_x1; - SCASM_ScanLength = dx; - SCASM_DeltaI = (polyScan->igs_c2-polyScan->igs_c1)/dx; - SCASM_StartI = polyScan->igs_c1; - ScanDraw_GouraudScan(); - } - NumScans--; - polyScan++; - } - } -} -void KDraw_Item_2dTexturePolygon(int *itemptr) -{ - - POLYHEADER *pheader = (POLYHEADER *) itemptr; - int TxIndex; - IMAGEHEADER *ImageHdr; - ItemColour = pheader->PolyColour; - - TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - - - /* Colour */ - - /* If MIP Mapping, calculate the scale */ - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - I_2DTEXTUREPOLYGON_PT *vector1; - I_2DTEXTUREPOLYGON_PT *vector2; - I_2DTEXTUREPOLYGON_PT *vector3; - int mip1, mip2; - int xyd, uvd; - VECTOR2D s0, s1; - VECTOR2D t0, t1; - - - /* Screen and Texture Space Vectors */ - /* Express the "uvd / xyd" ratio as a binary scale */ - - vector1 = (I_2DTEXTUREPOLYGON_PT *) &pheader->Poly1stPt; - vector2 = &vector1[1]; - vector3 = &vector1[2]; - - - /* Vector 1 */ - - s0.vx = vector1->i_x; - s0.vy = vector1->i_y; - s1.vx = vector2->i_x; - s1.vy = vector2->i_y; - - t0.vx = vector1->i_u >> 16; - t0.vy = vector1->i_v >> 16; - t1.vx = vector2->i_u >> 16; - t1.vy = vector2->i_v >> 16; - - xyd = FandVD_Distance_2d(&s0, &s1); - uvd = FandVD_Distance_2d(&t0, &t1); - - mip1 = FindShift32(uvd, xyd); - - - /* Vector 2 */ - - s0.vx = vector2->i_x; - s0.vy = vector2->i_y; - s1.vx = vector3->i_x; - s1.vy = vector3->i_y; - - t0.vx = t1.vx; - t0.vy = t1.vy; - t1.vx = vector3->i_u >> 16; - t1.vy = vector3->i_v >> 16; - - xyd = FandVD_Distance_2d(&s0, &s1); - uvd = FandVD_Distance_2d(&t0, &t1); - - mip2 = FindShift32(uvd, xyd); - - - /* Choose the larger of the two */ - - if(pheader->PolyFlags & iflag_no_mip) { - - MIP_Index = 0; - - } - - else { - - #if UseMIPMax - if(mip1 > mip2) - MIP_Index = mip1; - else - MIP_Index = mip2; - #endif - - #if UseMIPMin - if(mip1 > mip2) - MIP_Index = mip2; - else - MIP_Index = mip1; - #endif - - #if UseMIPAvg - MIP_Index = (mip1 + mip2) >> 1; - #endif - - } - - - /* Clamp "MIP_Index" */ - - #if MIP_INDEX_SUBTRACT - - MIP_Index -= MIP_INDEX_SUBTRACT; - if(MIP_Index < 0) MIP_Index = 0; - else if(MIP_Index > 6) MIP_Index = 6; - - #else - - if(MIP_Index > 6) MIP_Index = 6; - - #endif - - } - - { - int minYVertex = 0; - int maxYVertex = 0; - int maxVertexNum = 0; - - { - I_2DTEXTUREPOLYGON_PT *vertexPtr = (I_2DTEXTUREPOLYGON_PT*)&pheader->Poly1stPt; - int minY = vertexPtr->i_y; - int maxY = vertexPtr->i_y; - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - vertexPtr->i_u >>= MIP_Index; - vertexPtr->i_v >>= MIP_Index; - } - vertexPtr++; - - do - { - maxVertexNum++; - - if (minY > vertexPtr->i_y) - { - minY = vertexPtr->i_y; - minYVertex = maxVertexNum; - } - else if (maxY < vertexPtr->i_y) - { - maxY = vertexPtr->i_y; - maxYVertex = maxVertexNum; - } - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - vertexPtr->i_u >>= MIP_Index; - vertexPtr->i_v >>= MIP_Index; - } - - vertexPtr++; - } - while(vertexPtr->i_x != Term); - - } - - - /* Initialise the Scan Data Buffer */ - { - I_2DTEXTUREPOLYGON_PT *vertexPtr = (I_2DTEXTUREPOLYGON_PT*)&pheader->Poly1stPt; - I_2DTEXTUREPOLYGON_SCAN *polyScan; - int curVertex; - int SecondOpinion = 0; - - NumScans=0; - /* scan out the right edge */ - polyScan = (I_2DTEXTUREPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - - int nextVertex = curVertex-1; - if (nextVertex<0) nextVertex = maxVertexNum; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int x,y,u,v; - int deltaX,deltaU,deltaV; - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int widthU = vertexPtr[nextVertex].i_u - vertexPtr[curVertex].i_u; - int widthV = vertexPtr[nextVertex].i_v - vertexPtr[curVertex].i_v; - - deltaX = (width<<16)/height; - deltaU = widthU/height; - deltaV = widthV/height; - - x = vertexPtr[curVertex].i_x<<16; - u = vertexPtr[curVertex].i_u; - v = vertexPtr[curVertex].i_v; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->i2s_x2 = x>>16; - x+=deltaX; - polyScan->i2s_u2 = u; - u+=deltaU; - polyScan->i2s_v2 = v; - v+=deltaV; - - polyScan->i2s_y = y; - NumScans++; - polyScan++; - } - } - curVertex--; - if (curVertex<0) curVertex = maxVertexNum; - - } - while(curVertex!=maxYVertex); - - /* scan out the left edge */ - polyScan = (I_2DTEXTUREPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - - int nextVertex = curVertex+1; - if (nextVertex>maxVertexNum) nextVertex = 0; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int x,y,u,v; - int deltaX,deltaU,deltaV; - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int widthU = vertexPtr[nextVertex].i_u - vertexPtr[curVertex].i_u; - int widthV = vertexPtr[nextVertex].i_v - vertexPtr[curVertex].i_v; - - deltaX = (width<<16)/height; - deltaU = widthU/height; - deltaV = widthV/height; - - x = vertexPtr[curVertex].i_x<<16; - u = vertexPtr[curVertex].i_u; - v = vertexPtr[curVertex].i_v; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->i2s_x1 = x>>16; - x+=deltaX; - polyScan->i2s_u1 = u; - u+=deltaU; - polyScan->i2s_v1 = v; - v+=deltaV; - - SecondOpinion++; - polyScan++; - } - } - curVertex++; - if (curVertex>maxVertexNum) curVertex = 0; - - } - while(curVertex!=maxYVertex); - - if (SecondOpinion<NumScans) - { - textprint("WARNING: Rasterization error\n"); - NumScans = SecondOpinion; -// LOCALASSERT(0); - return; - } - } - - //draw 'em - KR_ScanDraw_Item_2dTexturePolygon_VideoModeType_8(itemptr); - - } -} -void KDraw_Item_Gouraud2dTexturePolygon(int *itemptr) -{ - POLYHEADER *pheader = (POLYHEADER *) itemptr; - int TxIndex; - IMAGEHEADER *ImageHdr; - ItemColour = pheader->PolyColour; - - TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - - - - /* Colour */ - - - /* If MIP Mapping, calculate the scale */ - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - I_GOURAUD2DTEXTUREPOLYGON_PT *vector1; - I_GOURAUD2DTEXTUREPOLYGON_PT *vector2; - I_GOURAUD2DTEXTUREPOLYGON_PT *vector3; - int mip1, mip2; - int xyd, uvd; - VECTOR2D s0, s1; - VECTOR2D t0, t1; - - - /* Screen and Texture Space Vectors */ - /* Express the "uvd / xyd" ratio as a binary scale */ - - vector1 = (I_GOURAUD2DTEXTUREPOLYGON_PT *) &pheader->Poly1stPt; - vector2 = &vector1[1]; - vector3 = &vector1[2]; - - - /* Vector 1 */ - - s0.vx = vector1->i_x; - s0.vy = vector1->i_y; - s1.vx = vector2->i_x; - s1.vy = vector2->i_y; - - t0.vx = vector1->i_u >> 16; - t0.vy = vector1->i_v >> 16; - t1.vx = vector2->i_u >> 16; - t1.vy = vector2->i_v >> 16; - - xyd = FandVD_Distance_2d(&s0, &s1); - uvd = FandVD_Distance_2d(&t0, &t1); - - mip1 = FindShift32(uvd, xyd); - - - /* Vector 2 */ - - s0.vx = vector2->i_x; - s0.vy = vector2->i_y; - s1.vx = vector3->i_x; - s1.vy = vector3->i_y; - - t0.vx = t1.vx; - t0.vy = t1.vy; - t1.vx = vector3->i_u >> 16; - t1.vy = vector3->i_v >> 16; - - xyd = FandVD_Distance_2d(&s0, &s1); - uvd = FandVD_Distance_2d(&t0, &t1); - - mip2 = FindShift32(uvd, xyd); - - - /* Choose the larger of the two */ - - if(pheader->PolyFlags & iflag_no_mip) { - - MIP_Index = 0; - - } - - else { - - #if UseMIPMax - if(mip1 > mip2) - MIP_Index = mip1; - else - MIP_Index = mip2; - #endif - - #if UseMIPMin - if(mip1 > mip2) - MIP_Index = mip2; - else - MIP_Index = mip1; - #endif - - #if UseMIPAvg - MIP_Index = (mip1 + mip2) >> 1; - #endif - - } - - - /* Clamp "MIP_Index" */ - - #if MIP_INDEX_SUBTRACT - - MIP_Index -= MIP_INDEX_SUBTRACT; - if(MIP_Index < 0) MIP_Index = 0; - else if(MIP_Index > 6) MIP_Index = 6; - - #else - - if(MIP_Index > 6) MIP_Index = 6; - - #endif - - } - - { - int minYVertex = 0; - int maxYVertex = 0; - int maxVertexNum = 0; - - { - I_GOURAUD2DTEXTUREPOLYGON_PT *vertexPtr = (I_GOURAUD2DTEXTUREPOLYGON_PT*)&pheader->Poly1stPt; - int minY = vertexPtr->i_y; - int maxY = vertexPtr->i_y; - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - vertexPtr->i_u >>= MIP_Index; - vertexPtr->i_v >>= MIP_Index; - } - vertexPtr++; - - do - { - maxVertexNum++; - - if (minY > vertexPtr->i_y) - { - minY = vertexPtr->i_y; - minYVertex = maxVertexNum; - } - else if (maxY < vertexPtr->i_y) - { - maxY = vertexPtr->i_y; - maxYVertex = maxVertexNum; - } - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - vertexPtr->i_u >>= MIP_Index; - vertexPtr->i_v >>= MIP_Index; - } - - vertexPtr++; - } - while(vertexPtr->i_x != Term); - - } - - - /* Initialise the Scan Data Buffer */ - { - I_GOURAUD2DTEXTUREPOLYGON_PT *vertexPtr = (I_GOURAUD2DTEXTUREPOLYGON_PT*)&pheader->Poly1stPt; - I_GOURAUD2DTEXTUREPOLYGON_SCAN *polyScan; - int curVertex; - int SecondOpinion=0; - - NumScans=0; - /* scan out the right edge */ - polyScan = (I_GOURAUD2DTEXTUREPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - - int nextVertex = curVertex-1; - if (nextVertex<0) nextVertex = maxVertexNum; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int i,x,y,u,v; - int deltaX,deltaI,deltaU,deltaV; - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_i - vertexPtr[curVertex].i_i; - int widthU = vertexPtr[nextVertex].i_u - vertexPtr[curVertex].i_u; - int widthV = vertexPtr[nextVertex].i_v - vertexPtr[curVertex].i_v; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - deltaU = widthU/height; - deltaV = widthV/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_i; - u = vertexPtr[curVertex].i_u; - v = vertexPtr[curVertex].i_v; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->ig2s_x2 = x>>16; - x+=deltaX; - polyScan->ig2s_c2 = i; - i+=deltaI; - polyScan->ig2s_u2 = u; - u+=deltaU; - polyScan->ig2s_v2 = v; - v+=deltaV; - - polyScan->ig2s_y = y; - NumScans++; - polyScan++; - } - } - curVertex--; - if (curVertex<0) curVertex = maxVertexNum; - - } - while(curVertex!=maxYVertex); - - /* scan out the left edge */ - polyScan = (I_GOURAUD2DTEXTUREPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - - int nextVertex = curVertex+1; - if (nextVertex>maxVertexNum) nextVertex = 0; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int i,x,y,u,v; - int deltaX,deltaI,deltaU,deltaV; - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_i - vertexPtr[curVertex].i_i; - int widthU = vertexPtr[nextVertex].i_u - vertexPtr[curVertex].i_u; - int widthV = vertexPtr[nextVertex].i_v - vertexPtr[curVertex].i_v; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - deltaU = widthU/height; - deltaV = widthV/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_i; - u = vertexPtr[curVertex].i_u; - v = vertexPtr[curVertex].i_v; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->ig2s_x1 = x>>16; - x+=deltaX; - polyScan->ig2s_c1 = i; - i+=deltaI; - polyScan->ig2s_u1 = u; - u+=deltaU; - polyScan->ig2s_v1 = v; - v+=deltaV; - - SecondOpinion++; - polyScan++; - } - } - curVertex++; - if (curVertex>maxVertexNum) curVertex = 0; - - } - while(curVertex!=maxYVertex); - - if (SecondOpinion<NumScans) - { - textprint("WARNING: Rasterization error\n"); - NumScans = SecondOpinion; -// LOCALASSERT(0); - return; - } - } - //draw 'em - KR_ScanDraw_Item_Gouraud2dTexturePolygon_VideoModeType_8(itemptr); - - #if 0 - { - unsigned char colour= pheader->PolyColour; - I_GOURAUD2DTEXTUREPOLYGON_SCAN *polyScan; - polyScan = (I_GOURAUD2DTEXTUREPOLYGON_SCAN*)ScanData; - SCASM_Lighting = TextureLightingTable+colour; - SCASM_ShadingTableSize = 256; - - while(NumScans) - { - int dx = polyScan->ig2s_x2 - polyScan->ig2s_x1; - if (dx>0) - { - SCASM_Destination = ScreenBuffer+(polyScan->ig2s_y * BackBufferPitch) + polyScan->ig2s_x1; - SCASM_ScanLength = dx; - SCASM_DeltaI = (polyScan->ig2s_c2-polyScan->ig2s_c1)/dx; - SCASM_StartI = polyScan->ig2s_c1; - ScanDraw_GouraudScan(); - } - NumScans--; - polyScan++; - } - } - #endif - } -} -#endif -#if 0 -void KDraw_Item_Gouraud3dTexturePolygon(int *itemptr) -{ - POLYHEADER *pheader = (POLYHEADER *) itemptr; - int TxIndex; - IMAGEHEADER *ImageHdr; - ItemColour = pheader->PolyColour; - - TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - - - - /* Colour */ - - - /* If MIP Mapping, calculate the scale */ - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - I_GOURAUD3DTEXTUREPOLYGON_PT *vector1; - I_GOURAUD3DTEXTUREPOLYGON_PT *vector2; - I_GOURAUD3DTEXTUREPOLYGON_PT *vector3; - int mip1, mip2; - int xyd, uvd; - VECTOR2D s0, s1; - VECTOR2D t0, t1; - - - /* Screen and Texture Space Vectors */ - /* Express the "uvd / xyd" ratio as a binary scale */ - - vector1 = (I_GOURAUD3DTEXTUREPOLYGON_PT *) &pheader->Poly1stPt; - vector2 = &vector1[1]; - vector3 = &vector1[2]; - - - /* Vector 1 */ - - s0.vx = vector1->i_x; - s0.vy = vector1->i_y; - s1.vx = vector2->i_x; - s1.vy = vector2->i_y; - - t0.vx = vector1->i_gtx3d_u / vector1->i_gtx3d_z; - t0.vy = vector1->i_gtx3d_v / vector1->i_gtx3d_z; - t1.vx = vector2->i_gtx3d_u / vector2->i_gtx3d_z; - t1.vy = vector2->i_gtx3d_v / vector2->i_gtx3d_z; - - xyd = FandVD_Distance_2d(&s0, &s1); - uvd = FandVD_Distance_2d(&t0, &t1); - - mip1 = FindShift32(uvd, xyd); - - - /* Vector 2 */ - - s0.vx = vector2->i_x; - s0.vy = vector2->i_y; - s1.vx = vector3->i_x; - s1.vy = vector3->i_y; - - t0.vx = t1.vx; - t0.vy = t1.vy; - t1.vx = vector3->i_gtx3d_u / vector3->i_gtx3d_z; - t1.vy = vector3->i_gtx3d_v / vector3->i_gtx3d_z; - - xyd = FandVD_Distance_2d(&s0, &s1); - uvd = FandVD_Distance_2d(&t0, &t1); - - mip2 = FindShift32(uvd, xyd); - - - /* Choose the larger of the two */ - - if(pheader->PolyFlags & iflag_no_mip) { - - MIP_Index = 0; - - } - - else { - - #if UseMIPMax - if(mip1 > mip2) - MIP_Index = mip1; - else - MIP_Index = mip2; - #endif - - #if UseMIPMin - if(mip1 > mip2) - MIP_Index = mip2; - else - MIP_Index = mip1; - #endif - - #if UseMIPAvg - MIP_Index = (mip1 + mip2) >> 1; - #endif - - } - - - /* Clamp "MIP_Index" */ - - #if MIP_INDEX_SUBTRACT - - MIP_Index -= MIP_INDEX_SUBTRACT; - if(MIP_Index < 0) MIP_Index = 0; - else if(MIP_Index > 6) MIP_Index = 6; - - #else - - if(MIP_Index > 6) MIP_Index = 6; - - #endif - - } - - { - int minYVertex = 0; - int maxYVertex = 0; - int maxVertexNum = 0; - float MIP_Divide = 1<<MIP_Index; - - { - I_GOURAUD3DTEXTUREPOLYGON_PT *vertexPtr = (I_GOURAUD3DTEXTUREPOLYGON_PT*)&pheader->Poly1stPt; - int minY = vertexPtr->i_y; - int maxY = vertexPtr->i_y; - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - vertexPtr->i_gtx3d_u /= MIP_Divide; - vertexPtr->i_gtx3d_v /= MIP_Divide; - } - vertexPtr++; - - do - { - maxVertexNum++; - - if (minY > vertexPtr->i_y) - { - minY = vertexPtr->i_y; - minYVertex = maxVertexNum; - } - else if (maxY < vertexPtr->i_y) - { - maxY = vertexPtr->i_y; - maxYVertex = maxVertexNum; - } - - if(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_MIP && ImageHdr->ImageFlags & ih_flag_mip) - { - vertexPtr->i_gtx3d_u /= MIP_Divide; - vertexPtr->i_gtx3d_v /= MIP_Divide; - } - - vertexPtr++; - } - while(vertexPtr->i_x != Term); - - } - - - /* Initialise the Scan Data Buffer */ - { - I_GOURAUD3DTEXTUREPOLYGON_PT *vertexPtr = (I_GOURAUD3DTEXTUREPOLYGON_PT*)&pheader->Poly1stPt; - I_GOURAUD3DTEXTUREPOLYGON_SCAN *polyScan; - int curVertex; - int SecondOpinion=0; - - NumScans=0; - - /* scan out the right edge */ - polyScan = (I_GOURAUD3DTEXTUREPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - - int nextVertex = curVertex-1; - if (nextVertex<0) nextVertex = maxVertexNum; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int i,x,y; - float u,v,z; - int deltaX,deltaI; - float deltaU,deltaV,deltaZ; - - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_gtx3d_i - vertexPtr[curVertex].i_gtx3d_i; - float widthU = vertexPtr[nextVertex].i_gtx3d_u - vertexPtr[curVertex].i_gtx3d_u; - float widthV = vertexPtr[nextVertex].i_gtx3d_v - vertexPtr[curVertex].i_gtx3d_v; - float widthZ = vertexPtr[nextVertex].i_gtx3d_z - vertexPtr[curVertex].i_gtx3d_z; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - deltaU = widthU/height; - deltaV = widthV/height; - deltaZ = widthZ/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_gtx3d_i; - u = vertexPtr[curVertex].i_gtx3d_u; - v = vertexPtr[curVertex].i_gtx3d_v; - z = vertexPtr[curVertex].i_gtx3d_z; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->ig3s_x2 = x>>16; - x+=deltaX; - polyScan->ig3s_c2 = i; - i+=deltaI; - polyScan->ig3s_u2 = u; - u+=deltaU; - polyScan->ig3s_v2 = v; - v+=deltaV; - polyScan->ig3s_z2 = z; - z+=deltaZ; - - polyScan->ig3s_y = y; - NumScans++; - polyScan++; - } - } - curVertex--; - if (curVertex<0) curVertex = maxVertexNum; - - } - while(curVertex!=maxYVertex); - - /* scan out the left edge */ - polyScan = (I_GOURAUD3DTEXTUREPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - - int nextVertex = curVertex+1; - if (nextVertex>maxVertexNum) nextVertex = 0; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int i,x,y; - float u,v,z; - int deltaX,deltaI; - float deltaU,deltaV,deltaZ; - - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_gtx3d_i - vertexPtr[curVertex].i_gtx3d_i; - float widthU = vertexPtr[nextVertex].i_gtx3d_u - vertexPtr[curVertex].i_gtx3d_u; - float widthV = vertexPtr[nextVertex].i_gtx3d_v - vertexPtr[curVertex].i_gtx3d_v; - float widthZ = vertexPtr[nextVertex].i_gtx3d_z - vertexPtr[curVertex].i_gtx3d_z; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - deltaU = widthU/height; - deltaV = widthV/height; - deltaZ = widthZ/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_gtx3d_i; - u = vertexPtr[curVertex].i_gtx3d_u; - v = vertexPtr[curVertex].i_gtx3d_v; - z = vertexPtr[curVertex].i_gtx3d_z; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->ig3s_x1 = x>>16; - x+=deltaX; - polyScan->ig3s_c1 = i; - i+=deltaI; - polyScan->ig3s_u1 = u; - u+=deltaU; - polyScan->ig3s_v1 = v; - v+=deltaV; - polyScan->ig3s_z1 = z; - z+=deltaZ; - - SecondOpinion++; - polyScan++; - } - } - curVertex++; - if (curVertex>maxVertexNum) curVertex = 0; - - } - while(curVertex!=maxYVertex); - - if (SecondOpinion<NumScans) - { - textprint("WARNING: Rasterization error\n"); - NumScans = SecondOpinion; -// LOCALASSERT(0); - return; - } - } - - //draw 'em - KR_ScanDraw_Item_Gouraud3dTexturePolygon_Linear_S_VideoModeType_8(itemptr); - } -} -#else -void KDraw_Item_Gouraud3dTexturePolygon(int *itemptr) -{ - POLYHEADER *pheader = (POLYHEADER *) itemptr; - int TxIndex; - IMAGEHEADER *ImageHdr; - ItemColour = pheader->PolyColour; - - TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - - - - { - int minYVertex = 0; - int maxYVertex = 0; - int maxVertexNum = 0; - - - { - I_GOURAUD3DTEXTUREPOLYGON_PT *vertexPtr = (I_GOURAUD3DTEXTUREPOLYGON_PT*)&pheader->Poly1stPt; - int minY = vertexPtr->i_y; - int maxY = vertexPtr->i_y; - - vertexPtr++; - - do - { - maxVertexNum++; - - if (minY > vertexPtr->i_y) - { - minY = vertexPtr->i_y; - minYVertex = maxVertexNum; - } - else if (maxY < vertexPtr->i_y) - { - maxY = vertexPtr->i_y; - maxYVertex = maxVertexNum; - } - - vertexPtr++; - } - while(vertexPtr->i_x != Term); - - } - - - /* Initialise the Scan Data Buffer */ - { - I_GOURAUD3DTEXTUREPOLYGON_PT *vertexPtr = (I_GOURAUD3DTEXTUREPOLYGON_PT*)&pheader->Poly1stPt; - I_GOURAUD3DTEXTUREPOLYGON_SCAN *polyScan; - int curVertex; - int SecondOpinion=0; - - NumScans=0; - - /* scan out the right edge */ - polyScan = (I_GOURAUD3DTEXTUREPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - - int nextVertex = curVertex-1; - if (nextVertex<0) nextVertex = maxVertexNum; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int i,x,y; - float u,v,z; - int deltaX,deltaI; - float deltaU,deltaV,deltaZ; - - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_gtx3d_i - vertexPtr[curVertex].i_gtx3d_i; - float widthU = vertexPtr[nextVertex].i_gtx3d_u - vertexPtr[curVertex].i_gtx3d_u; - float widthV = vertexPtr[nextVertex].i_gtx3d_v - vertexPtr[curVertex].i_gtx3d_v; - float widthZ = vertexPtr[nextVertex].i_gtx3d_z - vertexPtr[curVertex].i_gtx3d_z; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - deltaU = widthU/height; - deltaV = widthV/height; - deltaZ = widthZ/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_gtx3d_i; - u = vertexPtr[curVertex].i_gtx3d_u; - v = vertexPtr[curVertex].i_gtx3d_v; - z = vertexPtr[curVertex].i_gtx3d_z; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->ig3s_x2 = x>>16; - x+=deltaX; - polyScan->ig3s_c2 = i; - i+=deltaI; - polyScan->ig3s_u2 = u; - u+=deltaU; - polyScan->ig3s_v2 = v; - v+=deltaV; - polyScan->ig3s_z2 = z; - z+=deltaZ; - - polyScan->ig3s_y = y; - NumScans++; - polyScan++; - } - } - curVertex--; - if (curVertex<0) curVertex = maxVertexNum; - - } - while(curVertex!=maxYVertex); - - /* scan out the left edge */ - polyScan = (I_GOURAUD3DTEXTUREPOLYGON_SCAN*)ScanData; - curVertex = minYVertex; - do - { - int height; - - int nextVertex = curVertex+1; - if (nextVertex>maxVertexNum) nextVertex = 0; - - height = vertexPtr[nextVertex].i_y - vertexPtr[curVertex].i_y; - if (height!=0) - { - int i,x,y; - float u,v,z; - int deltaX,deltaI; - float deltaU,deltaV,deltaZ; - - int width = vertexPtr[nextVertex].i_x - vertexPtr[curVertex].i_x; - int contrast = vertexPtr[nextVertex].i_gtx3d_i - vertexPtr[curVertex].i_gtx3d_i; - float widthU = vertexPtr[nextVertex].i_gtx3d_u - vertexPtr[curVertex].i_gtx3d_u; - float widthV = vertexPtr[nextVertex].i_gtx3d_v - vertexPtr[curVertex].i_gtx3d_v; - float widthZ = vertexPtr[nextVertex].i_gtx3d_z - vertexPtr[curVertex].i_gtx3d_z; - - deltaX = (width<<16)/height; - deltaI = contrast/height; - deltaU = widthU/height; - deltaV = widthV/height; - deltaZ = widthZ/height; - - x = vertexPtr[curVertex].i_x<<16; - i = vertexPtr[curVertex].i_gtx3d_i; - u = vertexPtr[curVertex].i_gtx3d_u; - v = vertexPtr[curVertex].i_gtx3d_v; - z = vertexPtr[curVertex].i_gtx3d_z; - - for (y=vertexPtr[curVertex].i_y; y<vertexPtr[nextVertex].i_y; y++) - { - polyScan->ig3s_x1 = x>>16; - x+=deltaX; - polyScan->ig3s_c1 = i; - i+=deltaI; - polyScan->ig3s_u1 = u; - u+=deltaU; - polyScan->ig3s_v1 = v; - v+=deltaV; - polyScan->ig3s_z1 = z; - z+=deltaZ; - - SecondOpinion++; - polyScan++; - } - } - curVertex++; - if (curVertex>maxVertexNum) curVertex = 0; - - } - while(curVertex!=maxYVertex); - - if (SecondOpinion<NumScans) - { - textprint("WARNING: Rasterization error\n"); - NumScans = SecondOpinion; -// LOCALASSERT(0); - return; - } - } - - //draw 'em - Draw_Gouraud3dTexture_Spans(itemptr); - } -} - -#define PERS_STEP 16 -void Draw_Gouraud3dTexture_Spans(int *itemptr) -{ - I_GOURAUD3DTEXTUREPOLYGON_SCAN *sptr; - - if(NumScans) - { - int y = NumScans; - /* Get the Image Data required for the Draw */ - { - IMAGEHEADER *ImageHdr; - { - int TxIndex = ItemColour & ClrTxDefn; - ImageHdr = ImageHeaderPtrs[TxIndex]; - } - { - SCASM_TextureDeltaScan = ImageHdr->ImageWidth; - SCASM_Bitmap = ImageHdr->ImagePtr; - GLOBALASSERT(SCASM_Bitmap); - } - } - SCASM_Lighting = TextureLightingTable; - - sptr = (I_GOURAUD3DTEXTUREPOLYGON_SCAN *) ScanData; - do - { - int length = sptr->ig3s_x2 - sptr->ig3s_x1; - int dx=length; - - if (dx>0 && !(sptr->ig3s_y & KRenderDrawMode) ) - { - float deltaZ; - float endZ; - - float endU,endV; - float deltaU,deltaV; - - { - int StartI = sptr->ig3s_c1; - SCASM_DeltaI = (sptr->ig3s_c2 - StartI)/dx; - SCASM_StartI = StartI; - } - - SCASM_Destination = ScreenBuffer + (sptr->ig3s_y * BackBufferPitch) + sptr->ig3s_x1; - SCASM_ScanLength = PERS_STEP; - - { - float oneOverdx = 1.0/dx; - - endZ = sptr->ig3s_z1; - deltaZ = (sptr->ig3s_z2 - endZ)*oneOverdx; - - endU = sptr->ig3s_u1; - deltaU = (sptr->ig3s_u2 - endU)*oneOverdx; - - endV = sptr->ig3s_v1; - deltaV = (sptr->ig3s_v2 - endV)*oneOverdx; - } - { - float z = 65536.0/endZ; - SCASM_StartU = endU*z; - SCASM_StartV = endV*z; - } - while(dx>PERS_STEP) - { - /* subdivide! */ - int u,v; - - dx -= PERS_STEP; - - endZ += PERS_STEP*deltaZ; - endU += PERS_STEP*deltaU; - endV += PERS_STEP*deltaV; - - { - float z = 65536.0/endZ; - u = endU*z; - v = endV*z; - } - SCASM_DeltaU = (u-SCASM_StartU)/PERS_STEP; - SCASM_DeltaV = (v-SCASM_StartV)/PERS_STEP; - - /* draw PERS_STEP pixels */ - ScanDraw2D_Gouraud(); - - SCASM_StartU = u; - SCASM_StartV = v; - - SCASM_Destination +=PERS_STEP; - SCASM_StartI += PERS_STEP*SCASM_DeltaI; - } - if (dx>0) - { - int u,v; - SCASM_ScanLength = dx; - { - float z = 65536.0/sptr->ig3s_z2; - u = sptr->ig3s_u2*z; - v = sptr->ig3s_v2*z; - } - SCASM_DeltaU = (u-SCASM_StartU)/dx; - SCASM_DeltaV = (v-SCASM_StartV)/dx; - - /* draw 8 pixels */ - ScanDraw2D_Gouraud(); - } - - - - - - } - sptr++; - y--; - } - while(y); - } - -} -#endif - - - - - - - - - - - -#if 0 -void MakeInverseLightingTable(void) -{ - int lookingForColour; - - for(lookingForColour=1; lookingForColour<=255; lookingForColour++) - { - int exit =0; - int table; - for (table=128; (table>0 && (!exit)); table--) - { - int entry; - for(entry=1; (entry<=255 && (!exit)); entry++) - { - if(lookingForColour == *(TextureLightingTable + 256*(table) + entry)) - { - LighterTable[lookingForColour] = entry; - exit=1; - } - } - } - if (exit==0) LighterTable[lookingForColour] = 255; - } -} -#endif -struct ColourVector -{ - VECTORCH Direction; - int Magnitude; -}; - -struct ColourVector ColourTable[256]; - -void MakeInverseLightingTable(void) -{ - extern unsigned char TestPalette[]; - unsigned char *palPtr = TestPalette; - int i; - - for(i = 0; i < 256; i++) - { - VECTORCH colour; - int mag; - - colour.vx = *palPtr++; - colour.vy = *palPtr++; - colour.vz = *palPtr++; - mag = Magnitude(&colour); - - if (mag!=0) - { - colour.vx = (colour.vx*32)/mag; - colour.vy = (colour.vy*32)/mag; - colour.vz = (colour.vz*32)/mag; - } - ColourTable[i].Magnitude = mag; - ColourTable[i].Direction = colour; - } - - for(i = 0; i < 256; i++) - { - int entry; - int brightest=0; - - for(entry = 0; entry < 256; entry++) - { - VECTORCH v1 = ColourTable[i].Direction; - VECTORCH v2 = ColourTable[entry].Direction; - - if ((v1.vx == v2.vx) - &&(v1.vy == v2.vy) - &&(v1.vz == v2.vz) - &&(ColourTable[i].Magnitude < ColourTable[entry].Magnitude) - &&(ColourTable[brightest].Magnitude > ColourTable[entry].Magnitude ||(!brightest))) - brightest = entry; - } - if (brightest==0) - { - for(entry = 0; entry < 256; entry++) - { - VECTORCH v1 = ColourTable[i].Direction; - VECTORCH v2 = ColourTable[entry].Direction; - - if ((v1.vx>>2 == v2.vx>>1) - &&(v1.vy>>2 == v2.vy>>1) - &&(v1.vz>>2 == v2.vz>>1) - &&(ColourTable[i].Magnitude < ColourTable[entry].Magnitude) - &&(ColourTable[brightest].Magnitude > ColourTable[entry].Magnitude ||(!brightest))) - - brightest = entry; - } - } - - if (brightest==0) - { - for(entry = 0; entry < 256; entry++) - { - VECTORCH v1 = ColourTable[i].Direction; - VECTORCH v2 = ColourTable[entry].Direction; - - if ((v1.vx>>2 == v2.vx>>2) - &&(v1.vy>>2 == v2.vy>>2) - &&(v1.vz>>2 == v2.vz>>2) - &&(ColourTable[i].Magnitude < ColourTable[entry].Magnitude) - &&(ColourTable[brightest].Magnitude > ColourTable[entry].Magnitude ||(!brightest))) - brightest = entry; - } - } - #if 0 - if (brightest==0) - { - for(entry = 0; entry < 256; entry++) - { - VECTORCH v1 = ColourTable[i].Direction; - VECTORCH v2 = ColourTable[entry].Direction; - - if ((v1.vx>>3 == v2.vx>>3) - &&(v1.vy>>3 == v2.vy>>3) - &&(v1.vz>>3 == v2.vz>>3) - &&(ColourTable[i].Magnitude < ColourTable[entry].Magnitude) - &&(ColourTable[brightest].Magnitude > ColourTable[entry].Magnitude ||(!brightest))) - brightest = entry; - } - } - - #endif - if (brightest==0) brightest = i; - - LighterTable[i] = brightest; - } - - -} - - -void DrawPaletteScreen(void) -{ - int sortedColours[256]; - { - extern unsigned char TestPalette[]; - unsigned char *palPtr = TestPalette; - int i; - - for(i = 0; i < 256; i++) - { - VECTORCH colour; - int mag; - - colour.vx = *palPtr++; - colour.vy = *palPtr++; - colour.vz = *palPtr++; - mag = Magnitude(&colour); - - if (mag!=0) - { - colour.vx = (colour.vx*7)/mag; - colour.vy = (colour.vy*7)/mag; - colour.vz = (colour.vz*7)/mag; - } - ColourTable[i].Magnitude = mag; - ColourTable[i].Direction = colour; - } - - for(i = 0; i<256; i++) - { - int e; - int maxKey=-1; - int selectedEntry=0; - - for (e=0; e<256; e++) - { - int key = ColourTable[e].Direction.vx + ColourTable[e].Direction.vy*64+ColourTable[e].Direction.vz*64*64; - if (key>maxKey) - { - maxKey = key; - selectedEntry = e; - } - else if (key==maxKey) - { - if (ColourTable[e].Magnitude<ColourTable[selectedEntry].Magnitude) - selectedEntry = e; - } - } - - sortedColours[i] = selectedEntry; - ColourTable[selectedEntry].Direction.vx=-1; - ColourTable[selectedEntry].Direction.vy=-1; - ColourTable[selectedEntry].Direction.vz=-1; - } - - } - { - char colour = 0; - int *bufferPtr = (int*)ScreenBuffer; - int i,x,y; - - for (i=0; i<=12; i++) - { - for (y=0; y<=6; y++) - { - for (x=0; x<=19; x++) - { - unsigned int c=colour+x; - - if (c<256) - { - c = sortedColours[c]; - c = c + (c<<8) + (c<<16) +(c<<24); - *bufferPtr++=c; - *bufferPtr++=c; - *bufferPtr++=c; - *bufferPtr++=c; - } - else - { - bufferPtr++; - bufferPtr++; - bufferPtr++; - bufferPtr++; - } - } - } - colour+=20; - } - } - - #if 0 - { - extern unsigned char TestPalette[]; - unsigned char *palPtr = TestPalette; - int i; - - for(i = 0; i < 256; i++) - { - VECTORCH colour; - int mag; - - colour.vx = *palPtr++; - colour.vy = *palPtr++; - colour.vz = *palPtr++; - mag = Magnitude(&colour); - if (mag!=0) - { - colour.vx = (colour.vx*63)/mag; - colour.vy = (colour.vy*63)/mag; - colour.vz = (colour.vz*63)/mag; - } - - ColourTable[i].Direction = colour; - ColourTable[i].Magnitude = mag; - } - - for(i = 0; i<256; i++) - { - int e; - int maxKey=-1; - int selectedEntry=0; - - for (e=0; e<256; e++) - { - int key = ColourTable[e].Magnitude; - - if (key>maxKey) - { - maxKey = key; - selectedEntry = e; - } - else if (key==maxKey) - { - int key2 = ColourTable[e].Direction.vx + ColourTable[e].Direction.vy*64+ColourTable[e].Direction.vz*64*64; - int key3 = ColourTable[selectedEntry].Direction.vx - + ColourTable[selectedEntry].Direction.vy*64 - + ColourTable[selectedEntry].Direction.vz*64*64; - - if (key2<key3) - selectedEntry=e; - } - - } - - sortedColours[i] = selectedEntry; - ColourTable[selectedEntry].Magnitude=-1; - } - - } - { - char colour = 0; - int *bufferPtr = (int*)(ScreenBuffer+32000); - int i,x,y; - - for (i=0; i<=12; i++) - { - for (y=0; y<=6; y++) - { - for (x=0; x<=19; x++) - { - unsigned int c=colour+x; - - if (c<256) - { - c = sortedColours[c]; - c = c + (c<<8) + (c<<16) +(c<<24); - *bufferPtr++=c; - *bufferPtr++=c; - *bufferPtr++=c; - *bufferPtr++=c; - } - else - { - bufferPtr++; - bufferPtr++; - bufferPtr++; - bufferPtr++; - } - } - } - colour+=20; - } - } - #else - { - extern unsigned char TestPalette[]; - char colour = 0; - int *bufferPtr = (int*)(ScreenBuffer+32000); - int i,x,y; - - for (i=0; i<=12; i++) - { - for (y=0; y<=6; y++) - { - for (x=0; x<=19; x++) - { - unsigned int c=colour+x; - - if (c<256) - { - c = c + (c<<8) + (c<<16) +(c<<24); - *bufferPtr++=c; - *bufferPtr++=c; - *bufferPtr++=c; - *bufferPtr++=c; - } - else - { - bufferPtr++; - bufferPtr++; - bufferPtr++; - bufferPtr++; - } - } - } - colour+=20; - } - } - #endif -} - -void OddLineScreenCopy(unsigned int *source,unsigned int *dest) -{ - int lines = 240; - - do - { - int i = 640/4; - - dest += 640/4; - source += 640/4; - - do - { - *dest++=*source++; - } - while(--i); - } - while(--lines); - -} - - - -/*KJL***************************************************** -* Palette fading; a value of 65536 corresponds to normal * -* palette, 0 is completely black. * -*****************************************************KJL*/ -void SetPaletteFadeLevel(int fadeLevel) -{ - extern int ScanDrawMode; - if(ScanDrawDirectDraw == ScanDrawMode) - { - extern unsigned char TestPalette[]; - extern unsigned char TestPalette2[]; - { - int x; - for (x=0; x<768; x++) - { - TestPalette2[x] = ((unsigned int)TestPalette[x]*fadeLevel)>>16; - } - } - ChangePalette(TestPalette2); - } - else - { - d3d_light_ctrl.ctrl = LCCM_CONSTCOLOUR; - d3d_light_ctrl.r = fadeLevel; - d3d_light_ctrl.g = fadeLevel; - d3d_light_ctrl.b = fadeLevel; - } -} - -void FadeBetweenPalettes(unsigned char *palPtr, int fadeLevel) -{ - extern unsigned char TestPalette[]; - unsigned char TestPalette3[768]; - { - int x; - for (x=0; x<768; x++) - { - TestPalette3[x] = ( (unsigned int)TestPalette[x]*fadeLevel + (unsigned int)(palPtr[x])*(65536-fadeLevel) )>>16; - } - } - ChangePalette(TestPalette3); -} -void FadePaletteToWhite(unsigned char *palPtr,int fadeLevel) -{ - unsigned char TestPalette3[768]; - { - int x; - for (x=0; x<768; x++) - { - TestPalette3[x] = ( (unsigned int)(palPtr[x])*fadeLevel + 63*(65536-fadeLevel) )>>16; - } - } - ChangePalette(TestPalette3); -} - - -void BlankScreen(void) -{ - extern int ScanDrawMode; - - if (ScanDrawDirectDraw==ScanDrawMode) - { - extern unsigned char *ScreenBuffer; - extern unsigned char TestPalette[]; - unsigned int *screenPtr; - int i; - - screenPtr = (unsigned int *)ScreenBuffer; - i = ScreenDescriptorBlock.SDB_Width * ScreenDescriptorBlock.SDB_Height /4; - do - { - *screenPtr++=0; - } - while(--i); - } - else - { - ColourFillBackBuffer(0); - } - - // FlipBuffers(); -} - - - - -void GenerateReciprocalTable(void) -{ - int i=320; - - do - { - ReciprocalTable[i] = 65536/i; - } - while(--i); -} - - - - -#if 0 -#define NO_OF_STARS 500 -typedef struct -{ - VECTORCH Position; - int Colour; - -} STARDESC; -static STARDESC StarArray[NO_OF_STARS]; -#endif -void CreateStarArray(void) -{ - #if 0 - int i; - extern int sine[],cosine[]; - for(i=0; i<NO_OF_STARS; i++) - { - int phi = FastRandom()&4095; - int theta = FastRandom()&4095; - - StarArray[i].Position.vx = MUL_FIXED(GetCos(phi),GetSin(theta)); - StarArray[i].Position.vy = MUL_FIXED(GetSin(phi),GetSin(theta)); - StarArray[i].Position.vz = GetCos(theta); - StarArray[i].Colour = FastRandom()&32767; - } - #endif -} - -/* KJL 12:10:36 9/30/97 - starfield, currently implemented for 8 & 16 bit displays */ -void DrawStarfilledSky(void) -{ - #if 0 - int i; - extern VIEWDESCRIPTORBLOCK *Global_VDB_Ptr; - extern int ScanDrawMode; - - /* blank the screen */ - ColourFillBackBuffer(0); - - LockSurfaceAndGetBufferPointer(); - - if(AvP.PlayerType==I_Alien) /* wide frustrum */ - { - for(i=0; i<NO_OF_STARS; i++) - { - VECTORCH rotatedPosition = StarArray[i].Position; - - /* rotate star into view space */ - RotateVector(&rotatedPosition,&(Global_VDB_Ptr->VDB_Mat)); - - /* is star within alien (wide) view frustrum ? */ - if((-rotatedPosition.vx <= rotatedPosition.vz*2) - &&(rotatedPosition.vx <= rotatedPosition.vz*2) - &&(-rotatedPosition.vy*2 <= rotatedPosition.vz*3) - &&(rotatedPosition.vy*2 <= rotatedPosition.vz*3)) - { - /* project into screen space */ - int y = (rotatedPosition.vy*(Global_VDB_Ptr->VDB_ProjY))/rotatedPosition.vz+Global_VDB_Ptr->VDB_CentreY; - int x = (rotatedPosition.vx*(Global_VDB_Ptr->VDB_ProjX))/rotatedPosition.vz+Global_VDB_Ptr->VDB_CentreX; - - /* draw pixel of required bit depth */ - if (ScanDrawMode == ScanDrawDirectDraw) - { - /* 8 bit mode */ - *(ScreenBuffer + x + y*BackBufferPitch) = StarArray[i].Colour&255; - } - else - { - /* 16 bit mode */ - *(unsigned short*)(ScreenBuffer + (x*2 + y*BackBufferPitch)) = StarArray[i].Colour; - } - } - } - } - else /* normal frustrum */ - { - for(i=0; i<NO_OF_STARS; i++) - { - VECTORCH rotatedPosition = StarArray[i].Position; - - /* rotate star into view space */ - RotateVector(&rotatedPosition,&(Global_VDB_Ptr->VDB_Mat)); - - /* is star within normal view frustrum ? */ - if((-rotatedPosition.vx <= rotatedPosition.vz) - &&(rotatedPosition.vx <= rotatedPosition.vz) - &&(-rotatedPosition.vy*4 <= rotatedPosition.vz*3) - &&(rotatedPosition.vy*4 <= rotatedPosition.vz*3)) - { - /* project into screen space */ - int y = (rotatedPosition.vy*(Global_VDB_Ptr->VDB_ProjY))/rotatedPosition.vz+Global_VDB_Ptr->VDB_CentreY; - int x = (rotatedPosition.vx*(Global_VDB_Ptr->VDB_ProjX))/rotatedPosition.vz+Global_VDB_Ptr->VDB_CentreX; - - /* draw pixel of required bit depth */ - if (ScanDrawMode == ScanDrawDirectDraw) - { - /* 8 bit mode */ - *(ScreenBuffer + x + y*BackBufferPitch) = StarArray[i].Colour&255; - } - else - { - /* 16 bit mode */ - *(unsigned short*)(ScreenBuffer + (x*2 + y*BackBufferPitch)) = StarArray[i].Colour; - } - } - } - } - - UnlockSurface(); - #endif -}
\ No newline at end of file diff --git a/3dc/win95/LTCHUNK.CPP b/3dc/win95/LTCHUNK.CPP deleted file mode 100644 index b000a9c..0000000 --- a/3dc/win95/LTCHUNK.CPP +++ /dev/null @@ -1,489 +0,0 @@ -#include "chunk.hpp" - -#include "ltchunk.hpp" - - -#ifdef cencon -#define new my_new -#endif - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(ltchunk) - -//////////////////////////////////////////////////////////////////////////////////// -//Class Light_Set_Chunk - -RIF_IMPLEMENT_DYNCREATE("LIGHTSET",Light_Set_Chunk) - -CHUNK_WITH_CHILDREN_LOADER("LIGHTSET",Light_Set_Chunk) - -/* -Children for Light_Set_Chunk : - -"LTSETHDR" Light_Set_Header_Chunk -"STDLIGHT" Light_Chunk -"AMBIENCE" Lighting_Ambience_Chunk -"LITSCALE" Light_Scale_Chunk -"AVPSTRAT" AVP_Strategy_Chunk -*/ - -Light_Set_Chunk::Light_Set_Chunk (Chunk_With_Children * parent, char * light_set_name) -: Chunk_With_Children (parent, "LIGHTSET") -{ - new Light_Set_Header_Chunk (this, light_set_name); -} - - - -//////////////////////////////////////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("LTSETHDR",Light_Set_Header_Chunk) - -Light_Set_Header_Chunk::Light_Set_Header_Chunk (Light_Set_Chunk * parent, char l_set_name[8]) -: Chunk (parent, "LTSETHDR"), pad (0) -{ - strncpy (light_set_name, l_set_name, 8); -} - -void Light_Set_Header_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - strncpy (data_start, light_set_name, 8); - - data_start += 8; - - *((int *) data_start) = pad; -} - -Light_Set_Header_Chunk::Light_Set_Header_Chunk (Chunk_With_Children * parent, const char * data, size_t const /*size*/) -: Chunk (parent, "LTSETHDR") -{ - strncpy (light_set_name, data, 8); - - data += 8; - - pad = *((int *) data); -} - - -//////////////////////////////////////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("STDLIGHT",Light_Chunk) - - -void Light_Chunk::fill_data_block ( char * data_start) -{ - - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = light.light_number; - data_start += 4; - - *((ChunkVectorInt *) data_start) = light.location; - data_start += sizeof(ChunkVectorInt); - - *((ChunkMatrix *) data_start) = light.orientation; - data_start += sizeof(ChunkMatrix); - - *((int *) data_start) = light.brightness; - data_start += 4; - *((int *) data_start) = light.spread; - data_start += 4; - *((int *) data_start) = light.range; - data_start += 4; - - *((int *) data_start) = light.colour; - data_start += 4; - - *((int *) data_start) = light.engine_light_flags; - data_start += 4; - *((int *) data_start) = light.local_light_flags; - data_start += 4; - - *((int *) data_start) = light.pad1; - data_start += 4; - *((int *) data_start) = light.pad2; - -} -#if UseOldChunkLoader -Light_Chunk::Light_Chunk(Light_Set_Chunk * parent, const char * data, size_t const /*size*/) -: Chunk (parent, "STDLIGHT") -{ - light.light_number = *((int *) data); - data += 4; - - light.location = *((ChunkVector *) data); - data += sizeof(ChunkVector); - - light.orientation.mat11 = (int) *((double *) data); - data += 8; - light.orientation.mat12 = (int) *((double *) data); - data += 8; - light.orientation.mat13 = (int) *((double *) data); - data += 8; - light.orientation.mat21 = (int) *((double *) data); - data += 8; - light.orientation.mat22 = (int) *((double *) data); - data += 8; - light.orientation.mat23 = (int) *((double *) data); - data += 8; - light.orientation.mat31 = (int) *((double *) data); - data += 8; - light.orientation.mat32 = (int) *((double *) data); - data += 8; - light.orientation.mat33 = (int) *((double *) data); - data += 8; - - light.brightness = *((int *) data); - data += 4; - light.spread = *((int *) data); - data += 4; - light.range = *((int *) data); - data += 4; - - light.colour = *((int *) data); - data += 4; - - light.engine_light_flags = *((int *) data); - data += 4; - light.local_light_flags = *((int *) data); - data += 4; - - light.pad1 = *((int *) data); - data += 4; - light.pad2 = *((int *) data); - - #if engine || cencon - light_added_to_module = FALSE; - #endif - -} -#else -Light_Chunk::Light_Chunk(Chunk_With_Children * parent, const char * data, size_t const /*size*/) -: Chunk (parent, "STDLIGHT") -{ - light.light_number = *((int *) data); - data += 4; - - light.location = *((ChunkVectorInt *) data); - data += sizeof(ChunkVectorInt); - - light.orientation = *((ChunkMatrix *) data); - data += sizeof(ChunkMatrix); - - light.brightness = *((int *) data); - data += 4; - light.spread = *((int *) data); - data += 4; - light.range = *((int *) data); - data += 4; - - light.colour = *((int *) data); - data += 4; - - light.engine_light_flags = *((int *) data); - data += 4; - light.local_light_flags = *((int *) data); - data += 4; - - light.pad1 = *((int *) data); - data += 4; - light.pad2 = *((int *) data); - - #if engine || cencon - light_added_to_module = FALSE; - #endif - -} -#endif - -#if InterfaceEngine -AVP_Strategy_Chunk* Light_Chunk::GetStrategyChunk() -{ - List<Chunk*> chlist; - parent->lookup_child("AVPSTRAT",chlist); - for(LIF<Chunk*> chlif(&chlist);!chlif.done();chlif.next()) - { - AVP_Strategy_Chunk* asc=(AVP_Strategy_Chunk*)chlif(); - if(asc->index==light.light_number) return asc; - } - return 0; -} - -AVP_Strategy_Chunk* Light_Chunk::CreateStrategyChunk() -{ - AVP_Strategy_Chunk* asc=GetStrategyChunk(); - if(asc) return asc; - - asc=new AVP_Strategy_Chunk(parent); - asc->index=light.light_number; - return asc; -} -#endif - -//////////////////////////////////////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("SHPVTINT",Shape_Vertex_Intensities_Chunk) - - -Shape_Vertex_Intensities_Chunk::Shape_Vertex_Intensities_Chunk -(Chunk_With_Children *parent, char *lsn, int num_v, int * i_array) -: Chunk (parent, "SHPVTINT"), num_vertices(num_v), pad (0) -{ - strncpy (light_set_name, lsn, 8); - - intensity_array = new int [num_v]; - - for (int i=0; i<num_v; i++) - { - intensity_array[i] = i_array[i]; - } -} - - -void Shape_Vertex_Intensities_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - strncpy (data_start, light_set_name,8); - - data_start += 8; - - *((int *) data_start) = pad; - - data_start += 4; - - *((int *) data_start) = num_vertices; - - data_start += 4; - - int * cia = (int *)data_start, * ia = intensity_array; - - for (int i = num_vertices; i; i--) - { - *cia++ = *ia++; - } - -} - -Shape_Vertex_Intensities_Chunk::Shape_Vertex_Intensities_Chunk(Chunk_With_Children * parent, const char * data, size_t const /*size*/) -: Chunk (parent, "SHPVTINT") -{ - strncpy (light_set_name, data, 8); - - data += 8; - - pad = *((int *)data); - data += 4; - - num_vertices = *((int *)data); - data += 4; - - intensity_array = new int [num_vertices]; - - int * cia = (int *)data, * ia = intensity_array; - - for (int i = num_vertices; i; i--) - { - *ia++ = *cia++; - } -} - - -Shape_Vertex_Intensities_Chunk::~Shape_Vertex_Intensities_Chunk() -{ - if (intensity_array) - delete [] intensity_array; -} - -/////////////////////////////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("AMBIENCE",Lighting_Ambience_Chunk) - - -void Lighting_Ambience_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = ambience; - data_start += 4; -} - - - -/////////////////////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("LITSCALE",Light_Scale_Chunk) - -Light_Scale_Chunk::Light_Scale_Chunk(Light_Set_Chunk* parent,int mode) -:Chunk(parent,"LITSCALE") -{ - LightMode=mode; - prelight_multiply=runtime_multiply=1; - prelight_multiply_above=runtime_multiply_above=0; - prelight_add=runtime_add=0; - spare1=spare2=spare3=0; -} - -Light_Scale_Chunk::Light_Scale_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"LITSCALE") -{ - LightMode=*(int*)data; - data+=4; - prelight_multiply=*(float*)data; - data+=4; - prelight_multiply_above= (int) *(float*)data; - data+=4; - prelight_add= (int) *(float*)data; - data+=4; - - runtime_multiply=*(float*)data; - data+=4; - runtime_multiply_above= (int) *(float*)data; - data+=4; - runtime_add= (int) *(float*)data; - data+=4; - - spare1=*(int*)data; - data+=4; - spare2=*(int*)data; - data+=4; - spare3=*(int*)data; - data+=4; - -} - -void Light_Scale_Chunk::fill_data_block(char* data_start) -{ - strncpy(data_start,identifier,8); - data_start+=8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(int*)data_start=LightMode; - data_start+=4; - - *(float*)data_start=prelight_multiply; - data_start+=4; - *(float*)data_start= (float) prelight_multiply_above; - data_start+=4; - *(float*)data_start= (float) prelight_add; - data_start+=4; - - *(float*)data_start=runtime_multiply; - data_start+=4; - *(float*)data_start= (float) runtime_multiply_above; - data_start+=4; - *(float*)data_start= (float) runtime_add; - data_start+=4; - - *(int*)data_start=spare1; - data_start+=4; - *(int*)data_start=spare2; - data_start+=4; - *(int*)data_start=spare3; - data_start+=4; -} - -int Light_Scale_Chunk::ApplyPrelightScale(int l) -{ - if(l<prelight_multiply_above)return l; - l+=(prelight_add-prelight_multiply_above); - l= (int)(l*prelight_multiply); - l+=prelight_multiply_above; - l=min(l,255); - return max(l,prelight_multiply_above); -} -int Light_Scale_Chunk::ApplyRuntimeScale(int l) -{ - if(l<runtime_multiply_above)return l; - l+=(runtime_add-runtime_multiply_above); - l=(int)( l*runtime_multiply); - l+=runtime_multiply_above; - l=min(l,255); - return max(l,runtime_multiply_above); -} -//////////////////////////////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("PLOBJLIT",Placed_Object_Light_Chunk) - -Placed_Object_Light_Chunk::Placed_Object_Light_Chunk(Chunk_With_Children * parent, const char * data, size_t const /*size*/) -: Chunk (parent, "PLOBJLIT") -{ - light=*(Placed_Object_Light_Data*) data; - data+=sizeof(Placed_Object_Light_Data); - - num_extra_data=*(int*)data; - data+=4; - - if(num_extra_data) - { - extra_data=new int[num_extra_data]; - for(int i=0;i<num_extra_data;i++) - { - extra_data[i]=*(int*)data; - data+=4; - } - } - else - { - extra_data=0; - } -} - -Placed_Object_Light_Chunk::~Placed_Object_Light_Chunk() -{ - if(extra_data) - { - delete [] extra_data; - } -} - -void Placed_Object_Light_Chunk::fill_data_block(char* data) -{ - strncpy (data, identifier, 8); - - data += 8; - - *((int *) data) = chunk_size; - - data += 4; - - *(Placed_Object_Light_Data*)data=light; - data+=sizeof(Placed_Object_Light_Data); - - *(int*)data=num_extra_data; - data+=4; - - for(int i=0;i<num_extra_data;i++) - { - *(int*)data=extra_data[i]; - data+=4; - } -} - - -//////////////////////////////////////////////////////////////////////////////////// diff --git a/3dc/win95/LTCHUNK.HPP b/3dc/win95/LTCHUNK.HPP deleted file mode 100644 index 2ed6b78..0000000 --- a/3dc/win95/LTCHUNK.HPP +++ /dev/null @@ -1,273 +0,0 @@ -#ifndef _ltchunk_hpp -#define _ltchunk_hpp 1 - -#include "chunk.hpp" -#include "chnktype.hpp" - -#if InterfaceEngine -#include "strachnk.hpp" -#endif - -#define LOFlag_On 0x00000001 -#define LOFlag_ShadowData 0x00000002 -#define LOFlag_Changed 0x00000004 -#define LOFlag_Calc_Data 0x00000008 -#define LOFlag_Runtime 0x00000010 -#define LOFlag_Invisible 0x00000020 -#define LOFlag_NoPreLight 0x00000040 - -class Environment_Data_Chunk; - -class Light_Data -{ -public: - - int light_number; - ChunkVectorInt location; - ChunkMatrix orientation; - - int brightness; - int spread; - int range; - - int colour; - - int engine_light_flags; - int local_light_flags; - - int pad1; - int pad2; - -}; - - -#define PlacedLightType_Standard 0 -#define PlacedLightType_Strobe 1 -#define PlacedLightType_Flicker 2 - -#define PlacedLightOnOff_Standard 0 -#define PlacedLightOnOff_Fade 1 -#define PlacedLightOnOff_Flicker 2 - -#define PlacedLightFlag_On 0x00000001 -#define PlacedLightFlag_SwapColourBright 0x00000002 -#define PlacedLightFlag_NoSpecular 0x00000004 -class Placed_Object_Light_Data -{ -public: - - int brightness; - int spread; - int range; - - int up_colour; - int down_colour; - - int engine_light_flags; - int local_light_flags; - - int fade_up_time; - int fade_down_time; - int up_time; - int down_time; - int start_time; - - int light_type; - int on_off_type; - int flags; - - -}; - -class Light_Set_Chunk : public Chunk_With_Children -{ -public: - - // for user - - Light_Set_Chunk (Chunk_With_Children * parent, char * light_set_name); - Light_Set_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - -private: - - friend class Environment_Data_Chunk; - - - -}; - - -class Light_Set_Header_Chunk : public Chunk -{ -public: - - Light_Set_Header_Chunk (Light_Set_Chunk * parent, char l_set_name[8]); - Light_Set_Header_Chunk (Chunk_With_Children * parent, const char *, size_t const); - char light_set_name[8]; - - int pad; - - size_t size_chunk() - { - return (chunk_size = 12 + 8 + 4); - } - - void fill_data_block ( char * data_start); - -private: - - friend class Light_Set_Chunk; - - - -}; - - -class Light_Chunk : public Chunk -{ -public: - - Light_Chunk (Light_Set_Chunk * parent, Light_Data & new_light) - : Chunk (parent, "STDLIGHT"), light (new_light) {} - - Light_Chunk (Chunk_With_Children * parent, const char *, size_t const); - - Light_Data light; - - BOOL light_added_to_module; - - size_t size_chunk() - { - return (chunk_size = 12 + 9 * 4 + 3 * 4 + 9 * 4); - } - - void fill_data_block ( char * data_start); - -#if InterfaceEngine - AVP_Strategy_Chunk* GetStrategyChunk(); - AVP_Strategy_Chunk* CreateStrategyChunk(); -#endif - -private: - - friend class Light_Set_Chunk; - - - -}; - -//should be a child of an object_chunk -class Placed_Object_Light_Chunk : public Chunk -{ -public : - Placed_Object_Light_Chunk (Chunk_With_Children * parent, Placed_Object_Light_Data & new_light) - : Chunk (parent, "PLOBJLIT"), light (new_light),num_extra_data(0),extra_data(0) {} - - Placed_Object_Light_Chunk (Chunk_With_Children * parent, const char *, size_t const); - - ~Placed_Object_Light_Chunk(); - - Placed_Object_Light_Data light; - int* extra_data; - int num_extra_data; - - size_t size_chunk() - { - return (chunk_size = 12 +sizeof(Placed_Object_Light_Data) +4 +4*num_extra_data); - } - - void fill_data_block ( char * data_start); - -}; - - -class Shape_Vertex_Intensities_Chunk : public Chunk -{ -public: - - Shape_Vertex_Intensities_Chunk(Chunk_With_Children *, char *, int, int *); - Shape_Vertex_Intensities_Chunk(Chunk_With_Children *, const char *, size_t const); - ~Shape_Vertex_Intensities_Chunk(); - - char light_set_name[8]; - - int pad; - - int num_vertices; - - int * intensity_array; - - size_t size_chunk() - { - return (chunk_size = 12 + 8 + 4 + 4 + 4 * num_vertices); - } - - void fill_data_block ( char * data_start); - -private: - - friend class Object_Chunk; - - - -}; - -class Lighting_Ambience_Chunk : public Chunk -{ -public: - - Lighting_Ambience_Chunk (Light_Set_Chunk * parent, int _ambience) - : Chunk (parent, "AMBIENCE"), ambience (_ambience) - {} - Lighting_Ambience_Chunk (Chunk_With_Children * parent, const char * data, size_t const /*size*/) - : Chunk (parent, "AMBIENCE"), ambience (*((int *)data)) - {} - int ambience; - - size_t size_chunk() - { - return (chunk_size = 12 + 4); - } - - void fill_data_block ( char * data_start); - -private: - - friend class Light_Set_Chunk; - - - -}; - -#define PSXLightMode 0 -//details of how light data should be altered for different platforms. -//currently just playstation -class Light_Scale_Chunk : public Chunk -{ -public : - Light_Scale_Chunk(Light_Set_Chunk * parent,int mode); - Light_Scale_Chunk(Chunk_With_Children* parent,const char* data,size_t); - - void fill_data_block ( char * data_start); - size_t size_chunk() - { - return (chunk_size = 12 + 44); - } - - int LightMode; - float prelight_multiply; - int prelight_multiply_above; - int prelight_add; - - float runtime_multiply; - int runtime_multiply_above; - int runtime_add; - - - int ApplyPrelightScale(int l); - int ApplyRuntimeScale(int l); - - int spare1,spare2,spare3,spare4; -}; - -#endif
\ No newline at end of file diff --git a/3dc/win95/MISHCHNK.CPP b/3dc/win95/MISHCHNK.CPP deleted file mode 100644 index 5f4dde3..0000000 --- a/3dc/win95/MISHCHNK.CPP +++ /dev/null @@ -1,1999 +0,0 @@ -#include "chunk.hpp" -#include "chnktype.hpp" -#include "mishchnk.hpp" - -#include "shpchunk.hpp" -#include "obchunk.hpp" - - - -#include "huffman.hpp" - - -#include <mbstring.h> - -#ifdef cencon -#define new my_new -#endif - - -// Class Lockable_Chunk_With_Children functions - -#if cencon -#else -extern char * users_name; -#endif - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(mishchnk) - -BOOL Lockable_Chunk_With_Children::lock_chunk(File_Chunk & fchunk) -{ - if (!fchunk.filename) return FALSE; - - if (local_lock) return FALSE; // you can't lock a chunk twice - - #if DisableLock - if(external_lock) return FALSE; - local_lock = TRUE; - set_lock_user (users_name); - return TRUE; - #else - if (!fchunk.check_file()) return FALSE; - if (updated_outside || external_lock) return FALSE; - - HANDLE rif_file; - unsigned long bytes_read; - - int tries = 0; - - rif_file = CreateFile (fchunk.filename, GENERIC_WRITE + GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - - while(rif_file == INVALID_HANDLE_VALUE && tries<10) - { - rif_file = CreateFile (fchunk.filename, GENERIC_WRITE + GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - tries ++; - clock_t ctime = clock(); - double secs = (double)ctime / (double)CLOCKS_PER_SEC; - double secsgone; - do - { - ctime = clock(); - secsgone = (double)ctime / (double)CLOCKS_PER_SEC; - } - while( (secsgone-secs)<1); - } - - if (rif_file == INVALID_HANDLE_VALUE) { - return FALSE; - } - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> chfptrs; - list_chunks_in_file(& chfptrs, rif_file, identifier); - - LIF<int> cfpl(&chfptrs); - - if (chfptrs.size()) { - for (; !cfpl.done(); cfpl.next()) { - - SetFilePointer (rif_file, cfpl(),0,FILE_BEGIN); - - if (file_equals(rif_file)) break; - } - } - - if (!cfpl.done()) { - - // go to start of chunk - SetFilePointer (rif_file,cfpl(),0,FILE_BEGIN); - - // get header list - if (get_head_id()) - { - List<int> obhead; - list_chunks_in_file(& obhead, rif_file, get_head_id()); - - assert (obhead.size() == 1); - - int flags; - - // go to lock status in header - SetFilePointer(rif_file,obhead.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - SetFilePointer(rif_file,-4,0,FILE_CURRENT); - flags |= GENERAL_FLAG_LOCKED; - WriteFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - WriteFile (rif_file, (long *) &users_name[0], 16, &bytes_read, 0); - } - - } - - local_lock = TRUE; - - set_lock_user (users_name); - - CloseHandle (rif_file); - return TRUE; - #endif - -} - -BOOL Lockable_Chunk_With_Children::unlock_chunk (File_Chunk & fchunk, BOOL updateyn) -{ - if (updateyn) { - updated = TRUE; - } - #if DisableLock - local_lock = FALSE; - (void)fchunk; - #else - else - { - fchunk.check_file(); - if (updated_outside || external_lock) return FALSE; - - HANDLE rif_file; - unsigned long bytes_read; - - rif_file = CreateFile (fchunk.filename, GENERIC_WRITE + GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - - if (rif_file == INVALID_HANDLE_VALUE) { - return FALSE; - } - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> chfptrs; - list_chunks_in_file(& chfptrs, rif_file, identifier); - - List<obinfile> obs; - - char name[50]; - - LIF<int> ofpl(&chfptrs); - - if (chfptrs.size()) { - for (; !ofpl.done(); ofpl.next()) { - - SetFilePointer (rif_file, ofpl(),0,FILE_BEGIN); - - if (file_equals(rif_file)) break; - } - } - - if (!ofpl.done()) { - - // go to start of chunk - SetFilePointer (rif_file,ofpl(),0,FILE_BEGIN); - - // get header list - if (get_head_id()) - { - List<int> obhead; - list_chunks_in_file(& obhead, rif_file, get_head_id()); - - assert (obhead.size() == 1); - - int flags; - - // go to lock status in header - SetFilePointer(rif_file,obhead.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - SetFilePointer(rif_file,-4,0,FILE_CURRENT); - flags &= ~GENERAL_FLAG_LOCKED; - WriteFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - WriteFile (rif_file, (long *) &users_name[0], 16, &bytes_read, 0); - } - - } - - local_lock = FALSE; - - CloseHandle (rif_file); - } - #endif - - - return TRUE; - -} - - -BOOL Lockable_Chunk_With_Children::update_chunk_in_file(HANDLE &rif_file) -{ - - unsigned long bytes_read; - int length = 0; - - const char * hd_id = get_head_id(); - - if (!hd_id) return FALSE; - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - //twprintf("\nLooking for chunks in file\n"); - - List<int> shpfptrs; - list_chunks_in_file(& shpfptrs, rif_file, identifier); - - // look through chunks for the save of our current chunk - - //twprintf("Checking each chunk\n"); - - LIF<int> sfpl(&shpfptrs); - - if (shpfptrs.size()) { - for (; !sfpl.done(); sfpl.next()) { - - SetFilePointer (rif_file, sfpl()+8,0,FILE_BEGIN); - - ReadFile (rif_file, (long *) &(length), 4, &bytes_read, 0); - - SetFilePointer (rif_file, sfpl(),0,FILE_BEGIN); - if (file_equals(rif_file)) break; - } - } - - // then load the file after that chunk into a buffer, - // output the chunk and write the buffer - // unless the chunk is the last one in the file - - //twprintf("Updating file\n"); - - if (!sfpl.done()) - { - - int file_length = GetFileSize(rif_file,0); - - if (file_length > (sfpl() + length)) { - - SetFilePointer (rif_file, sfpl() + length,0,FILE_BEGIN); - - char * tempbuffer; - tempbuffer = new char [file_length - (sfpl() + length)]; - - ReadFile (rif_file, (long *) tempbuffer, (file_length - (sfpl() + length)), &bytes_read, 0); - - SetFilePointer (rif_file, sfpl() ,0,FILE_BEGIN); - - if (!deleted) - { - size_chunk(); - output_chunk(rif_file); - } - - WriteFile (rif_file, (long *) tempbuffer, (file_length - (sfpl() + length)), &bytes_read, 0); - - delete [] tempbuffer; - - SetEndOfFile (rif_file); - } - else{ - - SetFilePointer (rif_file, sfpl() ,0,FILE_BEGIN); - if (!deleted) - { - size_chunk(); - output_chunk(rif_file); - } - SetEndOfFile (rif_file); - } - - } - else { - - SetFilePointer (rif_file,0 ,0,FILE_END); - if (!deleted) - { - size_chunk(); - output_chunk(rif_file); - } - SetEndOfFile (rif_file); - } - - local_lock = FALSE; - - updated = FALSE; - - int file_length = GetFileSize(rif_file,0); - SetFilePointer (rif_file,8,0,FILE_BEGIN); - - WriteFile (rif_file, (long *) &file_length, 4, &bytes_read, 0); - - - // DO NOT PUT ANY CODE AFTER THIS - - if (deleted) delete this; - - // OR ELSE !!! - - return TRUE; - -} - - -size_t Lockable_Chunk_With_Children::size_chunk_for_process() -{ - if (output_chunk_for_process) - return size_chunk(); - return(chunk_size = 0); -} - - -void Lockable_Chunk_With_Children::fill_data_block_for_process(char * data_start) -{ - if (output_chunk_for_process) - { - fill_data_block(data_start); - output_chunk_for_process = FALSE; - } -} - - - - -/////////////////////////////////////// - -// Class File_Chunk functions - -/* -Children for File_Chunk : -"REBSHAPE" Shape_Chunk -"RSPRITES" AllSprites_Chunk -"RBOBJECT" Object_Chunk -"RIFVERIN" RIF_Version_Num_Chunk -"REBENVDT" Environment_Data_Chunk -"REBENUMS" Enum_Chunk -"OBJCHIER" Object_Hierarchy_Chunk -"OBHALTSH" Object_Hierarchy_Alternate_Shape_Set_Chunk -"HIDEGDIS" Hierarchy_Degradation_Distance_Chunk -"INDSOUND" Indexed_Sound_Chunk -"HSETCOLL" Hierarchy_Shape_Set_Collection_Chunk -"DUMMYOBJ" Dummy_Object_Chunk - -*/ - -File_Chunk::File_Chunk(const char * file_name) -: Chunk_With_Children (NULL, "REBINFF2") -{ -// Load in whole chunk and traverse - char rifIsCompressed = FALSE; - char *uncompressedData = NULL; - HANDLE rif_file; - DWORD file_size; - DWORD file_size_from_file; - unsigned long bytes_read; - char * buffer; - char * buffer_ptr; - char id_buffer[9]; - - Parent_File = this; - - error_code = 0; - object_array_size=0; - object_array=0; - - filename = new char [strlen(file_name) + 1]; - - strcpy (filename, file_name); - - rif_file = CreateFileA (file_name, GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - - if (rif_file == INVALID_HANDLE_VALUE) { - error_code = CHUNK_FAILED_ON_LOAD; - return; - } - - file_size = GetFileSize (rif_file, NULL); - - - if (!ReadFile(rif_file, id_buffer, 8, &bytes_read, 0)) { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - return; - } - - #if UseOldChunkLoader - if (strncmp (id_buffer, "REBINFLF", 8)) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - CloseHandle (rif_file); - return; - } - #else - /* KJL 16:46:14 19/09/98 - check for a compressed rif */ - if (!strncmp (id_buffer, COMPRESSED_RIF_IDENTIFIER, 8)) - { - rifIsCompressed = TRUE; - } - else if (strncmp (id_buffer, "REBINFF2", 8)) - { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - CloseHandle (rif_file); - return; - } - #endif - buffer = new char [file_size]; - - /* KJL 17:57:44 19/09/98 - if the rif is compressed, we must load the whole - file in and then pass it to the decompression routine, which will return a - pointer to the original data. */ - if (rifIsCompressed) - { - if (!ReadFile(rif_file, buffer+8, (file_size-8), &bytes_read, 0)) - { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - return; - } - uncompressedData = HuffmanDecompress((HuffmanPackage*)buffer); - file_size = ((HuffmanPackage*)buffer)->UncompressedDataSize; - - delete [] buffer; // kill the buffer the compressed file was loaded into - - buffer_ptr = buffer = uncompressedData+12; // skip header data - } - else // the normal uncompressed approach: - { - if (!ReadFile(rif_file, &file_size_from_file, 4, &bytes_read, 0)) { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - return; - } - - if (file_size != file_size_from_file) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - CloseHandle (rif_file); - return; - } - - if (!ReadFile(rif_file, buffer, (file_size-12), &bytes_read, 0)) - { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - return; - } - buffer_ptr = buffer; - } - - // Process the RIF - // The start of the first chunk - - while ((buffer_ptr-buffer)< ((signed) file_size-12) && !error_code) { - - if ((*(int *)(buffer_ptr + 8)) + (buffer_ptr-buffer) > ((signed)file_size-12)) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(buffer_ptr); - buffer_ptr += *(int *)(buffer_ptr + 8); - - } - - /* KJL 17:59:42 19/09/98 - release the memory holding the rif */ - if (rifIsCompressed) - { - free(uncompressedData); - } - else - { - delete [] buffer; - } - - CloseHandle (rif_file); - - post_input_processing(); - -} - -File_Chunk::File_Chunk() -: Chunk_With_Children (NULL, "REBINFF2") -{ -// Empty File chunk - new RIF_Version_Num_Chunk (this); - filename = 0; - - object_array_size=0; - object_array=0; -} - - -File_Chunk::~File_Chunk() -{ - if (filename) - delete [] filename; - - if(object_array) - free(object_array); -} - -#define SAVE_USING_COMPRESSION 1 - -BOOL File_Chunk::write_file (const char * fname) -{ - if(!fname) return FALSE; - //if a read_only file exists with this filename , then abort attempt to save - DWORD attributes = GetFileAttributesA(fname); - if (0xffffffff!=attributes) - { - if (attributes & FILE_ATTRIBUTE_READONLY) - { - return FALSE; - } - } - - - - HANDLE rif_file; - - if (filename) delete [] filename; - - filename = new char [strlen(fname) + 1]; - strcpy (filename, fname); - - //save under a temporary name in case a crash occurs during save; - int filename_start_pos=0; - int pos=0; - while(fname[pos]) - { - if(fname[pos]=='\\' || fname[pos]==':') - { - filename_start_pos=pos+1; - } - //go to next MBCS character in string - pos+=_mbclen((unsigned const char*)&fname[pos]); - } - if(!fname[filename_start_pos]) return FALSE; - - char* temp_name=new char[strlen(fname)+7]; - strcpy(temp_name,fname); - strcpy(&temp_name[filename_start_pos],"~temp~"); - strcpy(&temp_name[filename_start_pos+6],&fname[filename_start_pos]); - - prepare_for_output(); - - - #if SAVE_USING_COMPRESSION - //create a block containing the uncompressed rif file - unsigned char* uncompressedData = (unsigned char*) make_data_block_from_chunk(); - if(!uncompressedData) return FALSE; - - //do the compression thing - HuffmanPackage *outPackage = HuffmanCompression(uncompressedData,chunk_size); - delete [] uncompressedData; - if(!outPackage) return FALSE; - - //and now try to write the file - rif_file = CreateFileA (temp_name, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, - FILE_FLAG_RANDOM_ACCESS, 0); - - if (rif_file == INVALID_HANDLE_VALUE) { - delete [] temp_name; - free (outPackage); - return FALSE; - } - - unsigned long junk; - BOOL ok; - - ok = WriteFile (rif_file, (long *) outPackage,outPackage->CompressedDataSize+sizeof(HuffmanPackage), &junk, 0); - - CloseHandle (rif_file); - - free (outPackage); - - if(!ok) return FALSE; - - - #else - size_chunk(); - - rif_file = CreateFileA (temp_name, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, - FILE_FLAG_RANDOM_ACCESS, 0); - - if (rif_file == INVALID_HANDLE_VALUE) { - delete [] temp_name; - return FALSE; - } - - if (!(this->output_chunk(rif_file))) - { - CloseHandle (rif_file); - delete [] temp_name; - return FALSE; - } - - CloseHandle (rif_file); - #endif - - //Delete the old file with this name (if it exists) , and rename the temprary file - DeleteFileA(fname); - MoveFileA(temp_name,fname); - - delete [] temp_name; - - return TRUE; -} - -// the file_chunk must link all of its shapes & objects together - -void File_Chunk::post_input_processing() -{ - List<Shape_Chunk *> shplist; - List<Object_Chunk *> objlist; - - List<Chunk *> child_lists; - - lookup_child("REBSHAPE",child_lists); - - while (child_lists.size()) { - shplist.add_entry((Shape_Chunk *)child_lists.first_entry()); - child_lists.delete_first_entry(); - } - - lookup_child("RBOBJECT",child_lists); - - while (child_lists.size()) { - objlist.add_entry((Object_Chunk *)child_lists.first_entry()); - child_lists.delete_first_entry(); - } - - for (LIF<Shape_Chunk *> sli(&shplist); !sli.done(); sli.next()) - { - Shape_Chunk::max_id = max (Shape_Chunk::max_id,sli()->get_header()->file_id_num); - } - Shape_Chunk** shape_array=new Shape_Chunk*[Shape_Chunk::max_id+1]; - - for(sli.restart();!sli.done();sli.next()) - { - shape_array[sli()->get_header()->file_id_num]=sli(); - } - - for (LIF<Object_Chunk *> ol(&objlist); !ol.done(); ol.next()) - { - ol()->assoc_with_shape(shape_array[ol()->get_header()->shape_id_no]); - } - - delete shape_array; - - - Chunk_With_Children::post_input_processing(); -} - - - -BOOL File_Chunk::check_file() -{ - if (!filename) return TRUE; - - #if DisableLock - return(TRUE); - #else - - int flags; - int v_no; - char locker[17]; - - - HANDLE rif_file; - unsigned long bytes_read; - - int tries = 0; - - rif_file = CreateFileA (filename, GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - - while(rif_file == INVALID_HANDLE_VALUE && tries<10) - { - rif_file = CreateFileA (filename, GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - tries ++; - clock_t ctime = clock(); - double secs = (double)ctime / (double)CLOCKS_PER_SEC; - double secsgone; - do - { - ctime = clock(); - secsgone = (double)ctime / (double)CLOCKS_PER_SEC; - } - while( (secsgone-secs)<1); - } - - if (rif_file == INVALID_HANDLE_VALUE) { - error_code = CHECK_FAILED_NOT_OPEN; - return FALSE; - } - - - if (rif_file == INVALID_HANDLE_VALUE) { - error_code = CHECK_FAILED_NOT_OPEN; - return FALSE; - } - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> obfptrs; - list_chunks_in_file(& obfptrs, rif_file, "RBOBJECT"); - -// ok, go through the objects, first locate the header and find -// the associated object. - - if (obfptrs.size()) { - - for (LIF<int> obflst(&obfptrs); !obflst.done(); obflst.next()) { - - // go to start of chunk - SetFilePointer (rif_file,obflst(),0,FILE_BEGIN); - - // get header list - List<int> obhead; - list_chunks_in_file(& obhead, rif_file, "OBJHEAD1"); - - assert (obhead.size() == 1); - - // go to lock status in header - SetFilePointer(rif_file,obhead.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - ReadFile (rif_file, (long *) locker, 16, &bytes_read, 0); - - // go to version number - SetFilePointer(rif_file,obhead.first_entry() + 88,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &v_no, 4, &bytes_read, 0); - - char name[50]; - - // get object identifier - SetFilePointer(rif_file,obhead.first_entry() + 96,0,FILE_BEGIN); - int i = 0; - do ReadFile (rif_file, (long *) (name + i), 1, &bytes_read, 0); - while (name[i++] != 0); - - Object_Chunk * tmpob; - Object_Header_Chunk * tmpobh; - List<Chunk *> obchs; - lookup_child ("RBOBJECT",obchs); - - if (obchs.size()){ - for (LIF<Chunk *> obchls(&obchs); !obchls.done(); obchls.next()){ - tmpob = (Object_Chunk *)obchls(); - // if this is the same object - if (!strcmp (name, tmpob->object_data.o_name)) break; - } - if (!obchls.done()) { - tmpobh = tmpob->get_header(); - if (tmpobh) { - if (tmpobh->version_no < v_no) - tmpob->updated_outside = TRUE; - if (flags & GENERAL_FLAG_LOCKED) { - // do the lock check - if (!tmpob->local_lock) { - tmpob->external_lock = TRUE; - strncpy(tmpobh->lock_user, locker,16); - tmpobh->lock_user[16] = '\0'; - } - else if (strncmp(tmpobh->lock_user, locker,16)) { - tmpob->external_lock = TRUE; - strncpy(tmpobh->lock_user, locker,16); - tmpobh->lock_user[16] = '\0'; - } - } - } - - } - - } - - } - - } - - // shapes - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> shpfptrs; - list_chunks_in_file(& shpfptrs, rif_file, "REBSHAPE"); - - if (shpfptrs.size()) { - - for (LIF<int> shpflst(&shpfptrs); !shpflst.done(); shpflst.next()) { - - // go to start of chunk - SetFilePointer (rif_file,shpflst(),0,FILE_BEGIN); - - // get header list - List<int> shphead; - list_chunks_in_file(& shphead, rif_file, "SHPHEAD1"); - - assert (shphead.size() == 1); - - // go to lock status in header - SetFilePointer(rif_file,shphead.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - ReadFile (rif_file, (long *) locker, 16, &bytes_read, 0); - - int id; - // get shape identifier - ReadFile (rif_file, (long *) &id, 4, &bytes_read, 0); - - - // Here we update max_id - Shape_Chunk::max_id = max (Shape_Chunk::max_id,id); - - // go to version number - SetFilePointer(rif_file,shphead.first_entry() + 100,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &v_no, 4, &bytes_read, 0); - - Shape_Chunk * tmpshp; - Shape_Header_Chunk * tmpshph; - List<Chunk *> shpchs; - lookup_child ("REBSHAPE",shpchs); - - if (shpchs.size()){ - for (LIF<Chunk *> shpchls(&shpchs); !shpchls.done(); shpchls.next()){ - tmpshp = (Shape_Chunk *)shpchls(); - tmpshph = tmpshp->get_header(); - // if this is the same object - if (tmpshph) - if (id == tmpshph->file_id_num) break; - } - if (!shpchls.done()) { - if (tmpshph->version_no < v_no) - tmpshp->updated_outside = TRUE; - if (flags & GENERAL_FLAG_LOCKED) { - // do the lock check - if (!tmpshp->local_lock) { - tmpshp->external_lock = TRUE; - strncpy(tmpshph->lock_user, locker,16); - tmpshph->lock_user[16] = '\0'; - } - else if (strncmp(tmpshph->lock_user, locker,16)) { - tmpshp->external_lock = TRUE; - strncpy(tmpshph->lock_user, locker,16); - tmpshph->lock_user[16] = '\0'; - } - } - - } - - } - - } - - } - - // sprites - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> sprfptrs; - list_chunks_in_file(& sprfptrs, rif_file, "RSPRITES"); - List<Chunk *> sprchlst; - lookup_child("RSPRITES",sprchlst); - - AllSprites_Chunk * sprch; - AllSprites_Header_Chunk * sprhead = 0; - - if (sprchlst.size()) - { - sprch = (AllSprites_Chunk *)sprchlst.first_entry(); - sprhead = sprch->get_header(); - } - - if (sprhead) - { - if (sprfptrs.size()) - { - SetFilePointer (rif_file,sprfptrs.first_entry(),0,FILE_BEGIN); - - // get header list - List<int> sprchhl; - list_chunks_in_file(& sprchhl, rif_file, "ASPRHEAD"); - - assert (sprchhl.size() == 1); - - // go to lock status in header - SetFilePointer(rif_file,sprchhl.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - ReadFile (rif_file, (long *) locker, 16, &bytes_read, 0); - - // go to version number - SetFilePointer(rif_file,sprchhl.first_entry() + 32,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &v_no, 4, &bytes_read, 0); - - if (sprhead->version_no < v_no) - { - sprch->updated_outside = TRUE; - } - if (flags & GENERAL_FLAG_LOCKED) - { - if (!sprch->local_lock) { - sprch->external_lock = TRUE; - strncpy(sprhead->lock_user, locker,16); - sprhead->lock_user[16] = '\0'; - } - else if (strncmp(sprhead->lock_user, locker,16)) { - sprch->external_lock = TRUE; - strncpy(sprhead->lock_user, locker,16); - sprhead->lock_user[16] = '\0'; - } - } - } - } - - // environment data - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> edfptrs; - list_chunks_in_file(& edfptrs, rif_file, "REBENVDT"); - - Environment_Data_Chunk * ed; - Environment_Data_Header_Chunk * edhead = 0; - - - ed = (Environment_Data_Chunk *)lookup_single_child("REBENVDT"); - if (ed) - { - edhead = ed->get_header(); - } - - if (edhead) - { - if (edfptrs.size()) - { - SetFilePointer (rif_file,edfptrs.first_entry(),0,FILE_BEGIN); - - // get header list - List<int> edhl; list_chunks_in_file(& edhl, rif_file, "ENDTHEAD"); - - assert (edhl.size() == 1); - - // go to lock status in header - SetFilePointer(rif_file,edhl.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - ReadFile (rif_file, (long *) locker, 16, &bytes_read, 0); - - // go to version number - SetFilePointer(rif_file,edhl.first_entry() + 32,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &v_no, 4, &bytes_read, 0); - - if (edhead->version_no < v_no) - { - ed->updated_outside = TRUE; - } - if (flags & GENERAL_FLAG_LOCKED) - { - if (!ed->local_lock) { - ed->external_lock = TRUE; - strncpy(edhead->lock_user, locker,16); - edhead->lock_user[16] = '\0'; - } - else if (strncmp(edhead->lock_user, locker,16)) { - ed->external_lock = TRUE; - strncpy(edhead->lock_user, locker,16); - edhead->lock_user[16] = '\0'; - } - } - } - } - - // check file for REBENUMS chunk - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> enumfptrs; list_chunks_in_file(& enumfptrs, rif_file, "REBENUMS"); - - Enum_Chunk * enumch; - Enum_Header_Chunk * enumhead = 0; - - enumch = (Enum_Chunk *)lookup_single_child("REBENUMS"); - if (enumch) - { - enumhead = enumch->get_header(); - } - - if (enumhead) - { - if (enumfptrs.size()) - { - SetFilePointer (rif_file,enumfptrs.first_entry(),0,FILE_BEGIN); - - // get header list - List<int> enumchhl; list_chunks_in_file(& enumchhl, rif_file, "ENUMHEAD"); - - assert (enumchhl.size() == 1); - - // go to lock status in header - SetFilePointer(rif_file,enumchhl.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &flags, 4, &bytes_read, 0); - ReadFile (rif_file, (long *) locker, 16, &bytes_read, 0); - - // go to version number - SetFilePointer(rif_file,enumchhl.first_entry() + 32,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &v_no, 4, &bytes_read, 0); - - if (enumhead->version_no < v_no) - { - enumch->updated_outside = TRUE; - } - if (flags & GENERAL_FLAG_LOCKED) - { - if (!enumch->local_lock) { - enumch->external_lock = TRUE; - strncpy(enumhead->lock_user, locker,16); - enumhead->lock_user[16] = '\0'; - } - else if (strncmp(enumhead->lock_user, locker,16)) { - enumch->external_lock = TRUE; - strncpy(enumhead->lock_user, locker,16); - enumhead->lock_user[16] = '\0'; - } - } - } - } - - CloseHandle (rif_file); - - return TRUE; - #endif -} - - -#if InterfaceEngine - - extern File_Chunk * Env_Chunk; - -#endif - -BOOL File_Chunk::update_file() -{ - - #if DisableLock - if (!filename) return FALSE; - - char tempname [256]; - strcpy (tempname, filename); - - List<Shape_Chunk *> slist; - list_shapes(&slist); - List<Object_Chunk *> olist; - list_objects(&olist); - - for (LIF<Shape_Chunk *> sli(&slist); !sli.done(); sli.next()) - { - if (sli()->deleted) - { - delete sli(); - } - } - - for (LIF<Object_Chunk *> oli(&olist); !oli.done(); oli.next()) - { - if (oli()->deleted) - { - delete oli(); - } - } - - - return(write_file(tempname)); - - #else - -#if InterfaceEngine - - // log, to track error - char fname [256]; - char * dotpos; - - strcpy (fname, filename); - - dotpos = strrchr (fname, '.'); - - sprintf (dotpos, ".log"); - - FILE * log = fopen (fname, "a"); - -#endif - - if (!filename) return FALSE; - - twprintf("Updating %s\n",filename); - - check_file(); - - HANDLE rif_file; - unsigned long bytes_read; - - int tries = 0; - - //twprintf("Opening file\n"); - - rif_file = CreateFileA (filename, GENERIC_WRITE + GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - - if (rif_file == INVALID_HANDLE_VALUE) - { - DWORD error_num = GetLastError(); - switch (error_num) - { - case ERROR_SHARING_VIOLATION: - twprintf("Sharing violation - retrying\n"); - break; - case ERROR_ACCESS_DENIED: - twprintf("File is Read Only\n"); - return FALSE; - default: - twprintf("Unknown error updating file, Error code %#08x\n",error_num); - return FALSE; - } - } - - while(rif_file == INVALID_HANDLE_VALUE && tries<10) - { - twprintf("Again...\n"); - rif_file = CreateFileA (filename, GENERIC_WRITE + GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - tries ++; - clock_t ctime = clock(); - double secs = (double)ctime / (double)CLOCKS_PER_SEC; - double secsgone; - do - { - ctime = clock(); - secsgone = (double)ctime / (double)CLOCKS_PER_SEC; - } - while( (secsgone-secs)<1); - } - - if (rif_file == INVALID_HANDLE_VALUE) { - error_code = CHECK_FAILED_NOT_OPEN; - twprintf("ERROR - SHARING VIOLATION UNRESOLVED\n\n"); - return FALSE; - } - - //twprintf("Opened\n\n"); - - prepare_for_output(); - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - //twprintf("Version info\n"); - - List<int> verinf; list_chunks_in_file(& verinf, rif_file, "RIFVERIN"); - -// taking first entry of this list, if there are more - tough ha ha -// there shouldn't be - -// Just increment it by one and reoutput -// check_file sets the internal copy of the chunk to the current file -// setting, so we need to increment that as well - - if (verinf.size()) { - - int f_version_num; - SetFilePointer (rif_file,verinf.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &f_version_num, 4, &bytes_read, 0); - - SetFilePointer (rif_file,verinf.first_entry() + 12,0,FILE_BEGIN); - - RIF_Version_Num_Chunk* rvnc=(RIF_Version_Num_Chunk*)lookup_single_child ("RIFVERIN"); - - if (rvnc) - rvnc->file_version_no++; - - f_version_num++; - - WriteFile (rif_file, (long *) &f_version_num, 4, &bytes_read, 0); - - } - -// go through the list of shape chunks looking for shape chunks to output - //twprintf("\nShapes\n"); - - List<Chunk *> shplst; - lookup_child ("REBSHAPE",shplst); - - if (shplst.size()) - for (LIF<Chunk *> sli(&shplst); !sli.done(); sli.next()) { - - Shape_Chunk * tmpshpptr = ((Shape_Chunk *)sli()); - - if (tmpshpptr->updated && - !(tmpshpptr->updated_outside || tmpshpptr->external_lock)) - tmpshpptr->update_chunk_in_file(rif_file); - } - - -// go through the list of object chunks looking for chunks to output - //twprintf("\nObjects\n"); - - List<Chunk *> oblst; - lookup_child ("RBOBJECT",oblst); - - if (oblst.size()) - for (LIF<Chunk *> oli(&oblst); !oli.done(); oli.next()) { - - Object_Chunk * tmpobptr = ((Object_Chunk *)oli()); - - if (tmpobptr->updated && !(tmpobptr->updated_outside || tmpobptr->external_lock)) - tmpobptr->update_chunk_in_file(rif_file); - - } - - - //twprintf("\nSprites\n"); - - List<Chunk *> sprfptrs; - lookup_child ("RSPRITES",sprfptrs); - AllSprites_Chunk * sprch; - - if (sprfptrs.size()) - { - sprch = (AllSprites_Chunk *)sprfptrs.first_entry(); - if (sprch->updated && - !(sprch->updated_outside || sprch->external_lock)) - sprch->update_chunk_in_file(rif_file); - } - - //twprintf("\nEnvironment data\n"); - - Environment_Data_Chunk * ed; - - ed = (Environment_Data_Chunk *)lookup_single_child ("REBENVDT"); - if (ed) - { - -#if InterfaceEngine - - fprintf (log, "Env_Data %d %d %d %d", ed->updated, ed->local_lock, ed->updated_outside, ed->external_lock); - -#endif - - if (ed->updated && - !(ed->updated_outside || ed->external_lock)) - ed->update_chunk_in_file(rif_file); - } - - //twprintf("\nEnum data\n"); - - List<Chunk *> enumfptrs; - lookup_child ("REBENUMS",enumfptrs); - Enum_Chunk * enumch; - - if (enumfptrs.size()) - { - enumch = (Enum_Chunk *)enumfptrs.first_entry(); - if (enumch->updated && - !(enumch->updated_outside || enumch->external_lock)) - enumch->update_chunk_in_file(rif_file); - } - - // - - int file_length = GetFileSize(rif_file,0); - SetFilePointer (rif_file,8,0,FILE_BEGIN); - - WriteFile (rif_file, (long *) &file_length, 4, &bytes_read, 0); - - CloseHandle (rif_file); - -#if InterfaceEngine - - fclose (log); - -#endif - return TRUE; - - #endif //DisableLock -} - -BOOL File_Chunk::update_chunks_from_file() -{ - #if DisableLock - return(TRUE); - #endif - - if (!filename) return FALSE; - check_file(); - - HANDLE rif_file; - unsigned long bytes_read; - - rif_file = CreateFileA (filename, GENERIC_WRITE + GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - - if (rif_file == INVALID_HANDLE_VALUE) { - error_code = CHECK_FAILED_NOT_OPEN; - return FALSE; - } - - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> verinf; list_chunks_in_file(& verinf, rif_file, "RIFVERIN"); - - if (verinf.size()) { - - int f_version_num; - SetFilePointer (rif_file,verinf.first_entry() + 12,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &f_version_num, 4, &bytes_read, 0); - - SetFilePointer (rif_file,verinf.first_entry() + 12,0,FILE_BEGIN); - - List<Chunk *> lverinf; - lookup_child ("RIFVERIN",lverinf); - - if (lverinf.size()) - if (f_version_num == ((RIF_Version_Num_Chunk *)(lverinf.first_entry()))->file_version_no){ - CloseHandle (rif_file); - return TRUE; - } - - } - - // go through the list of object chunks looking for chunks to input - - List<Chunk *> oblst; - lookup_child ("RBOBJECT",oblst); - - if (oblst.size()) - for (LIF<Chunk *> oli(&oblst); !oli.done(); oli.next()) { - - Object_Chunk * tmpobptr = ((Object_Chunk *)oli()); - - if (tmpobptr->updated_outside) { - // find the chunk, then input it to a buffer and create a new object - // from the buffer - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> obfptrs; list_chunks_in_file(& obfptrs, rif_file, "RBOBJECT"); - - char name[50]; - - LIF<int> ofpl(&obfptrs); - - if (obfptrs.size()) { - for (; !ofpl.done(); ofpl.next()) { - - SetFilePointer (rif_file, ofpl(),0,FILE_BEGIN); - // get header list - List<int> obhead; list_chunks_in_file(& obhead, rif_file, "OBJHEAD1"); - - assert (obhead.size() == 1); - - // get object identifier - SetFilePointer(rif_file,obhead.first_entry() + 96,0,FILE_BEGIN); - int i = 0; - do ReadFile (rif_file, (long *) (name + i), 1, &bytes_read, 0); - while (name[i++] != 0); - - if (!strcmp(name, tmpobptr->object_data.o_name)) break; - } - } - - if (!ofpl.done()) { - - char * buffer; - - SetFilePointer (rif_file,ofpl()+8,0,FILE_BEGIN); - int length; - ReadFile(rif_file, (long *) &length, 4, &bytes_read, 0); - buffer = new char [length]; - ReadFile(rif_file, (long *) buffer, length-12, &bytes_read, 0); - new Object_Chunk (this, buffer, length-12); - delete [] buffer; - if (tmpobptr->get_header()) - if (tmpobptr->get_header()->associated_shape) - tmpobptr->deassoc_with_shape(tmpobptr->get_header()->associated_shape); - delete tmpobptr; - - } - - - } - - } - -// go through the list of shape chunks looking for shape chunks to input - - List<Chunk *> shplst; - lookup_child ("REBSHAPE",shplst); - - if (shplst.size()) - for (LIF<Chunk *> sli(&shplst); !sli.done(); sli.next()) { - - Shape_Chunk * tmpshpptr = ((Shape_Chunk *)sli()); - - Shape_Header_Chunk * shhead = tmpshpptr->get_header(); - - if (!shhead) continue; - - if (tmpshpptr->updated_outside) { - // find the chunk, then input it to a buffer and create a new object - // from the buffer - SetFilePointer (rif_file,0,0,FILE_BEGIN); - - List<int> shfptrs; list_chunks_in_file(& shfptrs, rif_file, "REBSHAPE"); - - LIF<int> sfpl(&shfptrs); - - if (shfptrs.size()) { - for (sfpl.restart(); !sfpl.done(); sfpl.next()) { - - SetFilePointer (rif_file, sfpl(),0,FILE_BEGIN); - // get header list - List<int> shphead; list_chunks_in_file(& shphead, rif_file, "SHPHEAD1"); - - assert (shphead.size() == 1); - - // get object identifier - SetFilePointer(rif_file,shphead.first_entry() + 32,0,FILE_BEGIN); - int sh_number; - ReadFile (rif_file, (long *) &sh_number, 4, &bytes_read, 0); - - if (sh_number == shhead->file_id_num) break; - } - } - - if (!sfpl.done()) { - - char * buffer; - - SetFilePointer (rif_file,sfpl()+8,0,FILE_BEGIN); - int length; - ReadFile(rif_file, (long *) &length, 4, &bytes_read, 0); - buffer = new char [length]; - ReadFile(rif_file, (long *) buffer, length-12, &bytes_read, 0); - new Shape_Chunk (this, buffer, length-12); - delete [] buffer; - // Associate with the new objects - if ((shhead->associated_objects_store).size()) - { - for (LIF<Object_Chunk *> aol(&(shhead->associated_objects_store)); !aol.done(); aol.next()) - { - tmpshpptr->deassoc_with_object(aol()); - } - } - delete tmpshpptr; - } - } - } - - post_input_processing(); - - CloseHandle(rif_file); - - return TRUE; - -} - -void File_Chunk::list_objects(List<Object_Chunk *> * pList) -{ - Chunk * child_ptr = children; - - while (pList->size()) - pList->delete_first_entry(); - - if (children) - while (child_ptr != NULL) { - if (strncmp ("RBOBJECT", child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - pList->add_entry((Object_Chunk *)child_ptr); - } - child_ptr = child_ptr->next; - } - -} - -void File_Chunk::list_shapes(List<Shape_Chunk *> * pList) -{ - Chunk * child_ptr = children; - - while (pList->size()) - pList->delete_first_entry(); - - if (children) - while (child_ptr != NULL) { - if (strncmp ("REBSHAPE", child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - pList->add_entry((Shape_Chunk *)child_ptr); - } - child_ptr = child_ptr->next; - } - -} - -void File_Chunk::list_dummy_objects(List<Dummy_Object_Chunk *> * pList){ - Chunk * child_ptr = children; - - while (pList->size()) - pList->delete_first_entry(); - - if (children) - while (child_ptr != NULL) { - if (strncmp ("DUMMYOBJ", child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - pList->add_entry((Dummy_Object_Chunk *)child_ptr); - } - child_ptr = child_ptr->next; - } - -} - -Environment_Data_Chunk * File_Chunk::get_env_data() -{ - List<Environment_Data_Chunk *> e_list; - Chunk * child_ptr = children; - - if (children) - while (child_ptr != NULL) { - if (strncmp ("REBENVDT", child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - e_list.add_entry((Environment_Data_Chunk *)child_ptr); - } - child_ptr = child_ptr->next; - } - - // There can be only ONE. - assert (e_list.size() < 2); - - if (e_list.size()) - return e_list.first_entry(); - else - { - return(0); - } -} - -void File_Chunk::build_object_array() -{ - List<Object_Chunk*> oblist; - list_objects(&oblist); - - if(object_array) - { - free(object_array); - object_array=0; - } - object_array_size=0; - - LIF<Object_Chunk*> oblif(&oblist); - - //find the highest object index - for(oblif.restart();!oblif.done();oblif.next()) - { - object_array_size=max(object_array_size,oblif()->object_data.index_num+1); - } - - if(object_array_size<=0) return; - - object_array = (Object_Chunk**) malloc(sizeof(Object_Chunk*)*object_array_size); - for(int i=0;i<object_array_size;i++) - { - object_array[i]=0; - } - - //now fill in object array - - for(oblif.restart();!oblif.done();oblif.next()) - { - int index=oblif()->object_data.index_num; - if(index>=0) - { - object_array[index]=oblif(); - } - } -} - -Object_Chunk* File_Chunk::get_object_by_index(int index) -{ - if(!object_array) build_object_array(); - if(index<0 || index>=object_array_size)return 0; - return object_array[index]; -} - -void File_Chunk::assign_index_to_object(Object_Chunk* object) -{ - assert(object); - - if(!object_array) build_object_array(); - //see if there is a free index - - for(int i=0;i<object_array_size;i++) - { - if(!object_array[i]) - { - object->object_data_store->index_num=i; - object_array[i]=object; - return; - } - } - - //add a new entry on the end of the array - object_array_size++; - - object_array=(Object_Chunk**) realloc(object_array,sizeof(Object_Chunk*)*object_array_size); - - - object->object_data_store->index_num=object_array_size-1;; - object_array[object_array_size-1]=object; -} - -///////////////////////////////////////// - -// Class GodFather_Chunk functions - -/* -Children for GodFather_Chunk : -"REBSHAPE" Shape_Chunk -"RSPRITES" AllSprites_Chunk -"RBOBJECT" Object_Chunk -"RIFVERIN" RIF_Version_Num_Chunk -"REBENVDT" Environment_Data_Chunk -"REBENUMS" Enum_Chunk -"OBJCHIER" Object_Hierarchy_Chunk -"OBHALTSH" Object_Hierarchy_Alternate_Shape_Set_Chunk - -*/ - -GodFather_Chunk::GodFather_Chunk(char * buffer, size_t size) -: Chunk_With_Children (NULL, "REBINFF2") -{ - Parent_File = this; - - char * buffer_ptr = buffer; - - // The start of the first chunk - - while ((buffer_ptr-buffer)< ((signed)size-12) && !error_code) { - - if ((*(int *)(buffer_ptr + 8)) + (buffer_ptr-buffer) > ((signed)size-12)) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(buffer_ptr); - buffer_ptr += *(int *)(buffer_ptr + 8); - - } - -} - -///////////////////////////////////////// - -// Class RIF_Version_Num_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("RIFVERIN",RIF_Version_Num_Chunk) - -void RIF_Version_Num_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = file_version_no; - -} - - -///////////////////////////////////////// - -// Class RIF_Name_Chunk functions -RIF_IMPLEMENT_DYNCREATE("RIFFNAME",RIF_Name_Chunk) - -RIF_Name_Chunk::RIF_Name_Chunk (Chunk_With_Children * parent, const char * rname) -: Chunk (parent, "RIFFNAME") -{ - rif_name = new char [strlen(rname)+1]; - strcpy (rif_name, rname); -} - -RIF_Name_Chunk::RIF_Name_Chunk (Chunk_With_Children * parent, const char * rdata, size_t /*rsize*/) -: Chunk (parent, "RIFFNAME") -{ - rif_name = new char [strlen(rdata)+1]; - strcpy (rif_name, rdata); -} - -RIF_Name_Chunk::~RIF_Name_Chunk () -{ - if (rif_name) - delete [] rif_name; -} - - -void RIF_Name_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - strcpy (data_start, rif_name); - -} - - -/////////////////////////////////////// - -/* -Children for RIF_File_Chunk : -"REBSHAPE" Shape_Chunk -"RSPRITES" AllSprites_Chunk -"RBOBJECT" Object_Chunk -"RIFVERIN" RIF_Version_Num_Chunk -"REBENVDT" Environment_Data_Chunk -"OBJCHIER" Object_Hierarchy_Chunk -"OBHALTSH" Object_Hierarchy_Alternate_Shape_Set_Chunk - -*/ - - -RIF_File_Chunk::RIF_File_Chunk (Chunk_With_Children * parent, const char * file_name) -: Chunk_With_Children (parent, "SUBRIFFL") -{ - char rifIsCompressed = FALSE; - char *uncompressedData = NULL; - HANDLE rif_file; - DWORD file_size; - DWORD file_size_from_file; - unsigned long bytes_read; - char * buffer; - char * buffer_ptr; - char id_buffer[9]; - - - Chunk * ParentFileStore = Parent_File; - - Parent_File = this; - - error_code = 0; - - rif_file = CreateFileA (file_name, GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - - - if (rif_file == INVALID_HANDLE_VALUE) { - error_code = CHUNK_FAILED_ON_LOAD; - Parent_File = ParentFileStore; - return; - } - - file_size = GetFileSize (rif_file, NULL); - - if (!ReadFile(rif_file, id_buffer, 8, &bytes_read, 0)) { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - Parent_File = ParentFileStore; - return; - } - - //check for compressed rif - if (!strncmp (id_buffer, COMPRESSED_RIF_IDENTIFIER, 8)) - { - rifIsCompressed = TRUE; - } - else if (strncmp (id_buffer, "REBINFF2", 8)) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - CloseHandle (rif_file); - Parent_File = ParentFileStore; - return; - } - - buffer = new char [file_size]; - - /* KJL 17:57:44 19/09/98 - if the rif is compressed, we must load the whole - file in and then pass it to the decompression routine, which will return a - pointer to the original data. */ - if (rifIsCompressed) - { - if (!ReadFile(rif_file, buffer+8, (file_size-8), &bytes_read, 0)) - { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - Parent_File = ParentFileStore; - delete [] buffer; - return; - } - uncompressedData = HuffmanDecompress((HuffmanPackage*)buffer); - file_size = ((HuffmanPackage*)buffer)->UncompressedDataSize; - - delete [] buffer; // kill the buffer the compressed file was loaded into - - buffer_ptr = buffer = uncompressedData+12; // skip header data - } - else // the normal uncompressed approach: - { - //get the file size stored in the rif file - if (!ReadFile(rif_file, &file_size_from_file, 4, &bytes_read, 0)) { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - Parent_File = ParentFileStore; - delete [] buffer; - return; - } - - //and compare with the actual file size - if (file_size != file_size_from_file) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - CloseHandle (rif_file); - Parent_File = ParentFileStore; - delete [] buffer; - return; - } - - //read the rest of the file into the buffer - if (!ReadFile(rif_file, buffer, (file_size-12), &bytes_read, 0)) - { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - Parent_File = ParentFileStore; - delete [] buffer; - return; - } - buffer_ptr = buffer; - } - - - - - // Process the RIF - - // The start of the first chunk - - while ((buffer_ptr-buffer)< ((signed) file_size-12) && !error_code) { - - if ((*(int *)(buffer_ptr + 8)) + (buffer_ptr-buffer) > ((signed)file_size-12)) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(buffer_ptr); - buffer_ptr += *(int *)(buffer_ptr + 8); - } - - /* KJL 17:59:42 19/09/98 - release the memory holding the rif */ - if (rifIsCompressed) - { - free(uncompressedData); - } - else - { - delete [] buffer; - } - - CloseHandle (rif_file); - - post_input_processing(); - - Parent_File = ParentFileStore; - -} - -void RIF_File_Chunk::post_input_processing() -{ - List<Shape_Chunk *> shplist; - List<Object_Chunk *> objlist; - - List<Chunk *> child_lists; - - lookup_child("REBSHAPE",child_lists); - - while (child_lists.size()) { - shplist.add_entry((Shape_Chunk *)child_lists.first_entry()); - child_lists.delete_first_entry(); - } - - lookup_child("RBOBJECT",child_lists); - - - while (child_lists.size()) { - objlist.add_entry((Object_Chunk *)child_lists.first_entry()); - child_lists.delete_first_entry(); - } - - for (LIF<Object_Chunk *> ol(&objlist); !ol.done(); ol.next()) { - - if (ol()->get_header()) { - - for (LIF<Shape_Chunk *> sl(&shplist); - !sl.done(); sl.next()) { - if (sl()->get_header()) - if (sl()->get_header()->file_id_num == ol()->get_header()->shape_id_no){ - ol()->assoc_with_shape(sl()); - break; - } - } - } - - } - - for (LIF<Shape_Chunk *> sli(&shplist); !sli.done(); sli.next()) - { - Shape_Chunk::max_id = max (Shape_Chunk::max_id,sli()->get_header()->file_id_num); - } - - Chunk_With_Children::post_input_processing(); -} - - -void RIF_File_Chunk::list_objects(List<Object_Chunk *> * pList) -{ - Chunk * child_ptr = children; - - while (pList->size()) - pList->delete_first_entry(); - - if (children) - while (child_ptr != NULL) { - if (strncmp ("RBOBJECT", child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - pList->add_entry((Object_Chunk *)child_ptr); - } - child_ptr = child_ptr->next; - } -} - -void RIF_File_Chunk::list_shapes(List<Shape_Chunk *> * pList) -{ - Chunk * child_ptr = children; - - while (pList->size()) - pList->delete_first_entry(); - - if (children) - while (child_ptr != NULL) { - if (strncmp ("REBSHAPE", child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - pList->add_entry((Shape_Chunk *)child_ptr); - } - child_ptr = child_ptr->next; - } - -} - -Environment_Data_Chunk * RIF_File_Chunk::get_env_data() -{ - List<Environment_Data_Chunk *> e_list; - Chunk * child_ptr = children; - - if (children) - while (child_ptr != NULL) { - if (strncmp ("REBENVDT", child_ptr->identifier, 8) == NULL) - { - assert (!child_ptr->r_u_miscellaneous()); - e_list.add_entry((Environment_Data_Chunk *)child_ptr); - } - child_ptr = child_ptr->next; - } - - // There can be only ONE. - assert (e_list.size() < 2); - - if (e_list.size()) - return e_list.first_entry(); - else - { - return(0); - } -} diff --git a/3dc/win95/MISHCHNK.HPP b/3dc/win95/MISHCHNK.HPP deleted file mode 100644 index 957398e..0000000 --- a/3dc/win95/MISHCHNK.HPP +++ /dev/null @@ -1,250 +0,0 @@ -#ifndef _miscchunk_hpp -#define _miscchunk_hpp 1 - -#include <time.h> -#include "chunk.hpp" - -#include "chnktype.hpp" - -#if engine - -#define UseLocalAssert No -#include "ourasert.h" -#define assert(x) GLOBALASSERT(x) - -#else - -#if cencon -#include "ccassert.h" -#else -#include <assert.h> -#endif - -#endif - -#if cencon -#include "output.hpp" -#else -#define twprintf printf - -extern char * users_name; -#endif - -class File_Chunk; - -class Lockable_Chunk_With_Children : public Chunk_With_Children -{ - -public: - - Lockable_Chunk_With_Children (Chunk_With_Children * parent, const char * identifier) - : Chunk_With_Children (parent, identifier), - updated (FALSE),updated_outside (FALSE),local_lock (FALSE),external_lock(FALSE), - output_chunk_for_process (FALSE), deleted (FALSE) - {} - - -// derived classes from this class must have the -// following functions (or it won't compile)!! - - virtual BOOL file_equals(HANDLE &) = 0; - // the file equals function knows to look in - // the file from the start of the current chunk - // to see if the current chunk is the same one - - virtual const char * get_head_id() = 0; - virtual void set_lock_user(char *) = 0; - -// this function will lock the chunk if it can - -// will return true on success or if the chunk has -// already been locked locally. - - BOOL lock_chunk(File_Chunk &); - -// The unlock_chunk will unlock the chunk -// if the updateyn flag is set, the updated flag will be set -// internally and the chunk may be updated on the next file update -// If there is no update, the chunk will be unlocked in the file - - BOOL unlock_chunk (File_Chunk &, BOOL updateyn); - - BOOL update_chunk_in_file(HANDLE &rif_file); - - // Selective output functions, - // These will output on condition of the flag, the flag will be set - // to FALSE - - BOOL output_chunk_for_process; - - virtual size_t size_chunk_for_process(); - - virtual void fill_data_block_for_process(char * data_start); - - - BOOL updated; - BOOL updated_outside; - BOOL local_lock; - BOOL external_lock; - - BOOL deleted; - -}; - - -/////////////////////////////////////////////// - -class Object_Chunk; -class Shape_Chunk; -class Dummy_Object_Chunk; -class Environment_Data_Chunk; - -class File_Chunk : public Chunk_With_Children -{ -public: - - //constructor - File_Chunk (const char * filename); - File_Chunk (); - - //destructor - ~File_Chunk (); - - // file handling - BOOL update_file (); - BOOL write_file (const char *); - - BOOL check_file(); - - BOOL update_chunks_from_file(); - - // the file_chunk must link all of its shapes & objects together - // in post_input_processing - - virtual void post_input_processing(); - - // copy string when constructed - // to this variable - char * filename; - - - // some easy access functions - - void list_objects(List<Object_Chunk *> * pList); - void list_shapes(List<Shape_Chunk *> * pList); - void list_dummy_objects(List<Dummy_Object_Chunk *> * pList); - - Environment_Data_Chunk * get_env_data(); - - Object_Chunk* get_object_by_index(int index); - void assign_index_to_object(Object_Chunk* object); - -private: - - friend class Shape_Chunk; - friend class Object_Chunk; - friend class Lockable_Chunk_With_Children; - - int flags; - - int object_array_size; - Object_Chunk** object_array; - - void build_object_array(); -}; - -/////////////////////////////////////////////// - - -class RIF_Version_Num_Chunk : public Chunk -{ -public: - RIF_Version_Num_Chunk (Chunk_With_Children * parent, const char *data, size_t /*size*/) - : Chunk (parent,"RIFVERIN"), file_version_no (*((int *) data)) - {} - - int file_version_no; - -// output_chunk updates the above - - virtual void fill_data_block (char * data_start); - - virtual size_t size_chunk () - { - chunk_size = 16; - return 16; - } - -private: - - friend class File_Chunk; - friend class GodFather_Chunk; - friend class RIF_File_Chunk; - - - - RIF_Version_Num_Chunk (Chunk_With_Children * parent) - : Chunk (parent,"RIFVERIN"), file_version_no (0) - {} -}; - -/////////////////////////////////////////////// - -class RIF_File_Chunk : public Chunk_With_Children -{ -public: - - // This is a special chunk which does not output itself - - RIF_File_Chunk (Chunk_With_Children * parent, const char * fname); - - size_t size_chunk() - { - return chunk_size = 0; - } - - virtual void post_input_processing(); - - BOOL output_chunk (HANDLE & /*h*/){return TRUE;}; - void fill_data_block (char * /*c*/){}; - - void list_objects(List<Object_Chunk *> * pList); - void list_shapes(List<Shape_Chunk *> * pList); - Environment_Data_Chunk * get_env_data(); - -}; - -/////////////////////////////////////////////// - -class RIF_Name_Chunk : public Chunk -{ -public: - - RIF_Name_Chunk (Chunk_With_Children * parent, const char * rname); - ~RIF_Name_Chunk(); - // constructor from buffer - RIF_Name_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize); - char * rif_name; - - virtual size_t size_chunk () - { - return (chunk_size = 12 + strlen (rif_name) + 4 - strlen (rif_name)%4); - } - - virtual void fill_data_block (char * data_start); - -private: - - friend class Environment_Data_Chunk; - friend class Environment_Game_Mode_Chunk; - friend class Shape_External_File_Chunk; - friend class Sprite_Header_Chunk; - - - -}; - - - - - -#endif
\ No newline at end of file diff --git a/3dc/win95/MMX_MATH.H b/3dc/win95/MMX_MATH.H deleted file mode 100644 index 594ac0e..0000000 --- a/3dc/win95/MMX_MATH.H +++ /dev/null @@ -1,469 +0,0 @@ -#ifndef _included_mmx_math_h_ -#define _included_mmx_math_h_ - -#if SUPPORT_MMX - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* -Calling-convention independent -definitions of inline MMX assembler -functions and declarations for non- -inline MMX assembler functions -*/ - -/* SPECIFICATION */ -/* -Dot Product and Vector Transform functions take -arguments referencing matrices or vectors whose -elements are 32 bit signed integers and arranged as -follows. All integers (including the results) are -in 16.16 fixed point form - ie. The 64-bit results -are shifted down 16 bits (divided by 65536) before -being written back as 32-bit values. Results are -rounded down (towards negative infinity). - -the matrix structure looks like this (not ideal!) -[ +00 +0c +18 ] -[ +04 +10 +1c ] -[ +08 +14 +20 ] - -and the vector structure looks like this -[ +00 ] -[ +04 ] -[ +08 ] -*/ - -/* TYPICAL CHARACTERISTICS */ -/* -Accuracy - -Internal rounding errors may be propogated, and -the results may not be exact. For the Dot Product -result and the Vector Transform results (x,y and z -independently), the error distributions are all -the same, as follows: - -Exact: 25% --1: 50% --2: 25% - -Better accuracy can be obtained by adding 1 to each integer result, -but this will produce poor results in the case of nice simple round -numbers, eg Dot({1.0,0.0,0.0},{0.0,1.0,0.0}) gives 1 not 0! - -Speed - -The DotProduct Takes 33 cycles (not including call instruction) -The inline DotProduct takes 30+1 cycles (the last instruction is pairable) -All Vector transforms take 63 cycles. These figures assume no -stalls due to cache misses or misaligned data. A matrix multiply -or cross product could be supplied if it is thought they would -be necessary - - -For optimal performance, it is recommended that vector and -matrix structures should be aligned to EIGHT byte boundaries. -To ensure this in arrays of vectors/matrices, the structure -should contain a dummy padding 32-bit value (recommended). -*/ - -/* storage class specifier for assembler calls */ - -#ifdef __WATCOMC__ -#define _asmcall -#define _asminline -#elif defined(_MSC_VER) -#define _asmcall static __inline -#define _asminline static __inline -#else -#error "Unknown compiler" -#endif - -/* forward reference declared in global scope */ -struct vectorch; -struct matrixch; - -/***********************/ -/* F-U-N-C-T-I-O-N */ -/* P-R-O-T-O-T-Y-P-E-S */ -/* F-O-R A-L-L */ -/* P-U-B-L-I-C */ -/* F-U-N-C-T-I-O-N-S */ -/***********************/ - -/* overwrites the input vector with the new vector */ -_asmcall void MMX_VectorTransform(struct vectorch * vector, struct matrixch const * matrix); -/* fills a new vector with the result of the input vector transformed by the matrix */ -_asmcall void MMX_VectorTransformed(struct vectorch * v_result, struct vectorch const * v_parm, struct matrixch const * matrix); -/* overwrites the input vector with the new vector, then adds another vector */ -_asmcall void MMX_VectorTransformAndAdd(struct vectorch * vector, struct matrixch const * matrix, struct vectorch const * v_add); -/* fills a new vector with the result of the input vector transformed by the matrix then added to another vector */ -_asmcall void MMX_VectorTransformedAndAdd(struct vectorch * v_result, struct vectorch const * v_parm, struct matrixch const * matrix, struct vectorch const * v_add); -/* compute dot product */ -_asmcall signed MMX_VectorDot(struct vectorch const * v1, struct vectorch const * v2); -/* this one assumes all the input vector elements are in the range [-32768,32767] */ -_asmcall signed MMX_VectorDot16(struct vectorch const * v1, struct vectorch const * v2); - -/* inline versions */ -_asminline signed MMXInline_VectorDot(struct vectorch const * v1, struct vectorch const * v2); -_asminline signed MMXInline_VectorDot16(struct vectorch const * v1, struct vectorch const * v2); - -/*****************/ -/* PRIVATE PARTS */ -/*****************/ - -/* Assembler labels */ -extern void MMXAsm_VectorTransform(void); -extern void MMXAsm_VectorTransformed(void); -extern void MMXAsm_VectorTransformAndAdd(void); -extern void MMXAsm_VectorTransformedAndAdd(void); -extern void MMXAsm_VectorDot(void); -extern void MMXAsm_VectorDot16(void); - -/* inline calls to MMX functions with correct parameters set */ -#ifdef __WATCOMC__ - -#pragma aux MMX_VectorTransform = "call MMXAsm_VectorTransform" parm [eax] [edx]; -#pragma aux MMX_VectorTransformed = "call MMXAsm_VectorTransformed" parm [eax] [edx] [ecx]; -#pragma aux MMX_VectorTransformAndAdd = "call MMXAsm_VectorTransformAndAdd" parm [eax] [edx] [ecx]; -#pragma aux MMX_VectorTransformedAndAdd = "call MMXAsm_VectorTransformedAndAdd" parm [eax] [edx] [ecx] [ebx]; -#pragma aux MMX_VectorDot = "call MMXAsm_VectorDot" parm [eax] [edx] value [eax]; -#pragma aux MMX_VectorDot16 = "call MMXAsm_VectorDot16" parm [eax] [edx] value [eax]; - -#elif defined(_MSC_VER) - -_asmcall void MMX_VectorTransform(struct vectorch * vector, struct matrixch const * matrix) -{ - _asm - { - mov eax,vector - mov edx,matrix - call MMXAsm_VectorTransform - } -} -_asmcall void MMX_VectorTransformed(struct vectorch * v_result, struct vectorch const * v_parm, struct matrixch const * matrix) -{ - _asm - { - mov eax,v_result - mov edx,v_parm - mov ecx,matrix - call MMXAsm_VectorTransformed - } -} -_asmcall void MMX_VectorTransformAndAdd(struct vectorch * vector, struct matrixch const * matrix, struct vectorch const * v_add) -{ - _asm - { - mov eax,vector - mov edx,matrix - mov ecx,v_add - call MMXAsm_VectorTransformAndAdd - } -} -_asmcall void MMX_VectorTransformedAndAdd(struct vectorch * v_result, struct vectorch const * v_parm, struct matrixch const * matrix, struct vectorch const * v_add) -{ - _asm - { - mov eax,v_result - mov edx,v_parm - mov ecx,matrix - mov ebx,v_add - call MMXAsm_VectorTransformedAndAdd - } -} -_asmcall signed MMX_VectorDot(struct vectorch const * v1, struct vectorch const * v2) -{ - signed retval; - _asm - { - mov eax,v1 - mov edx,v2 - call MMXAsm_VectorDot - mov retval,eax - } - return retval; -} -_asmcall signed MMX_VectorDot16(struct vectorch const * v1, struct vectorch const * v2) -{ - signed retval; - _asm - { - mov eax,v1 - mov edx,v2 - call MMXAsm_VectorDot16 - mov retval,eax - } - return retval; -} - -#else - -#error "Unknown compiler" - -#endif - - -/* Cross product? Mod? MatrixMultiply? */ - -/* globals */ - -extern int use_mmx_math; - -/* inline functions - no call */ - -extern __int64 const mmx_sign_mask; -extern __int64 const mmx_one_fixed_h; - -#ifdef __WATCOMC__ - -#pragma aux MMXInline_VectorDot = \ -\ -" movq mm0,[edx]" \ -\ -" movd mm2,[edx+08h]" \ -" movq mm4,mm0" \ -\ -" pand mm4,mmx_sign_mask" \ -" movq mm6,mm2" \ -\ -" movq mm1,[eax]" \ -" paddd mm4,mm4" \ -\ -" movd mm3,[eax+08h]" \ -" movq mm5,mm1" \ -\ -" pand mm6,mmx_sign_mask" \ -" movq mm7,mm3" \ -\ -" pand mm5,mmx_sign_mask" \ -" paddd mm6,mm6" \ -\ -" pand mm7,mmx_sign_mask" \ -" paddd mm5,mm5" \ -\ -" paddd mm0,mm4" \ -" paddd mm2,mm6" \ -\ -" paddd mm7,mm7" \ -" movq mm4,mm2" \ -\ -" punpcklwd mm4,mm0" \ -" paddd mm1,mm5" \ -\ -" punpckhwd mm2,mm0" \ -" paddd mm3,mm7" \ -\ -" movq mm5,mm3" \ -" punpckhwd mm3,mm1" \ -\ -" punpcklwd mm5,mm1" \ -" movq mm0,mm2" \ -\ -" movq mm1,mm4" \ -" pmaddwd mm0,mm3" \ -\ -" movq mm6,mm3" \ -" psrlq mm3,32" \ -\ -" movq mm7,mm5" \ -" punpckldq mm3,mm6" \ -\ -" pmaddwd mm1,mm5" \ -" psrlq mm5,32" \ -\ -" punpckldq mm5,mm7" \ -" pmaddwd mm2,mm3" \ -\ -" pmaddwd mm4,mm5" \ -" movq mm3,mm0" \ -\ -" punpckldq mm0,mm1" \ -\ -" psubd mm0,mmx_one_fixed_h" \ -" punpckhdq mm1,mm3" \ -\ -" psrad mm0,16" \ -" paddd mm2,mm4" \ -\ -" pslld mm1,16" \ -" paddd mm2,mm0" \ -\ -" paddd mm2,mm1" \ -\ -" movq mm1,mm2" \ -" psrlq mm2,32" \ -\ -" paddd mm1,mm2" \ -\ -" movd eax,mm1" \ -\ -" emms" \ -\ -" inc eax" \ -\ -parm [eax] [edx] value [eax]; - -#pragma aux MMXInline_VectorDot16 = \ -\ -" movd mm0,[edx+08h]" \ -\ -" packssdw mm0,[edx]" \ -\ -" movd mm1,[eax+08h]" \ -\ -" packssdw mm1,[eax]" \ -\ -" pmaddwd mm0,mm1" \ -\ -" movq mm1,mm0" \ -" psrlq mm0,32" \ -\ -" paddd mm0,mm1" \ -\ -" movd eax,mm0" \ -\ -" emms" \ -\ -parm [eax] [edx] value [eax]; - -#elif defined(_MSC_VER) - -_asminline signed MMXInline_VectorDot(struct vectorch const * v1, struct vectorch const * v2) -{ - signed retval; - _asm - { - mov edx,v1 - mov eax,v2 - - movq mm0,[edx] - - movd mm2,[edx+08h] - movq mm4,mm0 - - pand mm4,mmx_sign_mask - movq mm6,mm2 - - movq mm1,[eax] - paddd mm4,mm4 - - movd mm3,[eax+08h] - movq mm5,mm1 - - pand mm6,mmx_sign_mask - movq mm7,mm3 - - pand mm5,mmx_sign_mask - paddd mm6,mm6 - - pand mm7,mmx_sign_mask - paddd mm5,mm5 - - paddd mm0,mm4 - paddd mm2,mm6 - - paddd mm7,mm7 - movq mm4,mm2 - - punpcklwd mm4,mm0 - paddd mm1,mm5 - - punpckhwd mm2,mm0 - paddd mm3,mm7 - - movq mm5,mm3 - punpckhwd mm3,mm1 - - punpcklwd mm5,mm1 - movq mm0,mm2 - - movq mm1,mm4 - pmaddwd mm0,mm3 - - movq mm6,mm3 - psrlq mm3,32 - - movq mm7,mm5 - punpckldq mm3,mm6 - - pmaddwd mm1,mm5 - psrlq mm5,32 - - punpckldq mm5,mm7 - pmaddwd mm2,mm3 - - pmaddwd mm4,mm5 - movq mm3,mm0 - - punpckldq mm0,mm1 - - psubd mm0,mmx_one_fixed_h - punpckhdq mm1,mm3 - - psrad mm0,16 - paddd mm2,mm4 - - pslld mm1,16 - paddd mm2,mm0 - - paddd mm2,mm1 - - movq mm1,mm2 - psrlq mm2,32 - - paddd mm1,mm2 - - movd retval,mm1 - - emms - } - return retval+1; -} - -_asminline signed MMXInline_VectorDot16(struct vectorch const * v1, struct vectorch const * v2) -{ - signed retval; - _asm - { - mov eax,v1 - mov edx,v2 - - movd mm0,[edx+08h] - - packssdw mm0,[edx] - - movd mm1,[eax+08h] - - packssdw mm1,[eax] - - pmaddwd mm0,mm1 - - movq mm1,mm0 - psrlq mm0,32 - - paddd mm0,mm1 - - movd retval,mm0 - - emms - } - return retval; -} - -#else - -#error "Unknown compiler" - -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* SUPPORT_MMX */ - -#endif /* ! _included_mmx_math_h_ */ diff --git a/3dc/win95/Mmx_math.asm b/3dc/win95/Mmx_math.asm deleted file mode 100644 index ce5cb46..0000000 --- a/3dc/win95/Mmx_math.asm +++ /dev/null @@ -1,1272 +0,0 @@ -; want 8-byte alignment really!! -_DATA SEGMENT DWORD PUBLIC 'DATA' - - - PUBLIC _use_mmx_math - PUBLIC _mmx_sign_mask - PUBLIC _mmx_one_fixed_h - - align - _mmx_sign_mask:QWORD 0000800000008000h - _mmx_one_fixed_h:QWORD 0001000000000000h - _mmx_one_fixed_hl:QWORD 0001000000010000h - _mmx_one_hl:QWORD 0000000100000001h - store1:QWORD ? - _use_mmx_math:DWORD 1 - - - -_DATA ENDS - - - -; want 16-byte alignment really!! -_TEXT SEGMENT DWORD PUBLIC 'CODE' - ASSUME cs:_TEXT, ds:_DATA - -.586 - - PUBLIC MMXAsm_VectorDot_ - PUBLIC MMXAsm_VectorDot16_ - PUBLIC MMXAsm_VectorTransformed_ - PUBLIC MMXAsm_VectorTransform_ - PUBLIC MMXAsm_VectorTransformedAndAdd_ - PUBLIC MMXAsm_VectorTransformAndAdd_ - - PUBLIC _MMXAsm_VectorDot - PUBLIC _MMXAsm_VectorDot16 - PUBLIC _MMXAsm_VectorTransformed - PUBLIC _MMXAsm_VectorTransform - PUBLIC _MMXAsm_VectorTransformedAndAdd - PUBLIC _MMXAsm_VectorTransformAndAdd - - align -_MMXAsm_VectorDot: -MMXAsm_VectorDot_: - -if 0 - ; This is the unoptimized version - - ; get the data - movq mm0,[edx] - movq mm1,[eax] - movd mm2,[edx+08h] - movd mm3,[eax+08h] - - - ; get it into signed fixed format - movq mm4,mm0 - movq mm5,mm1 - movq mm6,mm2 - movq mm7,mm3 - - pand mm4,_mmx_sign_mask - pand mm5,_mmx_sign_mask - pand mm6,_mmx_sign_mask - pand mm7,_mmx_sign_mask - - paddd mm4,mm4 - paddd mm5,mm5 - paddd mm6,mm6 - paddd mm7,mm7 - - paddd mm0,mm4 - paddd mm1,mm5 - paddd mm2,mm6 - paddd mm3,mm7 - - ; at this point we have split all 32 bit values - ; into 16-bit pairs, high and low, both signed - - ; mm0: y1h y1l x1h x1l - ; mm1: y2h y2l x2h x2l - ; mm2: 0 0 z1h z1l - ; mm3: 0 0 z2h z2l - - ; swap 1st and 2nd words in mm0,mm1,mm2,mm3 ?? - movq mm4,mm2 - movq mm5,mm3 - punpcklwd mm4,mm0 - ; mm4: x1h z1h x1l z1l - punpcklwd mm5,mm1 - ; mm5: x2h z2h x2l z2l - punpckhwd mm2,mm0 - ; mm2: y1h 0 y1l 0 - punpckhwd mm3,mm1 - ; mm3: y2h 0 y2l 0 - - ; get the high and low products: x1h*x2h, x1l*x2l, etc - movq mm0,mm2 - pmaddwd mm0,mm3 - ; mm0: y1h*y2h y1l*y2l - movq mm1,mm4 - pmaddwd mm1,mm5 - ; mm1: x1h*x2h+z1h*z2h x1l*x2l+z1l*z2l - - ; exchange dwords in mm3 and mm5 - movq mm6,mm3 - movq mm7,mm5 - psrlq mm3,32 - psrlq mm5,32 - punpckldq mm3,mm6 - punpckldq mm5,mm7 - ; mm5: x2l z2l x2h z2h - ; mm3: y2l 0 y2h 0 - - ; compute the products x1h*x2l, x1l*x2h, etc - pmaddwd mm2,mm3 - ; mm2: y1h*y2l y1l*y2h - pmaddwd mm4,mm5 - ; mm4: x1h*x2l+z1h*z2l x1l*x2h+z1l*z2h - - paddd mm2,mm4 - ; mm2: x1h*x2l+y1h*y2l+z1h*z2l x1l*x2h+y1l*y2h+z1l*z2h - - ; get the low order dwords of mm0,mm1 - movq mm3,mm0 - punpckldq mm0,mm1 - ; mm0: x1l*x2l+z1l*z2l y1l*y2l - - ; unfortunately, at this point it is possible to have the - ; wrong value in mm0: if x1l,x2l,x1l,x2l - ; are all -0x8000, the result should - ; be +0x80000000, but of course this becomes - ; -0x80000000 - ; in fact the largest +ve value we could have is - ; +0x80000000 - ; and the lowest -ve value we could have is - ; -0x7fff0000 - ; = 0x80010000 - ; so subtracting ONE at this stage gives us a value - ; which is out by ONE, but twos-complement correct - psubd mm0,_mmx_one_fixed_h - - ; and the high order dwords - punpckhdq mm1,mm3 - ; mm1: x1h*x2h+z1h*z2h y1h*y2h - ; in fact it is swapped, but it doesn't matter - - ; shift the low order dwords down - psrad mm0,16 - ; and the high order dwords up - pslld mm1,16 - ; mm0: x1l*x2l+z1l*z2l>>16 -1 y1l*y2l>>16 - ; mm1: x1h*x2h+z1h*z2h<<16 y1h*y2h<<16 - ;(mm2) x1h*x2l+y1h*y2l+z1h*z2l x1l*x2h+y1l*y2h+z1l*z2h - - ; sum up - paddd mm2,mm0 - paddd mm2,mm1 - movq mm1,mm2 - psrlq mm2,32 - paddd mm1,mm2 - movd eax,mm1 - - emms - inc eax - ret - -else - ; - ; Now the optimized version - - movq mm0,[edx] - - movd mm2,[edx+08h] - movq mm4,mm0 - - - pand mm4,_mmx_sign_mask - movq mm6,mm2 - - movq mm1,[eax] - paddd mm4,mm4 - - movd mm3,[eax+08h] - movq mm5,mm1 - - pand mm6,_mmx_sign_mask - movq mm7,mm3 - - pand mm5,_mmx_sign_mask - paddd mm6,mm6 - - pand mm7,_mmx_sign_mask - paddd mm5,mm5 - - paddd mm0,mm4 - paddd mm2,mm6 - - paddd mm7,mm7 - movq mm4,mm2 - - punpcklwd mm4,mm0 - paddd mm1,mm5 - - punpckhwd mm2,mm0 - paddd mm3,mm7 - - movq mm5,mm3 - punpckhwd mm3,mm1 - - punpcklwd mm5,mm1 - movq mm0,mm2 - - movq mm1,mm4 - pmaddwd mm0,mm3 - - movq mm6,mm3 - psrlq mm3,32 - - movq mm7,mm5 - punpckldq mm3,mm6 - - pmaddwd mm1,mm5 - psrlq mm5,32 - - punpckldq mm5,mm7 - pmaddwd mm2,mm3 - - pmaddwd mm4,mm5 - movq mm3,mm0 - - ; these instructions won't pair and I have no instructions I can pair them with - punpckldq mm0,mm1 - - psubd mm0,_mmx_one_fixed_h - punpckhdq mm1,mm3 - - psrad mm0,16 - paddd mm2,mm4 - - pslld mm1,16 - paddd mm2,mm0 - - ; complete pairing is not possible at this stage - there are too many dependencies - paddd mm2,mm1 - - movq mm1,mm2 - psrlq mm2,32 - - paddd mm1,mm2 - - movd eax,mm1 - - emms - - inc eax - ret - -endif - - ; This takes 33 cycles, the orignal C -> nonMMX version takes 80 cycles - - align -_MMXAsm_VectorDot16: -MMXAsm_VectorDot16_: - - movd mm0,[edx+08h] - - packssdw mm0,[edx] - - movd mm1,[eax+08h] - - packssdw mm1,[eax] - - pmaddwd mm0,mm1 - - movq mm1,mm0 - psrlq mm0,32 - - paddd mm0,mm1 - - movd eax,mm0 - - emms - - ret - ; taking 14 cycles but assuming 16bit input vector fields - - - align -_MMXAsm_VectorTransformed: -MMXAsm_VectorTransformed_: - -if 0 - ; eax ptr to result - ; edx ptr to vector xh, xl, yh, yl, zh, zl - ; ecx ptr to matrix a11h, a11l, a12h, etc - - ; unoptimized version - - ; NOTE: in the Dot Product there was a problem - ; of an internal overflow where -32768*-32768 + -32768*-32768 gave 0x80000000 - ; which is -ve in two's complement - ; the additions and subtractions of ONE to resolve this problem - ; are marked '******' - - movq mm0,[edx] - movq mm1,mm0 - pand mm1,_mmx_sign_mask - paddd mm1,mm1 - paddd mm0,mm1 - ; mm0: yh yl xh xl - - movq mm2,[ecx] - movq mm3,mm2 - pand mm3,_mmx_sign_mask - paddd mm3,mm3 - paddd mm2,mm3 - ; mm2: a21h a21l a11h a11l - - movd mm4,[edx+08h] - movq mm5,mm4 - pand mm5,_mmx_sign_mask - paddd mm5,mm5 - paddd mm4,mm5 - ; mm4: 0 0 zh zl - - movq mm6,[ecx+18h] - movq mm7,mm6 - pand mm7,_mmx_sign_mask - paddd mm7,mm7 - paddd mm6,mm7 - ; mm6: a23h a23l a13h a13l - - ; interleave - - movq mm1,mm0 - punpckhwd mm0,mm4 - ; mm0: 0 yh 0 yl - punpcklwd mm1,mm4 - ; mm1: zh xh zl xl - - movq mm3,mm2 - punpckhwd mm2,mm6 - ; mm2: a23h a21h a23l a21l - punpcklwd mm3,mm6 - ; mm3: a13h a11h a13l a11l - - ; get a13*z, a11*x; a23*z a21*x, high and low products - movq mm4,mm1 - pmaddwd mm1,mm2 - movq mm6,mm4 - pmaddwd mm4,mm3 - ; mm0: 0 yh 0 yl - ; mm6: zh xh zl xl - ; mm2: a23h a21h a23l a21l - ; mm3: a13h a11h a13l a11l - ; mm1: zh*a23h+xh*a21h zl*a23l+xl*a21l - ; mm4: zh*a13h+xh*a11h zl*a13l+xl*a11l - - ; exchange dwords in mm6 - movq mm7,mm6 - psrlq mm6,32 - punpckldq mm6,mm7 - ; mm6: zl xl zh xh - ; mm7: zh xh zl xl - - ; get the high-low 'cross' products - pmaddwd mm2,mm6 - pmaddwd mm3,mm6 - ; mm2: a23h*zl+a21h*xl a23l*zh+a21l*xh - ; mm3: a13h*zl+a11h*xl a13l*zh+a11l*xh - - ; interleave mm1,mm4 and mm2,mm3 - movq mm5,mm4 - punpckldq mm4,mm1 - punpckhdq mm5,mm1 - ; mm4: zl*a23l+xl*a21l zl*a13l+xl*a11l ****** - ; mm5: zh*a23h+xh*a21h zh*a13h+xh*a11h - - ; ****** - psubd mm4,_mmx_one_fixed_hl - - - movq mm1,mm3 - punpckldq mm3,mm2 - punpckhdq mm1,mm2 - ; mm1: zl*a23h+xl*a21h zl*a13h+xl*a11h - ; mm3: zh*a23l+xh*a21l zh*a13l+xh*a11l - ; sum - paddd mm1,mm3 - ; shift the low order dwords down - psrad mm4,16 - ; and the high order dwords up - pslld mm5,16 - ; sum - paddd mm1,mm4 - paddd mm1,mm5 - ; mm1 holding x and y of the result - ; mm0: 0 yh 0 yl - ; mm1: z*a23+x*a21 z*a13+x*a11 - ; mm2: - ; mm3: - ; mm4: - ; mm5: - ; mm6: zl xl zh xh - ; mm7: zh xh zl xl - - ; grab some more of the matrix - movq mm2,[ecx+08h] - movq mm3,mm2 - pand mm3,_mmx_sign_mask - paddd mm3,mm3 - paddd mm2,mm3 ; mm7 not mm2 in optimized version - ; mm2: a12h a12l a31h a31l - - movd mm4,[ecx+20h] - movq mm5,mm4 - pand mm5,_mmx_sign_mask - paddd mm5,mm5 - paddd mm4,mm5 - ; mm4: 0 0 a33h a33l - - ; interleave - movq mm3,mm2 - punpcklwd mm2,mm4 - ; mm2: a33h a31h a33l a31l - psrlq mm3,32 - ; mm3: 0 0 a12h a12l - - ; compute mm2 * mm6/7 - movq mm4,mm2 - pmaddwd mm2,mm7 - pmaddwd mm4,mm6 - ; mm2: a33h*zh+a31h*xh a33l*zl+a31l*xl ****** - ; mm4: a33h*zl+a31h*xl a33l*zh+a31l*xh - movq mm7,mm2 - - ; ****** - psubd mm7,_mmx_one_fixed_hl - - pslld mm2,16 - psrad mm7,16 - paddd mm2,mm4 - paddd mm7,mm4 - psrlq mm2,32 - paddd mm2,mm7 - ; mm2: ? a33*z+a31*x - - - - ; get the rest of the matrix - movq mm5,[ecx+010h] - movq mm6,mm5 - pand mm6,_mmx_sign_mask - paddd mm6,mm6 - paddd mm5,mm6 - ; mm5: a32h a32l a22h a22l - ; mm3: 0 0 a12h a12l - - ; mm0: 0 yh 0 yl - movq mm7,mm0 - psrlq mm0,32 - punpcklwd mm0,mm7 - ; mm0: 0 0 yl yh - punpckldq mm0,mm0 - - ; mm0: yl yh yl yh - movq mm7,mm0 - pmaddwd mm0,mm3 - movq mm6,mm7 - pmaddwd mm7,mm5 - ; mm0: 0 yl*a12h+yh*a12l - ; mm7: yl*a32h+yh*a32l yl*a22h+yh*a22l - ; mm6: yl yh yl yh - punpckldq mm0,mm7 - ; mm0: yl*a22h+yh*a22l yl*a12h+yh*a12l - paddd mm1,mm0 - ; mm1: z*a23+x*a21+yl*a22h+yh*a22l z*a13+x*a11+yl*a12h+yh*a12l - psrlq mm7,32 - paddd mm2,mm7 - ; mm2: ? a33*z+a31*x+yl*a32h+yh*a32l - - - - ; mm5: a32h a32l a22h a22l - ; mm3: 0 0 a12h a12l - ; mm6: yl yh yl yh - - - - ; get all h and l separate - movq mm4,mm3 - punpcklwd mm3,mm5 - ; mm3: a22h a12h a22l a12l - punpckhwd mm5,mm4 - ; mm5: 0 a32h 0 a32l - movq mm4,mm3 - punpckhdq mm3,mm5 - ; mm3: 0 a32h a22h a12h - punpckldq mm4,mm5 - ; mm4: 0 a32l a22l a12l - punpckhwd mm6,mm6 - ; mm6: yl yl yh yh - movq mm0,mm6 - punpckhdq mm6,mm6 - ; mm6: yl yl yl yl - punpckldq mm0,mm0 - ; mm0: yh yh yh yh - pmullw mm3,mm0 - pmulhw mm4,mm6 - ; mm3: 0 a32h*yh a22h*yh a12h*yh - ; mm4: 0 a32l*yl>>16 a22l*yl>>16 a12l*yl>>16 - pxor mm7,mm7 - pcmpgtw mm7,mm4 - paddw mm3,mm7 - - movq mm5,mm4 - punpcklwd mm4,mm3 - punpckhwd mm5,mm3 - paddd mm1,mm4 - paddd mm2,mm5 - - ; ****** - paddd mm1,_mmx_one_hl - paddd mm2,_mmx_one_hl - - movq [eax],mm1 - movd [eax+08h],mm2 - - emms - ret - -else - ; - ; optimized version - - movq mm0,[edx] - - movd mm4,[edx+08h] - movq mm1,mm0 - - movq mm2,[ecx] - movq mm5,mm4 - - pand mm1,_mmx_sign_mask - movq mm3,mm2 - - pand mm5,_mmx_sign_mask - paddd mm1,mm1 - - movq mm6,[ecx+18h] - paddd mm5,mm5 - - pand mm3,_mmx_sign_mask - movq mm7,mm6 - - paddd mm0,mm1 - paddd mm3,mm3 - - pand mm7,_mmx_sign_mask - paddd mm2,mm3 - - movq mm1,mm0 - punpckhwd mm0,mm4 - - paddd mm4,mm5 - paddd mm7,mm7 - - paddd mm6,mm7 - punpcklwd mm1,mm4 - - movq mm3,mm2 - punpckhwd mm2,mm6 - - punpcklwd mm3,mm6 - movq mm4,mm1 - - movq mm6,mm1 - pmaddwd mm4,mm3 - - movq mm7,mm6 - psrlq mm6,32 - - pmaddwd mm1,mm2 - punpckldq mm6,mm7 - - movq store1,mm7 - pmaddwd mm3,mm6 - - movq mm7,[ecx+08h] - pmaddwd mm2,mm6 - - movq mm5,mm4 - punpckldq mm4,mm1 - - psubd mm4,_mmx_one_fixed_hl - punpckhdq mm5,mm1 - - movq mm1,mm7 - psrad mm4,16 - - pand mm1,_mmx_sign_mask - pslld mm5,16 - - paddd mm1,mm1 - paddd mm5,mm4 - - paddd mm7,mm1 - movq mm1,mm3 - - movd mm4,[ecx+20h] - punpckldq mm3,mm2 - - paddd mm3,mm5 - movq mm5,mm4 - - pand mm5,_mmx_sign_mask - punpckhdq mm1,mm2 - - paddd mm1,mm3 - paddd mm5,mm5 - - movq mm2,[ecx+010h] - movq mm3,mm7 - - paddd mm4,mm5 - movq mm5,mm2 - - pand mm2,_mmx_sign_mask - punpcklwd mm7,mm4 - - movq mm4,mm7 - psrlq mm3,32 - - pmaddwd mm7,store1 - paddd mm2,mm2 - - pmaddwd mm4,mm6 - movq mm6,mm0 - - psrlq mm0,32 - paddd mm5,mm2 - - punpcklwd mm0,mm6 - movq mm2,mm7 - - psubd mm7,_mmx_one_fixed_hl - pslld mm2,16 - - psrad mm7,16 - paddd mm2,mm4 - - paddd mm7,mm4 - punpckldq mm0,mm0 - - movq mm6,mm0 - psrlq mm2,32 - - paddd mm2,mm7 - movq mm7,mm6 - - pmaddwd mm0,mm3 - punpckhwd mm7,mm7 - - pmaddwd mm6,mm5 - movq mm4,mm3 - - punpcklwd mm3,mm5 - - punpckhwd mm5,mm4 - movq mm4,mm7 - - punpckldq mm0,mm6 - - paddd mm1,mm0 - punpckhdq mm7,mm7 - - movq mm0,mm3 - punpckldq mm3,mm5 - - pmulhw mm3,mm7 - punpckhdq mm0,mm5 - - punpckldq mm4,mm4 - - pmullw mm0,mm4 - psrlq mm6,32 - - paddd mm2,mm6 - pxor mm6,mm6 - - pcmpgtw mm6,mm3 - movq mm5,mm3 - - paddd mm1,_mmx_one_hl - paddw mm0,mm6 - - paddd mm2,_mmx_one_hl - punpcklwd mm3,mm0 - - paddd mm1,mm3 - punpckhwd mm5,mm0 - - paddd mm2,mm5 - - movq [eax],mm1 - - movd [eax+08h],mm2 - - emms - ret - ; 63 cycles compared with 204 for the C-nonMMX version -endif - - align -_MMXAsm_VectorTransform: -MMXAsm_VectorTransform_: - - movq mm0,[eax] - - movd mm4,[eax+08h] - movq mm1,mm0 - - movq mm2,[edx] - movq mm5,mm4 - - pand mm1,_mmx_sign_mask - movq mm3,mm2 - - pand mm5,_mmx_sign_mask - paddd mm1,mm1 - - movq mm6,[edx+18h] - paddd mm5,mm5 - - pand mm3,_mmx_sign_mask - movq mm7,mm6 - - paddd mm0,mm1 - paddd mm3,mm3 - - pand mm7,_mmx_sign_mask - paddd mm2,mm3 - - movq mm1,mm0 - punpckhwd mm0,mm4 - - paddd mm4,mm5 - paddd mm7,mm7 - - paddd mm6,mm7 - punpcklwd mm1,mm4 - - movq mm3,mm2 - punpckhwd mm2,mm6 - - punpcklwd mm3,mm6 - movq mm4,mm1 - - movq mm6,mm1 - pmaddwd mm4,mm3 - - movq mm7,mm6 - psrlq mm6,32 - - pmaddwd mm1,mm2 - punpckldq mm6,mm7 - - movq store1,mm7 - pmaddwd mm3,mm6 - - movq mm7,[edx+08h] - pmaddwd mm2,mm6 - - movq mm5,mm4 - punpckldq mm4,mm1 - - psubd mm4,_mmx_one_fixed_hl - punpckhdq mm5,mm1 - - movq mm1,mm7 - psrad mm4,16 - - pand mm1,_mmx_sign_mask - pslld mm5,16 - - paddd mm1,mm1 - paddd mm5,mm4 - - paddd mm7,mm1 - movq mm1,mm3 - - movd mm4,[edx+20h] - punpckldq mm3,mm2 - - paddd mm3,mm5 - movq mm5,mm4 - - pand mm5,_mmx_sign_mask - punpckhdq mm1,mm2 - - paddd mm1,mm3 - paddd mm5,mm5 - - movq mm2,[edx+010h] - movq mm3,mm7 - - paddd mm4,mm5 - movq mm5,mm2 - - pand mm2,_mmx_sign_mask - punpcklwd mm7,mm4 - - movq mm4,mm7 - psrlq mm3,32 - - pmaddwd mm7,store1 - paddd mm2,mm2 - - pmaddwd mm4,mm6 - movq mm6,mm0 - - psrlq mm0,32 - paddd mm5,mm2 - - punpcklwd mm0,mm6 - movq mm2,mm7 - - psubd mm7,_mmx_one_fixed_hl - pslld mm2,16 - - psrad mm7,16 - paddd mm2,mm4 - - paddd mm7,mm4 - punpckldq mm0,mm0 - - movq mm6,mm0 - psrlq mm2,32 - - paddd mm2,mm7 - movq mm7,mm6 - - pmaddwd mm0,mm3 - punpckhwd mm7,mm7 - - pmaddwd mm6,mm5 - movq mm4,mm3 - - punpcklwd mm3,mm5 - - punpckhwd mm5,mm4 - movq mm4,mm7 - - punpckldq mm0,mm6 - - paddd mm1,mm0 - punpckhdq mm7,mm7 - - movq mm0,mm3 - punpckldq mm3,mm5 - - pmulhw mm3,mm7 - punpckhdq mm0,mm5 - - punpckldq mm4,mm4 - - pmullw mm0,mm4 - psrlq mm6,32 - - paddd mm2,mm6 - pxor mm6,mm6 - - pcmpgtw mm6,mm3 - movq mm5,mm3 - - paddd mm1,_mmx_one_hl - paddw mm0,mm6 - - paddd mm2,_mmx_one_hl - punpcklwd mm3,mm0 - - paddd mm1,mm3 - punpckhwd mm5,mm0 - - paddd mm2,mm5 - - movq [eax],mm1 - - movd [eax+08h],mm2 - - emms - ret - ; 63 cycles compared with 204 for the C-nonMMX version - - - align -_MMXAsm_VectorTransformedAndAdd: -MMXAsm_VectorTransformedAndAdd_: - - movq mm0,[edx] - - movd mm4,[edx+08h] - movq mm1,mm0 - - movq mm2,[ecx] - movq mm5,mm4 - - pand mm1,_mmx_sign_mask - movq mm3,mm2 - - pand mm5,_mmx_sign_mask - paddd mm1,mm1 - - movq mm6,[ecx+18h] - paddd mm5,mm5 - - pand mm3,_mmx_sign_mask - movq mm7,mm6 - - paddd mm0,mm1 - paddd mm3,mm3 - - pand mm7,_mmx_sign_mask - paddd mm2,mm3 - - movq mm1,mm0 - punpckhwd mm0,mm4 - - paddd mm4,mm5 - paddd mm7,mm7 - - paddd mm6,mm7 - punpcklwd mm1,mm4 - - movq mm3,mm2 - punpckhwd mm2,mm6 - - punpcklwd mm3,mm6 - movq mm4,mm1 - - movq mm6,mm1 - pmaddwd mm4,mm3 - - movq mm7,mm6 - psrlq mm6,32 - - pmaddwd mm1,mm2 - punpckldq mm6,mm7 - - movq store1,mm7 - pmaddwd mm3,mm6 - - movq mm7,[ecx+08h] - pmaddwd mm2,mm6 - - movq mm5,mm4 - punpckldq mm4,mm1 - - psubd mm4,_mmx_one_fixed_hl - punpckhdq mm5,mm1 - - movq mm1,mm7 - psrad mm4,16 - - pand mm1,_mmx_sign_mask - pslld mm5,16 - - paddd mm1,mm1 - paddd mm5,mm4 - - paddd mm7,mm1 - movq mm1,mm3 - - movd mm4,[ecx+20h] - punpckldq mm3,mm2 - - paddd mm3,mm5 - movq mm5,mm4 - - pand mm5,_mmx_sign_mask - punpckhdq mm1,mm2 - - paddd mm1,mm3 - paddd mm5,mm5 - - movq mm2,[ecx+010h] - movq mm3,mm7 - - paddd mm4,mm5 - movq mm5,mm2 - - pand mm2,_mmx_sign_mask - punpcklwd mm7,mm4 - - movq mm4,mm7 - psrlq mm3,32 - - pmaddwd mm7,store1 - paddd mm2,mm2 - - pmaddwd mm4,mm6 - movq mm6,mm0 - - psrlq mm0,32 - paddd mm5,mm2 - - punpcklwd mm0,mm6 - movq mm2,mm7 - - psubd mm7,_mmx_one_fixed_hl - pslld mm2,16 - - psrad mm7,16 - paddd mm2,mm4 - - paddd mm7,mm4 - punpckldq mm0,mm0 - - movq mm6,mm0 - psrlq mm2,32 - - paddd mm2,mm7 - movq mm7,mm6 - - pmaddwd mm0,mm3 - punpckhwd mm7,mm7 - - pmaddwd mm6,mm5 - movq mm4,mm3 - - paddd mm1,_mmx_one_hl - punpcklwd mm3,mm5 - - punpckhwd mm5,mm4 - movq mm4,mm7 - - paddd mm2,_mmx_one_hl - punpckldq mm0,mm6 - - paddd mm1,mm0 - punpckhdq mm7,mm7 - - movq mm0,mm3 - punpckldq mm3,mm5 - - pmulhw mm3,mm7 - punpckhdq mm0,mm5 - - paddd mm1,[ebx] - punpckldq mm4,mm4 - - pmullw mm0,mm4 - psrlq mm6,32 - - paddd mm2,mm6 - pxor mm6,mm6 - - pcmpgtw mm6,mm3 - movq mm5,mm3 - - movd mm4,[ebx+08h] - paddw mm0,mm6 - - paddd mm2,mm4 - punpcklwd mm3,mm0 - - paddd mm1,mm3 - punpckhwd mm5,mm0 - - paddd mm2,mm5 - - movq [eax],mm1 - - movd [eax+08h],mm2 - - emms - ret - ; 63 cycles compared with 204 for the C-nonMMX version - - - align -_MMXAsm_VectorTransformAndAdd: -MMXAsm_VectorTransformAndAdd_: - - movq mm0,[eax] - - movd mm4,[eax+08h] - movq mm1,mm0 - - movq mm2,[edx] - movq mm5,mm4 - - pand mm1,_mmx_sign_mask - movq mm3,mm2 - - pand mm5,_mmx_sign_mask - paddd mm1,mm1 - - movq mm6,[edx+18h] - paddd mm5,mm5 - - pand mm3,_mmx_sign_mask - movq mm7,mm6 - - paddd mm0,mm1 - paddd mm3,mm3 - - pand mm7,_mmx_sign_mask - paddd mm2,mm3 - - movq mm1,mm0 - punpckhwd mm0,mm4 - - paddd mm4,mm5 - paddd mm7,mm7 - - paddd mm6,mm7 - punpcklwd mm1,mm4 - - movq mm3,mm2 - punpckhwd mm2,mm6 - - punpcklwd mm3,mm6 - movq mm4,mm1 - - movq mm6,mm1 - pmaddwd mm4,mm3 - - movq mm7,mm6 - psrlq mm6,32 - - pmaddwd mm1,mm2 - punpckldq mm6,mm7 - - movq store1,mm7 - pmaddwd mm3,mm6 - - movq mm7,[edx+08h] - pmaddwd mm2,mm6 - - movq mm5,mm4 - punpckldq mm4,mm1 - - psubd mm4,_mmx_one_fixed_hl - punpckhdq mm5,mm1 - - movq mm1,mm7 - psrad mm4,16 - - pand mm1,_mmx_sign_mask - pslld mm5,16 - - paddd mm1,mm1 - paddd mm5,mm4 - - paddd mm7,mm1 - movq mm1,mm3 - - movd mm4,[edx+20h] - punpckldq mm3,mm2 - - paddd mm3,mm5 - movq mm5,mm4 - - pand mm5,_mmx_sign_mask - punpckhdq mm1,mm2 - - paddd mm1,mm3 - paddd mm5,mm5 - - movq mm2,[edx+010h] - movq mm3,mm7 - - paddd mm4,mm5 - movq mm5,mm2 - - pand mm2,_mmx_sign_mask - punpcklwd mm7,mm4 - - movq mm4,mm7 - psrlq mm3,32 - - pmaddwd mm7,store1 - paddd mm2,mm2 - - pmaddwd mm4,mm6 - movq mm6,mm0 - - psrlq mm0,32 - paddd mm5,mm2 - - punpcklwd mm0,mm6 - movq mm2,mm7 - - psubd mm7,_mmx_one_fixed_hl - pslld mm2,16 - - psrad mm7,16 - paddd mm2,mm4 - - paddd mm7,mm4 - punpckldq mm0,mm0 - - movq mm6,mm0 - psrlq mm2,32 - - paddd mm2,mm7 - movq mm7,mm6 - - pmaddwd mm0,mm3 - punpckhwd mm7,mm7 - - pmaddwd mm6,mm5 - movq mm4,mm3 - - paddd mm1,_mmx_one_hl - punpcklwd mm3,mm5 - - punpckhwd mm5,mm4 - movq mm4,mm7 - - paddd mm2,_mmx_one_hl - punpckldq mm0,mm6 - - paddd mm1,mm0 - punpckhdq mm7,mm7 - - movq mm0,mm3 - punpckldq mm3,mm5 - - pmulhw mm3,mm7 - punpckhdq mm0,mm5 - - paddd mm1,[ecx] - punpckldq mm4,mm4 - - pmullw mm0,mm4 - psrlq mm6,32 - - paddd mm2,mm6 - pxor mm6,mm6 - - pcmpgtw mm6,mm3 - movq mm5,mm3 - - movd mm4,[ecx+08h] - paddw mm0,mm6 - - paddd mm2,mm4 - punpcklwd mm3,mm0 - - paddd mm1,mm3 - punpckhwd mm5,mm0 - - paddd mm2,mm5 - - movq [eax],mm1 - - movd [eax+08h],mm2 - - emms - ret - ; 63 cycles compared with 204 for the C-nonMMX version - - -_TEXT ENDS - -END - diff --git a/3dc/win95/OBCHUNK.CPP b/3dc/win95/OBCHUNK.CPP deleted file mode 100644 index 86e8857..0000000 --- a/3dc/win95/OBCHUNK.CPP +++ /dev/null @@ -1,1434 +0,0 @@ -#include "chunk.hpp" -#include "chnktype.hpp" -#include "mishchnk.hpp" -#include "obchunk.hpp" -#include "shpchunk.hpp" -#include "envchunk.hpp" -#include "md5.h" -// Class Object_Chunk functions - -#ifdef cencon -#define new my_new -#endif -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(obchunk) - -RIF_IMPLEMENT_DYNCREATE("RBOBJECT",Object_Chunk) - -/* -Children for Object_Chunk : - -"OBJHEAD1" Object_Header_Chunk -"OBINTDT" Object_Interface_Data_Chunk -"OBJPRJDT" Object_Project_Data_Chunk -"MODULEDT" Object_Module_Data_Chunk -"SHPVTINT" Shape_Vertex_Intensities_Chunk -"OBJTRAK2" Object_Track_Chunk2 -"TRAKSOUN" Object_Track_Sound_Chunk -"OBANSEQS" Object_Animation_Sequences_Chunk -"PLOBJLIT" Placed_Object_Light_Chunk -"ALTLOCAT" Object_Alternate_Locations_Chunk -*/ - - - - - -// from buffer -Object_Chunk::Object_Chunk(Chunk_With_Children * parent, const char *data, size_t size) -: Lockable_Chunk_With_Children (parent, "RBOBJECT"), - object_data () -{ - const char * buffer_ptr = data; - - object_data_store = (ChunkObject *) &object_data; - - while ((data-buffer_ptr)< (signed) size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed) size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(data); - data += *(int *)(data + 8); - - } - - program_object_index=-1; - -} - -// from data -Object_Chunk::Object_Chunk (Chunk_With_Children * parent, ChunkObject &obj) -: Lockable_Chunk_With_Children (parent, "RBOBJECT"), - object_data (obj) -{ - object_data_store = (ChunkObject *) &object_data; - object_data_store->index_num=-1; - - new Object_Header_Chunk(this); - new Object_Interface_Data_Chunk(this); - - //if the parent is a file_chunk get an object index - if(!strcmp(parent->identifier,"REBINFF2")) - { - ((File_Chunk*)parent)->assign_index_to_object(this); - } - program_object_index=-1; - - CalculateID(); -} - -Object_Chunk::~Object_Chunk() -{ -} - -Object_Header_Chunk * Object_Chunk::get_header() -{ - - return (Object_Header_Chunk *) this->lookup_single_child ("OBJHEAD1"); - - -} - -Shape_Chunk * Object_Chunk::get_assoc_shape() -{ - if (!get_header()) return 0; - - return get_header()->associated_shape; - -} - -BOOL Object_Chunk::assoc_with_shape (Shape_Chunk * shpch) -{ - Object_Header_Chunk * obhead = get_header(); - - if (!obhead) return 0; - - // check that we are not already associated with this shape - - if (obhead->associated_shape == shpch) return 1; - - Shape_Header_Chunk * shphead = shpch->get_header(); - - if (!shphead) return 0; - - // deassociate with the old shape - - if (obhead->associated_shape) - deassoc_with_shape (obhead->associated_shape); - - // associate with the new - - obhead->associated_shape = shpch; - - if (!shphead->associated_objects_store.contains(this)) - shphead->associated_objects_store.add_entry(this); - - return 1; - -} - -BOOL Object_Chunk::deassoc_with_shape (Shape_Chunk * shpch) -{ - Shape_Header_Chunk * shphead = shpch->get_header(); - - if (!shphead) return 0; - - if (shphead->associated_objects_store.contains(this)) - shphead->associated_objects_store.delete_entry(this); - - Object_Header_Chunk * obhead = get_header(); - - obhead->associated_shape = 0; - - return 1; - -} - -BOOL Object_Chunk::file_equals(HANDLE &rif_file) -{ - unsigned long bytes_read; - char name[50]; - - // get header list - List<int> obhead; - list_chunks_in_file (&obhead, rif_file, "OBJHEAD1"); - - if (obhead.size() != 1) return FALSE; - - // get object identifier - SetFilePointer(rif_file,obhead.first_entry() + 96,0,FILE_BEGIN); - int i = 0; - do ReadFile (rif_file, (long *) (name + i), 1, &bytes_read, 0); - while (name[i++] != 0); - - if (!strcmp(name, object_data.o_name) ) return (TRUE); - - return (FALSE); -} - -const char * Object_Chunk::get_head_id() -{ - Object_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return (0); - - return(hdptr->identifier); -} - -void Object_Chunk::set_lock_user (char * user) -{ - Object_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return; - - strncpy (hdptr->lock_user, user,16); - - hdptr->lock_user[16] = 0; -} - - -BOOL Object_Chunk::inc_v_no () -{ - Object_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return (FALSE); - - hdptr->version_no++; - - return (TRUE); -} - -BOOL Object_Chunk::same_and_updated(Object_Chunk & obj) -{ - - Object_Header_Chunk * hd1ptr = get_header(); - - if (!hd1ptr) return (0); - - Object_Header_Chunk * hd2ptr = obj.get_header(); - - if (!hd2ptr) return (0); - - return (hd1ptr->version_no < hd2ptr->version_no && - (!strcmp(obj.object_data.o_name, object_data.o_name)) ); - -} - -BOOL Object_Chunk::assoc_with_shape_no(File_Chunk *fc) -{ - Object_Header_Chunk * hdptr = get_header(); - Shape_Chunk * shp = NULL; - Shape_Header_Chunk * shphd; - - if (!hdptr) return (FALSE); - - List<Chunk *> chlst; - fc->lookup_child("REBSHAPE",chlst); - - for (LIF<Chunk *> l(&chlst); !l.done(); l.next()) - { - shp = (Shape_Chunk *)l(); - shphd = shp->get_header(); - if (shphd) - { - if (hdptr->shape_id_no == shphd->file_id_num) - break; - } - } - if (!l.done()) - { - assoc_with_shape(shp); - } - else - { - return(FALSE); - } - - return(TRUE); - - -} - - - - -void Object_Chunk::post_input_processing() -{ - CalculateID(); - - if (get_header()) - if (get_header()->flags & GENERAL_FLAG_LOCKED) - external_lock = TRUE; - - Chunk_With_Children::post_input_processing(); - -} - - -VModule_Array_Chunk * Object_Chunk::get_vmod_chunk() -{ - Object_Module_Data_Chunk * omdc = 0; - - omdc = (Object_Module_Data_Chunk *) lookup_single_child ("MODULEDT"); - - - if (omdc) - { - VModule_Array_Chunk * vmac = 0; - vmac = (VModule_Array_Chunk *)omdc->lookup_single_child ("VMDARRAY") ; - - if (vmac) return(vmac); - } - - return(0); - - -} - -void Object_Chunk::destroy(File_Chunk * fc) -{ - List<Chunk *> cl; - fc->lookup_child("RBOBJECT",cl); - - for (LIF<Chunk *> cli(&cl); !cli.done(); cli.next()) - { - Object_Chunk * ob = (Object_Chunk *)cli(); - if (ob == this) continue; - - VModule_Array_Chunk * vmac = ob->get_vmod_chunk(); - - BOOL in_object_va = FALSE; - - if (vmac) - { - int pos=0; - for(int i=0;i<vmac->num_array_items;i++) - { - - if (vmac->vmod_array[i].object_index==object_data.index_num) - { - in_object_va=TRUE; - //update branch indeces for branches that go beyond this point - for(int j=0;j<vmac->num_array_items;j++) - { - if(vmac->vmod_array[j].branch_no> pos) - vmac->vmod_array[j].branch_no--; - } - } - else - { - if(pos!=i) - { - vmac->vmod_array[pos]=vmac->vmod_array[i]; - } - pos++; - } - } - - if(in_object_va) - { - if(pos==0) - { - delete vmac; - } - else - { - //excess entries should be properly deleted when the array is deleted - vmac->num_array_items=pos; - } - - } - - } - - //now remove this object from any adjacency data - - Object_Module_Data_Chunk* omdc=(Object_Module_Data_Chunk*)ob->lookup_single_child("MODULEDT"); - if(omdc) - { - Adjacent_Module_Entry_Points_Chunk* amepc=(Adjacent_Module_Entry_Points_Chunk*)omdc->lookup_single_child("ADJMDLEP"); - - if(amepc) - { - for(LIF<Adjacent_Module> ad_lif(&amepc->adjacent_modules_list);!ad_lif.done();) - { - if(ad_lif().object_index==object_data.index_num) - ad_lif.delete_current(); - else - ad_lif.next(); - - } - } - } - - - } - - Shape_Chunk * shp = get_assoc_shape(); - - deassoc_with_shape (shp); - - lock_chunk(*fc); - - deleted = TRUE; - - unlock_chunk(*fc,TRUE); - -} - - -void Object_Chunk::update_my_chunkobject(ChunkObject & cob) -{ - //store the object's index , so that it doesn't get lost - int object_index=object_data_store->index_num; - *object_data_store = cob; - //replace the object index - object_data_store->index_num=object_index; - //recalculate the object's id in case the name has changed - CalculateID(); -} - -ObjectID Object_Chunk::CalculateID() -{ - ObjectID retval={0,0}; - List<Chunk*> chlist; - parent->lookup_child("REBENVDT",chlist); - if(!chlist.size()) return retval; - ((Environment_Data_Chunk*)chlist.first_entry())->lookup_child("RIFFNAME",chlist); - if(!chlist.size()) return retval; - char Name[100]; - - #if InterfaceEngine||cencon - //need to check for console specific rif files,and skip the 'sat' or 'psx' - //so that they get the same ids as the pc - const char* r_name=((RIF_Name_Chunk*)chlist.first_entry())->rif_name; - if(tolower(r_name[0])=='p' && tolower(r_name[1])=='s' && tolower(r_name[2])=='x' ) - strcpy(Name,&r_name[3]); - else if (tolower(r_name[0])=='s' && tolower(r_name[1])=='a' && tolower(r_name[2])=='t' ) - strcpy(Name,&r_name[3]); - else - strcpy(Name,r_name); - #else - strcpy(Name,((RIF_Name_Chunk*)chlist.first_entry())->rif_name); - #endif - - strcat(Name,object_data.o_name); - char buffer[16]; - md5_buffer(Name,strlen(Name),&buffer[0]); - buffer[7]=0; - object_data_store->ID=*(ObjectID*)&buffer[0]; - return object_data_store->ID; - -} - -///////////////////////////////////////// - -// Class Object_Header_Chunk functions -RIF_IMPLEMENT_DYNCREATE("OBJHEAD1",Object_Header_Chunk) - -// from buffer -#if UseOldChunkLoader -Object_Header_Chunk::Object_Header_Chunk(Object_Chunk * parent, const char * hdata, size_t /*hsize*/) -: Chunk (parent, "OBJHEAD1"), object_data (parent->object_data_store), -flags(0), version_no (0), associated_shape (0) -{ - flags = *((int *) hdata); - - if (flags & OBJECT_FLAG_BASE_OBJECT) - parent->object_data_store->is_base_object = TRUE; - else - { - parent->object_data_store->is_base_object = FALSE; - } - - strncpy (lock_user, (hdata + 4), 16); - lock_user[16] = '\0'; - - parent->object_data_store->float_location = *((ChunkVector *) (hdata + 20)); - parent->object_data_store->location = parent->object_data_store->float_location; - - parent->object_data_store->orientation.x =- *((double *) (hdata + 44)); - parent->object_data_store->orientation.y =- *((double *) (hdata + 52)); - parent->object_data_store->orientation.z =- *((double *) (hdata + 60)); - parent->object_data_store->orientation.w = *((double *) (hdata + 68)); - - version_no = *((int *) (hdata + 76)); - - shape_id_no = *((int *) (hdata + 80)); - - strcpy (parent->object_data_store->o_name, (hdata + 84)); - parent->object_data_store->ID.id1=0; - parent->object_data_store->ID.id2=0; - parent->object_data_store->index_num=-1; -} -#else -Object_Header_Chunk::Object_Header_Chunk(Chunk_With_Children * parent, const char * hdata, size_t /*hsize*/) -: Chunk (parent, "OBJHEAD1"), object_data (((Object_Chunk*)parent)->object_data_store), -flags(0), version_no (0), associated_shape (0) -{ - Object_Chunk* parent_object = (Object_Chunk*) parent; - - flags = *((int *) hdata); - - if (flags & OBJECT_FLAG_BASE_OBJECT) - parent_object->object_data_store->is_base_object = TRUE; - else - { - parent_object->object_data_store->is_base_object = FALSE; - } - - strncpy (lock_user, (hdata + 4), 16); - lock_user[16] = '\0'; - - hdata+=20; - - parent_object->object_data_store->location = *(ChunkVectorInt*) hdata; - hdata+=sizeof(ChunkVectorInt); - - parent_object->object_data_store->orientation = *((ChunkQuat *) hdata); - hdata+=sizeof(ChunkQuat); - - parent_object->object_data_store->index_num = *(int *) hdata; - hdata+=4; - - version_no = *((int *) hdata); - hdata+=4; - - shape_id_no = *((int *) hdata); - hdata+=4; - - strcpy (parent_object->object_data_store->o_name, hdata); - parent_object->object_data_store->ID.id1=0; - parent_object->object_data_store->ID.id2=0; -} -#endif - -//from data - -Object_Header_Chunk::Object_Header_Chunk (Object_Chunk * parent) -: Chunk (parent, "OBJHEAD1"), -object_data (parent->object_data_store), -flags (0), version_no (0), associated_shape(0) -{ - if (object_data->is_base_object) { - flags = OBJECT_FLAG_BASE_OBJECT; - } -} - - -size_t Object_Header_Chunk::size_chunk() -{ - int length = 72; - - length += (strlen(object_data->o_name)+1); - - length += (4-length%4)%4; - - chunk_size = length; - - return length; -} - -BOOL Object_Header_Chunk::output_chunk (HANDLE & hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -void Object_Header_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = flags; - strncpy ((data_start + 4), lock_user, 16); - data_start+=20; - - *((ChunkVectorInt *) (data_start)) = object_data->location; - data_start+=sizeof(ChunkVectorInt); - - *((ChunkQuat *) (data_start)) = object_data->orientation; - data_start+=sizeof(ChunkQuat); - - *(int*) data_start=object_data->index_num; - data_start+=4; - - *((int *) data_start) = version_no; - data_start+=4; - - *((int *) data_start) = shape_id_no; - data_start+=4; - - strcpy (data_start, object_data->o_name); -} - -void Object_Header_Chunk::prepare_for_output() -{ - version_no ++; -} - -///////////////////////////////////////// - -// Class Object_Interface_Data_Chunk functions -RIF_IMPLEMENT_DYNCREATE("OBINTDT",Object_Interface_Data_Chunk) - -/* -Children for Object_Interface_Data_Chunk : - -"OBJNOTES" Object_Notes_Chunk -*/ - -// from buffer -Object_Interface_Data_Chunk::Object_Interface_Data_Chunk(Chunk_With_Children * parent, const char *data, size_t size) -: Chunk_With_Children (parent, "OBINTDT") -{ - const char * buffer_ptr = data; - - while ((data-buffer_ptr)< (signed) size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed) size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(data); - data += *(int *)(data + 8); - } -} - -Object_Interface_Data_Chunk::Object_Interface_Data_Chunk (Object_Chunk * parent) -: Chunk_With_Children (parent, "OBINTDT") -{ - new Object_Notes_Chunk (this, "Enter notes here", strlen("Enter notes here") + 1); -} - - -/////////////////////////////////////// - -// Class Object_Notes_Chunk functions -RIF_IMPLEMENT_DYNCREATE("OBJNOTES",Object_Notes_Chunk) - -Object_Notes_Chunk::Object_Notes_Chunk (Chunk_With_Children * parent, - const char * _data, size_t _data_size) -: Chunk(parent, "OBJNOTES"), -data(NULL), data_size(_data_size) -{ - data_store = new char [data_size]; - - *((char **) &data) = data_store; - - for (int i = 0; i<(signed) data_size; i++) - data_store[i] = _data[i]; - -} - -void Object_Notes_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - for (int i = 0; i<((signed) chunk_size-12); i++) - data_start[i] = data[i]; -} - -Object_Notes_Chunk::~Object_Notes_Chunk () -{ - delete [] data_store; -} - -BOOL Object_Notes_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - - -/////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("MODULEDT",Object_Module_Data_Chunk) - -/* -Children For Object_Module_Data_Chunk : - -"VMDARRAY" VModule_Array_Chunk -"ADJMDLEP" Adjacent_Module_Entry_Points_Chunk -"MODFLAGS" Module_Flag_Chunk -"WAYPOINT" Module_Waypoint_Chunk -"MODACOUS" Module_Acoustics_Chunk -"AIMODMAS" AI_Module_Master_Chunk -"AIMODSLA" AI_Module_Slave_Chunk - -*/ - -Object_Module_Data_Chunk::Object_Module_Data_Chunk (Chunk_With_Children * parent,const char * mdata, size_t msize) -: Chunk_With_Children (parent, "MODULEDT") -{ - const char * buffer_ptr = mdata; - - while ((mdata-buffer_ptr)< (signed) msize) { - - if ((*(int *)(mdata + 8)) + (mdata-buffer_ptr) > (signed) msize) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - DynCreate(mdata); - mdata += *(int *)(mdata + 8); - - } - -} - -/////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("VMDARRAY",VModule_Array_Chunk) - -VModule_Array_Chunk::VModule_Array_Chunk(Object_Module_Data_Chunk * parent, VMod_Arr_Item * vma, int num_in_vma) -: Chunk (parent, "VMDARRAY") -{ - int i; - - num_array_items = num_in_vma; - - vmod_array = new VMod_Arr_Item [num_in_vma]; - - for (i=0; i<num_in_vma; i++) - { - vmod_array[i] = vma[i]; - } - -} - - -void VModule_Array_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = num_array_items; - - data_start += 4; - - for (int i=0; i<num_array_items; i++) - { - *((int *) data_start) = vmod_array[i].object_index; - data_start += 4; - - *((int *) data_start) = vmod_array[i].branch_no; - data_start += 4; - - *((int *) data_start) = vmod_array[i].flags; - data_start += 4; - - *((int *) data_start) = vmod_array[i].spare; - data_start += 4; - - } - -} - - -size_t VModule_Array_Chunk::size_chunk() -{ - chunk_size =16+16*num_array_items; - return(chunk_size); - -} - -#if UseOldChunkLoader -VModule_Array_Chunk::VModule_Array_Chunk (Object_Module_Data_Chunk * parent, const char * vmdata, size_t /*vmsize*/) -: Chunk (parent, "VMDARRAY") -{ - num_array_items = *((int *) vmdata); - - vmdata += 4; - - vmod_array = new VMod_Arr_Item [num_array_items]; - - for (int i=0; i<num_array_items; i++) - { - //vmod_array[i].type = *((int *) vmdata); - vmdata += 4; - vmod_array[i].branch_no = *((int *) vmdata); - vmdata += 4; - - //vmod_array[i].dir.x = *((double *) vmdata); - vmdata += 8; - //vmod_array[i].dir.y = *((double *) vmdata); - vmdata += 8; - //vmod_array[i].dir.z = *((double *) vmdata); - vmdata += 8; - - //vmod_array[i].angle = *((double *) vmdata); - vmdata += 8; - - vmod_array[i].flags = *((int *) vmdata); - vmdata += 4; - - vmod_array[i].spare = *((int *) vmdata); - vmdata += 4; - - vmod_array[i].object_index=-1; - - vmod_array[i].o_name = new char [strlen(vmdata) + 1]; - strcpy (vmod_array[i].o_name, vmdata); - vmdata += (strlen(vmod_array[i].o_name) + 1) + (4-(strlen(vmod_array[i].o_name) + 1)%4)%4; - - } - -} -#else -VModule_Array_Chunk::VModule_Array_Chunk (Chunk_With_Children * parent, const char * vmdata, size_t /*vmsize*/) -: Chunk (parent, "VMDARRAY") -{ - num_array_items = *((int *) vmdata); - - vmdata += 4; - - vmod_array = new VMod_Arr_Item [num_array_items]; - - for (int i=0; i<num_array_items; i++) - { - - vmod_array[i].object_index = *((int *) vmdata); - vmdata += 4; - - vmod_array[i].branch_no = *((int *) vmdata); - vmdata += 4; - - vmod_array[i].flags = *((int *) vmdata); - vmdata += 4; - - vmod_array[i].spare = *((int *) vmdata); - vmdata += 4; - - } - -} -#endif - -VModule_Array_Chunk::~VModule_Array_Chunk () -{ - delete [] vmod_array; -} - -/////////////////////////////////////// -#if 0 -void Adjacent_Modules_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = adjacent_modules_list.size(); - - data_start += 4; - - for (LIF<Adjacent_Module> ami(&adjacent_modules_list); !ami.done(); ami.next()) - { - - *((int *) data_start) = 0; - data_start += 4; - - *((int *) data_start) = 0; - data_start += 4; - - strcpy (data_start, ami().o_name); - data_start += (strlen(ami().o_name) + 1) + (4-(strlen(ami().o_name) + 1)%4)%4; - - } - -} - -size_t Adjacent_Modules_Chunk::size_chunk() -{ - int size = 16; - - for (LIF<Adjacent_Module> ami(&adjacent_modules_list); !ami.done(); ami.next()) - { - size += 8; - size += (strlen(ami().o_name) + 1) + (4-(strlen(ami().o_name) + 1)%4)%4; - } - - chunk_size = size; - return(size); - -} - -Adjacent_Modules_Chunk::Adjacent_Modules_Chunk (Object_Module_Data_Chunk * parent, const char * data, size_t /*size*/) -: Chunk (parent, "ADJMDLST") -{ - int num_array_items = *((int *) data); - - data += 4; - - for (int i=0; i<num_array_items; i++) - { - Adjacent_Module am; - - data += 8; - - am.o_name = new char [strlen(data) + 1]; - strcpy (am.o_name, data); - data += (strlen(am.o_name) + 1) + (4-(strlen(am.o_name) + 1)%4)%4; - - adjacent_modules_list.add_entry(am); - - } -} -#endif -/////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("ADJMDLEP",Adjacent_Module_Entry_Points_Chunk) - -void Adjacent_Module_Entry_Points_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = adjacent_modules_list.size(); - - data_start += 4; - - for (LIF<Adjacent_Module> ami(&adjacent_modules_list); !ami.done(); ami.next()) - { - - *((int *) data_start) = ami().object_index; - data_start += 4; - - *((int *) data_start) = ami().flags; - data_start += 4; - - *((ChunkVectorInt *) data_start) = ami().entry_point; - data_start += sizeof(ChunkVectorInt); - - - } - -} - - -size_t Adjacent_Module_Entry_Points_Chunk::size_chunk() -{ - chunk_size = 16+adjacent_modules_list.size()*20; - return(chunk_size); -} - -#if UseOldChunkLoader -Adjacent_Module_Entry_Points_Chunk::Adjacent_Module_Entry_Points_Chunk (Object_Module_Data_Chunk * parent, const char * data, size_t /*size*/) -: Chunk (parent, "ADJMDLEP") -{ - int num_array_items = *((int *) data); - - data += 4; - - for (int i=0; i<num_array_items; i++) - { - Adjacent_Module am; - - am.flags = *((int *) data); - data += 4; - - am.entry_point = *((ChunkVector *) data); - data += sizeof(ChunkVector); - - am.o_name = new char [strlen(data) + 1]; - strcpy (am.o_name, data); - data += (strlen(am.o_name) + 4)&~3; - - am.object_index=-1; - - adjacent_modules_list.add_entry(am); - - } -} -#else -Adjacent_Module_Entry_Points_Chunk::Adjacent_Module_Entry_Points_Chunk (Chunk_With_Children * parent, const char * data, size_t /*size*/) -: Chunk (parent, "ADJMDLEP") -{ - int num_array_items = *((int *) data); - - data += 4; - - for (int i=0; i<num_array_items; i++) - { - Adjacent_Module am; - - am.object_index = *((int *) data); - data += 4; - - am.flags = *((int *) data); - data += 4; - - am.entry_point = *((ChunkVectorInt *) data); - data += sizeof(ChunkVectorInt); - - - adjacent_modules_list.add_entry(am); - - } - -} -#endif - -/////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("MODFLAGS",Module_Flag_Chunk) - -Module_Flag_Chunk::Module_Flag_Chunk(Object_Module_Data_Chunk* parent) -:Chunk(parent,"MODFLAGS") -{ - Flags=spare=0; -} - -Module_Flag_Chunk::Module_Flag_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"MODFLAGS") -{ - Flags=*(int*)data; - data+=4; - spare=*(int*)data; -} - -void Module_Flag_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=Flags; - data_start+=4; - *(int*)data_start=spare; - -} -/////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("MODZONE",Module_Zone_Chunk) - -Module_Zone_Chunk::Module_Zone_Chunk(Object_Module_Data_Chunk* parent) -:Chunk(parent,"MODZONE") -{ - Zone=spare=0; -} - -Module_Zone_Chunk::Module_Zone_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"MODZONE") -{ - Zone=*(int*)data; - data+=4; - spare=*(int*)data; -} - -void Module_Zone_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=Zone; - data_start+=4; - *(int*)data_start=spare; - -} - -/////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("MODACOUS",Module_Acoustics_Chunk) - -Module_Acoustics_Chunk::Module_Acoustics_Chunk(Object_Module_Data_Chunk* parent) -:Chunk(parent,"MODACOUS") -{ - env_index=-1; //negative means default environment acoustics - reverb=-1.0; - spare=0; -} - -Module_Acoustics_Chunk::Module_Acoustics_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"MODACOUS") -{ - env_index=*(int*)data; - data+=4; - reverb=*(float*)data; - data+=4; - spare=*(int*)data; -} - -void Module_Acoustics_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=env_index; - data_start+=4; - *(float*)data_start=reverb; - data_start+=4; - *(int*)data_start=spare; - -} - - -/////////////////////////////////////// - - -RIF_IMPLEMENT_DYNCREATE("OBJTRAK2",Object_Track_Chunk2) - -Object_Track_Chunk2::Object_Track_Chunk2(Object_Chunk * parent) -: Chunk (parent, "OBJTRAK2") -{ - num_sections=0; - sections=0; - flags=timer_start=0; -} - -Object_Track_Chunk2::~Object_Track_Chunk2() -{ - if(sections) delete sections; -} - -void Object_Track_Chunk2::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=num_sections; - data_start+=4; - - for(int i=0;i<num_sections;i++) - { - *(ChunkTrackSection*)data_start=sections[i]; - data_start+=sizeof(ChunkTrackSection); - } - - *(int*)data_start=flags; - data_start+=4; - - *(int*)data_start=timer_start; - - - -} - -size_t Object_Track_Chunk2::size_chunk () -{ - chunk_size = 12 + 12 +num_sections*sizeof(ChunkTrackSection) ; - return(chunk_size); -} - -#if UseOldChunkLoader -Object_Track_Chunk2::Object_Track_Chunk2 (Chunk_With_Children * parent,const char * data, size_t /*size*/) -: Chunk (parent, "OBJTRAK2") -{ - num_sections=*(int*)data; - data+=4; - - if(num_sections) - sections=new ChunkTrackSection[num_sections]; - else - sections=0; - - for(int i=0;i<num_sections;i++) - { - sections[i].quat_start.w=(*(int*)data)/65536.0; - data+=4; - sections[i].quat_start.x=(*(int*)data)/-65536.0; - data+=4; - sections[i].quat_start.y=(*(int*)data)/-65536.0; - data+=4; - sections[i].quat_start.z=(*(int*)data)/-65536.0; - data+=4; - - sections[i].quat_end.w=(*(int*)data)/65536.0; - data+=4; - sections[i].quat_end.x=(*(int*)data)/-65536.0; - data+=4; - sections[i].quat_end.y=(*(int*)data)/-65536.0; - data+=4; - sections[i].quat_end.z=(*(int*)data)/-65536.0; - data+=4; - - - sections[i].pivot_start=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - sections[i].pivot_end=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - sections[i].object_offset=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - - sections[i].time_for_section=*(int*)data; - data+=sizeof(int); - sections[i].spare=*(int*)data; - data+=sizeof(int); - - - } - - flags=*(int*)data; - flags|=TrackFlag_QuatProblemSorted; - data+=4; - spare2=*(int*)timer_start; - - -} -#else -Object_Track_Chunk2::Object_Track_Chunk2 (Chunk_With_Children * parent,const char * data, size_t /*size*/) -: Chunk (parent, "OBJTRAK2") -{ - num_sections=*(int*)data; - data+=4; - - if(num_sections) - sections=new ChunkTrackSection[num_sections]; - else - sections=0; - - for(int i=0;i<num_sections;i++) - { - sections[i]=*(ChunkTrackSection*)data; - data+=sizeof(ChunkTrackSection); - } - - flags=*(int*)data; - data+=4; - timer_start=*(int*)data; - - if(!(flags & TrackFlag_QuatProblemSorted)) - { - for(i=0;i<num_sections;i++) - { - ChunkQuat temp=sections[i].quat_start; - sections[i].quat_start.x=-temp.w; - sections[i].quat_start.y=temp.x; - sections[i].quat_start.z=temp.y; - sections[i].quat_start.w=-temp.z; - - temp=sections[i].quat_end; - sections[i].quat_end.x=-temp.w; - sections[i].quat_end.y=temp.x; - sections[i].quat_end.z=temp.y; - sections[i].quat_end.w=-temp.z; - } - flags|=TrackFlag_QuatProblemSorted; - } - -} -#endif - -/////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("TRAKSOUN",Object_Track_Sound_Chunk) - -Object_Track_Sound_Chunk::Object_Track_Sound_Chunk(Chunk_With_Children* parent) -:Chunk(parent,"TRAKSOUN") -{ - wav_name=0; - inner_range=5000; - outer_range=40000; - max_volume=127; - pitch=0; - flags=0; - index=0; -} - -Object_Track_Sound_Chunk::Object_Track_Sound_Chunk(Chunk_With_Children* const parent,const char* data,size_t const ) -:Chunk(parent,"TRAKSOUN") -{ - inner_range=*(unsigned long*)data; - data+=4; - outer_range=*(unsigned long*)data; - data+=4; - - max_volume=*(int*)data; - data+=4; - pitch=*(int*)data; - data+=4; - flags=*(int*)data; - data+=4; - index=*(int*)data; - data+=4; - - wav_name=new char[strlen(data)+1]; - strcpy(wav_name,data); - -} - -Object_Track_Sound_Chunk::~Object_Track_Sound_Chunk() -{ - if(wav_name) delete wav_name; -} - -void Object_Track_Sound_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(unsigned long*)data_start=inner_range; - data_start+=4; - *(unsigned long*)data_start=outer_range; - data_start+=4; - - *(int*)data_start=max_volume; - data_start+=4; - *(int*)data_start=pitch; - data_start+=4; - *(int*)data_start=flags; - data_start+=4; - *(int*)data_start=index; - data_start+=4; - - strcpy(data_start,wav_name); - -} - -size_t Object_Track_Sound_Chunk::size_chunk() -{ - chunk_size=12+24; - chunk_size+=(strlen(wav_name)+4)&~3; - return chunk_size; -} -/////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("ALTLOCAT",Object_Alternate_Locations_Chunk) - -Object_Alternate_Locations_Chunk::Object_Alternate_Locations_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"ALTLOCAT") -{ - group=*(int*) data; - data+=4; - spare2=*(int*) data; - data+=4; - - num_locations=*(int*) data; - data+=4; - - if(num_locations) - locations=new AltObjectLocation[num_locations]; - else - locations=0; - - for(int i=0;i<num_locations;i++) - { - locations[i] = *(AltObjectLocation*) data; - data+=sizeof(AltObjectLocation); - } -} - -Object_Alternate_Locations_Chunk::Object_Alternate_Locations_Chunk(Chunk_With_Children* parent) -:Chunk(parent,"ALTLOCAT") -{ - num_locations=0; - locations=0; - group=spare2=0; -} - -Object_Alternate_Locations_Chunk::~Object_Alternate_Locations_Chunk() -{ - if(locations) delete [] locations; -} - -void Object_Alternate_Locations_Chunk::fill_data_block(char* data) -{ - strncpy (data, identifier, 8); - data += 8; - *((int *) data) = chunk_size; - data += 4; - - *(int*)data=group; - data+=4; - - *(int*)data=spare2; - data+=4; - - - *(int*) data = num_locations; - data+=4; - - for(int i=0;i<num_locations;i++) - { - *(AltObjectLocation*)data=locations[i]; - data+=sizeof(AltObjectLocation); - } - -} - -size_t Object_Alternate_Locations_Chunk::size_chunk() -{ - chunk_size=24+num_locations*sizeof(AltObjectLocation); - return chunk_size; -} - - -///////////////////////////////////////// -//class Object_Project_Data_Chunk - -RIF_IMPLEMENT_DYNCREATE("OBJPRJDT",Object_Project_Data_Chunk) - -CHUNK_WITH_CHILDREN_LOADER("OBJPRJDT",Object_Project_Data_Chunk) - -/* -Children for Object_Project_Data_Chunk : - -"MAPBLOCK" Map_Block_Chunk -"STRATEGY" Strategy_Chunk -"AVPSTRAT" AVP_Strategy_Chunk -*/ diff --git a/3dc/win95/OBCHUNK.HPP b/3dc/win95/OBCHUNK.HPP deleted file mode 100644 index b4780b3..0000000 --- a/3dc/win95/OBCHUNK.HPP +++ /dev/null @@ -1,503 +0,0 @@ -#ifndef _obchunk_hpp -#define _obchunk_hpp 1 - -#include "chunk.hpp" - -#include "chnktype.hpp" -#include "mishchnk.hpp" - - -// object flags - -#define OBJECT_FLAG_BASE_OBJECT 0x0000100 -#define OBJECT_FLAG_MODULE_OBJECT 0x0000200 -#define OBJECT_FLAG_PLACED_OBJECT 0x0000400 - -// Note these flags have to correspond with the ones used by ed_ob_type -// and AVP generator flags - -#define OBJECT_FLAG_AVPGAMEMODEMARINE 0x00000800 -#define OBJECT_FLAG_AVPGAMEMODEALIEN 0x00001000 -#define OBJECT_FLAG_AVPGAMEMODEPREDATOR 0x00002000 - -#define OBJECT_FLAG_PLATFORMLOADSET 0x00004000 -#define OBJECT_FLAG_PCLOAD 0x00008000 -#define OBJECT_FLAG_PSXLOAD 0x00010000 -#define OBJECT_FLAG_SATURNLOAD 0x00020000 - -#define OBJECT_FLAG_NOTDIFFICULTY1 0x00100000 -#define OBJECT_FLAG_NOTDIFFICULTY2 0x00200000 -#define OBJECT_FLAG_NOTDIFFICULTY3 0x00400000 - - -class Shape_Chunk; -class Shape_Header_Chunk; -class Object_Header_Chunk; - -// flags structure - -struct object_flags -{ - unsigned int locked : 1; -// add more flags here as they are needed -}; - - -class VModule_Array_Chunk; - -class Object_Chunk : public Lockable_Chunk_With_Children -{ -public: - - // constructor from buffer - Object_Chunk (Chunk_With_Children * parent,const char *, size_t); - - // constructor from data - - Object_Chunk (Chunk_With_Children * parent, ChunkObject &obj); - - // destructor - virtual ~Object_Chunk(); - - const ChunkObject object_data; - - Shape_Chunk * get_assoc_shape(); - - BOOL assoc_with_shape (Shape_Chunk *); - - BOOL deassoc_with_shape (Shape_Chunk *); - - Object_Header_Chunk * get_header(); - - BOOL inc_v_no(); - - BOOL same_and_updated(Object_Chunk &); - - BOOL assoc_with_shape_no(File_Chunk *); - - void update_my_chunkobject (ChunkObject &); - - // functions for the locking functionality - - BOOL file_equals (HANDLE &); - const char * get_head_id(); - void set_lock_user(char *); - - virtual void post_input_processing(); - - VModule_Array_Chunk * get_vmod_chunk(); - - // destroy object needs to go through all the other - // objects and delete itself from the VMAC - - void destroy(File_Chunk *); - - ObjectID CalculateID(); - - //program_object_index can be set by the program using the chunks , so you can find where - //the object has been put. - //I need it so that I can find out which module each object has been put into. - int program_object_index; - -private: - - friend class File_Chunk; - friend class Object_Header_Chunk; - - ChunkObject * object_data_store; - -}; - -/////////////////////////////////////////////// - -class Object_Header_Chunk : public Chunk -{ -public: - // constructor from buffer - Object_Header_Chunk (Chunk_With_Children * parent, const char * pdata, size_t psize); - virtual size_t size_chunk (); - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - const ChunkObject * const object_data; - - virtual void prepare_for_output(); - - const char * get_lockuser() - { - return lock_user; - } - - int flags; - -private: - - friend class Object_Chunk; - friend class Shape_Header_Chunk; - friend class RIF_File_Chunk; - friend class File_Chunk; - - friend class Environment; - - char lock_user[17]; - int version_no; - - int shape_id_no; - - Shape_Chunk * associated_shape; - - - - // constructor from data - Object_Header_Chunk (Object_Chunk * parent); - -}; - - -/////////////////////////////////////////////// - - -// automatically constructed when Object_Chunks are constructed from -// data - -class Object_Interface_Data_Chunk : public Chunk_With_Children -{ -public: - // constructor from buffer - Object_Interface_Data_Chunk (Chunk_With_Children * parent,const char *, size_t); -private: - - friend class Object_Chunk; - - - - // constructor from Object_Chunks - Object_Interface_Data_Chunk (Object_Chunk * parent); - -}; - -/////////////////////////////////////////////// - -class Object_Notes_Chunk : public Chunk -{ -public: - - Object_Notes_Chunk (Chunk_With_Children * parent, - const char * _data, size_t _data_size); - - - virtual ~Object_Notes_Chunk (); - - virtual size_t size_chunk () - { - chunk_size = (data_size + 12); - chunk_size += (4-chunk_size%4)%4; - return chunk_size; - } - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - const size_t data_size; - const char * const data; - -private: - - char * data_store; - -}; - -/////////////////////////////////////////////// - -class Object_Module_Data_Chunk : public Chunk_With_Children -{ -public: - - // constructor from Object_Chunks - Object_Module_Data_Chunk (Object_Chunk * parent) - : Chunk_With_Children (parent, "MODULEDT") - {} - // constructor from buffer - Object_Module_Data_Chunk (Chunk_With_Children * parent,const char *, size_t); - -private: - - friend class Object_Chunk; - friend class AI_Module_Master_Chunk; - friend class AI_Module_Slave_Chunk; - // constructor from buffer - Object_Module_Data_Chunk (Object_Chunk * parent,const char *, size_t); - -}; - -/////////////////////////////////////////////// - -class VModule_Array_Chunk : public Chunk -{ -public: - - VModule_Array_Chunk (Object_Module_Data_Chunk * parent, VMod_Arr_Item * vma, int num_in_vma); - VModule_Array_Chunk (Chunk_With_Children* parent, const char * vmdata, size_t vmsize); - ~VModule_Array_Chunk (); - - int num_array_items; - - VMod_Arr_Item * vmod_array; - - virtual void fill_data_block (char *); - virtual size_t size_chunk (); - -private: - - friend class Object_Module_Data_Chunk; - - -}; - - -/////////////////////////////////////////////// - -#if 0 -class Adjacent_Modules_Chunk : public Chunk -{ -public: - - Adjacent_Modules_Chunk(Object_Module_Data_Chunk * parent, List<Adjacent_Module> aml) - : Chunk (parent, "ADJMDLST"), adjacent_modules_list (aml) - {} - - List<Adjacent_Module> adjacent_modules_list; - - virtual void fill_data_block (char *); - virtual size_t size_chunk (); - - -private: - - friend class Object_Module_Data_Chunk; - - Adjacent_Modules_Chunk(Object_Module_Data_Chunk * parent, const char * data, size_t size); - -}; -#endif - -//a replacement for adjacent_modules_chunk -#define AdjacentModuleFlag_EntryPointSetByHand 0x00000001 -#define AdjacentModuleFlag_InsideAdjacentModule 0x00000002 -#define AdjacentModuleFlag_AdjacentModuleInsideMe 0x00000004 -#define AdjacentModuleFlag_Vertical 0x00000008 - -class Adjacent_Module_Entry_Points_Chunk : public Chunk -{ -public: - - Adjacent_Module_Entry_Points_Chunk(Object_Module_Data_Chunk * parent, List<Adjacent_Module> aml) - : Chunk (parent, "ADJMDLEP"), adjacent_modules_list (aml) - {} - Adjacent_Module_Entry_Points_Chunk(Chunk_With_Children * parent, const char * data, size_t size); - List<Adjacent_Module> adjacent_modules_list; - - virtual void fill_data_block (char *); - virtual size_t size_chunk (); - - -private: - - friend class Object_Module_Data_Chunk; - - - -}; - - -/////////////////////////////////////////////// - -class Module_Flag_Chunk : public Chunk -{ -public: - Module_Flag_Chunk(Object_Module_Data_Chunk * parent); - Module_Flag_Chunk(Chunk_With_Children* parent, const char * data, size_t ); - - virtual void fill_data_block(char*); - virtual size_t size_chunk() - {return chunk_size=20;} - - int Flags; - int spare; -private: - friend class Object_Module_Data_Chunk; - - - -}; -/////////////////////////////////////////////// - -class Module_Zone_Chunk : public Chunk -{ -public: - Module_Zone_Chunk(Object_Module_Data_Chunk * parent); - Module_Zone_Chunk(Chunk_With_Children* parent, const char * data, size_t ); - - virtual void fill_data_block(char*); - virtual size_t size_chunk() - {return chunk_size=20;} - - int Zone; - int spare; -private: - friend class Object_Module_Data_Chunk; -}; - - -/////////////////////////////////////////////// -class Module_Acoustics_Chunk : public Chunk -{ -public: - Module_Acoustics_Chunk(Object_Module_Data_Chunk * parent); - Module_Acoustics_Chunk(Chunk_With_Children* parent, const char * data, size_t ); - - virtual void fill_data_block(char*); - virtual size_t size_chunk() - {return chunk_size=24;} - - int env_index; - float reverb; - int spare; -private: - friend class Object_Module_Data_Chunk; - - - -}; -/////////////////////////////////////////////// - -class Object_Project_Data_Chunk : public Chunk_With_Children -{ -public: - - // constructor from Object_Chunks - Object_Project_Data_Chunk (Object_Chunk * parent) - : Chunk_With_Children (parent, "OBJPRJDT") - {} - // constructor from buffer - Object_Project_Data_Chunk (Chunk_With_Children * const parent,const char *,const size_t); -private: - - friend class Object_Chunk; - - - -}; - - - -/////////////////////////////////////////////// - - - -struct ChunkTrackSection -{ - - ChunkQuat quat_start; - ChunkQuat quat_end; - - ChunkVectorInt pivot_start; - ChunkVectorInt pivot_end; - - ChunkVectorInt object_offset; - - int time_for_section; - - int spare; - - -}; - -#define TrackFlag_Loop 0x00000001 -#define TrackFlag_PlayingAtStart 0x00000002 -#define TrackFlag_LoopBackAndForth 0x00000004 -#define TrackFlag_UseTrackSmoothing 0x00000008 -#define TrackFlag_QuatProblemSorted 0x80000000 - -class Object_Track_Chunk2 : public Chunk -{ -public: - - Object_Track_Chunk2 (Object_Chunk * parent); - Object_Track_Chunk2 (Chunk_With_Children * parent,const char *, size_t); - - ~Object_Track_Chunk2(); - - int num_sections; - ChunkTrackSection * sections; - - int flags; - int timer_start; - - virtual void fill_data_block (char *); - virtual size_t size_chunk (); - -private: - - friend class Object_Chunk; - - -}; - -#define TrackSoundFlag_Loop 0x00000001 -class Object_Track_Sound_Chunk : public Chunk -{ - public : - - Object_Track_Sound_Chunk(Chunk_With_Children* parent); - Object_Track_Sound_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - ~Object_Track_Sound_Chunk(); - - size_t size_chunk (); - void fill_data_block (char * data_start); - - char* wav_name; - unsigned long inner_range; - unsigned long outer_range; - int max_volume; - int pitch; - int flags; - int index; - -}; - -/////////////////////////////////////////////// - - -struct AltObjectLocation -{ - ChunkVectorInt position; - ChunkQuat orientation; - int spare1,spare2; -}; - - -//chunk for storing list of possible alternate locations for an object -//use for placed objects and generators and possibly sounds -class Object_Alternate_Locations_Chunk : public Chunk -{ -public : - Object_Alternate_Locations_Chunk(Chunk_With_Children* parent,const char* data, size_t); - Object_Alternate_Locations_Chunk(Chunk_With_Children* parent); - ~Object_Alternate_Locations_Chunk(); - - void fill_data_block(char* data); - size_t size_chunk(); - - int num_locations; - AltObjectLocation* locations; - - int group; //objects with the same group (other than 0) share the same die roll - - int spare2; -}; - -#endif
\ No newline at end of file diff --git a/3dc/win95/OEChunk.cpp b/3dc/win95/OEChunk.cpp deleted file mode 100644 index 86f3d87..0000000 --- a/3dc/win95/OEChunk.cpp +++ /dev/null @@ -1,167 +0,0 @@ -#if objedit -#include "Template.hpp" -#endif - -#include "OEChunk.h" -#include "Chunk.hpp" - -#ifdef cencon -#define new my_new -#endif -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(oechunk) - -extern Chunk *Parent_File; - -RIF_IMPLEMENT_DYNCREATE("MAPBLOCK",Map_Block_Chunk) - -Map_Block_Chunk::Map_Block_Chunk(Chunk_With_Children * parent,const char* data,size_t) - :Chunk(parent,"MAPBLOCK") -{ - strncpy(map_data.TemplateName,data,20); - strncpy(map_data.TemplateNotes,data+20,100); - map_data.MapType=*((int*)(data+120)); - map_data.MapShape=*((int*)(data+124)); - map_data.MapFlags=*((int*)(data+128)); - map_data.MapFlags2=*((int*)(data+132)); - map_data.MapFlags3=*((int*)(data+136)); - map_data.MapCType=*((int*)(data+140)); - map_data.MapCGameType=*((int*)(data+144)); - map_data.MapCStrategyS=*((int*)(data+148)); - map_data.MapCStrategyL=*((int*)(data+152)); - map_data.MapInteriorType=*((int*)(data+126)); - map_data.MapLightType=*((int*)(data+160)); - map_data.MapMass=*((int*)(data+164)); - map_data.MapNewtonV.vx=*((int*)(data+168)); - map_data.MapNewtonV.vy=*((int*)(data+172)); - map_data.MapNewtonV.vz=*((int*)(data+176)); - map_data.MapOrigin.vx=*((int*)(data+180)); - map_data.MapOrigin.vy=*((int*)(data+184)); - map_data.MapOrigin.vz=*((int*)(data+188)); - map_data.MapViewType=*((int*)(data+192)); - map_data.MapVDBData=*((int*)(data+196)); - map_data.SimShapeList=*((int*)(data+200)); -} - -RIF_IMPLEMENT_DYNCREATE("STRATEGY",Strategy_Chunk) - -Strategy_Chunk::Strategy_Chunk(Chunk_With_Children * parent,const char * data,size_t) - :Chunk(parent,"STRATEGY") -{ - strncpy(strategy_data.StrategyName,data,20); - strncpy(strategy_data.StrategyNotes,data+20,100); - strategy_data.Strategy=*((int*)(data+120)); -} - -void Map_Block_Chunk::fill_data_block (char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - strncpy (data_start,map_data.TemplateName,20); - data_start+=20; - strncpy (data_start,map_data.TemplateNotes,100); - data_start+=100; - - *((int*)data_start)=map_data.MapType; - data_start += 4; - - *((int*)data_start)=map_data.MapShape; - data_start += 4; - *((int*)data_start)=map_data.MapFlags; - data_start += 4; - *((int*)data_start)=map_data.MapFlags2; - data_start += 4; - *((int*)data_start)=map_data.MapFlags3; - data_start += 4; - *((int*)data_start)=map_data.MapCType; - data_start += 4; - *((int*)data_start)=map_data.MapCGameType; - data_start += 4; - *((int*)data_start)=map_data.MapCStrategyS; - data_start+=4; - *((int*)data_start)=map_data.MapCStrategyL;; - data_start+=4; - *((int*)data_start)=map_data.MapInteriorType; - data_start+=4; - *((int*)data_start)=map_data.MapLightType; - data_start+=4; - *((int*)data_start)=map_data.MapMass; - data_start+=4; - *((int*)data_start)=map_data.MapNewtonV.vx; - data_start+=4; - *((int*)data_start)=map_data.MapNewtonV.vy; - data_start+=4; - *((int*)data_start)=map_data.MapNewtonV.vz; - data_start+=4; - *((int*)data_start)=map_data.MapOrigin.vx; - data_start+=4; - *((int*)data_start)=map_data.MapOrigin.vy; - data_start+=4; - *((int*)data_start)=map_data.MapOrigin.vz; - data_start+=4; - *((int*)data_start)=map_data.MapViewType; - data_start+=4; - *((int*)data_start)=map_data.MapVDBData; - data_start+=4; - *((int*)data_start)=map_data.SimShapeList; -} - -void Strategy_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - strncpy (data_start,strategy_data.StrategyName,20); - data_start+=20; - strncpy (data_start,strategy_data.StrategyNotes,100); - data_start+=100; - - *((int*)data_start)=strategy_data.Strategy; -} - -BOOL Map_Block_Chunk::output_chunk(HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -BOOL Strategy_Chunk::output_chunk(HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - - diff --git a/3dc/win95/OEChunk.h b/3dc/win95/OEChunk.h deleted file mode 100644 index 92aa840..0000000 --- a/3dc/win95/OEChunk.h +++ /dev/null @@ -1,99 +0,0 @@ -#ifndef _oechunk_h_ -#define _oechunk_h_ 1 - -#include "Chunk.hpp" -#include "obchunk.hpp" - -#if objedit -#include "Template.hpp" -#endif -//#if engine -//#define VECTOR VECTORCH -//#endif - -#if engine -#else -struct VECTORCH -{ - int vx, vy, vz; -}; -#endif - -struct ChunkMapBlock -{ - char TemplateName[20]; - char TemplateNotes[100]; - int MapType; - int MapShape; - int MapFlags; - int MapFlags2; - int MapFlags3; - int MapCType; - int MapCGameType; - int MapCStrategyS; - int MapCStrategyL; - int MapInteriorType; - int MapLightType; - int MapMass; - VECTORCH MapNewtonV; - VECTORCH MapOrigin; - int MapViewType; - - int MapVDBData; - int SimShapeList; - - - -}; - -class Map_Block_Chunk : public Chunk -{ -public: - virtual size_t size_chunk() - { - return (chunk_size=216); - } - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - ChunkMapBlock map_data; - friend class Object_Project_Data_Chunk; - - Map_Block_Chunk (Object_Project_Data_Chunk * parent) - :Chunk(parent,"MAPBLOCK") - {} - - //constructor from buffer - Map_Block_Chunk (Chunk_With_Children * parent,const char* data,size_t); -}; - -struct ChunkStrategy -{ - char StrategyName[20]; - char StrategyNotes[100]; - int Strategy; -}; - -class Strategy_Chunk : public Chunk -{ -public : - virtual size_t size_chunk() - { - return (chunk_size=136); - } - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - ChunkStrategy strategy_data; - friend class Object_Project_Data_Chunk; - - Strategy_Chunk(Object_Project_Data_Chunk *parent) - :Chunk(parent,"STRATEGY") - {} - - //constructor from buffer - Strategy_Chunk (Chunk_With_Children * parent,const char* data,size_t); -}; -#endif
\ No newline at end of file diff --git a/3dc/win95/OURASERT.H b/3dc/win95/OURASERT.H deleted file mode 100644 index 6ffa3de..0000000 --- a/3dc/win95/OURASERT.H +++ /dev/null @@ -1,138 +0,0 @@ - -/* - This is our assert file for the Win95 - platform, with Dave's global/local assert - distinctions. -*/ - -/* - Note that WaitForReturn now calls FlushTextprintBuffer - and FlipBuffers implicitly. -*/ - -/* - Modified 10th December 1996 by Dave Malcolm. Now can be set so that - functions are supplied by the project/platform to fire when an assertion - fires. - - Also is set so that the compiler will generate an error message if you manage to - include the file more than once (with confusing definitons of UseLocalAssert); - this can be disabled. -*/ - - -#ifdef _OURASERT - #if StopCompilationOnMultipleInclusions - #error OURASERT.H included more than once - #endif -#else - #define _OURASERT 1 -#endif - - -#ifdef AVP_DEBUG_VERSION - #define ASSERT_SYSTEM_ON 1 -#else - #define ASSERT_SYSTEM_ON 0 -#endif - - -#if UseProjPlatAssert -/* New assertions system */ - - #ifdef __cplusplus - extern "C" { - #endif - int GlobalAssertFired(char* Filename, int LineNum, char* Condition); - int LocalAssertFired(char* Filename, int LineNum, char* Condition); - void ExitFired(char* Filename, int LineNum, int ExitCode); - #ifdef __cplusplus - }; - #endif - - - #if ASSERT_SYSTEM_ON - - #define GLOBALASSERT(x) \ - (void)( (x) ? 1 : \ - ( \ - GlobalAssertFired \ - ( \ - __FILE__, \ - __LINE__, \ - #x \ - ) \ - ) \ - ) - - #if UseLocalAssert - - #define LOCALASSERT(x) \ - (void)( (x) ? 1 : \ - ( \ - LocalAssertFired \ - ( \ - __FILE__, \ - __LINE__, \ - #x \ - ) \ - ) \ - ) - - #else - - #define LOCALASSERT(ignore) - - #endif - - - #define exit(x) ExitFired(__FILE__,__LINE__,x) - - #else - - #define GLOBALASSERT(ignore) ((void)0) - - #define LOCALASSERT(ignore) ((void)0) - - #endif - - -#else -/* Old assertions system */ - - #define GlobalAssertCode 0xffff - #define LocalAssertCode 0xfffe - - - #if 0//debug - - #define GLOBALASSERT(x) \ - (void)((x) ? 1 : \ - (textprint("\nGAF " #x "\nLINE %d\nFILE'%s'\n", \ - __LINE__, __FILE__), WaitForReturn(), \ - ExitSystem(), exit(GlobalAssertCode), \ - 0)) - - #if UseLocalAssert - - #define LOCALASSERT(x) \ - (void)((x) ? 1 : \ - (textprint("\nLAF " #x "LINE %d\nFILE'%s'\n", \ - __LINE__, __FILE__), WaitForReturn(), \ - ExitSystem(), exit(LocalAssertCode), \ - 0)) - - #else - - #define LOCALASSERT(ignore) - - #endif - - #else - - #define GLOBALASSERT(ignore) - - #define LOCALASSERT(ignore) - - #endif -#endif diff --git a/3dc/win95/OUR_MEM.C b/3dc/win95/OUR_MEM.C deleted file mode 100644 index 32a81ec..0000000 --- a/3dc/win95/OUR_MEM.C +++ /dev/null @@ -1,54 +0,0 @@ -#include "3dc.h" - -#include <malloc.h> - -#define UseLocalAssert No - -#include "ourasert.h" - -#if debug -int alloc_cnt = 0; -int deall_cnt = 0; -#endif - -void *AllocMem(size_t __size); -void DeallocMem(void *__ptr); - -/* Note: Never use AllocMem directly ! */ -/* Instead use AllocateMem() which is a */ -/* macro defined in mem3dc.h that allows */ -/* for debugging info. */ - -void *AllocMem(size_t __size) -{ - GLOBALASSERT(__size>0); - #if debug - alloc_cnt++; - #endif - - return malloc(__size); -}; - -/* Note: Never use DeallocMem directly ! */ -/* Instead use DeallocateMem() which is a */ -/* macro defined in mem3dc.h that allows */ -/* for debugging info. */ - -void DeallocMem(void *__ptr) -{ - #if debug - deall_cnt++; - #endif - - if(__ptr) free(__ptr); - - #if debug - else { - - textprint("ERROR - freeing null ptr\n"); - WaitForReturn(); - - } - #endif -}; - diff --git a/3dc/win95/PENTIME.H b/3dc/win95/PENTIME.H deleted file mode 100644 index 8c66961..0000000 --- a/3dc/win95/PENTIME.H +++ /dev/null @@ -1,64 +0,0 @@ -/* pentime.h */ -extern unsigned long int rdtsc_lo(void); -extern unsigned long int rdtsc_hi(void); -extern unsigned long int rdtsc_mid(void); - -#define ProfileStart() \ -{ \ - int time = rdtsc_lo(); -#define ProfileStop(x) \ - textprint("%s %d\n",x,rdtsc_lo()-time); \ -} - -#pragma aux rdtsc_lo = \ - "db 0fh, 31h" \ - value [eax] \ - modify [edx]; - -#pragma aux rdtsc_hi = \ - "db 0fh, 31h" \ - value [edx] \ - modify [eax]; - -#pragma aux rdtsc_mid = \ - "db 0fh, 31h" \ - "shr eax, 10h" \ - "shl edx, 10h" \ - "add eax, edx" \ - value [eax] \ - modify [edx]; - -/* Test to see if we have a Pentium or not. Note that this test is reliable - * enough for a tools project (where we can put in an overide switch) but not - * for a released product. - */ -extern unsigned char Pentium(void); -#pragma aux Pentium = \ - "pushfd" \ - "pop eax" \ - "or eax, 00200000h" \ - "push eax" \ - "popfd" \ - "pushfd" \ - "pop eax" \ - "mov ecx, eax" \ - "and eax, 00200000h" \ - "cmp eax, 0" \ - "je not_Pentium" \ - "mov eax, ecx" \ - "and eax, 0ffdfffffh" \ - "push eax" \ - "popfd" \ - "pushfd" \ - "pop eax" \ - "and eax, 00200000h" \ - "cmp eax, 0" \ - "jne not_Pentium" \ - "is_Pentium: mov al, 1" \ - "jmp finish" \ - "not_Pentium: mov al, 0" \ - "finish: nop" \ - value [al] \ - modify [eax ecx] - - diff --git a/3dc/win95/RAD.H b/3dc/win95/RAD.H deleted file mode 100644 index 3fdce40..0000000 --- a/3dc/win95/RAD.H +++ /dev/null @@ -1,606 +0,0 @@ -#ifndef __RAD__ -#define __RAD__ - -#define RADCOPYRIGHT "Copyright (C) 1994-98 RAD Game Tools, Inc." - -#ifndef __RADRES__ - -// __RADDOS__ means DOS code (16 or 32 bit) -// __RAD16__ means 16 bit code (Win16) -// __RAD32__ means 32 bit code (DOS, Win386, Win32s, Mac) -// __RADWIN__ means Windows code (Win16, Win386, Win32s) -// __RADWINEXT__ means Windows 386 extender (Win386) -// __RADNT__ means Win32s code -// __RADMAC__ means Macintosh -// __RAD68K__ means 68K Macintosh -// __RADPPC__ means PowerMac - - -#if (defined(__MWERKS__) && !defined(__INTEL__)) || defined(THINK_C) || defined(powerc) || defined(macintosh) || defined(__powerc) - - #define __RADMAC__ - #if defined(powerc) || defined(__powerc) - #define __RADPPC__ - #else - #define __RAD68K__ - #endif - - #define __RAD32__ - -#else - - #ifdef __DOS__ - #define __RADDOS__ - #endif - - #ifdef __386__ - #define __RAD32__ - #endif - - #ifdef _Windows //For Borland - #ifdef __WIN32__ - #define WIN32 - #else - #define __WINDOWS__ - #endif - #endif - - #ifdef _WINDOWS //For MS - #ifndef _WIN32 - #define __WINDOWS__ - #endif - #endif - - #ifdef _WIN32 - #define __RADWIN__ - #define __RADNT__ - #define __RAD32__ - #else - #ifdef __NT__ - #define __RADWIN__ - #define __RADNT__ - #define __RAD32__ - #else - #ifdef __WINDOWS_386__ - #define __RADWIN__ - #define __RADWINEXT__ - #define __RAD32__ - #else - #ifdef __WINDOWS__ - #define __RADWIN__ - #define __RAD16__ - #else - #ifdef WIN32 - #define __RADWIN__ - #define __RADNT__ - #define __RAD32__ - #endif - #endif - #endif - #endif - #endif - -#endif - -#if (!defined(__RADDOS__) && !defined(__RADWIN__) && !defined(__RADMAC__)) - #error RAD.H did not detect your platform. Define __DOS__, __WINDOWS__, WIN32, macintosh, or powerc. -#endif - -#ifdef __RADMAC__ - - // this define is for CodeWarrior 11's stupid new libs (even though - // we don't use longlong's). - - #define __MSL_LONGLONG_SUPPORT__ - - #define RADLINK - #define RADEXPLINK - - #ifdef __CFM68K__ - #ifdef __RADINDLL__ - #define RADEXPFUNC RADDEFFUNC __declspec(export) - #else - #define RADEXPFUNC RADDEFFUNC __declspec(import) - #endif - #else - #define RADEXPFUNC RADDEFFUNC - #endif - #define RADASMLINK - -#else - - #ifdef __RADNT__ - #ifndef _WIN32 - #define _WIN32 - #endif - #ifndef WIN32 - #define WIN32 - #endif - #endif - - #ifdef __RADWIN__ - #ifdef __RAD32__ - #ifdef __RADNT__ - - #define RADLINK __stdcall - #define RADEXPLINK __stdcall - - #ifdef __RADINEXE__ - #define RADEXPFUNC RADDEFFUNC - #else - #ifndef __RADINDLL__ - #define RADEXPFUNC RADDEFFUNC __declspec(dllimport) - #ifdef __BORLANDC__ - #if __BORLANDC__<=0x460 - #undef RADEXPFUNC - #define RADEXPFUNC RADDEFFUNC - #endif - #endif - #else - #define RADEXPFUNC RADDEFFUNC __declspec(dllexport) - #endif - #endif - #else - #define RADLINK __pascal - #define RADEXPLINK __far __pascal - #define RADEXPFUNC RADDEFFUNC - #endif - #else - #define RADLINK __pascal - #define RADEXPLINK __far __pascal __export - #define RADEXPFUNC RADDEFFUNC - #endif - #else - #define RADLINK __pascal - #define RADEXPLINK __pascal - #define RADEXPFUNC RADDEFFUNC - #endif - - #define RADASMLINK __cdecl - -#endif - -#ifdef __RADWIN__ - #ifndef _WINDOWS - #define _WINDOWS - #endif -#endif - -#ifdef __cplusplus - #define RADDEFFUNC extern "C" - #define RADDEFSTART extern "C" { - #define RADDEFEND } -#else - #define RADDEFFUNC - #define RADDEFSTART - #define RADDEFEND -#endif - - -RADDEFSTART - -#define s8 signed char -#define u8 unsigned char -#define u32 unsigned long -#define s32 signed long - -#ifdef __RAD32__ - #define PTR4 - - #define u16 unsigned short - #define s16 signed short - - #ifdef __RADMAC__ - - #include <string.h> - #include <memory.h> - #include <OSUtils.h> - - #define radstrlen strlen - - #define radmemset memset - - #define radmemcmp memcmp - - #define radmemcpy(dest,source,size) BlockMoveData((Ptr)(source),(Ptr)(dest),size) - - #define radmemcpydb(dest,source,size) BlockMoveData((Ptr)(source),(Ptr)(dest),size) - - #define radstrcat strcat - - #define radstrcpy strcpy - - static u32 inline radsqr(s32 a) { return(a*a); } - - #ifdef __RAD68K__ - - #pragma parameter __D0 mult64anddiv(__D0,__D1,__D2) - u32 mult64anddiv(u32 m1,u32 m2,u32 d) ={0x4C01,0x0C01,0x4C42,0x0C01}; - // muls.l d1,d1:d0 divs.l d2,d1:d0 - - #pragma parameter radconv32a(__A0,__D0) - void radconv32a(void* p,u32 n) ={0x4A80,0x600C,0x2210,0xE059,0x4841,0xE059,0x20C1,0x5380,0x6EF2}; - // tst.l d0 bra.s @loope @loop: move.l (a0),d1 ror.w #8,d1 swap d1 ror.w #8,d1 move.l d1,(a0)+ sub.l #1,d0 bgt.s @loop @loope: - - #else - - u32 mult64anddiv(u32 m1,u32 m2,u32 d); - - void radconv32a(void* p,u32 n); - - #endif - - #else - - #ifdef __WATCOMC__ - - u32 radsqr(s32 a); - #pragma aux radsqr = "mul eax" parm [eax] modify [EDX eax]; - - u32 mult64anddiv(u32 m1,u32 m2,u32 d); - #pragma aux mult64anddiv = "mul ecx" "div ebx" parm [eax] [ecx] [ebx] modify [EDX eax]; - - s32 radabs(s32 ab); - #pragma aux radabs = "test eax,eax" "jge skip" "neg eax" "skip:" parm [eax]; - - #define radabs32 radabs - - u32 DOSOut(const char* str); - #pragma aux DOSOut = "cld" "mov ecx,0xffffffff" "xor eax,eax" "mov edx,edi" "repne scasb" "not ecx" "dec ecx" "mov ebx,1" "mov ah,0x40" "int 0x21" parm [EDI] modify [EAX EBX ECX EDX EDI] value [ecx]; - - void DOSOutNum(const char* str,u32 len); - #pragma aux DOSOutNum = "mov ah,0x40" "mov ebx,1" "int 0x21" parm [edx] [ecx] modify [eax ebx]; - - u32 ErrOut(const char* str); - #pragma aux ErrOut = "cld" "mov ecx,0xffffffff" "xor eax,eax" "mov edx,edi" "repne scasb" "not ecx" "dec ecx" "xor ebx,ebx" "mov ah,0x40" "int 0x21" parm [EDI] modify [EAX EBX ECX EDX EDI] value [ecx]; - - void ErrOutNum(const char* str,u32 len); - #pragma aux ErrOutNum = "mov ah,0x40" "xor ebx,ebx" "int 0x21" parm [edx] [ecx] modify [eax ebx]; - - void radmemset16(void* dest,u16 value,u32 size); - #pragma aux radmemset16 = "cld" "mov bx,ax" "shl eax,16" "mov ax,bx" "mov bl,cl" "shr ecx,1" "rep stosd" "mov cl,bl" "and cl,1" "rep stosw" parm [EDI] [EAX] [ECX] modify [EAX EDX EBX ECX EDI]; - - void radmemset(void* dest,u8 value,u32 size); - #pragma aux radmemset = "cld" "mov ah,al" "mov bx,ax" "shl eax,16" "mov ax,bx" "mov bl,cl" "shr ecx,2" "and bl,3" "rep stosd" "mov cl,bl" "rep stosb" parm [EDI] [AL] [ECX] modify [EAX EDX EBX ECX EDI]; - - void radmemset32(void* dest,u32 value,u32 size); - #pragma aux radmemset32 = "cld" "rep stosd" parm [EDI] [EAX] [ECX] modify [EAX EDX EBX ECX EDI]; - - void radmemcpy(void* dest,const void* source,u32 size); - #pragma aux radmemcpy = "cld" "mov bl,cl" "shr ecx,2" "rep movsd" "mov cl,bl" "and cl,3" "rep movsb" parm [EDI] [ESI] [ECX] modify [EBX ECX EDI ESI]; - - void __far *radfmemcpy(void __far* dest,const void __far* source,u32 size); - #pragma aux radfmemcpy = "cld" "push es" "push ds" "mov es,cx" "mov ds,dx" "mov ecx,eax" "shr ecx,2" "rep movsd" "mov cl,al" "and cl,3" "rep movsb" "pop ds" "pop es" parm [CX EDI] [DX ESI] [EAX] modify [ECX EDI ESI] value [CX EDI]; - - void radmemcpydb(void* dest,const void* source,u32 size); //Destination bigger - #pragma aux radmemcpydb = "std" "mov bl,cl" "lea esi,[esi+ecx-4]" "lea edi,[edi+ecx-4]" "shr ecx,2" "rep movsd" "and bl,3" "jz dne" "add esi,3" "add edi,3" "mov cl,bl" "rep movsb" "dne:" "cld" parm [EDI] [ESI] [ECX] modify [EBX ECX EDI ESI]; - - char* radstrcpy(void* dest,const void* source); - #pragma aux radstrcpy = "cld" "mov edx,edi" "lp:" "mov al,[esi]" "inc esi" "mov [edi],al" "inc edi" "cmp al,0" "jne lp" parm [EDI] [ESI] modify [EAX EDX EDI ESI] value [EDX]; - - char __far* radfstrcpy(void __far* dest,const void __far* source); - #pragma aux radfstrcpy = "cld" "push es" "push ds" "mov es,cx" "mov ds,dx" "mov edx,edi" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" "pop ds" "pop es" parm [CX EDI] [DX ESI] modify [EAX EDX EDI ESI] value [CX EDX]; - - char* radstpcpy(void* dest,const void* source); - #pragma aux radstpcpy = "cld" "lp:" "mov al,[esi]" "inc esi" "mov [edi],al" "inc edi" "cmp al,0" "jne lp" "dec edi" parm [EDI] [ESI] modify [EAX EDI ESI] value [EDI]; - - char* radstpcpyrs(void* dest,const void* source); - #pragma aux radstpcpyrs = "cld" "lp:" "mov al,[esi]" "inc esi" "mov [edi],al" "inc edi" "cmp al,0" "jne lp" "dec esi" parm [EDI] [ESI] modify [EAX EDI ESI] value [ESI]; - - u32 radstrlen(const void* dest); - #pragma aux radstrlen = "cld" "mov ecx,0xffffffff" "xor eax,eax" "repne scasb" "not ecx" "dec ecx" parm [EDI] modify [EAX ECX EDI] value [ECX]; - - char* radstrcat(void* dest,const void* source); - #pragma aux radstrcat = "cld" "mov ecx,0xffffffff" "mov edx,edi" "xor eax,eax" "repne scasb" "dec edi" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" \ - parm [EDI] [ESI] modify [EAX ECX EDI ESI] value [EDX]; - - char* radstrchr(const void* dest,char chr); - #pragma aux radstrchr = "cld" "lp:" "lodsb" "cmp al,dl" "je fnd" "cmp al,0" "jnz lp" "mov esi,1" "fnd:" "dec esi" parm [ESI] [DL] modify [EAX ESI] value [esi]; - - s8 radmemcmp(const void* s1,const void* s2,u32 len); - #pragma aux radmemcmp = "cld" "rep cmpsb" "setne al" "jbe end" "neg al" "end:" parm [EDI] [ESI] [ECX] modify [ECX EDI ESI]; - - s8 radstrcmp(const void* s1,const void* s2); - #pragma aux radstrcmp = "lp:" "mov al,[esi]" "mov ah,[edi]" "cmp al,ah" "jne set" "cmp al,0" "je set" "inc esi" "inc edi" "jmp lp" "set:" "setne al" "jbe end" "neg al" "end:" \ - parm [EDI] [ESI] modify [EAX EDI ESI]; - - s8 radstricmp(const void* s1,const void* s2); - #pragma aux radstricmp = "lp:" "mov al,[esi]" "mov ah,[edi]" "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub al,32" "c1:" "cmp ah,'a'" "jb c2" "cmp ah,'z'" "ja c2" "sub ah,32" "c2:" "cmp al,ah" "jne set" "cmp al,0" "je set" \ - "inc esi" "inc edi" "jmp lp" "set:" "setne al" "jbe end" "neg al" "end:" \ - parm [EDI] [ESI] modify [EAX EDI ESI]; - - s8 radstrnicmp(const void* s1,const void* s2,u32 len); - #pragma aux radstrnicmp = "lp:" "mov al,[esi]" "mov ah,[edi]" "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub al,32" "c1:" "cmp ah,'a'" "jb c2" "cmp ah,'z'" "ja c2" "sub ah,32" "c2:" "cmp al,ah" "jne set" "cmp al,0" "je set" \ - "dec ecx" "jz set" "inc esi" "inc edi" "jmp lp" "set:" "setne al" "jbe end" "neg al" "end:" \ - parm [EDI] [ESI] [ECX] modify [EAX ECX EDI ESI]; - - char* radstrupr(void* s1); - #pragma aux radstrupr = "mov ecx,edi" "lp:" "mov al,[edi]" "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub [edi],32" "c1:" "inc edi" "cmp al,0" "jne lp" parm [EDI] modify [EAX EDI] value [ecx]; - - char* radstrlwr(void* s1); - #pragma aux radstrlwr = "mov ecx,edi" "lp:" "mov al,[edi]" "cmp al,'A'" "jb c1" "cmp al,'Z'" "ja c1" "add [edi],32" "c1:" "inc edi" "cmp al,0" "jne lp" parm [EDI] modify [EAX EDI] value [ecx]; - - u32 radstru32(const void* dest); - #pragma aux radstru32 = "cld" "xor ecx,ecx" "xor ebx,ebx" "xor edi,edi" "lodsb" "cmp al,45" "jne skip2" "mov edi,1" "jmp skip" "lp:" "mov eax,10" "mul ecx" "lea ecx,[eax+ebx]" \ - "skip:" "lodsb" "skip2:" "cmp al,0x39" "ja dne" "cmp al,0x30" "jb dne" "mov bl,al" "sub bl,0x30" "jmp lp" "dne:" "test edi,1" "jz pos" "neg ecx" "pos:" \ - parm [ESI] modify [EAX EBX EDX EDI ESI] value [ecx]; - - u16 GetDS(); - #pragma aux GetDS = "mov ax,ds" value [ax]; - - #ifdef __RADWINEXT__ - - #define _16To32(ptr16) ((void*)(((GetSelectorBase((u16)(((u32)(ptr16))>>16))+((u16)(u32)(ptr16)))-GetSelectorBase(GetDS())))) - - #endif - - #ifndef __RADWIN__ - #define int86 int386 - #define int86x int386x - #endif - - #define u32regs x - #define u16regs w - - #else - - #define radstrcpy strcpy - #define radstrcat strcat - #define radmemcpy memcpy - #define radmemcpydb memmove - #define radmemcmp memcmp - #define radmemset memset - #define radstrlen strlen - #define radstrchr strchr - #define radtoupper toupper - #define radstru32(s) ((u32)atol(s)) - #define radstricmp _stricmp - #define radstrcmp strcmp - #define radstrupr _strupr - #define radstrlwr _strlwr - #define BreakPoint() _asm {int 3} - - #ifdef _MSC_VER - - #pragma warning( disable : 4035) - - typedef char* RADPCHAR; - - u32 __inline radsqr(u32 m) { - _asm { - mov eax,[m] - mul eax - } - } - - u32 __inline mult64anddiv(u32 m1,u32 m2, u32 d) { - _asm { - mov eax,[m1] - mov ecx,[m2] - mul ecx - mov ecx,[d] - div ecx - } - } - - s32 __inline radabs(s32 ab) { - _asm { - mov eax,[ab] - test eax,eax - jge skip - neg eax - skip: - } - } - - u8 __inline radinp(u16 p) { - _asm { - mov dx,[p] - in al,dx - } - } - - void __inline radoutp(u16 p,u8 v) { - _asm { - mov dx,[p] - mov al,[v] - out dx,al - } - } - - RADPCHAR __inline radstpcpy(char* p1, char* p2) { - _asm { - mov edx,[p1] - mov ecx,[p2] - cld - lp: - mov al,[ecx] - inc ecx - mov [edx],al - inc edx - cmp al,0 - jne lp - dec edx - mov eax,edx - } - } - - RADPCHAR __inline radstpcpyrs(char* p1, char* p2) { - _asm { - mov edx,[p1] - mov ecx,[p2] - cld - lp: - mov al,[ecx] - inc ecx - mov [edx],al - inc edx - cmp al,0 - jne lp - dec ecx - mov eax,ecx - } - } - - void __inline radmemset16(void* dest,u16 value,u32 sizeb) { - _asm { - mov edi,[dest] - mov ax,[value] - mov ecx,[sizeb] - shl eax,16 - cld - mov ax,[value] - mov bl,cl - shr ecx,1 - rep stosd - mov cl,bl - and cl,1 - rep stosw - } - } - - void __inline radmemset32(void* dest,u32 value,u32 sizeb) { - _asm { - mov edi,[dest] - mov eax,[value] - mov ecx,[sizeb] - cld - rep stosd - } - } - - #pragma warning( default : 4035) - - #endif - - #endif - - #endif - -#else - - #define PTR4 __far - - #define u16 unsigned int - #define s16 signed int - - #ifdef __WATCOMC__ - - u32 radsqr(s32 a); - #pragma aux radsqr = "shl edx,16" "mov dx,ax" "mov eax,edx" "xor edx,edx" "mul eax" "shld edx,eax,16" parm [dx ax] modify [DX ax] value [dx ax]; - - s16 radabs(s16 ab); - #pragma aux radabs = "test ax,ax" "jge skip" "neg ax" "skip:" parm [ax] value [ax]; - - s32 radabs32(s32 ab); - #pragma aux radabs32 = "test dx,dx" "jge skip" "neg dx" "neg ax" "sbb dx,0" "skip:" parm [dx ax] value [dx ax]; - - u32 DOSOut(const char far* dest); - #pragma aux DOSOut = "cld" "and edi,0xffff" "mov dx,di" "mov ecx,0xffffffff" "xor eax,eax" 0x67 "repne scasb" "not ecx" "dec ecx" "mov bx,1" "push ds" "push es" "pop ds" "mov ah,0x40" "int 0x21" "pop ds" "movzx eax,cx" "shr ecx,16" \ - parm [ES DI] modify [AX BX CX DX DI ES] value [CX AX]; - - void DOSOutNum(const char far* str,u16 len); - #pragma aux DOSOutNum = "push ds" "mov ds,cx" "mov cx,bx" "mov ah,0x40" "mov bx,1" "int 0x21" "pop ds" parm [cx dx] [bx] modify [ax bx cx]; - - u32 ErrOut(const char far* dest); - #pragma aux ErrOut = "cld" "and edi,0xffff" "mov dx,di" "mov ecx,0xffffffff" "xor eax,eax" 0x67 "repne scasb" "not ecx" "dec ecx" "xor bx,bx" "push ds" "push es" "pop ds" "mov ah,0x40" "int 0x21" "pop ds" "movzx eax,cx" "shr ecx,16" \ - parm [ES DI] modify [AX BX CX DX DI ES] value [CX AX]; - - void ErrOutNum(const char far* str,u16 len); - #pragma aux ErrOutNum = "push ds" "mov ds,cx" "mov cx,bx" "mov ah,0x40" "xor bx,bx" "int 0x21" "pop ds" parm [cx dx] [bx] modify [ax bx cx]; - - void radmemset(void far *dest,u8 value,u32 size); - #pragma aux radmemset = "cld" "and edi,0ffffh" "shl ecx,16" "mov cx,bx" "mov ah,al" "mov bx,ax" "shl eax,16" "mov ax,bx" "mov bl,cl" "shr ecx,2" 0x67 "rep stosd" "mov cl,bl" "and cl,3" "rep stosb" parm [ES DI] [AL] [CX BX]; - - void radmemset16(void far* dest,u16 value,u32 size); - #pragma aux radmemset16 = "cld" "and edi,0ffffh" "shl ecx,16" "mov cx,bx" "mov bx,ax" "shl eax,16" "mov ax,bx" "mov bl,cl" "shr ecx,1" "rep stosd" "mov cl,bl" "and cl,1" "rep stosw" parm [ES DI] [AX] [CX BX]; - - void radmemcpy(void far* dest,const void far* source,u32 size); - #pragma aux radmemcpy = "cld" "push ds" "mov ds,dx" "and esi,0ffffh" "and edi,0ffffh" "shl ecx,16" "mov cx,bx" "shr ecx,2" 0x67 "rep movsd" "mov cl,bl" "and cl,3" "rep movsb" "pop ds" parm [ES DI] [DX SI] [CX BX] modify [CX SI DI ES]; - - s8 radmemcmp(const void far* s1,const void far* s2,u32 len); - #pragma aux radmemcmp = "cld" "push ds" "mov ds,dx" "shl ecx,16" "mov cx,bx" "rep cmpsb" "setne al" "jbe end" "neg al" "end:" "pop ds" parm [ES DI] [DX SI] [CX BX] modify [CX SI DI ES]; - - char far* radstrcpy(void far* dest,const void far* source); - #pragma aux radstrcpy = "cld" "push ds" "mov ds,dx" "and esi,0xffff" "and edi,0xffff" "mov dx,di" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" "pop ds" parm [ES DI] [DX SI] modify [AX DX DI SI ES] value [es dx]; - - char far* radstpcpy(void far* dest,const void far* source); - #pragma aux radstpcpy = "cld" "push ds" "mov ds,dx" "and esi,0xffff" "and edi,0xffff" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" "dec di" "pop ds" parm [ES DI] [DX SI] modify [DI SI ES] value [es di]; - - u32 radstrlen(const void far* dest); - #pragma aux radstrlen = "cld" "and edi,0xffff" "mov ecx,0xffffffff" "xor eax,eax" 0x67 "repne scasb" "not ecx" "dec ecx" "movzx eax,cx" "shr ecx,16" parm [ES DI] modify [AX CX DI ES] value [CX AX]; - - char far* radstrcat(void far* dest,const void far* source); - #pragma aux radstrcat = "cld" "and edi,0xffff" "mov ecx,0xffffffff" "and esi,0xffff" "push ds" "mov ds,dx" "mov dx,di" "xor eax,eax" 0x67 "repne scasb" "dec edi" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" "pop ds" \ - parm [ES DI] [DX SI] modify [AX CX DI SI ES] value [es dx]; - - char far* radstrchr(const void far* dest,char chr); - #pragma aux radstrchr = "cld" "lp:" 0x26 "lodsb" "cmp al,dl" "je fnd" "cmp al,0" "jnz lp" "xor ax,ax" "mov es,ax" "mov si,1" "fnd:" "dec si" parm [ES SI] [DL] modify [AX SI ES] value [es si]; - - s8 radstricmp(const void far* s1,const void far* s2); - #pragma aux radstricmp = "and edi,0xffff" "push ds" "mov ds,dx" "and esi,0xffff" "lp:" "mov al,[esi]" "mov ah,[edi]" "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub al,32" "c1:" \ - "cmp ah,'a'" "jb c2" "cmp ah,'z'" "ja c2" "sub ah,32" "c2:" "cmp al,ah" "jne set" "cmp al,0" "je set" \ - "inc esi" "inc edi" "jmp lp" "set:" "setne al" "jbe end" "neg al" "end:" "pop ds" \ - parm [ES DI] [DX SI] modify [AX DI SI]; - - u32 radstru32(const void far* dest); - #pragma aux radstru32 = "cld" "xor ecx,ecx" "xor ebx,ebx" "xor edi,edi" 0x26 "lodsb" "cmp al,45" "jne skip2" "mov edi,1" "jmp skip" "lp:" "mov eax,10" "mul ecx" "lea ecx,[eax+ebx]" \ - "skip:" 0x26 "lodsb" "skip2:" "cmp al,0x39" "ja dne" "cmp al,0x30" "jb dne" "mov bl,al" "sub bl,0x30" "jmp lp" "dne:" "test edi,1" "jz pos" "neg ecx" "pos:" \ - "movzx eax,cx" "shr ecx,16" parm [ES SI] modify [AX BX DX DI SI] value [cx ax]; - - u32 mult64anddiv(u32 m1,u32 m2,u32 d); - #pragma aux mult64anddiv = "shl ecx,16" "mov cx,ax" "shrd eax,edx,16" "mov ax,si" "mul ecx" "shl edi,16" "mov di,bx" "div edi" "shld edx,eax,16" "and edx,0xffff" "and eax,0xffff" parm [cx ax] [dx si] [di bx] \ - modify [ax bx cx dx si di] value [dx ax]; - - #endif - -#endif - -RADDEFEND - -#define u32neg1 ((u32)(s32)-1) -#define RAD_align(var) var; u8 junk##var[4-(sizeof(var)&3)]; -#define RAD_align_after(var) u8 junk##var[4-(sizeof(var)&3)]={0}; -#define RAD_align_init(var,val) var=val; u8 junk##var[4-(sizeof(var)&3)]={0}; -#define RAD_align_array(var,num) var[num]; u8 junk##var[4-(sizeof(var)&3)]; -#define RAD_align_string(var,str) char var[]=str; u8 junk##var[4-(sizeof(var)&3)]={0}; - -RADEXPFUNC void PTR4* RADEXPLINK radmalloc(u32 numbytes); -RADEXPFUNC void RADEXPLINK radfree(void PTR4* ptr); - -#ifdef __WATCOMC__ - - char bkbhit(); - #pragma aux bkbhit = "mov ah,1" "int 0x16" "lahf" "shr eax,14" "and eax,1" "xor al,1" ; - - char bgetch(); - #pragma aux bgetch = "xor ah,ah" "int 0x16" "test al,0xff" "jnz done" "mov al,ah" "or al,0x80" "done:" modify [AX]; - - void BreakPoint(); - #pragma aux BreakPoint = "int 3"; - - u8 radinp(u16 p); - #pragma aux radinp = "in al,dx" parm [DX]; - - u8 radtoupper(u8 p); - #pragma aux radtoupper = "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub al,32" "c1:" parm [al] value [al]; - - void radoutp(u16 p,u8 v); - #pragma aux radoutp = "out dx,al" parm [DX] [AL]; - -#endif - -// for multi-processor machines - -#ifdef __RADNT__ - #define LockedIncrement(var) _asm { lock inc [var] } - #define LockedDecrement(var) _asm { lock dec [var] } -#else - #define LockedIncrement(var) _asm { inc [var] } - #define LockedDecrement(var) _asm { dec [var] } -#endif - -#endif - -#endif - diff --git a/3dc/win95/SCANDRAW.ASM b/3dc/win95/SCANDRAW.ASM deleted file mode 100644 index aca3c4b..0000000 --- a/3dc/win95/SCANDRAW.ASM +++ /dev/null @@ -1,2096 +0,0 @@ -;.586 -;.8087 -; -; Assembly scandraws - designed for Pentiums/Pentium Pros but should work ok -; on 486s and strange hybrid processors. -; -; (C) Kevin Lea 12:03:17 96/12/05 -; -; Please excuse the mess, I haven't tidied up yet. Only the inner loops are -; well coded, since these take far more runtime than initialisation routines. -; - - -SOURCE_SBITSV EQU 16 -SOURCE_SBITSU EQU 7 - -_DATA SEGMENT DWORD PUBLIC 'DATA' - - EXTRN _SCASM_Lighting:DWORD - EXTRN _SCASM_Destination:DWORD - EXTRN _SCASM_Bitmap:DWORD - EXTRN _SCASM_StartU:DWORD - EXTRN _SCASM_StartV:DWORD - EXTRN _SCASM_StartI:DWORD - EXTRN _SCASM_DeltaU:DWORD - EXTRN _SCASM_DeltaV:DWORD - EXTRN _SCASM_DeltaI:DWORD - EXTRN _SCASM_ScanLength:DWORD - EXTRN _SCASM_ShadingTableSize:DWORD - EXTRN _SCASM_TextureDeltaScan:DWORD -; EXTRN _TLT:BYTE PTR - -if 0 - EXTRN _sine:DWORD ; - EXTRN _cosine:DWORD ; these 2 in 3D engine already - EXTRN _MTRB_Bitmap:DWORD - EXTRN _MTRB_Destination:DWORD - EXTRN _MTRB_ScanOffset:DWORD - EXTRN _MTRB_Angle:DWORD; - EXTRN _MTRB_InvScale:DWORD; - EXTRN _MTRB_ScreenHeight:DWORD; equ 48 - EXTRN _MTRB_ScreenWidth:DWORD; equ (49*2+1) - EXTRN _MTRB_ScreenCentreX:DWORD; equ (MTRB_ScreenWidth/2+1) - EXTRN _MTRB_ScreenCentreY:DWORD; equ MTRB_ScreenHeight - EXTRN _MTRB_CentreU:DWORD - EXTRN _MTRB_CentreV:DWORD -endif - - align - - - FixedScale dd 65536.0 - FixedScale8 dd 8192.0 ; 2^16 / 8 - One dd 1.0 - FloatTemp dd ? - FPUCW word ? - OldFPUCW word ? - - DeltaUFrac dd ? - DeltaVFrac dd ? - DeltaIFrac dd ? - Wholesections dd ? - PixelsRemaining dd ? - UVintVfracStepVCarry dd ? - UVintVfracStepVNoCarry dd ? - UVintVfracStep equ UVintVfracStepVNoCarry - IintWithCarry dd ? - IintNoCarry dd ? - IintStep equ IintNoCarry - - StackStore dd ? - - ShadeTable equ _TextureLightingTable - - - - aspectAdjust dd (6 SHL 16) / 5 - startingU dd 0 - startingV dd 0 - dUCol dd 0 - dVCol dd 0 - dURow dd 0 - dVRow dd 0 - rowCount dd 0 - - - - - -_DATA ENDS - -_TEXT SEGMENT BYTE PUBLIC 'CODE' - ASSUME cs:_TEXT, ds:_DATA - -.586 - -if 0 -align -PUBLIC _ScanDraw_GouraudScan -PUBLIC ScanDraw_GouraudScan_ -ScanDraw_GouraudScan_: -_ScanDraw_GouraudScan: - -; calculate horizontal deltas - pushad - ; mov [StackStore],esp - - mov eax,_SCASM_ScanLength - mov ebp,eax - - and eax,7 - shr ebp,3 - - mov [PixelsRemaining],eax - mov [Wholesections],ebp ; store widths - - - ; setup initial coordinates - mov ebx,_SCASM_DeltaI ; get i 16.16 step - mov eax,ebx ; copy it - sar eax,16 ; get i int step - shl ebx,16 ; get i frac step - imul eax,_SCASM_ShadingTableSize - mov IintNoCarry,eax ; save whole step in non-i-carry slot - add eax,_SCASM_ShadingTableSize ; calculate whole step + i carry - mov IintWithCarry,eax ; save in i-carry slot - - mov esi,_SCASM_StartI - mov edx,esi - sar esi,16 - shl edx,16 - imul esi,_SCASM_ShadingTableSize - add esi,_SCASM_Lighting - - xor eax,eax - mov edi,_SCASM_Destination - - test ebp,ebp - - jz GS_EndPixels -if 1 -GS_ScanLoop: - ; 8 pixel span code - ; edi = dest dib bits at current pixel - ; esi = lighting pointer - ; edx = i fraction 0.32 - ; ebp = carry scratch - - -; mov al,[esi] -; add edx,DeltaIFrac -; sbb ebp,ebp -; add esi,[4*ebp + IintStep] -; mov [edi],al - - mov al,[esi] ;get colour to draw - - add edx,ebx ;increase intensity - sbb ebp,ebp ;check for overflow - - add esi,[4*ebp + IintStep] ;add to esi required change - add edx,ebx ;increase intensity - - sbb ebp,ebp ;check for overflow - mov [edi+0],al ;draw out pixel - - mov al,[esi] - - add esi,[4*ebp + IintStep] - add edx,ebx - - sbb ebp,ebp - mov [edi+1],al - - mov al,[esi] - - add esi,[4*ebp + IintStep] - add edx,ebx - - sbb ebp,ebp - mov [edi+2],al - - mov al,[esi] - - add esi,[4*ebp + IintStep] - add edx,ebx - - sbb ebp,ebp - mov [edi+3],al - - mov al,[esi] - - add esi,[4*ebp + IintStep] - add edx,ebx - - sbb ebp,ebp - mov [edi+4],al - - mov al,[esi] - - add esi,[4*ebp + IintStep] - add edx,ebx - - sbb ebp,ebp - mov [edi+5],al - - mov al,[esi] - - add esi,[4*ebp + IintStep] - add edx,ebx - - sbb ebp,ebp - mov [edi+6],al - - mov al,[esi] - - add esi,[4*ebp + IintStep] - mov [edi+7],al - - - lea edi,[edi+8] - dec Wholesections ; decrement span count - - jnz GS_ScanLoop ; loop back -endif - - mov eax,[PixelsRemaining] - test eax,eax - jz GS_finish -GS_EndPixels: - - mov al,[esi] ; get texture pixel - - lea edi,[edi+1] - - add edx,ebx - sbb ebp,ebp - mov [edi-1],al - - add esi,[4*ebp + IintStep] - dec [PixelsRemaining] - - jnz GS_EndPixels -GS_finish: -; mov esp, [StackStore] - popad - ret -endif - -if 1 -align -PUBLIC _ScanDraw_GouraudScan -PUBLIC ScanDraw_GouraudScan_ -ScanDraw_GouraudScan_: -_ScanDraw_GouraudScan: - -; calculate horizontal deltas - pushad - mov [StackStore],esp - - mov eax,_SCASM_ScanLength - mov ecx,eax - - ; and ecx,7 - shr eax,3 - - mov [PixelsRemaining],ecx - mov [Wholesections],eax ; store widths - - - ; setup initial coordinates - mov esp,_SCASM_DeltaI ; get i 16.16 step -; sar esp,8 ; get i frac step - - mov ebx,_SCASM_StartI -; sar ebx,8 - mov edx,ebx - sar edx,8 - and edx,0xff00h - - mov esi,_SCASM_Lighting - - mov edi,_SCASM_Destination - add edi,ecx - ; test eax,eax - neg ecx - sub eax,eax - jz GS_EndPixels -if 1 - mov ecx,eax -GS_ScanLoop: - - - mov al,[esi+edx] - mov edx,ebx - - add ebx,esp - and edx,0xff00h - - mov [edi+0],al - nop - - lea edi,[edi+8] - dec ecx ; decrement span count - - jnz GS_ScanLoop ; loop back -endif - - mov ecx,[PixelsRemaining] - test ecx,ecx - jz GS_finish -GS_EndPixels: - - - - mov al,[esi+edx] - mov edx,ebx - - sar edx,8 - add ebx,esp - - and edx,0xff00h - mov [edi+ecx],al - - inc ecx - jnz GS_EndPixels -GS_finish: - mov esp, [StackStore] - popad - ret -endif - -align -; Drawing a 2D polygon which has DeltaV=0 and is transparent -PUBLIC _ScanDraw2D_VAlignedTransparent -PUBLIC ScanDraw2D_VAlignedTransparent_ -_ScanDraw2D_VAlignedTransparent: -ScanDraw2D_VAlignedTransparent_: - - pushad - mov [StackStore],esp - mov edx,_SCASM_ScanLength - - mov esi,_SCASM_StartU ; get u 16.16 fixedpoint coordinate - mov esp,esi ; copy it - sar esi,16 ; get integer part - shl esp,16 ; get fractional part - - mov eax,_SCASM_StartV ; get v 16.16 fixedpoint coordinate - sar eax,16 ; get integer part - imul eax,_SCASM_TextureDeltaScan ; calc texture scanline address - add esi,eax ; calc texture offset - add esi,_SCASM_Bitmap ; calc address - - mov edi,_SCASM_Destination - mov ebx,_SCASM_DeltaU ; get u 16.16 step - mov ecx,ebx ; copy it - sar ebx,16 ; get u int step - shl ecx,16 ; get u frac step - - ; ebx u int delta - ; ecx u frac delta - ; esp u frac total - ; edi dest - ; esi source - ; edx pixels to draw -VAT_ScanLoop: - mov al,[esi] ; get texture pixel 0 - add esp,ecx - - adc esi,ebx - inc edi - - test al,al - jz VAT_SkipPixel - - mov [edi-1],al - VAT_SkipPixel: - - dec edx ; decrement span count - jnz VAT_ScanLoop ; loop back - - mov esp, [StackStore] - popad - ret - -; Drawing a 2D polygon which has DeltaV=0 and is opaque -align -PUBLIC ScanDraw2D_VAlignedOpaque_ -PUBLIC _ScanDraw2D_VAlignedOpaque -ScanDraw2D_VAlignedOpaque_: -_ScanDraw2D_VAlignedOpaque: - - pushad - mov [StackStore],esp - mov edx,_SCASM_ScanLength - - mov esi,_SCASM_StartU ; get u 16.16 fixedpoint coordinate - mov esp,esi ; copy it - sar esi,16 ; get integer part - shl esp,16 ; get fractional part - - mov eax,_SCASM_StartV ; get v 16.16 fixedpoint coordinate - sar eax,16 ; get integer part - imul eax,_SCASM_TextureDeltaScan ; calc texture scanline address - add esi,eax ; calc texture offset - add esi,_SCASM_Bitmap ; calc address - - mov edi,_SCASM_Destination - - mov ebx,_SCASM_DeltaU ; get u 16.16 step - mov ecx,ebx ; copy it - sar ebx,16 ; get u int step - shl ecx,16 ; get u frac step - - ; ebx u int delta - ; ecx u frac delta - ; esp u frac total - ; edi dest - ; esi source - ; edx pixels to draw -VAO_ScanLoop: - mov al,[esi] ; get texture pixel 0 - add esp,ecx - - adc esi,ebx - dec edx ; decrement span count - - mov [edi],al - lea edi,[edi+1] - - jnz VAO_ScanLoop ; loop back - - mov esp, [StackStore] - popad - ret - - -; -; 2d case with shading -; -; mov eax,_SCASM_DeltaU - ; mov bl,ah -; mov eax,_SCASM_DeltaV - ; mov cl,ah - -if 0 -align -PUBLIC ScanDraw2D_Gouraud_ -PUBLIC _ScanDraw2D_Gouraud -ScanDraw2D_Gouraud_: -_ScanDraw2D_Gouraud: - -; calculate horizontal deltas - pushad - - mov [StackStore],esp - mov eax,_SCASM_ScanLength - - mov ebp,eax - ; and eax,7 - - shr ebp,3 - mov [PixelsRemaining],eax - - mov [Wholesections],ebp ; store widths - mov eax,_SCASM_DeltaV ; C1 1 ; get v 16.16 step - - mov edx,_SCASM_DeltaU ; C2 1 ; get u 16.16 step - mov ebx,eax ; C1 2 ; copy v 16.16 step - - sar eax,16 ; C1 3 ; get v int step - mov ecx,edx ; C2 2 ; copy u 16.16 step - - shl ebx,16 ; C1 4 ; get v frac step - mov esi,_SCASM_DeltaI ; C3 1 ; get i 16.16 step - - sar edx,16 ; C2 3 ; get u int step - mov esp,esi ; C3 2 ; copy i 16.16 step - - shl ecx,16 ; C2 4 ; get u frac step - mov DeltaVFrac,ebx ; C1 5 ; store it - - imul eax,_SCASM_TextureDeltaScan ; C1 6 ; calculate texture step for v int step - - sar esp,16-8 ; C3 3 ; get i int step - mov DeltaUFrac,ecx ; C2 5 ; store it - - sar esi,8 ; C3 4 ; get i frac step - add eax,edx ; C1+C2 1 ; calculate uint + vint step - - mov DeltaIFrac,esi ; C3 5 ; store it - mov UVintVfracStepVNoCarry,eax ; C1+C2 2 ; save whole step in non-v-carry slot - - and esp,0xffffff00h ; C3 6 - add eax,_SCASM_TextureDeltaScan ; C1+C2 3 ; calculate whole step + v carry - - mov IintNoCarry,esp ; C3 7 ; save whole step in non-i-carry slot - mov edi,_SCASM_Destination - - mov UVintVfracStepVCarry,eax ; C1+C2 4 ; save in v-carry slot - add esp,256 ; C3 8 ; calculate whole step + i carry - - mov IintWithCarry,esp ; C3 9 ; save in i-carry slot - mov esp,_SCASM_StartI ; C4 1 - - mov edx,esp ; C4 2 - mov esi,_SCASM_StartU ; C5 1 ; get u 16.16 fixedpoint coordinate - - sar esp,16-8 ; C4 3 - mov ebx,esi ; C5 2 ; copy it - - sar edx,8 ; C4 4 - mov ecx,_SCASM_StartV ; C6 1 ; get v 16.16 fixedpoint coordinate - - sar esi,16 ; C5 3 ; get integer part - mov eax,[edi] ; preread destination - - shl ebx,16 ; C5 4 ; get fractional part - mov eax,ecx ; C6 2 ; copy it - - sar eax,16 ; C6 3 ; get integer part - and esp,0xffffff00h ; C4 5 - - shl ecx,16 ; C6 4 ; get fractional part shift [tears removal] - add esp,_SCASM_Lighting ; C4 6 - - imul eax,_SCASM_TextureDeltaScan ; C6 5 ; calc texture scanline address - - - add esi,eax ; C7 1 ; calc texture offset - xor eax,eax - - add esi,_SCASM_Bitmap ; C7 2 ; calc address - test ebp,ebp - - - sar ebx,16 - sar ecx,16 - - mov eax,_SCASM_DeltaU - mov bl,ah - mov eax,_SCASM_DeltaV - mov cl,ah - - mov esp,[PixelsRemaining] - add edi,esp - neg esp -; mov eax,edx -; add ch,cl - - - jmp G3D_EndPixels - jz G3D_EndPixels -if 1 -G3D_ScanLoop: - ; 8 pixel span code - ; edi = dest dib bits at current pixel - ; esi = texture pointer at current u,v - ; esp = lighting pointer - ; ebx = u fraction 0.32 - ; ecx = v fraction 0.32 - ; edx = i fraction 0.32 - ; ebp = carry scratch - -; mov al,[edi] ; preread the destination cache line - - mov al,[esi] ; get texture pixel 0 - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - add ebx,DeltaUFrac - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi],al ; store pixel 0 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 1 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+1],al ; store pixel 1 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 2 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+2],al ; store pixel 2 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 3 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+3],al ; store pixel 3 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 4 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+4],al ; store pixel 4 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 5 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+5],al ; store pixel 5 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 6 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+6],al ; store pixel 6 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 7 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - dec Wholesections ; decrement span count - - mov [edi+7],al ; store pixel 7 - lea edi,[edi+8] - - jnz G3D_ScanLoop ; loop back -endif - - mov eax,[PixelsRemaining] - test eax,eax - jz G3D_finish -G3D_EndPixels: - - add ch,cl - mov eax,edx - - sbb ebp,ebp ; get -1 if carry - mov al,[esi] - - inc esp - add bh,bl - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - mov al,[eax+_TLT] - test esp,esp - - mov [edi+esp],al - jnz G3D_EndPixels -G3D_finish: - mov esp, [StackStore] - popad - ret - -endif - - -; -; -; NEW CODE -; -; - -if 1 -align -PUBLIC ScanDraw2D_Gouraud_ -PUBLIC _ScanDraw2D_Gouraud -ScanDraw2D_Gouraud_: -_ScanDraw2D_Gouraud: - -; calculate horizontal deltas - pushad - - mov [StackStore],esp - mov eax,_SCASM_ScanLength - - mov ebp,eax - and eax,7 - - shr ebp,3 - mov [PixelsRemaining],eax - - mov [Wholesections],ebp ; store widths - mov eax,_SCASM_DeltaV ; C1 1 ; get v 16.16 step - - mov edx,_SCASM_DeltaU ; C2 1 ; get u 16.16 step - mov ebx,eax ; C1 2 ; copy v 16.16 step - - sar eax,16 ; C1 3 ; get v int step - mov ecx,edx ; C2 2 ; copy u 16.16 step - - shl ebx,16 ; C1 4 ; get v frac step - mov esi,_SCASM_DeltaI ; C3 1 ; get i 16.16 step - - sar edx,16 ; C2 3 ; get u int step - mov esp,esi ; C3 2 ; copy i 16.16 step - - shl ecx,16 ; C2 4 ; get u frac step - mov DeltaVFrac,ebx ; C1 5 ; store it - - imul eax,_SCASM_TextureDeltaScan ; C1 6 ; calculate texture step for v int step - - sar esp,16-8 ; C3 3 ; get i int step - mov DeltaUFrac,ecx ; C2 5 ; store it - - shl esi,16 ; C3 4 ; get i frac step - add eax,edx ; C1+C2 1 ; calculate uint + vint step - - mov DeltaIFrac,esi ; C3 5 ; store it - mov UVintVfracStepVNoCarry,eax ; C1+C2 2 ; save whole step in non-v-carry slot - - and esp,0xffffff00h ; C3 6 - add eax,_SCASM_TextureDeltaScan ; C1+C2 3 ; calculate whole step + v carry - - mov IintNoCarry,esp ; C3 7 ; save whole step in non-i-carry slot - mov edi,_SCASM_Destination - - mov UVintVfracStepVCarry,eax ; C1+C2 4 ; save in v-carry slot - add esp,256 ; C3 8 ; calculate whole step + i carry - - mov IintWithCarry,esp ; C3 9 ; save in i-carry slot - mov esp,_SCASM_StartI ; C4 1 - - mov edx,esp ; C4 2 - mov esi,_SCASM_StartU ; C5 1 ; get u 16.16 fixedpoint coordinate - - sar esp,16-8 ; C4 3 - mov ebx,esi ; C5 2 ; copy it - - shl edx,16 ; C4 4 - mov ecx,_SCASM_StartV ; C6 1 ; get v 16.16 fixedpoint coordinate - - sar esi,16 ; C5 3 ; get integer part - mov eax,[edi] ; preread destination - - ; shl ebx,16 ; C5 4 ; get fractional part - and ebx,0xffffh - mov eax,ecx ; C6 2 ; copy it - - sar eax,16 ; C6 3 ; get integer part - and esp,0xffffff00h ; C4 5 - -; shl ecx,16 ; C6 4 ; get fractional part shift [tears removal] - and ecx,0xffffh - add esp,_SCASM_Lighting ; C4 6 - - imul eax,_SCASM_TextureDeltaScan ; C6 5 ; calc texture scanline address - - - add esi,eax ; C7 1 ; calc texture offset - mov eax,_SCASM_DeltaU - - mov bl,ah - mov eax,_SCASM_DeltaV - - mov cl,ah - xor eax,eax - - add esi,_SCASM_Bitmap ; C7 2 ; calc address - test ebp,ebp - - ; jmp G3D_EndPixels - jz G3D_EndPixels -if 1 -G3D_ScanLoop: - ; 8 pixel span code - ; edi = dest dib bits at current pixel - ; esi = texture pointer at current u,v - ; esp = lighting pointer - ; ebx = u fraction 0.32 - ; ecx = v fraction 0.32 - ; edx = i fraction 0.32 - ; ebp = carry scratch - -; mov al,[edi] ; preread the destination cache line - - mov al,[esi] ; get texture pixel 0 - ; add ecx,DeltaVFrac;test to remove tears - add ch,cl - - sbb ebp,ebp ; get -1 if carry -; add ebx,DeltaUFrac - add bh,bl - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - ; add ecx,DeltaVFrac;test to remove tears - add ch,cl - - sbb ebp,ebp ; get -1 if carry - mov [edi],al ; store pixel 0 - -; add ebx,DeltaUFrac - add bh,bl - mov al,[esi] ; get texture pixel 1 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] -; add ecx,DeltaVFrac;test to remove tears - add ch,cl - - sbb ebp,ebp ; get -1 if carry - mov [edi+1],al ; store pixel 1 - - ; add ebx,DeltaUFrac - add bh,bl - mov al,[esi] ; get texture pixel 2 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - ; add ecx,DeltaVFrac;test to remove tears - add ch,cl - - sbb ebp,ebp ; get -1 if carry - mov [edi+2],al ; store pixel 2 - -; add ebx,DeltaUFrac - add bh,bl - mov al,[esi] ; get texture pixel 3 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] -; add ecx,DeltaVFrac;test to remove tears - add ch,cl - - sbb ebp,ebp ; get -1 if carry - mov [edi+3],al ; store pixel 3 - -; add ebx,DeltaUFrac - add bh,bl - mov al,[esi] ; get texture pixel 4 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - ; add ecx,DeltaVFrac;test to remove tears - add ch,cl - - sbb ebp,ebp ; get -1 if carry - mov [edi+4],al ; store pixel 4 - -; add ebx,DeltaUFrac - add bh,bl - mov al,[esi] ; get texture pixel 5 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - ; add ecx,DeltaVFrac;test to remove tears - add ch,cl - - sbb ebp,ebp ; get -1 if carry - mov [edi+5],al ; store pixel 5 - -; add ebx,DeltaUFrac - add bh,bl - mov al,[esi] ; get texture pixel 6 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] -; add ecx,DeltaVFrac;test to remove tears - add ch,cl - - sbb ebp,ebp ; get -1 if carry - mov [edi+6],al ; store pixel 6 - - ; add ebx,DeltaUFrac - add bh,bl - mov al,[esi] ; get texture pixel 7 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - add esp,[4*ebp + IintStep] - dec Wholesections ; decrement span count - - mov [edi+7],al ; store pixel 7 - lea edi,[edi+8] - - jnz G3D_ScanLoop ; loop back -endif - - mov eax,[PixelsRemaining] - test eax,eax - jz G3D_finish -G3D_EndPixels: - - mov eax,[esi] - add ch,cl -; add ecx,DeltaVFrac - - sbb ebp,ebp ; get -1 if carry - and eax,0xffh - - add bh,bl -; add ebx,DeltaUFrac - lea edi,[edi+1] - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov al,[esp+eax] - - mov [edi-1],al - mov eax,[PixelsRemaining] - - add esp,[4*ebp + IintStep] - dec eax -; dec [PixelsRemaining] - - mov [PixelsRemaining],eax - jnz G3D_EndPixels -G3D_finish: - mov esp, [StackStore] - popad - ret -endif -; -; -; NEW CODE -; -; - -align -PUBLIC ScanDraw2D_GouraudTransparent_ -PUBLIC _ScanDraw2D_GouraudTransparent -ScanDraw2D_GouraudTransparent_: -_ScanDraw2D_GouraudTransparent: - -; calculate horizontal deltas - pushad - mov [StackStore],esp - - mov eax,_SCASM_ScanLength - mov [PixelsRemaining],eax - - mov eax,_SCASM_DeltaV ; get v 16.16 step - mov ebx,eax ; copy it - sar eax,16 ; get v int step - shl ebx,16 ; get v frac step - mov DeltaVFrac,ebx ; store it - - imul eax,_SCASM_TextureDeltaScan ; calculate texture step for v int step - - mov ebx,_SCASM_DeltaU ; get u 16.16 step - mov ecx,ebx ; copy it - sar ebx,16 ; get u int step - shl ecx,16 ; get u frac step - - mov DeltaUFrac,ecx ; store it - add eax,ebx ; calculate uint + vint step - mov UVintVfracStepVNoCarry,eax; save whole step in non-v-carry slot - add eax,_SCASM_TextureDeltaScan ; calculate whole step + v carry - mov UVintVfracStepVCarry,eax ; save in v-carry slot - - ; setup initial coordinates - mov edx,_SCASM_DeltaI ; get i 16.16 step - mov eax,edx ; copy it - sar eax,16 ; get i int step - shl edx,16 ; get i frac step - mov DeltaIFrac,edx ; store it - imul eax,_SCASM_ShadingTableSize - mov IintNoCarry,eax ; save whole step in non-i-carry slot - add eax,_SCASM_ShadingTableSize ; calculate whole step + i carry - mov IintWithCarry,eax ; save in i-carry slot - - mov esp,_SCASM_StartI - mov edx,esp - sar esp,16 - shl edx,16 - imul esp,_SCASM_ShadingTableSize - add esp,_SCASM_Lighting - - mov esi,_SCASM_StartU ; get u 16.16 fixedpoint coordinate - mov ebx,esi ; copy it - sar esi,16 ; get integer part - shl ebx,16 ; get fractional part - - mov ecx,_SCASM_StartV ; get v 16.16 fixedpoint coordinate - mov eax,ecx ; copy it - sar eax,16 ; get integer part - shl ecx,16 ; get fractional part shift [tears removal] - imul eax,_SCASM_TextureDeltaScan ; calc texture scanline address - add esi,eax ; calc texture offset - add esi,_SCASM_Bitmap ; calc address - - -; mov eax,_SCASM_DeltaU - ; mov bl,ah -; mov eax,_SCASM_DeltaV - ; mov cl,ah - - xor eax,eax - mov edi,_SCASM_Destination - -G2DT_EndPixels: - - mov al,[esi] ; get texture pixel - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - test eax,eax - - jz G2DT_SkipPixel - - mov al,[esp+eax] ; store pixel 0 - mov [edi],al - - - G2DT_SkipPixel: - - lea edi,[edi+1] - add ebx,DeltaUFrac - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - add esp,[4*ebp + IintStep] - - dec [PixelsRemaining] - jnz G2DT_EndPixels - - mov esp, [StackStore] - popad - ret - - - - - - - -align -PUBLIC ScanDraw2D_Opaque_ -PUBLIC _ScanDraw2D_Opaque -ScanDraw2D_Opaque_: -_ScanDraw2D_Opaque: - -; calculate horizontal deltas - pushad - mov [StackStore],esp - - mov eax,_SCASM_ScanLength - mov ebp,eax - - and eax,7 - shr ebp,3 - - mov [PixelsRemaining],eax - mov [Wholesections],ebp ; store widths - - - mov eax,_SCASM_DeltaV ; get v 16.16 step - mov ebx,eax ; copy it - sar eax,16 ; get v int step - shl ebx,16 ; get v frac step - mov DeltaVFrac,ebx ; store it - ;shl eax,7 - imul eax,_SCASM_TextureDeltaScan ; calculate texture step for v int step - - mov ebx,_SCASM_DeltaU ; get u 16.16 step - mov ecx,ebx ; copy it - sar ebx,16 ; get u int step - shl ecx,16 ; get u frac step - mov DeltaUFrac,ecx ; store it - add eax,ebx ; calculate uint + vint step - mov UVintVfracStepVNoCarry,eax; save whole step in non-v-carry slot - add eax,_SCASM_TextureDeltaScan ; calculate whole step + v carry - mov UVintVfracStepVCarry,eax ; save in v-carry slot - - ; setup initial coordinates - - mov esi,_SCASM_StartU ; get u 16.16 fixedpoint coordinate - mov ebx,esi ; copy it - sar esi,16 ; get integer part - shl ebx,16 ; get fractional part - - mov ecx,_SCASM_StartV ; get v 16.16 fixedpoint coordinate - mov edx,ecx ; copy it - sar edx,16 ; get integer part - shl ecx,16 ; get fractional part - ; shl edx,7 - imul edx,_SCASM_TextureDeltaScan ; calc texture scanline address - add esi,edx ; calc texture offset - add esi,_SCASM_Bitmap ; calc address - - mov edx,DeltaUFrac ; get register copy - mov esp,DeltaVFrac - mov edi,_SCASM_Destination - - test ebp,ebp - jz O2D_EndPixels - -if 1 -O2D_ScanLoop: - ; 8 pixel span code - ; edi = dest dib bits at current pixel - ; esi = texture pointer at current u,v - ; ebx = u fraction 0.32 - ; ecx = v fraction 0.32 - ; edx = u frac step - ; ebp = v carry scratch - -; mov al,[edi] ; preread the destination cache line - - mov al,[esi] ; get texture pixel 0 - - add ecx,esp ; increment v fraction - sbb ebp,ebp ; get -1 if carry - add ebx,edx ; increment u fraction - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - mov [edi+0],al ; store pixel 0 - - add ebx,edx ; increment u fraction - mov al,[esi] ; get texture pixel 1 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - mov [edi+1],al ; store pixel 1 - - add ebx,edx ; increment u fraction - mov al,[esi] ; get texture pixel 2 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - mov [edi+2],al ; store pixel 2 - - add ebx,edx ; increment u fraction - mov al,[esi] ; get texture pixel 3 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - mov [edi+3],al ; store pixel 3 - - add ebx,edx ; increment u fraction - mov al,[esi] ; get texture pixel 4 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - mov [edi+4],al ; store pixel 4 - - add ebx,edx ; increment u fraction - mov al,[esi] ; get texture pixel 5 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - mov [edi+5],al ; store pixel 5 - - add ebx,edx ; increment u fraction - mov al,[esi] ; get texture pixel 6 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - mov [edi+6],al ; store pixel 6 - - add ebx,edx ; increment u fraction - mov al,[esi] ; get texture pixel 7 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - - mov [edi+7],al ; store pixel 7 - - - add edi,8 ; increment to next span - dec Wholesections ; decrement span count - jnz O2D_ScanLoop ; loop back -endif - - mov eax,[PixelsRemaining] - test eax,eax - jz O2D_finish -O2D_EndPixels: - - mov al,[esi] ; get texture pixel - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - add ebx,edx ; increment u fraction - - mov [edi],al ; store pixel - lea edi,[edi+1] - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - dec [PixelsRemaining] - - jnz O2D_EndPixels - - - -O2D_finish: - mov esp, [StackStore] - popad - ret - - -align -PUBLIC ScanDraw2D_Transparent_ -PUBLIC _ScanDraw2D_Transparent -ScanDraw2D_Transparent_: -_ScanDraw2D_Transparent: - -; calculate horizontal deltas - pushad - mov [StackStore],esp - - mov ebp,_SCASM_ScanLength - mov [PixelsRemaining],ebp - - mov eax,_SCASM_DeltaV ; get v 16.16 step - mov ebx,eax ; copy it - sar eax,16 ; get v int step - shl ebx,16 ; get v frac step - mov DeltaVFrac,ebx ; store it - ;shl eax,7 - imul eax,_SCASM_TextureDeltaScan ; calculate texture step for v int step - - mov ebx,_SCASM_DeltaU ; get u 16.16 step - mov ecx,ebx ; copy it - sar ebx,16 ; get u int step - shl ecx,16 ; get u frac step - mov DeltaUFrac,ecx ; store it - add eax,ebx ; calculate uint + vint step - mov UVintVfracStepVNoCarry,eax; save whole step in non-v-carry slot - add eax,_SCASM_TextureDeltaScan ; calculate whole step + v carry - mov UVintVfracStepVCarry,eax ; save in v-carry slot - - ; setup initial coordinates - - mov esi,_SCASM_StartU ; get u 16.16 fixedpoint coordinate - mov ebx,esi ; copy it - sar esi,16 ; get integer part - shl ebx,16 ; get fractional part - - mov ecx,_SCASM_StartV ; get v 16.16 fixedpoint coordinate - mov edx,ecx ; copy it - sar edx,16 ; get integer part - shl ecx,16 ; get fractional part - ; shl edx,7 - imul edx,_SCASM_TextureDeltaScan ; calc texture scanline address - add esi,edx ; calc texture offset - add esi,_SCASM_Bitmap ; calc address - - mov edx,DeltaUFrac ; get register copy - mov esp,DeltaVFrac - mov edi,_SCASM_Destination - -T2D_EndPixels: - - mov al,[esi] ; get texture pixel - add ecx,esp ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - test al,al - - jz T2D_SkipPixel - - mov [edi],al ; store pixel - T2D_SkipPixel: - - lea edi,[edi+1] - add ebx,edx ; increment u fraction - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - dec [PixelsRemaining] - - jnz T2D_EndPixels - - mov esp, [StackStore] - popad - ret - -align -PUBLIC ScanDraw2D_TransparentLit_ -PUBLIC _ScanDraw2D_TransparentLit -ScanDraw2D_TransparentLit_: -_ScanDraw2D_TransparentLit: - -; calculate horizontal deltas - pushad - mov [StackStore],esp - - mov ebp,_SCASM_ScanLength - mov [PixelsRemaining],ebp - - mov esp,_SCASM_StartI - imul esp,_SCASM_ShadingTableSize - add esp,_SCASM_Lighting - - mov eax,_SCASM_DeltaV ; get v 16.16 step - mov ebx,eax ; copy it - sar eax,16 ; get v int step - shl ebx,16 ; get v frac step - mov DeltaVFrac,ebx ; store it - ;shl eax,7 - imul eax,_SCASM_TextureDeltaScan ; calculate texture step for v int step - - mov ebx,_SCASM_DeltaU ; get u 16.16 step - mov ecx,ebx ; copy it - sar ebx,16 ; get u int step - shl ecx,16 ; get u frac step - mov DeltaUFrac,ecx ; store it - add eax,ebx ; calculate uint + vint step - mov UVintVfracStepVNoCarry,eax; save whole step in non-v-carry slot - add eax,_SCASM_TextureDeltaScan ; calculate whole step + v carry - mov UVintVfracStepVCarry,eax ; save in v-carry slot - - ; setup initial coordinates - - mov esi,_SCASM_StartU ; get u 16.16 fixedpoint coordinate - mov ebx,esi ; copy it - sar esi,16 ; get integer part - shl ebx,16 ; get fractional part - - mov ecx,_SCASM_StartV ; get v 16.16 fixedpoint coordinate - mov edx,ecx ; copy it - sar edx,16 ; get integer part - shl ecx,16 ; get fractional part - ; shl edx,7 - imul edx,_SCASM_TextureDeltaScan ; calc texture scanline address - add esi,edx ; calc texture offset - add esi,_SCASM_Bitmap ; calc address - - mov edx,DeltaUFrac ; get register copy - ; mov esp,DeltaVFrac - mov edi,_SCASM_Destination - xor eax,eax - -TL2D_EndPixels: - - mov al,[esi] ; get texture pixel - add ecx,DeltaVFrac ; increment v fraction - - sbb ebp,ebp ; get -1 if carry - test al,al - - jz TL2D_SkipPixel - - mov al,[eax+esp] - mov [edi],al ; store pixel - TL2D_SkipPixel: - - lea edi,[edi+1] - add ebx,edx ; increment u fraction - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - dec [PixelsRemaining] - - jnz TL2D_EndPixels - - mov esp, [StackStore] - popad - ret - -if 0 -PUBLIC MotionTrackerRotateBlit_ -MotionTrackerRotateBlit_: - -; calculate horizontal deltas - pushad - mov [StackStore],esp - - - mov eax,_MTRB_Angle - mov eax,[_cosine + eax * 4] - shl eax,16 - 7 - imul [_MTRB_InvScale] - shrd eax,edx,16 - mov [dUCol],eax - - - mov eax,[_MTRB_Angle] - mov eax,[_sine + eax * 4] - shl eax,16 - 7 - imul [_MTRB_InvScale] - shrd eax,edx,16 - mov [dVCol],eax - mov esp,eax -; calculate vertical deltas - - mov eax,[dVCol] - neg eax - ; imul [aspectAdjust] - ; shrd eax,edx,16 - mov [dURow],eax - - mov eax,[dUCol] -; imul [aspectAdjust] -; shrd eax,edx,16 - mov [dVRow],eax - - mov eax,_MTRB_CentreU ; put CentreU&V in 16.16 for now - shl eax,16-7 - mov [startingU],eax - mov eax,_MTRB_CentreV - shl eax,16-7 - mov [startingV],eax - - -; move up by yOrg - - mov eax,[dUCol] - imul eax,_MTRB_ScreenCentreX - sub [startingU],eax - - mov eax,[dURow] - imul eax,_MTRB_ScreenCentreY - sub [startingU],eax - - mov eax,[dVCol] - imul eax,_MTRB_ScreenCentreX - sub [startingV],eax - - mov eax,[dVRow] - imul eax,_MTRB_ScreenCentreY - sub [startingV],eax - -; fixup end of row deltas - - mov eax,[dUCol] - imul eax,_MTRB_ScreenWidth - neg eax - add eax,[dURow] - mov [dURow],eax - - - mov eax,[dVCol] - imul eax,_MTRB_ScreenWidth - neg eax - add eax,[dVRow] - mov [dVRow],eax - - - - mov esi,[_MTRB_Bitmap] - mov edi,[_MTRB_Destination] - - mov ecx,[startingU] - mov edx,[startingV] - - mov ebx,_MTRB_ScreenHeight ; initialize row count - mov ah,bl -MTRB_RowLoop: - mov ebx,_MTRB_ScreenWidth ; initialize column count - -MTRB_ColLoop: - mov ebp,edx - shr ebp,32 - 7 - shld ebp,ecx,7 - - add edx,esp - add ecx,[dUCol] - - mov al,[esi+ebp] - test al,al - jz MTRB_SkipPixel - mov [edi],al - MTRB_SkipPixel: - - lea edi,[edi+1] - - dec ebx - - jnz MTRB_ColLoop - - add ecx,[dURow] - add edx,[dVRow] - add edi,[_MTRB_ScanOffset] - - dec ah - jnz MTRB_RowLoop - - - mov esp, [StackStore] - popad - ret - -PUBLIC MotionTrackerRotateBlit8_ -PUBLIC _MotionTrackerRotateBlit8 -MotionTrackerRotateBlit8_: -_MotionTrackerRotateBlit8: - -; calculate horizontal deltas - pushad - mov [StackStore],esp - - - mov eax,_MTRB_Angle - mov eax,[_cosine + eax * 4] - shl eax,16 - 8 - imul [_MTRB_InvScale] - shrd eax,edx,16 - mov [dUCol],eax - - - mov eax,[_MTRB_Angle] - mov eax,[_sine + eax * 4] - shl eax,16 - 8 - imul [_MTRB_InvScale] - shrd eax,edx,16 - mov [dVCol],eax - mov esp,eax -; calculate vertical deltas - - mov eax,[dVCol] - neg eax - ; imul [aspectAdjust] - ; shrd eax,edx,16 - mov [dURow],eax - - mov eax,[dUCol] -; imul [aspectAdjust] -; shrd eax,edx,16 - mov [dVRow],eax - - mov eax,_MTRB_CentreU ; put CentreU&V in 16.16 for now - shl eax,16-8 - mov [startingU],eax - mov eax,_MTRB_CentreV - shl eax,16-8 - mov [startingV],eax - - -; move up by yOrg - - mov eax,[dUCol] - imul eax,_MTRB_ScreenCentreX - sub [startingU],eax - - mov eax,[dURow] - imul eax,_MTRB_ScreenCentreY - sub [startingU],eax - - mov eax,[dVCol] - imul eax,_MTRB_ScreenCentreX - sub [startingV],eax - - mov eax,[dVRow] - imul eax,_MTRB_ScreenCentreY - sub [startingV],eax - -; fixup end of row deltas - - mov eax,[dUCol] - imul eax,_MTRB_ScreenWidth - neg eax - add eax,[dURow] - mov [dURow],eax - - - mov eax,[dVCol] - imul eax,_MTRB_ScreenWidth - neg eax - add eax,[dVRow] - mov [dVRow],eax - - - - mov esi,[_MTRB_Bitmap] - mov edi,[_MTRB_Destination] - - mov ecx,[startingU] - mov edx,[startingV] - - mov ebx,_MTRB_ScreenHeight ; initialize row count - mov ah,bl -MTRB_RowLoop8: - mov ebx,_MTRB_ScreenWidth ; initialize column count - -MTRB_ColLoop8: - mov ebp,edx - shr ebp,32 - 8 - shld ebp,ecx,8 - - add edx,esp - add ecx,[dUCol] - - mov al,[esi+ebp] - test al,al - jz MTRB_SkipPixel8 - mov [edi],al - MTRB_SkipPixel8: - - lea edi,[edi+1] - - dec ebx - - jnz MTRB_ColLoop8 - - add ecx,[dURow] - add edx,[dVRow] - add edi,[_MTRB_ScanOffset] - - dec ah - jnz MTRB_RowLoop8 - - - mov esp, [StackStore] - popad - ret -endif - - - - - - -; floating point test area -if 0 - -PUBLIC ScanDrawF3D_Gouraud_ -ScanDrawF3D_Gouraud_: - -; calculate horizontal deltas - - pushad - - ; put the FPU in 32 bit mode - ; @todo move this out of here! -; fstcw [OldFPUCW] ; store copy of CW - ; mov ax,OldFPUCW ; get it in ax -; and eax,NOT 1100000000y ; 24 bit precision -; mov [FPUCW],ax ; store it -; fldcw [FPUCW] ; load the FPU - finit - ; mov [StackStore],esp - - mov eax,_SCASM_ScanLength - mov ebp,eax - - and eax,7 - shr ebp,3 - - mov [PixelsRemaining],eax - mov [Wholesections],ebp ; store widths - -if 0 - ; setup initial coordinates - mov edx,_SCASM_DeltaI ; get i 16.16 step - mov eax,edx ; copy it - sar eax,16 ; get i int step - shl edx,16 ; get i frac step - mov DeltaIFrac,edx ; store it - imul eax,_SCASM_ShadingTableSize - mov IintNoCarry,eax ; save whole step in non-i-carry slot - add eax,_SCASM_ShadingTableSize ; calculate whole step + i carry - mov IintWithCarry,eax ; save in i-carry slot - - mov esp,_SCASM_StartI - mov edx,esp - sar esp,16 - shl edx,16 - imul esp,_SCASM_ShadingTableSize - add esp,_SCASM_Lighting -endif - ;****************************************************************************************** - mov ebx,_ScanDescPtr - - ; calculate ULeft and VLeft ; FPU Stack (ZL = ZLeft) - ; st0 st1 st2 st3 st4 st5 st6 st7 - fld DWORD PTR [ebx+4] ; V/ZL - fld DWORD PTR [ebx] ; U/ZL V/ZL - fld DWORD PTR [ebx+8] ; 1/ZL U/ZL V/ZL - fld1 ; 1 1/ZL U/ZL V/ZL - fdiv st,st(1) ; ZL 1/ZL U/ZL V/ZL - fld st ; ZL ZL 1/ZL U/ZL V/ZL - fmul st,st(4) ; VL ZL 1/ZL U/ZL V/ZL - fxch st(1) ; ZL VL 1/ZL U/ZL V/ZL - fmul st,st(3) ; UL VL 1/ZL U/ZL V/ZL - - fstp st(5) ; VL 1/ZL U/ZL V/ZL UL - fstp st(5) ; 1/ZL U/ZL V/ZL UL VL - - ; calculate right side OverZ terms ; st0 st1 st2 st3 st4 st5 st6 st7 - - fadd DWORD PTR [ebx+20] ; 1/ZR U/ZL V/ZL UL VL - fxch st(1) ; U/ZL 1/ZR V/ZL UL VL - fadd DWORD PTR [ebx+12] ; U/ZR 1/ZR V/ZL UL VL - fxch st(2) ; V/ZL 1/ZR U/ZR UL VL - fadd DWORD PTR [ebx+16] ; V/ZR 1/ZR U/ZR UL VL - - ; calculate right side coords ; st0 st1 st2 st3 st4 st5 st6 st7 - - fld1 ; 1 V/ZR 1/ZR U/ZR UL VL - ; @todo overlap this guy - fdiv st,st(2) ; ZR V/ZR 1/ZR U/ZR UL VL - fld st ; ZR ZR V/ZR 1/ZR U/ZR UL VL - fmul st,st(2) ; VR ZR V/ZR 1/ZR U/ZR UL VL - fxch st(1) ; ZR VR V/ZR 1/ZR U/ZR UL VL - fmul st,st(4) ; UR VR V/ZR 1/ZR U/ZR UL VL - ;****************************************************************************************** - xor eax,eax - mov edi,_SCASM_Destination - - test ebp,ebp - jz GF3D_EndPixels - -GF3D_ScanLoop: - ; at this point the FPU contains ; st0 st1 st2 st3 st4 st5 st6 st7 - ; UR VR V/ZR 1/ZR U/ZR UL VL - - ; convert left side coords - - fld st(5) ; UL UR VR V/ZR 1/ZR U/ZR UL VL - fmul [FixedScale] ; UL16 UR VR V/ZR 1/ZR U/ZR UL VL - fistp [_SCASM_StartU] ; UR VR V/ZR 1/ZR U/ZR UL VL - - fld st(6) ; VL UR VR V/ZR 1/ZR U/ZR UL VL - fmul [FixedScale] ; VL16 UR VR V/ZR 1/ZR U/ZR UL VL - fistp [_SCASM_StartV] ; UR VR V/ZR 1/ZR U/ZR UL VL - - ; calculate deltas ; st0 st1 st2 st3 st4 st5 st6 st7 - - fsubr st(5),st ; UR VR V/ZR 1/ZR U/ZR dU VL - fxch st(1) ; VR UR V/ZR 1/ZR U/ZR dU VL - fsubr st(6),st ; VR UR V/ZR 1/ZR U/ZR dU dV - fxch st(6) ; dV UR V/ZR 1/ZR U/ZR dU VR - - fmul [FixedScale8] ; dV8 UR V/ZR 1/ZR U/ZR dU VR - fistp [_SCASM_DeltaV] ; UR V/ZR 1/ZR U/ZR dU VR - - fxch st(4) ; dU V/ZR 1/ZR U/ZR UR VR - fmul [FixedScale8] ; dU8 V/ZR 1/ZR U/ZR UR VR - fistp [_SCASM_DeltaU] ; V/ZR 1/ZR U/ZR UR VR - - ; increment terms for next span ; st0 st1 st2 st3 st4 st5 st6 st7 - ; Right terms become Left terms---->; V/ZL 1/ZL U/ZL UL VL - - mov ebx,_ScanDescPtr - fadd DWORD PTR [ebx+16] ; V/ZR 1/ZL U/ZL UL VL - fxch st(1) ; 1/ZL V/ZR U/ZL UL VL - fadd DWORD PTR [ebx+20] ; 1/ZR V/ZR U/ZL UL VL - fxch st(2) ; U/ZL V/ZR 1/ZR UL VL - fadd DWORD PTR [ebx+12] ; U/ZR V/ZR 1/ZR UL VL - fxch st(2) ; 1/ZR V/ZR U/ZR UL VL - fxch st(1) ; V/ZR 1/ZR U/ZR UL VL - - ; calculate right side coords ; st0 st1 st2 st3 st4 st5 st6 st7 - - fld1 ; 1 V/ZR 1/ZR U/ZR UL VL - fdiv st,st(2) ; ZR V/ZR 1/ZR U/ZR UL VL - - ; set up affine registers - - ; setup delta values - - mov eax,_SCASM_DeltaV ; get v 16.16 step - mov ebx,eax ; copy it - sar eax,16 ; get v int step - shl ebx,16 ; get v frac step - mov DeltaVFrac,ebx ; store it - - imul eax,_SCASM_TextureDeltaScan ; calculate texture step for v int step - - mov ebx,_SCASM_DeltaU ; get u 16.16 step - mov ecx,ebx ; copy it - sar ebx,16 ; get u int step - shl ecx,16 ; get u frac step - - mov DeltaUFrac,ecx ; store it - add eax,ebx ; calculate uint + vint step - mov UVintVfracStepVNoCarry,eax; save whole step in non-v-carry slot - add eax,_SCASM_TextureDeltaScan ; calculate whole step + v carry - mov UVintVfracStepVCarry,eax ; save in v-carry slot - - - mov esi,_SCASM_StartU ; get u 16.16 fixedpoint coordinate - mov ebx,esi ; copy it - sar esi,16 ; get integer part - shl ebx,16 ; get fractional part - - mov ecx,_SCASM_StartV ; get v 16.16 fixedpoint coordinate - mov eax,ecx ; copy it - sar eax,16 ; get integer part - shl ecx,16 ; get fractional part shift [tears removal] - imul eax,_SCASM_TextureDeltaScan ; calc texture scanline address - add esi,eax ; calc texture offset - add esi,_SCASM_Bitmap ; calc address - - - ; 8 pixel span code - ; edi = dest dib bits at current pixel - ; esi = texture pointer at current u,v - ; esp = lighting pointer - ; ebx = u fraction 0.32 - ; ecx = v fraction 0.32 - ; edx = i fraction 0.32 - ; ebp = carry scratch - -; mov al,[edi] ; preread the destination cache line - - mov al,[esi] ; get texture pixel 0 - - add ecx,DeltaVFrac;test to remove tears - sbb ebp,ebp ; get -1 if carry - add ebx,DeltaUFrac - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - -; add edx,DeltaIFrac -; sbb ebp,ebp -; mov al,[esp+eax] -; add esp,[4*ebp + IintStep] - - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi],al ; store pixel 0 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 1 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - -; add edx,DeltaIFrac -; sbb ebp,ebp -; mov al,[esp+eax] -; add esp,[4*ebp + IintStep] - - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+1],al ; store pixel 1 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 2 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - -; add edx,DeltaIFrac -; sbb ebp,ebp -; mov al,[esp+eax] -; add esp,[4*ebp + IintStep] - - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+2],al ; store pixel 2 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 3 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - -; add edx,DeltaIFrac -; sbb ebp,ebp -; mov al,[esp+eax] -; add esp,[4*ebp + IintStep] - - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+3],al ; store pixel 3 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 4 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - -; add edx,DeltaIFrac -; sbb ebp,ebp -; mov al,[esp+eax] -; add esp,[4*ebp + IintStep] - - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+4],al ; store pixel 4 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 5 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - -; add edx,DeltaIFrac -; sbb ebp,ebp -; mov al,[esp+eax] -; add esp,[4*ebp + IintStep] - - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+5],al ; store pixel 5 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 6 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - -; add edx,DeltaIFrac -; sbb ebp,ebp -; mov al,[esp+eax] -; add esp,[4*ebp + IintStep] - - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - mov [edi+6],al ; store pixel 6 - - add ebx,DeltaUFrac - mov al,[esi] ; get texture pixel 7 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - -; add edx,DeltaIFrac -; sbb ebp,ebp -; mov al,[esp+eax] -; add esp,[4*ebp + IintStep] - dec Wholesections ; decrement span count - - - mov [edi+7],al ; store pixel 7 - lea edi,[edi+8] - - - ; the fdiv is done, finish right ; st0 st1 st2 st3 st4 st5 st6 st7 - ; ZR V/ZR 1/ZR U/ZR UL VL - - fld st ; ZR ZR V/ZR 1/ZR U/ZR UL VL - fmul st,st(2) ; VR ZR V/ZR 1/ZR U/ZR UL VL - fxch st(1) ; ZR VR V/ZR 1/ZR U/ZR UL VL - fmul st,st(4) ; UR VR V/ZR 1/ZR U/ZR UL VL - - jnz GF3D_ScanLoop ; loop back - - mov eax,[PixelsRemaining] - test eax,eax - jz GF3D_finish -GF3D_EndPixels: -if 0 - mov al,[esi] ; get texture pixel - add ecx,DeltaVFrac;test to remove tears - - sbb ebp,ebp ; get -1 if carry - add ebx,DeltaUFrac - - lea edi,[edi+1] - mov al,[esp+eax] ; store pixel 0 - - adc esi,[4*ebp+UVintVfracStep] ; add in step ints & carries - add edx,DeltaIFrac - - sbb ebp,ebp - mov [edi-1],al - - add esp,[4*ebp + IintStep] - dec [PixelsRemaining] - - jnz GF3D_EndPixels -endif - -FPUReturn: - - ; busy FPU registers: ; st0 st1 st2 st3 st4 st5 st6 st7 - ; xxx xxx xxx xxx xxx xxx xxx - ffree st(0) - ffree st(1) - ffree st(2) - ffree st(3) - ffree st(4) - ffree st(5) - ffree st(6) - finit -; fldcw [OldFPUCW] ; restore the FPU - -GF3D_finish: -; mov esp, [StackStore] - popad - ret - -endif - - - - -_TEXT ENDS - -END diff --git a/3dc/win95/SHPCHUNK.CPP b/3dc/win95/SHPCHUNK.CPP deleted file mode 100644 index a494767..0000000 --- a/3dc/win95/SHPCHUNK.CPP +++ /dev/null @@ -1,3869 +0,0 @@ -#include <math.h> - -#include "chunk.hpp" -#include "chnktype.hpp" -#include "shpchunk.hpp" -#include "obchunk.hpp" - - -#if cencon || InterfaceEngine -#include "fnamefnc.hpp" -#include "zsp.hpp" -#include "bmpnames.hpp" -#include "envchunk.hpp" -#include "animchnk.hpp" -#include "chunkpal.hpp" -#include "fragchnk.hpp" -#endif - -#ifdef cencon -#define new my_new -#endif -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(shpchunk) - -RIF_IMPLEMENT_DYNCREATE("REBSHAPE",Shape_Chunk) - -int Shape_Chunk::max_id = 0; -BOOL Shape_External_File_Chunk::UpdatingExternalShape=FALSE; - -// Class Shape_Chunk functions - -/* -Children for Shape_Chunk : - -"SHPRAWVT" Shape_Vertex_Chunk -"SHPPOLYS" Shape_Polygon_Chunk -"SHPHEAD1" Shape_Header_Chunk -"SHPVNORM" Shape_Vertex_Normal_Chunk -"SHPPNORM" Shape_Polygon_Normal_Chunk -"SHPTEXFN" Shape_Texture_Filenames_Chunk -"SHPUVCRD" Shape_UV_Coord_Chunk -"SHPMRGDT" Shape_Merge_Data_Chunk -"SHPCENTR" Shape_Centre_Chunk -"SHPMORPH" Shape_Morphing_Data_Chunk -"SHPEXTFL" Shape_External_File_Chunk -"SHPPCINF" Shape_Poly_Change_Info_Chunk -"TEXTANIM" Animation_Chunk -"SHPFRAGS" Shape_Fragments_Chunk -"ANIMSEQU" Anim_Shape_Sequence_Chunk -"PNOTINBB" Poly_Not_In_Bounding_Box_Chunk -"ANSHCEN2" Anim_Shape_Centre_Chunk -"ASALTTEX" Anim_Shape_Alternate_Texturing_Chunk -"SHPPRPRO" Shape_Preprocessed_Data_Chunk -*/ - -Shape_Chunk::Shape_Chunk(Chunk_With_Children * parent, const char *data, size_t size) -: Lockable_Chunk_With_Children (parent, "REBSHAPE"), shape_data () -{ - const char * buffer_ptr = data; - - shape_data_store = (ChunkShape *) &shape_data; - - while ((data-buffer_ptr)< (signed)size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed)size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - -/*--------------------------------------------------------------------** -** N.B. all changes to shape formats should be made to the sub shapes ** -**--------------------------------------------------------------------*/ - -/*--------------------------------------------------------------------------** -** And of course the external file post input processing function should be ** -** changed so that any new chunks will be copied over ** -**--------------------------------------------------------------------------*/ - -/*----------------------------------------------------------------------------** -** Oy READ THE NOTES, also destroy_auxiliary_chunks should be changed as well ** -**----------------------------------------------------------------------------*/ - - DynCreate(data); - data += *(int *)(data + 8); - -/*--------------------------------------------------------------------** -** N.B. all changes to shape formats should be made to the sub shapes ** -**--------------------------------------------------------------------*/ - -/*--------------------------------------------------------------------------** -** And of course the external file post input processing function should be ** -** changed so that any new chunks will be copied over ** -**--------------------------------------------------------------------------*/ - -/*----------------------------------------------------------------------------** -** Oy READ THE NOTES, also destroy_auxiliary_chunks should be changed as well ** -**----------------------------------------------------------------------------*/ - - } - #if cencon || InterfaceEngine - List<Chunk*>chlist; - lookup_child("CONSHAPE",chlist); - for(LIF<Chunk*> chlif(&chlist);!chlif.done();chlif.next()) - { - ((Console_Shape_Chunk*)chlif())->generate_console_chunkshape(); - } - #endif -} - -Shape_Chunk::Shape_Chunk (Chunk_With_Children * parent, ChunkShape &shp_dat) -: Lockable_Chunk_With_Children (parent, "REBSHAPE"), shape_data (shp_dat) -{ - shape_data_store = (ChunkShape *) &shape_data; - - new Shape_Header_Chunk (this); - - if (shape_data.v_list) new Shape_Vertex_Chunk (this, shape_data.num_verts); - if (shape_data.v_normal_list) new Shape_Vertex_Normal_Chunk (this, shape_data.num_verts); - if (shape_data.p_normal_list) new Shape_Polygon_Normal_Chunk (this, shape_data.num_polys); - if (shape_data.poly_list) new Shape_Polygon_Chunk (this, shape_data.num_polys); - if (shape_data.uv_list) new Shape_UV_Coord_Chunk (this, shape_data.num_uvs); - if (shape_data.texture_fns) new Shape_Texture_Filenames_Chunk (this, shape_data.num_texfiles); - - - - //calculate the shape's centre and radius_about_centre - shape_data_store->centre=(shape_data_store->min+shape_data_store->max)/2; - shape_data_store->radius_about_centre=0; - for(int i=0;i<shape_data_store->num_verts;i++) - { - float length = (float) mod(shape_data_store->v_list[i]-shape_data_store->centre); - if(length>shape_data_store->radius_about_centre) - { - shape_data_store->radius_about_centre=length; - } - } - - //if the shape hasn't got a Shape_Centre_Chunk , create one. - - if(!lookup_single_child("SHPCENTR")) - { - new Shape_Centre_Chunk(this); - } -} - -Shape_Chunk::~Shape_Chunk () -{ -} - -Shape_Chunk* Shape_Chunk::make_copy_of_chunk() -{ - char* Data=this->make_data_block_from_chunk(); - Shape_Chunk* NewShape=new Shape_Chunk(parent,Data+12,this->size_chunk()-12); - delete [] Data; - delete NewShape->get_header(); - new Shape_Header_Chunk(NewShape); - //need to call post_input_processing in order to copy morphing data correctly - NewShape->post_input_processing(); - NewShape->updated=TRUE; - return NewShape; -} - -Shape_Header_Chunk * Shape_Chunk::get_header() -{ - - return (Shape_Header_Chunk *) this->lookup_single_child ("SHPHEAD1"); - -} - -List<Object_Chunk *> const & Shape_Chunk::list_assoc_objs() -{ - if (!get_header()) - { - static List<Object_Chunk *> empty_list; - return empty_list; - } - - return get_header()->associated_objects_store; -} - -BOOL Shape_Chunk::assoc_with_object (Object_Chunk *obch) -{ - return obch->assoc_with_shape(this); -} - -BOOL Shape_Chunk::deassoc_with_object (Object_Chunk *obch) -{ - return obch->deassoc_with_shape(this); -} - - -void Shape_Chunk::post_input_processing() -{ - if (get_header()) - if (get_header()->flags & GENERAL_FLAG_LOCKED) - external_lock = TRUE; - -#if 0 //shouldn't need to recalculate extents each time shape is loaded - // recalculate the shape extents - - ChunkVector max, min; - - max.x = -1000000000; - max.y = -1000000000; - max.z = -1000000000; - - min.x = 1000000000; - min.y = 1000000000; - min.z = 1000000000; - - float radius = 0; - - for (int i=0; i<shape_data_store->num_verts; i++) - { - max.x = max(max.x, shape_data_store->v_list[i].x); - max.y = max(max.y, shape_data_store->v_list[i].y); - max.z = max(max.z, shape_data_store->v_list[i].z); - - min.x = min(min.x, shape_data_store->v_list[i].x); - min.y = min(min.y, shape_data_store->v_list[i].y); - min.z = min(min.z, shape_data_store->v_list[i].z); - - float temp_rad =(float) mod(shape_data_store->v_list[i]); - - radius = max (radius, temp_rad); - } - - shape_data_store->max = max; - shape_data_store->min = min; - shape_data_store->radius = radius; -#endif - - - Chunk_With_Children::post_input_processing(); - -} - -void Shape_Chunk::destroy_auxiliary_chunks() -{ - //split up into different blocks to stop compiler crashing when optimizations are turned on - - List<Chunk *> chlst; - - lookup_child("SHPZSPDT",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child("SHPMRGDT",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - - lookup_child("SHPMORPH",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - - lookup_child("TEXTANIM",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - - lookup_child("SHPPCINF",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child("SHPFRAGS",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child("ANIMSEQU",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child("PNOTINBB",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child("ANSHCEN2",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child("CONSHAPE",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child("ASALTTEX",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - lookup_child("SHPPRPRO",chlst); - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - -} - - - -BOOL Shape_Chunk::file_equals(HANDLE &rif_file) -{ - unsigned long bytes_read; - int id; - Shape_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return (FALSE); - - // get header list - List<int> obhead; - list_chunks_in_file (&obhead, rif_file, "SHPHEAD1"); - - if (obhead.size() != 1) return FALSE; - - // get object identifier - SetFilePointer(rif_file,obhead.first_entry() + 32,0,FILE_BEGIN); - ReadFile (rif_file, (long *) &(id), 4, &bytes_read, 0); - - if (hdptr->file_id_num == id) return TRUE; - - return (FALSE); -} - -const char * Shape_Chunk::get_head_id() -{ - Shape_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return (0); - - return(hdptr->identifier); -} - -void Shape_Chunk::set_lock_user (char * user) -{ - Shape_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return; - - strncpy (hdptr->lock_user, user,16); - - hdptr->lock_user[16] = 0; -} - -BOOL Shape_Chunk::inc_v_no () -{ - Shape_Header_Chunk * hdptr = get_header(); - - if (!hdptr) return (FALSE); - - hdptr->version_no++; - - return (TRUE); -} - -BOOL Shape_Chunk::same_and_updated(Shape_Chunk & shp) -{ - - Shape_Header_Chunk * hd1ptr = get_header(); - - if (!hd1ptr) return (0); - - Shape_Header_Chunk * hd2ptr = shp.get_header(); - - if (!hd2ptr) return (0); - - return (hd1ptr->version_no < hd2ptr->version_no && hd1ptr->file_id_num == hd2ptr->file_id_num); - -} - -BOOL Shape_Chunk::assoc_with_object_list(File_Chunk *fc) -{ - Shape_Header_Chunk * hdptr = get_header(); - Object_Chunk * ob = NULL; - - if (!hdptr) return (FALSE); - - List<Chunk *> chlst; - fc->lookup_child("RBOBJECT",chlst); - - for (LIF<char *> n(&(hdptr->object_names_store)); !n.done(); n.next()) - { - for (LIF<Chunk *> l(&chlst); !l.done(); l.next()) - { - ob = (Object_Chunk *)l(); - if ( !strcmp(ob->object_data.o_name, n()) ) - break; - } - if (!l.done()) - assoc_with_object(ob); - else - { - return(FALSE); - } - } - return(TRUE); - - -} - -BOOL Shape_Chunk::update_my_chunkshape (ChunkShape & cshp) -{ - // Firstly lose all the chunks that were with - // the old chunk shape - List <Chunk *> chlst; - - lookup_child ("SHPRAWVT",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - lookup_child ("SHPVNORM",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child ("SHPPNORM",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child ("SHPPOLYS",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child ("SHPUVCRD",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child ("SHPTEXFN",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - *shape_data_store = cshp; - - if (shape_data.v_list) new Shape_Vertex_Chunk (this, shape_data.num_verts); - if (shape_data.v_normal_list) new Shape_Vertex_Normal_Chunk (this, shape_data.num_verts); - if (shape_data.p_normal_list) new Shape_Polygon_Normal_Chunk (this, shape_data.num_polys); - if (shape_data.poly_list) new Shape_Polygon_Chunk (this, shape_data.num_polys); - if (shape_data.uv_list) new Shape_UV_Coord_Chunk (this, shape_data.num_uvs); - if (shape_data.texture_fns) new Shape_Texture_Filenames_Chunk (this, shape_data.num_texfiles); - - - //calculate the shape's centre and radius_about_centre - shape_data_store->centre=(shape_data_store->min+shape_data_store->max)/2; - shape_data_store->radius_about_centre=0; - for(int i=0;i<shape_data_store->num_verts;i++) - { - float length = (float) mod(shape_data_store->v_list[i]-shape_data_store->centre); - if(length>shape_data_store->radius_about_centre) - { - shape_data_store->radius_about_centre=length; - } - } - - //if the shape hasn't got a Shape_Centre_Chunk , create one. - - if(!lookup_single_child("SHPCENTR")) - { - new Shape_Centre_Chunk(this); - } - - - return TRUE; -} - -Console_Shape_Chunk* Shape_Chunk::get_console_shape_data(Console_Type ct) -{ - List<Chunk*> chlist; - lookup_child("CONSHAPE",chlist); - for(LIF<Chunk*> chlif(&chlist);!chlif.done();chlif.next()) - { - Console_Shape_Chunk* csc=(Console_Shape_Chunk*)chlif(); - List<Chunk*> chlist2; - csc->lookup_child("CONSTYPE",chlist2); - if(chlist2.size()) - { - if(((Console_Type_Chunk*)chlist2.first_entry())->console==ct) - return csc; - } - } - - return 0;//no console specific shape data -} - -///////////////////////////////////////// - -// Class Shape_Vertex_Chunk functions - -// These can only be children of Shape_Chunks -// the shape chunks data will automatically be updated by it is created - -// from buffer - -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPRAWVT",Shape_Vertex_Chunk,"REBSHAPE",Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPRAWVT",Shape_Vertex_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPRAWVT",Shape_Vertex_Chunk,"ANIMFRAM",Anim_Shape_Frame_Chunk) - -Shape_Vertex_Chunk::Shape_Vertex_Chunk(Shape_Chunk * parent, const char * vtdata , size_t vtsize) -: Chunk (parent, "SHPRAWVT"), vert_data (NULL), - num_verts (vtsize / 12) // 12 bytes per vertex -{ - int i; - - parent->shape_data_store->v_list = new ChunkVectorInt[num_verts]; - parent->shape_data_store->num_verts = num_verts; - - *((ChunkVectorInt**) &vert_data) = parent->shape_data_store->v_list; - - for (i=0;i<num_verts;i++) - { - parent->shape_data_store->v_list[i] = *((ChunkVectorInt *) vtdata ); - vtdata+=sizeof(ChunkVectorInt); - } - -} - - -Shape_Vertex_Chunk::Shape_Vertex_Chunk(Shape_Sub_Shape_Chunk * parent, const char * vtdata , size_t vtsize) -: Chunk (parent, "SHPRAWVT"), vert_data (NULL), - num_verts (vtsize / 12) // 12 bytes per vertex -{ - int i; - - parent->shape_data_store->v_list = new ChunkVectorInt[num_verts]; - parent->shape_data_store->num_verts = num_verts; - - *((ChunkVectorInt**) &vert_data) = parent->shape_data_store->v_list; - - for (i=0;i<num_verts;i++) - { - parent->shape_data_store->v_list[i] = *((ChunkVectorInt *) vtdata ); - vtdata+=sizeof(ChunkVectorInt); - } - -} - - -Shape_Vertex_Chunk::Shape_Vertex_Chunk(Anim_Shape_Frame_Chunk * parent, const char * vtdata , size_t vtsize) -: Chunk (parent, "SHPRAWVT"), vert_data (NULL), - num_verts (vtsize / 12) // 12 bytes per vertex -{ - int i; - - ChunkVectorInt* v_list = new ChunkVectorInt[num_verts]; - *(ChunkVectorInt**)&vert_data=v_list; - - for (i=0;i<num_verts;i++) - { - v_list[i] = *((ChunkVectorInt *) vtdata ); - vtdata+=sizeof(ChunkVectorInt); - } - -} - -BOOL Shape_Vertex_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; - -} - -void Shape_Vertex_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - for (int i=0;i<num_verts;i++) - { - *(ChunkVectorInt *) data_start = vert_data[i]; - data_start+=sizeof(ChunkVectorInt); - - } -} - -///////////////////////////////////////// - -// Class Shape_Vertex_Normal_Chunk functions - -// These can only be children of Shape_Chunks -// the shape chunks data will automatically be updated by it is created -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPVNORM",Shape_Vertex_Normal_Chunk,"REBSHAPE",Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPVNORM",Shape_Vertex_Normal_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) - -// from buffer -Shape_Vertex_Normal_Chunk::Shape_Vertex_Normal_Chunk(Shape_Chunk * parent, const char * vtdata , size_t vtsize) -: Chunk (parent, "SHPVNORM"), vert_norm_data (NULL), - num_verts (vtsize / sizeof(ChunkVectorInt)) -{ - int i; - - parent->shape_data_store->v_normal_list = new ChunkVectorFloat[num_verts]; - *((ChunkVectorFloat**) &vert_norm_data) = parent->shape_data_store->v_normal_list; - - for (i=0;i<num_verts;i++) - { - parent->shape_data_store->v_normal_list[i] = *((ChunkVectorFloat *) vtdata); - vtdata+=sizeof(ChunkVectorFloat); - } - -} - -Shape_Vertex_Normal_Chunk::Shape_Vertex_Normal_Chunk(Shape_Sub_Shape_Chunk * parent, const char * vtdata , size_t vtsize) -: Chunk (parent, "SHPVNORM"), vert_norm_data (NULL), - num_verts (vtsize / sizeof(ChunkVectorInt)) -{ - int i; - - parent->shape_data_store->v_normal_list = new ChunkVectorFloat[num_verts]; - *((ChunkVectorFloat**) &vert_norm_data) = parent->shape_data_store->v_normal_list; - - for (i=0;i<num_verts;i++) - { - parent->shape_data_store->v_normal_list[i] = *((ChunkVectorFloat *) vtdata ); - vtdata+=sizeof(ChunkVectorFloat); - } - -} - -BOOL Shape_Vertex_Normal_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; - -} - -void Shape_Vertex_Normal_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - for (int i=0;i<num_verts;i++) - { - *((ChunkVectorFloat *) data_start ) = vert_norm_data[i]; - data_start+=sizeof(ChunkVectorFloat); - } - -} -///////////////////////////////////////// - -// Class Shape_Polygon_Normal_Chunk functions - -// These can only be children of Shape_Chunks -// the shape chunks data will automatically be updated by it is created -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPPNORM",Shape_Polygon_Normal_Chunk,"REBSHAPE",Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPPNORM",Shape_Polygon_Normal_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPPNORM",Shape_Polygon_Normal_Chunk,"ANIMFRAM",Anim_Shape_Frame_Chunk) - -// from buffer -Shape_Polygon_Normal_Chunk::Shape_Polygon_Normal_Chunk(Shape_Chunk * parent, const char * pndata , size_t pnsize) -: Chunk (parent, "SHPPNORM"), poly_norm_data (NULL), - num_polys (pnsize / sizeof(ChunkVectorFloat)) -{ - int i; - - parent->shape_data_store->p_normal_list = new ChunkVectorFloat[num_polys]; - *((ChunkVectorFloat**) &poly_norm_data) = parent->shape_data_store->p_normal_list; - - for (i=0;i<num_polys;i++) - { - parent->shape_data_store->p_normal_list[i] = *((ChunkVectorFloat *) pndata ); - pndata+=sizeof(ChunkVectorFloat); - } - -} - -Shape_Polygon_Normal_Chunk::Shape_Polygon_Normal_Chunk(Shape_Sub_Shape_Chunk * parent, const char * pndata , size_t pnsize) -: Chunk (parent, "SHPPNORM"), poly_norm_data (NULL), - num_polys (pnsize / sizeof(ChunkVectorFloat)) -{ - int i; - - parent->shape_data_store->p_normal_list = new ChunkVectorFloat[num_polys]; - *((ChunkVectorFloat**) &poly_norm_data) = parent->shape_data_store->p_normal_list; - - for (i=0;i<num_polys;i++) - { - parent->shape_data_store->p_normal_list[i] = *((ChunkVectorFloat *) pndata ); - pndata+=sizeof(ChunkVectorFloat); - } - -} - -Shape_Polygon_Normal_Chunk::Shape_Polygon_Normal_Chunk(Anim_Shape_Frame_Chunk * parent, const char * pndata , size_t pnsize) -: Chunk (parent, "SHPPNORM"), poly_norm_data (NULL), - num_polys (pnsize / sizeof(ChunkVectorFloat)) -{ - int i; - - ChunkVectorFloat* p_normal_list = new ChunkVectorFloat[num_polys]; - *((ChunkVectorFloat**) &poly_norm_data) = p_normal_list; - - for (i=0;i<num_polys;i++) - { - p_normal_list[i] = *((ChunkVectorFloat *) pndata ); - pndata+=sizeof(ChunkVectorFloat); - } - -} - -BOOL Shape_Polygon_Normal_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; - -} - -void Shape_Polygon_Normal_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - for (int i=0;i<num_polys;i++) - { - *(ChunkVectorFloat *) data_start = poly_norm_data[i]; - data_start+=sizeof(ChunkVectorFloat); - } - -} - -///////////////////////////////////////// - -// Class Shape_Polygon_Chunk functions - -// These can only be children of Shape_Chunks -// the shape chunks data will automatically be updated by it is created - -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPPOLYS",Shape_Polygon_Chunk,"REBSHAPE",Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPPOLYS",Shape_Polygon_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPPOLYS",Shape_Polygon_Chunk,"CONSHAPE",Console_Shape_Chunk) - -// from buffer -Shape_Polygon_Chunk::Shape_Polygon_Chunk (Shape_Chunk * parent, const char * pdata, size_t psize) -: Chunk (parent, "SHPPOLYS"), - poly_data (parent->shape_data_store->poly_list), num_polys (psize / 36) // 9 * 4 bytes per polygon -{ - int i, j; - - parent->shape_data_store->poly_list = new ChunkPoly [num_polys]; - parent->shape_data_store->num_polys = num_polys; - - *((ChunkPoly **) &poly_data) = parent->shape_data_store->poly_list; - - for (i=0; i<num_polys; i++) - { - parent->shape_data_store->poly_list[i].engine_type = *((int *) (pdata + (36*i))); - parent->shape_data_store->poly_list[i].normal_index = *((int *) (pdata + (36*i) + 4)); - parent->shape_data_store->poly_list[i].flags = *((int *) (pdata + (36*i) + 8)); - parent->shape_data_store->poly_list[i].colour = *((int *) (pdata + (36*i) + 12)); - - parent->shape_data_store->poly_list[i].num_verts = 0; - - for (j=0; *((int *) (pdata + (36*i) + 16 + (j*4))) != -1; j++) - { - parent->shape_data_store->poly_list[i].vert_ind[j] = *((int *) (pdata + (36*i) + 16 + (j*4))); - parent->shape_data_store->poly_list[i].num_verts++; - } - - } - -} - -Shape_Polygon_Chunk::Shape_Polygon_Chunk (Shape_Sub_Shape_Chunk * parent, const char * pdata, size_t psize) -: Chunk (parent, "SHPPOLYS"), - poly_data (parent->shape_data_store->poly_list), num_polys (psize / 36) // 9 * 4 bytes per polygon -{ - int i, j; - - parent->shape_data_store->poly_list = new ChunkPoly [num_polys]; - parent->shape_data_store->num_polys = num_polys; - - *((ChunkPoly **) &poly_data) = parent->shape_data_store->poly_list; - - for (i=0; i<num_polys; i++) - { - parent->shape_data_store->poly_list[i].engine_type = *((int *) (pdata + (36*i))); - parent->shape_data_store->poly_list[i].normal_index = *((int *) (pdata + (36*i) + 4)); - parent->shape_data_store->poly_list[i].flags = *((int *) (pdata + (36*i) + 8)); - parent->shape_data_store->poly_list[i].colour = *((int *) (pdata + (36*i) + 12)); - - parent->shape_data_store->poly_list[i].num_verts = 0; - - for (j=0; *((int *) (pdata + (36*i) + 16 + (j*4))) != -1; j++) - { - parent->shape_data_store->poly_list[i].vert_ind[j] = *((int *) (pdata + (36*i) + 16 + (j*4))); - parent->shape_data_store->poly_list[i].num_verts++; - } - - } - -} - -Shape_Polygon_Chunk::Shape_Polygon_Chunk (Console_Shape_Chunk * parent, const char * pdata, size_t psize) -: Chunk (parent, "SHPPOLYS"), - poly_data(0), num_polys (psize / 36) // 9 * 4 bytes per polygon -{ - int i, j; - - ChunkPoly* poly_list = new ChunkPoly [num_polys]; - - *((ChunkPoly **) &poly_data) =poly_list; - - for (i=0; i<num_polys; i++) - { - poly_list[i].engine_type = *((int *) (pdata + (36*i))); - poly_list[i].normal_index = *((int *) (pdata + (36*i) + 4)); - poly_list[i].flags = *((int *) (pdata + (36*i) + 8)); - poly_list[i].colour = *((int *) (pdata + (36*i) + 12)); - - poly_list[i].num_verts = 0; - - for (j=0; *((int *) (pdata + (36*i) + 16 + (j*4))) != -1; j++) - { - poly_list[i].vert_ind[j] = *((int *) (pdata + (36*i) + 16 + (j*4))); - poly_list[i].num_verts++; - } - - } - -} - -BOOL Shape_Polygon_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; - -} - -void Shape_Polygon_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - for (int i=0;i<num_polys;i++) { - *((int *) (data_start + i*36)) = poly_data[i].engine_type; - *((int *) (data_start + i*36 + 4)) = poly_data[i].normal_index; - *((int *) (data_start + i*36 + 8)) = poly_data[i].flags; - *((int *) (data_start + i*36 + 12)) = poly_data[i].colour; - for (int j = 0; j<poly_data[i].num_verts; j++) - *((int *) (data_start + i*36 + 16 + j*4)) = poly_data[i].vert_ind[j]; - for (; j<5; j++) - *((int *) (data_start + i*36 + 16 + j*4)) = -1; - - } - -} -///////////////////////////////////////// -//Class Shape_Centre_Chunk : - -RIF_IMPLEMENT_DYNCREATE("SHPCENTR",Shape_Centre_Chunk) - -Shape_Centre_Chunk::Shape_Centre_Chunk(Chunk_With_Children* parent,const char* data, size_t datasize) -:Chunk (parent,"SHPCENTR") -{ - assert(datasize==16); - - //find parent's chunkshape - ChunkShape* cs=0; - if(!strcmp(parent->identifier,"REBSHAPE")) - { - cs=((Shape_Chunk*)parent)->shape_data_store; - } - else if(!strcmp(parent->identifier,"SUBSHAPE")) - { - cs=((Shape_Sub_Shape_Chunk*)parent)->shape_data_store; - } - assert(cs); - - //fill in the appropriate entries - cs->centre=*(ChunkVectorInt*)data; - data+=sizeof(ChunkVectorInt); - - cs->radius_about_centre=*(float*)data; -} - -void Shape_Centre_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - //find parent's chunkshape - ChunkShape* cs=0; - if(!strcmp(parent->identifier,"REBSHAPE")) - { - cs=((Shape_Chunk*)parent)->shape_data_store; - } - else if(!strcmp(parent->identifier,"SUBSHAPE")) - { - cs=((Shape_Sub_Shape_Chunk*)parent)->shape_data_store; - } - assert(cs); - - - *(ChunkVectorInt*)data_start=cs->centre; - data_start+=sizeof(ChunkVectorInt); - - *(float*)data_start=cs->radius; -} - - -///////////////////////////////////////// - -// Class Shape_UV_Coord_Chunk functions - -// These can only be children of Shape_Chunks -// the shape chunks data will automatically be updated by it is created -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPUVCRD",Shape_UV_Coord_Chunk,"REBSHAPE",Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPUVCRD",Shape_UV_Coord_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPUVCRD",Shape_UV_Coord_Chunk,"CONSHAPE",Console_Shape_Chunk) - -// from buffer -Shape_UV_Coord_Chunk::Shape_UV_Coord_Chunk (Shape_Chunk * parent, const char * uvdata, size_t /*uvsize*/) -: Chunk (parent, "SHPUVCRD"), -uv_data (NULL), num_uvs (*((int *) uvdata)) -{ - int i,j; - - if (num_uvs) - { - parent->shape_data_store->uv_list = new ChunkUV_List[num_uvs]; - } - else - { - parent->shape_data_store->uv_list = 0; - } - *((ChunkUV_List**) &uv_data) = parent->shape_data_store->uv_list; - - parent->shape_data_store->num_uvs = num_uvs; - - uvdata += 4; - - for (i=0;i<num_uvs;i++) - { - parent->shape_data_store->uv_list[i].num_verts = *((int *) uvdata); - uvdata += 4; - - for (j=0; j<parent->shape_data_store->uv_list[i].num_verts; j++) - { - parent->shape_data_store->uv_list[i].vert[j] = *((ChunkUV *)uvdata); - uvdata += sizeof(ChunkUV); - } - } - -} - -Shape_UV_Coord_Chunk::Shape_UV_Coord_Chunk (Shape_Sub_Shape_Chunk * parent, const char * uvdata, size_t /*uvsize*/) -: Chunk (parent, "SHPUVCRD"), -uv_data (NULL), num_uvs (*((int *) uvdata)) -{ - int i,j; - - parent->shape_data_store->uv_list = new ChunkUV_List[num_uvs]; - *((ChunkUV_List**) &uv_data) = parent->shape_data_store->uv_list; - - parent->shape_data_store->num_uvs = num_uvs; - - uvdata += 4; - - for (i=0;i<num_uvs;i++) - { - parent->shape_data_store->uv_list[i].num_verts = *((int *) uvdata); - uvdata += 4; - - for (j=0; j<parent->shape_data_store->uv_list[i].num_verts; j++) - { - parent->shape_data_store->uv_list[i].vert[j] = *((ChunkUV *)uvdata); - uvdata += sizeof(ChunkUV); - } - } - -} - -Shape_UV_Coord_Chunk::Shape_UV_Coord_Chunk (Console_Shape_Chunk * parent, const char * uvdata, size_t /*uvsize*/) -: Chunk (parent, "SHPUVCRD"), -uv_data (NULL), num_uvs (*((int *) uvdata)) -{ - int i,j; - - ChunkUV_List* uv_list= new ChunkUV_List[num_uvs]; - *((ChunkUV_List**) &uv_data) = uv_list; - - uvdata += 4; - - for (i=0;i<num_uvs;i++) - { - uv_list[i].num_verts = *((int *) uvdata); - uvdata += 4; - - for (j=0; j<uv_list[i].num_verts; j++) - { - uv_list[i].vert[j] = *((ChunkUV *)uvdata); - uvdata += sizeof(ChunkUV); - } - } - -} - -Shape_UV_Coord_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; - -} - - -void Shape_UV_Coord_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = num_uvs; - - data_start += 4; - - for (int i=0;i<num_uvs;i++) - { - *((int *)data_start) = uv_data[i].num_verts; - data_start += 4; - for (int j = 0; j< uv_data[i].num_verts; j++) - { - *((ChunkUV *) data_start) = uv_data[i].vert[j]; - data_start += sizeof(ChunkUV); - } - } - -} - -size_t Shape_UV_Coord_Chunk::size_chunk () -{ - chunk_size = 12 + 4; - for (int i=0; i<num_uvs; i++) - chunk_size += (4+(sizeof(ChunkUV)*uv_data[i].num_verts)); - - return chunk_size; - -} - -///////////////////////////////////////// - -// Class Shape_Texture_Filenames_Chunk functions - -// These can only be children of Shape_Chunks -// the shape chunks data will automatically be updated by it is created - -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPTEXFN",Shape_Texture_Filenames_Chunk,"REBSHAPE",Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPTEXFN",Shape_Texture_Filenames_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) -// from buffer -Shape_Texture_Filenames_Chunk::Shape_Texture_Filenames_Chunk (Shape_Chunk * parent, const char * tfndata, size_t /*tfnsize*/) -: Chunk (parent, "SHPTEXFN"), -tex_fns (), num_tex_fns (*((int *) tfndata)) -{ - int i; - - parent->shape_data_store->texture_fns = new char * [num_tex_fns]; - *((char***) &tex_fns) = parent->shape_data_store->texture_fns; - - parent->shape_data_store->num_texfiles = num_tex_fns; - - tfndata += 4; - - for (i=0; i<num_tex_fns; i++) { - parent->shape_data_store->texture_fns[i] = new char [strlen(tfndata)+1]; - strcpy (parent->shape_data_store->texture_fns[i], tfndata); - tfndata += (strlen(tfndata)+1); - } - -} - -Shape_Texture_Filenames_Chunk::Shape_Texture_Filenames_Chunk (Shape_Sub_Shape_Chunk * parent, const char * tfndata, size_t /*tfnsize*/) -: Chunk (parent, "SHPTEXFN"), -tex_fns (), num_tex_fns (*((int *) tfndata)) -{ - int i; - - parent->shape_data_store->texture_fns = new char * [num_tex_fns]; - *((char***) &tex_fns) = parent->shape_data_store->texture_fns; - - parent->shape_data_store->num_texfiles = num_tex_fns; - - tfndata += 4; - - for (i=0; i<num_tex_fns; i++) { - parent->shape_data_store->texture_fns[i] = new char [strlen(tfndata)+1]; - strcpy (parent->shape_data_store->texture_fns[i], tfndata); - tfndata += (strlen(tfndata)+1); - } - -} - -Shape_Texture_Filenames_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; - -} - - -void Shape_Texture_Filenames_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = num_tex_fns; - - data_start += 4; - - for (int i=0;i<num_tex_fns;i++) { - sprintf(data_start, "%s", tex_fns[i]); - data_start += (strlen (tex_fns[i]) + 1); - } - -} - -size_t Shape_Texture_Filenames_Chunk::size_chunk() -{ - chunk_size = 16; - - for (int i=0;i<num_tex_fns;i++) - chunk_size += (strlen (tex_fns[i]) + 1); - - chunk_size += (4-chunk_size%4)%4; - - return chunk_size; - -} - - -///////////////////////////////////////// - -// Class Shape_Header_Chunk functions - -// These can only be children of Shape_Chunks -// the shape chunks data will automatically be updated by it is created -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPHEAD1",Shape_Header_Chunk,"REBSHAPE",Shape_Chunk) - - -Shape_Header_Chunk::Shape_Header_Chunk (Shape_Chunk * parent, const char * hdata, size_t /*hsize*/) - : Chunk (parent, "SHPHEAD1"), - shape_data (parent->shape_data_store) -{ - int num_as_obj; - - flags = *((int *) hdata); - - strncpy (lock_user, (hdata + 4), 16); - lock_user[16] = '\0'; - hdata+=20; - - file_id_num = *((int *) hdata ); - hdata+=4; - - - parent->shape_data_store->num_verts = *((int *) hdata ); - hdata+=4; - parent->shape_data_store->num_polys = *((int *) hdata ); - hdata+=4; - - parent->shape_data_store->radius = *((float *) hdata); - hdata+=4; - - parent->shape_data_store->max.x = *((int *) hdata); - hdata+=4; - parent->shape_data_store->min.x = *((int *) hdata); - hdata+=4; - - parent->shape_data_store->max.y = *((int *) hdata); - hdata+=4; - parent->shape_data_store->min.y = *((int *) hdata); - hdata+=4; - - parent->shape_data_store->max.z = *((int *) hdata); - hdata+=4; - parent->shape_data_store->min.z = *((int *) hdata); - hdata+=4; - - version_no = *((int *) hdata); - hdata+=4; - - num_as_obj = *((int *) hdata); - hdata+=4; - - char * obj_store; - - for (int i = 0; i< num_as_obj; i++) - { - obj_store = new char [strlen (hdata) +1]; - strcpy (obj_store, (hdata)); - object_names_store.add_entry(obj_store); - hdata += (strlen (hdata)+1); - } - -} - -Shape_Header_Chunk::~Shape_Header_Chunk() -{ - for (LIF<char *> aon(&object_names_store); - !aon.done(); aon.next() ) - delete [] aon(); -} - -size_t Shape_Header_Chunk::size_chunk() -{ - int length = 80; - - for (LIF<char *> aon(&object_names_store); - !aon.done(); aon.next() ) - length += (strlen (aon()) + 1); - - length += (4-length%4)%4; - - chunk_size = length; - - return length; -} - -BOOL Shape_Header_Chunk::output_chunk(HANDLE & hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -void Shape_Header_Chunk::fill_data_block(char * data_start) -{ - - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = flags; - strncpy ((data_start + 4), lock_user, 16); - *((int *) (data_start+20)) = file_id_num; - data_start+=24; - - *((int *) data_start) = shape_data->num_verts; - data_start+=4; - *((int *) data_start) = shape_data->num_polys; - data_start+=4; - - *((float *) data_start) = shape_data->radius; - data_start+=4; - - *((int *) data_start) = shape_data->max.x; - data_start+=4; - *((int *) data_start) = shape_data->min.x; - data_start+=4; - - *((int *) data_start) = shape_data->max.y; - data_start+=4; - *((int *) data_start) = shape_data->min.y; - data_start+=4; - - *((int *) data_start) = shape_data->max.z; - data_start+=4; - *((int *) data_start) = shape_data->min.z; - data_start+=4; - - *((int *) data_start) = version_no; - data_start+=4; - - *((int *) data_start) = object_names_store.size(); - data_start+=4; - - - for (LIF<char *> ons(&object_names_store); !ons.done(); ons.next()) - { - strcpy (data_start, ons()); - data_start += (strlen(ons())+1); - } - -} - - -void Shape_Header_Chunk::prepare_for_output() -{ -// this will also set the object chunks numbers as well, -// so that it is done in the right order - - char * str; - - if (file_id_num == -1) file_id_num = ++(Shape_Chunk::max_id); - - while (object_names_store.size()) { - delete [] object_names_store.first_entry(); - object_names_store.delete_first_entry(); - } - - for (LIF<Object_Chunk *> aosl(&associated_objects_store); - !aosl.done(); aosl.next() ) { - - if (aosl()->get_header()) - aosl()->get_header()->shape_id_no = file_id_num; - - str = new char [strlen(aosl()->object_data.o_name) + 1]; - strcpy(str, aosl()->object_data.o_name); - object_names_store.add_entry(str); - - } - - Shape_Chunk::max_id = max(Shape_Chunk::max_id, file_id_num); - -// this should always be the last thing - - version_no ++; -} - - - -///////////////////////////////////////// - -// Class Shape_Merge_Data_Chunk functions - -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPMRGDT",Shape_Merge_Data_Chunk,"REBSHAPE",Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPMRGDT",Shape_Merge_Data_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) - -Shape_Merge_Data_Chunk::Shape_Merge_Data_Chunk(Shape_Chunk * parent, int * m_dt, int n_ps) -: Chunk (parent, "SHPMRGDT"), num_polys (n_ps) -{ - merge_data = new int [n_ps]; - for (int i=0; i<n_ps; i++) - { - merge_data[i] = m_dt[i]; - } - -} - -Shape_Merge_Data_Chunk::Shape_Merge_Data_Chunk(Shape_Sub_Shape_Chunk * parent, int * m_dt, int n_ps) -: Chunk (parent, "SHPMRGDT"), num_polys (n_ps) -{ - merge_data = new int [n_ps]; - for (int i=0; i<n_ps; i++) - { - merge_data[i] = m_dt[i]; - } - -} - - -Shape_Merge_Data_Chunk::Shape_Merge_Data_Chunk (Shape_Chunk * parent, const char *md, size_t ms) -: Chunk (parent, "SHPMRGDT"), num_polys (ms/4) -{ - - merge_data = new int [num_polys]; - for (int i=0; i<num_polys; i++) - { - merge_data[i] = *((int *)(md+4*i)); - } -} - -Shape_Merge_Data_Chunk::Shape_Merge_Data_Chunk (Shape_Sub_Shape_Chunk * parent, const char *md, size_t ms) -: Chunk (parent, "SHPMRGDT"), num_polys (ms/4) -{ - - merge_data = new int [num_polys]; - for (int i=0; i<num_polys; i++) - { - merge_data[i] = *((int *)(md+4*i)); - } -} - - -Shape_Merge_Data_Chunk::~Shape_Merge_Data_Chunk() -{ - if (num_polys) delete merge_data; -} - -void Shape_Merge_Data_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - for (int i=0; i<num_polys; i++) - { - *((int *) (data_start+i*4) ) = merge_data[i]; - } - -} - - -///////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SHPEXTFL",Shape_External_File_Chunk) - -/* -Children for Shape_External_File_Chunk : - -"SHPEXTFN" Shape_External_Filename_Chunk) -"BMPLSTST" Bitmap_List_Store_Chunk) -"BMNAMVER" BMP_Names_Version_Chunk) -"BMNAMEXT" BMP_Names_ExtraData_Chunk) -"RIFFNAME" RIF_Name_Chunk) -"BMPMD5ID" Bitmap_MD5_Chunk) -"EXTOBJNM" Shape_External_Object_Name_Chunk) -*/ - -CHUNK_WITH_CHILDREN_LOADER("SHPEXTFL",Shape_External_File_Chunk) - - - -Shape_External_File_Chunk::Shape_External_File_Chunk (Chunk_With_Children * parent, const char * fname) -:Chunk_With_Children (parent, "SHPEXTFL") -{ - new Shape_External_Filename_Chunk (this, fname); - post_input_processing(); -} - -#if cencon || InterfaceEngine - -void Shape_External_File_Chunk::update_from_external_rif(BOOL force_scale_update) -{ - if(UpdatingExternalShape) - { - return; - } - - Shape_Chunk * parent_shp = (Shape_Chunk *) parent; - - Environment_Data_Chunk * envd = 0; - envd = (Environment_Data_Chunk *) parent_shp->parent->lookup_single_child("REBENVDT"); - - BOOL fixpal = IsFixedPalette(envd); - - List<Chunk *> chlst; - lookup_child("SHPEXTFN",chlst); - - if (chlst.size()) - { - UpdatingExternalShape=TRUE; - - Shape_External_Filename_Chunk * sefc = (Shape_External_Filename_Chunk *)chlst.first_entry(); - - #if cencon - twprintf("Locating %s\n",sefc->file_name); - char * locatedfile = FindExistingFileInPath_PreferWriteable(CWnd::GetActiveWindow(),sefc->file_name,"RifSearchPath"); - twprintf("Loading %s\n",locatedfile ? locatedfile : sefc->file_name); - RIF_File_Chunk * rfc = new RIF_File_Chunk (this, locatedfile ? locatedfile : sefc->file_name); - #elif InterfaceEngine - RIF_File_Chunk * rfc; - char * locatedfile = FindExistingFile_PreferWriteable(sefc->file_name,"RifSearchPath",FALSE); - if (locatedfile) - { - rfc = new RIF_File_Chunk (this, locatedfile); - } - else - { - UpdatingExternalShape=FALSE; - return; - } - #endif - - //Now loaded external file,so UpdatingExternalShape can now be reset - UpdatingExternalShape=FALSE; - - if (rfc->error_code != 0) - { - #if cencon - extern BOOL SuppressFailedToFindShapeRifErrors; - - if(!SuppressFailedToFindShapeRifErrors) - { - char message[300]; - sprintf(message,"Error loading shape rif : %s",locatedfile ? locatedfile : sefc->file_name); - twMessageBox(CWnd::GetActiveWindow(),message,"Tools Control Area", MB_TASKMODAL+MB_OK+MB_ICONHAND); - } - #endif - if (locatedfile) - { - delete[] locatedfile; - } - delete rfc; - return; - } - - Shape_Chunk* shp=0; - lookup_child("EXTOBJNM",chlst); - - - if(chlst.size()) - { - //we have an object name so we need to search for the correct object in the file - Shape_External_Object_Name_Chunk* seonm=(Shape_External_Object_Name_Chunk*) chlst.first_entry(); - - rfc->lookup_child("RBOBJECT",chlst); - for(LIF<Chunk*> chlif(&chlst);!chlif.done();chlif.next()) - { - Object_Chunk* oc=(Object_Chunk*)chlif(); - if(!strcmp(oc->object_data.o_name,seonm->object_name))break; - } - if(chlif.done()) - { - //can't find the object - #if cencon - char message[300]; - sprintf(message,"Failed to find %s in %s\n(There may be several different rif files with the same name)",seonm->object_name,locatedfile); - twMessageBox(CWnd::GetActiveWindow(),message,"Tools Control Area", MB_TASKMODAL+MB_OK+MB_ICONHAND); - #endif - delete [] locatedfile; - delete rfc; - return; - } - - shp=((Object_Chunk*)chlif())->get_assoc_shape(); - } - else - { - //no object name,so there has to be just one shape in the file - rfc->lookup_child("REBSHAPE",chlst); - - if (chlst.size() != 1) - { - #if cencon - char message[300]; - sprintf(message,"There are %d shapes in %s\n(There should only be one)\n",chlst.size(),locatedfile); - twMessageBox(CWnd::GetActiveWindow(),message,"Tools Control Area", MB_TASKMODAL+MB_OK+MB_ICONHAND); - #endif - Environment_Data_Chunk * edc = 0; - edc = (Environment_Data_Chunk *)rfc->lookup_single_child("REBENVDT"); - if(edc) - { - lookup_child("RIFFNAME",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - edc->lookup_child("RIFFNAME",chlst); - - if (chlst.size()) - { - new RIF_Name_Chunk (this, ((RIF_Name_Chunk *)chlst.first_entry())->rif_name); - } - } - delete [] locatedfile; - delete rfc; - return; - } - - shp = (Shape_Chunk *)chlst.first_entry(); - } - delete [] locatedfile; - locatedfile=0; - - // set so that it updates it whatever - - if (shp->get_header()->version_no != sefc->version_no || TRUE) - { - //if the shape doesn't have any associated objects,get scale from external file's - //environment scale chunk. - //also get scale if force_scale_update is true - if(parent_shp->list_assoc_objs().size()==0 || force_scale_update) - { - if(force_scale_update) - { - sefc->rescale=1; - } - List<Chunk*> chlist=rfc->lookup_child("REBENVDT"); - if(chlist.size()) - { - chlist=((Chunk_With_Children*)chlist.first_entry())->lookup_child("ENVSDSCL"); - if(chlist.size()) - { - Environment_Scale_Chunk* esc =(Environment_Scale_Chunk*)chlist.first_entry(); - sefc->rescale=esc->scale; - } - } - } - // copy all the data over from the loaded shape into the parent - ChunkShape cs = shp->shape_data; - - cs.rescale(sefc->rescale); - - - // here we may want to sort out texture index nos. - - - // hmmm fix me - // definitely fixme... - // everytime the file is loaded, - // the shape is updated, and its bmps - // and thus the palette-up-to-date flag is reset, - // and the machine reckons on a new palette. - - parent_shp->local_lock = TRUE; - - parent_shp->update_my_chunkshape (cs); - - parent_shp->local_lock = FALSE; - - // delete all other chunks in the parent shape - // apart form the header !!!! - - parent_shp->destroy_auxiliary_chunks(); - - char * tempbuffer; - Chunk* child_chunk; - - child_chunk=shp->lookup_single_child("SHPZSPDT"); - if (child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - new Shape_ZSP_Data_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - delete [] tempbuffer; - } - - child_chunk = shp->lookup_single_child("SHPMRGDT"); - if (child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - new Shape_Merge_Data_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - delete [] tempbuffer; - } - - child_chunk = shp->lookup_single_child("SHPMORPH"); - if (child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - new Shape_Morphing_Data_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - delete [] tempbuffer; - } - - child_chunk = shp->lookup_single_child("TEXTANIM"); - if (child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - new Animation_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - delete [] tempbuffer; - } - - child_chunk = shp->lookup_single_child("SHPPCINF"); - if (child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - new Shape_Poly_Change_Info_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - delete [] tempbuffer; - } - - - child_chunk = shp->lookup_single_child("SHPFRAGS"); - if (child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - Shape_Fragments_Chunk * sfc = new Shape_Fragments_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - - List<Chunk *> cl2; - sfc->lookup_child("SUBSHAPE",cl2); - - for (LIF<Chunk *> cli2(&cl2); !cli2.done(); cli2.next()) - { - Shape_Sub_Shape_Chunk * sssc = (Shape_Sub_Shape_Chunk *)cli2(); - - ChunkShape sscs = sssc->shape_data; - sscs.rescale(sefc->rescale); - sssc->update_my_chunkshape (sscs); - - Shape_Fragment_Location_Chunk * sflc = (Shape_Fragment_Location_Chunk *)sssc->lookup_single_child("FRAGLOCN"); - if (sflc) - { - sflc->frag_loc.x =(int) (sflc->frag_loc.x*sefc->rescale); - sflc->frag_loc.y =(int) (sflc->frag_loc.y*sefc->rescale); - sflc->frag_loc.z =(int) (sflc->frag_loc.z*sefc->rescale); - } - - } - - delete [] tempbuffer; - } - - shp->lookup_child("ANIMSEQU",chlst); - for(LIF<Chunk*> chlif(&chlst);!chlif.done();chlif.next()) - { - Anim_Shape_Sequence_Chunk* assc=(Anim_Shape_Sequence_Chunk*)chlif(); - new Anim_Shape_Sequence_Chunk(parent_shp,&assc->sequence_data); - } - - child_chunk = shp->lookup_single_child("PNOTINBB"); - if(child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - new Poly_Not_In_Bounding_Box_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - delete [] tempbuffer; - } - child_chunk = shp->lookup_single_child("ANSHCEN2"); - if(child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - new Anim_Shape_Centre_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - delete [] tempbuffer; - } - child_chunk = shp->lookup_single_child("ASALTTEX"); - if(child_chunk) - { - tempbuffer = child_chunk->make_data_block_from_chunk(); - new Anim_Shape_Alternate_Texturing_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - delete [] tempbuffer; - } - shp->lookup_child("CONSHAPE",chlst); - for(chlif.restart();!chlif.done();chlif.next()) - { - tempbuffer = chlif()->make_data_block_from_chunk(); - Console_Shape_Chunk* csc=new Console_Shape_Chunk (parent_shp, (tempbuffer + 12), (*(int *) (tempbuffer + 8))-12); - csc->generate_console_chunkshape(); - delete [] tempbuffer; - } - - parent_shp->updated = TRUE; - - sefc->version_no = shp->get_header()->version_no; - - } - - Bitmap_List_Store_Chunk * blsc = 0; - - Global_BMP_Name_Chunk * gbnc = 0; - - Environment_Data_Chunk * edc = 0; - - edc = (Environment_Data_Chunk *)rfc->lookup_single_child("REBENVDT"); - - - if (edc) - { - gbnc = (Global_BMP_Name_Chunk *) edc->lookup_single_child("BMPNAMES"); - if (gbnc) - { - if (!gbnc->bmps.size()) gbnc = 0; - } - - List<Chunk *> oldlst; - lookup_child("BMPLSTST",oldlst); - if (oldlst.size()>1) - { - while (oldlst.size()) - { - delete oldlst.first_entry(); - oldlst.delete_first_entry(); - } - } - - if (oldlst.size()) - { - blsc = (Bitmap_List_Store_Chunk *)oldlst.first_entry(); - } - else - { - if (gbnc) blsc = new Bitmap_List_Store_Chunk(this); - } - - BMP_Names_ExtraData * extended = 0; - if (blsc) - { - extended = blsc->GetExtendedData(); - if (fixpal) - extended->flags = (GlobalBMPFlags)(extended->flags | GBF_FIXEDPALETTE); - else - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_FIXEDPALETTE); - } - if (gbnc) - { - //if ((gbnc->get_version_num()!=blsc->get_version_num()) || (gbnc->bmps.size() != blsc->bmps.size())) - /*update regardless of version number*/ - { // other checks could be done as well - if (blsc->bmps.size()) - { - BOOL neednewpalette = FALSE; - - List<BMP_Name> newlist = gbnc->bmps; - for (LIF<BMP_Name> newLIF(&newlist); !newLIF.done(); newLIF.next()) - { - BMP_Name newcur = newLIF(); - newcur.flags = (BMPN_Flags) (newcur.flags & ~(COMPLETED_BMPN_FLAGS | ChunkBMPFlag_FixedPalette)); - if (fixpal) newcur.flags = (BMPN_Flags) (newcur.flags | ChunkBMPFlag_FixedPalette); - for (LIF<BMP_Name> oldLIF(&blsc->bmps); !oldLIF.done(); oldLIF.next()) - { - BMP_Name oldcur = oldLIF(); - if (newcur == oldcur) - { - // do we need to requantize? - if ((oldcur.flags ^ newcur.flags) & CHECKMODIFY_BMPN_FLAGS - || newcur.flags & ChunkBMPFlag_UsesTransparency - && !(newcur.flags & ChunkBMPFlag_IFF) - && !(oldcur.flags & ChunkBMPFlag_IFF) - && oldcur.DifferentTransparencyColour(newcur)) - oldcur.flags = (BMPN_Flags)(oldcur.flags & ~COMPLETED_BMPN_FLAGS); - // keep some of the old flags - the ones that can differ - newcur.flags = (BMPN_Flags)(newcur.flags & COPY_BMPN_FLAGS); - newcur.flags = (BMPN_Flags)(newcur.flags | oldcur.flags & ~COPY_BMPN_FLAGS); - if (oldcur.version_num != newcur.version_num) - { - neednewpalette = TRUE; - newcur.flags = (BMPN_Flags)(newcur.flags & ~ChunkBMPFlag_HistogramExists); - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - } - break; - } - } - if (oldLIF.done()) - { - // reset palette up to date flag - neednewpalette = TRUE; - newcur.flags = (BMPN_Flags)(newcur.flags & ~(ChunkBMPFlag_HistogramExists | COMPLETED_BMPN_FLAGS)); - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - } - newLIF.change_current(newcur); - } - - // check if any bitmaps have been removed - for (LIF<BMP_Name> bli(&blsc->bmps); !bli.done(); bli.next()) - { - if (!newlist.contains(bli())) - { - // delete assoc files - neednewpalette = TRUE; - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - } - } - - if (neednewpalette) - { - Palette_Outdated(envd); - if (fixpal) FixedPalette_Outdated(envd); - envd->updated = TRUE; - } - blsc->bmps = newlist; - } - else - { - blsc->bmps = gbnc->bmps; - for (LIF<BMP_Name> flagresetLIF(&blsc->bmps); !flagresetLIF.done(); flagresetLIF.next()) - { - BMP_Name current = flagresetLIF(); - current.flags = (BMPN_Flags)(current.flags & (COPY_BMPN_FLAGS & ~ChunkBMPFlag_FixedPalette)); - if (fixpal) current.flags = (BMPN_Flags) (current.flags | ChunkBMPFlag_FixedPalette); - flagresetLIF.change_current(current); - } - // reset palette up to date flag - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - Palette_Outdated(envd); - if (fixpal) FixedPalette_Outdated(envd); - envd->updated = TRUE; - } - blsc->max_index = gbnc->max_index; - blsc->set_version_num(gbnc->get_version_num()); - parent_shp->updated = TRUE; - } - } - else - { - if (blsc) - { - if (blsc->bmps.size()) - { - // reset palette up to date flag - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - Palette_Outdated(envd); - if (fixpal) FixedPalette_Outdated(envd); - envd->updated = TRUE; - parent_shp->updated = TRUE; - } - delete blsc; - } - } - } - - lookup_child("RIFFNAME",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - if (edc) - { - edc->lookup_child("RIFFNAME",chlst); - - if (chlst.size()) - { - new RIF_Name_Chunk (this, ((RIF_Name_Chunk *)chlst.first_entry())->rif_name); - } - - } - - delete rfc; - } - -} - -void Shape_External_File_Chunk::post_input_processing() -{ - - update_from_external_rif(FALSE); - Chunk_With_Children::post_input_processing(); - -} -#else -void Shape_External_File_Chunk::post_input_processing() -{ - Chunk_With_Children::post_input_processing(); -} -#endif - -const char* Shape_External_File_Chunk::get_shape_name() -{ - Shape_External_Object_Name_Chunk* seonc=(Shape_External_Object_Name_Chunk*)lookup_single_child("EXTOBJNM"); - if(seonc) - { - return seonc->shape_name; - } - - RIF_Name_Chunk* rnc=(RIF_Name_Chunk*)lookup_single_child("RIFFNAME"); - if(rnc) - { - return rnc->rif_name; - } - - return 0; - -} - -///////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SHPEXTFN",Shape_External_Filename_Chunk) - -Shape_External_Filename_Chunk::Shape_External_Filename_Chunk(Chunk_With_Children * parent, const char * fname) -: Chunk (parent, "SHPEXTFN") -{ - file_name = new char [strlen(fname)+1]; - strcpy (file_name, fname); - - rescale = 1; - version_no = -1; - -} - -Shape_External_Filename_Chunk::Shape_External_Filename_Chunk (Chunk_With_Children * parent, const char *fdata, size_t /*fsize*/) -: Chunk (parent, "SHPEXTFN") -{ - rescale = *((double *) fdata); - fdata += 8; - version_no = *((int *) fdata); - fdata += 4; - file_name = new char [strlen(fdata)+1]; - strcpy (file_name, fdata); -} - -Shape_External_Filename_Chunk::~Shape_External_Filename_Chunk() -{ - if (file_name) - delete [] file_name; -} - -void Shape_External_Filename_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((double *) data_start) = rescale; - - data_start += 8; - - *((int *) data_start) = version_no; - - data_start += 4; - - strcpy (data_start, file_name); - -} - -/////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("EXTOBJNM",Shape_External_Object_Name_Chunk) - -Shape_External_Object_Name_Chunk::Shape_External_Object_Name_Chunk(Chunk_With_Children * parent, const char * oname) -: Chunk (parent, "EXTOBJNM") -{ - object_name = new char [strlen(oname)+1]; - shape_name=0; - strcpy (object_name, oname); - pad=0; - - RIF_Name_Chunk* rnc=(RIF_Name_Chunk*)parent->lookup_single_child("RIFFNAME"); - if(rnc) - { - shape_name=new char[strlen(object_name)+strlen(rnc->rif_name)+2]; - sprintf(shape_name,"%s@%s",object_name,rnc->rif_name); - } - else - { - shape_name=new char[strlen(object_name)+10+2]; - sprintf(shape_name,"%s@*NotFound*",object_name); - } -} - -Shape_External_Object_Name_Chunk::Shape_External_Object_Name_Chunk (Chunk_With_Children * parent, const char *data, size_t /*fsize*/) -: Chunk (parent, "EXTOBJNM") -{ - pad=*(int*)data; - data+=4; - object_name = new char [strlen(data)+1]; - strcpy (object_name, data); - shape_name=0; -} - -Shape_External_Object_Name_Chunk::~Shape_External_Object_Name_Chunk() -{ - if (object_name) - delete [] object_name; - if(shape_name) - delete [] shape_name; -} - -void Shape_External_Object_Name_Chunk::post_input_processing() -{ - RIF_Name_Chunk* rnc=(RIF_Name_Chunk*)parent->lookup_single_child("RIFFNAME"); - if(rnc) - { - shape_name=new char[strlen(object_name)+strlen(rnc->rif_name)+2]; - sprintf(shape_name,"%s@%s",object_name,rnc->rif_name); - } - else - { - shape_name=new char[strlen(object_name)+10+2]; - sprintf(shape_name,"%s@*NotFound*",object_name); - } -} - -void Shape_External_Object_Name_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start =pad; - - data_start+=4; - - strcpy (data_start, object_name); - -} - -/////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPMORPH",Shape_Morphing_Data_Chunk,"REBSHAPE",Shape_Chunk) -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SHPMORPH",Shape_Morphing_Data_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) - -/* -Children for Shape_Morphing_Data_Chunk : - -"SUBSHAPE" Shape_Sub_Shape_Chunk -"FRMMORPH" Shape_Morphing_Frame_Data_Chunk -*/ - - -Shape_Morphing_Data_Chunk::Shape_Morphing_Data_Chunk (Shape_Chunk * parent, const char *data, size_t size) -: Chunk_With_Children (parent, "SHPMORPH"), parent_shape (parent), parent_sub_shape (0) -{ - const char * buffer_ptr = data; - - while ((data-buffer_ptr)< (signed)size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed)size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(data); - data += *(int *)(data + 8); - - } - -} -Shape_Morphing_Data_Chunk::Shape_Morphing_Data_Chunk (Shape_Sub_Shape_Chunk * parent, const char *data, size_t size) -: Chunk_With_Children (parent, "SHPMORPH"), parent_sub_shape (parent), parent_shape (0) -{ - const char * buffer_ptr = data; - - while ((data-buffer_ptr)< (signed)size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed)size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - DynCreate(data); - data += *(int *)(data + 8); - - - } - -} - - -void Shape_Morphing_Data_Chunk::prepare_for_output() -{ - int max_id = 0; - - List<Chunk *> cl; - lookup_child("SUBSHAPE",cl); - - for (LIF<Chunk *> cli(&cl); !cli.done(); cli.next()) - { - max_id = max (max_id, ((Shape_Sub_Shape_Chunk *)cli())->get_header()->file_id_num); - } - - for (cli.restart(); !cli.done(); cli.next()) - { - if (((Shape_Sub_Shape_Chunk *)cli())->get_header()->file_id_num == -1) - { - ((Shape_Sub_Shape_Chunk *)cli())->get_header()->file_id_num = ++max_id; - } - } - Chunk_With_Children::prepare_for_output(); - -} - -/////////////////////////////////////// - -#ifdef new -#pragma message("new defined") -#endif - -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("FRMMORPH",Shape_Morphing_Frame_Data_Chunk,"SHPMORPH",Shape_Morphing_Data_Chunk) - -Shape_Morphing_Frame_Data_Chunk::Shape_Morphing_Frame_Data_Chunk (Shape_Morphing_Data_Chunk * parent,const char *data, size_t /*size*/) -: Chunk (parent, "FRMMORPH") -{ - a_flags = *((int *)data); - data +=4; - a_speed = *((int *)data); - data +=4; - num_frames = *((int *)data); - data +=4; - - if (num_frames) - frame_store = new int [num_frames * 3]; - else - frame_store=0; - for (int i=0; i<num_frames; i++) - { - frame_store[i*3] = *((int *)data); - data +=4; - frame_store[i*3+1] = *((int *)data); - data +=4; - frame_store[i*3+2] = *((int *)data); - data +=4; - } -} - -void Shape_Morphing_Frame_Data_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - *((int *) data_start) = a_flags; - data_start += 4; - *((int *) data_start) = a_speed; - data_start += 4; - *((int *) data_start) = num_frames; - data_start += 4; - for (int i=0; i<num_frames; i++) - { - *((int *) data_start) = frame_store[i*3]; - data_start += 4; - *((int *) data_start) = frame_store[i*3 + 1]; - data_start += 4; - *((int *) data_start) = frame_store[i*3 + 2]; - data_start += 4; - } -} - -Shape_Morphing_Frame_Data_Chunk::~Shape_Morphing_Frame_Data_Chunk() -{ - if (frame_store) delete [] frame_store; - while (anim_frames.size()) - { - delete anim_frames.first_entry(); - anim_frames.delete_first_entry(); - } -} - -void Shape_Morphing_Frame_Data_Chunk::prepare_for_output() -{ - // get the number of each shape in each frame - - // N.B. this relies on the fact that the shapes are numbered - // but they will be by the parent class which will have it's prepare - // for output called first - - if (frame_store) - delete [] frame_store; - - if (anim_frames.size()) - { - frame_store = new int [ anim_frames.size() * 3 ]; - } - else - { - frame_store = 0; - } - - int num_f = 0; - - for (LIF<a_frame *> afi(&anim_frames); !afi.done(); afi.next()) - { - int s1no, s2no; - if (afi()->shape1a) - s1no = afi()->shape1a->get_header()->file_id_num; - else - s1no = -1; - if (afi()->shape2a) - s2no = afi()->shape2a->get_header()->file_id_num; - else - s2no = -1; - - frame_store[num_f] = s1no; - frame_store[num_f+1] = s2no; - frame_store[num_f+2] = afi()->spare; - num_f ++; - } - num_frames = num_f; -} - - -void Shape_Morphing_Frame_Data_Chunk::post_input_processing() -{ - List<Shape_Sub_Shape_Chunk *> shplist; - List<Chunk *> child_lists; - - Shape_Morphing_Data_Chunk * pchnk = (Shape_Morphing_Data_Chunk *) parent; - - pchnk->lookup_child("SUBSHAPE",child_lists); - - while (child_lists.size()) { - shplist.add_entry((Shape_Sub_Shape_Chunk *)child_lists.first_entry()); - child_lists.delete_first_entry(); - } - - LIF<Shape_Sub_Shape_Chunk *> sl(&shplist); - - for (int i = 0; i<num_frames; i++) - { - Shape_Chunk * sh1b = 0, *sh2b = 0; - Shape_Sub_Shape_Chunk * sh1a = 0, *sh2a = 0; - a_frame * fr; - - if (frame_store[i*2] == -1) - { - sh1b = pchnk->parent_shape; - } - else - { - for (; !sl.done(); sl.next()) { - if (sl()->get_header()) - if (sl()->get_header()->file_id_num == frame_store[i]) - break; - } - if (!sl.done()) - { - sh1a = sl(); - } - } - - if (frame_store[i*2+1] == -1) - { - sh2b = pchnk->parent_shape; - } - else - { - for (sl.restart(); !sl.done(); sl.next()) { - if (sl()->get_header()) - if (sl()->get_header()->file_id_num == frame_store[i+1]) - break; - } - if (!sl.done()) - { - sh2a = sl(); - } - } - if ((sh1a || sh1b) && (sh2a || sh2b)) - { - fr = new a_frame; - if (sh1a) - fr->shape1a = sh1a; - else if (sh1b) - fr->shape1b = sh1b; - - if (sh2a) - fr->shape2a = sh2a; - else if (sh2b) - fr->shape2b = sh2b; - - fr->spare = frame_store[i+2]; - anim_frames.add_entry(fr); - } - - } -} - -///////////////////////////////////////// - -// Class Shape_Sub_Shape_Chunk functions - - -RIF_IMPLEMENT_DYNCREATE("SUBSHAPE",Shape_Sub_Shape_Chunk) -/* -Children for Shape_Sub_Shape_Chunk : - -"SHPRAWVT" Shape_Vertex_Chunk -"SHPPOLYS" Shape_Polygon_Chunk -"SUBSHPHD" Shape_Sub_Shape_Header_Chunk -"SHPVNORM" Shape_Vertex_Normal_Chunk -"SHPPNORM" Shape_Polygon_Normal_Chunk -"SHPTEXFN" Shape_Texture_Filenames_Chunk -"SHPUVCRD" Shape_UV_Coord_Chunk -"SHPMRGDT" Shape_Merge_Data_Chunk -"SHPCENTR" Shape_Centre_Chunk -"SHPMORPH" Shape_Morphing_Data_Chunk -"SHPEXTFL" Shape_External_File_Chunk -"SHPPCINF" Shape_Poly_Change_Info_Chunk -"TEXTANIM" Animation_Chunk -"SHPFRAGS" Shape_Fragments_Chunk -"ANIMSEQU" Anim_Shape_Sequence_Chunk -"PNOTINBB" Poly_Not_In_Bounding_Box_Chunk -"ANSHCEN2" Anim_Shape_Centre_Chunk -"ASALTTEX" Anim_Shape_Alternate_Texturing_Chunk -"SHPPRPRO" Shape_Preprocessed_Data_Chunk - - -"SHPFNAME" Shape_Name_Chunk -"FRAGDATA" Shape_Fragments_Data_Chunk -"FRAGLOCN" Shape_Fragment_Location_Chunk -*/ - -Shape_Sub_Shape_Chunk::Shape_Sub_Shape_Chunk(Chunk_With_Children * parent, const char *data, size_t size) -: Chunk_With_Children (parent, "SUBSHAPE"), shape_data () -{ - const char * buffer_ptr = data; - - shape_data_store = (ChunkShape *) &shape_data; - - while ((data-buffer_ptr)< (signed)size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed)size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(data); - data += *(int *)(data + 8); - - } - #if cencon || InterfaceEngine - List<Chunk*>chlist; - lookup_child("CONSHAPE",chlist); - for(LIF<Chunk*> chlif(&chlist);!chlif.done();chlif.next()) - { - ((Console_Shape_Chunk*)chlif())->generate_console_chunkshape(); - } - #endif -} - -Shape_Sub_Shape_Chunk::Shape_Sub_Shape_Chunk (Chunk_With_Children * parent, ChunkShape &shp_dat) -: Chunk_With_Children (parent, "SUBSHAPE"), shape_data (shp_dat) -{ - shape_data_store = (ChunkShape *) &shape_data; - - new Shape_Sub_Shape_Header_Chunk (this); - - if (shape_data.v_list) new Shape_Vertex_Chunk (this, shape_data.num_verts); - if (shape_data.v_normal_list) new Shape_Vertex_Normal_Chunk (this, shape_data.num_verts); - if (shape_data.p_normal_list) new Shape_Polygon_Normal_Chunk (this, shape_data.num_polys); - if (shape_data.poly_list) new Shape_Polygon_Chunk (this, shape_data.num_polys); - if (shape_data.uv_list) new Shape_UV_Coord_Chunk (this, shape_data.num_uvs); - if (shape_data.texture_fns) new Shape_Texture_Filenames_Chunk (this, shape_data.num_texfiles); - - //calculate the shape's centre and radius_about_centre - shape_data_store->centre=(shape_data_store->min+shape_data_store->max)/2; - shape_data_store->radius_about_centre=0; - for(int i=0;i<shape_data_store->num_verts;i++) - { - float length = (float) mod(shape_data_store->v_list[i]-shape_data_store->centre); - if(length>shape_data_store->radius_about_centre) - { - shape_data_store->radius_about_centre=length; - } - } - - //if the shape hasn't got a Shape_Centre_Chunk , create one. - - if(!lookup_single_child("SHPCENTR")) - { - new Shape_Centre_Chunk(this); - } -} - -Shape_Sub_Shape_Chunk::~Shape_Sub_Shape_Chunk () -{ -} - -Shape_Sub_Shape_Chunk* Shape_Sub_Shape_Chunk::make_copy_of_chunk() -{ - char* Data=this->make_data_block_from_chunk(); - Shape_Sub_Shape_Chunk* NewShape=new Shape_Sub_Shape_Chunk(parent,Data+12,this->size_chunk()-12); - delete [] Data; - delete NewShape->get_header(); - new Shape_Sub_Shape_Header_Chunk(NewShape); - return NewShape; -} - -Shape_Sub_Shape_Header_Chunk * Shape_Sub_Shape_Chunk::get_header() -{ - - return (Shape_Sub_Shape_Header_Chunk *) this->lookup_single_child ("SUBSHPHD"); - -} - -BOOL Shape_Sub_Shape_Chunk::update_my_chunkshape (ChunkShape & cshp) -{ - // Firstly lose all the chunks that were with - // the old chunk shape - List <Chunk *> chlst; - - lookup_child ("SHPRAWVT",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - lookup_child ("SHPVNORM",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child ("SHPPNORM",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child ("SHPPOLYS",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child ("SHPUVCRD",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - - lookup_child ("SHPTEXFN",chlst); - - while (chlst.size()) - { - delete chlst.first_entry(); - chlst.delete_first_entry(); - } - - *shape_data_store = cshp; - - if (shape_data.v_list) new Shape_Vertex_Chunk (this, shape_data.num_verts); - if (shape_data.v_normal_list) new Shape_Vertex_Normal_Chunk (this, shape_data.num_verts); - if (shape_data.p_normal_list) new Shape_Polygon_Normal_Chunk (this, shape_data.num_polys); - if (shape_data.poly_list) new Shape_Polygon_Chunk (this, shape_data.num_polys); - if (shape_data.uv_list) new Shape_UV_Coord_Chunk (this, shape_data.num_uvs); - if (shape_data.texture_fns) new Shape_Texture_Filenames_Chunk (this, shape_data.num_texfiles); - - //calculate the shape's centre and radius_about_centre - shape_data_store->centre=(shape_data_store->min+shape_data_store->max)/2; - shape_data_store->radius_about_centre=0; - for(int i=0;i<shape_data_store->num_verts;i++) - { - float length=(float)mod(shape_data_store->v_list[i]-shape_data_store->centre); - if(length>shape_data_store->radius_about_centre) - { - shape_data_store->radius_about_centre=length; - } - } - - //if the shape hasn't got a Shape_Centre_Chunk , create one. - - if(!lookup_single_child("SHPCENTR")) - { - new Shape_Centre_Chunk(this); - } - - - return TRUE; -} - - -const char * Shape_Sub_Shape_Chunk::get_shape_name() -{ - Shape_Name_Chunk* snc=(Shape_Name_Chunk*)lookup_single_child("SHPFNAME"); - if (snc) - { - return snc->shape_name; - } - else - { - return(0); - } -} - -Console_Shape_Chunk* Shape_Sub_Shape_Chunk::get_console_shape_data(Console_Type ct) -{ - List<Chunk*> chlist; - lookup_child("CONSHAPE",chlist); - for(LIF<Chunk*> chlif(&chlist);!chlif.done();chlif.next()) - { - Console_Shape_Chunk* csc=(Console_Shape_Chunk*)chlif(); - List<Chunk*> chlist2; - csc->lookup_child("CONSTYPE",chlist2); - if(chlist2.size()) - { - if(((Console_Type_Chunk*)chlist2.first_entry())->console==ct) - return csc; - } - } - - return 0;//no console specific shape data -} - -///////////////////////////////////////// - -// Class Shape_Sub_Shape_Header_Chunk functions - -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SUBSHPHD",Shape_Sub_Shape_Header_Chunk,"SUBSHAPE",Shape_Sub_Shape_Chunk) - -// These can only be children of Shape_Sub_Shape_Chunks -// the shape chunks data will automatically be updated by it is created - -Shape_Sub_Shape_Header_Chunk::Shape_Sub_Shape_Header_Chunk (Shape_Sub_Shape_Chunk * parent, const char * hdata, size_t /*hsize*/) - : Chunk (parent, "SUBSHPHD"), - shape_data (parent->shape_data_store) -{ - flags = *((int *) hdata); - hdata += 4; - - file_id_num = *((int *) (hdata)); - hdata += 4; - - parent->shape_data_store->num_verts = *((int *) (hdata)); - hdata += 4; - parent->shape_data_store->num_polys = *((int *) (hdata)); - hdata += 4; - - parent->shape_data_store->radius = *((float *) (hdata)); - hdata += 4; - - parent->shape_data_store->max.x = *((int *) (hdata)); - hdata += 4; - parent->shape_data_store->min.x = *((int *) (hdata)); - hdata += 4; - - parent->shape_data_store->max.y = *((int *) (hdata)); - hdata += 4; - parent->shape_data_store->min.y = *((int *) (hdata)); - hdata += 4; - - parent->shape_data_store->max.z = *((int *) (hdata)); - hdata += 4; - parent->shape_data_store->min.z = *((int *) (hdata)); -} - -Shape_Sub_Shape_Header_Chunk::~Shape_Sub_Shape_Header_Chunk() -{ -} - -size_t Shape_Sub_Shape_Header_Chunk::size_chunk() -{ - return chunk_size = 44 + 12; -} - - -void Shape_Sub_Shape_Header_Chunk::fill_data_block(char * data_start) -{ - - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = flags; - data_start += 4; - - *((int *) (data_start)) = file_id_num; - data_start += 4; - - *((int *) (data_start)) = shape_data->num_verts; - data_start += 4; - *((int *) (data_start)) = shape_data->num_polys; - data_start += 4; - - *((float *) (data_start)) = shape_data->radius; - data_start += 4; - - *((int *) (data_start)) = shape_data->max.x; - data_start += 4; - *((int *) (data_start)) = shape_data->min.x; - data_start += 4; - - *((int *) (data_start)) = shape_data->max.y; - data_start += 4; - *((int *) (data_start)) = shape_data->min.y; - data_start += 4; - - *((int *) (data_start)) = shape_data->max.z; - data_start += 4; - *((int *) (data_start)) = shape_data->min.z; - -} - -///////////////////////////////////////// - - -// Class Shape_Poly_Change_Info_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("SHPPCINF",Shape_Poly_Change_Info_Chunk) - -void Shape_Poly_Change_Info_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = original_num_verts; - - data_start += 4; - - *((int *) data_start) = change_list.size(); - - data_start += 4; - - for (LIF<poly_change_info> pcii(&change_list); !pcii.done(); pcii.next()) - { - *((int *) data_start) = pcii().poly_num; - - data_start += 4; - - *((int *) data_start) = pcii().vert_num_before; - - data_start += 4; - - *((int *) data_start) = pcii().vert_num_after; - - data_start += 4; - } - - -} - -Shape_Poly_Change_Info_Chunk::Shape_Poly_Change_Info_Chunk (Chunk_With_Children * parent,const char * data, size_t /*size*/) -: Chunk (parent, "SHPPCINF") -{ - original_num_verts = *((int *) data); - - data += 4; - - int n_entries = *((int *) data); - - data += 4; - - for (int i=0; i<n_entries; i++) - { - poly_change_info pci; - - pci.poly_num = *((int *) data); - data += 4; - pci.vert_num_before = *((int *) data); - data += 4; - pci.vert_num_after = *((int *) data); - data += 4; - - change_list.add_entry(pci); - } - -} - - -///////////////////////////////////////// - -// Class Shape_Name_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("SHPFNAME",Shape_Name_Chunk) - -Shape_Name_Chunk::Shape_Name_Chunk (Chunk_With_Children * parent, const char * sname) -: Chunk (parent, "SHPFNAME") -{ - shape_name = new char [strlen(sname)+1]; - strcpy (shape_name, sname); -} - -Shape_Name_Chunk::Shape_Name_Chunk (Chunk_With_Children * parent, const char * sndata, size_t /*rsize*/) -: Chunk (parent, "SHPFNAME") -{ - shape_name = new char [strlen(sndata)+1]; - strcpy (shape_name, sndata); -} - -Shape_Name_Chunk::~Shape_Name_Chunk () -{ - if (shape_name) - delete [] shape_name; -} - - -void Shape_Name_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - strcpy (data_start, shape_name); - -} - -///////////////////////////////////////// - -// Class Shape_Fragments_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("SHPFRAGS",Shape_Fragments_Chunk) - -CHUNK_WITH_CHILDREN_LOADER("SHPFRAGS",Shape_Fragments_Chunk) -/* -Children for Shape_Fragments_Chunk : - -"SUBSHAPE" Shape_Sub_Shape_Chunk -"SHPFRGTP" Shape_Fragment_Type_Chunk -"FRGSOUND" Fragment_Type_Sound_Chunk -*/ - - -///////////////////////////////////////// - -// Class Shape_Fragments_Data_Chunk functions -RIF_IMPLEMENT_DYNCREATE("FRAGDATA",Shape_Fragments_Data_Chunk) - -void Shape_Fragments_Data_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = num_fragments; - - data_start += 4; - - *((int *) data_start) = pad1; - - data_start += 4; - - *((int *) data_start) = pad2; - - data_start += 4; - - *((int *) data_start) = pad3; - -} - -Shape_Fragments_Data_Chunk::Shape_Fragments_Data_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/) -: Chunk (parent, "FRAGDATA") -{ - num_fragments = *((int *) sdata); - - sdata += 4; - - pad1 = *((int *) sdata); - - sdata += 4; - - pad2 = *((int *) sdata); - - sdata += 4; - - pad3 = *((int *) sdata); - - sdata += 4; - -} - - -///////////////////////////////////////// - -// Class Shape_Fragments_Location_Chunk functions -RIF_IMPLEMENT_DYNCREATE("FRAGLOCN",Shape_Fragment_Location_Chunk) - -void Shape_Fragment_Location_Chunk::fill_data_block (char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((ChunkVectorInt *) data_start) = frag_loc; - - data_start += sizeof(ChunkVectorInt); - - - *((int *) data_start) = pad1; - - data_start += 4; - - *((int *) data_start) = pad2; - - data_start += 4; - - *((int *) data_start) = pad3; - - data_start += 4; - - *((int *) data_start) = pad4; - -} - -Shape_Fragment_Location_Chunk::Shape_Fragment_Location_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/) -: Chunk (parent, "FRAGLOCN") -{ - frag_loc = *((ChunkVectorInt *) sdata); - - sdata += sizeof(ChunkVectorInt); - - - pad1 = *((int *) sdata); - - sdata += 4; - - pad2 = *((int *) sdata); - - sdata += 4; - - pad3 = *((int *) sdata); - - sdata += 4; - - pad4 = *((int *) sdata); - -} - -///////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("SHPFRGTP",Shape_Fragment_Type_Chunk) -Shape_Fragment_Type_Chunk::Shape_Fragment_Type_Chunk(Chunk_With_Children* parent,const char* name) -:Chunk(parent,"SHPFRGTP") -{ - frag_type_name=new char[strlen(name)+1]; - strcpy(frag_type_name,name); - pad1=pad2-0; -} - -Shape_Fragment_Type_Chunk::Shape_Fragment_Type_Chunk(Chunk_With_Children* const parent,const char* data,size_t const ) -:Chunk(parent,"SHPFRGTP") -{ - int length=strlen(data)+1; - frag_type_name=new char[length]; - strcpy(frag_type_name,data); - data+=(length+3)&~3; - - pad1=*(int*)data; - data+=4; - pad2=*(int*)data; - data+=4; -} - -Shape_Fragment_Type_Chunk::~Shape_Fragment_Type_Chunk() -{ - if(frag_type_name) delete frag_type_name; -} - -void Shape_Fragment_Type_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - strcpy(data_start,frag_type_name); - data_start+=(strlen(frag_type_name)+4)&~3; - - *(int*)data_start=pad1; - data_start+=4; - *(int*)data_start=pad2; - data_start+=4; - -} - -size_t Shape_Fragment_Type_Chunk::size_chunk() -{ - chunk_size=12+8; - chunk_size+=(strlen(frag_type_name)+4)&~3; - return chunk_size; -} - - -///////////////////////////////////////// - -// Class Anim_Shape_Sequence_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("ANIMSEQU",Anim_Shape_Sequence_Chunk) - -/* -Children for Anim_Shape_Sequence_Chunk : -"ANISEQDT" Anim_Shape_Sequence_Data_Chunk -"ANIMFRAM" Anim_Shape_Frame_Chunk -*/ - -Anim_Shape_Sequence_Chunk::Anim_Shape_Sequence_Chunk(Chunk_With_Children * const parent, const char *data, size_t const size) -: Chunk_With_Children (parent, "ANIMSEQU") -{ - - sequence_data_store=(ChunkAnimSequence*)&sequence_data; - - const char * buffer_ptr = data; - - while ((data-buffer_ptr)< (signed)size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed)size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(data); - data += *(int *)(data + 8); - - } - if(!ConstructSequenceDataFromChildren()) - { - //this sequence is no longer valid - delete this; - } -} -Anim_Shape_Sequence_Chunk::Anim_Shape_Sequence_Chunk(Chunk_With_Children * const parent, int sequencenum,const char* name) -: Chunk_With_Children (parent, "ANIMSEQU") -{ - - sequence_data_store=(ChunkAnimSequence*)&sequence_data; - - sequence_data_store->SequenceNum=sequencenum; - sequence_data_store->name=new char[strlen(name)+1]; - strcpy(sequence_data_store->name,name); - RegenerateChildChunks(); -} - -Anim_Shape_Sequence_Chunk::Anim_Shape_Sequence_Chunk(Chunk_With_Children * const parent, ChunkAnimSequence const* cas ) -: Chunk_With_Children (parent, "ANIMSEQU") -{ - - sequence_data_store=(ChunkAnimSequence*)&sequence_data; - *(ChunkAnimSequence*)&sequence_data=*cas; - RegenerateChildChunks(); -} - - -int Anim_Shape_Sequence_Chunk::ConstructSequenceDataFromChildren() -{ - Anim_Shape_Sequence_Data_Chunk* assdc=(Anim_Shape_Sequence_Data_Chunk*)lookup_single_child("ANISEQDT"); - if(!assdc) - { - return 0; - } - sequence_data_store->name=assdc->name; - sequence_data_store->SequenceNum=assdc->SequenceNum; - sequence_data_store->flags=assdc->flags; - sequence_data_store->pad2=assdc->pad2; - sequence_data_store->pad3=assdc->pad3; - sequence_data_store->pad4=assdc->pad4; - - List<Chunk*> chlist; - lookup_child("ANIMFRAM",chlist); - sequence_data_store->NumFrames=chlist.size(); - if(sequence_data_store->NumFrames) - { - sequence_data_store->Frames=new ChunkAnimFrame*[sequence_data_store->NumFrames]; - for(int i=0;i<sequence_data_store->NumFrames;i++) - { - sequence_data_store->Frames[i]=0; - } - } - for(LIF<Chunk*> chlif(& chlist);!chlif.done();chlif.next()) - { - Anim_Shape_Frame_Chunk* asfc=(Anim_Shape_Frame_Chunk*)chlif(); - - Anim_Shape_Frame_Data_Chunk* asfdc=(Anim_Shape_Frame_Data_Chunk*)asfc->lookup_single_child("ANIFRADT"); - if(!asfdc) return 0; - if(asfdc->FrameNum>=sequence_data_store->NumFrames) return 0; - - if(sequence_data_store->Frames[asfdc->FrameNum])return 0; - sequence_data_store->Frames[asfdc->FrameNum]=new ChunkAnimFrame; - ChunkAnimFrame* caf=sequence_data_store->Frames[asfdc->FrameNum]; - - Shape_Vertex_Chunk* svc=(Shape_Vertex_Chunk*) asfc->lookup_single_child("SHPRAWVT"); - if(!svc)return 0; - - Shape_Polygon_Normal_Chunk* spnc=(Shape_Polygon_Normal_Chunk*)asfc->lookup_single_child("SHPPNORM"); - if(!spnc) return 0; - - caf->name=asfdc->name; - caf->flags=asfdc->flags; - caf->num_interp_frames=asfdc->num_interp_frames; - caf->pad3=asfdc->pad3; - caf->pad4=asfdc->pad4; - - caf->num_verts=svc->num_verts; - caf->v_list=(ChunkVectorInt*)svc->vert_data; - - caf->num_polys=spnc->num_polys; - caf->p_normal_list=(ChunkVectorFloat*)spnc->poly_norm_data; - - } - return 1; -} -void Anim_Shape_Sequence_Chunk::post_input_processing() -{ - - List<int>* poly_not_in_bb=0; - List<Chunk*> chlist; - parent->lookup_child("PNOTINBB",chlist); - if(chlist.size()) - poly_not_in_bb=&((Poly_Not_In_Bounding_Box_Chunk*)chlist.first_entry())->poly_no; - if(!strcmp(parent->identifier,"REBSHAPE")) - { - sequence_data_store->UpdateNormalsAndExtents(&((Shape_Chunk*)parent)->shape_data,poly_not_in_bb); - } - else if(!strcmp(parent->identifier,"SUBSHAPE")) - { - sequence_data_store->UpdateNormalsAndExtents(&((Shape_Sub_Shape_Chunk*)parent)->shape_data,poly_not_in_bb); - } - - Chunk_With_Children::post_input_processing(); -} - - -void Anim_Shape_Sequence_Chunk::update_my_sequencedata(ChunkAnimSequence & seq) -{ - *sequence_data_store=seq; - RegenerateChildChunks(); -} - -void Anim_Shape_Sequence_Chunk::set_sequence_flags(int flags) -{ - sequence_data_store->flags=flags; -} -void Anim_Shape_Sequence_Chunk::set_frame_flags(int frameno,int flags) -{ - if(frameno< sequence_data_store->NumFrames) - { - if(sequence_data_store->Frames[frameno]) - { - sequence_data_store->Frames[frameno]->flags=flags; - } - } -} - -void Anim_Shape_Sequence_Chunk::RegenerateChildChunks() -{ - List<Chunk*> chlist; - lookup_child("ANISEQDT",chlist); - while(chlist.size()) - { - delete chlist.first_entry(); - chlist.delete_first_entry(); - } - lookup_child("ANIMFRAM",chlist); - while(chlist.size()) - { - delete chlist.first_entry(); - chlist.delete_first_entry(); - } - - new Anim_Shape_Sequence_Data_Chunk(this,sequence_data_store); - for(int i=0;i<sequence_data_store->NumFrames;i++) - { - if(sequence_data_store->Frames[i]->flags & animframeflag_interpolated_frame)continue; - new Anim_Shape_Frame_Chunk(this,sequence_data_store->Frames[i],i); - } -} - -void Anim_Shape_Sequence_Chunk::GenerateInterpolatedFrames() -{ - - if(!strcmp(parent->identifier,"REBSHAPE")) - { - sequence_data_store->GenerateInterpolatedFrames(&((Shape_Chunk*)parent)->shape_data); - } - else if(!strcmp(parent->identifier,"SUBSHAPE")) - { - sequence_data_store->GenerateInterpolatedFrames(&((Shape_Sub_Shape_Chunk*)parent)->shape_data); - } -} -///////////////////////////////////////// - -// Class Anim_Shape_Frame_Chunk functions -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("ANIMFRAM",Anim_Shape_Frame_Chunk,"ANIMSEQU",Anim_Shape_Sequence_Chunk) - -/* -Children for Anim_Shape_Frame_Chunk : - -"ANIFRADT" Anim_Shape_Frame_Data_Chunk -"SHPPNORM" Shape_Polygon_Normal_Chunk -"SHPRAWVT" Shape_Vertex_Chunk -*/ - -Anim_Shape_Frame_Chunk::Anim_Shape_Frame_Chunk(Anim_Shape_Sequence_Chunk *const parent, const char *data, size_t const size) -: Chunk_With_Children (parent, "ANIMFRAM") -{ - const char * buffer_ptr = data; - - while ((data-buffer_ptr)< (signed)size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed)size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - DynCreate(data); - data += *(int *)(data + 8); - } -} - - -Anim_Shape_Frame_Chunk::Anim_Shape_Frame_Chunk(Anim_Shape_Sequence_Chunk * const parent,ChunkAnimFrame* caf,int frameno) -: Chunk_With_Children (parent, "ANIMFRAM") -{ - new Anim_Shape_Frame_Data_Chunk(this,caf,frameno); - new Shape_Vertex_Chunk(this,caf->v_list,caf->num_verts); - new Shape_Polygon_Normal_Chunk(this,caf->p_normal_list,caf->num_polys); - -} -///////////////////////////////////////// - -// Class Anim_Shape_Sequence_Data_Chunk functions - -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("ANISEQDT",Anim_Shape_Sequence_Data_Chunk,"ANIMSEQU",Anim_Shape_Sequence_Chunk) - -Anim_Shape_Sequence_Data_Chunk::Anim_Shape_Sequence_Data_Chunk(Anim_Shape_Sequence_Chunk* const parent,const char* data,size_t const/*datasize*/) -: Chunk(parent, "ANISEQDT") -{ - SequenceNum=*(int*)data; - data+=4; - flags=*(int*)data; - data+=4; - pad2=*(int*)data; - data+=4; - pad3=*(int*)data; - data+=4; - pad4=*(int*)data; - data+=4; - name=new char[strlen(data)+1]; - strcpy(name,data); - -} - -Anim_Shape_Sequence_Data_Chunk::Anim_Shape_Sequence_Data_Chunk(Anim_Shape_Sequence_Chunk* const parent,ChunkAnimSequence* cas) -: Chunk(parent, "ANISEQDT") -{ - SequenceNum=cas->SequenceNum; - name=cas->name; - flags=cas->flags; - pad2=cas->pad2; - pad3=cas->pad3; - pad4=cas->pad4; - -} - -void Anim_Shape_Sequence_Data_Chunk::fill_data_block(char* datastart) -{ - strncpy (datastart, identifier, 8); - datastart += 8; - *((int *) datastart) = chunk_size; - datastart += 4; - - *(int*)datastart=SequenceNum; - datastart+=4; - *(int*)datastart=flags; - datastart+=4; - *(int*)datastart=pad2; - datastart+=4; - *(int*)datastart=pad3; - datastart+=4; - *(int*)datastart=pad4; - datastart+=4; - - strcpy(datastart,name ? name : ""); - -} - -size_t Anim_Shape_Sequence_Data_Chunk::size_chunk() -{ - return chunk_size = 12+20 - +(name ? strlen(name) : 0) - +3 +3&~3; -} - - -///////////////////////////////////////// - -// Class Anim_Shape_Frame_Data_Chunk functions -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("ANIFRADT",Anim_Shape_Frame_Data_Chunk,"ANIMFRAM",Anim_Shape_Frame_Chunk) - -Anim_Shape_Frame_Data_Chunk::Anim_Shape_Frame_Data_Chunk(Anim_Shape_Frame_Chunk* const parent,const char* data,size_t const /*datasize*/) -: Chunk(parent, "ANIFRADT") -{ - FrameNum=*(int*)data; - data+=4; - flags=*(int*)data; - data+=4; - num_interp_frames=*(int*)data; - data+=4; - pad3=*(int*)data; - data+=4; - pad4=*(int*)data; - data+=4; - name=new char[strlen(data)+1]; - strcpy(name,data); - -} - -Anim_Shape_Frame_Data_Chunk::Anim_Shape_Frame_Data_Chunk(Anim_Shape_Frame_Chunk* const parent,ChunkAnimFrame* caf,int frameno) -: Chunk(parent, "ANIFRADT") -{ - FrameNum=frameno; - name=caf->name; - flags=caf->flags; - num_interp_frames=caf->num_interp_frames; - pad3=caf->pad3; - pad4=caf->pad4; - -} - - -void Anim_Shape_Frame_Data_Chunk::fill_data_block(char* datastart) -{ - strncpy (datastart, identifier, 8); - datastart += 8; - *((int *) datastart) = chunk_size; - datastart += 4; - - *(int*)datastart=FrameNum; - datastart+=4; - *(int*)datastart=flags; - datastart+=4; - *(int*)datastart=num_interp_frames; - datastart+=4; - *(int*)datastart=pad3; - datastart+=4; - *(int*)datastart=pad4; - datastart+=4; - - strcpy(datastart,name ? name : ""); - -} - -size_t Anim_Shape_Frame_Data_Chunk::size_chunk() -{ - return chunk_size = 12+20 - +(name ? strlen(name) : 0) - +3 +3&~3; -} - -///////////////////////////////////////// - -// Class Anim_Shape_Alternate_Texturing_Chunk functions -RIF_IMPLEMENT_DYNCREATE("ASALTTEX",Anim_Shape_Alternate_Texturing_Chunk) - -/* -Children for Anim_Shape_Alternate_Texturing_Chunk : -"SUBSHAPE" Shape_Sub_Shape_Chunk -*/ - -Anim_Shape_Alternate_Texturing_Chunk::Anim_Shape_Alternate_Texturing_Chunk(Chunk_With_Children *const parent, const char *data, size_t const size) -: Chunk_With_Children (parent, "ASALTTEX") -{ - const char * buffer_ptr = data; - - while ((data-buffer_ptr)< (signed)size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed)size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - DynCreate(data); - data += *(int *)(data + 8); - } -} - -Shape_Sub_Shape_Chunk* Anim_Shape_Alternate_Texturing_Chunk::CreateNewSubShape(const char* name) -{ - if(!name) return 0; - //check to make sure that name isn't already in use - List<Chunk*> chlist; - lookup_child("SUBSHAPE",chlist); - for(LIF<Chunk*> chlif(& chlist);!chlif.done();chlif.next()) - { - Shape_Sub_Shape_Chunk* sssc=(Shape_Sub_Shape_Chunk*) chlif(); - if(!_stricmp(name,sssc->get_shape_name()))return 0; - } - ChunkShape cs; - if(!_stricmp(parent->identifier,"REBSHAPE")) - cs=((Shape_Chunk*)parent)->shape_data; - else if(!_stricmp(parent->identifier,"SUBSHAPE")) - cs=((Shape_Sub_Shape_Chunk*)parent)->shape_data; - else - return 0; - Shape_Sub_Shape_Chunk* sssc=new Shape_Sub_Shape_Chunk(this,cs); - new Shape_Name_Chunk(sssc,name); - - - //copy the texture animation data - Chunk_With_Children* anim_chunk=(Chunk_With_Children*)parent->lookup_single_child("TEXTANIM"); - if(anim_chunk) - { - char * tempbuffer = anim_chunk->make_data_block_from_chunk(); - sssc->DynCreate(tempbuffer); - delete [] tempbuffer; - - } - - Shape_Merge_Data_Chunk* smdc=(Shape_Merge_Data_Chunk*)parent->lookup_single_child("SHPMRGDT"); - if(smdc) - { - new Shape_Merge_Data_Chunk(sssc,smdc->merge_data,smdc->num_polys); - } - return sssc; - -} - -///////////////////////////////////////// - -// Class Poly_Not_In_Bounding_Box_Chunk functions -RIF_IMPLEMENT_DYNCREATE("PNOTINBB",Poly_Not_In_Bounding_Box_Chunk) - -Poly_Not_In_Bounding_Box_Chunk::Poly_Not_In_Bounding_Box_Chunk(Chunk_With_Children* const parent,const char* data,size_t const datasize) -:Chunk(parent,"PNOTINBB") -{ - for(int i=0;i<( ( (signed)datasize ) /4)-2;i++) - { - poly_no.add_entry(*(int*)data); - data+=4; - } - pad1=*(int*)data; - data+=4; - pad2=*(int*)data; - -} - -Poly_Not_In_Bounding_Box_Chunk::Poly_Not_In_Bounding_Box_Chunk(Chunk_With_Children* const parent) -:Chunk(parent,"PNOTINBB") -{ - pad1=pad2=0; -} - -size_t Poly_Not_In_Bounding_Box_Chunk::size_chunk() -{ - return chunk_size=(20+4*poly_no.size()); -} - -void Poly_Not_In_Bounding_Box_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - for(LIF<int> plif(&poly_no);!plif.done();plif.next()) - { - *(int*)data_start=plif(); - data_start+=4; - } - *(int*)data_start=pad1; - data_start+=4; - *(int*)data_start=pad2; -} - - -///////////////////////////////////////// - -// Class Anim_Shape_Centre_Chunk functions - -RIF_IMPLEMENT_DYNCREATE("ANSHCEN2",Anim_Shape_Centre_Chunk) - -Anim_Shape_Centre_Chunk::Anim_Shape_Centre_Chunk(Chunk_With_Children* const parent,const char* data,size_t const /*datasize*/) -:Chunk(parent,"ANSHCEN2") -{ - Centre=*(ChunkVectorInt*)data; - data+=sizeof(ChunkVectorInt); - flags=*(int*)data; - data+=4; - pad2=*(int*)data; - -} - -Anim_Shape_Centre_Chunk::Anim_Shape_Centre_Chunk(Chunk_With_Children* const parent) -:Chunk(parent,"ANSHCEN2") -{ - Centre.x=0; - Centre.y=0; - Centre.z=0; - flags=pad2=0; -} - -size_t Anim_Shape_Centre_Chunk::size_chunk() -{ - return chunk_size=(20+sizeof(ChunkVectorInt)); -} - -void Anim_Shape_Centre_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(ChunkVectorInt*)data_start=Centre; - data_start+=sizeof(ChunkVectorInt); - *(int*)data_start=flags; - data_start+=4; - *(int*)data_start=pad2; - -} - - - -///////////////////////////////////////// - -// Class Console_Shape_Chunk functions - -/* -Children for Console_Shape_Chunk : - -"SHPPOLYS" Shape_Polygon_Chunk -"SHPUVCRD" Shape_UV_Coord_Chunk -"TEXTANIM" Animation_Chunk - -"CONSTYPE" Console_Type_Chunk -*/ - - -Console_Shape_Chunk::Console_Shape_Chunk(Chunk_With_Children * const parent, const char *data, size_t size) -: Chunk_With_Children (parent, "CONSHAPE") -{ - - shape_data_store=(ChunkShape*)&shape_data; - - const char * buffer_ptr = data; - - while ((data-buffer_ptr)< (signed)size) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed)size) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - - DynCreate(data); - data += *(int *)(data + 8); - } - } - -} - -Console_Shape_Chunk::Console_Shape_Chunk(Chunk_With_Children* const parent,Console_Type ct) -:Chunk_With_Children(parent,"CONSHAPE") -{ - shape_data_store=(ChunkShape*)&shape_data; - new Console_Type_Chunk(this,ct); -} -void Console_Shape_Chunk::generate_console_chunkshape() -{ - //sort out the chunkshape - if(!strcmp(parent->identifier,"REBSHAPE")) - { - *shape_data_store=((Shape_Chunk*)parent)->shape_data; - } - else if(!strcmp(parent->identifier,"SUBSHAPE")) - { - *shape_data_store=((Shape_Sub_Shape_Chunk*)parent)->shape_data; - } - else - { - delete this; - return; - } - - Shape_Polygon_Chunk* spc=(Shape_Polygon_Chunk*)lookup_single_child("SHPPOLYS"); - if(spc) - { - if(spc->num_polys!=shape_data_store->num_polys) - { - //console shape is no longer valid.kill it. - delete this; - return; - } - - ChunkPoly* poly_list=shape_data_store->poly_list; - shape_data_store->poly_list=(ChunkPoly*)spc->poly_data; - for(int i=0;i<shape_data_store->num_polys;i++) - { - for(int j=0;j<4;j++) - { - shape_data_store->poly_list[i].vert_ind[j]=poly_list[i].vert_ind[j]; - } - } - delete [] poly_list; - } - Shape_UV_Coord_Chunk* succ=(Shape_UV_Coord_Chunk*)lookup_single_child("SHPUVCRD"); - if(succ) - { - delete [] shape_data_store->uv_list; - shape_data_store->uv_list=(ChunkUV_List*)succ->uv_data; - shape_data_store->num_uvs=succ->num_uvs; - } -} - -void Console_Shape_Chunk::update_my_chunkshape(ChunkShape & cshp) -{ - List<Chunk*> chlist; - lookup_child("SHPUVCRD",chlist); - while(chlist.size()) - { - delete chlist.first_entry(); - chlist.delete_first_entry(); - } - lookup_child("SHPPOLYS",chlist); - while(chlist.size()) - { - delete chlist.first_entry(); - chlist.delete_first_entry(); - } - *shape_data_store=cshp; - if (shape_data.poly_list) new Shape_Polygon_Chunk (this, shape_data.num_polys); - if (shape_data.uv_list) new Shape_UV_Coord_Chunk (this, shape_data.num_uvs); - -} - - -///////////////////////////////////////// - -// Class Console_Type_Chunk functions -RIF_IMPLEMENT_DYNCREATE("CONSTYPE",Console_Type_Chunk) - -void Console_Type_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(int*)data_start=(int)console; -} - - -///////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SHPPRPRO",Shape_Preprocessed_Data_Chunk) - -Shape_Preprocessed_Data_Chunk::Shape_Preprocessed_Data_Chunk (Chunk_With_Children * parent, const char * data, size_t ) -:Chunk(parent,"SHPPRPRO") -{ - block_size=*(int*)data; - data+=4; - first_pointer=*(int*)data; - data+=4; - - if(block_size) - { - memory_block=new unsigned int[block_size]; - memcpy(memory_block,data,block_size*4); - data+=block_size*4; - } - else - { - memory_block=0; - } - - num_extra_data=*(int*)data; - data+=4; - - if(num_extra_data) - { - extra_data=new int[num_extra_data]; - memcpy(extra_data,data,num_extra_data*4); - } - else - { - extra_data=0; - } -} - -Shape_Preprocessed_Data_Chunk::Shape_Preprocessed_Data_Chunk (Chunk_With_Children * parent,int _block_size,int _first_pointer,unsigned int* _memory_block) -:Chunk(parent,"SHPPRPRO") -{ - num_extra_data=0; - extra_data=0; - block_size=_block_size; - first_pointer=_first_pointer; - - if(block_size) - { - memory_block=new unsigned int[block_size]; - memcpy(memory_block,_memory_block,block_size*4); - } - else - { - memory_block=0; - } - -} - -void Shape_Preprocessed_Data_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(int*)data_start=block_size; - data_start+=4; - *(int*)data_start=first_pointer; - data_start+=4; - - memcpy(data_start,memory_block,4*block_size); - data_start+=4*block_size; - - *(int*)data_start=num_extra_data; - data_start+=4; - memcpy(data_start,extra_data,4*num_extra_data); -} - -void* Shape_Preprocessed_Data_Chunk::GetMemoryBlock() -{ - void* retval=memory_block; - - unsigned int* current=(unsigned int*)&first_pointer; - unsigned int* next; - while((*current>>16)!=0xffff) - { - next=&memory_block[(*current)>>16]; - *current=(unsigned int)&memory_block[(*current)&0xffff]; - current=next; - } - *current=(unsigned int)&memory_block[(*current)&0xffff]; - - memory_block=0; - block_size=0; - return retval; -} - diff --git a/3dc/win95/SHPCHUNK.HPP b/3dc/win95/SHPCHUNK.HPP deleted file mode 100644 index 1529d19..0000000 --- a/3dc/win95/SHPCHUNK.HPP +++ /dev/null @@ -1,1095 +0,0 @@ -#ifndef _shpchunk_hpp -#define _shpchunk_hpp 1 - -#include "chunk.hpp" - -#include "chnktype.hpp" -#include "mishchnk.hpp" - -// shape flags - -#define SHAPE_FLAG_PALETTISED 0x0000100 -#define SHAPE_FLAG_USEZSP 0x0000200 -#define SHAPE_FLAG_USEAUGZS 0x0000400 -#define SHAPE_FLAG_USEAUGZSL 0x0000800 -#define SHAPE_FLAG_EXTERNALFILE 0x0001000 -#define SHAPE_FLAG_RECENTRED 0x0002000 - - -#define SHAPE_FLAG_UNSTABLEBOUND_ZPOS 0x00004000 -#define SHAPE_FLAG_UNSTABLEBOUND_ZNEG 0x00008000 -#define SHAPE_FLAG_UNSTABLEBOUND_YPOS 0x00010000 -#define SHAPE_FLAG_UNSTABLEBOUND_YNEG 0x00020000 -#define SHAPE_FLAG_UNSTABLEBOUND_XPOS 0x00040000 -#define SHAPE_FLAG_UNSTABLEBOUND_XNEG 0x00080000 - -#define SHAPE_FLAG_PSX_SUBDIVIDE 0x80000000 - -//flags that need to be removed before being copied into the shapeheaders -#define ChunkInternalItemFlags 0x00000000 - -class Object_Chunk; -class Shape_Header_Chunk; -class Anim_Shape_Frame_Chunk; -class Console_Shape_Chunk; -// flags structure - -struct shape_flags -{ - unsigned int locked : 1; -// add more flags here as they are needed -}; - -enum Console_Type -{ - CT_PSX=0, - CT_Saturn=1, - - // IMPORTANT - // since enums are not guaranteed to assume any particular - // storage class, code compiled on different compilers or - // with different settings may result in enums to be written - // to the data block as a char and read back in as an int, - // with the three most significant bytes containing junk. - // THIS MASK MUST BE KEPT UP TO DATE AS THE ENUM IS EXTENDED; - // ALSO ENSURE THAT NEW FILES LOADED INTO OLD SOFTWARE WILL - // NOT HAVE THEIR ENUM VALUE OVER-MASKED; THE MASK IS ONLY - // HERE TO ATTEMPT TO REMOVE PROBLEMS FROM FILES MADE - // PRIOR TO ITS INTRODUCTION - CT_MASK=0xff -}; - -// The shape chunk contains and handles all the interface data for the -// child chunks that it recognises in ChunkShape - -/*--------------------------------------------------------------------** -** N.B. all changes to shape formats should be made to the sub shapes ** -**--------------------------------------------------------------------*/ - -class Shape_Chunk : public Lockable_Chunk_With_Children -{ -public: - - // constructor from buffer - Shape_Chunk (Chunk_With_Children * parent, const char *, size_t); - - // constructor from data (public so that other shape tools can call) - Shape_Chunk (Chunk_With_Children * parent, ChunkShape &shp_dat); - - // I want the external file load to be as transparent as possible - // i.e. we have a shape which is loaded as usaul - it should then - // load the shape which is its main copy and copy itself over !!! - - // Problems will be encountered with the texturing data though - - // but this stuff should onyl be worked with with a hardware - // accelerator - so that should solve many of the problems - - // destructor - virtual ~Shape_Chunk(); - - const ChunkShape shape_data; - - Shape_Header_Chunk * get_header(); - - Shape_Chunk* make_copy_of_chunk(); - - List<Object_Chunk *> const & list_assoc_objs(); - - BOOL assoc_with_object(Object_Chunk *); - - BOOL deassoc_with_object(Object_Chunk *); - - // destroy all auxiliary chunks - // that is all except the header and the chunkshape - void destroy_auxiliary_chunks(); - - // functions for the locking functionality - - BOOL file_equals (HANDLE &); - const char * get_head_id(); - void set_lock_user(char *); - - virtual void post_input_processing(); - - Console_Shape_Chunk* get_console_shape_data(Console_Type); - - BOOL inc_v_no(); - - BOOL same_and_updated(Shape_Chunk &); - - BOOL assoc_with_object_list(File_Chunk *); - - BOOL update_my_chunkshape (ChunkShape & cshp); - - // THIS IS A HACK, DO NOT USE AFTER AVP AUGUST DEMO - - BOOL has_door; - -private: - - friend class Object_Chunk; - friend class Shape_Vertex_Chunk; - friend class Shape_Vertex_Normal_Chunk; - friend class Shape_Polygon_Normal_Chunk; - friend class Shape_Polygon_Chunk; - friend class Shape_Texture_Filenames_Chunk; - friend class Shape_UV_Coord_Chunk; - friend class Shape_Header_Chunk; - friend class Shape_External_File_Chunk; - friend class RIF_File_Chunk; - friend class File_Chunk; - friend class Shape_Centre_Chunk; - - ChunkShape * shape_data_store; - - static int max_id; // for id checking - -}; - -/////////////////////////////////////////////// - -class Shape_Sub_Shape_Header_Chunk; - -class Shape_Sub_Shape_Chunk : public Chunk_With_Children -{ -public: - - // constructor from buffer - Shape_Sub_Shape_Chunk (Chunk_With_Children * parent, const char *, size_t); - - // constructor from data (public so that other shape tools can call) - Shape_Sub_Shape_Chunk (Chunk_With_Children * parent, ChunkShape &shp_dat); - - // destructor - virtual ~Shape_Sub_Shape_Chunk(); - - const ChunkShape shape_data; - - Shape_Sub_Shape_Header_Chunk * get_header(); - - Shape_Sub_Shape_Chunk* make_copy_of_chunk(); - - BOOL update_my_chunkshape (ChunkShape & cshp); - - const char * get_shape_name(); - - Console_Shape_Chunk* get_console_shape_data(Console_Type); - - // Number stored for list_pos when loading - - int list_pos_number; - -private: - - friend class Shape_Vertex_Chunk; - friend class Shape_Vertex_Normal_Chunk; - friend class Shape_Polygon_Normal_Chunk; - friend class Shape_Polygon_Chunk; - friend class Shape_Texture_Filenames_Chunk; - friend class Shape_UV_Coord_Chunk; - friend class Shape_Sub_Shape_Header_Chunk; - friend class Shape_Centre_Chunk; - - ChunkShape * shape_data_store; - -}; - -/////////////////////////////////////////////// - -class Shape_Sub_Shape_Header_Chunk : public Chunk -{ -public: - // constructor from buffer - Shape_Sub_Shape_Header_Chunk (Shape_Sub_Shape_Chunk * parent, const char * pdata, size_t psize); - - ~Shape_Sub_Shape_Header_Chunk(); - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - const ChunkShape * const shape_data; - - int file_id_num; - - int flags; - -private: - - friend class Shape_Sub_Shape_Chunk; - friend class Shape_Morphing_Frame_Data_Chunk; - - - - // constructor from data - Shape_Sub_Shape_Header_Chunk (Shape_Sub_Shape_Chunk * parent) - : Chunk (parent, "SUBSHPHD"), - shape_data (parent->shape_data_store), - flags (0), file_id_num (-1) - {} - -}; - - -/////////////////////////////////////////////// -#define AnimCentreFlag_CentreSetByUser 0x00000001 //centre should not be recalculated from the extents of the sequences - -class Anim_Shape_Centre_Chunk : public Chunk -{ - public: - Anim_Shape_Centre_Chunk(Chunk_With_Children* const parent,const char*,size_t const); - Anim_Shape_Centre_Chunk(Chunk_With_Children* const parent); - - ChunkVectorInt Centre; - int flags; - int pad2; - - virtual void fill_data_block(char* data_start); - virtual size_t size_chunk(); -}; -/////////////////////////////////////////////// -class Anim_Shape_Sequence_Chunk :public Chunk_With_Children -{ - public: -//if the first constructor is used then the vertex normals and extents won't be calculated -//unless the post_input_processing function is called - Anim_Shape_Sequence_Chunk(Chunk_With_Children* const parent,const char*,size_t const); - Anim_Shape_Sequence_Chunk(Chunk_With_Children* const parent,int sequencenum,const char* name); - Anim_Shape_Sequence_Chunk(Chunk_With_Children* const parent,ChunkAnimSequence const* cas); - - virtual void post_input_processing(); - - const ChunkAnimSequence sequence_data; - - void update_my_sequencedata (ChunkAnimSequence &); - - void set_sequence_flags(int flags); - void set_frame_flags(int frameno,int flags); - - void GenerateInterpolatedFrames(); - - private : - ChunkAnimSequence *sequence_data_store; - - int ConstructSequenceDataFromChildren();//copies everyting into the sequence_data - void RegenerateChildChunks(); -}; - -/////////////////////////////////////////////// -class Anim_Shape_Sequence_Data_Chunk:public Chunk -{ - public: - Anim_Shape_Sequence_Data_Chunk(Anim_Shape_Sequence_Chunk* const parent,const char*,size_t const); - Anim_Shape_Sequence_Data_Chunk(Anim_Shape_Sequence_Chunk* const parent,ChunkAnimSequence* cas); - - private: - friend class Anim_Shape_Sequence_Chunk; - - int SequenceNum; - int flags,pad2,pad3,pad4; - char* name; - - virtual size_t size_chunk(); - - virtual void fill_data_block(char* data_start); -}; - -/////////////////////////////////////////////// -class Anim_Shape_Frame_Chunk : public Chunk_With_Children -{ - public: - Anim_Shape_Frame_Chunk(Anim_Shape_Sequence_Chunk* const parent,const char*,size_t const); - Anim_Shape_Frame_Chunk(Anim_Shape_Sequence_Chunk * const parent,ChunkAnimFrame* caf,int frameno); -}; - -/////////////////////////////////////////////// -class Anim_Shape_Frame_Data_Chunk : public Chunk -{ - public: - Anim_Shape_Frame_Data_Chunk(Anim_Shape_Frame_Chunk* const parent,const char*,size_t const); - Anim_Shape_Frame_Data_Chunk(Anim_Shape_Frame_Chunk* const parent,ChunkAnimFrame* caf,int frameno); - - private: - friend class Anim_Shape_Frame_Chunk; - friend class Anim_Shape_Sequence_Chunk; - - int FrameNum; - int flags,num_interp_frames,pad3,pad4; - char* name;//name of asc file for frame - - virtual size_t size_chunk(); - - virtual void fill_data_block(char* data_start); -}; -/////////////////////////////////////////////// -class Anim_Shape_Alternate_Texturing_Chunk : public Chunk_With_Children -{ - public : - Anim_Shape_Alternate_Texturing_Chunk(Chunk_With_Children* const parent,const char*,size_t const); - Anim_Shape_Alternate_Texturing_Chunk(Chunk_With_Children* const parent) - :Chunk_With_Children(parent,"ASALTTEX") - {} - - Shape_Sub_Shape_Chunk* CreateNewSubShape(const char* name); -}; -/////////////////////////////////////////////// -class Poly_Not_In_Bounding_Box_Chunk : public Chunk -{ - public : - Poly_Not_In_Bounding_Box_Chunk(Chunk_With_Children* const parent,const char*,size_t const); - Poly_Not_In_Bounding_Box_Chunk(Chunk_With_Children* const parent); - - virtual size_t size_chunk(); - - virtual void fill_data_block(char* data_start); - - - List<int> poly_no; - int pad1,pad2; -}; -/////////////////////////////////////////////// - -class Console_Type_Chunk: public Chunk -{ - public : - Console_Type_Chunk(Chunk_With_Children* const parent,const char* data,size_t) - :Chunk(parent,"CONSTYPE"),console((Console_Type)(*(int*)data & CT_MASK)) - {} - Console_Type_Chunk(Chunk_With_Children* const parent,Console_Type ct) - :Chunk(parent,"CONSTYPE"),console(ct) - {} - - Console_Type console; - - virtual size_t size_chunk() - {return chunk_size=16;} - - virtual void fill_data_block(char * data_start); -}; -/////////////////////////////////////////////// -class Console_Shape_Chunk : public Chunk_With_Children -{ - public : - Console_Shape_Chunk(Chunk_With_Children* const parent,const char*,size_t); - Console_Shape_Chunk(Chunk_With_Children* const parent,Console_Type ct); - - const ChunkShape shape_data; - - void generate_console_chunkshape();//needs parent's chunkshape to be set up first - - void update_my_chunkshape(ChunkShape&); - private: - friend class Shape_Polygon_Chunk; - friend class Shape_UV_Coord_Chunk; - ChunkShape * shape_data_store; -}; -/////////////////////////////////////////////// - -class Shape_Vertex_Chunk : public Chunk -{ -public: - - - virtual size_t size_chunk () - { - return (chunk_size = (12 + (num_verts*sizeof(ChunkVectorInt)))); - } - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - const ChunkVectorInt * const vert_data; - - const int num_verts; - - // constructor from buffer - Shape_Vertex_Chunk (Shape_Sub_Shape_Chunk * parent, const char * vtdata, size_t vtsize); - Shape_Vertex_Chunk (Shape_Chunk * parent, const char * vtdata, size_t vtsize); - Shape_Vertex_Chunk (Anim_Shape_Frame_Chunk * parent, const char * vtdata, size_t vtsize); -private: - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - friend class Anim_Shape_Frame_Chunk; - - - // constructor from data - Shape_Vertex_Chunk (Shape_Sub_Shape_Chunk * parent, int n_verts) - : Chunk (parent, "SHPRAWVT"), - vert_data (parent->shape_data_store->v_list), num_verts (n_verts) - {} - - Shape_Vertex_Chunk (Shape_Chunk * parent, int n_verts) - : Chunk (parent, "SHPRAWVT"), - vert_data (parent->shape_data_store->v_list), num_verts (n_verts) - {} - - Shape_Vertex_Chunk (Anim_Shape_Frame_Chunk * parent,ChunkVectorInt* v_list ,int n_verts) - : Chunk (parent, "SHPRAWVT"), - vert_data (v_list), num_verts (n_verts) - {} - -}; - - -/////////////////////////////////////////////// - -class Shape_Vertex_Normal_Chunk: public Chunk -{ -public: - // constructor from buffer - Shape_Vertex_Normal_Chunk (Shape_Sub_Shape_Chunk * parent, const char * vtdata, size_t vtsize); - Shape_Vertex_Normal_Chunk (Shape_Chunk * parent, const char * vtdata, size_t vtsize); - - virtual size_t size_chunk () - { - return (chunk_size = (12 + (num_verts*sizeof(ChunkVectorFloat)))); - } - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - const ChunkVectorFloat * const vert_norm_data; - - const int num_verts; - -private: - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - - - // constructor from data - Shape_Vertex_Normal_Chunk (Shape_Sub_Shape_Chunk * parent, int n_verts) - : Chunk (parent, "SHPVNORM"), - vert_norm_data (parent->shape_data_store->v_normal_list), num_verts (n_verts) - {} - - Shape_Vertex_Normal_Chunk (Shape_Chunk * parent, int n_verts) - : Chunk (parent, "SHPVNORM"), - vert_norm_data (parent->shape_data_store->v_normal_list), num_verts (n_verts) - {} - -}; - - -/////////////////////////////////////////////// - -class Shape_Polygon_Normal_Chunk: public Chunk -{ -public: - // constructor from buffer - Shape_Polygon_Normal_Chunk (Shape_Sub_Shape_Chunk * parent, const char * pndata, size_t pnsize); - Shape_Polygon_Normal_Chunk (Shape_Chunk * parent, const char * pndata, size_t pnsize); - Shape_Polygon_Normal_Chunk (Anim_Shape_Frame_Chunk * parent, const char * pndata, size_t pnsize); - - virtual size_t size_chunk () - { - return (chunk_size = (12 + (num_polys*sizeof(ChunkVectorFloat)))); - } - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - const ChunkVectorFloat * const poly_norm_data; - - const int num_polys; - -private: - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - friend class Anim_Shape_Frame_Chunk; - - - - // constructor from data - Shape_Polygon_Normal_Chunk (Shape_Sub_Shape_Chunk * parent, int n_polys) - : Chunk (parent, "SHPPNORM"), - poly_norm_data (parent->shape_data_store->p_normal_list), num_polys (n_polys) - {} - - Shape_Polygon_Normal_Chunk (Shape_Chunk * parent, int n_polys) - : Chunk (parent, "SHPPNORM"), - poly_norm_data (parent->shape_data_store->p_normal_list), num_polys (n_polys) - {} - - Shape_Polygon_Normal_Chunk (Anim_Shape_Frame_Chunk * parent,ChunkVectorFloat* p_normal_list ,int n_polys) - : Chunk (parent, "SHPPNORM"), - poly_norm_data (p_normal_list), num_polys (n_polys) - {} - -}; - - -/////////////////////////////////////////////// - -class Shape_Polygon_Chunk : public Chunk -{ -public: - // constructor from buffer - Shape_Polygon_Chunk (Shape_Sub_Shape_Chunk * parent, const char * pdata, size_t psize); - Shape_Polygon_Chunk (Shape_Chunk * parent, const char * pdata, size_t psize); - Shape_Polygon_Chunk (Console_Shape_Chunk * parent, const char * pdata, size_t psize); - - virtual size_t size_chunk () - { - return (chunk_size = (12 + (num_polys*36)));// 36 bytes per vertex - } - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - const ChunkPoly * const poly_data; - - const int num_polys; - -private: - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - friend class Console_Shape_Chunk; - - - - // constructor from data - Shape_Polygon_Chunk (Shape_Sub_Shape_Chunk * parent, int n_polys) - : Chunk (parent, "SHPPOLYS"), - poly_data (parent->shape_data_store->poly_list), num_polys (n_polys) - {} - - Shape_Polygon_Chunk (Shape_Chunk * parent, int n_polys) - : Chunk (parent, "SHPPOLYS"), - poly_data (parent->shape_data_store->poly_list), num_polys (n_polys) - {} - - Shape_Polygon_Chunk (Console_Shape_Chunk * parent, int n_polys) - : Chunk (parent, "SHPPOLYS"), - poly_data (parent->shape_data_store->poly_list), num_polys (n_polys) - {} - -}; - -/////////////////////////////////////////////// - -class Shape_Header_Chunk : public Chunk -{ -public: - // constructor from buffer - Shape_Header_Chunk (Shape_Chunk * parent, const char * pdata, size_t psize); - - ~Shape_Header_Chunk(); - - virtual size_t size_chunk (); - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - const ChunkShape * const shape_data; - - virtual void prepare_for_output(); - - char lock_user[17]; - - List<char *> object_names_store; - - int flags; - -private: - - friend class Shape_Chunk; - friend class Object_Chunk; - friend class RIF_File_Chunk; - friend class File_Chunk; - friend class Environment; - friend class Shape_Morphing_Frame_Data_Chunk; - friend class Shape_External_File_Chunk; - - int version_no; - - int file_id_num; - - List<Object_Chunk *> associated_objects_store; - - - - // constructor from data - Shape_Header_Chunk (Shape_Chunk * parent) - : Chunk (parent, "SHPHEAD1"), - shape_data (parent->shape_data_store), - flags (0), file_id_num (-1), version_no (0) - {} - -}; -/////////////////////////////////////////////// -class Shape_Centre_Chunk : public Chunk -{ -public : - // constructor from buffer - Shape_Centre_Chunk (Chunk_With_Children * parent, const char * data, size_t datasize); - - virtual size_t size_chunk () - {return chunk_size=4*4+12;} - - virtual void fill_data_block (char * data_start); - -private: - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - - - // constructor from data - Shape_Centre_Chunk (Chunk_With_Children * parent) - : Chunk (parent, "SHPCENTR") - {} - - //the data for this chunk is stored in its parent's ChunkShape -}; -/////////////////////////////////////////////// - -class Shape_UV_Coord_Chunk : public Chunk -{ -public: - // constructor from buffer - Shape_UV_Coord_Chunk (Shape_Sub_Shape_Chunk * parent, const char * uvdata, size_t uvsize); - Shape_UV_Coord_Chunk (Shape_Chunk * parent, const char * uvdata, size_t uvsize); - Shape_UV_Coord_Chunk (Console_Shape_Chunk * parent, const char * uvdata, size_t uvsize); - - virtual size_t size_chunk (); - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - const ChunkUV_List * const uv_data; - - const int num_uvs; - -private: - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - friend class Console_Shape_Chunk; - - - // constructor from data - Shape_UV_Coord_Chunk (Shape_Sub_Shape_Chunk * parent, int n_uvs) - : Chunk (parent, "SHPUVCRD"), - uv_data (parent->shape_data_store->uv_list), num_uvs (n_uvs) - {} - - Shape_UV_Coord_Chunk (Shape_Chunk * parent, int n_uvs) - : Chunk (parent, "SHPUVCRD"), - uv_data (parent->shape_data_store->uv_list), num_uvs (n_uvs) - {} - - Shape_UV_Coord_Chunk (Console_Shape_Chunk * parent, int n_uvs) - : Chunk (parent, "SHPUVCRD"), - uv_data (parent->shape_data_store->uv_list), num_uvs (n_uvs) - {} - -}; - -/////////////////////////////////////////////// - -class Shape_Texture_Filenames_Chunk : public Chunk -{ -public: - // constructor from buffer - Shape_Texture_Filenames_Chunk (Shape_Sub_Shape_Chunk * parent, const char * tfndata, size_t tfnsize); - Shape_Texture_Filenames_Chunk (Shape_Chunk * parent, const char * tfndata, size_t tfnsize); - - virtual size_t size_chunk (); - - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - char ** tex_fns; - - const int num_tex_fns; - -private: - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - - - // constructor from data - Shape_Texture_Filenames_Chunk (Shape_Sub_Shape_Chunk * parent, int n_tfns) - : Chunk (parent, "SHPTEXFN"), - tex_fns (parent->shape_data_store->texture_fns), num_tex_fns (n_tfns) - {} - - Shape_Texture_Filenames_Chunk (Shape_Chunk * parent, int n_tfns) - : Chunk (parent, "SHPTEXFN"), - tex_fns (parent->shape_data_store->texture_fns), num_tex_fns (n_tfns) - {} - - -}; - - - -/////////////////////////////////////////////// - -class Shape_Merge_Data_Chunk : public Chunk -{ -public: - - Shape_Merge_Data_Chunk (Shape_Sub_Shape_Chunk * parent, int *, int); - Shape_Merge_Data_Chunk (Shape_Chunk * parent, int *, int); - - ~Shape_Merge_Data_Chunk (); - - int * merge_data; - int num_polys; - - size_t size_chunk() - { - return chunk_size = 12 + num_polys*4; - } - - void fill_data_block (char *); - - Shape_Merge_Data_Chunk (Shape_Sub_Shape_Chunk * parent, const char *, size_t); - Shape_Merge_Data_Chunk (Shape_Chunk * parent, const char *, size_t); - -}; - - -/////////////////////////////////////////////// - -class Shape_External_File_Chunk : public Chunk_With_Children -{ -public: - - Shape_External_File_Chunk (Chunk_With_Children * parent, const char * fname); - Shape_External_File_Chunk (Chunk_With_Children * const parent, const char *, size_t const); - - void post_input_processing(); - - #if cencon || InterfaceEngine - void update_from_external_rif(BOOL force_scale_update); - #endif - - //gets name from shape_external_object_name_chunk if it has one - //otherwise takes name from rif_name_chunk - const char * get_shape_name(); -private: - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - - //Used to avoid updating external shapes in files that have been loaded - //by Shape_External_File_Chunk::post_input_processing - static BOOL UpdatingExternalShape; - -}; - - -/////////////////////////////////////////////// - - -class Shape_External_Filename_Chunk : public Chunk -{ -public: - - Shape_External_Filename_Chunk (Chunk_With_Children * parent, const char * fname); - Shape_External_Filename_Chunk (Chunk_With_Children * parent, const char *, size_t); - ~Shape_External_Filename_Chunk (); - - // Here is stored the shape name, rescale value and version number. - - char * file_name; - - double rescale; - - int version_no; - - size_t size_chunk() - { - return chunk_size = 12 + 8 + 4 + strlen(file_name) + (4-strlen(file_name)%4); - } - - void fill_data_block (char *); - - -private: - - friend class Shape_External_File_Chunk; - friend class Sprite_Header_Chunk; - - -}; - - - -/////////////////////////////////////////////// - -//This is needed if more than one shape is being imported from a rif file -class Shape_External_Object_Name_Chunk : public Chunk -{ -public : - Shape_External_Object_Name_Chunk(Chunk_With_Children * parent, const char * fname); - Shape_External_Object_Name_Chunk (Chunk_With_Children * parent, const char *, size_t); - ~Shape_External_Object_Name_Chunk(); - - int pad; - char* object_name; - char* shape_name; //a combination of object and file name - size_t size_chunk() - { - return chunk_size = 12 +4+ strlen(object_name) + (4-strlen(object_name)%4); - } - - void post_input_processing(); - - void fill_data_block (char *); - -private: - - friend class Shape_External_File_Chunk; - -}; - -/////////////////////////////////////////////// - -class Shape_Morphing_Data_Chunk : public Chunk_With_Children -{ -public: - - Shape_Morphing_Data_Chunk (Shape_Chunk * parent) - : Chunk_With_Children (parent, "SHPMORPH"), parent_shape (parent) {} - - Shape_Chunk * parent_shape; - Shape_Sub_Shape_Chunk * parent_sub_shape; - - virtual void prepare_for_output(); - - Shape_Morphing_Data_Chunk (Shape_Chunk * parent, const char *, size_t); - Shape_Morphing_Data_Chunk (Shape_Sub_Shape_Chunk * parent, const char *, size_t); - -}; - - -/////////////////////////////////////////////// - -class Shape_Morphing_Frame_Data_Chunk : public Chunk -{ -public: - - // constructor from wherever - Shape_Morphing_Frame_Data_Chunk (Shape_Morphing_Data_Chunk * parent) - : Chunk (parent, "FRMMORPH"), frame_store (0), num_frames(0) - {} - // constructor from buffer - Shape_Morphing_Frame_Data_Chunk (Shape_Morphing_Data_Chunk * parent,const char *, size_t); - - ~Shape_Morphing_Frame_Data_Chunk(); - - int a_flags; - int a_speed; - - List<a_frame *> anim_frames; - - virtual void fill_data_block (char *); - virtual size_t size_chunk () - { - return (chunk_size = 12 + 12 + num_frames * 12); - } - - virtual void prepare_for_output(); - virtual void post_input_processing(); - -private: - - int num_frames; - int * frame_store; - - friend class Shape_Morphing_Data_Chunk; - - -}; - -/////////////////////////////////////////////// - -class Shape_Poly_Change_Info_Chunk : public Chunk -{ -public: - - Shape_Poly_Change_Info_Chunk (Shape_Chunk * parent, List<poly_change_info> & pci, int orig_num_v) - : Chunk (parent, "SHPPCINF"), change_list (pci), original_num_verts (orig_num_v) - {} - - int original_num_verts; - List<poly_change_info> change_list; - - virtual void fill_data_block (char *); - virtual size_t size_chunk () - { - return (chunk_size = 12 + 4 + 4 + change_list.size() * 12); - } - - Shape_Poly_Change_Info_Chunk (Chunk_With_Children * parent,const char *, size_t); -}; - -/////////////////////////////////////////////// - -class Shape_Name_Chunk : public Chunk -{ -public: - Shape_Name_Chunk (Chunk_With_Children * parent, const char * rname); - // constructor from buffer - Shape_Name_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize); - ~Shape_Name_Chunk(); - - char * shape_name; - - virtual size_t size_chunk () - { - return (chunk_size = 12 + strlen (shape_name) + 4 - strlen (shape_name)%4); - } - - virtual void fill_data_block (char * data_start); - -private: - - friend class Shape_Sub_Shape_Chunk; - -}; - -/////////////////////////////////////////////// - -class Shape_Fragments_Chunk : public Chunk_With_Children -{ -public: - - Shape_Fragments_Chunk (Chunk_With_Children * parent) - : Chunk_With_Children (parent, "SHPFRAGS") - {} - - Shape_Fragments_Chunk (Chunk_With_Children * const parent, char const *, const size_t); - -}; - -/////////////////////////////////////////////// -class Shape_Fragment_Type_Chunk : public Chunk -{ -public : - Shape_Fragment_Type_Chunk(Chunk_With_Children* parent,const char* name); - Shape_Fragment_Type_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - ~Shape_Fragment_Type_Chunk(); - - size_t size_chunk (); - void fill_data_block (char * data_start); - - char* frag_type_name; - int pad1,pad2; - - - -}; -/////////////////////////////////////////////// - -class Shape_Fragments_Data_Chunk : public Chunk -{ -public: - - Shape_Fragments_Data_Chunk (Chunk_With_Children * parent, int num_frags) - : Chunk (parent, "FRAGDATA"), num_fragments (num_frags), - pad1(0), pad2(0), pad3(0) - {} - Shape_Fragments_Data_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize); - - int num_fragments; - - int pad1, pad2, pad3; - - virtual size_t size_chunk () - { - return (chunk_size = 12 + 16); - } - - virtual void fill_data_block (char *); - -private: - - friend class Shape_Sub_Shape_Chunk; - - -}; - -/////////////////////////////////////////////// - -class Shape_Fragment_Location_Chunk : public Chunk -{ -public: - - Shape_Fragment_Location_Chunk (Chunk_With_Children * parent, ChunkVectorInt & location) - : Chunk (parent, "FRAGLOCN"), frag_loc (location), - pad1(0), pad2(0), pad3(0), pad4(0) - {} - Shape_Fragment_Location_Chunk (Chunk_With_Children * parent, const char * sdata, size_t ssize); - - ChunkVectorInt frag_loc; - - int pad1, pad2, pad3, pad4; - - virtual size_t size_chunk () - { - return (chunk_size = 12 + 28); - } - - virtual void fill_data_block (char *); - -private: - - friend class Shape_Sub_Shape_Chunk; - - -}; - -/////////////////////////////////////////////// -class Shape_Preprocessed_Data_Chunk : public Chunk -{ -public: - - Shape_Preprocessed_Data_Chunk (Chunk_With_Children * parent,int _blocksize,int _first_pointer,unsigned int* _memory_block); - Shape_Preprocessed_Data_Chunk (Chunk_With_Children * parent, const char * data, size_t ssize); - ~Shape_Preprocessed_Data_Chunk () - { - if(extra_data) delete extra_data; - if(memory_block) delete memory_block; - } - - virtual size_t size_chunk () - { - return (chunk_size = 12 + 12+block_size*4+num_extra_data*4); - } - - virtual void fill_data_block (char *); - - - int num_extra_data; - int* extra_data; - - void* GetMemoryBlock(); - -private: - - int block_size; - int first_pointer; - unsigned int* memory_block; - - friend class Shape_Chunk; - friend class Shape_Sub_Shape_Chunk; - -}; -#endif
\ No newline at end of file diff --git a/3dc/win95/SMACK.H b/3dc/win95/SMACK.H deleted file mode 100644 index fcab4cb..0000000 --- a/3dc/win95/SMACK.H +++ /dev/null @@ -1,433 +0,0 @@ -#ifndef SMACKH -#define SMACKH - -#define SMACKVERSION "3.1s" - -#ifndef __RADRES__ - -#include "rad.h" - -RADDEFSTART - -typedef struct SmackTag { - u32 Version; // SMK2 only right now - u32 Width; // Width (1 based, 640 for example) - u32 Height; // Height (1 based, 480 for example) - u32 Frames; // Number of frames (1 based, 100 = 100 frames) - u32 MSPerFrame; // Frame Rate - u32 SmackerType; // bit 0 set=ring frame - u32 LargestInTrack[7]; // Largest single size for each track - u32 tablesize; // Size of the init tables - u32 codesize; // Compression info - u32 absize; // ditto - u32 detailsize; // ditto - u32 typesize; // ditto - u32 TrackType[7]; // high byte=0x80-Comp,0x40-PCM data,0x20-16 bit,0x10-stereo - u32 extra; // extra value (should be zero) - u32 NewPalette; // set to one if the palette changed - u8 Palette[772]; // palette data - u32 PalType; // type of palette - u32 FrameNum; // Frame Number to be displayed - u32 FrameSize; // The current frame's size in bytes - u32 SndSize; // The current frame sound tracks' size in bytes - s32 LastRectx; // Rect set in from SmackToBufferRect (X coord) - s32 LastRecty; // Rect set in from SmackToBufferRect (Y coord) - s32 LastRectw; // Rect set in from SmackToBufferRect (Width) - s32 LastRecth; // Rect set in from SmackToBufferRect (Height) - u32 OpenFlags; // flags used on open - u32 LeftOfs; // Left Offset used in SmackTo - u32 TopOfs; // Top Offset used in SmackTo - u32 LargestFrameSize; // Largest frame size - u32 Highest1SecRate; // Highest 1 sec data rate - u32 Highest1SecFrame; // Highest 1 sec data rate starting frame - u32 ReadError; // Set to non-zero if a read error has ocurred - u32 addr32; // translated address for 16 bit interface -} Smack; - -#define SmackHeaderSize(smk) ((((u8*)&((smk)->extra))-((u8*)(smk)))+4) - -typedef struct SmackSumTag { - u32 TotalTime; // total time - u32 MS100PerFrame; // MS*100 per frame (100000/MS100PerFrame=Frames/Sec) - u32 TotalOpenTime; // Time to open and prepare for decompression - u32 TotalFrames; // Total Frames displayed - u32 SkippedFrames; // Total number of skipped frames - u32 SoundSkips; // Total number of sound skips - u32 TotalBlitTime; // Total time spent blitting - u32 TotalReadTime; // Total time spent reading - u32 TotalDecompTime; // Total time spent decompressing - u32 TotalBackReadTime; // Total time spent reading in background - u32 TotalReadSpeed; // Total io speed (bytes/second) - u32 SlowestFrameTime; // Slowest single frame time - u32 Slowest2FrameTime; // Second slowest single frame time - u32 SlowestFrameNum; // Slowest single frame number - u32 Slowest2FrameNum; // Second slowest single frame number - u32 AverageFrameSize; // Average size of the frame - u32 HighestMemAmount; // Highest amount of memory allocated - u32 TotalExtraMemory; // Total extra memory allocated - u32 HighestExtraUsed; // Highest extra memory actually used -} SmackSum; - - -//======================================================================= -#define SMACKNEEDPAN 0x00020L // Will be setting the pan -#define SMACKNEEDVOLUME 0x00040L // Will be setting the volume -#define SMACKFRAMERATE 0x00080L // Override fr (call SmackFrameRate first) -#define SMACKLOADEXTRA 0x00100L // Load the extra buffer during SmackOpen -#define SMACKPRELOADALL 0x00200L // Preload the entire animation -#define SMACKNOSKIP 0x00400L // Don't skip frames if falling behind -#define SMACKSIMULATE 0x00800L // Simulate the speed (call SmackSim first) -#define SMACKFILEHANDLE 0x01000L // Use when passing in a file handle -#define SMACKTRACK1 0x02000L // Play audio track 1 -#define SMACKTRACK2 0x04000L // Play audio track 2 -#define SMACKTRACK3 0x08000L // Play audio track 3 -#define SMACKTRACK4 0x10000L // Play audio track 4 -#define SMACKTRACK5 0x20000L // Play audio track 5 -#define SMACKTRACK6 0x40000L // Play audio track 6 -#define SMACKTRACK7 0x80000L // Play audio track 7 -#define SMACKTRACKS (SMACKTRACK1|SMACKTRACK2|SMACKTRACK3|SMACKTRACK4|SMACKTRACK5|SMACKTRACK6|SMACKTRACK7) - -#define SMACKBUFFERREVERSED 0x00000001 -#define SMACKBUFFER555 0x80000000 -#define SMACKBUFFER565 0xc0000000 -#define SMACKBUFFER16 (SMACKBUFFER555|SMACKBUFFER565) - -#define SMACKYINTERLACE 0x100000L // Force interleaving Y scaling -#define SMACKYDOUBLE 0x200000L // Force doubling Y scaling -#define SMACKYNONE (SMACKYINTERLACE|SMACKYDOUBLE) // Force normal Y scaling -#define SMACKFILEISSMK 0x2000000L // Internal flag for 16 to 32 bit thunking - -#define SMACKAUTOEXTRA 0xffffffffL // NOT A FLAG! - Use as extrabuf param -//======================================================================= - -#define SMACKSURFACEFAST 0 -#define SMACKSURFACESLOW 1 -#define SMACKSURFACEDIRECT 2 - -RADEXPFUNC Smack PTR4* RADEXPLINK SmackOpen(const char PTR4* name,u32 flags,u32 extrabuf); - -#ifdef __RADMAC__ - #include <files.h> - - RADEXPFUNC Smack PTR4* RADEXPLINK SmackMacOpen(FSSpec* fsp,u32 flags,u32 extrabuf); -#endif - -RADEXPFUNC u32 RADEXPLINK SmackDoFrame(Smack PTR4* smk); -RADEXPFUNC void RADEXPLINK SmackNextFrame(Smack PTR4* smk); -RADEXPFUNC u32 RADEXPLINK SmackWait(Smack PTR4* smk); -RADEXPFUNC void RADEXPLINK SmackClose(Smack PTR4* smk); - -RADEXPFUNC void RADEXPLINK SmackVolumePan(Smack PTR4* smk, u32 trackflag,u32 volume,u32 pan); - -RADEXPFUNC void RADEXPLINK SmackSummary(Smack PTR4* smk,SmackSum PTR4* sum); - -RADEXPFUNC u32 RADEXPLINK SmackSoundInTrack(Smack PTR4* smk,u32 trackflags); -RADEXPFUNC u32 RADEXPLINK SmackSoundOnOff(Smack PTR4* smk,u32 on); - -#ifndef __RADMAC__ -RADEXPFUNC void RADEXPLINK SmackToScreen(Smack PTR4* smk,u32 left,u32 top,u32 BytePS,const u16 PTR4* WinTbl,void* SetBank,u32 Flags); -#endif - -RADEXPFUNC void RADEXPLINK SmackToBuffer(Smack PTR4* smk,u32 left,u32 top,u32 Pitch,u32 destheight,const void PTR4* buf,u32 Flags); -RADEXPFUNC u32 RADEXPLINK SmackToBufferRect(Smack PTR4* smk, u32 SmackSurface); - -RADEXPFUNC void RADEXPLINK SmackGoto(Smack PTR4* smk,u32 frame); -RADEXPFUNC void RADEXPLINK SmackColorRemap(Smack PTR4* smk,const void PTR4* remappal,u32 numcolors,u32 paltype); -RADEXPFUNC void RADEXPLINK SmackColorTrans(Smack PTR4* smk,const void PTR4* trans); -RADEXPFUNC void RADEXPLINK SmackFrameRate(u32 forcerate); -RADEXPFUNC void RADEXPLINK SmackSimulate(u32 sim); - -RADEXPFUNC u32 RADEXPLINK SmackGetTrackData(Smack PTR4* smk,void PTR4* dest,u32 trackflag); - -RADEXPFUNC void RADEXPLINK SmackSoundCheck(void); - - -//====================================================================== - -// the functions for the new SmackBlit API - -typedef struct _SMACKBLIT PTR4* HSMACKBLIT; - -typedef struct _SMACKBLIT { - u32 Flags; - u8 PTR4* Palette; - u32 PalType; - u16 PTR4* SmoothTable; - u16 PTR4* Conv8to16Table; - u32 whichmode; - u32 palindex; - u32 t16index; - u32 smoothindex; - u32 smoothtype; - u32 firstpalette; -} SMACKBLIT; - -#define SMACKBLIT1X 1 -#define SMACKBLIT2X 2 -#define SMACKBLIT2XSMOOTHING 4 -#define SMACKBLIT2XINTERLACE 8 - -RADEXPFUNC HSMACKBLIT RADEXPLINK SmackBlitOpen(u32 flags); -RADEXPFUNC void RADEXPLINK SmackBlitSetPalette(HSMACKBLIT sblit, void PTR4* Palette,u32 PalType); -RADEXPFUNC u32 RADEXPLINK SmackBlitSetFlags(HSMACKBLIT sblit,u32 flags); -RADEXPFUNC void RADEXPLINK SmackBlit(HSMACKBLIT sblit,void PTR4* dest, u32 destpitch, u32 destx, u32 desty, void PTR4* src, u32 srcpitch, u32 srcx, u32 srcy, u32 srcw, u32 srch); -RADEXPFUNC void RADEXPLINK SmackBlitClear(HSMACKBLIT sblit,void PTR4* dest, u32 destpitch, u32 destx, u32 desty, u32 destw, u32 desth, s32 color); -RADEXPFUNC void RADEXPLINK SmackBlitClose(HSMACKBLIT sblit); -RADEXPFUNC void RADEXPLINK SmackBlitTrans(HSMACKBLIT sblit,void PTR4* dest, u32 destpitch, u32 destx, u32 desty, void PTR4* src, u32 srcpitch, u32 srcx, u32 srcy, u32 srcw, u32 srch, u32 trans); -RADEXPFUNC void RADEXPLINK SmackBlitMask(HSMACKBLIT sblit,void PTR4* dest, u32 destpitch, u32 destx, u32 desty, void PTR4* src, u32 srcpitch, u32 srcx, u32 srcy, u32 srcw, u32 srch, u32 trans,void PTR4* mask); -RADEXPFUNC void RADEXPLINK SmackBlitMerge(HSMACKBLIT sblit,void PTR4* dest, u32 destpitch, u32 destx, u32 desty, void PTR4* src, u32 srcpitch, u32 srcx, u32 srcy, u32 srcw, u32 srch, u32 trans,void PTR4* back); -RADEXPFUNC char PTR4* RADEXPLINK SmackBlitString(HSMACKBLIT sblit,char PTR4* dest); - -#ifndef __RADMAC__ -RADEXPFUNC u32 RADEXPLINK SmackUseMMX(u32 flag); //0=off, 1=on, 2=query current -#endif - -//====================================================================== -#ifdef __RADDOS__ - - #define SMACKSOUNDNONE -1 - - extern void* SmackTimerSetupAddr; - extern void* SmackTimerReadAddr; - extern void* SmackTimerDoneAddr; - - typedef void RADEXPLINK (*SmackTimerSetupType)(void); - typedef u32 RADEXPLINK (*SmackTimerReadType)(void); - typedef void RADEXPLINK (*SmackTimerDoneType)(void); - - #define SmackTimerSetup() ((SmackTimerSetupType)(SmackTimerSetupAddr))() - #define SmackTimerRead() ((SmackTimerReadType)(SmackTimerReadAddr))() - #define SmackTimerDone() ((SmackTimerDoneType)(SmackTimerDoneAddr))() - - RADEXPFUNC u8 RADEXPLINK SmackSoundUseMSS(void* DigDriver); - - #ifndef AIL_startup - #ifdef __SW_3R - extern s32 cdecl AIL_startup_reg(void); - #define AIL_startup AIL_startup_reg - #else - extern s32 cdecl AIL_startup_stack(void); - #define AIL_startup AIL_startup_stack - #endif - #endif - #define SmackSoundMSSLiteInit() SmackSoundMSSLiteInitWithStart(&AIL_startup); - RADEXPFUNC void RADEXPLINK SmackSoundMSSLiteInitWithStart(void* start); - RADEXPFUNC void RADEXPLINK SmackSoundMSSLiteDone(void); - - RADEXPFUNC u8 RADEXPLINK SmackSoundUseSOS3r(u32 SOSDriver,u32 MaxTimerSpeed); - RADEXPFUNC u8 RADEXPLINK SmackSoundUseSOS3s(u32 SOSDriver,u32 MaxTimerSpeed); - RADEXPFUNC u8 RADEXPLINK SmackSoundUseSOS4r(u32 SOSDriver,u32 MaxTimerSpeed); - RADEXPFUNC u8 RADEXPLINK SmackSoundUseSOS4s(u32 SOSDriver,u32 MaxTimerSpeed); - - #ifdef __SW_3R - #define SmackSoundUseSOS3 SmackSoundUseSOS3r - #define SmackSoundUseSOS4 SmackSoundUseSOS4r - #else - #define SmackSoundUseSOS3 SmackSoundUseSOS3s - #define SmackSoundUseSOS4 SmackSoundUseSOS4s - #endif - -#else - - #define SMACKRESRESET 0 - #define SMACKRES640X400 1 - #define SMACKRES640X480 2 - #define SMACKRES800X600 3 - #define SMACKRES1024X768 4 - - RADEXPFUNC u32 RADEXPLINK SmackSetSystemRes(u32 mode); // use SMACKRES* values - - #define SMACKNOCUSTOMBLIT 128 - #define SMACKSMOOTHBLIT 256 - #define SMACKINTERLACEBLIT 512 - - #ifdef __RADMAC__ - - #include <windows.h> - #include <palettes.h> - #include <qdoffscreen.h> - - #define SmackTimerSetup() - #define SmackTimerDone() - RADEXPFUNC u32 RADEXPLINK SmackTimerRead(void); - - RADEXPFUNC s32 RADEXPLINK SmackGDSurfaceType( GDHandle gd ); - - #define SMACKAUTOBLIT 0 - #define SMACKDIRECTBLIT 1 - #define SMACKGWORLDBLIT 2 - - typedef struct SmackBufTag { - u32 Reversed; - u32 SurfaceType; // SMACKSURFACExxxxxx - u32 BlitType; // SMACKxxxxxBLIT - u32 Width; - u32 Height; - u32 Pitch; - u32 Zoomed; - u32 ZWidth; - u32 ZHeight; - u32 DispColors; // colors on screen - u32 MaxPalColors; - u32 PalColorsInUse; - u32 StartPalColor; - u32 EndPalColor; - void* Buffer; - void* Palette; - u32 PalType; - u32 SoftwareCursor; - - WindowPtr wp; - GWorldPtr gwp; - CTabHandle cth; - PaletteHandle palh; - - GDHandle gd; - u32 gdSurfaceType; - HSMACKBLIT sblit; - void * ScreenAddr; - u32 ScreenPitch; - - s32 manyblits; - s32 PTR4* blitrects; - s32 PTR4* rectsptr; - s32 maxrects; - s32 numrects; - - } SmackBuf; - - #else - - #ifdef __RADWIN__ - - #define INCLUDE_MMSYSTEM_H - #include "windows.h" - #include "windowsx.h" - - #ifdef __RADNT__ // to combat WIN32_LEAN_AND_MEAN - - #include "mmsystem.h" - - RADEXPFUNC s32 RADEXPLINK SmackDDSurfaceType(void* lpDDS); - - #endif - - #define SMACKAUTOBLIT 0 - #define SMACKFULL320X240BLIT 1 - #define SMACKFULL320X200BLIT 2 - #define SMACKFULL320X200DIRECTBLIT 3 - #define SMACKSTANDARDBLIT 4 - #define SMACKWINGBLIT 5 - #define SMACKDIBSECTIONBLIT 5 - - #define WM_SMACKACTIVATE WM_USER+0x5678 - - typedef struct SmackBufTag { - u32 Reversed; // 1 if the buffer is upside down - u32 SurfaceType; // SMACKSURFACExxxx defines - u32 BlitType; // SMACKxxxxBLIT defines - u32 FullScreen; // 1 if full-screen - u32 Width; - u32 Height; - u32 Pitch; - u32 Zoomed; - u32 ZWidth; - u32 ZHeight; - u32 DispColors; // colors on the screen - u32 MaxPalColors; // total possible colors in palette (usually 256) - u32 PalColorsInUse; // Used colors in palette (usually 236) - u32 StartPalColor; // first usable color index (usually 10) - u32 EndPalColor; // last usable color index (usually 246) - RGBQUAD Palette[256]; - u32 PalType; - u32 forceredraw; // force a complete redraw on next blit (for >8bit) - u32 didapalette; // force an invalidate on the next palette change - - void PTR4* Buffer; - void PTR4* DIBRestore; - u32 OurBitmap; - u32 OrigBitmap; - u32 OurPalette; - u32 WinGDC; - u32 FullFocused; - u32 ParentHwnd; - u32 OldParWndProc; - u32 OldDispWndProc; - u32 DispHwnd; - u32 WinGBufHandle; - void PTR4* lpDD; - void PTR4* lpDDSP; - u32 DDSurfaceType; - HSMACKBLIT DDblit; - s32 ddSoftwarecur; - s32 didaddblit; - s32 lastwasdd; - RECT ddscreen; - s32 manyblits; - s32 PTR4* blitrects; - s32 PTR4* rectsptr; - s32 maxrects; - s32 numrects; - HDC lastdc; - } SmackBuf; - - RADEXPFUNC void RADEXPLINK SmackGet(Smack PTR4* smk,void PTR4* dest); - RADEXPFUNC void RADEXPLINK SmackBufferGet( SmackBuf PTR4* sbuf, void PTR4* dest); - - RADEXPFUNC u8 RADEXPLINK SmackSoundUseMSS(void PTR4* dd); - RADEXPFUNC u8 RADEXPLINK SmackSoundUseDirectSound(void PTR4* dd); // NULL=Create - RADEXPFUNC void RADEXPLINK SmackSoundSetDirectSoundHWND(HWND hw); - RADEXPFUNC u8 RADEXPLINK SmackSoundUseDW(u32 openfreq, u32 openbits, u32 openchans); - - #define SmackTimerSetup() - #define SmackTimerDone() - #define SmackTimerRead timeGetTime - - #endif - - #endif - - #ifdef __RADMAC__ - RADEXPFUNC SmackBuf PTR4* RADEXPLINK SmackBufferOpen( WindowPtr wp, u32 BlitType, u32 width, u32 height, u32 ZoomW, u32 ZoomH ); - RADEXPFUNC u32 RADEXPLINK SmackBufferBlit( SmackBuf PTR4* sbuf, s32 hwndx, s32 hwndy, s32 subx, s32 suby, s32 subw, s32 subh ); - RADEXPFUNC void RADEXPLINK SmackBufferFromScreen( SmackBuf PTR4* destbuf, s32 x, s32 y); - - RADEXPFUNC s32 RADEXPLINK SmackIsSoftwareCursor(GDHandle gd); - RADEXPFUNC s32 RADEXPLINK SmackCheckCursor(WindowPtr wp,s32 x,s32 y,s32 w,s32 h); - RADEXPFUNC void RADEXPLINK SmackRestoreCursor(s32 checkcount); - #else - RADEXPFUNC SmackBuf PTR4* RADEXPLINK SmackBufferOpen( HWND wnd, u32 BlitType, u32 width, u32 height, u32 ZoomW, u32 ZoomH ); - RADEXPFUNC u32 RADEXPLINK SmackBufferBlit( SmackBuf PTR4* sbuf, HDC dc, s32 hwndx, s32 hwndy, s32 subx, s32 suby, s32 subw, s32 subh ); - RADEXPFUNC void RADEXPLINK SmackBufferFromScreen( SmackBuf PTR4* destbuf, HWND hw, s32 x, s32 y); - - RADEXPFUNC s32 RADEXPLINK SmackIsSoftwareCursor(void* lpDDSP,HCURSOR cur); - RADEXPFUNC s32 RADEXPLINK SmackCheckCursor(HWND wnd,s32 x,s32 y,s32 w,s32 h); - RADEXPFUNC void RADEXPLINK SmackRestoreCursor(s32 checkcount); - #endif - - RADEXPFUNC void RADEXPLINK SmackBufferStartMultipleBlits( SmackBuf PTR4* sbuf ); - RADEXPFUNC void RADEXPLINK SmackBufferEndMultipleBlits( SmackBuf PTR4* sbuf ); - - RADEXPFUNC char PTR4* RADEXPLINK SmackBufferString(SmackBuf PTR4* sb,char PTR4* dest); - - RADEXPFUNC void RADEXPLINK SmackBufferNewPalette( SmackBuf PTR4* sbuf, const void PTR4* pal, u32 paltype ); - RADEXPFUNC u32 RADEXPLINK SmackBufferSetPalette( SmackBuf PTR4* sbuf ); - RADEXPFUNC void RADEXPLINK SmackBufferClose( SmackBuf PTR4* sbuf ); - - RADEXPFUNC void RADEXPLINK SmackBufferClear( SmackBuf PTR4* destbuf, u32 color); - - RADEXPFUNC void RADEXPLINK SmackBufferToBuffer( SmackBuf PTR4* destbuf, s32 destx, s32 desty, const SmackBuf PTR4* sourcebuf,s32 sourcex,s32 sourcey,s32 sourcew,s32 sourceh); - RADEXPFUNC void RADEXPLINK SmackBufferToBufferTrans( SmackBuf PTR4* destbuf, s32 destx, s32 desty, const SmackBuf PTR4* sourcebuf,s32 sourcex,s32 sourcey,s32 sourcew,s32 sourceh,u32 TransColor); - RADEXPFUNC void RADEXPLINK SmackBufferToBufferMask( SmackBuf PTR4* destbuf, s32 destx, s32 desty, const SmackBuf PTR4* sourcebuf,s32 sourcex,s32 sourcey,s32 sourcew,s32 sourceh,u32 TransColor,const SmackBuf PTR4* maskbuf); - RADEXPFUNC void RADEXPLINK SmackBufferToBufferMerge( SmackBuf PTR4* destbuf, s32 destx, s32 desty, const SmackBuf PTR4* sourcebuf,s32 sourcex,s32 sourcey,s32 sourcew,s32 sourceh,u32 TransColor,const SmackBuf PTR4* mergebuf); - RADEXPFUNC void RADEXPLINK SmackBufferCopyPalette( SmackBuf PTR4* destbuf, SmackBuf PTR4* sourcebuf, u32 remap); - - RADEXPFUNC u32 RADEXPLINK SmackBufferFocused( SmackBuf PTR4* sbuf); - -#endif - -RADDEFEND - -#endif - -#endif diff --git a/3dc/win95/SMSOPT.H b/3dc/win95/SMSOPT.H deleted file mode 100644 index 614b415..0000000 --- a/3dc/win95/SMSOPT.H +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------------------------------- -// DESCRIPTION: SMSOPT.H - Options for SMS compilation -// -// AUTHOR: Mark Tolley -// -// HISTORY: Created 19th Sept 1996 -// -//------------------------------------------------------------------- - -// Incorporated into sndmanag.h and xxxxxsnd.h - -#ifndef SMSOPT_H -#define SMSOPT_H - - -// #DEFINES -// General switches -#define SOUND_ON 0 // Compile sound commands in main game code -#define SOUND_3D 1 // Compile 3D sound functions - - // (NB switching this off makes SMS independent of 3DC) - -// Platform switches - ONLY ONE OF THESE SHOULD BE ON!! -#define SMS_SATURN 0 // Compile SMS for Saturn -#define SMS_PSX 0 // Compile SMS for PSX -#define SMS_PCDOS 0 // Compile SMS for PC-DOS -#define SMS_WIN32 1 // Compile SMS for PC-Win95 - -// Sound source switches -#define MIDI_ON 1 // Compile MIDI-specific code -#define DIGI_ON 1 // Compile WAV-specific code -#define CDDA_ON 1 // Compile CDDA-specific code - -// Any other sound-specific compiler switches -#define SMS_FORCE_PENTIUM_TO_DOS_QUALITY 0 // Forces Pentium to use - // DOS quality sound. May help to speed things - // up... NB 3D SOUND WON'T WORK PROPERLY -#define SMS_TIMER 1 // Implement timing for ONEHI. Relies on NormalFrameTime -#endif // SMSOPT_H -// END OF FILE diff --git a/3dc/win95/SNDCHUNK.CPP b/3dc/win95/SNDCHUNK.CPP deleted file mode 100644 index c0e08d3..0000000 --- a/3dc/win95/SNDCHUNK.CPP +++ /dev/null @@ -1,351 +0,0 @@ -#include "chunk.hpp" -#include "envchunk.hpp" -#include "sndchunk.hpp" -#include "obchunk.hpp" -#include "md5.h" - -#ifdef cencon -#define new my_new -#endif -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(sndchunk) - -RIF_IMPLEMENT_DYNCREATE("SOUNDOB2",Sound_Object_Chunk) - -Sound_Object_Chunk::Sound_Object_Chunk (Chunk_With_Children * parent, - ChunkVectorInt & pos, - const char * _name - ) -: Chunk (parent, "SOUNDOB2"), position (pos), - inner_range (0), outer_range (0), max_volume (0), pitch (0), - flags (0), probability (0), pad3 (0), - snd_name (0), wav_name (0) -{ - if (_name) - { - snd_name = new char [strlen(_name)+1]; - strcpy (snd_name, _name); - } - else - { - snd_name = new char [1]; - snd_name [0] = 0; - } -} - -Sound_Object_Chunk::~Sound_Object_Chunk() -{ - if (snd_name) - delete [] snd_name; - if (wav_name) - delete [] wav_name; -} - -Sound_Object_Chunk::Sound_Object_Chunk (Chunk_With_Children * parent, const char * data, size_t /*ssize*/) -: Chunk (parent, "SOUNDOB2"), snd_name (0), wav_name (0) -{ - position = *((ChunkVectorInt *) data); - data += sizeof(ChunkVectorInt); - - inner_range = *((int *)data); - data += 4; - outer_range = *((int *)data); - data += 4; - max_volume = *((int *)data); - data += 4; - pitch = *((int *)data); - data += 4; - flags = *((int *)data); - data += 4; - probability = *((int *)data); - data += 4; - pad3 = *((int *)data); - data += 4; - snd_name = new char [strlen (data) + 1]; - strcpy (snd_name, data); - data += strlen (data) + 1; - if (strlen(data)) - { - wav_name = new char [strlen (data) + 1]; - strcpy (wav_name, data); - } -} - -void Sound_Object_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((ChunkVectorInt *) data_start) = position; - data_start += sizeof(ChunkVectorInt); - - - *((int *)data_start) = inner_range; - data_start += 4; - *((int *)data_start) = outer_range; - data_start += 4; - *((int *)data_start) = max_volume; - data_start += 4; - *((int *)data_start) = pitch; - data_start += 4; - *((int *)data_start) = flags; - data_start += 4; - *((int *)data_start) = probability; - data_start += 4; - *((int *)data_start) = pad3; - data_start += 4; - - sprintf (data_start, "%s", snd_name); - data_start += strlen (snd_name) + 1; - if (wav_name) - { - sprintf (data_start, "%s", wav_name); - } - else - { - *data_start = 0; - } -} - - -ObjectID Sound_Object_Chunk::CalculateID() -{ - ObjectID retval={0,0}; - - char buffer[16]; - md5_buffer(snd_name,strlen(snd_name),&buffer[0]); - buffer[7]=0; - retval = *(ObjectID*)&buffer[0]; - return retval; -} - -Sound_Object_Extra_Data_Chunk* Sound_Object_Chunk::get_extra_data_chunk() -{ - List<Chunk*> chlist; - parent->lookup_child("SOUNDEXD",chlist); - if(!chlist.size())return 0; - - for(LIF<Chunk*> chlif(&chlist);!chlif.done();chlif.next()) - { - Sound_Object_Extra_Data_Chunk* soedc=(Sound_Object_Extra_Data_Chunk*)chlif(); - Sound_Object_Extra_Name_Chunk* sname=(Sound_Object_Extra_Name_Chunk*) soedc->lookup_single_child("SOUNDNAM"); - - if(sname) - { - if(!strcmp(snd_name,sname->name)) - { - return soedc; - } - } - } - //no extra data chunk found - return 0; - -} -Sound_Object_Extra_Data_Chunk* Sound_Object_Chunk::create_extra_data_chunk() -{ - Sound_Object_Extra_Data_Chunk* soedc=get_extra_data_chunk(); - if(soedc)return soedc; - - return new Sound_Object_Extra_Data_Chunk(parent,this); -} - -Object_Alternate_Locations_Chunk* Sound_Object_Chunk::get_alternate_locations_chunk() -{ - Sound_Object_Extra_Data_Chunk* soedc=get_extra_data_chunk(); - if(!soedc) return 0; - return (Object_Alternate_Locations_Chunk*)soedc->lookup_single_child("ALTLOCAT"); -} - -Object_Alternate_Locations_Chunk* Sound_Object_Chunk::create_alternate_locations_chunk() -{ - Sound_Object_Extra_Data_Chunk* soedc=create_extra_data_chunk(); - - Object_Alternate_Locations_Chunk* loc_chunk=(Object_Alternate_Locations_Chunk*)soedc->lookup_single_child("ALTLOCAT"); - if(loc_chunk) return loc_chunk; - - return new Object_Alternate_Locations_Chunk(soedc); -} - - -///////////////////////////////////////////////////////////////////////////////////// -//class Sound_Object_Extra_Data_Chunk -RIF_IMPLEMENT_DYNCREATE("SOUNDEXD",Sound_Object_Extra_Data_Chunk) - -CHUNK_WITH_CHILDREN_LOADER("SOUNDEXD",Sound_Object_Extra_Data_Chunk) - -/* -Children for Sound_Object_Extra_Data_Chunk : - -"SOUNDNAM" Sound_Object_Extra_Name_Chunk -"ALTLOCAT" Object_Alternate_Locations_Chunk -*/ - - -Sound_Object_Extra_Data_Chunk::Sound_Object_Extra_Data_Chunk(Chunk_With_Children* parent,Sound_Object_Chunk* soc) -:Chunk_With_Children(parent,"SOUNDEXD") -{ - new Sound_Object_Extra_Name_Chunk(this,soc->snd_name); -} - -Sound_Object_Chunk* Sound_Object_Extra_Data_Chunk::get_sound_chunk() -{ - List<Chunk*> chlist; - - lookup_child("SOUNDNAM",chlist); - if(!chlist.size()) return 0; - const char* name=((Sound_Object_Extra_Name_Chunk*)chlist.first_entry())->name; - - parent->lookup_child("SOUNDEXD",chlist); - for(LIF<Chunk*> chlif(&chlist);!chlif.done();chlif.next()) - { - Sound_Object_Chunk* soc=(Sound_Object_Chunk*)chlif(); - if(!strcmp(soc->snd_name,name)) - { - return soc; - } - } - //no sound chunk found - return 0; -} - -///////////////////////////////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SOUNDNAM",Sound_Object_Extra_Name_Chunk) - -Sound_Object_Extra_Name_Chunk::Sound_Object_Extra_Name_Chunk(Chunk_With_Children * parent, const char * data, size_t /*size*/) -:Chunk(parent,"SOUNDNAM") -{ - int length=strlen(data); - name=new char[length+1]; - strcpy(name,data); -} - -Sound_Object_Extra_Name_Chunk::Sound_Object_Extra_Name_Chunk(Chunk_With_Children * parent, const char * _name) -:Chunk(parent,"SOUNDNAM") -{ - name=new char[strlen(_name)+1]; - strcpy(name,_name); -} - -Sound_Object_Extra_Name_Chunk::~Sound_Object_Extra_Name_Chunk() -{ - delete name; -} - -void Sound_Object_Extra_Name_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - strcpy(data_start,name); -} - - -size_t Sound_Object_Extra_Name_Chunk::size_chunk() -{ - chunk_size=12; - chunk_size+=(strlen(name)+4)&~3; - return chunk_size; -} -///////////////////////////////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("INDSOUND",Indexed_Sound_Chunk) - -Indexed_Sound_Chunk::Indexed_Sound_Chunk(Chunk_With_Children* parent,const char* data,const size_t) -:Chunk(parent,"INDSOUND") -{ - CHUNK_EXTRACT(index,int) - CHUNK_EXTRACT_STRING(wav_name) - CHUNK_EXTRACT(inner_range,int) - CHUNK_EXTRACT(outer_range,int) - CHUNK_EXTRACT(max_volume,int) - CHUNK_EXTRACT(pitch,int) - CHUNK_EXTRACT(flags,int) - CHUNK_EXTRACT_ARRAY(num_extra_data,extra_data,int) -} - -Indexed_Sound_Chunk::Indexed_Sound_Chunk(Chunk_With_Children* parent) -:Chunk(parent,"INDSOUND") -{ - index=0; - wav_name=0; - num_extra_data=0; - extra_data=0; -} - -Indexed_Sound_Chunk::~Indexed_Sound_Chunk() -{ - if(extra_data) delete [] extra_data; - if(wav_name) delete [] wav_name; -} - -void Indexed_Sound_Chunk::fill_data_block(char * data) -{ - CHUNK_FILL_START - CHUNK_FILL(index,int) - CHUNK_FILL_STRING(wav_name) - CHUNK_FILL(inner_range,int) - CHUNK_FILL(outer_range,int) - CHUNK_FILL(max_volume,int) - CHUNK_FILL(pitch,int) - CHUNK_FILL(flags,int) - CHUNK_FILL_ARRAY(num_extra_data,extra_data,int) - -} - -size_t Indexed_Sound_Chunk::size_chunk() -{ - chunk_size=12+24; - chunk_size+=4+4*num_extra_data; - if(wav_name) - chunk_size+=(strlen(wav_name)+4)&~3; - else - chunk_size+=4; - - return chunk_size; -} - -///////////////////////////////////////////////////////////////////////////////////// -/* -Sound_Collection_Chunk::Sound_Collection_Chunk(Chunk_With_Children* parent,const char* data,const size_t) -:Chunk(parent,"SOUNDCOL") -{ - CHUNK_EXTRACT(index,int) - CHUNK_EXTRACT_ARRAY(num_sounds,sounds,ChunkSoundWeighting) - CHUNK_EXTRACT(spare,int) -} - -Sound_Collection_Chunk::Sound_Collection_Chunk(Chunk_With_Children* parent) -:Chunk(parent,"SOUNDCOL") -{ - index=-1; - num_sounds=0; - sounds=0; - spare=0; -} - -Sound_Collection_Chunk::~Sound_Collection_Chunk() -{ - if(sounds) delete [] sounds; -} - -void Sound_Collection_Chunk::fill_data_block(char* data) -{ - CHUNK_FILL_START - CHUNK_FILL(index,int) - CHUNK_FILL_ARRAY(num_sounds,sounds,ChunkSoundWeighting) - CHUNK_FILL(spare,int) -} - -size_t Sound_Collection_Chunk::size_chunk() -{ - chunk_size=12+12+num_sounds*sizeof(ChunkSoundWeighting); - return chunk_size; -} -*/
\ No newline at end of file diff --git a/3dc/win95/SNDCHUNK.HPP b/3dc/win95/SNDCHUNK.HPP deleted file mode 100644 index 86483e5..0000000 --- a/3dc/win95/SNDCHUNK.HPP +++ /dev/null @@ -1,156 +0,0 @@ -#ifndef _sndchunk_hpp -#define _sndchunk_hpp 1 -#include "chnktype.hpp" - -#define SoundObjectFlag_NotPlayingAtStart 0x00000001 -#define SoundObjectFlag_NoLoop 0x00000002 - -class Object_Alternate_Locations_Chunk; -class Sound_Object_Extra_Data_Chunk; - -class Sound_Object_Chunk : public Chunk -{ -public: - - Sound_Object_Chunk (Chunk_With_Children * parent, - ChunkVectorInt & pos, - const char * name - ); - // constructor from buffer - Sound_Object_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/); - - ~Sound_Object_Chunk (); - - ChunkVectorInt position; - - unsigned long inner_range; //millimetres - unsigned long outer_range; //millimetres - int max_volume; //from 0 to 127 - int pitch; //pitch shift in 1/1536ths of an actave - - int flags; - int probability; - int pad3; - - char * snd_name; - char * wav_name; - - size_t size_chunk () - { - chunk_size = 12 + 3*4 + 7*4 + strlen(snd_name) + 1; - if (wav_name) - { - chunk_size += strlen (wav_name); - } - else - { - chunk_size += 1; - } - - chunk_size += 4 - chunk_size%4; - return (chunk_size); - } - - void fill_data_block (char *); - - ObjectID CalculateID(); - - Sound_Object_Extra_Data_Chunk* get_extra_data_chunk(); - Sound_Object_Extra_Data_Chunk* create_extra_data_chunk(); //gets chunk if it exists , otherwise creates a new one - - Object_Alternate_Locations_Chunk* get_alternate_locations_chunk(); - Object_Alternate_Locations_Chunk* create_alternate_locations_chunk(); //gets chunk if it exists , otherwise creates a new one - -private: - - friend class Special_Objects_Chunk; - - - -}; - -//For attaching extra data to the sound objects -class Sound_Object_Extra_Data_Chunk : public Chunk_With_Children -{ -public: - Sound_Object_Extra_Data_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - Sound_Object_Extra_Data_Chunk (Chunk_With_Children * parent,Sound_Object_Chunk*); - - Sound_Object_Chunk* get_sound_chunk(); -}; - -//Needed so I can match the extra data chunk with the appropriate sound chunk -class Sound_Object_Extra_Name_Chunk : public Chunk -{ -public : - Sound_Object_Extra_Name_Chunk(Chunk_With_Children* parent,const char*,size_t); - Sound_Object_Extra_Name_Chunk(Chunk_With_Children* parent,const char* _name); - ~Sound_Object_Extra_Name_Chunk(); - - char* name; - - - virtual size_t size_chunk(); - virtual void fill_data_block(char* data_start); -}; - - - -#define IndexedSoundFlag_Loop 0x00000001 -class Indexed_Sound_Chunk : public Chunk -{ -public : - - Indexed_Sound_Chunk(Chunk_With_Children* parent,const char*,const size_t); - Indexed_Sound_Chunk(Chunk_With_Children* parent); - ~Indexed_Sound_Chunk(); - - size_t size_chunk(); - void fill_data_block(char*); - - int index; - char* wav_name; - unsigned long inner_range; //millimetres - unsigned long outer_range; //millimetres - int max_volume; //from 0 to 127 - int pitch; //pitch shift in 1/1536ths of an actave - int flags; - - int num_extra_data; - int* extra_data; -}; - - - -/* -struct ChunkSoundWeighting -{ - int index; - int weighting; -}; - -//a collection of indeces of possible sounds to play -class Sound_Collection_Chunk : public Chunk -{ -public : - - Sound_Collection_Chunk(Chunk_With_Children* parent,const char*,const size_t); - Sound_Collection_Chunk(Chunk_With_Children* parent); - ~Sound_Collection_Chunk(); - - size_t size_chunk(); - void fill_data_block(char*); - - int index; - - int num_sounds; - ChunkSoundWeighting* sounds; - - int spare; - - -}; -*/ - - -#endif diff --git a/3dc/win95/STRING.CPP b/3dc/win95/STRING.CPP deleted file mode 100644 index 4ea96b5..0000000 --- a/3dc/win95/STRING.CPP +++ /dev/null @@ -1,305 +0,0 @@ -#include <string.h> -#include <ctype.h> -#include <malloc.h> -#include "string.hpp" - -String::String() -: rep(0) -, len(0) -, cstring(0) -{ -} - -String::String(char const * str, size_t maxlen) -: rep(0) -, len(strlen(str)) -, cstring(0) -{ - if (len > maxlen) len = maxlen; - if (!len) return; - rep = (char *)malloc(len*sizeof(char)); - memcpy(rep,str,len*sizeof(char)); -} - -String::String(String const & str, size_t start, size_t leng) -: rep(0) -, len(leng) -, cstring(0) -{ - if (start>str.len) return; - if (start+len>str.len) len=str.len-start; - if (!len) return; - rep = (char *)malloc(len*sizeof(char)); - memcpy(rep,&str.rep[start],len*sizeof(char)); -} - -String::String(char c, size_t n) -: rep(0) -, len(n) -, cstring(0) -{ - if (len) - { - rep = (char *)malloc(len*sizeof(char)); - for (size_t p=0; p<len; ++p) - rep[p]=c; - } -} - -String::~String() -{ - if (cstring) free(cstring); - if (rep) free(rep); -} - -char const * String::c_str() const -{ - if (!len) return ""; - if (cstring) - { - if (strlen(cstring)==len && !strncmp(cstring,rep,len)) - return cstring; - free(cstring); - } - char * newcstr = (char *)malloc(len+1); - memcpy(newcstr,rep,len*sizeof(char)); - newcstr[len]=0; - *(char * *)&cstring = newcstr; - return newcstr; -} - -#if 0 -String::operator char () const -{ - return len ? rep[0] : 0; -} -#endif - -String & String::operator = (String const & str) -{ - if (&str != this) - { - if (rep) free(rep); - rep = 0; - len = str.len; - if (len) - { - rep = (char *)malloc(len*sizeof(char)); - memcpy(rep,str.rep,len*sizeof(char)); - } - } - return *this; -} - -String & String::operator = (char const * str) -{ - if (rep) free(rep); - rep = 0; - len = strlen(str); - if (len) - { - rep = (char *)malloc(len*sizeof(char)); - memcpy(rep,str,len*sizeof(char)); - } - return *this; -} - -String & String::operator += (String const & str) -{ - if (&str != this) - { - if (str.len) - { - rep = (char *)realloc(rep,(len+str.len)*sizeof(char)); - memcpy(&rep[len],str.rep,str.len*sizeof(char)); - len += str.len; - } - } - else if (len) - { - rep = (char *)realloc(rep,len*2*sizeof(char)); - memcpy(&rep[len],rep,len*sizeof(char)); - len *= 2; - } - return *this; -} - -String & String::operator += (char const * str) -{ - size_t clen = strlen(str); - if (clen) - { - rep = (char *)realloc(rep,(len+clen)*sizeof(char)); - memcpy(&rep[len],str,clen*sizeof(char)); - len += clen; - } - return *this; -} - -#define STRING_COMPARES(op) \ -int operator op (String const & str1, String const & str2) \ -{ \ - return strcmp(str1.c_str(),str2.c_str()) op 0; \ -} \ -int operator op (String const & str1, char const * str2) \ -{ \ - return strcmp(str1.c_str(),str2) op 0; \ -} \ -int operator op (char const * str1, String const & str2) \ -{ \ - return strcmp(str1,str2.c_str()) op 0; \ -} \ -int operator op (String const & str1, char c) \ -{ \ - char buf[] = { c, 0 }; \ - return strcmp(str1.c_str(),buf) op 0; \ -} \ -int operator op (char c, String const & str2) \ -{ \ - char buf[] = { c, 0 }; \ - return strcmp(buf,str2.c_str()) op 0; \ -} -STRING_COMPARES(==) -STRING_COMPARES(!=) -STRING_COMPARES(<=) -STRING_COMPARES(>=) -STRING_COMPARES(<) -STRING_COMPARES(>) - -void String::put_at(size_t pos, char c) -{ - if (pos<len) - rep[pos]=c; - else - operator += (c); -} - -int String::match(String const & str) const -{ - for (size_t pos = 0; pos<len || pos<str.len; ++pos) - { - if (pos>=len || pos>=str.len || rep[pos] != str.rep[pos]) return (int)pos; - } - return -1; -} - -int String::match(char const * str) const -{ - for (size_t pos = 0; pos<len || *str; ++pos, ++str) - { - if (pos>=len || !*str || rep[pos] != *str) return (int)pos; - } - return -1; -} - -int String::index(String const & str, size_t pos) const -{ - if (!str.len) return (int)pos; - for (size_t spos = 0, rpos = pos; pos<len; ++pos) - { - if (rep[pos]==str.rep[spos]) - { - if (!spos) rpos = pos; - ++spos; - if (spos >= str.len) return (int)rpos; - } - else spos = 0; - } - return -1; -} - -int String::index(char const * str, size_t pos) const -{ - if (!*str) return (int)pos; - char const * strP = str; - for (size_t rpos = pos; pos<len; ++pos) - { - if (rep[pos]==*strP) - { - if (strP==str) rpos = pos; - ++strP; - if (!*strP) return (int)rpos; - } - else strP = str; - } - return -1; -} - -String String::upper() const -{ - String rstr(*this); - for (size_t pos=0; pos<rstr.len; ++pos) - { - rstr.rep[pos] = (char)toupper(rstr.rep[pos]); - } - return rstr; -} - -String String::lower() const -{ - String rstr(*this); - for (size_t pos=0; pos<rstr.len; ++pos) - { - rstr.rep[pos] = (char)tolower(rstr.rep[pos]); - } - return rstr; -} - -String::String(String const & str1, String const & str2) -: rep(0) -, len(str1.len + str2.len) -, cstring(0) -{ - if (!len) return; - rep = (char *)malloc(len*sizeof(char)); - if (str1.len) memcpy(rep,str1.rep,str1.len*sizeof(char)); - if (str2.len) memcpy(&rep[str1.len],str2.rep,str2.len*sizeof(char)); -} - -String::String(char const * str1, String const & str2) -: rep(0) -, cstring(0) -{ - size_t clen = strlen(str1); - len = clen + str2.len; - if (!len) return; - rep = (char *)malloc(len*sizeof(char)); - if (clen) memcpy(rep,str1,clen*sizeof(char)); - if (str2.len) memcpy(&rep[clen],str2.rep,str2.len*sizeof(char)); -} - -String::String(String const & str1, char const * str2) -: rep(0) -, cstring(0) -{ - size_t clen = strlen(str2); - len = str1.len + clen; - if (!len) return; - rep = (char *)malloc(len*sizeof(char)); - if (str1.len) memcpy(rep,str1.rep,str1.len*sizeof(char)); - if (clen) memcpy(&rep[str1.len],str2,clen*sizeof(char)); -} - -String::String(char c, String const & str2) -: rep(0) -, len(1 + str2.len) -, cstring(0) -{ - rep = (char *)malloc(len*sizeof(char)); - rep[0]=c; - if (str2.len) memcpy(&rep[1],str2.rep,str2.len*sizeof(char)); -} - -String::String(String const & str1, char c) -: rep(0) -, len(str1.len + 1) -, cstring(0) -{ - rep = (char *)malloc(len*sizeof(char)); - if (str1.len) memcpy(rep,str1.rep,str1.len*sizeof(char)); - rep[str1.len]=c; -} - - - - diff --git a/3dc/win95/STRING.HPP b/3dc/win95/STRING.HPP deleted file mode 100644 index 71f7558..0000000 --- a/3dc/win95/STRING.HPP +++ /dev/null @@ -1,183 +0,0 @@ -#ifndef _included_string_hpp_ -#define _included_string_hpp_ - -#ifdef __WATCOMC__ -#include <string.hpp> -#else - -#ifndef __cplusplus -#error "string.hpp requires C++ compilation" -#endif - -#include <stddef.h> - -//const size_t NPOS = (size_t) -1; -#define _BIGSIZET ((size_t)-1) - -class String -{ -public: - String(); - String(char const *, size_t = _BIGSIZET); - String(String const &, size_t = 0, size_t = _BIGSIZET); - String(char, size_t = 1); - - ~String(); - - inline operator char const * () const; - char const * c_str() const; - //operator char () const; - - String & operator = (String const &); - String & operator = (char const *); - - String & operator += (String const &); - String & operator += (char const *); - - inline String operator () (size_t, size_t) const; - inline char & operator () (size_t); - inline char const & operator () (size_t) const; - inline char & operator [] (size_t); - inline char const & operator [] (size_t) const; - - friend int operator == (String const &, String const &); - friend int operator == (String const &, char const *); - friend int operator == (char const *, String const &); - friend int operator == (String const &, char); - friend int operator == (char, String const &); - - friend int operator != (String const &, String const &); - friend int operator != (String const &, char const *); - friend int operator != (char const *, String const &); - friend int operator != (String const &, char); - friend int operator != (char, String const &); - - friend int operator <= (String const &, String const &); - friend int operator <= (String const &, char const *); - friend int operator <= (char const *, String const &); - friend int operator <= (String const &, char); - friend int operator <= (char, String const &); - - friend int operator >= (String const &, String const &); - friend int operator >= (String const &, char const *); - friend int operator >= (char const *, String const &); - friend int operator >= (String const &, char); - friend int operator >= (char, String const &); - - friend int operator < (String const &, String const &); - friend int operator < (String const &, char const *); - friend int operator < (char const *, String const &); - friend int operator < (String const &, char); - friend int operator < (char, String const &); - - friend int operator > (String const &, String const &); - friend int operator > (String const &, char const *); - friend int operator > (char const *, String const &); - friend int operator > (String const &, char); - friend int operator > (char, String const &); - - friend inline String operator + (String const &, String const &); - friend inline String operator + (String const &, char const *); - friend inline String operator + (char const *, String const &); - friend inline String operator + (String const &, char); - friend inline String operator + (char, String const &); - - inline size_t length() const; - - inline char const & get_at(size_t) const; - void put_at(size_t, char); - - int match(String const &) const; - int match(char const *) const; - - int index(String const &, size_t = 0) const; - int index(char const *, size_t = 0 ) const; - - String upper() const; - String lower() const; - - inline int operator ! () const; - inline int valid() const; - friend inline int valid(String const &); - -private: - String(String const &, String const &); - String(char const *, String const &); - String(String const &, char const *); - String(char, String const &); - String(String const &, char); - - char * rep; - size_t len; - char * cstring; -}; - -inline String::operator char const * () const -{ - return c_str(); -} - -inline String String::operator () (size_t start, size_t leng) const -{ - return String(*this,start,leng); -} - -inline char & String::operator () (size_t pos) -{ - return operator [] (pos); -} - -inline char const & String::operator () (size_t pos) const -{ - return operator [] (pos); -} - -inline char & String::operator [] (size_t pos) -{ - return rep[pos]; -} - -inline char const & String::operator [] (size_t pos) const -{ - return rep[pos]; -} - -#define STRING_CONSTRCAT(arg1,arg2) \ -inline String operator + (arg1 a1,arg2 a2) \ -{ \ - return String(a1,a2); \ -} -STRING_CONSTRCAT(String const &, String const &) -STRING_CONSTRCAT(char const *, String const &) -STRING_CONSTRCAT(String const &, char const *) -STRING_CONSTRCAT(char , String const &) -STRING_CONSTRCAT(String const &, char) - -inline size_t String::length() const -{ - return len; -} - -inline char const & String::get_at(size_t pos) const -{ - return operator [] (pos); -} - -inline int String::operator ! () const -{ - return !valid(); -} - -inline int String::valid() const -{ - return 1; -} - -inline int valid(String const & str) -{ - return str.valid(); -} - -#endif - -#endif
\ No newline at end of file diff --git a/3dc/win95/ShowCmds.h b/3dc/win95/ShowCmds.h deleted file mode 100644 index bbb1d41..0000000 --- a/3dc/win95/ShowCmds.h +++ /dev/null @@ -1,43 +0,0 @@ -/* KJL 14:42:10 29/03/98 - ShowCmds.h - - defines the variables that describe the status of the debugging text - - - eg. if ShowDebuggingText.FPS == 1, then the frame-rate show be displayed. - -*/ -struct DEBUGGINGTEXTOPTIONS -{ - unsigned int FPS :1; - unsigned int Environment :1; - unsigned int Coords :1; - unsigned int Module :1; - unsigned int Target :1; - - unsigned int Networking: 1; - unsigned int Dynamics :1; - unsigned int GunPos :1; - unsigned int Tears :1; - unsigned int PolyCount :1; - unsigned int Sounds :1; -}; - -extern struct DEBUGGINGTEXTOPTIONS ShowDebuggingText; - -#ifdef AVP_DEBUG_VERSION - #define DEBUGGING_TEXT_ON 1 -#else - #define DEBUGGING_TEXT_ON 0 -#endif - -#if DEBUGGING_TEXT_ON -extern int PrintDebuggingText(const char* t, ...); -#else -#define PrintDebuggingText(ignore) -#endif - -#if 1 -extern int ReleasePrintDebuggingText(const char* t, ...); -#else -#define PrintDebuggingText(ignore) -#endif diff --git a/3dc/win95/Sprchunk.cpp b/3dc/win95/Sprchunk.cpp deleted file mode 100644 index c8f74f3..0000000 --- a/3dc/win95/Sprchunk.cpp +++ /dev/null @@ -1,964 +0,0 @@ -#include "sprchunk.hpp" -#include "mishchnk.hpp" - -#if cencon -#include "fnamefnc.hpp" -#include "bmpnames.hpp" -#include "shpchunk.hpp" -#endif - -#ifdef cencon -#define new my_new -#endif -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(sprchunk) - -extern Chunk* Parent_File; - -RIF_IMPLEMENT_DYNCREATE("SPRACTIO",Sprite_Action_Chunk) - -Sprite_Action_Chunk::Sprite_Action_Chunk(Chunk_With_Children* parent,const char* data,size_t /*datasize*/) -: Chunk(parent, "SPRACTIO") -{ - Action=*((int*)data); - data+=4; - NumYaw=*((int*)data); - data+=4; - NumPitch=*((int*)data); - data+=4; - NumFrames=*((int*)data); - data+=4; - Flags=*((int*)data); - data+=4; - FrameTime=*((int*)data); - data+=4; - FrameList=new Frame**[NumYaw]; - for(int i=0;i<NumYaw;i++) - { - FrameList[i]=new Frame*[NumPitch]; - for(int j=0;j<NumPitch;j++) - { - FrameList[i][j]=new Frame[NumFrames]; - for(int k=0;k<NumFrames;k++) - { - Frame* f=&FrameList[i][j][k]; - f->Texture=*((int*)data); - data+=4; - f->CentreX=*((int*)data); - data+=4; - f->CentreY=*((int*)data); - data+=4; - for(int l=0;l<4;l++) - { - f->UVCoords[l][0]=*((int*)data); - data+=4; - f->UVCoords[l][1]=*((int*)data); - data+=4; - } - } - } - } -} -Sprite_Action_Chunk::Sprite_Action_Chunk(Chunk_With_Children* parent) -: Chunk(parent, "SPRACTIO") -{ - Action=-1; - NumPitch=0; - NumYaw=0; - NumFrames=0; - FrameList=0; - Flags=0; - FrameTime=200; -} -size_t Sprite_Action_Chunk::size_chunk() -{ - chunk_size=36+NumFrames*NumPitch*NumYaw*44; - return chunk_size; -} - -Sprite_Action_Chunk::~Sprite_Action_Chunk() -{ - for(int i=0;i<NumYaw;i++) - { - for(int j=0;j<NumPitch;j++) - { - delete [] FrameList[i][j]; - } - delete[] FrameList[i]; - } - delete [] FrameList; -} - - -BOOL Sprite_Action_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -void Sprite_Action_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=Action; - data_start += 4; - *(int*)data_start=NumYaw; - data_start += 4; - *(int*)data_start=NumPitch; - data_start += 4; - *(int*)data_start=NumFrames; - data_start += 4; - *(int*)data_start=Flags; - data_start += 4; - *(int*)data_start=FrameTime; - data_start += 4; - - for(int i=0;i<NumYaw;i++) - { - for(int j=0;j<NumPitch;j++) - { - for(int k=0;k<NumFrames;k++) - { - Frame* f=&FrameList[i][j][k]; - *(int*)data_start=f->Texture; - data_start += 4; - *(int*)data_start=f->CentreX; - data_start +=4; - *(int*)data_start=f->CentreY; - data_start +=4; - for(int l=0;l<4;l++) - { - *(int*)data_start=f->UVCoords[l][0]; - data_start+=4; - *(int*)data_start=f->UVCoords[l][1]; - data_start+=4; - } - } - } - } -} - -////////////////////////////////////////////////// -//Class Sprite_Header_Chunk -RIF_IMPLEMENT_DYNCREATE("SPRIHEAD",Sprite_Header_Chunk) -CHUNK_WITH_CHILDREN_LOADER("SPRIHEAD",Sprite_Header_Chunk) - -/* -Children for Sprite_Header_Chunk : - -"SPRITVER" Sprite_Version_Number_Chunk -"SPRITEPC" PC_Sprite_Chunk -"SPRITEPS" Playstation_Sprite_Chunk -"SPRITESA" Saturn_Sprite_Chunk -"BMPLSTST" Bitmap_List_Store_Chunk -"BMNAMVER" BMP_Names_Version_Chunk -"BMNAMEXT" BMP_Names_ExtraData_Chunk -"RIFFNAME" RIF_Name_Chunk -"SHPEXTFN" Shape_External_Filename_Chunk -"SPRISIZE" Sprite_Size_Chunk -"BMPMD5ID" Bitmap_MD5_Chunk -"SPRBMPSC" Sprite_Bitmap_Scale_Chunk -"SPRBMPCE" Sprite_Bitmap_Centre_Chunk -"SPREXTEN" Sprite_Extent_Chunk -*/ - - -Sprite_Header_Chunk::Sprite_Header_Chunk(const char * file_name, Chunk_With_Children * parent) -: Chunk_With_Children(parent,"SPRIHEAD") -{ -// Load in whole chunk and traverse - HANDLE rif_file; - DWORD file_size; - DWORD file_size_from_file; - unsigned long bytes_read; - char * buffer; - char * buffer_ptr; - char id_buffer[9]; - - Parent_File = this; - - error_code = 0; - - - rif_file = CreateFileA (file_name, GENERIC_READ, 0, 0, OPEN_EXISTING, - FILE_FLAG_RANDOM_ACCESS, 0); - - if (rif_file == INVALID_HANDLE_VALUE) { - return; - } - - file_size = GetFileSize (rif_file, NULL); - - - if (!ReadFile(rif_file, id_buffer, 8, &bytes_read, 0)) { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - return; - } - - if (strncmp (id_buffer, "SPRIHEAD", 8)) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - CloseHandle (rif_file); - return; - } - - if (!ReadFile(rif_file, &file_size_from_file, 4, &bytes_read, 0)) { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - return; - } - - if (file_size != file_size_from_file) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - CloseHandle (rif_file); - return; - } - - - buffer = new char [file_size]; - - if (!ReadFile(rif_file, buffer, (file_size-12), &bytes_read, 0)) { - error_code = CHUNK_FAILED_ON_LOAD; - CloseHandle (rif_file); - return; - } - - // Process the file - - buffer_ptr = buffer; - - - // The start of the first chunk - - while ((buffer_ptr-buffer)< ((signed) file_size-12) && !error_code) { - - if ((*(int *)(buffer_ptr + 8)) + (buffer_ptr-buffer) > ((signed) file_size-12)) { - error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - DynCreate(buffer_ptr); - buffer_ptr += *(int *)(buffer_ptr + 8); - - } - - delete [] buffer; - - CloseHandle (rif_file); - -} - - -Sprite_Header_Chunk::write_file(const char* fname) -{ - HANDLE rif_file; - - rif_file = CreateFileA (fname, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, - FILE_FLAG_RANDOM_ACCESS, 0); - - if (rif_file == INVALID_HANDLE_VALUE) { - return CHUNK_FAILED_ON_WRITE; - } - - size_chunk(); - - if (!(this->output_chunk(rif_file))) - return CHUNK_FAILED_ON_WRITE; - - CloseHandle (rif_file); - - return 0; -} - -Sprite_Header_Chunk::output_chunk(HANDLE & hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -#if cencon -void Sprite_Header_Chunk::post_input_processing() -{ - if (parent) - { - List<Chunk *> chlst; - GetRootChunk()->lookup_child("REBENVDT",chlst); - Lockable_Chunk_With_Children * envd = 0; - if (chlst.size()) envd = (Lockable_Chunk_With_Children *) chlst.first_entry(); - - BOOL fixpal = IsFixedPalette(envd); - - lookup_child("SHPEXTFN",chlst); - - if (chlst.size()) - { - Shape_External_Filename_Chunk * sefc = (Shape_External_Filename_Chunk *)chlst.first_entry(); - - #if cencon - twprintf("Locating %s\n",sefc->file_name); - char * locatedfile = FindExistingFileInPath_PreferWriteable(CWnd::GetActiveWindow(),sefc->file_name,"RifSearchPath"); - twprintf("Loading %s\n",locatedfile ? locatedfile : sefc->file_name); - Sprite_Header_Chunk rfc(locatedfile ? locatedfile : sefc->file_name); - if (locatedfile) - { - delete[] locatedfile; - } - #else - Sprite_Header_Chunk rfc(sefc->file_name); - #endif - - if (rfc.error_code != 0) - { - return; - } - - lookup_child("SPRITVER",chlst); - int myver = -2; - if (chlst.size()) - { - Sprite_Version_Number_Chunk * svnc = (Sprite_Version_Number_Chunk *)chlst.first_entry(); - myver = svnc->version_num; - } - rfc.lookup_child("SPRITVER",chlst); - int yourver = -1; - if (chlst.size()) - { - Sprite_Version_Number_Chunk * svnc = (Sprite_Version_Number_Chunk *)chlst.first_entry(); - yourver = svnc->version_num; - } - - if (yourver != myver) - { - #define NOT_A_BITMAP_RELATED_CHUNK \ - strncmp ("BMPLSTST", child_ptr->identifier, 8) && \ - strncmp ("BMNAMVER", child_ptr->identifier, 8) && \ - strncmp ("BMNAMEXT", child_ptr->identifier, 8) && \ - strncmp ("RIFFNAME", child_ptr->identifier, 8) && \ - strncmp ("SHPEXTFN", child_ptr->identifier, 8) && \ - strncmp ("BMPMD5ID", child_ptr->identifier, 8) - - Chunk * child_ptr = children; - List <Chunk *> chunks_to_delete; - while (child_ptr != NULL) - { - if (NOT_A_BITMAP_RELATED_CHUNK) - { - chunks_to_delete.add_entry(child_ptr); - } - child_ptr = child_ptr->next; - } - for (LIF<Chunk *> delchunks(&chunks_to_delete); !delchunks.done(); delchunks.next()) - { - delete delchunks(); - } - - child_ptr = rfc.children; - while (child_ptr != NULL) - { - if (NOT_A_BITMAP_RELATED_CHUNK) - { - #define CREATE_CHUNK_END(_datablock) \ - new Miscellaneous_Chunk(this,_datablock,_datablock+12,*(int *)(_datablock+8)-12); - - #define CREATE_CHUNK_FOR(_datablock,_id,_chunkclass) \ - if (!strncmp(_datablock,_id,8)) { \ - new _chunkclass(this,_datablock+12,*(int *)(_datablock+8)-12); \ - } else - - child_ptr->prepare_for_output(); - char * datablock = child_ptr->make_data_block_from_chunk(); - - CREATE_CHUNK_FOR(datablock,"SPRITVER",Sprite_Version_Number_Chunk) - CREATE_CHUNK_FOR(datablock,"SPRITEPC",PC_Sprite_Chunk) - CREATE_CHUNK_FOR(datablock,"SPRITEPS",Playstation_Sprite_Chunk) - CREATE_CHUNK_FOR(datablock,"SPRITESA",Saturn_Sprite_Chunk) - CREATE_CHUNK_FOR(datablock,"SPRISIZE",Sprite_Size_Chunk) - CREATE_CHUNK_FOR(datablock,"SPRBMPSC",Sprite_Bitmap_Scale_Chunk) - CREATE_CHUNK_FOR(datablock,"SPRBMPCE",Sprite_Bitmap_Centre_Chunk) - CREATE_CHUNK_FOR(datablock,"SPREXTEN",Sprite_Extent_Chunk) - CREATE_CHUNK_END(datablock) - - delete[] datablock; - } - child_ptr = child_ptr->next; - } - - } - - Chunk_With_BMPs * blsc = 0; - Chunk_With_BMPs * gbnc = 0; - - rfc.lookup_child("BMPLSTST",chlst); - if (chlst.size()) - { - gbnc = (Chunk_With_BMPs *) chlst.first_entry(); - if (!gbnc->bmps.size()) gbnc = 0; - } - - List<Chunk *> oldlst; - lookup_child("BMPLSTST",oldlst); - assert (oldlst.size()<2); - - if (oldlst.size()) - { - blsc = (Bitmap_List_Store_Chunk *)oldlst.first_entry(); - } - else - { - if (gbnc) blsc = new Bitmap_List_Store_Chunk(this); - } - - BMP_Names_ExtraData * extended = 0; - if (blsc) - { - extended = blsc->GetExtendedData(); - if (fixpal) - extended->flags = (GlobalBMPFlags)(extended->flags | GBF_FIXEDPALETTE); - else - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_FIXEDPALETTE); - } - if (gbnc) - { - if ((gbnc->get_version_num()!=blsc->get_version_num()) || (gbnc->bmps.size() != blsc->bmps.size())) - { // other checks could be done as well - if (blsc->bmps.size()) - { - BOOL neednewpalette = FALSE; - - List<BMP_Name> newlist = gbnc->bmps; - for (LIF<BMP_Name> newLIF(&newlist); !newLIF.done(); newLIF.next()) - { - BMP_Name newcur = newLIF(); - newcur.flags = (BMPN_Flags) (newcur.flags & ~(COMPLETED_BMPN_FLAGS | ChunkBMPFlag_FixedPalette)); - if (fixpal) newcur.flags = (BMPN_Flags) (newcur.flags | ChunkBMPFlag_FixedPalette); - for (LIF<BMP_Name> oldLIF(&blsc->bmps); !oldLIF.done(); oldLIF.next()) - { - BMP_Name oldcur = oldLIF(); - if (newcur == oldcur) - { - // do we need to requantize? - if ((oldcur.flags ^ newcur.flags) & CHECKMODIFY_BMPN_FLAGS - || newcur.flags & ChunkBMPFlag_UsesTransparency - && !(newcur.flags & ChunkBMPFlag_IFF) - && !(oldcur.flags & ChunkBMPFlag_IFF) - && oldcur.DifferentTransparencyColour(newcur)) - oldcur.flags = (BMPN_Flags)(oldcur.flags & ~COMPLETED_BMPN_FLAGS); - // keep some of the old flags - the ones that can differ - newcur.flags = (BMPN_Flags)(newcur.flags & COPY_BMPN_FLAGS); - newcur.flags = (BMPN_Flags)(newcur.flags | oldcur.flags & ~COPY_BMPN_FLAGS); - if (oldcur.version_num != newcur.version_num) - { - neednewpalette = TRUE; - newcur.flags = (BMPN_Flags)(newcur.flags & ~ChunkBMPFlag_HistogramExists); - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - } - break; - } - } - if (oldLIF.done()) - { - // reset palette up to date flag - neednewpalette = TRUE; - newcur.flags = (BMPN_Flags)(newcur.flags & ~(ChunkBMPFlag_HistogramExists | COMPLETED_BMPN_FLAGS)); - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - } - newLIF.change_current(newcur); - } - - // check if any bitmaps have been removed - for (LIF<BMP_Name> bli(&blsc->bmps); !bli.done(); bli.next()) - { - if (!newlist.contains(bli())) - { - // delete assoc files - neednewpalette = TRUE; - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - } - } - - if (neednewpalette) - { - Palette_Outdated(envd); - if (fixpal) FixedPalette_Outdated(envd); - envd->updated = TRUE; - } - blsc->bmps = newlist; - } - else - { - blsc->bmps = gbnc->bmps; - for (LIF<BMP_Name> flagresetLIF(&blsc->bmps); !flagresetLIF.done(); flagresetLIF.next()) - { - BMP_Name current = flagresetLIF(); - current.flags = (BMPN_Flags)(current.flags & (COPY_BMPN_FLAGS & ~ChunkBMPFlag_FixedPalette)); - if (fixpal) current.flags = (BMPN_Flags) (current.flags | ChunkBMPFlag_FixedPalette); - flagresetLIF.change_current(current); - } - // reset palette up to date flag - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - Palette_Outdated(envd); - if (fixpal) FixedPalette_Outdated(envd); - envd->updated = TRUE; - } - blsc->max_index = gbnc->max_index; - blsc->set_version_num(gbnc->get_version_num()); - assert (!strcmp("RSPRITES",parent->identifier)); - ((Lockable_Chunk_With_Children *)parent)->updated = TRUE; - } - } - else - { - if (blsc) - { - if (blsc->bmps.size()) - { - // reset palette up to date flag - extended->flags = (GlobalBMPFlags)(extended->flags & ~GBF_HISTOGRAMEXISTS); - Palette_Outdated(envd); - if (fixpal) FixedPalette_Outdated(envd); - envd->updated = TRUE; - assert (!strcmp("RSPRITES",parent->identifier)); - ((Lockable_Chunk_With_Children *)parent)->updated = TRUE; - } - delete blsc; - } - } - - } - - } - Chunk_With_Children::post_input_processing(); -} -#endif -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SPRITEPC",PC_Sprite_Chunk,"SPRIHEAD",Sprite_Header_Chunk) - -PC_Sprite_Chunk::PC_Sprite_Chunk(Sprite_Header_Chunk* parent,const char* data,size_t datasize) -:Chunk_With_Children(parent,"SPRITEPC") -{ - const char * buffer_ptr = data; - - - while ((data-buffer_ptr)< (signed) datasize) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed) datasize) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - if (!strncmp(data, "SPRACTIO",8)) { - new Sprite_Action_Chunk (this, (data + 12), (*(int *) (data + 8))-12); - data += *(int *)(data + 8); - } - else { - new Miscellaneous_Chunk (this, data, (data + 12), (*(int *) (data + 8)) -12 ); - data += *(int *)(data + 8); - } - - } -} -///////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SPRITESA",Saturn_Sprite_Chunk,"SPRIHEAD",Sprite_Header_Chunk) - - -Saturn_Sprite_Chunk::Saturn_Sprite_Chunk(Sprite_Header_Chunk* parent,const char* data,size_t datasize) -:Chunk_With_Children(parent,"SPRITESA") -{ - const char * buffer_ptr = data; - - - while ((data-buffer_ptr)< (signed) datasize) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed) datasize) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - if (!strncmp(data, "SPRACTIO",8)) { - new Sprite_Action_Chunk (this, (data + 12), (*(int *) (data + 8))-12); - data += *(int *)(data + 8); - } - else { - new Miscellaneous_Chunk (this, data, (data + 12), (*(int *) (data + 8)) -12 ); - data += *(int *)(data + 8); - } - - } -} -///////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE_DECLARE_PARENT("SPRITEPS",Playstation_Sprite_Chunk,"SPRIHEAD",Sprite_Header_Chunk) - -Playstation_Sprite_Chunk::Playstation_Sprite_Chunk(Sprite_Header_Chunk* parent,const char* data,size_t datasize) -:Chunk_With_Children(parent,"SPRITEPS") -{ - const char * buffer_ptr = data; - - - while ((data-buffer_ptr)< (signed) datasize) { - - if ((*(int *)(data + 8)) + (data-buffer_ptr) > (signed) datasize) { - Parent_File->error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED; - break; - } - - if (!strncmp(data, "SPRACTIO",8)) { - new Sprite_Action_Chunk (this, (data + 12), (*(int *) (data + 8))-12); - data += *(int *)(data + 8); - } - else { - new Miscellaneous_Chunk (this, data, (data + 12), (*(int *) (data + 8)) -12 ); - data += *(int *)(data + 8); - } - - } -} - - - -//////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SPRISIZE",Sprite_Size_Chunk) - - -Sprite_Size_Chunk::Sprite_Size_Chunk(Chunk_With_Children* parent,const char* data,size_t /*datasize*/) -: Chunk(parent, "SPRISIZE") -{ - scale=*(double*)data; - data+=8; - maxy=*(double*)data; - data+=8; - maxx=*(double*)data; - data+=8; - radius=*(int*)data; - data+=4; - Flags=*(int*)data; - data+=4; -} - -Sprite_Size_Chunk::Sprite_Size_Chunk(Chunk_With_Children* parent) -: Chunk(parent, "SPRISIZE") -{ - scale=15.625; - maxy=1000; - maxx=500; - radius=0; - Flags=0; -} - -BOOL Sprite_Size_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -size_t Sprite_Size_Chunk::size_chunk() -{ - chunk_size=44; - return chunk_size; -} - -void Sprite_Size_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(double*)data_start=scale; - data_start+=8; - *(double*)data_start=maxy; - data_start+=8; - *(double*)data_start=maxx; - data_start+=8; - *(int*)data_start=radius; - data_start+=4; - *(int*)data_start=Flags; - data_start+=4; -} -/////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SPRITVER",Sprite_Version_Number_Chunk) - -Sprite_Version_Number_Chunk::Sprite_Version_Number_Chunk(Chunk_With_Children* parent,const char* data,size_t /*datasize*/) -: Chunk(parent, "SPRITVER") -{ - version_num=*(int*)data; - data+=4; -} - -Sprite_Version_Number_Chunk::Sprite_Version_Number_Chunk(Chunk_With_Children* parent) -: Chunk(parent, "SPRITVER") -{ - version_num=0; -} - -BOOL Sprite_Version_Number_Chunk::output_chunk (HANDLE &hand) -{ - unsigned long junk; - BOOL ok; - char * data_block; - - data_block = this->make_data_block_from_chunk(); - - ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); - - delete [] data_block; - - if (!ok) return FALSE; - - return TRUE; -} - -size_t Sprite_Version_Number_Chunk::size_chunk() -{ - chunk_size=16; - return chunk_size; -} - -void Sprite_Version_Number_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=version_num; -} - - -////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SPRBMPSC",Sprite_Bitmap_Scale_Chunk) - - -Sprite_Bitmap_Scale_Chunk::Sprite_Bitmap_Scale_Chunk(Chunk_With_Children* parent,const char* data,size_t /*datasize*/) -: Chunk(parent, "SPRBMPSC") -{ - NumBitmaps=*(int*)data; - data+=4; - if(NumBitmaps) - { - Scale=new float[NumBitmaps]; - for(int i=0;i<NumBitmaps;i++) - { - Scale[i]=*(float*)data; - data+=sizeof(float); - } - } - else - Scale=0; -} -Sprite_Bitmap_Scale_Chunk::Sprite_Bitmap_Scale_Chunk(Chunk_With_Children* parent) -: Chunk(parent, "SPRBMPSC") -{ - NumBitmaps=0; - Scale=0; -} -Sprite_Bitmap_Scale_Chunk::~Sprite_Bitmap_Scale_Chunk() -{ - delete [] Scale; -} -size_t Sprite_Bitmap_Scale_Chunk::size_chunk() -{ - chunk_size=16+sizeof(float)*NumBitmaps; - return chunk_size; -} - -void Sprite_Bitmap_Scale_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=NumBitmaps; - data_start+=4; - for(int i=0;i<NumBitmaps;i++) - { - *(float*)data_start=Scale[i]; - data_start+=sizeof(float); - } -} -///////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SPRBMPCE",Sprite_Bitmap_Centre_Chunk) - -Sprite_Bitmap_Centre_Chunk::Sprite_Bitmap_Centre_Chunk(Chunk_With_Children* parent,const char* data,size_t /*datasize*/) -: Chunk(parent, "SPRBMPCE") -{ - NumBitmaps=*(int*)data; - data+=4; - if(NumBitmaps) - { - CentreX=new int[NumBitmaps]; - CentreY=new int[NumBitmaps]; - OffsetX=new int[NumBitmaps]; - OffsetY=new int[NumBitmaps]; - - for(int i=0;i<NumBitmaps;i++) - { - CentreX[i]=*(int*)data; - data+=4; - CentreY[i]=*(int*)data; - data+=4; - OffsetX[i]=*(int*)data; - data+=4; - OffsetY[i]=*(int*)data; - data+=4; - } - } - else - { - CentreX=0; - CentreY=0; - OffsetX=0; - OffsetY=0; - } - spare=*(int*)data; -} -Sprite_Bitmap_Centre_Chunk::Sprite_Bitmap_Centre_Chunk(Chunk_With_Children* parent) -: Chunk(parent, "SPRBMPCE") -{ - NumBitmaps=0; - CentreX=CentreY=0; - OffsetX=OffsetY=0; - spare=0; -} -Sprite_Bitmap_Centre_Chunk::~Sprite_Bitmap_Centre_Chunk() -{ - delete [] CentreX; - delete [] CentreY; - delete [] OffsetX; - delete [] OffsetY; -} -size_t Sprite_Bitmap_Centre_Chunk::size_chunk() -{ - chunk_size=20+16*NumBitmaps; - return chunk_size; -} - -void Sprite_Bitmap_Centre_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=NumBitmaps; - data_start+=4; - for(int i=0;i<NumBitmaps;i++) - { - *(int*)data_start=CentreX[i]; - data_start+=4; - *(int*)data_start=CentreY[i]; - data_start+=4; - *(int*)data_start=OffsetX[i]; - data_start+=4; - *(int*)data_start=OffsetY[i]; - data_start+=4; - } - *(int*)data_start=spare; -} -///////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("SPREXTEN",Sprite_Extent_Chunk) - -Sprite_Extent_Chunk::Sprite_Extent_Chunk(Chunk_With_Children* parent,const char* data,size_t /*datasize*/) -: Chunk(parent, "SPREXTEN") -{ - minx=*(double*)data; - data+=8; - maxx=*(double*)data; - data+=8; - miny=*(double*)data; - data+=8; - maxy=*(double*)data; - data+=8; - spare1=*(int*)data; - data+=4; - spare2=*(int*)data; - data+=4; -} -Sprite_Extent_Chunk::Sprite_Extent_Chunk(Chunk_With_Children* parent) -: Chunk(parent, "SPREXTEN") -{ - minx=miny=-1000; - maxx=maxy=1000; - spare1=spare2=0; -} -size_t Sprite_Extent_Chunk::size_chunk() -{ - chunk_size=12+40; - return chunk_size; -} - -void Sprite_Extent_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(double*)data_start=minx; - data_start+=8; - *(double*)data_start=maxx; - data_start+=8; - *(double*)data_start=miny; - data_start+=8; - *(double*)data_start=maxy; - data_start+=8; - - *(int*)data_start=spare1; - data_start+=4; - *(int*)data_start=spare2; - data_start+=4; - -} diff --git a/3dc/win95/Sprchunk.hpp b/3dc/win95/Sprchunk.hpp deleted file mode 100644 index de0fff7..0000000 --- a/3dc/win95/Sprchunk.hpp +++ /dev/null @@ -1,175 +0,0 @@ -#ifndef _sprchunk_hpp -#define _sprchunk_hpp -#include "chunk.hpp" -#include "Chnktype.hpp" -//#include "stdafx.h" -struct Frame -{ - int Texture; - int CentreX; - int CentreY; - int UVCoords[4][2]; -#if cencon - int OldTexNum; -#endif -}; - -class Sprite_Header_Chunk : public Chunk_With_Children -{ -public: - Sprite_Header_Chunk(Chunk_With_Children* const parent,const char*,size_t const); - Sprite_Header_Chunk(const char* file_name, Chunk_With_Children * parent = NULL); - Sprite_Header_Chunk() - : Chunk_With_Children(0,"SPRIHEAD"){} - Sprite_Header_Chunk(Chunk_With_Children* parent) - : Chunk_With_Children(parent,"SPRIHEAD"){} - - write_file(const char* fname); - virtual BOOL output_chunk(HANDLE &hand); - #if cencon - virtual void post_input_processing(); - #endif - -}; - -class PC_Sprite_Chunk : public Chunk_With_Children -{ -public: - PC_Sprite_Chunk(Sprite_Header_Chunk* parent,const char*,size_t); - PC_Sprite_Chunk(Sprite_Header_Chunk* parent) - : Chunk_With_Children(parent,"SPRITEPC"){} -}; - -class Saturn_Sprite_Chunk : public Chunk_With_Children -{ -public: - Saturn_Sprite_Chunk(Sprite_Header_Chunk* parent,const char*,size_t); - Saturn_Sprite_Chunk(Sprite_Header_Chunk* parent) - : Chunk_With_Children(parent,"SPRITESA"){} -}; -class Playstation_Sprite_Chunk : public Chunk_With_Children -{ -public: - Playstation_Sprite_Chunk(Sprite_Header_Chunk* parent,const char*,size_t); - Playstation_Sprite_Chunk(Sprite_Header_Chunk* parent) - : Chunk_With_Children(parent,"SPRITEPS"){} -}; - - -#define SpriteActionFlag_FlipSecondSide 0x00000001 //for actions where only right facing views are available -class Sprite_Action_Chunk : public Chunk -{ -public: - Sprite_Action_Chunk(Chunk_With_Children* parent,const char*,size_t); - Sprite_Action_Chunk(Chunk_With_Children* parent); - ~Sprite_Action_Chunk(); - - virtual BOOL output_chunk (HANDLE &hand); - - virtual size_t size_chunk(); - - virtual void fill_data_block(char* data_start); - -public: - - int Action; - int NumYaw; - int NumPitch; - int NumFrames; - Frame*** FrameList; - int Flags; - int FrameTime; - -}; -#define SpriteFlag_NoLight 0x00000001 -#define SpriteFlag_SemiTrans 0x00000002 //for playstation -class Sprite_Size_Chunk : public Chunk -{ -public: - Sprite_Size_Chunk(Chunk_With_Children* parent,const char*,size_t); - Sprite_Size_Chunk(Chunk_With_Children* parent); - - virtual BOOL output_chunk (HANDLE &hand); - - virtual size_t size_chunk(); - - virtual void fill_data_block(char* data_start); - -public: - - double scale; - double maxy; - double maxx; - int radius; - int Flags ; -}; - -class Sprite_Extent_Chunk : public Chunk -{ -public: - Sprite_Extent_Chunk(Chunk_With_Children* parent,const char*,size_t); - Sprite_Extent_Chunk(Chunk_With_Children* parent); - - - virtual size_t size_chunk(); - - virtual void fill_data_block(char* data_start); - -public: - - double minx; - double maxx; - double miny; - double maxy; - int spare1,spare2; -}; - -class Sprite_Version_Number_Chunk : public Chunk -{ -public: - Sprite_Version_Number_Chunk(Chunk_With_Children* parent,const char*,size_t); - Sprite_Version_Number_Chunk(Chunk_With_Children* parent); - - virtual BOOL output_chunk (HANDLE &hand); - - virtual size_t size_chunk(); - - virtual void fill_data_block(char* data_start); - -public: - int version_num; -}; - -class Sprite_Bitmap_Scale_Chunk : public Chunk -{ -public : - Sprite_Bitmap_Scale_Chunk(Chunk_With_Children* parent,const char*,size_t); - Sprite_Bitmap_Scale_Chunk(Chunk_With_Children* parent); - ~Sprite_Bitmap_Scale_Chunk(); - - virtual size_t size_chunk(); - virtual void fill_data_block(char* data_start); - - int NumBitmaps; - float* Scale; -}; - -class Sprite_Bitmap_Centre_Chunk : public Chunk -{ -public : - Sprite_Bitmap_Centre_Chunk(Chunk_With_Children* parent,const char*,size_t); - Sprite_Bitmap_Centre_Chunk(Chunk_With_Children* parent); - ~Sprite_Bitmap_Centre_Chunk(); - - virtual size_t size_chunk(); - virtual void fill_data_block(char* data_start); - - int NumBitmaps; - int* CentreX; - int* CentreY; - int* OffsetX; - int* OffsetY; - int spare; - -}; -#endif diff --git a/3dc/win95/TEXIO.C b/3dc/win95/TEXIO.C deleted file mode 100644 index 27c85cb..0000000 --- a/3dc/win95/TEXIO.C +++ /dev/null @@ -1,1883 +0,0 @@ -#if 1 - - -#include "3dc.h" - -#include <conio.h> -#include <sys\stat.h> - -#include "inline.h" - -#ifdef RIFF_SYSTEM -#include "chnktexi.h" -#endif - -#define UseLocalAssert 0 -#include "ourasert.h" - -#else - -#include <stdio.h> -#include <conio.h> -#include <sys\stat.h> - -#include "system.h" -#include "equates.h" -#include "platform.h" -#include "shape.h" -#include "prototyp.h" -#include "inline.h" - -#ifdef RIFF_SYSTEM -#include "chnktexi.h" -#endif - - -#endif - - -#include "awTexLd.h" -#include "alt_tab.h" - -/* - #define for experimental purposes - ONLY!!! -*/ - -#define DefinedTextureType TextureTypePPM - - -#if 0 -#if debug -int tripa = 100; -int tripb = 100; -int tripc = 0; -#define trip_up tripa = tripb / tripc; -#endif -#endif - - -/* - - externs for commonly used global variables and arrays - -*/ - - extern SHAPEHEADER **mainshapelist; - extern (*ShapeLanguageFunctions[])(SHAPEINSTR *shapeinstrptr); - extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; - extern unsigned char *ScreenBuffer; - extern char projectsubdirectory[]; - extern int ScanDrawMode; - extern int VideoModeType; - -/* - - Global Variables for PC Functions - -*/ - - TEXTURE *ImageBuffer; /* Memory Resident Image Data */ - - #ifdef MaxImageGroups - #if MaxImageGroups < 2 /* optimize if this multiple groups are not required */ - #undef MaxImageGroups - #endif /* MaxImageGroups < 2 */ - #endif /* MaxImageGroups */ - - #ifdef MaxImageGroups - - #include "txioctrl.h" - - /* - basically, I want there to be more than one image header array - so that I can load some images once only, then load shapes, call - InitializeTextures, DeallocateAllImages, etc. and only the images associated - with the shapes load are deallocated. - I might want to load shapes in two blocks, calling InitializeTextures - for each load. - - There will need to be as many slots for ImageHeaderArrays as MaxImageGroups - - I want this to be completely invisible to anyone except programmers on - PC projects that require this feature - - Jake. - */ - - /* these three globals must behave the same */ - int NumImages = 0; /* # current images */ - IMAGEHEADER *ImageHeaderPtrs[MaxImageGroups*MaxImages]; /* Ptrs to Image Header Blocks */ - IMAGEHEADER ImageHeaderArray[MaxImageGroups*MaxImages]; /* Array of Image Headers */ - - int NumImagesArray[MaxImageGroups]; /* must be static to ensure initialization to zero */ - static int CurrentImageGroup = 0; - static IMAGEHEADER *NextFreeImageHeaderPtr[MaxImageGroups]; - - #else /* ! MaxImageGroups */ - - int NumImages = 0; /* # current images */ - IMAGEHEADER *ImageHeaderPtrs[MaxImages]; /* Ptrs to Image Header Blocks */ - IMAGEHEADER ImageHeaderArray[MaxImages]; /* Array of Image Headers */ - - static IMAGEHEADER *NextFreeImageHeaderPtr; - - #endif /* ! MaxImageGroups */ - - -/* - - Initialise General Texture Data Structures and Variables - -*/ - - -#if LoadingMapsShapesAndTexturesEtc - - -void InitialiseImageHeaders(void) - -{ - #ifdef MaxImageGroups - - NumImages = CurrentImageGroup * MaxImages; - NextFreeImageHeaderPtr[CurrentImageGroup] = &ImageHeaderArray[CurrentImageGroup*MaxImages]; - - #else - - NumImages = 0; - NextFreeImageHeaderPtr = ImageHeaderArray; - - #endif -} - - -int LoadImageCHsForShapes(SHAPEHEADER **shapelist) - -{ - - SHAPEHEADER **shlistptr; - SHAPEHEADER *shptr; - char **txfiles; - int TxIndex; - int LTxIndex; - - -/* - - Build the Texture List - -*/ - - shlistptr = shapelist; - - while(*shlistptr) { - - shptr = *shlistptr++; - - /* If the shape has textures */ - - if(shptr->sh_localtextures) { - - txfiles = shptr->sh_localtextures; - - LTxIndex = 0; - - while(*txfiles) { - - /* The RIFF Image loaders have changed to support not loading the same image twice - JH 17-2-96 */ - - char *src; - char *dst; - char fname[ImageNameSize]; - char *texfilesptr; - #ifndef RIFF_SYSTEM - int i, j, NewImage; - char *iname; - IMAGEHEADER *ihptr; - IMAGEHEADER *new_ihptr; - void* im; - #endif - - txfilesptr = *txfiles++; - - /* - - "txfilesptr" is in the form "textures\<fname>". We need to - prefix that text with the name of the current textures path. - - Soon this path may be varied but for now it is just the name of - the current project subdirectory. - - */ - - src = projectsubdirectory; - dst = fname; - - while(*src) - *dst++ = *src++; - - src = txfilesptr; - - while(*src) - *dst++ = *src++; - - *dst = 0; - - #ifdef RIFF_SYSTEM - - /* This function calls GetExistingImageHeader to figure out if the image is already loaded */ - TxIndex = CL_LoadImageOnce(fname,(ScanDrawDirectDraw == ScanDrawMode ? LIO_CHIMAGE : LIO_D3DTEXTURE)|LIO_TRANSPARENT|LIO_RELATIVEPATH|LIO_RESTORABLE); - GLOBALASSERT(GEI_NOTLOADED != TxIndex); - - #else - - /* If there are already images, try and find this one */ - - NewImage = Yes; - - #ifdef MaxImageGroups - - TxIndex = CurrentImageGroup * MaxImages; /* Assume image 0 */ - - if(NumImagesArray[CurrentImageGroup]) { - - for(i=NumImagesArray[CurrentImageGroup]; i!=0 && NewImage!=No; i--) { - - #else - - TxIndex = 0; /* Assume image 0 */ - - if(NumImages) { - - for(i=NumImages; i!=0 && NewImage!=No; i--) { - - #endif - - ihptr = ImageHeaderPtrs[TxIndex]; - - iname = &ihptr->ImageName[0]; - - j = CompareFilenameCH(txfilesptr, iname); - - if(j) NewImage = No; - - else TxIndex++; - - } - - } - - - /* If this is a new image, add it */ - - if(NewImage) { - - /* Get an Image Header */ - - new_ihptr = GetImageHeader(); - - if(new_ihptr) { - - if (ScanDrawMode == ScanDrawDirectDraw) - im = (void*) LoadImageCH(&fname[0], new_ihptr); - else - im = LoadImageIntoD3DImmediateSurface - (&fname[0], new_ihptr, DefinedTextureType); - - } - - } - - #endif - - /* - - The local index for this image in this shape is - "LTxIndex". - - The global index for the image is "TxIndex". - - We must go through the shape's items and change all the - local references to global. - - */ - - MakeShapeTexturesGlobal(shptr, TxIndex, LTxIndex); - - LTxIndex++; /* Next Local Texture */ - - } - - /* Is this shape a sprite that requires resizing? */ - - if((shptr->shapeflags & ShapeFlag_Sprite) && - (shptr->shapeflags & ShapeFlag_SpriteResizing)) { - - SpriteResizing(shptr); - - } - - } - - } - - - return Yes; - - -} - - -#else - - -#define InitTexPrnt No - -int InitialiseTextures(void) - -{ - - SHAPEHEADER **shlistptr; - SHAPEHEADER *shptr; - char **txfiles; - int TxIndex; - int LTxIndex; - - /* - - Free up any currently loaded images - - The caller is responsible for any other structures which might refer - to the currently loaded images - - */ - - #ifdef MaxImageGroups - - DeallocateCurrentImages(); - - NumImages = CurrentImageGroup * MaxImages; - NextFreeImageHeaderPtr[CurrentImageGroup] = &ImageHeaderArray[CurrentImageGroup*MaxImages]; - - #else - - DeallocateAllImages(); - - /* Initialise Image Header Variables */ - - NumImages = 0; - NextFreeImageHeaderPtr = ImageHeaderArray; - - #endif - - /* Added 23/3/98 by DHM so that this can be called without loading any - shapes (to get textprint working in the menus): - */ - if ( NULL == mainshapelist ) - { - return Yes; - // early exit - } - - /* Build the Texture List */ - - shlistptr = &mainshapelist[0]; - - while(*shlistptr) { - - shptr = *shlistptr++; - - /* If the shape has textures */ - - if(shptr->sh_localtextures) { - - #if InitTexPrnt - textprint("This shape has textures\n"); - #endif - - txfiles = shptr->sh_localtextures; - - LTxIndex = 0; - - while(*txfiles) { - - /* The RIFF Image loaders have changed to support not loading the same image twice - JH 17-2-96 */ - - char *src; - char *dst; - char fname[ImageNameSize]; - char *txfilesptr; - #ifndef RIFF_SYSTEM - int i, j, NewImage; - char *iname; - IMAGEHEADER *ihptr; - IMAGEHEADER *new_ihptr; - void* im; - #endif - - txfilesptr = *txfiles++; - - /* - - "txfilesptr" is in the form "textures\<fname>". We need to - prefix that text with the name of the current textures path. - - Soon this path may be varied but for now it is just the name of - the current project subdirectory. - - */ - - src = projectsubdirectory; - dst = fname; - - while(*src) - *dst++ = *src++; - - src = txfilesptr; - - while(*src) - *dst++ = *src++; - - *dst = 0; - - - #if InitTexPrnt - textprint(" A Texture\n"); - #endif - - - #ifdef RIFF_SYSTEM - - /* This function calls GetExistingImageHeader to figure out if the image is already loaded */ - TxIndex = CL_LoadImageOnce(fname,(ScanDrawDirectDraw == ScanDrawMode ? LIO_CHIMAGE : LIO_D3DTEXTURE)|LIO_TRANSPARENT|LIO_RELATIVEPATH|LIO_RESTORABLE); - GLOBALASSERT(GEI_NOTLOADED != TxIndex); - - #else - - /* If there are already images, try and find this one */ - - NewImage = Yes; - - #ifdef MaxImageGroups - - TxIndex = CurrentImageGroup * MaxImages; /* Assume image 0 */ - - if(NumImagesArray[CurrentImageGroup]) { - - for(i=NumImagesArray[CurrentImageGroup]; i!=0 && NewImage!=No; i--) { - - #else - - TxIndex = 0; /* Assume image 0 */ - - if(NumImages) { - - for(i=NumImages; i!=0 && NewImage!=No; i--) { - - #endif - - ihptr = ImageHeaderPtrs[TxIndex]; - - iname = &ihptr->ImageName[0]; - - j = CompareFilenameCH(txfilesptr, iname); - - if(j) NewImage = No; - - else TxIndex++; - - } - - } - - - /* If this is a new image, add it */ - - if(NewImage) { - - #if InitTexPrnt - textprint("New Image\n"); - WaitForReturn(); - #endif - - /* Get an Image Header */ - - new_ihptr = GetImageHeader(); - - if(new_ihptr) { - - if (ScanDrawMode == ScanDrawDirectDraw) - im = (void*) LoadImageCH(&fname[0], new_ihptr); - else - im = LoadImageIntoD3DImmediateSurface - (&fname[0], new_ihptr, DefinedTextureType); - - if(im) { - - #if InitTexPrnt - textprint("Load OK, NumImages = %d\n", NumImages); - WaitForReturn(); - #endif - - } - - } - - } - - - /* test */ - - #if InitTexPrnt - else textprint("Image Already Exists\n"); - #endif - - #endif - - /* - - The local index for this image in this shape is - "LTxIndex". - - The global index for the image is "TxIndex". - - We must go through the shape's items and change all the - local references to global. - - */ - - #if InitTexPrnt - textprint("\nLocal to Global for Shape\n"); - #endif - - MakeShapeTexturesGlobal(shptr, TxIndex, LTxIndex); - - LTxIndex++; /* Next Local Texture */ - - } - - /* Is this shape a sprite that requires resizing? */ - - if((shptr->shapeflags & ShapeFlag_Sprite) && - (shptr->shapeflags & ShapeFlag_SpriteResizing)) { - - SpriteResizing(shptr); - - } - - } - - } - - #if InitTexPrnt - textprint("\nFinished PP for textures\n"); - - WaitForReturn(); - - #endif - - - return Yes; - - -} - - -#endif - - -/* - - This function accepts a shape header, a global texture index and a local - index. It searches through all the items that use textures and converts all - local references to a texture to global references. - - The index to a texture that refers to the IMAGEHEADER pointer array is in - the low word of the colour int. - - Bit #15 is set if this index refers to a local texture. - - Here is an example of a textured item: - - -int CUBE_item3[]={ - - I_2dTexturedPolygon,3*vsize,0, - - (3<<TxDefn) + TxLocal + 0, - - 7*vsize,5*vsize,1*vsize,3*vsize, - Term - -}; - - - To test for a local texture use: - - if(ColourInt & TxLocal) - - - - NOTE - - The procedure is NOT reversible! - - If one wishes to reconstruct the table, all the shapes and textures must be - reloaded and the initialisation function recalled. - - Actually a function could be written that relates global filenames back to - local filenames, so in a sense that is not true. This function will only be - written if it is needed. - -*/ - -void MakeShapeTexturesGlobal(SHAPEHEADER *shptr, int TxIndex, int LTxIndex) - -{ - - int **ShapeItemArrayPtr; - POLYHEADER *ShapeItemPtr; - - #if SupportBSP - SHAPEDATA_BSP_BLOCK *ShapeBSPPtr; - int num_bsp_blocks; - int j, k; - #endif - - int i, txi; - - - /* Are the items in a pointer array? */ - - if(shptr->items) { - - #if InitTexPrnt - textprint("Item Array\n"); - #endif - - ShapeItemArrayPtr = shptr->items; - - for(i = shptr->numitems; i!=0; i--) { - - ShapeItemPtr = (POLYHEADER *) *ShapeItemArrayPtr++; - - #if SupportZBuffering - - if(ShapeItemPtr->PolyItemType == I_2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ZB_2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_Gouraud2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ZB_Gouraud2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_Gouraud3dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ZB_Gouraud3dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ScaledSprite - || ShapeItemPtr->PolyItemType == I_3dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ZB_3dTexturedPolygon) { - #else - if(ShapeItemPtr->PolyItemType == I_2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_Gouraud2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_Gouraud3dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ScaledSprite - || ShapeItemPtr->PolyItemType == I_3dTexturedPolygon){ - #endif /* SupportZBuffering */ - - if(ShapeItemPtr->PolyFlags & iflag_txanim) { - - MakeTxAnimFrameTexturesGlobal(shptr, ShapeItemPtr, - LTxIndex, TxIndex); - - } - - if(ShapeItemPtr->PolyColour & TxLocal) { - - txi = ShapeItemPtr->PolyColour; - txi &= ~TxLocal; /* Clear Flag */ - txi &= ClrTxDefn; /* Clear UV array index */ - - /* Is this the local index? */ - - if(txi == LTxIndex) { - - /* Clear low word, OR in global index */ - - ShapeItemPtr->PolyColour &= ClrTxIndex; - ShapeItemPtr->PolyColour |= TxIndex; - - } - - } - - } - - } - - } - - #if SupportBSP - - /* Or are they in a BSP block array? */ - - else if(shptr->sh_bsp_blocks) { - - #if InitTexPrnt - textprint("BSP Block Array\n"); - #endif - - #if 0 - /* Find the BSP Instruction */ - ShInstrPtr = shptr->sh_instruction; - num_bsp_blocks = 0; - while(ShInstrPtr->sh_instr != I_ShapeEnd) { - if(ShInstrPtr->sh_instr == I_ShapeBSPTree) { - num_bsp_blocks = ShInstrPtr->sh_numitems; - } - ShInstrPtr++; - } - #endif - - num_bsp_blocks = FindNumBSPNodes(shptr); - - - #if InitTexPrnt - textprint("Number of BSP blocks = %d\n", num_bsp_blocks); - #endif - - if(num_bsp_blocks) { - - ShapeBSPPtr = shptr->sh_bsp_blocks; - - for(k=num_bsp_blocks; k!=0; k--) { - - ShapeItemArrayPtr = ShapeBSPPtr->bsp_block_data; - - for(j=ShapeBSPPtr->bsp_numitems; j!=0; j--) { - - ShapeItemPtr = (POLYHEADER *) *ShapeItemArrayPtr++; - - #if InitTexPrnt - textprint("shape item\n"); - #endif - - if(ShapeItemPtr->PolyItemType == I_2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ZB_2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_Gouraud2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ZB_Gouraud2dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_Gouraud3dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ZB_Gouraud3dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ScaledSprite - || ShapeItemPtr->PolyItemType == I_3dTexturedPolygon - || ShapeItemPtr->PolyItemType == I_ZB_3dTexturedPolygon) { - - if(ShapeItemPtr->PolyFlags & iflag_txanim) { - - MakeTxAnimFrameTexturesGlobal(shptr, ShapeItemPtr, - LTxIndex, TxIndex); - - } - - #if InitTexPrnt - textprint(" - textured\n"); - #endif - - if(ShapeItemPtr->PolyColour & TxLocal) { - - #if InitTexPrnt - textprint(" - local index\n"); - #endif - - txi = ShapeItemPtr->PolyColour; - txi &= ~(TxLocal); /* Clear Flag */ - txi &= ClrTxDefn; /* Clear Defn */ - - #if InitTexPrnt - textprint(" - is %d\n", txi); - textprint(" - LTxIndex is %d\n", LTxIndex); - #endif - - /* Is this the local index? */ - - if(txi == LTxIndex) { - - /* Clear low word, OR in global index */ - - ShapeItemPtr->PolyColour &= ClrTxIndex; - ShapeItemPtr->PolyColour |= TxIndex; - - #if InitTexPrnt - textprint("Local %d, Global %d\n", LTxIndex, TxIndex); - #endif - - } - - } - - } - - } - - ShapeBSPPtr++; - - } - - } - - } - - #endif /* SupportBSP */ - - /* Otherwise the shape has no item data */ - - -} - - -/* - - The animated texture frames each have a local image index in their frame - header structure. Convert these to global texture list indices in the same - way that the item function does. - -*/ - -void MakeTxAnimFrameTexturesGlobal(SHAPEHEADER *sptr, - POLYHEADER *pheader, - int LTxIndex, int TxIndex) - -{ - - TXANIMHEADER **txah_ptr; - TXANIMHEADER *txah; - TXANIMFRAME *txaf; - int **shape_textures; - int *txf_imageptr; - int texture_defn_index; - int i, txi, image; - - - #if 0 - textprint("LTxIndex = %d, TxIndex = %d\n", LTxIndex, TxIndex); - WaitForReturn(); - #endif - - - /* Get the animation sequence header */ - - shape_textures = sptr->sh_textures; - texture_defn_index = (pheader->PolyColour >> TxDefn); - txah_ptr = (TXANIMHEADER **) shape_textures[texture_defn_index]; - - - /* The first array element is the sequence shadow, which we skip here */ - - txah_ptr++; - - - /* Process the animation sequences */ - - while(*txah_ptr) { - - /* Get the animation header */ - - txah = *txah_ptr++; - - /* Process the animation frames */ - - if(txah && txah->txa_numframes) { - - txaf = txah->txa_framedata; - - for(i = txah->txa_numframes; i!=0; i--) { - - /* Multi-View Sprite? */ - - if(sptr->shapeflags & ShapeFlag_MultiViewSprite) { - - txf_imageptr = (int *) txaf->txf_image; - - for(image = txah->txa_num_mvs_images; image!=0; image--) { - - if(*txf_imageptr & TxLocal) { - - txi = *txf_imageptr; - txi &= ~TxLocal; /* Clear Flag */ - - if(txi == LTxIndex) { - - *txf_imageptr = TxIndex; - - } - - } - - txf_imageptr++; - - } - - } - - else { - - if(txaf->txf_image & TxLocal) { - - txi = txaf->txf_image; - txi &= ~TxLocal; /* Clear Flag */ - - if(txi == LTxIndex) { - - txaf->txf_image = TxIndex; - - } - - } - - } - - txaf++; - - } - - } - - } - -} - - - -/* - - Sprite Resizing - - or - - An Optimisation For Sprite Images - - This shape is a sprite which has requested the UV rescaling optimisation. - The UV array is resized to fit the sprite image bounding rectangle, and - after the UV array, in the space provided (don't forget that!), is a new - shape local space XY array of points which overwrite the standard values - when the shape is displayed. - -*/ - -#define sr_print No - -void SpriteResizing(SHAPEHEADER *sptr) - -{ - - TXANIMHEADER **txah_ptr; - TXANIMHEADER *txah; - TXANIMFRAME *txaf; - int **shape_textures; - IMAGEHEADER *ihdr; - IMAGEEXTENTS e; - IMAGEEXTENTS e_curr; - IMAGEPOLYEXTENTS e_poly; - int *uvptr; - int texture_defn_index; - int **item_array_ptr; - int *item_ptr; - POLYHEADER *pheader; - int i, f; - int polypts[4 * vsize]; - int *iptr; - int *iptr2; - int *mypolystart; - int *ShapePoints = *(sptr->points); - VECTOR2D cen_poly; - VECTOR2D size_poly; - VECTOR2D cen_uv_curr; - VECTOR2D size_uv_curr; - VECTOR2D cen_uv; - VECTOR2D size_uv; - VECTOR2D tv; - int *txf_imageptr; - int **txf_uvarrayptr; - int *txf_uvarray; - int image; - int num_images; - - - #if sr_print - textprint("\nSprite Resize Shape\n\n"); - #endif - - - /* Get the animation sequence header */ - - shape_textures = sptr->sh_textures; - - item_array_ptr = sptr->items; /* Assume item array */ - item_ptr = item_array_ptr[0]; /* Assume only one polygon */ - pheader = (POLYHEADER *) item_ptr; - - - /* Get the polygon points, and at the same time the extents, assuming an XY plane polygon */ - - e_poly.x_low = bigint; - e_poly.y_low = bigint; - - e_poly.x_high = smallint; - e_poly.y_high = smallint; - - iptr = polypts; - mypolystart = &pheader->Poly1stPt; - - for(i = 4; i!=0; i--) { - - iptr[ix] = ((VECTORCH*)ShapePoints)[*mypolystart].vx; - iptr[iy] = ((VECTORCH*)ShapePoints)[*mypolystart].vy; - iptr[iz] = ((VECTORCH*)ShapePoints)[*mypolystart].vz; - - if(iptr[ix] < e_poly.x_low) e_poly.x_low = iptr[ix]; - if(iptr[iy] < e_poly.y_low) e_poly.y_low = iptr[iy]; - if(iptr[ix] > e_poly.x_high) e_poly.x_high = iptr[ix]; - if(iptr[iy] > e_poly.y_high) e_poly.y_high = iptr[iy]; - - iptr += vsize; - mypolystart++; - - } - - - /* TEST */ - /*trip_up;*/ - - - texture_defn_index = (pheader->PolyColour >> TxDefn); - txah_ptr = (TXANIMHEADER **) shape_textures[texture_defn_index]; - - - /* The first array element is the sequence shadow, which we skip here */ - - txah_ptr++; - - - /* Process the animation sequences */ - - while(*txah_ptr) { - - /* Get the animation header */ - - txah = *txah_ptr++; - - /* Process the animation frames */ - - if(txah && txah->txa_numframes) { - - txaf = txah->txa_framedata; - - for(f = txah->txa_numframes; f!=0; f--) { - - - /* Multi-View Sprite? */ - - if(sptr->shapeflags & ShapeFlag_MultiViewSprite) { - - txf_imageptr = (int *) txaf->txf_image; - num_images = txah->txa_num_mvs_images; - - txf_uvarrayptr = (int **) txaf->txf_uvdata; - - } - - /* A standard "Single View" Sprite has just one image */ - - else { - - txf_imageptr = &txaf->txf_image; - num_images = 1; - - txf_uvarrayptr = &txaf->txf_uvdata; - - } - - - for(image = 0; image < num_images; image++) { - - - #if sr_print - textprint("image %d of %d \n", (image + 1), num_images); - #endif - - - /* Get the image */ - - ihdr = ImageHeaderPtrs[txf_imageptr[image]]; - - /* Get the uv array ptr */ - - txf_uvarray = txf_uvarrayptr[image]; - - /* Find the extents of the image, assuming transparency */ - - #if 0 - FindImageExtents(ihdr, txaf->txf_numuvs, txaf->txf_uvdata, &e, &e_curr); - #else - FindImageExtents(ihdr, txaf->txf_numuvs, txf_uvarray, &e, &e_curr); - #endif - - /* Convert the image extents to fixed point */ - - #if sr_print - textprint("extents = %d, %d\n", e.u_low, e.v_low); - textprint(" %d, %d\n", e.u_high, e.v_high); - WaitForReturn(); - #endif - - e.u_low <<= 16; - e.v_low <<= 16; - e.u_high <<= 16; - e.v_high <<= 16; - - /* - - We now have all the information needed to create a NEW UV array and a NEW - polygon points XY array. - - */ - - /* Centre of the polygon */ - - cen_poly.vx = (e_poly.x_low + e_poly.x_high) / 2; - cen_poly.vy = (e_poly.y_low + e_poly.y_high) / 2; - - /* Size of the polygon */ - - size_poly.vx = e_poly.x_high - e_poly.x_low; - size_poly.vy = e_poly.y_high - e_poly.y_low; - - - /* Centre of the current cookie */ - - cen_uv_curr.vx = (e_curr.u_low + e_curr.u_high) / 2; - cen_uv_curr.vy = (e_curr.v_low + e_curr.v_high) / 2; - - /* Size of the current cookie */ - - size_uv_curr.vx = e_curr.u_high - e_curr.u_low; - size_uv_curr.vy = e_curr.v_high - e_curr.v_low; - - - /* Centre of the new cookie */ - - cen_uv.vx = (e.u_low + e.u_high) / 2; - cen_uv.vy = (e.v_low + e.v_high) / 2; - - /* Size of the new cookie */ - - size_uv.vx = e.u_high - e.u_low; - size_uv.vy = e.v_high - e.v_low; - - - /* Write out the new UV data */ - - #if 0 - uvptr = txaf->txf_uvdata; - #else - uvptr = txf_uvarray; - #endif - - - /* - - Convert the duplicate UV array to this new scale - ASSUME that the format is "TL, BL, BR, TR" - - */ - - uvptr[0] = e.u_low; - uvptr[1] = e.v_low; - - uvptr[2] = e.u_low; - uvptr[3] = e.v_high; - - uvptr[4] = e.u_high; - uvptr[5] = e.v_high; - - uvptr[6] = e.u_high; - uvptr[7] = e.v_low; - - - /* - - Create the new polygon XY array - - */ - - uvptr += (txaf->txf_numuvs * 2); /* Advance the pointer past the UV array */ - - - /* Copy the polygon points (XY only) to the UV array space */ - - iptr = polypts; - iptr2 = uvptr; - - for(i = 4; i!=0; i--) { - - iptr2[0] = iptr[ix]; - iptr2[1] = iptr[iy]; - - iptr += vsize; - iptr2 += 2; - - } - - - /* Scale the polygon points */ - - iptr = uvptr; - - for(i = 4; i!=0; i--) { - - iptr[0] = WideMulNarrowDiv(iptr[0], size_uv.vx, size_uv_curr.vx); - iptr[1] = WideMulNarrowDiv(iptr[1], size_uv.vy, size_uv_curr.vy); - - iptr += 2; - - } - - - /* The translation vector in UV space */ - - tv.vx = cen_uv.vx - cen_uv_curr.vx; - tv.vy = cen_uv.vy - cen_uv_curr.vy; - - - /* And now in world space */ - - tv.vx = WideMulNarrowDiv(tv.vx, size_poly.vx, size_uv_curr.vx); - tv.vy = WideMulNarrowDiv(tv.vy, size_poly.vy, size_uv_curr.vy); - - - /* Translate the polygon points */ - - iptr = uvptr; - - for(i = 4; i!=0; i--) { - - iptr[0] += tv.vx; - iptr[1] += tv.vy; - - iptr += 2; - - } - - - #if sr_print - textprint(" (image done)\n"); - #endif - - - } - - - #if sr_print - textprint("\n"); - #endif - - - /* Next Texture Animation Frame */ - - txaf++; - - } - - } - - } - - - #if sr_print - textprint("\nResize done\n\n"); - #endif - -} - - -/* - - This function is for animated sprites, although it has been given an interface that would - allow anyone to call it for their own purposes. It assumes that colour 0 is transparent and - then calculates the actual maximum extents of the image. - - NOTE: - - The image scanned is that given by the CURRENT UV ARRAY and may therefore be smaller than - the actual image. This allows for animation sequences with frames on the same image. - -*/ - -void FindImageExtents(IMAGEHEADER *ihdr, int numuvs, int *uvdata, IMAGEEXTENTS *e, IMAGEEXTENTS *e_curr) - -{ - - int i; - int *uvptr; - int u, v; - int startu, endu; - int startv, endv; - - - /* Find the current UV extents */ - - e_curr->u_low = bigint; - e_curr->v_low = bigint; - - e_curr->u_high = smallint; - e_curr->v_high = smallint; - - uvptr = uvdata; - - for(i = numuvs; i!=0; i--) { - - if(uvptr[0] < e_curr->u_low) e_curr->u_low = uvptr[0]; - if(uvptr[1] < e_curr->v_low) e_curr->v_low = uvptr[1]; - - if(uvptr[0] > e_curr->u_high) e_curr->u_high = uvptr[0]; - if(uvptr[1] > e_curr->v_high) e_curr->v_high = uvptr[1]; - - uvptr += 2; - - } - - - /* Look for the actual UV extents, assuming that colour 0 is transparent */ - - switch(VideoModeType) { - - case VideoModeType_8: - - { - - TEXTURE *tptr = ihdr->ImagePtr; - TEXTURE texel; - - - /* Search for u_low and v_low */ - - e->u_low = bigint; - e->v_low = bigint; - - startv = e_curr->v_low >> 16; - endv = e_curr->v_high >> 16; - startu = e_curr->u_low >> 16; - endu = e_curr->u_high >> 16; - - for(v = startv; v <= endv; v++) { - - for(u = startu; u <= endu; u++) { - - texel = tptr[(v * ihdr->ImageWidth) + u]; - - if(texel) { - - if(u < e->u_low) e->u_low = u; - if(v < e->v_low) e->v_low = v; - - } - - } - - } - - if(e->u_low == bigint) e->u_low = e_curr->u_low; - if(e->v_low == bigint) e->v_low = e_curr->v_low; - - - /* Search for u_high and v_high */ - - e->u_high = smallint; - e->v_high = smallint; - - for(v = endv; v >= startv; v--) { - - for(u = endu; u >= startu; u--) { - - texel = tptr[(v * ihdr->ImageWidth) + u]; - - if(texel) { - - if(u > e->u_high) e->u_high = u; - if(v > e->v_high) e->v_high = v; - - } - - } - - } - - if(e->u_high == smallint) e->u_high = e_curr->u_high; - if(e->v_high == smallint) e->v_high = e_curr->v_high; - - - /* TEST */ - /*trip_up;*/ - - } - - break; - - case VideoModeType_15: - break; - - case VideoModeType_24: - break; - - case VideoModeType_8T: - break; - - } - -} - - - -/* - - Return a pointer to the next image header - -*/ - - -IMAGEHEADER* GetImageHeader(void) -{ - - IMAGEHEADER *iheader; - - #ifdef MaxImageGroups - - /* NumImages always points to the correct point in the array */ - do - { - iheader = NextFreeImageHeaderPtr[CurrentImageGroup]++; - } - while (IsImageInUse(CurrentImageGroup,NumImagesArray[CurrentImageGroup]++) ? ++NumImages : 0); - - GLOBALASSERT(NumImagesArray[CurrentImageGroup] < MaxImages); - - #else - - iheader = NextFreeImageHeaderPtr++; - GLOBALASSERT(NumImages < MaxImages); - - #endif - - /* ensure flags are zero */ - memset(iheader,0,sizeof(IMAGEHEADER)); - - ImageHeaderPtrs[NumImages] = iheader; - NumImages++; - - return iheader; - -} - - -/* - - Return the address of a texture image in memory, else null - -*/ - -#if 0 -void* GetTexture(int texindex) - -{ - - /* Ahem... */ - - return No; - -} -#endif - -/* - - Allocate memory for a Texture Image - -*/ - -#if 0 -TEXTURE* GetTextureMemory(int txsize) - -{ - - /* Err... */ - return No; - -} -#endif - -/* - - Deallocate memory for a Texture Image - -*/ - -#if 0 -void ReturnTextureMemory(TEXTURE *txptr) - -{ - -} -#endif - -static void DeallocateImageHeader(IMAGEHEADER * ihptr) -{ - if (ihptr->hBackup) - { - if (ihptr->DDSurface) - { - GLOBALASSERT(!ihptr->D3DTexture); - ATRemoveSurface(ihptr->DDSurface); - } - else if (ihptr->D3DTexture) - { - GLOBALASSERT(!ihptr->DDSurface); - ATRemoveTexture(ihptr->D3DTexture); - } - - AwDestroyBackupTexture(ihptr->hBackup); - ihptr->hBackup = 0; - } - - if (ihptr->ImagePtr) - { - DeallocateMem(ihptr->ImagePtr); - ihptr->ImagePtr = 0; - } - - if (ihptr->DDSurface) - { - ReleaseDDSurface(ihptr->DDSurface); - ihptr->DDSurface = (void*) 0; - } - - if (ihptr->D3DTexture) - { - ReleaseD3DTexture(ihptr->D3DTexture); - ihptr->D3DTexture = (void*) 0; - ihptr->D3DHandle = (void*) 0; - } -} - -static void MinimizeImageHeader(IMAGEHEADER * ihptr) -{ - if (ihptr->DDSurface) - { - ReleaseDDSurface(ihptr->DDSurface); - ihptr->DDSurface = (void*) 0; - } - - if (ihptr->D3DTexture) - { - ReleaseD3DTexture(ihptr->D3DTexture); - ihptr->D3DTexture = (void*) 0; - ihptr->D3DHandle = (void*) 0; - } -} - -static void RestoreImageHeader(IMAGEHEADER * ihptr) -{ - if (ScanDrawDirectDraw != ScanDrawMode) - ReloadImageIntoD3DImmediateSurface(ihptr); -} - -#ifdef MaxImageGroups - -void SetCurrentImageGroup(unsigned int group) -{ - GLOBALASSERT(group < MaxImageGroups); - CurrentImageGroup = group; - NumImages = group*MaxImages + NumImagesArray[group]; -} - -int DeallocateCurrentImages(void) -{ - int i; - IMAGEHEADER *ihptr; - - if (NumImagesArray[CurrentImageGroup]) - { - ihptr = &ImageHeaderArray[CurrentImageGroup*MaxImages]; - for (i = 0; i < NumImagesArray[CurrentImageGroup]; ++i) - { - if (CanDeleteImage(CurrentImageGroup,i)) - DeallocateImageHeader(ihptr); - ++ihptr; - } - NumImagesArray[CurrentImageGroup] = 0; - NumImages = CurrentImageGroup * MaxImages; - NextFreeImageHeaderPtr[CurrentImageGroup] = &ImageHeaderArray[CurrentImageGroup*MaxImages]; - ImageGroupFreed(CurrentImageGroup); - } - - return Yes; /* ok for the moment */ -} - -void NowDeleteImage(int img_group, int img_num_offset) -{ - DeallocateImageHeader(&ImageHeaderArray[img_group*MaxImages+img_num_offset]); -} - -int DeallocateAllImages(void) -{ - int i, j; - IMAGEHEADER *ihptr; - - for (j=0; j<MaxImageGroups; ++j) - { - if (NumImagesArray[j]) - { - ihptr = &ImageHeaderArray[j*MaxImages]; - for (i = 0; i<NumImagesArray[j]; ++i) - { - if (CanDeleteImage(j,i)) - DeallocateImageHeader(ihptr); - ++ihptr; - } - NumImagesArray[j] = 0; - } - ImageGroupFreed(j); - } - NumImages = CurrentImageGroup * MaxImages; - NextFreeImageHeaderPtr[CurrentImageGroup] = &ImageHeaderArray[CurrentImageGroup*MaxImages]; - - return Yes; /* ok for the moment */ -} - -static void MinimizeImageCallback(int i, void * gP) -{ - int g = *(int *)gP; - MinimizeImageHeader(ImageHeaderPtrs[g*MaxImages+i]); -} - -int MinimizeAllImages(void) -{ - int i, j; - IMAGEHEADER *ihptr; - - for (j=0; j<MaxImageGroups; ++j) - { - if (NumImagesArray[j]) - { - ihptr = &ImageHeaderArray[j*MaxImages]; - for (i = 0; i<NumImagesArray[j]; ++i) - { - MinimizeImageHeader(ihptr); - ++ihptr; - } - } - EnumLeftoverImages(j,NumImagesArray[j],MinimizeImageCallback,&j); - } - - return Yes; /* ok for the moment */ -} - -static void RestoreImageCallback(int i, void * gP) -{ - int g = *(int *)gP; - RestoreImageHeader(ImageHeaderPtrs[g*MaxImages+i]); -} - -int RestoreAllImages(void) -{ - int i, j; - IMAGEHEADER *ihptr; - - for (j=0; j<MaxImageGroups; ++j) - { - if (NumImagesArray[j]) - { - ihptr = &ImageHeaderArray[j*MaxImages]; - for (i = 0; i<NumImagesArray[j]; ++i) - { - RestoreImageHeader(ihptr); - ++ihptr; - } - } - EnumLeftoverImages(j,NumImagesArray[j],RestoreImageCallback,&j); - } - - return Yes; /* ok for the moment */ -} - -#if debug - -struct ImageGroupDebugInfo -{ - int num_texels; - int num_images; - int num_shared; - int num_leftover; -}; - -static struct ImageGroupDebugInfo db_gp_info[MaxImageGroups]; - -static void DbShareImgCallback(int imgnum, void * user) -{ - int g = *(int *)user; - - ++db_gp_info[g].num_shared; -} - -static void DbLeftoverImgCallback(int i, void * user) -{ - int g = *(int *)user; - - ++db_gp_info[g].num_leftover; - - db_gp_info[g].num_texels += ImageHeaderPtrs[g*MaxImages+i]->ImageWidth * ImageHeaderPtrs[g*MaxImages+i]->ImageHeight; -} - -void ImageGroupsDebugPrintInit(void) -{ - int g; - for (g=0; g<MaxImageGroups; g++) - { - int i; - - db_gp_info[g].num_texels = 0; - db_gp_info[g].num_images = NumImagesArray[g]; - db_gp_info[g].num_shared = 0; - db_gp_info[g].num_leftover = 0; - - EnumSharedImages(g,NumImagesArray[g],DbShareImgCallback,&g); - EnumLeftoverImages(g,NumImagesArray[g],DbLeftoverImgCallback,&g); - - for (i=0; i<NumImagesArray[g]; ++i) - { - db_gp_info[g].num_texels += ImageHeaderPtrs[g*MaxImages+i]->ImageWidth * ImageHeaderPtrs[g*MaxImages+i]->ImageHeight; - } - } -} - -void ImageGroupsDebugPrint(void) -{ - int g; - textprint("IMAGE GROUP DEBUG INFO\nGP N_IMG N_SHR N_LFT N_TEXELS\n"); - for (g=0; g<MaxImageGroups; ++g) - { - textprint("%2d %5d %5d %5d %8d\n",g,db_gp_info[g].num_images,db_gp_info[g].num_shared,db_gp_info[g].num_leftover,db_gp_info[g].num_texels); - } -} - -#endif - -#else - -int DeallocateAllImages(void) -{ - int i; - IMAGEHEADER *ihptr; - - if (NumImages) - { - ihptr = ImageHeaderArray; - for (i = NumImages; i!=0; i--) - { - DeallocateImageHeader(ihptr++); - } - NumImages = 0; - NextFreeImageHeaderPtr = ImageHeaderArray; - } - - return Yes; /* ok for the moment */ -} - -int MinimizeAllImages(void) -{ - int i; - IMAGEHEADER *ihptr; - - if (NumImages) - { - ihptr = ImageHeaderArray; - for (i = NumImages; i!=0; i--) - { - MinimizeImageHeader(ihptr++); - } - } - - return Yes; /* ok for the moment */ -} - -int RestoreAllImages(void) -{ - int i; - IMAGEHEADER *ihptr; - - if (NumImages) - { - ihptr = ImageHeaderArray; - for (i = NumImages; i!=0; i--) - { - RestoreImageHeader(ihptr++); - } - } - - return Yes; /* ok for the moment */ -} - -#endif - - -#ifdef RIFF_SYSTEM - -/* -The RIFF_SYSTEM uses this function to return an image number -for an image which might be already loaded. The argument -passed points to the full pathname of the image that the -system wants to load, so an explicit stricmp on the -image names of already loaded images will suffice. To -avoid loading images more than once, it ensures that the -path generated for two identical images will always be -the same. It also fills in the ImageName field with the -fill path of images it loads. - -Currently I am assuming that users of ImageGroups will -no longer need images in group n+1 when images in group -n are deleted, so I can check in all groups from 0...Current -to see if the image is already loaded. - -Jake. -*/ - -int GetExistingImageNum(char const * fname) -{ - int i; - IMAGEHEADER * iharrayptr; - - #ifdef MaxImageGroups - - int g; - - for (g=0; g<MaxImageGroups; ++g) - { - for (i=0, iharrayptr = &ImageHeaderArray[g*MaxImages]; i<NumImagesArray[g]; ++i, ++iharrayptr) - { - if (!stricmp(iharrayptr->ImageName,fname)) - { - if (g!=CurrentImageGroup) - MarkImageInUseByGroup(g,i,CurrentImageGroup); - return i+g*MaxImages; - } - } - } - - #else - - for (i=0, iharrayptr = ImageHeaderArray; i<NumImages; ++i, ++iharrayptr) - { - if (!stricmp(iharrayptr->ImageName,fname)) return i; - } - - #endif - - return GEI_NOTLOADED; -} - -#endif - diff --git a/3dc/win95/TOOLCHNK.CPP b/3dc/win95/TOOLCHNK.CPP deleted file mode 100644 index b4a897b..0000000 --- a/3dc/win95/TOOLCHNK.CPP +++ /dev/null @@ -1,41 +0,0 @@ -#include "toolchnk.hpp" - -#ifdef cencon -#define new my_new -#endif - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(toolchnk) - -RIF_IMPLEMENT_DYNCREATE("CAMORIGN",Camera_Origin_Chunk) - -Camera_Origin_Chunk::Camera_Origin_Chunk(Chunk_With_Children* parent) -:Chunk(parent,"CAMORIGN") -{ - location.x=0; - location.y=0; - location.z=0; - ChunkMatrix identity={1,0,0,0,1,0,0,0,1}; - orientation=identity; -} - -Camera_Origin_Chunk::Camera_Origin_Chunk(Chunk_With_Children* parent,const char* data,size_t ) -:Chunk(parent,"CAMORIGN") -{ - location=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - orientation=*(ChunkMatrix*)data; -} - -void Camera_Origin_Chunk::fill_data_block(char * data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(ChunkVector*)data_start=location; - data_start+=sizeof(ChunkVector); - *(ChunkMatrix*)data_start=orientation; -} - diff --git a/3dc/win95/TOOLCHNK.HPP b/3dc/win95/TOOLCHNK.HPP deleted file mode 100644 index f266d72..0000000 --- a/3dc/win95/TOOLCHNK.HPP +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _toolchnk_hpp -#define _toolchnk_hpp - -#include "chunk.hpp" -#include "chnktype.hpp" - -class Camera_Origin_Chunk :public Chunk -{ -public : - Camera_Origin_Chunk(Chunk_With_Children* parent); - Camera_Origin_Chunk(Chunk_With_Children * parent,const char* data,size_t size); - - ChunkVector location; - ChunkMatrix orientation;//not used yet - - virtual void fill_data_block (char * data_start); - virtual size_t size_chunk (){return chunk_size=12+sizeof(ChunkVector)+sizeof(ChunkMatrix); } - - -}; - - -#endif
\ No newline at end of file diff --git a/3dc/win95/TXIOCTRL.CPP b/3dc/win95/TXIOCTRL.CPP deleted file mode 100644 index 53aded5..0000000 --- a/3dc/win95/TXIOCTRL.CPP +++ /dev/null @@ -1,110 +0,0 @@ -#include "txioctrl.h" - -#ifdef MaxImageGroups - -#include "list_tem.hpp" - -struct ImageNumber -{ - int group; - int offset; - - ImageNumber(){} - ImageNumber(int g,int o) : group(g), offset(o) {} - - inline int operator == (ImageNumber const & in2) const - { return group==in2.group && offset==in2.offset; } - inline int operator != (ImageNumber const & in2) const - { return ! operator == (in2); } -}; - -static List<ImageNumber> imgs_used_by_group[MaxImageGroups]; - -static List<int> * grps_used_by_image[MaxImageGroups][MaxImages]; - -void MarkImageInUseByGroup(int img_group, int img_num_offset, int group_using) -{ - if (imgs_used_by_group[group_using].contains(ImageNumber(img_group,img_num_offset))) return; - - imgs_used_by_group[group_using].add_entry(ImageNumber(img_group,img_num_offset)); - - List<int> * & grps_used_by_imageR = grps_used_by_image[img_group][img_num_offset]; - - if (!grps_used_by_imageR) - grps_used_by_imageR = new List<int>(img_group); // includes itself - - if (!grps_used_by_imageR->contains(group_using)) - grps_used_by_imageR->add_entry(group_using); -} - -int IsImageInUse(int img_group, int img_num_offset) -{ - if (grps_used_by_image[img_group][img_num_offset]) - return 1; - else - return 0; -} - -int CanDeleteImage(int img_group, int img_num_offset) -{ - if (grps_used_by_image[img_group][img_num_offset]) - { - if (grps_used_by_image[img_group][img_num_offset]->contains(img_group)) - { - grps_used_by_image[img_group][img_num_offset]->delete_entry(img_group); // remove itself - if (!grps_used_by_image[img_group][img_num_offset]->size()) - { - delete grps_used_by_image[img_group][img_num_offset]; - grps_used_by_image[img_group][img_num_offset] = 0; - return 1; - } - else - return 0; - } - else - return 0; - } - else - return 1; -} - -void ImageGroupFreed(int img_group) -{ - while (imgs_used_by_group[img_group].size()) - { - ImageNumber used = imgs_used_by_group[img_group].first_entry(); - - List<int> * & grps_used_by_imageR = grps_used_by_image[used.group][used.offset]; - - grps_used_by_imageR->delete_entry(img_group); - - if (!grps_used_by_imageR->size()) - { - NowDeleteImage(used.group,used.offset); - delete grps_used_by_imageR; - grps_used_by_imageR = 0; - } - - imgs_used_by_group[img_group].delete_first_entry(); - } -} - -void EnumSharedImages(int group_num, int numimages, ImageNumberCallbackFunction callback_fn, void * user) -{ - for (int i=0; i<numimages; ++i) - { - if (grps_used_by_image[group_num][i]) - callback_fn(i,user); - } -} - -void EnumLeftoverImages(int group_num, int numimages, ImageNumberCallbackFunction callback_fn, void * user) -{ - for (int i=numimages; i<MaxImages; ++i) - { - if (grps_used_by_image[group_num][i]) - callback_fn(i,user); - } -} - -#endif // MaxImageGroups diff --git a/3dc/win95/TXIOCTRL.H b/3dc/win95/TXIOCTRL.H deleted file mode 100644 index 556d986..0000000 --- a/3dc/win95/TXIOCTRL.H +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef _included_txioctrl_h_ -#define _included_txioctrl_h_ - -#include "system.h" - -#ifdef MaxImageGroups -#if MaxImageGroups < 2 /* optimize if this multiple groups are not required */ -#undef MaxImageGroups -#endif /* MaxImageGroups < 2 */ -#endif /* MaxImageGroups */ - -#ifdef MaxImageGroups - -#ifdef __cplusplus -extern "C" { -#endif - -void ImageGroupFreed(int img_group); - -void MarkImageInUseByGroup(int img_group, int img_num_offset, int group_using); - -int IsImageInUse(int img_group, int img_num_offset); - -int CanDeleteImage(int img_group, int img_num_offset); - -void NowDeleteImage(int img_group, int img_num_offset); - -#if debug - -void ImageGroupsDebugPrint(void); - -void ImageGroupsDebugPrintInit(void); - -#endif /* debug */ - -typedef void (*ImageNumberCallbackFunction) (int imgnum, void * user); - -void EnumSharedImages(int group_num, int numimages, ImageNumberCallbackFunction callback_fn, void * user); - -void EnumLeftoverImages(int group_num, int numimages, ImageNumberCallbackFunction callback_fn, void * user); - -#ifdef __cplusplus -} -#endif - -#endif /* MaxImageGroups */ - -#endif /* ! _included_txioctrl_h_ */ diff --git a/3dc/win95/VRAMTIME.C b/3dc/win95/VRAMTIME.C deleted file mode 100644 index a4fae03..0000000 --- a/3dc/win95/VRAMTIME.C +++ /dev/null @@ -1,33 +0,0 @@ -#include <windows.h> - -#include "vramtime.h" - -static DWORD transition_times_matrix[][VWS_MAXSTATES] = -{ -/* from DDRELEASE */ - { 0, 20, 0, 100, 100 }, -/* from D3DTEXRELEASE */ - { 20, 0, 100, 100, 100 }, -/* from DDCREATE */ - { 0, 100, 0, 20, 100 }, -/* from D3DTEXCREATE */ - { 20, 100, 20, 20, 100 }, -/* from UNKNOWN */ - { 100, 100, 100, 100, 100 } -}; - - -void WaitForVRamReady(VRAM_WAIT_STATE vws) -{ - static DWORD old_time = 0; - static VRAM_WAIT_STATE old_vws = VWS_UNKNOWN; - - DWORD new_time; - - if (0==old_time) old_time = timeGetTime(); - - do new_time = timeGetTime(); while (new_time - old_time < transition_times_matrix[old_vws][vws]); - - old_time = new_time; - old_vws = vws; -} diff --git a/3dc/win95/VRAMTIME.H b/3dc/win95/VRAMTIME.H deleted file mode 100644 index aa740c2..0000000 --- a/3dc/win95/VRAMTIME.H +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef _included_vramtime_h_ -#define _included_vramtime_h_ - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum VramWaitState -{ - VWS_DDRELEASE, - VWS_D3DTEXRELEASE, - VWS_DDCREATE, - VWS_D3DTEXCREATE, - VWS_UNKNOWN, - VWS_MAXSTATES - -} VRAM_WAIT_STATE; - -void WaitForVRamReady(VRAM_WAIT_STATE); - -#ifdef __cplusplus -} -#endif - -#endif /* ! _included_vramtime_h_ */ diff --git a/3dc/win95/VideoModes.cpp b/3dc/win95/VideoModes.cpp deleted file mode 100644 index a91af42..0000000 --- a/3dc/win95/VideoModes.cpp +++ /dev/null @@ -1,387 +0,0 @@ -extern "C" -{ - -#include "3dc.h" -#include "videomodes.h" -#include "awTexLd.h" // to set the surface format for Aw gfx dd surface loads - -extern LPDIRECTDRAW lpDD; -DEVICEANDVIDEOMODESDESC DeviceDescriptions[MAX_DEVICES]; -int NumberOfDevices; -int CurrentlySelectedDevice=0; -int CurrentlySelectedVideoMode=0; - -D3DDEVICEDESC D3DDeviceDesc; -int D3DDeviceDescIsValid; - - - -extern void GetDeviceAndVideoModePrefences(void); -static void SelectBasicDeviceAndVideoMode(void); -static void SetDeviceAndVideoModePreferences(void); -extern void SaveDeviceAndVideoModePreferences(void); -extern void LoadDeviceAndVideoModePreferences(void); - -HRESULT WINAPI D3DDeviceEnumerator(LPGUID lpGuid, - LPSTR lpDeviceDescription, LPSTR lpDeviceName, - LPD3DDEVICEDESC lpHWDesc, LPD3DDEVICEDESC lpHELDesc, LPVOID lpContext) -{ - /* hardware only please */ - if (!lpHWDesc->dcmColorModel) - { - return D3DENUMRET_OK; - } - - /* that'll do */ - D3DDeviceDesc = *lpHWDesc; - D3DDeviceDescIsValid = 1; - - return D3DENUMRET_CANCEL; -} - - - - - -HRESULT WINAPI EnumVideoModesCallback(LPDDSURFACEDESC2 pddsd, LPVOID Context) -{ - DEVICEANDVIDEOMODESDESC *dPtr = &DeviceDescriptions[NumberOfDevices]; - VIDEOMODEDESC *vmPtr = &(dPtr->VideoModes[dPtr->NumberOfVideoModes]); - - vmPtr->Width = pddsd->dwWidth; - vmPtr->Height = pddsd->dwHeight; - vmPtr->ColourDepth = pddsd->ddpfPixelFormat.dwRGBBitCount; - - if (vmPtr->ColourDepth<=8 || vmPtr->Width<512 || vmPtr->Height<384) - return DDENUMRET_OK; - - if (vmPtr->ColourDepth<=16) - { - if (!(D3DDeviceDesc.dwDeviceRenderBitDepth & DDBD_16)) - { - return DDENUMRET_OK; - } - } - else if (vmPtr->ColourDepth<=24) - { - if (!(D3DDeviceDesc.dwDeviceRenderBitDepth & DDBD_24)) - { - return DDENUMRET_OK; - } - } - else if (vmPtr->ColourDepth<=32) - { - if (!(D3DDeviceDesc.dwDeviceRenderBitDepth & DDBD_32)) - { - return DDENUMRET_OK; - } - } - - dPtr->NumberOfVideoModes++; - - if (dPtr->NumberOfVideoModes < MAX_VIDEOMODES) - { - return DDENUMRET_OK; - } - else - { - return DDENUMRET_CANCEL; - } -} - - -//----------------------------------------------------------------------------- -// Name: DDEnumCallbackEx() -// Desc: This callback gets the information for each device enumerated -//----------------------------------------------------------------------------- -BOOL WINAPI DDEnumCallbackEx(GUID *pGUID, LPSTR pDescription, LPSTR pName, LPVOID pContext, HMONITOR hm) -{ - LPDIRECTDRAW pDD; // DD1 interface, used to get DD4 interface - LPDIRECTDRAW4 pDD4 = NULL; // DirectDraw4 interface - LPDIRECT3D pD3D = NULL; - HRESULT hRet; - DDCAPS HELCaps; - - // Create the main DirectDraw object - hRet = DirectDrawCreate(pGUID, &pDD, NULL); - if (hRet != DD_OK) - { - return DDENUMRET_CANCEL; - } - - // Fetch DirectDraw4 interface - hRet = pDD->QueryInterface(IID_IDirectDraw4, (LPVOID *)&pDD4); - if (hRet != DD_OK) - { - return DDENUMRET_CANCEL; - } - - memset(&DeviceDescriptions[NumberOfDevices].DriverCaps, 0, sizeof(DDCAPS)); - DeviceDescriptions[NumberOfDevices].DriverCaps.dwSize = sizeof(DDCAPS); - memset(&HELCaps, 0, sizeof(DDCAPS)); - HELCaps.dwSize = sizeof(DDCAPS); - - hRet = pDD->GetCaps(&DeviceDescriptions[NumberOfDevices].DriverCaps, &HELCaps); - - if ((hRet != DD_OK) || !(DeviceDescriptions[NumberOfDevices].DriverCaps.dwCaps & DDCAPS_3D)) - { - // Finished with the DirectDraw object, so release it - if (pDD4) pDD4->Release(); - return DDENUMRET_OK; - } - - // Get the device information and save it - if (pGUID) - { - DeviceDescriptions[NumberOfDevices].DDGUID = *pGUID; - DeviceDescriptions[NumberOfDevices].DDGUIDIsSet = 1; - } - else - { - DeviceDescriptions[NumberOfDevices].DDGUIDIsSet = 0; - } - hRet = pDD4->GetDeviceIdentifier(&DeviceDescriptions[NumberOfDevices].DeviceInfo,0); - hRet = pDD4->GetDeviceIdentifier(&DeviceDescriptions[NumberOfDevices].DeviceInfoHost,DDGDI_GETHOSTIDENTIFIER); - - // check available video modes - DeviceDescriptions[NumberOfDevices].NumberOfVideoModes = 0; - - hRet = pDD->QueryInterface(IID_IDirect3D, (LPVOID*) &pD3D); - - hRet = pD3D->EnumDevices(D3DDeviceEnumerator, NULL); - if (pD3D) pD3D->Release(); - - if (!D3DDeviceDescIsValid) - { - // Finished with the DirectDraw object, so release it - if (pDD4) pDD4->Release(); - return DDENUMRET_OK; - } - - - hRet = pDD4->EnumDisplayModes(0, NULL, 0, EnumVideoModesCallback); - - - // Finished with the DirectDraw object, so release it - if (pDD4) pDD4->Release(); - - // Bump to the next open slot or finish the callbacks if full - if (NumberOfDevices < MAX_DEVICES) - NumberOfDevices++; - else - return DDENUMRET_CANCEL; - return DDENUMRET_OK; -} - - - - -int EnumerateCardsAndVideoModes(void) -{ - LPDIRECTDRAWENUMERATEEX pDirectDrawEnumerateEx; - HINSTANCE hDDrawDLL; - - NumberOfDevices=0; - - // Do a GetModuleHandle and GetProcAddress in order to get the - // DirectDrawEnumerateEx function - hDDrawDLL = GetModuleHandle("DDRAW"); - if (!hDDrawDLL) - { - return -1; - } - pDirectDrawEnumerateEx = (LPDIRECTDRAWENUMERATEEX )GetProcAddress(hDDrawDLL,"DirectDrawEnumerateExA"); - if (pDirectDrawEnumerateEx) - { - pDirectDrawEnumerateEx(DDEnumCallbackEx, NULL, - DDENUM_ATTACHEDSECONDARYDEVICES | - DDENUM_DETACHEDSECONDARYDEVICES | - DDENUM_NONDISPLAYDEVICES); - } - else - { - return -1; - } - - if (0 == NumberOfDevices) - { - return -1; - } - - LoadDeviceAndVideoModePreferences(); - return 0; -} - -char buffer[32]; -extern char *GetVideoModeDescription2(void) -{ - strncpy(buffer, DeviceDescriptions[CurrentlySelectedDevice].DeviceInfo.szDescription,24); - buffer[24] = 0; - return buffer; -} - -extern char *GetVideoModeDescription3(void) -{ - DEVICEANDVIDEOMODESDESC *dPtr = &DeviceDescriptions[CurrentlySelectedDevice]; - VIDEOMODEDESC *vmPtr = &(dPtr->VideoModes[CurrentlySelectedVideoMode]); - sprintf(buffer,"%dx%dx%d",vmPtr->Width,vmPtr->Height,vmPtr->ColourDepth); - return buffer; -} - -extern void PreviousVideoMode2(void) -{ - if (CurrentlySelectedVideoMode--<=0) - { - if(CurrentlySelectedDevice--<=0) - { - CurrentlySelectedDevice = NumberOfDevices-1; - } - CurrentlySelectedVideoMode = DeviceDescriptions[CurrentlySelectedDevice].NumberOfVideoModes-1; - } -} - -extern void NextVideoMode2(void) -{ - if (++CurrentlySelectedVideoMode>=DeviceDescriptions[CurrentlySelectedDevice].NumberOfVideoModes) - { - CurrentlySelectedVideoMode = 0; - if(++CurrentlySelectedDevice>=NumberOfDevices) - { - CurrentlySelectedDevice = 0; - } - } -} - -void GetCorrectDirectDrawObject(void) -{ - extern int SelectDirectDrawObject(LPGUID pGUID); - finiObjectsExceptDD(); - finiObjects(); - - if(DeviceDescriptions[CurrentlySelectedDevice].DDGUIDIsSet) - { - SelectDirectDrawObject(&DeviceDescriptions[CurrentlySelectedDevice].DDGUID); - } - else - { - SelectDirectDrawObject(NULL); - } - TestInitD3DObject(); -} - - -DEVICEANDVIDEOMODE PreferredDeviceAndVideoMode; - -extern void GetDeviceAndVideoModePrefences(void) -{ - int i; - - CurrentlySelectedDevice = -1; - CurrentlySelectedVideoMode = -1; - - for (i=0; i<NumberOfDevices; i++) - { - if (PreferredDeviceAndVideoMode.DDGUID == DeviceDescriptions[i].DDGUID) - { - CurrentlySelectedDevice = i; - break; - } - } - if (CurrentlySelectedDevice==-1) - { - SelectBasicDeviceAndVideoMode(); - return; - } - - DEVICEANDVIDEOMODESDESC *dPtr = &DeviceDescriptions[CurrentlySelectedDevice]; - for (i=0; i<dPtr->NumberOfVideoModes; i++) - { - if ((PreferredDeviceAndVideoMode.Width == dPtr->VideoModes[i].Width) - &&(PreferredDeviceAndVideoMode.Height == dPtr->VideoModes[i].Height) - &&(PreferredDeviceAndVideoMode.ColourDepth == dPtr->VideoModes[i].ColourDepth)) - { - CurrentlySelectedVideoMode = i; - break; - } - } - if (CurrentlySelectedDevice==-1) - { - SelectBasicDeviceAndVideoMode(); - return; - } - - SetDeviceAndVideoModePreferences(); -} - - -static void SelectBasicDeviceAndVideoMode(void) -{ - CurrentlySelectedDevice = -1; - CurrentlySelectedVideoMode = -1; - - /* look for a basic 640x480x16 bit mode */ - for (int d=0; d<NumberOfDevices; d++) - { - DEVICEANDVIDEOMODESDESC *dPtr = &DeviceDescriptions[d]; - - for (int i=0; i<dPtr->NumberOfVideoModes; i++) - { - if ((640 == dPtr->VideoModes[i].Width) - &&(480 == dPtr->VideoModes[i].Height) - &&(16 == dPtr->VideoModes[i].ColourDepth)) - { - CurrentlySelectedVideoMode = i; - CurrentlySelectedDevice = d; - break; - /* note this only breaks out of the video mode loop; - all drivers are scanned through */ - } - } - } - - if (CurrentlySelectedDevice==-1) - { - /* good grief, just pick the first possible thing */ - CurrentlySelectedDevice = 0; - CurrentlySelectedVideoMode = 0; - } - - SetDeviceAndVideoModePreferences(); -} - -static void SetDeviceAndVideoModePreferences(void) -{ - DEVICEANDVIDEOMODESDESC *dPtr = &DeviceDescriptions[CurrentlySelectedDevice]; - VIDEOMODEDESC *vmPtr = &(dPtr->VideoModes[CurrentlySelectedVideoMode]); - - PreferredDeviceAndVideoMode.DDGUID = dPtr->DDGUID; - PreferredDeviceAndVideoMode.DDGUIDIsSet = dPtr->DDGUIDIsSet; - PreferredDeviceAndVideoMode.Width = vmPtr->Width; - PreferredDeviceAndVideoMode.Height = vmPtr->Height; - PreferredDeviceAndVideoMode.ColourDepth = vmPtr->ColourDepth; - -} - -extern void SaveDeviceAndVideoModePreferences(void) -{ - SetDeviceAndVideoModePreferences(); - - FILE* file=fopen("AvP_Video.cfg","wb"); - if(!file) return; - fwrite(&PreferredDeviceAndVideoMode,sizeof(DEVICEANDVIDEOMODE),1,file); - fclose(file); -} -extern void LoadDeviceAndVideoModePreferences(void) -{ - FILE* file=fopen("AvP_Video.cfg","rb"); - if(!file) - { - SelectBasicDeviceAndVideoMode(); - return; - } - fread(&PreferredDeviceAndVideoMode,sizeof(DEVICEANDVIDEOMODE),1,file); - fclose(file); - GetDeviceAndVideoModePrefences(); -} - -};
\ No newline at end of file diff --git a/3dc/win95/VideoModes.h b/3dc/win95/VideoModes.h deleted file mode 100644 index 1e18200..0000000 --- a/3dc/win95/VideoModes.h +++ /dev/null @@ -1,40 +0,0 @@ -#define MAX_DEVICES 4 -#define MAX_VIDEOMODES 100 - - -typedef struct -{ - int Width; - int Height; - int ColourDepth; -} VIDEOMODEDESC; - -typedef struct -{ - GUID DDGUID; - int DDGUIDIsSet; - - DDDEVICEIDENTIFIER DeviceInfo; - DDDEVICEIDENTIFIER DeviceInfoHost; - DDCAPS DriverCaps; - - VIDEOMODEDESC VideoModes[MAX_VIDEOMODES]; - int NumberOfVideoModes; - -} DEVICEANDVIDEOMODESDESC; - -typedef struct -{ - GUID DDGUID; - int DDGUIDIsSet; - int Width; - int Height; - int ColourDepth; - -} DEVICEANDVIDEOMODE; - -extern DEVICEANDVIDEOMODESDESC DeviceDescriptions[MAX_DEVICES]; -extern int NumberOfDevices; -extern int CurrentlySelectedDevice; -extern int CurrentlySelectedVideoMode; - diff --git a/3dc/win95/ZMOUSE.H b/3dc/win95/ZMOUSE.H deleted file mode 100644 index 5064b31..0000000 --- a/3dc/win95/ZMOUSE.H +++ /dev/null @@ -1,164 +0,0 @@ -/**************************************************************************** -* * -* ZMOUSE.H -- Include file for IntelliMouse(tm) 1.0 * -* * -* NOTE: Zmouse.h contains #defines required when providing IntelliMouse * -* wheel support for Windows95 and NT3.51. Wheel is supported * -* natively in WinNT4.0, please refer to the NT4.0 SDK for more info * -* on providing support for IntelliMouse in NT4.0. * -* * -* Copyright (c) 1983-1996, Microsoft Corp. All rights reserved. * -* * -\***************************************************************************/ - - -/************************************************************************** - Client Appplication (API) Defines for Wheel rolling -***************************************************************************/ - - -// Apps need to call RegisterWindowMessage using the #define below to -// get the message number that is sent to the foreground window -// when a wheel roll occurs - -#ifdef UNICODE -#define MSH_MOUSEWHEEL L"MSWHEEL_ROLLMSG" -#else -#define MSH_MOUSEWHEEL "MSWHEEL_ROLLMSG" -#endif - // wParam = wheel rotation expressed in multiples of WHEEL_DELTA - // lParam is the mouse coordinates - -#define WHEEL_DELTA 120 // Default value for rolling one notch - - -#ifndef WM_MOUSEWHEEL -#define WM_MOUSEWHEEL (WM_MOUSELAST+1) // message that will be supported - // by the OS -#endif - - -/************************************************************************** - Client Appplication (API) Defines for - * determining if wheel support active - * determining # of Scroll Lines -***************************************************************************/ - -// Class name for MSWHEEL.EXE's invisible window -// use FindWindow to get hwnd to MSWHEEL -#ifdef UNICODE -#define MOUSEZ_CLASSNAME L"MouseZ" // wheel window class -#define MOUSEZ_TITLE L"Magellan MSWHEEL" // wheel window title -#else -#define MOUSEZ_CLASSNAME "MouseZ" // wheel window class -#define MOUSEZ_TITLE "Magellan MSWHEEL" // wheel window title -#endif - -#define MSH_WHEELMODULE_CLASS (MOUSEZ_CLASSNAME) -#define MSH_WHEELMODULE_TITLE (MOUSEZ_TITLE) - -// Apps need to call RegisterWindowMessage using the #defines -// below to get the message numbers for: -// 1) the message that can be sent to the MSWHEEL window to -// query if wheel support is active (MSH_WHEELSUPPORT)> -// 2) the message to query for the number of scroll lines -// (MSH_SCROLL_LINES) -// -// To send a message to MSWheel window, use FindWindow with the #defines -// for CLASS and TITLE above. If FindWindow fails to find the MSWHEEL -// window or the return from SendMessage is false, then Wheel support -// is not currently available. - -#ifdef UNICODE -#define MSH_WHEELSUPPORT L"MSH_WHEELSUPPORT_MSG" // name of msg to send - // to query for wheel support -#else -#define MSH_WHEELSUPPORT "MSH_WHEELSUPPORT_MSG" // name of msg to send - // to query for wheel support -#endif - -// MSH_WHEELSUPPORT -// wParam - not used -// lParam - not used -// returns BOOL - TRUE if wheel support is active, FALSE otherwise - - -#ifdef UNICODE -#define MSH_SCROLL_LINES L"MSH_SCROLL_LINES_MSG" -#else -#define MSH_SCROLL_LINES "MSH_SCROLL_LINES_MSG" -#endif - -// MSH_SCROLL_LINES -// wParam - not used -// lParam - not used -// returns int - number of lines to scroll on a wheel roll - -#ifndef WHEEL_PAGESCROLL -#define WHEEL_PAGESCROLL (UINT_MAX) // signifies to scroll a page, also - // defined in winuser.h in the - // NT4.0 SDK -#endif - -#ifndef SPI_SETWHEELSCROLLLINES -#define SPI_SETWHEELSCROLLLINES 105 // Also defined in winuser.h in the - // NT4.0 SDK, please see the NT4.0 SDK - // documentation for NT4.0 implementation - // specifics. - // For Win95 and WinNT3.51, - // Mswheel broadcasts the message - // WM_SETTINGCHANGE (equivalent to - // WM_WININICHANGE) when the scroll - // lines has changed. Applications - // will recieve the WM_SETTINGCHANGE - // message with the wParam set to - // SPI_SETWHEELSCROLLLINES. When - // this message is recieved the application - // should query Mswheel for the new - // setting. -#endif - - -/********************************************************************* -* INLINE FUNCTION: HwndMsWheel -* Purpose : Get a reference to MSWheel Window, the registered messages, -* wheel support active setting, and number of scrollLines -* Params : PUINT puiMsh_MsgMouseWheel - address of UINT to contain returned registered wheel message -* PUINT puiMsh_Msg3DSupport - address of UINT to contain wheel support registered message -* PUINT puiMsh_MsgScrollLines - address of UINT to contain Scroll lines registered message -* PBOOL pf3DSupport - address of BOOL to contain returned flag for wheel support active -* PINT piScrollLines - address of int to contain returned scroll lines -* Returns : HWND handle to the MsWheel window -* Note : The return value for pf3DSupport and piScrollLines is dependant -* on the POINT32 module. If POINT32 module is not running then -* the values returned for these parameters will be -* FALSE and 3, respectively. -*********************************************************************/ -__inline HWND HwndMSWheel( - PUINT puiMsh_MsgMouseWheel, - PUINT puiMsh_Msg3DSupport, - PUINT puiMsh_MsgScrollLines, - PBOOL pf3DSupport, - PINT piScrollLines -) -{ - HWND hdlMsWheel; - - hdlMsWheel = FindWindow(MSH_WHEELMODULE_CLASS, MSH_WHEELMODULE_TITLE); - - *puiMsh_MsgMouseWheel = RegisterWindowMessage(MSH_MOUSEWHEEL); - *puiMsh_Msg3DSupport = RegisterWindowMessage(MSH_WHEELSUPPORT); - *puiMsh_MsgScrollLines = RegisterWindowMessage(MSH_SCROLL_LINES); - - if (*puiMsh_Msg3DSupport) - *pf3DSupport = (BOOL)SendMessage(hdlMsWheel, *puiMsh_Msg3DSupport, 0, 0); - else - *pf3DSupport = FALSE; // default to FALSE - - if (*puiMsh_MsgScrollLines) - *piScrollLines = (int)SendMessage(hdlMsWheel, *puiMsh_MsgScrollLines, 0, 0); - else - *piScrollLines = 3; // default - - return(hdlMsWheel); -} diff --git a/3dc/win95/Zsp.cpp b/3dc/win95/Zsp.cpp deleted file mode 100644 index 1484812..0000000 --- a/3dc/win95/Zsp.cpp +++ /dev/null @@ -1,511 +0,0 @@ -#include <math.h> - -#if cencon -#include "AFXWIN.H" -#include "list_tem.hpp" - -#include "Vectors.hpp" -#include "environs.hpp" -#include "shpchunk.hpp" -#elif shpedit -#include "list_tem.hpp" -#include "Vectors.hpp" -#else -#include "list_tem.hpp" -#endif - -#include "zsp.hpp" - -#ifdef cencon -#define new my_new -#endif - -#if shpedit -#define twprintf printf -#endif - -// ZSP creation functions - -#if cencon -void generate_zsp_data (int num_cubes, CWnd * pWnd) -{ - Shape_Chunk * shpch = Sel_Obj->get_assoc_shape(); - - if (!shpch->lock_chunk(*(Main_Env.environment))) - { - char message[300]; - char * locker = "Unknown"; - - Shape_Header_Chunk * head = shpch->get_header(); - if (head) - locker = head->lock_user; - - sprintf (message, "Shape locked by %s\n can not continue", locker); - - pWnd->MessageBox (message, "Tools Control Area", - MB_ICONHAND + MB_OK + MB_TASKMODAL); - return; - } - start_text_window(pWnd); - - - ZSP_Data * zsp = new ZSP_Data (shpch->shape_data, num_cubes); - new Shape_ZSP_Data_Chunk (shpch, *zsp); - - shpch->unlock_chunk (*(Main_Env.environment), TRUE); - stop_text_window(); - - delete zsp; -} -#endif - -#if cencon || shpedit - -ZSP_Data::ZSP_Data (const ChunkShape & shp, int num_cubes) -{ - double xsize,ysize,zsize; - double max_size; - Vector cube_vector; - int num_subshapes; - - xsize = fabs(shp.max.x) + fabs(shp.min.x); - ysize = fabs(shp.max.y) + fabs(shp.min.y); - zsize = fabs(shp.max.z) + fabs(shp.min.z); - - max_size=max(xsize,ysize); - max_size=max(max_size,zsize); - - cube_size = max_size / num_cubes; - - int nc = num_cubes+2; - - num_x_cubes = nc-(int) ( nc-(xsize / cube_size) ); - num_y_cubes = nc-(int) ( nc-(ysize / cube_size) ); - num_z_cubes = nc-(int) ( nc-(zsize / cube_size) ); - - cube_vector.x = cube_size / 2; - cube_vector.y = cube_size / 2; - cube_vector.z = cube_size / 2; - cube_radius = mod(cube_vector); - - num_subshapes = num_x_cubes * num_y_cubes * num_z_cubes; - - int i,j,k; - double xstart, ystart, zstart; - double xstart_tmp, ystart_tmp, zstart_tmp; - - - xstart = shp.min.x; - ystart = shp.min.y; - zstart = shp.min.z; - - xstart_tmp = xstart; - - twprintf ("Number of zones is \n",num_subshapes); - - for(i = 0; i < num_x_cubes; i++) { - - twprintf ("x = %d\n",i); - - ystart_tmp = ystart; - - for(j = 0; j < num_y_cubes; j++) { - - twprintf ("y = %d\nz = ",j); - - zstart_tmp = zstart; - - for(k = 0; k < num_z_cubes; k++) { - - twprintf ("%d ",k); - - /* Process the subshape and update the ZSP pointer array */ - - ZSP_zone temp_zone(shp, xstart_tmp, ystart_tmp, - zstart_tmp, cube_size); - - zone_array.add_entry(temp_zone); - - zstart_tmp += cube_size; - - } - - twprintf ("\n"); - - ystart_tmp += cube_size; - - } - - xstart_tmp += cube_size; - - } - - - -} - - - -static int zone_polygons[20000]; -static unsigned char vertex_outcode [20000]; - -ZSP_zone::ZSP_zone (const ChunkShape & shp, double xstart, double ystart, - double zstart, double cube_size) -{ - double xplane0, xplane1; - double yplane0, yplane1; - double zplane0, zplane1; - int i,j; - int outcode_or, outcode_and; - int vert_outcode; - - num_z_polys = 0; - num_z_verts = 0; - - /* Bounding planes in terms of axis limits */ - - xplane0 = xstart; - xplane1 = xstart + cube_size; - - yplane0 = ystart; - yplane1 = ystart + cube_size; - - zplane0 = zstart; - zplane1 = zstart + cube_size; - - for (i=0; i<shp.num_polys; i++) - { - for (j=0; j<shp.poly_list[i].num_verts; j++) - { - vert_outcode = 0; - - int point_no = shp.poly_list[i].vert_ind[j]; - - if(shp.v_list[point_no].x < xplane0) vert_outcode |= rsp_oc_x0; - if(shp.v_list[point_no].x > xplane1) vert_outcode |= rsp_oc_x1; - if(shp.v_list[point_no].y < yplane0) vert_outcode |= rsp_oc_y0; - if(shp.v_list[point_no].y > yplane1) vert_outcode |= rsp_oc_y1; - if(shp.v_list[point_no].z < zplane0) vert_outcode |= rsp_oc_z0; - if(shp.v_list[point_no].z > zplane1) vert_outcode |= rsp_oc_z1; - - if(j==0) { - - outcode_or = vert_outcode; - outcode_and = vert_outcode; - - } - - else { - - outcode_or |= vert_outcode; - outcode_and &= vert_outcode; - - } - - } - - if (outcode_and == 0) - { - zone_polygons[num_z_polys] = i; - num_z_polys++; - } - - } - - if (!num_z_polys) - { - z_poly_list=0; - z_vert_list=0; - return; - } - - z_poly_list = new int [num_z_polys]; - for (i=0; i<num_z_polys; i++) - { - z_poly_list[i] = zone_polygons[i]; - } - - for (i=0; i<shp.num_verts; i++) - { - vertex_outcode[i] = 0; - } - - for (i=0; i<num_z_polys; i++) - { - for (j=0; j<shp.poly_list[z_poly_list[i]].num_verts; j++) - { - vertex_outcode[shp.poly_list[z_poly_list[i]].vert_ind[j]] = 1; - } - } - - for (i=0; i<shp.num_verts; i++) - { - if (vertex_outcode[i]) num_z_verts++; - } - - z_vert_list = new int[num_z_verts]; - - j=0; - - for (i=0; i<shp.num_verts; i++) - { - if (vertex_outcode[i]) - z_vert_list[j++] = i; - } - -} - -#endif - - -ZSP_Data::~ZSP_Data() -{ - while (zone_array.size()) - { - zone_array.delete_first_entry(); - } -} - -ZSP_Data::ZSP_Data (const char * zdata, size_t /*zsize*/) -{ - const char * ptr = zdata; - - num_x_cubes = *((int *) ptr); - ptr += 4; - - num_y_cubes = *((int *) ptr); - ptr += 4; - - num_z_cubes = *((int *) ptr); - ptr += 4; - - cube_size = *((double *) ptr); - ptr += 8; - - cube_radius = *((double *) ptr); - ptr += 8; - - int i,j; - - int numzones = num_x_cubes*num_y_cubes*num_z_cubes; - - for (i=0; i<numzones; i++) - { - ZSP_zone tmpzone; - - tmpzone.num_z_polys = *((int *) ptr); - ptr += 4; - - tmpzone.num_z_verts = *((int *) ptr); - ptr += 4; - - if (tmpzone.num_z_polys) - tmpzone.z_poly_list = new int [tmpzone.num_z_polys]; - - for (j=0; j<tmpzone.num_z_polys; j++) - { - tmpzone.z_poly_list[j] = *((int *) ptr); - ptr += 4; - } - - if (tmpzone.num_z_verts) - tmpzone.z_vert_list = new int [tmpzone.num_z_verts]; - - for (j=0; j<tmpzone.num_z_verts; j++) - { - tmpzone.z_vert_list[j] = *((int *) ptr); - ptr += 4; - } - - zone_array.add_entry(tmpzone); - } - -} - - -ZSP_zone::ZSP_zone () -{ - num_z_polys = 0; - z_poly_list = 0; - num_z_verts = 0; - z_vert_list = 0; -} - -ZSP_zone::~ZSP_zone () -{ - if (num_z_polys) - delete [] z_poly_list; - if (num_z_verts) - delete [] z_vert_list; -} - -ZSP_zone::ZSP_zone (const ZSP_zone &zz) -{ - if (zz.num_z_polys) - { - num_z_polys = zz.num_z_polys; - z_poly_list = new int [num_z_polys]; - - int i; - - for (i=0; i<num_z_polys; i++) - { - z_poly_list[i] = zz.z_poly_list[i]; - } - } - else - { - z_poly_list = 0; - num_z_polys = 0; - } - - - if (zz.num_z_verts) - { - num_z_verts = zz.num_z_verts; - z_vert_list = new int [num_z_verts]; - - int i; - - for (i=0; i<num_z_verts; i++) - { - z_vert_list[i] = zz.z_vert_list[i]; - } - } - else - { - z_vert_list = 0; - num_z_verts = 0; - } - -} - -ZSP_zone & ZSP_zone::operator=(const ZSP_zone &zz) -{ - - if (num_z_polys) - delete [] z_poly_list; - if (num_z_verts) - delete [] z_vert_list; - - if (zz.num_z_polys) - { - num_z_polys = zz.num_z_polys; - z_poly_list = new int [num_z_polys]; - - int i; - - for (i=0; i<num_z_polys; i++) - { - z_poly_list[i] = zz.z_poly_list[i]; - } - } - else - { - z_poly_list = 0; - num_z_polys = 0; - } - - - if (zz.num_z_verts) - { - num_z_verts = zz.num_z_verts; - z_vert_list = new int [num_z_verts]; - - int i; - - for (i=0; i<num_z_verts; i++) - { - z_vert_list[i] = zz.z_vert_list[i]; - } - } - else - { - z_vert_list = 0; - num_z_verts = 0; - } - - return(*this); - -} - - -unsigned char operator==(const ZSP_zone &z1, const ZSP_zone &z2) -{ - return(&z1 == &z2); -} - -unsigned char operator!=(const ZSP_zone &z1, const ZSP_zone &z2) -{ - return(&z1 != &z2); -} - - - -///////////////////////////////////////// - -// Class Shape_ZSP_Data_Chunk functions - -size_t Shape_ZSP_Data_Chunk::size_chunk () -{ - int sz = 12 + 12 + 16; - - ZSP_Data * zdata = (ZSP_Data *)(&zspdata); - - for (LIF<ZSP_zone> znl(&zdata->zone_array); !znl.done(); znl.next()) - { - sz += 8 + (znl().num_z_polys * 4) + (znl().num_z_verts * 4); - } - - return (chunk_size = sz); -} - -void Shape_ZSP_Data_Chunk::fill_data_block ( char * data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = zspdata.num_x_cubes; - data_start += 4; - - *((int *) data_start) = zspdata.num_y_cubes; - data_start += 4; - - *((int *) data_start) = zspdata.num_z_cubes; - data_start += 4; - - *((double *) data_start) = zspdata.cube_size; - data_start += 8; - - *((double *) data_start) = zspdata.cube_radius; - data_start += 8; - - ZSP_Data * zdata = (ZSP_Data *)(&zspdata); - - for (LIF<ZSP_zone> znl(&zdata->zone_array); !znl.done(); znl.next()) - { - *((int *) data_start) = znl().num_z_polys; - data_start += 4; - - *((int *) data_start) = znl().num_z_verts; - data_start += 4; - - int i; - for (i=0; i<znl().num_z_polys; i++) - { - *((int *) data_start) = znl().z_poly_list[i]; - data_start += 4; - } - - for (i=0; i<znl().num_z_verts; i++) - { - *((int *) data_start) = znl().z_vert_list[i]; - data_start += 4; - } - } -} diff --git a/3dc/win95/Zsp.hpp b/3dc/win95/Zsp.hpp deleted file mode 100644 index 8f008b5..0000000 --- a/3dc/win95/Zsp.hpp +++ /dev/null @@ -1,107 +0,0 @@ -#ifndef _zsp_hpp -#define _zsp_hpp 1 - -#include "shpchunk.hpp" - - -#define rsp_oc_x0 0x00000001 -#define rsp_oc_x1 0x00000002 -#define rsp_oc_y0 0x00000004 -#define rsp_oc_y1 0x00000008 -#define rsp_oc_z0 0x00000010 -#define rsp_oc_z1 0x00000020 - - -// this file should be included from chunk.hpp - - -struct ChunkShape; - -struct ZSP_zone -{ -#if (cencon || shpedit) - ZSP_zone (const ChunkShape &, double, double, double, double); -#endif - - ZSP_zone (); - ~ZSP_zone(); - - ZSP_zone (const ZSP_zone &); - ZSP_zone & operator=(const ZSP_zone &); - - int num_z_polys; - int * z_poly_list; - int num_z_verts; - int * z_vert_list; - - friend unsigned char operator==(const ZSP_zone &, const ZSP_zone &); - friend unsigned char operator!=(const ZSP_zone &, const ZSP_zone &); -}; - - -class ZSP_Data -{ - -public: - -#if (cencon || shpedit) - ZSP_Data (const ChunkShape &, int); -#endif - - ZSP_Data (const char * zdata, size_t zsize); - - ~ZSP_Data (); - - double cube_size; - double cube_radius; - - int num_x_cubes, num_y_cubes, num_z_cubes; - - List<ZSP_zone> zone_array; - - -}; - - -///////////////////////////////////////// - -class Shape_ZSP_Data_Chunk : public Chunk -{ -public: - -#if cencon || shpedit - Shape_ZSP_Data_Chunk (Shape_Sub_Shape_Chunk * parent, ZSP_Data zspin) - : Chunk(parent, "SHPZSPDT"), zspdata (zspin) - {} - - Shape_ZSP_Data_Chunk (Shape_Chunk * parent, ZSP_Data zspin) - : Chunk(parent, "SHPZSPDT"), zspdata (zspin) - {} -#endif - - const ZSP_Data zspdata; - - size_t size_chunk (); - void fill_data_block (char *); - - Shape_ZSP_Data_Chunk (Shape_Sub_Shape_Chunk * parent, const char * zdata, size_t zsize) - : Chunk (parent, "SHPZSPDT"), zspdata (zdata, zsize) - {} - - Shape_ZSP_Data_Chunk (Shape_Chunk * parent, const char * zdata, size_t zsize) - : Chunk (parent, "SHPZSPDT"), zspdata (zdata, zsize) - {} - -}; - - - - - - - - - - - -#endif diff --git a/3dc/win95/advwin32.h b/3dc/win95/advwin32.h deleted file mode 100644 index da57f87..0000000 --- a/3dc/win95/advwin32.h +++ /dev/null @@ -1,111 +0,0 @@ -/************************************************************* -Module name: AdvWin32.H -Notices: Copyright (c) 1995 Jeffrey Richter -*************************************************************/ - -#ifndef ADVWIN32_H_INCLUDED -#define ADVWIN32_H_INCLUDED - -/* Disable Visual C++ warnings which fire when reading Windows OS headers. */ -#ifndef __WATCOMC__ - -/* Disable ridiculous warnings so that the code */ -/* compiles cleanly using warning level 4. */ - -/* nonstandard extension 'single line comment' was used */ -#pragma warning(disable: 4001) - -// nonstandard extension used : nameless struct/union -#pragma warning(disable: 4201) - -// nonstandard extension used : bit field types other than int -#pragma warning(disable: 4214) - -// Note: Creating precompiled header -#pragma warning(disable: 4699) - -// unreferenced inline function has been removed -#pragma warning(disable: 4514) - -// unreferenced formal parameter -#pragma warning(disable: 4100) - -// 'type' differs in indirection to slightly different base -// types from 'other type' -#pragma warning(disable: 4057) - -// named type definition in parentheses -#pragma warning(disable: 4115) - -// nonstandard extension used : benign typedef redefinition -#pragma warning(disable: 4209) - -// conditional expression is constant : used to differentiate between internal and external versions -#pragma warning(disable: 4127) - -// comma operator in array index, disabled due to assertions in array indicies -#pragma warning(disable: 4709) - -// assignment operator could not be generated, disable as often the operator isn't used. -#pragma warning(disable: 4512) - -// 'function' selected for automatic inline expansion - when a function not declared inline was inlined: well done compiler, aren't you clever! -#pragma warning(disable: 4711) - -// 'function' not expanded. -#pragma warning(disable: 4710) - -#pragma warning(disable: 4032) - -#pragma warning(disable: 4702) - -///////////////////////////////////////////////////////////// - -// Create an ARRAY_SIZE macro that returns the number of -// elements in an array. This is a handy macro that I use -// frequently throughout the sample applications. -#define ARRAY_SIZE(Array) \ - (sizeof(Array) / sizeof((Array)[0])) - -///////////////////////////////////////////////////////////// - -// Create a BEGINTHREADEX macro that calls the C run-time's -// _beginthreadex function. The C run-time library doesn't -// want to have any reliance on Win32 data types such as -// HANDLE. This means that a Win32 programmer needs to cast -// the return value to a HANDLE. This is terribly inconvenient, -// so I have created this macro to perform the casting. -typedef unsigned (__stdcall *PTHREAD_START) (void *); - -#define BEGINTHREADEX(lpsa, cbStack, lpStartAddr, \ - lpvThreadParm, fdwCreate, lpIDThread) \ - ((HANDLE)_beginthreadex( \ - (void *) (lpsa), \ - (unsigned) (cbStack), \ - (PTHREAD_START) (lpStartAddr), \ - (void *) (lpvThreadParm), \ - (unsigned) (fdwCreate), \ - (unsigned *) (lpIDThread))) - - -///////////////////////////////////////////////////////////// - - -// Compile all CONTEXT structures to use 32-bit members -// instead of 16-bit members. Currently, the only sample -// application that requires this is TInjLib.16 in order -// for it to work correctly on the DEC Alpha AXP. -#define _PORTABLE_32BIT_CONTEXT - -#endif /* ifndef __WATCOMC__ */ - -///////////////////////////////////////////////////////////// - -// Force all EXEs/DLLs to use STRICT type checking. -#ifndef STRICT - #define STRICT 1 -#endif - -#endif /* ifndef ADVWIN32_H_INCLUDED */ - -////////////////////////// End Of File ////////////////////// diff --git a/3dc/win95/alt_tab.cpp b/3dc/win95/alt_tab.cpp deleted file mode 100644 index 529abcb..0000000 --- a/3dc/win95/alt_tab.cpp +++ /dev/null @@ -1,390 +0,0 @@ -#ifndef DB_LEVEL - #define DB_LEVEL 5 -#endif -#include "db.h" - -#ifndef HT_FAIL - #define HT_FAIL db_msg1 -#endif -#include "hash_tem.hpp" - -#ifdef _CPPRTTI - #include <typeinfo> -#endif - -#include "awTexLd.h" - -#include "alt_tab.h" - -template <class DX_PTR> -class AltTabRestore -{ - public: - virtual ~AltTabRestore(){} - virtual void DoRestore(DX_PTR * pDxGraphic) = 0; -}; - -template <class DX_PTR> -class AltTabAwRestore : public AltTabRestore<DX_PTR> -{ - public: - AltTabAwRestore(AW_BACKUPTEXTUREHANDLE hBackup) : m_hBackup(hBackup) {} - private: - AW_BACKUPTEXTUREHANDLE m_hBackup; - protected: - virtual void DoRestore(DX_PTR * pDxGraphic); -}; - -void AltTabAwRestore<DDSurface>::DoRestore(DDSurface * pSurface) -{ - DDSurface * pNewSurface = AwCreateSurface("rtf",m_hBackup,pSurface,AW_TLF_PREVSRCALL); - // should have succeeded - db_assert1(pNewSurface); - // should return the same pointer! - db_assert1(pNewSurface == pSurface); - // don't need both references - pNewSurface->Release(); -} - -void AltTabAwRestore<D3DTexture>::DoRestore(D3DTexture * pTexture) -{ - D3DTexture * pNewTexture = AwCreateTexture("rtf",m_hBackup,pTexture,AW_TLF_PREVSRCALL); - // should have succeeded - db_assert1(pNewTexture); - // should return the same pointer! - db_assert1(pNewTexture == pTexture); - // don't need both references - pNewTexture->Release(); -} - -template <class DX_PTR> -class AltTabUserRestore : public AltTabRestore<DX_PTR> -{ - public: - typedef void (* PFN_RESTORE) (DX_PTR * pDxGraphic, void * pUser); - #ifdef NDEBUG - AltTabUserRestore(PFN_RESTORE pfnRestore, void * pUser) : m_pfnRestore(pfnRestore), m_pUser(pUser) {} - #else - AltTabUserRestore(PFN_RESTORE pfnRestore, void * pUser, char const * pszFuncName) : m_pfnRestore(pfnRestore), m_pUser(pUser), m_pszFuncName(pszFuncName) {} - #endif - private: - PFN_RESTORE m_pfnRestore; - void * m_pUser; - char const * m_pszFuncName; - protected: - virtual void DoRestore(DX_PTR * pDxGraphic); -}; - -template <class DX_PTR> -void AltTabUserRestore<DX_PTR>::DoRestore(DX_PTR * pDxGraphic) -{ - #ifdef _CPPRTTI - db_logf4(("\t\tCalling User Restore Function %s = %p (%s * = %p, void * = %p)",m_pszFuncName,m_pfnRestore,typeid(*pDxGraphic).name(),pDxGraphic,m_pUser)); - #else - db_logf4(("\t\tCalling User Restore Function %s = %p (IUnknown * = %p, void * = %p)",m_pszFuncName,m_pfnRestore,pDxGraphic,m_pUser)); - #endif - - m_pfnRestore(pDxGraphic, m_pUser); -} - -template <class DX_PTR> -struct AltTabEntry -{ - DX_PTR * m_pDxGraphic; - AltTabRestore<DX_PTR> * m_pRestore; - #ifndef NDEBUG - char const * m_pszFile; - unsigned m_nLine; - char * m_pszDebugString; - #endif - - inline bool operator == (AltTabEntry const & rEntry) const - { return m_pDxGraphic == rEntry.m_pDxGraphic; } - inline bool operator != (AltTabEntry const & rEntry) const - { return ! operator == (rEntry); } - - friend inline HashFunction(AltTabEntry const & rEntry) - { return HashFunction(rEntry.m_pDxGraphic); } -}; - -struct AltTabLists -{ - HashTable<AltTabEntry<D3DTexture> > m_listTextures; - HashTable<AltTabEntry<DDSurface> > m_listSurfaces; -}; - -#ifdef NDEBUG -static AltTabLists g_atlists; -#else -static -struct AltTabDebugLists : AltTabLists -{ - ~AltTabDebugLists() - { - // destructor for derived class will be called before destructor - // for base class, so we can make assersions about the base class: - // everything *should* have been removed from these lists before exiting - if (m_listSurfaces.Size()) - { - db_logf1(("ERROR: AltTab lists still referring to %u surface(s) on exiting",m_listSurfaces.Size())); - unsigned i = 1; - for - ( - HashTable<AltTabEntry<DDSurface> >::ConstIterator itSurfaces(m_listSurfaces); - !itSurfaces.Done(); itSurfaces.Next() - ) - { - db_logf1(("\t%u. Included in line %u of %s (details: %s)",i++,itSurfaces.Get().m_nLine,itSurfaces.Get().m_pszFile,itSurfaces.Get().m_pszDebugString ? itSurfaces.Get().m_pszDebugString : "n/a")); - } - - } - else - { - db_logf1(("OK on exiting: AltTab surface lists are clean")); - } - if (m_listTextures.Size()) - { - db_logf1(("ERROR: AltTab lists still referring to %u texture(s) on exiting",m_listTextures.Size())); - unsigned i = 1; - for - ( - HashTable<AltTabEntry<D3DTexture> >::ConstIterator itTextures(m_listTextures); - !itTextures.Done(); itTextures.Next() - ) - { - db_logf1(("\t%u. Included in line %u of %s (details: %s)",i++,itTextures.Get().m_nLine,itTextures.Get().m_pszFile,itTextures.Get().m_pszDebugString ? itTextures.Get().m_pszDebugString : "n/a")); - } - } - else - { - db_logf1(("OK on exiting: AltTab texture lists are clean")); - } - } -} - g_atlists; -#endif - -#ifdef NDEBUG - void ATIncludeTexture(D3DTexture * pTexture, AW_BACKUPTEXTUREHANDLE hBackup) -#else - void _ATIncludeTexture(D3DTexture * pTexture, AW_BACKUPTEXTUREHANDLE hBackup, char const * pszFile, unsigned nLine, char const * pszDebugString) -#endif -{ - db_assert1(pTexture); - db_assert1(hBackup); - HashTable<AltTabEntry<D3DTexture> >::Node * pNewNode = g_atlists.m_listTextures.NewNode(); - pNewNode->d.m_pDxGraphic = pTexture; - pNewNode->d.m_pRestore = new AltTabAwRestore<D3DTexture>(hBackup); - #ifndef NDEBUG - pNewNode->d.m_pszFile = pszFile; - pNewNode->d.m_nLine = nLine; - if (pszDebugString) - { - pNewNode->d.m_pszDebugString = new char [strlen(pszDebugString)+1]; - strcpy(pNewNode->d.m_pszDebugString,pszDebugString); - } - else - pNewNode->d.m_pszDebugString = NULL; - #endif - g_atlists.m_listTextures.AddAsserted(pNewNode); -} - -#ifdef NDEBUG - void ATIncludeSurface(DDSurface * pSurface, AW_BACKUPTEXTUREHANDLE hBackup) -#else - void _ATIncludeSurface(DDSurface * pSurface, AW_BACKUPTEXTUREHANDLE hBackup, char const * pszFile, unsigned nLine, char const * pszDebugString) -#endif -{ - db_assert1(pSurface); - db_assert1(hBackup); - HashTable<AltTabEntry<DDSurface> >::Node * pNewNode = g_atlists.m_listSurfaces.NewNode(); - pNewNode->d.m_pDxGraphic = pSurface; - pNewNode->d.m_pRestore = new AltTabAwRestore<DDSurface>(hBackup); - #ifndef NDEBUG - pNewNode->d.m_pszFile = pszFile; - pNewNode->d.m_nLine = nLine; - if (pszDebugString) - { - pNewNode->d.m_pszDebugString = new char [strlen(pszDebugString)+1]; - strcpy(pNewNode->d.m_pszDebugString,pszDebugString); - } - else - pNewNode->d.m_pszDebugString = NULL; - #endif - g_atlists.m_listSurfaces.AddAsserted(pNewNode); -} - -#ifdef NDEBUG - void ATIncludeTextureEx(D3DTexture * pTexture, AT_PFN_RESTORETEXTURE pfnRestore, void * pUser) -#else - void _ATIncludeTextureEx(D3DTexture * pTexture, AT_PFN_RESTORETEXTURE pfnRestore, void * pUser, char const * pszFile, unsigned nLine, char const * pszFuncName, char const * pszDebugString) -#endif -{ - db_assert1(pTexture); - db_assert1(pfnRestore); - HashTable<AltTabEntry<D3DTexture> >::Node * pNewNode = g_atlists.m_listTextures.NewNode(); - pNewNode->d.m_pDxGraphic = pTexture; - #ifndef NDEBUG - pNewNode->d.m_pRestore = new AltTabUserRestore<D3DTexture>(pfnRestore,pUser,pszFuncName); - pNewNode->d.m_pszFile = pszFile; - pNewNode->d.m_nLine = nLine; - if (pszDebugString) - { - pNewNode->d.m_pszDebugString = new char [strlen(pszDebugString)+1]; - strcpy(pNewNode->d.m_pszDebugString,pszDebugString); - } - else - pNewNode->d.m_pszDebugString = NULL; - #else - pNewNode->d.m_pRestore = new AltTabUserRestore<D3DTexture>(pfnRestore,pUser); - #endif - g_atlists.m_listTextures.AddAsserted(pNewNode); -} - -#ifdef NDEBUG - void ATIncludeSurfaceEx(DDSurface * pSurface, AT_PFN_RESTORESURFACE pfnRestore, void * pUser) -#else - void _ATIncludeSurfaceEx(DDSurface * pSurface, AT_PFN_RESTORESURFACE pfnRestore, void * pUser, char const * pszFile, unsigned nLine, char const * pszFuncName, char const * pszDebugString) -#endif -{ - db_assert1(pSurface); - db_assert1(pfnRestore); - HashTable<AltTabEntry<DDSurface> >::Node * pNewNode = g_atlists.m_listSurfaces.NewNode(); - pNewNode->d.m_pDxGraphic = pSurface; - #ifndef NDEBUG - pNewNode->d.m_pRestore = new AltTabUserRestore<DDSurface>(pfnRestore,pUser,pszFuncName); - pNewNode->d.m_pszFile = pszFile; - pNewNode->d.m_nLine = nLine; - if (pszDebugString) - { - pNewNode->d.m_pszDebugString = new char [strlen(pszDebugString)+1]; - strcpy(pNewNode->d.m_pszDebugString,pszDebugString); - } - else - pNewNode->d.m_pszDebugString = NULL; - #else - pNewNode->d.m_pRestore = new AltTabUserRestore<DDSurface>(pfnRestore,pUser); - #endif - g_atlists.m_listSurfaces.AddAsserted(pNewNode); -} - -void ATRemoveTexture(D3DTexture * pTexture) -{ - db_assert1(pTexture); - AltTabEntry<D3DTexture> ateRemove; - ateRemove.m_pDxGraphic = pTexture; - AltTabEntry<D3DTexture> const * pEntry = g_atlists.m_listTextures.Contains(ateRemove); - db_assert1(pEntry); - db_assert1(pEntry->m_pRestore); - delete pEntry->m_pRestore; - #ifndef NDEBUG - if (pEntry->m_pszDebugString) - delete[] pEntry->m_pszDebugString; - #endif - g_atlists.m_listTextures.RemoveAsserted(ateRemove); -} - -void ATRemoveSurface(DDSurface * pSurface) -{ - db_assert1(pSurface); - AltTabEntry<DDSurface> ateRemove; - ateRemove.m_pDxGraphic = pSurface; - AltTabEntry<DDSurface> const * pEntry = g_atlists.m_listSurfaces.Contains(ateRemove); - db_assert1(pEntry); - db_assert1(pEntry->m_pRestore); - delete pEntry->m_pRestore; - #ifndef NDEBUG - if (pEntry->m_pszDebugString) - delete[] pEntry->m_pszDebugString; - #endif - g_atlists.m_listSurfaces.RemoveAsserted(ateRemove); -} - -void ATOnAppReactivate() -{ - db_log1("ATOnAppReactivate() called"); - // surfaces - for - ( - HashTable<AltTabEntry<DDSurface> >::ConstIterator itSurfaces(g_atlists.m_listSurfaces); - !itSurfaces.Done(); itSurfaces.Next() - ) - { - DDSurface * pSurface = itSurfaces.Get().m_pDxGraphic; - db_logf5(("\tIs surface %p lost?? [included at line %u of %s (details: %s)]",pSurface,itSurfaces.Get().m_nLine,itSurfaces.Get().m_pszFile,itSurfaces.Get().m_pszDebugString ? itSurfaces.Get().m_pszDebugString : "n/a")); - HRESULT hResult = pSurface->IsLost(); - if (DDERR_SURFACELOST == hResult) - { - db_logf4(("\t\tSurface %p is lost - restoring",pSurface)); - hResult = pSurface->Restore(); - if (DD_OK == hResult) - { - db_logf5(("\t\tRestore() returned DD_OK",pSurface)); - db_assert1(itSurfaces.Get().m_pRestore); - itSurfaces.Get().m_pRestore->DoRestore(pSurface); - } - else - { - db_logf1(("\t\tERROR [%p->Restore()] %s",pSurface,AwDxErrorToString(hResult))); - } - } - else if (DD_OK != hResult) - { - db_logf1(("\t\tERROR [%p->IsLost()] %s",pSurface,AwDxErrorToString(hResult))); - } - else - { - db_logf5(("\t\tSurface %p wasn't lost",pSurface)); - } - } - - // textures - for - ( - HashTable<AltTabEntry<D3DTexture> >::ConstIterator itTextures(g_atlists.m_listTextures); - !itTextures.Done(); itTextures.Next() - ) - { - D3DTexture * pTexture = itTextures.Get().m_pDxGraphic; - db_logf5(("\tIs texture %p lost?? [included at line %u of %s (details: %s)]",pTexture,itTextures.Get().m_nLine,itTextures.Get().m_pszFile,itTextures.Get().m_pszDebugString ? itTextures.Get().m_pszDebugString : "n/a")); - DDSurface * pSurface; - HRESULT hResult = pTexture->QueryInterface(GUID_DD_SURFACE,reinterpret_cast<void * *>(&pSurface)); - if (DD_OK != hResult) - { - db_logf1(("\t\tERROR [%p->QueryInterface(GUID_DD_SURFACE,%p)] %s",pTexture,&pSurface,AwDxErrorToString(hResult))); - } - else - { - hResult = pSurface->IsLost(); - if (DDERR_SURFACELOST == hResult) - { - db_logf4(("\t\tTexture %p is lost - restoring",pTexture)); - hResult = pSurface->Restore(); - if (DD_OK == hResult) - { - db_logf5(("\t\tRestore() returned DD_OK",pTexture)); - db_assert1(itTextures.Get().m_pRestore); - itTextures.Get().m_pRestore->DoRestore(pTexture); - } - else - { - db_logf1(("\t\tERROR [%p->Restore()] %s",pTexture,AwDxErrorToString(hResult))); - } - } - else if (DD_OK != hResult) - { - db_logf1(("\t\tERROR [%p->IsLost()] %s",pTexture,AwDxErrorToString(hResult))); - } - else - { - db_logf5(("\t\tTexture %p wasn't lost",pTexture)); - } - // don't need this reference anymore - pSurface->Release(); - } - } - - db_log1("ATOnAppReactivate() returning"); -} - - diff --git a/3dc/win95/alt_tab.h b/3dc/win95/alt_tab.h deleted file mode 100644 index 4e91bb7..0000000 --- a/3dc/win95/alt_tab.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -JH - 18/02/98 -Deal with lost surfaces and textures - restore them when the application is re-activated -*/ - -#ifndef _INCLUDED_ALT_TAB_H_ -#define _INCLUDED_ALT_TAB_H_ - -#include "aw.h" - -#ifdef __cplusplus - extern "C" { -#endif - -typedef void (* AT_PFN_RESTORETEXTURE) (D3DTexture * pTexture, void * pUser); -typedef void (* AT_PFN_RESTORESURFACE) (DDSurface * pSurface, void * pUser); - -#ifdef NDEBUG - extern void ATIncludeTexture(D3DTexture * pTexture, AW_BACKUPTEXTUREHANDLE hBackup); - extern void ATIncludeTextureEx(D3DTexture * pTexture, AT_PFN_RESTORETEXTURE pfnRestore, void * pUser); - extern void ATIncludeSurface(DDSurface * pSurface, AW_BACKUPTEXTUREHANDLE hBackup); - extern void ATIncludeSurfaceEx(DDSurface * pSurface, AT_PFN_RESTORESURFACE pfnRestore, void * pUser); -#else - extern void _ATIncludeTexture(D3DTexture * pTexture, AW_BACKUPTEXTUREHANDLE hBackup, char const * pszFile, unsigned nLine, char const * pszDebugString); - extern void _ATIncludeTextureEx(D3DTexture * pTexture, AT_PFN_RESTORETEXTURE pfnRestore, void * pUser, char const * pszFile, unsigned nLine, char const * pszFuncName, char const * pszDebugString); - extern void _ATIncludeSurface(DDSurface * pSurface, AW_BACKUPTEXTUREHANDLE hBackup, char const * pszFile, unsigned nLine, char const * pszDebugString); - extern void _ATIncludeSurfaceEx(DDSurface * pSurface, AT_PFN_RESTORESURFACE pfnRestore, void * pUser, char const * pszFile, unsigned nLine, char const * pszFuncName, char const * pszDebugString); - #define ATIncludeTexture(p,h) _ATIncludeTexture(p,h,__FILE__,__LINE__,NULL) - #define ATIncludeTextureEx(p,f,u) _ATIncludeTextureEx(p,f,u,__FILE__,__LINE__,#f ,NULL) - #define ATIncludeSurface(p,h) _ATIncludeSurface(p,h,__FILE__,__LINE__,NULL) - #define ATIncludeSurfaceEx(p,f,u) _ATIncludeSurfaceEx(p,f,u,__FILE__,__LINE__,#f ,NULL) - #define ATIncludeTextureDb(p,h,d) _ATIncludeTexture(p,h,__FILE__,__LINE__,d) - #define ATIncludeTextureExDb(p,f,u,d) _ATIncludeTextureEx(p,f,u,__FILE__,__LINE__,#f ,d) - #define ATIncludeSurfaceDb(p,h,d) _ATIncludeSurface(p,h,__FILE__,__LINE__,d) - #define ATIncludeSurfaceExDb(p,f,u,d) _ATIncludeSurfaceEx(p,f,u,__FILE__,__LINE__,#f ,d) -#endif - -extern void ATRemoveTexture(D3DTexture * pTexture); -extern void ATRemoveSurface(DDSurface * pSurface); - -extern void ATOnAppReactivate(); - -#ifdef __cplusplus - } -#endif - -#endif /* ! _INCLUDED_ALT_TAB_H_ */ diff --git a/3dc/win95/animobs.cpp b/3dc/win95/animobs.cpp deleted file mode 100644 index f85001f..0000000 --- a/3dc/win95/animobs.cpp +++ /dev/null @@ -1,593 +0,0 @@ -#include "hierchnk.hpp" -#include "Animobs.hpp" -#include "list_tem.hpp" -#include <math.h> - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(animobs) - -RIF_IMPLEMENT_DYNCREATE("OBASEQFR",Object_Animation_Sequence_Frame_Chunk) - -void Object_Animation_Sequence_Frame_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - - *((float *) data_start) = orientation.x; - data_start += 4; - *((float *) data_start) = orientation.y; - data_start += 4; - *((float *) data_start) = orientation.z; - data_start += 4; - *((float *) data_start) = orientation.w; - data_start += 4; - - *((int *) data_start) = transform.x; - data_start += 4; - *((int *) data_start) = transform.y; - data_start += 4; - *((int *) data_start) = transform.z; - data_start += 4; - - *((int *) data_start) = at_frame_no; - data_start += 4; - - *((int *) data_start) = frame_ref_no; - data_start += 4; - - *((int *) data_start) = flags; - data_start += 4; - - *(int*) data_start=num_extra_data; - data_start+=4; - - for (int i=0; i<num_extra_data; i++) - { - *((int *) data_start) = extra_data[i]; - data_start += 4; - } - -} - -#if UseOldChunkLoader -Object_Animation_Sequence_Frame_Chunk::Object_Animation_Sequence_Frame_Chunk (Object_Animation_Sequence_Chunk * parent,const char *data_start, size_t) -: Chunk (parent, "OBASEQFR") -{ - orientation.x = -(*(double *) data_start); - data_start += 8; - orientation.y = -(*(double *) data_start); - data_start += 8; - orientation.z = -(*(double *) data_start); - data_start += 8; - orientation.w = (*(double *) data_start); - data_start += 8; - - transform.x = *((double *) data_start); - data_start += 8; - transform.y = *((double *) data_start); - data_start += 8; - transform.z = *((double *) data_start); - data_start += 8; - - at_frame_no = *((int *) data_start); - data_start += 4; - - frame_ref_no = *((int *) data_start); - data_start += 4; - - flags = *((int *) data_start); - data_start += 4; - - num_extra_data=0; - extra_data=0; - -} -#else -Object_Animation_Sequence_Frame_Chunk::Object_Animation_Sequence_Frame_Chunk (Chunk_With_Children * parent,const char *data_start, size_t) -: Chunk (parent, "OBASEQFR") -{ - orientation.x = *((float *) data_start); - data_start += 4; - orientation.y = *((float *) data_start); - data_start += 4; - orientation.z = *((float *) data_start); - data_start += 4; - orientation.w = *((float *) data_start); - data_start += 4; - - transform.x = *((int *) data_start); - data_start += 4; - transform.y = *((int *) data_start); - data_start += 4; - transform.z = *((int *) data_start); - data_start += 4; - - at_frame_no = *((int *) data_start); - data_start += 4; - - frame_ref_no = *((int *) data_start); - data_start += 4; - - flags = *((int *) data_start); - data_start += 4; - - num_extra_data=*(int*) data_start; - data_start+=4; - - if(num_extra_data) - extra_data=new int[num_extra_data]; - else - extra_data=0; - - - for (int i=0; i<num_extra_data; i++) - { - extra_data[i] = *((int *) data_start); - data_start += 4; - } - -} -#endif - -void Object_Animation_Sequence_Frame_Chunk::set_sound_index(int ind) -{ - if(ind>=0 && ind<=127) - { - flags &=~HierarchyFrame_SoundIndexMask; - flags |= (ind<<24); - } -} - -RIF_IMPLEMENT_DYNCREATE("OBASEQHD",Object_Animation_Sequence_Header_Chunk) - -void Object_Animation_Sequence_Header_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *((int *) data_start) = num_frames; - data_start += 4; - - *((int *) data_start) = sequence_number; - data_start += 4; - - *((int *) data_start) = sub_sequence_number; - data_start += 4; - - *(int*)data_start=num_extra_data; - data_start+=4; - - for (int i=0; i<num_extra_data; i++) - { - *((int *) data_start) = extra_data[i]; - data_start += 4; - } - - if (sequence_name) - { - sprintf (data_start, "%s", sequence_name); - } - else - { - *data_start = 0; - } - -} - -Object_Animation_Sequence_Header_Chunk::~Object_Animation_Sequence_Header_Chunk() -{ - if (sequence_name) - delete sequence_name; - if(extra_data) - delete extra_data; -} - - -#if UseOldChunkLoader -Object_Animation_Sequence_Header_Chunk::Object_Animation_Sequence_Header_Chunk (Chunk_With_Children * parent,const char * data_start, size_t) -: Chunk (parent, "OBASEQHD"), sequence_name (0) -{ - num_frames = *((int *) data_start); - data_start += 4; - - sequence_number = *((int *) data_start); - data_start += 4; - - sub_sequence_number = *((int *) data_start); - data_start += 4; - - num_extra_data=0; - extra_data=0; - data_start+=40; - - if (strlen(data_start)) - { - sequence_name = new char [strlen(data_start) + 1]; - strcpy (sequence_name, data_start); - } -} -#else -Object_Animation_Sequence_Header_Chunk::Object_Animation_Sequence_Header_Chunk (Chunk_With_Children * parent,const char * data_start, size_t) -: Chunk (parent, "OBASEQHD"), sequence_name (0) -{ - num_frames = *((int *) data_start); - data_start += 4; - - sequence_number = *((int *) data_start); - data_start += 4; - - sub_sequence_number = *((int *) data_start); - data_start += 4; - - num_extra_data=*(int*) data_start; - data_start+=4; - - if(num_extra_data) - extra_data=new int[num_extra_data]; - else - extra_data=0; - - - for (int i=0; i<num_extra_data; i++) - { - extra_data[i] = *((int *) data_start); - data_start += 4; - } - - - if (strlen(data_start)) - { - sequence_name = new char [strlen(data_start) + 1]; - strcpy (sequence_name, data_start); - } -} -#endif - - - -Object_Animation_Sequence_Header_Chunk * Object_Animation_Sequence_Chunk::get_header() -{ - return(Object_Animation_Sequence_Header_Chunk *) lookup_single_child("OBASEQHD"); -} - -void Object_Animation_Sequence_Chunk::get_frames(List <Object_Animation_Sequence_Frame_Chunk*> *pList) -{ - List <Chunk *> cl; - lookup_child ("OBASEQFR",cl); - - for (LIF<Chunk *> cli(&cl); !cli.done(); cli.next()) - { - pList->add_entry((Object_Animation_Sequence_Frame_Chunk *)cli()); - } - -} - -//////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("OBANSEQS",Object_Animation_Sequences_Chunk) - -void Object_Animation_Sequences_Chunk::list_sequences(List <Object_Animation_Sequence_Chunk *> * pList) -{ - List <Chunk *> cl; - lookup_child ("OBANSEQC",cl); - - for (LIF<Chunk *> cli(&cl); !cli.done(); cli.next()) - { - pList->add_entry((Object_Animation_Sequence_Chunk *)cli()); - } -} - - -Object_Animation_Sequence_Chunk::Object_Animation_Sequence_Chunk(Object_Animation_Sequences_Chunk* parent,Object_Animation_Sequence_Chunk* template_seq,ChunkQuat & orient ,ChunkVectorInt & trans) -:Chunk_With_Children (parent, "OBANSEQC") -{ - Object_Animation_Sequence_Header_Chunk* template_header=template_seq->get_header(); - Object_Animation_Sequence_Header_Chunk* header=new Object_Animation_Sequence_Header_Chunk(this); - - header->num_frames=65536; - header->sequence_number=template_header->sequence_number; - header->sub_sequence_number=template_header->sub_sequence_number; - header->sequence_name=new char[strlen(template_header->sequence_name)+1]; - strcpy(header->sequence_name,template_header->sequence_name); - - Object_Animation_Sequence_Frame_Chunk* oasfc=new Object_Animation_Sequence_Frame_Chunk(this); - - oasfc->orientation=orient; - oasfc->transform=trans; - oasfc->at_frame_no=0; - oasfc->frame_ref_no=0; - - //see if template sequence is a delta sequence - List<Object_Animation_Sequence_Frame_Chunk*> framelist; - template_seq->get_frames(&framelist); - while(framelist.size()) - { - if(framelist.first_entry()->flags & HierarchyFrameFlag_DeltaFrame) - { - oasfc->flags=HierarchyFrameFlag_DeltaFrame; - break; - } - framelist.delete_first_entry(); - } - - -} - -Object_Animation_Sequence_Chunk * Object_Animation_Sequences_Chunk::get_sequence (int num, int subnum) -{ - List <Object_Animation_Sequence_Chunk *> seq_list; - list_sequences(&seq_list); - - for (LIF<Object_Animation_Sequence_Chunk *> sli(&seq_list); !sli.done(); sli.next()) - { - Object_Animation_Sequence_Header_Chunk * oashc = sli()->get_header(); - if (oashc) - { - if (oashc->sequence_number == num && oashc->sub_sequence_number == subnum) - { - break; - } - } - } - - if (!sli.done()) - { - return(sli()); - } - else - { - return(0); - } -} - -int Object_Animation_Sequence_Chunk::get_sequence_time() -{ - Object_Animation_Sequence_Time_Chunk* time_chunk=(Object_Animation_Sequence_Time_Chunk*)lookup_single_child("OBASEQTM"); - if(time_chunk) - { - return time_chunk->sequence_time; - } - return 0; -} - -int Object_Animation_Sequence_Chunk::get_sequence_speed() -{ - Object_Animation_Sequence_Speed_Chunk* speed_chunk=(Object_Animation_Sequence_Speed_Chunk*)lookup_single_child("OBASEQSP"); - if(speed_chunk) - { - return speed_chunk->sequence_speed; - } - return 0; -} - -BOOL Object_Animation_Sequence_Chunk::get_sequence_vector(ChunkVectorFloat* direction) -{ - if(!direction) return FALSE; - - //default direction is forwards - direction->x=0; - direction->y=0; - direction->z=1; - - - Object_Animation_Sequence_Speed_Chunk* speed_chunk=(Object_Animation_Sequence_Speed_Chunk*)lookup_single_child("OBASEQSP"); - if(speed_chunk) - { - double radian_angle=(speed_chunk->angle/360.0)*2*3.1415278; - direction->x =(float) sin(radian_angle); - direction->z =(float) cos(radian_angle); - - return TRUE; - } - else - { - return FALSE; - } -} - -int Object_Animation_Sequence_Chunk::get_sequence_flags() -{ - Object_Animation_Sequence_Flags_Chunk* flag_chunk=(Object_Animation_Sequence_Flags_Chunk*)lookup_single_child("OBASEQFL"); - if(flag_chunk) - { - return flag_chunk->flags; - } - return 0; -} - -void Object_Animation_Sequence_Chunk::set_sequence_flags(int new_flags) -{ - //find existing flag_chunk , or create a new one - Object_Animation_Sequence_Flags_Chunk* flag_chunk=(Object_Animation_Sequence_Flags_Chunk*)lookup_single_child("OBASEQFL"); - if(flag_chunk) - { - //set the flags - flag_chunk->flags = new_flags; - } - else - { - //create a new chunk then - new Object_Animation_Sequence_Flags_Chunk(this,new_flags); - } -} - -Hierarchy_Bounding_Box_Chunk* Object_Animation_Sequence_Chunk::get_bounding_box() -{ - return (Hierarchy_Bounding_Box_Chunk*)lookup_single_child("HIERBBOX"); -} - -//////////////////////////////////////////////////////////////////////////////// - /*--------------------------------------** - ** Object_Animation_Sequence_Time_Chunk ** - **--------------------------------------*/ - -RIF_IMPLEMENT_DYNCREATE("OBASEQTM",Object_Animation_Sequence_Time_Chunk) - -Object_Animation_Sequence_Time_Chunk::Object_Animation_Sequence_Time_Chunk (Chunk_With_Children * parent,const char * data_start, size_t) -: Chunk (parent, "OBASEQTM") -{ - sequence_time=*(unsigned int*) data_start; -} - -void Object_Animation_Sequence_Time_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(unsigned int*) data_start = sequence_time; -} - -//////////////////////////////////////////////////////////////////////////////// - /*---------------------------------------** - ** Object_Animation_Sequence_Speed_Chunk ** - **---------------------------------------*/ - -RIF_IMPLEMENT_DYNCREATE("OBASEQSP",Object_Animation_Sequence_Speed_Chunk) - -Object_Animation_Sequence_Speed_Chunk::Object_Animation_Sequence_Speed_Chunk (Chunk_With_Children * parent,const char * data, size_t) -: Chunk (parent, "OBASEQSP") -{ - CHUNK_EXTRACT(sequence_speed,int) - CHUNK_EXTRACT(angle,int) - CHUNK_EXTRACT(spare,int) -} - -void Object_Animation_Sequence_Speed_Chunk::fill_data_block(char* data) -{ - CHUNK_FILL_START - CHUNK_FILL(sequence_speed,int) - CHUNK_FILL(angle,int) - CHUNK_FILL(spare,int) -} - -//////////////////////////////////////////////////////////////////////////////// - /*---------------------------------------** - ** Object_Animation_Sequence_Flags_Chunk ** - **---------------------------------------*/ - - -RIF_IMPLEMENT_DYNCREATE("OBASEQFL",Object_Animation_Sequence_Flags_Chunk) - -Object_Animation_Sequence_Flags_Chunk::Object_Animation_Sequence_Flags_Chunk (Chunk_With_Children * parent,const char * data, size_t) -: Chunk (parent, "OBASEQFL") -{ - CHUNK_EXTRACT(flags,int) -} - -void Object_Animation_Sequence_Flags_Chunk::fill_data_block(char* data) -{ - CHUNK_FILL_START - CHUNK_FILL(flags,int) -} - -//////////////////////////////////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("OBANALLS",Object_Animation_All_Sequence_Chunk) - -Object_Animation_All_Sequence_Chunk::Object_Animation_All_Sequence_Chunk(Chunk_With_Children* parent) -:Chunk(parent,"OBANALLS") -{ - num_sequences=0; - sequences=0; -} - -Object_Animation_All_Sequence_Chunk::Object_Animation_All_Sequence_Chunk(Chunk_With_Children * const parent,const char * data, const size_t) -:Chunk(parent,"OBANALLS") -{ - num_sequences=*(int*)data; - data+=4; - - if(num_sequences) sequences=new Object_Animation_Sequence[num_sequences]; - else sequences=0; - - for(int i=0;i<num_sequences;i++) - { - Object_Animation_Sequence* seq=&sequences[i]; - seq->num_frames=*(int*)data; - data+=4; - seq->sequence_number=*(int*)data; - data+=4; - seq->sub_sequence_number=*(int*)data; - data+=4; - seq->sequence_time=*(int*)data; - data+=4; - - if(seq->num_frames) seq->frames=new Object_Animation_Frame[seq->num_frames]; - else seq->frames=0; - - for(unsigned j=0;j<seq->num_frames;j++) - { - seq->frames[j]=*(Object_Animation_Frame*)data; - data+=sizeof(Object_Animation_Frame); - } - } -} - -void Object_Animation_All_Sequence_Chunk::fill_data_block(char* data) -{ - strncpy (data, identifier, 8); - data += 8; - *((int *) data) = chunk_size; - data += 4; - - *(int*)data=num_sequences; - data+=4; - - for(int i=0;i<num_sequences;i++) - { - Object_Animation_Sequence* seq=&sequences[i]; - *(int*)data=seq->num_frames; - data+=4; - *(int*)data=seq->sequence_number; - data+=4; - *(int*)data=seq->sub_sequence_number; - data+=4; - *(int*)data=seq->sequence_time; - data+=4; - - for(unsigned j=0;j<seq->num_frames;j++) - { - *(Object_Animation_Frame*)data=seq->frames[j]; - data+=sizeof(Object_Animation_Frame); - } - - } -} - -size_t Object_Animation_All_Sequence_Chunk::size_chunk() -{ - chunk_size=12+4; - chunk_size+=num_sequences*16; - for(int i=0;i<num_sequences;i++) - { - chunk_size+=sequences[i].num_frames*sizeof(Object_Animation_Frame); - } - return chunk_size; -} - - -//////////////////////////////////////////////////////////////////////////////// - -//loader for Object_Animation_Sequences_Chunk -CHUNK_WITH_CHILDREN_LOADER("OBANSEQS",Object_Animation_Sequences_Chunk) - - - -//Object_Animation_Sequence_Chunk - -RIF_IMPLEMENT_DYNCREATE("OBANSEQC",Object_Animation_Sequence_Chunk) -//loader for Object_Animation_Sequence_Chunk -CHUNK_WITH_CHILDREN_LOADER("OBANSEQC",Object_Animation_Sequence_Chunk) diff --git a/3dc/win95/animobs.hpp b/3dc/win95/animobs.hpp deleted file mode 100644 index 0cdb9f8..0000000 --- a/3dc/win95/animobs.hpp +++ /dev/null @@ -1,286 +0,0 @@ -#ifndef _animobs_hpp -#define _animobs_hpp 1 - -#include "chunk.hpp" -#include "chnktype.hpp" - -class Object_Animation_Sequence_Header_Chunk; -class Object_Animation_Sequence_Frame_Chunk; -class Object_Animation_Sequence_Chunk; -class Hierarchy_Bounding_Box_Chunk; - -class Object_Animation_Sequences_Chunk : public Chunk_With_Children -{ -public: - - Object_Animation_Sequences_Chunk (Chunk_With_Children * parent) - : Chunk_With_Children (parent, "OBANSEQS") - {} - Object_Animation_Sequences_Chunk (Chunk_With_Children * const parent,const char *, const size_t); - - void list_sequences(List <Object_Animation_Sequence_Chunk *> * pList); - - Object_Animation_Sequence_Chunk * get_sequence (int num, int sub_num); - -private: - - friend class Object_Chunk; - friend class Object_Hierarchy_Chunk; - - -}; - - - - -class Object_Animation_Sequence_Chunk : public Chunk_With_Children -{ -public: - - Object_Animation_Sequence_Chunk (Object_Animation_Sequences_Chunk * parent) - : Chunk_With_Children (parent, "OBANSEQC") - {} - Object_Animation_Sequence_Chunk (Chunk_With_Children * const parent,const char *, const size_t); - - //creates sequence of one frame ,with name taken from template_seq - Object_Animation_Sequence_Chunk(Object_Animation_Sequences_Chunk * parent,Object_Animation_Sequence_Chunk* template_seq,ChunkQuat& orient,ChunkVectorInt& trans); - - Object_Animation_Sequence_Header_Chunk * get_header(); - - void get_frames(List <Object_Animation_Sequence_Frame_Chunk *>* ); - - int get_sequence_time(); //gets time in ms - int get_sequence_speed(); //gets movement speed in mm/second - - //get (normalised) direction of movement for sequence - //if no direction has been set then returns false , and sets direction to a forward vector - BOOL get_sequence_vector(ChunkVectorFloat* direction); - - //getting and setting flags for this sequence - int get_sequence_flags(); - void set_sequence_flags(int new_flags); - - Hierarchy_Bounding_Box_Chunk* get_bounding_box(); //gets the chunk with the bounding box for the sequence -private: - - friend class Object_Animation_Sequences_Chunk; - - -}; - - - -#define HierarchyFrameFlag_DeltaFrame 0x80000000 -#define HierarchyFrame_SoundIndexMask 0x7f000000 -#define HierarchyFrame_FlagMask 0x00ffffff - -class Object_Animation_Sequence_Frame_Chunk : public Chunk -{ -public: - - Object_Animation_Sequence_Frame_Chunk (Object_Animation_Sequence_Chunk * parent) - : Chunk (parent, "OBASEQFR"), at_frame_no (-1), frame_ref_no (-1) - { - ChunkQuat identity = {0,0,0,1}; - orientation = identity; - - transform.x = 0; - transform.y = 0; - transform.z = 0; - - flags =0; - - num_extra_data=0; - extra_data=0; - } - Object_Animation_Sequence_Frame_Chunk (Chunk_With_Children * parent,const char *, size_t); - - ~Object_Animation_Sequence_Frame_Chunk(){if(extra_data) delete extra_data;} - - ChunkQuat orientation; - ChunkVectorInt transform; - - signed long at_frame_no; //frame start time (0-65535) - - signed long frame_ref_no; //frame index number - - int flags; - - int num_extra_data; - int* extra_data; - - virtual void fill_data_block (char *); - virtual size_t size_chunk () - { - return(chunk_size = 12 + 4*4 + 3*4 + 4 + 4 + 8+4*num_extra_data); - } - - void set_sound_index(int ind); - int get_sound_index(){return ((flags & HierarchyFrame_SoundIndexMask )>>24);} - -private: - - friend class Object_Animation_Sequence_Chunk; - - -}; - - - - -class Object_Animation_Sequence_Header_Chunk : public Chunk -{ -public: - - Object_Animation_Sequence_Header_Chunk(Chunk_With_Children * parent) - : Chunk (parent, "OBASEQHD"), num_frames (0), sequence_number (-1), - sub_sequence_number (-1), sequence_name (0) - { - num_extra_data=0; - extra_data=0; - } - Object_Animation_Sequence_Header_Chunk (Chunk_With_Children * parent,const char *, size_t); - - ~Object_Animation_Sequence_Header_Chunk(); - - unsigned long num_frames; - - signed long sequence_number; - signed long sub_sequence_number; - - int num_extra_data; - int* extra_data; - - char * sequence_name; - - virtual void fill_data_block (char *); - virtual size_t size_chunk () - { - if (sequence_name) - { - return(chunk_size = 12 + 16 + 4*num_extra_data + strlen(sequence_name) + 4 - strlen(sequence_name)%4); - } - else - { - return(chunk_size = 12 + 16 + 4*num_extra_data + 4); - } - } - -private: - - friend class Object_Animation_Sequence_Chunk; - - -}; - -class Object_Animation_Sequence_Time_Chunk : public Chunk -{ -public : - Object_Animation_Sequence_Time_Chunk(Chunk_With_Children* parent) - : Chunk (parent,"OBASEQTM") , sequence_time(0) - { - } - Object_Animation_Sequence_Time_Chunk (Chunk_With_Children * parent,const char *, size_t); - - unsigned int sequence_time; //in milliseconds - - virtual void fill_data_block (char *); - virtual size_t size_chunk (){ return chunk_size=16;} - -private: - - friend class Object_Animation_Sequence_Chunk; - - -}; - - -class Object_Animation_Sequence_Speed_Chunk : public Chunk -{ -public : - Object_Animation_Sequence_Speed_Chunk(Chunk_With_Children* parent) - : Chunk (parent,"OBASEQSP") , sequence_speed(0) ,angle(0),spare(0) - { - } - Object_Animation_Sequence_Speed_Chunk (Chunk_With_Children * parent,const char *, size_t); - - int sequence_speed; //in mm/second - int angle; //in degrees (mainly for tools use) - int spare; - - virtual void fill_data_block (char *); - virtual size_t size_chunk (){ return chunk_size=24;} - -private: - - friend class Object_Animation_Sequence_Chunk; - - -}; - -#define MummySequenceFlag_UpperSequence 0x00000001 -#define MummySequenceFlag_LowerSequence 0x00000002 -#define SequenceFlag_Loops 0x00000004 -#define SequenceFlag_NoLoop 0x00000008 -#define SequenceFlag_NoInterpolation 0x00000010 -#define SequenceFlag_HalfFrameRate 0x00000020 - -class Object_Animation_Sequence_Flags_Chunk : public Chunk -{ -public : - Object_Animation_Sequence_Flags_Chunk(Chunk_With_Children* parent,int _flags) - : Chunk (parent,"OBASEQFL") , flags(_flags) - { - } - Object_Animation_Sequence_Flags_Chunk (Chunk_With_Children * parent,const char *, size_t); - - int flags; - - virtual void fill_data_block (char *); - virtual size_t size_chunk (){ return chunk_size=16;} - -}; - - -struct Object_Animation_Frame -{ - ChunkQuat orientation; - ChunkVectorInt transform; - signed long at_frame_no; //frame start time (0-65535) - int flags; - - int get_sound_index(){return ((flags & HierarchyFrame_SoundIndexMask )>>24);} - -}; - -struct Object_Animation_Sequence -{ - ~Object_Animation_Sequence(){delete [] frames;} - - unsigned long num_frames; - signed long sequence_number; - signed long sub_sequence_number; - unsigned int sequence_time; //in milliseconds - Object_Animation_Frame* frames; -}; - -#define Get_Object_Animation_All_Sequence_Chunk(parent) (Object_Animation_All_Sequence_Chunk*)(parent)->lookup_single_child("OBANALLS") - -//a more compact version of the sequence and frame data -//this format isn't recognized by any of the tools however. -class Object_Animation_All_Sequence_Chunk : public Chunk -{ -public: - - Object_Animation_All_Sequence_Chunk (Chunk_With_Children * parent); - Object_Animation_All_Sequence_Chunk (Chunk_With_Children * const parent,const char *, const size_t); - ~Object_Animation_All_Sequence_Chunk () {delete [] sequences;} - - virtual void fill_data_block (char *); - virtual size_t size_chunk (); - - int num_sequences; - Object_Animation_Sequence* sequences; - -}; -#endif
\ No newline at end of file diff --git a/3dc/win95/aw.h b/3dc/win95/aw.h deleted file mode 100644 index 8e43f33..0000000 --- a/3dc/win95/aw.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef _INCLUDED_AW_H_ -#define _INCLUDED_AW_H_ - -#include <d3d.h> - -typedef IDirectDraw DDObject; -typedef IDirect3DDevice D3DDevice; -typedef IDirect3DTexture D3DTexture; -typedef IDirectDrawSurface DDSurface; -typedef IDirectDrawPalette DDPalette; - -#define GUID_D3D_TEXTURE IID_IDirect3DTexture -#define GUID_DD_SURFACE IID_IDirectDrawSurface - -typedef DDSURFACEDESC DD_SURFACE_DESC; -typedef DDSCAPS DD_S_CAPS; - -struct AwBackupTexture; -typedef struct AwBackupTexture * AW_BACKUPTEXTUREHANDLE; - -#endif /* _INCLUDED_AW_H_ */
\ No newline at end of file diff --git a/3dc/win95/awBmpLd.cpp b/3dc/win95/awBmpLd.cpp deleted file mode 100644 index 375e1d7..0000000 --- a/3dc/win95/awBmpLd.cpp +++ /dev/null @@ -1,192 +0,0 @@ -#include "advwin32.h" -#ifndef DB_LEVEL -#define DB_LEVEL 4 -#endif -#include "db.h" - -#include "awTexLd.hpp" - -// BMP Loader - -class AwBmpLoader : public AwTl::TypicalTexFileLoader -{ - protected: - virtual void LoadHeaderInfo(MediaMedium * pMedium); - virtual AwTl::Colour * GetPalette(); - virtual bool AreRowsReversed(); - virtual void LoadNextRow(AwTl::PtrUnion pRow); - - WORD bmp_bitdepth; - DWORD bmp_offset; - DWORD bmp_headsize; - - unsigned bmp_filepitchpad; - unsigned bmp_bitmask; - - MediaMedium * m_pMedium; -}; - -void AwBmpLoader::LoadHeaderInfo(MediaMedium * pMedium) -{ - m_pMedium = pMedium; // store for later - - db_log4("\tLoading a BMP file"); - - pMedium->MovePos(+10); // 2 bytes BM (magic) and 4 bytes bmp_filesize and 4 bytes reserved - - MediaRead(pMedium,&bmp_offset); - MediaRead(pMedium,&bmp_headsize); - // 12 for OS/2 1.x 40 for Windows, 64 for OS/2 2.x - if (12 != bmp_headsize && 40 != bmp_headsize && 64 != bmp_headsize) - { - awTlLastErr = AW_TLE_BADFILEFORMAT; - db_logf3(("AwCreateTexture(): ERROR: BMP_headersize (%u) is not a recognized BMP format",bmp_headsize)); - } - #if DB_LEVEL >= 4 - switch (bmp_headsize) - { - case 12: - db_log4("\tBMP format is OS/2 1.x"); - break; - case 40: - db_log4("\tBMP format is Windows 3.x"); - break; - case 64: - db_log4("\tBMP format is OS/2 2.x"); - } - #endif - if (bmp_headsize >= 40) - { - DWORD width, height; - MediaRead(pMedium,&width); - MediaRead(pMedium,&height); - m_nWidth = width; - m_nHeight = height; - } - else - { - WORD width, height; - MediaRead(pMedium,&width); - MediaRead(pMedium,&height); - m_nWidth = width; - m_nHeight = height; - } - // next WORD is planes and should == 1 - WORD bmp_planes = 0; // ALEX: added in initialization to prevent compiler warnings - MediaRead(pMedium,&bmp_planes); - if (1!=bmp_planes) - { - awTlLastErr = AW_TLE_BADFILEDATA; - db_log3("AwCreateTexture(): ERROR: BMP_planes should be 1"); - } - MediaRead(pMedium,&bmp_bitdepth); - db_logf4(("\tBMP_bitdepth is %hd",bmp_bitdepth)); - if (1!=bmp_bitdepth && 2!=bmp_bitdepth && 4!=bmp_bitdepth && 8!=bmp_bitdepth && 24!=bmp_bitdepth) - { - awTlLastErr = AW_TLE_BADFILEDATA; - db_logf3(("AwCreateTexture(): ERROR: BMP_bitdepth (%u) should be 1,2,4,8 or 24",bmp_bitdepth)); - } - if (bmp_headsize >= 40) - { - // next DWORD is compression, not supported so only accept 0 - DWORD compression = 0; - MediaRead(pMedium,&compression); - if (compression) - { - db_log3("AwCreateTexture(): ERROR: Cannont read compressed BMP files"); - awTlLastErr = AW_TLE_BADFILEFORMAT; - } - // DWORD bmp_size - ignored, 2xDWORDS ignored - pMedium->MovePos(+12); - DWORD palette_size = 0; // ALEX: added in initialization to prevent compiler warnings - MediaRead(pMedium,&palette_size); - m_nPaletteSize = palette_size; - // skip to the start of the palette if there would be one - pMedium->MovePos(bmp_headsize-36); - } - else - { - m_nPaletteSize = 0; - } - bmp_offset -= (bmp_headsize+14); - if (!m_nPaletteSize && bmp_bitdepth<=8) - m_nPaletteSize = 1<<bmp_bitdepth; - if (m_nPaletteSize) - bmp_offset -= bmp_headsize >= 40 ? m_nPaletteSize*4 : m_nPaletteSize*3; - - db_logf4(("\tBMP_palettesize is %u",m_nPaletteSize)); - bmp_filepitchpad = (~(m_nWidth*bmp_bitdepth-1))/8 & 3; - db_logf4(("\tBMP has %u bytes padding per row",bmp_filepitchpad)); - - bmp_bitmask = (1<<bmp_bitdepth)-1; -} - -AwTl::Colour * AwBmpLoader::GetPalette() -{ - db_assert1(m_nPaletteSize); - db_assert1(m_pPalette); - - if (m_nPaletteSize > 256) - { - awTlLastErr = AW_TLE_BADFILEDATA; - db_log3("AwCreateTexture(): ERROR: BMP_palettesize is too large"); - } - else - { - AwTl::Colour * pmP = m_pPalette; - for (unsigned pc = m_nPaletteSize; pc; --pc,++pmP) - { - MediaRead(m_pMedium,&pmP->b); - MediaRead(m_pMedium,&pmP->g); - MediaRead(m_pMedium,&pmP->r); - if (bmp_headsize >= 40) m_pMedium->MovePos(+1); - } - } - // skip to the start of the pixel data - m_pMedium->MovePos(bmp_offset); - - return m_pPalette; -} - -bool AwBmpLoader::AreRowsReversed() -{ - return true; -} - -void AwBmpLoader::LoadNextRow(AwTl::PtrUnion pRow) -{ - if (m_nPaletteSize) - { - unsigned shift = 0; - BYTE byte = 0; // Not needed. - - for (unsigned colcount = m_nWidth; colcount; --colcount) - { - if (!shift) - { - shift = 8; - MediaRead(m_pMedium, &byte); - } - shift -= bmp_bitdepth; - *pRow.byteP++ = static_cast<BYTE>(byte>>shift & bmp_bitmask); - } - } - else - { - for (unsigned colcount = m_nWidth; colcount; --colcount) - { - MediaRead(m_pMedium,&pRow.colourP->b); - MediaRead(m_pMedium,&pRow.colourP->g); - MediaRead(m_pMedium,&pRow.colourP->r); - ++pRow.colourP; - } - } - m_pMedium->MovePos(bmp_filepitchpad); -} - -#ifdef _MSC_VER - // VC5.0 tries to compile out code that is in a library - // and it thinks isn't being used - #line 186 -#endif -AWTEXLD_IMPLEMENT_DYNCREATE("BM",AwBmpLoader) diff --git a/3dc/win95/awIffLd.cpp b/3dc/win95/awIffLd.cpp deleted file mode 100644 index de3be19..0000000 --- a/3dc/win95/awIffLd.cpp +++ /dev/null @@ -1,507 +0,0 @@ -#include "advwin32.h" -#ifndef DB_LEVEL -#define DB_LEVEL 4 -#endif -#include "db.h" -#ifndef DB_COMMA - #define DB_COMMA , -#endif - -#pragma warning(disable: 4701) -#include "awTexLd.hpp" -#pragma warning(default: 4701) - -#include "iff.hpp" -#include "iff_ILBM.hpp" - -#include "list_tem.hpp" - -#include <limits.h> - -// conversion functors for IFF loader -class AwIffConvNull -{ - public: - static inline unsigned DoConv (unsigned const * _colP, AwTl::Colour const * db_code1(DB_COMMA unsigned)) - { - db_assert1(AwTl::pixelFormat.palettizedB); - return *_colP; - } -}; - -class AwIffConvNonTransp : public AwTl::Colour::ConvNonTransp -{ - public: - static inline unsigned DoConv(unsigned const * pCol, AwTl::Colour const * pPalette db_code1(DB_COMMA unsigned nPaletteSize)) - { - db_assert1(pPalette); - db_onlyassert1(*pCol < nPaletteSize); - return AwTl::Colour::ConvNonTransp::DoConv(&pPalette[*pCol]); - } -}; - -class AwIffConvTransp -{ - public: - static unsigned iTranspCol; // the index of the transparent colour - static unsigned rawTranspCol; // the value of a transparent pixel on the surface - - static inline unsigned DoConv(unsigned const * pCol, AwTl::Colour const * pPalette db_code1(DB_COMMA unsigned nPaletteSize)) - { - using namespace AwTl; - - if (*pCol == iTranspCol) return rawTranspCol; - unsigned rv = AwIffConvNonTransp::DoConv(pCol,pPalette db_code1(DB_COMMA nPaletteSize)); - if (rv != rawTranspCol) return rv; - - // make the colour non-transparent (nb: only an occasional case) - - // OK, Here's the plan: - - // First, suppose that I were to decrease either the Red, Green or Blue - // component in order to make the colour non-transparent. - // Taking Red as an example, I'll work out what the resultant red value - // will be if I decrease red to achieve a non-transparent colour - // I'll compare this to the actual red value of the colour in question - // The lower the difference, the better it'll be (ie. closer to the - // original colour). - // Obviously, I'll do the same for Green and Blue - // Then I'll repeat the process but this time considering increasing - // the components. - // I'll then have six values which are scores (the lower the better) - // for what colour component to change and how to change it. - // If any of the components cannot be decreased (ie. their resulting - // value is already zero) or increased (ie. their resulting value - // is at maximum), then I'll set the corresponding score to - // UINT_MAX so that that colour-changing operation won't be selected - // (because that'll be the one that buggers everything up). - - unsigned nRedDiffDown = - (pPalette[*pCol].r < 1<<pixelFormat.redRightShift ) ? UINT_MAX - : (pPalette[*pCol].r & (1<<pixelFormat.redRightShift )-1) + ((1<<pixelFormat.redRightShift )+1)/2; - - unsigned nGreenDiffDown = - (pPalette[*pCol].g < 1<<pixelFormat.greenRightShift) ? UINT_MAX - : (pPalette[*pCol].g & (1<<pixelFormat.greenRightShift)-1) + ((1<<pixelFormat.greenRightShift)+1)/2; - - unsigned nBlueDiffDown = - (pPalette[*pCol].b < 1<<pixelFormat.blueRightShift ) ? UINT_MAX - : (pPalette[*pCol].b & (1<<pixelFormat.blueRightShift )-1) + ((1<<pixelFormat.blueRightShift )+1)/2; - - unsigned nRedDiffUp = - (pPalette[*pCol].r >= (255 & ~((1<<pixelFormat.redRightShift )-1) ) ? UINT_MAX - : (1<<pixelFormat.redRightShift )*3/2 - (pPalette[*pCol].r & (1<<pixelFormat.redRightShift )-1)); - - unsigned nGreenDiffUp = - (pPalette[*pCol].g >= (255 & ~((1<<pixelFormat.greenRightShift)-1) ) ? UINT_MAX - : (1<<pixelFormat.greenRightShift)*3/2 - (pPalette[*pCol].g & (1<<pixelFormat.greenRightShift)-1)); - - unsigned nBlueDiffUp = - (pPalette[*pCol].b >= (255 & ~((1<<pixelFormat.blueRightShift )-1) ) ? UINT_MAX - : (1<<pixelFormat.blueRightShift )*3/2 - (pPalette[*pCol].b & (1<<pixelFormat.blueRightShift )-1)); - - // Pick lowest value and do the business - - Colour colAdj = pPalette[*pCol]; - - #if defined(_MSC_VER) && _MSC_VER >= 1100 - // VC5.0 gives inane warnings when += type operators - // are used on types smaller than int (even with - // explicit casting!) - #pragma warning(disable:4244) - #endif - if - ( - nBlueDiffUp <= nBlueDiffDown - && nBlueDiffUp <= nRedDiffUp - && nBlueDiffUp <= nRedDiffDown - && nBlueDiffUp <= nGreenDiffUp - && nBlueDiffUp <= nGreenDiffDown - ) - { - colAdj.b += static_cast<unsigned char>(1<<pixelFormat.blueRightShift); - } - else if - ( - nBlueDiffDown <= nRedDiffUp - && nBlueDiffDown <= nRedDiffDown - && nBlueDiffDown <= nGreenDiffUp - && nBlueDiffDown <= nGreenDiffDown - ) - { - colAdj.b -= static_cast<unsigned char>(1<<pixelFormat.blueRightShift); - } - else if - ( - nRedDiffUp <= nRedDiffDown - && nRedDiffUp <= nGreenDiffUp - && nRedDiffUp <= nGreenDiffDown - ) - { - colAdj.r += static_cast<unsigned char>(1<<pixelFormat.redRightShift); - } - else if - ( - nRedDiffDown <= nGreenDiffUp - && nRedDiffDown <= nGreenDiffDown - ) - { - colAdj.r -= static_cast<unsigned char>(1<<pixelFormat.redRightShift); - } - else if (nGreenDiffUp <= nGreenDiffDown) - { - colAdj.g += static_cast<unsigned char>(1<<pixelFormat.greenRightShift); - } - else - { - colAdj.g -= static_cast<unsigned char>(1<<pixelFormat.greenRightShift); - } - #if defined(_MSC_VER) && _MSC_VER == 1100 - // VC5.0 gives inane warnings when += type operators - // are used on types smaller than int (even with - // explicit casting!) - #pragma warning(default:4244) - #endif - - return Colour::ConvNonTransp::DoConv(&colAdj); - } -}; - -unsigned AwIffConvTransp::iTranspCol; -unsigned AwIffConvTransp::rawTranspCol; - -// IFF Loader - -class AwIffLoader : public AwTl::TexFileLoader -{ - public: - AwIffLoader() : m_pPalette(NULL), m_bDecoding(false) {} - protected: - virtual ~AwIffLoader(); - - virtual void LoadHeaderInfo(MediaMedium * pMedium); - - virtual unsigned GetNumColours(); - - virtual unsigned GetMinPaletteSize(); - - virtual bool HasTransparentMask(bool bDefault); - - virtual void AllocateBuffers(bool bWantBackup, unsigned nMaxPaletteSize); - - virtual void OnBeginRestoring(unsigned nMaxPaletteSize); - - virtual AwTl::Colour * GetPalette(); - - - virtual AwTl::PtrUnion GetRowPtr(unsigned nRow); - - virtual void LoadNextRow(AwTl::PtrUnion pRow); - - virtual void ConvertRow(AwTl::PtrUnion pDest, unsigned nDestWidth, AwTl::PtrUnionConst pSrc, unsigned nSrcOffset, unsigned nSrcWidth, AwTl::Colour * pPalette db_code1(DB_COMMA unsigned nPaletteSize)); - - virtual DWORD GetTransparentColour(); - - virtual void OnFinishLoading(bool bSuccess); - - virtual void OnFinishRestoring(bool bSuccess); - - virtual AwBackupTexture * CreateBackupTexture(); - - private: - static bool Enumerator(IFF::Chunk * pChunk, void * pData); - // list of chunks found by enumerator - List<IFF::IlbmBodyChunk *> m_listBodyChunks; - - // smallest and largest palette sizes of versions of this image - unsigned m_nMaxPaletteSize; - unsigned m_nMinPaletteSize; - - // buffer for palette - - // since the IFF cmap table is in a different format to what the Aw loaders require - // (maybe should think about standardizing the data types?) - AwTl::Colour * m_pPalette; - - // iff data - IFF::File m_ifData; - IFF::IlbmBmhdChunk * m_pHdr; - IFF::IlbmCmapChunk * m_pCmap; - IFF::IlbmBodyChunk * m_pBody; - - bool m_bDecoding; -}; - -AwIffLoader::~AwIffLoader() -{ - if (m_pPalette) delete[] m_pPalette; -} - -void AwIffLoader::LoadHeaderInfo(MediaMedium * pMedium) -{ - db_log4("\tLoading an IFF file"); - - while (m_listBodyChunks.size()) - m_listBodyChunks.delete_first_entry(); - - if (!m_ifData.Load(pMedium) || !m_ifData.GetContents()) - { - if (NO_ERROR == (awTlLastWinErr = GetLastError())) - awTlLastErr = AW_TLE_BADFILEDATA; - else - awTlLastErr = AW_TLE_CANTREADFILE; - - db_log3("AwCreateTexture(): ERROR: IFF file load failed"); - } - else - { - m_nMinPaletteSize = UINT_MAX; - m_nMaxPaletteSize = 0; - m_ifData.GetContents()->EnumChildren("ILBM","BODY",Enumerator,this); - } -} - -unsigned AwIffLoader::GetNumColours() -{ - return m_nMaxPaletteSize; -} - -unsigned AwIffLoader::GetMinPaletteSize() -{ - return m_nMinPaletteSize; -} - -void AwIffLoader::AllocateBuffers(bool /*bWantBackup*/, unsigned nMaxPaletteSize) -{ - // we will need to allocate buffers when restoring as well as first-time loading - // so allocate buffers in OnBeginRestoring() which we'll call here - - OnBeginRestoring(nMaxPaletteSize); -} - -bool AwIffLoader::Enumerator(IFF::Chunk * pChunk, void * pData) -{ - db_assert1(pChunk); - db_assert1(pData); - AwIffLoader * pThis = static_cast<AwIffLoader *>(pData); - - IFF::Chunk * pCmap = pChunk->GetProperty("CMAP"); - IFF::Chunk * pHdr = pChunk->GetProperty("BMHD"); - if (pCmap && pHdr) // must have these two properties - { - unsigned nThisPaletteSize = static_cast<IFF::IlbmCmapChunk *>(pCmap)->nEntries; - db_logf4(("\tfound a %u colour %scompressed IFF body chunk",nThisPaletteSize,static_cast<IFF::IlbmBmhdChunk *>(pHdr)->eCompression ? "" : "un")); - - pThis->m_listBodyChunks.add_entry(static_cast<IFF::IlbmBodyChunk *>(pChunk)); - - if (nThisPaletteSize < pThis->m_nMinPaletteSize) - pThis->m_nMinPaletteSize = nThisPaletteSize; - - if (nThisPaletteSize > pThis->m_nMaxPaletteSize) - pThis->m_nMaxPaletteSize = nThisPaletteSize; - } - else db_log3("AwCreateTexture(): WARNING: IFF body chunk found with insufficient associated property chunks"); - - return true; // continue enumeration -} - -void AwIffLoader::OnBeginRestoring(unsigned nMaxPaletteSize) -{ - using namespace AwTl; - - if (m_listBodyChunks.size()) - { - // if decodeing, m_pBody will be valid - if (m_bDecoding) - { - m_pBody->EndDecode(); - m_bDecoding = false; - } - - m_pBody = NULL; - unsigned nBestPaletteSize = 0; - - for (LIF<IFF::IlbmBodyChunk *> itChunks(&m_listBodyChunks); !itChunks.done(); itChunks.next()) - { - IFF::IlbmCmapChunk * pCmap = static_cast<IFF::IlbmCmapChunk *>(itChunks()->GetProperty("CMAP")); - db_assert1(pCmap); - - if ((!nMaxPaletteSize || pCmap->nEntries <= nMaxPaletteSize) && pCmap->nEntries > nBestPaletteSize) - { - m_pBody = itChunks(); - m_pCmap = pCmap; - nBestPaletteSize = pCmap->nEntries; - } - } - - if (m_pBody) - { - m_pHdr = static_cast<IFF::IlbmBmhdChunk *>(m_pBody->GetProperty("BMHD")); - // delete old buffers - if (m_pPalette) delete[] m_pPalette; - // allocate buffer for palette, make it extra big to cope with corrupt files - unsigned nAllocPaletteSize = m_pCmap->nEntries; - unsigned nAllocPaletteSizeShift = 0; - while (0!=(nAllocPaletteSize >>= 1)) - { - ++nAllocPaletteSizeShift; - } - m_pPalette = new Colour [2<<nAllocPaletteSizeShift]; // prevent corrupt data causing a crash - //m_pPalette = new Colour [m_pCmap->nEntries]; - // copy the palette - for (unsigned i=0; i<m_pCmap->nEntries; ++i) - { - // hacked testa - m_pPalette[i].r = m_pCmap->pTable[i].r; - m_pPalette[i].g = m_pCmap->pTable[i].g; - m_pPalette[i].b = m_pCmap->pTable[i].b; - } - // set the width height and palette size in the base class - m_nPaletteSize = m_pCmap->nEntries; - m_nWidth = m_pHdr->width; - m_nHeight = m_pHdr->height; - // prepare to decode the data - m_pBody->BeginDecode(); - m_bDecoding = true; - // set the transparent mask colours - switch (m_pHdr->eMasking) - { - case IFF::IlbmBmhdChunk::MASK_NONE: - break; - case IFF::IlbmBmhdChunk::MASK_TRANSPARENTCOL: - AwIffConvTransp::iTranspCol = m_pHdr->iTranspCol; - if (pixelFormat.palettizedB) - AwIffConvTransp::rawTranspCol = AwIffConvTransp::iTranspCol; - else - AwIffConvTransp::rawTranspCol = - static_cast<unsigned>(m_pPalette[AwIffConvTransp::iTranspCol].r)>>pixelFormat.redRightShift<<pixelFormat.redLeftShift - |static_cast<unsigned>(m_pPalette[AwIffConvTransp::iTranspCol].g)>>pixelFormat.greenRightShift<<pixelFormat.greenLeftShift - |static_cast<unsigned>(m_pPalette[AwIffConvTransp::iTranspCol].b)>>pixelFormat.blueRightShift<<pixelFormat.blueLeftShift; - break; - default: - db_log3("AwCreateTexture(): ERROR: IFF mask field wrong"); - awTlLastErr = AW_TLE_BADFILEDATA; - } - } - else - { - awTlLastErr = AW_TLE_CANTPALETTIZE; // no suitable chunk found - db_log3("AwCreateTexture(): ERROR: No suitable IFF body chunk found"); - } - } - else - { - awTlLastErr = AW_TLE_BADFILEDATA; - db_log3("AwCreateTexture(): ERROR: IFF file not loaded or contains no image data"); - } -} - -AwTl::Colour * AwIffLoader::GetPalette() -{ - return m_pPalette; -} - -bool AwIffLoader::HasTransparentMask(bool bDefault) -{ - if (m_listBodyChunks.size()) - { - IFF::IlbmBmhdChunk * pHdr = static_cast<IFF::IlbmBmhdChunk *>(m_listBodyChunks.first_entry()->GetProperty("BMHD")); - db_assert1(pHdr); - return (IFF::IlbmBmhdChunk::MASK_TRANSPARENTCOL == pHdr->eMasking); - } - else - return bDefault; -} - -DWORD AwIffLoader::GetTransparentColour() -{ - return AwIffConvTransp::rawTranspCol; -} - -AwTl::PtrUnion AwIffLoader::GetRowPtr(unsigned /*nRow*/) -{ - // the iff object has an internal buffer to which a pointer - // is returned when we decode each row - // unfortunately we have to cast constness away, but never mind - return const_cast<unsigned *>(m_pBody->DecodeNextRow()); -} - -void AwIffLoader::LoadNextRow(AwTl::PtrUnion /*pRow*/) -{ - // GetRowPtr() has called DecodeNextRow() - // which has filled in the data already - // so do nothing here -} - -void AwIffLoader::ConvertRow(AwTl::PtrUnion pDest, unsigned nDestWidth, AwTl::PtrUnionConst pSrc, unsigned nSrcOffset, unsigned nSrcWidth, AwTl::Colour * pPalette db_code1(DB_COMMA unsigned nPaletteSize)) -{ - using namespace AwTl; - - // we have overridden this function for two reasons: - // 1. The data type for each texel in the row is unsigned int - // to allow for the fact that all images are palettized - // with no limit on the palette size. The default - // implementation would assume BYTE (unsigned char) - // 2. The transparency flag and colour is stored in the - // file and the transparency flag passed to AwCreateTexture() - // is ignored. The transparent colour does not have to be 0,0,0 - // either - - db_assert1(pPalette); - db_assert1(pPalette == m_pPalette); - // we can still use GenericConvertRow though, using the conversion functors above - - if (pixelFormat.palettizedB) - { - GenericConvertRow<AwIffConvNull,unsigned>::Do(pDest, nDestWidth, pSrc.uintP+nSrcOffset, nSrcWidth); - } - else - { - switch (m_pHdr->eMasking) - { - case IFF::IlbmBmhdChunk::MASK_NONE: - GenericConvertRow<AwIffConvNonTransp,unsigned>::Do(pDest, nDestWidth, pSrc.uintP+nSrcOffset, nSrcWidth, pPalette db_code1(DB_COMMA nPaletteSize)); - break; - case IFF::IlbmBmhdChunk::MASK_TRANSPARENTCOL: - GenericConvertRow<AwIffConvTransp,unsigned>::Do(pDest, nDestWidth, pSrc.uintP+nSrcOffset, nSrcWidth, pPalette db_code1(DB_COMMA nPaletteSize)); - break; - default: - db_log3("AwCreateTexture(): ERROR: IFF mask field wrong"); - awTlLastErr = AW_TLE_BADFILEDATA; - } - } -} - -void AwIffLoader::OnFinishLoading(bool /*bSuccess*/) -{ - if (m_bDecoding) - { - m_pBody->EndDecode(); - m_bDecoding = false; - } -} - -void AwIffLoader::OnFinishRestoring(bool /*bSuccess*/) -{ - if (m_bDecoding) - { - m_pBody->EndDecode(); - m_bDecoding = false; - } -} - -AwBackupTexture * AwIffLoader::CreateBackupTexture() -{ - // use the same object for restoring - AddRef(); - return this; -} - -// Valid file ID fields: 'FORM' 'LIST' 'CAT ' - we can load them all -#ifdef _MSC_VER - // VC5.0 tries to compile out code that is in a library - // and it thinks isn't being used - #line 427 -#endif -AWTEXLD_IMPLEMENT_DYNCREATE("FORM",AwIffLoader) -AWTEXLD_IMPLEMENT_DYNCREATE("LIST",AwIffLoader) -AWTEXLD_IMPLEMENT_DYNCREATE("CAT ",AwIffLoader) diff --git a/3dc/win95/awPnmLd.cpp b/3dc/win95/awPnmLd.cpp deleted file mode 100644 index 4e54f2e..0000000 --- a/3dc/win95/awPnmLd.cpp +++ /dev/null @@ -1,239 +0,0 @@ -#include "advwin32.h" -#ifndef DB_LEVEL -#define DB_LEVEL 4 -#endif -#include "db.h" - -#include "awTexLd.hpp" - -// PNM loaders - -class AwPnmLoader : public AwTl::TypicalTexFileLoader -{ - protected: - void _AWTL_VARARG ParseHeader(unsigned nFields,...); - - MediaMedium * m_pMedium; -}; - -void _AWTL_VARARG AwPnmLoader::ParseHeader(unsigned nFields,...) -{ - va_list ap; - va_start(ap,nFields); - - m_pMedium->MovePos(+2); // skip past magic - - BYTE c = 0; - while (nFields) - { - unsigned * fieldP = va_arg(ap,unsigned *); - bool comment = false; - bool done = false; - do - { - MediaRead(m_pMedium, &c); - switch (c) - { - case '\n': - comment = false; - break; - case '#': - comment = true; - break; - default: - if (!comment && !isspace(c)) - done = true; - } - } - while (!done); - char bufA[512]; - char * bufP = bufA; - do - { - *bufP++ = c; - MediaRead(m_pMedium, &c); - } - while (!isspace(c)); - *bufP = 0; - *fieldP = atoi(bufA); - - -- nFields; - } - // c should now be a newline character - if ('\n'!=c) - awTlLastErr = AW_TLE_BADFILEDATA; - - va_end(ap); -} - -class AwPpmLoader : public AwPnmLoader -{ - protected: - virtual void LoadHeaderInfo(MediaMedium * pMedium); - virtual AwTl::Colour * GetPalette(); - virtual void LoadNextRow(AwTl::PtrUnion pRow); - - unsigned pm_maxval; -}; - -void AwPpmLoader::LoadHeaderInfo(MediaMedium * pMedium) -{ - m_pMedium = pMedium; - - db_log4("\tLoading a PPM file"); - - ParseHeader(3,&m_nWidth,&m_nHeight,&pm_maxval); - - db_logf4(("\tPPM_maxval is %u",pm_maxval)); - if (pm_maxval > 255) - { - awTlLastErr = AW_TLE_BADFILEFORMAT; - db_log3("AwCreateTexture(): PPM_maxval too large"); - } - - m_nPaletteSize = 0; -} - -AwTl::Colour * AwPpmLoader::GetPalette() -{ - // never palettized - return NULL; -} - -void AwPpmLoader::LoadNextRow(AwTl::PtrUnion pRow) -{ - if (pm_maxval != 255) - for (unsigned colcount = m_nWidth; colcount; --colcount) - { - BYTE byte; - MediaRead(m_pMedium,&byte); - pRow.colourP->r = static_cast<BYTE>(static_cast<unsigned>(byte)*255/pm_maxval); - MediaRead(m_pMedium,&byte); - pRow.colourP->g = static_cast<BYTE>(static_cast<unsigned>(byte)*255/pm_maxval); - MediaRead(m_pMedium,&byte); - pRow.colourP->b = static_cast<BYTE>(static_cast<unsigned>(byte)*255/pm_maxval); - ++pRow.colourP; - } - else - for (unsigned colcount = m_nWidth; colcount; --colcount) - { - MediaRead(m_pMedium,&pRow.colourP->r); - MediaRead(m_pMedium,&pRow.colourP->g); - MediaRead(m_pMedium,&pRow.colourP->b); - ++pRow.colourP; - } -} - - -class AwPgmLoader : public AwPnmLoader -{ - protected: - virtual void LoadHeaderInfo(MediaMedium * pMedium); - virtual AwTl::Colour * GetPalette(); - virtual void LoadNextRow(AwTl::PtrUnion pRow); - - unsigned pm_maxval; -}; - -void AwPgmLoader::LoadHeaderInfo(MediaMedium * pMedium) -{ - m_pMedium = pMedium; - - db_log4("\tLoading a PGM file"); - - ParseHeader(3,&m_nWidth,&m_nHeight,&pm_maxval); - - db_logf4(("\tPGM_maxval is %u",pm_maxval)); - if (pm_maxval > 255) - { - awTlLastErr = AW_TLE_BADFILEFORMAT; - db_log3("AwCreateTexture(): PGM_maxval too large"); - } - - m_nPaletteSize = pm_maxval+1; -} - -AwTl::Colour * AwPgmLoader::GetPalette() -{ - db_assert1(m_nPaletteSize); - db_assert1(m_pPalette); - - unsigned step8 = (256*255)/pm_maxval; - unsigned val8 = 127; - AwTl::Colour * pmP = m_pPalette; - for (unsigned pc = m_nPaletteSize; pc; --pc,++pmP,val8+=step8) - pmP->r = pmP->g = pmP->b = static_cast<BYTE>(val8/256); - - return m_pPalette; -} - -void AwPgmLoader::LoadNextRow(AwTl::PtrUnion pRow) -{ - m_pMedium->ReadBlock(pRow,m_nWidth); -} - - -class AwPbmLoader : public AwPnmLoader -{ - protected: - virtual void LoadHeaderInfo(MediaMedium * pMedium); - virtual AwTl::Colour * GetPalette(); - virtual void LoadNextRow(AwTl::PtrUnion pRow); -}; - - -void AwPbmLoader::LoadHeaderInfo(MediaMedium * pMedium) -{ - m_pMedium = pMedium; - - db_log4("\tLoading a PBM file"); - - ParseHeader(2,&m_nWidth,&m_nHeight); - - m_nPaletteSize = 2; -} - -AwTl::Colour * AwPbmLoader::GetPalette() -{ - db_assert1(m_nPaletteSize); - db_assert1(m_pPalette); - - m_pPalette[0].r = 0; - m_pPalette[0].g = 0; - m_pPalette[0].b = 0; - m_pPalette[1].r = 255; - m_pPalette[1].g = 255; - m_pPalette[1].b = 255; - - return m_pPalette; -} - -void AwPbmLoader::LoadNextRow(AwTl::PtrUnion pRow) -{ - unsigned shift = 0; - BYTE byte = 0; - - for (unsigned colcount = m_nWidth; colcount; --colcount) - { - if (!shift) - { - shift = 8; - MediaRead(m_pMedium,&byte); - byte = (BYTE) ~byte; - } - --shift; - *pRow.byteP++ = static_cast<BYTE>(byte>>shift & 1); - } -} - -#ifdef _MSC_VER - // VC5.0 tries to compile out code that is in a library - // and it thinks isn't being used - #line 228 -#endif -AWTEXLD_IMPLEMENT_DYNCREATE("P6",AwPpmLoader) -AWTEXLD_IMPLEMENT_DYNCREATE("P5",AwPgmLoader) -AWTEXLD_IMPLEMENT_DYNCREATE("P4",AwPbmLoader) - - - diff --git a/3dc/win95/awTexLd.cpp b/3dc/win95/awTexLd.cpp deleted file mode 100644 index 65f4b7a..0000000 --- a/3dc/win95/awTexLd.cpp +++ /dev/null @@ -1,2974 +0,0 @@ -#include "advwin32.h" -#ifndef DB_LEVEL -#define DB_LEVEL 4 -#endif -#include "db.h" - -#ifndef NDEBUG - #define HT_FAIL db_log1 - #include "hash_tem.hpp" // for the backup surfaces memory leak checking -#endif - -#ifdef _MSC_VER - #include "iff.hpp" -#endif - -#include "list_tem.hpp" - -#include <stdlib.h> -#include <stdarg.h> -#include <limits.h> - -#include "awTexLd.h" -#pragma warning(disable: 4701) -#include "awTexLd.hpp" -#pragma warning(default: 4701) - -#ifdef _CPPRTTI - #include <typeinfo.h> -#endif - -/* awTexLd.cpp - Author: Jake Hotson */ - -/*****************************************/ -/* Preprocessor switches for experiments */ -/*****************************************/ - -#define MIPMAPTEST 0 // experiment to create mip map surfaces for textures, but doesn't bother putting any data into them - -/*****************************/ -/* DB_LEVEL dependent macros */ -/*****************************/ - -#if DB_LEVEL >= 5 -#define inline // prevent function inlining at level 5 debugging -#endif - -/*****************************************************/ -/* ZEROFILL and SETDWSIZE macros ensure that I won't */ -/* accidentally get the parameters wrong */ -/*****************************************************/ - -#if 1 // which do you prefer? - -// zero mem -template <class X> -static inline void ZEROFILL(X & x) -{ - memset(&x,0,sizeof(X)); -} - -// set dwSize -template <class X> -static inline void SETDWSIZE(X & x) -{ - x.dwSize = sizeof(X); -} - -template <class X> -static inline void INITDXSTRUCT(X & x) -{ - ZEROFILL(x); - SETDWSIZE(x); -} - -#else - -#define ZEROFILL(x) (memset(&x,0,sizeof x)) -#define SETDWSIZE(x) (x.dwSize = sizeof x) -#define INITDXSTRUCT(x) (ZEROFILL(x),SETDWSIZE(x)) - -#endif - -/*****************************************************************/ -/* Put everything I can in a namespace to avoid naming conflicts */ -/*****************************************************************/ - -namespace AwTl -{ - /**************************************************/ - /* Allow breakpoints to be potentially hard coded */ - /* into macros and template functions */ - /**************************************************/ - - db_code5(void BrkPt(){}) - #define BREAKPOINT db_code5(::AwTl::BrkPt();) - - #if DB_LEVEL > 4 - static unsigned GetRefCount(IUnknown * pUnknown) - { - if (!pUnknown) return 0; - pUnknown->AddRef(); - return static_cast<unsigned>(pUnknown->Release()); - } - #endif - - /*********************************/ - /* Pixel format global structure */ - /*********************************/ - - PixelFormat pixelFormat; - - PixelFormat pfTextureFormat; - PixelFormat pfSurfaceFormat; - - static inline void SetBitShifts(unsigned * leftShift,unsigned * rightShift,unsigned mask) - { - if (!mask) - *leftShift = 0; - else - for (*leftShift = 0; !(mask & 1); ++*leftShift, mask>>=1) - ; - for (*rightShift = 8; mask; --*rightShift, mask>>=1) - ; - } - - /************************************/ - /* D3D Driver info global structure */ - /************************************/ - - static - struct DriverDesc - { - DriverDesc() : validB(false), ddP(NULL) {} - - bool validB : 1; - bool needSquareB : 1; - bool needPow2B : 1; - - unsigned minWidth; - unsigned minHeight; - unsigned maxWidth; - unsigned maxHeight; - - DWORD memFlag; - - DDObject * ddP; - } - driverDesc; - - /*************************************************************************/ - /* Class used to hold all the parameters for the CreateTexture functions */ - /*************************************************************************/ - - class CreateTextureParms - { - public: - inline CreateTextureParms() - : fileNameS(NULL) - , fileH(INVALID_HANDLE_VALUE) - , dataP(NULL) - , restoreH(NULL) - , maxReadBytes(UINT_MAX) - , bytesReadP(NULL) - , flags(AW_TLF_DEFAULT) - , originalWidthP(NULL) - , originalHeightP(NULL) - , widthP(NULL) - , heightP(NULL) - , backupHP(NULL) - , prevTexP(static_cast<D3DTexture *>(NULL)) - , prevTexB(false) - , loadTextureB(false) - , callbackF(NULL) - , rectA(NULL) - { - } - - SurfUnion DoCreate() const; - - bool loadTextureB; - - LPCTSTR fileNameS; - HANDLE fileH; - PtrUnionConst dataP; - AW_BACKUPTEXTUREHANDLE restoreH; - - unsigned maxReadBytes; - unsigned * bytesReadP; - - unsigned flags; - - unsigned * widthP; - unsigned * heightP; - - unsigned * originalWidthP; - unsigned * originalHeightP; - - AW_BACKUPTEXTUREHANDLE * backupHP; - - SurfUnion prevTexP; - bool prevTexB; // used when rectA is non-NULL, otherwise prevTexP is used - - AW_TL_PFN_CALLBACK callbackF; - void * callbackParam; - - unsigned numRects; - AwCreateGraphicRegion * rectA; - }; - - - /****************************************/ - /* Reference Count Object Debug Support */ - /****************************************/ - - #ifndef NDEBUG - - static bool g_bAllocListActive = false; - - class AllocList : public ::HashTable<RefCntObj *> - { - public: - AllocList() - { - g_bAllocListActive = true; - } - ~AllocList() - { - if (Size()) - { - db_log1(("AW: Potential Memory Leaks Detected!!!")); - } - #ifdef _CPPRTTI - #pragma message("Run-Time Type Identification (RTTI) is enabled") - for (Iterator itLeak(*this) ; !itLeak.Done() ; itLeak.Next()) - { - db_logf1(("\tAW Object not deallocated: Type: %s RefCnt: %u",typeid(*itLeak.Get()).name(),itLeak.Get()->m_nRefCnt)); - } - if (Size()) - { - db_log1(("AW: Object dump complete")); - } - #else // ! _CPPRTTI - #pragma message("Run-Time Type Identification (RTTI) is not enabled - memory leak checking will not report types") - unsigned nRefs(0); - for (Iterator itLeak(*this) ; !itLeak.Done() ; itLeak.Next()) - { - nRefs += itLeak.Get()->m_nRefCnt; - } - if (Size()) - { - db_logf1(("AW: Objects not deallocated: Number of Objects: %u Number of References: %u",Size(),nRefs)); - } - #endif // ! _CPPRTTI - g_bAllocListActive = false; - } - }; - - static AllocList g_listAllocated; - - void DbRemember(RefCntObj * pObj) - { - g_listAllocated.AddAsserted(pObj); - } - - void DbForget(RefCntObj * pObj) - { - if (g_bAllocListActive) - g_listAllocated.RemoveAsserted(pObj); - } - - #endif // ! NDEBUG - - /********************************************/ - /* structure to contain loading information */ - /********************************************/ - - struct LoadInfo - { - DDSurface * surfaceP; - bool surface_lockedB; - DDSurface * dst_surfaceP; - D3DTexture * textureP; - D3DTexture * dst_textureP; - - unsigned surface_width; - unsigned surface_height; - PtrUnion surface_dataP; - LONG surface_pitch; - DWORD dwCapsCaps; - - unsigned * widthP; - unsigned * heightP; - SurfUnion prevTexP; - SurfUnion resultP; - unsigned top,left,bottom,right; - unsigned width,height; // set to right-left and bottom-top - - AwCreateGraphicRegion * rectP; - - bool skipB; // used to indicate that a surface/texture was not lost and .`. does not need restoring - - LoadInfo() - : surfaceP(NULL) - , surface_lockedB(false) - , dst_surfaceP(NULL) - , textureP(NULL) - , dst_textureP(NULL) - , skipB(false) - { - } - }; - - /*******************************/ - /* additiional texture formats */ - /*******************************/ - - struct AdditionalPixelFormat : PixelFormat - { - bool canDoTranspB; - unsigned maxColours; - - // for List - bool operator == (AdditionalPixelFormat const &) const { return false; } - bool operator != (AdditionalPixelFormat const &) const { return true; } - }; - - static List<AdditionalPixelFormat> listTextureFormats; - -} // namespace AwTl - -/*******************/ -/* Generic Loaders */ -/*******************/ - -#define HANDLE_DXERROR(s) \ - if (DD_OK != awTlLastDxErr) { \ - awTlLastErr = AW_TLE_DXERROR; \ - db_logf3(("AwCreateGraphic() failed whilst %s",s)); \ - db_log1("AwCreateGraphic(): ERROR: DirectX SDK call failed"); \ - goto EXIT_WITH_ERROR; \ - } else { \ - db_logf5(("\tsuccessfully completed %s",s)); \ - } - -#define ON_ERROR_RETURN_NULL(s) \ - if (awTlLastErr != AW_TLE_OK) { \ - db_logf3(("AwCreateGraphic() failed whilst %s",s)); \ - db_logf1(("AwCreateGraphic(): ERROR: %s",AwTlErrorToString())); \ - return static_cast<D3DTexture *>(NULL); \ - } else { \ - db_logf5(("\tsuccessfully completed %s",s)); \ - } - -#define CHECK_MEDIA_ERRORS(s) \ - if (pMedium->m_fError) { \ - db_logf3(("AwCreateGraphic(): The following media errors occurred whilst %s",s)); \ - if (pMedium->m_fError & MediaMedium::MME_VEOFMET) { \ - db_log3("\tA virtual end of file was met"); \ - if (awTlLastErr == AW_TLE_OK) awTlLastErr = AW_TLE_EOFMET; \ - } \ - if (pMedium->m_fError & MediaMedium::MME_EOFMET) { \ - db_log3("\tAn actual end of file was met"); \ - if (awTlLastErr == AW_TLE_OK) awTlLastErr = AW_TLE_EOFMET; \ - } \ - if (pMedium->m_fError & MediaMedium::MME_OPENFAIL) { \ - db_log3("\tThe file could not be opened"); \ - if (awTlLastErr == AW_TLE_OK) { awTlLastErr = AW_TLE_CANTOPENFILE; awTlLastWinErr = GetLastError(); } \ - } \ - if (pMedium->m_fError & MediaMedium::MME_CLOSEFAIL) { \ - db_log3("\tThe file could not be closed"); \ - if (awTlLastErr == AW_TLE_OK) { awTlLastErr = AW_TLE_CANTOPENFILE; awTlLastWinErr = GetLastError(); } \ - } \ - if (pMedium->m_fError & MediaMedium::MME_UNAVAIL) { \ - db_log3("\tA requested operation was not available"); \ - if (awTlLastErr == AW_TLE_OK) { awTlLastErr = AW_TLE_CANTREADFILE; awTlLastWinErr = GetLastError(); } \ - } \ - if (pMedium->m_fError & MediaMedium::MME_IOERROR) { \ - db_log3("\tA read error occurred"); \ - if (awTlLastErr == AW_TLE_OK) { awTlLastErr = AW_TLE_CANTREADFILE; awTlLastWinErr = GetLastError(); } \ - } \ - } - -AwTl::SurfUnion AwBackupTexture::Restore(AwTl::CreateTextureParms const & rParams) -{ - using namespace AwTl; - - ChoosePixelFormat(rParams); - - if (!pixelFormat.validB) - db_log3("AwCreateGraphic(): ERROR: pixel format not valid"); - if (!driverDesc.ddP || !driverDesc.validB && rParams.loadTextureB) - db_log3("AwCreateGraphic(): ERROR: driver description not valid"); - - awTlLastErr = pixelFormat.validB && driverDesc.ddP && (driverDesc.validB || !rParams.loadTextureB) ? AW_TLE_OK : AW_TLE_NOINIT; - - ON_ERROR_RETURN_NULL("initializing restore") - - OnBeginRestoring(pixelFormat.palettizedB ? 1<<pixelFormat.bitsPerPixel : 0); - - ON_ERROR_RETURN_NULL("initializing restore") - - SurfUnion pTex = CreateTexture(rParams); - - OnFinishRestoring(AW_TLE_OK == awTlLastErr ? true : false); - - return pTex; -} - -bool AwBackupTexture::HasTransparentMask(bool bDefault) -{ - return bDefault; -} - -DWORD AwBackupTexture::GetTransparentColour() -{ - return 0; -} - -void AwBackupTexture::ChoosePixelFormat(AwTl::CreateTextureParms const & _parmsR) -{ - using namespace AwTl; - - pixelFormat.validB = false; // set invalid first - - // which flags to use? - unsigned fMyFlags = - _parmsR.flags & AW_TLF_PREVSRCALL ? db_assert1(_parmsR.restoreH), m_fFlags - : _parmsR.flags & AW_TLF_PREVSRC ? db_assert1(_parmsR.restoreH), - _parmsR.flags & ~AW_TLF_TRANSP | m_fFlags & AW_TLF_TRANSP - : _parmsR.flags; - - // transparency? - m_bTranspMask = HasTransparentMask(fMyFlags & AW_TLF_TRANSP ? true : false); - - #if 0 - if (_parmsR.prevTexP.voidP) - { - // use the previous format - } - else if (_parmsR.prevTexB) - { - // use the previous format from one of the regiouns - } - else - #endif - - if (_parmsR.loadTextureB || fMyFlags & AW_TLF_TEXTURE) - { - // use a texture format - unsigned nColours = GetNumColours(); - unsigned nMinPalSize = GetMinPaletteSize(); - - PixelFormat const * pFormat = &pfTextureFormat; - - for (LIF<AdditionalPixelFormat> itFormat(&listTextureFormats); !itFormat.done(); itFormat.next()) - { - AdditionalPixelFormat const * pThisFormat = &itFormat(); - // is this format suitable? - // ignoring alpha for now - if - ( - (nMinPalSize <= 1U<<pThisFormat->bitsPerPixel && nMinPalSize || !pThisFormat->palettizedB) // few enough colours for palettized format - && (nColours <= pThisFormat->maxColours && nColours || !pThisFormat->maxColours) // pass the max colours test - && (pThisFormat->canDoTranspB || !m_bTranspMask) // pass the transparency test - ) - { - pFormat = pThisFormat; - } - } - - pixelFormat = *pFormat; - - #if DB_LEVEL >= 4 - if (pixelFormat.palettizedB) - { - db_logf4(("\tchosen %u-bit palettized texture format",pixelFormat.bitsPerPixel)); - } - else - { - if (pixelFormat.alphaB) - { - unsigned alpha_l_shft,alpha_r_shft; - SetBitShifts(&alpha_l_shft,&alpha_r_shft,pixelFormat.ddpf.dwRGBAlphaBitMask); - - db_logf4(("\tchosen %u-bit %u%u%u%u texture format", - pixelFormat.bitsPerPixel, - 8U-pixelFormat.redRightShift, - 8U-pixelFormat.greenRightShift, - 8U-pixelFormat.blueRightShift, - 8U-alpha_r_shft)); - } - else - { - db_logf4(("\tchosen %u-bit %u%u%u texture format", - pixelFormat.bitsPerPixel, - 8U-pixelFormat.redRightShift, - 8U-pixelFormat.greenRightShift, - 8U-pixelFormat.blueRightShift)); - } - } - #endif - } - else - { - // use display surface format - pixelFormat = pfSurfaceFormat; - } - -} - -AwTl::SurfUnion AwBackupTexture::CreateTexture(AwTl::CreateTextureParms const & _parmsR) -{ - using namespace AwTl; - - // which flags to use? - unsigned fMyFlags = - _parmsR.flags & AW_TLF_PREVSRCALL ? db_assert1(_parmsR.restoreH), - _parmsR.flags & (AW_TLF_CHECKLOST|AW_TLF_SKIPNOTLOST) | m_fFlags & ~(AW_TLF_CHECKLOST|AW_TLF_SKIPNOTLOST) - : _parmsR.flags & AW_TLF_PREVSRC ? db_assert1(_parmsR.restoreH), - _parmsR.flags & ~AW_TLF_TRANSP | m_fFlags & AW_TLF_TRANSP - : _parmsR.flags; - - db_code1(ULONG refcnt;) - - DDPalette * dd_paletteP = NULL; - LoadInfo * arrLoadInfo = NULL; - unsigned nLoadInfos = 0; - { - // quick error check - if (pixelFormat.palettizedB && (!m_nPaletteSize || 1U<<pixelFormat.bitsPerPixel < m_nPaletteSize)) - awTlLastErr = AW_TLE_CANTPALETTIZE; - if (!m_nHeight || !m_nWidth) - awTlLastErr = AW_TLE_BADFILEDATA; - if (AW_TLE_OK != awTlLastErr) - { - db_log1("AwCreateGraphic() failed whilst interpreting the header data or palette"); - goto EXIT_WITH_ERROR; - } - - if (_parmsR.originalWidthP) *_parmsR.originalWidthP = m_nWidth; - if (_parmsR.originalHeightP) *_parmsR.originalHeightP = m_nHeight; - - if (_parmsR.rectA) - { - nLoadInfos = 0; - arrLoadInfo = _parmsR.numRects ? new LoadInfo[_parmsR.numRects] : NULL; - for (unsigned i=0; i<_parmsR.numRects; ++i) - { - _parmsR.rectA[i].width = 0; - _parmsR.rectA[i].height = 0; - if - ( - _parmsR.rectA[i].top < m_nHeight - && _parmsR.rectA[i].left < m_nWidth - && (!_parmsR.prevTexB || (_parmsR.loadTextureB ? (_parmsR.rectA[i].pTexture != NULL) : (_parmsR.rectA[i].pSurface != NULL))) - && _parmsR.rectA[i].right > _parmsR.rectA[i].left - && _parmsR.rectA[i].bottom > _parmsR.rectA[i].top - ) - { - // rectangle covers at least some of the image and non-null previous texture - arrLoadInfo[nLoadInfos].widthP = &_parmsR.rectA[i].width; - arrLoadInfo[nLoadInfos].heightP = &_parmsR.rectA[i].height; - if (_parmsR.prevTexB) - { - if (_parmsR.loadTextureB) - arrLoadInfo[nLoadInfos].prevTexP = _parmsR.rectA[i].pTexture; - else - arrLoadInfo[nLoadInfos].prevTexP = _parmsR.rectA[i].pSurface; - } - else - { - arrLoadInfo[nLoadInfos].prevTexP = static_cast<D3DTexture *>(NULL); - if (_parmsR.loadTextureB) - _parmsR.rectA[i].pTexture = NULL; - else - _parmsR.rectA[i].pSurface = NULL; - } - - arrLoadInfo[nLoadInfos].rectP = &_parmsR.rectA[i]; - arrLoadInfo[nLoadInfos].top = _parmsR.rectA[i].top; - arrLoadInfo[nLoadInfos].left = _parmsR.rectA[i].left; - arrLoadInfo[nLoadInfos].bottom = _parmsR.rectA[i].bottom; - arrLoadInfo[nLoadInfos].right = _parmsR.rectA[i].right; - - if (arrLoadInfo[nLoadInfos].right > m_nWidth) arrLoadInfo[nLoadInfos].right = m_nWidth; - if (arrLoadInfo[nLoadInfos].bottom > m_nHeight) arrLoadInfo[nLoadInfos].bottom = m_nHeight; - - arrLoadInfo[nLoadInfos].width = arrLoadInfo[nLoadInfos].right - arrLoadInfo[nLoadInfos].left; - arrLoadInfo[nLoadInfos].height = arrLoadInfo[nLoadInfos].bottom - arrLoadInfo[nLoadInfos].top; - - ++nLoadInfos; - } - else - { - if (!_parmsR.prevTexB) - _parmsR.rectA[i].pTexture = NULL; - } - } - } - else - { - nLoadInfos = 1; - arrLoadInfo = new LoadInfo[1]; - arrLoadInfo[0].widthP = _parmsR.widthP; - arrLoadInfo[0].heightP = _parmsR.heightP; - arrLoadInfo[0].prevTexP = _parmsR.prevTexP; - arrLoadInfo[0].rectP = NULL; - arrLoadInfo[0].top = 0; - arrLoadInfo[0].left = 0; - arrLoadInfo[0].bottom = m_nHeight; - arrLoadInfo[0].right = m_nWidth; - arrLoadInfo[0].width = m_nWidth; - arrLoadInfo[0].height = m_nHeight; - } - - bool bSkipAll = true; - - // loop creating surfaces - {for (unsigned i=0; i<nLoadInfos; ++i) - { - LoadInfo * pLoadInfo = &arrLoadInfo[i]; - - db_logf4(("\trectangle from image (%u,%u)-(%u,%u)",pLoadInfo->left,pLoadInfo->top,pLoadInfo->right,pLoadInfo->bottom)); - db_logf5(("\treference count on input surface %u",_parmsR.loadTextureB ? GetRefCount(pLoadInfo->prevTexP.textureP) : GetRefCount(pLoadInfo->prevTexP.surfaceP))); - - // determine what the width and height of the surface will be - - if (_parmsR.loadTextureB || fMyFlags & AW_TLF_TEXTURE) - { - awTlLastErr = - AwGetTextureSize - ( - &pLoadInfo->surface_width, - &pLoadInfo->surface_height, - fMyFlags & AW_TLF_MINSIZE && pLoadInfo->rectP ? pLoadInfo->rectP->right - pLoadInfo->rectP->left : pLoadInfo->width, - fMyFlags & AW_TLF_MINSIZE && pLoadInfo->rectP ? pLoadInfo->rectP->bottom - pLoadInfo->rectP->top : pLoadInfo->height - ); - if (awTlLastErr != AW_TLE_OK) - goto EXIT_WITH_ERROR; - } - else - { - pLoadInfo->surface_width = fMyFlags & AW_TLF_MINSIZE && pLoadInfo->rectP ? pLoadInfo->rectP->right - pLoadInfo->rectP->left : pLoadInfo->width; - pLoadInfo->surface_height = fMyFlags & AW_TLF_MINSIZE && pLoadInfo->rectP ? pLoadInfo->rectP->bottom - pLoadInfo->rectP->top : pLoadInfo->height; - #if 1 // not sure if this is required... - pLoadInfo->surface_width += 3; - pLoadInfo->surface_width &= ~3; - pLoadInfo->surface_height += 3; - pLoadInfo->surface_height &= ~3; - #endif - } - - if (pLoadInfo->widthP) *pLoadInfo->widthP = pLoadInfo->surface_width; - if (pLoadInfo->heightP) *pLoadInfo->heightP = pLoadInfo->surface_height; - - // Create DD Surface - - DD_SURFACE_DESC ddsd; - INITDXSTRUCT(ddsd); - ddsd.ddpfPixelFormat = pixelFormat.ddpf; - ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT; - if (_parmsR.loadTextureB || fMyFlags & AW_TLF_TEXTURE) - pLoadInfo->dwCapsCaps = DDSCAPS_TEXTURE | (fMyFlags & (AW_TLF_COMPRESS|AW_TLF_TEXTURE) ? DDSCAPS_SYSTEMMEMORY : driverDesc.memFlag); - else - pLoadInfo->dwCapsCaps = DDSCAPS_OFFSCREENPLAIN | (fMyFlags & AW_TLF_VIDMEM ? DDSCAPS_VIDEOMEMORY : DDSCAPS_SYSTEMMEMORY); - ddsd.ddsCaps.dwCaps = pLoadInfo->dwCapsCaps; - ddsd.dwHeight = pLoadInfo->surface_height; - ddsd.dwWidth = pLoadInfo->surface_width; - - #if MIPMAPTEST - /* - D3DPTEXTURECAPS_POW2 - All nonmipmapped textures must have widths and heights specified as powers of two if this flag is set. - (Note that all mipmapped textures must always have dimensions that are powers of two.) - */ - if (128==pLoadInfo->surface_width && 128==pLoadInfo->surface_height) - { - ddsd.ddsCaps.dwCaps |= DDSCAPS_MIPMAP | DDSCAPS_COMPLEX; - ddsd.dwFlags |= DDSD_MIPMAPCOUNT; - ddsd.dwMipMapCount = 3; - } - #endif - - if (pLoadInfo->prevTexP.voidP && (!_parmsR.loadTextureB || !(fMyFlags & AW_TLF_COMPRESS))) - { - if (_parmsR.loadTextureB) - awTlLastDxErr = pLoadInfo->prevTexP.textureP->QueryInterface(GUID_DD_SURFACE,(LPVOID *)&pLoadInfo->surfaceP); - else - awTlLastDxErr = pLoadInfo->prevTexP.surfaceP->QueryInterface(GUID_DD_SURFACE,(LPVOID *)&pLoadInfo->surfaceP); - HANDLE_DXERROR("getting direct draw surface interface") - #if DB_LEVEL >= 5 - if (_parmsR.loadTextureB) - db_logf5(("\t\tnow prev tex ref %u new surface i/f ref %u",GetRefCount(pLoadInfo->prevTexP.textureP),GetRefCount(pLoadInfo->surfaceP))); - else - db_logf5(("\t\tnow prev surf ref %u new surface i/f ref %u",GetRefCount(pLoadInfo->prevTexP.surfaceP),GetRefCount(pLoadInfo->surfaceP))); - #endif - - // check for lost surfaces - if (fMyFlags & AW_TLF_CHECKLOST) - { - awTlLastDxErr = pLoadInfo->surfaceP->IsLost(); - - if (DDERR_SURFACELOST == awTlLastDxErr) - { - db_log4("\tRestoring Lost Surface"); - - awTlLastDxErr = pLoadInfo->surfaceP->Restore(); - } - else if (DD_OK == awTlLastDxErr && (fMyFlags & AW_TLF_SKIPNOTLOST)) - { - db_log4("\tSkipping Surface which was not Lost"); - - pLoadInfo->skipB = true; - } - - HANDLE_DXERROR("testing for lost surface and restoring if necessary"); - } - - if (!pLoadInfo->skipB) - { - // check that the surface desc is OK - // note that SetSurfaceDesc is *only* supported for changing the surface memory pointer - DD_SURFACE_DESC old_ddsd; - INITDXSTRUCT(old_ddsd); - awTlLastDxErr = pLoadInfo->surfaceP->GetSurfaceDesc(&old_ddsd); - HANDLE_DXERROR("getting previous surface desc") - // check width, height, RGBBitCount and memory type - if (old_ddsd.dwFlags & DDSD_ALL || (old_ddsd.dwFlags & (DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT)) == (DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT)) - { - if (old_ddsd.dwHeight == pLoadInfo->surface_height && old_ddsd.dwWidth == pLoadInfo->surface_width && (old_ddsd.ddsCaps.dwCaps & (DDSCAPS_SYSTEMMEMORY|DDSCAPS_VIDEOMEMORY|DDSCAPS_TEXTURE)) == pLoadInfo->dwCapsCaps) - { - unsigned bpp = 0; - if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED8) - bpp = 8; - else if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED4) - bpp = 4; - else if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED2) - bpp = 2; - else if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED1) - bpp = 1; - else if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_RGB) - bpp = old_ddsd.ddpfPixelFormat.dwRGBBitCount; - if (pixelFormat.bitsPerPixel != bpp) - awTlLastErr = AW_TLE_CANTRELOAD; - } - else - awTlLastErr = AW_TLE_CANTRELOAD; - } - else - awTlLastErr = AW_TLE_CANTRELOAD; - if (AW_TLE_OK != awTlLastErr) - { - db_log1("AwCreateGraphic() failed because existing surface is incompatible"); - goto EXIT_WITH_ERROR; - } - } - else - { - pLoadInfo->surfaceP->Release(); - pLoadInfo->surfaceP = NULL; - } - } - else - { - if (pLoadInfo->prevTexP.voidP && (fMyFlags & AW_TLF_CHECKLOST)) - { - db_assert1(_parmsR.loadTextureB); - - awTlLastDxErr = pLoadInfo->prevTexP.textureP->QueryInterface(GUID_DD_SURFACE,(LPVOID *)&pLoadInfo->surfaceP); - HANDLE_DXERROR("getting direct draw surface interface") - - db_logf5(("\t\tnow prev tex ref %u new surface i/f ref %u",GetRefCount(pLoadInfo->prevTexP.textureP),GetRefCount(pLoadInfo->surfaceP))); - - awTlLastDxErr = pLoadInfo->surfaceP->IsLost(); - - if (DDERR_SURFACELOST == awTlLastDxErr) - { - db_log4("\tRestoring Lost Surface"); - - awTlLastDxErr = pLoadInfo->surfaceP->Restore(); - } - else if (DD_OK == awTlLastDxErr && (fMyFlags & AW_TLF_SKIPNOTLOST)) - { - db_log4("\tSkipping Surface which was not Lost"); - - pLoadInfo->skipB = true; - } - - HANDLE_DXERROR("testing for lost surface and restoring if necessary"); - - pLoadInfo->surfaceP->Release(); - pLoadInfo->surfaceP = NULL; - } - - if (!pLoadInfo->skipB) - { - do - { - awTlLastDxErr = driverDesc.ddP->CreateSurface(&ddsd,&pLoadInfo->surfaceP,NULL); - } - while - ( - DDERR_OUTOFVIDEOMEMORY == awTlLastDxErr - && _parmsR.callbackF - && _parmsR.callbackF(_parmsR.callbackParam) - ); - - HANDLE_DXERROR("creating direct draw surface") - } - } - - if (pLoadInfo->skipB) - { - db_assert1(pLoadInfo->prevTexP.voidP); - - // skipping so result is same as input - pLoadInfo->resultP = pLoadInfo->prevTexP; - - if (_parmsR.loadTextureB) - pLoadInfo->prevTexP.textureP->AddRef(); - else - pLoadInfo->prevTexP.surfaceP->AddRef(); - } - - #if MIPMAPTEST - if (128==surface_width && 128==surface_height) - { - // test if we can get attached surfaces... - DDSCAPS ddscaps; - ZEROFILL(ddscaps); - ddscaps.dwCaps = DDSCAPS_TEXTURE | DDSCAPS_MIPMAP; - DDSurface * mip2P; - awTlLastDxErr = pLoadInfo->surfaceP->GetAttachedSurface(&ddscaps,&mip2P); - HANDLE_DXERROR("getting first mipmap") - DDSurface * mip3P; - awTlLastDxErr = mip2P->GetAttachedSurface(&ddscaps,&mip3P); - HANDLE_DXERROR("getting second mipmap") - db_logf5(("\tabout to release 2nd mip with ref %u",GetRefCount(mip2P))); - db_code1(refcnt =) - mip2P->Release(); - db_onlyassert1(1==refcnt); - db_logf5(("\tabout to release 3nd mip with ref %u",GetRefCount(mip3P))); - db_code1(refcnt =) - mip3P->Release(); - db_onlyassert1(1==refcnt); - } - #endif - - bSkipAll = bSkipAll && pLoadInfo->skipB; - }} - - if (!bSkipAll) - { - Colour * paletteP = m_nPaletteSize ? GetPalette() : NULL; - - unsigned y = 0; - bool reversed_rowsB = AreRowsReversed(); - if (reversed_rowsB) - { - y = m_nHeight-1; - } - - for (unsigned rowcount = m_nHeight; rowcount; --rowcount) - { - PtrUnion src_rowP = GetRowPtr(y); - db_assert1(src_rowP.voidP); - - // allow loading of the next row from the file - LoadNextRow(src_rowP); - - // loop for copying data to surfaces - for (unsigned i=0; i<nLoadInfos; ++i) - { - LoadInfo * pLoadInfo = &arrLoadInfo[i]; - - if (!pLoadInfo->skipB) - { - // are we in the vertical range of this surface? - if (y>=pLoadInfo->top && y<pLoadInfo->bottom) - { - if (!pLoadInfo->surface_lockedB) - { - // lock the surfaces - DD_SURFACE_DESC ddsd; - INITDXSTRUCT(ddsd); - awTlLastDxErr = pLoadInfo->surfaceP->Lock(NULL,&ddsd,DDLOCK_WRITEONLY|DDLOCK_NOSYSLOCK,NULL); - HANDLE_DXERROR("locking direct draw surface") - pLoadInfo->surface_lockedB = true; - pLoadInfo->surface_dataP.voidP = ddsd.lpSurface; - pLoadInfo->surface_dataP.byteP += ddsd.lPitch * (y-pLoadInfo->top); - pLoadInfo->surface_pitch = ddsd.lPitch; - } - - // convert and copy the section of the row to the direct draw surface - ConvertRow(pLoadInfo->surface_dataP,pLoadInfo->surface_width,src_rowP,pLoadInfo->left,pLoadInfo->width,paletteP db_code1(DB_COMMA m_nPaletteSize)); - - // do the bottom row twice if the dd surface is bigger - if (pLoadInfo->bottom-1 == y && pLoadInfo->surface_height > pLoadInfo->height) - { - PtrUnion next_surface_rowP = pLoadInfo->surface_dataP; - next_surface_rowP.byteP += pLoadInfo->surface_pitch; - ConvertRow(next_surface_rowP,pLoadInfo->surface_width,src_rowP,pLoadInfo->left,pLoadInfo->width,paletteP db_code1(DB_COMMA m_nPaletteSize)); - } - - // next ddsurface row - if (reversed_rowsB) - pLoadInfo->surface_dataP.byteP -= pLoadInfo->surface_pitch; - else - pLoadInfo->surface_dataP.byteP += pLoadInfo->surface_pitch; - } - else if (pLoadInfo->surface_lockedB) - { - // unlock the surface - awTlLastDxErr = pLoadInfo->surfaceP->Unlock(NULL); - HANDLE_DXERROR("unlocking direct draw surface") - pLoadInfo->surface_lockedB = false; - } - } - } - - // next row - if (reversed_rowsB) - --y; - else - ++y; - - if (AW_TLE_OK != awTlLastErr) - { - db_log1("AwCreateGraphic() failed whilst copying data to direct draw surface"); - goto EXIT_WITH_ERROR; - } - } - - // create a palette for the surfaces if there is one - DWORD palcreateflags = 0; - PALETTEENTRY colour_tableA[256]; - if (pixelFormat.palettizedB) - { - if (!_parmsR.loadTextureB && !(fMyFlags & AW_TLF_TEXTURE)) - { - db_log3("AwCreateGraphic(): WARNING: setting a palette on a DD surface may have no effect"); - } - - #if 0 - if (m_bTranspMask) - { - colour_tableA[0].peRed = 0; - colour_tableA[0].peGreen = 0; - colour_tableA[0].peBlue = 0; - colour_tableA[0].peFlags = 0; - for (unsigned i=1; i<m_nPaletteSize; ++i) - { - colour_tableA[i].peRed = paletteP[i].r; - colour_tableA[i].peGreen = paletteP[i].g; - colour_tableA[i].peBlue = paletteP[i].b; - if (!(paletteP[i].r + paletteP[i].g + paletteP[i].b)) - colour_tableA[i].peRed = 1; - colour_tableA[i].peFlags = 0; - } - } - else - #endif - { - for (unsigned i=0; i<m_nPaletteSize; ++i) - { - colour_tableA[i].peRed = paletteP[i].r; - colour_tableA[i].peGreen = paletteP[i].g; - colour_tableA[i].peBlue = paletteP[i].b; - colour_tableA[i].peFlags = 0; - } - } - for (unsigned i=m_nPaletteSize; i<256; ++i) - colour_tableA[i].peFlags = 0; - switch (pixelFormat.bitsPerPixel) - { - default: - CANT_HAPPEN - case 8: - palcreateflags = DDPCAPS_8BIT | DDPCAPS_ALLOW256; - break; - case 4: - palcreateflags = DDPCAPS_4BIT; - break; - case 2: - palcreateflags = DDPCAPS_2BIT; - break; - case 1: - palcreateflags = DDPCAPS_1BIT; - break; - } - awTlLastDxErr = driverDesc.ddP->CreatePalette(palcreateflags,colour_tableA,&dd_paletteP,NULL); - HANDLE_DXERROR("creating palette for direct draw surface") - } - - {for (unsigned i=0; i<nLoadInfos; ++i) - { - LoadInfo * pLoadInfo = &arrLoadInfo[i]; - - if (!pLoadInfo->skipB) - { - // unlock the surface - if (pLoadInfo->surface_lockedB) - { - awTlLastDxErr = pLoadInfo->surfaceP->Unlock(NULL); - HANDLE_DXERROR("unlocking direct draw surface") - pLoadInfo->surface_lockedB = false; - } - - if (pixelFormat.palettizedB) - { - // set the palette on the surface - awTlLastDxErr = pLoadInfo->surfaceP->SetPalette(dd_paletteP); - HANDLE_DXERROR("setting palette on direct draw surface") - } - } - - }} - - if (pixelFormat.palettizedB) - { - db_logf5(("\tabout to release palette with ref %u",GetRefCount(dd_paletteP))); - dd_paletteP->Release(); - dd_paletteP = NULL; - } - - DWORD dwColourKey; - DDCOLORKEY invis; - // get colour for chroma keying if required - if (m_bTranspMask && (!pixelFormat.alphaB || fMyFlags & AW_TLF_CHROMAKEY)) - { - dwColourKey = GetTransparentColour(); - invis.dwColorSpaceLowValue = dwColourKey; - invis.dwColorSpaceHighValue = dwColourKey; - } - - {for (unsigned i=0; i<nLoadInfos; ++i) - { - LoadInfo * pLoadInfo = &arrLoadInfo[i]; - - if (!pLoadInfo->skipB) - { - // do the copying crap and Texture::Load() stuff - see CopyD3DTexture in d3_func.cpp - - if (_parmsR.loadTextureB) - { - // get a texture pointer - awTlLastDxErr = pLoadInfo->surfaceP->QueryInterface(GUID_D3D_TEXTURE,(LPVOID *)&pLoadInfo->textureP); - HANDLE_DXERROR("getting texture interface on direct draw surface") - db_logf5(("\t\tnow surface ref %u texture ref %u",GetRefCount(pLoadInfo->surfaceP),GetRefCount(pLoadInfo->textureP))); - - if (fMyFlags & AW_TLF_COMPRESS) // deal with Texture::Load and ALLOCONLOAD flag - { - if (pLoadInfo->prevTexP.voidP) - { - // load into the existing texture - awTlLastDxErr = pLoadInfo->prevTexP.textureP->QueryInterface(GUID_DD_SURFACE,(LPVOID *)&pLoadInfo->dst_surfaceP); - HANDLE_DXERROR("getting direct draw surface interface") - db_logf5(("\t\tnow prev texture ref %u dst surface ref %u",GetRefCount(pLoadInfo->prevTexP.textureP),GetRefCount(pLoadInfo->dst_surfaceP))); - // check that the surface desc is OK - // note that SetSurfaceDesc is *only* supported for changing the surface memory pointer - DD_SURFACE_DESC old_ddsd; - INITDXSTRUCT(old_ddsd); - awTlLastDxErr = pLoadInfo->surfaceP->GetSurfaceDesc(&old_ddsd); - HANDLE_DXERROR("getting previous surface desc") - // check width, height, RGBBitCount and memory type - if (old_ddsd.dwFlags & DDSD_ALL || (old_ddsd.dwFlags & (DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT)) == (DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT)) - { - if (old_ddsd.dwHeight == pLoadInfo->surface_height && old_ddsd.dwWidth == pLoadInfo->surface_width && (old_ddsd.ddsCaps.dwCaps & (DDSCAPS_SYSTEMMEMORY|DDSCAPS_VIDEOMEMORY|DDSCAPS_TEXTURE)) == pLoadInfo->dwCapsCaps) - { - unsigned bpp = 0; - if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED8) - bpp = 8; - else if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED4) - bpp = 4; - else if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED2) - bpp = 2; - else if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED1) - bpp = 1; - else if (old_ddsd.ddpfPixelFormat.dwFlags & DDPF_RGB) - bpp = old_ddsd.ddpfPixelFormat.dwRGBBitCount; - if (pixelFormat.bitsPerPixel != bpp) - awTlLastErr = AW_TLE_CANTRELOAD; - } - else - awTlLastErr = AW_TLE_CANTRELOAD; - } - else - awTlLastErr = AW_TLE_CANTRELOAD; - if (AW_TLE_OK != awTlLastErr) - { - db_log1("AwCreateGraphic() failed because existing surface is incompatible"); - goto EXIT_WITH_ERROR; - } - } - else - { - DD_SURFACE_DESC ddsd; - - INITDXSTRUCT(ddsd); - - awTlLastDxErr = pLoadInfo->surfaceP->GetSurfaceDesc(&ddsd); - HANDLE_DXERROR("getting direct draw surface desc") - - ddsd.ddsCaps.dwCaps &= ~DDSCAPS_SYSTEMMEMORY; - ddsd.ddsCaps.dwCaps |= DDSCAPS_ALLOCONLOAD | driverDesc.memFlag; - do - { - awTlLastDxErr = driverDesc.ddP->CreateSurface(&ddsd,&pLoadInfo->dst_surfaceP,NULL); - } - while - ( - DDERR_OUTOFVIDEOMEMORY == awTlLastDxErr - && _parmsR.callbackF - && _parmsR.callbackF(_parmsR.callbackParam) - ); - HANDLE_DXERROR("creating destination direct draw surface") - } - - // create a zero palette if required -> Texture::Load() will copy in correct palette - if (pixelFormat.palettizedB) - { - memset(colour_tableA,0,sizeof colour_tableA); - - awTlLastDxErr = driverDesc.ddP->CreatePalette(palcreateflags,colour_tableA,&dd_paletteP,NULL); - HANDLE_DXERROR("creating palette for destination direct draw surface") - awTlLastDxErr = pLoadInfo->dst_surfaceP->SetPalette(dd_paletteP); - HANDLE_DXERROR("setting palette on destination direct draw surface") - db_logf5(("\tabout to release dest palette with ref %u",GetRefCount(dd_paletteP))); - dd_paletteP->Release(); - dd_paletteP = NULL; - } - - // get a texture pointer on the destination - awTlLastDxErr = pLoadInfo->dst_surfaceP->QueryInterface(GUID_D3D_TEXTURE,(LPVOID *)&pLoadInfo->dst_textureP); - HANDLE_DXERROR("getting texture interface on destination direct draw surface") - db_logf5(("\t\tnow dst surface ref %u dst texture ref %u",GetRefCount(pLoadInfo->dst_surfaceP),GetRefCount(pLoadInfo->dst_textureP))); - - do - { - awTlLastDxErr = pLoadInfo->dst_textureP->Load(pLoadInfo->textureP); - } - while - ( - DDERR_OUTOFVIDEOMEMORY == awTlLastDxErr - && _parmsR.callbackF - && _parmsR.callbackF(_parmsR.callbackParam) - ); - HANDLE_DXERROR("loading texture into destination") - - // release src texture and surface, and set pointers to point to dst texture and surface - db_logf5(("\tabout to release internal surface with ref %u",GetRefCount(pLoadInfo->surfaceP))); - db_code1(refcnt =) - pLoadInfo->surfaceP->Release(); - db_onlyassert1(1==refcnt); - pLoadInfo->surfaceP = pLoadInfo->dst_surfaceP; - pLoadInfo->dst_surfaceP = NULL; - - db_logf5(("\tabout to release internal texture i/f with ref %u",GetRefCount(pLoadInfo->textureP))); - db_code1(refcnt =) - pLoadInfo->textureP->Release(); - db_onlyassert1(!refcnt); - pLoadInfo->textureP = pLoadInfo->dst_textureP; - pLoadInfo->dst_textureP = NULL; - } - } - - // set chroma keying if required - if (m_bTranspMask && (!pixelFormat.alphaB || fMyFlags & AW_TLF_CHROMAKEY)) - { - awTlLastDxErr = pLoadInfo->surfaceP->SetColorKey(DDCKEY_SRCBLT,&invis); - HANDLE_DXERROR("setting the colour key") - } - - if (_parmsR.loadTextureB) - { - // release the direct draw interface: - // since the textureP was obtained with a call - // to QueryInterface on the surface (increasing - // its referenc count), this wont actually release - // the surface - - db_logf5(("\tabout to release surface i/f with ref %u",GetRefCount(pLoadInfo->surfaceP))); - db_code1(refcnt =) - pLoadInfo->surfaceP->Release(); - pLoadInfo->surfaceP = NULL; - // if loading into a previous texture, refcnt may be two or more, our ref and the ref passed to us - db_onlyassert1(1==refcnt|| pLoadInfo->prevTexP.voidP); - - pLoadInfo->resultP = pLoadInfo->textureP; - } - else - { - db_assert1(pLoadInfo->surfaceP); - - DDSurface * pSurfaceReturn = NULL; - - awTlLastDxErr = pLoadInfo->surfaceP->QueryInterface(GUID_DD_SURFACE, (LPVOID *)&pSurfaceReturn); - HANDLE_DXERROR("getting the required DDSurface interface") - db_logf5(("\t\tnow surface ref %u return surface ref %u",GetRefCount(pLoadInfo->surfaceP),GetRefCount(pSurfaceReturn))); - - pLoadInfo->resultP = pSurfaceReturn; - } - } - }} - - // release the IDirectDrawSurface interfaces if returning DDSurface interfaces - if (!_parmsR.loadTextureB) - { - for (unsigned i=0; i<nLoadInfos; ++i) - { - if (!arrLoadInfo[i].skipB) - { - db_assert1(arrLoadInfo[i].surfaceP); - db_logf5(("\tabout to release internal surface i/f with ref %u",GetRefCount(arrLoadInfo[i].surfaceP))); - arrLoadInfo[i].surfaceP->Release(); - } - } - } - } - - // OK - db_log4("AwCreateGraphic() OK"); - - SurfUnion pRet = static_cast<D3DTexture *>(NULL); - - if (!_parmsR.rectA) - { - // if loading the entire graphic as one surface/texture, return pointer to that - pRet = arrLoadInfo[0].resultP; - } - else - { - // return NULL, but fill in the pTexture or pSurface members of the AwCreateGraphicRegion - for (unsigned i=0; i<nLoadInfos; ++i) - { - LoadInfo * pLoadInfo = &arrLoadInfo[i]; - - db_assert1(pLoadInfo->rectP); - - if (_parmsR.loadTextureB) - { - if (pLoadInfo->prevTexP.voidP) - { - db_assert1(pLoadInfo->prevTexP.textureP == pLoadInfo->rectP->pTexture); - db_assert1(pLoadInfo->resultP.textureP == pLoadInfo->rectP->pTexture); - db_logf5(("\tabout to release duplicate texture i/f with ref %u",GetRefCount(pLoadInfo->resultP.textureP))); - pLoadInfo->resultP.textureP->Release(); - } - else - { - pLoadInfo->rectP->pTexture = pLoadInfo->resultP.textureP; - } - db_logf5(("\tresultant texture for region with ref count %u",GetRefCount(pLoadInfo->rectP->pTexture))); - } - else - { - if (pLoadInfo->prevTexP.voidP) - { - db_assert1(pLoadInfo->prevTexP.surfaceP == pLoadInfo->rectP->pSurface); - db_assert1(pLoadInfo->resultP.surfaceP == pLoadInfo->rectP->pSurface); - db_logf5(("\tabout to release duplicate surface i/f with ref %u",GetRefCount(pLoadInfo->resultP.surfaceP))); - pLoadInfo->resultP.surfaceP->Release(); - } - else - { - pLoadInfo->rectP->pSurface = pLoadInfo->resultP.surfaceP; - } - db_logf5(("\tresultant texture for surface with ref count %u",GetRefCount(pLoadInfo->rectP->pSurface))); - } - } - } - delete[] arrLoadInfo; - - #if DB_LEVEL >= 5 - if (_parmsR.loadTextureB) - db_logf5(("AwCreateGraphic(): returning texture with ref cnt %u",GetRefCount(pRet.textureP))); - else - db_logf5(("AwCreateGraphic(): returning surface with ref cnt %u",GetRefCount(pRet.surfaceP))); - #endif - - return pRet; - } - - EXIT_WITH_ERROR: - { - - db_logf2(("AwCreateGraphic(): ERROR: %s",AwTlErrorToString())); - - if (arrLoadInfo) - { - for (unsigned i=0; i<nLoadInfos; ++i) - { - LoadInfo * pLoadInfo = &arrLoadInfo[i]; - - db_logf5(("\tref counts: dst tex %u dst surf %u int tex %u int surf %u", - GetRefCount(pLoadInfo->dst_textureP), - GetRefCount(pLoadInfo->dst_surfaceP), - GetRefCount(pLoadInfo->textureP), - GetRefCount(pLoadInfo->surfaceP))); - - if (pLoadInfo->dst_textureP) - { - pLoadInfo->dst_textureP->Release(); - } - if (pLoadInfo->textureP) - { - pLoadInfo->textureP->Release(); - } - if (pLoadInfo->dst_surfaceP) - { - pLoadInfo->dst_surfaceP->Release(); - } - if (pLoadInfo->surfaceP) - { - if (pLoadInfo->surface_lockedB) - pLoadInfo->surfaceP->Unlock(NULL); - db_code1(refcnt =) - pLoadInfo->surfaceP->Release(); - db_onlyassert1(!refcnt); - } - - if (pLoadInfo->rectP) - { - pLoadInfo->rectP->width = 0; - pLoadInfo->rectP->height = 0; - } - } - - delete[] arrLoadInfo; - } - - if (dd_paletteP) - { - db_code1(refcnt =) - dd_paletteP->Release(); - db_onlyassert1(!refcnt); - } - - return static_cast<D3DTexture *>(NULL); - } -} - -void AwBackupTexture::OnBeginRestoring(unsigned nMaxPaletteSize) -{ - if (nMaxPaletteSize && (nMaxPaletteSize < m_nPaletteSize || !m_nPaletteSize)) - { - awTlLastErr = AW_TLE_CANTPALETTIZE; - db_logf3(("AwCreateGraphic(): [restoring] ERROR: Palette size is %u, require %u",m_nPaletteSize,nMaxPaletteSize)); - } -} - -bool AwBackupTexture::AreRowsReversed() -{ - return false; -} - -void AwBackupTexture::ConvertRow(AwTl::PtrUnion pDest, unsigned nDestWidth, AwTl::PtrUnionConst pSrc, unsigned nSrcOffset, unsigned nSrcWidth, AwTl::Colour * pPalette db_code1(DB_COMMA unsigned nPaletteSize)) -{ - using namespace AwTl; - - if (pPalette) - { - if (pixelFormat.palettizedB) - { - GenericConvertRow<Colour::ConvNull,BYTE>::Do(pDest,nDestWidth,pSrc.byteP+nSrcOffset,nSrcWidth); - } - else - { - if (m_bTranspMask) - GenericConvertRow<Colour::ConvTransp,BYTE>::Do(pDest,nDestWidth,pSrc.byteP+nSrcOffset,nSrcWidth,pPalette db_code1(DB_COMMA nPaletteSize)); - else - GenericConvertRow<Colour::ConvNonTransp,BYTE>::Do(pDest,nDestWidth,pSrc.byteP+nSrcOffset,nSrcWidth,pPalette db_code1(DB_COMMA nPaletteSize)); - } - } - else - { - if (m_bTranspMask) - GenericConvertRow<Colour::ConvTransp,Colour>::Do(pDest,nDestWidth,pSrc.colourP+nSrcOffset,nSrcWidth); - else - GenericConvertRow<Colour::ConvNonTransp,Colour>::Do(pDest,nDestWidth,pSrc.colourP+nSrcOffset,nSrcWidth); - } -} - -void AwBackupTexture::OnFinishRestoring(bool) -{ -} - -namespace AwTl { - - Colour * TypicalBackupTexture::GetPalette() - { - return m_pPalette; - } - - PtrUnion TypicalBackupTexture::GetRowPtr(unsigned nRow) - { - return m_ppPixMap[nRow]; - } - - void TypicalBackupTexture::LoadNextRow(PtrUnion) - { - // already loaded - } - - unsigned TypicalBackupTexture::GetNumColours() - { - return m_nPaletteSize; - } - - unsigned TypicalBackupTexture::GetMinPaletteSize() - { - return m_nPaletteSize; - } - - - SurfUnion TexFileLoader::Load(MediaMedium * pMedium, CreateTextureParms const & rParams) - { - m_fFlags = rParams.flags; - - awTlLastErr = AW_TLE_OK; - - LoadHeaderInfo(pMedium); - - CHECK_MEDIA_ERRORS("loading file headers") - ON_ERROR_RETURN_NULL("loading file headers") - - ChoosePixelFormat(rParams); - - if (!pixelFormat.validB) - db_log3("AwCreateGraphic(): ERROR: pixel format not valid"); - if (!driverDesc.ddP || !driverDesc.validB && rParams.loadTextureB) - db_log3("AwCreateGraphic(): ERROR: driver description not valid"); - - awTlLastErr = pixelFormat.validB && driverDesc.ddP && (driverDesc.validB || !rParams.loadTextureB) ? AW_TLE_OK : AW_TLE_NOINIT; - - ON_ERROR_RETURN_NULL("initializing load") - - AllocateBuffers(rParams.backupHP ? true : false, pixelFormat.palettizedB ? 1<<pixelFormat.bitsPerPixel : 0); - - CHECK_MEDIA_ERRORS("allocating buffers") - ON_ERROR_RETURN_NULL("allocating buffers") - - db_logf4(("\tThe image in the file is %ux%u with %u %spalette",m_nWidth,m_nHeight,m_nPaletteSize ? m_nPaletteSize : 0,m_nPaletteSize ? "colour " : "")); - - SurfUnion pTex = CreateTexture(rParams); - - bool bOK = AW_TLE_OK == awTlLastErr; - - CHECK_MEDIA_ERRORS("loading image data") - - if (bOK && awTlLastErr != AW_TLE_OK) - { - // an error occurred which was not detected in CreateTexture() - if (pTex.voidP) - { - if (rParams.loadTextureB) - pTex.textureP->Release(); - else - pTex.surfaceP->Release(); - pTex.voidP = NULL; - } - else - { - db_assert1(rParams.rectA); - - for (unsigned i=0; i<rParams.numRects; ++i) - { - AwCreateGraphicRegion * pRect = &rParams.rectA[i]; - - if (!rParams.prevTexB) - { - // release what was created - if (rParams.loadTextureB) - pRect->pTexture->Release(); - else - pRect->pSurface->Release(); - } - pRect->width = 0; - pRect->height = 0; - } - } - db_logf1(("AwCreateGraphic(): ERROR: %s",AwTlErrorToString())); - bOK = false; - } - - OnFinishLoading(bOK); - - if (bOK && rParams.backupHP) - { - *rParams.backupHP = CreateBackupTexture(); - } - - return pTex; - } - - void TexFileLoader::OnFinishLoading(bool) - { - } - - - TypicalTexFileLoader::~TypicalTexFileLoader() - { - if (m_pPalette) - { - delete[] m_pPalette; - - if (m_pRowBuf) delete[] m_pRowBuf.byteP; - if (m_ppPixMap) - { - delete[] m_ppPixMap->byteP; - delete[] m_ppPixMap; - } - } - else - { - if (m_pRowBuf) delete[] m_pRowBuf.colourP; - if (m_ppPixMap) - { - delete[] m_ppPixMap->colourP; - delete[] m_ppPixMap; - } - } - } - - unsigned TypicalTexFileLoader::GetNumColours() - { - return m_nPaletteSize; - } - - unsigned TypicalTexFileLoader::GetMinPaletteSize() - { - return m_nPaletteSize; - } - - void TypicalTexFileLoader::AllocateBuffers(bool bWantBackup, unsigned /*nMaxPaletteSize*/) - { - if (m_nPaletteSize) - { - m_pPalette = new Colour [ m_nPaletteSize ]; - } - - if (bWantBackup) - { - m_ppPixMap = new PtrUnion [m_nHeight]; - if (m_nPaletteSize) - { - m_ppPixMap->byteP = new BYTE [m_nHeight*m_nWidth]; - BYTE * pRow = m_ppPixMap->byteP; - for (unsigned y=1;y<m_nHeight;++y) - { - pRow += m_nWidth; - m_ppPixMap[y].byteP = pRow; - } - } - else - { - m_ppPixMap->colourP = new Colour [m_nHeight*m_nWidth]; - Colour * pRow = m_ppPixMap->colourP; - for (unsigned y=1;y<m_nHeight;++y) - { - pRow += m_nWidth; - m_ppPixMap[y].colourP = pRow; - } - } - } - else - { - if (m_nPaletteSize) - m_pRowBuf.byteP = new BYTE [m_nWidth]; - else - m_pRowBuf.colourP = new Colour [m_nWidth]; - } - } - - PtrUnion TypicalTexFileLoader::GetRowPtr(unsigned nRow) - { - if (m_ppPixMap) - { - return m_ppPixMap[nRow]; - } - else - { - return m_pRowBuf; - } - } - - AwBackupTexture * TypicalTexFileLoader::CreateBackupTexture() - { - AwBackupTexture * pBackup = new TypicalBackupTexture(*this,m_ppPixMap,m_pPalette); - m_ppPixMap = NULL; - m_pPalette = NULL; - return pBackup; - } - - /****************************************************************************/ - /* For determining which loader should be used for the file format detected */ - /****************************************************************************/ - - static - class MagicFileIdTree - { - public: - MagicFileIdTree() - : m_pfnCreate(NULL) - #ifdef _MSC_VER - , hack(0) - #endif - { - for (unsigned i=0; i<256; ++i) - m_arrNextLayer[i]=NULL; - } - - ~MagicFileIdTree() - { - for (unsigned i=0; i<256; ++i) - if (m_arrNextLayer[i]) delete m_arrNextLayer[i]; - } - - MagicFileIdTree * m_arrNextLayer [256]; - - TexFileLoader * (* m_pfnCreate) (); - - #ifdef _MSC_VER - unsigned hack; - #endif - } - * g_pMagicFileIdTree = NULL; - - void RegisterLoader(char const * pszMagic, TexFileLoader * (* pfnCreate) () ) - { - static MagicFileIdTree mfidt; - -#ifdef _MSC_VER - // Touch the loaders. - { - mfidt.hack += reinterpret_cast<unsigned>(&rlcAwBmpLoader_187); - - mfidt.hack += reinterpret_cast<unsigned>(&rlcAwIffLoader_428); - mfidt.hack += reinterpret_cast<unsigned>(&rlcAwIffLoader_429); - mfidt.hack += reinterpret_cast<unsigned>(&rlcAwIffLoader_430); - - mfidt.hack += reinterpret_cast<unsigned>(&rlcAwPpmLoader_229); - mfidt.hack += reinterpret_cast<unsigned>(&rlcAwPgmLoader_230); - mfidt.hack += reinterpret_cast<unsigned>(&rlcAwPbmLoader_231); - - mfidt.hack += reinterpret_cast<unsigned>(&rccIlbmBmhdChunk_4); - mfidt.hack += reinterpret_cast<unsigned>(&rccIlbmCmapChunk_5); - mfidt.hack += reinterpret_cast<unsigned>(&rccIlbmBodyChunk_6); - mfidt.hack += reinterpret_cast<unsigned>(&rccIlbmGrabChunk_7); - } -#endif - g_pMagicFileIdTree = &mfidt; - - MagicFileIdTree * pLayer = g_pMagicFileIdTree; - - while (*pszMagic) - { - BYTE c = static_cast<BYTE>(*pszMagic++); - - if (!pLayer->m_arrNextLayer[c]) - pLayer->m_arrNextLayer[c] = new MagicFileIdTree; - - pLayer = pLayer->m_arrNextLayer[c]; - } - - db_assert1(!pLayer->m_pfnCreate); - - pLayer->m_pfnCreate = pfnCreate; - } - - static - TexFileLoader * CreateLoaderObject(MediaMedium * pMedium) - { - TexFileLoader * (* pfnBest) () = NULL; - - signed nMoveBack = 0; - - BYTE c; - - MagicFileIdTree * pLayer = g_pMagicFileIdTree; - - while (pLayer) - { - if (pLayer->m_pfnCreate) - pfnBest = pLayer->m_pfnCreate; - - MediaRead(pMedium,&c); - - -- nMoveBack; - - pLayer = pLayer->m_arrNextLayer[c]; - } - - pMedium->MovePos(nMoveBack); - - if (pfnBest) - return pfnBest(); - else - return NULL; - } - - /**********************************/ - /* These are the loader functions */ - /**********************************/ - - static inline SurfUnion DoLoadTexture(MediaMedium * pMedium, CreateTextureParms const & rParams) - { - TexFileLoader * pLoader = CreateLoaderObject(pMedium); - - if (!pLoader) - { - awTlLastErr = AW_TLE_BADFILEFORMAT; - db_log1("AwCreateGraphic(): ERROR: file format not recognized"); - return static_cast<D3DTexture *>(NULL); - } - else - { - SurfUnion pTex = pLoader->Load(pMedium,rParams); - pLoader->Release(); - return pTex; - } - } - - static inline SurfUnion LoadTexture(MediaMedium * pMedium, CreateTextureParms const & _parmsR) - { - if (_parmsR.bytesReadP||_parmsR.maxReadBytes!=UINT_MAX) - { - MediaSection * pMedSect = new MediaSection; - pMedSect->Open(pMedium,_parmsR.maxReadBytes); - SurfUnion pTex = DoLoadTexture(pMedSect,_parmsR); - pMedSect->Close(); - if (_parmsR.bytesReadP) *_parmsR.bytesReadP = pMedSect->GetUsedSize(); - delete pMedSect; - return pTex; - } - else - { - return DoLoadTexture(pMedium,_parmsR); - } - } - - SurfUnion CreateTextureParms::DoCreate() const - { - if (INVALID_HANDLE_VALUE!=fileH) - { - MediaWinFileMedium * pMedium = new MediaWinFileMedium; - pMedium->Attach(fileH); - SurfUnion pTex = LoadTexture(pMedium,*this); - pMedium->Detach(); - pMedium->Release(); - return pTex; - } - else if (dataP) - { - MediaMemoryReadMedium * pMedium = new MediaMemoryReadMedium; - pMedium->Open(dataP); - SurfUnion pTex = LoadTexture(pMedium,*this); - pMedium->Close(); - pMedium->Release(); - return pTex; - } - else - { - db_assert1(restoreH); - return restoreH->Restore(*this); - } - } - - #if DB_LEVEL >= 4 - static void LogPrimCaps(LPD3DPRIMCAPS _pcP, bool _triB) - { - #define DEVCAP(mask,can_or_does,explanation) \ - db_logf4(("\t\t" can_or_does "%s " explanation, _pcP->MEMBER & (mask) ? "" : "not")); - - #define MEMBER dwMiscCaps - DEVCAP(D3DPMISCCAPS_CONFORMANT,"Does ","conform to OpenGL standard") - if (_triB) - { - DEVCAP(D3DPMISCCAPS_CULLCCW,"Does ","support counterclockwise culling through the D3DRENDERSTATE_CULLMODE state") - DEVCAP(D3DPMISCCAPS_CULLCW,"Does ","support clockwise triangle culling through the D3DRENDERSTATE_CULLMODE state") - db_logf4(("\t\tDoes %s perform triangle culling", _pcP->dwMiscCaps & (D3DPMISCCAPS_CULLNONE) ? "not" : "")); - } - else - { - DEVCAP(D3DPMISCCAPS_LINEPATTERNREP,"Can","handle values other than 1 in the wRepeatFactor member of the D3DLINEPATTERN structure") - } - DEVCAP(D3DPMISCCAPS_MASKPLANES,"Can","perform a bitmask of color planes") - DEVCAP(D3DPMISCCAPS_MASKZ,"Can","enable and disable modification of the z-buffer on pixel operations") - #undef MEMBER - #define MEMBER dwRasterCaps - DEVCAP(D3DPRASTERCAPS_ANISOTROPY,"Does ","support anisotropic filtering") - DEVCAP(D3DPRASTERCAPS_ANTIALIASEDGES,"Can","antialias lines forming the convex outline of objects") - DEVCAP(D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT,"Does","support antialiasing that is dependent on the sort order of the polygons") - DEVCAP(D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT,"Does","support antialiasing that is not dependent on the sort order of the polygons") - DEVCAP(D3DPRASTERCAPS_DITHER,"Can","dither to improve color resolution") - DEVCAP(D3DPRASTERCAPS_FOGRANGE,"Does ","support range-based fog") - DEVCAP(D3DPRASTERCAPS_FOGTABLE,"Does ","calculate the fog value by referring to a lookup table containing fog values that are indexed to the depth of a given pixel") - DEVCAP(D3DPRASTERCAPS_FOGVERTEX,"Does ","calculate the fog value during the lighting operation") - DEVCAP(D3DPRASTERCAPS_MIPMAPLODBIAS,"Does ","support level-of-detail (LOD) bias adjustments") - DEVCAP(D3DPRASTERCAPS_PAT,"Can","perform patterned drawing for the primitive being queried") - DEVCAP(D3DPRASTERCAPS_ROP2,"Can","support raster operations other than R2_COPYPEN") - DEVCAP(D3DPRASTERCAPS_STIPPLE,"Can","stipple polygons to simulate translucency") - DEVCAP(D3DPRASTERCAPS_SUBPIXEL,"Does ","perform subpixel placement of z, color, and texture data, rather than working with the nearest integer pixel coordinate") - DEVCAP(D3DPRASTERCAPS_SUBPIXELX,"Is ","subpixel accurate along the x-axis only and is clamped to an integer y-axis scan line") - DEVCAP(D3DPRASTERCAPS_XOR,"Can","support XOR operations") - DEVCAP(D3DPRASTERCAPS_ZBIAS,"Does ","support z-bias values") - DEVCAP(D3DPRASTERCAPS_ZBUFFERLESSHSR,"Can","perform hidden-surface removal without requiring the application to sort polygons, and without requiring the allocation of a z-buffer") - DEVCAP(D3DPRASTERCAPS_ZTEST,"Can","perform z-test operations") - #undef MEMBER - #define MEMBER dwZCmpCaps - DEVCAP(D3DPCMPCAPS_ALWAYS,"Can","always pass the z test") - DEVCAP(D3DPCMPCAPS_EQUAL,"Can","pass the z test if the new z equals the current z") - DEVCAP(D3DPCMPCAPS_GREATER,"Can","pass the z test if the new z is greater than the current z") - DEVCAP(D3DPCMPCAPS_GREATEREQUAL,"Can","pass the z test if the new z is greater than or equal to the current z") - DEVCAP(D3DPCMPCAPS_LESS,"Can","pass the z test if the new z is less than the current z") - DEVCAP(D3DPCMPCAPS_LESSEQUAL,"Can","pass the z test if the new z is less than or equal to the current z") - DEVCAP(D3DPCMPCAPS_NEVER,"Can","always fail the z test") - DEVCAP(D3DPCMPCAPS_NOTEQUAL,"Can","pass the z test if the new z does not equal the current z") - #undef MEMBER - #define MEMBER dwSrcBlendCaps - DEVCAP(D3DPBLENDCAPS_BOTHINVSRCALPHA,"Can","source blend with source blend factor of (1-As, 1-As, 1-As, 1-As) and destination blend factor of (As, As, As, As); the destination blend selection is overridden") - DEVCAP(D3DPBLENDCAPS_BOTHSRCALPHA,"Can","source blend with source blend factor of (As, As, As, As) and destination blend factor of (1-As, 1-As, 1-As, 1-As); the destination blend selection is overridden") - DEVCAP(D3DPBLENDCAPS_DESTALPHA,"Can","source blend with blend factor of (Ad, Ad, Ad, Ad)") - DEVCAP(D3DPBLENDCAPS_DESTCOLOR,"Can","source blend with blend factor of (Rd, Gd, Bd, Ad)") - DEVCAP(D3DPBLENDCAPS_INVDESTALPHA,"Can","source blend with blend factor of (1-Ad, 1-Ad, 1-Ad, 1-Ad)") - DEVCAP(D3DPBLENDCAPS_INVDESTCOLOR,"Can","source blend with blend factor of (1-Rd, 1-Gd, 1-Bd, 1-Ad)") - DEVCAP(D3DPBLENDCAPS_INVSRCALPHA,"Can","source blend with blend factor of (1-As, 1-As, 1-As, 1-As)") - DEVCAP(D3DPBLENDCAPS_INVSRCCOLOR,"Can","source blend with blend factor of (1-Rd, 1-Gd, 1-Bd, 1-Ad)") - DEVCAP(D3DPBLENDCAPS_ONE,"Can","source blend with blend factor of (1, 1, 1, 1)") - DEVCAP(D3DPBLENDCAPS_SRCALPHA,"Can","source blend with blend factor of (As, As, As, As)") - DEVCAP(D3DPBLENDCAPS_SRCALPHASAT,"Can","source blend with blend factor of (f, f, f, 1); f = min(As, 1-Ad).") - DEVCAP(D3DPBLENDCAPS_SRCCOLOR,"Can","source blend with blend factor of (Rs, Gs, Bs, As)") - DEVCAP(D3DPBLENDCAPS_ZERO,"Can","source blend with blend factor of (0, 0, 0, 0)") - #undef MEMBER - #define MEMBER dwDestBlendCaps - DEVCAP(D3DPBLENDCAPS_BOTHINVSRCALPHA,"Can","destination blend with source blend factor of (1-As, 1-As, 1-As, 1-As) and destination blend factor of (As, As, As, As); the destination blend selection is overridden") - DEVCAP(D3DPBLENDCAPS_BOTHSRCALPHA,"Can","destination blend with source blend factor of (As, As, As, As) and destination blend factor of (1-As, 1-As, 1-As, 1-As); the destination blend selection is overridden") - DEVCAP(D3DPBLENDCAPS_DESTALPHA,"Can","destination blend with blend factor of (Ad, Ad, Ad, Ad)") - DEVCAP(D3DPBLENDCAPS_DESTCOLOR,"Can","destination blend with blend factor of (Rd, Gd, Bd, Ad)") - DEVCAP(D3DPBLENDCAPS_INVDESTALPHA,"Can","destination blend with blend factor of (1-Ad, 1-Ad, 1-Ad, 1-Ad)") - DEVCAP(D3DPBLENDCAPS_INVDESTCOLOR,"Can","destination blend with blend factor of (1-Rd, 1-Gd, 1-Bd, 1-Ad)") - DEVCAP(D3DPBLENDCAPS_INVSRCALPHA,"Can","destination blend with blend factor of (1-As, 1-As, 1-As, 1-As)") - DEVCAP(D3DPBLENDCAPS_INVSRCCOLOR,"Can","destination blend with blend factor of (1-Rd, 1-Gd, 1-Bd, 1-Ad)") - DEVCAP(D3DPBLENDCAPS_ONE,"Can","destination blend with blend factor of (1, 1, 1, 1)") - DEVCAP(D3DPBLENDCAPS_SRCALPHA,"Can","destination blend with blend factor of (As, As, As, As)") - DEVCAP(D3DPBLENDCAPS_SRCALPHASAT,"Can","destination blend with blend factor of (f, f, f, 1); f = min(As, 1-Ad)") - DEVCAP(D3DPBLENDCAPS_SRCCOLOR,"Can","destination blend with blend factor of (Rs, Gs, Bs, As)") - DEVCAP(D3DPBLENDCAPS_ZERO,"Can","destination blend with blend factor of (0, 0, 0, 0)") - #undef MEMBER - #define MEMBER dwAlphaCmpCaps - DEVCAP(D3DPCMPCAPS_ALWAYS,"Can","always pass the alpha test") - DEVCAP(D3DPCMPCAPS_EQUAL,"Can","pass the alpha test if the new alpha equals the current alpha") - DEVCAP(D3DPCMPCAPS_GREATER,"Can","pass the alpha test if the new alpha is greater than the current alpha") - DEVCAP(D3DPCMPCAPS_GREATEREQUAL,"Can","pass the alpha test if the new alpha is greater than or equal to the current alpha") - DEVCAP(D3DPCMPCAPS_LESS,"Can","pass the alpha test if the new alpha is less than the current alpha") - DEVCAP(D3DPCMPCAPS_LESSEQUAL,"Can","pass the alpha test if the new alpha is less than or equal to the current alpha") - DEVCAP(D3DPCMPCAPS_NEVER,"Can","always fail the alpha test") - DEVCAP(D3DPCMPCAPS_NOTEQUAL,"Can","pass the alpha test if the new alpha does not equal the current alpha") - #undef MEMBER - #define MEMBER dwShadeCaps - DEVCAP(D3DPSHADECAPS_ALPHAFLATBLEND,"Can","support an alpha component for flat blended transparency") - DEVCAP(D3DPSHADECAPS_ALPHAFLATSTIPPLED,"Can","support an alpha component for flat stippled transparency") - DEVCAP(D3DPSHADECAPS_ALPHAGOURAUDBLEND,"Can","support an alpha component for Gouraud blended transparency") - DEVCAP(D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED,"Can","support an alpha component for Gouraud stippled transparency") - DEVCAP(D3DPSHADECAPS_ALPHAPHONGBLEND,"Can","support an alpha component for Phong blended transparency") - DEVCAP(D3DPSHADECAPS_ALPHAPHONGSTIPPLED,"Can","support an alpha component for Phong stippled transparency") - DEVCAP(D3DPSHADECAPS_COLORFLATMONO,"Can","support colored flat shading in the D3DCOLOR_MONO color model") - DEVCAP(D3DPSHADECAPS_COLORFLATRGB,"Can","support colored flat shading in the D3DCOLOR_RGB color model") - DEVCAP(D3DPSHADECAPS_COLORGOURAUDMONO,"Can","support colored flat shading in the D3DCOLOR_MONO color model") - DEVCAP(D3DPSHADECAPS_COLORGOURAUDRGB,"Can","support colored Gouraud shading in the D3DCOLOR_RGB color model") - DEVCAP(D3DPSHADECAPS_COLORPHONGMONO,"Can","support colored Phong shading in the D3DCOLOR_MONO color model") - DEVCAP(D3DPSHADECAPS_COLORPHONGRGB,"Can","support colored Phong shading in the D3DCOLOR_RGB color model") - DEVCAP(D3DPSHADECAPS_FOGFLAT,"Can","support fog in the flat shading model") - DEVCAP(D3DPSHADECAPS_FOGGOURAUD,"Can","support fog in the Gouraud shading model") - DEVCAP(D3DPSHADECAPS_FOGPHONG,"Can","support fog in the Phong shading model") - DEVCAP(D3DPSHADECAPS_SPECULARFLATMONO,"Can","support specular highlights in flat shading in the D3DCOLOR_MONO color model") - DEVCAP(D3DPSHADECAPS_SPECULARFLATRGB,"Can","support specular highlights in flat shading in the D3DCOLOR_RGB color model") - DEVCAP(D3DPSHADECAPS_SPECULARGOURAUDMONO,"Can","support specular highlights in Gouraud shading in the D3DCOLOR_MONO color model") - DEVCAP(D3DPSHADECAPS_SPECULARGOURAUDRGB,"Can","support specular highlights in Gouraud shading in the D3DCOLOR_RGB color model") - DEVCAP(D3DPSHADECAPS_SPECULARPHONGMONO,"Can","support specular highlights in Phong shading in the D3DCOLOR_MONO color model") - DEVCAP(D3DPSHADECAPS_SPECULARPHONGRGB,"Can","support specular highlights in Phong shading in the D3DCOLOR_RGB color model") - #undef MEMBER - #define MEMBER dwTextureCaps - DEVCAP(D3DPTEXTURECAPS_ALPHA,"Does ","support RGBA textures in the D3DTEX_DECAL and D3DTEX_MODULATE texture filtering modes") - DEVCAP(D3DPTEXTURECAPS_BORDER,"Does ","support texture mapping along borders") - DEVCAP(D3DPTEXTURECAPS_PERSPECTIVE,"Does ","support perspective correction") - DEVCAP(D3DPTEXTURECAPS_POW2,"Does ","require all nonmipmapped textures to have widths and heights specified as powers of two") - DEVCAP(D3DPTEXTURECAPS_SQUAREONLY,"Does ","require all textures to be square") - DEVCAP(D3DPTEXTURECAPS_TRANSPARENCY,"Does ","support texture transparency") - #undef MEMBER - #define MEMBER dwTextureFilterCaps - DEVCAP(D3DPTFILTERCAPS_LINEAR,"Can","use a weighted average of a 2x2 area of texels surrounding the desired pixel") - DEVCAP(D3DPTFILTERCAPS_LINEARMIPLINEAR,"Can","use a weighted average of a 2x2 area of texels, and also interpolate between mipmaps") - DEVCAP(D3DPTFILTERCAPS_LINEARMIPNEAREST,"Can","use a weighted average of a 2x2 area of texels, and also use a mipmap") - DEVCAP(D3DPTFILTERCAPS_MIPLINEAR,"Can","choose two mipmaps whose texels most closely match the size of the pixel to be textured, and interpolate between them") - DEVCAP(D3DPTFILTERCAPS_MIPNEAREST,"Can","use an appropriate mipmap for texel selection") - DEVCAP(D3DPTFILTERCAPS_NEAREST,"Can","use the texel with coordinates nearest to the desired pixel value is used") - #undef MEMBER - #define MEMBER dwTextureBlendCaps - DEVCAP(D3DPTBLENDCAPS_ADD,"Can","use the additive texture-blending mode") - DEVCAP(D3DPTBLENDCAPS_COPY,"Can","use copy mode texture-blending") - DEVCAP(D3DPTBLENDCAPS_DECAL,"Can","use decal texture-blending mode") - DEVCAP(D3DPTBLENDCAPS_DECALALPHA,"Can","use decal-alpha texture-blending mode") - DEVCAP(D3DPTBLENDCAPS_DECALMASK,"Can","use decal-mask texture-blending mode") - DEVCAP(D3DPTBLENDCAPS_MODULATE,"Can","use modulate texture-blending mode") - DEVCAP(D3DPTBLENDCAPS_MODULATEALPHA,"Can","use modulate-alpha texture-blending mode") - DEVCAP(D3DPTBLENDCAPS_MODULATEMASK,"Can","use modulate-mask texture-blending mode") - #undef MEMBER - #define MEMBER dwTextureAddressCaps - DEVCAP(D3DPTADDRESSCAPS_BORDER,"Does ","support setting coordinates outside the range [0.0, 1.0] to the border color") - DEVCAP(D3DPTADDRESSCAPS_CLAMP,"Can","clamp textures to addresses") - DEVCAP(D3DPTADDRESSCAPS_INDEPENDENTUV,"Can","separate the texture-addressing modes of the U and V coordinates of the texture") - DEVCAP(D3DPTADDRESSCAPS_MIRROR,"Can","mirror textures to addresses") - DEVCAP(D3DPTADDRESSCAPS_WRAP,"Can","wrap textures to addresses") - #undef MEMBER - #undef DEVCAP - db_logf4(("\t\tMaximum size of the supported stipple is %u x %u",_pcP->dwStippleWidth,_pcP->dwStippleHeight)); - } - static void LogCaps(LPD3DDEVICEDESC _descP) - { - if (_descP->dwFlags & D3DDD_BCLIPPING) - { - db_logf4(("\tCan%s perform 3D clipping",_descP->bClipping ? "" : "not")); - } - else db_log4("\tHas unknown 3D clipping capability"); - - if (_descP->dwFlags & D3DDD_COLORMODEL) - { - db_logf4(("\tCan%s use mono (ramp) colour model",_descP->dcmColorModel & D3DCOLOR_MONO ? "" : "not")); - db_logf4(("\tCan%s use full RGB colour model",_descP->dcmColorModel & D3DCOLOR_RGB ? "" : "not")); - } - else db_log4("\tHas unknown colour model"); - - if (_descP->dwFlags & D3DDD_DEVCAPS) - { - #define DEVCAP(mask,can_or_does,explanation) \ - db_logf4(("\t" can_or_does "%s " explanation,_descP->dwDevCaps & (mask) ? "" : "not")); - - DEVCAP(D3DDEVCAPS_CANRENDERAFTERFLIP,"Can","queue rendering commands after a page flip") - DEVCAP(D3DDEVCAPS_DRAWPRIMTLVERTEX,"Does ","export a DrawPrimitive-aware HAL") - DEVCAP(D3DDEVCAPS_EXECUTESYSTEMMEMORY,"Can","use execute buffers from system memory") - DEVCAP(D3DDEVCAPS_EXECUTEVIDEOMEMORY,"Can","use execute buffer from video memory") - DEVCAP(D3DDEVCAPS_FLOATTLVERTEX,"Does ","accept floating point for post-transform vertex data") - DEVCAP(D3DDEVCAPS_SORTDECREASINGZ,"Does ","need Z data sorted for decreasing depth") - DEVCAP(D3DDEVCAPS_SORTEXACT,"Does ","need data sorted exactly") - DEVCAP(D3DDEVCAPS_SORTINCREASINGZ,"Does ","need data sorted for increasing depth") - DEVCAP(D3DDEVCAPS_TEXTURENONLOCALVIDMEM,"Can","retrieve textures from nonlocal video (AGP) memory") - DEVCAP(D3DDEVCAPS_TEXTURESYSTEMMEMORY,"Can","retrieve textures from system memory") - DEVCAP(D3DDEVCAPS_TEXTUREVIDEOMEMORY,"Can","retrieve textures from device memory") - DEVCAP(D3DDEVCAPS_TLVERTEXSYSTEMMEMORY,"Can","use buffers from system memory for transformed and lit vertices") - DEVCAP(D3DDEVCAPS_TLVERTEXVIDEOMEMORY,"Can","use buffers from video memory for transformed and lit vertices") - - #undef DEVCAP - } - else db_log4("\tHas unknown device capabilities"); - - if (_descP->dwFlags & D3DDD_DEVICERENDERBITDEPTH) - { - #define DEVCAP(mask,explanation) \ - db_logf4(("\tCan%s render to "explanation" surface",_descP->dwDeviceRenderBitDepth & (mask) ? "" : "not")); - - DEVCAP(DDBD_8,"an 8-bit") - DEVCAP(DDBD_16,"a 16-bit") - DEVCAP(DDBD_24,"a 24-bit") - DEVCAP(DDBD_32,"a 32-bit") - - #undef DEVCAP - } - else db_log4("\tHas unknown rendering target bitdepth requirements"); - - if (_descP->dwFlags & D3DDD_DEVICEZBUFFERBITDEPTH) - { - #define DEVCAP(mask,explanation) \ - db_logf4(("\tCan%s use "explanation" Z-buffer",_descP->dwDeviceZBufferBitDepth & (mask) ? "" : "not")); - - DEVCAP(DDBD_8,"an 8-bit") - DEVCAP(DDBD_16,"a 16-bit") - DEVCAP(DDBD_24,"a 24-bit") - DEVCAP(DDBD_32,"a 32-bit") - - #undef DEVCAP - } - else db_log4("\tHas unknown Z-buffer bitdepth requirements"); - - if (_descP->dwFlags & D3DDD_TRANSFORMCAPS) - { - db_log4("\tTransform capabilities are known"); - } - else db_log4("\tHas unknown transform capabilities"); - - if (_descP->dwFlags & D3DDD_LIGHTINGCAPS) - { - db_log4("\tLighting capabilities are known"); - } - else db_log4("\tHas unknown lighting capabilities"); - - if (_descP->dwFlags & D3DDD_LINECAPS) - { - db_log4("\tLine drawing capabilities follow"); - LogPrimCaps(&_descP->dpcLineCaps,false); - } - else db_log4("\tHas unknown line drawing capabilities"); - - if (_descP->dwFlags & D3DDD_TRICAPS) - { - db_log4("\tTriangle rendering capabilities follow"); - LogPrimCaps(&_descP->dpcTriCaps,true); - } - else db_log4("\tHas unknown triangle rendering capabilities"); - - if (_descP->dwFlags & D3DDD_MAXBUFFERSIZE) - { - unsigned max_exb = _descP->dwMaxBufferSize; - if (!max_exb) max_exb = UINT_MAX; - db_logf4(("\tMaximum execute buffer size is %u",max_exb)); - } - else db_log4("\tHas unknown maximum execute buffer size"); - - if (_descP->dwFlags & D3DDD_MAXVERTEXCOUNT) - { - db_logf4(("\tMaximum vertex count is %u",_descP->dwMaxVertexCount)); - } - else db_log4("\tHas unknown maximum vertex count"); - - unsigned max_tw = _descP->dwMaxTextureWidth; - unsigned max_th = _descP->dwMaxTextureHeight; - unsigned max_sw = _descP->dwMaxStippleWidth; - unsigned max_sh = _descP->dwMaxStippleHeight; - if (!max_tw) max_tw = UINT_MAX; - if (!max_th) max_th = UINT_MAX; - if (!max_sw) max_sw = UINT_MAX; - if (!max_sh) max_sh = UINT_MAX; - - db_logf4(("\tMinimum texture size is %u x %u",_descP->dwMinTextureWidth,_descP->dwMinTextureHeight)); - db_logf4(("\tMaximum texture size is %u x %u",max_tw,max_th)); - db_logf4(("\tMinimum stipple size is %u x %u",_descP->dwMinStippleWidth,_descP->dwMinStippleHeight)); - db_logf4(("\tMaximum stipple size is %u x %u",max_sw,max_sh)); - } - #endif - - // Parse the format string and get the parameters - - static bool ParseParams(CreateTextureParms * pParams, char const * _argFormatS, va_list ap) - { - bool bad_parmsB = false; - db_code2(unsigned ch_off = 0;) - db_code2(char ch = 0;) - - while (*_argFormatS && !bad_parmsB) - { - db_code2(++ch_off;) - db_code2(ch = *_argFormatS;) - switch (*_argFormatS++) - { - case 's': - if (pParams->fileNameS || INVALID_HANDLE_VALUE!=pParams->fileH || pParams->dataP || pParams->restoreH) - bad_parmsB = true; - else - { - pParams->fileNameS = va_arg(ap,LPCTSTR); - db_logf4(("\tFilename = \"%s\"",pParams->fileNameS)); - } - break; - case 'h': - if (pParams->fileNameS || INVALID_HANDLE_VALUE!=pParams->fileH || pParams->dataP || pParams->restoreH) - bad_parmsB = true; - else - { - pParams->fileH = va_arg(ap,HANDLE); - db_logf4(("\tFile HANDLE = 0x%08x",pParams->fileH)); - } - break; - case 'p': - if (pParams->fileNameS || INVALID_HANDLE_VALUE!=pParams->fileH || pParams->dataP || pParams->restoreH) - bad_parmsB = true; - else - { - pParams->dataP = va_arg(ap,void const *); - db_logf4(("\tData Pointer = %p",pParams->dataP)); - } - break; - case 'r': - if (pParams->fileNameS || INVALID_HANDLE_VALUE!=pParams->fileH || pParams->dataP || pParams->restoreH || UINT_MAX!=pParams->maxReadBytes || pParams->bytesReadP || pParams->backupHP) - bad_parmsB = true; - else - { - pParams->restoreH = va_arg(ap,AW_BACKUPTEXTUREHANDLE); - db_logf4(("\tRestore Handle = 0x%08x",pParams->restoreH)); - } - break; - case 'x': - if (UINT_MAX!=pParams->maxReadBytes || pParams->restoreH) - bad_parmsB = true; - else - { - pParams->maxReadBytes = va_arg(ap,unsigned); - db_logf4(("\tMax bytes to read = %u",pParams->maxReadBytes)); - } - break; - case 'N': - if (pParams->bytesReadP || pParams->restoreH) - bad_parmsB = true; - else - { - pParams->bytesReadP = va_arg(ap,unsigned *); - db_logf4(("\tPtr to bytes read = %p",pParams->bytesReadP)); - } - break; - case 'f': - if (AW_TLF_DEFAULT!=pParams->flags) - bad_parmsB = true; - else - { - pParams->flags = va_arg(ap,unsigned); - db_logf4(("\tFlags = 0x%08x",pParams->flags)); - } - break; - case 'W': - if (pParams->widthP || pParams->rectA) - bad_parmsB = true; - else - { - pParams->widthP = va_arg(ap,unsigned *); - db_logf4(("\tPtr to width = %p",pParams->widthP)); - } - break; - case 'H': - if (pParams->heightP || pParams->rectA) - bad_parmsB = true; - else - { - pParams->heightP = va_arg(ap,unsigned *); - db_logf4(("\tPtr to height = %p",pParams->heightP)); - } - break; - case 'X': - if (pParams->originalWidthP) - bad_parmsB = true; - else - { - pParams->originalWidthP = va_arg(ap,unsigned *); - db_logf4(("\tPtr to image width = %p",pParams->originalWidthP)); - } - break; - case 'Y': - if (pParams->originalHeightP) - bad_parmsB = true; - else - { - pParams->originalHeightP = va_arg(ap,unsigned *); - db_logf4(("\tPtr to image height = %p",pParams->originalHeightP)); - } - break; - case 'B': - if (pParams->backupHP || pParams->restoreH) - bad_parmsB = true; - else - { - pParams->backupHP = va_arg(ap,AW_BACKUPTEXTUREHANDLE *); - db_logf4(("\tPtr to backup handle = %p",pParams->backupHP)); - } - break; - case 't': - if (pParams->prevTexP.voidP) - bad_parmsB = true; - else if (pParams->rectA) - { - pParams->prevTexB = true; - db_log4("\tPrevious DDSurface * or D3DTexture * in rectangle array"); - } - else if (pParams->loadTextureB) - { - pParams->prevTexP = va_arg(ap,D3DTexture *); - db_logf4(("\tPrevious D3DTexture * = %p",pParams->prevTexP.textureP)); - } - else - { - pParams->prevTexP = va_arg(ap,DDSurface *); - db_logf4(("\tPrevious DDSurface * = %p",pParams->prevTexP.surfaceP)); - } - break; - case 'c': - if (pParams->callbackF) - bad_parmsB = true; - else - { - pParams->callbackF = va_arg(ap,AW_TL_PFN_CALLBACK); - pParams->callbackParam = va_arg(ap,void *); - db_logf4(("\tCallback function = %p, param = %p",pParams->callbackF,pParams->callbackParam)); - } - break; - case 'a': - if (pParams->prevTexP.voidP || pParams->rectA || pParams->widthP || pParams->heightP) - bad_parmsB = true; - else - { - pParams->numRects = va_arg(ap,unsigned); - pParams->rectA = va_arg(ap,AwCreateGraphicRegion *); - db_logf4(("\tRectangle array = %p, size = %u",pParams->rectA,pParams->numRects)); - } - break; - default: - bad_parmsB = true; - } - } - - if (!pParams->fileNameS && INVALID_HANDLE_VALUE==pParams->fileH && !pParams->dataP && !pParams->restoreH) - { - awTlLastErr = AW_TLE_BADPARMS; - db_log2("AwCreateGraphic(): ERROR: No data medium is specified"); - return false; - } - else if (bad_parmsB) - { - awTlLastErr = AW_TLE_BADPARMS; - db_logf2(("AwCreateGraphic(): ERROR: Unexpected '%c' in format string at character %u",ch,ch_off)); - return false; - } - else - { - db_log5("\tParameters are OK"); - return true; - } - } - - // Use the parameters parsed to load the surface or texture - - SurfUnion LoadFromParams(CreateTextureParms * pParams) - { - if (pParams->fileNameS) - { - pParams->fileH = CreateFile(pParams->fileNameS,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); - - if (INVALID_HANDLE_VALUE==pParams->fileH) - { - awTlLastErr = AW_TLE_CANTOPENFILE; - awTlLastWinErr = GetLastError(); - db_logf1(("AwCreateGraphic(): ERROR opening file \"%s\"",pParams->fileNameS)); - db_log2(AwTlErrorToString()); - return static_cast<D3DTexture *>(NULL); - } - - SurfUnion textureP = pParams->DoCreate(); - - CloseHandle(pParams->fileH); - - return textureP; - } - else return pParams->DoCreate(); - } - -} // namespace AwTl - -/******************************/ -/* PUBLIC: AwSetTextureFormat */ -/******************************/ - -#define IS_VALID_MEMBER(sP,mem) (reinterpret_cast<unsigned>(&(sP)->mem) - reinterpret_cast<unsigned>(sP) < static_cast<unsigned>((sP)->dwSize)) - -#if defined(__WATCOMC__) && (__WATCOMC__ <= 1100) // currently Watcom compiler crashes when the macro is expanded with the db_logf code in it -#define GET_VALID_MEMBER(sP,mem,deflt) (IS_VALID_MEMBER(sP,mem) ? (sP)->mem : (deflt)) -#else -#define GET_VALID_MEMBER(sP,mem,deflt) (IS_VALID_MEMBER(sP,mem) ? (sP)->mem : (db_logf4((FUNCTION_NAME ": WARNING: %s->%s is not valid",#sP ,#mem )),(deflt))) -#endif - -#define HANDLE_INITERROR(test,s) \ - if (!(test)) { \ - db_logf3((FUNCTION_NAME " failed becuse %s",s)); \ - db_log1(FUNCTION_NAME ": ERROR: unexpected parameters"); \ - return AW_TLE_BADPARMS; \ - } else { \ - db_logf5(("\t" FUNCTION_NAME " passed check '%s'",#test )); \ - } - -#define FUNCTION_NAME "AwSetD3DDevice()" - -AW_TL_ERC AwSetD3DDevice(D3DDevice * _d3ddeviceP) -{ - using AwTl::driverDesc; - - driverDesc.validB = false; - - db_logf4(("AwSetD3DDevice(%p) called",_d3ddeviceP)); - - HANDLE_INITERROR(_d3ddeviceP,"D3DDevice * is NULL") - - D3DDEVICEDESC hw_desc; - D3DDEVICEDESC hel_desc; - INITDXSTRUCT(hw_desc); - INITDXSTRUCT(hel_desc); - - awTlLastDxErr = _d3ddeviceP->GetCaps(&hw_desc,&hel_desc); - if (DD_OK != awTlLastDxErr) - { - db_logf2(("AwSetD3DDevice(): ERROR: %s",AwDxErrorToString())); - return AW_TLE_DXERROR; - } - - db_log4("Direct3D Device Hardware Capabilities:"); - db_code4(AwTl::LogCaps(&hw_desc);) - db_log4("Direct3D Device Emulation Capabilities:"); - db_code4(AwTl::LogCaps(&hel_desc);) - - LPD3DDEVICEDESC descP = (GET_VALID_MEMBER(&hw_desc,dwFlags,0) & D3DDD_COLORMODEL && GET_VALID_MEMBER(&hw_desc,dcmColorModel,0) & (D3DCOLOR_RGB|D3DCOLOR_MONO)) ? &hw_desc : &hel_desc; - db_logf4(("Direct3D Device is %s",&hw_desc==descP ? "HAL" : "emulation only")); - - HANDLE_INITERROR(GET_VALID_MEMBER(descP,dwFlags,0) & D3DDD_DEVCAPS && IS_VALID_MEMBER(descP,dwDevCaps),"LPD3DDEVICEDESC::dwDevCaps is not valid") - HANDLE_INITERROR(descP->dwDevCaps & (D3DDEVCAPS_TEXTUREVIDEOMEMORY|D3DDEVCAPS_TEXTURENONLOCALVIDMEM|D3DDEVCAPS_TEXTURESYSTEMMEMORY),"Textures cannot be in ANY type of memory") - - driverDesc.memFlag = descP->dwDevCaps & D3DDEVCAPS_TEXTURESYSTEMMEMORY ? DDSCAPS_SYSTEMMEMORY : DDSCAPS_VIDEOMEMORY; - driverDesc.minWidth = GET_VALID_MEMBER(descP,dwMinTextureWidth,0); - driverDesc.minHeight = GET_VALID_MEMBER(descP,dwMinTextureHeight,0); - driverDesc.maxWidth = GET_VALID_MEMBER(descP,dwMaxTextureWidth,0); - driverDesc.maxHeight = GET_VALID_MEMBER(descP,dwMaxTextureHeight,0); - driverDesc.needPow2B = GET_VALID_MEMBER(descP,dpcTriCaps.dwTextureCaps,0) & D3DPTEXTURECAPS_POW2 ? true : false; - driverDesc.needSquareB = GET_VALID_MEMBER(descP,dpcTriCaps.dwTextureCaps,0) & D3DPTEXTURECAPS_SQUAREONLY ? true : false; - // if max w and h are 0, make them as large as possible - if (!driverDesc.maxWidth) driverDesc.maxWidth = UINT_MAX; - if (!driverDesc.maxHeight) driverDesc.maxHeight = UINT_MAX; - - db_log4("AwSetD3DDevice() OK"); - - db_log4("Direct 3D Device texture characteristics follow:"); - db_logf4(("\tMinimum texture size: %u x %u",driverDesc.minWidth,driverDesc.minHeight)); - db_logf4(("\tMaximum texture size: %u x %u",driverDesc.maxWidth,driverDesc.maxHeight)); - db_logf4(("\tTextures %s be sqaure",driverDesc.needSquareB ? "must" : "need not")); - db_logf4(("\tTextures %s be a power of two in width and height",driverDesc.needPow2B ? "must" : "need not")); - db_logf4(("\tTextures can%s be in non-local video (AGP) memory",descP->dwDevCaps & D3DDEVCAPS_TEXTURENONLOCALVIDMEM ? "" : "not")); - db_logf4(("\tTextures can%s be in local video (device) memory",descP->dwDevCaps & D3DDEVCAPS_TEXTUREVIDEOMEMORY ? "" : "not")); - db_logf4(("\tTextures can%s be in system memory",descP->dwDevCaps & D3DDEVCAPS_TEXTURESYSTEMMEMORY ? "" : "not")); - db_logf4(("\tTextures will be in %s memory",driverDesc.memFlag & DDSCAPS_SYSTEMMEMORY ? "system" : "video")); - - driverDesc.validB = true; - - return AW_TLE_OK; -} - -AW_TL_ERC AwSetDDObject(DDObject * _ddP) -{ - using AwTl::driverDesc; - - db_logf4(("AwSetDDObject(%p) called.",_ddP)); - #ifdef DIRECTDRAW_VERSION - db_logf4(("\tCompiled with DirectDraw Version %u.%u",DIRECTDRAW_VERSION/0x100U,DIRECTDRAW_VERSION%0x100U)); - #else - db_log4("\tCompiled with unknown DirectDraw version"); - #endif - - - HANDLE_INITERROR(_ddP,"DDObject * is NULL") - driverDesc.ddP = _ddP; - - return AW_TLE_OK; -} - -AW_TL_ERC AwSetD3DDevice(DDObject * _ddP, D3DDevice * _d3ddeviceP) -{ - db_logf4(("AwSetD3DDevice(%p,%p) called",_ddP,_d3ddeviceP)); - - AW_TL_ERC iResult = AwSetDDObject(_ddP); - - if (AW_TLE_OK != iResult) - return iResult; - else - return AwSetD3DDevice(_d3ddeviceP); -} - -#undef FUNCTION_NAME -#define FUNCTION_NAME "AwSetPixelFormat()" -static AW_TL_ERC AwSetPixelFormat(AwTl::PixelFormat * _pfP, LPDDPIXELFORMAT _ddpfP) -{ - using AwTl::SetBitShifts; - - _pfP->validB = false; - - // parameter check - HANDLE_INITERROR(_ddpfP,"DDPIXELFORMAT is NULL") - HANDLE_INITERROR(IS_VALID_MEMBER(_ddpfP,dwFlags),"DDPIXELFORMAT::dwFlags is an invalid field") - HANDLE_INITERROR(!(_ddpfP->dwFlags & DDPF_ALPHA),"DDPIXELFORMAT describes an alpha only surface") - HANDLE_INITERROR(!(_ddpfP->dwFlags & DDPF_PALETTEINDEXEDTO8),"DDPIXELFORMAT describes a 1- 2- or 4- bit surface indexed to an 8-bit palette. This is not yet supported") - HANDLE_INITERROR(!(_ddpfP->dwFlags & DDPF_ZBUFFER),"DDPIXELFORMAT describes Z buffer") - HANDLE_INITERROR(!(_ddpfP->dwFlags & DDPF_ZPIXELS),"DDPIXELFORMAT describes a RGBZ surface") - HANDLE_INITERROR(!(_ddpfP->dwFlags & DDPF_YUV),"DDPIXELFORMAT describes a YUV surface. This is not yet supported") - HANDLE_INITERROR(!(_ddpfP->dwFlags & DDPF_FOURCC),"DDPIXELFORMAT gives a FourCC code for a non RGB surface. This is not yet supported") - - _pfP->palettizedB = true; - switch (_ddpfP->dwFlags & (DDPF_PALETTEINDEXED8|DDPF_PALETTEINDEXED4|DDPF_PALETTEINDEXED2|DDPF_PALETTEINDEXED1)) - { - case 0: - _pfP->palettizedB = false; - break; - case DDPF_PALETTEINDEXED1: - _pfP->bitsPerPixel = 1; - break; - case DDPF_PALETTEINDEXED2: - _pfP->bitsPerPixel = 2; - break; - case DDPF_PALETTEINDEXED4: - _pfP->bitsPerPixel = 4; - break; - case DDPF_PALETTEINDEXED8: - _pfP->bitsPerPixel = 8; - break; - default: - db_log1("AwSetPixelFormat(): ERROR: more than one DDPF_PALETTEINDEXED<n> flags is set"); - return AW_TLE_BADPARMS; - } - - _pfP->alphaB = _ddpfP->dwFlags & DDPF_ALPHAPIXELS ? true : false; - - if (_pfP->palettizedB) - { - HANDLE_INITERROR(!_pfP->alphaB,"alpha channel info is on a palettized format. This is not yet supported") - #if DB_LEVEL >= 4 - if (_ddpfP->dwFlags & DDPF_RGB) - { - db_log4(FUNCTION_NAME ": WARNING: RGB data supplied for a palettized format is ignored"); - db_logf4(("\tRGB bitcount is %u",GET_VALID_MEMBER(_ddpfP,dwRGBBitCount,0))); - db_logf4(("\tRed Mask is 0x%08x",GET_VALID_MEMBER(_ddpfP,dwRBitMask,0))); - db_logf4(("\tGreen Mask is 0x%08x",GET_VALID_MEMBER(_ddpfP,dwGBitMask,0))); - db_logf4(("\tBlue Mask is 0x%08x",GET_VALID_MEMBER(_ddpfP,dwBBitMask,0))); - } - #endif - } - else - { - HANDLE_INITERROR(IS_VALID_MEMBER(_ddpfP,dwRGBBitCount),"DDPIXELFORMAT::dwRGBBitCount is an invalid field") - switch (_ddpfP->dwRGBBitCount) - { - case 4: - case 8: - case 16: - case 24: - case 32: - break; - default: - db_log1("AwSetPixelFormat(): ERROR: RGB bit count is not 4,8,16,24 or 32"); - return AW_TLE_BADPARMS; - } - - HANDLE_INITERROR(!_pfP->alphaB || GET_VALID_MEMBER(_ddpfP,dwRGBAlphaBitMask,0),"Pixel format specifies alpha channel info but alpha mask is zero") - HANDLE_INITERROR(IS_VALID_MEMBER(_ddpfP,dwRBitMask),"DDPIXELFORMAT::dwRBitMask is an invalid field") - HANDLE_INITERROR(IS_VALID_MEMBER(_ddpfP,dwGBitMask),"DDPIXELFORMAT::dwGBitMask is an invalid field") - HANDLE_INITERROR(IS_VALID_MEMBER(_ddpfP,dwBBitMask),"DDPIXELFORMAT::dwBBitMask is an invalid field") - - _pfP->bitsPerPixel = _ddpfP->dwRGBBitCount; - SetBitShifts(&_pfP->redLeftShift,&_pfP->redRightShift,_ddpfP->dwRBitMask); - SetBitShifts(&_pfP->greenLeftShift,&_pfP->greenRightShift,_ddpfP->dwGBitMask); - SetBitShifts(&_pfP->blueLeftShift,&_pfP->blueRightShift,_ddpfP->dwBBitMask); - } - ZEROFILL(_pfP->ddpf); - memcpy(&_pfP->ddpf,_ddpfP,__min(_ddpfP->dwSize,sizeof(DDPIXELFORMAT))); - if (!_pfP->alphaB) - _pfP->ddpf.dwRGBAlphaBitMask = 0; - - db_log4("AwSetPixelFormat() OK"); - - #if DB_LEVEL >= 4 - db_logf4(("Pixel Format is %u-bit %s",_pfP->bitsPerPixel,_pfP->palettizedB ? "palettized" : _pfP->alphaB ? "RGBA" : "RGB")); - if (!_pfP->palettizedB) - { - if (_pfP->alphaB) - { - unsigned alpha_l_shft,alpha_r_shft; - SetBitShifts(&alpha_l_shft,&alpha_r_shft,_pfP->ddpf.dwRGBAlphaBitMask); - db_logf4(("\t%u-%u-%u-%u",8-_pfP->redRightShift,8-_pfP->greenRightShift,8-_pfP->blueRightShift,8-alpha_r_shft)); - db_logf4(("\tAlpha->[%u..%u]",alpha_l_shft+7-alpha_r_shft,alpha_l_shft)); - } - else - { - db_logf4(("\t%u-%u-%u",8-_pfP->redRightShift,8-_pfP->greenRightShift,8-_pfP->blueRightShift)); - } - db_logf4(("\tRed->[%u..%u]",_pfP->redLeftShift+7-_pfP->redRightShift,_pfP->redLeftShift)); - db_logf4(("\tGreen->[%u..%u]",_pfP->greenLeftShift+7-_pfP->greenRightShift,_pfP->greenLeftShift)); - db_logf4(("\tBlue->[%u..%u]",_pfP->blueLeftShift+7-_pfP->blueRightShift,_pfP->blueLeftShift)); - } - #endif - - _pfP->validB = true; - return AW_TLE_OK; -} - -AW_TL_ERC AwSetTextureFormat2(LPDDPIXELFORMAT _ddpfP) -{ - db_logf4(("AwSetTextureFormat(%p) called",_ddpfP)); - - using namespace AwTl; - - while (listTextureFormats.size()) - listTextureFormats.delete_first_entry(); - - return AwSetPixelFormat(&pfTextureFormat, _ddpfP); -} - -AW_TL_ERC AwSetAdditionalTextureFormat2(LPDDPIXELFORMAT _ddpfP, unsigned _maxAlphaBits, int _canDoTransp, unsigned _maxColours) -{ - db_logf4(("AwSetAdditionalTextureFormat(%p.%u,%d,%u) called",_ddpfP,_maxAlphaBits,_canDoTransp,_maxColours)); - - using namespace AwTl; - - AdditionalPixelFormat pf; - - AW_TL_ERC erc = AwSetPixelFormat(&pf, _ddpfP); - - if (AW_TLE_OK == erc) - { - pf.canDoTranspB = _canDoTransp ? true : false; - pf.maxColours = _maxColours; - - listTextureFormats.add_entry_end(pf); - } - - return erc; -} - -AW_TL_ERC AwSetSurfaceFormat2(LPDDPIXELFORMAT _ddpfP) -{ - db_logf4(("AwSetSurfaceFormat(%p) called",_ddpfP)); - - using namespace AwTl; - - return AwSetPixelFormat(&pfSurfaceFormat, _ddpfP); -} - -/****************************/ -/* PUBLIC: AwGetTextureSize */ -/****************************/ - -AW_TL_ERC AwGetTextureSize(register unsigned * _widthP, register unsigned * _heightP, unsigned _width, unsigned _height) -{ - db_assert1(_widthP); - db_assert1(_heightP); - - using AwTl::driverDesc; - - if (!driverDesc.validB) - { - db_log3("AwGetTextureSize(): ERROR: driver description not valid"); - return AW_TLE_NOINIT; - } - - if (_width < driverDesc.minWidth) _width = driverDesc.minWidth; - if (_height < driverDesc.minHeight) _height = driverDesc.minHeight; - - if (driverDesc.needPow2B) - { - *_widthP = 1; - while (*_widthP < _width) *_widthP <<= 1; - *_heightP = 1; - while (*_heightP < _height) *_heightP <<= 1; - } - else - { - *_widthP = _width; - *_heightP = _height; - } - - if (driverDesc.needSquareB) - { - if (*_widthP < *_heightP) *_widthP = *_heightP; - else *_heightP = *_widthP; - } - - #if 1 // not sure if this is required... - *_widthP += 3; - *_widthP &= ~3; - *_heightP += 3; - *_heightP &= ~3; - #endif - - db_logf4(("\tAwGetTextureSize(): d3d texture will be %ux%u",*_widthP,*_heightP)); - - if (*_widthP > driverDesc.maxWidth || *_heightP > driverDesc.maxHeight) - { - db_log3("AwGetTextureSize(): ERROR: image size too large to be a d3d texture"); - return AW_TLE_IMAGETOOLARGE; - } - else return AW_TLE_OK; -} - - -/******************************/ -/* PUBLIC: AwCreate functions */ -/******************************/ - -D3DTexture * _AWTL_VARARG AwCreateTexture(char const * _argFormatS, ...) -{ - db_logf4(("AwCreateTexture(\"%s\") called",_argFormatS)); - - using namespace AwTl; - - va_list ap; - va_start(ap,_argFormatS); - CreateTextureParms parms; - parms.loadTextureB = true; - bool bParmsOK = ParseParams(&parms, _argFormatS, ap); - va_end(ap); - return bParmsOK ? LoadFromParams(&parms).textureP : NULL; -} - -DDSurface * _AWTL_VARARG AwCreateSurface(char const * _argFormatS, ...) -{ - db_logf4(("AwCreateSurface(\"%s\") called",_argFormatS)); - - using namespace AwTl; - - va_list ap; - va_start(ap,_argFormatS); - CreateTextureParms parms; - parms.loadTextureB = false; - bool bParmsOK = ParseParams(&parms, _argFormatS, ap); - va_end(ap); - return bParmsOK ? LoadFromParams(&parms).surfaceP : NULL; -} - -AW_TL_ERC AwDestroyBackupTexture(AW_BACKUPTEXTUREHANDLE _bH) -{ - db_logf4(("AwDestroyBackupTexture(0x%08x) called",_bH)); - if (_bH) - { - _bH->Release(); - return AW_TLE_OK; - } - else - { - db_log1("AwDestroyBackupTexture(): ERROR: AW_BACKUPTEXTUREHANDLE==NULL"); - return AW_TLE_BADPARMS; - } -} - -/*********************************/ -/* PUBLIC DEBUG: LastErr globals */ -/*********************************/ - -AW_TL_ERC awTlLastErr; -HRESULT awTlLastDxErr; -DWORD awTlLastWinErr; - -/*******************************************/ -/* PUBLIC DEBUG: AwErrorToString functions */ -/*******************************************/ - -#ifndef NDEBUG -char const * AwWinErrorToString(DWORD error) -{ - if (NO_ERROR==error) return "No error"; - static TCHAR buffer[1024]; - if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,error,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),buffer,sizeof buffer/sizeof(TCHAR)-1,NULL)) - wsprintf(buffer,TEXT("FormatMessage() failed; previous Windows error code: 0x%08X"),error); - for (TCHAR * bufP = buffer; *bufP; ++bufP) - { - switch (*bufP) - { - case '\n': - case '\r': - *bufP=' '; - } - } - return reinterpret_cast<char *>(buffer); -} - -char const * AwTlErrorToString(AwTlErc error) -{ - char const * defaultS; - switch (error) - { - case AW_TLE_OK: - return "No error"; - case AW_TLE_DXERROR: - if (DD_OK==awTlLastDxErr) - return "Unknown DirectX error"; - else - return AwDxErrorToString(); - case AW_TLE_BADPARMS: - return "Invalid parameters or functionality not supported"; - case AW_TLE_NOINIT: - return "Initialization failed or not performed"; - case AW_TLE_CANTOPENFILE: - defaultS = "Unknown error opening file"; - goto WIN_ERR; - case AW_TLE_CANTREADFILE: - defaultS = "Unknown error reading file"; - WIN_ERR: - if (NO_ERROR==awTlLastWinErr) - return defaultS; - else - return AwWinErrorToString(); - case AW_TLE_EOFMET: - return "Unexpected end of file during texture load"; - case AW_TLE_BADFILEFORMAT: - return "Texture file format not recognized"; - case AW_TLE_BADFILEDATA: - return "Texture file data not consistent"; - case AW_TLE_CANTPALETTIZE: - return "Texture file data not palettized"; - case AW_TLE_IMAGETOOLARGE: - return "Image is too large for a texture"; - case AW_TLE_CANTRELOAD: - return "New image is wrong size or format to load into existing texture"; - default: - return "Unknown texture loading error"; - } -} - -char const * AwDxErrorToString(HRESULT error) -{ - switch(error) { - case DD_OK: - return "No error.\0"; - case DDERR_ALREADYINITIALIZED: - return "This object is already initialized.\0"; - case DDERR_BLTFASTCANTCLIP: - return "Return if a clipper object is attached to the source surface passed into a BltFast call.\0"; - case DDERR_CANNOTATTACHSURFACE: - return "This surface can not be attached to the requested surface.\0"; - case DDERR_CANNOTDETACHSURFACE: - return "This surface can not be detached from the requested surface.\0"; - case DDERR_CANTCREATEDC: - return "Windows can not create any more DCs.\0"; - case DDERR_CANTDUPLICATE: - return "Can't duplicate primary & 3D surfaces, or surfaces that are implicitly created.\0"; - case DDERR_CLIPPERISUSINGHWND: - return "An attempt was made to set a cliplist for a clipper object that is already monitoring an hwnd.\0"; - case DDERR_COLORKEYNOTSET: - return "No src color key specified for this operation.\0"; - case DDERR_CURRENTLYNOTAVAIL: - return "Support is currently not available.\0"; - case DDERR_DIRECTDRAWALREADYCREATED: - return "A DirectDraw object representing this driver has already been created for this process.\0"; - case DDERR_EXCEPTION: - return "An exception was encountered while performing the requested operation.\0"; - case DDERR_EXCLUSIVEMODEALREADYSET: - return "An attempt was made to set the cooperative level when it was already set to exclusive.\0"; - case DDERR_GENERIC: - return "Generic failure.\0"; - case DDERR_HEIGHTALIGN: - return "Height of rectangle provided is not a multiple of reqd alignment.\0"; - case DDERR_HWNDALREADYSET: - return "The CooperativeLevel HWND has already been set. It can not be reset while the process has surfaces or palettes created.\0"; - case DDERR_HWNDSUBCLASSED: - return "HWND used by DirectDraw CooperativeLevel has been subclassed, this prevents DirectDraw from restoring state.\0"; - case DDERR_IMPLICITLYCREATED: - return "This surface can not be restored because it is an implicitly created surface.\0"; - case DDERR_INCOMPATIBLEPRIMARY: - return "Unable to match primary surface creation request with existing primary surface.\0"; - case DDERR_INVALIDCAPS: - return "One or more of the caps bits passed to the callback are incorrect.\0"; - case DDERR_INVALIDCLIPLIST: - return "DirectDraw does not support the provided cliplist.\0"; - case DDERR_INVALIDDIRECTDRAWGUID: - return "The GUID passed to DirectDrawCreate is not a valid DirectDraw driver identifier.\0"; - case DDERR_INVALIDMODE: - return "DirectDraw does not support the requested mode.\0"; - case DDERR_INVALIDOBJECT: - return "DirectDraw received a pointer that was an invalid DIRECTDRAW object.\0"; - case DDERR_INVALIDPARAMS: - return "One or more of the parameters passed to the function are incorrect.\0"; - case DDERR_INVALIDPIXELFORMAT: - return "The pixel format was invalid as specified.\0"; - case DDERR_INVALIDPOSITION: - return "Returned when the position of the overlay on the destination is no longer legal for that destination.\0"; - case DDERR_INVALIDRECT: - return "Rectangle provided was invalid.\0"; - case DDERR_LOCKEDSURFACES: - return "Operation could not be carried out because one or more surfaces are locked.\0"; - case DDERR_NO3D: - return "There is no 3D present.\0"; - case DDERR_NOALPHAHW: - return "Operation could not be carried out because there is no alpha accleration hardware present or available.\0"; - case DDERR_NOBLTHW: - return "No blitter hardware present.\0"; - case DDERR_NOCLIPLIST: - return "No cliplist available.\0"; - case DDERR_NOCLIPPERATTACHED: - return "No clipper object attached to surface object.\0"; - case DDERR_NOCOLORCONVHW: - return "Operation could not be carried out because there is no color conversion hardware present or available.\0"; - case DDERR_NOCOLORKEY: - return "Surface doesn't currently have a color key\0"; - case DDERR_NOCOLORKEYHW: - return "Operation could not be carried out because there is no hardware support of the destination color key.\0"; - case DDERR_NOCOOPERATIVELEVELSET: - return "Create function called without DirectDraw object method SetCooperativeLevel being called.\0"; - case DDERR_NODC: - return "No DC was ever created for this surface.\0"; - case DDERR_NODDROPSHW: - return "No DirectDraw ROP hardware.\0"; - case DDERR_NODIRECTDRAWHW: - return "A hardware-only DirectDraw object creation was attempted but the driver did not support any hardware.\0"; - case DDERR_NOEMULATION: - return "Software emulation not available.\0"; - case DDERR_NOEXCLUSIVEMODE: - return "Operation requires the application to have exclusive mode but the application does not have exclusive mode.\0"; - case DDERR_NOFLIPHW: - return "Flipping visible surfaces is not supported.\0"; - case DDERR_NOGDI: - return "There is no GDI present.\0"; - case DDERR_NOHWND: - return "Clipper notification requires an HWND or no HWND has previously been set as the CooperativeLevel HWND.\0"; - case DDERR_NOMIRRORHW: - return "Operation could not be carried out because there is no hardware present or available.\0"; - case DDERR_NOOVERLAYDEST: - return "Returned when GetOverlayPosition is called on an overlay that UpdateOverlay has never been called on to establish a destination.\0"; - case DDERR_NOOVERLAYHW: - return "Operation could not be carried out because there is no overlay hardware present or available.\0"; - case DDERR_NOPALETTEATTACHED: - return "No palette object attached to this surface.\0"; - case DDERR_NOPALETTEHW: - return "No hardware support for 16 or 256 color palettes.\0"; - case DDERR_NORASTEROPHW: - return "Operation could not be carried out because there is no appropriate raster op hardware present or available.\0"; - case DDERR_NOROTATIONHW: - return "Operation could not be carried out because there is no rotation hardware present or available.\0"; - case DDERR_NOSTRETCHHW: - return "Operation could not be carried out because there is no hardware support for stretching.\0"; - case DDERR_NOT4BITCOLOR: - return "DirectDrawSurface is not in 4 bit color palette and the requested operation requires 4 bit color palette.\0"; - case DDERR_NOT4BITCOLORINDEX: - return "DirectDrawSurface is not in 4 bit color index palette and the requested operation requires 4 bit color index palette.\0"; - case DDERR_NOT8BITCOLOR: - return "DirectDrawSurface is not in 8 bit color mode and the requested operation requires 8 bit color.\0"; - case DDERR_NOTAOVERLAYSURFACE: - return "Returned when an overlay member is called for a non-overlay surface.\0"; - case DDERR_NOTEXTUREHW: - return "Operation could not be carried out because there is no texture mapping hardware present or available.\0"; - case DDERR_NOTFLIPPABLE: - return "An attempt has been made to flip a surface that is not flippable.\0"; - case DDERR_NOTFOUND: - return "Requested item was not found.\0"; - case DDERR_NOTLOCKED: - return "Surface was not locked. An attempt to unlock a surface that was not locked at all, or by this process, has been attempted.\0"; - case DDERR_NOTPALETTIZED: - return "The surface being used is not a palette-based surface.\0"; - case DDERR_NOVSYNCHW: - return "Operation could not be carried out because there is no hardware support for vertical blank synchronized operations.\0"; - case DDERR_NOZBUFFERHW: - return "Operation could not be carried out because there is no hardware support for zbuffer blitting.\0"; - case DDERR_NOZOVERLAYHW: - return "Overlay surfaces could not be z layered based on their BltOrder because the hardware does not support z layering of overlays.\0"; - case DDERR_OUTOFCAPS: - return "The hardware needed for the requested operation has already been allocated.\0"; - case DDERR_OUTOFMEMORY: - return "DirectDraw does not have enough memory to perform the operation.\0"; - case DDERR_OUTOFVIDEOMEMORY: - return "DirectDraw does not have enough video memory to perform the operation.\0"; - case DDERR_OVERLAYCANTCLIP: - return "The hardware does not support clipped overlays.\0"; - case DDERR_OVERLAYCOLORKEYONLYONEACTIVE: - return "Can only have ony color key active at one time for overlays.\0"; - case DDERR_OVERLAYNOTVISIBLE: - return "Returned when GetOverlayPosition is called on a hidden overlay.\0"; - case DDERR_PALETTEBUSY: - return "Access to this palette is being refused because the palette is already locked by another thread.\0"; - case DDERR_PRIMARYSURFACEALREADYEXISTS: - return "This process already has created a primary surface.\0"; - case DDERR_REGIONTOOSMALL: - return "Region passed to Clipper::GetClipList is too small.\0"; - case DDERR_SURFACEALREADYATTACHED: - return "This surface is already attached to the surface it is being attached to.\0"; - case DDERR_SURFACEALREADYDEPENDENT: - return "This surface is already a dependency of the surface it is being made a dependency of.\0"; - case DDERR_SURFACEBUSY: - return "Access to this surface is being refused because the surface is already locked by another thread.\0"; - case DDERR_SURFACEISOBSCURED: - return "Access to surface refused because the surface is obscured.\0"; - case DDERR_SURFACELOST: - return "Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.\0"; - case DDERR_SURFACENOTATTACHED: - return "The requested surface is not attached.\0"; - case DDERR_TOOBIGHEIGHT: - return "Height requested by DirectDraw is too large.\0"; - case DDERR_TOOBIGSIZE: - return "Size requested by DirectDraw is too large, but the individual height and width are OK.\0"; - case DDERR_TOOBIGWIDTH: - return "Width requested by DirectDraw is too large.\0"; - case DDERR_UNSUPPORTED: - return "Action not supported.\0"; - case DDERR_UNSUPPORTEDFORMAT: - return "FOURCC format requested is unsupported by DirectDraw.\0"; - case DDERR_UNSUPPORTEDMASK: - return "Bitmask in the pixel format requested is unsupported by DirectDraw.\0"; - case DDERR_VERTICALBLANKINPROGRESS: - return "Vertical blank is in progress.\0"; - case DDERR_WASSTILLDRAWING: - return "Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.\0"; - case DDERR_WRONGMODE: - return "This surface can not be restored because it was created in a different mode.\0"; - case DDERR_XALIGN: - return "Rectangle provided was not horizontally aligned on required boundary.\0"; - case D3DERR_BADMAJORVERSION: - return "D3DERR_BADMAJORVERSION\0"; - case D3DERR_BADMINORVERSION: - return "D3DERR_BADMINORVERSION\0"; - case D3DERR_EXECUTE_LOCKED: - return "D3DERR_EXECUTE_LOCKED\0"; - case D3DERR_EXECUTE_NOT_LOCKED: - return "D3DERR_EXECUTE_NOT_LOCKED\0"; - case D3DERR_EXECUTE_CREATE_FAILED: - return "D3DERR_EXECUTE_CREATE_FAILED\0"; - case D3DERR_EXECUTE_DESTROY_FAILED: - return "D3DERR_EXECUTE_DESTROY_FAILED\0"; - case D3DERR_EXECUTE_LOCK_FAILED: - return "D3DERR_EXECUTE_LOCK_FAILED\0"; - case D3DERR_EXECUTE_UNLOCK_FAILED: - return "D3DERR_EXECUTE_UNLOCK_FAILED\0"; - case D3DERR_EXECUTE_FAILED: - return "D3DERR_EXECUTE_FAILED\0"; - case D3DERR_EXECUTE_CLIPPED_FAILED: - return "D3DERR_EXECUTE_CLIPPED_FAILED\0"; - case D3DERR_TEXTURE_NO_SUPPORT: - return "D3DERR_TEXTURE_NO_SUPPORT\0"; - case D3DERR_TEXTURE_NOT_LOCKED: - return "D3DERR_TEXTURE_NOT_LOCKED\0"; - case D3DERR_TEXTURE_LOCKED: - return "D3DERR_TEXTURE_LOCKED\0"; - case D3DERR_TEXTURE_CREATE_FAILED: - return "D3DERR_TEXTURE_CREATE_FAILED\0"; - case D3DERR_TEXTURE_DESTROY_FAILED: - return "D3DERR_TEXTURE_DESTROY_FAILED\0"; - case D3DERR_TEXTURE_LOCK_FAILED: - return "D3DERR_TEXTURE_LOCK_FAILED\0"; - case D3DERR_TEXTURE_UNLOCK_FAILED: - return "D3DERR_TEXTURE_UNLOCK_FAILED\0"; - case D3DERR_TEXTURE_LOAD_FAILED: - return "D3DERR_TEXTURE_LOAD_FAILED\0"; - case D3DERR_MATRIX_CREATE_FAILED: - return "D3DERR_MATRIX_CREATE_FAILED\0"; - case D3DERR_MATRIX_DESTROY_FAILED: - return "D3DERR_MATRIX_DESTROY_FAILED\0"; - case D3DERR_MATRIX_SETDATA_FAILED: - return "D3DERR_MATRIX_SETDATA_FAILED\0"; - case D3DERR_SETVIEWPORTDATA_FAILED: - return "D3DERR_SETVIEWPORTDATA_FAILED\0"; - case D3DERR_MATERIAL_CREATE_FAILED: - return "D3DERR_MATERIAL_CREATE_FAILED\0"; - case D3DERR_MATERIAL_DESTROY_FAILED: - return "D3DERR_MATERIAL_DESTROY_FAILED\0"; - case D3DERR_MATERIAL_SETDATA_FAILED: - return "D3DERR_MATERIAL_SETDATA_FAILED\0"; - case D3DERR_LIGHT_SET_FAILED: - return "D3DERR_LIGHT_SET_FAILED\0"; - #if 0 // retained mode error codes - case D3DRMERR_BADOBJECT: - return "D3DRMERR_BADOBJECT\0"; - case D3DRMERR_BADTYPE: - return "D3DRMERR_BADTYPE\0"; - case D3DRMERR_BADALLOC: - return "D3DRMERR_BADALLOC\0"; - case D3DRMERR_FACEUSED: - return "D3DRMERR_FACEUSED\0"; - case D3DRMERR_NOTFOUND: - return "D3DRMERR_NOTFOUND\0"; - case D3DRMERR_NOTDONEYET: - return "D3DRMERR_NOTDONEYET\0"; - case D3DRMERR_FILENOTFOUND: - return "The file was not found.\0"; - case D3DRMERR_BADFILE: - return "D3DRMERR_BADFILE\0"; - case D3DRMERR_BADDEVICE: - return "D3DRMERR_BADDEVICE\0"; - case D3DRMERR_BADVALUE: - return "D3DRMERR_BADVALUE\0"; - case D3DRMERR_BADMAJORVERSION: - return "D3DRMERR_BADMAJORVERSION\0"; - case D3DRMERR_BADMINORVERSION: - return "D3DRMERR_BADMINORVERSION\0"; - case D3DRMERR_UNABLETOEXECUTE: - return "D3DRMERR_UNABLETOEXECUTE\0"; - #endif - default: - return "Unrecognized error value.\0"; - } -} -#endif diff --git a/3dc/win95/awTexLd.h b/3dc/win95/awTexLd.h deleted file mode 100644 index 8b143a9..0000000 --- a/3dc/win95/awTexLd.h +++ /dev/null @@ -1,565 +0,0 @@ -#ifndef _INCLUDED_AWTEXLD_H_ -#define _INCLUDED_AWTEXLD_H_ - -#include <windows.h> -#include <d3d.h> - -/*********************************************/ -/* Note: */ -/* */ -/* This header file contains typedefs for */ -/* DDObject */ -/* D3DDevice */ -/* D3DTexture */ -/* D3DSurface */ -/* and #defines for their corresponding IIDs */ -/* GUID_DD_SURFACE */ -/* GUID_D3D_TEXTURE */ -/* */ -/* They are currently typedeffed as follows */ -/* typedef IDirectDraw2 DDObject; */ -/* typedef IDirect3DDevice D3DDevice; */ -/* typedef IDirect3DTexture D3DTexture; */ -/* typedef IDirect3DSurface DDSurface; */ -/*********************************************/ -#include "aw.h" - -/***********************************************************************************/ -/* awTexLd.h - Author: Jake Hotson */ -/* */ -/* Loading of textures into D3D surfaces */ -/* requires DirectX 5 or later */ -/* requires db.c and db.h */ -/* also requires */ -/* Watcom C++ 11.0 or later */ -/* or Microsoft Visual C++ 5.0 or later */ -/* or another suitable compiler */ -/* */ -/* Load any known file format */ -/* Microsoft bitmap (.BMP) */ -/* OS/2 1.x bitmap (.BMP) */ -/* OS/2 2.x bitmap (.BMP) */ -/* Portable Bitmap (.PBM) */ -/* Portable Graymap (.PGM) */ -/* Portable Pixelmap (.PPM) */ -/* */ -/* Load from various media */ -/* File name */ -/* Windows file handle */ -/* Raw file data in memory */ -/* */ -/* Load into any given texture format provided a conversion is possible */ -/* Pad to the required size that the driver will accept */ -/* */ -/* Optional handling of transparency */ -/* Use alpha bits if available */ -/* Otherwise chroma keying to be used */ -/* Transparency colour is RGB(0,0,0) for non palettized data */ -/* Or index 0 in palettized data */ -/* */ -/* Optional storing of processed raw data */ -/* Use internal format independent of DirectX */ -/* Function to reload from this data into a possibly different texture format */ -/* */ -/* Five optional levels of diagnostics possible */ -/* 1. Logs when a function returns because of an error */ -/* 2. Logs the nature of the error */ -/* 3. Logs immediately when an error occurs */ -/* 4. Logs information as data is parsed, and when main functions are called */ -/* 5. Logs success of every small subsection of code */ -/* */ -/* Maximum error reporting */ -/* */ -/* Optimal Loading Speed */ -/***********************************************************************************/ - -/* Version 2.1 */ -#define AW_TL_VERSION 210 /* Preprocessor constant can be used to determine the version of this code */ - -/* -Version History: ----------------- -version AW_TL_VERSION -0.9 090 Incomplete & May still contain bugs -0.91 091 AW_TLF_CHROMAKEY flag, and 't' option supported. Fewer bugs -0.92 092 Slightly more debug code -0.93 093 Using typedefs DDObject, D3DDevice, D3DTexture -1.0 100 Assumed to be bug-free -1.1 110 Internal redesign with interface to support any file format -1.2 120 Allow for loading into Direct Draw surfaces which are not textures -1.21 121 Two extra format flags to get width and height of actual image (as opposed to DD/D3D surface) -1.22 122 Split up the initialization function AwSetD3DDevice() into DD part and D3D part -1.3 130 New function: AwGetTextureSize() -1.31 131 New format flag for a callback function for when video mem runs out -1.4 140 Support for loading image split into several surfaces/textures and for loading surfaces as textures -1.5 150 Multiple texture format support - -2.0 200 Beginning support for DX 6.0 - new AwSet..Format functions take LPDDPIXELFORMAT not LPDDSURFACEDESC -2.1 210 AW_TLF_CHECKLOST and AW_TLF_SKIPNOTLOST flags added -*/ - -/**********************************************/ -/* Handle C++ linkage and optional parameters */ -/**********************************************/ - -#ifdef __cplusplus - extern "C" { - #define _AWTL_DEFAULTPARM(v) = (v) -#else /* ! __cplusplus */ - #define _AWTL_DEFAULTPARM(v) -#endif /* ? __cplusplus */ - -#ifdef _MSC_VER - #define _AWTL_VARARG __cdecl -#else - #define _AWTL_VARARG -#endif - -/******************************/ -/* return codes & error codes */ -/******************************/ - -typedef -enum AwTlErc -{ - /* General Errors */ - AW_TLE_OK /* apparent success */ - , AW_TLE_DXERROR /* unexpected DirectX error - see awTlLastDxErr */ - , AW_TLE_BADPARMS /* parameters passed to function were invalid, or requested unsupported functionality */ - , AW_TLE_NOINIT /* initialization functions have not been successfully called */ - /* File reading errors */ - , AW_TLE_CANTOPENFILE /* file open failed - see awTlLastWinErr for the Windows error code */ - , AW_TLE_CANTREADFILE /* unexpected error reading file - see awTlLastWinErr for the Windows error code */ - , AW_TLE_EOFMET /* unexpected end of file encountered */ - , AW_TLE_BADFILEFORMAT /* file format identifier not recognized */ - , AW_TLE_BADFILEDATA /* file data not consistent */ - /* Conversion errors */ - , AW_TLE_CANTPALETTIZE /* texture format is palettized; file data is not */ - , AW_TLE_IMAGETOOLARGE /* image size is larger in one or both dimensions than maximum texture size */ - , AW_TLE_CANTRELOAD /* loading a new texture into an existing surface failed because the existing surface is an unsuitable size, etc. */ -} - AW_TL_ERC; - -extern AW_TL_ERC awTlLastErr; -extern HRESULT awTlLastDxErr; -extern DWORD awTlLastWinErr; - -#ifdef NDEBUG - #define AwTlErrorToString ThisIsADebugFunction! /* generate compiler error */ - #define AwDxErrorToString ThisIsADebugFunction! /* generate compiler error */ - #define AwWinErrorToString ThisIsADebugFunction! /* generate compiler error */ -#else /* ! NDEBUG */ - extern char const * AwTlErrorToString(AW_TL_ERC _AWTL_DEFAULTPARM(awTlLastErr)); - extern char const * AwDxErrorToString(HRESULT _AWTL_DEFAULTPARM(awTlLastDxErr)); - extern char const * AwWinErrorToString(DWORD _AWTL_DEFAULTPARM(awTlLastWinErr)); -#endif /* ? NDEBUG */ - -/*********/ -/* Flags */ -/*********/ - -enum -{ - AW_TLF_DEFAULT = 0x00000000U /* no flags set */ - , AW_TLF_TRANSP = 0x00000001U /* src data has transparency */ - , AW_TLF_PREVSRC = 0x00000002U /* in AwRestoreTexture, use previously stored source data flags (AW_TLF_TRANSP only) */ - , AW_TLF_COMPRESS = 0x00000004U /* use ALLOCONLOAD flag */ - , AW_TLF_CHROMAKEY = 0x00000008U /* use chroma keying for transparency when the texture format has an alpha channel */ - , AW_TLF_VIDMEM = 0x00000010U /* use Video memory for surfaces which are not textures */ - , AW_TLF_PREVSRCALL = 0x00000020U /* in AwRestoreTexture, use ALL previously stored flags, except AW_TLF_CHECKLOST and AW_TLF_SKIPNOTLOST */ - , AW_TLF_TEXTURE = 0x00000040U /* in AwCreateSurface, create a surface in the texture format with the texture flag set */ - , AW_TLF_MINSIZE = 0x00000080U /* with the 'a' option, ensure all surfaces/textures created are at least as big as the rectangle specified even if the rect is partially off the image */ - , AW_TLF_CHECKLOST = 0x00000100U /* checks for lost surfaces and calls restore on them */ - , AW_TLF_SKIPNOTLOST = 0x00000200U /* if the above flag also is specified, does not bother trying to restore surfaces which weren't lost */ - - , _AW_TLF_FORCE32BITENUM = 0x0fffffffU /* probably entirely unnecessary */ -}; - -/*********/ -/* Types */ -/*********/ - -/* a callback function */ -typedef int (* AW_TL_PFN_CALLBACK) (void *); - -/* Structure for receiving specific regions of an image in a surface or texture. - * A pointer to an array of thise structures is passed to the AwCreate... - * functions if the 'a' format specifier is used. The fields 'left', 'right', - * 'top' and 'bottom' specify the rectangle to cut out of the image being loaded - * and must be valid. In AwCreateSurface, the 'pSurface' field is used and is a - * pointer to the Direct Draw surface created; in AwCreateTexture, the - * 'pTexture' field is used and is a pointer to the Direct 3D texture created. - * If an error occurs all the pointers in the array will be set to NULL. The - * 'width' and 'height' fields will be filled in with the width and height of - * the surface or texture that is created. If the rectangle specified is - * completely outsided the main image, the width and height will be set to zero, - * and the pointer field will be set to NULL, but this does not constitute an - * error. If the 't' option is used, the pointer fields are assumed to be valid - * textures or surfaces into which to load the new textures or surfaces. If the - * pointer is NULL, the structure is ignored. The pointers will remain unchanged - * even in the event of an error or a rectangle specified outside the main - * image, though the width and height will still be set to zero. - */ -struct AwCreateGraphicRegion -{ - unsigned left, top, right, bottom; /* rectangle to cut from the original image */ - unsigned width, height; /* width and height of the resulting surface or texture */ - union /* DDSurface or D3DTexture pointer depending on the context used */ - { - DDSurface * pSurface; /* Direct Draw Surface object pointer */ - D3DTexture * pTexture; /* Direct 3D Texture object pointer */ - }; -}; - -/* typedef to save typing 'struct' when not using C++ */ -typedef struct AwCreateGraphicRegion AW_CREATEGRAPHICREGION; - -/********************/ -/* Public functions */ -/********************/ - -/* AwSetD3DDevice(DDObject * _ddP, D3DDevice * _d3ddeviceP) - - Description: - Tells the texture loaders about the DirectDraw and - Direct3D setup. You must call this function before - loading any textures, and also every time you change - the DirectDraw or Direct3D device setup. - As of v1.22 this function is overloaded and only - available to C++ programmers. - - Parameters: - _ddP - Pointer to the DirectDraw object obtained from - a call to DirectDrawCreate(). - _d3ddeviceP - Pointer to the Direct3DDevice object obtained - from its GUID which is the lpGuid parameter in - a call to a D3DENUMDEVICESCALLBACK function for - your chosen driver. - - Returns: - AW_TLE_OK if the function completed successfully; - AW_TLE_BADPARMS if the parameters passed to the - function were incorrect - AW_TLE_DXERROR if a DirectX SDK call failed -*/ -#ifdef __cplusplus - extern "C++" AW_TL_ERC AwSetD3DDevice(DDObject * _ddP, D3DDevice * _d3ddeviceP); -#endif - -/* AwSetDDObject(DDObject * _ddP) - AwSetD3DDevice(D3DDevice * _d3ddeviceP) - - Description: - These functions together do what the two parameter - version of AwSetD3DDevice(), above, does. You - needn't call AwSetD3DDevice() if you are only - loading direct draw surfaces. The parameters and - return values are as described above. -*/ - -extern AW_TL_ERC AwSetD3DDevice(D3DDevice * _d3ddeviceP); -extern AW_TL_ERC AwSetDDObject(DDObject * _ddP); - -/* AwSetTextureFormat2(LPDDPIXELFORMAT _ddpfP) - - Description: - Informs the texture loaders of the currently slected - texture format. You must call this function before - loading any textures, and also every time you change - the texture format. - - Parameters: - _ddpfP - Pointer to a DDPIXELFORMAT structure which - describes the texture format. - - Returns: - AW_TLE_OK if the function completed successfully; - AW_TLE_BADPARMS if the parameters passed to the - function were incorrect -*/ -extern AW_TL_ERC AwSetTextureFormat2(LPDDPIXELFORMAT _ddpfP); -#define AwSetTextureFormat(_descP) (AwSetTextureFormat2((_descP) ? &(_descP)->ddpfPixelFormat : NULL)) - -/* AwSetAdditionalTextureFormat2(LPDDPIXELFORMAT _ddpfP, unsigned _maxAlphaBits, int _canDoTransp, unsigned _maxColours) - - Description: - Informs the texture loaders an additional texture - format that should be used in certain cases. After - a call to AwSetTextureFormat, there are no - additional formats. Each additional format that you - want to make available should be set with a call to - this function. When a texture is being loaded, the - additional formats are considered in the order that - they were set (ie. the order in which the calls to - this function were made). For each format - considered, if it could be used for the image and - the image's specification passes the tests for this - format, the format will replace the previously - chosen format (either the base format set by - AwSetTextureFormat or an earlier additional format - whose conditions of use were also met). - - Parameters: - _ddpfP - Pointer to a DDPIXELFORMAT structure which - describes the texture format. - _maxAlphaBits - Specifies that this format should only be used - for images that do not have more bits of alpha - information than this value. - _canDoTransp - If zero, specifies that this format should not - be used for images which have a transparent - colour. - _maxColours - Specifies that this format should only be used - for images that do not contain more unique - colours than this value. If this value is zero, - the format can be used for images with any - number of colours. If this value is non-zero, - this format will not be used for images whose - number of unique colours cannot be determined. - - Returns: - AW_TLE_OK if the function completed successfully; - AW_TLE_NOINIT if AwSetTextureFormat was not - previously called. - AW_TLE_BADPARMS if the parameters passed to the - function were incorrect -*/ -extern AW_TL_ERC AwSetAdditionalTextureFormat2(LPDDPIXELFORMAT _ddpfP, unsigned _maxAlphaBits, int _canDoTransp, unsigned _maxColours); -#define AwSetAdditionalTextureFormat(_descP, _maxAlphaBits, _canDoTransp, _maxColours) (AwSetAdditionalTextureFormat2((_descP) ? &(_descP->ddpfPixelFormat) : NULL,_maxAlphaBits,_canDoTransp,_maxColours)) - -/* AwSetSurfaceFormat2(LPDDPIXELFORMAT _ddpfP) - - Description: - As for AwSetTextureFormat but tells AwCreateSurface() - what format surfaces for blitting should be in -*/ -extern AW_TL_ERC AwSetSurfaceFormat2(LPDDPIXELFORMAT _ddpfP); -#define AwSetSurfaceFormat(_descP) (AwSetSurfaceFormat2((_descP) ? &(_descP)->ddpfPixelFormat : NULL)) - -/* AwGetTextureSize(unsigned * _widthP, unsigned * _heightP, unsigned _width, unsigned _height) - - Description: - Calculates the size required for a texture on the - current driver, given a minimum size required to - hold the proposed image. - - Parameters: - _widthP - Pointer to a variable which will receive the - width required for a Direct 3D texture. - _heightP - Pointer to a variable which will receive the - height. - _width - Minimum width required for the proposed image. - _height - Minimum height required. - - Returns: - AW_TLE_OK if the required Direct 3D texture size was - calculated; - AW_TLE_IMAGETOOLARGE if the driver specifies a - maximum texture size which is less than the size - that would be required to hold an image of the - proposed size; - AW_TLE_NOINIT if driver information was unavailable - because initialization functions weren't called. -*/ -extern AW_TL_ERC AwGetTextureSize(unsigned * _widthP, unsigned * _heightP, unsigned _width, unsigned _height); - -/* AwCreateTexture(char const * _argFormatS, ...) - - Description: - Creates a Direct3D texture for use by the device - renderer. The exact functionality is determined by - the first argument which is a format specifier - string. - - Parameters: - _argFormatS - Pointer to a null terminated string which - specifies the order, types and interpretations - of the other parameters. Each character in the - string corresponds to a parameter passed to the - function, and the parameters are parsed in the - same order as their format specifiers appear in - the string. For clarity, upper case letters are - used to indicate paramters which are pointers to - data that will be filled in by the function, and - lower case letters are used for parameters which - are simply data to be used by the function. - - The following specifiers are permitted: - - s The next argument is of type 'LPCTSTR' and is a - pointer to a ASCII or UNICODE string which is - the filename of an image file to load. - h The next argument is of type 'HANDLE' and is a - Windows file handle with its file pointer set to - the start of an image file's data. - p The next argument is of type 'void const *' and - is a pointer to an image file's data in memory. - r The next argument is of type - 'AW_BACKUPTEXTUREHANDLE' and is used to restore - a previously loaded texture, possibly with the - texture format or Direct3D device having - changed. - x The next argument is of type 'unsigned' and is - the maximum number of bytes that should be read - from a file or memory. If parsing the file data - would cause more bytes to be read than this - value, the function fails and the error is - 'AW_TLE_EOFMET'. This may be useful in - conjunction with format specifier 'm' in order - to prevent a general protection (GP) fault. - N The next argument is of type 'unsigned *' and - points to a variable which will receive the - number of bytes which are actually read from a - file or memory. This value will be filled in - even if the function fails (unless the error is - 'AW_TLE_BADPARMS'). - f The next argument is of type 'unsigned' and can - be any combination of 'AW_TLF_...' flags (above) - which control special functionality. - W The next argument is of type 'unsigned *' and - points to a variable which will receive the - width of the texture that is created. - H The next argument is of type 'unsigned *' and - points to a variable which will receive the - height of the texture that is created. - X The next argument is of type 'unsigned *' and - points to a variable which will receive the - width of the original image. - Y The next argument is of type 'unsigned *' and - points to a variable which will receive the - height of the original image. - B The next argument is of type - 'AW_BACKUPTEXTUREHANDLE *' and points to a - variable which will receive a handle that can - later be used with format specifier 'r' in a - call to this function in order to avoid - reloading from a file an image that has - previously been loaded. This value will be - filled in only if the function succeeds. When - you no longer need this handle, you should - deallocate the memory associated with it by - calling 'AwDestroyBackupTexture()'. - t The next argument is of type 'D3DTexture *' - and is used to load the new texture into an - existing texture surface. The parameter is NOT - Release()d; you should do this yourself. This is - only guaranteed to work if the new texture is of - the same height and pitch as the previous one - and compression is not used on either. - c The next two arguments indicate a callback - function which will be called if a texture cannot - be created due to insufficient video memory. The - idea is to allow the callee to free some video - memory and request further attempts at creating - the texture. The first of the two arguments is of - type AW_TL_PFN_CALLBACK and is a function pointer - to the function that would be called. This - function takes one parameter of type 'void *' - which is an implementation-specific value, and - returns type 'int', which is non-zero if another - attempt at creating the texture should be made. - If the callback function returns zero, then the - texture load will be aborted. The second of the - two arguments is of type 'void *' and is the - implementation-specific value passed to the - callback function. - a The next two arguments indicate an array of - rectangles to cut out of the original image and - create textures for each rectangle. The first of - these two arguments is of type 'unsigned' and is - the size of the array. The second argument is of - type 'AW_CREATEGRAPHICREGION *' and points to an - array of AwCreateGraphicRegion structs, each - indicating a region to cut out of the original - image and create a texture for. In this case, the - function always returns NULL, and you should test - for failure by examining awTlLastErr. The 't' - option, if used, must appear after 'a' in the - format string, and does not correspond to any - parameter, since the texture into which to - reload will be specified for each region in - the array of structures. The 'W' and 'H' options - will be ignored. For more information, see the - definition of this structure above. - - There are some restrictions on parameters: - - Exactly one of 's', 'h', 'p' or 'r' must be - used. - - Neither 'x' nor 'N' may be used with 'r'. - - 'r' cannot be used with 'B'. - - Neither 'W' or 'H' should be used with 'a'. - - Each specifier should be used only once. - - 't' may not appear before 'a'. - - There are no other restriction on the order - that the parameters occur. - - Returns: - A valid D3DTexture * if the function succeeds; - awTlLastErr will also be AW_TLE_OK - NULL if the function fails. awTlLastErr will be - AW_TLE_BADPARMS if the parameters were - incorrect, or any other error code if the - parameters were correct but another error - occurred. -*/ -extern D3DTexture * _AWTL_VARARG AwCreateTexture(char const * _argFormatS, ...); - -/* AwCreateSurface(char const * _argFormatS, ...) - - Description: - As for AwCreateTexture(), but returns a pointer to - a newly created direct draw surface which is not a - texture - - Parameters: - _argFormatS - As AwCreateTexture(), except - - t The next argument is of type 'DDSurface *' - -*/ -extern DDSurface * _AWTL_VARARG AwCreateSurface(char const * _argFormatS, ...); - -/* AwDestroyBackupTexture(AW_BACKUPTEXTUREHANDLE _bH) - - Description: - Deallocates the memory associated with a backup - texture handle, created by a call to - 'AwCreateTexture()' with a 'B' specifier. The handle - cannot be used after this. - - Parameters: - _bH - The handle whose associated memory should be - deallocated. - - Returns: - AW_TLE_OK if the function succeeds. - AW_TLE_BADPARMS if the handle was not valid. -*/ -extern AW_TL_ERC AwDestroyBackupTexture(AW_BACKUPTEXTUREHANDLE _bH); - -/* End Wrappers */ -#ifdef __cplusplus - } -#endif /* __cplusplus */ - -#endif /* ! _INCLUDED_AWTEXLD_H_ */ diff --git a/3dc/win95/awTexLd.hpp b/3dc/win95/awTexLd.hpp deleted file mode 100644 index e47d87e..0000000 --- a/3dc/win95/awTexLd.hpp +++ /dev/null @@ -1,507 +0,0 @@ -#ifndef _INCLUDED_AWTEXLD_HPP_ -#define _INCLUDED_AWTEXLD_HPP_ - -#include "awTexLd.h" -#include "media.hpp" -#include "db.h" -#ifndef DB_COMMA - #define DB_COMMA , -#endif - -// Nasty hack to touch the classes so MSVC++ doesn't discards them. -#ifdef _MSC_VER - extern class AwTlRegisterLoaderClass_AwBmpLoader_187 rlcAwBmpLoader_187; - - extern class AwTlRegisterLoaderClass_AwIffLoader_428 rlcAwIffLoader_428; - extern class AwTlRegisterLoaderClass_AwIffLoader_429 rlcAwIffLoader_429; - extern class AwTlRegisterLoaderClass_AwIffLoader_430 rlcAwIffLoader_430; - - extern class AwTlRegisterLoaderClass_AwPpmLoader_229 rlcAwPpmLoader_229; - extern class AwTlRegisterLoaderClass_AwPgmLoader_230 rlcAwPgmLoader_230; - extern class AwTlRegisterLoaderClass_AwPbmLoader_231 rlcAwPbmLoader_231; - - extern class RegisterChunkClassIlbmBmhdChunk_4 rccIlbmBmhdChunk_4; - extern class RegisterChunkClassIlbmCmapChunk_5 rccIlbmCmapChunk_5; - extern class RegisterChunkClassIlbmBodyChunk_6 rccIlbmBodyChunk_6; - extern class RegisterChunkClassIlbmGrabChunk_7 rccIlbmGrabChunk_7; - -#endif - -namespace AwTl { - - #define CANT_HAPPEN db_msgf1(("AwCreateTexture(): (Line %u) CAN'T HAPPEN!",__LINE__)); - - /*********************************/ - /* Pixel format global structure */ - /*********************************/ - - struct PixelFormat - { - PixelFormat() : validB(false){} - - bool palettizedB : 1; - bool alphaB : 1; - bool validB : 1; - - unsigned bitsPerPixel; - unsigned redLeftShift; - unsigned redRightShift; - unsigned greenLeftShift; - unsigned greenRightShift; - unsigned blueLeftShift; - unsigned blueRightShift; - - DDPIXELFORMAT ddpf; - }; - - // DO SOMTHING ABOUT THIS - extern PixelFormat pixelFormat; - - class CreateTextureParms; - - /********************/ - /* Colour structure */ - /********************/ - - struct Colour - { - BYTE r,g,b; - - class ConvNonTransp - { - public: - static inline unsigned DoConv (Colour const * _colP, Colour const * = NULL db_code1(DB_COMMA unsigned = 0)) - { - return - static_cast<unsigned>(_colP->r)>>pixelFormat.redRightShift<<pixelFormat.redLeftShift - |static_cast<unsigned>(_colP->g)>>pixelFormat.greenRightShift<<pixelFormat.greenLeftShift - |static_cast<unsigned>(_colP->b)>>pixelFormat.blueRightShift<<pixelFormat.blueLeftShift - |pixelFormat.ddpf.dwRGBAlphaBitMask - ; - } - static inline unsigned DoConv(BYTE const * _colP, Colour const * _paletteP db_code1(DB_COMMA unsigned _paletteSize)) - { - db_assert1(_paletteP); - db_onlyassert1(*_colP < _paletteSize); - return DoConv(&_paletteP[*_colP]); - } - }; - - class ConvTransp - { - private: - static inline unsigned MakeNonTranspCol(Colour const * _colP) - { - unsigned rv = ConvNonTransp::DoConv(_colP); - if (rv) return rv; - // make one of r,g or b in the output == 1, choose the one which is closest to the input - unsigned rdiff = (1<<pixelFormat.redRightShift) - _colP->r; - unsigned bdiff = (1<<pixelFormat.blueRightShift) - _colP->b; - unsigned gdiff = (1<<pixelFormat.greenRightShift) - _colP->g; - if (bdiff<=rdiff && bdiff<=gdiff) - return 1<<pixelFormat.blueLeftShift; - else if (rdiff<=gdiff) - return 1<<pixelFormat.redLeftShift; - else - return 1<<pixelFormat.greenLeftShift; - } - public: - static inline unsigned DoConv (Colour const * _colP, Colour const * = NULL db_code1(DB_COMMA unsigned = 0)) - { - if (!_colP->b && !_colP->r && !_colP->g) - //return pixelFormat.alphaB ? pixelFormat.ddsd.ddpfPixelFormat.dwRBitMask|pixelFormat.ddsd.ddpfPixelFormat.dwGBitMask|pixelFormat.ddsd.ddpfPixelFormat.dwBBitMask : 0; - return 0; - else - return MakeNonTranspCol(_colP); - } - static inline unsigned DoConv(BYTE const * _colP, Colour const * _paletteP db_code1(DB_COMMA unsigned _paletteSize)) - { - db_assert1(_paletteP); - db_onlyassert1(*_colP < _paletteSize); - if (!*_colP) - //return pixelFormat.alphaB ? pixelFormat.ddsd.ddpfPixelFormat.dwRBitMask|pixelFormat.ddsd.ddpfPixelFormat.dwGBitMask|pixelFormat.ddsd.ddpfPixelFormat.dwBBitMask : 0; - return 0; - else - return MakeNonTranspCol(&_paletteP[*_colP]); - } - }; - - class ConvNull - { - public: - static inline unsigned DoConv (BYTE const * _colP, Colour const * db_code1(DB_COMMA unsigned = 0)) - { - db_assert1(pixelFormat.palettizedB); - return *_colP; - } - }; - }; - - /*****************/ - /* Pointer union */ - /*****************/ - - union SurfUnion - { - D3DTexture * textureP; - DDSurface * surfaceP; - void * voidP; - SurfUnion(){} - SurfUnion(D3DTexture * p) : textureP(p){} - SurfUnion(DDSurface * p) : surfaceP(p){} - }; - - union PtrUnion - { - void * voidP; - char * charP; - signed char * scharP; - unsigned char * ucharP; - BYTE * byteP; - short * shortP; - unsigned short * ushortP; - WORD * wordP; - signed * intP; - unsigned * uintP; - DWORD * dwordP; - long * longP; - unsigned long * ulongP; - Colour * colourP; - - inline PtrUnion(){} - inline PtrUnion(void * _voidP):voidP(_voidP){} - inline operator void * () const { return voidP; } - }; - - union PtrUnionConst - { - void const * voidP; - char const * charP; - signed char const * scharP; - unsigned char const * ucharP; - BYTE const * byteP; - short const * shortP; - unsigned short const * ushortP; - WORD const * wordP; - signed const * intP; - unsigned const * uintP; - DWORD const * dwordP; - long const * longP; - unsigned long const * ulongP; - Colour const * colourP; - - inline PtrUnionConst(){} - inline PtrUnionConst(void const * _voidP):voidP(_voidP){} - inline PtrUnionConst(PtrUnion _uP):voidP(_uP.voidP){} - inline operator void const * () const { return voidP; } - }; - - /***************************************/ - /* Generic copying to surface function */ - /***************************************/ - - template<class CONVERT, class SRCTYPE> - class GenericConvertRow - { - public: - static void Do (PtrUnion _dstRowP, unsigned _dstWidth, SRCTYPE const * _srcRowP, unsigned _srcWidth, Colour const * _paletteP = NULL db_code1(DB_COMMA unsigned _paletteSize = 0)); - }; - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4701) -#endif - - template<class CONVERT, class SRCTYPE> - void GenericConvertRow<CONVERT, SRCTYPE>::Do (PtrUnion _dstRowP, unsigned _dstWidth, SRCTYPE const * _srcRowP, unsigned _srcWidth, Colour const * _paletteP db_code1(DB_COMMA unsigned _paletteSize)) - { - switch (pixelFormat.bitsPerPixel) - { - default: - CANT_HAPPEN - case 16: - { - db_assert1(!pixelFormat.palettizedB); - for (unsigned colcount = _srcWidth; colcount; --colcount) - { - *_dstRowP.wordP++ = static_cast<WORD>(CONVERT::DoConv(_srcRowP++,_paletteP db_code1(DB_COMMA _paletteSize))); - } - if (_srcWidth<_dstWidth) - *_dstRowP.wordP = static_cast<WORD>(CONVERT::DoConv(_srcRowP-1,_paletteP db_code1(DB_COMMA _paletteSize))); - break; - } - case 24: - { - db_assert1(!pixelFormat.palettizedB); - union { DWORD dw; BYTE b[3]; } u; - for (unsigned colcount = _srcWidth; colcount; --colcount) - { - u.dw = static_cast<DWORD>(CONVERT::DoConv(_srcRowP++,_paletteP db_code1(DB_COMMA _paletteSize))); - *_dstRowP.byteP++ = u.b[0]; - *_dstRowP.byteP++ = u.b[1]; - *_dstRowP.byteP++ = u.b[2]; - } - if (_srcWidth<_dstWidth) - { - *_dstRowP.byteP++ = u.b[0]; - *_dstRowP.byteP++ = u.b[1]; - *_dstRowP.byteP = u.b[2]; - } - } - case 32: - { - db_assert1(!pixelFormat.palettizedB); - for (unsigned colcount = _srcWidth; colcount; --colcount) - { - *_dstRowP.dwordP++ = static_cast<DWORD>(CONVERT::DoConv(_srcRowP++,_paletteP db_code1(DB_COMMA _paletteSize))); - } - if (_srcWidth<_dstWidth) - *_dstRowP.dwordP = static_cast<DWORD>(CONVERT::DoConv(_srcRowP-1,_paletteP db_code1(DB_COMMA _paletteSize))); - break; - } - case 8: - { - for (unsigned colcount = _srcWidth; colcount; --colcount) - { - *_dstRowP.byteP++ = static_cast<BYTE>(CONVERT::DoConv(_srcRowP++,_paletteP db_code1(DB_COMMA _paletteSize))); - } - if (_srcWidth<_dstWidth) - *_dstRowP.byteP = static_cast<BYTE>(CONVERT::DoConv(_srcRowP-1,_paletteP db_code1(DB_COMMA _paletteSize))); - break; - } - case 1: - case 2: - db_assert1(pixelFormat.palettizedB); - case 4: - { - unsigned shift=0; - unsigned val; - --_dstRowP.byteP; // decrement here because we increment before the first write - for (unsigned colcount = _srcWidth; colcount; --colcount) - { - val = CONVERT::DoConv(_srcRowP++,_paletteP db_code1(DB_COMMA _paletteSize)); - if (!shift) - *++_dstRowP.byteP = static_cast<BYTE>(val); - else - *_dstRowP.byteP |= static_cast<BYTE>(val<<shift); - shift += pixelFormat.bitsPerPixel; - shift &= 7; - } - if (_srcWidth<_dstWidth) - { - if (!shift) - *++_dstRowP.byteP = static_cast<BYTE>(val); - else - *_dstRowP.byteP |= static_cast<BYTE>(val<<shift); - } - break; - } - } - } - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - - // reference counting support - class RefCntObj - { - public: - unsigned AddRef() { return ++m_nRefCnt; } - unsigned Release() { if (0==(--m_nRefCnt)) { delete this; return 0;} else return m_nRefCnt; } - protected: - virtual ~RefCntObj(){ - #ifndef NDEBUG - DbForget(this); - #endif - } - RefCntObj() : m_nRefCnt(1){ - #ifndef NDEBUG - DbRemember(this); - #endif - } - RefCntObj(RefCntObj const &) : m_nRefCnt(1){ - #ifndef NDEBUG - DbRemember(this); - #endif - } - RefCntObj & operator = (RefCntObj const &){ return *this;} - private: - unsigned m_nRefCnt; - - #ifndef NDEBUG - friend void DbRemember(RefCntObj * pObj); - friend void DbForget(RefCntObj * pObj); - friend class AllocList; - #endif - }; - - SurfUnion LoadFromParams(CreateTextureParms *); - -} // namespace AwTl - -struct AwBackupTexture : public AwTl::RefCntObj -{ - public: - AwTl::SurfUnion Restore(AwTl::CreateTextureParms const & rParams); - protected: - AwTl::SurfUnion CreateTexture(AwTl::CreateTextureParms const & rParams); - - void ChoosePixelFormat(AwTl::CreateTextureParms const & rParams); - - virtual ~AwBackupTexture(){} - - // return the number of unique colours in the image or zero if this cannot be determined - virtual unsigned GetNumColours() = 0; - - // return the smallest palette size that is available for the image - virtual unsigned GetMinPaletteSize() = 0; - - // return true if the image has a single transparent colour - virtual bool HasTransparentMask(bool bDefault); - - // called when a backup texture is about to be used for restoring, but after the above two functions have been called - virtual void OnBeginRestoring(unsigned nMaxPaletteSize); - - virtual AwTl::Colour * GetPalette() = 0; - - virtual bool AreRowsReversed(); - - virtual AwTl::PtrUnion GetRowPtr(unsigned nRow) = 0; - - virtual void LoadNextRow(AwTl::PtrUnion pRow) = 0; - - virtual void ConvertRow(AwTl::PtrUnion pDest, unsigned nDestWidth, AwTl::PtrUnionConst pSrc, unsigned nSrcOffset, unsigned nSrcWidth, AwTl::Colour * pPalette db_code1(DB_COMMA unsigned nPaletteSize)); - - virtual DWORD GetTransparentColour(); - - virtual void OnFinishRestoring(bool bSuccess); - - // metrics - unsigned m_nWidth; - unsigned m_nHeight; - unsigned m_nPaletteSize; // 0 inicates no palette - - unsigned m_fFlags; - - private: - bool m_bTranspMask; - - friend AwTl::SurfUnion AwTl::LoadFromParams(AwTl::CreateTextureParms *); -}; - -namespace AwTl { - - class TypicalBackupTexture : public ::AwBackupTexture - { - public: - TypicalBackupTexture(AwBackupTexture const & rBase, PtrUnion * ppPixMap, Colour * pPalette) - : AwBackupTexture(rBase) - , m_ppPixMap(ppPixMap) - , m_pPalette(pPalette) - {} - - virtual ~TypicalBackupTexture() - { - if (m_pPalette) - { - delete[] m_pPalette; - if (m_ppPixMap) - { - delete[] m_ppPixMap->byteP; - delete[] m_ppPixMap; - } - } - else - { - if (m_ppPixMap) - { - delete[] m_ppPixMap->colourP; - delete[] m_ppPixMap; - } - } - } - - virtual Colour * GetPalette(); - - virtual PtrUnion GetRowPtr(unsigned nRow); - - virtual void LoadNextRow(PtrUnion pRow); - - // note: the palette size member must be set in - // LoadHeaderInfo() for these functions to work correctly - virtual unsigned GetNumColours(); - - virtual unsigned GetMinPaletteSize(); - - private: - PtrUnion * m_ppPixMap; - Colour * m_pPalette; - }; - - class TexFileLoader : public AwBackupTexture - { - public: - SurfUnion Load(MediaMedium * pMedium, CreateTextureParms const & rParams); - - protected: - // standard constructor - // & destructor - - // Interface Functions. Each overridden version should set awTlLastErr - // when an error occurs - - // Called to set the width and height members; the palette size member can also be safely set at this point. - // Neither the width height or palette size members need actually be set until AllocateBuffers returns - virtual void LoadHeaderInfo(MediaMedium * pMedium) = 0; - - // should ensure that the palette size is set - virtual void AllocateBuffers(bool bWantBackup, unsigned nMaxPaletteSize) = 0; - - virtual void OnFinishLoading(bool bSuccess); - - virtual AwBackupTexture * CreateBackupTexture() = 0; - }; - - class TypicalTexFileLoader : public TexFileLoader - { - protected: - TypicalTexFileLoader() : m_pRowBuf(NULL), m_ppPixMap(NULL), m_pPalette(NULL) {} - - virtual ~TypicalTexFileLoader(); - - virtual unsigned GetNumColours(); - - virtual unsigned GetMinPaletteSize(); - - virtual void AllocateBuffers(bool bWantBackup, unsigned nMaxPaletteSize); - - virtual PtrUnion GetRowPtr(unsigned nRow); - - virtual AwBackupTexture * CreateBackupTexture(); - - Colour * m_pPalette; - private: - PtrUnion * m_ppPixMap; - - PtrUnion m_pRowBuf; - }; - - extern void RegisterLoader(char const * pszMagic, AwTl::TexFileLoader * (* pfnCreate) () ); - -} // namespace AwTl - -#define AWTEXLD_IMPLEMENT_DYNCREATE(pszMagic, tokenClassName) _AWTEXLD_IMPLEMENT_DYNCREATE_LINE_EX(pszMagic,tokenClassName,__LINE__) -#define _AWTEXLD_IMPLEMENT_DYNCREATE_LINE_EX(pszMagic, tokenClassName, nLine) _AWTEXLD_IMPLEMENT_DYNCREATE_LINE(pszMagic,tokenClassName,nLine) - -#define _AWTEXLD_IMPLEMENT_DYNCREATE_LINE(pszMagic,tokenClassName,nLine) \ - AwTl::TexFileLoader * AwTlCreateClassObject ##_## tokenClassName ##_## nLine () { \ - return new tokenClassName; \ - } \ - class AwTlRegisterLoaderClass ##_## tokenClassName ##_## nLine { \ - public: AwTlRegisterLoaderClass ##_## tokenClassName ##_## nLine () { \ - AwTl::RegisterLoader(pszMagic, AwTlCreateClassObject ##_## tokenClassName ##_## nLine); \ - } \ - } rlc ## tokenClassName ##_## nLine; - -#endif // ! _INCLUDED_AWTEXLD_HPP_ diff --git a/3dc/win95/bink.c b/3dc/win95/bink.c deleted file mode 100644 index 6050fbe..0000000 --- a/3dc/win95/bink.c +++ /dev/null @@ -1,208 +0,0 @@ -/* Bink! player, KJL 99/4/30 */ -#include "bink.h" - -#include "3dc.h" -#include "d3_func.h" - -#define UseLocalAssert 1 -#include "ourasert.h" - -extern char *ScreenBuffer; -extern LPDIRECTSOUND DSObject; -extern int GotAnyKey; -extern int IntroOutroMoviesAreActive; -extern DDPIXELFORMAT DisplayPixelFormat; - -extern void DirectReadKeyboard(void); - - -static int BinkSurfaceType; - -void PlayBinkedFMV(char *filenamePtr) -{ - BINK* binkHandle; - int playing = 1; - - if (!IntroOutroMoviesAreActive) return; - -// if (!IntroOutroMoviesAreActive) return; - BinkSurfaceType = GetBinkPixelFormat(); - - /* skip FMV if surface type not supported */ - if (BinkSurfaceType == -1) return; - - /* use Direct sound */ - BinkSoundUseDirectSound(DSObject); - /* open smacker file */ - binkHandle = BinkOpen(filenamePtr,0); - if (!binkHandle) - { - char message[100]; - sprintf(message,"Unable to access file: %s\n",filenamePtr); - MessageBox(NULL,message,"AvP Error",MB_OK+MB_SYSTEMMODAL); - exit(0x111); - return; - } - - while(playing) - { - CheckForWindowsMessages(); - if (!BinkWait(binkHandle)) - playing = NextBinkFrame(binkHandle); - - FlipBuffers(); - DirectReadKeyboard(); - if (GotAnyKey) playing = 0; - } - /* close file */ - BinkClose(binkHandle); -} - -static int NextBinkFrame(BINK *binkHandle) -{ - /* unpack frame */ - BinkDoFrame(binkHandle); - - BinkCopyToBuffer(binkHandle,(void*)ScreenBuffer,640*2,480,(640-binkHandle->Width)/2,(480-binkHandle->Height)/2,BinkSurfaceType); - - //BinkToBuffer(binkHandle,(640-binkHandle->Width)/2,(480-binkHandle->Height)/2,640*2,480,(void*)ScreenBuffer,GetBinkPixelFormat(&DisplayPixelFormat)); - - /* are we at the last frame yet? */ - if ((binkHandle->FrameNum==(binkHandle->Frames-1))) return 0; - - /* next frame, please */ - BinkNextFrame(binkHandle); - return 1; -} - -static int GetBinkPixelFormat(void) -{ - if( (DisplayPixelFormat.dwFlags & DDPF_RGB) && !(DisplayPixelFormat.dwFlags & DDPF_PALETTEINDEXED8) ) - { - int m; - int redShift=0; - int greenShift=0; - int blueShift=0; - - m = DisplayPixelFormat.dwRBitMask; - LOCALASSERT(m); - while(!(m&1)) m>>=1; - while(m&1) - { - m>>=1; - redShift++; - } - - m = DisplayPixelFormat.dwGBitMask; - LOCALASSERT(m); - while(!(m&1)) m>>=1; - while(m&1) - { - m>>=1; - greenShift++; - } - - m = DisplayPixelFormat.dwBBitMask; - LOCALASSERT(m); - while(!(m&1)) m>>=1; - while(m&1) - { - m>>=1; - blueShift++; - } - - if(redShift == 5) - { - if (greenShift == 5) - { - if (blueShift == 5) - { - return BINKSURFACE555; - } - else // not supported - { - return -1; - } - } - else if (greenShift == 6) - { - if (blueShift == 5) - { - return BINKSURFACE565; - } - else // not supported - { - return -1; - } - } - } - else if (redShift == 6) - { - if (greenShift == 5) - { - if (blueShift == 5) - { - return BINKSURFACE655; - } - else // not supported - { - return -1; - } - } - else if (greenShift == 6) - { - if (blueShift == 4) - { - return BINKSURFACE664; - } - else // not supported - { - return -1; - } - } - } - else - { - return -1; - } - } - - return -1; -} - -BINK *MenuBackground = 0; - -extern void StartMenuBackgroundBink(void) -{ - char *filenamePtr = "fmvs/menubackground.bik";//newer.bik"; - - /* open smacker file */ - MenuBackground = BinkOpen(filenamePtr,0); - BinkSurfaceType = GetBinkPixelFormat(); - BinkDoFrame(MenuBackground); -} - -extern int PlayMenuBackgroundBink(void) -{ - int newframe = 0; - if(!MenuBackground) return 0; - - if (!BinkWait(MenuBackground)&&IntroOutroMoviesAreActive) newframe=1; - - if(newframe) BinkDoFrame(MenuBackground); - - BinkCopyToBuffer(MenuBackground,(void*)ScreenBuffer,640*2,480,(640-MenuBackground->Width)/2,(480-MenuBackground->Height)/2,BinkSurfaceType|BINKSURFACECOPYALL); - - /* next frame, please */ - if(newframe)BinkNextFrame(MenuBackground); - - return 1; -} -extern void EndMenuBackgroundBink(void) -{ - if(!MenuBackground) return; - - BinkClose(MenuBackground); - MenuBackground = 0; -} - diff --git a/3dc/win95/bink.h b/3dc/win95/bink.h deleted file mode 100644 index 2d5d29f..0000000 --- a/3dc/win95/bink.h +++ /dev/null @@ -1,488 +0,0 @@ -#ifndef BINKH -#define BINKH - -#define BINKVERSION "0.8e" - -#ifndef __RADRES__ - -#include "bink_rad.h" - -RADDEFSTART - -typedef struct BINK PTR4* HBINK; - -typedef s32 (RADLINK PTR4* BINKIOOPEN) (struct BINKIO PTR4* Bnkio, const char PTR4 *name, u32 flags); -typedef u32 (RADLINK PTR4* BINKIOREADHEADER) (struct BINKIO PTR4* Bnkio, s32 Offset, void PTR4* Dest,u32 Size); -typedef u32 (RADLINK PTR4* BINKIOREADFRAME) (struct BINKIO PTR4* Bnkio, u32 Framenum,s32 origofs,void PTR4* dest,u32 size); -typedef u32 (RADLINK PTR4* BINKIOGETBUFFERSIZE)(struct BINKIO PTR4* Bnkio, u32 Size); -typedef void (RADLINK PTR4* BINKIOSETINFO) (struct BINKIO PTR4* Bnkio, void PTR4* Buf,u32 Size,u32 FileSize,u32 simulate); -typedef u32 (RADLINK PTR4* BINKIOIDLE) (struct BINKIO PTR4* Bnkio); -typedef void (RADLINK PTR4* BINKIOCLOSE) (struct BINKIO PTR4* Bnkio); - -typedef struct BINKIO { - BINKIOREADHEADER ReadHeader; - BINKIOREADFRAME ReadFrame; - BINKIOGETBUFFERSIZE GetBufferSize; - BINKIOSETINFO SetInfo; - BINKIOIDLE Idle; - BINKIOCLOSE Close; - HBINK bink; - volatile u32 DoingARead; - volatile u32 BytesRead; - volatile u32 TotalTime; - volatile u32 ForegroundTime; - volatile u32 BufSize; - volatile u32 BufHighUsed; - volatile u32 CurBufSize; - volatile u32 CurBufUsed; - volatile u8 iodata[128]; -} BINKIO; - -typedef s32 (RADLINK PTR4* BINKSNDOPEN) (struct BINKSND PTR4* BnkSnd, u32 freq, s32 bits, s32 chans, u32 flags, HBINK bink); -typedef void (RADLINK PTR4* BINKSNDRESET) (struct BINKSND PTR4* BnkSnd); -typedef s32 (RADLINK PTR4* BINKSNDREADY) (struct BINKSND PTR4* BnkSnd); -typedef s32 (RADLINK PTR4* BINKSNDLOCK) (struct BINKSND PTR4* BnkSnd, u8 PTR4* PTR4* addr, u32 PTR4* len); -typedef s32 (RADLINK PTR4* BINKSNDUNLOCK) (struct BINKSND PTR4* BnkSnd, u32 filled); -typedef void (RADLINK PTR4* BINKSNDVOLUME) (struct BINKSND PTR4* BnkSnd, s32 volume); -typedef void (RADLINK PTR4* BINKSNDPAN) (struct BINKSND PTR4* BnkSnd, s32 pan); -typedef s32 (RADLINK PTR4* BINKSNDOFF) (struct BINKSND PTR4* BnkSnd, s32 status); -typedef s32 (RADLINK PTR4* BINKSNDPAUSE) (struct BINKSND PTR4* BnkSnd, s32 status); -typedef void (RADLINK PTR4* BINKSNDCLOSE) (struct BINKSND PTR4* BnkSnd); - -typedef BINKSNDOPEN (RADLINK PTR4* BINKSNDSYSOPEN) (u32 param); - -typedef struct BINKSND { - BINKSNDRESET SetParam; - BINKSNDRESET Reset; - BINKSNDREADY Ready; - BINKSNDLOCK Lock; - BINKSNDUNLOCK Unlock; - BINKSNDVOLUME Volume; - BINKSNDPAN Pan; - BINKSNDPAUSE Pause; - BINKSNDOFF Off; - BINKSNDCLOSE Close; - u32 BestSizeIn16; - u32 SoundDroppedOut; - u32 freq; - s32 bits,chans; - u8 snddata[128]; -} BINKSND; - -typedef struct BINKRECT { - s32 Left,Top,Width,Height; -} BINKRECT; - -#define BINKMAXDIRTYRECTS 8 - -typedef struct BUNDLEPOINTERS { - void* typeptr; - void* type16ptr; - void* colorptr; - void* bits2ptr; - void* motionXptr; - void* motionYptr; - void* dctptr; - void* mdctptr; - void* patptr; -} BUNDLEPOINTERS; - - -typedef struct BINK { - u32 Width; // Width (1 based, 640 for example) - u32 Height; // Height (1 based, 480 for example) - u32 StretchWidth; // Default stretch width - u32 StretchHeight; // Default stretch height (used for Y double) - u32 Frames; // Number of frames (1 based, 100 = 100 frames) - u32 FrameNum; // Frame to *be* displayed (1 based) - u32 LastFrameNum; // Last frame decompressed or skipped (1 based) - - u32 FrameRate; // Frame Rate Numerator - u32 FrameRateDiv; // Frame Rate Divisor (frame rate=numerator/divisor) - - u32 ReadError; // Non-zero if a read error has ocurred - u32 OpenFlags; // flags used on open - u32 BinkType; // Bink flags - - u32 Size; // size of file - u32 FrameSize; // The current frame's size in bytes - u32 SndSize; // The current frame sound tracks' size in bytes - - BINKRECT FrameRects[BINKMAXDIRTYRECTS];// Dirty rects from BinkGetRects - s32 NumRects; - - u32 YPlaneNum; // which YPlane is current - void PTR4* YPlane[2]; // pointer to the uncompressed Y (Cr and Cr follow) - u32 YWidth; // widths and heights of the video planes - u32 YHeight; - u32 UVWidth; - u32 UVHeight; - - void PTR4* MaskPlane; // pointer to the mask plane (Ywidth/16*Yheight/16) - u32 MaskPitch; // Mask Pitch - u32 MaskLength; // total length of the mask plane - - u32 LargestFrameSize; // Largest frame size - u32 InternalFrames; // how many frames were potentially compressed - - s32 NumTracks; // how many tracks - - u32 Highest1SecRate; // Highest 1 sec data rate - u32 Highest1SecFrame; // Highest 1 sec data rate starting frame - - s32 Paused; // is the bink movie paused? - - u32 BackgroundThread; // handle to background thread - - // everything below is for internal Bink use - - void PTR4* compframe; // compressed frame data - void PTR4* preloadptr; // preloaded compressed frame data - u32* frameoffsets; // offsets of each of the frames - - BINKIO bio; // IO structure - u8 PTR4* ioptr; // io buffer ptr - u32 iosize; // io buffer size - u32 decompheight; // height not include interlacing - - s32 trackindex; // track index - u32 PTR4* tracksizes; // largest single frame of track - u32 PTR4* tracktypes; // type of each sound track - s32 PTR4* trackIDs; // external track numbers - - u32 numrects; // number of rects from BinkGetRects - - u32 playedframes; // how many frames have we played - u32 firstframetime; // very first frame start - u32 startframetime; // start frame start - u32 startblittime; // start of blit period - u32 startsynctime; // start of synched time - u32 startsyncframe; // frame of startsynctime - u32 twoframestime; // two frames worth of time - u32 entireframetime; // entire frame time - - u32 slowestframetime; // slowest frame in ms - u32 slowestframe; // slowest frame number - u32 slowest2frametime; // second slowest frame in ms - u32 slowest2frame; // second slowest frame - - u32 soundon; // sound turned on? - u32 videoon; // video turned on? - - u32 totalmem; // total memory used - u32 timedecomp; // total time decompressing - u32 timeblit; // total time blitting - u32 timeopen; // total open time - - u32 fileframerate; // frame rate originally in the file - u32 fileframeratediv; - - u32 threadcontrol; // controls the background reading thread - - u32 runtimeframes; // max frames for runtime analysis - u32 runtimemoveamt; // bytes to move each frame - u32 PTR4* rtframetimes; // start times for runtime frames - u32 PTR4* rtdecomptimes; // decompress times for runtime frames - u32 PTR4* rtblittimes; // blit times for runtime frames - u32 PTR4* rtreadtimes; // read times for runtime frames - - u32 lastdecompframe; // last frame number decompressed - - u32 sndbufsize; // sound buffer size - u8 PTR4* sndbuf; // sound buffer - u8 PTR4* sndend; // end of the sound buffer - u8 PTR4* sndwritepos; // current write position - u8 PTR4* sndreadpos; // current read position - u32 sndcomp; // sound compression handle - u32 sndamt; // amount of sound currently in the buffer - volatile u32 sndreenter; // re-entrancy check on the sound - u32 sndconvert8; // convert back to 8-bit sound at runtime - BINKSND bsnd; // SND structure - u32 skippedlastblit; // skipped last frame? - u32 skippedblits; // how many blits were skipped - u32 soundskips; // number of sound stops - - BUNDLEPOINTERS bunp; // pointers to internal temporary memory -} BINK; - - -typedef struct BINKSUMMARY { - u32 Width; // Width of frames - u32 Height; // Height of frames - u32 TotalTime; // total time (ms) - u32 FileFrameRate; // frame rate - u32 FileFrameRateDiv; // frame rate divisor - u32 FrameRate; // frame rate - u32 FrameRateDiv; // frame rate divisor - u32 TotalOpenTime; // Time to open and prepare for decompression - u32 TotalFrames; // Total Frames - u32 TotalPlayedFrames; // Total Frames played - u32 SkippedFrames; // Total number of skipped frames - u32 SkippedBlits; // Total number of skipped blits - u32 SoundSkips; // Total number of sound skips - u32 TotalBlitTime; // Total time spent blitting - u32 TotalReadTime; // Total time spent reading - u32 TotalDecompTime; // Total time spent decompressing - u32 TotalBackReadTime; // Total time spent reading in background - u32 TotalReadSpeed; // Total io speed (bytes/second) - u32 SlowestFrameTime; // Slowest single frame time (ms) - u32 Slowest2FrameTime; // Second slowest single frame time (ms) - u32 SlowestFrameNum; // Slowest single frame number - u32 Slowest2FrameNum; // Second slowest single frame number - u32 AverageDataRate; // Average data rate of the movie - u32 AverageFrameSize; // Average size of the frame - u32 HighestMemAmount; // Highest amount of memory allocated - u32 TotalIOMemory; // Total extra memory allocated - u32 HighestIOUsed; // Highest extra memory actually used - u32 Highest1SecRate; // Highest 1 second rate - u32 Highest1SecFrame; // Highest 1 second start frame -} BINKSUMMARY; - - -typedef struct BINKREALTIME { - u32 FrameNum; // Current frame number - u32 FrameRate; // frame rate - u32 FrameRateDiv; // frame rate divisor - u32 Frames; // frames in this sample period - u32 FramesTime; // time is ms for these frames - u32 FramesDecompTime; // time decompressing these frames - u32 FramesReadTime; // time reading these frames - u32 FramesBlitTime; // time blitting these frames - u32 ReadBufferSize; // size of read buffer - u32 ReadBufferUsed; // amount of read buffer currently used - u32 FramesDataRate; // data rate for these frames -} BINKREALTIME; - -#define BINKMARKER 'fKIB' - -typedef struct BINKHDR { - u32 Marker; // BNKa - u32 Size; // size of the file-8 - u32 Frames; // Number of frames (1 based, 100 = 100 frames) - u32 LargestFrameSize; // Size in bytes of largest frame - u32 InternalFrames; // Number of internal frames - - u32 Width; // Width (1 based, 640 for example) - u32 Height; // Height (1 based, 480 for example) - u32 FrameRate; // frame rate - u32 FrameRateDiv; // frame rate divisor (framerate/frameratediv=fps) - - u32 Flags; // height compression options - u32 NumTracks; // number of tracks -} BINKHDR; - - -//======================================================================= -#define BINKFRAMERATE 0x00080000L // Override fr (call BinkFrameRate first) -#define BINKPRELOADALL 0x00100000L // Preload the entire animation -#define BINKSNDTRACK 0x00200000L // Set the track number to play -#define BINKNOSKIP 0x00400000L // Don't skip frames if falling behind -#define BINKNOFILLIOBUF 0x00800000L // Fill the IO buffer in SmackOpen -#define BINKSIMULATE 0x01000000L // Simulate the speed (call BinkSim first) -#define BINKFILEHANDLE 0x02000000L // Use when passing in a file handle -#define BINKIOSIZE 0x04000000L // Set an io size (call BinkIOSize first) -#define BINKIOPROCESSOR 0x08000000L // Set an io processor (call BinkIO first) -#define BINKFROMMEMORY 0x40000000L // Use when passing in a pointer to the file -#define BINKNOTHREADEDIO 0x80000000L // Don't use a background thread for IO - -#define BINKSURFACEYINTERLACE 0x20000000L // Force interleaving Y scaling -#define BINKSURFACEYDOUBLE 0x10000000L // Force doubling Y scaling -#define BINKSURFACEYFORCENONE 0x30000000L // Force Y scaling off - -#define BINKSURFACEFAST 0x00000000L -#define BINKSURFACESLOW 0x80000000L -#define BINKSURFACEDIRECT 0x40000000L - -#define BINKSURFACEFLIPPED 0x08000000L -#define BINKSURFACECOPYALL 0x04000000L // copy all pixels (not just changed) -#define BINKSURFACENOSKIP 0x01000000L // don't skip the blit if behind in sound - -#define BINKSURFACE24 0 -#define BINKSURFACE32 1 -#define BINKSURFACE555 2 -#define BINKSURFACE565 3 -#define BINKSURFACE655 4 -#define BINKSURFACE664 5 -#define BINKSURFACE8P 6 -#define BINKSURFACEYUY2 7 -#define BINKSURFACEUYVY 8 -#define BINKSURFACEYV12 9 -#define BINKSURFACEMASK 15 - -#define BINKGOTOQUICK 1 - -#define BINKGETKEYPREVIOUS 0 -#define BINKGETKEYNEXT 1 -#define BINKGETKEYCLOSEST 2 -#define BINKGETKEYNOTEQUAL 128 - -//======================================================================= - -RADEXPFUNC void PTR4* RADEXPLINK BinkLogoAddress(void); - -RADEXPFUNC void RADEXPLINK BinkSetError(const char PTR4* err); -RADEXPFUNC char PTR4* RADEXPLINK BinkGetError(void); - -RADEXPFUNC HBINK RADEXPLINK BinkOpen(const char PTR4* name,u32 flags); - -#ifdef __RADMAC__ - #include <files.h> - - RADEXPFUNC HBINK RADEXPLINK BinkMacOpen(FSSpec* fsp,u32 flags); -#endif - -RADEXPFUNC u32 RADEXPLINK BinkDoFrame(HBINK bnk); -RADEXPFUNC void RADEXPLINK BinkNextFrame(HBINK bnk); -RADEXPFUNC s32 RADEXPLINK BinkWait(HBINK bnk); -RADEXPFUNC void RADEXPLINK BinkClose(HBINK bnk); -RADEXPFUNC s32 RADEXPLINK BinkPause(HBINK bnk,s32 pause); -RADEXPFUNC s32 RADEXPLINK BinkCopyToBuffer(HBINK bnk,void* dest,u32 destpitch,u32 destheight,u32 destx,u32 desty,u32 flags); -RADEXPFUNC s32 RADEXPLINK BinkGetRects(HBINK bnk,u32 surfacetype); -RADEXPFUNC void RADEXPLINK BinkGoto(HBINK bnk,u32 frame,s32 flags); // use 1 for the first frame -RADEXPFUNC u32 RADEXPLINK BinkGetKeyFrame(HBINK bnk,u32 frame,s32 flags); - -RADEXPFUNC u32 RADEXPLINK BinkSetVideoOnOff(HBINK bnk,s32 onoff); -RADEXPFUNC u32 RADEXPLINK BinkSetSoundOnOff(HBINK bnk,s32 onoff); -RADEXPFUNC void RADEXPLINK BinkSetVolume(HBINK bnk,s32 volume); -RADEXPFUNC void RADEXPLINK BinkSetPan(HBINK bnk,s32 pan); -RADEXPFUNC void RADEXPLINK BinkService(HBINK bink); - -RADEXPFUNC u32 RADEXPLINK BinkGetTrackType(HBINK bnk,u32 trackindex); -RADEXPFUNC u32 RADEXPLINK BinkGetTrackID(HBINK bnk,u32 trackindex); -RADEXPFUNC u32 RADEXPLINK BinkGetTrackData(HBINK bnk,void PTR4* dest,u32 trackindex); - -RADEXPFUNC void RADEXPLINK BinkGetSummary(HBINK bnk,BINKSUMMARY PTR4* sum); -RADEXPFUNC void RADEXPLINK BinkGetRealtime(HBINK bink,BINKREALTIME PTR4* run,u32 frames); - -#define BINKNOSOUND 0xffffffff - -RADEXPFUNC void RADEXPLINK BinkSetSoundTrack(u32 track); -RADEXPFUNC void RADEXPLINK BinkSetIO(BINKIOOPEN io); -RADEXPFUNC void RADEXPLINK BinkSetFrameRate(u32 forcerate,u32 forceratediv); -RADEXPFUNC void RADEXPLINK BinkSetSimulate(u32 sim); -RADEXPFUNC void RADEXPLINK BinkSetIOSize(u32 iosize); - -RADEXPFUNC s32 RADEXPLINK BinkSetSoundSystem(BINKSNDSYSOPEN open, u32 param); - -#ifdef __RADWIN__ - - RADEXPFUNC BINKSNDOPEN RADEXPLINK BinkOpenDirectSound(u32 param); // don't call directly - #define BinkSoundUseDirectSound(lpDS) BinkSetSoundSystem(BinkOpenDirectSound,(u32)lpDS) - - #define BinkTimerSetup() - #define BinkTimerDone() - #define BinkTimerRead timeGetTime - - #define INCLUDE_MMSYSTEM_H - #include "windows.h" - #include "windowsx.h" - - #ifdef __RADNT__ // to combat WIN32_LEAN_AND_MEAN - - #include "mmsystem.h" - - RADEXPFUNC s32 RADEXPLINK BinkDDSurfaceType(void PTR4* lpDDS); - - #endif - -#endif - -#ifndef __RADMAC__ - - RADEXPFUNC BINKSNDOPEN RADEXPLINK BinkOpenMiles(u32 param); // don't call directly - #define BinkSoundUseMiles(hdigdriver) BinkSetSoundSystem(BinkOpenMiles,(u32)hdigdriver) - -#endif - - -#ifndef __RADDOS__ - -//========================================================================= -typedef struct BINKBUFFER * HBINKBUFFER; - -typedef struct BINKBUFFER { - u32 Width; - u32 Height; - u32 WindowWidth; - u32 WindowHeight; - u32 SurfaceType; - void* Buffer; - u32 BufferPitch; - s32 ClientOffsetX; - s32 ClientOffsetY; - u32 ScreenWidth; - u32 ScreenHeight; - u32 ScreenDepth; - u32 ExtraWindowWidth; - u32 ExtraWindowHeight; - u32 ScaleFlags; - u32 StretchWidth; - u32 StretchHeight; - - s32 surface; - void* ddsurface; - void* ddclipper; - s32 destx,desty; - u32 HWND; - s32 ddoverlay; - s32 ddoffscreen; - s32 lastovershow; - - s32 issoftcur; - u32 cursorcount; - void* buffertop; - u32 type; - s32 noclipping; - -} BINKBUFFER; - - -#define BINKBUFFERSTRETCHXINT 0x80000000 -#define BINKBUFFERSTRETCHX 0x40000000 -#define BINKBUFFERSHRINKXINT 0x20000000 -#define BINKBUFFERSHRINKX 0x10000000 -#define BINKBUFFERSTRETCHYINT 0x08000000 -#define BINKBUFFERSTRETCHY 0x04000000 -#define BINKBUFFERSHRINKYINT 0x02000000 -#define BINKBUFFERSHRINKY 0x01000000 -#define BINKBUFFERRESOLUTION 0x00800000 - -#define BINKBUFFERAUTO 0 -#define BINKBUFFERPRIMARY 1 -#define BINKBUFFERYV12OVERLAY 2 -#define BINKBUFFERYUY2OVERLAY 3 -#define BINKBUFFERUYVYOVERLAY 4 -#define BINKBUFFERYV12OFFSCREEN 5 -#define BINKBUFFERYUY2OFFSCREEN 6 -#define BINKBUFFERUYVYOFFSCREEN 7 -#define BINKBUFFERRGBOFFSCREENVIDEO 8 -#define BINKBUFFERRGBOFFSCREENSYSTEM 9 -#define BINKBUFFERDRAWDIB 10 -#define BINKBUFFERTYPEMASK 31 - -RADEXPFUNC HBINKBUFFER RADEXPLINK BinkBufferOpen( HWND wnd, u32 width, u32 height, u32 bufferflags); -RADEXPFUNC void RADEXPLINK BinkBufferClose( HBINKBUFFER buf); -RADEXPFUNC s32 RADEXPLINK BinkBufferLock( HBINKBUFFER buf); -RADEXPFUNC s32 RADEXPLINK BinkBufferUnlock( HBINKBUFFER buf); -RADEXPFUNC void RADEXPLINK BinkBufferSetResolution( s32 w, s32 h, s32 bits); -RADEXPFUNC void RADEXPLINK BinkBufferCheckWinPos( HBINKBUFFER buf, s32 PTR4* destx, s32 PTR4* desty); -RADEXPFUNC s32 RADEXPLINK BinkBufferSetOffset( HBINKBUFFER buf, s32 destx, s32 desty); -RADEXPFUNC void RADEXPLINK BinkBufferBlit( HBINKBUFFER buf, BINKRECT PTR4* rects, u32 numrects ); -RADEXPFUNC s32 RADEXPLINK BinkBufferSetScale( HBINKBUFFER buf, u32 w, u32 h); -RADEXPFUNC s32 RADEXPLINK BinkBufferSetHWND( HBINKBUFFER buf, HWND newwnd); -RADEXPFUNC char PTR4* RADEXPLINK BinkBufferDescription( HBINKBUFFER buf); -RADEXPFUNC char PTR4* RADEXPLINK BinkBufferGetError(); - -RADEXPFUNC s32 RADEXPLINK BinkDDSurfaceType(void PTR4* lpDDS); -RADEXPFUNC s32 RADEXPLINK BinkIsSoftwareCursor(void PTR4* lpDDSP,HCURSOR cur); -RADEXPFUNC s32 RADEXPLINK BinkCheckCursor(HWND wnd,s32 x,s32 y,s32 w,s32 h); -RADEXPFUNC void RADEXPLINK BinkRestoreCursor(s32 checkcount); - -#endif - -RADDEFEND - -#endif - -#endif - diff --git a/3dc/win95/bink_Rad.h b/3dc/win95/bink_Rad.h deleted file mode 100644 index bfbc07e..0000000 --- a/3dc/win95/bink_Rad.h +++ /dev/null @@ -1,699 +0,0 @@ -#ifndef __RAD__ -#define __RAD__ - -#define RADCOPYRIGHT "Copyright (C) 1994-99 RAD Game Tools, Inc." - -#ifndef __RADRES__ - -// __RADDOS__ means DOS code (16 or 32 bit) -// __RAD16__ means 16 bit code (Win16) -// __RAD32__ means 32 bit code (DOS, Win386, Win32s, Mac) -// __RADWIN__ means Windows code (Win16, Win386, Win32s) -// __RADWINEXT__ means Windows 386 extender (Win386) -// __RADNT__ means Win32s code -// __RADMAC__ means Macintosh -// __RAD68K__ means 68K Macintosh -// __RADPPC__ means PowerMac - - -#if (defined(__MWERKS__) && !defined(__INTEL__)) || defined(THINK_C) || defined(powerc) || defined(macintosh) || defined(__powerc) - - #define __RADMAC__ - #if defined(powerc) || defined(__powerc) - #define __RADPPC__ - #else - #define __RAD68K__ - #endif - - #define __RAD32__ - -#else - - #ifdef __MWERKS__ - #define _WIN32 - #endif - - #ifdef __DOS__ - #define __RADDOS__ - #endif - - #ifdef __386__ - #define __RAD32__ - #endif - - #ifdef _Windows //For Borland - #ifdef __WIN32__ - #define WIN32 - #else - #define __WINDOWS__ - #endif - #endif - - #ifdef _WINDOWS //For MS - #ifndef _WIN32 - #define __WINDOWS__ - #endif - #endif - - #ifdef _WIN32 - #define __RADWIN__ - #define __RADNT__ - #define __RAD32__ - #else - #ifdef __NT__ - #define __RADWIN__ - #define __RADNT__ - #define __RAD32__ - #else - #ifdef __WINDOWS_386__ - #define __RADWIN__ - #define __RADWINEXT__ - #define __RAD32__ - #else - #ifdef __WINDOWS__ - #define __RADWIN__ - #define __RAD16__ - #else - #ifdef WIN32 - #define __RADWIN__ - #define __RADNT__ - #define __RAD32__ - #endif - #endif - #endif - #endif - #endif - -#endif - -#if (!defined(__RADDOS__) && !defined(__RADWIN__) && !defined(__RADMAC__)) - #error RAD.H did not detect your platform. Define __DOS__, __WINDOWS__, WIN32, macintosh, or powerc. -#endif - -#ifdef __RADMAC__ - - // this define is for CodeWarrior 11's stupid new libs (even though - // we don't use longlong's). - - #define __MSL_LONGLONG_SUPPORT__ - - #define RADLINK - #define RADEXPLINK - - #ifdef __CFM68K__ - #ifdef __RADINDLL__ - #define RADEXPFUNC RADDEFFUNC __declspec(export) - #else - #define RADEXPFUNC RADDEFFUNC __declspec(import) - #endif - #else - #define RADEXPFUNC RADDEFFUNC - #endif - #define RADASMLINK - -#else - - #ifdef __RADNT__ - #ifndef _WIN32 - #define _WIN32 - #endif - #ifndef WIN32 - #define WIN32 - #endif - #endif - - #ifdef __RADWIN__ - #ifdef __RAD32__ - #ifdef __RADNT__ - - #define RADLINK __stdcall - #define RADEXPLINK __stdcall - - #ifdef __RADINEXE__ - #define RADEXPFUNC RADDEFFUNC - #else - #ifndef __RADINDLL__ - #define RADEXPFUNC RADDEFFUNC __declspec(dllimport) - #ifdef __BORLANDC__ - #if __BORLANDC__<=0x460 - #undef RADEXPFUNC - #define RADEXPFUNC RADDEFFUNC - #endif - #endif - #else - #define RADEXPFUNC RADDEFFUNC __declspec(dllexport) - #endif - #endif - #else - #define RADLINK __pascal - #define RADEXPLINK __far __pascal - #define RADEXPFUNC RADDEFFUNC - #endif - #else - #define RADLINK __pascal - #define RADEXPLINK __far __pascal __export - #define RADEXPFUNC RADDEFFUNC - #endif - #else - #define RADLINK __pascal - #define RADEXPLINK __pascal - #define RADEXPFUNC RADDEFFUNC - #endif - - #define RADASMLINK __cdecl - -#endif - -#ifdef __RADWIN__ - #ifndef _WINDOWS - #define _WINDOWS - #endif -#endif - -#ifdef __cplusplus - #define RADDEFFUNC extern "C" - #define RADDEFSTART extern "C" { - #define RADDEFEND } -#else - #define RADDEFFUNC - #define RADDEFSTART - #define RADDEFEND -#endif - - -RADDEFSTART - -#define s8 signed char -#define u8 unsigned char -#define u32 unsigned long -#define s32 signed long -#define u64 unsigned __int64 -#define s64 signed __int64 -#define f32 float -#define f64 double - - -#ifdef __RAD32__ - #define PTR4 - - #define u16 unsigned short - #define s16 signed short - - #ifdef __RADMAC__ - - #include <string.h> - #include <memory.h> - #include <OSUtils.h> - - #define radstrlen strlen - - #define radmemset memset - - #define radmemcmp memcmp - - #define radmemcpy(dest,source,size) BlockMoveData((Ptr)(source),(Ptr)(dest),size) - - #define radmemcpydb(dest,source,size) BlockMoveData((Ptr)(source),(Ptr)(dest),size) - - #define radstrcat strcat - - #define radstrcpy strcpy - - static u32 inline radsqr(s32 a) { return(a*a); } - - #ifdef __RAD68K__ - - #pragma parameter __D0 mult64anddiv(__D0,__D1,__D2) - u32 mult64anddiv(u32 m1,u32 m2,u32 d) ={0x4C01,0x0C01,0x4C42,0x0C01}; - // muls.l d1,d1:d0 divs.l d2,d1:d0 - - #pragma parameter radconv32a(__A0,__D0) - void radconv32a(void* p,u32 n) ={0x4A80,0x600C,0x2210,0xE059,0x4841,0xE059,0x20C1,0x5380,0x6EF2}; - // tst.l d0 bra.s @loope @loop: move.l (a0),d1 ror.w #8,d1 swap d1 ror.w #8,d1 move.l d1,(a0)+ sub.l #1,d0 bgt.s @loop @loope: - - #else - - u32 mult64anddiv(u32 m1,u32 m2,u32 d); - - void radconv32a(void* p,u32 n); - - #endif - - #else - - #ifdef __WATCOMC__ - - u32 radsqr(s32 a); - #pragma aux radsqr = "mul eax" parm [eax] modify [EDX eax]; - - u32 mult64anddiv(u32 m1,u32 m2,u32 d); - #pragma aux mult64anddiv = "mul ecx" "div ebx" parm [eax] [ecx] [ebx] modify [EDX eax]; - - s32 radabs(s32 ab); - #pragma aux radabs = "test eax,eax" "jge skip" "neg eax" "skip:" parm [eax]; - - #define radabs32 radabs - - u32 DOSOut(const char* str); - #pragma aux DOSOut = "cld" "mov ecx,0xffffffff" "xor eax,eax" "mov edx,edi" "repne scasb" "not ecx" "dec ecx" "mov ebx,1" "mov ah,0x40" "int 0x21" parm [EDI] modify [EAX EBX ECX EDX EDI] value [ecx]; - - void DOSOutNum(const char* str,u32 len); - #pragma aux DOSOutNum = "mov ah,0x40" "mov ebx,1" "int 0x21" parm [edx] [ecx] modify [eax ebx]; - - u32 ErrOut(const char* str); - #pragma aux ErrOut = "cld" "mov ecx,0xffffffff" "xor eax,eax" "mov edx,edi" "repne scasb" "not ecx" "dec ecx" "xor ebx,ebx" "mov ah,0x40" "int 0x21" parm [EDI] modify [EAX EBX ECX EDX EDI] value [ecx]; - - void ErrOutNum(const char* str,u32 len); - #pragma aux ErrOutNum = "mov ah,0x40" "xor ebx,ebx" "int 0x21" parm [edx] [ecx] modify [eax ebx]; - - void radmemset16(void* dest,u16 value,u32 size); - #pragma aux radmemset16 = "cld" "mov bx,ax" "shl eax,16" "mov ax,bx" "mov bl,cl" "shr ecx,1" "rep stosd" "mov cl,bl" "and cl,1" "rep stosw" parm [EDI] [EAX] [ECX] modify [EAX EDX EBX ECX EDI]; - - void radmemset(void* dest,u8 value,u32 size); - #pragma aux radmemset = "cld" "mov ah,al" "mov bx,ax" "shl eax,16" "mov ax,bx" "mov bl,cl" "shr ecx,2" "and bl,3" "rep stosd" "mov cl,bl" "rep stosb" parm [EDI] [AL] [ECX] modify [EAX EDX EBX ECX EDI]; - - void radmemset32(void* dest,u32 value,u32 size); - #pragma aux radmemset32 = "cld" "rep stosd" parm [EDI] [EAX] [ECX] modify [EAX EDX EBX ECX EDI]; - - void radmemcpy(void* dest,const void* source,u32 size); - #pragma aux radmemcpy = "cld" "mov bl,cl" "shr ecx,2" "rep movsd" "mov cl,bl" "and cl,3" "rep movsb" parm [EDI] [ESI] [ECX] modify [EBX ECX EDI ESI]; - - void __far *radfmemcpy(void __far* dest,const void __far* source,u32 size); - #pragma aux radfmemcpy = "cld" "push es" "push ds" "mov es,cx" "mov ds,dx" "mov ecx,eax" "shr ecx,2" "rep movsd" "mov cl,al" "and cl,3" "rep movsb" "pop ds" "pop es" parm [CX EDI] [DX ESI] [EAX] modify [ECX EDI ESI] value [CX EDI]; - - void radmemcpydb(void* dest,const void* source,u32 size); //Destination bigger - #pragma aux radmemcpydb = "std" "mov bl,cl" "lea esi,[esi+ecx-4]" "lea edi,[edi+ecx-4]" "shr ecx,2" "rep movsd" "and bl,3" "jz dne" "add esi,3" "add edi,3" "mov cl,bl" "rep movsb" "dne:" "cld" parm [EDI] [ESI] [ECX] modify [EBX ECX EDI ESI]; - - char* radstrcpy(void* dest,const void* source); - #pragma aux radstrcpy = "cld" "mov edx,edi" "lp:" "mov al,[esi]" "inc esi" "mov [edi],al" "inc edi" "cmp al,0" "jne lp" parm [EDI] [ESI] modify [EAX EDX EDI ESI] value [EDX]; - - char __far* radfstrcpy(void __far* dest,const void __far* source); - #pragma aux radfstrcpy = "cld" "push es" "push ds" "mov es,cx" "mov ds,dx" "mov edx,edi" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" "pop ds" "pop es" parm [CX EDI] [DX ESI] modify [EAX EDX EDI ESI] value [CX EDX]; - - char* radstpcpy(void* dest,const void* source); - #pragma aux radstpcpy = "cld" "lp:" "mov al,[esi]" "inc esi" "mov [edi],al" "inc edi" "cmp al,0" "jne lp" "dec edi" parm [EDI] [ESI] modify [EAX EDI ESI] value [EDI]; - - char* radstpcpyrs(void* dest,const void* source); - #pragma aux radstpcpyrs = "cld" "lp:" "mov al,[esi]" "inc esi" "mov [edi],al" "inc edi" "cmp al,0" "jne lp" "dec esi" parm [EDI] [ESI] modify [EAX EDI ESI] value [ESI]; - - u32 radstrlen(const void* dest); - #pragma aux radstrlen = "cld" "mov ecx,0xffffffff" "xor eax,eax" "repne scasb" "not ecx" "dec ecx" parm [EDI] modify [EAX ECX EDI] value [ECX]; - - char* radstrcat(void* dest,const void* source); - #pragma aux radstrcat = "cld" "mov ecx,0xffffffff" "mov edx,edi" "xor eax,eax" "repne scasb" "dec edi" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" \ - parm [EDI] [ESI] modify [EAX ECX EDI ESI] value [EDX]; - - char* radstrchr(const void* dest,char chr); - #pragma aux radstrchr = "cld" "lp:" "lodsb" "cmp al,dl" "je fnd" "cmp al,0" "jnz lp" "mov esi,1" "fnd:" "dec esi" parm [ESI] [DL] modify [EAX ESI] value [esi]; - - s8 radmemcmp(const void* s1,const void* s2,u32 len); - #pragma aux radmemcmp = "cld" "rep cmpsb" "setne al" "jbe end" "neg al" "end:" parm [EDI] [ESI] [ECX] modify [ECX EDI ESI]; - - s8 radstrcmp(const void* s1,const void* s2); - #pragma aux radstrcmp = "lp:" "mov al,[esi]" "mov ah,[edi]" "cmp al,ah" "jne set" "cmp al,0" "je set" "inc esi" "inc edi" "jmp lp" "set:" "setne al" "jbe end" "neg al" "end:" \ - parm [EDI] [ESI] modify [EAX EDI ESI]; - - s8 radstricmp(const void* s1,const void* s2); - #pragma aux radstricmp = "lp:" "mov al,[esi]" "mov ah,[edi]" "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub al,32" "c1:" "cmp ah,'a'" "jb c2" "cmp ah,'z'" "ja c2" "sub ah,32" "c2:" "cmp al,ah" "jne set" "cmp al,0" "je set" \ - "inc esi" "inc edi" "jmp lp" "set:" "setne al" "jbe end" "neg al" "end:" \ - parm [EDI] [ESI] modify [EAX EDI ESI]; - - s8 radstrnicmp(const void* s1,const void* s2,u32 len); - #pragma aux radstrnicmp = "lp:" "mov al,[esi]" "mov ah,[edi]" "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub al,32" "c1:" "cmp ah,'a'" "jb c2" "cmp ah,'z'" "ja c2" "sub ah,32" "c2:" "cmp al,ah" "jne set" "cmp al,0" "je set" \ - "dec ecx" "jz set" "inc esi" "inc edi" "jmp lp" "set:" "setne al" "jbe end" "neg al" "end:" \ - parm [EDI] [ESI] [ECX] modify [EAX ECX EDI ESI]; - - char* radstrupr(void* s1); - #pragma aux radstrupr = "mov ecx,edi" "lp:" "mov al,[edi]" "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub [edi],32" "c1:" "inc edi" "cmp al,0" "jne lp" parm [EDI] modify [EAX EDI] value [ecx]; - - char* radstrlwr(void* s1); - #pragma aux radstrlwr = "mov ecx,edi" "lp:" "mov al,[edi]" "cmp al,'A'" "jb c1" "cmp al,'Z'" "ja c1" "add [edi],32" "c1:" "inc edi" "cmp al,0" "jne lp" parm [EDI] modify [EAX EDI] value [ecx]; - - u32 radstru32(const void* dest); - #pragma aux radstru32 = "cld" "xor ecx,ecx" "xor ebx,ebx" "xor edi,edi" "lodsb" "cmp al,45" "jne skip2" "mov edi,1" "jmp skip" "lp:" "mov eax,10" "mul ecx" "lea ecx,[eax+ebx]" \ - "skip:" "lodsb" "skip2:" "cmp al,0x39" "ja dne" "cmp al,0x30" "jb dne" "mov bl,al" "sub bl,0x30" "jmp lp" "dne:" "test edi,1" "jz pos" "neg ecx" "pos:" \ - parm [ESI] modify [EAX EBX EDX EDI ESI] value [ecx]; - - u16 GetDS(); - #pragma aux GetDS = "mov ax,ds" value [ax]; - - #ifdef __RADWINEXT__ - - #define _16To32(ptr16) ((void*)(((GetSelectorBase((u16)(((u32)(ptr16))>>16))+((u16)(u32)(ptr16)))-GetSelectorBase(GetDS())))) - - #endif - - #ifndef __RADWIN__ - #define int86 int386 - #define int86x int386x - #endif - - #define u32regs x - #define u16regs w - - #else - - #define radstrcpy strcpy - #define radstrcat strcat - #define radmemcpy memcpy - #define radmemcpydb memmove - #define radmemcmp memcmp - #define radmemset memset - #define radstrlen strlen - #define radstrchr strchr - #define radtoupper toupper - #define radstru32(s) ((u32)atol(s)) - #define radstricmp _stricmp - #define radstrcmp strcmp - #define radstrupr _strupr - #define radstrlwr _strlwr - #define BreakPoint() __asm {int 3} - - #ifdef _MSC_VER - - #pragma warning( disable : 4035) - - typedef char* RADPCHAR; - - u32 __inline radsqr(u32 m) { - __asm { - mov eax,[m] - mul eax - } - } - - u32 __inline mult64anddiv(u32 m1,u32 m2, u32 d) { - __asm { - mov eax,[m1] - mov ecx,[m2] - mul ecx - mov ecx,[d] - div ecx - } - } - - s32 __inline radabs(s32 ab) { - __asm { - mov eax,[ab] - test eax,eax - jge skip - neg eax - skip: - } - } - - u8 __inline radinp(u16 p) { - __asm { - mov dx,[p] - in al,dx - } - } - - void __inline radoutp(u16 p,u8 v) { - __asm { - mov dx,[p] - mov al,[v] - out dx,al - } - } - - RADPCHAR __inline radstpcpy(char* p1, char* p2) { - __asm { - mov edx,[p1] - mov ecx,[p2] - cld - lp: - mov al,[ecx] - inc ecx - mov [edx],al - inc edx - cmp al,0 - jne lp - dec edx - mov eax,edx - } - } - - RADPCHAR __inline radstpcpyrs(char* p1, char* p2) { - __asm { - mov edx,[p1] - mov ecx,[p2] - cld - lp: - mov al,[ecx] - inc ecx - mov [edx],al - inc edx - cmp al,0 - jne lp - dec ecx - mov eax,ecx - } - } - - void __inline radmemset16(void* dest,u16 value,u32 sizeb) { - __asm { - mov edi,[dest] - mov ax,[value] - mov ecx,[sizeb] - shl eax,16 - cld - mov ax,[value] - mov bl,cl - shr ecx,1 - rep stosd - mov cl,bl - and cl,1 - rep stosw - } - } - - void __inline radmemset32(void* dest,u32 value,u32 sizeb) { - __asm { - mov edi,[dest] - mov eax,[value] - mov ecx,[sizeb] - cld - rep stosd - } - } - - u32 __inline __stdcall RADsqrt(u32 sq) { - __asm { - fild dword ptr [sq] - fsqrt - fistp word ptr [sq] - movzx eax,word ptr [sq] - } - } - - void __inline RADCycleTimerStartAddr(u32* addr) - { - __asm { - mov ecx,[addr] -#ifdef __MWERKS__ - rdtsc -#else -#if _MSC_VER<=1100 - __emit 0xf - __emit 0x31 -#else - rdtsc -#endif -#endif - mov [ecx],eax - } - } - - u32 __inline RADCycleTimerDeltaAddr(u32* addr) - { - __asm { -#ifdef __MWERKS__ - rdtsc -#else -#if _MSC_VER<=1100 - __emit 0xf - __emit 0x31 -#else - rdtsc -#endif -#endif - mov ecx,[addr] - sub eax,[ecx] - mov [ecx],eax - } - } - - #define RADCycleTimerStart(var) RADCycleTimerStartAddr(&var) - #define RADCycleTimerDelta(var) RADCycleTimerDeltaAddr(&var) - - #pragma warning( default : 4035) - - #endif - - #endif - - #endif - -#else - - #define PTR4 __far - - #define u16 unsigned int - #define s16 signed int - - #ifdef __WATCOMC__ - - u32 radsqr(s32 a); - #pragma aux radsqr = "shl edx,16" "mov dx,ax" "mov eax,edx" "xor edx,edx" "mul eax" "shld edx,eax,16" parm [dx ax] modify [DX ax] value [dx ax]; - - s16 radabs(s16 ab); - #pragma aux radabs = "test ax,ax" "jge skip" "neg ax" "skip:" parm [ax] value [ax]; - - s32 radabs32(s32 ab); - #pragma aux radabs32 = "test dx,dx" "jge skip" "neg dx" "neg ax" "sbb dx,0" "skip:" parm [dx ax] value [dx ax]; - - u32 DOSOut(const char far* dest); - #pragma aux DOSOut = "cld" "and edi,0xffff" "mov dx,di" "mov ecx,0xffffffff" "xor eax,eax" 0x67 "repne scasb" "not ecx" "dec ecx" "mov bx,1" "push ds" "push es" "pop ds" "mov ah,0x40" "int 0x21" "pop ds" "movzx eax,cx" "shr ecx,16" \ - parm [ES DI] modify [AX BX CX DX DI ES] value [CX AX]; - - void DOSOutNum(const char far* str,u16 len); - #pragma aux DOSOutNum = "push ds" "mov ds,cx" "mov cx,bx" "mov ah,0x40" "mov bx,1" "int 0x21" "pop ds" parm [cx dx] [bx] modify [ax bx cx]; - - u32 ErrOut(const char far* dest); - #pragma aux ErrOut = "cld" "and edi,0xffff" "mov dx,di" "mov ecx,0xffffffff" "xor eax,eax" 0x67 "repne scasb" "not ecx" "dec ecx" "xor bx,bx" "push ds" "push es" "pop ds" "mov ah,0x40" "int 0x21" "pop ds" "movzx eax,cx" "shr ecx,16" \ - parm [ES DI] modify [AX BX CX DX DI ES] value [CX AX]; - - void ErrOutNum(const char far* str,u16 len); - #pragma aux ErrOutNum = "push ds" "mov ds,cx" "mov cx,bx" "mov ah,0x40" "xor bx,bx" "int 0x21" "pop ds" parm [cx dx] [bx] modify [ax bx cx]; - - void radmemset(void far *dest,u8 value,u32 size); - #pragma aux radmemset = "cld" "and edi,0ffffh" "shl ecx,16" "mov cx,bx" "mov ah,al" "mov bx,ax" "shl eax,16" "mov ax,bx" "mov bl,cl" "shr ecx,2" 0x67 "rep stosd" "mov cl,bl" "and cl,3" "rep stosb" parm [ES DI] [AL] [CX BX]; - - void radmemset16(void far* dest,u16 value,u32 size); - #pragma aux radmemset16 = "cld" "and edi,0ffffh" "shl ecx,16" "mov cx,bx" "mov bx,ax" "shl eax,16" "mov ax,bx" "mov bl,cl" "shr ecx,1" "rep stosd" "mov cl,bl" "and cl,1" "rep stosw" parm [ES DI] [AX] [CX BX]; - - void radmemcpy(void far* dest,const void far* source,u32 size); - #pragma aux radmemcpy = "cld" "push ds" "mov ds,dx" "and esi,0ffffh" "and edi,0ffffh" "shl ecx,16" "mov cx,bx" "shr ecx,2" 0x67 "rep movsd" "mov cl,bl" "and cl,3" "rep movsb" "pop ds" parm [ES DI] [DX SI] [CX BX] modify [CX SI DI ES]; - - s8 radmemcmp(const void far* s1,const void far* s2,u32 len); - #pragma aux radmemcmp = "cld" "push ds" "mov ds,dx" "shl ecx,16" "mov cx,bx" "rep cmpsb" "setne al" "jbe end" "neg al" "end:" "pop ds" parm [ES DI] [DX SI] [CX BX] modify [CX SI DI ES]; - - char far* radstrcpy(void far* dest,const void far* source); - #pragma aux radstrcpy = "cld" "push ds" "mov ds,dx" "and esi,0xffff" "and edi,0xffff" "mov dx,di" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" "pop ds" parm [ES DI] [DX SI] modify [AX DX DI SI ES] value [es dx]; - - char far* radstpcpy(void far* dest,const void far* source); - #pragma aux radstpcpy = "cld" "push ds" "mov ds,dx" "and esi,0xffff" "and edi,0xffff" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" "dec di" "pop ds" parm [ES DI] [DX SI] modify [DI SI ES] value [es di]; - - u32 radstrlen(const void far* dest); - #pragma aux radstrlen = "cld" "and edi,0xffff" "mov ecx,0xffffffff" "xor eax,eax" 0x67 "repne scasb" "not ecx" "dec ecx" "movzx eax,cx" "shr ecx,16" parm [ES DI] modify [AX CX DI ES] value [CX AX]; - - char far* radstrcat(void far* dest,const void far* source); - #pragma aux radstrcat = "cld" "and edi,0xffff" "mov ecx,0xffffffff" "and esi,0xffff" "push ds" "mov ds,dx" "mov dx,di" "xor eax,eax" 0x67 "repne scasb" "dec edi" "lp:" "lodsb" "stosb" "test al,0xff" "jnz lp" "pop ds" \ - parm [ES DI] [DX SI] modify [AX CX DI SI ES] value [es dx]; - - char far* radstrchr(const void far* dest,char chr); - #pragma aux radstrchr = "cld" "lp:" 0x26 "lodsb" "cmp al,dl" "je fnd" "cmp al,0" "jnz lp" "xor ax,ax" "mov es,ax" "mov si,1" "fnd:" "dec si" parm [ES SI] [DL] modify [AX SI ES] value [es si]; - - s8 radstricmp(const void far* s1,const void far* s2); - #pragma aux radstricmp = "and edi,0xffff" "push ds" "mov ds,dx" "and esi,0xffff" "lp:" "mov al,[esi]" "mov ah,[edi]" "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub al,32" "c1:" \ - "cmp ah,'a'" "jb c2" "cmp ah,'z'" "ja c2" "sub ah,32" "c2:" "cmp al,ah" "jne set" "cmp al,0" "je set" \ - "inc esi" "inc edi" "jmp lp" "set:" "setne al" "jbe end" "neg al" "end:" "pop ds" \ - parm [ES DI] [DX SI] modify [AX DI SI]; - - u32 radstru32(const void far* dest); - #pragma aux radstru32 = "cld" "xor ecx,ecx" "xor ebx,ebx" "xor edi,edi" 0x26 "lodsb" "cmp al,45" "jne skip2" "mov edi,1" "jmp skip" "lp:" "mov eax,10" "mul ecx" "lea ecx,[eax+ebx]" \ - "skip:" 0x26 "lodsb" "skip2:" "cmp al,0x39" "ja dne" "cmp al,0x30" "jb dne" "mov bl,al" "sub bl,0x30" "jmp lp" "dne:" "test edi,1" "jz pos" "neg ecx" "pos:" \ - "movzx eax,cx" "shr ecx,16" parm [ES SI] modify [AX BX DX DI SI] value [cx ax]; - - u32 mult64anddiv(u32 m1,u32 m2,u32 d); - #pragma aux mult64anddiv = "shl ecx,16" "mov cx,ax" "shrd eax,edx,16" "mov ax,si" "mul ecx" "shl edi,16" "mov di,bx" "div edi" "shld edx,eax,16" "and edx,0xffff" "and eax,0xffff" parm [cx ax] [dx si] [di bx] \ - modify [ax bx cx dx si di] value [dx ax]; - - #endif - -#endif - -RADDEFEND - -#define u32neg1 ((u32)(s32)-1) -#define RAD_align(var) var; u8 junk##var[4-(sizeof(var)&3)]; -#define RAD_align_after(var) u8 junk##var[4-(sizeof(var)&3)]={0}; -#define RAD_align_init(var,val) var=val; u8 junk##var[4-(sizeof(var)&3)]={0}; -#define RAD_align_array(var,num) var[num]; u8 junk##var[4-(sizeof(var)&3)]; -#define RAD_align_string(var,str) char var[]=str; u8 junk##var[4-(sizeof(var)&3)]={0}; - - -RADEXPFUNC void PTR4* RADEXPLINK radmalloc(u32 numbytes); -RADEXPFUNC void RADEXPLINK radfree(void PTR4* ptr); - - -#ifdef __WATCOMC__ - - char bkbhit(); - #pragma aux bkbhit = "mov ah,1" "int 0x16" "lahf" "shr eax,14" "and eax,1" "xor al,1" ; - - char bgetch(); - #pragma aux bgetch = "xor ah,ah" "int 0x16" "test al,0xff" "jnz done" "mov al,ah" "or al,0x80" "done:" modify [AX]; - - void BreakPoint(); - #pragma aux BreakPoint = "int 3"; - - u8 radinp(u16 p); - #pragma aux radinp = "in al,dx" parm [DX]; - - u8 radtoupper(u8 p); - #pragma aux radtoupper = "cmp al,'a'" "jb c1" "cmp al,'z'" "ja c1" "sub al,32" "c1:" parm [al] value [al]; - - void radoutp(u16 p,u8 v); - #pragma aux radoutp = "out dx,al" parm [DX] [AL]; - -#else - -// for multi-processor machines - -#ifdef __RADNT__ - #define LockedIncrement(var) __asm { lock inc [var] } - #define LockedDecrement(var) __asm { lock dec [var] } - void __inline LockedIncrementFunc(void PTR4* var) { - __asm { - mov eax,[var] - lock inc [eax] - } - } - - void __inline LockedDecrementFunc(void PTR4* var) { - __asm { - mov eax,[var] - lock dec [eax] - } - } - -#else - - #ifdef __RADMAC__ - - #define LockedIncrement(var) {++(var);} - #define LockedDecrement(var) {--(var);} - - #define LockedIncrementFunc(ptr) {++(*((u32*)(var)));} - #define LockedDecrementFunc(ptr) {--(*((u32*)(var)));} - - #else - - #define LockedIncrement(var) __asm { inc [var] } - #define LockedDecrement(var) __asm { dec [var] } - void __inline LockedIncrementFunc(void PTR4* var) { __asm { mov eax,[var] - inc [eax] } } - void __inline LockedDecrementFunc(void PTR4* var) { __asm { mov eax,[var] - dec [eax] } } - #endif - -#endif - -#endif - -#endif - -#endif - diff --git a/3dc/win95/chnkload.cpp b/3dc/win95/chnkload.cpp deleted file mode 100644 index 2113372..0000000 --- a/3dc/win95/chnkload.cpp +++ /dev/null @@ -1,4024 +0,0 @@ -#include <stdlib.h> -#include <string.hpp> - -#include "list_tem.hpp" -#include "chnkload.hpp" -#include "oechunk.h" -#include "stratdef.h" -//#include "bh_types.h" -#include "shpchunk.hpp" -#include "envchunk.hpp" -#include "obchunk.hpp" -#include "chunkpal.hpp" -#include "bmpnames.hpp" -#include "ltchunk.hpp" -#include "chnktexi.h" -#include "sprchunk.hpp" -#include "gsprchnk.hpp" -#include "animchnk.hpp" -#include "fragchnk.hpp" -#include "jsndsup.h" -#include "mempool.h" -#include <math.h> -// for log file -void SetupAnimatedTextures(Shape_Chunk* sc,SHAPEHEADER* shp,Animation_Chunk* ac,Shape_Merge_Data_Chunk* smdc); -void SetupAnimOnTriangle(SHAPEHEADER* shp,TEXANIM* ta,int poly); -void SetupAnimOnQuad(Shape_Chunk* sc,SHAPEHEADER* shp,TEXANIM* ta1,TEXANIM* ta2,int poly); - -// what we need to do for now is load shapes into the mainshapelist -// and objects into the Mapheader - Map - - -double local_scale; - -File_Chunk * Env_Chunk = 0; - -RIFFHANDLE current_rif_handle; - -unsigned char const * PaletteMapTable; - -////////////////////////////////////////////////////////// -extern LOADED_SOUND const * GetSoundForMainRif(const char* wav_name); -extern char * extsounddir ; -extern char * sounddir ; - -struct Shape_Fragment_Type -{ - Shape_Fragment_Type(const char*); - ~Shape_Fragment_Type(); - void AddShape(SHAPEHEADER*); - void Setup_sh_frags(Fragment_Type_Chunk*); - - char* name; - List<SHAPEHEADER*> shapelist; - SHAPEFRAGMENTDESC* sh_fragdesc; -}; - -Shape_Fragment_Type::Shape_Fragment_Type(const char* _name) -{ - name=new char[strlen(_name)+1]; - strcpy(name,_name); - sh_fragdesc=0; -} - -Shape_Fragment_Type::~Shape_Fragment_Type() -{ - while(shapelist.size()) - { - shapelist.first_entry()->sh_fragdesc=0; - delete shapelist.first_entry(); - } - if(sh_fragdesc) - { - #if USE_LEVEL_MEMORY_POOL - if(sh_fragdesc->sh_fragsound) - { - if(sh_fragdesc->sh_fragsound->sound_loaded) - LoseSound(sh_fragdesc->sh_fragsound->sound_loaded); - } - #else - if(sh_fragdesc->sh_frags)DeallocateMem(sh_fragdesc->sh_frags); - if(sh_fragdesc->sh_fragsound) - { - if(sh_fragdesc->sh_fragsound->sound_loaded) - LoseSound(sh_fragdesc->sh_fragsound->sound_loaded); - DeallocateMem(sh_fragdesc->sh_fragsound); - } - DeallocateMem(sh_fragdesc); - #endif - - } - if(name) delete name; -} - -void Shape_Fragment_Type::AddShape(SHAPEHEADER* shp) -{ - shapelist.add_entry(shp); - if(sh_fragdesc) shp->sh_fragdesc=sh_fragdesc; -} - - -void Shape_Fragment_Type::Setup_sh_frags(Fragment_Type_Chunk* ftc) -{ - if(sh_fragdesc) return; - List<Chunk*> chlist; - ftc->lookup_child("FRGTYPSC",chlist); - - sh_fragdesc=(SHAPEFRAGMENTDESC*)PoolAllocateMem(sizeof(SHAPEFRAGMENTDESC)); - for(LIF<SHAPEHEADER*> slif(&shapelist);!slif.done();slif.next()) - { - slif()->sh_fragdesc=sh_fragdesc; - } - - - sh_fragdesc->sh_frags = (SHAPEFRAGMENT *)PoolAllocateMem((chlist.size()+1) * sizeof(SHAPEFRAGMENT)); - int pos=0; - while(chlist.size()) - { - Fragment_Type_Shape_Chunk* ftsc=(Fragment_Type_Shape_Chunk*)chlist.first_entry(); - - int shapeindex=GetLoadedShapeMSL(ftsc->name); - if(shapeindex!=-1) - { - sh_fragdesc->sh_frags[pos].ShapeIndex=shapeindex; - sh_fragdesc->sh_frags[pos].NumFrags=ftsc->num_fragments; - - sh_fragdesc->sh_frags[pos].x_offset = 0; - sh_fragdesc->sh_frags[pos].y_offset = 0; - sh_fragdesc->sh_frags[pos].z_offset = 0; - pos++; - } - - chlist.delete_first_entry(); - } - sh_fragdesc->sh_frags[pos].ShapeIndex = -1; - sh_fragdesc->sh_frags[pos].NumFrags = -1; - - sh_fragdesc->sh_fragsound=0; - - Chunk * pChunk = ftc->lookup_single_child("FRGSOUND"); - if(pChunk) - { - Fragment_Type_Sound_Chunk* ftsoc=(Fragment_Type_Sound_Chunk*) pChunk; - - - sh_fragdesc->sh_fragsound=(SHAPEFRAGMENTSOUND*)PoolAllocateMem(sizeof(SHAPEFRAGMENTSOUND)); - sh_fragdesc->sh_fragsound->sound_loaded=GetSoundForMainRif (ftsoc->wav_name); - sh_fragdesc->sh_fragsound->inner_range=ftsoc->inner_range*local_scale; - sh_fragdesc->sh_fragsound->outer_range=ftsoc->outer_range*local_scale; - sh_fragdesc->sh_fragsound->pitch=ftsoc->pitch; - sh_fragdesc->sh_fragsound->max_volume=ftsoc->max_volume; - - } - - -} - - -static List<Shape_Fragment_Type*> FragList; - -void ApplyFragTypeToShape(SHAPEHEADER* shp,const char* name) -{ - for(LIF<Shape_Fragment_Type*> flif(&FragList);!flif.done();flif.next()) - { - if(!_stricmp(flif()->name,name)) - { - flif()->AddShape(shp); - return; - } - } - Shape_Fragment_Type* sft=new Shape_Fragment_Type(name); - sft->AddShape(shp); - FragList.add_entry(sft); -} - -void SetupFragmentType(Fragment_Type_Chunk* ftc) -{ - const char* name=ftc->get_name(); - if(!name) return; - - Shape_Fragment_Type* sft=0; - for(LIF<Shape_Fragment_Type*> flif(&FragList);!flif.done();flif.next()) - { - if(!_stricmp(flif()->name,name)) - { - sft=flif(); - break; - } - } - if(!sft) - { - return; - } - - sft->Setup_sh_frags(ftc); -} - -void DeallocateFragments(SHAPEHEADER* shp,SHAPEFRAGMENTDESC* sh_fragdesc) -{ - for(LIF<Shape_Fragment_Type*> flif(&FragList);!flif.done();flif.next()) - { - if(flif()->sh_fragdesc==sh_fragdesc) - { - flif()->shapelist.delete_entry(shp); - if(!flif()->shapelist.size()) - { - //no more shapes use this fragment type - so deallocate it - delete flif(); - flif.delete_current(); - } - return; - } - } - //sh_fragdesc not generated by a fragment type so deallocate it. - #if USE_LEVEL_MEMORY_POOL - if(sh_fragdesc->sh_fragsound) - { - if(sh_fragdesc->sh_fragsound->sound_loaded) - LoseSound(sh_fragdesc->sh_fragsound->sound_loaded); - } - #else - if(sh_fragdesc->sh_frags)DeallocateMem(sh_fragdesc->sh_frags); - if(sh_fragdesc->sh_fragsound) - { - if(sh_fragdesc->sh_fragsound->sound_loaded) - LoseSound(sh_fragdesc->sh_fragsound->sound_loaded); - DeallocateMem(sh_fragdesc->sh_fragsound); - } - DeallocateMem(sh_fragdesc); - #endif -} - -void DeallocateAllFragments() -{ - while(FragList.size()) - { - Shape_Fragment_Type* frag_type=FragList.first_entry(); - - while(frag_type->shapelist.size()) - { - frag_type->shapelist.delete_first_entry(); - } - frag_type->sh_fragdesc=0; - delete frag_type; - - FragList.delete_first_entry(); - } -} - -///////////////////////////////////////// -///////////////////////////////////////// -// Hold data about chunk loaded shapes // -///////////////////////////////////////// -///////////////////////////////////////// - -class ShapeInMSL -{ -private: - void AddToHashTables(); - void RemoveFromHashTables(); - - #define SIM_HASH_BITS 6 - #define SIM_HASH_SIZE (1<<SIM_HASH_BITS) - #define SIM_HASH_MASK (SIM_HASH_SIZE-1) - - static List<ShapeInMSL const *> hash_msl[]; - static List<ShapeInMSL const *> hash_ptr[]; - static List<ShapeInMSL const *> hash_name[]; - - static int HashMSLFunc(int); - static int HashPtrFunc(SHAPEHEADER *); - static int HashNameFunc(char const *); - - - int listpos; - SHAPEHEADER * shptr; - String name; - BOOL in_hash_table; - -public: - - inline int Listpos() const { return listpos; } - inline SHAPEHEADER * Shptr() const { return shptr; } - inline char const * Name() const { return name; } - - static ShapeInMSL const * GetByName(char const *); - static ShapeInMSL const * GetByMSL(int); - static ShapeInMSL const * GetByPtr(SHAPEHEADER *); - static void PurgeMSLShapeList(); - - ShapeInMSL(); - ShapeInMSL(int _p); - ShapeInMSL(SHAPEHEADER * _s, char const * _n, int _p); - ShapeInMSL(ShapeInMSL const &); - ShapeInMSL & operator = (ShapeInMSL const &); - ~ShapeInMSL(); - - BOOL operator == (ShapeInMSL const & s2) const - { return (GLS_NOTINLIST==listpos && GLS_NOTINLIST==s2.listpos) ? shptr == s2.shptr : listpos == s2.listpos; } - inline BOOL operator != (ShapeInMSL const & s2) const { return ! operator == (s2); } -}; - -void ShapeInMSL::AddToHashTables() -{ - if (GLS_NOTINLIST != listpos) - hash_msl[HashMSLFunc(listpos)].add_entry(this); - hash_ptr[HashPtrFunc(shptr)].add_entry(this); - hash_name[HashNameFunc(name)].add_entry(this); - - in_hash_table = TRUE; -} - -void ShapeInMSL::RemoveFromHashTables() -{ - if (GLS_NOTINLIST != listpos) - hash_msl[HashMSLFunc(listpos)].delete_entry(this); - hash_ptr[HashPtrFunc(shptr)].delete_entry(this); - hash_name[HashNameFunc(name)].delete_entry(this); - - in_hash_table = FALSE; -} - -List<ShapeInMSL const *> ShapeInMSL::hash_msl[SIM_HASH_SIZE]; -List<ShapeInMSL const *> ShapeInMSL::hash_ptr[SIM_HASH_SIZE]; -List<ShapeInMSL const *> ShapeInMSL::hash_name[SIM_HASH_SIZE]; - -int ShapeInMSL::HashMSLFunc(int pos) -{ - return pos & SIM_HASH_MASK; -} - -int ShapeInMSL::HashPtrFunc(SHAPEHEADER * shp) -{ - size_t p = (size_t)shp; - - while (p>=SIM_HASH_SIZE) - p = (p & SIM_HASH_MASK) ^ (p>>SIM_HASH_BITS); - - return (int)p; -} - -int ShapeInMSL::HashNameFunc(char const * nam) -{ - int v = 0; - - while (*nam) v += (unsigned char)toupper(*nam++); - - return v & SIM_HASH_MASK; -} - -ShapeInMSL const * ShapeInMSL::GetByMSL(int pos) -{ - for (LIF<ShapeInMSL const *> i(&hash_msl[HashMSLFunc(pos)]); !i.done(); i.next()) - { - if (i()->listpos == pos) return i(); - } - return 0; -} - -ShapeInMSL const * ShapeInMSL::GetByPtr(SHAPEHEADER * shp) -{ - for (LIF<ShapeInMSL const *> i(&hash_ptr[HashPtrFunc(shp)]); !i.done(); i.next()) - { - if (i()->shptr == shp) return i(); - } - return 0; -} - -ShapeInMSL const * ShapeInMSL::GetByName(char const * nam) -{ - for (LIF<ShapeInMSL const *> i(&hash_name[HashNameFunc(nam)]); !i.done(); i.next()) - { - if (!_stricmp(i()->name,nam)) return i(); - } - return 0; -} - -ShapeInMSL::ShapeInMSL() -: shptr(0) -, listpos(GLS_NOTINLIST) -, in_hash_table(FALSE) -{ -} - -ShapeInMSL::ShapeInMSL(int _p) -: shptr(0) -, listpos(_p) -, in_hash_table(FALSE) -{ -} - -ShapeInMSL::ShapeInMSL(SHAPEHEADER * _s, char const * _n, int _p) -: shptr(_s) -, name(_n) -, listpos(_p) -, in_hash_table(FALSE) -{ - AddToHashTables(); -} - -ShapeInMSL::ShapeInMSL(ShapeInMSL const & sim) -: shptr(sim.shptr) -, name(sim.name) -, listpos(sim.listpos) -, in_hash_table(FALSE) -{ - if (sim.in_hash_table) AddToHashTables(); -} - -ShapeInMSL & ShapeInMSL::operator = (ShapeInMSL const & sim) -{ - if (&sim != this) - { - if (in_hash_table) RemoveFromHashTables(); - shptr = sim.shptr; - name = sim.name; - listpos = sim.listpos; - if (sim.in_hash_table) AddToHashTables(); - } - return *this; -} - -ShapeInMSL::~ShapeInMSL() -{ - if (in_hash_table) RemoveFromHashTables(); -} - - -static List<ShapeInMSL*> msl_shapes; - -void ShapeInMSL::PurgeMSLShapeList() -{ - for(int i=0;i<SIM_HASH_SIZE;i++) - { - while(hash_msl[i].size())hash_msl[i].delete_first_entry(); - while(hash_ptr[i].size())hash_ptr[i].delete_first_entry(); - while(hash_name[i].size())hash_name[i].delete_first_entry(); - } - - while(msl_shapes.size()) - { - ShapeInMSL* shp_msl=msl_shapes.first_entry(); - shp_msl->in_hash_table=FALSE; - delete shp_msl; - msl_shapes.delete_first_entry(); - } -} -void PurgeMSLShapeList() -{ - ShapeInMSL::PurgeMSLShapeList(); -} - -///////////////////////////////////////// -///////////////////////////////////////// -///////////////////////////////////////// - -extern "C" -{ - extern unsigned char *TextureLightingTable; - extern int ScanDrawMode; -}; - - -///////////////////////////////////////// -// Functions which operate on RIFFHANDLEs -///////////////////////////////////////// - -// load a rif file into memory -RIFFHANDLE load_rif (const char * fname) -{ - File_Chunk * fc = new File_Chunk (fname); - - if (fc->error_code != 0) - { - delete fc; - #if OUTPUT_LOG - CL_LogFile.lprintf("FAILED TO LOAD RIF: %s\n",fname); - #endif - ReleaseDirect3D(); - char message[200]; - sprintf(message,"Error loading %s",fname); - MessageBox(NULL,message,"AvP",MB_OK+MB_SYSTEMMODAL); - exit(0x111); - return INVALID_RIFFHANDLE; - } - #if OUTPUT_LOG - CL_LogFile.lprintf("Successfully Loaded RIF: %s\n",fname); - #endif - - RIFFHANDLE h = current_rif_handle = new _RifHandle; - h->fc = Env_Chunk = fc; - - Chunk * pChunk = fc->lookup_single_child("REBENVDT"); - if (pChunk) - { - h->envd = (Environment_Data_Chunk *)pChunk; - } - - return h; -} - -RIFFHANDLE load_rif_non_env (const char * fname) -{ - File_Chunk * fc = new File_Chunk (fname); - - if (fc->error_code != 0) - { - delete fc; - #if OUTPUT_LOG - CL_LogFile.lprintf("FAILED TO LOAD RIF: %s\n",fname); - #endif - - ReleaseDirect3D(); - char message[200]; - sprintf(message,"Error loading %s",fname); - MessageBox(NULL,message,"AvP",MB_OK+MB_SYSTEMMODAL); - exit(0x111); - return INVALID_RIFFHANDLE; - } - #if OUTPUT_LOG - CL_LogFile.lprintf("Successfully Loaded RIF: %s\n",fname); - #endif - - RIFFHANDLE h = current_rif_handle = new _RifHandle; - h->fc = fc; - - Chunk * pChunk = fc->lookup_single_child("REBENVDT"); - if (pChunk) - { - h->envd = (Environment_Data_Chunk *)pChunk; - } - - return h; -} - - -// deallocate the shapes, unload the rif, close the handle -void undo_rif_load (RIFFHANDLE h) -{ - deallocate_loaded_shapes(h); - unload_rif(h); - close_rif_handle(h); -} - -// deallocate the shapes copied from the rif -void deallocate_loaded_shapes (RIFFHANDLE h) -{ - - // because the SHAPEHEADER is calloced, we can - // just delete the arrays we want - - LIF<ShapeInMSL*> msl_shape_lif(&msl_shapes); - - while (h->shape_nums.size()) - { - #if !StandardShapeLanguage - #error Must have standard shape language - #endif - - int list_pos = h->shape_nums.first_entry(); - h->shape_nums.delete_first_entry(); - - DeallocateLoadedShapeheader(mainshapelist[list_pos]); - - FreeMSLPos(list_pos); - - for(msl_shape_lif.restart();!msl_shape_lif.done();msl_shape_lif.next()) - { - if(list_pos==msl_shape_lif()->Listpos()) - { - delete msl_shape_lif(); - msl_shape_lif.delete_current(); - break; - } - } - } - - // ?????????? FIXME - if (Map[0].MapType6Objects) - { - DeallocateMem (Map[0].MapType6Objects); - Map[0].MapType6Objects = 0; - } -} - -// unloads the rif but keeps the handle and associated copied shapes -void unload_rif (RIFFHANDLE h) -{ - if (h->fc) - { - if (h->fc == Env_Chunk) - Env_Chunk = 0; - delete h->fc; - h->fc = 0; - } - h->envd = 0; - h->palparent = 0; - h->max_index = 0; - if (h->tex_index_nos) delete[] h->tex_index_nos; - h->tex_index_nos = 0; -} - -// close the handle - performs tidying up and memory deallocation -void close_rif_handle (RIFFHANDLE h) -{ - delete h; -} - - -////////////////////////////////////////////////////////// - - - -// copies sprite to msl -int copy_sprite_to_mainshapelist(RIFFHANDLE h, Sprite_Header_Chunk * shc, int/* flags*/) -{ - int list_pos = GetMSLPos(); - - copy_sprite_to_shapeheader (h, mainshapelist[list_pos], shc, list_pos); - - post_process_shape(mainshapelist[list_pos]); - - h->shape_nums.add_entry(list_pos); - - return list_pos; -} - -static void setup_tex_conv_array ( - int & max_indices, - int * & conv_array, - RIFFHANDLE h, - Chunk_With_Children * tmpshp - ) -{ - String rif_name; - - max_indices = h->max_index; - conv_array = h->tex_index_nos; - - // find out if its come from elsewhere!!!!!!! - // Doo Dee Doo Doh - // Just come back from the pub - sorry - - Chunk * pChunk = tmpshp->lookup_single_child("SHPEXTFL"); - - Shape_External_File_Chunk * seflc = 0; - Bitmap_List_Store_Chunk * blsc = 0; - - - if (pChunk) - { - seflc = (Shape_External_File_Chunk *)pChunk; - pChunk = seflc->lookup_single_child("BMPLSTST"); - if (pChunk) - { - blsc = (Bitmap_List_Store_Chunk *) pChunk; - } - pChunk = seflc->lookup_single_child("RIFFNAME"); - if (pChunk) - { - rif_name = ((RIF_Name_Chunk *)pChunk)->rif_name; - } - } - - if (blsc) - { - - // load in the textures from the shape - - max_indices = 0; - for (LIF<BMP_Name> bns (&blsc->bmps); !bns.done(); bns.next()) - { - max_indices = max(bns().index,max_indices); - } - - conv_array = new int [max_indices+1]; - for (int i=0; i<=max_indices; i++) - { - conv_array[i] = -1; - } - - if (Env_Chunk == 0) - Env_Chunk = h->fc; - // JH 17-2-97 -- image loaders have changed to avoid loading the same image twice - for (bns.restart() ; !bns.done(); bns.next()) - { - if (!(bns().flags & ChunkBMPFlag_NotInPC)) - { - String tex; - if (bns().flags & ChunkBMPFlag_IFF) - { - tex = bns().filename; - } - else - { - tex = rif_name; - tex += "\\"; - tex += bns().filename; - } - - int imgnum = load_rif_bitmap(tex,bns().flags); - if (GEI_NOTLOADED != imgnum) - conv_array[bns().index] = imgnum; - } - } - - } - -} - -CopyShapeAnimationHeader(SHAPEHEADER* shpfrom,SHAPEHEADER* shpto) -{ - GLOBALASSERT(shpfrom->numitems==shpto->numitems); - GLOBALASSERT(shpfrom->animation_header); - shpto->animation_header=shpfrom->animation_header; - shpto->animation_header->num_shapes_using_this++; - //find a sequence which has some frames; - - shapeanimationsequence* sas=0; - for(int i=0;i<shpto->animation_header->num_sequences;i++) - { - sas=&shpto->animation_header->anim_sequences[i]; - if(sas->num_frames) - break; - - } - GLOBALASSERT(i<shpto->animation_header->num_sequences); - - //copy the pointers for the first frame of this sequence - #if !USE_LEVEL_MEMORY_POOL - DeallocateMem(shpto->points[0]); - DeallocateMem(shpto->sh_normals[0]); - DeallocateMem(shpto->sh_vnormals[0]); - #endif - - shpto->points[0]=sas->anim_frames[0].vertices; - shpto->sh_normals[0]=sas->anim_frames[0].item_normals; - shpto->sh_vnormals[0]=sas->vertex_normals; - -} - -// copies shape to msl -CTM_ReturnType copy_to_mainshapelist(RIFFHANDLE h, Shape_Chunk * tmpshp, int flags,const ChunkObject* object) -{ - int local_max_index; - int * local_tex_index_nos; - - int list_pos = GetMSLPos(); - int main_shape_num = list_pos; - int start_shape_no = list_pos; - String rif_name; - - setup_tex_conv_array (local_max_index, local_tex_index_nos, h, tmpshp); - - - Shape_Preprocessed_Data_Chunk* spdc=(Shape_Preprocessed_Data_Chunk*)tmpshp->lookup_single_child("SHPPRPRO"); - if(spdc) - { - copy_preprocessed_to_shapeheader ( - h, - spdc, - mainshapelist[list_pos], - tmpshp, - flags, - local_max_index, - local_tex_index_nos, - list_pos, - object - ); - } - else - { - - copy_to_shapeheader ( - h, - tmpshp->shape_data, - mainshapelist[list_pos], - tmpshp, - flags, - local_max_index, - local_tex_index_nos, - list_pos, - object - ); - } - - Shape_External_File_Chunk * seflc = 0; - - Chunk * pChunk = tmpshp->lookup_single_child("SHPEXTFL"); - - if (pChunk) - { - seflc = (Shape_External_File_Chunk *)pChunk; - rif_name = seflc->get_shape_name(); - msl_shapes.add_entry(new ShapeInMSL(mainshapelist[list_pos],rif_name,list_pos)); - } - else - { - List<Object_Chunk*> const & oblist=tmpshp->list_assoc_objs(); - if(oblist.size()) - { - Object_Chunk* oc=oblist.first_entry(); - if(oc->get_header()->flags & OBJECT_FLAG_PLACED_OBJECT) - { - msl_shapes.add_entry(new ShapeInMSL(mainshapelist[list_pos],oc->object_data.o_name,list_pos)); - - } - } - } - - post_process_shape(mainshapelist[list_pos]); - - h->shape_nums.add_entry(list_pos); - - if (tmpshp->count_children("ANIMSEQU")) - { - //look for alternate texture mappings - pChunk=tmpshp->lookup_single_child("ASALTTEX"); - if(pChunk) - { - List<Chunk *> chlst; - ((Chunk_With_Children*)pChunk)->lookup_child("SUBSHAPE",chlst); - for(LIF<Chunk*> chlif(&chlst);!chlif.done();chlif.next()) - { - Shape_Sub_Shape_Chunk* sssc=(Shape_Sub_Shape_Chunk*)chlif(); - - list_pos=GetMSLPos(); - copy_to_shapeheader ( - h, - sssc->shape_data, - mainshapelist[list_pos], - sssc, - flags, - local_max_index, - local_tex_index_nos, - list_pos, - object - ); - CopyShapeAnimationHeader(mainshapelist[start_shape_no],mainshapelist[list_pos]); - - const char* shpname=sssc->get_shape_name(); - GLOBALASSERT(shpname); - msl_shapes.add_entry(new ShapeInMSL(mainshapelist[list_pos],shpname,list_pos)); - h->shape_nums.add_entry(list_pos); - - post_process_shape(mainshapelist[list_pos]); - - } - } - } - - Shape_Fragments_Chunk * sfc = 0; - - pChunk = tmpshp->lookup_single_child ("SHPFRAGS"); - - if (pChunk) - { - sfc = (Shape_Fragments_Chunk *)pChunk; - - pChunk=sfc->lookup_single_child("SHPFRGTP"); - if(pChunk) - { - //the shape is using a fragment type - Shape_Fragment_Type_Chunk* sftc=(Shape_Fragment_Type_Chunk*)pChunk; - ApplyFragTypeToShape(mainshapelist[main_shape_num],sftc->frag_type_name); - } - else - { - List<Chunk *> cl; - sfc->lookup_child ("SUBSHAPE", cl); - if (cl.size()) - { - mainshapelist[main_shape_num]->sh_fragdesc = (SHAPEFRAGMENTDESC *)PoolAllocateMem(sizeof(SHAPEFRAGMENTDESC)); - - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags = (SHAPEFRAGMENT *)PoolAllocateMem((cl.size()+1) * sizeof(SHAPEFRAGMENT)); - mainshapelist[main_shape_num]->sh_fragdesc->sh_fragsound = 0; - - int fragpos = 0; - - for (LIF<Chunk *> cli(&cl); !cli.done(); cli.next(), fragpos++) - { - Shape_Sub_Shape_Chunk * sssc = ((Shape_Sub_Shape_Chunk *)cli()); - - list_pos = GetMSLPos(); - - - copy_to_shapeheader ( - h, - sssc->shape_data, - mainshapelist[list_pos], - sssc, - flags, - local_max_index, - local_tex_index_nos, - list_pos, - object - ); - post_process_shape(mainshapelist[list_pos]); - h->shape_nums.add_entry(list_pos); - - int num_frags = 1; - - pChunk = sssc->lookup_single_child("FRAGDATA"); - if (pChunk) - { - num_frags = ((Shape_Fragments_Data_Chunk *)pChunk)->num_fragments; - } - - Shape_Fragment_Location_Chunk * sflc = 0; - - pChunk = sssc->lookup_single_child("FRAGLOCN"); - if (pChunk) - { - sflc = (Shape_Fragment_Location_Chunk *)pChunk; - } - - - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].ShapeIndex = list_pos; - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].NumFrags = num_frags; - - if (sflc) - { - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].x_offset = sflc->frag_loc.x * local_scale; - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].y_offset = sflc->frag_loc.y * local_scale; - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].z_offset = sflc->frag_loc.z * local_scale; - - } - else - { - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].x_offset = 0; - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].y_offset = 0; - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].z_offset = 0; - } - - } - - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].ShapeIndex = -1; - mainshapelist[main_shape_num]->sh_fragdesc->sh_frags[fragpos].NumFrags = -1; - - //see if fragment has a sound to go with it - Fragment_Type_Sound_Chunk* ftsoc=(Fragment_Type_Sound_Chunk*) sfc->lookup_single_child("FRGSOUND"); - if(ftsoc) - { - mainshapelist[main_shape_num]->sh_fragdesc->sh_fragsound=(SHAPEFRAGMENTSOUND*)PoolAllocateMem(sizeof(SHAPEFRAGMENTSOUND)); - mainshapelist[main_shape_num]->sh_fragdesc->sh_fragsound->sound_loaded=GetSoundForMainRif (ftsoc->wav_name); - mainshapelist[main_shape_num]->sh_fragdesc->sh_fragsound->inner_range=ftsoc->inner_range*local_scale; - mainshapelist[main_shape_num]->sh_fragdesc->sh_fragsound->outer_range=ftsoc->outer_range*local_scale; - mainshapelist[main_shape_num]->sh_fragdesc->sh_fragsound->pitch=ftsoc->pitch; - mainshapelist[main_shape_num]->sh_fragdesc->sh_fragsound->max_volume=ftsoc->max_volume; - } - - - } - } - } - - #if SupportMorphing && LOAD_MORPH_SHAPES - - /*-------------------** - ** Morphing stuff ** - **-------------------*/ - MORPHCTRL * mc = 0; - - if (!(flags & CCF_NOMORPH)) - { - pChunk = tmpshp->lookup_single_child ("SHPMORPH"); - if (pChunk) - { - // this shape has some morphing data - - // (store the list no. of the shape) - Shape_Morphing_Data_Chunk * smdc = (Shape_Morphing_Data_Chunk *)pChunk; - - // set all the subshape list_pos numbers to -1 - // so later we can check to see if it has already been loaded - List<Chunk *> chlst; - smdc->lookup_child("SUBSHAPE",chlst); - for (LIF<Chunk *> ssi(&chlst); !ssi.done(); ssi.next()) - { - ((Shape_Sub_Shape_Chunk *)ssi())->list_pos_number = -1; - } - - pChunk = smdc->lookup_single_child("FRMMORPH"); - if (pChunk) - { - Shape_Morphing_Frame_Data_Chunk * smfdc = (Shape_Morphing_Frame_Data_Chunk *)pChunk; - // Check there are some frames!! - if (smfdc->anim_frames.size()) - { - mc = (MORPHCTRL *)AllocateMem(sizeof(MORPHCTRL)); - mc->ObMorphFlags = smfdc->a_flags; - mc->ObMorphSpeed = smfdc->a_speed; - MORPHHEADER * mh = (MORPHHEADER *)AllocateMem(sizeof(MORPHHEADER)); - mc->ObMorphHeader = mh; - mh->mph_numframes = 0; - mh->mph_frames = (MORPHFRAME *)AllocateMem(sizeof(MORPHFRAME) * (smfdc->anim_frames.size()) ); - - int frame_no = 0; - - for (LIF<a_frame *> afi(&smfdc->anim_frames); !afi.done(); afi.next()) - { - if (afi()->shape1a) - { - if (afi()->shape1a->list_pos_number == -1) - { - list_pos = GetMSLPos(); - - Shape_Preprocessed_Data_Chunk* spdc=(Shape_Preprocessed_Data_Chunk*)afi()->shape1a->lookup_single_child("SHPPRPRO"); - if(spdc) - { - copy_preprocessed_to_shapeheader ( - h, - spdc, - mainshapelist[list_pos], - afi()->shape1a, - flags, - local_max_index, - local_tex_index_nos, - list_pos, - object - ); - } - else - { - - copy_to_shapeheader ( - h, - afi()->shape1a->shape_data, - mainshapelist[list_pos], - afi()->shape1a, - flags, - local_max_index, - local_tex_index_nos, - list_pos, - object - ); - } - - post_process_shape(mainshapelist[list_pos]); - afi()->shape1a->list_pos_number = list_pos; - h->shape_nums.add_entry(list_pos); - /* - Copy the item data for this door shape from the main shape. This is largely done to cope - with the problem of the polygons being merged differently in different morph shapes. - */ - SHAPEHEADER* main_shape=mainshapelist[main_shape_num]; - SHAPEHEADER* this_shape=mainshapelist[list_pos]; - - this_shape->numitems=main_shape->numitems; - this_shape->items=main_shape->items; - this_shape->sh_textures=main_shape->sh_textures; - this_shape->sh_normals=main_shape->sh_normals; - - //update shape instructions (probably not uses anyway) - this_shape->sh_instruction[1].sh_numitems=main_shape->numitems; - this_shape->sh_instruction[1].sh_instr_data=main_shape->sh_normals; - - this_shape->sh_instruction[4].sh_numitems=main_shape->numitems; - this_shape->sh_instruction[4].sh_instr_data=main_shape->items; - - } - mh->mph_frames[frame_no].mf_shape1 = afi()->shape1a->list_pos_number; - } - else - { - mh->mph_frames[frame_no].mf_shape1 = main_shape_num; - } - - if (afi()->shape2a) - { - if (afi()->shape2a->list_pos_number == -1) - { - list_pos = GetMSLPos(); - - Shape_Preprocessed_Data_Chunk* spdc=(Shape_Preprocessed_Data_Chunk*)afi()->shape2a->lookup_single_child("SHPPRPRO"); - if(spdc) - { - copy_preprocessed_to_shapeheader ( - h, - spdc, - mainshapelist[list_pos], - afi()->shape1a, - flags, - local_max_index, - local_tex_index_nos, - list_pos, - object - ); - } - else - { - - copy_to_shapeheader ( - h, - afi()->shape2a->shape_data, - mainshapelist[list_pos], - afi()->shape2a, - 0, - local_max_index, - local_tex_index_nos, - list_pos, - object - ); - } - post_process_shape(mainshapelist[list_pos]); - afi()->shape2a->list_pos_number = list_pos; - h->shape_nums.add_entry(list_pos); - - /* - Copy the item data for this door shape from the main shape. This is largely done to cope - with the problem of the polygons being merged differently in different morph shapes. - */ - SHAPEHEADER* main_shape=mainshapelist[main_shape_num]; - SHAPEHEADER* this_shape=mainshapelist[list_pos]; - - this_shape->numitems=main_shape->numitems; - this_shape->items=main_shape->items; - this_shape->sh_textures=main_shape->sh_textures; - this_shape->sh_normals=main_shape->sh_normals; - - //update shape instructions (probably not uses anyway) - this_shape->sh_instruction[1].sh_numitems=main_shape->numitems; - this_shape->sh_instruction[1].sh_instr_data=main_shape->sh_normals; - - this_shape->sh_instruction[4].sh_numitems=main_shape->numitems; - this_shape->sh_instruction[4].sh_instr_data=main_shape->items; - } - mh->mph_frames[frame_no].mf_shape2 = afi()->shape2a->list_pos_number; - } - else - { - mh->mph_frames[frame_no].mf_shape2 = main_shape_num; - } - if (frame_no == 0) - { - start_shape_no = mh->mph_frames[frame_no].mf_shape1; - } - frame_no ++; - } - mh->mph_numframes = frame_no; - mh->mph_maxframes = frame_no << 16; - } - } - } - } - - CTM_ReturnType retval = { start_shape_no, main_shape_num, mc }; - if(local_tex_index_nos!=h->tex_index_nos) delete [] local_tex_index_nos; - return retval; - - #else - - if(local_tex_index_nos!=h->tex_index_nos) delete [] local_tex_index_nos; - return list_pos; - - #endif -} - -// load textures for environment -BOOL load_rif_bitmaps (RIFFHANDLE h, int/* flags*/) -{ - Global_BMP_Name_Chunk * gbnc = 0; - - if (h->envd) - { - Chunk * pChunk = h->envd->lookup_single_child ("BMPNAMES"); - if (pChunk) gbnc = (Global_BMP_Name_Chunk *) pChunk; - } - - h->max_index = 0; - - if (gbnc) - { - for (LIF<BMP_Name> bns (&gbnc->bmps); !bns.done(); bns.next()) - { - h->max_index = max(bns().index,h->max_index); - } - - if (h->tex_index_nos) delete h->tex_index_nos; - h->tex_index_nos = new int [h->max_index+1]; - for (int i=0; i<=h->max_index; i++) - { - h->tex_index_nos[i] = -1; - } - - if (Env_Chunk == 0) - Env_Chunk = h->fc; - for (bns.restart() ; !bns.done(); bns.next()) - { - if (!(bns().flags & ChunkBMPFlag_NotInPC)) - { - // JH 17-2-97 -- image loaders have changed to avoid loading the same image twice - int imgnum = load_rif_bitmap(bns().filename,bns().flags); - if (GEI_NOTLOADED != imgnum) - h->tex_index_nos[bns().index] = imgnum; - } - } - - return TRUE; - } - else return FALSE; -} - -// set the quantization event depending on cl_pszGameMode -BOOL set_quantization_event(RIFFHANDLE h, int /*flags*/) -{ - if (h->envd) - { - h->palparent = h->envd; - - if (cl_pszGameMode) - { - List<Chunk *> egmcs; - h->envd->lookup_child("GAMEMODE",egmcs); - - for (LIF<Chunk *> egmcLIF(&egmcs); !egmcLIF.done(); egmcLIF.next()) - { - Environment_Game_Mode_Chunk * egmcm = (Environment_Game_Mode_Chunk *) egmcLIF(); - if (egmcm->id_equals(cl_pszGameMode)) - { - h->palparent = egmcm; - break; - } - } - - } - - return TRUE; - } - else - { - h->palparent = 0; - return FALSE; - } -} - -// copy palette -BOOL copy_rif_palette (RIFFHANDLE h, int /*flags*/) -{ - if (h->palparent) - { - List<Chunk *> chlst; - h->palparent->lookup_child("ENVPALET",chlst); - for (LIF<Chunk *> i_ch(&chlst); !i_ch.done(); i_ch.next()) - { - Environment_Palette_Chunk * palch = (Environment_Palette_Chunk *)i_ch(); - if (!(palch->flags & EnvPalFlag_V2) && palch->width*palch->height <= 256 ) - { - for (int i=0; i<palch->width*palch->height*3; i++) - { - TestPalette[i] = (unsigned char)(palch->pixel_data[i] >> 2); - } - return TRUE; - } - } - } - - return FALSE; -} - -// copy texture lighting table -BOOL copy_rif_tlt (RIFFHANDLE h, int /*flags*/) -{ - if (h->palparent) - { - List<Chunk *> chlst; - h->palparent->lookup_child("ENVTXLIT",chlst); - if(TextureLightingTable) - { - DeallocateMem(TextureLightingTable); - TextureLightingTable = 0; - } - for (LIF<Chunk *> i_ch(&chlst); !i_ch.done(); i_ch.next()) - { - Environment_TLT_Chunk * tltch = (Environment_TLT_Chunk *)i_ch(); - - if ((tltch->flags & ChunkTLTFlag_V2 && - ScreenDescriptorBlock.SDB_Flags & SDB_Flag_TLTPalette || - !(tltch->flags & ChunkTLTFlag_V2) && - !(ScreenDescriptorBlock.SDB_Flags & SDB_Flag_TLTPalette)) && - tltch->table - ){ - TextureLightingTable = (unsigned char*)AllocateMem(tltch->width * tltch->num_levels); - memcpy(TextureLightingTable,tltch->table,tltch->width*tltch->num_levels); - if (ScreenDescriptorBlock.SDB_Flags & SDB_Flag_TLTPalette) - { - ScreenDescriptorBlock.SDB_Flags &= ~(SDB_Flag_TLTSize|SDB_Flag_TLTShift); - if (tltch->width != 256) - { - ScreenDescriptorBlock.SDB_Flags |= SDB_Flag_TLTSize; - ScreenDescriptorBlock.TLTSize = tltch->width; - for (int shft = 0; 1<<shft < tltch->width; ++shft) - ; - if (1<<shft==tltch->width) - { - ScreenDescriptorBlock.SDB_Flags |= SDB_Flag_TLTShift; - ScreenDescriptorBlock.TLTShift = shft; - } - } - } - return TRUE; - } - - } - } - - return FALSE; -} - -// copy palette remap table (15-bit) - post_process_shape may use it -BOOL get_rif_palette_remap_table (RIFFHANDLE h, int /*flags*/) -{ - PaletteMapTable = 0; - if (h->palparent) - { - Chunk * pChunk = h->palparent->lookup_single_child("CLRLOOKP"); - if (pChunk) - { - Coloured_Polygons_Lookup_Chunk * cplook = (Coloured_Polygons_Lookup_Chunk *)pChunk; - - if (cplook->table) - { - PaletteMapTable = cplook->table; - return TRUE; - } - - } - } - - return FALSE; -} - -// copy one named shape or sprite; intended to go in position listpos -static SHAPEHEADER * CreateShapeFromRif (RIFFHANDLE h, char const * shapename, int listpos = GLS_NOTINLIST) -{ - if (!h->fc) return 0; // no rif file loaded - - List<Chunk *> shape_chunks; - h->fc->lookup_child("REBSHAPE",shape_chunks); - - for (LIF<Chunk *> search(&shape_chunks); !search.done(); search.next()) - { - Shape_Chunk * cur_shape = (Shape_Chunk *) search(); - - Chunk * pShpextfile = cur_shape->lookup_single_child("SHPEXTFL"); - - if (pShpextfile) - { - Shape_External_File_Chunk * shexdata = (Shape_External_File_Chunk *) pShpextfile; - - Chunk * pRnc = shexdata->lookup_single_child("RIFFNAME"); - if (pRnc) - { - RIF_Name_Chunk * rnc = (RIF_Name_Chunk *) pRnc; - if (!_stricmp(rnc->rif_name,shapename)) // haha! matching shape found - { - SHAPEHEADER * shptr = 0; - int local_max_index; - int * local_tex_index_nos; - setup_tex_conv_array (local_max_index, local_tex_index_nos, h, cur_shape); - - copy_to_shapeheader( - h, - cur_shape->shape_data, - shptr, - cur_shape, - 0, - local_max_index, - local_tex_index_nos, - listpos - ); - if(local_tex_index_nos!=h->tex_index_nos) delete [] local_tex_index_nos; - - return shptr; - } - } - } - } - //look to see if is a sprite - Chunk * pSprite_chunks = h->fc->lookup_single_child("RSPRITES"); - if(pSprite_chunks) - { - AllSprites_Chunk* asc=(AllSprites_Chunk*) pSprite_chunks; - List<Chunk *> sprite_chunks; - asc->lookup_child("SPRIHEAD",sprite_chunks); - for(LIF<Chunk*> slif(&sprite_chunks);!slif.done();slif.next()) - { - Sprite_Header_Chunk* shc=(Sprite_Header_Chunk*)slif(); - Chunk * pRn=shc->lookup_single_child("RIFFNAME"); - if(pRn) - { - RIF_Name_Chunk* rnc=(RIF_Name_Chunk*)pRn; - if (!_stricmp(rnc->rif_name,shapename)) // haha! matching sprite found - { - SHAPEHEADER * shptr = 0; - copy_sprite_to_shapeheader(h,shptr, shc, listpos); - return shptr; - } - } - - } - } - return 0; // could not match shape -} - -// copy one named shape or sprite; does not put in main shape list -SHAPEHEADER * CopyNamedShapePtr (RIFFHANDLE h, char const * shapename) -{ - return CreateShapeFromRif(h,shapename); -} - -// copy one named shape or sprite; put it in the main shape list -int CopyNamedShapeMSL (RIFFHANDLE h, char const * shapename) -{ - int listpos = GetMSLPos(); - SHAPEHEADER * shp = CreateShapeFromRif(h,shapename,listpos); - if (shp) - { - h->shape_nums.add_entry(listpos); - mainshapelist[listpos] = shp; - return listpos; - } - else - { - FreeMSLPos(listpos); - return GLS_NOTINLIST; - } -} - -//////////////////////////////////////////////////////////////////////// -// Functions which do not operate on RIFFHANDLEs and may become obsolete -//////////////////////////////////////////////////////////////////////// - -SHAPEHEADER * CopyNamedShape (char const * shapename) -{ - return CopyNamedShapePtr (current_rif_handle,shapename); -} - -///////////////////////////////////////////// -// Functions for handling the main shape list -///////////////////////////////////////////// - -//////////////////////////////////////////////// -// Functions retrieving data about loaded shapes -//////////////////////////////////////////////// - -// gets the main shape list position of a shape loaded into the msl -int GetLoadedShapeMSL(char const * shapename) -{ - ShapeInMSL const * sim = ShapeInMSL::GetByName(shapename); - - if (sim) - return sim->Listpos(); - else - return GLS_NOTINLIST; -} - -// ditto, but returns a pointer; the shape need not be in the msl -SHAPEHEADER * GetLoadedShapePtr(char const * shapename) -{ - ShapeInMSL const * sim = ShapeInMSL::GetByName(shapename); - - if (sim) - return sim->Shptr(); - else - return 0; -} - -// gets name of shape from msl pos -char const * GetMSLLoadedShapeName(int listpos) -{ - ShapeInMSL const * sim = ShapeInMSL::GetByMSL(listpos); - - if (sim) - return sim->Name(); - else - return 0; -} - -// gets name of shape from pointer; the shape need not be in msl -char const * GetPtrLoadedShapeName(SHAPEHEADER * shptr) -{ - ShapeInMSL const * sim = ShapeInMSL::GetByPtr(shptr); - - if (sim) - return sim->Name(); - else - return 0; -} - -// free a reference to a named shape if it exists - not necessary since these are all tidied up -void FreeShapeNameReference(SHAPEHEADER * shptr) -{ - for (LIF<ShapeInMSL*> search(&msl_shapes); !search.done(); search.next()) - { - if (search()->Shptr() == shptr) - { - delete search(); - search.delete_current(); - break; - } - } - - return; -} - -////////////////////////////////////////////////////////////////////////////// -// Initializing, deallocating of shapes, mainly hooks for project specific fns -////////////////////////////////////////////////////////////////////////////// - -// delete a shape by the shapeheader -void DeallocateLoadedShapePtr(SHAPEHEADER * shp) -{ - DeallocateLoadedShapeheader(shp); - - FreeShapeNameReference(shp); -} - -// delete a shape by the shape list number -void DeallocateLoadedShapeMSL(RIFFHANDLE h, int list_pos) -{ - h->shape_nums.delete_entry(list_pos); - - DeallocateLoadedShapeheader(mainshapelist[list_pos]); - - FreeMSLPos(list_pos); - - for(LIF<ShapeInMSL*> msl_shape_lif(&msl_shapes);!msl_shape_lif.done();msl_shape_lif.next()) - { - if(list_pos==msl_shape_lif()->Listpos()) - { - delete msl_shape_lif(); - msl_shape_lif.delete_current(); - break; - } - } -} - -void DeallocateRifLoadedShapeheader(SHAPEHEADER * shp) -{ - // because the SHAPEHEADER is calloced, we can - // just delete the arrays we want - - #if !StandardShapeLanguage - #error Must have standard shape language - #endif - - int max_num_texs = 0; - int i; - - if(shp->animation_header) - { - // so it gets deallocated properly - shp->points[0] = 0; - shp->sh_normals[0] = 0; - shp->sh_vnormals[0] = 0; - } - if (shp->sh_fragdesc) - { - DeallocateFragments(shp,shp->sh_fragdesc); - } - - #if !USE_LEVEL_MEMORY_POOL - if (shp->points) - { - if (*shp->points) DeallocateMem(*shp->points); - DeallocateMem(shp->points); - } - if (shp->sh_normals) - { - if (*shp->sh_normals) DeallocateMem(*shp->sh_normals); - DeallocateMem(shp->sh_normals); - } - if (shp->sh_vnormals) - { - if (*shp->sh_vnormals) DeallocateMem(*shp->sh_vnormals); - DeallocateMem(shp->sh_vnormals); - } - if (shp->sh_extraitemdata) - DeallocateMem(shp->sh_extraitemdata); - /* the items are allocated in one big bunch - // 9 int's per item (to make bsp simple) - // this should be changed if it is to be done - // a different way - */ - if (shp->items) - { - if(shp->shapeflags & ShapeFlag_MultiViewSprite) - { - TXANIMHEADER** thlist=(TXANIMHEADER**)shp->sh_textures[0]; - for(int j=1;thlist[j]!=0;j++) - { - int k; - TXANIMHEADER* th=thlist[j]; - for(k=0;k<th->txa_numframes;k++) - { - txanimframe_mvs* tf=(txanimframe_mvs*)&th->txa_framedata[k]; - if(tf->txf_uvdata[0])DeallocateMem(tf->txf_uvdata[0]); - if(tf->txf_uvdata)DeallocateMem(tf->txf_uvdata); - if(tf->txf_images)DeallocateMem(tf->txf_images); - } - if(th->txa_framedata)DeallocateMem (th->txa_framedata); - DeallocateMem (th); - } - DeallocateMem (thlist); - shp->sh_textures[0]=0; - } - else - { - for (i=0; i<shp->numitems; i++) - { - if (is_textured(shp->items[i][0])) - { - int UVIndex = (shp->items[i][3] &0xffff0000) >> 16; - max_num_texs = max (max_num_texs, shp->items[i][3] &0x7fff); - if(shp->items[i][2]& iflag_txanim) - { - int j; - TXANIMHEADER** thlist=(TXANIMHEADER**)shp->sh_textures[UVIndex]; - for(j=1;thlist[j]!=0;j++) - { - int k; - TXANIMHEADER* th=thlist[j]; - for(k=0;k<th->txa_numframes;k++) - { - if(th->txa_framedata[k].txf_uvdata)DeallocateMem(th->txa_framedata[k].txf_uvdata); - } - if(th->txa_framedata)DeallocateMem (th->txa_framedata); - DeallocateMem (th); - } - DeallocateMem (thlist); - shp->sh_textures[UVIndex]=0; - } - else - { - if(shp->sh_textures[UVIndex])DeallocateMem(shp->sh_textures[UVIndex]); - } - } - } - } - DeallocateMem (*shp->items); - DeallocateMem (shp->items); - } - - if (shp->sh_textures) - { - DeallocateMem (shp->sh_textures); - } - - if (shp->sh_localtextures) - { - for (i=0; i<(max_num_texs+1); i++) - { - DeallocateMem (shp->sh_localtextures[i]); - } - DeallocateMem (shp->sh_localtextures); - } - - - - #if SupportTrackOptimisation - if (shp->sh_track_data) - DeallocateMem(shp->sh_track_data); - #endif - if (shp->sh_instruction) - DeallocateMem(shp->sh_instruction); - #if SupportBSP - if (shp->sh_bsp_blocks) - DeallocateMem(shp->sh_bsp_blocks); - #endif - - if(shp->animation_header) - { - shp->animation_header->num_shapes_using_this--; - if(shp->animation_header->num_shapes_using_this==0) - { - shapeanimationheader* sah=shp->animation_header; - for(int i=0;i<sah->num_sequences;i++) - { - shapeanimationsequence* sas=&sah->anim_sequences[i]; - for(int j=0;j<sas->num_frames;j++) - { - shapeanimationframe*saf=&sas->anim_frames[j]; - DeallocateMem(saf->vertices); - DeallocateMem(saf->item_normals); - } - if(sas->vertex_normals)DeallocateMem(sas->vertex_normals); - if(sas->anim_frames)DeallocateMem(sas->anim_frames); - } - DeallocateMem(sah->anim_sequences); - DeallocateMem(sah); - } - } - - if(shp->shape_degradation_array) - { - DeallocateMem(shp->shape_degradation_array); - } - - DeallocateMem(shp); - #endif //!USE_LEVEL_MEMORY_POOL -} - -/////// -// Misc -/////// - -// return TRUE if the poly item type corresponds to a textured polygon -BOOL is_textured (int type) -{ - if ( - type == I_2dTexturedPolygon - || type == I_Gouraud2dTexturedPolygon - || type == I_3dTexturedPolygon - || type == I_Gouraud3dTexturedPolygon - || type == I_ZB_2dTexturedPolygon - || type == I_ZB_Gouraud2dTexturedPolygon - || type == I_ZB_3dTexturedPolygon - || type == I_ZB_Gouraud3dTexturedPolygon - ) - { - return(TRUE); - } - return(FALSE); -} - - -#if SupportModules - -// static Object_Chunk ** o_chunk_array; - -void copy_to_module (Object_Chunk * ob, int mod_pos, int shplst_pos) -{ - Object_Project_Data_Chunk * opdc = 0; - Map_Block_Chunk * mapblok = 0; - Strategy_Chunk * strat = 0; - - MODULEMAPBLOCK * Map = (MODULEMAPBLOCK *) PoolAllocateMem (sizeof(MODULEMAPBLOCK)); - - *Map = Empty_Module_Map; - - MainScene.sm_module[mod_pos].m_mapptr = Map; - MainScene.sm_module[mod_pos].name = (char *) PoolAllocateMem (strlen (ob->object_data.o_name)+1); - strcpy (MainScene.sm_module[mod_pos].name, ob->object_data.o_name); - - *((int *)MainScene.sm_module[mod_pos].m_name) = mod_pos + ONE_FIXED; - // add 65536 to this value to this value to preserve 0 - - Chunk * pChunk = ob->lookup_single_child("OBJPRJDT"); - if (pChunk) opdc = (Object_Project_Data_Chunk *)pChunk; - if (opdc) - { - pChunk = opdc->lookup_single_child("MAPBLOCK"); - if (pChunk) mapblok = (Map_Block_Chunk *)pChunk; - pChunk = opdc->lookup_single_child("STRATEGY"); - if (pChunk) strat = (Strategy_Chunk *)pChunk; - } - - if (mapblok) - { - Map->MapType = mapblok->map_data.MapType; - Map->MapFlags= mapblok->map_data.MapFlags; - #if (StandardStrategyAndCollisions || IntermediateSSACM) - Map->MapCType = mapblok->map_data.MapCType; - Map->MapCGameType = mapblok->map_data.MapCGameType; - Map->MapCStrategyS = mapblok->map_data.MapCStrategyS; - Map->MapCStrategyL = mapblok->map_data.MapCStrategyL; - #endif - Map->MapInteriorType = mapblok->map_data.MapInteriorType; -// Map->MapLightType = mapblok->map_data.MapLightType; -// Map->MapMass = mapblok->map_data.MapMass; -// Map->MapNewtonV.vx = mapblok->map_data.MapNewtonV.vx; -// Map->MapNewtonV.vy = mapblok->map_data.MapNewtonV.vy; -// Map->MapNewtonV.vz = mapblok->map_data.MapNewtonV.vz; -// Map->MapOrigin.vx = mapblok->map_data.MapOrigin.vx; -// Map->MapOrigin.vy = mapblok->map_data.MapOrigin.vy; -// Map->MapOrigin.vz = mapblok->map_data.MapOrigin.vz; -// Map->MapViewType = mapblok->map_data.MapViewType; - } - - #if (StandardStrategyAndCollisions || IntermediateSSACM) - if (strat) - { - Map->MapStrategy = strat->strategy_data.Strategy; - } - #endif - - Map->MapShape = shplst_pos; - - Map->MapWorld.vx = (int) (ob->object_data.location.x*local_scale); - Map->MapWorld.vy = (int) (ob->object_data.location.y*local_scale); - Map->MapWorld.vz = (int) (ob->object_data.location.z*local_scale); - -#if 0 - QUAT q; - - q.quatx = (int) (ob->object_data.orientation.x*ONE_FIXED); - q.quaty = (int) (ob->object_data.orientation.y*ONE_FIXED); - q.quatz = (int) (ob->object_data.orientation.z*ONE_FIXED); - q.quatw = (int) (ob->object_data.orientation.w*ONE_FIXED); - - - MATRIXCH m; - - QuatToMat (&q, &m); - - EULER e; - - MatrixToEuler(&m, &e); - - Map->MapEuler.EulerX = -e.EulerX; - Map->MapEuler.EulerY = -e.EulerY; - Map->MapEuler.EulerZ = -e.EulerZ; - -#endif - - -} - -#endif - -void SetupAnimOnTriangle(SHAPEHEADER* shp,TEXANIM* ta,int poly, int * local_tex_index_nos) -{ - if(!is_textured(shp->items[poly][0]))return; - txanimheader** thlist=(txanimheader**)PoolAllocateMem((ta->NumSeq+2)*sizeof(txanimheader*)); - thlist[0]=0; - thlist[ta->NumSeq+1]=0; - for(int i=0;i<ta->NumSeq;i++) - { - thlist[i+1]=(txanimheader*)PoolAllocateMem(sizeof(txanimheader)); - txanimheader* th=thlist[i+1]; - - FrameList* fl=ta->Seq[i]; - th->txa_flags=fl->Flags; - if(!(ta->AnimFlags & AnimFlag_NotPlaying))th->txa_flags|=txa_flag_play; - th->txa_numframes=fl->NumFrames+1; - if(fl->Flags & txa_flag_nointerptofirst) - { - th->txa_flags&=~txa_flag_nointerptofirst; - th->txa_numframes--; - } - th->txa_currentframe=0; - th->txa_state=0; - th->txa_maxframe=(th->txa_numframes-1)<<16; - th->txa_speed=fl->Speed; - th->txa_framedata=(txanimframe*)PoolAllocateMem(th->txa_numframes*sizeof(txanimframe)); - th->txa_anim_id=ta->Identifier; - - txanimframe* tf; - for(int j=0;j<th->txa_numframes;j++) - { - tf=&th->txa_framedata[j]; - tf->txf_flags=0; - tf->txf_scale=ONE_FIXED; - tf->txf_scalex=0; - tf->txf_scaley=0; - tf->txf_orient=0; - tf->txf_orientx=0; - tf->txf_orienty=0; - tf->txf_numuvs=3; - tf->txf_uvdata=(int*)PoolAllocateMem(6*sizeof(int)); - if(j==fl->NumFrames) - { - tf->txf_image=local_tex_index_nos[fl->Textures[0]]; - for(int k=0;k<6;k++) - { - tf->txf_uvdata[k]=fl->UVCoords[k]<<16; - } - } - else - { - tf->txf_image=local_tex_index_nos[fl->Textures[j]]; - for(int k=0;k<6;k++) - { - tf->txf_uvdata[k]=fl->UVCoords[j*6+k]<<16; - } - } - } - } - int UVIndex=shp->items[poly][3]>>16; - #if !USE_LEVEL_MEMORY_POOL - if(shp->sh_textures[UVIndex])DeallocateMem(shp->sh_textures[UVIndex]); - #endif - shp->sh_textures[UVIndex]=(int*)thlist; - shp->items[poly][2]|=iflag_txanim; - shp->items[poly][3]=UVIndex<<16; - -} -void SetupAnimOnQuad(Shape_Chunk* sc,SHAPEHEADER* shp,TEXANIM* ta1,TEXANIM* ta2,int poly, int * local_tex_index_nos) -{ - if(!is_textured(shp->items[poly][0]))return; - if(ta1->ID!=ta2->ID)return; - int VertConv[3];//conversion between vert nos in triangles and vert nos in quad - int VertFrom,VertTo;//for remaining vert in second poly - VertTo=6; - for(int i=0;i<3;i++) - { - for(int j=0;j<4;j++) - { - if(sc->shape_data.poly_list[ta1->poly].vert_ind[i]==(shp->items[poly][j+4]))break; - } - if(j==4)return; - VertConv[i]=j; - VertTo-=j; - } - for(i=0;i<3;i++) - { - if(sc->shape_data.poly_list[ta2->poly].vert_ind[i]==(shp->items[poly][4+VertTo]))break; - } - if(i==3)return; - VertFrom=i; - - txanimheader** thlist=(txanimheader**)PoolAllocateMem((ta1->NumSeq+2)*sizeof(txanimheader*)); - thlist[0]=0; - thlist[ta1->NumSeq+1]=0; - for(i=0;i<ta1->NumSeq;i++) - { - thlist[i+1]=(txanimheader*)PoolAllocateMem(sizeof(txanimheader)); - txanimheader* th=thlist[i+1]; - FrameList* fl1=ta1->Seq[i]; - FrameList* fl2=ta2->Seq[i]; - th->txa_flags=fl1->Flags; - if(!(ta1->AnimFlags & AnimFlag_NotPlaying))th->txa_flags|=txa_flag_play; - th->txa_numframes=fl1->NumFrames+1; - if(fl1->Flags & txa_flag_nointerptofirst) - { - th->txa_flags&=~txa_flag_nointerptofirst; - th->txa_numframes--; - } - th->txa_currentframe=0; - th->txa_state=0; - th->txa_maxframe=(th->txa_numframes-1)<<16; - th->txa_speed=fl1->Speed; - th->txa_framedata=(txanimframe*)PoolAllocateMem(th->txa_numframes*sizeof(txanimframe)); - th->txa_anim_id=ta1->Identifier; - - txanimframe* tf; - for(int j=0;j<th->txa_numframes;j++) - { - tf=&th->txa_framedata[j]; - tf->txf_flags=0; - tf->txf_scale=ONE_FIXED; - tf->txf_scalex=0; - tf->txf_scaley=0; - tf->txf_orient=0; - tf->txf_orientx=0; - tf->txf_orienty=0; - tf->txf_numuvs=4; - tf->txf_uvdata=(int*)PoolAllocateMem(8*sizeof(int)); - if(j==fl1->NumFrames) - { - tf->txf_image=local_tex_index_nos[fl1->Textures[0]]; - for(int k=0;k<3;k++) - { - tf->txf_uvdata[VertConv[k]*2]=fl1->UVCoords[k*2]<<16; - tf->txf_uvdata[VertConv[k]*2+1]=fl1->UVCoords[k*2+1]<<16; - } - tf->txf_uvdata[VertTo*2]=fl2->UVCoords[VertFrom*2]<<16; - tf->txf_uvdata[VertTo*2+1]=fl2->UVCoords[VertFrom*2+1]<<16; - - } - else - { - tf->txf_image=local_tex_index_nos[fl1->Textures[j]]; - for(int k=0;k<3;k++) - { - tf->txf_uvdata[VertConv[k]*2]=fl1->UVCoords[j*6+k*2]<<16; - tf->txf_uvdata[VertConv[k]*2+1]=fl1->UVCoords[j*6+k*2+1]<<16; - } - tf->txf_uvdata[VertTo*2]=fl2->UVCoords[j*6+VertFrom*2]<<16; - tf->txf_uvdata[VertTo*2+1]=fl2->UVCoords[j*6+VertFrom*2+1]<<16; - } - } - } - int UVIndex=shp->items[poly][3]>>16; - #if !USE_LEVEL_MEMORY_POOL - if(shp->sh_textures[UVIndex])DeallocateMem(shp->sh_textures[UVIndex]); - #endif - shp->sh_textures[UVIndex]=(int*)thlist; - shp->items[poly][2]|=iflag_txanim; - shp->items[poly][3]=UVIndex<<16; - - -} -void SetupAnimatedTextures(Shape_Chunk* sc,SHAPEHEADER* shp,Animation_Chunk* ac,Shape_Merge_Data_Chunk* smdc, int * local_tex_index_nos) -{ - //create conversion between unmerged poly nos and merged poly nos - int* PolyConv=0; - int* mgd=0; - - if(smdc) - { - mgd=smdc->merge_data; - PolyConv=new int[smdc->num_polys]; - for(int i=0, j=0;i<smdc->num_polys;i++) - { - if(mgd[i]==-1) - { - PolyConv[i]=j; - j++; - } - else if(mgd[i]>i) - { - if(shp->items[j][7]==-1) - { - //quad in merge data,but not actually merged; - PolyConv[i]=j; - j++; - PolyConv[mgd[i]]=j; - j++; - } - else - { - PolyConv[i]=j; - PolyConv[mgd[i]]=j; - j++; - } - } - - } - - for(i=0;i<ac->NumPolys;i++) - { - TEXANIM* ta1,*ta2; - ta1=ac->AnimList[i]; - if(mgd[ta1->poly]==-1) - { - SetupAnimOnTriangle(shp,ta1,PolyConv[ta1->poly], local_tex_index_nos); - } - else if(mgd[ta1->poly]>ta1->poly) - { - for(j=0;j<ac->NumPolys;j++) - { - if(ac->AnimList[j]->poly==mgd[ta1->poly])break; - } - if(j<ac->NumPolys) - { - ta2=ac->AnimList[j]; - if(PolyConv[ta1->poly]==PolyConv[ta2->poly]) - { - SetupAnimOnQuad(sc,shp,ta1,ta2,PolyConv[ta1->poly], local_tex_index_nos); - } - else - { - SetupAnimOnTriangle(shp,ta1,PolyConv[ta1->poly], local_tex_index_nos); - SetupAnimOnTriangle(shp,ta2,PolyConv[ta2->poly], local_tex_index_nos); - } - } - else if(PolyConv[ta1->poly]!=PolyConv[mgd[ta1->poly]]) - { - SetupAnimOnTriangle(shp,ta1,PolyConv[ta1->poly], local_tex_index_nos); - } - } - } - if(PolyConv)delete [] PolyConv; - } - else - { - for(int i=0;i<ac->NumPolys;i++) - { - SetupAnimOnTriangle(shp,ac->AnimList[i],ac->AnimList[i]->poly, local_tex_index_nos); - } - } - shp->shapeflags|=ShapeFlag_HasTextureAnimation; -} - - -void SetupAnimatingShape(Shape_Chunk* sc,SHAPEHEADER* shp, Shape_Merge_Data_Chunk* smdc) -{ - //create conversion between unmerged poly nos and merged poly nos - int* PolyConv=0; - int* mgd=0; - - PolyConv=new int[smdc->num_polys]; - - if(smdc) - { - mgd=smdc->merge_data; - for(int i=0, j=0;i<smdc->num_polys;i++) - { - if(mgd[i]==-1) - { - PolyConv[i]=j; - j++; - } - else if(mgd[i]>i) - { - if(shp->items[j][7]==-1) - { - //quad in merge data,but not actually merged; - PolyConv[i]=j; - j++; - PolyConv[mgd[i]]=j; - j++; - } - else - { - PolyConv[i]=j; - PolyConv[mgd[i]]=j; - j++; - } - } - - } - - } - else - { - for(int i=0;i<smdc->num_polys;i++) - { - PolyConv[i]=i; - } - } - - ChunkVectorInt Centre={0,0,0}; - Chunk * pChunk = sc->lookup_single_child("ANSHCEN2"); - if(pChunk) - Centre=((Anim_Shape_Centre_Chunk*)pChunk)->Centre; - - int numseq=0; - List<Chunk *> chlist; - sc->lookup_child("ANIMSEQU",chlist); - for(LIF<Chunk*> chlif(&chlist);!chlif.done();chlif.next()) - { - Anim_Shape_Sequence_Chunk* assc=(Anim_Shape_Sequence_Chunk*)chlif(); - numseq=max(assc->sequence_data.SequenceNum+1,numseq); - } - - shapeanimationheader* sah=(shapeanimationheader*)PoolAllocateMem(sizeof(shapeanimationheader)); - shp->animation_header=sah; - sah->num_sequences=numseq; - sah->anim_sequences=(shapeanimationsequence*)PoolAllocateMem(sizeof(shapeanimationsequence)*numseq); - sah->num_shapes_using_this=1; - //sah->vertices_store = shp->points[0]; - //sah->item_normals_store = shp->sh_normals[0]; - //sah->vertex_normals_store = shp->sh_vnormals[0]; - - for( int i=0;i<numseq;i++) - { - sah->anim_sequences[i].num_frames=0; - sah->anim_sequences[i].anim_frames=0; - } - - - - for(chlif.restart();!chlif.done();chlif.next()) - { - Anim_Shape_Sequence_Chunk* assc=(Anim_Shape_Sequence_Chunk*)chlif(); - assc->GenerateInterpolatedFrames(); - const ChunkAnimSequence * cas=& assc->sequence_data; - if(!cas->NumFrames)continue; - shapeanimationsequence* sas =&sah->anim_sequences[cas->SequenceNum]; - - sas->max_x=(int)((cas->max.x-Centre.x)*local_scale); - sas->min_x=(int)((cas->min.x-Centre.x)*local_scale); - sas->max_y=(int)((cas->max.y-Centre.y)*local_scale); - sas->min_y=(int)((cas->min.y-Centre.y)*local_scale); - sas->max_z=(int)((cas->max.z-Centre.z)*local_scale); - sas->min_z=(int)((cas->min.z-Centre.z)*local_scale); - - int x=max(-sas->min_x,sas->max_x); - int y=max(-sas->min_y,sas->max_y); - int z=max(-sas->min_z,sas->max_z); - sas->radius=sqrt(x*x+y*y+z*z); - - - sas->vertex_normals=(int*)PoolAllocateMem(sizeof(VECTORCH)*cas->num_verts); - for(i=0;i<cas->num_verts;i++) - { - sas->vertex_normals[i*3]=(int)(cas->v_normal_list[i].x*ONE_FIXED); - sas->vertex_normals[i*3+1]=(int)(cas->v_normal_list[i].y*ONE_FIXED); - sas->vertex_normals[i*3+2]=(int)(cas->v_normal_list[i].z*ONE_FIXED); - } - - sas->num_frames=cas->NumFrames; - sas->anim_frames=(shapeanimationframe*)PoolAllocateMem(sizeof(shapeanimationframe)*cas->NumFrames); - - for(i=0;i<cas->NumFrames;i++) - { - const ChunkAnimFrame* caf=cas->Frames[i]; - shapeanimationframe* saf=&sas->anim_frames[i]; - - saf->vertices=(int*)PoolAllocateMem(sizeof(VECTORCH)*caf->num_verts); - for(int j=0;j<caf->num_verts;j++) - { - saf->vertices[j*3]=(int)((caf->v_list[j].x-Centre.x)*local_scale); - saf->vertices[j*3+1]=(int)((caf->v_list[j].y-Centre.y)*local_scale); - saf->vertices[j*3+2]=(int)((caf->v_list[j].z-Centre.z)*local_scale); - } - - saf->item_normals=(int*) PoolAllocateMem(sizeof(VECTORCH)*shp->numitems); - for(j=0;j<caf->num_polys;j++) - { - saf->item_normals[PolyConv[j]*3]=(int)(caf->p_normal_list[j].x*ONE_FIXED); - saf->item_normals[PolyConv[j]*3+1]=(int)(caf->p_normal_list[j].y*ONE_FIXED); - saf->item_normals[PolyConv[j]*3+2]=(int)(caf->p_normal_list[j].z*ONE_FIXED); - - } - } - } - - delete [] PolyConv; - - - //find a sequence which has some frames; - shapeanimationsequence* sas=0; - for(i=0;i<shp->animation_header->num_sequences;i++) - { - sas=&shp->animation_header->anim_sequences[i]; - if(sas->num_frames) - break; - - } - GLOBALASSERT(i<shp->animation_header->num_sequences); - - //copy the pointers for the first frame of this sequence - #if !USE_LEVEL_MEMORY_POOL - DeallocateMem(shp->points[0]); - DeallocateMem(shp->sh_normals[0]); - DeallocateMem(shp->sh_vnormals[0]); - #endif - - shp->points[0]=sas->anim_frames[0].vertices; - shp->sh_normals[0]=sas->anim_frames[0].item_normals; - shp->sh_vnormals[0]=sas->vertex_normals; -} - - -BOOL copy_to_shapeheader ( - RIFFHANDLE h, - ChunkShape const & cshp, - SHAPEHEADER *& shphd, - Chunk_With_Children * shape, - int flags, - int local_max_index, - int * local_tex_index_nos, - int /*listpos*/, - const ChunkObject* object - ) -{ - ChunkShape merged_cshp; - const ChunkShape* cshp_ptr; - - if(shape->lookup_single_child("SHPMRGDT")) - { - merged_cshp=cshp; - pre_process_shape(h,merged_cshp,shape,flags); - - cshp_ptr=&merged_cshp; - } - else - { - cshp_ptr=&cshp; - } - - shphd = (SHAPEHEADER *) PoolAllocateMem(sizeof(SHAPEHEADER)); - memset(shphd,0,sizeof(SHAPEHEADER)); - - int i,j; - int * tptr; - - // header data (note shapeheader is calloced) - - shphd->numpoints = cshp_ptr->num_verts; - shphd->numitems = cshp_ptr->num_polys; - - - shphd->shaperadius = (int) (cshp_ptr->radius*local_scale); - - shphd->shapemaxx = (int) (cshp_ptr->max.x*local_scale); - shphd->shapeminx = (int) (cshp_ptr->min.x*local_scale); - shphd->shapemaxy = (int) (cshp_ptr->max.y*local_scale); - shphd->shapeminy = (int) (cshp_ptr->min.y*local_scale); - shphd->shapemaxz = (int) (cshp_ptr->max.z*local_scale); - shphd->shapeminz = (int) (cshp_ptr->min.z*local_scale); - - // AllocateMem arrays - - shphd->points = (int **) PoolAllocateMem (sizeof(int *)); - *(shphd->points) = (int *) PoolAllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_vnormals = (int **) PoolAllocateMem (sizeof(int *)); - *(shphd->sh_vnormals) = (int *) PoolAllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_normals = (int **) PoolAllocateMem (sizeof(int *)); - *(shphd->sh_normals) = (int *) PoolAllocateMem (sizeof(int) * shphd->numitems * 3); - - // for textures - if (cshp_ptr->num_uvs) - shphd->sh_textures = (int **) PoolAllocateMem (sizeof(int *) * cshp_ptr->num_uvs); - if (cshp_ptr->num_texfiles) - shphd->sh_localtextures = (char **) PoolAllocateMem (sizeof(char *) * (cshp_ptr->num_texfiles+1)); - - int * item_list; - - shphd->items = (int **) PoolAllocateMem (sizeof(int *) * shphd->numitems); - item_list = (int *) PoolAllocateMem (sizeof(int) * shphd->numitems * 9); - - tptr = *(shphd->points); - - - - if(object && local_scale!=1) - { - //convert from floating point to integers using world coordinates in an attempt to stop - //tears from being generated - ChunkVector object_float; - object_float.x=(double)object->location.x; - object_float.y=(double)object->location.y; - object_float.z=(double)object->location.z; - - VECTORCH object_int; - object_int.vx=object_float.x*local_scale; - object_int.vy=object_float.y*local_scale; - object_int.vz=object_float.z*local_scale; - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = (int) ((cshp_ptr->v_list[i].x+object_float.x)*local_scale); - tptr[i*3 + 1] = (int) ((cshp_ptr->v_list[i].y+object_float.y)*local_scale); - tptr[i*3 + 2] = (int) ((cshp_ptr->v_list[i].z+object_float.z)*local_scale); - - tptr[i*3]-=object_int.vx; - tptr[i*3+1]-=object_int.vy; - tptr[i*3+2]-=object_int.vz; - } - - } - else - { - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = (int) (cshp_ptr->v_list[i].x*local_scale); - tptr[i*3 + 1] = (int) (cshp_ptr->v_list[i].y*local_scale); - tptr[i*3 + 2] = (int) (cshp_ptr->v_list[i].z*local_scale); - } - } - - tptr = *(shphd->sh_vnormals); - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] =(int) (cshp_ptr->v_normal_list[i].x*ONE_FIXED); - tptr[i*3 + 1] =(int) (cshp_ptr->v_normal_list[i].y*ONE_FIXED); - tptr[i*3 + 2] =(int) (cshp_ptr->v_normal_list[i].z*ONE_FIXED); - } - - tptr = *(shphd->sh_normals); - - for (i=0; i<shphd->numitems; i++) { - tptr[i*3] =(int) (cshp_ptr->p_normal_list[i].x*ONE_FIXED); - tptr[i*3 + 1] =(int) (cshp_ptr->p_normal_list[i].y*ONE_FIXED); - tptr[i*3 + 2] =(int) (cshp_ptr->p_normal_list[i].z*ONE_FIXED); - } - - - for (i=0; i<shphd->numitems; i++) - shphd->items[i] = &item_list[i*9]; - - int * uv_imnums = 0; - if (cshp_ptr->num_uvs) - { - uv_imnums = new int[cshp_ptr->num_uvs]; - for (i=0; i<cshp_ptr->num_uvs; ++i) - { - uv_imnums[i]=-1; - shphd->sh_textures[i]=0; - } - } - - for (i=0; i<shphd->numitems; i++) { - - item_list[i*9] = (cshp_ptr->poly_list[i].engine_type); - item_list[i*9 + 1] = (cshp_ptr->poly_list[i].normal_index * 3); - item_list[i*9 + 2] = (cshp_ptr->poly_list[i].flags&~ChunkInternalItemFlags); - item_list[i*9 + 3] = (cshp_ptr->poly_list[i].colour); - - if ( is_textured(item_list[i*9]) && !( item_list[i*9 + 3] & 0x8000 ) ) - { - int texno = item_list[i*9 + 3] & 0x7fff; - int UVIndex= item_list[i*9 + 3]>>16; - - if (texno <= local_max_index && - local_tex_index_nos[texno] != -1 && - cshp_ptr->uv_list[UVIndex].num_verts) - - { - item_list[i*9 + 3] &= 0xffff0000; - uv_imnums[item_list[i*9+3]>>16]=local_tex_index_nos[texno]; - item_list[i*9 + 3] += local_tex_index_nos[texno]; - - shphd->sh_textures[UVIndex] = (int *) PoolAllocateMem (sizeof(int) * cshp_ptr->uv_list[UVIndex].num_verts * 2); - for (j=0; j<cshp_ptr->uv_list[UVIndex].num_verts; j++) { - (shphd->sh_textures[UVIndex])[(j*2)] = ProcessUVCoord(h,UVC_POLY_U,(int)cshp_ptr->uv_list[UVIndex].vert[j].u,uv_imnums[UVIndex]); - (shphd->sh_textures[UVIndex])[(j*2)+1] = ProcessUVCoord(h,UVC_POLY_V,(int)cshp_ptr->uv_list[UVIndex].vert[j].v,uv_imnums[UVIndex]); - } - - - } - else - { - item_list[i*9] = I_Polyline; - item_list[i*9 + 2] = (cshp_ptr->poly_list[i].flags&~ChunkInternalItemFlags) | iflag_nolight; - item_list[i*9 + 3] = 0xffffffff; - } - } - - - for (j=0;j<cshp_ptr->poly_list[i].num_verts;j++) - // item_list[i*9 + 4 +j] = (cshp_ptr->poly_list[i].vert_ind[j] *3); - /* KJL 12:21:58 9/17/97 - I've removed the annoying *3 */ - item_list[i*9 + 4 +j] = (cshp_ptr->poly_list[i].vert_ind[j]); - for (;j<5;j++) - item_list[i*9 + 4 +j] = -1; - } - - if (uv_imnums) delete[] uv_imnums; - - if (cshp_ptr->num_texfiles) - { - for (i=0; i<cshp_ptr->num_texfiles; i++) { - #if john - shphd->sh_localtextures[i] = - (char *) PoolAllocateMem (sizeof(char) * (strlen(cshp_ptr->texture_fns[i]) + strlen(TexturesRoot) + 1) ); - sprintf (shphd->sh_localtextures[i],"%s%s",TexturesRoot, cshp_ptr->texture_fns[i]); - char * dotpos; - dotpos = strrchr (shphd->sh_localtextures[i], '.'); - sprintf (dotpos,".pg0"); - #else - shphd->sh_localtextures[i] = - (char *) PoolAllocateMem (sizeof(char) * (strlen(cshp_ptr->texture_fns[i]) + 1) ); - strcpy (shphd->sh_localtextures[i], cshp_ptr->texture_fns[i]); - #endif - } - shphd->sh_localtextures[i] = 0; - } - - - - - SHAPEINSTR * instruct = (SHAPEINSTR *)PoolAllocateMem(sizeof(SHAPEINSTR)*6); - - shphd->sh_instruction = instruct; - - - instruct[0].sh_instr = I_ShapePoints; /*I_shapepoints*/ - instruct[0].sh_numitems = shphd->numpoints; - instruct[0].sh_instr_data = shphd->points; - - instruct[1].sh_instr = I_ShapeNormals; /*I_shapenormals*/ - instruct[1].sh_numitems = shphd->numitems; - instruct[1].sh_instr_data = shphd->sh_normals; - - instruct[2].sh_instr = I_ShapeProject; /*I_shapeproject*/ - instruct[2].sh_numitems = shphd->numpoints; - instruct[2].sh_instr_data = shphd->points; - - instruct[3].sh_instr = I_ShapeVNormals; /*I_shapevnormals*/ - instruct[3].sh_numitems = shphd->numpoints; - instruct[3].sh_instr_data = shphd->sh_vnormals; - - instruct[4].sh_instr = I_ShapeItems; - instruct[4].sh_numitems = shphd->numitems; - instruct[4].sh_instr_data = shphd->items; - - instruct[5].sh_instr = I_ShapeEnd; /*I_shapeEND*/ - instruct[5].sh_numitems = 0; - instruct[5].sh_instr_data = 0; - - - Chunk * pchAnim = shape->lookup_single_child("TEXTANIM"); - if(pchAnim) - { - Animation_Chunk* ac=(Animation_Chunk*)pchAnim; - Shape_Merge_Data_Chunk* smdc=0; - Chunk * pCh = shape->lookup_single_child("SHPMRGDT"); - if(pCh) smdc=(Shape_Merge_Data_Chunk*)pCh; - SetupAnimatedTextures((Shape_Chunk*)shape,shphd,ac,smdc, local_tex_index_nos); - } - - if(shape->count_children("ANIMSEQU")) - { - Shape_Merge_Data_Chunk* smdc=0; - Chunk * pCh=shape->lookup_single_child("SHPMRGDT"); - if(pCh) smdc=(Shape_Merge_Data_Chunk*)pCh; - SetupAnimatingShape((Shape_Chunk*)shape,shphd,smdc); - } - - return TRUE; - - -} -BOOL copy_preprocessed_to_shapeheader ( - RIFFHANDLE h, - Shape_Preprocessed_Data_Chunk* spdc, - SHAPEHEADER *& shphd, - Chunk_With_Children * shape, - int /*flags*/, - int local_max_index, - int * local_tex_index_nos, - int /*listpos*/, - const ChunkObject* object - ) -{ - shphd = (SHAPEHEADER*)spdc->GetMemoryBlock(); - - for (int i=0; i<shphd->numitems; i++) - { - if(is_textured(shphd->items[i][0])) - { - int texno = shphd->items[i][3] & 0x7fff; - if (texno <= local_max_index && - local_tex_index_nos[texno] != -1) - - { - shphd->items[i][3] &= 0xffff0000; - shphd->items[i][3] += local_tex_index_nos[texno]; - - - } - else - { - shphd->items[i][0] = I_Polyline; - shphd->items[i][2] |=iflag_nolight; - shphd->items[i][3] = 0xffffffff; - } - } - } - - - return TRUE; - - -} - -BOOL copy_sprite_to_shapeheader (RIFFHANDLE h, SHAPEHEADER *& shphd,Sprite_Header_Chunk* shc, int listpos) -{ - Chunk * pChunk=shc->lookup_single_child("SPRITEPC"); - if(!pChunk) - { - return 0; - } - PC_Sprite_Chunk* sc=(PC_Sprite_Chunk*)pChunk; - - pChunk = shc->lookup_single_child("SPRISIZE"); - if(!pChunk) - { - return 0; - } - Sprite_Size_Chunk* ssc=(Sprite_Size_Chunk*)pChunk; - - Sprite_Extent_Chunk* sec=0; - pChunk=shc->lookup_single_child("SPREXTEN"); - if(pChunk) - sec=(Sprite_Extent_Chunk*)pChunk; - - pChunk=shc->lookup_single_child("SPRBMPSC"); - if(!pChunk) - { - return 0; - } - Sprite_Bitmap_Scale_Chunk* sbsc=(Sprite_Bitmap_Scale_Chunk*)pChunk; - - shphd = (SHAPEHEADER *) PoolAllocateMem(sizeof(SHAPEHEADER)); - memset(shphd,0,sizeof(SHAPEHEADER)); - - int i; - int * tptr; - int * BmpConv=0; - int local_max_index; - String sprite_name; - - - - Bitmap_List_Store_Chunk * blsc = 0; - - - pChunk = shc->lookup_single_child("BMPLSTST"); - if (pChunk) - { - blsc = (Bitmap_List_Store_Chunk *) pChunk; - } - pChunk = shc->lookup_single_child("RIFFNAME"); - if (pChunk) - { - sprite_name = ((RIF_Name_Chunk *)pChunk)->rif_name; - msl_shapes.add_entry(new ShapeInMSL(shphd,sprite_name,listpos)); - } - - if (blsc) - { - // load in the textures from the shape - - local_max_index = 0; - for (LIF<BMP_Name> bns (&blsc->bmps); !bns.done(); bns.next()) - { - local_max_index = max(bns().index,local_max_index); - } - - BmpConv = new int [local_max_index+1]; - for (i=0; i<=local_max_index; i++) - { - BmpConv[i] = -1; - } - - if (Env_Chunk == 0) - Env_Chunk = h->fc; - // JH 17-2-97 -- image loaders have changed to avoid loading the same image twice - for (bns.restart() ; !bns.done(); bns.next()) - { - if(bns().flags & ChunkBMPFlag_NotInPC) continue; - - String tex; - if (bns().flags & ChunkBMPFlag_IFF) - { - tex = bns().filename; - } - else - { - tex = sprite_name; - tex += "\\"; - tex += bns().filename; - } - - int imgnum = load_rif_bitmap(bns().filename,bns().flags); - if (GEI_NOTLOADED != imgnum) - BmpConv[bns().index] = imgnum; - } - - } - // header data (note shapeheader is calloced) - - shphd->numpoints = 4; - shphd->numitems = 1; - - - shphd->shaperadius =ssc->radius*GlobalScale; - - if(sec) - { - shphd->shapemaxx =sec->maxx*GlobalScale; - shphd->shapeminx =sec->minx*GlobalScale; - shphd->shapemaxy =sec->maxy*GlobalScale; - shphd->shapeminy =sec->miny*GlobalScale; - - } - else - { - shphd->shapemaxx =ssc->maxx*GlobalScale; - shphd->shapeminx =-ssc->maxx*GlobalScale; - shphd->shapemaxy =ssc->maxy*GlobalScale; - shphd->shapeminy =-ssc->maxy*GlobalScale; - } - shphd->shapemaxz =501*GlobalScale; - shphd->shapeminz =-501*GlobalScale; - - // AllocateMem arrays - - shphd->points = (int **) PoolAllocateMem (sizeof(int *)); - *(shphd->points) = (int *) PoolAllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_vnormals = (int **) PoolAllocateMem (sizeof(int *)); - *(shphd->sh_vnormals) = (int *) PoolAllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_normals = (int **) PoolAllocateMem (sizeof(int *)); - *(shphd->sh_normals) = (int *) PoolAllocateMem (sizeof(int) * shphd->numitems * 3); - - shphd->sh_textures = (int **) PoolAllocateMem (sizeof(int *)); - - int * item_list; - - shphd->items = (int **) PoolAllocateMem (sizeof(int *) * shphd->numitems); - item_list = (int *) PoolAllocateMem (sizeof(int) * shphd->numitems * 9); - - tptr = *(shphd->points); - - tptr[0]=shphd->shapemaxx; - tptr[1]=shphd->shapeminy; - tptr[2]=0; - tptr[3]=shphd->shapemaxx; - tptr[4]=shphd->shapemaxy; - tptr[5]=0; - tptr[6]=shphd->shapeminx; - tptr[7]=shphd->shapemaxy; - tptr[8]=0; - tptr[9]=shphd->shapeminx; - tptr[10]=shphd->shapeminy; - tptr[11]=0; - - tptr = *(shphd->sh_vnormals); - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = 0; - tptr[i*3 + 1] = 0; - tptr[i*3 + 2] = ONE_FIXED; - } - - tptr = *(shphd->sh_normals); - - for (i=0; i<shphd->numitems; i++) { - tptr[i*3] = 0; - tptr[i*3 + 1] = 0; - tptr[i*3 + 2] = ONE_FIXED; - } - - - for (i=0; i<shphd->numitems; i++) - shphd->items[i] = &item_list[i*9]; - - - item_list[0]=I_2dTexturedPolygon; - item_list[1]=0; - item_list[2]=iflag_ignore0| iflag_txanim|iflag_no_bfc; - if(ssc->Flags & SpriteFlag_NoLight) item_list[2]|=iflag_nolight; - if(ssc->Flags & SpriteFlag_SemiTrans) item_list[2]|=iflag_transparent; - item_list[3]=0; - item_list[4]=0; - item_list[5]=1; - item_list[6]=2; - item_list[7]=3; - item_list[8]=-1; - - SHAPEINSTR * instruct = (SHAPEINSTR *)PoolAllocateMem(sizeof(SHAPEINSTR)*6); - - shphd->sh_instruction = instruct; - - instruct[0].sh_instr = I_ShapeSpriteRPoints; /*I_shapepoints*/ - instruct[0].sh_numitems = 4; - instruct[0].sh_instr_data = shphd->points; - - instruct[1].sh_instr = I_ShapeNormals; /*I_shapenormals*/ - instruct[1].sh_numitems = shphd->numitems; - instruct[1].sh_instr_data = shphd->sh_normals; - - instruct[2].sh_instr = I_ShapeProject; /*I_shapeproject*/ - instruct[2].sh_numitems = shphd->numpoints; - instruct[2].sh_instr_data = shphd->points; - - instruct[3].sh_instr = I_ShapeVNormals; /*I_shapevnormals*/ - instruct[3].sh_numitems = shphd->numpoints; - instruct[3].sh_instr_data = shphd->sh_vnormals; - - instruct[4].sh_instr = I_ShapeItems; - instruct[4].sh_numitems = shphd->numitems; - instruct[4].sh_instr_data = shphd->items; - - instruct[5].sh_instr = I_ShapeEnd; /*I_shapeEND*/ - instruct[5].sh_numitems = 0; - instruct[5].sh_instr_data = 0; - - shphd->shapeflags=ShapeFlag_MultiViewSprite|ShapeFlag_SpriteResizing|ShapeFlag_Sprite; - - List<Chunk *> chlist; - sc->lookup_child("SPRACTIO",chlist); - - int MaxSeq=0; - for(LIF<Chunk*>chlif(&chlist);!chlif.done();chlif.next()) - { - MaxSeq=max(MaxSeq,((Sprite_Action_Chunk*)chlif())->Action); - } - txanimheader** thlist=(txanimheader**)PoolAllocateMem((3+MaxSeq)*sizeof(txanimheader)); - thlist[0]=thlist[MaxSeq+2]=0; - for(i=1;i<MaxSeq+2;i++) - { - thlist[i]=(txanimheader*)PoolAllocateMem(sizeof(txanimheader)); - thlist[i]->txa_numframes=0; - thlist[i]->txa_maxframe=0; - thlist[i]->txa_num_mvs_images=0; - thlist[i]->txa_framedata=0; - } - while(chlist.size()) - { - Sprite_Action_Chunk* sac=(Sprite_Action_Chunk*) chlist.first_entry(); - txanimheader* th=thlist[sac->Action+1]; - - th->txa_flags=txa_flag_play; - th->txa_numframes=sac->NumFrames+1; - th->txa_currentframe=0; - th->txa_state=0; - th->txa_maxframe=(th->txa_numframes-1)<<16; - if(sac->FrameTime) - th->txa_speed=65536000/sac->FrameTime; - else - th->txa_speed=65536*8; - - th->txa_num_mvs_images=sac->NumYaw*sac->NumPitch*2; - - th->txa_eulerxshift=12; - int j=sac->NumPitch; - while(j) - { - j=j>>1; - th->txa_eulerxshift--; - } - th->txa_euleryshift=12; - j=sac->NumYaw; - while(j) - { - j=j>>1; - th->txa_euleryshift--; - } - if(sac->NumYaw==1) - { - th->txa_euleryshift=12; - th->txa_num_mvs_images=sac->NumPitch; - } - - th->txa_framedata=(txanimframe*)PoolAllocateMem(th->txa_numframes*sizeof(txanimframe_mvs)); - - txanimframe_mvs* tf; - for(j=0;j<th->txa_numframes;j++) - { - int framefrom=j; - if(j==sac->NumFrames) framefrom=0; - tf=(txanimframe_mvs*)&th->txa_framedata[j]; - tf->txf_flags=0; - tf->txf_scale=ONE_FIXED; - tf->txf_scalex=0; - tf->txf_scaley=0; - tf->txf_orient=0; - tf->txf_orientx=0; - tf->txf_orienty=0; - tf->txf_numuvs=4; - - tf->txf_uvdata=(int**)PoolAllocateMem((th->txa_num_mvs_images)*sizeof(int*)); - int* uvdata=(int*)PoolAllocateMem(th->txa_num_mvs_images*16*sizeof(int)); - for(int k=0;k<th->txa_num_mvs_images;k++) - { - tf->txf_uvdata[k]=&uvdata[16*k]; - } - - tf->txf_images=(int*)PoolAllocateMem(th->txa_num_mvs_images*sizeof(int)); - int ny=2*sac->NumYaw; - if(sac->NumYaw==1) ny=1; - int y,y2; - int pos,pos2; - for(y=0;y<ny;y+=2) - { - for(int p=0;p<sac->NumPitch;p++) - { - y2=(y-1+ny)%ny; - pos=y*sac->NumPitch+p; - pos2=y2*sac->NumPitch+p; - Frame* f=&sac->FrameList[y/2][p][framefrom]; - - GLOBALASSERT(f->Texture<=local_max_index); - GLOBALASSERT(f->Texture>=0); - GLOBALASSERT(BmpConv[f->Texture]!=-1); - - tf->txf_images[pos]=BmpConv[f->Texture]; - tf->txf_images[pos2]=BmpConv[f->Texture]; - - float bmpscale=sbsc->Scale[f->Texture]; - if(y>ny/2 && (sac->Flags & SpriteActionFlag_FlipSecondSide)) - { - for(int l=0;l<4;l++) - { - tf->txf_uvdata[pos][l*2]=ProcessUVCoord(h,UVC_SPRITE_U,f->UVCoords[3-l][0]<<16,BmpConv[f->Texture]); - tf->txf_uvdata[pos][l*2+1]=ProcessUVCoord(h,UVC_SPRITE_V,f->UVCoords[3-l][1]<<16,BmpConv[f->Texture]); - tf->txf_uvdata[pos2][l*2]=ProcessUVCoord(h,UVC_SPRITE_U,f->UVCoords[3-l][0]<<16,BmpConv[f->Texture]); - tf->txf_uvdata[pos2][l*2+1]=ProcessUVCoord(h,UVC_SPRITE_V,f->UVCoords[3-l][1]<<16,BmpConv[f->Texture]); - - - tf->txf_uvdata[pos][l*2+8]=-(f->UVCoords[3-l][0]-f->CentreX)*bmpscale*GlobalScale; - tf->txf_uvdata[pos][l*2+9]=(f->UVCoords[3-l][1]-f->CentreY)*bmpscale*GlobalScale; - tf->txf_uvdata[pos2][l*2+8]=-(f->UVCoords[3-l][0]-f->CentreX)*bmpscale*GlobalScale; - tf->txf_uvdata[pos2][l*2+9]=(f->UVCoords[3-l][1]-f->CentreY)*bmpscale*GlobalScale; - - } - } - else - { - for(int l=0;l<4;l++) - { - tf->txf_uvdata[pos][l*2]=ProcessUVCoord(h,UVC_SPRITE_U,f->UVCoords[l][0]<<16,BmpConv[f->Texture]); - tf->txf_uvdata[pos][l*2+1]=ProcessUVCoord(h,UVC_SPRITE_V,f->UVCoords[l][1]<<16,BmpConv[f->Texture]); - tf->txf_uvdata[pos2][l*2]=ProcessUVCoord(h,UVC_SPRITE_U,f->UVCoords[l][0]<<16,BmpConv[f->Texture]); - tf->txf_uvdata[pos2][l*2+1]=ProcessUVCoord(h,UVC_SPRITE_V,f->UVCoords[l][1]<<16,BmpConv[f->Texture]); - - - tf->txf_uvdata[pos][l*2+8]=(f->UVCoords[l][0]-f->CentreX)*bmpscale*GlobalScale; - tf->txf_uvdata[pos][l*2+9]=(f->UVCoords[l][1]-f->CentreY)*bmpscale*GlobalScale; - tf->txf_uvdata[pos2][l*2+8]=(f->UVCoords[l][0]-f->CentreX)*bmpscale*GlobalScale; - tf->txf_uvdata[pos2][l*2+9]=(f->UVCoords[l][1]-f->CentreY)*bmpscale*GlobalScale; - - } - } - } - } - } - - chlist.delete_first_entry(); - } - shphd->sh_textures[0]=(int*)thlist; - delete [] BmpConv; - return TRUE; -} - - - -BOOL copy_to_map6(Object_Chunk * ob,MAPBLOCK6* mapblock, int shplst_pos) -{ - - Object_Project_Data_Chunk * opdc = 0; - Map_Block_Chunk * mapblok = 0; - Strategy_Chunk * strat = 0; - - if (ob->object_data.is_base_object) - *mapblock = Empty_Landscape_Type6; - else *mapblock = Empty_Object_Type6; - - - - Chunk * pChunk = ob->lookup_single_child("OBJPRJDT"); - if (pChunk) opdc = (Object_Project_Data_Chunk *)pChunk; - if (opdc) - { - pChunk = opdc->lookup_single_child("MAPBLOCK"); - if (pChunk) mapblok = (Map_Block_Chunk *)pChunk; - pChunk = opdc->lookup_single_child("STRATEGY"); - if (pChunk) strat = (Strategy_Chunk *)pChunk; - } - - if (mapblok) - { - mapblock->MapType = mapblok->map_data.MapType; - mapblock->MapFlags= mapblok->map_data.MapFlags; - - #if (StandardStrategyAndCollisions || IntermediateSSACM) - mapblock->MapCType = mapblok->map_data.MapCType; - mapblock->MapCGameType = mapblok->map_data.MapCGameType; - mapblock->MapCStrategyS = mapblok->map_data.MapCStrategyS; - mapblock->MapCStrategyL = mapblok->map_data.MapCStrategyL; - #endif - - mapblock->MapInteriorType = mapblok->map_data.MapInteriorType; -// mapblock->MapLightType = mapblok->map_data.MapLightType; -// mapblock->MapMass = mapblok->map_data.MapMass; -// mapblock->MapNewtonV.vx = mapblok->map_data.MapNewtonV.vx; -// mapblock->MapNewtonV.vy = mapblok->map_data.MapNewtonV.vy; -// mapblock->MapNewtonV.vz = mapblok->map_data.MapNewtonV.vz; -// mapblock->MapOrigin.vx = mapblok->map_data.MapOrigin.vx; -// mapblock->MapOrigin.vy = mapblok->map_data.MapOrigin.vy; -// mapblock->MapOrigin.vz = mapblok->map_data.MapOrigin.vz; -// mapblock->MapViewType = mapblok->map_data.MapViewType; - } - - #if (StandardStrategyAndCollisions || IntermediateSSACM) - if (strat) - { - mapblock->MapStrategy = strat->strategy_data.Strategy; - } - #endif - - mapblock->MapShape = shplst_pos; - - mapblock->MapWorld.vx = (int) (ob->object_data.location.x*local_scale); - mapblock->MapWorld.vy = (int) (ob->object_data.location.y*local_scale); - mapblock->MapWorld.vz = (int) (ob->object_data.location.z*local_scale); - - QUAT q; - - q.quatx = -ob->object_data.orientation.x*ONE_FIXED; - q.quaty = -ob->object_data.orientation.y*ONE_FIXED; - q.quatz = -ob->object_data.orientation.z*ONE_FIXED; - q.quatw = ob->object_data.orientation.w*ONE_FIXED; - - MATRIXCH m; - - QuatToMat (&q, &m); - - EULER e; - - MatrixToEuler(&m, &e); - - /* - This function is only being used by the tools. - At least for the moment I need the Euler to contain - the 'inverse' rotation ,until I get round to sorting things - out properly. Richard - */ - - mapblock->MapEuler.EulerX = e.EulerX; - mapblock->MapEuler.EulerY = e.EulerY; - mapblock->MapEuler.EulerZ = e.EulerZ; - - #if InterfaceEngine - mapblock->o_chunk = (void *)ob; - #endif - - return TRUE; -} - - - - - -BOOL tex_merge_polys ( ChunkPoly & p1, ChunkPoly & p2, ChunkPoly & p, ChunkShape & shp, int * /*mgd*/) -{ - int j; - - if (p1.engine_type != p2.engine_type) - return(FALSE); - - if ((p1.colour & 0xffff) != (p2.colour & 0xffff)) - return(FALSE); - - if (p1.flags != p2.flags) - return(FALSE); - - - int p1_uvind = p1.colour >> 16; - int p2_uvind = p2.colour >> 16; - - ChunkUV_List uv; - p = p1; - p.num_verts = 4; - uv.num_verts = 4; - - int num_ins = 0; - int p_onv = 0; - int new_p_onv; - int * p_on = p1.vert_ind; - int * p_oth = p2.vert_ind; - int * temp; - - ChunkUV * uv_on = shp.uv_list[p1_uvind].vert; - ChunkUV * uv_oth = shp.uv_list[p2_uvind].vert; - ChunkUV * uvtemp; - - while (num_ins < 4) - { - uv.vert[num_ins] = uv_on[p_onv]; - p.vert_ind[num_ins++] = p_on[p_onv]; - for (j=0; j<3; j++) - { - if (p_on[p_onv] == p_oth[j] && - (uv_on[p_onv].u != uv_oth[j].u || uv_on[p_onv].v != uv_oth[j].v)) - { - return(FALSE); - } - if (p_on[p_onv] == p_oth[j]) - break; - } - if (j==3) p_onv = (p_onv+1)%3; - else - { - new_p_onv = j; - for (j=0; j<3; j++) - { - if (p_on[(p_onv+1)%3] == p_oth[j] && - (uv_on[(p_onv+1)%3].u != uv_oth[j].u || uv_on[(p_onv+1)%3].v != uv_oth[j].v)) - { - return (FALSE); - } - if (p_on[(p_onv+1)%3] == p_oth[j]) - break; - } - if (j==3) p_onv = (p_onv+1)%3; - else - { - temp = p_on; - p_on = p_oth; - p_oth = temp; - p_onv = (new_p_onv+1)%3; - - uvtemp = uv_on; - uv_on = uv_oth; - uv_oth = uvtemp; - } - } - } - - shp.uv_list[p1_uvind] = uv; - - return(TRUE); - - -} - -BOOL merge_polys ( ChunkPoly & p1, ChunkPoly & p2, ChunkPoly & p, int * /*mgd*/) -{ - int j; - - if (p1.engine_type != p2.engine_type) - return(FALSE); - - if (p1.colour != p2.colour) - return(FALSE); - - if (p1.flags != p2.flags) - return(FALSE); - - - p = p1; - p.num_verts = 4; - int num_ins = 0; - int p_onv = 0; - int new_p_onv; - int * p_on = p1.vert_ind; - int * p_oth = p2.vert_ind; - int * temp; - - while (num_ins < 4) - { - p.vert_ind[num_ins++] = p_on[p_onv]; - for (j=0; j<3; j++) - { - if (p_on[p_onv] == p_oth[j]) - break; - } - if (j==3) p_onv = (p_onv+1)%3; - else - { - new_p_onv = j; - for (j=0; j<3; j++) - { - if (p_on[(p_onv+1)%3] == p_oth[j]) - break; - } - if (j==3) p_onv = (p_onv+1)%3; - else - { - temp = p_on; - p_on = p_oth; - p_oth = temp; - p_onv = (new_p_onv+1)%3; - } - } - } - return(TRUE); -} - - -void merge_polygons_in_chunkshape (ChunkShape & shp, Shape_Merge_Data_Chunk * smdc) -{ - int * mgd = smdc->merge_data; - - int p_no = 0; - - - ChunkPoly * new_polys = new ChunkPoly [shp.num_polys]; - ChunkVectorFloat * new_pnorms = new ChunkVectorFloat [shp.num_polys]; - - for (int i = 0; i<shp.num_polys; i++) - { - if (mgd[i] == -1) - { - new_polys[p_no] = shp.poly_list[i]; - new_polys[p_no].normal_index = p_no; - new_pnorms[p_no] = shp.p_normal_list[i]; - p_no ++; - } - else if (mgd[i]>i) - { - ChunkPoly p; - - BOOL merged = FALSE; - - //make sure points are within 10mm of being planar - - int mpoly=mgd[i]; - //find the 'unique vertex' in the second triangle - for(int j=0;j<3;j++) - { - for(int k=0;k<3;k++) - { - if(shp.poly_list[mpoly].vert_ind[j]==shp.poly_list[i].vert_ind[k])break; - } - if(k==3) - { - break; - } - } - GLOBALASSERT(j!=3); - int vert1=shp.poly_list[mpoly].vert_ind[j]; - int vert2=shp.poly_list[mpoly].vert_ind[(j+1)%3]; - ChunkVectorInt diff=shp.v_list[vert1]-shp.v_list[vert2]; - ChunkVectorFloat* norm=&shp.p_normal_list[i]; - - //take the dot product of the normal and the difference to find the distance form the first - //triangles plane - float distance= (float)diff.x*norm->x + (float)diff.y*norm->y + (float)diff.z*norm->z; - - if(distance>-1 && distance <1) - { - if (is_textured(shp.poly_list[i].engine_type)) - { - merged = tex_merge_polys ( shp.poly_list[i], shp.poly_list[mgd[i]], p, shp, mgd); - } - else - { - merged = merge_polys ( shp.poly_list[i], shp.poly_list[mgd[i]], p, mgd); - } - } - if (merged) - { - p.normal_index = p_no; - new_polys[p_no] = p; - new_pnorms[p_no] = shp.p_normal_list[i]; - p_no++; - } - else - { - new_polys[p_no] = shp.poly_list[i]; - new_polys[p_no].normal_index = p_no; - new_pnorms[p_no] = shp.p_normal_list[i]; - p_no ++; - - new_polys[p_no] = shp.poly_list[mgd[i]]; - new_polys[p_no].normal_index = p_no; - new_pnorms[p_no] = shp.p_normal_list[mgd[i]]; - p_no ++; - } - - } - } - - delete [] shp.poly_list; - delete [] shp.p_normal_list; - shp.poly_list = new_polys; - shp.p_normal_list = new_pnorms; - shp.num_polys = p_no; - -} - - - - - - -#if 0 -BOOL copy_to_mainshpl (Shape_Chunk * shp, int list_pos) -{ - SHAPEHEADER * shphd = (SHAPEHEADER *) AllocateMem(sizeof(SHAPEHEADER)); - memset(shphd,0,sizeof(SHAPEHEADER)); - - ChunkShape cshp = shp->shape_data; - - Shape_Merge_Data_Chunk * smdc = 0; - - Chunk * pChunk = shp->lookup_single_child("SHPMRGDT"); - if (pChunk) - { - smdc = (Shape_Merge_Data_Chunk *) pChunk; - } - - merge_polygons_in_chunkshape (cshp,smdc); - - int i,j, * tptr; - - mainshapelist[list_pos] = shphd; - - // header data (note shapeheader is calloced) - - shphd->shapeflags = shphd->shapeflags | (ShapeFlag_AugZ | ShapeFlag_AugZ_Lite | - ShapeFlag_SizeSortItems); // SIZE HACK!!! - shphd->numpoints = cshp.num_verts; - shphd->numitems = cshp.num_polys; - - shphd->shaperadius = (int) (cshp.radius*local_scale); - - shphd->shapemaxx = (int) (cshp.max.x*local_scale); - shphd->shapeminx = (int) (cshp.min.x*local_scale); - shphd->shapemaxy = (int) (cshp.max.y*local_scale); - shphd->shapeminy = (int) (cshp.min.y*local_scale); - shphd->shapemaxz = (int) (cshp.max.z*local_scale); - shphd->shapeminz = (int) (cshp.min.z*local_scale); - - // AllocateMem arrays - - shphd->points = (int **) AllocateMem (sizeof(int *)); - *(shphd->points) = (int *) AllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_vnormals = (int **) AllocateMem (sizeof(int *)); - *(shphd->sh_vnormals) = (int *) AllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_normals = (int **) AllocateMem (sizeof(int *)); - *(shphd->sh_normals) = (int *) AllocateMem (sizeof(int) * shphd->numitems * 3); - - // for textures - if (cshp.num_uvs) - shphd->sh_textures = (int **) AllocateMem (sizeof(int *) * cshp.num_uvs); - if (cshp.num_texfiles) - shphd->sh_localtextures = (char **) AllocateMem (sizeof(char *) * (cshp.num_texfiles+1)); - - int * item_list; - - shphd->items = (int **) AllocateMem (sizeof(int *) * shphd->numitems); - item_list = (int *) AllocateMem (sizeof(int) * shphd->numitems * 9); - - tptr = *(shphd->points); - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = (int) (cshp.v_list[i].x*local_scale); - tptr[i*3 + 1] = (int) (cshp.v_list[i].y*local_scale); - tptr[i*3 + 2] = (int) (cshp.v_list[i].z*local_scale); - } - - tptr = *(shphd->sh_vnormals); - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = (int) (cshp.v_normal_list[i].x*ONE_FIXED); - tptr[i*3 + 1] = (int) (cshp.v_normal_list[i].y*ONE_FIXED); - tptr[i*3 + 2] = (int) (cshp.v_normal_list[i].z*ONE_FIXED); - } - - tptr = *(shphd->sh_normals); - - for (i=0; i<shphd->numitems; i++) { - tptr[i*3] = (int) (cshp.p_normal_list[i].x*ONE_FIXED); - tptr[i*3 + 1] = (int) (cshp.p_normal_list[i].y*ONE_FIXED); - tptr[i*3 + 2] = (int) (cshp.p_normal_list[i].z*ONE_FIXED); - } - - - for (i=0; i<shphd->numitems; i++) - shphd->items[i] = &item_list[i*9]; - - - - for (i=0; i<shphd->numitems; i++) { - - - item_list[i*9] = (cshp.poly_list[i].engine_type); -// item_list[i*9] = I_Polyline; - - /* trap for polylines*/ - if((item_list[i*9] < 2 ) || (item_list[i*9] > 9)) - { - item_list[i*9] = I_Polygon; - } -#if 1 - /* try to set gouraud, for hazing*/ - - if(item_list[i*9] == I_Polygon) - { - item_list[i*9] = I_GouraudPolygon; - } - - if(item_list[i*9] == I_2dTexturedPolygon) - { - item_list[i*9] = I_Gouraud2dTexturedPolygon; - } - - if(item_list[i*9] == I_3dTexturedPolygon) - { - item_list[i*9] = I_Gouraud2dTexturedPolygon; - } -#endif - -// if(item_list[i*9] == I_Polygon) -// { -// item_list[i*9] = I_ZB_Polygon; -// /*HACK HACK ROXHACK*/ -// } - - #if SupportZBuffering - #else - if(item_list[i*9] == I_ZB_Polygon) - item_list[i*9] = I_Polygon; - - if(item_list[i*9] == I_ZB_GouraudPolygon) - item_list[i*9] = I_GouraudPolygon; - - if(item_list[i*9] == I_ZB_PhongPolygon) - item_list[i*9] = I_PhongPolygon; - - if(item_list[i*9] == I_ZB_2dTexturedPolygon) - item_list[i*9] = I_2dTexturedPolygon; - - if(item_list[i*9] == I_ZB_Gouraud2dTexturedPolygon) - item_list[i*9] = I_Gouraud2dTexturedPolygon; - - if(item_list[i*9] == I_ZB_3dTexturedPolygon) - item_list[i*9] = I_3dTexturedPolygon; - #endif - - - - item_list[i*9 + 1] = (cshp.poly_list[i].normal_index * 3); - item_list[i*9 + 2] = (cshp.poly_list[i].flags&~ChunkInternalItemFlags); -// item_list[i*9 + 2] = (cshp.poly_list[i].flags) | iflag_nolight; - item_list[i*9 + 3] = (cshp.poly_list[i].colour); - -#if 1 - if ( (item_list[i*9] == I_2dTexturedPolygon - || item_list[i*9] == I_Gouraud2dTexturedPolygon - || item_list[i*9] == I_3dTexturedPolygon - || item_list[i*9] == I_Gouraud3dTexturedPolygon - ) && - !( item_list[i*9 + 3] & 0x8000 ) ) - { - int texno = item_list[i*9 + 3] & 0x7fff; - - if (texno <= max_index) - if ((tex_index_nos[texno] != -1)) - { - item_list[i*9 + 3] &= 0xffff0000; - item_list[i*9 + 3] += tex_index_nos[texno]; - - /* hack in iflag_no_light */ - item_list[i*9 + 2] |= iflag_gsort_ptest /*| iflag_nolight*/ | iflag_linear_s | iflag_tx2dor3d; - - } - else - { - item_list[i*9] = I_Polygon; - item_list[i*9 + 2] = (cshp.poly_list[i].flags&~ChunkInternalItemFlags) | iflag_nolight; - item_list[i*9 + 3] = 0xffffffff; - } - else - { - item_list[i*9] = I_Polygon; - item_list[i*9 + 2] = (cshp.poly_list[i].flags&~ChunkInternalItemFlags) | iflag_nolight; - item_list[i*9 + 3] = 0xffffffff; - } - } -#endif - -// item_list[i*9 + 3] = 0xffffffff; - - - for (j=0;j<cshp.poly_list[i].num_verts;j++) -// item_list[i*9 + 4 +j] = (cshp.poly_list[i].vert_ind[j] *3); - /* KJL 12:21:58 9/17/97 - I've removed the annoying *3 */ - item_list[i*9 + 4 +j] = (cshp.poly_list[i].vert_ind[j]); - for (;j<5;j++) - item_list[i*9 + 4 +j] = -1; - } - - if (cshp.num_uvs) - { - for (i=0; i<cshp.num_uvs; i++) { - shphd->sh_textures[i] = (int *) AllocateMem (sizeof(int) * cshp.uv_list[i].num_verts * 2); - for (j=0; j<cshp.uv_list[i].num_verts; j++) { - (shphd->sh_textures[i])[(j*2)] = (int)cshp.uv_list[i].vert[j].u; - (shphd->sh_textures[i])[(j*2)+1] = (int)cshp.uv_list[i].vert[j].v; - } - } - } - - if (cshp.num_texfiles) - { - for (i=0; i<cshp.num_texfiles; i++) { - #if john - shphd->sh_localtextures[i] = - (char *) AllocateMem (sizeof(char) * (strlen(cshp.texture_fns[i]) + strlen(TexturesRoot) + 1) ); - sprintf (shphd->sh_localtextures[i],"%s%s",TexturesRoot, cshp.texture_fns[i]); - char * dotpos; - dotpos = strrchr (shphd->sh_localtextures[i], '.'); - sprintf (dotpos,".pg0"); - #else - shphd->sh_localtextures[i] = - (char *) AllocateMem (sizeof(char) * (strlen(cshp.texture_fns[i]) + 1) ); - strcpy (shphd->sh_localtextures[i], cshp.texture_fns[i]); - #endif - } - shphd->sh_localtextures[i] = 0; - } - - - - - SHAPEINSTR * instruct = (SHAPEINSTR *)AllocateMem(sizeof(SHAPEINSTR)*6); - - shphd->sh_instruction = instruct; - - - - instruct[0].sh_instr = I_ShapePoints; /*I_shapepoints*/ - instruct[0].sh_numitems = shphd->numpoints; - instruct[0].sh_instr_data = shphd->points; - - instruct[1].sh_instr = I_ShapeNormals; /*I_shapenormals*/ - instruct[1].sh_numitems = shphd->numitems; - instruct[1].sh_instr_data = shphd->sh_normals; - - instruct[2].sh_instr = I_ShapeProject; /*I_shapeproject*/ - instruct[2].sh_numitems = shphd->numpoints; - instruct[2].sh_instr_data = shphd->points; - - instruct[3].sh_instr = I_ShapeVNormals; /*I_shapevnormals*/ - instruct[3].sh_numitems = shphd->numpoints; - instruct[3].sh_instr_data = shphd->sh_vnormals; - - instruct[4].sh_instr = I_ShapeItems; - instruct[4].sh_numitems = shphd->numitems; - instruct[4].sh_instr_data = shphd->items; - - instruct[5].sh_instr = I_ShapeEnd; /*I_shapeEND*/ - instruct[5].sh_numitems = 0; - instruct[5].sh_instr_data = 0; - - - Chunk * pchAnim = shp->lookup_single_child("TEXTANIM"); - if (pchAnim) - { - Shape_Merge_Data_Chunk* smdc=0; - Chunk * pChunk=shp->lookup_single_child("SHPMRGDT"); - if(pChunk) smdc=(Shape_Merge_Data_Chunk*)pChunk; - SetupAnimatedTextures(shp,shphd,(Animation_Chunk*)pchAnim,smdc); - } - - - - return TRUE; - -} -#endif - -#if 0 -BOOL copy_to_mainshpl (Shape_Sub_Shape_Chunk * shp, int list_pos) -{ - SHAPEHEADER * shphd = (SHAPEHEADER *) AllocateMem(sizeof(SHAPEHEADER)); - memset(shphd,0,sizeof(SHAPEHEADER)); - - ChunkShape cshp = shp->shape_data; - - Shape_Merge_Data_Chunk * smdc = 0; - - Chunk * pChunk = shp->lookup_single_child("SHPMRGDT"); - if (pChunk) - { - smdc = (Shape_Merge_Data_Chunk *) pChunk; - } - - merge_polygons_in_chunkshape (cshp,smdc); - - int i,j, * tptr; - - mainshapelist[list_pos] = shphd; - - // header data (note shapeheader is calloced) - - shphd->shapeflags = shphd->shapeflags | (ShapeFlag_AugZ | ShapeFlag_AugZ_Lite | - ShapeFlag_SizeSortItems); // SIZE HACK!!! - shphd->numpoints = cshp.num_verts; - shphd->numitems = cshp.num_polys; - - shphd->shaperadius = (int) (cshp.radius*local_scale); - - shphd->shapemaxx = (int) (cshp.max.x*local_scale); - shphd->shapeminx = (int) (cshp.min.x*local_scale); - shphd->shapemaxy = (int) (cshp.max.y*local_scale); - shphd->shapeminy = (int) (cshp.min.y*local_scale); - shphd->shapemaxz = (int) (cshp.max.z*local_scale); - shphd->shapeminz = (int) (cshp.min.z*local_scale); - - // AllocateMem arrays - - shphd->points = (int **) AllocateMem (sizeof(int *)); - *(shphd->points) = (int *) AllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_vnormals = (int **) AllocateMem (sizeof(int *)); - *(shphd->sh_vnormals) = (int *) AllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_normals = (int **) AllocateMem (sizeof(int *)); - *(shphd->sh_normals) = (int *) AllocateMem (sizeof(int) * shphd->numitems * 3); - - // for textures - if (cshp.num_uvs) - shphd->sh_textures = (int **) AllocateMem (sizeof(int *) * cshp.num_uvs); - if (cshp.num_texfiles) - shphd->sh_localtextures = (char **) AllocateMem (sizeof(char *) * (cshp.num_texfiles+1)); - - int * item_list; - - shphd->items = (int **) AllocateMem (sizeof(int *) * shphd->numitems); - item_list = (int *) AllocateMem (sizeof(int) * shphd->numitems * 9); - - tptr = *(shphd->points); - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = (int) (cshp.v_list[i].x*local_scale); - tptr[i*3 + 1] = (int) (cshp.v_list[i].y*local_scale); - tptr[i*3 + 2] = (int) (cshp.v_list[i].z*local_scale); - } - - tptr = *(shphd->sh_vnormals); - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = (int) (cshp.v_normal_list[i].x*ONE_FIXED); - tptr[i*3 + 1] = (int) (cshp.v_normal_list[i].y*ONE_FIXED); - tptr[i*3 + 2] = (int) (cshp.v_normal_list[i].z*ONE_FIXED); - } - - tptr = *(shphd->sh_normals); - - for (i=0; i<shphd->numitems; i++) { - tptr[i*3] = (int) (cshp.p_normal_list[i].x*ONE_FIXED); - tptr[i*3 + 1] = (int) (cshp.p_normal_list[i].y*ONE_FIXED); - tptr[i*3 + 2] = (int) (cshp.p_normal_list[i].z*ONE_FIXED); - } - - - for (i=0; i<shphd->numitems; i++) - shphd->items[i] = &item_list[i*9]; - - - - for (i=0; i<shphd->numitems; i++) { - - - item_list[i*9] = (cshp.poly_list[i].engine_type); -// item_list[i*9] = I_Polyline; -#if 1 - /* try to set gouraud, for hazing*/ - - if(item_list[i*9] == I_Polygon) - { - item_list[i*9] = I_GouraudPolygon; - } - - if(item_list[i*9] == I_2dTexturedPolygon) - { - item_list[i*9] = I_Gouraud2dTexturedPolygon; - } - - if(item_list[i*9] == I_3dTexturedPolygon) - { - item_list[i*9] = I_Gouraud2dTexturedPolygon; - } -#endif - -// if((item_list[i*9] < 2 ) || (item_list[i*9] > 9)) -// { -// item_list[i*9] = I_Polygon; -// } -#if 1 - /* try to set gouraud, for hazing*/ - - if(item_list[i*9] == I_Polygon) - { - item_list[i*9] = I_GouraudPolygon; - } - - if(item_list[i*9] == I_2dTexturedPolygon) - { - item_list[i*9] = I_Gouraud2dTexturedPolygon; - } - - if(item_list[i*9] == I_3dTexturedPolygon) - { - item_list[i*9] = I_Gouraud2dTexturedPolygon; - } -#endif - -// if(item_list[i*9] == I_Polygon) -// { -// item_list[i*9] = I_ZB_Polygon; -// /*HACK HACK ROXHACK*/ -// } - - #if SupportZBuffering - #else - if(item_list[i*9] == I_ZB_Polygon) - item_list[i*9] = I_Polygon; - - if(item_list[i*9] == I_ZB_GouraudPolygon) - item_list[i*9] = I_GouraudPolygon; - - if(item_list[i*9] == I_ZB_PhongPolygon) - item_list[i*9] = I_PhongPolygon; - - if(item_list[i*9] == I_ZB_2dTexturedPolygon) - item_list[i*9] = I_2dTexturedPolygon; - - if(item_list[i*9] == I_ZB_Gouraud2dTexturedPolygon) - item_list[i*9] = I_Gouraud2dTexturedPolygon; - - if(item_list[i*9] == I_ZB_3dTexturedPolygon) - item_list[i*9] = I_3dTexturedPolygon; - #endif - - - - item_list[i*9 + 1] = (cshp.poly_list[i].normal_index * 3); - item_list[i*9 + 2] = (cshp.poly_list[i].flags&~ChunkInternalItemFlags); -// item_list[i*9 + 2] = (cshp.poly_list[i].flags) | iflag_nolight; - item_list[i*9 + 3] = (cshp.poly_list[i].colour); - -#if 1 - if ( (item_list[i*9] == 5 || item_list[i*9] == 6 - || item_list[i*9] == 7) && - !( item_list[i*9 + 3] & 0x8000 ) ) - { - int texno = item_list[i*9 + 3] & 0x7fff; - - if (texno <= max_index) - if ((tex_index_nos[texno] != -1)) - { - item_list[i*9 + 3] &= 0xffff0000; - item_list[i*9 + 3] += tex_index_nos[texno]; - - /* hack in iflag_no_light */ - item_list[i*9 + 2] |= iflag_gsort_ptest /*| iflag_nolight*/ | iflag_linear_s | iflag_tx2dor3d; - - } - else - { - item_list[i*9] = I_Polygon; - item_list[i*9 + 2] = (cshp.poly_list[i].flags&~ChunkInternalItemFlags) | iflag_nolight; - item_list[i*9 + 3] = 0xffffffff; - } - else - { - item_list[i*9] = I_Polygon; - item_list[i*9 + 2] = (cshp.poly_list[i].flags &~ChunkInternalItemFlags) | iflag_nolight; - item_list[i*9 + 3] = 0xffffffff; - } - } -#endif - -// item_list[i*9 + 3] = 0xffffffff; - - - for (j=0;j<cshp.poly_list[i].num_verts;j++) -// item_list[i*9 + 4 +j] = (cshp.poly_list[i].vert_ind[j] *3); - /* KJL 12:23:02 9/17/97 - I've removed the annoying *3 */ - item_list[i*9 + 4 +j] = (cshp.poly_list[i].vert_ind[j]); - for (;j<5;j++) - item_list[i*9 + 4 +j] = -1; - } - - if (cshp.num_uvs) - { - for (i=0; i<cshp.num_uvs; i++) { - shphd->sh_textures[i] = (int *) AllocateMem (sizeof(int) * cshp.uv_list[i].num_verts * 2); - for (j=0; j<cshp.uv_list[i].num_verts; j++) { - (shphd->sh_textures[i])[(j*2)] = (int)cshp.uv_list[i].vert[j].u; - (shphd->sh_textures[i])[(j*2)+1] = (int)cshp.uv_list[i].vert[j].v; - } - } - } - - if (cshp.num_texfiles) - { - for (i=0; i<cshp.num_texfiles; i++) { - #if john - shphd->sh_localtextures[i] = - (char *) AllocateMem (sizeof(char) * (strlen(cshp.texture_fns[i]) + strlen(TexturesRoot) + 1) ); - sprintf (shphd->sh_localtextures[i],"%s%s",TexturesRoot, cshp.texture_fns[i]); - char * dotpos; - dotpos = strrchr (shphd->sh_localtextures[i], '.'); - sprintf (dotpos,".pg0"); - #else - shphd->sh_localtextures[i] = - (char *) AllocateMem (sizeof(char) * (strlen(cshp.texture_fns[i]) + 1) ); - strcpy (shphd->sh_localtextures[i], cshp.texture_fns[i]); - #endif - } - shphd->sh_localtextures[i] = 0; - } - - - - - SHAPEINSTR * instruct = (SHAPEINSTR *)AllocateMem(sizeof(SHAPEINSTR)*6); - - shphd->sh_instruction = instruct; - - - instruct[0].sh_instr = I_ShapePoints; /*I_shapepoints*/ - instruct[0].sh_numitems = shphd->numpoints; - instruct[0].sh_instr_data = shphd->points; - - instruct[1].sh_instr = I_ShapeNormals; /*I_shapenormals*/ - instruct[1].sh_numitems = shphd->numitems; - instruct[1].sh_instr_data = shphd->sh_normals; - - instruct[2].sh_instr = I_ShapeProject; /*I_shapeproject*/ - instruct[2].sh_numitems = shphd->numpoints; - instruct[2].sh_instr_data = shphd->points; - - instruct[3].sh_instr = I_ShapeVNormals; /*I_shapevnormals*/ - instruct[3].sh_numitems = shphd->numpoints; - instruct[3].sh_instr_data = shphd->sh_vnormals; - - instruct[4].sh_instr = I_ShapeItems; - instruct[4].sh_numitems = shphd->numitems; - instruct[4].sh_instr_data = shphd->items; - - instruct[5].sh_instr = I_ShapeEnd; /*I_shapeEND*/ - instruct[5].sh_numitems = 0; - instruct[5].sh_instr_data = 0; - - - - return TRUE; -#if 0 - SHAPEHEADER * shphd = (SHAPEHEADER *) AllocateMem(sizeof(SHAPEHEADER)); - memset(shphd,0,sizeof(SHAPEHEADER)); - - ChunkShape cshp = shp->shape_data; - - Shape_Merge_Data_Chunk * smdc = 0; - - Chunk * pChunk = shp->lookup_single_child("SHPMRGDT"); - if (pChunk) - { - smdc = (Shape_Merge_Data_Chunk *) pChunk; - } - - merge_polygons_in_chunkshape (cshp,smdc); - - int i,j, * tptr; - - mainshapelist[list_pos] = shphd; - - // header data (note shapeheader is calloced) - - shphd->numpoints = cshp.num_verts; - shphd->numitems = cshp.num_polys; - - shphd->shaperadius = (int) (cshp.radius*local_scale); - - shphd->shapeflags = shphd->shapeflags | (ShapeFlag_AugZ | ShapeFlag_AugZ_Lite | - ShapeFlag_SizeSortItems); // SIZE HACK!!! - - shphd->shapemaxx = (int) (cshp.max.x*local_scale); - shphd->shapeminx = (int) (cshp.min.x*local_scale); - shphd->shapemaxy = (int) (cshp.max.y*local_scale); - shphd->shapeminy = (int) (cshp.min.y*local_scale); - shphd->shapemaxz = (int) (cshp.max.z*local_scale); - shphd->shapeminz = (int) (cshp.min.z*local_scale); - - // AllocateMem arrays - - shphd->points = (int **) AllocateMem (sizeof(int *)); - *(shphd->points) = (int *) AllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_vnormals = (int **) AllocateMem (sizeof(int *)); - *(shphd->sh_vnormals) = (int *) AllocateMem (sizeof(int) * shphd->numpoints * 3); - - shphd->sh_normals = (int **) AllocateMem (sizeof(int *)); - *(shphd->sh_normals) = (int *) AllocateMem (sizeof(int) * shphd->numitems * 3); - - // for textures - if (cshp.num_uvs) - shphd->sh_textures = (int **) AllocateMem (sizeof(int *) * cshp.num_uvs); - if (cshp.num_texfiles) - shphd->sh_localtextures = (char **) AllocateMem (sizeof(char *) * (cshp.num_texfiles+1)); - - int * item_list; - - shphd->items = (int **) AllocateMem (sizeof(int *) * shphd->numitems); - item_list = (int *) AllocateMem (sizeof(int) * shphd->numitems * 9); - - tptr = *(shphd->points); - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = (int) (cshp.v_list[i].x*local_scale); - tptr[i*3 + 1] = (int) (cshp.v_list[i].y*local_scale); - tptr[i*3 + 2] = (int) (cshp.v_list[i].z*local_scale); - } - - tptr = *(shphd->sh_vnormals); - - for (i=0; i<shphd->numpoints; i++) { - tptr[i*3] = (int) (cshp.v_normal_list[i].x*ONE_FIXED); - tptr[i*3 + 1] = (int) (cshp.v_normal_list[i].y*ONE_FIXED); - tptr[i*3 + 2] = (int) (cshp.v_normal_list[i].z*ONE_FIXED); - } - - tptr = *(shphd->sh_normals); - - for (i=0; i<shphd->numitems; i++) { - tptr[i*3] = (int) (cshp.p_normal_list[i].x*ONE_FIXED); - tptr[i*3 + 1] = (int) (cshp.p_normal_list[i].y*ONE_FIXED); - tptr[i*3 + 2] = (int) (cshp.p_normal_list[i].z*ONE_FIXED); - } - - - for (i=0; i<shphd->numitems; i++) - shphd->items[i] = &item_list[i*9]; - - - for (i=0; i<shphd->numitems; i++) { - item_list[i*9] = (cshp.poly_list[i].engine_type); -// item_list[i*9] = I_Polyline; - - - if((item_list[i*9] < 2 ) || (item_list[i*9] > 9)) - { - item_list[i*9] = I_Polygon; - } - - if(item_list[i*9] == I_2dTexturedPolygon) - { - item_list[i*9] = I_Polygon; - } - - if(item_list[i*9] == I_3dTexturedPolygon) - { - item_list[i*9] = I_2dTexturedPolygon; - } - -// if(item_list[i*9] == I_Polygon) -// { -// item_list[i*9] = I_ZB_Polygon; -// /*HACK HACK ROXHACK*/ -// } - - item_list[i*9 + 1] = (cshp.poly_list[i].normal_index * 3); - item_list[i*9 + 2] = (cshp.poly_list[i].flags&~ChunkInternalItemFlags); -// item_list[i*9 + 2] = (cshp.poly_list[i].flags) | iflag_nolight; - item_list[i*9 + 3] = (cshp.poly_list[i].colour); - - if ( (item_list[i*9] == 5 || item_list[i*9] == 6) && - !( item_list[i*9 + 3] & 0x8000 ) ) - { - int texno = item_list[i*9 + 3] & 0x7fff; - - if (texno < max_index) - if (tex_index_nos[texno] != -1) - { - item_list[i*9 + 3] &= 0xffff0000; - item_list[i*9 + 3] += tex_index_nos[texno]; - } - else - { - item_list[i*9] = I_Polyline; - item_list[i*9 + 2] = (cshp.poly_list[i].flags &~ChunkInternalItemFlags) /*| iflag_nolight*/; - item_list[i*9 + 3] = 0xffffffff; - } - else - { - item_list[i*9] = I_Polyline; - item_list[i*9 + 2] = (cshp.poly_list[i].flags &~ChunkInternalItemFlags) /*| iflag_nolight*/; - item_list[i*9 + 3] = 0xffffffff; - } - } - - -// item_list[i*9 + 3] = 0xffffffff; - for (j=0;j<cshp.poly_list[i].num_verts;j++) -// item_list[i*9 + 4 +j] = (cshp.poly_list[i].vert_ind[j] *3); - /* KJL 12:23:02 9/17/97 - I've removed the annoying *3 */ - item_list[i*9 + 4 +j] = (cshp.poly_list[i].vert_ind[j]); - for (;j<5;j++) - item_list[i*9 + 4 +j] = -1; - } - - if (cshp.num_uvs) - { - for (i=0; i<cshp.num_uvs; i++) { - shphd->sh_textures[i] = (int *) AllocateMem (sizeof(int) * cshp.uv_list[i].num_verts * 2); - for (j=0; j<cshp.uv_list[i].num_verts; j++) { - (shphd->sh_textures[i])[(j*2)] = (int)cshp.uv_list[i].vert[j].u; - (shphd->sh_textures[i])[(j*2)+1] = (int)cshp.uv_list[i].vert[j].v; - } - } - } - /* - * FILENAME: e:\avpcode\3dc\win95\chnkload.cpp - * - * PARAMETERS: - * - * DESCRIPTION: - * - * RETURNS: - * - */ - - - if (cshp.num_texfiles) - { - for (i=0; i<cshp.num_texfiles; i++) { - #if john - shphd->sh_localtextures[i] = - (char *) AllocateMem (sizeof(char) * (strlen(cshp.texture_fns[i]) + strlen(TexturesRoot) + 1) ); - sprintf (shphd->sh_localtextures[i],"%s%s",TexturesRoot, cshp.texture_fns[i]); - char * dotpos; - dotpos = strrchr (shphd->sh_localtextures[i], '.'); - sprintf (dotpos,".pg0"); - #else - shphd->sh_localtextures[i] = - (char *) AllocateMem (sizeof(char) * (strlen(cshp.texture_fns[i]) + 1) ); - strcpy (shphd->sh_localtextures[i], cshp.texture_fns[i]); - #endif - } - shphd->sh_localtextures[i] = 0; - } - - - - - SHAPEINSTR * instruct = (SHAPEINSTR *)AllocateMem(sizeof(SHAPEINSTR)*6); - - shphd->sh_instruction = instruct; - - - instruct[0].sh_instr = I_ShapePoints; /*I_shapepoints*/ - instruct[0].sh_numitems = shphd->numpoints; - instruct[0].sh_instr_data = shphd->points; - - instruct[1].sh_instr = I_ShapeNormals; /*I_shapenormals*/ - instruct[1].sh_numitems = shphd->numitems; - instruct[1].sh_instr_data = shphd->sh_normals; - - instruct[2].sh_instr = I_ShapeProject; /*I_shapeproject*/ - instruct[2].sh_numitems = shphd->numpoints; - instruct[2].sh_instr_data = shphd->points; - - instruct[3].sh_instr = I_ShapeVNormals; /*I_shapevnormals*/ - instruct[3].sh_numitems = shphd->numpoints; - instruct[3].sh_instr_data = shphd->sh_vnormals; - - instruct[4].sh_instr = I_ShapeItems; - instruct[4].sh_numitems = shphd->numitems; - instruct[4].sh_instr_data = shphd->items; - - instruct[5].sh_instr = I_ShapeEnd; /*I_shapeEND*/ - instruct[5].sh_numitems = 0; - instruct[5].sh_instr_data = 0; - - - - return TRUE; -#endif -} -#endif - - - - - diff --git a/3dc/win95/d3_func.cpp b/3dc/win95/d3_func.cpp deleted file mode 100644 index 923e7f2..0000000 --- a/3dc/win95/d3_func.cpp +++ /dev/null @@ -1,949 +0,0 @@ - -// Interface functions (written in C++) for -// Direct3D immediate mode system - -// Must link to C code in main engine system - -extern "C" { - -// Mysterious definition required by objbase.h -// (included via one of the include files below) -// to start definition of obscure unique in the -// universe IDs required by Direct3D before it -// will deign to cough up with anything useful... - -#define INITGUID - -#include "3dc.h" - -#include "awTexLd.h" - -#include "dxlog.h" -#include "module.h" -#include "inline.h" - -#include "d3_func.h" -#include "d3dmacs.h" - -#include "string.h" - -#include "kshape.h" -#include "eax.h" -#include "vmanpset.h" - -extern "C++" { -#include "chnktexi.h" -#include "chnkload.hpp" // c++ header which ignores class definitions/member functions if __cplusplus is not defined ? -#include "r2base.h" -} - -#define UseLocalAssert No -#include "ourasert.h" - - - -// FIXME!!! Structures in d3d structure -// never have any size field set!!! -// This is how it's done in Microsoft's -// demo code --- but ARE THEY LYING??? - -// As far as I know the execute buffer should always be in -// system memory on any configuration, but this may -// eventually have to be changed to something that reacts -// to the caps bit in the driver, once drivers have reached -// the point where we can safely assume that such bits will be valid. -#define ForceExecuteBufferIntoSystemMemory Yes - -// To define TBLEND mode --- at present -// it must be on for ramp textures and -// off for evrything else... -#define ForceTBlendCopy No - -// Set to Yes for debugging, to No for normal -// operations (i.e. if we need a palettised -// file for an accelerator, load it from -// pre-palettised data, using code not yet -// written as of 27 / 8/ 96) -#define QuantiseOnLoad Yes - -// Set to Yes to make default texture filter bilinear averaging rather -// than nearest -BOOL BilinearTextureFilter = 1; - -extern LPDIRECTDRAW lpDD; - -#if 0// -// Externs - -extern int VideoMode; -extern int DXMemoryMode; -extern int ZBufferRequestMode; -extern int RasterisationRequestMode; -extern int SoftwareScanDrawRequestMode; -extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; -extern VIEWDESCRIPTORBLOCK* Global_VDB_Ptr; -extern IMAGEHEADER ImageHeaderArray[]; -extern BOOL MMXAvailable; - - -//Globals - -int D3DDriverMode; - - - -static unsigned char DefaultD3DTextureFilterMin; -static unsigned char DefaultD3DTextureFilterMax; - - -#if SuppressWarnings -static int* itemptr_tmp; - -#ifdef __WATCOMC__ -#pragma warning 389 5 -#pragma message("Note: Disabled Warning W389 'Integral value may be truncated...'") -#endif - -#endif - - -#endif // -HRESULT LastError; -int ExBufSize; - -LPDIRECT3DEXECUTEBUFFER lpD3DExecCmdBuf; -LPDIRECTDRAWSURFACE lpZBuffer; -extern LPDIRECTDRAWSURFACE lpDDSBack; -extern LPDIRECTDRAWSURFACE lpDDSPrimary; -extern LPDIRECTDRAWPALETTE lpDDPal[]; // DirectDraw palette - -D3DINFO d3d; -BOOL D3DHardwareAvailable; - -int StartDriver; -int StartFormat; - - -static int devZBufDepth; - - -extern int WindowMode; -extern int ZBufferMode; -extern int ScanDrawMode; -extern int VideoModeColourDepth; - -extern enum TexFmt { D3TF_4BIT, D3TF_8BIT, D3TF_16BIT, D3TF_32BIT, D3TF_MAX } d3d_desired_tex_fmt; - -// Callback function to enumerate devices present -// on system (required so that device interface GUID -// can be retrieved if for no other reason). Device -// information is copied into instance of structure -// defined in d3_func.h - -HRESULT WINAPI DeviceEnumerator(LPGUID lpGuid, - LPSTR lpDeviceDescription, LPSTR lpDeviceName, - LPD3DDEVICEDESC lpHWDesc, LPD3DDEVICEDESC lpHELDesc, LPVOID lpContext) -{ - int *lpStartDriver = (int *)lpContext; - - /* - Record the D3D driver's description - of itself. - */ - - memcpy(&d3d.Driver[d3d.NumDrivers].Guid, lpGuid, sizeof(GUID)); - strcpy(d3d.Driver[d3d.NumDrivers].About, lpDeviceDescription); - strcpy(d3d.Driver[d3d.NumDrivers].Name, lpDeviceName); - - /* - Is this a hardware device or software emulation? Checking the color - model for a valid model works. - */ - - if (lpHWDesc->dcmColorModel) - { - D3DHardwareAvailable = Yes; - d3d.Driver[d3d.NumDrivers].Hardware = Yes; - memcpy(&d3d.Driver[d3d.NumDrivers].Desc, lpHWDesc, - sizeof(D3DDEVICEDESC)); - } - else - { - d3d.Driver[d3d.NumDrivers].Hardware = No; - memcpy(&d3d.Driver[d3d.NumDrivers].Desc, lpHELDesc, - sizeof(D3DDEVICEDESC)); - } - - /* - Does this driver do texture mapping? - */ - - d3d.Driver[d3d.NumDrivers].Textures = - (d3d.Driver[d3d.NumDrivers].Desc.dpcTriCaps.dwTextureCaps & - D3DPTEXTURECAPS_PERSPECTIVE) ? TRUE : FALSE; - - /* - Can this driver use a z-buffer? - */ - - d3d.Driver[d3d.NumDrivers].ZBuffer = - d3d.Driver[d3d.NumDrivers].Desc.dwDeviceZBufferBitDepth & (DDBD_16 | DDBD_24 | DDBD_32) - ? TRUE : FALSE; - -// The driver description is recorded here, -// and some basic things like ZBuffering -// availability are noted separately. Other -// things such as hardware acceleration for -// translucency could potentially be noted here -// for use in the Write functions to decide -// whether e.g. iflag_transparent should be -// treated as valid. Obviously this will -// require modification of the D3DDRIVERINFO -// structure in d3_func.h - - *lpStartDriver = d3d.NumDrivers; - - d3d.NumDrivers++; - if (d3d.NumDrivers == MAX_D3D_DRIVERS) - return (D3DENUMRET_CANCEL); - else - return (D3DENUMRET_OK); -} - -// This function is called from -// InitialiseDirect3DImmediateMode, to -// insert and execute opcodes which cannot -// be run during a "real" scene because of -// some obscure feature of Direct3D. - - - -// Initialise Direct3D immediate mode system - -BOOL InitialiseDirect3DImmediateMode(void) -{ - BOOL RetVal; -// to tell device enum function that it has not been called before - StartDriver = -1; -// to tell texture enum function that it has not been called before - StartFormat = -1; - -// default is no hardware -// note that we are still resetting -// this here just in case the test from -// InitialiseSystem failed and things aren't -// what we thought... - D3DHardwareAvailable = No; - -// Zero d3d structure - memset(&d3d, 0, sizeof(D3DINFO)); - -// Set up Direct3D interface object - - LastError = lpDD->QueryInterface(IID_IDirect3D, (LPVOID*) &d3d.lpD3D); - LOGDXERR(LastError); - - if (LastError != DD_OK) - return FALSE; -// Use callback function to enumerate available devices on system -// and acquire device GUIDs etc -// note that we are still resetting -// this here just in case the test from -// InitialiseSystem failed and things aren't -// what we thought... - LastError = d3d.lpD3D->EnumDevices(DeviceEnumerator, (LPVOID)&StartDriver); - LOGDXERR(LastError); - - if (LastError != D3D_OK) - return FALSE; - -// Must be run as soon as possible in the -// initialisation sequence, but after the -// device enumeration (and obviously after -// DirectDraw object and surface initialisation). - SelectD3DDriverAndDrawMode(); - d3d.ThisDriver = d3d.Driver[d3d.CurrentDriver].Desc; - -// Test!!! Release D3D object if we don't need it and do an -// early exit. Will this fix the banding problem on some -// accelerators in palettised modes?? -// Evidently not. Still, probably a good thing to do... -// But!!! The whole banding problem appears to be a -// modeX emulation problem on some 3D accelerator cards... - #if 1 - if (ScanDrawMode == ScanDrawDirectDraw) - { - ReleaseDirect3DNotDDOrImages(); - return TRUE; - } - #endif - - -// Note that this must be done BEFORE the D3D device object is created - #if SupportZBuffering - if (ZBufferMode != ZBufferOff) - { - RetVal = CreateD3DZBuffer(); - if (RetVal == FALSE) return FALSE; - } - #endif - -// Set up Direct3D device object (must be linked to back buffer) - LastError = lpDDSBack->QueryInterface(d3d.Driver[d3d.CurrentDriver].Guid, - (LPVOID*)&d3d.lpD3DDevice); - LOGDXERR(LastError); - - if (LastError != DD_OK) - return FALSE; - - AW_TL_ERC awErr = AwSetD3DDevice(d3d.lpD3DDevice); - GLOBALASSERT(AW_TLE_OK==awErr); -// Enumerate texture formats and pick one -// (palettised if possible). - d3d.NumTextureFormats = 0; - - d3d_desired_tex_fmt=D3TF_8BIT; - - LastError = d3d.lpD3DDevice->EnumTextureFormats - (TextureFormatsEnumerator, - (LPVOID)&StartFormat); - LOGDXERR(LastError); - - if (LastError != D3D_OK) - #if debug - { - ReleaseDirect3D(); - exit(LastError); - } - #else - return FALSE; - #endif - - d3d.CurrentTextureFormat = StartFormat; - - // NEW NEW NEW - // Note: we are NOT restricted to only one texture format - awErr = AwSetTextureFormat(&d3d.TextureFormat[StartFormat].ddsd); - GLOBALASSERT(AW_TLE_OK==awErr); - -// Create viewport - LastError = d3d.lpD3D->CreateViewport(&d3d.lpD3DViewport, NULL); - LOGDXERR(LastError); - - if (LastError != D3D_OK) - return FALSE; - -// Add viewport to desired device - LastError = d3d.lpD3DDevice->AddViewport(d3d.lpD3DViewport); - LOGDXERR(LastError); - - if (LastError != D3D_OK) - return FALSE; - -// Set up viewport data - -// Note that the viewport is always set to the -// SDB limits because internal clipping is handled -// within the main engine code using the VDB -// system. - - { - // Configure viewport here - D3DVIEWPORT viewPort; - memset(&viewPort, 0, sizeof(D3DVIEWPORT)); - viewPort.dwSize = sizeof(D3DVIEWPORT); - viewPort.dwX = 0; // origins x and y - viewPort.dwY = 0; - viewPort.dwWidth = ScreenDescriptorBlock.SDB_Width; - viewPort.dwHeight = ScreenDescriptorBlock.SDB_Height; - viewPort.dvScaleX = D3DVAL((float)viewPort.dwWidth / 2.0); // ????was 2.0 - viewPort.dvScaleY = D3DVAL((float)viewPort.dwHeight / 2.0); // ????was 2.0 - viewPort.dvMaxX = D3DVAL(D3DDivide(D3DVAL(viewPort.dwWidth), - D3DVAL(2 * viewPort.dvScaleX))); // ???? - viewPort.dvMaxY = D3DVAL(D3DDivide(D3DVAL(viewPort.dwHeight), - D3DVAL(2 * viewPort.dvScaleY))); // ???? - - // And actually set viewport - LastError = d3d.lpD3DViewport->SetViewport(&viewPort); - LOGDXERR(LastError); - - if (LastError != D3D_OK) - return FALSE; - } - -// At present we will not set a background material for the -// viewport, staying instead with the blit code in backdrop.c - -// Also, we are not currently adding default lights to the -// viewport, since the engine lighting system is completely -// disconnected from the immediate mode lighting module. - -// Create execute buffer - - { - // Locals for execute buffer - D3DEXECUTEBUFFERDESC d3dexDesc; - - // Set up structure to initialise buffer - // Note some instructions (e.g. lines) may be smaller than a - // triangle, but none can be larger - ExBufSize = ((sizeof(D3DINSTRUCTION) + sizeof(D3DTRIANGLE)) - * MaxD3DInstructions) - + (sizeof(D3DTLVERTEX) * MaxD3DVertices); - memset(&d3dexDesc, 0, sizeof(D3DEXECUTEBUFFERDESC)); - d3dexDesc.dwSize = sizeof(D3DEXECUTEBUFFERDESC); - d3dexDesc.dwFlags = D3DDEB_BUFSIZE | D3DDEB_CAPS; - d3dexDesc.dwBufferSize = ExBufSize; - #if ForceExecuteBufferIntoSystemMemory - d3dexDesc.dwCaps = D3DDEBCAPS_SYSTEMMEMORY; - #else - d3dexDesc.dwCaps = D3DDEBCAPS_MEM; // untested!!! - #endif - - // Create buffer - LastError = d3d.lpD3DDevice->CreateExecuteBuffer - (&d3dexDesc, &lpD3DExecCmdBuf, NULL); - LOGDXERR(LastError); - - if (LastError != D3D_OK) - return FALSE; - } - - // Temporary patch here because the defaults function - // buggers palette setting in ScanDrawDirectDraw - // for some really obscure reason... - - if (ScanDrawMode != ScanDrawDirectDraw) - SetExecuteBufferDefaults(); - - - return TRUE; -} - -#if 1 - -// Note that error conditions have been removed -// on the grounds that an early exit will prevent -// EndScene being run if this function is used, -// which screws up all subsequent buffers - -BOOL RenderD3DScene(void) - -{ - // Begin scene - // My theory is that the functionality of this - // thing must invoke a DirectDraw surface lock - // on the back buffer without telling you. However, - // we shall see... - - LastError = d3d.lpD3DDevice->BeginScene(); - LOGDXERR(LastError); - - // if (LastError != D3D_OK) - // return FALSE; - - // Execute buffer - LastError = d3d.lpD3DDevice->Execute(lpD3DExecCmdBuf, - d3d.lpD3DViewport, D3DEXECUTE_UNCLIPPED); - LOGDXERR(LastError); - - // if (LastError != D3D_OK) - // return FALSE; - - // End scene - LastError = d3d.lpD3DDevice->EndScene(); - LOGDXERR(LastError); - - // if (LastError != D3D_OK) - // return FALSE; - - - - return TRUE; -} - -#else - -int Time1, Time2, Time3, Time4; - -BOOL RenderD3DScene(void) - -{ - - // Begin scene - // My theory is that the functionality of this - // thing must invoke a DirectDraw surface lock - // on the back buffer without telling you. However, - // we shall see... - - Time1 = GetWindowsTickCount(); - - LastError = d3d.lpD3DDevice->BeginScene(); - LOGDXERR(LastError); - - if (LastError != D3D_OK) - return FALSE; - - Time2 = GetWindowsTickCount(); - - // Execute buffer - #if 1 - LastError = d3d.lpD3DDevice->Execute(lpD3DExecCmdBuf, - d3d.lpD3DViewport, D3DEXECUTE_UNCLIPPED); - LOGDXERR(LastError); - #else - LastError = d3d.lpD3DDevice->Execute(lpD3DExecCmdBuf, - d3d.lpD3DViewport, D3DEXECUTE_CLIPPED); - LOGDXERR(LastError); - #endif - - if (LastError != D3D_OK) - return FALSE; - - Time3 = GetWindowsTickCount(); - - // End scene - LastError = d3d.lpD3DDevice->EndScene(); - LOGDXERR(LastError); - - if (LastError != D3D_OK) - return FALSE; - - Time4 = GetWindowsTickCount(); - - - - return TRUE; - -#endif - - -// With a bit of luck this should automatically -// release all the Direct3D and DirectDraw -// objects using their own functionality. -// A separate call to finiObjects -// is not required. -// NOTE!!! This depends on Microsoft macros -// in d3dmacs.h, which is in the win95 directory -// and must be upgraded from sdk upgrades!!! - -void ReleaseDirect3D(void) - -{ - DeallocateAllImages(); - RELEASE(d3d.lpD3DViewport); - RELEASE(d3d.lpD3DDevice); - #if SupportZBuffering - RELEASE(lpZBuffer); - #endif - RELEASE(lpDDPal[0]); - RELEASE(lpDDSBack); - RELEASE(lpDDSPrimary); - RELEASE(d3d.lpD3D); - RELEASE(lpDD); - - /* release Direct Input stuff */ - ReleaseDirectKeyboard(); - ReleaseDirectMouse(); - ReleaseDirectInput(); - - // Reset windows palette entry allocation - if ((VideoModeColourDepth == 8) && (WindowMode == WindowModeSubWindow)) - { - HDC hdc = GetDC(NULL); - SetSystemPaletteUse(hdc, SYSPAL_STATIC); - ReleaseDC(NULL, hdc); - } -} - -// Release all Direct3D objects -// but not DirectDraw - -void ReleaseDirect3DNotDDOrImages(void) - -{ - RELEASE(d3d.lpD3DViewport); - RELEASE(d3d.lpD3DDevice); - #if SupportZBuffering - RELEASE(lpZBuffer); - #endif - RELEASE(d3d.lpD3D); -} - -void ReleaseDirect3DNotDD(void) - -{ - DeallocateAllImages(); - RELEASE(d3d.lpD3DViewport); - RELEASE(d3d.lpD3DDevice); - #if SupportZBuffering - RELEASE(lpZBuffer); - #endif - RELEASE(d3d.lpD3D); -} - - -// NOTE!!! These functions depend on Microsoft macros -// in d3dmacs.h, which is in the win95 directory -// and must be upgraded from sdk upgrades!!! - - -// ALSO NOTE!!! All this stuff involves heavy -// use of floating point assembler in software -// emulation, probably hand parallelised between -// the FPU and the processor or something bizarre, -// implying that this stuff SHOULD NOT be used -// one anything below a Pentium. - -// AND AGAIN!!! Due to the nature of the item -// format, the rasterisation module MUST RECEIVE -// repeated vertices in the data area. Tough shit, -// Microsoft, that's what I say... - -void WritePolygonToExecuteBuffer(int* itemptr) - -{ -} - -void WriteGouraudPolygonToExecuteBuffer(int* itemptr) - -{ -} - -void Write2dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - -void WriteGouraud2dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - - -void Write3dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ - } - -void WriteGouraud3dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - -#if SupportZBuffering - -// To make effective use of 16 bit z buffers (common -// on hardware accelerators) we must have a z coordinate -// which has been transformed into screen space in such a -// way that linearity and planearity are preserved, i.e. as -// if we had done a homogeneous transformation. For the case -// in which the far clipping plane is much further away than the -// near one (effectively true for 3dc, especially as there is -// no far clipping plane as such), the appropriate transformation -// can be reduced to zScreen = (ZWorld - ZNear) / ZWorld. This -// calculation is therefore (unfortunately) done for each vertex -// for z buffered items, taking ZNear to be the current -// VDB_ClipZ * GlobalScale. - - -void WriteZBPolygonToExecuteBuffer(int* itemptr) - -{ -} - -void WriteZBGouraudPolygonToExecuteBuffer(int* itemptr) - -{ -} - -void WriteZB2dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - - -void WriteZBGouraud2dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - -void WriteZB3dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - -void WriteZBGouraud3dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - -#endif - - - -void WriteBackdrop2dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - -// Same as ordinary 2d textured draw at present, but may e.g. -// require different texture wrapping behaviour or -// w values. - -void WriteBackdrop3dTexturedPolygonToExecuteBuffer(int* itemptr) - -{ -} - - -// Note that this is all dead crap and deeply unoptimised -// But then... a) it's really only a test and -// b) it's for the tools group anyway... - - -void DirectWriteD3DLine(VECTOR2D* LineStart, VECTOR2D* LineEnd, int LineColour) - -{ - -} - - -// reload D3D image -- assumes a base pointer points to the image loaded -// from disc, in a suitable format - -void ReloadImageIntoD3DImmediateSurface(IMAGEHEADER* iheader) -{ - - void *reloadedTexturePtr = ReloadImageIntoD3DTexture(iheader); - LOCALASSERT(reloadedTexturePtr != NULL); - - int gotTextureHandle = GetTextureHandle(iheader); - LOCALASSERT(gotTextureHandle == TRUE); -} - -void* ReloadImageIntoD3DTexture(IMAGEHEADER* iheader) -{ - // NOTE FIXME BUG HACK - // what if the image was a DD surface ?? - - if (iheader->hBackup) - { - iheader->D3DTexture = AwCreateTexture("rf",AW_TLF_PREVSRC|AW_TLF_COMPRESS); - return iheader->D3DTexture; - } - else return NULL; -} - -int GetTextureHandle(IMAGEHEADER *imageHeaderPtr) -{ - LPDIRECT3DTEXTURE Texture = (LPDIRECT3DTEXTURE) imageHeaderPtr->D3DTexture; - - LastError = Texture->GetHandle(d3d.lpD3DDevice, (D3DTEXTUREHANDLE*)&(imageHeaderPtr->D3DHandle)); - - if (LastError != D3D_OK) return FALSE; - - return TRUE; -} - - - -void ReleaseD3DTexture(void* D3DTexture) - -{ - LPDIRECT3DTEXTURE lpTexture; - - lpTexture = (LPDIRECT3DTEXTURE) D3DTexture; - RELEASE(lpTexture); -} - - -#if SupportZBuffering - -BOOL CreateD3DZBuffer(void) - -{ - DDSURFACEDESC ddsd; - - // For safety, kill any existing z buffer - #if SupportZBuffering - RELEASE(lpZBuffer); - #endif - - - // If we do not have z buffering support - // on this driver, give up now - if (!(d3d.Driver[d3d.CurrentDriver].ZBuffer)) - return FALSE; - - memset(&ddsd,0,sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddsd.dwFlags = (DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS | DDSD_ZBUFFERBITDEPTH); - ddsd.dwHeight = ScreenDescriptorBlock.SDB_Height; - ddsd.dwWidth = ScreenDescriptorBlock.SDB_Width; - ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER; - - // If we are on a hardware driver, then the z buffer - // MUST be in video memory. Otherwise, it MUST be - // in system memory. I think. - - if (d3d.Driver[d3d.CurrentDriver].Hardware) - ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY; - else - ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY; - - // Get the Z buffer bit depth from this driver's - // D3D device description and add it to the description - // of the surface we want to create - - devZBufDepth = d3d.Driver[d3d.CurrentDriver].Desc.dwDeviceZBufferBitDepth; - - if (devZBufDepth & DDBD_32) - ddsd.dwZBufferBitDepth = 32; - else if (devZBufDepth & DDBD_24) - ddsd.dwZBufferBitDepth = 24; - else if (devZBufDepth & DDBD_16) - ddsd.dwZBufferBitDepth = 16; - else if (devZBufDepth & DDBD_8) - ddsd.dwZBufferBitDepth = 8; - else - { - #if debug - ReleaseDirect3D(); - exit(0x511621); - #else - return FALSE; - #endif - } - - // Eight-bit z buffer? Fuck off. - if (ddsd.dwZBufferBitDepth == 8) - return FALSE; - - // Now we must actually make the z buffer - - LastError = lpDD->CreateSurface(&ddsd,&lpZBuffer, NULL); - - if (LastError != DD_OK) - { - RELEASE(lpZBuffer); - return FALSE; - } - - LastError = lpDDSBack->AddAttachedSurface(lpZBuffer); - - if (LastError != DD_OK) - { - RELEASE(lpZBuffer); - return FALSE; - } - - return TRUE; -} - -#define ZFlushVal 0xffffffff - -// At present we are using my z flush function, with the -// (undocumented) addition of a fill colour for the -// actual depth fill, since it seems to work and at least -// I know what it does. If it starts failing we'll probably -// have to go back to invoking the viewport clear through -// Direct3D. - -void FlushD3DZBuffer(void) - -{ - - DDBLTFX ddbltfx; - - memset(&ddbltfx, 0, sizeof(ddbltfx)); - ddbltfx.dwSize = sizeof(ddbltfx); - ddbltfx.dwFillDepth = devZBufDepth; - ddbltfx.dwFillColor = ZFlushVal; - - /* lets blt a color to the surface*/ - LastError = lpZBuffer->Blt(NULL, NULL, NULL, DDBLT_DEPTHFILL | DDBLT_WAIT, &ddbltfx); - -} -void SecondFlushD3DZBuffer(void) -{ - #if 1 - { - WriteEndCodeToExecuteBuffer(); - UnlockExecuteBufferAndPrepareForUse(); - ExecuteBuffer(); - LockExecuteBuffer(); - } - - DDBLTFX ddbltfx; - - memset(&ddbltfx, 0, sizeof(ddbltfx)); - ddbltfx.dwSize = sizeof(ddbltfx); - ddbltfx.dwFillDepth = devZBufDepth; - ddbltfx.dwFillColor = ZFlushVal; - - /* lets blt a color to the surface*/ - LastError = lpZBuffer->Blt(NULL, NULL, NULL, DDBLT_DEPTHFILL | DDBLT_WAIT, &ddbltfx); - #else - extern void ClearZBufferWithPolygon(void); - ClearZBufferWithPolygon(); - #endif -} - - -#endif -void FlushZB(void) -{ - HRESULT hRes; - D3DRECT d3dRect; - - - d3dRect.lX1 = 0; - d3dRect.lX2 = 640; - d3dRect.lY1 = 0; - d3dRect.lY2 = 480; - hRes = d3d.lpD3DViewport->Clear(1, &d3dRect, D3DCLEAR_ZBUFFER); - - -} - - - -// For extern "C" - -}; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/3dc/win95/d3_func.h b/3dc/win95/d3_func.h deleted file mode 100644 index eedbd5e..0000000 --- a/3dc/win95/d3_func.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef _included_d3_func_h_ -#define _included_d3_func_h_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - Direct3D globals -*/ - -/* - Maximum number of Direct3D drivers ever - expected to be resident on the system. -*/ -#define MAX_D3D_DRIVERS 5 -/* - Maximum number of texture formats ever - expected to be reported by a Direct3D - driver. -*/ -#define MAX_TEXTURE_FORMATS 10 - -/* - Description of a D3D driver. -*/ - -typedef struct D3DDriverInfo { - char Name[30]; /* short name of driver */ - char About[50]; /* string about driver */ - D3DDEVICEDESC Desc; /* full driver description */ - GUID Guid; /* wacky universally unique id thingy */ - BOOL Hardware; /* accelerated driver? */ - BOOL Textures; /* Texture mapping available? */ - BOOL ZBuffer; /* Z Buffering available? */ -} D3DDRIVERINFO; - -/* - Description of a D3D driver texture - format. -*/ - -typedef struct D3DTextureFormat { - DDSURFACEDESC ddsd; /* DDSURFACEDESC for the surface description */ - BOOL Palette; /* is Palettized? */ - int RedBPP; /* #red bits per pixel */ - int BlueBPP; /* #blue bits per pixel */ - int GreenBPP; /* #green bits per pixel */ - int IndexBPP; /* number of bits in palette index */ -} D3DTEXTUREFORMAT; - - -typedef struct D3DInfo { - LPDIRECT3D lpD3D; - LPDIRECT3DDEVICE lpD3DDevice; - LPDIRECT3DVIEWPORT lpD3DViewport; - int NumDrivers; - int CurrentDriver; - D3DDEVICEDESC ThisDriver; - D3DDRIVERINFO Driver[MAX_D3D_DRIVERS]; - int CurrentTextureFormat; - int NumTextureFormats; - D3DTEXTUREFORMAT TextureFormat[MAX_TEXTURE_FORMATS]; -} D3DINFO; - - - -/* KJL 14:24:45 12/4/97 - render state information */ -enum TRANSLUCENCY_TYPE -{ - TRANSLUCENCY_OFF, - TRANSLUCENCY_NORMAL, - TRANSLUCENCY_INVCOLOUR, - TRANSLUCENCY_COLOUR, - TRANSLUCENCY_GLOWING, - TRANSLUCENCY_DARKENINGCOLOUR, - TRANSLUCENCY_JUSTSETZ, - TRANSLUCENCY_NOT_SET -}; - -enum FILTERING_MODE_ID -{ - FILTERING_BILINEAR_OFF, - FILTERING_BILINEAR_ON, - FILTERING_NOT_SET -}; - -typedef struct -{ - enum TRANSLUCENCY_TYPE TranslucencyMode; - enum FILTERING_MODE_ID FilteringMode; - int FogDistance; - unsigned int FogIsOn :1; - unsigned int WireFrameModeIsOn :1; - -} RENDERSTATES; - - - - - -#ifdef __cplusplus -} -#endif - -#endif /* ! _included_d3_func_h_ */ diff --git a/3dc/win95/d3dmacs.h b/3dc/win95/d3dmacs.h deleted file mode 100644 index ce26f43..0000000 --- a/3dc/win95/d3dmacs.h +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 1995, 1996 Microsoft Corporation. All Rights Reserved. - * - * File: d3dmacs.h - * - * Useful macros for generating execute buffers. Consult the D3D sample - * code for examples of their usage. - * - * Use OP_NOP to QWORD align triangle and line instructions. - */ - -#ifndef __D3DMACS_H__ -#define __D3DMACS_H__ - -#undef RELEASE - -#ifndef __cplusplus -#define MAKE_MATRIX(lpDev, handle, data) \ - if (lpDev->lpVtbl->CreateMatrix(lpDev, &handle) != D3D_OK) \ - return FALSE; \ - if (lpDev->lpVtbl->SetMatrix(lpDev, handle, &data) != D3D_OK) \ - return FALSE -#define RELEASE(x) if (x != NULL) {x->lpVtbl->Release(x); x = NULL;} -#endif - -#ifdef __cplusplus -#define MAKE_MATRIX(lpDev, handle, data) \ - if (lpDev->CreateMatrix(&handle) != D3D_OK) \ - return FALSE; \ - if (lpDev->SetMatrix(handle, &data) != D3D_OK) \ - return FALSE -#define RELEASE(x) if (x != NULL) {x->Release(); x = NULL;} -#endif - -#define PUTD3DINSTRUCTION(op, sz, cnt, ptr) \ - ((LPD3DINSTRUCTION) ptr)->bOpcode = op; \ - ((LPD3DINSTRUCTION) ptr)->bSize = sz; \ - ((LPD3DINSTRUCTION) ptr)->wCount = cnt; \ - ptr = (void *)(((LPD3DINSTRUCTION) ptr) + 1) - -#define VERTEX_DATA(loc, cnt, ptr) \ - if ((ptr) != (loc)) memcpy((ptr), (loc), sizeof(D3DVERTEX) * (cnt)); \ - ptr = (void *)(((LPD3DVERTEX) (ptr)) + (cnt)) - -// OP_MATRIX_MULTIPLY size: 4 (sizeof D3DINSTRUCTION) -#define OP_MATRIX_MULTIPLY(cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_MATRIXMULTIPLY, sizeof(D3DMATRIXMULTIPLY), cnt, ptr) - -// MATRIX_MULTIPLY_DATA size: 12 (sizeof MATRIXMULTIPLY) -#define MATRIX_MULTIPLY_DATA(src1, src2, dest, ptr) \ - ((LPD3DMATRIXMULTIPLY) ptr)->hSrcMatrix1 = src1; \ - ((LPD3DMATRIXMULTIPLY) ptr)->hSrcMatrix2 = src2; \ - ((LPD3DMATRIXMULTIPLY) ptr)->hDestMatrix = dest; \ - ptr = (void *)(((LPD3DMATRIXMULTIPLY) ptr) + 1) - -// OP_STATE_LIGHT size: 4 (sizeof D3DINSTRUCTION) -#define OP_STATE_LIGHT(cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_STATELIGHT, sizeof(D3DSTATE), cnt, ptr) - -// OP_STATE_TRANSFORM size: 4 (sizeof D3DINSTRUCTION) -#define OP_STATE_TRANSFORM(cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_STATETRANSFORM, sizeof(D3DSTATE), cnt, ptr) - -// OP_STATE_RENDER size: 4 (sizeof D3DINSTRUCTION) -#define OP_STATE_RENDER(cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_STATERENDER, sizeof(D3DSTATE), cnt, ptr) - -// STATE_DATA size: 8 (sizeof D3DSTATE) -#define STATE_DATA(type, arg, ptr) \ - ((LPD3DSTATE) ptr)->drstRenderStateType = (D3DRENDERSTATETYPE)type; \ - ((LPD3DSTATE) ptr)->dwArg[0] = arg; \ - ptr = (void *)(((LPD3DSTATE) ptr) + 1) - -// OP_PROCESS_VERTICES size: 4 (sizeof D3DINSTRUCTION) -#define OP_PROCESS_VERTICES(cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_PROCESSVERTICES, sizeof(D3DPROCESSVERTICES), cnt, ptr) - -// PROCESSVERTICES_DATA size: 16 (sizeof D3DPROCESSVERTICES) -#define PROCESSVERTICES_DATA(flgs, strt, cnt, ptr) \ - ((LPD3DPROCESSVERTICES) ptr)->dwFlags = flgs; \ - ((LPD3DPROCESSVERTICES) ptr)->wStart = strt; \ - ((LPD3DPROCESSVERTICES) ptr)->wDest = strt; \ - ((LPD3DPROCESSVERTICES) ptr)->dwCount = cnt; \ - ((LPD3DPROCESSVERTICES) ptr)->dwReserved = 0; \ - ptr = (void *)(((LPD3DPROCESSVERTICES) ptr) + 1) - -// OP_TRIANGLE_LIST size: 4 (sizeof D3DINSTRUCTION) -#define OP_TRIANGLE_LIST(cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_TRIANGLE, sizeof(D3DTRIANGLE), cnt, ptr) - -#define TRIANGLE_LIST_DATA(loc, count, ptr) \ - if ((ptr) != (loc)) memcpy((ptr), (loc), sizeof(D3DTRIANGLE) * (count)); \ - ptr = (void *)(((LPD3DTRIANGLE) (ptr)) + (count)) - -// OP_LINE_LIST size: 4 (sizeof D3DINSTRUCTION) -#define OP_LINE_LIST(cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_LINE, sizeof(D3DLINE), cnt, ptr) - -#define LINE_LIST_DATA(loc, count, ptr) \ - if ((ptr) != (loc)) memcpy((ptr), (loc), sizeof(D3DLINE) * (count)); \ - ptr = (void *)(((LPD3DLINE) (ptr)) + (count)) - -// OP_POINT_LIST size: 8 (sizeof D3DINSTRUCTION + sizeof D3DPOINT) -#define OP_POINT_LIST(first, cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_POINT, sizeof(D3DPOINT), 1, ptr); \ - ((LPD3DPOINT)(ptr))->wCount = cnt; \ - ((LPD3DPOINT)(ptr))->wFirst = first; \ - ptr = (void*)(((LPD3DPOINT)(ptr)) + 1) - -// OP_SPAN_LIST size: 8 (sizeof D3DINSTRUCTION + sizeof D3DSPAN) -#define OP_SPAN_LIST(first, cnt, ptr) \ - PUTD3DINSTRUCTION(D3DOP_SPAN, sizeof(D3DSPAN), 1, ptr); \ - ((LPD3DSPAN)(ptr))->wCount = cnt; \ - ((LPD3DSPAN)(ptr))->wFirst = first; \ - ptr = (void*)(((LPD3DSPAN)(ptr)) + 1) - -// OP_BRANCH_FORWARD size: 18 (sizeof D3DINSTRUCTION + sizeof D3DBRANCH) -#define OP_BRANCH_FORWARD(tmask, tvalue, tnegate, toffset, ptr) \ - PUTD3DINSTRUCTION(D3DOP_BRANCHFORWARD, sizeof(D3DBRANCH), 1, ptr); \ - ((LPD3DBRANCH) ptr)->dwMask = tmask; \ - ((LPD3DBRANCH) ptr)->dwValue = tvalue; \ - ((LPD3DBRANCH) ptr)->bNegate = tnegate; \ - ((LPD3DBRANCH) ptr)->dwOffset = toffset; \ - ptr = (void *)(((LPD3DBRANCH) (ptr)) + 1) - -// OP_SET_STATUS size: 20 (sizeof D3DINSTRUCTION + sizeof D3DSTATUS) -#define OP_SET_STATUS(flags, status, _x1, _y1, _x2, _y2, ptr) \ - PUTD3DINSTRUCTION(D3DOP_SETSTATUS, sizeof(D3DSTATUS), 1, ptr); \ - ((LPD3DSTATUS)(ptr))->dwFlags = flags; \ - ((LPD3DSTATUS)(ptr))->dwStatus = status; \ - ((LPD3DSTATUS)(ptr))->drExtent.x1 = _x1; \ - ((LPD3DSTATUS)(ptr))->drExtent.y1 = _y1; \ - ((LPD3DSTATUS)(ptr))->drExtent.x2 = _x2; \ - ((LPD3DSTATUS)(ptr))->drExtent.y2 = _y2; \ - ptr = (void *)(((LPD3DSTATUS) (ptr)) + 1) - -// OP_NOP size: 4 -#define OP_NOP(ptr) \ - PUTD3DINSTRUCTION(D3DOP_TRIANGLE, sizeof(D3DTRIANGLE), 0, ptr) - -#define OP_EXIT(ptr) \ - PUTD3DINSTRUCTION(D3DOP_EXIT, 0, 0, ptr) - -#define QWORD_ALIGNED(ptr) \ - !(0x00000007L & (ULONG)(ptr)) - -#endif // __D3DMACS_H__ diff --git a/3dc/win95/d3load.c b/3dc/win95/d3load.c deleted file mode 100644 index 011106b..0000000 --- a/3dc/win95/d3load.c +++ /dev/null @@ -1,316 +0,0 @@ -/***************************************************************************/ -/* Loading a PPM file into a surface */ -/***************************************************************************/ -/* - * LoadSurface - * Loads a ppm file into a texture map DD surface of the given format. The - * memory flag specifies DDSCAPS_SYSTEMMEMORY or DDSCAPS_VIDEOMEMORY. - */ -LPDIRECTDRAWSURFACE -D3DAppILoadSurface(LPDIRECTDRAW lpDD, LPCSTR lpName, - LPDDSURFACEDESC lpFormat, DWORD memoryflag) -{ - LPDIRECTDRAWSURFACE lpDDS; - DDSURFACEDESC ddsd, format; - D3DCOLOR colors[256]; - D3DCOLOR c; - DWORD dwWidth, dwHeight; - int i, j; - FILE *fp; - char *lpC; - CHAR buf[100]; - LPDIRECTDRAWPALETTE lpDDPal; - PALETTEENTRY ppe[256]; - int psize; - DWORD pcaps; - int color_count; - BOOL bQuant = FALSE; - HRESULT ddrval; - - /* - * Find the image file and open it - */ - fp = D3DAppIFindFile(lpName, "rb"); - if (fp == NULL) { - D3DAppISetErrorString("Cannot find %s.\n", lpName); - return NULL; - } - /* - * Is it a PPM file? - */ - fgets(buf, sizeof buf, fp); - if (lstrcmp(buf, "P6\n")) { - fclose(fp); - D3DAppISetErrorString("%s is not a PPM file.\n", lpName); - return NULL; - } - /* - * Skip any comments - */ - do { - fgets(buf, sizeof buf, fp); - } while (buf[0] == '#'); - /* - * Read the width and height - */ - sscanf(buf, "%d %d\n", &dwWidth, &dwHeight); - fgets(buf, sizeof buf, fp); /* skip next line */ - /* - * Create a surface of the given format using the dimensions of the PPM - * file. - */ - memcpy(&format, lpFormat, sizeof(DDSURFACEDESC)); - if (format.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED8) { - bQuant = TRUE; - psize = 256; - pcaps = DDPCAPS_8BIT | DDPCAPS_ALLOW256; - } else if (format.ddpfPixelFormat.dwFlags & DDPF_PALETTEINDEXED4) { - bQuant = TRUE; - psize = 16; - pcaps = DDPCAPS_4BIT; - } - memcpy(&ddsd, &format, sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT; - ddsd.ddsCaps.dwCaps = DDSCAPS_TEXTURE | memoryflag; - ddsd.dwHeight = dwHeight; - ddsd.dwWidth = dwWidth; - - ddrval = lpDD->lpVtbl->CreateSurface(lpDD, &ddsd, &lpDDS, NULL); - if (ddrval != DD_OK) { - D3DAppISetErrorString("CreateSurface for texture failed (loadtex).\n%s", - D3DAppErrorToString(ddrval)); - return NULL; - } - /* - * Lock the surface so it can be filled with the PPM file - */ - memset(&ddsd, 0, sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof(DDSURFACEDESC); - ddrval = lpDDS->lpVtbl->Lock(lpDDS, NULL, &ddsd, 0, NULL); - if (ddrval != DD_OK) { - lpDDS->lpVtbl->Release(lpDDS); - D3DAppISetErrorString("Lock failed while loading surface (loadtex).\n%s", - D3DAppErrorToString(ddrval)); - return NULL; - } - /* - * The method of loading depends on the pixel format of the dest surface - */ - if (!bQuant) { - /* - * The texture surface is not palettized - */ - unsigned long* lpLP; - unsigned short* lpSP; - unsigned char* lpCP; - unsigned long m; - int s; - int red_shift, red_scale; - int green_shift, green_scale; - int blue_shift, blue_scale; - /* - * Determine the red, green and blue masks' shift and scale. - */ - for (s = 0, m = format.ddpfPixelFormat.dwRBitMask; !(m & 1); - s++, m >>= 1); - red_shift = s; - red_scale = 255 / (format.ddpfPixelFormat.dwRBitMask >> s); - for (s = 0, m = format.ddpfPixelFormat.dwGBitMask; !(m & 1); - s++, m >>= 1); - green_shift = s; - green_scale = 255 / (format.ddpfPixelFormat.dwGBitMask >> s); - for (s = 0, m = format.ddpfPixelFormat.dwBBitMask; !(m & 1); - s++, m >>= 1); - blue_shift = s; - blue_scale = 255 / (format.ddpfPixelFormat.dwBBitMask >> s); - /* - * Each RGB bit count requires different pointers - */ - switch (format.ddpfPixelFormat.dwRGBBitCount) { - case 32 : - for (j = 0; j < (int)dwHeight; j++) { - /* - * Point to next row in texture surface - */ - lpLP = (unsigned long*)(((char*)ddsd.lpSurface) + - ddsd.lPitch * j); - for (i = 0; i < (int)dwWidth; i++) { - int r, g, b; - /* - * Read each value, scale it and shift it into position - */ - r = getc(fp) / red_scale; - g = getc(fp) / green_scale; - b = getc(fp) / blue_scale; - *lpLP = (r << red_shift) | (g << green_shift) | - (b << blue_shift); - lpLP++; - } - } - break; - case 16 : - for (j = 0; j < (int)dwHeight; j++) { - lpSP = (unsigned short*)(((char*)ddsd.lpSurface) + - ddsd.lPitch * j); - for (i = 0; i < (int)dwWidth; i++) { - int r, g, b; - r = getc(fp) / red_scale; - g = getc(fp) / green_scale; - b = getc(fp) / blue_scale; - *lpSP = (r << red_shift) | (g << green_shift) | - (b << blue_shift); - lpSP++; - } - } - break; - case 8: - for (j = 0; j < (int)dwHeight; j++) { - lpCP = (unsigned char*)(((char*)ddsd.lpSurface) + - ddsd.lPitch * j); - for (i = 0; i < (int)dwWidth; i++) { - int r, g, b; - r = getc(fp) / red_scale; - g = getc(fp) / green_scale; - b = getc(fp) / blue_scale; - *lpCP = (r << red_shift) | (g << green_shift) | - (b << blue_shift); - lpCP++; - } - } - break; - default: - /* - * This wasn't a format I recognize - */ - lpDDS->lpVtbl->Unlock(lpDDS, NULL); - fclose(fp); - lpDDS->lpVtbl->Release(lpDDS); - D3DAppISetErrorString("Unknown pixel format (loadtex)."); - return NULL; - } - /* - * Unlock the texture and return the surface pointer - */ - lpDDS->lpVtbl->Unlock(lpDDS, NULL); - fclose(fp); - return (lpDDS); - } - - /* - * We assume the 8-bit palettized case - */ - color_count = 0; /* number of colors in the texture */ - for (j = 0; j < (int)dwHeight; j++) { - /* - * Point to next row in surface - */ - lpC = ((char*)ddsd.lpSurface) + ddsd.lPitch * j; - for (i = 0; i < (int)dwWidth; i++) { - int r, g, b, k; - /* - * Get the next red, green and blue values and turn them into a - * D3DCOLOR - */ - r = getc(fp); - g = getc(fp); - b = getc(fp); - c = RGB_MAKE(r, g, b); - /* - * Search for this color in a table of colors in this texture - */ - for (k = 0; k < color_count; k++) - if (c == colors[k]) break; - if (k == color_count) { - /* - * This is a new color, so add it to the list - */ - color_count++; - /* - * More than 256 and we fail (8-bit) - */ - if (color_count > psize) { - color_count--; - k = color_count - 1; - //goto burst_colors; - } - colors[k] = c; - } - /* - * Set the "pixel" value on the surface to be the index into the - * color table - */ - if (psize == 16) { - if ((i & 1) == 0) - *lpC = k & 0xf; - else { - *lpC |= (k & 0xf) << 4; - lpC++; - } - } else { - *lpC = (char)k; - lpC++; - } - } - } - /* - * Close the file and unlock the surface - */ - fclose(fp); - lpDDS->lpVtbl->Unlock(lpDDS, NULL); - -//burst_colors: - if (color_count > psize) { - /* - * If there are more than 256 colors, we overran our palette - */ - lpDDS->lpVtbl->Unlock(lpDDS, NULL); - lpDDS->lpVtbl->Release(lpDDS); - D3DAppISetErrorString("Palette burst. (loadtex).\n"); - return (NULL); - } - - /* - * Create a palette with the colors in our color table - */ - memset(ppe, 0, sizeof(PALETTEENTRY) * 256); - for (i = 0; i < color_count; i++) { - ppe[i].peRed = (unsigned char)RGB_GETRED(colors[i]); - ppe[i].peGreen = (unsigned char)RGB_GETGREEN(colors[i]); - ppe[i].peBlue = (unsigned char)RGB_GETBLUE(colors[i]); - } - /* - * Set all remaining entry flags to D3DPAL_RESERVED, which are ignored by - * the renderer. - */ - for (; i < 256; i++) - ppe[i].peFlags = D3DPAL_RESERVED; - /* - * Create the palette with the DDPCAPS_ALLOW256 flag because we want to - * have access to all entries. - */ - ddrval = lpDD->lpVtbl->CreatePalette(lpDD, - DDPCAPS_INITIALIZE | pcaps, - ppe, &lpDDPal, NULL); - if (ddrval != DD_OK) { - lpDDS->lpVtbl->Release(lpDDS); - D3DAppISetErrorString("Create palette failed while loading surface (loadtex).\n%s", - D3DAppErrorToString(ddrval)); - return (NULL); - } - /* - * Finally, bind the palette to the surface - */ - ddrval = lpDDS->lpVtbl->SetPalette(lpDDS, lpDDPal); - if (ddrval != DD_OK) { - lpDDS->lpVtbl->Release(lpDDS); - lpDDPal->lpVtbl->Release(lpDDPal); - D3DAppISetErrorString("SetPalette failed while loading surface (loadtex).\n%s", - D3DAppErrorToString(ddrval)); - return (NULL); - } - - lpDDPal->lpVtbl->Release(lpDDPal); - - return lpDDS; -} diff --git a/3dc/win95/db.c b/3dc/win95/db.c deleted file mode 100644 index 90fd200..0000000 --- a/3dc/win95/db.c +++ /dev/null @@ -1,1039 +0,0 @@ -#ifndef NDEBUG - -/* ******************************************************************** * - * * - * DB.C - Debugging functions. * - * * - * By: Garry Lancaster Version: 2.0 * - * * - * ******************************************************************** */ - -/* N O T E S ********************************************************** */ - -/* A lot of these functions should be called via macros defined in db.h */ - -/* If you don't want to link this file with Windows OS files set the - * define DB_NOWINDOWS. This will also stop linking with the Direct Draw - * stuff, which is, after all, a part of Windows. If you want Windows - * stuff, but NOT Direct Draw, define DB_NODIRECTDRAW. - */ - -/* ******************************************************************** * - * * - * I N T E R F A C E - both internal and external. * - * * - * ******************************************************************** */ - -/* I N C L U D E S **************************************************** */ - -/* Windows includes. Actually internal, but here to allow pre-compilation. */ -#include "advwin32.h" -#ifndef DB_NOWINDOWS - #include <windows.h> - #include "advwin32.h" -#endif -#ifndef DB_NODIRECTDRAW - #include <ddraw.h> -#endif -#include "db.h" /* Contains most off the interface. */ - -/* G L O B A L S ****************************************************** */ -/* Have external linkage. */ -volatile BOOL DZ_NULL; - -/* This variable dictates whether macros ending _opt get executed. */ -int db_option = 0; /* Default is off. */ - -/* ******************************************************************** * - * * - * I N T E R N A L * - * * - * ******************************************************************** */ - -/* I N C L U D E S **************************************************** */ - -/* Defining DB_NOWINDOWS implies DB_NODIRECTDRAW should also be defined. */ -#ifdef DB_NOWINDOWS - #ifndef DB_NODIRECTDRAW - #define DB_NODIRECTDRAW - #endif -#endif - -/* ANSI includes. */ -#include <stdio.h> -#include <stdlib.h> -#include <ctype.h> -#include <conio.h> -#include <direct.h> /* For getcwd() */ -#include <stdarg.h> /* For variable arguments. */ - -/* C O N S T A N T S ************************************************** */ - -/* Possible return value for MessageBox() */ -#define NO_MEMORY 0 - -/* Possible value for the width field of a font_struct. */ -#define PROP_WIDTH 0 - -/* Logfile name */ -#define LOGFILE_NAME "LOGFILE.TXT" - -/* Set this to 1 if the logfile name is an absolute path. Otherwise the - * logfile will go in the directory that is current when db_log_init() - * is called. - */ -#define ABSOLUTE_PATH 0 - -/* M A C R O S ******************************************************** */ - -/* Causes a division by zero exception. */ -#define DB_FORCE_EXCEPTION() ( db_vol_zero = 1 / db_vol_zero ) - -/* Cause a brakepoint. */ -#define DB_FORCE_BRAKEPOINT() do {__asm int 3} while(0) - -/* T Y P E S ********************************************************** */ - - -typedef struct font_struct *fontPtr; - -struct font_struct { - void *dummy1; - unsigned short dummy2, dummy3; - void *dummy4; - char filename[16]; - unsigned short width, height; - unsigned short ascent, avgwidth; - unsigned char byte_width; - unsigned char filler1; - short filler2; - char facename[28]; - unsigned short *prop_width_dataP; - unsigned char *bitmapP; -}; - -union PtrPackTag -{ - unsigned char *cP; - unsigned short *wP; - unsigned long *lP; -}; - -/* G L O B A L ******************************************************** */ -/* Should all be static. */ -static BOOL db_use_brakepoints = FALSE; - -/* Name of file to output log messages to. */ -static char LogFileNameP[255]; - -/* Have we initialized the log file? */ -static int InitialisedLog = 0; - -/* Type of display mode we are in. */ -static int db_display_type = DB_DOS; - -/* For DirectDraw mode. */ -static struct db_dd_mode_tag dd_mode = {NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0}; -static fontPtr FontP = NULL; - -/* Volatile zero. */ -static volatile int db_vol_zero = 0; - -/* Text strings for output. */ -static const char* db_assert_textA[ 3 ] = -{ - "ASSERTION FAILED!", - "Expression: %s", - "File: %s Line: %d" -}; -static const char* db_prompt_std = - "Quit program/force e(x)ception? [y/n/x]"; -static const char* db_prompt_windows = - "Quit program? [Yes/No]/force exception? [Cancel]"; -static const char* db_assert_log_begin_text = - "DB: FAILED ASSERTION BEGINS"; -static const char* db_assert_log_end_text = - "DB: FAILED ASSERTION ENDS"; -static const char* db_msg_log_begin_text = - "DB: MSG BEGINS"; -static const char* db_msg_log_end_text = - "DB: MSG ENDS"; - -#ifdef DB_NOWINDOWS -static char db_log_file_name[261] = LOGFILE_NAME; -#else -static char db_log_file_name[MAX_PATH+1] = LOGFILE_NAME; -#endif - - -/* P R O T O S ******************************************************** */ -/* Should all be static. */ - -static void db_do_std_prompt(unsigned yOffset); - -#ifndef DB_NOWINDOWS -static void db_do_win_prompt(const char* titleStrP, const char* bodyStrP); -#endif /* ifndef DB_NOWINDOWS */ - -#ifndef DB_NODIRECTDRAW - -/* Load debugging font, return NULL if we fail. */ -static fontPtr guiload_font(char *new_fname); - -/* Cleanup function for the above. */ -static fontPtr CleanupFontLoadFail(HANDLE fH, fontPtr fontP); - -/* Outputs debugging text. */ -static void out_text(LPDIRECTDRAWSURFACE surfP, int xc, int yc, - const char *text, short x_limit, fontPtr fP); - -/* Debounce all the keys the Direct Draw stuff uses. */ -static void Debounce(void); - -/* Wait for any outstanding flip operations to be completed, provided - * that the user specified DB_FLIP in the bltOrFlip field of the - * db_dd_mode_tag function. If they specified DB_BLIT this function returns - * immediately. - */ -static void DbWaitForHw(void); - -/* Flips between the draw and visible surfaces. */ -static void DbFlip(void); - -/* Blits the contents of the draw surface to the visible surface. */ -static void DbBlt(void); - -#endif /* ifndef DB_NODIRECTDRAW */ - -/* F U N C T I O N S ************************************************** */ - -/* ******************************************************************** * - * * - * I N T E R F A C E - both internal and external. * - * * - * ******************************************************************** */ - -/* NEW FNS for formatted debug strings. */ -void __cdecl db_logf_fired(const char *fmtStrP, ...) -{ - char msg[ 1024 ]; - va_list varArgList; - - va_start( varArgList, fmtStrP ); - vsprintf( msg, fmtStrP, varArgList ); - va_end( varArgList ); - - db_log_fired( msg ); -} - -void __cdecl db_printf_fired(int x, int y, const char *fmtStrP, ...) -{ - char msg[ 256 ]; - va_list varArgList; - - va_start( varArgList, fmtStrP ); - vsprintf( msg, fmtStrP, varArgList ); - va_end( varArgList ); - - db_print_fired( x, y, msg ); -} - -void __cdecl db_msgf_fired(const char *fmtStrP, ...) -{ - char msg[ 256 ]; - va_list varArgList; - - va_start( varArgList, fmtStrP ); - vsprintf( msg, fmtStrP, varArgList ); - va_end( varArgList ); - - db_msg_fired( (const char *) msg ); -} - -/* Called whenever an assertion fails. */ -void db_assert_fail(const char *exprP, const char *fileP, int line) -{ - db_log_fired( db_assert_log_begin_text ); - db_log_fired( db_assert_textA[ 0 ] ); - db_logf_fired( db_assert_textA[ 1 ], exprP ); - db_logf_fired( db_assert_textA[ 2 ], fileP, line ); - db_log_fired( db_assert_log_end_text ); - - switch(db_display_type) - { - case DB_DOS: - printf( db_assert_textA[ 0 ] ); - printf("\n"); - printf( db_assert_textA[ 1 ], exprP ); - printf("\n"); - printf( db_assert_textA[ 2 ], fileP, line ); - printf("\n"); - db_do_std_prompt( 0 ); - break; -#ifndef DB_NODIRECTDRAW - case DB_DIRECTDRAW: - { - char msg[256]; - unsigned short xLimit = (unsigned short) dd_mode.width; - - /* Wait for any hardware to finish flipping. */ - DbWaitForHw(); - - out_text((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP, - 0, 0, db_assert_textA[ 0 ], xLimit, FontP); - wsprintf(msg, db_assert_textA[ 1 ], exprP); - out_text((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP, - 0, 16, msg, xLimit, FontP); - wsprintf(msg, db_assert_textA[ 2 ], fileP, line); - out_text((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP, - 0, 32, msg, xLimit, FontP); - db_do_std_prompt( 48 ); - } - break; -#endif -#ifndef DB_NOWINDOWS - case DB_WINDOWS: - { - char fmtMsg[ 256 ]; - char msg[256]; - - strcpy( fmtMsg, db_assert_textA[ 1 ] ); - strcat( fmtMsg, db_assert_textA[ 2 ] ); - strcat( fmtMsg, db_prompt_windows ); - sprintf(msg, fmtMsg, exprP, fileP, line); - - db_do_win_prompt( db_assert_textA[ 0 ], msg ); - } - break; -#endif - default: - break; - } -} - -/* Displays a message and has the program pause until the user responds - * to it. - */ -void db_msg_fired(const char *strP) -{ - db_log_fired( db_msg_log_begin_text ); - db_log_fired( strP ); - db_log_fired( db_msg_log_end_text ); - - switch(db_display_type) - { - case DB_DOS: - printf("%s\n", strP); - db_do_std_prompt( 0 ); - break; -#ifndef DB_NOWINDOWS - case DB_WINDOWS: - db_do_win_prompt( "Debugging Message", strP ); - break; -#endif -#ifndef DB_NODIRECTDRAW - case DB_DIRECTDRAW: - { - unsigned short xLimit = (unsigned short) dd_mode.width; - - /* Wait for any flip hardware to be ready. */ - DbWaitForHw(); - - out_text((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP, - 0, 0, strP, xLimit, FontP); - db_do_std_prompt( 16 ); - } - break; -#endif - default: - break; - } -} - -/* Displays a message and continues program execution immediately. */ -void db_print_fired(int x, int y, const char *strP) -{ - switch(db_display_type) - { - case DB_DOS: - printf("%s\n", strP); - break; -#ifndef DB_NOWINDOWS - case DB_WINDOWS: - break; -#endif -#ifndef DB_NODIRECTDRAW - case DB_DIRECTDRAW: - { - unsigned short xLimit = (unsigned short) (dd_mode.width - x); - out_text((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP, x, y, - strP, xLimit, FontP); - break; - } -#endif - default: - break; - } -} - -/* Writes a message to a log file. */ -/* At least files can be output in the same way under DOS, Windows and - * Direct Draw! - */ -void db_log_fired(const char *strP) -{ - /* Have we intialised the file? */ - if(!InitialisedLog) db_log_init(); - { - /* Open a file for appending, creating one if it doesn't yet exist. */ - FILE *fP = fopen(LogFileNameP, "a+"); - - if(!fP) return; - - fprintf(fP, "%s\n", strP); - fclose(fP); - } -} - -void db_log_init(void) -{ - #if ABSOLUTE_PATH - sprintf( LogFileNameP, "%s", db_log_file_name ); - #else - /* Append the log file name to the current working directory. */ - sprintf( LogFileNameP, "%s\\%s", getcwd( LogFileNameP, 240 ), - db_log_file_name ); - #endif - - /* Delete old log file. */ - remove(LogFileNameP); - - /* Flag that we have initialised the log file. */ - InitialisedLog = 1; -} - -extern void db_set_log_file_ex(const char *strP) -{ - InitialisedLog = 0; - - strcpy(db_log_file_name, strP); -} - -void db_set_mode_ex(int mode, void *modeInfoP, void *newFontP) -{ - db_display_type = mode; -#ifndef DB_NODIRECTDRAW - if(dd_mode.visibleSurfaceP) - { - IDirectDrawSurface_Release((LPDIRECTDRAWSURFACE) dd_mode.visibleSurfaceP); - dd_mode.visibleSurfaceP = NULL; - } - - if(dd_mode.drawSurfaceP) - { - IDirectDrawSurface_Release((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP); - dd_mode.drawSurfaceP = NULL; - } - - if(mode == DB_DIRECTDRAW) - { - dd_mode = *((struct db_dd_mode_tag *) modeInfoP); - - if(dd_mode.visibleSurfaceP) - { - IDirectDrawSurface_AddRef((LPDIRECTDRAWSURFACE) dd_mode.visibleSurfaceP); - } - - if(dd_mode.drawSurfaceP) - { - IDirectDrawSurface_AddRef((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP); - } - - if(!FontP) - { - if(!newFontP) - FontP = guiload_font("DIALOG.FNT"); - else - FontP = (fontPtr) newFontP; - } - if(!FontP) - { - db_log_fired("DB ERROR: Font load failed. Exiting..."); - exit(0); - } - } -#endif -} - -/* Called to set whether exceptions or brakepoints are called. */ -void DbUseBrakepoints(BOOL use_brakepoints) -{ - db_use_brakepoints = use_brakepoints; -} - -int db_get_mode(void** modeInfoPP, void **FontPP) -{ - // blank return areas - *FontPP = NULL; - *modeInfoPP = NULL; - -#ifndef DB_NODIRECTDRAW - if(db_display_type == DB_DIRECTDRAW) - { - // copy font data - *FontPP = (void *) FontP; - - // copy surface data - *modeInfoPP = (void *) &dd_mode; - } -#endif - return db_display_type; -} - -void db_uninit(void) -{ - #ifndef DB_NODIRECTDRAW - if(FontP) - { - if(FontP->bitmapP) - { - GlobalFree(FontP->bitmapP); - } - if(FontP->prop_width_dataP) - { - GlobalFree(FontP->prop_width_dataP); - } - - GlobalFree(FontP); - FontP = NULL; - } - - if(dd_mode.visibleSurfaceP) - { - IDirectDrawSurface_Release((LPDIRECTDRAWSURFACE) dd_mode.visibleSurfaceP); - } - - if(dd_mode.drawSurfaceP) - { - IDirectDrawSurface_Release((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP); - } - - #endif -} - -/* ******************************************************************** * - * * - * I N T E R N A L * - * * - * ******************************************************************** */ - -static void db_do_std_prompt(unsigned yOffset) -{ - int ch = 0; - - switch(db_display_type) - { - case DB_DOS: - printf( db_prompt_std ); - printf("\n"); - do - { - ch = toupper(getch()); - } - while((ch != 'N') && (ch != 'Y') && (ch != 'X')); - break; -#ifndef DB_NODIRECTDRAW - case DB_DIRECTDRAW: - { - SHORT response; - BOOL done = FALSE; - unsigned short xLimit = (unsigned short) dd_mode.width; - - out_text((LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP, - 0, yOffset, db_prompt_std, xLimit, FontP); - - /* Show the message. */ - if(dd_mode.bltOrFlip == DB_FLIP) - { - DbFlip(); - } - else - { - DbBlt(); - } - - /* Wait for a valid key press. */ - do - { - response = GetAsyncKeyState('Y'); - if(response & 0x8000) - { - ch = 'Y'; - done = TRUE; - } - response = GetAsyncKeyState('N'); - if(response & 0x8000) - { - ch = 'N'; - done = TRUE; - } - response = GetAsyncKeyState('X'); - if(response & 0x8000) - { - ch = 'X'; - done = TRUE; - } - } - while(!done); - - Debounce(); - - /* Return the flip surfaces to their pre-message state. */ - if(dd_mode.bltOrFlip == DB_FLIP) - { - DbFlip(); - } - break; - } -#endif /* ifndef DB_NODIRECTDRAW */ - }/* switch(db_display_type) */ - - if(ch == 'Y') - { - exit(-10); - } - else if(ch == 'X') - { - if(db_use_brakepoints) - { - DB_FORCE_BRAKEPOINT(); - } - else - { - DB_FORCE_EXCEPTION(); - } - } - -}/* db_do_std_prompt() */ - -#ifndef DB_NOWINDOWS -static void db_do_win_prompt(const char* titleStrP, const char* bodyStrP) -{ - int response; - - response = MessageBox - ( - NULL, /* Dialog has no KNOWN parent window. */ - bodyStrP, /* Message to go in box. */ - titleStrP, /* Box title. */ - MB_YESNOCANCEL| /* Put up a 'Yes' and a 'No' button. */ - MB_SETFOREGROUND| /* Shove message box to front of display. */ - MB_ICONEXCLAMATION| /* Use an exclamation mark to decorate box. */ - MB_TASKMODAL /* Suspend current task until box is closed. */ - ); - - if((response == IDYES) || (response == NO_MEMORY)) - { - exit( -10 ); - } - else if(response == IDCANCEL) - { - if(db_use_brakepoints) - { - DB_FORCE_BRAKEPOINT(); - } - else - { - DB_FORCE_EXCEPTION(); - } - } -}/* db_do_win_prompt() */ -#endif /* ifndef DB_NOWINDOWS */ - -#ifndef DB_NODIRECTDRAW - -static fontPtr guiload_font(char *new_fname) -{ - HANDLE *fH; - BOOL status; - unsigned short c, byte, y; - union PtrPackTag dest; - unsigned char inByte; - fontPtr fntSP; - DWORD bytesRead; - - /* Open file for reading */ - fH = CreateFile(new_fname, GENERIC_READ, 0, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if(!fH) - { - db_log_fired("DB ERROR: Couldn't open font file."); - return CleanupFontLoadFail(NULL, NULL); - } - - - /* Allocate memory for our font structure */ - fntSP = (fontPtr) - GlobalAlloc(GMEM_FIXED, sizeof(struct font_struct)); - if(!fntSP) - { - db_log_fired("DB ERROR: Not enough memory for font structure."); - return CleanupFontLoadFail(fH, NULL); - } - - /* Nullify pointers inside the font structure. */ - fntSP->bitmapP = NULL; - fntSP->prop_width_dataP = NULL; - - /* Load up font structure */ - status = ReadFile(fH, fntSP, sizeof(struct font_struct), &bytesRead, - NULL); - if((!status) || (bytesRead != sizeof(struct font_struct))) - { - db_log_fired("DB ERROR: Error reading structure from font file."); - return CleanupFontLoadFail(fH, fntSP); - } - - /* Allocate memory for font bitmap */ - fntSP->bitmapP = (unsigned char *) GlobalAlloc(GMEM_FIXED, - fntSP->byte_width * dd_mode.bitsPerPixel * fntSP->height * 128); - if(!fntSP->bitmapP) - { - db_log_fired("DB ERROR: Not enough memory for font bitmap."); - return CleanupFontLoadFail(fH, fntSP); - } - - /* Work out proportional text widths for this font - * (if the font is proportional). - */ - if(fntSP->width == PROP_WIDTH) - { - /* Allocate memory for proportional width data */ - fntSP->prop_width_dataP = (unsigned short *) - GlobalAlloc(GMEM_FIXED, 256); - if(!fntSP->prop_width_dataP) - { - db_log_fired("DB ERROR: Not enough memory for proportional " - "font data"); - return CleanupFontLoadFail(fH, fntSP); - } - - /* Read proportional width data */ - status = ReadFile(fH, fntSP->prop_width_dataP, 256, &bytesRead, - NULL); - if((!status) || (bytesRead != 256)) - { - db_log_fired("DB ERROR: Error reading proportional font data " - "from file."); - return CleanupFontLoadFail(fH, fntSP); - } - - /* Round width of font to nearest long word. */ - { - int i; - unsigned short *propP = fntSP->prop_width_dataP; - - if(dd_mode.bitsPerPixel == 8) - { - for(i = 0; i < 128; i ++) - { - /* Round up to 4 pixels. */ - *propP = (unsigned short) ((*propP + 3U) & (~3U)); - } - propP++; - } - else - { - for(i = 0; i < 128; i ++) - { - /* Round up to 2 pixels. */ - *propP = (unsigned short) ((*propP + 1U) & (~1U)); - } - propP++; - } - } - } - else - { - /* Round width to nearest long word. */ - if(dd_mode.bitsPerPixel == 8) - { - /* Round up to 4 pixels. */ - fntSP->width = (unsigned char) ((fntSP->width + 2) & (~3)); - } - else - { - /* Round up to 2 pixels. */ - fntSP->width = (unsigned char) ((fntSP->width + 1) & (~1)); - } - } - - /* Load up bitmap data */ - dest.cP = fntSP->bitmapP; - for(c = 0; c < 128; c ++) - { - for(y = 0; y < fntSP->height; y ++) - { - for(byte = 0; byte < fntSP->byte_width; byte ++) - { - unsigned char bitMask = 0x80; - - /* Read a byte of data */ - status = ReadFile(fH, &inByte, 1, &bytesRead, NULL); - if((!status) || (bytesRead != 1)) - { - db_log_fired("DB ERROR: Error reading font bitmap from " - "file."); - return CleanupFontLoadFail(fH, fntSP); - } - - /* Translate 1 bit per pixel data into current Direct Draw - * screen mode bit depth. - */ - if(dd_mode.bitsPerPixel == 8) - { - do - { - if(inByte & bitMask) *(dest.cP) = - (unsigned char) dd_mode.foreCol; - else *(dest.cP) = (unsigned char) dd_mode.backCol; - dest.cP++; - - /* Shift bitMask 1 bit to the right */ - bitMask >>= 1; - } - while(bitMask); - } - else - { - do - { - if(inByte & bitMask) *(dest.wP) = dd_mode.foreCol; - else *(dest.wP) = dd_mode.backCol; - dest.wP++; - - /* Shift bitMask 1 bit to the right */ - bitMask >>= 1; - } - while(bitMask); - } - } - } - } - - /* Close the font file */ - CloseHandle(fH); - - return fntSP; -} - -static fontPtr CleanupFontLoadFail(HANDLE fH, fontPtr fontP) -{ - /* Close file if necessary */ - if(fH) CloseHandle(fH); - - /* Is the font struct allocated? */ - if(fontP) - { - /* Yes. Is the bitmap allocated? If so, free it. */ - if(fontP->bitmapP) GlobalFree(fontP->bitmapP); - - /* Is the proportional width data allocated. If so, free it. */ - if(fontP->prop_width_dataP) GlobalFree(fontP->prop_width_dataP); - - /* Free the font structure. */ - GlobalFree(fontP); - } - - return NULL; -} - -static void out_text(LPDIRECTDRAWSURFACE surfP, int xc, int yc, - const char *text, short x_limit, fontPtr fP) -{ - register unsigned long *srcP, *destP; - register unsigned int x, y; - unsigned long heightTimesPitch, charOffset; - unsigned int prop_width; - int srcIncr, longsPerLine; - unsigned int bitShift; - DDSURFACEDESC surfaceDesc; - - /* Lock the surface. */ - { - HRESULT res; - - surfaceDesc.dwSize = sizeof surfaceDesc; - res = IDirectDrawSurface_Lock(surfP, NULL, &surfaceDesc, - DDLOCK_WAIT, NULL); - if(res != DD_OK) - { - db_log3("Couldn't lock surface."); - return; - } - } - - /* Round xc to nearest long word. */ - if(dd_mode.bitsPerPixel == 8) - { - xc = (xc + 2) & (~3); - bitShift = 2; - } - else - { - xc = (xc + 1) & (~1); - bitShift = 1; - } - - /* Point to DRAM buffer co-ordinate where the top left of the - * first character should be written. - */ - destP = (unsigned long *) surfaceDesc.lpSurface + - ((yc * surfaceDesc.lPitch) >> 2) + (xc >> bitShift); - heightTimesPitch = (fP->height * surfaceDesc.lPitch) >> 2; - longsPerLine = (fP->byte_width * dd_mode.bitsPerPixel) >> 2; - charOffset = longsPerLine * fP->height; - - /* Write our text string */ - while(*text != '\0') - { - /* Blit a single character */ - /* Point srcP to first byte of the bitmap for the current - * character. - */ - srcP = ((unsigned long *) fP->bitmapP) + (*text) * charOffset; - - /* Get width of this character (in pixels). */ - if(fP->width == PROP_WIDTH) - prop_width = *(fP->prop_width_dataP + (*text)); - else prop_width = fP->width; - - /* Check we will not exceed our original x_limit if we blit - * this character. If we will, we should stop writing. - */ - x_limit = (short) (x_limit - prop_width); - if(x_limit < 0) break; - - /* Convert prop_width from pixels to longs. */ - prop_width >>= bitShift; - - srcIncr = longsPerLine - prop_width; - - y = fP->height; - do - { - x = prop_width; - do - { - /* Move 1 long word. */ - *destP++ = *srcP++; - } - while(--x != 0); - - /* Point to start of next horizontal line of character square - * in DRAM buffer. - */ - destP += (surfaceDesc.lPitch >> 2) - prop_width; - srcP += srcIncr; - } - while(--y != 0); - - /* Point to start of next character position in DRAM buffer */ - destP -= heightTimesPitch - prop_width; - - /* Advance one character in text string */ - text++; - } - - /* Unlock surface. */ - { - HRESULT res; - - res = IDirectDrawSurface_Unlock(surfP, - (LPVOID) surfaceDesc.lpSurface); - if(res != DD_OK) db_log_fired("Couldn't unlock surface."); - } - return; -} - -static void Debounce(void) -{ - BOOL bouncing; - - /* Debounce all the keys we use - that is Y, N, and RETURN. */ - do - { - bouncing = FALSE; - if(GetAsyncKeyState('Y') & 0x8000) bouncing = TRUE; - if(GetAsyncKeyState('N') & 0x8000) bouncing = TRUE; - if(GetAsyncKeyState('X') & 0x8000) bouncing = TRUE; - if(GetAsyncKeyState(VK_RETURN) & 0x8000) bouncing = TRUE; - } - while(bouncing); -} - -static void DbWaitForHw(void) -{ - /* Wait until the last flip is finished and the last blt done */ - BOOL finished; - - /* Stay in this loop until the hardware is free. */ - do - { - finished = TRUE; - - /* Make sure all flips are done. */ - if(dd_mode.bltOrFlip == DB_FLIP) - { - if(IDirectDrawSurface_GetFlipStatus( - (LPDIRECTDRAWSURFACE) dd_mode.visibleSurfaceP, - DDGFS_ISFLIPDONE) != DD_OK) - finished = FALSE; - } - } - while(!finished); -} - -static void DbFlip(void) -{ - LPDIRECTDRAWSURFACE fromSurfP = - (LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP; - LPDIRECTDRAWSURFACE toSurfP = - (LPDIRECTDRAWSURFACE) dd_mode.visibleSurfaceP; - HRESULT res; - - /* Try to flip the screen. */ - res = IDirectDrawSurface_Flip(toSurfP, fromSurfP, DDFLIP_WAIT); - - if(res != DD_OK) - db_log_fired("Internal debug flip failed - message lost!"); -} - -static void DbBlt(void) -{ - LPDIRECTDRAWSURFACE fromSurfP = - (LPDIRECTDRAWSURFACE) dd_mode.drawSurfaceP; - LPDIRECTDRAWSURFACE toSurfP = - (LPDIRECTDRAWSURFACE) dd_mode.visibleSurfaceP; - HRESULT res; - RECT toRect; - - /* Initialise to Rect. */ - toRect.left = dd_mode.bltXOffset; - toRect.top = dd_mode.bltYOffset; - toRect.right = toRect.left + dd_mode.width; - toRect.bottom = toRect.top + dd_mode.height; - - /* Try to blit from the draw to the visible surface. */ - res = IDirectDrawSurface_Blt(toSurfP, &toRect, fromSurfP, NULL, - DDBLT_WAIT, NULL); - - if(res != DD_OK) - db_log_fired("Internal debug blit failed - message lost."); -} - -#endif - -#else - ; -#endif /* ! NDEBUG */ diff --git a/3dc/win95/fail.c b/3dc/win95/fail.c deleted file mode 100644 index 013f1ec..0000000 --- a/3dc/win95/fail.c +++ /dev/null @@ -1,37 +0,0 @@ -/* LotU: Error handling functions. - - Copyright (C) 1995, Jamie Lokier. - Written for Rebellion Developments, Ltd. - - Permission to use, copy, modify and distribute this file for any - purpose by Rebellion Developments, Ltd. is hereby granted. If you - want to use this file outside the company, please let me know. -*/ - -#include "3dc.h" -#include "fail.h" -#include "dxlog.h" - -void -fail (const char * format, ...) -{ - va_list ap; - - LOGDXSTR(format); - va_start (ap, format); - if (format != 0) - vfprintf (stderr, format, ap); - va_end (ap); - - exit (EXIT_FAILURE); -} - -void FAILHandleCompilerWarningMessage(void) -{ - int temp; - - temp = D3DRMMAP_PERSPCORRECT; - temp = D3DRMMAP_WRAPU; - temp = D3DRMMAP_WRAPV; - temp = D3DRMGROUP_ALLGROUPS; -}
\ No newline at end of file diff --git a/3dc/win95/fail.h b/3dc/win95/fail.h deleted file mode 100644 index 8838103..0000000 --- a/3dc/win95/fail.h +++ /dev/null @@ -1,44 +0,0 @@ -/* LotU: Error handling functions. - - Copyright (C) 1995, Jamie Lokier. - Written for Rebellion Developments, Ltd. - - Permission to use, copy, modify and distribute this file for any - purpose by Rebellion Developments, Ltd. is hereby granted. If you - want to use this file outside the company, please let me know. -*/ - -#ifndef __fail_h -#define __fail_h 1 - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef _MSC_VER -#define VARARG_DECL __cdecl -#else -#define VARARG_DECL -#endif - -#ifdef __GNUC__ - -#if __GNUC__ >= 2 && __GNUC_MINOR__ >= 5 -extern void -VARARG_DECL fail (const char * __format, ...) - __attribute__ ((noreturn, format (printf, 1, 2))); -#else -extern __volatile__ void VARARG_DECL fail (const char * __format, ...); -#endif - -#else - -extern void VARARG_DECL fail (const char * __format, ...); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __fail_h */ diff --git a/3dc/win95/fragchnk.cpp b/3dc/win95/fragchnk.cpp deleted file mode 100644 index dc998d7..0000000 --- a/3dc/win95/fragchnk.cpp +++ /dev/null @@ -1,255 +0,0 @@ -#include "fragchnk.hpp" - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(fragchnk) - -RIF_IMPLEMENT_DYNCREATE("FRAGTYPE",Fragment_Type_Chunk) - -CHUNK_WITH_CHILDREN_LOADER("FRAGTYPE",Fragment_Type_Chunk) - -/* -Children for Fragment_Type_Chunk : - -Fragment_Type_Data_Chunk "FRGTYPDC" -Fragment_Type_Shape_Chunk "FRGTYPSC" -Fragment_Type_Sound_Chunk "FRGSOUND" -*/ - - -const char* Fragment_Type_Chunk::get_name() -{ - Fragment_Type_Data_Chunk* ftdc=(Fragment_Type_Data_Chunk*)lookup_single_child("FRGTYPDC"); - - if(ftdc) - return ftdc->frag_type_name; - else - return 0; - -} - -//////////////////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("FRGTYPDC",Fragment_Type_Data_Chunk) - -Fragment_Type_Data_Chunk::Fragment_Type_Data_Chunk(Chunk_With_Children* parent,const char* name) -:Chunk(parent,"FRGTYPDC") -{ - frag_type_name=new char[strlen(name)+1]; - strcpy(frag_type_name,name); - pad1=pad2=pad3=0; -} - -Fragment_Type_Data_Chunk::Fragment_Type_Data_Chunk(Chunk_With_Children* const parent,const char* data,size_t const ) -:Chunk(parent,"FRGTYPDC") -{ - int length=strlen(data)+1; - frag_type_name=new char[length]; - strcpy(frag_type_name,data); - data+=(length+3)&~3; - - pad1=*(int*)data; - data+=4; - pad2=*(int*)data; - data+=4; - pad3=*(int*)data; - data+=4; -} - -Fragment_Type_Data_Chunk::~Fragment_Type_Data_Chunk() -{ - if(frag_type_name) delete frag_type_name; -} - -void Fragment_Type_Data_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - strcpy(data_start,frag_type_name); - data_start+=(strlen(frag_type_name)+4)&~3; - - *(int*)data_start=pad1; - data_start+=4; - *(int*)data_start=pad2; - data_start+=4; - *(int*)data_start=pad3; - data_start+=4; - -} - -size_t Fragment_Type_Data_Chunk::size_chunk() -{ - chunk_size=12+12; - chunk_size+=(strlen(frag_type_name)+4)&~3; - return chunk_size; -} - - -//////////////////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("FRGTYPSC",Fragment_Type_Shape_Chunk) - -Fragment_Type_Shape_Chunk::Fragment_Type_Shape_Chunk(Chunk_With_Children* parent,const char* _name,int number,ChunkVectorInt _location) -:Chunk(parent,"FRGTYPSC") -{ - name=new char[strlen(_name)+1]; - strcpy(name,_name); - num_fragments=number; - location=_location; - pad1=pad2=pad3=0; -} - -#if UseOldChunkLoader -Fragment_Type_Shape_Chunk::Fragment_Type_Shape_Chunk(Chunk_With_Children* const parent,const char* data,size_t const ) -:Chunk(parent,"FRGTYPSC") -{ - int length=strlen(data)+1; - name=new char[length]; - strcpy(name,data); - data+=(length+3)&~3; - - num_fragments=*(int*)data; - data+=4; - - location=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - - - pad1=*(int*)data; - data+=4; - pad2=*(int*)data; - data+=4; - pad3=*(int*)data; - data+=4; -}; -#else -Fragment_Type_Shape_Chunk::Fragment_Type_Shape_Chunk(Chunk_With_Children* const parent,const char* data,size_t const ) -:Chunk(parent,"FRGTYPSC") -{ - int length=strlen(data)+1; - name=new char[length]; - strcpy(name,data); - data+=(length+3)&~3; - - num_fragments=*(int*)data; - data+=4; - - location=*(ChunkVectorInt*)data; - data+=sizeof(ChunkVectorInt); - - - pad1=*(int*)data; - data+=4; - pad2=*(int*)data; - data+=4; - pad3=*(int*)data; - data+=4; -} -#endif - -Fragment_Type_Shape_Chunk::~Fragment_Type_Shape_Chunk() -{ - if(name) delete name; -} - -void Fragment_Type_Shape_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - strcpy(data_start,name); - data_start+=(strlen(name)+4)&~3; - - *(int*)data_start=num_fragments; - data_start+=4; - - *(ChunkVectorInt*)data_start=location; - data_start+=sizeof(ChunkVectorInt); - - *(int*)data_start=pad1; - data_start+=4; - *(int*)data_start=pad2; - data_start+=4; - *(int*)data_start=pad3; - data_start+=4; - -} - -size_t Fragment_Type_Shape_Chunk::size_chunk() -{ - chunk_size=12+16+sizeof(ChunkVectorInt); - chunk_size+=(strlen(name)+4)&~3; - return chunk_size; -} - -//////////////////////////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("FRGSOUND",Fragment_Type_Sound_Chunk) - -Fragment_Type_Sound_Chunk::Fragment_Type_Sound_Chunk(Chunk_With_Children* parent) -:Chunk(parent,"FRGSOUND") -{ - wav_name=0; - inner_range=5000; - outer_range=40000; - max_volume=127; - pitch=0; - pad=0; -} - -Fragment_Type_Sound_Chunk::Fragment_Type_Sound_Chunk(Chunk_With_Children* const parent,const char* data,size_t const ) -:Chunk(parent,"FRGSOUND") -{ - inner_range=*(unsigned long*)data; - data+=4; - outer_range=*(unsigned long*)data; - data+=4; - - max_volume=*(int*)data; - data+=4; - pitch=*(int*)data; - data+=4; - pad=*(int*)data; - data+=4; - - wav_name=new char[strlen(data)+1]; - strcpy(wav_name,data); - -} - -Fragment_Type_Sound_Chunk::~Fragment_Type_Sound_Chunk() -{ - if(wav_name) delete wav_name; -} - -void Fragment_Type_Sound_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(unsigned long*)data_start=inner_range; - data_start+=4; - *(unsigned long*)data_start=outer_range; - data_start+=4; - - *(int*)data_start=max_volume; - data_start+=4; - *(int*)data_start=pitch; - data_start+=4; - *(int*)data_start=pad; - data_start+=4; - - strcpy(data_start,wav_name); - -} - -size_t Fragment_Type_Sound_Chunk::size_chunk() -{ - chunk_size=12+20; - chunk_size+=(strlen(wav_name)+4)&~3; - return chunk_size; -} - diff --git a/3dc/win95/fragchnk.hpp b/3dc/win95/fragchnk.hpp deleted file mode 100644 index 4fc806e..0000000 --- a/3dc/win95/fragchnk.hpp +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef _fragchnk_hpp_ -#define _fragchnk_hpp_ - -#include "chunk.hpp" -#include "chnktype.hpp" - - -class Fragment_Type_Data_Chunk : public Chunk -{ -public : - - Fragment_Type_Data_Chunk(Chunk_With_Children* parent,const char* name); - Fragment_Type_Data_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - ~Fragment_Type_Data_Chunk(); - - size_t size_chunk (); - void fill_data_block (char * data_start); - - - char* frag_type_name; - int pad1,pad2,pad3; - -}; - -class Fragment_Type_Shape_Chunk : public Chunk -{ -public: - - Fragment_Type_Shape_Chunk(Chunk_With_Children* parent,const char* _name,int number,ChunkVectorInt _location); - Fragment_Type_Shape_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - ~Fragment_Type_Shape_Chunk(); - - size_t size_chunk (); - void fill_data_block (char * data_start); - - - int num_fragments; - ChunkVectorInt location; - char* name; - - int pad1,pad2,pad3; - -}; -class Fragment_Type_Sound_Chunk : public Chunk -{ -public: - - Fragment_Type_Sound_Chunk(Chunk_With_Children* parent); - Fragment_Type_Sound_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - ~Fragment_Type_Sound_Chunk(); - - size_t size_chunk (); - void fill_data_block (char * data_start); - - char* wav_name; - unsigned long inner_range; - unsigned long outer_range; - int max_volume; - int pitch; - int pad; - -}; - -class Fragment_Type_Chunk : public Chunk_With_Children -{ -public : - Fragment_Type_Chunk(Chunk_With_Children * parent,const char* name) - : Chunk_With_Children (parent, "FRAGTYPE") - {new Fragment_Type_Data_Chunk(this,name);} - - Fragment_Type_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - - const char* get_name(); - -}; - - - - - - -#endif
\ No newline at end of file diff --git a/3dc/win95/hierchnk.cpp b/3dc/win95/hierchnk.cpp deleted file mode 100644 index 5b26379..0000000 --- a/3dc/win95/hierchnk.cpp +++ /dev/null @@ -1,609 +0,0 @@ -#include "hierchnk.hpp" -#include "obchunk.hpp" -//#include "animobs.hpp" - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(hierchnk) - -/////////////Object_Hierarchy_Chunk//////////////////// -RIF_IMPLEMENT_DYNCREATE("OBJCHIER",Object_Hierarchy_Chunk) - -//loader for Object_Hierarchy_Chunk -CHUNK_WITH_CHILDREN_LOADER("OBJCHIER",Object_Hierarchy_Chunk) - -/* -children for Object_Hierarchy_Chunk: - -"OBJCHIER" Object_Hierarchy_Chunk) -"OBJHIERD" Object_Hierarchy_Data_Chunk) -"OBHIERNM" Object_Hierarchy_Name_Chunk) -"HIERBBOX" Hierarchy_Bounding_Box_Chunk) -"OBANSEQS" Object_Animation_Sequences_Chunk) -"OBANALLS" Object_Animation_All_Sequence_Chunk) - -*/ - -List <Object_Hierarchy_Chunk *> Object_Hierarchy_Chunk::list_h_children() -{ - List <Chunk *> cl; - lookup_child ("OBJCHIER",cl); - List <Object_Hierarchy_Chunk *> h_l; - - for (LIF<Chunk *> cli(&cl); !cli.done(); cli.next()) - { - h_l.add_entry((Object_Hierarchy_Chunk *)cli()); - } - return(h_l); - -} - -Object_Hierarchy_Data_Chunk * Object_Hierarchy_Chunk::get_data () -{ - return((Object_Hierarchy_Data_Chunk *)lookup_single_child ("OBJHIERD")); - -} - -Object_Hierarchy_Name_Chunk * Object_Hierarchy_Chunk::get_name () -{ - return((Object_Hierarchy_Name_Chunk *)lookup_single_child ("OBHIERNM")); -} -////////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("OBJHIERD",Object_Hierarchy_Data_Chunk) - -Object_Hierarchy_Data_Chunk::Object_Hierarchy_Data_Chunk (Object_Hierarchy_Chunk * parent, const char * obname) -: Chunk (parent, "OBJHIERD"), ob_name (0), object(0) -{ - num_extra_data=0; - extra_data=0; - - if (obname) - { - ob_name = new char [strlen(obname)+1]; - strcpy (ob_name, obname); - - Chunk_With_Children * root = GetRootChunk(); - - List<Chunk *> oblist; - root->lookup_child ("RBOBJECT",oblist); - - for (LIF<Chunk *> oli(&oblist); !oli.done(); oli.next()) - { - Object_Chunk * ob = (Object_Chunk *)oli(); - - if (!strcmp (ob->object_data.o_name, ob_name)) - { - *((Object_Chunk **)&object) = ob; - break; - } - } - } - -} - -Object_Hierarchy_Data_Chunk::~Object_Hierarchy_Data_Chunk() -{ - if (ob_name) - delete [] ob_name; - - if(extra_data) - delete extra_data; -} - - -size_t Object_Hierarchy_Data_Chunk::size_chunk () -{ - if (ob_name) - { - chunk_size = 12 + 4+4*num_extra_data + strlen(ob_name) + 4 - strlen(ob_name)%4; - } - else - { - chunk_size = 12 + 4+4*num_extra_data + 4; - } - return chunk_size; -} - - -void Object_Hierarchy_Data_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*) data_start=num_extra_data; - data_start+=4; - - for (int i=0; i<num_extra_data; i++) - { - *((int *) data_start) = extra_data[i]; - data_start += 4; - } - - if (ob_name) - { - sprintf (data_start, "%s", ob_name); - } - else - { - *data_start = 0; - } - -} - -#if UseOldChunkLoader -Object_Hierarchy_Data_Chunk::Object_Hierarchy_Data_Chunk (Object_Hierarchy_Chunk * parent, const char * data_start, size_t /*ssize*/) -: Chunk (parent, "OBJHIERD"), object(0), ob_name (0) -{ - - num_extra_data=0; - extra_data=0; - - data_start+=40; - - if (strlen(data_start)) - { - ob_name = new char [strlen(data_start) + 1]; - strcpy (ob_name, data_start); - } -} -#else -Object_Hierarchy_Data_Chunk::Object_Hierarchy_Data_Chunk (Chunk_With_Children * parent, const char * data_start, size_t /*ssize*/) -: Chunk (parent, "OBJHIERD"), object(0), ob_name (0) -{ - num_extra_data=*(int*)data_start; - data_start+=4; - - if(num_extra_data) - extra_data=new int[num_extra_data]; - else - extra_data=0; - - - for (int i=0; i<num_extra_data; i++) - { - extra_data[i] = *((int *) data_start); - data_start += 4; - } - - if (strlen(data_start)) - { - ob_name = new char [strlen(data_start) + 1]; - strcpy (ob_name, data_start); - } -} -#endif - -void Object_Hierarchy_Data_Chunk::post_input_processing () -{ - find_object_for_this_section(); -} - -void Object_Hierarchy_Data_Chunk::find_object_for_this_section () -{ - *((Object_Chunk **)&object) = NULL; - - Chunk_With_Children * root = GetRootChunk(); - - List<Chunk *> oblist; - root->lookup_child ("RBOBJECT",oblist); - - for (LIF<Chunk *> oli(&oblist); !oli.done(); oli.next()) - { - Object_Chunk * ob = (Object_Chunk *)oli(); - - if (!strcmp (ob->object_data.o_name, ob_name)) - { - *((Object_Chunk **)&object) = ob; - break; - } - } -} -////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("OBHIERNM",Object_Hierarchy_Name_Chunk) - -Object_Hierarchy_Name_Chunk::Object_Hierarchy_Name_Chunk (Object_Hierarchy_Chunk * parent, const char * hname) -: Chunk (parent, "OBHIERNM") -{ - if (hname) - { - hierarchy_name = new char [strlen(hname)+1]; - strcpy (hierarchy_name, hname); - } - else - { - hierarchy_name = new char [1]; - *hierarchy_name = 0; - } -} - -Object_Hierarchy_Name_Chunk::~Object_Hierarchy_Name_Chunk() -{ - if (hierarchy_name) - { - delete [] hierarchy_name; - } -} - -void Object_Hierarchy_Name_Chunk::fill_data_block (char *data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - strcpy (data_start, hierarchy_name); - -} - -Object_Hierarchy_Name_Chunk::Object_Hierarchy_Name_Chunk (Chunk_With_Children * parent, const char * data, size_t /*ssize*/) -: Chunk (parent, "OBHIERNM") -{ - hierarchy_name = new char [strlen(data)+1]; - strcpy (hierarchy_name, data); -} - - -/////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("OBHALTSH",Object_Hierarchy_Alternate_Shape_Set_Chunk) - -Object_Hierarchy_Alternate_Shape_Set_Chunk::Object_Hierarchy_Alternate_Shape_Set_Chunk(Chunk_With_Children* parent,int num,const char* name) -:Chunk(parent,"OBHALTSH") -{ - Shape_Set_Name=new char[strlen(name)+1]; - Shape_Set_Num=num; - strcpy(Shape_Set_Name,name); - flags=0; - spare[0]=spare[1]=spare[2]=0; -} -Object_Hierarchy_Alternate_Shape_Set_Chunk::Object_Hierarchy_Alternate_Shape_Set_Chunk(Chunk_With_Children* parent,const char* name) -:Chunk(parent,"OBHALTSH") -{ - Shape_Set_Name=new char[strlen(name)+1]; - strcpy(Shape_Set_Name,name); - flags=0; - spare[0]=spare[1]=spare[2]=0; - Shape_Set_Num=-1; - - //find next available shape set number - List<Chunk*> chlist; - parent->lookup_child("OBHALTSH",chlist); - int num=0; - for(LIF<Chunk*> chlif(&chlist);!chlif.done();) - { - Object_Hierarchy_Alternate_Shape_Set_Chunk* ohassc=(Object_Hierarchy_Alternate_Shape_Set_Chunk*) chlif(); - if(ohassc->Shape_Set_Num==num) - { - num++; - chlif.restart(); - } - else - { - chlif.next(); - } - } - - Shape_Set_Num=num; - -} - -Object_Hierarchy_Alternate_Shape_Set_Chunk::Object_Hierarchy_Alternate_Shape_Set_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"OBHALTSH") -{ - - Shape_Set_Num=*(int*)data; - data+=4; - - int name_length=strlen(data)+1; - Shape_Set_Name=new char[name_length]; - strcpy(Shape_Set_Name,data); - data+=(name_length+3)&~3; - - int num_shapes=*(int*)data; - data+=4; - - for(int i=0;i<num_shapes;i++) - { - Replaced_Shape_Details* rsd=new Replaced_Shape_Details; - - name_length=strlen(data)+1; - rsd->old_object_name=new char[name_length]; - strcpy(rsd->old_object_name,data); - data+=(name_length+3)&~3; - - name_length=strlen(data)+1; - rsd->new_object_name=new char[name_length]; - strcpy(rsd->new_object_name,data); - data+=(name_length+3)&~3; - - Replaced_Shape_List.add_entry(rsd); - } - - flags=*(int*)data; - data+=4; - - for(i=0;i<3;i++) - { - spare[i]=*(int*)data; - data+=4; - } - -} - -Object_Hierarchy_Alternate_Shape_Set_Chunk::~Object_Hierarchy_Alternate_Shape_Set_Chunk() -{ - if(Shape_Set_Name) delete Shape_Set_Name; - - while(Replaced_Shape_List.size()) - { - delete Replaced_Shape_List.first_entry(); - Replaced_Shape_List.delete_first_entry(); - } - -} - -void Object_Hierarchy_Alternate_Shape_Set_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=Shape_Set_Num; - data_start+=4; - - strcpy(data_start,Shape_Set_Name); - data_start+=(strlen(Shape_Set_Name)+4)&~3; - - *(int*)data_start=Replaced_Shape_List.size(); - data_start+=4; - - for(LIF<Replaced_Shape_Details*> rlif(&Replaced_Shape_List);!rlif.done();rlif.next()) - { - strcpy(data_start,rlif()->old_object_name); - data_start+=(strlen(rlif()->old_object_name)+4)&~3; - - strcpy(data_start,rlif()->new_object_name); - data_start+=(strlen(rlif()->new_object_name)+4)&~3; - } - - *(int*)data_start=flags; - data_start+=4; - - for(int i=0;i<3;i++) - { - *(int*)data_start=spare[i]; - data_start+=4; - } - -} - -size_t Object_Hierarchy_Alternate_Shape_Set_Chunk::size_chunk() -{ - chunk_size=36; - chunk_size+=(strlen(Shape_Set_Name)+4)&~3; - for(LIF<Replaced_Shape_Details*> rlif(&Replaced_Shape_List);!rlif.done();rlif.next()) - { - chunk_size+=(strlen(rlif()->old_object_name)+4)&~3; - chunk_size+=(strlen(rlif()->new_object_name)+4)&~3; - } - return chunk_size; - -} - - -/////////////////////////////////////////////////// -RIF_IMPLEMENT_DYNCREATE("HSETCOLL",Hierarchy_Shape_Set_Collection_Chunk) - -Hierarchy_Shape_Set_Collection_Chunk::Hierarchy_Shape_Set_Collection_Chunk(Chunk_With_Children* parent,int num,const char* name) -:Chunk(parent,"HSETCOLL") -{ - Set_Collection_Name=new char[strlen(name)+1]; - Set_Collection_Num=num; - strcpy(Set_Collection_Name,name); - TypeIndex=flags=0; -} - - -Hierarchy_Shape_Set_Collection_Chunk::Hierarchy_Shape_Set_Collection_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"HSETCOLL") -{ - - Set_Collection_Num=*(int*)data; - data+=4; - - int name_length=strlen(data)+1; - Set_Collection_Name=new char[name_length]; - strcpy(Set_Collection_Name,data); - data+=(name_length+3)&~3; - - int list_length=*(int*)data; - data+=4; - - for(int i=0;i<list_length;i++) - { - Index_List.add_entry(*(int*)data); - data+=4; - } - - TypeIndex=*(int*)data; - data+=4; - flags=*(int*)data; - data+=4; -} - -Hierarchy_Shape_Set_Collection_Chunk::~Hierarchy_Shape_Set_Collection_Chunk() -{ - if(Set_Collection_Name) delete Set_Collection_Name; -} - -void Hierarchy_Shape_Set_Collection_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=Set_Collection_Num; - data_start+=4; - - strcpy(data_start,Set_Collection_Name); - data_start+=(strlen(Set_Collection_Name)+4)&~3; - - *(int*)data_start=Index_List.size(); - data_start+=4; - - for(LIF<int> slif(&Index_List);!slif.done();slif.next()) - { - *(int*)data_start=slif(); - data_start+=4; - } - - *(int*)data_start=TypeIndex; - data_start+=4; - *(int*)data_start=flags; - data_start+=4; - -} - -size_t Hierarchy_Shape_Set_Collection_Chunk::size_chunk() -{ - chunk_size=12+16; - chunk_size+=(strlen(Set_Collection_Name)+4)&~3; - chunk_size+=Index_List.size()*4; - return chunk_size; - -} - -/////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("HIDEGDIS",Hierarchy_Degradation_Distance_Chunk) - -Hierarchy_Degradation_Distance_Chunk::Hierarchy_Degradation_Distance_Chunk(Chunk_With_Children* parent,int _num_detail_levels) -:Chunk(parent,"HIDEGDIS") -{ - num_detail_levels=_num_detail_levels; - if(num_detail_levels) - { - distance_array=new int[num_detail_levels]; - } - else - { - distance_array=0; - } - //fill in some arbitrary distance values - for(int i=0;i<num_detail_levels;i++) - { - distance_array[i]=i*10000; - } - -} - -Hierarchy_Degradation_Distance_Chunk::Hierarchy_Degradation_Distance_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"HIDEGDIS") -{ - num_detail_levels=*(int*)data; - data+=sizeof(int); - - if(num_detail_levels) - { - distance_array=new int[num_detail_levels]; - } - else - { - distance_array=0; - } - - for(int i=0;i<num_detail_levels;i++) - { - distance_array[i]=*(int*)data; - data+=sizeof(int); - } - -} - -Hierarchy_Degradation_Distance_Chunk::~Hierarchy_Degradation_Distance_Chunk() -{ - if(distance_array)delete distance_array; -} - -void Hierarchy_Degradation_Distance_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - - data_start += 8; - - *((int *) data_start) = chunk_size; - - data_start += 4; - - *(int*)data_start=num_detail_levels; - data_start+=4; - - for(int i=0;i<num_detail_levels;i++) - { - *(int*)data_start=distance_array[i]; - data_start+=4; - } -} - -size_t Hierarchy_Degradation_Distance_Chunk::size_chunk() -{ - chunk_size=16+num_detail_levels*4; - return chunk_size; - -} - - -/////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("HIERBBOX",Hierarchy_Bounding_Box_Chunk) - -#if UseOldChunkLoader -Hierarchy_Bounding_Box_Chunk::Hierarchy_Bounding_Box_Chunk(Chunk_With_Children* parent,const char* data,size_t datasize) -:Chunk(parent,"HIERBBOX") -{ - assert(datasize==2*sizeof(ChunkVector)); - - - min=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - max=*(ChunkVector*)data; -} -#else -Hierarchy_Bounding_Box_Chunk::Hierarchy_Bounding_Box_Chunk(Chunk_With_Children* parent,const char* data,size_t datasize) -:Chunk(parent,"HIERBBOX") -{ - assert(datasize==2*sizeof(ChunkVectorInt)); - - min=*(ChunkVectorInt*)data; - data+=sizeof(ChunkVectorInt); - max=*(ChunkVectorInt*)data; -} -#endif -void Hierarchy_Bounding_Box_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(ChunkVectorInt*)data_start=min; - data_start+=sizeof(ChunkVectorInt); - *(ChunkVectorInt*)data_start=max; -} -/////////////////////////////////////////////////// diff --git a/3dc/win95/hierchnk.hpp b/3dc/win95/hierchnk.hpp deleted file mode 100644 index 3e2881b..0000000 --- a/3dc/win95/hierchnk.hpp +++ /dev/null @@ -1,203 +0,0 @@ -#ifndef _hierchnk_hpp -#define _hierchnk_hpp 1 - -#include "chunk.hpp" -#include "list_tem.hpp" -#include "chnktype.hpp" - -class Object_Chunk; -class Object_Hierarchy_Data_Chunk; -class Object_Hierarchy_Name_Chunk; - -class Shape_Chunk; - -#ifdef MAXEXPORT - class INode; -#endif - - -class Object_Hierarchy_Chunk : public Chunk_With_Children -{ -public: - - Object_Hierarchy_Chunk(Chunk_With_Children * parent) - : Chunk_With_Children (parent, "OBJCHIER") - {} - // constructor from buffer - Object_Hierarchy_Chunk (Chunk_With_Children * const parent,const char *, size_t const); - - List <Object_Hierarchy_Chunk *> list_h_children(); - - Object_Hierarchy_Data_Chunk * get_data (); - Object_Hierarchy_Name_Chunk * get_name (); - - -#ifdef MAXEXPORT - INode* node; -#endif - - -}; - -class Object_Hierarchy_Data_Chunk : public Chunk -{ -public: - - Object_Hierarchy_Data_Chunk (Object_Hierarchy_Chunk * parent, const char * obname); - Object_Hierarchy_Data_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/); - - ~Object_Hierarchy_Data_Chunk (); - - int num_extra_data; - int* extra_data; - - Object_Chunk * const object; - - virtual size_t size_chunk (); - - virtual void fill_data_block (char * data_start); - - virtual void post_input_processing(); - - void find_object_for_this_section(); //find the object_chunk from the name - - char * ob_name; - -private: - - friend class Object_Hierarchy_Chunk; - - -}; - - -// This chunk will normally go in the root as a way of identifiying the hierarchy -class Object_Hierarchy_Name_Chunk : public Chunk -{ -public: - - Object_Hierarchy_Name_Chunk (Object_Hierarchy_Chunk * parent, const char * hname); - Object_Hierarchy_Name_Chunk (Chunk_With_Children * parent, const char * sdata, size_t /*ssize*/); - ~Object_Hierarchy_Name_Chunk(); - - char * hierarchy_name; - - virtual size_t size_chunk () - { - return(chunk_size = 12 + strlen (hierarchy_name) + 4 - strlen (hierarchy_name)%4); - } - - virtual void fill_data_block (char * data_start); - -private: - - friend class Object_Hierarchy_Chunk; - - -}; - - -struct Replaced_Shape_Details -{ - ~Replaced_Shape_Details() - { - if(old_object_name) delete old_object_name; - if(new_object_name) delete new_object_name; - } - - //object name of shape to be replaced - char* old_object_name; - //object that replaces it. - char* new_object_name; -}; - - -#define Avp_ShapeSet_Flag_Female 0x00000001 - -#define List_Object_Hierarchy_Alternate_Shape_Set_Chunk(parent,list) (parent)->lookup_child("OBHALTSH",list) -class Object_Hierarchy_Alternate_Shape_Set_Chunk : public Chunk -{ -public : - Object_Hierarchy_Alternate_Shape_Set_Chunk(Chunk_With_Children* parent,int num,const char* name); - Object_Hierarchy_Alternate_Shape_Set_Chunk(Chunk_With_Children* parent,const char* name); - Object_Hierarchy_Alternate_Shape_Set_Chunk (Chunk_With_Children * parent, const char * data, size_t /*ssize*/); - ~Object_Hierarchy_Alternate_Shape_Set_Chunk(); - - virtual size_t size_chunk(); - - virtual void fill_data_block (char * data_start); - - char* Shape_Set_Name; - int Shape_Set_Num; - - List<Replaced_Shape_Details*> Replaced_Shape_List; - - int flags; - int spare[3]; - -private: - - -}; - - -#define AvP_HColl_Flag_NotRandom 0x00000001 - -#define List_Hierarchy_Shape_Set_Collection_Chunk(parent,list) (parent)->lookup_child("HSETCOLL",list) -//this chunk hold a list of indeces for shape_set_chunks that should be applied -class Hierarchy_Shape_Set_Collection_Chunk : public Chunk -{ -public : - Hierarchy_Shape_Set_Collection_Chunk(Chunk_With_Children* parent,int num,const char* name); - Hierarchy_Shape_Set_Collection_Chunk (Chunk_With_Children * parent, const char * data, size_t /*ssize*/); - ~Hierarchy_Shape_Set_Collection_Chunk(); - - virtual size_t size_chunk(); - - virtual void fill_data_block (char * data_start); - - char* Set_Collection_Name; - int Set_Collection_Num; - - List<int> Index_List; - - int TypeIndex; - int flags; -}; - -class Hierarchy_Degradation_Distance_Chunk : public Chunk -{ -public : - Hierarchy_Degradation_Distance_Chunk(Chunk_With_Children * parent, const char * data, size_t /*ssize*/); - Hierarchy_Degradation_Distance_Chunk(Chunk_With_Children* parent,int _num_detail_levels); - ~Hierarchy_Degradation_Distance_Chunk(); - - virtual size_t size_chunk(); - - virtual void fill_data_block (char * data_start); - - int num_detail_levels; - int* distance_array; - - -private: -}; - -class Hierarchy_Bounding_Box_Chunk :public Chunk -{ -public : - Hierarchy_Bounding_Box_Chunk(Chunk_With_Children * parent,const char*data,size_t datasize); - - Hierarchy_Bounding_Box_Chunk(Chunk_With_Children * parent) - :Chunk(parent,"HIERBBOX") - {} - - virtual void fill_data_block (char * data_start); - - virtual size_t size_chunk() - {return chunk_size=12+6*4;} - - ChunkVectorInt min; - ChunkVectorInt max; -}; -#endif
\ No newline at end of file diff --git a/3dc/win95/huffman.cpp b/3dc/win95/huffman.cpp deleted file mode 100644 index b2a0275..0000000 --- a/3dc/win95/huffman.cpp +++ /dev/null @@ -1,520 +0,0 @@ -#include "stdio.h" -#include "stdlib.h" -#include "string.h" -#include "malloc.h" -#include "huffman.hpp" - -/* KJL 17:12:25 17/09/98 - Huffman compression/decompression routines */ - -typedef struct -{ - int Symbol; - unsigned int Count; -} HuffItem; - -typedef struct HuffNode // 16-byte node structure -{ - union - { // the FIRST four bytes - struct HuffNode *zero; // points to the "zero" branch or... - unsigned int value; // holds the value of an end node - }; - - union - { // the SECOND four bytes - struct HuffNode *one; // points to the "one" branch or... - struct HuffNode *link; // points to next end node in list - }; - - struct HuffNode *parent; // the THIRD four bytes, parent node - - union - { // the FOURTH four bytes - unsigned int bits; // the bit pattern of this end node - struct - { - unsigned char flag; - unsigned char curdepth; - unsigned char maxdepth; - unsigned char unused; - }; - }; - -} HuffNode; - -typedef struct -{ - long wid; - long bits; - -} HuffEncode; - -static HuffItem SymbolCensus[257]; -static HuffNode TreeNodes[2*257]; -static int Depths[MAX_DEPTH+1]; -static HuffEncode EncodingTable[257]; - -#define AllocateMemory malloc - - -/* KJL 17:16:03 17/09/98 - Compression */ -static void PerformSymbolCensus(unsigned char *sourcePtr, int length); -#ifdef __WATCOMC__ -static int HuffItemsSortSub(const void *cmp1, const void *cmp2); -#else -static int __cdecl HuffItemsSortSub(const void *cmp1, const void *cmp2); -#endif -static void SortCensusData(void); -static void BuildHuffmanTree(void); -static void MakeHuffTreeFromHuffItems(HuffNode *base, HuffItem *source, int count); -static void MakeCodeLengthsFromHuffTree(int *dest, HuffNode *source, int maxdepth); -static int HuffDepthsAdjust(int *depth, int maxdepth); -static void MakeHuffmanEncodeTable(HuffEncode *encodetable, HuffItem *item, int *depths); -static int HuffEncodeBytes(int *dest, unsigned char *source, int count, HuffEncode *table); - - -extern HuffmanPackage *HuffmanCompression(unsigned char *sourcePtr, int length) -{ - HuffmanPackage *outpackage; - - - // Step 1: Perform the symbol census - PerformSymbolCensus(sourcePtr,length); - // Step 2: Sorting the census data - SortCensusData(); - // Step 3: Building the Huffman tree - BuildHuffmanTree(); - // Step 4: Making the code lengths table - MakeCodeLengthsFromHuffTree(Depths, TreeNodes, MAX_DEPTH); - // Step 5: Limiting code lengths - HuffDepthsAdjust(Depths, MAX_DEPTH); - // Step 6: Making the encoding table - MakeHuffmanEncodeTable(EncodingTable,&SymbolCensus[256],Depths); - // Step 7: Encoding data - outpackage = (HuffmanPackage*)AllocateMemory(sizeof(HuffmanPackage)+length); - strncpy(outpackage->Identifier,COMPRESSED_RIF_IDENTIFIER,8); - outpackage->CompressedDataSize = HuffEncodeBytes((int*)(outpackage+1), sourcePtr, length, EncodingTable); - outpackage->UncompressedDataSize = length; - for (int n = 0; n < MAX_DEPTH; n++) - { - outpackage->CodelengthCount[n] = Depths[n + 1]; - } - for (n = 0; n < 256; n++) - { - outpackage->ByteAssignment[n] = SymbolCensus[n + 1].Symbol; - } - return outpackage; -} - -static void PerformSymbolCensus(unsigned char *sourcePtr, int length) -{ - // init array - for (int i=0; i<257; i++) - { - SymbolCensus[i].Symbol = i; - SymbolCensus[i].Count = 0; - } - - // count 'em - do - { - SymbolCensus[*sourcePtr++].Count++; - } - while (--length); -} - -#ifdef __WATCOMC__ -static int HuffItemsSortSub(const void *cmp1, const void *cmp2) -#else -static int __cdecl HuffItemsSortSub(const void *cmp1, const void *cmp2) -#endif -{ - if (((HuffItem *)cmp1)->Count > ((HuffItem *)cmp2)->Count) - return 1; - if (((HuffItem *)cmp1)->Count < ((HuffItem *)cmp2)->Count) - return -1; - return 0; -} -static void SortCensusData(void) -{ - qsort(SymbolCensus, 257, sizeof(HuffItem), HuffItemsSortSub); -} - -static void BuildHuffmanTree(void) -{ - MakeHuffTreeFromHuffItems(TreeNodes,SymbolCensus,257); -} - -static void MakeHuffTreeFromHuffItems(HuffNode *base, HuffItem *source, int count) -{ - HuffNode *movdest, *temp; - int n, upperlim, lowerlim, index; - unsigned int sum; - - if (!count) return; - - movdest = base + 1; - temp = base + count; - memset(temp, 0, count * sizeof(HuffNode)); - for (n = 0; n < count; n++) - { - temp[n].bits = source[n].Count; - } - while (upperlim = --count) - { - if (temp[0].zero) - temp[0].zero->parent = temp[0].one->parent = movdest; - if (temp[1].zero) - temp[1].zero->parent = temp[1].one->parent = movdest + 1; - movdest[0] = *temp++; - movdest[1] = *temp; - sum = movdest[0].bits + movdest[1].bits; - lowerlim = 1; - - while (lowerlim != upperlim) - { - index = (lowerlim + upperlim) >> 1; - if (sum >= temp[index].bits) - { - lowerlim = index + 1; - } - else - { - upperlim = index; - } - } - index = lowerlim - 1; - memmove(temp, temp + 1, index * sizeof(HuffNode)); - temp[index].bits = sum; - temp[index].zero = movdest; - temp[index].one = movdest + 1; - movdest += 2; - } - base[0] = temp[0]; - if (base[0].zero) - base[0].zero->parent = base[0].one->parent = base; -} - -static void MakeCodeLengthsFromHuffTree(int *dest, HuffNode *source, int maxdepth) -{ - int n, depth; - HuffNode *back; - - for (n = 0; n < maxdepth + 1; n++) - dest[n] = 0; - depth = 0; - while (1) - { - while (source->one) - { - source = source->one; - depth++; - } - - if (depth > maxdepth) dest[maxdepth]++; - else dest[depth]++; - - do - { - back = source; - source = source->parent; - if (!depth--) - return; - } - while (back == source->zero); - - source = source->zero; - depth++; - } -} - -static int HuffDepthsAdjust(int *depth, int maxdepth) -{ - unsigned int n, m, items, sum, goal, gain, busts; - unsigned int promotions, excess, hi; - - goal = 1 << maxdepth; - for (n = 0, sum = 0, items = 0; n <= maxdepth; n++) - { - items += depth[n]; - sum += (goal >> n) * depth[n]; - } - if (items > goal) - return -1; // failure - for (n = maxdepth - 1; sum > goal; n--) - { - if (depth[n]) - { - gain = (1 << (maxdepth - n)) - 1; - busts = (sum - goal + gain - 1) / gain; - busts = depth[n] < busts ? depth[n] : busts; - depth[n] -= busts; - depth[maxdepth] += busts; - sum -= busts * gain; - } - } - excess = goal - sum; - for (n = 0; excess; n++) - { - hi = 1 << (maxdepth - n); - for (m = n + 1; m <= maxdepth; m++) - { - gain = hi - (1 << (maxdepth - m)); - if (excess < gain) - break; - if (depth[m]) - { - promotions = excess / gain; - promotions = depth[m] > promotions ? promotions : depth[m]; - depth[n] += promotions; - depth[m] -= promotions; - excess -= promotions * gain; - } - } - } - return 0; // success -} - -static void MakeHuffmanEncodeTable(HuffEncode *encodetable, HuffItem *item, int *depths) -{ - unsigned int d, bitwidth, depthbit, bt, cur; - int *dep; - - dep = depths + 1; // skip depth zero - bitwidth = 0; // start from small bitwidths - cur = 0; // current bit pattern - do - { - do - { - bitwidth++; // go deeper - depthbit = 1 << (bitwidth - 1); // keep depth marker - d = *dep++; // get count here - } - while (!d); // until count non-zero - while (d--) - { // for all on this level - encodetable[item->Symbol].wid = bitwidth; // record width - encodetable[item->Symbol].bits = cur; // record bits - item--; // count backwards an item - bt = depthbit; // bt is a temp value - while (1) - { - cur ^= bt; // do an add modulo 1 - if ((cur & bt) || !bt) // break if now a 1 - break; // or out of bits - bt >>= 1; // do next bit position - } - } - } - while (cur); // until cur exhausted -} - -static int HuffEncodeBytes(int *dest, unsigned char *source, int count, HuffEncode *table) -{ - int *start; - int wid, val, available; - unsigned int accum, bits; - unsigned char *sourcelim, *sourceend; - - if (!count) return 0; - - start = dest; - sourcelim = sourceend = source + count; - available = 32; - if (sourcelim - 32 < sourcelim) - { - sourcelim -= 32; - } - else - { - sourcelim = source; - } - if (source < sourcelim) - { - do - { - goto lpstart; - do - { - accum = (accum >> wid) | (bits << (32 - wid)); -lpstart: val = *source++; - wid = table[val].wid; - bits = table[val].bits; - } - while ((available -= wid) >= 0); - - wid += available; - if (wid) accum = (accum >> wid) | (bits << (32 - wid)); - *dest++ = accum; - wid -= available; - accum = bits << (32 - wid); - available += 32; - } - while (source < sourcelim); - } - while (1) - { - if (source < sourceend) - { - val = *source++; - } - else if (source == sourceend) - { - val = 0x100; // terminator - source++; - } - else break; // done - - wid = table[val].wid; - bits = table[val].bits; - - if ((available -= wid) < 0) - { - wid += available; - if (wid) - accum = (accum >> wid) | (bits << (32 - wid)); - *dest++ = accum; - wid -= available; - accum = bits << (32 - wid); - available += 32; - } - else - { - accum = (accum >> wid) | (bits << (32 - wid)); - } - } - *dest++ = accum >> available; - return (dest - start) * 4; -} - - - - - - -/* KJL 17:16:24 17/09/98 - Decompression */ -static int DecodeTable[1<<MAX_DEPTH]; - -static void MakeHuffmanDecodeTable(int *depth, int depthmax, unsigned char *list); -static int HuffmanDecode(unsigned char *dest, int *source, int *table, int length); - - -extern char *HuffmanDecompress(HuffmanPackage *inpackage) -{ - unsigned char *uncompressedData = NULL; - // Step 1: Make the decoding table - MakeHuffmanDecodeTable(inpackage->CodelengthCount, MAX_DEPTH, inpackage->ByteAssignment); - - // Step 2: Decode data - uncompressedData = (unsigned char*)AllocateMemory(inpackage->UncompressedDataSize+16); - if (uncompressedData) - { - HuffmanDecode(uncompressedData,(int*)(inpackage+1),DecodeTable,inpackage->UncompressedDataSize); - } - - return (char*)uncompressedData; -} - -static void MakeHuffmanDecodeTable(int *depth, int depthmax, unsigned char *list) -{ - int thisdepth, depthbit, repcount, repspace, lenbits, temp, count; - int *outp; - int o = 0; - unsigned char *p; - int *outtbl = DecodeTable; - - lenbits = 0; - repcount = 1 << depthmax; - repspace = 1; - thisdepth = 0; - depthbit = 4; - p = (unsigned char *)list + 255; - while (1) - { - do - { - lenbits++; - depthbit <<= 1; - repspace <<= 1; - repcount >>= 1; - } - while (!(thisdepth = *depth++)); - do - { - if (p < list) - { - temp = 0xff; - } - else - { - temp = lenbits | (*p-- << 8); - } - outp = outtbl + (o >> 2); - count = repcount; - do - { - *outp = temp; - outp += repspace; - } - while (--count); - temp = depthbit; - do - { - temp >>= 1; - if (temp & 3) return; - o ^= temp; - } - while (!(o & temp)); - } - while (--thisdepth); - } -} - - -#define EDXMASK ((((1 << (MAX_DEPTH + 1)) - 1) ^ 1) ^ -1) - -static int HuffmanDecode(unsigned char *dest, int *source, int *table, int length) -{ - unsigned char *start; - int available, reserve, fill, wid; - unsigned int bits=0, resbits; - unsigned char *p; - - start = dest; - available = 0; - reserve = 0; - wid = 0; - do - { - available += wid; - fill = 31 - available; - bits <<= fill; - if (fill > reserve) - { - fill -= reserve; - available += reserve; - if (reserve) - { - bits = (bits >> reserve) | (resbits << (32 - reserve)); - } - resbits = *source++; - reserve = 32; - } - bits = (bits >> fill) | (resbits << (32 - fill)); - resbits >>= fill; - reserve -= fill; - available = 31; - goto lpent; - do - { - bits >>= wid; - *dest++ = p[1]; -lpent: p = (unsigned char *)(((short *)table)+(bits & ~EDXMASK)); - } - while ((available -= (wid = *p)) >= 0 && (dest-start)!=length); - - } - while (available > -32 && (dest-start)!=length); - return dest - start; -} diff --git a/3dc/win95/huffman.hpp b/3dc/win95/huffman.hpp deleted file mode 100644 index 58faf2a..0000000 --- a/3dc/win95/huffman.hpp +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef _huffman_hpp_included -#define _huffman_hpp_included 1 - -#ifdef __cplusplus - extern "C" - { -#endif - -#define MAX_DEPTH 11 -typedef struct -{ - char Identifier[8]; - int CompressedDataSize; - int UncompressedDataSize; - int CodelengthCount[MAX_DEPTH]; - unsigned char ByteAssignment[256]; -} HuffmanPackage; - -/* KJL 17:16:03 17/09/98 - Compression */ -extern HuffmanPackage *HuffmanCompression(unsigned char *sourcePtr, int length); - -/* KJL 16:53:53 19/09/98 - Decompression */ -extern char *HuffmanDecompress(HuffmanPackage *inpackage); - - -#define COMPRESSED_RIF_IDENTIFIER "REBCRIF1" -#ifdef __cplusplus - }; -#endif - -#endif
\ No newline at end of file diff --git a/3dc/win95/iff.cpp b/3dc/win95/iff.cpp deleted file mode 100644 index fe455db..0000000 --- a/3dc/win95/iff.cpp +++ /dev/null @@ -1,826 +0,0 @@ -#include "advwin32.h" -#include "iff.hpp" - -#include <stdio.h> -#include <tchar.h> - -#if defined(_CPPRTTI) && !defined(NDEBUG) - #include <typeinfo> -#endif - -#ifndef NDEBUG - #define HT_FAIL(str) (::IFF::DisplayMessage(TEXT("IFF Internal Error"),TEXT(str)),exit(-45)) -#endif - -#include "hash_tem.hpp" - -namespace IFF -{ - /*****************************/ - /* Original File: iffObj.cpp */ - /*****************************/ - - #ifndef NDEBUG - - static bool g_bAllocListActive = false; - - class AllocList : public ::HashTable<Unknown *> - { - public: - AllocList() - { - g_bAllocListActive = true; - } - ~AllocList() - { - #ifdef _CPPRTTI // this works in MSVC 5.0 - ie. the macro is defined if RTTI is turned on - // but there appears to be no preprocessor way of determining if RTTI is turned on under Watcom - // No, I think it works in Watcom too, actually... - #pragma message("Run-Time Type Identification (RTTI) is enabled") - for (Iterator itLeak(*this) ; !itLeak.Done() ; itLeak.Next()) - { - TCHAR buf[256]; - ::wsprintf(buf,TEXT("Object not deallocated:\nType: %s\nRefCnt: %u"),typeid(*itLeak.Get()).name(),itLeak.Get()->m_nRefCnt); - DisplayMessage(TEXT("Memory Leak!"),buf); - } - #else // ! _CPPRTTI - unsigned nRefs(0); - for (Iterator itLeak(*this) ; !itLeak.Done() ; itLeak.Next()) - { - nRefs += itLeak.Get()->m_nRefCnt; - } - if (Size()) - { - char buf[256]; - ::sprintf(buf,"Objects not deallocated:\nNumber of Objects: %u\nNumber of References: %u",Size(),nRefs); - DisplayMessage("Memory Leaks!",buf); - } - #endif // ! _CPPRTTI - g_bAllocListActive = false; - } - }; - - static AllocList g_listAllocated; - - void DbRemember(Unknown * pObj) - { - g_listAllocated.AddAsserted(pObj); - } - - void DbForget(Unknown * pObj) - { - if (g_bAllocListActive) - g_listAllocated.RemoveAsserted(pObj); - } - - #endif // ! NDEBUG - - /******************************/ - /* Original File: iffFile.cpp */ - /******************************/ - - bool GenericFile::Load(::MediaMedium * pMedium) - { - ArchvIn ar; - - ar.Open(pMedium); - if (!ar.m_bError) - Serialize(&ar); - ar.Close(); - - return ! ar.m_bError; - } - - #ifndef IFF_READ_ONLY - bool GenericFile::Write(::MediaMedium * pMedium) - { - ArchvOut ar; - - ar.Open(pMedium); - if (!ar.m_bError) - Serialize(&ar); - ar.Close(); - - return ! ar.m_bError; - } - #endif // ! IFF_READ_ONLY - - - #ifdef _IFF_WIN_TARGET - typedef ::MediaWinFileMedium DeviceFileHandle; - #else - typedef ::MediaStdFileMedium DeviceFileHandle; - #endif - - bool GenericFile::Load(TCHAR const * pszFileName) - { - #ifndef IFF_READ_ONLY - if (m_pszFileName) delete[] m_pszFileName; - m_pszFileName = new TCHAR [_tcslen(pszFileName)+1]; - _tcscpy(m_pszFileName,pszFileName); - #endif // ! IFF_READ_ONLY - - #ifdef _IFF_WIN_TARGET - ::MediaWinFileMedium * pMedium = new ::MediaWinFileMedium; - pMedium->Open(pszFileName, GENERIC_READ); - #else - ::MediaStdFileMedium * pMedium = new ::MediaStdFileMedium; - pMedium->Open(pszFileName, "rb"); - #endif - - bool bRet = Load(pMedium); - - pMedium->Release(); - - return bRet; - } - - #ifndef IFF_READ_ONLY - bool GenericFile::Write(TCHAR const * pszFileName) - { - if (pszFileName) - { - if (m_pszFileName) delete[] m_pszFileName; - m_pszFileName = new TCHAR [_tcslen(pszFileName)+1]; - _tcscpy(m_pszFileName,pszFileName); - } - - if (!m_pszFileName) return false; - - #ifdef _IFF_WIN_TARGET - ::MediaWinFileMedium * pMedium = new ::MediaWinFileMedium; - pMedium->Open(pszFileName, GENERIC_WRITE); - #else - ::MediaStdFileMedium * pMedium = new ::MediaStdFileMedium; - pMedium->Open(pszFileName, "wb"); - #endif - - bool bRet = Write(pMedium); - - pMedium->Release(); - - return bRet; - } - #endif // ! IFF_READ_ONLY - - void File::Serialize(Archive * pArchv) - { - if (pArchv->m_bIsLoading) - { - if (m_pContents) - { - m_pContents->Release(); - m_pContents = NULL; - } - - pArchv->Transfer(m_idType); - - if (!!m_idType && (m_idType == ID("FORM") || m_idType == ID("LIST") || m_idType == ID("CAT "))) - { - m_pContents = static_cast<Composite *>(Chunk::Load(ID_ANY,pArchv,m_idType)); - } - else - { - pArchv->m_bError = true; - } - } - else - { - if (m_pContents) - m_pContents->Chunk::Write(pArchv); - else - pArchv->m_bError = true; - } - } - - File::~File() - { - if (m_pContents) - m_pContents->Release(); - } - - /*******************************/ - /* Original File: iffChunk.cpp */ - /*******************************/ - - class RegEntry - { - public: - ID m_idParent; - ID m_idChunk; - Chunk * (* m_pfnCreate) (); - inline bool operator == (RegEntry const & rEntry) const - { - return m_idParent == rEntry.m_idParent && m_idChunk == rEntry.m_idChunk; - } - inline bool operator != (RegEntry const & rEntry) const - { - return ! operator == (rEntry); - } - }; - -} // namespace IFF - -inline unsigned HashFunction(IFF::RegEntry const & rEntry) -{ - return HashFunction(rEntry.m_idChunk.m_nID); -} - -namespace IFF { - - static ::HashTable<RegEntry> * g_pRegister = NULL; - - void Chunk::Register(ID idParent, ID idChunk, Chunk * (* pfnCreate) () ) - { - static ::HashTable<RegEntry> reg; - - g_pRegister = ® - - RegEntry entry; - entry.m_idParent = idParent; - entry.m_idChunk = idChunk; - entry.m_pfnCreate = pfnCreate; - - reg.AddAsserted(entry); - } - - Chunk * Chunk::DynCreate(ID idParent, ID idChunk) - { - if (g_pRegister) - { - RegEntry test; - test.m_idParent = idParent; - test.m_idChunk = idChunk; - test.m_pfnCreate = NULL; - - RegEntry const * pEntry = g_pRegister->Contains(test); - if (pEntry) - { - return pEntry->m_pfnCreate(); - } - } - return new MiscChunk(idChunk); - } - - void Chunk::Write(Archive * pArchv) - { - Archive * pSubArchv = pArchv->OpenSubArchive(); - - Serialize(pSubArchv); - - UINT32 nSize = pSubArchv->GetSize(); - pArchv->Transfer(m_idCk); - pArchv->Transfer(nSize); - - pArchv->CloseSubArchive(pSubArchv); - - BYTE z = 0; - if (nSize & 1) pArchv->Transfer(z); - } - - Chunk * Chunk::Load(ID idParent, Archive * pArchv, ID idChunk, bool bKnown) - { - if (!idChunk) - pArchv->Transfer(idChunk); - - Chunk * pChunk = bKnown ? DynCreate(idParent, idChunk) : new MiscChunk(idChunk); - - UINT32 nSize; - pArchv->Transfer(nSize); - - Archive * pSubArchv = pArchv->OpenSubArchive(nSize); - pChunk->Serialize(pSubArchv); - pArchv->CloseSubArchive(pSubArchv); - - BYTE z = 0; - if (nSize & 1) pArchv->Transfer(z); - - return pChunk; - } - - Chunk * Chunk::GetProperty(ID idProp) const - { - if (m_pParent && m_pNode) - return m_pParent->GetProperty(m_pNode,idProp); - else - return NULL; - } - - /*******************************/ - /* Original File: iffBlock.cpp */ - /*******************************/ - - Composite::~Composite() - { - DeleteAllChildren(); - } - - ChildNode * Composite::GetFirstChild(ID idMatch) const - { - for (ChildNode * pSrchNode = m_pFirst; pSrchNode; pSrchNode = GetNextChild(pSrchNode)) - { - if (pSrchNode->GetChunk()->m_idCk == idMatch && !pSrchNode->GetChunk()->IsUnknown()) return pSrchNode; - } - return NULL; - } - - ChildNode * Composite::GetLastChild(ID idMatch) const - { - for (ChildNode * pSrchNode = m_pLast; pSrchNode; pSrchNode = GetPrevChild(pSrchNode)) - { - if (pSrchNode->GetChunk()->m_idCk == idMatch && !pSrchNode->GetChunk()->IsUnknown()) return pSrchNode; - } - return NULL; - } - - ChildNode * Composite::GetNextChild(ChildNode const * pNode, ID idMatch) - { - for (ChildNode * pSrchNode = GetNextChild(pNode); pSrchNode; pSrchNode = GetNextChild(pSrchNode)) - { - if (pSrchNode->GetChunk()->m_idCk == idMatch && !pSrchNode->GetChunk()->IsUnknown()) return pSrchNode; - } - return NULL; - } - - ChildNode * Composite::GetPrevChild(ChildNode const * pNode, ID idMatch) - { - for (ChildNode * pSrchNode = GetPrevChild(pNode); pSrchNode; pSrchNode = GetPrevChild(pSrchNode)) - { - if (pSrchNode->GetChunk()->m_idCk == idMatch && !pSrchNode->GetChunk()->IsUnknown()) return pSrchNode; - } - return NULL; - } - - Chunk * Composite::GetProperty(ChildNode const * pNode, ID idProp) const - { - // search backward for ID - - ChildNode * pFindNode = GetPrevChild(pNode, idProp); - - if (pFindNode) return pFindNode->GetChunk(); - - // if not found, search parent backwards, for "PROP ...." then get that - // and if not in the parent, search its parent similarly - // provided all these parents are of type LIST .... - - for (Composite const * pThis = this; pThis->m_pParent && pThis->m_pParent->m_idCk == ID("LIST"); pThis = pThis->m_pParent) - { - if (pThis->m_pNode) - { - for (ChildNode * pFindProp = pThis->m_pParent->GetPrevChild(pThis->m_pNode,"PROP"); pFindProp; pFindProp = pThis->m_pParent->GetPrevChild(pFindProp,"PROP")) - { - Composite * pProp = static_cast<Composite *>(pFindProp->GetChunk()); - if (pProp->m_idData == m_idData) - { - ChildNode * pFindNode = pProp->GetLastChild(idProp); - - if (pFindNode) return pFindNode->GetChunk(); - } - } - - } - } - - return NULL; - } - - void Composite::DeleteChild(ChildNode * pNode) - { - if (pNode->m_pPrev) - pNode->m_pPrev->m_pNext = pNode->m_pNext; - else - m_pFirst = pNode->m_pNext; - - if (pNode->m_pNext) - pNode->m_pNext->m_pPrev = pNode->m_pPrev; - else - m_pLast = pNode->m_pPrev; - - pNode->m_pChunk->m_pParent = NULL; - pNode->m_pChunk->m_pNode = NULL; - pNode->m_pChunk->Release(); - pNode->Release(); - } - - void Composite::DeleteAllChildren() - { - while (m_pFirst) - DeleteChild(m_pFirst); - } - - ChildNode * Composite::InsertChildFirst(Chunk * pChunk) - { - pChunk->AddRef(); - pChunk->m_pParent = this; - - ChildNode * pNode = new ChildNode; - pChunk->m_pNode = pNode; - - pNode->m_pChunk = pChunk; - pNode->m_pPrev = NULL; - pNode->m_pNext = m_pFirst; - - if (m_pFirst) - m_pFirst->m_pPrev = pNode; - - m_pFirst = pNode; - - if (!m_pLast) - m_pLast = m_pFirst; - - return pNode; - } - - ChildNode * Composite::InsertChildLast(Chunk * pChunk) - { - pChunk->m_pParent = this; - pChunk->AddRef(); - - ChildNode * pNode = new ChildNode; - pChunk->m_pNode = pNode; - - pNode->m_pChunk = pChunk; - pNode->m_pNext = NULL; - pNode->m_pPrev = m_pLast; - - if (m_pLast) - m_pLast->m_pNext = pNode; - - m_pLast = pNode; - - if (!m_pFirst) - m_pFirst = m_pLast; - - return pNode; - } - - ChildNode * Composite::InsertChildAfter(ChildNode * pRefNode, Chunk * pChunk) - { - pChunk->m_pParent = this; - pChunk->AddRef(); - - ChildNode * pNode = new ChildNode; - pChunk->m_pNode = pNode; - - pNode->m_pChunk = pChunk; - pNode->m_pNext = pRefNode->m_pNext; - pNode->m_pPrev = pRefNode; - - if (pRefNode->m_pNext) - pRefNode->m_pNext->m_pPrev = pNode; - else - m_pLast = pNode; - - pRefNode->m_pNext = pNode; - - return pNode; - } - - ChildNode * Composite::InsertChildBefore(ChildNode * pRefNode, Chunk * pChunk) - { - pChunk->m_pParent = this; - pChunk->AddRef(); - - ChildNode * pNode = new ChildNode; - pChunk->m_pNode = pNode; - - pNode->m_pChunk = pChunk; - pNode->m_pPrev = pRefNode->m_pPrev; - pNode->m_pNext = pRefNode; - - if (pRefNode->m_pPrev) - pRefNode->m_pPrev->m_pNext = pNode; - else - m_pFirst = pNode; - - pRefNode->m_pPrev = pNode; - - return pNode; - } - - bool Composite::EnumChildren(ID idData, ID idChunk, bool (* pfnCallback) (Chunk *, void *), void * pData) const - { - if (m_idData != idData) return true; - - for (ChildNode * pNode = GetFirstChild(idChunk); pNode; pNode = GetNextChild(pNode,idChunk)) - { - if (!pfnCallback(pNode->GetChunk(),pData)) return false; - } - - return true; - } - - bool Composite::IsValidChildID(ID) const - { - return true; - } - - Chunk * Composite::LoadChunk(Archive * pArchv) const - { - ID idChunk; - pArchv->Transfer(idChunk); - - return Chunk::Load(m_idData, pArchv, idChunk, IsValidChildID(idChunk)); - } - - void Composite::Serialize(Archive * pArchv) - { - pArchv->Transfer(m_idData); - - if (pArchv->m_bIsLoading) - { - DeleteAllChildren(); - - while (pArchv->GetSize()) - { - Chunk * pChunk = LoadChunk(pArchv); - InsertChildLast(pChunk); - pChunk->Release(); - } - } - else - { - for (ChildNode * pNode = m_pFirst; pNode; pNode = GetNextChild(pNode)) - { - pNode->GetChunk()->Write(pArchv); - } - } - } - - bool Form::IsValidChildID(ID id) const - { - // contents: FORM | LIST | CAT | LocalChunk - return ID("PROP") != id; - } - - bool Cat::EnumChildren(ID idData, ID idChunk, bool (* pfnCallback) (Chunk *, void *), void * pData) const - { - for (ChildNode * pNode = GetFirstChild(); pNode; pNode = GetNextChild(pNode)) - { - Composite const * pComposite = static_cast<Composite const *>(pNode->GetChunk()); - if (pComposite->m_idData == idData && !pComposite->EnumChildren(idData,idChunk,pfnCallback,pData)) return false; - } - - return true; - } - - bool Cat::IsValidChildID(ID id) const - { - // contentes: FROM | LIST | CAT - return ID("FORM") == id || ID("LIST") == id || ID("CAT ") == id; - } - - bool List::EnumChildren(ID idData, ID idChunk, bool (* pfnCallback) (Chunk *, void *), void * pData) const - { - for (ChildNode * pNode = GetFirstChild(); pNode; pNode = GetNextChild(pNode)) - { - Composite const * pComposite = static_cast<Composite const *>(pNode->GetChunk()); - if (pComposite->m_idData == idData && !pComposite->EnumChildren(idData,idChunk,pfnCallback,pData)) return false; - } - - return true; - } - - bool List::IsValidChildID(ID id) const - { - // contentes: FROM | LIST | CAT | PROP - return ID("FORM") == id || ID("LIST") == id || ID("CAT ") == id || ID("PROP") == id; - } - - bool Prop::IsValidChildID(ID id) const - { - // contentes: LocalChunk - return ID("FORM") != id && ID("LIST") != id && ID("CAT ") != id && ID("PROP") != id; - } - - IFF_IMPLEMENT_DYNCREATE(ID_ANY,"FORM",Form) - IFF_IMPLEMENT_DYNCREATE(ID_ANY,"LIST",List) - IFF_IMPLEMENT_DYNCREATE(ID_ANY,"CAT ",Cat) - IFF_IMPLEMENT_DYNCREATE(ID_ANY,"PROP",Prop) - - /*******************************/ - /* Original File: iffMscCk.cpp */ - /*******************************/ - - #ifdef IFF_READ_ONLY - - void MiscChunk::Serialize(Archive * ){} - - #else // ! IFF_READ_ONLY - - void MiscChunk::Serialize(Archive * pArchv) - { - if (pArchv->m_bIsLoading) - { - if (m_pData) - delete[] m_pData; - m_nSize = pArchv->GetSize(); - m_pData = new BYTE [m_nSize]; - } - - pArchv->TransferBlock(m_pData,m_nSize); - } - - MiscChunk::~MiscChunk() - { - if (m_pData) - delete[] m_pData; - } - - /*******************************/ - /* Original File: iffSData.cpp */ - /*******************************/ - - DataBlock::~DataBlock() - { - delete[] m_pBlock; - } - - inline bool DataBlock::WriteToFile(::MediaMedium * pMedium) const - { - pMedium->WriteBlock(m_pBlock,m_nCurSize); - return pMedium->m_fError ? false : true; - } - - void DataBlock::Expand(unsigned nMinSize) - { - while (m_nMaxSize < nMinSize) - m_nMaxSize*=2; - - UBYTE * pNewBlock = new UBYTE [m_nMaxSize]; - memcpy(pNewBlock,m_pBlock,m_nCurSize); - delete[] m_pBlock; - m_pBlock = pNewBlock; - } - - DataNode::~DataNode() - { - if (m_pPrev) - m_pPrev->Release(); - if (m_pData) - m_pData->Release(); - if (m_pNext) - m_pNext->Release(); - } - - unsigned DataNode::GetDataSize() const - { - return - (m_pPrev ? m_pPrev->GetDataSize() : 0) - + (m_pData ? m_pData->GetDataSize() : 0) - + (m_pNext ? m_pNext->GetDataSize() : 0) - ; - } - - bool DataNode::WriteToFile(::MediaMedium * pMedium) const - { - return - (m_pPrev ? m_pPrev->WriteToFile(pMedium) : true) - && (m_pData ? m_pData->WriteToFile(pMedium) : true) - && (m_pNext ? m_pNext->WriteToFile(pMedium) : true) - ; - } - - SerialData::~SerialData() - { - m_pData->Release(); - if (m_pPrev) - m_pPrev->Release(); - } - - void SerialData::Clear() - { - m_pData->Release(); - if (m_pPrev) - m_pPrev->Release(); - m_pData = new DataBlock; - m_pPrev = NULL; - } - - unsigned SerialData::GetDataSize() const - { - return - (m_pPrev ? m_pPrev->GetDataSize() : 0) - + m_pData->GetDataSize() - ; - } - - bool SerialData::WriteToFile(::MediaMedium * pMedium) const - { - return - (m_pPrev ? m_pPrev->WriteToFile(pMedium) : true) - && m_pData->WriteToFile(pMedium) - ; - } - - /*******************************/ - /* Original File: iffArchO.cpp */ - /*******************************/ - - void ArchvOut::Open(::MediaMedium * pMedium) - { - if (m_pMedium) m_pMedium->Release(); - - m_pMedium = pMedium; - m_pMedium->AddRef(); - - if (m_pMedium->m_fError) - { - m_bError = true; - m_pMedium->Release(); - m_pMedium = NULL; - } - } - - void ArchvOut::Close() - { - if (m_pMedium) - { - if (!WriteToFile(m_pMedium)) - m_bError = true; - m_pMedium->Release(); - m_pMedium = NULL; - } - } - - ArchvOut::~ArchvOut() - { - Close(); - } - - Archive * ArchvOut::OpenSubArchive(unsigned) - { - return new ArchvOut; - } - - void ArchvOut::CloseSubArchive(Archive * pSub) - { - m_bError = m_bError || pSub->m_bError; - Append(static_cast<ArchvOut *>(pSub)); - pSub->Release(); - } - - #endif // IFF_READ_ONLY - - /*******************************/ - /* Original File: iffArchI.cpp */ - /*******************************/ - - void ArchvIn::Open(::MediaMedium * pMedium) - { - if (m_pMedium) m_pMedium->Release(); - - m_pMedium = pMedium; - m_pMedium->AddRef(); - - if (m_pMedium->m_fError) - { - m_bError = true; - m_pMedium->Release(); - m_pMedium = NULL; - } - else - { - m_nEndPos = m_pMedium->GetRemainingSize(); - m_nBytesRemaining = m_nEndPos; - } - } - - void ArchvIn::Close() - { - if (m_pMedium) - { - m_pMedium->SetPos(m_nEndPos); - m_pMedium->Release(); - m_pMedium = NULL; - } - } - - inline ArchvIn::ArchvIn(ArchvIn * pParent, unsigned nSize) - : _IFF_ARCHI_FLAG(true) - , m_pMedium(pParent->m_pMedium) - , m_nBytesRemaining(nSize) - { - m_nEndPos = pParent->m_pMedium->GetPos(); - m_nEndPos += nSize; - pParent->m_nBytesRemaining -= nSize; - m_pMedium->AddRef(); - } - - ArchvIn::~ArchvIn() - { - Close(); - } - - Archive * ArchvIn::OpenSubArchive(unsigned nSize) - { - return new ArchvIn(this,nSize); - } - - void ArchvIn::CloseSubArchive(Archive * pSub) - { - m_bError = m_bError || pSub->m_bError; - pSub->Release(); - } - -} // namespace IFF
\ No newline at end of file diff --git a/3dc/win95/iff.hpp b/3dc/win95/iff.hpp deleted file mode 100644 index 9250171..0000000 --- a/3dc/win95/iff.hpp +++ /dev/null @@ -1,991 +0,0 @@ -#ifndef _INCLUDED_IFF_HPP_ -#define _INCLUDED_IFF_HPP_ - -#if defined(_WIN32) || defined(WIN32) || defined(WINDOWS) || defined(_WINDOWS) - #define _IFF_WIN_TARGET - #include <windows.h> -#else // ! WIN32 && ! _WIN32 && ! WINDOWS && ! _WINDOWS - #include <stdio.h> - #include <conio.h> -#endif // ! WIN32 && ! _WIN32 && ! WINDOWS && ! _WINDOWS - -#include "media.hpp" - -namespace IFF -{ - /*************************/ - /* Class Hierarchy: */ - /* */ - /* + Unknown */ - /* + SerializableObj */ - /* + GenericFile */ - /* + File */ - /* + Chunk */ - /* + Composite */ - /* + Form */ - /* + Cat */ - /* + List */ - /* + Prop */ - /* + MiscChunk */ - /* + <user chunks> */ - /* + Arvhive */ - /* + ArchvIn */ - /* + ArchvOut(*) */ - /* + DataBlock */ - /* + DataNode */ - /* + SerialData */ - /* + ArchvOut(*) */ - /* + ChildNode */ - /* + DeviceHandle */ - /*************************/ - - #ifdef _IFF_WIN_TARGET - inline void DisplayMessage(TCHAR const * pszTitle,TCHAR const * pszText) - { - ::MessageBox(NULL,pszText,pszTitle,MB_OK|MB_ICONEXCLAMATION|MB_SETFOREGROUND); - } - #else - inline void DisplayMessage(char const * pszTitle,char const * pszText) - { - ::printf("%s\n%s\n",pszTitle,pszText); - while (::kbhit()) - ::getch(); - while (!::kbhit() || '\r' != ::getch()) - ; - } - #endif - - // forward refs - //class Unknown; - //class SerializableObj; - //class GenericFile; - //class File; - //class Chunk; - class Composite; - //class Form; - //class Cat; - //class List; - //class Prop; - //class MiscChunk; - //class Archive; - //class ArchvIn; - //class ArchvOut; - //class DataBlock; - //class DataNode; - //class SerialData; - class ChildNode; - //class DeviceHandle; - - /*****************************/ - /* Original File: iffObj.hpp */ - /*****************************/ - - class Unknown - { - public: - unsigned AddRef() { return ++m_nRefCnt; } - unsigned Release() { if (0==(--m_nRefCnt)) { delete this; return 0;} else return m_nRefCnt; } - protected: - virtual ~Unknown() { - #ifndef NDEBUG - DbForget(this); - #endif - } - Unknown() : m_nRefCnt(1) { - #ifndef NDEBUG - DbRemember(this); - #endif - } - Unknown(Unknown const &) : m_nRefCnt(1) { - #ifndef NDEBUG - DbRemember(this); - #endif - } - private: - unsigned m_nRefCnt; - - #ifndef NDEBUG - friend void DbRemember(Unknown * pObj); - friend void DbForget(Unknown * pObj); - friend class AllocList; - #endif - }; - - /*******************************/ - /* Original File: iffTypes.hpp */ - /*******************************/ - - // deal with any silly bastard who's put #define BYTE ... in a header, etc. - #ifdef BYTE - #undef BYTE - #pragma message("BYTE was defined - undefining") - #endif - typedef signed char BYTE; - typedef unsigned char UBYTE; - - typedef signed short INT16; - typedef unsigned short UINT16; - - typedef signed INT32; - typedef unsigned UINT32; - - typedef signed __int64 INT64; - typedef unsigned __int64 UINT64; - - struct RGBTriple - { - UBYTE r; - UBYTE g; - UBYTE b; - }; - - union ID - { - UINT32 m_nID; - char m_sID[4]; - - inline ID(){} - inline ID(char const * pszID) { m_nID = *reinterpret_cast<UINT32 const *>(pszID); } - inline ID(UINT32 nID) : m_nID(nID) {} - inline operator UINT32 () const { return m_nID; } - inline operator char const * () const { return &m_sID[0]; } - inline bool operator == (ID const & rId) const { return !m_nID || !rId.m_nID || m_nID == rId.m_nID; } - inline bool operator != (ID const & rId) const { return ! operator == (rId); } - inline bool operator ! () const { return !m_nID; } - }; - - ID const ID_ANY(0U); - - #ifndef IFF_READ_ONLY - - /*******************************/ - /* Original File: iffSData.hpp */ - /*******************************/ - - class DataBlock : public Unknown - { - public: - virtual ~DataBlock(); - DataBlock() : m_pBlock(new UBYTE [128]), m_nMaxSize(128), m_nCurSize(0) {} - - unsigned GetDataSize() const; - UBYTE const * GetDataPtr() const; - - bool WriteToFile(::MediaMedium * pMedium) const; - - void Append(UBYTE byte); - void Append(void const * pData, unsigned nSize); - - private: - void Expand(unsigned nMinSize); - - UBYTE * m_pBlock; - unsigned m_nMaxSize; - unsigned m_nCurSize; - }; - - inline unsigned DataBlock::GetDataSize() const - { - return m_nCurSize; - } - - inline UBYTE const * DataBlock::GetDataPtr() const - { - return m_pBlock; - } - - inline void DataBlock::Append(UBYTE byte) - { - if (m_nCurSize >= m_nMaxSize) - Expand(m_nCurSize+1); - - m_pBlock[m_nCurSize++] = byte; - } - - inline void DataBlock::Append(void const * pData, unsigned nSize) - { - if (m_nCurSize+nSize > m_nMaxSize) - Expand(m_nCurSize+nSize+32); - - memcpy(&m_pBlock[m_nCurSize],pData,nSize); - - m_nCurSize += nSize; - } - - class DataNode : public Unknown - { - public: - DataNode(DataNode * pNext, DataBlock * pData, DataNode * pPrev) - : m_pNext(pNext) - , m_pData(pData) - , m_pPrev(pPrev) - { - if (pNext) pNext->AddRef(); - if (pData) pData->AddRef(); - if (pPrev) pPrev->AddRef(); - } - virtual ~DataNode(); - - unsigned GetDataSize() const; - - bool WriteToFile(::MediaMedium * pMedium) const; - - private: - DataNode * m_pNext; - DataBlock * m_pData; - DataNode * m_pPrev; - }; - - class SerialData : public Unknown - { - public: - virtual ~SerialData(); - SerialData() : m_pPrev(NULL), m_pData(new DataBlock) {}; - - void Clear(); - - unsigned GetDataSize() const; - - bool WriteToFile(::MediaMedium * pMedium) const; - - void Append(UBYTE byte); - void Append(void const * pData, unsigned nSize); - - void Append(SerialData * pData); - - private: - DataBlock * m_pData; - DataNode * m_pPrev; - }; - - inline void SerialData::Append(UBYTE byte) - { - m_pData->Append(byte); - } - - inline void SerialData::Append(void const * pData, unsigned nSize) - { - m_pData->Append(pData,nSize); - } - - inline void SerialData::Append(SerialData * pIns) - { - DataNode * pNewNode = new DataNode(pIns->m_pPrev,m_pData,m_pPrev); - - m_pData->Release(); - m_pData = pIns->m_pData; - pIns->m_pData->AddRef(); - - if (m_pPrev) - m_pPrev->Release(); - m_pPrev = pNewNode; - } - - /*******************************/ - /* Original File: iffArchv.hpp */ - /*******************************/ - - class Archive : public Unknown - { - public: - // constructor - construct with true iff the archive is for loading data - Archive(bool bIsLoading) : m_bIsLoading(bIsLoading), m_bError(false) {} - - // to determine easily whenever necessary if the archive is loading data - bool const m_bIsLoading; - bool m_bError; - - // returns either the size in bytes of the data so far written to a storing archive - // or the number of bytes remaining to be read from a loading archive, could be negative - // if too many bytes were read - virtual signed GetSize() const = 0; - - // if the archive is loading, nSize bytes are sectioned off to be read from a sub-archive - // or if the archive is storing, nSize is ignored and data written to the sub-archive - // will be stored when the sub-archive is closed - virtual Archive * OpenSubArchive(unsigned nSize = 0) = 0; - - // commits data written temporarily to a sub-archive (if storing) - // and advances the archive to the next byte after the sub-archive's data - virtual void CloseSubArchive(Archive * pSub) = 0; - - virtual void Open(::MediaMedium * pMedium) = 0; - virtual void Close() = 0; - - virtual void Transfer(RGBTriple &) = 0; - virtual void Transfer(BYTE &) = 0; - virtual void Transfer(UBYTE &) = 0; - virtual void Transfer(INT16 &) = 0; - virtual void Transfer(UINT16 &) = 0; - virtual void Transfer(INT32 &) = 0; - virtual void Transfer(UINT32 &) = 0; - virtual void Transfer(INT64 &) = 0; - virtual void Transfer(UINT64 &) = 0; - virtual void Transfer(ID &) = 0; - - virtual void TransferBlock(void * pData,unsigned nSize) = 0; - }; - - /*******************************/ - /* Original File: iffArchO.hpp */ - /*******************************/ - - class ArchvOut : public Archive, public SerialData - { - public: - ArchvOut() : Archive(false), m_pMedium(NULL) {} - ~ArchvOut(); - - signed GetSize() const; - - Archive * OpenSubArchive(unsigned nSize = 0); - - void CloseSubArchive(Archive * pSub); - - void Open(::MediaMedium * pMedium); - void Close(); - - void Transfer(RGBTriple &); - void Transfer(BYTE &); - void Transfer(UBYTE &); - void Transfer(INT16 &); - void Transfer(UINT16 &); - void Transfer(INT32 &); - void Transfer(UINT32 &); - void Transfer(INT64 &); - void Transfer(UINT64 &); - void Transfer(ID &); - - void TransferBlock(void * pData,unsigned nSize); - - private: - ::MediaMedium * m_pMedium; - }; - - inline signed ArchvOut::GetSize() const - { - return GetDataSize(); - } - - inline void ArchvOut::Transfer(RGBTriple & n) - { - Append(n.r); - Append(n.g); - Append(n.b); - } - - inline void ArchvOut::Transfer(BYTE & n) - { - Append(n); - } - - inline void ArchvOut::Transfer(UBYTE & n) - { - Append(n); - } - - inline void ArchvOut::Transfer(INT16 & n) - { - Append(static_cast<BYTE>(n >> 8)); - Append(static_cast<BYTE>(n)); - } - - inline void ArchvOut::Transfer(UINT16 & n) - { - Append(static_cast<UBYTE>(n >> 8)); - Append(static_cast<UBYTE>(n)); - } - - inline void ArchvOut::Transfer(INT32 & n) - { - Append(static_cast<BYTE>(n >> 24)); - Append(static_cast<BYTE>(n >> 16)); - Append(static_cast<BYTE>(n >> 8)); - Append(static_cast<BYTE>(n)); - } - - inline void ArchvOut::Transfer(UINT32 & n) - { - Append(static_cast<UBYTE>(n >> 24)); - Append(static_cast<UBYTE>(n >> 16)); - Append(static_cast<UBYTE>(n >> 8)); - Append(static_cast<UBYTE>(n)); - } - - inline void ArchvOut::Transfer(INT64 & n) - { - Append(static_cast<BYTE>(n >> 56)); - Append(static_cast<BYTE>(n >> 48)); - Append(static_cast<BYTE>(n >> 40)); - Append(static_cast<BYTE>(n >> 32)); - Append(static_cast<BYTE>(n >> 24)); - Append(static_cast<BYTE>(n >> 16)); - Append(static_cast<BYTE>(n >> 8)); - Append(static_cast<BYTE>(n)); - } - - inline void ArchvOut::Transfer(UINT64 & n) - { - Append(static_cast<UBYTE>(n >> 56)); - Append(static_cast<UBYTE>(n >> 48)); - Append(static_cast<UBYTE>(n >> 40)); - Append(static_cast<UBYTE>(n >> 32)); - Append(static_cast<UBYTE>(n >> 24)); - Append(static_cast<UBYTE>(n >> 16)); - Append(static_cast<UBYTE>(n >> 8)); - Append(static_cast<UBYTE>(n)); - } - - inline void ArchvOut::Transfer(ID & n) - { - Append(&n,4); - } - - inline void ArchvOut::TransferBlock(void * pData,unsigned nSize) - { - Append(pData,nSize); - } - - #endif // ! IFF_READ_ONLY - - /*******************************/ - /* Original File: iffArchI.hpp */ - /*******************************/ - - #ifdef IFF_READ_ONLY - #define _IFF_ARCHI_BASE Unknown - #define _IFF_ARCHI_GENR ArchvIn - #define _IFF_ARCHI_FLAG m_bIsLoading - #define _IFF_ARCHI_INIT ,m_bError(false) - #else // ! IFF_READ_ONLY - #define _IFF_ARCHI_BASE Archive - #define _IFF_ARCHI_GENR Archive - #define _IFF_ARCHI_FLAG Archive - #define _IFF_ARCHI_INIT - #endif // ! IFF_READ_ONLY - - class ArchvIn : public _IFF_ARCHI_BASE - { - public: - ArchvIn() : _IFF_ARCHI_FLAG(true), m_pMedium(NULL) _IFF_ARCHI_INIT {} - ~ArchvIn(); - - #ifdef IFF_READ_ONLY - bool const m_bIsLoading; - bool m_bError; - #endif // IFF_READ_ONLY - - signed GetSize() const; - - _IFF_ARCHI_GENR * OpenSubArchive(unsigned nSize = 0); - - void CloseSubArchive(_IFF_ARCHI_GENR * pSub); - - void Open(::MediaMedium * pMedium); - void Close(); - - void Transfer(RGBTriple &); - void Transfer(BYTE &); - void Transfer(UBYTE &); - void Transfer(INT16 &); - void Transfer(UINT16 &); - void Transfer(INT32 &); - void Transfer(UINT32 &); - void Transfer(INT64 &); - void Transfer(UINT64 &); - void Transfer(ID &); - - void TransferBlock(void * pData,unsigned nSize); - - private: - ArchvIn(ArchvIn * pParent, unsigned nSize); - - ::MediaMedium * m_pMedium; - signed m_nBytesRemaining; - unsigned m_nEndPos; - }; - - #ifdef IFF_READ_ONLY - typedef ArchvIn Archive; - #endif // IFF_READ_ONLY - - inline signed ArchvIn::GetSize() const - { - return m_nBytesRemaining; - } - - inline void ArchvIn::Transfer(RGBTriple & n) - { - m_nBytesRemaining -= 3; - if (m_nBytesRemaining >= 0) - { - ::MediaRead(m_pMedium, &n.r); - ::MediaRead(m_pMedium, &n.g); - ::MediaRead(m_pMedium, &n.b); - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(UBYTE & n) - { - m_nBytesRemaining -= 1; - if (m_nBytesRemaining >= 0) - { - ::MediaRead(m_pMedium, &n); - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(BYTE & n) - { - m_nBytesRemaining -= 1; - if (m_nBytesRemaining >= 0) - { - ::MediaRead(m_pMedium, &n); - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(UINT16 & n) - { - m_nBytesRemaining -= 2; - if (m_nBytesRemaining >= 0) - { - UBYTE byte; - ::MediaRead(m_pMedium, &byte); - n = byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(INT16 & n) - { - m_nBytesRemaining -= 2; - if (m_nBytesRemaining >= 0) - { - BYTE byte; - ::MediaRead(m_pMedium, &byte); - n = byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(UINT32 & n) - { - m_nBytesRemaining -= 4; - if (m_nBytesRemaining >= 0) - { - UBYTE byte; - ::MediaRead(m_pMedium, &byte); - n = byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(INT32 & n) - { - m_nBytesRemaining -= 4; - if (m_nBytesRemaining >= 0) - { - BYTE byte; - ::MediaRead(m_pMedium, &byte); - n = byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(UINT64 & n) - { - m_nBytesRemaining -= 8; - if (m_nBytesRemaining >= 0) - { - UBYTE byte; - ::MediaRead(m_pMedium, &byte); - n = byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(INT64 & n) - { - m_nBytesRemaining -= 8; - if (m_nBytesRemaining >= 0) - { - BYTE byte; - ::MediaRead(m_pMedium, &byte); - n = byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - ::MediaRead(m_pMedium, &byte); - n <<= 8; - n |= byte; - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::Transfer(ID & n) - { - m_nBytesRemaining -= 4; - if (m_nBytesRemaining >= 0) - { - // cast pointer to pointer to 4 byte data type to force 4 byte 'fast' read - ::MediaRead(m_pMedium, reinterpret_cast<UINT32 *>(&n.m_sID[0])); - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - inline void ArchvIn::TransferBlock(void * pData,unsigned nSize) - { - m_nBytesRemaining -= nSize; - if (m_nBytesRemaining >= 0) - { - m_pMedium->ReadBlock(pData,nSize); - if (m_pMedium->m_fError) m_bError = true; - } - else m_bError = true; - } - - /*******************************/ - /* Original File: iffSrlOb.hpp */ - /*******************************/ - - class SerializableObj : public Unknown - { - public: - virtual void Serialize(Archive * pArchv) = 0; - }; - - /*******************************/ - /* Original File: iffChunk.hpp */ - /*******************************/ - - class Chunk : public SerializableObj - { - public: - ID m_idCk; - - Chunk * GetProperty(ID idProp) const; - - virtual bool IsUnknown() const { return false; } - - void Write(Archive * pArchv); - static Chunk * Load(ID idParent, Archive * pArchv, ID idChunk = ID_ANY, bool bKnown = true); - - static Chunk * DynCreate(ID idParent, ID idChunk); - static void Register(ID idParent, ID idChunk, Chunk * (* pfnCreate) () ); - - Composite const * GetParent() const { return m_pParent; } - - protected: - Chunk() : m_pParent(NULL) {} - - private: - Composite const * m_pParent; // mot reference counted - ChildNode const * m_pNode; // not reference counted either - - friend class Composite; - }; - - #define IFF_IMPLEMENT_DYNCREATE(idParent,idChunk,tokenClassName) _IFF_IMPLEMENT_DYNCREATE_LINE_EX(idParent,idChunk,tokenClassName,__LINE__) - #define _IFF_IMPLEMENT_DYNCREATE_LINE_EX(idParent,idChunk,tokenClassName,nLine) _IFF_IMPLEMENT_DYNCREATE_LINE(idParent,idChunk,tokenClassName,nLine) - - #define _IFF_IMPLEMENT_DYNCREATE_LINE(idParent,idChunk,tokenClassName,nLine) \ - static IFF::Chunk * CreateClassObject ## tokenClassName ##_## nLine () { \ - IFF::Chunk * pChunk = new IFF::tokenClassName; \ - pChunk->m_idCk = idChunk; \ - return pChunk; \ - } \ - class RegisterChunkClass ## tokenClassName ##_## nLine { \ - public: RegisterChunkClass ## tokenClassName ##_## nLine () { \ - IFF::Chunk::Register(idParent , idChunk , CreateClassObject ## tokenClassName ##_## nLine); \ - } \ - } rcc ## tokenClassName ##_## nLine; - - /*******************************/ - /* Original File: iffBlock.hpp */ - /*******************************/ - - class ChildNode : public Unknown - { - public: - Chunk * GetChunk() const { return m_pChunk; } - private: - ChildNode * m_pNext; - ChildNode * m_pPrev; - Chunk * m_pChunk; - - friend class Composite; - }; - - class Composite : public Chunk - { - public: - ID m_idData; - - Composite() : m_pFirst(NULL), m_pLast(NULL) {} - virtual ~Composite(); - - ChildNode * GetFirstChild() const { return m_pFirst; } - ChildNode * GetFirstChild(ID idMatch) const; - ChildNode * GetLastChild() const { return m_pLast; } - ChildNode * GetLastChild(ID idMatch) const; - static ChildNode * GetNextChild(ChildNode const * pNode) { return pNode->m_pNext; } - static ChildNode * GetNextChild(ChildNode const * pNode, ID idMatch); - static ChildNode * GetPrevChild(ChildNode const * pNode) { return pNode->m_pPrev; } - static ChildNode * GetPrevChild(ChildNode const * pNode, ID idMatch); - - Chunk * GetProperty(ChildNode const * pNode, ID idProp) const; - - void DeleteChild(ChildNode * pNode); - void DeleteAllChildren(); - - ChildNode * InsertChildFirst(Chunk * pChunk); - ChildNode * InsertChildLast(Chunk * pChunk); - ChildNode * InsertChildAfter(ChildNode * pNode, Chunk * pChunk); - ChildNode * InsertChildBefore(ChildNode * pNode, Chunk * pChunk); - - // pfnCallback should return true to continue the enumeration, false to finish - virtual bool EnumChildren(ID idData, ID idChunk, bool (* pfnCallback) (Chunk *, void *), void * pData) const; - - protected: - virtual void Serialize(Archive * pArchv); - - virtual Chunk * LoadChunk(Archive * pArchv) const; - virtual bool IsValidChildID(ID id) const; - - private: - ChildNode * m_pFirst; - ChildNode * m_pLast; - }; - - class Form : public Composite - { - public: - Form() { m_idCk = "FORM"; } - protected: - virtual bool IsValidChildID(ID id) const; - }; - - class Cat : public Composite - { - public: - Cat() { m_idCk = "CAT "; } - virtual bool EnumChildren(ID idData, ID idChunk, bool (* pfnCallback) (Chunk *, void *), void * pData) const; - protected: - virtual bool IsValidChildID(ID id) const; - }; - - class List : public Composite - { - public: - List() { m_idCk = "LIST"; } - virtual bool EnumChildren(ID idData, ID idChunk, bool (* pfnCallback) (Chunk *, void *), void * pData) const; - protected: - virtual bool IsValidChildID(ID id) const; - }; - - class Prop : public Composite - { - public: - Prop() { m_idCk = "PROP"; } - protected: - virtual bool IsValidChildID(ID id) const; - }; - - /*******************************/ - /* Original File: iffMscCk.hpp */ - /*******************************/ - - class MiscChunk : public Chunk - { - public: - MiscChunk(ID id) - #ifndef IFF_READ_ONLY - : m_pData(NULL) - #endif // ! IFF_READ_ONLY - { - m_idCk = id; - } - - virtual bool IsUnknown() const { return true; } - - protected: - virtual void Serialize(Archive * pArchv); - #ifndef IFF_READ_ONLY - virtual ~MiscChunk(); - #endif // ! IFF_READ_ONLY - - private: - #ifndef IFF_READ_ONLY - BYTE * m_pData; - unsigned m_nSize; - #endif // ! IFF_READ_ONLY - }; - - /******************************/ - /* Original File: iffFile.hpp */ - /******************************/ - - class GenericFile : public SerializableObj - { - public: - #ifndef IFF_READ_ONLY - GenericFile() : m_pszFileName(NULL) {} - virtual ~GenericFile() { if (m_pszFileName) delete[] m_pszFileName; } - #endif - - bool Load(TCHAR const * pszFileName); - bool Load(::MediaMedium * pMedium); - - #ifndef IFF_READ_ONLY - bool Write(TCHAR const * pszFileName = NULL); - bool Write(::MediaMedium * pMedium); - #endif // ! IFF_READ_ONLY - - private: - #ifndef IFF_READ_ONLY - TCHAR * m_pszFileName; - #endif // ! IFF_READ_ONLY - }; - - class File : public GenericFile - { - public: - virtual ~File(); - File() : m_pContents(NULL) {} - - Composite * GetContents() const; - void SetContents(Composite * pContents); - - protected: - virtual void Serialize(Archive * pArchv); - - private: - ID m_idType; - Composite * m_pContents; - }; - - inline Composite * File::GetContents() const - { - return m_pContents; - } - - inline void File::SetContents(Composite * pContents) - { - if (m_pContents) m_pContents->Release(); - if (pContents) - { - pContents->AddRef(); - m_idType = pContents->m_idCk; - } - m_pContents = pContents; - } - - // Have a static object of this in each file: - // It will detect if some files are compiled with - // IFF_READ_ONLY defined differently to each other - static class ConsistencyCheck - { - public: inline ConsistencyCheck() - { - #ifdef IFF_READ_ONLY - static bool bReadOnly = true; - if (!bReadOnly) - #else - static bool bReadOnly = false; - if (bReadOnly) - #endif - { - DisplayMessage - ( - #ifdef NDEBUG - TEXT("Error"), - TEXT("IFF_READ_ONLY definition not consistent") - #else - TEXT("IFF Compile Option Error"), - TEXT("Some files which #include \"iff.hpp\"\n") - TEXT("have the macro IFF_READ_ONLY defined\n") - TEXT("and some don't.\n\n") - TEXT("Please ensure this is consistent and recompile.") - #endif - ); - exit(-45); - } - } - } - consistencyCheck; - -} // namespace IFF - -#endif // ! _INCLUDED_IFF_HPP_ diff --git a/3dc/win95/iff_ILBM.cpp b/3dc/win95/iff_ILBM.cpp deleted file mode 100644 index 128f7ad..0000000 --- a/3dc/win95/iff_ILBM.cpp +++ /dev/null @@ -1,327 +0,0 @@ -#include "advwin32.h" -#include "iff_ILBM.hpp" - -IFF_IMPLEMENT_DYNCREATE("ILBM","BMHD",IlbmBmhdChunk) -IFF_IMPLEMENT_DYNCREATE("ILBM","CMAP",IlbmCmapChunk) -IFF_IMPLEMENT_DYNCREATE("ILBM","BODY",IlbmBodyChunk) -IFF_IMPLEMENT_DYNCREATE("ILBM","GRAB",IlbmGrabChunk) - -namespace IFF -{ - void IlbmBmhdChunk::Serialize(Archive * pArchv) - { - pArchv->Transfer(width); - pArchv->Transfer(height); - pArchv->Transfer(xTopLeft); - pArchv->Transfer(yTopLeft); - pArchv->Transfer(nBitPlanes); - pArchv->Transfer(eMasking); - pArchv->Transfer(eCompression); - pArchv->Transfer(flags); - pArchv->Transfer(iTranspCol); - pArchv->Transfer(xAspectRatio); - pArchv->Transfer(yAspectRatio); - pArchv->Transfer(xMax); - pArchv->Transfer(yMax); - } - - void IlbmCmapChunk::Serialize(Archive * pArchv) - { - if (pArchv->m_bIsLoading) - { - nEntries = pArchv->GetSize()/3; - if (pTable) delete[] pTable; - pTable = new RGBTriple [nEntries]; - } - - for (unsigned i=0; i<nEntries; ++i) - pArchv->Transfer(pTable[i]); - } - - IlbmCmapChunk::~IlbmCmapChunk() - { - if (pTable) delete[] pTable; - } - - void IlbmBodyChunk::Serialize(Archive * pArchv) - { - if (pArchv->m_bIsLoading) - { - nSize = pArchv->GetSize(); - if (pData) delete[] pData; - pData = new UBYTE [nSize]; - } - - pArchv->TransferBlock(pData,nSize); - } - - bool IlbmBodyChunk::GetHeaderInfo() const - { - Chunk * pHdr = GetProperty("BMHD"); - if (!pHdr) - { - return false; - } - nWidth = static_cast<IlbmBmhdChunk *>(pHdr)->width; - eCompression = static_cast<IlbmBmhdChunk *>(pHdr)->eCompression; - nBitPlanes = static_cast<IlbmBmhdChunk *>(pHdr)->nBitPlanes; - return true; - } - - #ifndef IFF_READ_ONLY - bool IlbmBodyChunk::BeginEncode() - { - if (!GetHeaderInfo()) - { - return false; - } - - pEncodeDst = new DataBlock; - pEncodeSrc = new UBYTE [(nWidth+7)/8]; - - nSizeNonCprss = 0; - nSizeCprss = 0; - - return true; - } - -// The uninitialised part of byte is shifted out. -#ifdef _MSC_VER -#pragma warning(disable: 4701) -#endif - bool IlbmBodyChunk::EncodeNextRow(unsigned const * pRow) - { - if (!pEncodeDst) return false; - - for (unsigned b=0; b<nBitPlanes; ++b) - { - UBYTE * pBuf = pEncodeSrc; - - unsigned byte; - for (unsigned x=0; x<nWidth; ++x) - { - byte <<= 1; - byte |= pRow[x]>>b & 1; - - if (7==(x&7)) *pBuf++ = static_cast<UBYTE>(byte); - } - if (nWidth & 7) - { - byte <<= 8-(nWidth & 7); - *pBuf = static_cast<UBYTE>(byte); - } - - if (eCompression) - { - nSizeNonCprss += (nWidth+7)/8; - - UBYTE const * pBuf = pEncodeSrc; - unsigned i=(nWidth+7)/8; - - while (i) - { - if (1==i) - { - pEncodeDst->Append(0); - pEncodeDst->Append(*pBuf); - nSizeCprss += 2; - i=0; - } - else if (i>1) - { - if (pBuf[0]==pBuf[1]) - { - unsigned j=2; - while (j<i && j<0x80 && pBuf[j-1]==pBuf[j]) - ++j; - pEncodeDst->Append(static_cast<UBYTE>(0x101-j)); - pEncodeDst->Append(*pBuf); - pBuf += j; - i -= j; - nSizeCprss += 2; - } - else - { - unsigned j=2; - while (j<i && j<0x80 && (pBuf[j]!=pBuf[j-1] || pBuf[j-1]!=pBuf[j-2])) - ++j; - if (j<i && pBuf[j]==pBuf[j-1] && pBuf[j-1]==pBuf[j-2]) - j-=2; - pEncodeDst->Append(static_cast<UBYTE>(j-1)); - pEncodeDst->Append(pBuf,j); - pBuf += j; - i -= j; - nSizeCprss += j+1; - } - } - } - - } - else - { - pEncodeDst->Append(pEncodeSrc,(nWidth+7)/8); - } - } - - return true; - } -#ifdef _MSC_VER -#pragma warning(default: 4701) -#endif - - bool IlbmBodyChunk::EndEncode() - { - if (!pEncodeDst) return false; - - if (pData) delete[] pData; - nSize = pEncodeDst->GetDataSize(); - pData = new UBYTE[nSize]; - - memcpy(pData,pEncodeDst->GetDataPtr(),nSize); - - delete pEncodeDst; - delete[] pEncodeSrc; - - pEncodeDst = NULL; - pEncodeSrc = NULL; - - return true; - } - #endif - - bool IlbmBodyChunk::BeginDecode() const - { - if (pDecodeDst) delete[] pDecodeDst; - if (!pData || !GetHeaderInfo()) - { - pDecodeSrc = NULL; - pDecodeDst = NULL; - return false; - } - - pDecodeSrc = pData; - nRemaining = nSize; - - pDecodeDst = new unsigned [nWidth]; - - return pData != NULL; - } - -// The uninitialised part of pDecodeDst is shifted out. -#ifdef _MSC_VER -#pragma warning(disable: 4701) -#endif - unsigned const * IlbmBodyChunk::DecodeNextRow() const - { - if (!pDecodeSrc || !pDecodeDst) return NULL; - - for (unsigned x=0; x<nWidth; ++x) - pDecodeDst[x]=0; - - if (eCompression) - { - unsigned repcnt = 0; - unsigned rawcnt = 0; - - for (unsigned b=0; b<nBitPlanes; ++b) - { - unsigned byte; - for (unsigned x=0; x<nWidth; ++x) - { - if (!(x&7)) - { - if (!nRemaining) return NULL; - - REPEAT_SKIP: - byte = *pDecodeSrc; - - if (rawcnt) - { - --rawcnt; - ++pDecodeSrc; - --nRemaining; - } - else if (repcnt) - { - --repcnt; - if (!repcnt) - { - ++pDecodeSrc; - --nRemaining; - } - } - else // byte is control byte - { - ++pDecodeSrc; - --nRemaining; - - if (!nRemaining) return NULL; - - if (byte<0x80) - { - rawcnt = byte; - byte = *pDecodeSrc++; - --nRemaining; - } - else if (byte>0x80) - { - repcnt = 0x100 - byte; - byte = *pDecodeSrc; - } - else goto REPEAT_SKIP; - } - } - - pDecodeDst[x] |= (byte>>7 & 1)<<b; - - byte <<= 1; - } - - } - } - else - { - for (unsigned b=0; b<nBitPlanes; ++b) - { - unsigned byte; - for (unsigned x=0; x<nWidth; ++x) - { - if (!(x&7)) - { - if (!nRemaining) return NULL; - - byte = *pDecodeSrc++; - --nRemaining; - } - - pDecodeDst[x] |= (byte>>7 & 1)<<b; - - byte <<= 1; - } - - } - } - - - return pDecodeDst; - } -#ifdef _MSC_VER -#pragma warning(default: 4701) -#endif - - IlbmBodyChunk::~IlbmBodyChunk() - { - if (pData) delete[] pData; - if (pDecodeDst) delete[] pDecodeDst; - #ifndef IFF_READ_ONLY - if (pEncodeDst) delete pEncodeDst; - if (pEncodeSrc) delete[] pEncodeSrc; - #endif - } - - void IlbmGrabChunk::Serialize(Archive * pArchv) - { - pArchv->Transfer(xHotSpot); - pArchv->Transfer(yHotSpot); - } -} diff --git a/3dc/win95/iff_ILBM.hpp b/3dc/win95/iff_ILBM.hpp deleted file mode 100644 index 8a83b38..0000000 --- a/3dc/win95/iff_ILBM.hpp +++ /dev/null @@ -1,164 +0,0 @@ -#ifndef _INCLUDED_IFF_ILBM_HPP_ -#define _INCLUDED_IFF_ILBM_HPP_ - -#include "iff.hpp" - -namespace IFF -{ - class IlbmBmhdChunk : public Chunk - { - public: - UINT16 width; - UINT16 height; - UINT16 xTopLeft; - UINT16 yTopLeft; - UBYTE nBitPlanes; - enum - { - MASK_NONE = 0, - MASK_HASMASK = 1, - MASK_TRANSPARENTCOL = 2, - MASK_LASSO = 3 - }; - UBYTE eMasking; - enum - { - COMPRESS_NONE = 0, - COMPRESS_RUNLENGTH = 1, - COMPRESS_S3TC =2 //will have s3tc chunk instead of body chunk - }; - UBYTE eCompression; - UBYTE flags; - UINT16 iTranspCol; - UBYTE xAspectRatio; - UBYTE yAspectRatio; - UINT16 xMax; - UINT16 yMax; - - IlbmBmhdChunk() { m_idCk = "BMHD"; } - - protected: - virtual void Serialize(Archive * pArchv); - }; - - class IlbmCmapChunk : public Chunk - { - public: - unsigned nEntries; - RGBTriple * pTable; - - void CreateNew(unsigned nSize); - - IlbmCmapChunk() : pTable(NULL) { m_idCk = "CMAP"; } - virtual ~IlbmCmapChunk(); - - protected: - virtual void Serialize(Archive * pArchv); - }; - - inline void IlbmCmapChunk::CreateNew(unsigned nSize) - { - if (pTable) delete[] pTable; - pTable = new RGBTriple [nSize]; - nEntries = nSize; - } - - class IlbmBodyChunk : public Chunk - { - public: - IlbmBodyChunk() : pData(NULL), pDecodeDst(NULL) - #ifndef IFF_READ_ONLY - , pEncodeDst(NULL), pEncodeSrc(NULL) - #endif - { m_idCk = "BODY"; } - virtual ~IlbmBodyChunk(); - - #ifndef IFF_READ_ONLY - bool BeginEncode(); - bool EncodeFirstRow(unsigned const * pRow); - bool EncodeNextRow(unsigned const * pRow); - bool EndEncode(); - - float GetCompressionRatio() const; - #endif - - bool BeginDecode() const; - unsigned const * DecodeFirstRow() const; - unsigned const * DecodeNextRow() const; - bool EndDecode() const; - - protected: - virtual void Serialize(Archive * pArchv); - - virtual bool GetHeaderInfo() const; // fills in these three data members - mutable unsigned nWidth; - mutable unsigned eCompression; - mutable unsigned nBitPlanes; - - private: - unsigned nSize; - UBYTE * pData; - - mutable UBYTE const * pDecodeSrc; - mutable unsigned nRemaining; - mutable unsigned * pDecodeDst; - - #ifndef IFF_READ_ONLY - DataBlock * pEncodeDst; - UBYTE * pEncodeSrc; - - unsigned nSizeNonCprss; - unsigned nSizeCprss; - #endif - }; - - #ifndef IFF_READ_ONLY - inline bool IlbmBodyChunk::EncodeFirstRow(unsigned const * pRow) - { - if (BeginEncode()) - return EncodeNextRow(pRow); - else - return false; - } - - inline float IlbmBodyChunk::GetCompressionRatio() const - { - if (!nSizeNonCprss) return 0.0F; - - return (static_cast<float>(nSizeNonCprss)-static_cast<float>(nSizeCprss))/static_cast<float>(nSizeNonCprss); - } - #endif - - inline unsigned const * IlbmBodyChunk::DecodeFirstRow() const - { - if (BeginDecode()) - return DecodeNextRow(); - else - return NULL; - } - - inline bool IlbmBodyChunk::EndDecode() const - { - if (pDecodeDst) - { - delete[] pDecodeDst; - pDecodeDst = NULL; - return true; - } - else return false; - } - - class IlbmGrabChunk : public Chunk - { - public: - UINT16 xHotSpot; - UINT16 yHotSpot; - - IlbmGrabChunk() { m_idCk = "GRAB"; } - - protected: - virtual void Serialize(Archive * pArchv); - }; -} - -#endif // ! _INCLUDED_IFF_ILBM_HPP_ diff --git a/3dc/win95/io.c b/3dc/win95/io.c deleted file mode 100644 index ab2c540..0000000 --- a/3dc/win95/io.c +++ /dev/null @@ -1,1970 +0,0 @@ -#include "3dc.h" - -#include <sys\stat.h> -#include <string.h> - -#include "inline.h" -#include "module.h" -#include "krender.h" - -#include "chnktexi.h" -#include "d3d_hud.h" -#define UseLocalAssert Yes -#include "ourasert.h" -#include "hud_layout.h" - -#undef textprint - - -#if SupportTLTFiles -#define Output_TLT_File No -#endif - -#define Output_VEA_File No - -#define Proper_8Bit_MIP No - -#define DontLet222ColoursGoToBlack Yes - -#define textprintOn Yes - -#define DHMtextprint Yes - /* define to use Dave Malcolm's replacement textprint routines */ - - -/* As specified by Roxby */ -#define ClearScreenColour 1000 - -/* - To filter frame rate values from - Windows timer to provide a smoother - ride. This may make some AI systems - etc behave better, though it will take - some time to catch up if there is a genuine - abrupt transition in the frame rate. - - There may also be some sort of convergence - instability here!!!! IMPORTANT - FIXME!!!! (possibly) - - Although this code was derived from - some of Jamie's filter algorithms, I have - mangled it hideously, so _don't blame him_! -*/ - -#define KalmanTimer No - -/* - Experiment to try and fix mystery driver problems - Don't set with ForceWindowsPalette on!!! - Leave this on!!! - On some video cards it seems necessary not only to - set palette on vblanking interval, but also AFTER - D3D initialisation is complete... -*/ - -#define ChangePaletteOnVBAlways Yes - -/* - Turn on or off checking for the validity - of a video mode before switching to it. - Actually causes problems on some systems - because the DirectDraw enumerator fails to - report valid modes (although on other systems - it can report ones that can't be reached, ho - hum), so at least for Chris H. it needs to be - turned off. - NOTE THAT THIS SHOULD HAVE THE SAME SETTING AS - CheckVideoModes at the start of dd_func.cpp, at - least until we make it a system.h value or - something else sensible... -*/ - -#define CheckVideoModes No - - -/* - - externs for commonly used global variables and arrays - -*/ - -extern SCENE Global_Scene; -extern SHAPEHEADER **mainshapelist; -extern SHAPEHEADER *testpaletteshapelist[]; -extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; -extern int sine[]; -extern int cosine[]; -extern int AdaptiveHazingFlag; -extern int *Global_ShapeNormals; -extern int *Global_ShapePoints; -extern int *ItemPointers[]; -extern int ItemData[]; -extern char projectsubdirectory[]; - -extern int WinLeftX; -extern int WinRightX; -extern int WinTopY; -extern int WinBotY; - -extern int WindowRequestMode; -extern int VideoRequestMode; -extern int ZBufferRequestMode; -extern int RasterisationRequestMode; -extern int SoftwareScanDrawRequestMode; -extern int DXMemoryRequestMode; - -extern int TotalVideoMemory; -extern int NumAvailableVideoModes; -extern VIDEOMODEINFO AvailableVideoModes[]; - -extern int memoryInitialisationFailure; - -extern IMAGEHEADER ImageHeaderArray[]; /* Array of Image Headers */ - -/* - - Global Variables for PC Watcom Functions - and Windows 95! - -*/ - - int DrawMode = DrawPerVDB; -/* Win95 default ought to be per frame */ - -/* Timer */ - long lastTickCount; - - unsigned char *ScreenBuffer = 0; /* Ensure initialised to Null */ - unsigned char *ScreenBuffer2 = 0; - - - unsigned char LPTestPalette[1024]; /* to cast to lp*/ - - int InputMode; - - int VideoMode; - int VideoModeType; - int VideoModeTypeScreen; - int WindowMode; - int ScanDrawMode; - int ZBufferMode; - int DXMemoryMode; - unsigned char AttemptVideoModeRestart; - VIDEORESTARTMODES VideoRestartMode; - - PROCESSORTYPES ProcessorType; - BOOL MMXAvailable; - - unsigned char *TextureLightingTable = 0; - - unsigned char *PaletteRemapTable = 0; - - int **ShadingTableArray = 0; - int NumShadingTables = 0; - - unsigned char **PaletteShadingTableArray = 0; - int NumPaletteShadingTables = 0; - - int FrameRate; - int NormalFrameTime; - int PrevNormalFrameTime; - extern int CloakingPhase; - - /* These two are dummy values to get the DOS platform to compile */ - - unsigned char KeyCode; - unsigned char KeyASCII; - - - #if SuppressWarnings - unsigned char *palette_tmp; - static VIEWDESCRIPTORBLOCK* vdb_tmp; - static SCREENDESCRIPTORBLOCK* sdb_tmp; - #endif - - /* Keyboard */ - unsigned char KeyboardInput[MAX_NUMBER_OF_INPUT_KEYS]; - unsigned char GotAnyKey; - - /* Input communication with Windows Procedure */ - /* Print system */ - -#if !DHMtextprint - PRINTQUEUEITEM PrintQueue[MaxMessages]; - int MessagesStoredThisFrame; -#endif - - int textprintPosX; - int textprintPosY; - IMAGEHEADER* fontHeader; - - /* Added 28/11/97 by DHM: boolean for run-time switching on/off of textprint */ - int bEnableTextprint = No; - - /* Added 28/1/98 by DHM: as above, but applies specifically to textprintXY */ - int bEnableTextprintXY = Yes; - - /* Palette */ - - unsigned char PaletteBuffer[768 + 1]; - -/* Test Palette */ - -unsigned char TestPalette[768]; -unsigned char TestPalette2[768]; - - - - -/* KJL 11:48:45 28/01/98 - used to scale NormalFrameTime, so the game can be slowed down */ -int TimeScale=65536; - -/* KJL 16:00:11 28/01/98 - unscaled frame time */ -int RealFrameTime; -int GlobalFrameCounter; -int RouteFinder_CallsThisFrame; - -/* KJL 15:08:43 29/03/98 - added to give extra flexibility to debugging text */ -int PrintDebuggingText(const char* t, ...); -int ReleasePrintDebuggingText(const char* t, ...); - - -/* - - IO and Other Functions for the PC - -*/ - - -/* - - Get Shape Data - - Function returns a pointer to the Shape Header Block - -*/ - -SHAPEHEADER* GetShapeData(int shapenum) - -{ - - if(shapenum>=0 && shapenum< maxshapes) - { - SHAPEHEADER *sptr = mainshapelist[shapenum]; - return sptr; - } - - return NULL; -} - - -/* - - Platform specific VDB functions for Initialisation and ShowView() - -*/ - -void PlatformSpecificVDBInit(VIEWDESCRIPTORBLOCK *vdb) - -{ - #if SuppressWarnings - vdb_tmp = vdb; - #endif -} - - -void PlatformSpecificShowViewEntry(VIEWDESCRIPTORBLOCK *vdb, SCREENDESCRIPTORBLOCK *sdb) - -{ - #if SuppressWarnings - vdb_tmp = vdb; - sdb_tmp = sdb; - #endif -} - - -void PlatformSpecificShowViewExit(VIEWDESCRIPTORBLOCK *vdb, SCREENDESCRIPTORBLOCK *sdb) - -{ - #if SuppressWarnings - vdb_tmp = vdb; - sdb_tmp = sdb; - #endif -} - - -/* - - Convert UNIX to MS-DOS - -*/ - -void GetDOSFilename(char *fnameptr) - -{ - - while(*fnameptr) { - - if(*fnameptr == 0x2f) *fnameptr = 0x5c; - fnameptr++; - - } - -} - - -/* - - Compare two strings. - - Return Yes if they're the same, else No. - -*/ - -/* - IMPORTANT!!! - This function is not ideal!!! It is used - here because this is only an initialisation - stage, but if you want to compare strings - elsewhere you should either use the C library - function or (if there's a problem with that) - write your own. -*/ - -int CompareStringCH(char *string1, char *string2) - -{ - - char *srtmp; - char *srtmp2; - int slen1 = 0; - int slen2 = 0; - int i; - - - srtmp = string1; - - while(*srtmp++ != 0) - slen1++; - - srtmp = string2; - - while(*srtmp++ != 0) - slen2++; - - if(slen1 != slen2) return No; - - else { - - srtmp = string1; - srtmp2 = string2; - - for(i=slen1; i!=0; i--) - if(*srtmp++ != *srtmp2++) return No; - - return Yes; - - } - -} - - -/* - - Compare two filenames. - - The first filename is assumed to be raw i.e. has no project subdirectory appended. - The second is assumed to be ready for use. - - Make a copy of both strings, prefix the copy of the first with the project subdirectory - and convert them to DOS format before the comparison. - -*/ - -int CompareFilenameCH(char *string1, char *string2) - -{ - - char *srtmp1; - char *srtmp2; - int slen1 = 0; - int slen2 = 0; - int i; - char fname1[ImageNameSize]; - char fname2[ImageNameSize]; - - - #if 0 - textprint(" Compare "); textprint(string1); textprint("\n"); - textprint(" with "); textprint(string2); textprint("\n"); - /*WaitForReturn();*/ - #endif - - - /* Make a copy of string 1, adding the project subdirectory */ - - srtmp1 = projectsubdirectory; - srtmp2 = fname1; - while(*srtmp1) *srtmp2++ = *srtmp1++; - srtmp1 = string1; - while(*srtmp1) *srtmp2++ = *srtmp1++; - *srtmp2 = 0; - - /* Make a copy of string 2 */ - - srtmp1 = string2; - srtmp2 = fname2; - while(*srtmp1) *srtmp2++ = *srtmp1++; - *srtmp2 = 0; - - /* How long are they? */ - - srtmp1 = fname1; - while(*srtmp1++ != 0) - slen1++; - - srtmp2 = fname2; - while(*srtmp2++ != 0) - slen2++; - - fname1[slen1] = 0; /* Term */ - fname2[slen2] = 0; - - #if 0 - textprint("slen1 = %d, ", slen1); - textprint("slen2 = %d\n", slen2); - #endif - - #if 0 - textprint(" Compare "); textprint(fname1); textprint("\n"); - textprint(" with "); textprint(fname2); textprint("\n"); - /*WaitForReturn();*/ - #endif - - - GetDOSFilename(fname1); - GetDOSFilename(fname2); - - - if(slen1 != slen2) { - /*textprint("not same\n");*/ - return No; - } - - srtmp1 = fname1; - srtmp2 = fname2; - - #if 0 - textprint(" Compare "); textprint(srtmp1); textprint("\n"); - textprint(" with "); textprint(srtmp2); textprint("\n"); - WaitForReturn(); - #endif - - for(i = slen1; i!=0; i--) { - if(*srtmp1++ != *srtmp2++) { - /*textprint("not same\n");*/ - return No; - } - } - - /*textprint("same\n");*/ - return Yes; - -} - - - - - - - -/* - - Create an RGB table for "palette" - - "GetRemappedPaletteColour()" is an access function for this table - -*/ - - -#define remap_table_size (1 << (remap_table_rgb_bits * 3)) - - -#define cprt_info No -#define cprt_cnt No - - - -int NearestColour(int rs, int gs, int bs, unsigned char *palette) - -{ - - int i; - VECTORCH p0; - VECTORCH p1; - int nearest_index; - int nearest_delta; - int d; - - - p0.vx = rs; - p0.vy = gs; - p0.vz = bs; - - nearest_index = 0; - nearest_delta = bigint; - - for(i = 0; i < 256; i++) { - - p1.vx = palette[0]; - p1.vy = palette[1]; - p1.vz = palette[2]; - - d = FandVD_Distance_3d(&p0, &p1); - - if(d < nearest_delta) { - - nearest_delta = d; - nearest_index = i; - - } - - palette += 3; - - } - - return nearest_index; - -} - - - - - - - - - - -/*************************************************************************/ -/*************************************************************************/ - - - - - -/* - - PC Video Mode Array Functions - -*/ - - -#define m320diag (378 + 6) - - - - - -/* - - PC Video Mode Function Arrays - -*/ - -void (*SetVideoMode[]) (void) = { - -0 - -}; - - - - - - - - - - - - - - - - -/* - - Initialise System and System Variables - -*/ - -void InitialiseSystem(HINSTANCE hInstance, int nCmdShow) - -{ - BOOL rc; - - /* - Pick up processor type - */ - - ProcessorType = ReadProcessorType(); - - if ((ProcessorType == PType_PentiumMMX) || - (ProcessorType == PType_Klamath) || - (ProcessorType == PType_OffTopOfScale)) - MMXAvailable = TRUE; - else - MMXAvailable = FALSE; - - /* - Copy initial requests to current variables, - subject to later modification. - */ - - VideoMode = VideoRequestMode; - WindowMode = WindowRequestMode; - - /* - Initialise dubious restart - system for ModeX emulation - and other problems - */ - - AttemptVideoModeRestart = No; - - VideoRestartMode = NoRestartRequired; - - /* - Potentially a whole suite of caps - functions could be sensibly called - from here, to determine available - sound hardware, network links, 3D - hardware acceleration etc - */ - - /* - Initialise the basic Direct Draw object, - find a hardware 3D capable driver if - possible and appropriate, and - determine what display modes, available - video memory etc exist. - */ - - if (InitialiseDirectDrawObject() - == FALSE) - /* - If we cannot get a video mode, - fail. No point in a non debugging option - for this. - */ - { - ReleaseDirect3D(); - exit(0x997799); - } - - /* - Initialise global to say whether - we think there is an onboard 3D - acceleration card / motherboard - built-in - */ - - TestInitD3DObject(); - -/* - This is (HOPEFULLY!!) now the right - place to put this call. Note that it is - not absolutely certain that we can do test - blits from DirectDraw without setting - a cooperative level, however... And note also - that MMX works better with the back buffer in - system memory... -*/ - TestMemoryAccess(); - - /* Initialise main window, windows procedure etc */ - rc = InitialiseWindowsSystem(hInstance, nCmdShow, WinInitFull); - - /* Initialise input interface */ - memset((void*)KeyboardInput, No, MAX_NUMBER_OF_INPUT_KEYS); - GotAnyKey = No; - - /* launch Direct Input */ - InitialiseDirectInput(); - InitialiseDirectKeyboard(); - InitialiseDirectMouse(); - InitJoysticks(); - - /* Initialise textprint system */ - textprintPosX = 0; - textprintPosY = 0; - #if debug - InitPrintQueue(); - #endif - - #if SUPPORT_MMX - SelectMMXOptions(); - #endif - - { - /* CDF 4/2/97 */ - extern void ConstructOneOverSinTable(void); - - ConstructOneOverSinTable(); - } - -} - - -/* - - Exit the system - -*/ - -void ExitSystem(void) -{ - /* Game specific exit functions */ - ExitGame(); - - - // Added by Mark so that Direct Sound exits cleanly - #if SOUND_ON - ExitSoundSystem(); // In ds_func.cpp - #endif - - /* - Shaft DirectDraw and hit Direct3D - with a blunt Bill. - Note that ReleaseDirect3D is currently - responsible for whacking DirectDraw - and DirectInput as well; I should probably - rename it ReleaseDirectX sometime... - */ - - ReleaseDirect3D(); - - /* Kill windows procedures */ - ExitWindowsSystem(); -} - -/* - Timer functions are based on Windows timer - giving number of millisecond ticks since Windows - was last booted. Note this will wrap round after - Windows has been up continuously for approximately - 49.7 days. This is not considered to be too - significant a limitation... -*/ - - - -void ResetFrameCounter(void) -{ - lastTickCount = timeGetTime(); - - /* KJL 15:03:33 12/16/96 - I'm setting NormalFrameTime too, rather than checking that it's - non-zero everytime I have to divide by it, since it usually is zero on the first frame. */ - NormalFrameTime = 65536 >> 4; - PrevNormalFrameTime = NormalFrameTime; - - RealFrameTime = NormalFrameTime; - FrameRate = 16; - GlobalFrameCounter=0; - CloakingPhase = 0; - - - RouteFinder_CallsThisFrame=0; -} -void FrameCounterHandler(void) -{ - int newTickCount = timeGetTime(); - int fcnt; - - fcnt = newTickCount - lastTickCount; - lastTickCount = newTickCount; - - if (fcnt == 0) - fcnt = 1; /* for safety */ - - FrameRate = TimerFrame / fcnt; - - PrevNormalFrameTime = NormalFrameTime; - NormalFrameTime = DIV_FIXED(fcnt,TimerFrame); - - RealFrameTime = NormalFrameTime; - - { - if (TimeScale!=ONE_FIXED) - { - NormalFrameTime = MUL_FIXED(NormalFrameTime,TimeScale); - } - - } - /* cap NormalFrameTime if frame rate is really low */ - if (NormalFrameTime>16384) NormalFrameTime=16384; - GlobalFrameCounter++; - CloakingPhase += NormalFrameTime>>5; - - RouteFinder_CallsThisFrame=0; -} - -/* - - This jump table has been provided - solely to ensure compatibility with - DOS and other versions. - -*/ - -void (*UpdateScreen[]) (void) = { - - FlipBuffers, - FlipBuffers, - FlipBuffers, - FlipBuffers, - - FlipBuffers, - FlipBuffers, - FlipBuffers, - FlipBuffers, - - FlipBuffers, - FlipBuffers, - FlipBuffers, - FlipBuffers, - - FlipBuffers, - FlipBuffers, - FlipBuffers, - FlipBuffers, - - FlipBuffers, - FlipBuffers, - FlipBuffers, - FlipBuffers, - - FlipBuffers, - FlipBuffers, - FlipBuffers, - FlipBuffers - -}; - - -/* - Not supported in Windows 95 !!! -*/ - - -void PlotPixelTest(int x, int y, unsigned char col) - -{ - -} - - -/* - - Wait for Return Key - - Such a function may not be defined on some platforms - - On Windows 95 the description of this function has - been changed, so that it calls FlushTextprintBuffer - and FlipBuffers before going into the actual - WaitForReturn code. This is necessary if it is to - behave in the same way after a textprint call as it - does on the DOS platform. - -*/ - -void WaitForReturn(void) - -{ - /* Crude but probably serviceable for now */ - long SavedTickCount; - SavedTickCount = lastTickCount; - -/* Display any lingering text */ - FlushTextprintBuffer(); - FlipBuffers(); - - while (!(KeyboardInput[KEY_CR])) - DirectReadKeyboard(); - - lastTickCount = SavedTickCount; -} - - - - -/* - By copying the globals here we guarantee - that game functions will receive a set of - input values updated at a defined time -*/ - - -void ReadUserInput(void) -{ - DirectReadMouse(); - ReadJoysticks(); - DirectReadKeyboard(); -} - -/* - At present all keyboard and mouse input is handled - through project specific functionality in win_func, - and all these functions are therefore empty. Later - we may port to DirectInput, at which point we - may reactivate these. -*/ - - - -void ReadKeyboard(void) - -{ -} - - -void ReadMouse(void) - -{ - - -} - - - -/* - Not NECESSARILY the standard functionality, - but it seems good enough to me... -*/ - -void CursorHome(void) - -{ -/* Reset positions for textprint system */ - textprintPosX = 0; - textprintPosY = 0; -} - - -void GetProjectFilename(char *fname, char *image) -{ - - char *src; - char *dst; - - - src = projectsubdirectory; - dst = fname; - - while(*src) - *dst++ = *src++; - - src = image; - - while(*src) - *dst++ = *src++; - - *dst = 0; - -} - - - - - - - -/* - - Attempts to load the image file. - - Returns a pointer to the image if successful, else zero. - - Image Header is filled out if successful, else ignore it. - - NOTE - - The pointer to the image data is also stored in the image - header. - -*/ - -TEXTURE* LoadImageCH(char *fname, IMAGEHEADER *iheader) -{ - return 0; -} - - - - - - - - - -void ConvertToDDPalette(unsigned char* src, unsigned char* dst, int length, int flags) -{ - int i; - -/* - Copy palette, introducing flags and shifting up - to 8 bit triple -*/ - - for (i=0; i<length; i++) - { - *dst++ = (*src++) << 2; - *dst++ = (*src++) << 2; - *dst++ = (*src++) << 2; - *dst++ = flags; - } -} - -/* - - Platform specific version of "printf()" - - Not all platforms support, or indeed are ABLE to support printf() in its - general form. For this reasons calls to textprint() are made through this - function. - -*/ - -/* - If debug or textprintOn are not defined, these - function defintions are collapsed to a simple - return value, which should collapse to no object - code under optimisation. - The whole issue of turning on or off textprint - beyond this point is hereby left to Kevin and - Chris H to fight to the death about... -*/ - -#if DHMtextprint - - -/* - Dave Malcolm 21/11/96: - - I have rewritten the Win95 textprint routines below. - - It should now support: - - carriage returns are no longer automatic at the end of lines; there is a #define if you want this behaviour back - - carriage return characters cause a carriage return - - wraparound at the right-hand edge of the screen, with textprint() wrapping to the left-hand edge, - and textprintXY() wrapping back to the X coordinate - - clipping at the bottom edge of the screen - - a warning message if text has been lost due to clipping or buffer overflows etc. - - a y-offset that can be used to scroll up and down the text overlay output from textprint -*/ - - /* VERSION SETTINGS: */ - #define AutomaticNewLines No - /* set this to Yes and you will get a \n inserted automatically at the end of each line */ - #if AutomaticNewLines - #error Not yet written... - #endif - - /* LOW LEVEL ASSERTION SUPPORT */ - /* - We cannot use standard assertions in this routine because this routine is called by the standard - assertion routine, and so would run the risk of infinite loops and excitingly obscure bugs. - - For this reason we define a special assert macro. - */ - -#if 1 - #define LOWLEVELASSERT(ignore) -#else - #if debug - - #define LOWLEVELASSERT(x) \ - (void) \ - ( \ - (x) \ - ? 1 : (ReleaseDirect3D(),exit(GlobalAssertCode),0) \ - ) - - #else - /* Assertions are disabled at compile-time: */ - #define LOWLEVELASSERT(ignore) - - #endif -#endif - - - /* - We extract arguments into a buffer, with a dodgy hack to increase it in size to give more defence - against buffer overflows; there seems to be no easy & robust way to give vsprintf() a buffer size... - - This buffer is reset once per string per frame - */ - #define PARANOIA_BYTES (1024) - #define TEXTPRINT_BUFFER_SIZE (MaxMsgChars+PARANOIA_BYTES+1) - static char TextprintBuffer[TEXTPRINT_BUFFER_SIZE]=""; - - /* - - The PRINTQUEUEITEM structure from PLATFORM.H is not used by my system; instead of queueing strings to be - displayed we do it on a character by character basis, with a limit on the total number of chars per frame. - - This limit is set to be (MaxMsgChars*MaxMessages), which gives the same power and more flexibility than the - old system. - - When the queue is full, additional characters get ignored. - - This is queue is reset once per frame. - - */ - - typedef struct daveprintchar { - char CharToPrint; - int x,y; - } DAVEPRINTCHAR; - - #define DHM_PRINT_QUEUE_SIZE (MaxMsgChars*MaxMessages) - - static DAVEPRINTCHAR DHM_PrintQueue[DHM_PRINT_QUEUE_SIZE]; - static int DHM_NumCharsInQueue=0; - - static int fTextLost=No; - static char TextLostMessage[]="textprint warning:TEXT LOST"; - #define TEXT_LOST_X (50) - #define TEXT_LOST_Y (20) - - volatile int textprint_Y_offset=0; - - -/* Dave's version of initialising the print queue */ -void InitPrintQueue(void) -{ - DHM_NumCharsInQueue=0; - fTextLost=No; -} - -/* - - Old systems comment: - Write all messages in buffer to screen - (to be called at end of frame, after surface - / execute buffer unlock in DrawItemListContents, - so that text appears at the front of the back - buffer immediately before the flip). - - This is Dave's version of the same: -*/ - -void FlushTextprintBuffer(void) - -{ - /* PRECONDITION: */ - { - LOWLEVELASSERT(DHM_NumCharsInQueue<DHM_PRINT_QUEUE_SIZE); - } - - /* CODE: */ - { - { - int i; - DAVEPRINTCHAR* pDPR=&DHM_PrintQueue[0]; - - for (i=0; i<DHM_NumCharsInQueue; i++) - { - #if 0 - BlitWin95Char - ( - pDPR->x, - pDPR->y, - pDPR->CharToPrint - ); - #else - D3D_BlitWhiteChar - ( - pDPR->x, - pDPR->y, - pDPR->CharToPrint - ); - #endif - pDPR++; - } - - if (fTextLost) - { - /* Display error message in case test has been lost due to clipping of Y edge, or buffer overflow */ - int i; - int NumChars=strlen(TextLostMessage); - - for (i=0;i<NumChars;i++) - { - // BlitWin95Char(TEXT_LOST_X+(i*CharWidth),TEXT_LOST_Y,TextLostMessage[i]); - } - - fTextLost=No; - } - } - DHM_NumCharsInQueue=0; - - } -} - -static int LastDisplayableXForChars(void) -{ - return ScreenDescriptorBlock.SDB_Width-CharWidth; -} - -static int LastDisplayableYForChars(void) -{ - return ScreenDescriptorBlock.SDB_Height-CharHeight; -} - - -static void DHM_AddToQueue(int x,int y, char Ch) -{ - - if - ( - (y>=0) - && - (y<=LastDisplayableYForChars()) - ) - { - if (DHM_NumCharsInQueue<DHM_PRINT_QUEUE_SIZE) - { - DAVEPRINTCHAR* pDPR=&DHM_PrintQueue[DHM_NumCharsInQueue++]; - /* We insert into the queue at this position, updating the length of the queue */ - - pDPR->x=x; - pDPR->y=y; - pDPR->CharToPrint=Ch; - } - else - { - /* Otherwise the queue if full, we will have to ignore this char; set an error flag so we get a message*/ - fTextLost=Yes; - } - } - else - { - /* Otherwise the text is off the top or bottom of the screen; set an error flag to get a message up*/ - fTextLost=Yes; - } -} - -static int DHM_MoveBufferToQueue(int* pPosX,int* pPosY,int fZeroLeftMargin) -{ - /* - Function takes two integers by reference (using pointers), and outputs whatever is in - the string buffer into the character queue, so that code can be shared by textprint() and textprintXY() - - Returns "number of lines": any carriage returns or word wraps - */ - - /* PRECONDITION */ - { - LOWLEVELASSERT(pPosX); - LOWLEVELASSERT(pPosY); - } - - /* CODE */ - { - int NumLines=0; - - int LeftMarginX; - - if (fZeroLeftMargin) - { - LeftMarginX=0; - } - else - { - LeftMarginX=*pPosX; - } - - - - /* Iterate through the string in the buffer, adding the individual characters to the queue */ - { - char* pCh=&TextprintBuffer[0]; - int SafetyCount=0; - - while - ( - ((*pCh)!='\0') - && - ((SafetyCount++)<MaxMsgChars) - ) - { - switch (*pCh) - { - case '\n': - { - /* Wrap around to next line.,. */ - (*pPosY)+=HUD_FONT_HEIGHT; - (*pPosX)=LeftMarginX; - NumLines++; - - } - break; - default: - { - /* It is a standard character or a space */ - DHM_AddToQueue(*pPosX,(*pPosY)+textprint_Y_offset, *pCh); - - (*pPosX)+=AAFontWidths[*pCh];//CharWidthInPixels(*pCh); - - if ((*pPosX)>LastDisplayableXForChars()) - { - /* Wrap around to next line.,. */ - (*pPosY)+=HUD_FONT_HEIGHT; - (*pPosX)=LeftMarginX; - NumLines++; - } - } - } - - /* ...and on to the next character*/ - pCh++; - } - } - - /* Clear the string buffer */ - { - TextprintBuffer[0]='\0'; - } - - return NumLines; - } - -} - - -int textprint(const char* t, ...) -{ - #if (debug && textprintOn) - if - ( - bEnableTextprint - ) - { - /* - Get message string from arguments into buffer... - */ - { - va_list ap; - - va_start(ap, t); - vsprintf(&TextprintBuffer[0], t, ap); - va_end(ap); - } - - /* - Attempt to trap buffer overflows... - */ - { - LOWLEVELASSERT(strlen(TextprintBuffer)<TextprintBuffer); - } - - return DHM_MoveBufferToQueue(&textprintPosX,&textprintPosY,Yes); - - - } - else - { - // Run-time disabling of textprint() - return 0; - } - #else - /* Do nothing; hope the function call gets optimised away */ - return 0; - #endif -} -int PrintDebuggingText(const char* t, ...) -{ - /* - Get message string from arguments into buffer... - */ - { - va_list ap; - - va_start(ap, t); - vsprintf(&TextprintBuffer[0], t, ap); - va_end(ap); - } - - /* - Attempt to trap buffer overflows... - */ - { - LOWLEVELASSERT(strlen(TextprintBuffer)<TextprintBuffer); - } - - return DHM_MoveBufferToQueue(&textprintPosX,&textprintPosY,Yes); -} -int ReleasePrintDebuggingText(const char* t, ...) -{ - /* - Get message string from arguments into buffer... - */ - { - va_list ap; - - va_start(ap, t); - vsprintf(&TextprintBuffer[0], t, ap); - va_end(ap); - } - - /* - Attempt to trap buffer overflows... - */ - { - LOWLEVELASSERT(strlen(TextprintBuffer)<TextprintBuffer); - } - - return DHM_MoveBufferToQueue(&textprintPosX,&textprintPosY,Yes); -} - - -int textprintXY(int x, int y, const char* t, ...) - -{ - #if (debug && textprintOn) - if - ( - bEnableTextprintXY - ) - { - /* - Get message string from arguments into buffer... - */ - { - va_list ap; - - va_start(ap, t); - vsprintf(&TextprintBuffer[0], t, ap); - va_end(ap); - } - - /* - Attempt to trap buffer overflows... - */ - { - LOWLEVELASSERT(strlen(TextprintBuffer)<TextprintBuffer); - } - - { - int localX=x; - int localY=y; - - return DHM_MoveBufferToQueue(&localX,&localY,No); - } - - - } - else - { - // Run-time disabling of textprint() - return 0; - } - #else - { - /* Do nothing; hope the function call gets optimised away */ - - return 0; - } - #endif -} - - - - /* - * - * - - End of Dave Malcolm's text routines; old version is below - - * - * - */ -#else - -/* - NOTE!!!! All this software is intended for debugging - only. It emulates the print interface in any video - mode supported by the engine, but there are limits - - messages will pile up at the bottom of the screen - and overwrite each other, all messages will appear at the - fron in the main screen (NOT clipped to the VDB), messages - will not wrap round if they are longer than a screen line - unless \n is inserted in the print string, and the text colour - is not guaranteed to be white in paletted modes. - So there. -*/ - - -/* - IMPORTANT!!!! - Messages longer than MaxMsgChars are liable - to CRASH this routine. I haven't bothered - to do anything about this on the grounds that - we can't tell how long the message is until after - the vsprintf call, and the crash is likely to - occur in vsprintf itself as it overflows the - buffer. -*/ - -/* - !!!!! FIXME?? - textprints don't seem to appear - in SubWindow mode --- possibly - because the colours in the font - are going to system font colours which - are invisible??? -*/ - -#if (debug && textprintOn) - -int textprint(const char* t, ...) - -{ - int i,j; - va_list ap; - char message[MaxMsgChars]; - char outmsg[MaxMsgChars]; - int numlines; - int CharCount; - int XPos=0; - - va_start(ap, t); - - vsprintf(&message[0], t, ap); - - va_end(ap); - - i = 0; - j = 0; - numlines = 0; - CharCount = strlen(&message[0]); - - /* Read through message buffer until we reach the terminator */ - while ((i < CharCount) && (message[i] != '\0')) - { - outmsg[j++] = message[i]; - XPos+=CharWidth; - /* newline within string */ - if ((message[i] == '\n')||(XPos>ScreenDescriptorBlock.SDB_Width)) - { - /* Display string and reset to start of next line */ - WriteStringToTextBuffer(textprintPosX, textprintPosY, - &outmsg[0]); - textprintPosX = 0; - textprintPosY += HUD_FONT_HEIGHT; - XPos=0; - /* Messages can pile up at bottom of screen */ - if (textprintPosY > ScreenDescriptorBlock.SDB_Height) - textprintPosY = ScreenDescriptorBlock.SDB_Height; - /* Clear output string and reset variables */ - { - int k; - for (k=0; k<(j+1); k++) - outmsg[k] = 0; - } - j = 0; - /* Record number of lines output */ - numlines++; - } - i++; - } - - /* Flush any remaining characters */ - WriteStringToTextBuffer(textprintPosX, textprintPosY, - &outmsg[0]); - textprintPosX = 0; - textprintPosY += HUD_FONT_HEIGHT; - /* Messages can pile up at bottom of screen */ - if (textprintPosY > ScreenDescriptorBlock.SDB_Height) - textprintPosY = ScreenDescriptorBlock.SDB_Height; - numlines++; - - return numlines; -} - -/* - Textprint to defined location on screen - (in screen coordinates for current video - mode). - NOTE!!! Newlines within strings sent to this - function will be IGNORED. -*/ - -int textprintXY(int x, int y, const char* t, ...) - -{ - va_list ap; - char message[MaxMsgChars]; - - va_start(ap, t); - - vsprintf(&message[0], t, ap); - - va_end(ap); - - WriteStringToTextBuffer(x, y, &message[0]); - - return 1; /* for one line */ -} - -#else - -int textprint(const char* t, ...) - -{ - return 0; -} - -int textprintXY(int x, int y, const char* t, ...) - -{ - return 0; -} - -#endif - - -/* - Add string to text buffer -*/ - -void WriteStringToTextBuffer(int x, int y, unsigned char *buffer) - -{ - if (MessagesStoredThisFrame < MaxMessages) - { - strcpy(PrintQueue[MessagesStoredThisFrame].text, buffer); - - PrintQueue[MessagesStoredThisFrame].text_length = strlen(buffer); - PrintQueue[MessagesStoredThisFrame].x = x; - PrintQueue[MessagesStoredThisFrame].y = y; - - MessagesStoredThisFrame++; - } -} - - -/* - Display string of chracters, starting at passed pointer, - at location on screen starting with x and y. - - Patched by Dave Malcolm 20/11/96 so that text wraps around when it reaches the right hand edge of the screen, in - this routine, at least... -*/ - - -void DisplayWin95String(int x, int y, unsigned char *buffer) - -{ - int InitialX=x; - int stlen; - unsigned char ch; - - stlen = strlen(buffer); - - do - { - ch = (unsigned char) *buffer; - BlitWin95Char(x, y, ch); - x += CharWidth; - if (x > (ScreenDescriptorBlock.SDB_Width - - CharWidth)) - { - #if 1 - /* Wrap to new line, based on coordinates for display...*/ - x=InitialX; - y+=HUD_FONT_HEIGHT; - #else - /* Characters will pile up at screen edge */ - x = (ScreenDescriptorBlock.SDB_Width - CharWidth); - #endif - } - - buffer++; - stlen--; - } - while ((ch != '\n') && (ch != '\0') && - (stlen > 0)); -} - -/* - Write all messages in buffer to screen - (to be called at end of frame, after surface - / execute buffer unlock in DrawItemListContents, - so that text appears at the front of the back - buffer immediately before the flip). -*/ - -void FlushTextprintBuffer(void) - -{ - int i; - - for (i=0; i<MessagesStoredThisFrame; i++) - { - if (PrintQueue[i].text_length) - DisplayWin95String(PrintQueue[i].x, - PrintQueue[i].y, PrintQueue[i].text); - - /* - More mystery code from Roxby --- an extra safety - check for printing?? Or a hangover from a linked - list version of the data structure??? - */ - PrintQueue[i].text_length = 0; - } - - MessagesStoredThisFrame = 0; -} - -/* Initialise print queue */ - -void InitPrintQueue(void) - -{ - int i; - - /* Mystery code from Roxby here... */ - for (i=0; i < MaxMessages; i++) - PrintQueue[i].text_length = 0; - - MessagesStoredThisFrame = 0; -} - -#endif - /*end of old version of text routines */ - -/* - Load main, 8 bit paletted, font - (assumed to be on hard drive at present) - and create hi and true colour mode fonts - from it. Note that for this system to work - properly all bits on must be white or similar - in 8 bit mode 222 and Raw256 palettes as well - as mode 8T. -*/ - -/* - MUST be called after GenerateDirectDrawSurface, - i.e. AFTER SetVideoMode. - AND ONLY ONCE!!!! -*/ - -#if debug || PreBeta -extern LPDIRECTDRAWSURFACE lpDDDbgFont; -#endif - - - - - - - - -/* - This function is intended to allow YOU, - the user, to obtain your heart's fondest desires - by one simple call. Money? Love? A better job? - It's all here, you have only to ask... - No, I was lying actually. - In fact, this should allow you to change - display modes cleanly. Pass your request modes - (as normally set up in system.c). For all entries - which you do not want to change, simply pass - the current global value (e.g. ZBufferRequestMode - in the NewZBufferMode entry). - - Note that the function must always be passed the - HINSTANCE and nCmdShow from winmain. -*/ - -/* - Note that this function will NOT - reinitialise the DirectDraw object - or switch to or from a hardware DD - device, but it will release and rebuild - all the Direct3D objects. -*/ - -/* - Note that you MUST be in the right - directory for a texture reload before you - call this, and normal operations CAN change - the directory... -*/ - -/* - NOTE!!! If you start in DirectDraw mode - and go to Direct3D mode, this function - CANNOT POSSIBLY WORK WITHOUT A FULL SHAPE - RELOAD, since the shape data is overwritten - during DirectDraw initialisation!!!! - - NOTE ALSO: TEXTURE RELOAD MAY BE DODGY - WITHOUT A SHAPE RELOAD!!! -*/ - -int ChangeDisplayModes(HINSTANCE hInst, int nCmd, - int NewVideoMode, int NewWindowMode, - int NewZBufferMode, int NewRasterisationMode, - int NewSoftwareScanDrawMode, int NewDXMemoryMode) -{ - BOOL rc; - BOOL ChangeWindow = No; - -/* - Shut down DirectX objects and destroy - the current window, if necessary. -*/ - - if (NewWindowMode != WindowMode) - ChangeWindow = Yes; - - DeallocateAllImages(); - - ReleaseDirect3DNotDD(); - - finiObjectsExceptDD(); - - - if (ChangeWindow) - ExitWindowsSystem(); - -/* Test!! */ - -/* - Set the request modes and actual modes - according to the passed values. -*/ - - VideoRequestMode = NewVideoMode; - WindowRequestMode = NewWindowMode; - ZBufferRequestMode = NewZBufferMode; - RasterisationRequestMode = NewRasterisationMode; - SoftwareScanDrawRequestMode = NewSoftwareScanDrawMode; - DXMemoryRequestMode = NewDXMemoryMode; - - VideoMode = VideoRequestMode; - WindowMode = WindowRequestMode; - - /* this may reconstruct the dd object depending - on the rasterisation request mode and whether - a hardware dd driver is selected or could be - available */ - ChangeDirectDrawObject(); - - /* - Check that our new video mode exists, - and pick a valid option if it doesn't and - we can find one. - */ - - #if CheckVideoModes - if (WindowMode == WindowModeFullScreen) - { - if (!(CheckForVideoModes(VideoMode))) - { - VideoMode = VideoMode_DX_640x480x8; - if (!(CheckForVideoModes(VideoMode))) - { - VideoMode = VideoMode_DX_640x480x15; - if (!(CheckForVideoModes(VideoMode))) - { - ReleaseDirect3D(); // for safety - return FALSE; - } - } - } - } - #endif - -/* - Recreate the window, allowing - for possible change in WindowMode. -*/ - - if (ChangeWindow) - { - rc = InitialiseWindowsSystem(hInst, nCmd, - WinInitChange); - - if (rc == FALSE) - return rc; - } - -/* - Set the video mode again. This - will handle all changes to DirectDraw - objects, all Direct3D initialisation, - and other request modes such as - zbuffering. -*/ - - /* - Err... shutting down and restarting - on a hardware driver appears to - screw up file handling somehow... - umm... but not for Microsoft demos, - obviously... - FIXME!!! - */ - /* test only!!! */ - #if 0 - chdir("d:\3dc"); - #endif - - SetVideoMode[VideoMode](); - -/* - Lose all the textures and reload the - debugging font -*/ - - InitialiseTextures(); - - -/* - Well, we HOPE it's okay... -*/ - - return TRUE; -} - - -/* - Reverse of ConvertToDDPalette, introduced - to maintain internal interfaces only... -*/ - -void ConvertDDToInternalPalette(unsigned char* src, unsigned char* dst, int length) -{ - int i; - -/* - Copy palette, shifting down - to 5 bit triple -*/ - - for (i=0; i<length; i++) - { - *dst++ = (*src++) >> 2; - *dst++ = (*src++) >> 2; - *dst++ = (*src++) >> 2; - } -} - - diff --git a/3dc/win95/item.c b/3dc/win95/item.c deleted file mode 100644 index af4edef..0000000 --- a/3dc/win95/item.c +++ /dev/null @@ -1,306 +0,0 @@ - -#include "3dc.h" -#include "module.h" -#include "inline.h" -#include "krender.h" /* KJL 11:37:53 12/05/96 - new scandraws patch */ - -/* KJL 15:02:50 05/14/97 - new max lighting intensity */ -#define MAX_INTENSITY (65536*4-1) - - -#if StandardShapeLanguage - - -#define UseLocalAssert Yes - -#include "ourasert.h" - -/* - The outputclockwise compile option has been - maintained in case anyone wants to use the existing - triangle array code with counterclockwise ordering. - In the case of Win95, we might want to this if we can ever - persuade the Direct3D rasterisation module to come up - with CULL_CCW set. Note that outputtriangles has now been purged - from the system. -*/ - -#define outputclockwise Yes - -#define use_div_fixed Yes - -#define trip_debugger No - -#if trip_debugger -int testa = 0; -int testb = 100; -int testc = 0; -#endif - -/* - To make scan draws work backwards as - well as forwards, i.e. to cope with - items that would be backface culled - without the no cull flag set, as in racing - game TLOs. - This should now work for all polygon types. -*/ - -#define ReverseDraws Yes - -/* - To optimise scan draws with local variables - explicitly braced to improve compiler - optimisation. - NOTE THIS IS -->ONLY<-- IMPLEMENTED FOR - VIDEOMODETYPE_8, 2DTEXTURE, 3DTEXTURE (LINEAR) - AND 3DTEXTURE (LINEAR_S) AT PRESENT. - AND NOT ALL THE OPTIONS INSIDE THOSE!!! - NOTE ALSO THAT THIS APPEARS TO PRODUCE BAD CODE - WITH WATCOM 10.0 AND -oeitlr, BUT WE HOPE IT WILL - WORK WITH WATCOM 10.6 - -->CRASHES, AS IT HAPPENS!!!<-- -*/ -/* - Prototypes -*/ - - - -/* - - externs for commonly used global variables and arrays - -*/ - - extern int VideoModeType; - extern int VideoModeTypeScreen; - extern int ScanDrawMode; - extern int **ShadingTableArray; - extern unsigned char **PaletteShadingTableArray; - extern VIEWDESCRIPTORBLOCK *Global_VDB_Ptr; - extern unsigned char *ScreenBuffer; - - - - extern IMAGEHEADER *ImageHeaderPtrs[MaxImages]; - extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; - extern long BackBufferPitch; - - /* For multiple execute buffers */ - extern int NumVertices; - - -#endif /* for support3dtextures */ - -/* - - Global Variables - -*/ - - -// int *ItemPointers[maxpolyptrs]; - -// int ItemData[maxpolys * avgpolysize]; - - - int **NextFreeItemPtr; - int *NextFreeItemData; - - int NumFreeItemPtrs; - int NumFreeItemData; - - int ItemCount; /* Instead of a Terminator */ - - POLYHEADER *global_pheader; - - int MIP_Index; - -/* - - Global Variables For Scan Convertors - -*/ - - int ScanData[maxpolys*maxscansize]; - int *NextFreeScanData; - int NumFreeScanData; - int NumScans; - - - int NumPolyPts; - - - -/* - - Item Data Structures. - - Buffer Initialisation and Allocation Functions. - -*/ - - - - -/* - John and Neal's code - Note this is only experimental, for the interface engine, - and therefore does not go through the standard scan draw - function array!!! Also, it only works in VideoModeType_8!!! - USE AT YOUR PERIL!!!! -*/ - -void Draw_Line_VMType_8(VECTOR2D* LineStart, VECTOR2D* LineEnd, int LineColour) -{ - int gosa, tame, hani, dire; - int w, x, y; - int x1, y1, x2, y2; - unsigned char *sbufferptr; - unsigned char colour = LineColour; - - x1 = LineStart->vx; - y1 = LineStart->vy; - x2 = LineEnd->vx; - y2 = LineEnd->vy; - - x1=max(x1,Global_VDB_Ptr->VDB_ClipLeft); - x1=min(x1,Global_VDB_Ptr->VDB_ClipRight-1); - x2=max(x2,Global_VDB_Ptr->VDB_ClipLeft); - x2=min(x2,Global_VDB_Ptr->VDB_ClipRight-1); - - y1=max(y1,Global_VDB_Ptr->VDB_ClipUp); - y1=min(y1,Global_VDB_Ptr->VDB_ClipDown-1); - y2=max(y2,Global_VDB_Ptr->VDB_ClipUp); - y2=min(y2,Global_VDB_Ptr->VDB_ClipDown-1); - - if( abs( x2 - x1 ) < abs( y2 - y1 ) ) { - if( y2 < y1 ) { - w = y1; - y1 = y2; - y2 = w; - w = x1; - x1 = x2; - x2 = w; - } - dire = x1 < x2 ? 1 : -1; - gosa = abs( x2 - x1 ); - hani = y2 - y1; - tame = hani / 2; - x = x1; - for( y = y1; y <= y2; y++ ) { - sbufferptr = - ScreenBuffer + - (y * BackBufferPitch) + x; - *sbufferptr = colour; - tame += gosa; - if( tame > hani ) { - x += dire; - tame -= hani; - } - } - } else { - if( x2 < x1 ) { - w = x1; - x1 = x2; - x2 = w; - w = y1; - y1 = y2; - y2 = w; - } - dire = y1 < y2 ? 1 : -1; - gosa = abs( y2 - y1 ); - hani = x2 - x1; - tame = hani / 2; - y = y1; - for( x = x1; x <= x2; x++ ) { - sbufferptr = - ScreenBuffer + - (y * BackBufferPitch) + x; - *sbufferptr = colour; - tame += gosa; - if( tame > hani ) { - y += dire; - tame -= hani; - } - } - } - -} - - - -/* - - Scan Convert and Draw I_GouraudPolygon - -*/ - - -void Draw_Item_GouraudPolygon(int *itemptr) -{ - if (ScanDrawMode == ScanDrawDirectDraw) - { - KDraw_Item_GouraudPolygon(itemptr); - } -} - - -void Draw_Item_2dTexturePolygon(int *itemptr) -{ - if (ScanDrawMode == ScanDrawDirectDraw) - { - KDraw_Item_2dTexturePolygon(itemptr); - } -} - -void Draw_Item_Gouraud2dTexturePolygon(int *itemptr) -{ - if (ScanDrawMode == ScanDrawDirectDraw) - { - KDraw_Item_Gouraud2dTexturePolygon(itemptr); - } -} - -void Draw_Item_Gouraud3dTexturePolygon(int *itemptr) -{ - if (ScanDrawMode == ScanDrawDirectDraw) - { - KDraw_Item_Gouraud3dTexturePolygon(itemptr); - } -} - -void Draw_Item_ZB_Gouraud3dTexturePolygon(int *itemptr) -{ -} - -void Draw_Item_ZB_GouraudPolygon(int *itemptr) -{ -} - - -void Draw_Item_ZB_2dTexturePolygon(int *itemptr) -{ -} - - -void Draw_Item_ZB_Gouraud2dTexturePolygon(int *itemptr) -{ -} - - - -void Draw_Item_ZB_3dTexturedPolygon(int *itemptr) -{ -} - - - - - - - - - - diff --git a/3dc/win95/list_tem.cpp b/3dc/win95/list_tem.cpp deleted file mode 100644 index 08ead10..0000000 --- a/3dc/win95/list_tem.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#ifdef NDEBUG -; -#else - -char const * list_fail_get_data_from_sentinel = "%s: Tried to get data from sentinel\n"; -char const * list_fail_add_entry_after = "%s: Tried to add after a nonexistent List entry\n"; -char const * list_fail_add_entry_before = "%s: Tried to add before a nonexistent List entry\n"; -char const * list_fail_delete_entry = "%s: Tried to delete a nonexistent List entry\n"; -char const * list_fail_delete_entry_by_pointer = "%s: Tried to delete-by-pointer the sentinel of a list.\n"; -char const * list_fail_alter_entry = "%s: Tried to alter a nonexistent List entry\n"; -char const * list_fail_next_entry_nonexist = "%s: Tried to get entry after nonexistent entry."; -char const * list_fail_next_entry_sentinel = "%s: Tried to get next entry, which is sentinel."; -char const * list_fail_prev_entry_nonexist = "%s: Tried to get entry before nonexistent entry"; -char const * list_fail_prev_entry_sentinel = "%s: Tried to get previous entry, which is sentinel."; -char const * list_fail_last_entry = "%s: Tried to get last entry from a 0-length list.\n."; -char const * list_fail_first_entry = "%s: Tried to get first entry from a 0-length list.\n."; -char const * list_fail_similar_entry = "%s: Tried to get entry similar to nonexistent entry"; -char const * list_fail_delete_last_entry = "%s: Tried to delete last element from an empty List.\n"; -char const * list_fail_delete_first_entry = "%s: Tried to delete first element from an empty List.\n"; -char const * list_fail_operator = "%s: Tried to get entry %d from %d-entry list.\n"; -char const * lit_fail_next = "%s: Tried to take an Iterator past the sentinel of a List.\n"; -char const * lit_fail_operator = "%s: Tried to take contents of sentinel of List\n"; -char const * lit_fail_delete_current = "%s: Tried to delete sentinel of List\n"; -char const * lit_fail_change_current = "%s: Tried to change contents of sentinel of List\n"; - -#endif - - diff --git a/3dc/win95/list_tem.hpp b/3dc/win95/list_tem.hpp deleted file mode 100644 index 1bd59ef..0000000 --- a/3dc/win95/list_tem.hpp +++ /dev/null @@ -1,871 +0,0 @@ -// Doubly linked list class. -// -// Inserts new entries at the *end* of the list -- so add_entry() -// followed by delete_last_entry() will do nothing. -// -// -// Usage: -// -// List<Thing> l; creates an empty list. -// Thing a; List<Thing> l(a); creates a list containing a. -// -// void l.add_entry(Thing a); adds an entry. -// void l.delete_entry(Thing a); removes `a' from the list if it's there, -// aborts if it's not. -// void l.delete_{first,last}_entry deletes the first/last entry. -// Thing l.{first,last}_entry returns the first/last entry. -// bool l.contains(Thing a) is a in the list? -#ifndef list_template_hpp -#define list_template_hpp - -#pragma once - -#include <stdio.h> - -#ifdef _CPPRTTI // run time type information available - #include <typeinfo.h> - #define LIST_TEM_TYPEID_THIS typeid(*this).name() -#else - #define LIST_TEM_TYPEID_THIS "?" -#endif - -#if defined(engine) -// Not all preprocessors do lazy evaluation. DW -#if engine - #include "mem3dc.h" -#endif -#endif - -#ifdef NDEBUG - #define fail if (0) - #define list_fail_get_data_from_sentinel NULL - #define list_fail_add_entry_after NULL - #define list_fail_add_entry_before NULL - #define list_fail_delete_entry NULL - #define list_fail_delete_entry_by_pointer NULL - #define list_fail_alter_entry NULL - #define list_fail_next_entry_nonexist NULL - #define list_fail_next_entry_sentinel NULL - #define list_fail_prev_entry_nonexist NULL - #define list_fail_prev_entry_sentinel NULL - #define list_fail_last_entry NULL - #define list_fail_first_entry NULL - #define list_fail_similar_entry NULL - #define list_fail_delete_last_entry NULL - #define list_fail_delete_first_entry NULL - #define list_fail_operator NULL - #define lit_fail_next NULL - #define lit_fail_operator NULL - #define lit_fail_delete_current NULL - #define lit_fail_change_current NULL -#else - #include "fail.h" - extern char const * list_fail_get_data_from_sentinel; - extern char const * list_fail_add_entry_after; - extern char const * list_fail_add_entry_before; - extern char const * list_fail_delete_entry; - extern char const * list_fail_delete_entry_by_pointer; - extern char const * list_fail_alter_entry; - extern char const * list_fail_next_entry_nonexist; - extern char const * list_fail_next_entry_sentinel; - extern char const * list_fail_prev_entry_nonexist; - extern char const * list_fail_prev_entry_sentinel; - extern char const * list_fail_last_entry; - extern char const * list_fail_first_entry; - extern char const * list_fail_similar_entry; - extern char const * list_fail_delete_last_entry; - extern char const * list_fail_delete_first_entry; - extern char const * list_fail_operator; - extern char const * lit_fail_next; - extern char const * lit_fail_operator; - extern char const * lit_fail_delete_current; - extern char const * lit_fail_change_current; -#endif - -// The first declaration of these class templates was previously as friends -// of List. However, Visual C++ 5 can't parse them unless we give a -// forward declaration first - I think this is a compiler bug - Garry. -template<class T> -class List_Iterator_Forward; -template<class T> -class ConstList_Iterator_Forward; -template<class T> -class List_Iterator_Backward; -template<class T> -class ConstList_Iterator_Backward; -template<class T> -class List_Iterator_Loop; - -template<class T> -struct List_Member; - -template<class T> -struct List_Member_Base -{ - union - { - List_Member_Base<T> *prev; - #ifndef __WATCOMC__ - List_Member<T> *prev_debug; // encourage the debugger to display the list members data - #endif // hopefully casting from base to derived class would not - // cause the actual value of the ptr to change, so the debugger - // will display the information correctly, and this union - // won't cause any kind of performance hit - - //watcom doesn't appear to like this, unfortunately. - - - - }; - union - { - List_Member_Base<T> *next; - #ifndef __WATCOMC__ - List_Member<T> *next_debug; - #endif - }; - virtual ~List_Member_Base() {} -}; - -template<class T> -struct List_Member : public List_Member_Base<T> -{ - T data; - List_Member<T>(const T& n) : data(n) {} -}; - -template<class T> -class List { -private: - List_Member_Base<T> *sentinel; - int n_entries; - mutable T **entry_pointers; - mutable bool calculated_indices; - - T& data(List_Member_Base<T>* e) const - { - if (e == sentinel) - fail(list_fail_get_data_from_sentinel,LIST_TEM_TYPEID_THIS); - return ((List_Member<T>*)e)->data; - } - -public: - List() { - sentinel = new List_Member_Base<T>; - - sentinel->next = sentinel; - sentinel->prev = sentinel; - - n_entries = 0; - entry_pointers = 0; - calculated_indices = false; - } - - List(const T& n) { - sentinel = new List_Member_Base<T>; - sentinel->next = sentinel; - sentinel->prev = sentinel; - n_entries = 0; - entry_pointers = 0; - calculated_indices = false; - - add_entry(n); - } - - List(const List<T>& l) { - sentinel = new List_Member_Base<T>; - - sentinel->next = sentinel; - sentinel->prev = sentinel; - n_entries = 0; - - entry_pointers = 0; - calculated_indices = false; - - List_Member_Base<T>* m = l.sentinel->next; - while (m != l.sentinel) { - add_entry(data(m)); - m = m->next; - } - - } - - List<T>& operator= (const List<T>& l) { - while(n_entries != 0) delete_last_entry(); - if (entry_pointers != 0) - delete[] entry_pointers; - - List_Member_Base<T>* m = l.sentinel->next; - while (m != l.sentinel) { - add_entry(data(m)); - m = m->next; - } - calculated_indices = false; - entry_pointers = 0; - return *this; - } - - ~List() { - while (n_entries != 0) delete_last_entry(); - delete sentinel; - delete[] entry_pointers; - } - - void add_entry(const T& n) { - add_entry_end(n); - } - - void add_entry_end(const T& n) { - List_Member<T> *e = new List_Member<T>(n); - e->next = sentinel; - e->prev = sentinel->prev; - sentinel->prev->next = e; - sentinel->prev = e; - n_entries++; - cleanup(); - } - - void add_entry_start(const T& n) { - List_Member<T> *e = new List_Member<T>(n); - e->prev = sentinel; - e->next = sentinel->next; - sentinel->next->prev = e; - sentinel->next = e; - n_entries++; - cleanup(); - } - - void add_entry_after(const T& n, const T& d) { - List_Member_Base<T> *f = sentinel->next; - while (f != sentinel && data(f) != d) { - f = f->next; - } - if (f == sentinel) { - fail(list_fail_add_entry_after,LIST_TEM_TYPEID_THIS); - } else { - List_Member<T> *e = new List_Member<T>(n); - e->next = f->next; - e->prev = f; - e->next->prev = e; - f->next = e; - n_entries++; - } - cleanup(); - } - - void add_entry_before(const T& n, const T& d) { - List_Member_Base<T> *f = sentinel->next; - while (f != sentinel && data(f) != d) { - f = f->next; - } - if (f == sentinel) { - fail(list_fail_add_entry_before,LIST_TEM_TYPEID_THIS); - } else { - List_Member<T> *e = new List_Member<T>(n); - e->prev = f->prev; - e->next = f; - e->prev->next = e; - f->prev = e; - n_entries++; - } - cleanup(); - } - - void delete_entry(const T& d) { - List_Member_Base<T> *e = sentinel->next; - while (e != sentinel && data(e) != d && e != sentinel) { - e = e->next; - } - if (e == sentinel) { - fail(list_fail_delete_entry,LIST_TEM_TYPEID_THIS); - } else { - e->prev->next = e->next; - e->next->prev = e->prev; - delete e; - } - n_entries--; - cleanup(); - } - - void delete_entry_backward(const T& d) { - List_Member_Base<T> *e = sentinel->prev; - while (e != sentinel && data(e) != d && e != sentinel) { - e = e->prev; - } - if (e == sentinel) { - fail(list_fail_delete_entry,LIST_TEM_TYPEID_THIS); - } else { - e->prev->next = e->next; - e->next->prev = e->prev; - delete e; - } - n_entries--; - cleanup(); - } - - void delete_entry_by_pointer(List_Member_Base<T>* l) { - if (l == sentinel) - fail(list_fail_delete_entry_by_pointer,LIST_TEM_TYPEID_THIS); - l->next->prev = l->prev; - l->prev->next = l->next; - delete l; - l = 0; // so we get a seg if we try and reuse it - n_entries--; - cleanup(); - } - - void alter_entry(const T& od, const T& nd) { - List_Member_Base<T> *e = sentinel->next; - while (e != sentinel && data(e) != od) { - e = e->next; - } - if (e == sentinel) { - fail(list_fail_alter_entry,LIST_TEM_TYPEID_THIS); - } else { - // Remove this entry, and put a new one in it's place. We can't - // just do e->data = nd, because that's assignment, and we don't - // want to require an assignment operator to be defined for - // every thing that we put on a list. - List_Member<T> * n = new List_Member<T>(nd); - e->prev->next = n; - e->next->prev = n; - n->next = e->next; - n->prev = e->prev; - delete e; - } - cleanup(); - } - - T next_entry(const T& d) const { - List_Member_Base<T> *e = sentinel->next; - while (e != sentinel && data(e) != d && e != sentinel) { - e = e->next; - } - if (e == sentinel) { - fail(list_fail_next_entry_nonexist,LIST_TEM_TYPEID_THIS); - } else { - if (e->next == sentinel) - fail(list_fail_next_entry_sentinel,LIST_TEM_TYPEID_THIS); - return data(e->next); - } - return data(e->next); - } - - T prev_entry(const T& d) const { - List_Member_Base<T> *e = sentinel->next; - while (e!= sentinel && data(e) != d) { - e = e->next; - } - if (e == sentinel) { - fail(list_fail_prev_entry_nonexist,LIST_TEM_TYPEID_THIS); - } else { - if (e->prev == sentinel) - fail(list_fail_prev_entry_sentinel,LIST_TEM_TYPEID_THIS); - return data(e->prev); - } - return data(e->prev); - } - - T const & similar_entry(T const& d) const - { - List_Member_Base<T> *e = sentinel->next; - while (e != sentinel) - { - if (data(e) == d) - break; - e = e->next; - - } - if (e == sentinel) - { - fail(list_fail_similar_entry,LIST_TEM_TYPEID_THIS); - } - return data(e); - } - - bool contains(const T& d) { - List_Member_Base<T> *e = sentinel->next; - while (e != sentinel && data(e) != d) { - e = e->next; - } - if (e == sentinel) return false; - else return true; - } - - void delete_last_entry() { - if (sentinel->prev == sentinel) { - fail(list_fail_delete_last_entry,LIST_TEM_TYPEID_THIS); - } else { - // aiee. These lines work, but are a bit hairy. - - sentinel->prev = sentinel->prev->prev; - delete sentinel->prev->next; - sentinel->prev->next = sentinel; - n_entries--; - } - cleanup(); - } - - void delete_first_entry() { - if (sentinel->next == sentinel) { - fail(list_fail_delete_last_entry,LIST_TEM_TYPEID_THIS); - } else { - sentinel->next = sentinel->next->next; - delete sentinel->next->prev; - sentinel->next->prev = sentinel; - n_entries--; - } - cleanup(); - } - - T const & operator[](int i) const { - if (i < 0 || i >= n_entries) - fail(list_fail_operator,LIST_TEM_TYPEID_THIS, i+1, n_entries); - - if (!calculated_indices) { - if (entry_pointers != 0) - delete[] entry_pointers; - entry_pointers = new T*[n_entries+1]; - List_Member_Base<T>*e = sentinel->next; - int j = 0; - while (e != sentinel) { - entry_pointers[j] = &data(e); - e = e->next; - j++; - } - calculated_indices = true; - } - return *entry_pointers[i]; - } - - T & last_entry() - { - if (n_entries == 0) - fail(list_fail_last_entry,LIST_TEM_TYPEID_THIS); - return data(sentinel->prev); - } - - T const & last_entry() const - { - if (n_entries == 0) - fail(list_fail_last_entry,LIST_TEM_TYPEID_THIS); - return data(sentinel->prev); - } - - T & first_entry() - { - if (n_entries == 0) - fail(list_fail_first_entry,LIST_TEM_TYPEID_THIS); - return data(sentinel->next); - } - - T const & first_entry() const - { - if (n_entries == 0) - fail(list_fail_first_entry,LIST_TEM_TYPEID_THIS); - return data(sentinel->next); - } - - int size() const { return n_entries; } - - void cleanup() { calculated_indices = false; if (entry_pointers != 0) delete[] entry_pointers; entry_pointers = 0;} - - bool operator==(const List <T> &l1) const - { - if (n_entries != l1.n_entries) return false; - for (List_Member_Base<T> * e = sentinel->next, *e1 = l1.sentinel->next; e != sentinel; e = e->next, e1 = e1->next) - { - if (((List_Member<T> *)e)->data != ((List_Member<T> *)e1)->data) return false; - } - return true; - } - - bool operator!=(const List <T> &l1) const - { - if (n_entries != l1.n_entries) return true; - for (List_Member_Base<T> * e = sentinel->next, *e1 = l1.sentinel->next; e != sentinel; e = e->next, e1 = e1->next) - { - if (((List_Member<T> *)e)->data != ((List_Member<T> *)e1)->data) return true; - } - return false; - } - - friend class List_Iterator_Forward<T>; - friend class ConstList_Iterator_Forward<T>; - friend class List_Iterator_Backward<T>; - friend class ConstList_Iterator_Backward<T>; - friend class List_Iterator_Loop<T>; -}; - -// Use List_Iterator_{Forward,Backward} as follows: -// -// for(List_Iterator_Forward<T*> oi(&(List_of_T*)); // a _pointer_ -// // to the list. -// !oi.done(); -// oi.next() ) { -// do_something( oi() ) ; -// } -// -// First entry is the one past the sentinel, and next() and -// operator() fail if you try and iterate too far; check if it's -// done() before doing anything else, basically. -// -// As it's a doubly-linked list, we can go backwards and -// forwards. next() takes us to the entry that the type of iterator -// suggests; un_next() takes us in the other direction. un_next() is -// an ugly name, but next() and prev() are too suggestive of a -// particular direction. - -template<class T> -class List_Iterator_Forward -{ -private: - union - { - List_Member_Base<T> *m; - List_Member<T> *m_debug; // encourage the debugger to display the list members data - // hopefully casting from base to derived class would not - // cause the actual value of the ptr to change, so the debugger - // will display the information correctly, and this union - // won't cause any kind of performance hit - }; - List<T> *l; - -public: - List_Iterator_Forward() {} - List_Iterator_Forward(List<T> *list) { l = list; m = l->sentinel->next; } - - void next() { - if (m != l->sentinel) { - m = m->next; - } else - fail(lit_fail_next,LIST_TEM_TYPEID_THIS); - } - - void un_next() { - if (m != l->sentinel) { - m = m->prev; - } else - fail(lit_fail_next,LIST_TEM_TYPEID_THIS); - } - - T & operator() () const { - if (m == l->sentinel) - fail(lit_fail_operator,LIST_TEM_TYPEID_THIS); - return l->data(m); - } - - void delete_current() { - if (m != l->sentinel) { - m = m->next; - l->delete_entry_by_pointer(m->prev); - } else - fail(lit_fail_delete_current,LIST_TEM_TYPEID_THIS); - } - - void change_current(T const &new_val) const { - if (m != l->sentinel) { - // Delete the current member out of the list, put a new one in. - - List_Member<T> * n = new List_Member<T>(new_val); - m->prev->next = n; - m->next->prev = n; - n->next = m->next; - n->prev = m->prev; - delete m; - *(List_Member_Base<T> **)&m =n; // or we're pointing at the thing we just deleted. - l->cleanup(); // because it's changed, but the List doesn't know that. - } else - fail(lit_fail_change_current,LIST_TEM_TYPEID_THIS); - } - - bool done() { if (m == l->sentinel) return true; else return false; } - void restart() { m = l->sentinel->next; } - // Go to the end of the list. - void end() { m = l->sentinel->prev; } -}; - -#define LIF List_Iterator_Forward - -template<class T> -class ConstList_Iterator_Forward -{ - private: - union - { - List_Member_Base<T> *m; - List_Member<T> *m_debug; // encourage the debugger to display the list members data - }; - List<T> const *l; - - public: - ConstList_Iterator_Forward(List<T> const *list) { l = list; m = l->sentinel->next; } - ConstList_Iterator_Forward(){} - - void next() { - if (m == l->sentinel) { - fail(lit_fail_next,LIST_TEM_TYPEID_THIS); - } - m = m->next; - } - - void un_next() { - if (m == l->sentinel) { - fail(lit_fail_next,LIST_TEM_TYPEID_THIS); - } - m = m->prev; - } - - T const & operator() () const { - if (m == l->sentinel) - fail(lit_fail_operator,LIST_TEM_TYPEID_THIS); - return l->data(m); - } - - #if 0 // shouldn't really be available on a const list - void change_current(T const & new_val) const { - if (m != l->sentinel) { - m->data = new_val; - } else - fail(lit_fail_change_current,LIST_TEM_TYPEID_THIS); - } - #endif - - bool done() const { if (m == l->sentinel) return true; else return false; } - void restart() { m = l->sentinel->next; } - // Go to the end of the list. - void end() { m = l->sentinel->prev; } -}; - -#define CLIF ConstList_Iterator_Forward - -template<class T> -class List_Iterator_Backward -{ -private: - union - { - List_Member_Base<T> *m; - List_Member<T> *m_debug; // encourage the debugger to display the list members data - }; - List<T> *l; - -public: - List_Iterator_Backward() {} - List_Iterator_Backward(List<T> *list) { l = list; m = l->sentinel->prev; } - - void next() { - if (m != l->sentinel) { - m = m->prev; - } else - fail(lit_fail_next,LIST_TEM_TYPEID_THIS); - } - - void un_next() { - if (m != l->sentinel) { - m = m->next; - } else - fail(lit_fail_next,LIST_TEM_TYPEID_THIS); - } - - T & operator() () const { - if (m == l->sentinel) - fail(lit_fail_operator,LIST_TEM_TYPEID_THIS); - return l->data(m); - } - - void delete_current() { - if (m != l->sentinel) { - m = m->prev; - l->delete_entry_by_pointer(m->next); - } else - fail(lit_fail_delete_current,LIST_TEM_TYPEID_THIS); - } - - void change_current(T const & new_val) { - if (m != l->sentinel) { - // Delete the current member out of the list, put a new one in. - - List_Member<T> * n = new List_Member<T>(new_val); - m->prev->next = n; - m->next->prev = n; - n->next = m->next; - n->prev = m->prev; - delete m; - m = n; // or we're pointing at the thing we just deleted. - l->cleanup(); // because it's changed, but the List doesn't know that. - } else - fail(lit_fail_change_current,LIST_TEM_TYPEID_THIS); - } - - bool done() { if (m == l->sentinel) return true; else return false; } - void restart() { m = l->sentinel->prev; } - // Go to the end of the list. - void end() { m = l->sentinel->prev; } -}; - -#define LIB List_Iterator_Backward - -template<class T> -class ConstList_Iterator_Backward -{ - private: - union - { - List_Member_Base<T> *m; - List_Member<T> *m_debug; // encourage the debugger to display the list members data - }; - List<T> const *l; - - public: - ConstList_Iterator_Backward(List<T> const *list) { l = list; m = l->sentinel->prev; } - ConstList_Iterator_Backward(){} - - void next() { - if (m == l->sentinel) { - fail(lit_fail_next,LIST_TEM_TYPEID_THIS); - } - m = m->prev; - } - - void un_next() { - if (m == l->sentinel) { - fail(lit_fail_next,LIST_TEM_TYPEID_THIS); - } - m = m->next; - } - - T const & operator() () const { - if (m == l->sentinel) - fail(lit_fail_operator,LIST_TEM_TYPEID_THIS); - return l->data(m); - } - - #if 0 // shouldn't really be available on a const list - void change_current(T const & new_val) const { - if (m != l->sentinel) { - m->data = new_val; - } else - fail(lit_fail_change_current,LIST_TEM_TYPEID_THIS); - } - #endif - - bool done() const { if (m == l->sentinel) return true; else return false; } - void restart() { m = l->sentinel->prev; } - // Go to the end of the list. - void end() { m = l->sentinel->prev; } -}; - -#define CLIB ConstList_Iterator_Backward - -/* - A looping list iterator class : - next from the last member will go to the first - previous from the first member will go to the last -*/ - -template<class T> -class List_Iterator_Loop -{ - private: - union - { - List_Member_Base<T> *m; - List_Member<T> *m_debug; // encourage the debugger to display the list members data - }; - List<T> *l; - - public: - List_Iterator_Loop(List<T> *list) { l = list; m = l->sentinel->next; } - - void next() { - m=m->next; - if (m == l->sentinel) { - m = m->next; - } - } - - void previous() { - m=m->prev; - if (m == l->sentinel) { - m = m->prev; - } - } - - T const & operator() () { - if (m == l->sentinel) - { - m=m->next;//needed in case iterator was created before anything was added to the list - if (m == l->sentinel) - { - fail(lit_fail_operator,LIST_TEM_TYPEID_THIS); - } - } - return l->data(m); - } - - void delete_current() { - if (m == l->sentinel) - { - m=m->next;//needed in case iterator was created before anything was added to the list - if (m == l->sentinel) - { - fail(lit_fail_delete_current,LIST_TEM_TYPEID_THIS); - } - } - m = m->next; - l->delete_entry_by_pointer(m->prev); - } - - - void change_current(T const & new_val) - { - if (m == l->sentinel) - m=m->next;//needed in case iterator was created before anything was added to the list - - if (m != l->sentinel) - { - // Delete the current member out of the list, put a new one in. - List_Member<T> * n = new List_Member<T>(new_val); - m->prev->next = n; - m->next->prev = n; - n->next = m->next; - n->prev = m->prev; - delete m; - m = n; // or we're pointing at the thing we just deleted. - l->cleanup(); // because it's changed, but the List doesn't know that. - } - else - fail(lit_fail_change_current,LIST_TEM_TYPEID_THIS); - } - - // Go to the start of the list. - void restart() { m = l->sentinel->next; } - - // Go to the end of the list. - void end() { m = l->sentinel->prev; } - - // Is it on the last entry. - bool at_last() const { if (m == l->sentinel->prev) return true; else return false; } - - // Get the next entry but done move the pointer. - T const & get_next() { - if (m->next == l->sentinel) - { - if (m->next->next == l->sentinel) - { - fail(lit_fail_operator,LIST_TEM_TYPEID_THIS); - } - return l->data(m->next->next); - } - return l->data(m->next); - } -}; - -#define LIL List_Iterator_Loop - -#ifdef NDEBUG - #undef fail // allow other code to have local variables called or differently scoped 'fail' -#endif - -#endif diff --git a/3dc/win95/md5.c b/3dc/win95/md5.c deleted file mode 100644 index a71a3c3..0000000 --- a/3dc/win95/md5.c +++ /dev/null @@ -1,364 +0,0 @@ -/* md5.c - Functions to compute MD5 message digest of files or memory blocks - according to the definition of MD5 in RFC 1321 from April 1992. - Copyright (C) 1995 Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - -/* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>. */ -#define STDC_HEADERS 1 - -#include "advwin32.h" - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <sys/types.h> - -#if STDC_HEADERS -# include <stdlib.h> -# include <string.h> -#else -# ifndef HAVE_MEMCPY -# define memcpy(d, s, n) bcopy ((s), (d), (n)) -# endif -#endif - -#include "md5.h" - -#ifdef WORDS_BIGENDIAN -# define SWAP(n) \ - (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24)) -#else -# define SWAP(n) (n) -#endif - - -/* This array contains the bytes used to pad the buffer to the next - 64-byte boundary. (RFC 1321, 3.1: Step 1) */ -static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ }; - - -/* Initialize structure containing state of computation. - (RFC 1321, 3.3: Step 3) */ -void -md5_init_ctx (struct md5_ctx *ctx) -{ - ctx->A = 0x67452301; - ctx->B = 0xefcdab89; - ctx->C = 0x98badcfe; - ctx->D = 0x10325476; -} - -/* Put result from CTX in first 16 bytes following RESBUF. The result must - be in little endian byte order. */ -void * -md5_read_ctx(const struct md5_ctx *ctx, void *resbuf) -{ - ((md5_uint32 *) resbuf)[0] = SWAP (ctx->A); - ((md5_uint32 *) resbuf)[1] = SWAP (ctx->B); - ((md5_uint32 *) resbuf)[2] = SWAP (ctx->C); - ((md5_uint32 *) resbuf)[3] = SWAP (ctx->D); - - return resbuf; -} - -/* Compute MD5 message digest for bytes read from STREAM. The - resulting message digest number will be written into the 16 bytes - beginning at RESBLOCK. */ -#ifdef _MSC_VER -#pragma warning(disable: 4701) -#endif - -int md5_stream(FILE *stream, void *resblock) -{ - /* Important: BLOCKSIZE must be a multiple of 64. */ -#define BLOCKSIZE 64 - struct md5_ctx ctx; - md5_uint32 len[2]; - char buffer[BLOCKSIZE + 72]; - size_t pad, sum; - - /* Initialize the computation context. */ - md5_init_ctx (&ctx); - - len[0] = 0; - len[1] = 0; - - /* Iterate over full file contents. */ - while (1) - { - /* We read the file in blocks of BLOCKSIZE bytes. One call of the - computation function processes the whole buffer so that with the - next round of the loop another block can be read. */ - size_t n; - sum = 0; - - /* Read block. Take care for partial reads. */ - do - { - n = fread (buffer, 1, BLOCKSIZE - sum, stream); - - sum += n; - } - while (sum < BLOCKSIZE && n != 0); - if (n == 0 && ferror (stream)) - return 1; - - /* RFC 1321 specifies the possible length of the file up to 2^64 bits. - Here we only compute the number of bytes. Do a double word - increment. */ - len[0] += sum; - if (len[0] < sum) - ++len[1]; - - /* If end of file is reached, end the loop. */ - if (n == 0) - break; - - /* Process buffer with BLOCKSIZE bytes. Note that - BLOCKSIZE % 64 == 0 - */ - md5_process_block (buffer, BLOCKSIZE, &ctx); - } - - /* We can copy 64 byte because the buffer is always big enough. FILLBUF - contains the needed bits. */ - memcpy (&buffer[sum], fillbuf, 64); - - /* Compute amount of padding bytes needed. Alignment is done to - (N + PAD) % 64 == 56 - There is always at least one byte padded. I.e. even the alignment - is correctly aligned 64 padding bytes are added. */ - pad = sum & 63; - pad = pad >= 56 ? 64 + 56 - pad : 56 - pad; - - /* Put the 64-bit file length in *bits* at the end of the buffer. */ - *(md5_uint32 *) &buffer[sum + pad] = SWAP (len[0] << 3); - *(md5_uint32 *) &buffer[sum + pad + 4] = SWAP ((len[1] << 3) - | (len[0] >> 29)); - - /* Process last bytes. */ - md5_process_block (buffer, sum + pad + 8, &ctx); - - /* Construct result in desired memory. */ - md5_read_ctx (&ctx, resblock); - return 0; -} -#ifdef _MSC_VER -#pragma warning(default: 4701) -#endif - -/* Compute MD5 message digest for LEN bytes beginning at BUFFER. The - result is always in little endian byte order, so that a byte-wise - output yields to the wanted ASCII representation of the message - digest. */ -void * -md5_buffer (const char *buffer, size_t len, void *resblock) -{ - struct md5_ctx ctx; - char restbuf[64 + 72]; - size_t blocks = len & ~63; - size_t pad, rest; - - /* Initialize the computation context. */ - md5_init_ctx (&ctx); - - /* Process whole buffer but last len % 64 bytes. */ - md5_process_block (buffer, blocks, &ctx); - - /* REST bytes are not processed yet. */ - rest = len - blocks; - /* Copy to own buffer. */ - memcpy (restbuf, &buffer[blocks], rest); - /* Append needed fill bytes at end of buffer. We can copy 64 byte - because the buffer is always big enough. */ - memcpy (&restbuf[rest], fillbuf, 64); - - /* PAD bytes are used for padding to correct alignment. Note that - always at least one byte is padded. */ - pad = rest >= 56 ? 64 + 56 - rest : 56 - rest; - - /* Put length of buffer in *bits* in last eight bytes. */ - *(md5_uint32 *) &restbuf[rest + pad] = (md5_uint32) SWAP (len << 3); - *(md5_uint32 *) &restbuf[rest + pad + 4] = (md5_uint32) SWAP (len >> 29); - - /* Process last bytes. */ - md5_process_block (restbuf, rest + pad + 8, &ctx); - - /* Put result in desired memory area. */ - return md5_read_ctx (&ctx, resblock); -} - - -/* These are the four functions used in the four steps of the MD5 algorithm - and defined in the RFC 1321. The first function is a little bit optimized - (as found in Colin Plumbs public domain implementation). */ -/* #define FF(b, c, d) ((b & c) | (~b & d)) */ -#define FF(b, c, d) (d ^ (b & (c ^ d))) -#define FG(b, c, d) FF (d, b, c) -#define FH(b, c, d) (b ^ c ^ d) -#define FI(b, c, d) (c ^ (b | ~d)) - -/* Process LEN bytes of BUFFER, accumulating context into CTX. - It is assumed that LEN % 64 == 0. */ - -void -md5_process_block (const void *buffer, size_t len, struct md5_ctx *ctx) -{ - md5_uint32 correct_words[16]; - const md5_uint32 *words = buffer; - size_t nwords = len / sizeof (md5_uint32); - const md5_uint32 *endp = words + nwords; - md5_uint32 A = ctx->A; - md5_uint32 B = ctx->B; - md5_uint32 C = ctx->C; - md5_uint32 D = ctx->D; - - /* Process all bytes in the buffer with 64 bytes in each round of - the loop. */ - while (words < endp) - { - md5_uint32 *cwp = correct_words; - md5_uint32 A_save = A; - md5_uint32 B_save = B; - md5_uint32 C_save = C; - md5_uint32 D_save = D; - - /* First round: using the given function, the context and a constant - the next context is computed. Because the algorithms processing - unit is a 32-bit word and it is determined to work on words in - little endian byte order we perhaps have to change the byte order - before the computation. To reduce the work for the next steps - we store the swapped words in the array CORRECT_WORDS. */ - -#define OP(a, b, c, d, s, T) \ - do \ - { \ - a += FF (b, c, d) + (*cwp++ = SWAP (*words)) + T; \ - ++words; \ - CYCLIC (a, s); \ - a += b; \ - } \ - while (0) - - /* It is unfortunate that C does not provide an operator for - cyclic rotation. Hope the C compiler is smart enough. */ -#define CYCLIC(w, s) (w = (w << s) | (w >> (32 - s))) - - /* Before we start, one word to the strange constants. - They are defined in RFC 1321 as - - T[i] = (int) (4294967296.0 * fabs (sin (i))), i=1..64 - */ - - /* Round 1. */ - OP (A, B, C, D, 7, 0xd76aa478); - OP (D, A, B, C, 12, 0xe8c7b756); - OP (C, D, A, B, 17, 0x242070db); - OP (B, C, D, A, 22, 0xc1bdceee); - OP (A, B, C, D, 7, 0xf57c0faf); - OP (D, A, B, C, 12, 0x4787c62a); - OP (C, D, A, B, 17, 0xa8304613); - OP (B, C, D, A, 22, 0xfd469501); - OP (A, B, C, D, 7, 0x698098d8); - OP (D, A, B, C, 12, 0x8b44f7af); - OP (C, D, A, B, 17, 0xffff5bb1); - OP (B, C, D, A, 22, 0x895cd7be); - OP (A, B, C, D, 7, 0x6b901122); - OP (D, A, B, C, 12, 0xfd987193); - OP (C, D, A, B, 17, 0xa679438e); - OP (B, C, D, A, 22, 0x49b40821); - - /* For the second to fourth round we have the possibly swapped words - in CORRECT_WORDS. Redefine the macro to take an additional first - argument specifying the function to use. */ -#undef OP -#define OP(f, a, b, c, d, k, s, T) \ - do \ - { \ - a += f (b, c, d) + correct_words[k] + T; \ - CYCLIC (a, s); \ - a += b; \ - } \ - while (0) - - /* Round 2. */ - OP (FG, A, B, C, D, 1, 5, 0xf61e2562); - OP (FG, D, A, B, C, 6, 9, 0xc040b340); - OP (FG, C, D, A, B, 11, 14, 0x265e5a51); - OP (FG, B, C, D, A, 0, 20, 0xe9b6c7aa); - OP (FG, A, B, C, D, 5, 5, 0xd62f105d); - OP (FG, D, A, B, C, 10, 9, 0x02441453); - OP (FG, C, D, A, B, 15, 14, 0xd8a1e681); - OP (FG, B, C, D, A, 4, 20, 0xe7d3fbc8); - OP (FG, A, B, C, D, 9, 5, 0x21e1cde6); - OP (FG, D, A, B, C, 14, 9, 0xc33707d6); - OP (FG, C, D, A, B, 3, 14, 0xf4d50d87); - OP (FG, B, C, D, A, 8, 20, 0x455a14ed); - OP (FG, A, B, C, D, 13, 5, 0xa9e3e905); - OP (FG, D, A, B, C, 2, 9, 0xfcefa3f8); - OP (FG, C, D, A, B, 7, 14, 0x676f02d9); - OP (FG, B, C, D, A, 12, 20, 0x8d2a4c8a); - - /* Round 3. */ - OP (FH, A, B, C, D, 5, 4, 0xfffa3942); - OP (FH, D, A, B, C, 8, 11, 0x8771f681); - OP (FH, C, D, A, B, 11, 16, 0x6d9d6122); - OP (FH, B, C, D, A, 14, 23, 0xfde5380c); - OP (FH, A, B, C, D, 1, 4, 0xa4beea44); - OP (FH, D, A, B, C, 4, 11, 0x4bdecfa9); - OP (FH, C, D, A, B, 7, 16, 0xf6bb4b60); - OP (FH, B, C, D, A, 10, 23, 0xbebfbc70); - OP (FH, A, B, C, D, 13, 4, 0x289b7ec6); - OP (FH, D, A, B, C, 0, 11, 0xeaa127fa); - OP (FH, C, D, A, B, 3, 16, 0xd4ef3085); - OP (FH, B, C, D, A, 6, 23, 0x04881d05); - OP (FH, A, B, C, D, 9, 4, 0xd9d4d039); - OP (FH, D, A, B, C, 12, 11, 0xe6db99e5); - OP (FH, C, D, A, B, 15, 16, 0x1fa27cf8); - OP (FH, B, C, D, A, 2, 23, 0xc4ac5665); - - /* Round 4. */ - OP (FI, A, B, C, D, 0, 6, 0xf4292244); - OP (FI, D, A, B, C, 7, 10, 0x432aff97); - OP (FI, C, D, A, B, 14, 15, 0xab9423a7); - OP (FI, B, C, D, A, 5, 21, 0xfc93a039); - OP (FI, A, B, C, D, 12, 6, 0x655b59c3); - OP (FI, D, A, B, C, 3, 10, 0x8f0ccc92); - OP (FI, C, D, A, B, 10, 15, 0xffeff47d); - OP (FI, B, C, D, A, 1, 21, 0x85845dd1); - OP (FI, A, B, C, D, 8, 6, 0x6fa87e4f); - OP (FI, D, A, B, C, 15, 10, 0xfe2ce6e0); - OP (FI, C, D, A, B, 6, 15, 0xa3014314); - OP (FI, B, C, D, A, 13, 21, 0x4e0811a1); - OP (FI, A, B, C, D, 4, 6, 0xf7537e82); - OP (FI, D, A, B, C, 11, 10, 0xbd3af235); - OP (FI, C, D, A, B, 2, 15, 0x2ad7d2bb); - OP (FI, B, C, D, A, 9, 21, 0xeb86d391); - - /* Add the starting values of the context. */ - A += A_save; - B += B_save; - C += C_save; - D += D_save; - } - - /* Put checksum in context given as argument. */ - ctx->A = A; - ctx->B = B; - ctx->C = C; - ctx->D = D; -} diff --git a/3dc/win95/md5.h b/3dc/win95/md5.h deleted file mode 100644 index 2306a7e..0000000 --- a/3dc/win95/md5.h +++ /dev/null @@ -1,125 +0,0 @@ - -#ifdef __cplusplus -extern "C"{ -#endif - -/* md5.h - Declaration of functions and data types used for MD5 sum - computing library functions. - Copyright (C) 1995 Free Software Foundation, Inc. - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ - -#ifndef _MD5_H -#define _MD5_H - -#include <stdio.h> - -#if defined HAVE_LIMITS_H || _LIBC -# include <limits.h> -#endif - -/* The following contortions are an attempt to use the C preprocessor - to determine an unsigned integral type that is 32 bits wide. An - alternative approach is to use autoconf's AC_CHECK_SIZEOF macro, but - doing that would require that the configure script compile and *run* - the resulting executable. Locally running cross-compiled executables - is usually not possible. */ - -#if defined __STDC__ && __STDC__ -# define UINT_MAX_32_BITS 4294967295U -#else -# define UINT_MAX_32_BITS 0xFFFFFFFF -#endif - -/* If UINT_MAX isn't defined, assume it's a 32-bit type. - This should be valid for all systems GNU cares about because - that doesn't include 16-bit systems, and only modern systems - (that certainly have <limits.h>) have 64+-bit integral types. */ - -#ifndef UINT_MAX -# define UINT_MAX UINT_MAX_32_BITS -#endif - -#if UINT_MAX == UINT_MAX_32_BITS - typedef unsigned int md5_uint32; -#else -# if USHRT_MAX == UINT_MAX_32_BITS - typedef unsigned short md5_uint32; -# else -# if ULONG_MAX == UINT_MAX_32_BITS - typedef unsigned long md5_uint32; -# else - /* The following line is intended to evoke an error. - Using #error is not portable enough. */ - "Cannot determine unsigned 32-bit data type." -# endif -# endif -#endif - -#undef __P -#if defined (__STDC__) && __STDC__ -#define __P(x) x -#else -#define __P(x) () -#endif - -/* Structure to save state of computation between the single steps. */ -struct md5_ctx -{ - md5_uint32 A; - md5_uint32 B; - md5_uint32 C; - md5_uint32 D; -}; - -/* - * The following three functions are build up the low level used in - * the functions `md5_stream' and `md5_buffer'. - */ - -/* Initialize structure containing state of computation. - (RFC 1321, 3.3: Step 3) */ -void md5_init_ctx __P ((struct md5_ctx *ctx)); - -/* Starting with the result of former calls of this function (or the - initialzation function update the context for the next LEN bytes - starting at BUFFER. - It is necessary that LEN is a multiple of 64!!! */ -void md5_process_block __P ((const void *buffer, size_t len, - struct md5_ctx *ctx)); - -/* Put result from CTX in first 16 bytes following RESBUF. The result is - always in little endian byte order, so that a byte-wise output yields - to the wanted ASCII representation of the message digest. */ -void *md5_read_ctx __P ((const struct md5_ctx *ctx, void *resbuf)); - - -/* Compute MD5 message digest for bytes read from STREAM. The - resulting message digest number will be written into the 16 bytes - beginning at RESBLOCK. */ -int md5_stream __P ((FILE *stream, void *resblock)); - -/* Compute MD5 message digest for LEN bytes beginning at BUFFER. The - result is always in little endian byte order, so that a byte-wise - output yields to the wanted ASCII representation of the message - digest. */ -//void *md5_buffer __P((const char *buffer, size_t len, void *resblock)); -void *md5_buffer (const char *buffer, size_t len, void *resblock); -#endif - -#ifdef __cplusplus -}; -#endif - diff --git a/3dc/win95/media.cpp b/3dc/win95/media.cpp deleted file mode 100644 index acb1427..0000000 --- a/3dc/win95/media.cpp +++ /dev/null @@ -1,556 +0,0 @@ -#include "advwin32.h" -#include "media.hpp" - -void * MediaMedium::GetWriteBuffer(unsigned * pSize, unsigned /*nDesiredSize*/) -{ - *pSize = 0; - m_fError |= MME_UNAVAIL; - return NULL; -} - -void const * MediaMedium::GetReadBuffer(unsigned * pSize, unsigned /*nDesiredSize*/) -{ - *pSize = 0; - m_fError |= MME_UNAVAIL; - return NULL; -} - -void MediaMedium::CloseWriteBuffer(unsigned /*nPosOffset*/) -{ - m_fError |= MME_UNAVAIL; -} - -void MediaMedium::CloseReadBuffer(unsigned /*nPosOffset*/) -{ - m_fError |= MME_UNAVAIL; -} - -void MediaMedium::DoWriteBlock(void const * /*pData*/, unsigned /*nSize*/) -{ - m_fError |= MME_UNAVAIL; -} - -void MediaMedium::DoReadBlock(void * /*pData*/, unsigned /*nSize*/) -{ - m_fError |= MME_UNAVAIL; -} - -unsigned MediaMedium::GetRemainingSize() -{ - return UINT_MAX; -} - -// MediaWinFileMedium - -#ifdef _MEDIA_WIN_TARGET - -unsigned MediaWinFileMedium::GetRemainingSize() -{ - if (INVALID_HANDLE_VALUE == m_hFile) - { - m_fError |= MME_UNAVAIL; - return 0; - } - - unsigned nSize = GetFileSize(m_hFile,NULL); - - if (0xffffffff == nSize) - { - m_fError |= MME_UNAVAIL; - return 0; - } - - return nSize - GetPos(); -} - -void * MediaWinFileMedium::GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize) -{ - m_pBuffer = new char [nDesiredSize]; - *pSize = nDesiredSize; - return m_pBuffer; -} - -void const * MediaWinFileMedium::GetReadBuffer(unsigned * pSize, unsigned nDesiredSize) -{ - if (INVALID_HANDLE_VALUE == m_hFile) - // the base/default implementation raises an error - return MediaMedium::GetReadBuffer(pSize,nDesiredSize); - - m_pBuffer = new char [nDesiredSize]; - - DWORD nBytesRead = 0; - - if (!ReadFile(m_hFile, m_pBuffer, nDesiredSize, &nBytesRead, NULL)) - m_fError |= MME_IOERROR; - else if (!nBytesRead) - m_fError |= MME_EOFMET; - - *pSize = m_nReadBufLen = nBytesRead; - - return m_pBuffer; -} - -void MediaWinFileMedium::CloseWriteBuffer(unsigned nPosOffset) -{ - if (INVALID_HANDLE_VALUE == m_hFile) - { - // the base/default implementation raises an error - MediaMedium::CloseWriteBuffer(nPosOffset); - return; - } - - DWORD nBytesWritten = 0; - - if (!WriteFile(m_hFile, m_pBuffer, nPosOffset, &nBytesWritten, NULL)) - m_fError |= MME_IOERROR; - else if (nBytesWritten < nPosOffset) - m_fError |= MME_EOFMET; - - delete [] m_pBuffer; -} - -void MediaWinFileMedium::CloseReadBuffer(unsigned nPosOffset) -{ - if (INVALID_HANDLE_VALUE == m_hFile) - { - // the base/default implementation raises an error - MediaMedium::CloseReadBuffer(nPosOffset); - return; - } - - if (nPosOffset != m_nReadBufLen && 0xffffffff == SetFilePointer(m_hFile,nPosOffset - m_nReadBufLen,NULL,FILE_CURRENT)) - m_fError |= MME_UNAVAIL; - - m_nReadBufLen = 0; - - delete [] m_pBuffer; -} - -void MediaWinFileMedium::DoWriteBlock(void const * pData, unsigned nSize) -{ - if (INVALID_HANDLE_VALUE == m_hFile) - { - MediaMedium::DoWriteBlock(pData,nSize); - return; - } - - DWORD nBytesWritten = 0; - - if (!WriteFile(m_hFile, pData, nSize, &nBytesWritten, NULL)) - m_fError |= MME_IOERROR; - else if (nBytesWritten < nSize) - m_fError |= MME_EOFMET; -} - -void MediaWinFileMedium::DoReadBlock(void * pData, unsigned nSize) -{ - if (INVALID_HANDLE_VALUE == m_hFile) - { - MediaMedium::DoReadBlock(pData,nSize); - return; - } - - DWORD nBytesRead = 0; - - if (!ReadFile(m_hFile, pData, nSize, &nBytesRead, NULL)) - m_fError |= MME_IOERROR; - else if (nBytesRead < nSize) - m_fError |= MME_EOFMET; -} - -unsigned MediaWinFileMedium::DoGetPos() -{ - unsigned nFilePos = SetFilePointer(m_hFile,0,NULL,FILE_CURRENT); - - if (0xffffffff == nFilePos) - { - m_fError |= MME_UNAVAIL; - return 0; - } - - return nFilePos - m_nReadBufLen; -} - -void MediaWinFileMedium::DoSetPos(unsigned nPos) -{ - if (0xffffffff == SetFilePointer(m_hFile,nPos,NULL,FILE_BEGIN)) - m_fError |= MME_UNAVAIL; -} - -#endif // _MEDIA_WIN_TARGET - -// MediaStdFileMedium - -unsigned MediaStdFileMedium::GetRemainingSize() -{ - if (!m_pFile) - { - m_fError |= MME_UNAVAIL; - return 0; - } - - long nPos = ftell(m_pFile); - - if (-1L == nPos || fseek(m_pFile,0,SEEK_END)) - { - m_fError |= MME_UNAVAIL; - return 0; - } - - long nSize = ftell(m_pFile); - - fseek(m_pFile,nPos,SEEK_SET); - - if (-1L == nSize) - { - m_fError |= MME_UNAVAIL; - return 0; - } - - return nSize - GetPos(); -} - -void * MediaStdFileMedium::GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize) -{ - m_pBuffer = new char [nDesiredSize]; - *pSize = nDesiredSize; - return m_pBuffer; -} - -void const * MediaStdFileMedium::GetReadBuffer(unsigned * pSize, unsigned nDesiredSize) -{ - if (!m_pFile) - // the base/default implementation raises an error - return MediaMedium::GetReadBuffer(pSize,nDesiredSize); - - m_pBuffer = new char [nDesiredSize]; - - *pSize = m_nReadBufLen = fread(m_pBuffer, 1, nDesiredSize, m_pFile); - - if (!m_nReadBufLen) - { - if (feof(m_pFile)) - m_fError |= MME_EOFMET; - else - m_fError |= MME_IOERROR; - } - - return m_pBuffer; -} - -void MediaStdFileMedium::CloseWriteBuffer(unsigned nPosOffset) -{ - if (!m_pFile) - { - // the base/default implementation raises an error - MediaMedium::CloseWriteBuffer(nPosOffset); - return; - } - - if (fwrite(m_pBuffer, 1, nPosOffset, m_pFile) < nPosOffset) - { - if (feof(m_pFile)) - m_fError |= MME_EOFMET; - else - m_fError |= MME_IOERROR; - } - - delete [] m_pBuffer; -} - -void MediaStdFileMedium::CloseReadBuffer(unsigned nPosOffset) -{ - if (!m_pFile) - { - // the base/default implementation raises an error - MediaMedium::CloseReadBuffer(nPosOffset); - return; - } - - if (nPosOffset != m_nReadBufLen && fseek(m_pFile,nPosOffset - m_nReadBufLen,SEEK_CUR)) - m_fError |= MME_UNAVAIL; - - m_nReadBufLen = 0; - delete [] m_pBuffer; -} - -void MediaStdFileMedium::DoWriteBlock(void const * pData, unsigned nSize) -{ - if (!m_pFile) - { - MediaMedium::DoWriteBlock(pData,nSize); - return; - } - - if (fwrite(pData, 1, nSize, m_pFile) < nSize) - { - if (feof(m_pFile)) - m_fError |= MME_EOFMET; - else - m_fError |= MME_IOERROR; - } -} - -void MediaStdFileMedium::DoReadBlock(void * pData, unsigned nSize) -{ - if (!m_pFile) - { - MediaMedium::DoReadBlock(pData,nSize); - return; - } - - if (fread(pData, 1, nSize, m_pFile) < nSize) - { - if (feof(m_pFile)) - m_fError |= MME_EOFMET; - else - m_fError |= MME_IOERROR; - } -} - -unsigned MediaStdFileMedium::DoGetPos() -{ - long nFilePos = ftell(m_pFile); - - if (-1L == nFilePos) - { - m_fError |= MME_UNAVAIL; - return 0; - } - - return nFilePos - m_nReadBufLen; -} - -void MediaStdFileMedium::DoSetPos(unsigned nPos) -{ - if (fseek(m_pFile,nPos,SEEK_SET)) - m_fError |= MME_UNAVAIL; -} - -// MediaMemoryReadMedium - -void const * MediaMemoryReadMedium::GetReadBuffer(unsigned * pSize, unsigned nDesiredSize) -{ - if (!m_pMem) - // the base/default implementation raises an error - return MediaMedium::GetReadBuffer(pSize,nDesiredSize); - - *pSize = nDesiredSize; - - return static_cast<char const *>(m_pMem)+m_nOffset/sizeof(char); -} - -void MediaMemoryReadMedium::CloseReadBuffer(unsigned nPosOffset) -{ - if (!m_pMem) - { - // the base/default implementation raises an error - MediaMedium::CloseReadBuffer(nPosOffset); - return; - } - - m_nOffset += nPosOffset; -} - -void MediaMemoryReadMedium::DoReadBlock(void * pData, unsigned nSize) -{ - if (!m_pMem) - { - MediaMedium::DoReadBlock(pData,nSize); - return; - } - - memcpy(pData,static_cast<char const *>(m_pMem)+m_nOffset/sizeof(char),nSize); - - m_nOffset += nSize; -} - -unsigned MediaMemoryReadMedium::DoGetPos() -{ - return m_nOffset; -} - -void MediaMemoryReadMedium::DoSetPos(unsigned nPos) -{ - m_nOffset = nPos; -} - -// MediaMemoryMedium - -void * MediaMemoryMedium::GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize) -{ - if (!m_pMem) - // the base/default implementation raises an error - return MediaMedium::GetWriteBuffer(pSize,nDesiredSize); - - *pSize = nDesiredSize; - - return static_cast<char *>(m_pMem)+m_nOffset/sizeof(char); -} - -void MediaMemoryMedium::CloseWriteBuffer(unsigned nPosOffset) -{ - if (!m_pMem) - { - // the base/default implementation raises an error - MediaMedium::CloseWriteBuffer(nPosOffset); - return; - } - - m_nOffset += nPosOffset; -} - -void MediaMemoryMedium::DoWriteBlock(void const * pData, unsigned nSize) -{ - if (!m_pMem) - { - MediaMedium::DoWriteBlock(pData,nSize); - return; - } - - memcpy(static_cast<char *>(m_pMem)+m_nOffset/sizeof(char),pData,nSize); - - m_nOffset += nSize; -} - -// MediaSection - -unsigned MediaSection::GetRemainingSize() -{ - if (!m_pMedium) - { - m_fError |= MME_UNAVAIL; - return 0; - } - - unsigned nSectionSize = m_nMaxSize - GetPos(); - unsigned nMediaSize = m_pMedium->GetRemainingSize(); - m_fError |= m_pMedium->m_fError; - - return nSectionSize < nMediaSize ? nSectionSize : nMediaSize; -} - -void * MediaSection::GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize) -{ - if (!m_pMedium) - return MediaMedium::GetWriteBuffer(pSize,nDesiredSize); - - if (m_nPos + nDesiredSize > m_nMaxSize) - { - nDesiredSize = m_nMaxSize - m_nPos; - } - - void * p = m_pMedium->GetWriteBuffer(pSize,nDesiredSize); - m_fError |= m_pMedium->m_fError; - return p; -} - -void const * MediaSection::GetReadBuffer(unsigned * pSize, unsigned nDesiredSize) -{ - if (!m_pMedium) - return MediaMedium::GetReadBuffer(pSize,nDesiredSize); - - if (m_nPos + nDesiredSize > m_nMaxSize) - { - nDesiredSize = m_nMaxSize - m_nPos; - } - - void const * p = m_pMedium->GetReadBuffer(pSize,nDesiredSize); - m_fError |= m_pMedium->m_fError; - return p; -} - -void MediaSection::CloseWriteBuffer(unsigned nPosOffset) -{ - if (!m_pMedium) - { - MediaMedium::CloseWriteBuffer(nPosOffset); - return; - } - - m_nPos += nPosOffset; - - m_pMedium->CloseWriteBuffer(nPosOffset); - m_fError |= m_pMedium->m_fError; -} - -void MediaSection::CloseReadBuffer(unsigned nPosOffset) -{ - if (!m_pMedium) - { - MediaMedium::CloseReadBuffer(nPosOffset); - return; - } - - m_nPos += nPosOffset; - - m_pMedium->CloseReadBuffer(nPosOffset); - m_fError |= m_pMedium->m_fError; -} - -void MediaSection::DoWriteBlock(void const * pData, unsigned nSize) -{ - if (!m_pMedium) - { - MediaMedium::DoWriteBlock(pData,nSize); - return; - } - - if (m_nPos + nSize > m_nMaxSize) - { - m_fError |= MME_VEOFMET; - return; - } - - m_nPos += nSize; - - m_pMedium->DoWriteBlock(pData,nSize); - m_fError |= m_pMedium->m_fError; -} - -void MediaSection::DoReadBlock(void * pData, unsigned nSize) -{ - if (!m_pMedium) - { - MediaMedium::DoReadBlock(pData,nSize); - return; - } - - if (m_nPos + nSize > m_nMaxSize) - { - m_fError |= MME_VEOFMET; - return; - } - - m_nPos += nSize; - - m_pMedium->DoReadBlock(pData,nSize); - m_fError |= m_pMedium->m_fError; -} - -unsigned MediaSection::DoGetPos() -{ - return m_nPos; -} - -void MediaSection::DoSetPos(unsigned nPos) -{ - if (!m_pMedium) - { - m_fError |= MME_UNAVAIL; - return; - } - - if (nPos > m_nMaxSize) - { - m_fError |= MME_VEOFMET; - return; - } - - m_pMedium->DoSetPos(m_pMedium->DoGetPos()+nPos-m_nPos); - if (m_nPos > m_nUsedPos) m_nUsedPos = m_nPos; - m_nPos = nPos; - - m_fError |= m_pMedium->m_fError; -} - diff --git a/3dc/win95/media.hpp b/3dc/win95/media.hpp deleted file mode 100644 index 73f36b7..0000000 --- a/3dc/win95/media.hpp +++ /dev/null @@ -1,681 +0,0 @@ -#ifndef _INCLUDED_MEDIA_HPP_ -#define _INCLUDED_MEDIA_HPP_ - -#if defined(_WIN32) || defined(WIN32) || defined(WINDOWS) || defined(_WINDOWS) - #define _MEDIA_WIN_TARGET - #include <windows.h> -#endif // WIN32 || _WIN32 || WINDOWS || _WINDOWS - -#include <stdio.h> -#include <conio.h> -#include <limits.h> -#include <string.h> - -class MediaMedium; - -// use this to read in simple data types -// note especially that if the size of TYPE is greater than the -// default buffer size, then the operation will fail -// and the virtual end of file error flag will be set -// - use ReadBlock instead -template <class TYPE> -void MediaRead(MediaMedium * pThis, TYPE * p); - -// use this to write simple data types -// note especially that if the size of TYPE is greater than the -// default buffer size, then the operation will fail -// and the virtual end of file error flag will be set -// - use WriteBlock instead -template <class TYPE> -void MediaWrite(MediaMedium * pThis, TYPE d); - -#ifdef __WATCOMC__ -template <class TYPE> class _Media_CompilerHack; -#endif - -class MediaMedium -{ - protected: - // standard constructor - MediaMedium() : m_nRefCnt(1), - m_fError(0), m_nDefBufSize(1024), - m_nWriteBufPos(0), m_nReadBufPos(0), - m_nBufLenUsed(0), m_nBufSize(0), - m_pReadBuffer(NULL), m_pWriteBuffer(NULL) {} - - virtual ~MediaMedium() {} - - public: - // allow reference counting - unsigned AddRef() { return ++m_nRefCnt; } - unsigned Release() { if (0==(--m_nRefCnt)) { delete this; return 0;} else return m_nRefCnt; } - - enum - { - // error code flags - MME_VEOFMET = 0x00000001 // virtual end of file met - ,MME_EOFMET = 0x00000002 // actual end of file met - ,MME_OPENFAIL = 0x00000004 // failed to open medium - ,MME_CLOSEFAIL = 0x00000008 // failed to close medium - ,MME_UNAVAIL = 0x00000010 // requested operation was not available - ,MME_IOERROR = 0x00000020 // read/write operation failed - }; - unsigned m_fError; - - unsigned m_nDefBufSize; // default read or write buffer sizes for buffering small objects - - // flush read/write buffers. You should call this function after the last read or write operation on the object - // alternatively, derived (implementation) classes close methods should call this - void Flush() - { - if (m_pReadBuffer) - { - unsigned nBufStartPos = DoGetPos(); - CloseReadBuffer(m_nReadBufPos > m_nBufLenUsed ? m_nReadBufPos : m_nBufLenUsed); - DoSetPos(nBufStartPos + m_nReadBufPos); - m_pReadBuffer = NULL; - m_nReadBufPos = 0; - } - else if (m_pWriteBuffer) - { - unsigned nBufStartPos = DoGetPos(); - CloseWriteBuffer(m_nWriteBufPos > m_nBufLenUsed ? m_nWriteBufPos : m_nBufLenUsed); - DoSetPos(nBufStartPos + m_nWriteBufPos); - m_pWriteBuffer = NULL; - m_nWriteBufPos = 0; - } - m_nBufSize = 0; - m_nBufLenUsed = 0; - } - - // use this to write a block of raw data - void WriteBlock(void const * pData, unsigned nSize) - { - Flush(); - DoWriteBlock(pData,nSize); - } - - // this may be faster, but will only work if the block size no more than the default buffer size - void WriteBufferedBlock(void const * pData, unsigned nSize) - { - if (m_nWriteBufPos + nSize <= m_nBufSize) - { - memcpy(static_cast<char *>(m_pWriteBuffer) + m_nWriteBufPos/sizeof(char), pData, nSize); - m_nWriteBufPos += nSize; - } - else - { - Flush(); - m_pWriteBuffer = GetWriteBuffer(&m_nBufSize,m_nDefBufSize); - if (nSize <= m_nBufSize) - { - memcpy(m_pWriteBuffer, pData, nSize); - m_nWriteBufPos = nSize; - } - else - { - m_fError |= MME_VEOFMET; - } - } - } - - // use this to read a block of raw data - void ReadBlock(void * pData, unsigned nSize) - { - Flush(); - DoReadBlock(pData,nSize); - } - - // this may be faster, but will only work if the block size no more than the default buffer size - void ReadBufferedBlock(void * pData, unsigned nSize) - { - if (m_nReadBufPos + nSize <= m_nBufSize) - { - memcpy(pData, static_cast<char const *>(m_pReadBuffer) + m_nReadBufPos/sizeof(char), nSize); - m_nReadBufPos += nSize; - } - else - { - Flush(); - m_pReadBuffer = GetReadBuffer(&m_nBufSize,m_nDefBufSize); - if (nSize <= m_nBufSize) - { - memcpy(pData, m_pReadBuffer, nSize); - m_nReadBufPos = nSize; - } - else - { - m_fError |= MME_VEOFMET; - } - } - } - - // move the 'file' pointer nOffset bytes - // this will not necessarily cause buffers to be flushed - // if the pointer can be moved within the current buffer, - // some of the buffer may be left uninitialized, and no - // error will occur, which otherwise might (particularly - // if the object has write access) - void MovePos(signed nOffset) - { - if (m_pReadBuffer) - { - if (nOffset>0 && m_nReadBufPos+nOffset<=m_nBufSize) - { - m_nReadBufPos+=nOffset; - return; - } - else if (nOffset<=0 && m_nReadBufPos>=static_cast<unsigned>(-nOffset)) - { - if (m_nBufLenUsed < m_nReadBufPos) m_nBufLenUsed = m_nReadBufPos; - m_nReadBufPos+=nOffset; - return; - } - } - else if (m_pWriteBuffer) - { - if (nOffset>0 && m_nWriteBufPos+nOffset<=m_nBufSize) - { - m_nWriteBufPos+=nOffset; - return; - } - else if (nOffset<=0 && m_nWriteBufPos>=static_cast<unsigned>(-nOffset)) - { - if (m_nBufLenUsed < m_nWriteBufPos) m_nBufLenUsed = m_nWriteBufPos; - m_nWriteBufPos+=nOffset; - return; - } - } - // else - Flush(); - DoSetPos(DoGetPos()+nOffset); - } - - // set the 'file' pointer - // you would normally only pass values which have been - // previously returned by a call to GetPos - // note that this will not necessarily cause buffers to be flushed - // if the pointer can be moved within the current buffer, - // some of the buffer may be left uninitialized, and no - // error will occur, which otherwise might (particularly - // if the object has write access) - void SetPos(unsigned nPos) - { - unsigned nNewBufPos = nPos - DoGetPos(); - if (nNewBufPos <= m_nBufSize) - { - if (m_pReadBuffer) - { - if (m_nBufLenUsed < m_nReadBufPos) m_nBufLenUsed = m_nReadBufPos; - m_nReadBufPos = nNewBufPos; - } - else // pWriteBuffer - { - if (m_nBufLenUsed < m_nWriteBufPos) m_nBufLenUsed = m_nWriteBufPos; - m_nWriteBufPos = nNewBufPos; - } - } - else - { - Flush(); - DoSetPos(nPos); - } - } - - // get the 'file' pointer. The returned value - // can be used in a call to SetPos - unsigned GetPos() - { - return DoGetPos()+m_nReadBufPos+m_nWriteBufPos; - } - - virtual unsigned GetRemainingSize(); - - private: - void * m_pWriteBuffer; - void const * m_pReadBuffer; - unsigned m_nReadBufPos; - unsigned m_nWriteBufPos; - unsigned m_nBufSize; - unsigned m_nBufLenUsed; - - unsigned m_nRefCnt; - - protected: - - // the non-pure functions default implementation sets the unavailable error flag - - // it is safe to assume that these four functions will be called in a logical order - // and that only one buffer (read or write) will be required at once - - // this two functions may return NULL only if *pSize is set to zero - // *pSize should otherwise be set to the actual size of the buffer returned - - // get a pointer to memory where data can be written to directly - virtual void * GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize); - - // get a pointer to memory where data can be read from directly - virtual void const * GetReadBuffer(unsigned * pSize, unsigned nDesiredSize); - - // close the buffer 'allocated' above and assume nPosOffset bytes were transferred - // and that the 'file' pointer should be positioned at the end of the transferred data - virtual void CloseWriteBuffer(unsigned nPosOffset); - virtual void CloseReadBuffer(unsigned nPosOffset); - - // transfer a block of data - // it is safe to assume that no buffer will be open - virtual void DoWriteBlock(void const * pData, unsigned nSize); - virtual void DoReadBlock(void * pData, unsigned nSize); - - // if a buffer is open, should return pos at start of buffer - virtual unsigned DoGetPos() = 0; - - // it is safe to assume that no buffer will be open - virtual void DoSetPos(unsigned nPos) = 0; - - friend class MediaSection; - - friend class _Media_CompilerHack; -}; - -#ifdef __WATCOMC__ -template <class TYPE> -#endif -class _Media_CompilerHack -{ - public: - #ifndef __WATCOMC__ - template <class TYPE> - #endif - static inline void MediaRead(MediaMedium * pThis, TYPE * p) - { - if (pThis->m_nReadBufPos + sizeof(TYPE) <= pThis->m_nBufSize) - { - *p = *reinterpret_cast<TYPE const *>(static_cast<char const *>(pThis->m_pReadBuffer) + pThis->m_nReadBufPos/sizeof(char)); - - pThis->m_nReadBufPos += sizeof(TYPE); - } - else - { - pThis->Flush(); - pThis->m_pReadBuffer = pThis->GetReadBuffer(&pThis->m_nBufSize,pThis->m_nDefBufSize); - if (sizeof(TYPE) <= pThis->m_nBufSize) - { - *p = *static_cast<TYPE const *>(pThis->m_pReadBuffer); - pThis->m_nReadBufPos = sizeof(TYPE); - } - else - { - pThis->m_fError |= MediaMedium::MME_VEOFMET; - } - } - } - - #ifndef __WATCOMC__ - template <class TYPE> - #endif - static inline void MediaWrite(MediaMedium * pThis, TYPE d) - { - if (pThis->m_nWriteBufPos + sizeof(TYPE) <= pThis->m_nBufSize) - { - *reinterpret_cast<TYPE *>(static_cast<char *>(pThis->m_pWriteBuffer) + pThis->m_nWriteBufPos/sizeof(char)) = d; - - pThis->m_nWriteBufPos += sizeof(TYPE); - } - else - { - pThis->Flush(); - pThis->m_pWriteBuffer = pThis->GetWriteBuffer(&pThis->m_nBufSize,pThis->m_nDefBufSize); - if (sizeof(TYPE) <= pThis->m_nBufSize) - { - *static_cast<TYPE *>(pThis->m_pWriteBuffer) = d; - pThis->m_nWriteBufPos = sizeof(TYPE); - } - else - { - pThis->m_fError |= MediaMedium::MME_VEOFMET; - } - } - } -}; - -// use this to read in simple data types -// note especially that if the size of TYPE is greater than the -// default buffer size, then the operation will fail -// and the virtual end of file error flag will be set -// - use ReadBlock instead -template <class TYPE> -inline void MediaRead(MediaMedium * pThis, TYPE * p) -{ - _Media_CompilerHack - #ifdef __WATCOMC__ - <TYPE> - #endif - ::MediaRead(pThis,p); -} - -// use this to write simple data types -// note especially that if the size of TYPE is greater than the -// default buffer size, then the operation will fail -// and the virtual end of file error flag will be set -// - use WriteBlock instead -template <class TYPE> -inline void MediaWrite(MediaMedium * pThis, TYPE d) -{ - _Media_CompilerHack - #ifdef __WATCOMC__ - <TYPE> - #endif - ::MediaWrite(pThis,d); -} - -#ifdef _MEDIA_WIN_TARGET - -class MediaWinFileMedium : public MediaMedium -{ - public: - MediaWinFileMedium() : m_hFile(INVALID_HANDLE_VALUE), m_nReadBufLen(0) {} - - void Attach(HANDLE hFile) - { - m_hFile = hFile; - } - void Detach() - { - Flush(); - m_hFile = INVALID_HANDLE_VALUE; - } - - void Open(LPCTSTR pszFileName, DWORD dwDesiredAccess) - { - DWORD dwShareMode; - DWORD dwCreationDistribution; - switch (dwDesiredAccess & (GENERIC_READ|GENERIC_WRITE)) - { - case 0: - dwShareMode = FILE_SHARE_READ|FILE_SHARE_WRITE; - dwCreationDistribution = OPEN_EXISTING; - break; - case GENERIC_READ: - dwShareMode = FILE_SHARE_READ; - dwCreationDistribution = OPEN_EXISTING; - break; - case GENERIC_WRITE: - dwShareMode = 0; - dwCreationDistribution = CREATE_ALWAYS; - break; - default: // GENERIC_WRITE|GENERIC_READ - dwCreationDistribution = OPEN_ALWAYS; - dwShareMode = 0; - } - m_hFile = CreateFile - ( - pszFileName, - dwDesiredAccess, - dwShareMode, - NULL, - dwCreationDistribution, - FILE_ATTRIBUTE_NORMAL, - NULL - ); - if (INVALID_HANDLE_VALUE == m_hFile) - m_fError |= MME_OPENFAIL; - } - void Close() - { - if (INVALID_HANDLE_VALUE == m_hFile) - m_fError |= MME_CLOSEFAIL; - else - { - Flush(); - if (!CloseHandle(m_hFile)) - m_fError |= MME_CLOSEFAIL; - else - m_hFile = INVALID_HANDLE_VALUE; - } - } - - ~MediaWinFileMedium() - { - // should already be closed... - Close(); - } - - virtual unsigned GetRemainingSize(); - - private: - HANDLE m_hFile; - - char * m_pBuffer; - unsigned m_nReadBufLen; - - protected: - - // get a pointer to memory where data can be written to directly - virtual void * GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize); - - // get a pointer to memory where data can be read from directly - virtual void const * GetReadBuffer(unsigned * pSize, unsigned nDesiredSize); - - // close the buffer allocated above and assume nPosOffset were transferred - virtual void CloseWriteBuffer(unsigned nPosOffset); - virtual void CloseReadBuffer(unsigned nPosOffset); - - // transfer a block of data: the buffer should be closed - virtual void DoWriteBlock(void const * pData, unsigned nSize); - virtual void DoReadBlock(void * pData, unsigned nSize); - - // if a buffer is open, should return pos at start of buffer - virtual unsigned DoGetPos(); - - // requires that no buffer is oben - virtual void DoSetPos(unsigned nPos); -}; - -#endif // _MEDIA_WIN_TARGET - -class MediaStdFileMedium : public MediaMedium -{ - public: - MediaStdFileMedium() : m_pFile(NULL), m_nReadBufLen(0) {} - - void Attach(FILE * pFile) - { - m_pFile = pFile; - } - void Detach() - { - Flush(); - m_pFile = NULL; - } - - void Open(char const * pszFileName, char const * pszOpenMode) - { - m_pFile = fopen(pszFileName,pszOpenMode); - if (!m_pFile) - m_fError |= MME_OPENFAIL; - } - void Close() - { - if (!m_pFile) - m_fError |= MME_CLOSEFAIL; - else - { - Flush(); - if (fclose(m_pFile)) - m_fError |= MME_CLOSEFAIL; - else - m_pFile = NULL; - } - } - - ~MediaStdFileMedium() - { - // should already be closed... - Close(); - } - - virtual unsigned GetRemainingSize(); - - private: - FILE * m_pFile; - - char * m_pBuffer; - unsigned m_nReadBufLen; - - protected: - - // get a pointer to memory where data can be written to directly - virtual void * GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize); - - // get a pointer to memory where data can be read from directly - virtual void const * GetReadBuffer(unsigned * pSize, unsigned nDesiredSize); - - // close the buffer allocated above and assume nPosOffset were transferred - virtual void CloseWriteBuffer(unsigned nPosOffset); - virtual void CloseReadBuffer(unsigned nPosOffset); - - // transfer a block of data: the buffer should be closed - virtual void DoWriteBlock(void const * pData, unsigned nSize); - virtual void DoReadBlock(void * pData, unsigned nSize); - - // if a buffer is open, should return pos at start of buffer - virtual unsigned DoGetPos(); - - // requires that no buffer is oben - virtual void DoSetPos(unsigned nPos); -}; - -class MediaMemoryReadMedium : public MediaMedium -{ - public: - MediaMemoryReadMedium() : m_pMem(NULL) {} - - void Open(void const * p) - { - m_pMem = p; - m_nOffset = 0; - } - - void Close() - { - if (m_pMem) - { - Flush(); - m_pMem = NULL; - } - else - m_fError |= MME_CLOSEFAIL; - } - - private: - void const * m_pMem; - - protected: - unsigned m_nOffset; - - // get a pointer to memory where data can be read from directly - virtual void const * GetReadBuffer(unsigned * pSize, unsigned nDesiredSize); - - // close the buffer allocated above and assume nPosOffset were transferred - virtual void CloseReadBuffer(unsigned nPosOffset); - - // transfer a block of data: the buffer should be closed - virtual void DoReadBlock(void * pData, unsigned nSize); - - // if a buffer is open, should return pos at start of buffer - virtual unsigned DoGetPos(); - - // requires that no buffer is oben - virtual void DoSetPos(unsigned nPos); -}; - -class MediaMemoryMedium : public MediaMemoryReadMedium -{ - public: - MediaMemoryMedium() : m_pMem(NULL) {} - - void Open(void * p) - { - m_pMem = p; - MediaMemoryReadMedium::Open(p); - } - - void Close() - { - MediaMemoryReadMedium::Close(); - m_pMem = NULL; - } - - private: - void * m_pMem; - - protected: - - // get a pointer to memory where data can be written to directly - virtual void * GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize); - - // close the buffer allocated above and assume nPosOffset were transferred - virtual void CloseWriteBuffer(unsigned nPosOffset); - - // transfer a block of data: the buffer should be closed - virtual void DoWriteBlock(void const * pData, unsigned nSize); -}; - - -class MediaSection : public MediaMedium -{ - public: - MediaSection() : m_pMedium(NULL) {} - - void Open(MediaMedium * pMedium, unsigned nMaxSize = UINT_MAX) - { - m_pMedium = pMedium; - m_nMaxSize = nMaxSize; - m_nPos = 0; - m_nUsedPos = 0; - } - void Close() - { - if (m_pMedium) - Flush(); - if (m_nPos > m_nUsedPos) m_nUsedPos = m_nPos; - m_pMedium = NULL; - } - unsigned GetUsedSize() const - { - return (m_nPos > m_nUsedPos) ? m_nPos : m_nUsedPos; - } - - virtual unsigned GetRemainingSize(); - - private: - MediaMedium * m_pMedium; - unsigned m_nMaxSize; - unsigned m_nPos; - unsigned m_nUsedPos; - - protected: - // get a pointer to memory where data can be written to directly - virtual void * GetWriteBuffer(unsigned * pSize, unsigned nDesiredSize); - - // get a pointer to memory where data can be read from directly - virtual void const * GetReadBuffer(unsigned * pSize, unsigned nDesiredSize); - - // close the buffer allocated above and assume nPosOffset were transferred - virtual void CloseWriteBuffer(unsigned nPosOffset); - virtual void CloseReadBuffer(unsigned nPosOffset); - - // transfer a block of data: the buffer should be closed - virtual void DoWriteBlock(void const * pData, unsigned nSize); - virtual void DoReadBlock(void * pData, unsigned nSize); - - // if a buffer is open, should return pos at start of buffer - virtual unsigned DoGetPos(); - - // requires that no buffer is oben - virtual void DoSetPos(unsigned nPos); -}; - - -#endif diff --git a/3dc/win95/objedit.h b/3dc/win95/objedit.h deleted file mode 100644 index c39b2ec..0000000 --- a/3dc/win95/objedit.h +++ /dev/null @@ -1,84 +0,0 @@ - -#include "Chunk.hpp" - -#define VECTOR VECTORCH - -struct ChunkMapBlock -{ - char TemplateName[20]; - char TemplateNotes[100]; - int MapType; - int MapShape; - int MapFlags; - int MapFlags2; - int MapFlags3; - int MapCType; - int MapCGameType; - int MapCStrategyS; - int MapCStrategyL; - int MapInteriorType; - int MapLightType; - int MapMass; - VECTOR MapNewtonV; - VECTOR MapOrigin; - int MapViewType; - - int MapVDBData; - int SimShapeList; - - - -}; - -class Map_Block_Chunk : public Chunk -{ -public: - virtual size_t size_chunk() - { - return (chunk_size=216); - } - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - ChunkMapBlock map_data; - friend class Object_Project_Data_Chunk; - - Map_Block_Chunk (Object_Project_Data_Chunk * parent) - :Chunk(parent,"MAPBLOCK") - {} -private: - - //constructor from buffer - Map_Block_Chunk (Object_Project_Data_Chunk * parent,const char* data); -}; - -struct ChunkStrategy -{ - char StrategyName[20]; - char StrategyNotes[100]; - int Strategy; -}; - -class Strategy_Chunk : public Chunk -{ -public : - virtual size_t size_chunk() - { - return (chunk_size=136); - } - virtual BOOL output_chunk (HANDLE &); - - virtual void fill_data_block (char * data_start); - - ChunkStrategy strategy_data; - friend class Object_Project_Data_Chunk; - - Strategy_Chunk(Object_Project_Data_Chunk *parent) - :Chunk(parent,"STRATEGY") - {} -private: - - //constructor from buffer - Strategy_Chunk (Object_Project_Data_Chunk * parent,const char* data); -}; diff --git a/3dc/win95/plat_shp.c b/3dc/win95/plat_shp.c deleted file mode 100644 index 8a67984..0000000 --- a/3dc/win95/plat_shp.c +++ /dev/null @@ -1,369 +0,0 @@ -/*RWH moved to a seperate file*/ - - -#include "3dc.h" -#include "module.h" -#include "inline.h" - -#include "gameplat.h" -#include "gamedef.h" - - -#include "dynblock.h" -#include "dynamics.h" -#define UseLocalAssert No -#include "ourasert.h" - - -/* * - * - * - * * * - * * * - *** - * -*/ -/*KJL*********************************************** -* Polygon Access Functions V1.0, 18:12:27 11/07/96 * -***********************************************KJL*/ - -int SetupPolygonAccess(DISPLAYBLOCK *objectPtr); -void AccessNextPolygon(void); -void GetPolygonVertices(struct ColPolyTag *polyPtr); -void GetPolygonNormal(struct ColPolyTag *polyPtr); -int SetupPolygonAccessFromShapeIndex(int shapeIndex); - - -/* the following are needed for morphing support */ -#if SupportMorphing -extern MORPHDISPLAY MorphDisplay; -extern VECTORCH MorphedPts[]; -#endif - -VECTORCH *ShapePointsPtr; -int *ShapeNormalsPtr; -int *Shape2NormalsPtr; -char ShapeIsMorphed; -int **ItemArrayPtr; -POLYHEADER *PolyheaderPtr; - -int SetupPolygonAccess(DISPLAYBLOCK *objectPtr) -{ - SHAPEHEADER *shape1Ptr; - - #if SupportMorphing - if (objectPtr->ObMorphCtrl) /* morphable object? */ - { - VECTORCH *shape1PointsPtr; - VECTORCH *shape2PointsPtr; - - /* Set up the morph data */ - GetMorphDisplay(&MorphDisplay, objectPtr); - - shape1Ptr = MorphDisplay.md_sptr1; - - if(MorphDisplay.md_lerp == 0x0000) - { - - ShapePointsPtr = (VECTORCH *)*shape1Ptr->points; - ShapeNormalsPtr = (int *) *(shape1Ptr->sh_normals); - ShapeIsMorphed=0; - - } - else if(MorphDisplay.md_lerp == 0xffff) - { - SHAPEHEADER *shape2Ptr; - shape2Ptr = MorphDisplay.md_sptr2; - - ShapePointsPtr = (VECTORCH *)*shape2Ptr->points; - ShapeNormalsPtr = (int *) *(shape2Ptr->sh_normals); - ShapeIsMorphed=0; - } - else - { - SHAPEHEADER *shape2Ptr; - shape2Ptr = MorphDisplay.md_sptr2; - - shape1PointsPtr = (VECTORCH *)(*shape1Ptr->points); - shape2PointsPtr = (VECTORCH *)(*shape2Ptr->points); - - /* you're going to need all the points so you might as well morph them all at once now */ - { - int numberOfPoints = shape1Ptr->numpoints; - VECTORCH *morphedPointsPtr = (VECTORCH *) MorphedPts; - - while(numberOfPoints--) - { - VECTORCH vertex1 = *shape1PointsPtr; - VECTORCH vertex2 = *shape2PointsPtr; - - if( (vertex1.vx == vertex2.vx && vertex1.vy == vertex2.vy && vertex1.vz == vertex2.vz) ) - { - *morphedPointsPtr = vertex1; - } - else - { - /* KJL 15:27:20 05/22/97 - I've changed this to speed things up, If a vertex - component has a magnitude greater than 32768 things will go wrong. */ - morphedPointsPtr->vx = vertex1.vx + (((vertex2.vx-vertex1.vx)*MorphDisplay.md_lerp)>>16); - morphedPointsPtr->vy = vertex1.vy + (((vertex2.vy-vertex1.vy)*MorphDisplay.md_lerp)>>16); - morphedPointsPtr->vz = vertex1.vz + (((vertex2.vz-vertex1.vz)*MorphDisplay.md_lerp)>>16); - } - - shape1PointsPtr++; - shape2PointsPtr++; - morphedPointsPtr++; - } - } - - ShapePointsPtr = (VECTORCH *)MorphedPts; - ShapeNormalsPtr = (int *) *(shape1Ptr->sh_normals); - Shape2NormalsPtr = (int *) *(shape2Ptr->sh_normals); - ShapeIsMorphed=1; - } - ItemArrayPtr = (int **)shape1Ptr->items; - } - else /* not a morphing object */ - #endif - { - shape1Ptr = GetShapeData(objectPtr->ObShape); - - ShapePointsPtr = (VECTORCH *)(*shape1Ptr->points); - ShapeNormalsPtr = (int *)(*shape1Ptr->sh_normals); - ItemArrayPtr = (int **)shape1Ptr->items; - ShapeIsMorphed=0; - } - - { - int *itemPtr = *ItemArrayPtr; - PolyheaderPtr = (POLYHEADER *) itemPtr; - } - - return shape1Ptr->numitems; -} -void AccessNextPolygon(void) -{ - int *itemPtr = *(ItemArrayPtr++); - PolyheaderPtr = (POLYHEADER *) itemPtr; - return; -} - -void GetPolygonVertices(struct ColPolyTag *polyPtr) -{ - int *vertexNumberPtr = &PolyheaderPtr->Poly1stPt; - - polyPtr->PolyPoint[0] = *(ShapePointsPtr + *vertexNumberPtr++); - polyPtr->PolyPoint[1] = *(ShapePointsPtr + *vertexNumberPtr++); - polyPtr->PolyPoint[2] = *(ShapePointsPtr + *vertexNumberPtr++); - - if (*vertexNumberPtr != Term) - { - polyPtr->PolyPoint[3] = *(ShapePointsPtr + *vertexNumberPtr); - polyPtr->NumberOfVertices=4; - } - else - { - polyPtr->NumberOfVertices=3; - } - - return; -} -void GetPolygonNormal(struct ColPolyTag *polyPtr) -{ - if (ShapeIsMorphed) - { - VECTORCH n1Ptr = *(VECTORCH*)(ShapeNormalsPtr + PolyheaderPtr->PolyNormalIndex); - VECTORCH n2Ptr = *(VECTORCH*)(Shape2NormalsPtr + PolyheaderPtr->PolyNormalIndex); - - if( ((n1Ptr.vx == n2Ptr.vx) - && (n1Ptr.vy == n2Ptr.vy) - && (n1Ptr.vz == n2Ptr.vz)) - || (MorphDisplay.md_lerp == 0) ) - { - polyPtr->PolyNormal = n1Ptr; - } - else if(MorphDisplay.md_lerp == 0xffff) - { - polyPtr->PolyNormal = n2Ptr; - } - else - { - VECTORCH *pointPtr[3]; - int *vertexNumPtr = &PolyheaderPtr->Poly1stPt; - - pointPtr[0] = (ShapePointsPtr + *vertexNumPtr++); - pointPtr[1] = (ShapePointsPtr + *vertexNumPtr++); - pointPtr[2] = (ShapePointsPtr + *vertexNumPtr); - - MakeNormal - ( - pointPtr[0], - pointPtr[1], - pointPtr[2], - &polyPtr->PolyNormal - ); - } - } - else /* not morphed */ - { - polyPtr->PolyNormal = *(VECTORCH*)(ShapeNormalsPtr + PolyheaderPtr->PolyNormalIndex); - - /* KJL 20:55:36 05/14/97 - turned off for alpha */ - #if 0 - if( (polyPtr->PolyNormal.vx==0) - &&(polyPtr->PolyNormal.vy==0) - &&(polyPtr->PolyNormal.vz==0) ) - { - textprint("shape data has zero normal\n"); - } - #endif - - } - return; -} - -/*-----------------------Patrick 1/12/96-------------------------- - I have added this function to initialise polygon access for a - module based on the shape index specified in its mapblock.... - Specifically, this is for setting up location data for modules - during game initialisation, and so doesn't support morphing. - ----------------------------------------------------------------*/ -int SetupPolygonAccessFromShapeIndex(int shapeIndex) -{ - SHAPEHEADER *shape1Ptr; - - shape1Ptr = GetShapeData(shapeIndex); - ShapePointsPtr = (VECTORCH *)(*shape1Ptr->points); - ShapeNormalsPtr = (int *)(*shape1Ptr->sh_normals); - ItemArrayPtr = (int **)shape1Ptr->items; - ShapeIsMorphed=0; - - { - int *itemPtr = *ItemArrayPtr; - PolyheaderPtr = (POLYHEADER *) itemPtr; - } - - return shape1Ptr->numitems; -} - -/*--------------------Patrick 17/12/96---------------------------- - I have added some more shape data access functions...... - PSX versions are required. - ----------------------------------------------------------------*/ - -static VECTORCH patPointData; -static int patPolyVertexIndices[4]; -static VECTORCH *patShapePointsPtr; - -int SetupPointAccessFromShapeIndex(int shapeIndex) -{ - SHAPEHEADER *shapePtr; - - shapePtr = GetShapeData(shapeIndex); - patShapePointsPtr = (VECTORCH *)(*shapePtr->points); - - return shapePtr->numpoints; -} - - -VECTORCH* AccessNextPoint(void) -{ - patPointData = *patShapePointsPtr++; - return &patPointData; -} - -VECTORCH* AccessPointFromIndex(int index) -{ - patPointData = patShapePointsPtr[index]; - return &patPointData; -} - -/* KJL 18:51:08 21/11/98 - similiar function for polys */ -POLYHEADER *AccessPolyFromIndex(int index) -{ - int *itemPtr = *(ItemArrayPtr+index); - PolyheaderPtr = (POLYHEADER *) itemPtr; - return PolyheaderPtr; -} - -void DestroyPolygon(int shapeIndex,int polyIndex) -{ - SHAPEHEADER *shapePtr = GetShapeData(shapeIndex); - shapePtr->numitems--; - *(ItemArrayPtr+polyIndex) = *(ItemArrayPtr+shapePtr->numitems); -} - -void ReplaceVertexInPolygon(int polyIndex, int oldVertex, int newVertex) -{ - int *vertexNumberPtr; - int *itemPtr = *(ItemArrayPtr+polyIndex); - PolyheaderPtr = (POLYHEADER *) itemPtr; - - vertexNumberPtr = &PolyheaderPtr->Poly1stPt; - - while(*vertexNumberPtr != Term) - { - if (*vertexNumberPtr == oldVertex) - { - *vertexNumberPtr = newVertex; - } - vertexNumberPtr++; - } - - { - VECTORCH newNormal; - VECTORCH *pointPtr[3]; - int *vertexNumPtr = &PolyheaderPtr->Poly1stPt; - pointPtr[0] = (ShapePointsPtr + *vertexNumPtr++); - pointPtr[1] = (ShapePointsPtr + *vertexNumPtr++); - pointPtr[2] = (ShapePointsPtr + *vertexNumPtr); - MakeNormal - ( - pointPtr[0], - pointPtr[1], - pointPtr[2], - &newNormal - ); - *(VECTORCH*)(ShapeNormalsPtr + PolyheaderPtr->PolyNormalIndex)=newNormal; - } - - -} -VECTORCH *GetPolygonNormalFromIndex(void) -{ - return (VECTORCH*)(ShapeNormalsPtr + PolyheaderPtr->PolyNormalIndex); -} - -int *GetPolygonVertexIndices(void) -{ - int *vertexNumberPtr = &PolyheaderPtr->Poly1stPt; - int numberOfVertices=0; - - patPolyVertexIndices[3] = -1; - - while(*vertexNumberPtr != Term) - { - patPolyVertexIndices[numberOfVertices++] = (*vertexNumberPtr); - vertexNumberPtr++; - } - - return &patPolyVertexIndices[0]; -} - - -/*--------------------Roxby 3/7/97---------------------------- - I have added some more shape data access functions...... - taken from PSX versions - ----------------------------------------------------------------*/ - - -void SetupPolygonFlagAccessForShape(SHAPEHEADER *shape) -{ -} - - -int Request_PolyFlags(void *polygon) -{ - POLYHEADER *poly = (POLYHEADER*)polygon; - return poly->PolyFlags; -} diff --git a/3dc/win95/plat_shp.h b/3dc/win95/plat_shp.h deleted file mode 100644 index c6551d8..0000000 --- a/3dc/win95/plat_shp.h +++ /dev/null @@ -1,11 +0,0 @@ -/* Plat_Shp.h */ - - -extern void SetupPolygonFlagAccessForShape(SHAPEHEADER *shape); -extern int Request_PolyFlags(void *polygon); - -extern int SetupPolygonAccess(DISPLAYBLOCK *objectPtr); -extern void AccessNextPolygon(void); -extern void GetPolygonVertices(struct ColPolyTag *polyPtr); -extern void GetPolygonNormal(struct ColPolyTag *polyPtr); -extern int SetupPolygonAccessFromShapeIndex(int shapeIndex); diff --git a/3dc/win95/platform.h b/3dc/win95/platform.h deleted file mode 100644 index 7cab03d..0000000 --- a/3dc/win95/platform.h +++ /dev/null @@ -1,939 +0,0 @@ -#ifndef PLATFORM_INCLUDED - -/* - - Platform Specific Header Include - -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - Minimise header files to - speed compiles... -*/ - -#define WIN32_LEAN_AND_MEAN - -/* - Standard windows functionality -*/ - -#include <windows.h> -#include <windowsx.h> -#include <winuser.h> -#include <mmsystem.h> -#include <stdlib.h> -#include <stdarg.h> -#include <stdio.h> - -/* - DirectX functionality -*/ - -#include "ddraw.h" -#include "d3d.h" -#include "dsound.h" -#include "dplay.h" -#include "dinput.h" -#include "dplobby.h" -//#include "fastfile.h" - - -#define platform_pc Yes - -#define Saturn No - -#define Hardware2dTextureClipping No - - -/* - - Types - -*/ - -typedef RECT RECT_AVP; - - -/* Watcom C 64-bit values */ - -typedef struct LONGLONGCH { - - unsigned int lo32; - int hi32; - -} LONGLONGCH; - - -/* - - Sine and Cosine - -*/ - -#define GetSin(a) sine[a] -#define GetCos(a) cosine[a] - -/* - Available processor types -*/ - -typedef enum { - - PType_OffBottomOfScale, - PType_486, - PType_Pentium, - PType_P6, - PType_PentiumMMX, - PType_Klamath, - PType_OffTopOfScale - -} PROCESSORTYPES; - - -/* - - VGA Palette Entry - -*/ - -typedef struct vgapaletteentry { - - unsigned char vga_r; - unsigned char vga_g; - unsigned char vga_b; - -} VGAPALETTEENTRY; - - -extern void LoadAndChangeToPalette(char*); - -/* - Video mode decsription (to be filled - in by DirectDraw callback). -*/ - -typedef struct videomodeinfo { - - int Width; /* in pixels */ - int Height; /* in pixels */ - int ColourDepth; /* in bits per pixel */ - -} VIDEOMODEINFO; - -/* - Maximum number of display modes - that could be detected on unknown - hardware. -*/ - -#define MaxAvailableVideoModes 100 - -/* - #defines, structures etc for - textprint system -*/ - -#define MaxMsgChars 100 -#define MaxMessages 20 - -/* Font description */ - -#define CharWidth 8 /* In PIXELS, not bytes */ -#define CharHeight 10 /* In PIXELS, not bytes */ -#define CharVertSep (CharHeight + 0) /* In PIXELS, not bytes */ - -#define FontStart 33 // random squiggle in standard ASCII -#define FontEnd 127 // different random squiggle in standard ASCII - -#define FontInvisValue 0x00 // value to be colour keyed out of font blit - -typedef struct printqueueitem { - - char text[MaxMsgChars]; - int text_length; - int x; - int y; - -} PRINTQUEUEITEM; - - - -/* KJL 12:30:05 9/9/97 - new keyboard, mouse etc. enum */ -enum KEY_ID -{ - KEY_ESCAPE, - - KEY_0, - KEY_1, - KEY_2, - KEY_3, - KEY_4, - KEY_5, - KEY_6, - KEY_7, - KEY_8, - KEY_9, - - KEY_A, - KEY_B, - KEY_C, - KEY_D, - KEY_E, - KEY_F, - KEY_G, - KEY_H, - KEY_I, - KEY_J, - KEY_K, - KEY_L, - KEY_M, - KEY_N, - KEY_O, - KEY_P, - KEY_Q, - KEY_R, - KEY_S, - KEY_T, - KEY_U, - KEY_V, - KEY_W, - KEY_X, - KEY_Y, - KEY_Z, - - KEY_LEFT, - KEY_RIGHT, - KEY_UP, - KEY_DOWN, - KEY_CR, - KEY_TAB, - KEY_INS, - KEY_DEL, - KEY_END, - KEY_HOME, - KEY_PAGEUP, - KEY_PAGEDOWN, - KEY_BACKSPACE, - KEY_COMMA, - KEY_FSTOP, - KEY_SPACE, - - KEY_LEFTSHIFT, - KEY_RIGHTSHIFT, - KEY_LEFTALT, - KEY_RIGHTALT, - KEY_LEFTCTRL, - KEY_RIGHTCTRL, - - KEY_CAPS, - KEY_NUMLOCK, - KEY_SCROLLOK, - - KEY_NUMPAD0, - KEY_NUMPAD1, - KEY_NUMPAD2, - KEY_NUMPAD3, - KEY_NUMPAD4, - KEY_NUMPAD5, - KEY_NUMPAD6, - KEY_NUMPAD7, - KEY_NUMPAD8, - KEY_NUMPAD9, - KEY_NUMPADSUB, - KEY_NUMPADADD, - KEY_NUMPADDEL, - KEY_NUMPADENTER, - KEY_NUMPADDIVIDE, - KEY_NUMPADMULTIPLY, - - KEY_LBRACKET, - KEY_RBRACKET, - KEY_SEMICOLON, - KEY_APOSTROPHE, - KEY_GRAVE, - KEY_BACKSLASH, - KEY_SLASH, - KEY_CAPITAL, - KEY_MINUS, - KEY_EQUALS, - KEY_LWIN, - KEY_RWIN, - KEY_APPS, - - - KEY_F1, - KEY_F2, - KEY_F3, - KEY_F4, - KEY_F5, - KEY_F6, - KEY_F7, - KEY_F8, - KEY_F9, - KEY_F10, - KEY_F11, - KEY_F12, - - KEY_JOYSTICK_BUTTON_1, - KEY_JOYSTICK_BUTTON_2, - KEY_JOYSTICK_BUTTON_3, - KEY_JOYSTICK_BUTTON_4, - KEY_JOYSTICK_BUTTON_5, - KEY_JOYSTICK_BUTTON_6, - KEY_JOYSTICK_BUTTON_7, - KEY_JOYSTICK_BUTTON_8, - KEY_JOYSTICK_BUTTON_9, - KEY_JOYSTICK_BUTTON_10, - KEY_JOYSTICK_BUTTON_11, - KEY_JOYSTICK_BUTTON_12, - KEY_JOYSTICK_BUTTON_13, - KEY_JOYSTICK_BUTTON_14, - KEY_JOYSTICK_BUTTON_15, - KEY_JOYSTICK_BUTTON_16, - - KEY_LMOUSE, - KEY_MMOUSE, - KEY_RMOUSE, - - KEY_MOUSEBUTTON4, - KEY_MOUSEWHEELUP, - KEY_MOUSEWHEELDOWN, - - // Dutch - KEY_ORDINAL, - KEY_LESSTHAN, - KEY_PLUS, - - // French - KEY_RIGHTBRACKET, - KEY_ASTERISK, - KEY_DOLLAR, - KEY_U_GRAVE, - KEY_EXCLAMATION, - KEY_COLON, - - // German - KEY_BETA, - KEY_A_UMLAUT, - KEY_O_UMLAUT, - KEY_U_UMLAUT, - KEY_HASH, - - // Spanish - KEY_UPSIDEDOWNEXCLAMATION, - KEY_C_CEDILLA, - KEY_N_TILDE, - - // accents & diacritics - KEY_DIACRITIC_GRAVE, - KEY_DIACRITIC_ACUTE, - KEY_DIACRITIC_CARET, - KEY_DIACRITIC_UMLAUT, - - - KEY_VOID=255, // used to indicate a blank spot in the key config - MAX_NUMBER_OF_INPUT_KEYS, - -}; -/* - Mouse handler modes (velocity mode is for - interfacing to input functions that need - to read the mouse velocity, e.g. WeRequest - functions, while poistion mode is for menus - and similar problems). - - The initial mode is defined as a compiled in - global in game.c -*/ - -typedef enum { - - MouseVelocityMode, - MousePositionMode - -} MOUSEMODES; - - -/* Defines for the purpose of familiarity of name only */ - -#define LeftButton 0x0001 -#define RightButton 0x0002 -#define MiddleButton 0x0004 - - - - -/* - Video Modes -*/ - -typedef enum { - - VideoMode_DX_320x200x8, - VideoMode_DX_320x200x8T, - VideoMode_DX_320x200x15, - VideoMode_DX_320x240x8, - - VideoMode_DX_640x480x8, - VideoMode_DX_640x480x8T, - VideoMode_DX_640x480x15, - VideoMode_DX_640x480x24, - - VideoMode_DX_800x600x8, - VideoMode_DX_800x600x8T, - VideoMode_DX_800x600x15, - VideoMode_DX_800x600x24, - - VideoMode_DX_1024x768x8, - VideoMode_DX_1024x768x8T, - VideoMode_DX_1024x768x15, - VideoMode_DX_1024x768x24, - - VideoMode_DX_1280x1024x8, - VideoMode_DX_1280x1024x8T, - VideoMode_DX_1280x1024x15, - VideoMode_DX_1280x1024x24, - - VideoMode_DX_1600x1200x8, - VideoMode_DX_1600x1200x8T, - VideoMode_DX_1600x1200x15, - VideoMode_DX_1600x1200x24, - - MaxVideoModes - -} VIDEOMODES; - - -#define MaxScreenWidth 1600 /* Don't get this wrong! */ - - -/* - Max no of palettes -- at present there is NO - code for palette switching and ALL palette - calls within the DirectDraw interface system - run on palette 0 -*/ - -#define MaxPalettes 4 - -/* - - Video Mode Types - -*/ - -typedef enum { - - VideoModeType_8, - VideoModeType_15, - VideoModeType_24, - VideoModeType_8T - -} VIDEOMODETYPES; - - -/* - Windows modes -*/ - -typedef enum { - - WindowModeFullScreen, - WindowModeSubWindow - -} WINDOWMODES; - -typedef struct WinScaleXY { - - float x; - float y; - -} WINSCALEXY; - - -/* - Dubious hack for dubious - aspects of DirectDraw initialisation -*/ - -typedef enum { - - /* Default */ - NoRestartRequired, - /* - Characteristic of driver which - will not support changing to a different - bit depth without rebooting - */ - RestartDisplayModeNotAvailable, - /* - Characteristic of ModeX emulation leading - to no video memory being available because - of the need to cooperate with a large existing - GDI surface which cannot be reduced without a - reboot - */ - RestartOutOfVidMemForPrimary - -} VIDEORESTARTMODES; - -/* - Load modes for putting an image - in a DirectDraw surface --- either - do or do not deallocate the - system memory image, but always - keep the DirectDraw one -*/ - -typedef enum { - - LoadModeDirectDrawOnly, - LoadModeFull - -} IMAGELOADMODES; - - -/* - Direct3D driver modes -*/ - -typedef enum { - - D3DSoftwareRGBDriver, - D3DSoftwareRampDriver, - D3DHardwareRGBDriver - -} D3DMODES; - -/* - Software scan draw request modes -*/ - -typedef enum { - - RequestScanDrawDirectDraw, - RequestScanDrawSoftwareRGB, - RequestScanDrawRamp, - RequestScanDrawDefault - -} SOFTWARESCANDRAWREQUESTMODES; - -/* - Rasterisation request modes -*/ - -typedef enum { - - RequestSoftwareRasterisation, - RequestDefaultRasterisation - -} RASTERREQUESTMODES; - - -/* - Actual scan draw mode -*/ - -typedef enum { - - ScanDrawDirectDraw, - ScanDrawD3DRamp, - ScanDrawD3DSoftwareRGB, - ScanDrawD3DHardwareRGB - -} SCANDRAWMODES; - - -/* - Z buffering request modes -*/ - -typedef enum { - - RequestZBufferNever, - RequestZBufferAlways, - RequestZBufferDefault - -} ZBUFFERREQUESTMODES; - -/* - Z buffering modes -*/ - -typedef enum { - - ZBufferOn, - ZBufferWriteOnly, - ZBufferOff - -} ZBUFFERMODES; - -/* - Request modes for DirectX - memory usage -*/ - -typedef enum { - - RequestSystemMemoryAlways, - RequestDefaultMemoryAllocation - -} DXMEMORYREQUESTMODES; - - -/* - DirectX memory usage modes -*/ - -typedef enum { - - SystemMemoryPreferred, - VideoMemoryPreferred - -} DXMEMORYMODES; - -/* - - .BMP File header - -*/ - -/* - Pack the header to 1 byte alignment so that the - loader works (John's code, still under test). -*/ - -#ifdef __WATCOMC__ -#pragma pack (1) -#endif - -typedef struct bmpheader { - - unsigned short BMP_ID; /* Contains 'BM' */ - int BMP_Size; - - short BMP_Null1; - short BMP_Null2; - - int BMP_Image; /* Byte offset of image start relative to offset 14 */ - int BMP_HeadSize; /* Size of header (40 for Windows, 12 for OS/2) */ - int BMP_Width; /* Width of image in pixels */ - int BMP_Height; /* Height of image in pixels */ - - short BMP_Planes; /* Number of image planes (must be 1) */ - short BMP_Bits; /* Number of bits per pixel (1,4,8 or 24) */ - - int BMP_Comp; /* Compression type */ - int BMP_CSize; /* Size in bytes of compressed image */ - int BMP_Hres; /* Horizontal resolution in pixels/meter */ - int BMP_Vres; /* Vertical resolution in pixels/meter */ - int BMP_Colours; /* Number of colours used, below (N) */ - int BMP_ImpCols; /* Number of important colours */ - -} BMPHEADER; - -#ifdef __WATCOMC__ -#pragma pack (4) -#endif - -/* - Types of texture files that can be - requested from the main D3D texture - loader. -*/ - -typedef enum { - - TextureTypePGM, - TextureTypePPM - -} TEXTUREFILETYPE; - -/* - Windows initialisation modes. - See InitialiseWindowsSystem - in the default win_proj.cpp - for a full description. -*/ - -typedef enum { - - WinInitFull, - WinInitChange - -} WININITMODES; - -/* - - Triangle Array Limits etc. - -*/ - -#define maxarrtriangles 7 /* Could be 6 if all shape data in triangles */ -#define trianglesize (1 + 1 + 1 + 1 + (6 * 3) + 1) /* largest, could be 5*3 if no 3d texturing */ -#define pta_max 9 /* Could be 8 if all shape data in triangles */ - -/* header + xy + terminator */ -#define item_polygon_trianglesize (1 + 1 + 1 + 1 + (2 * 3) + 1) -/* header + xyi + terminator */ -#define item_gouraudpolygon_trianglesize (1 + 1 + 1 + 1 + (3 * 3) + 1) -/* header + xyuv + terminator */ -#define item_2dtexturedpolygon_trianglesize (1 + 1 + 1 + 1 + (4 * 3) + 1) -/* header + xyuvi + terminator */ -#define item_gouraud2dtexturedpolygon_trianglesize (1 + 1 + 1 + 1 + (5 * 3) + 1) -/* header + xyuvw + terminator */ -#define item_3dtexturedpolygon_trianglesize (1 + 1 + 1 + 1 + (5 * 3) + 1) -/* header + xyuvwi + terminator */ -#define item_gouraud3dtexturedpolygon_trianglesize (1 + 1 + 1 + 1 + (6 * 3) + 1) - -/* - - Vertex sizes - - For copying vertices from item list polygons to triangles - - e.g. - - Vertex 2 (x component) of the quad would be (for Item_Polygon) - - q[2 * i_poly_vsize + i_vstart + ix] - - WARNING: If the item format changes these MUST be updated - -*/ - -#define vstart 4 - -#define poly_vsize 2 -#define gpoly_vsize 3 -#define t2poly_vsize 4 -#define gt2poly_vsize 5 -#define t3poly_vsize 5 -#define gt3poly_vsize 6 - - - -/* - - Triangle Array Structure - -*/ - -typedef struct trianglearray { - - int TA_NumTriangles; - int *TA_ItemPtr; - int *TA_TriangleArray[maxarrtriangles]; - -} TRIANGLEARRAY; - -/* - Function prototypes -*/ - -/* - Windows functionality. Note current - DirectInput functions are also here since - they are really part of the Win32 multimedia - library. -*/ - -long GetWindowsTickCount(void); -void CheckForWindowsMessages(void); -BOOL ExitWindowsSystem(void); -BOOL InitialiseWindowsSystem(HANDLE hInstance, int nCmdShow, int WinInitMode); -void KeyboardHandlerKeyDown(WPARAM wParam); -void KeyboardHandlerKeyUp(WPARAM wParam); -void MouseVelocityHandler(UINT message, LPARAM lParam); -void MousePositionHandler(UINT message, LPARAM lParam); -int ReadJoystick(void); -int CheckForJoystick(void); -BOOL SpawnRasterThread(); -BOOL WaitForRasterThread(); - - -/* DirectDraw */ -void finiObjects(void); -void GenerateDirectDrawSurface(void); -void LockSurfaceAndGetBufferPointer(void); -void UnlockSurface(void); -void finiObjects(void); -void ColourFillBackBuffer(int FillColour); -void ColourFillBackBufferQuad(int FillColour, int LeftX, - int TopY, int RightX, int BotY); -void FlipBuffers(void); -void BlitToBackBuffer(void* lpBackground, RECT* destRectPtr, RECT* srcRectPtr); -void BlitToBackBufferWithoutTearing(void* lpBackground, RECT* destRectPtr, RECT* srcRectPtr); -void BlitWin95Char(int x, int y, unsigned char toprint); -void ReleaseDDSurface(void* DDSurface); -BOOL InitialiseDirectDrawObject(void); -BOOL ChangeDirectDrawObject(void); -BOOL CheckForVideoModes(int TestVideoMode); -void finiObjectsExceptDD(void); -BOOL TestMemoryAccess(void); -int ChangePalette (unsigned char* NewPalette); -int GetAvailableVideoMemory(void); -void HandleVideoModeRestarts(HINSTANCE hInstance, int nCmdShow); -void* MakeBackdropSurface(void); -void ReleaseBackdropSurface(void); -void LockBackdropSurface(void); -void UnlockBackdropSurface(void); -void ComposeBackdropBackBuffer(void); -int GetSingleColourForPrimary(int Colour); - -/* - DirectX functionality only available in - C++ under Watcom at present -*/ -#ifdef __cplusplus -HRESULT CALLBACK EnumDisplayModesCallback(LPDDSURFACEDESC pddsd, LPVOID Context); -BOOL FAR PASCAL EnumDDObjectsCallback(GUID FAR* lpGUID, LPSTR lpDriverDesc, - LPSTR lpDriverName, LPVOID lpContext); -#if triplebuffer -/* - must be WINAPI to support Windows FAR PASCAL - calling convention. Must be HRESULT to support - enumeration return value. NOTE THIS FUNCTION - DOESN'T WORK (DOCS WRONG) AND TRIPLE BUFFERING - HAS BEEN REMOVED ANYWAY 'COS IT'S USELESS... -*/ -HRESULT WINAPI InitTripleBuffers(LPDIRECTDRAWSURFACE lpdd, - LPDDSURFACEDESC lpsd, LPVOID lpc); -#endif -#endif - -/* Direct 3D Immediate Mode Rasterisation Module */ -BOOL InitialiseDirect3DImmediateMode(void); -BOOL LockExecuteBuffer(void); -BOOL UnlockExecuteBufferAndPrepareForUse(void); -BOOL BeginD3DScene(void); -BOOL EndD3DScene(void); -BOOL ExecuteBuffer(void); -BOOL RenderD3DScene(void); -void ReleaseDirect3D(void); -void WritePolygonToExecuteBuffer(int* itemptr); -void WriteGouraudPolygonToExecuteBuffer(int* itemptr); -void Write2dTexturedPolygonToExecuteBuffer(int* itemptr); -void WriteGouraud2dTexturedPolygonToExecuteBuffer(int* itemptr); -void Write3dTexturedPolygonToExecuteBuffer(int* itemptr); -void WriteGouraud3dTexturedPolygonToExecuteBuffer(int* itemptr); -void WriteBackdrop2dTexturedPolygonToExecuteBuffer(int* itemptr); -void WriteBackdrop3dTexturedPolygonToExecuteBuffer(int* itemptr); -void WriteEndCodeToExecuteBuffer(void); -void ReleaseD3DTexture(void* D3DTexture); -void ReleaseDirect3DNotDD(void); -void ReleaseDirect3DNotDDOrImages(void); -BOOL SetExecuteBufferDefaults(void); -void SelectD3DDriverAndDrawMode(void); -#if SUPPORT_MMX -void SelectMMXOptions(void); -#endif -BOOL TestInitD3DObject(void); - -#if SupportZBuffering -BOOL CreateD3DZBuffer(void); -void FlushD3DZBuffer(void); -void WriteZBPolygonToExecuteBuffer(int* itemptr); -void WriteZBGouraudPolygonToExecuteBuffer(int* itemptr); -void WriteZB2dTexturedPolygonToExecuteBuffer(int* itemptr); -void WriteZBGouraud2dTexturedPolygonToExecuteBuffer(int* itemptr); -void WriteZB3dTexturedPolygonToExecuteBuffer(int* itemptr); -void WriteZBGouraud3dTexturedPolygonToExecuteBuffer(int* itemptr); -#endif - -#ifdef __cplusplus -HRESULT WINAPI DeviceEnumerator(LPGUID lpGuid, - LPSTR lpDeviceDescription, LPSTR lpDeviceName, - LPD3DDEVICEDESC lpHWDesc, LPD3DDEVICEDESC lpHELDesc, LPVOID lpContext); -HRESULT CALLBACK TextureFormatsEnumerator - (LPDDSURFACEDESC lpDDSD, LPVOID lpContext); -#endif - -/* KJL 11:28:31 9/9/97 - Direct Input prototypes */ -BOOL InitialiseDirectInput(void); -void ReleaseDirectInput(void); -BOOL InitialiseDirectKeyboard(); -void DirectReadKeyboard(void); -void ReleaseDirectKeyboard(void); -BOOL InitialiseDirectMouse(); -void DirectReadMouse(void); -void ReleaseDirectMouse(void); - -/* - Internal -*/ -#ifdef AVP_DEBUG_VERSION -int textprint(const char* t, ...); -#else -#define textprint(ignore) -#endif - - -void MakePaletteShades(VGAPALETTEENTRY *vga_palptr, int hue, int pal_shades_per_hue); -void ConvertToDDPalette(unsigned char* src, unsigned char* dst, int length, int flags); -int textprintXY(int x, int y, const char* t, ...); -void LoadSystemFonts(char* fname); -void DisplayWin95String(int x, int y, unsigned char *buffer); -void WriteStringToTextBuffer(int x, int y, unsigned char *buffer); -void FlushTextprintBuffer(void); -void InitPrintQueue(void); -void InitJoysticks(void); -void ReadJoysticks(void); -int ChangeDisplayModes(HINSTANCE hInst, int nCmd, - int NewVideoMode, int NewWindowMode, - int NewZBufferMode, int NewRasterisationMode, - int NewSoftwareScanDrawMode, int NewDXMemoryMode); -int DeallocateAllImages(void); -int MinimizeAllImages(void); -int RestoreAllImages(void); -void ConvertDDToInternalPalette(unsigned char* src, unsigned char* dst, int length); -PROCESSORTYPES ReadProcessorType(void); - -/* EXTERNS FOR GLOBALS GO HERE !!!!!! */ -extern DDCAPS direct_draw_caps; - -/* - - Jake's image functions - -*/ - -void * CopyD3DTexture(struct imageheader *iheader); - -#ifdef MaxImageGroups - - #if (MaxImageGroups > 1) - - void SetCurrentImageGroup(unsigned int group); - int DeallocateCurrentImages(void); - - #endif /* MaxImageGroups > 1 */ - -#endif /* defined(MaxImageGroups) */ - - -/* - Project callbacks -*/ - -void ExitGame(void); - -void ProjectSpecificBufferFlipPostProcessing(); - -void ProjectSpecificItemListPostProcessing(); - -#if optimiseflip -void ProcessProjectWhileWaitingToBeFlippable(); -#endif - -#ifdef __cplusplus -}; -#endif - -#define PLATFORM_INCLUDED - -#endif diff --git a/3dc/win95/plspecfn.c b/3dc/win95/plspecfn.c deleted file mode 100644 index 26c9527..0000000 --- a/3dc/win95/plspecfn.c +++ /dev/null @@ -1,1475 +0,0 @@ - -#include "3dc.h" - -#include <math.h> - -#include "inline.h" -#include "module.h" -#include "stratdef.h" -#include "gamedef.h" -#include "bh_types.h" -#include "pvisible.h" - - - -#if SupportWindows95 -#include "krender.h" /* KJL 10:48:25 02/05/97 */ -#include "kzsort.h" -#include "kshape.h" -#endif - - -/* - - Platform Specific Functions - - These functions have been written specifically for a given platform. - - They are not necessarily IO or inline functions; these have their own files. - -*/ - - -/* - - externs for commonly used global variables and arrays - -*/ - - extern VECTORCH RotatedPts[]; - extern unsigned int Outcodes[]; - extern DISPLAYBLOCK *Global_ODB_Ptr; - extern VIEWDESCRIPTORBLOCK *Global_VDB_Ptr; - extern SHAPEHEADER *Global_ShapeHeaderPtr; - extern MATRIXCH LToVMat; - #if SupportMorphing - extern VECTORCH MorphedPts[]; - extern MORPHDISPLAY MorphDisplay; - #endif - - extern DISPLAYBLOCK *OnScreenBlockList[]; - extern int NumOnScreenBlocks; - extern int NumActiveBlocks; - extern DISPLAYBLOCK *ActiveBlockList[]; - #if SupportModules - extern char *ModuleLocalVisArray; - #endif - - - -/* - - Global Variables - -*/ - - LONGLONGCH ll_one14 = {one14, 0}; - LONGLONGCH ll_zero = {0, 0}; - - - - - - -/* - - Find out which objects are in the View Volume. - - The list of these objects, "OnScreenBlockList", is constructed in a number - of stages. - - The Range Test is a simple outcode of the View Space Location against the - Object Radius. The View Volume Test is more involved. The VSL is tested - against each of the View Volume Planes. If it is more than one Object Radius - outside any plane, the test fails. - -*/ - -/* - - This is the main view volume test shell - -*/ - - - - - - - - -#if StandardShapeLanguage - - -/* - - Shape Points - - The item array is a table of pointers to item arrays. The points data is - in the first and only item array. - - Rotate each point and write it out to the Rotated Points Buffer - - NOTE: - - There is a global pointer to the shape header "Global_ShapeHeaderPtr" - -*/ - - -#define print_bfcro_stats No - -#if SupportMorphing -#define checkmorphpts No -#endif - - -void ShapePointsInstr(SHAPEINSTR *shapeinstrptr) - -{ - - int **shapeitemarrayptr; - int *shapeitemptr; - VECTORCH *rotptsptr; - int x, y, z; - int numitems; - #if print_bfcro_stats - int num_rot, num_not_rot; - #endif - - - - /* - - Kevin, morphed doors WON'T be using shared points, so I've put your - patch here, AFTER the intercept for the shared version of the points - instruction -- Chris. - - */ - - #if KZSORT_ON /* KJL 15:13:46 02/07/97 - used for z-sorting doors correctly! */ - { - extern int *MorphedObjectPointsPtr; - MorphedObjectPointsPtr = 0; - } - #endif - - - /* Set up pointers */ - - shapeitemarrayptr = shapeinstrptr->sh_instr_data; - shapeitemptr = *shapeitemarrayptr; - rotptsptr = &RotatedPts[0]; - - - - #if SupportMorphing - - if(Global_ODB_Ptr->ObMorphCtrl) { - - - #if LazyEvaluationForMorphing - - VECTORCH *morphptsptr; - - if(Global_ODB_Ptr->ObMorphedPts == 0) { - - Global_ODB_Ptr->ObMorphedPts = GetMorphedPts(Global_ODB_Ptr, - &MorphDisplay); - - } - - morphptsptr = Global_ODB_Ptr->ObMorphedPts; - - GLOBALASSERT(shapeinstrptr->sh_numitems<maxmorphPts); - - for(numitems = shapeinstrptr->sh_numitems; numitems!=0; numitems--) { - - #if SUPPORT_MMX - if (use_mmx_math) - MMX_VectorTransformedAndAdd(rotptsptr,morphptsptr,<oVMat,&Global_ODB_Ptr->ObView); - else - #endif - { - rotptsptr->vx = MUL_FIXED(LToVMat.mat11, morphptsptr->vx); - rotptsptr->vx += MUL_FIXED(LToVMat.mat21, morphptsptr->vy); - rotptsptr->vx += MUL_FIXED(LToVMat.mat31, morphptsptr->vz); - rotptsptr->vx += Global_ODB_Ptr->ObView.vx; - - rotptsptr->vy = MUL_FIXED(LToVMat.mat12, morphptsptr->vx); - rotptsptr->vy += MUL_FIXED(LToVMat.mat22, morphptsptr->vy); - rotptsptr->vy += MUL_FIXED(LToVMat.mat32, morphptsptr->vz); - rotptsptr->vy += Global_ODB_Ptr->ObView.vy; - - rotptsptr->vz = MUL_FIXED(LToVMat.mat13, morphptsptr->vx); - rotptsptr->vz += MUL_FIXED(LToVMat.mat23, morphptsptr->vy); - rotptsptr->vz += MUL_FIXED(LToVMat.mat33, morphptsptr->vz); - rotptsptr->vz += Global_ODB_Ptr->ObView.vz; - } - - rotptsptr->vy = MUL_FIXED(rotptsptr->vy,87381); - morphptsptr++; - rotptsptr++; - - } - - - #else /* LazyEvaluationForMorphing */ - - - VECTORCH *morphptsptr = &MorphedPts[0]; - SHAPEHEADER *sptr1; - SHAPEHEADER *sptr2; - int *shapeitemptr1; - int *shapeitemptr2; - int x1, y1, z1; - int x2, y2, z2; - #if checkmorphpts - int num_old_pts = 0; - int num_new_pts = 0; - #endif - - - /*textprint("morphing points\n");*/ - - sptr1 = MorphDisplay.md_sptr1; - sptr2 = MorphDisplay.md_sptr2; - - shapeitemptr1 = *(sptr1->points); - shapeitemptr2 = *(sptr2->points); - - - #if KZSORT_ON /* KJL 15:13:46 02/07/97 - used for z-sorting doors correctly! */ - { - extern int *MorphedObjectPointsPtr; - MorphedObjectPointsPtr = shapeitemptr2; - } - #endif - - - for(numitems = shapeinstrptr->sh_numitems; numitems!=0; numitems--) { - - x1 = shapeitemptr1[ix]; - y1 = shapeitemptr1[iy]; - z1 = shapeitemptr1[iz]; - - x2 = shapeitemptr2[ix]; - y2 = shapeitemptr2[iy]; - z2 = shapeitemptr2[iz]; - - if(x1 == x2 && y1 == y2 && z1 == z2) { - - x = x1; - y = y1; - z = z1; - - #if checkmorphpts - num_old_pts++; - #endif - - } - - else if(MorphDisplay.md_lerp == 0) { - - x = x1; - y = y1; - z = z1; - - } - - else if(MorphDisplay.md_lerp == 0xffff) { - - x = x2; - y = y2; - z = z2; - - } - - else - { - /* KJL 15:27:20 05/22/97 - I've changed this to speed things up, If a vertex - component has a magnitude greater than 32768 things will go wrong. */ - x = x1 + (((x2-x1)*MorphDisplay.md_lerp)>>16); - y = y1 + (((y2-y1)*MorphDisplay.md_lerp)>>16); - z = z1 + (((z2-z1)*MorphDisplay.md_lerp)>>16); - - #if checkmorphpts - num_new_pts++; - #endif - - } - - morphptsptr->vx = x; - morphptsptr->vy = y; - morphptsptr->vz = z; - - /* KJL 16:07:15 11/27/97 - I know this test is inside the loop, - but all this will go when I change to float everywhere. */ - #if MIRRORING_ON - if(!Global_ODB_Ptr->ObMyModule || MirroringActive) - #else - if (!Global_ODB_Ptr->ObMyModule) - #endif - { - #if SUPPORT_MMX - if (use_mmx_math) - MMX_VectorTransformedAndAdd(rotptsptr,morphptsptr,<oVMat,&Global_ODB_Ptr->ObView); - else - #endif - { - rotptsptr->vx = MUL_FIXED(LToVMat.mat11, x); - rotptsptr->vx += MUL_FIXED(LToVMat.mat21, y); - rotptsptr->vx += MUL_FIXED(LToVMat.mat31, z); - rotptsptr->vx += Global_ODB_Ptr->ObView.vx; - - rotptsptr->vy = MUL_FIXED(LToVMat.mat12, x); - rotptsptr->vy += MUL_FIXED(LToVMat.mat22, y); - rotptsptr->vy += MUL_FIXED(LToVMat.mat32, z); - rotptsptr->vy += Global_ODB_Ptr->ObView.vy; - - rotptsptr->vz = MUL_FIXED(LToVMat.mat13, x); - rotptsptr->vz += MUL_FIXED(LToVMat.mat23, y); - rotptsptr->vz += MUL_FIXED(LToVMat.mat33, z); - rotptsptr->vz += Global_ODB_Ptr->ObView.vz; - } - } - else /* KJL 14:33:24 11/27/97 - experiment to get rid of tears */ - { - x += Global_ODB_Ptr->ObWorld.vx - Global_VDB_Ptr->VDB_World.vx; - y += Global_ODB_Ptr->ObWorld.vy - Global_VDB_Ptr->VDB_World.vy; - z += Global_ODB_Ptr->ObWorld.vz - Global_VDB_Ptr->VDB_World.vz; - - rotptsptr->vx = MUL_FIXED(LToVMat.mat11, x); - rotptsptr->vx += MUL_FIXED(LToVMat.mat21, y); - rotptsptr->vx += MUL_FIXED(LToVMat.mat31, z); - - rotptsptr->vy = MUL_FIXED(LToVMat.mat12, x); - rotptsptr->vy += MUL_FIXED(LToVMat.mat22, y); - rotptsptr->vy += MUL_FIXED(LToVMat.mat32, z); - - rotptsptr->vz = MUL_FIXED(LToVMat.mat13, x); - rotptsptr->vz += MUL_FIXED(LToVMat.mat23, y); - rotptsptr->vz += MUL_FIXED(LToVMat.mat33, z); - } - - - shapeitemptr1 += vsize; - shapeitemptr2 += vsize; - morphptsptr++; - - rotptsptr->vy = MUL_FIXED(rotptsptr->vy,87381); - rotptsptr++; - - } - - #if checkmorphpts - textprint("num_old_pts = %d\n", num_old_pts); - textprint("num_new_pts = %d\n", num_new_pts); - #endif - - - #endif /* LazyEvaluationForMorphing */ - - - } - - else { - - #endif - - #if MIRRORING_ON - int useFirstMethod = 0; - - - if(!Global_ODB_Ptr->ObMyModule || MirroringActive) - { - useFirstMethod = 1; - } - if (Global_ODB_Ptr->ObStrategyBlock) - { - #if 0 - if(Global_ODB_Ptr->ObStrategyBlock->I_SBtype == I_BehaviourInanimateObject) - { - INANIMATEOBJECT_STATUSBLOCK* osPtr = Global_ODB_Ptr->ObStrategyBlock->SBdataptr; - if(osPtr->typeId==IOT_Static) - { - useFirstMethod=0; - } - } - #endif - } - - if(useFirstMethod) - #else - if (!Global_ODB_Ptr->ObMyModule) - #endif - { - for(numitems = shapeinstrptr->sh_numitems; numitems!=0; numitems--) - { - #if SUPPORT_MMX - if (use_mmx_math) - MMX_VectorTransformedAndAdd(rotptsptr,(VECTORCH *)shapeitemptr,<oVMat,&Global_ODB_Ptr->ObView); - else - #endif - { - x = shapeitemptr[ix]; - y = shapeitemptr[iy]; - z = shapeitemptr[iz]; - - rotptsptr->vx = MUL_FIXED(LToVMat.mat11, x); - rotptsptr->vx += MUL_FIXED(LToVMat.mat21, y); - rotptsptr->vx += MUL_FIXED(LToVMat.mat31, z); - rotptsptr->vx += Global_ODB_Ptr->ObView.vx; - - rotptsptr->vy = MUL_FIXED(LToVMat.mat12, x); - rotptsptr->vy += MUL_FIXED(LToVMat.mat22, y); - rotptsptr->vy += MUL_FIXED(LToVMat.mat32, z); - rotptsptr->vy += Global_ODB_Ptr->ObView.vy; - - rotptsptr->vz = MUL_FIXED(LToVMat.mat13, x); - rotptsptr->vz += MUL_FIXED(LToVMat.mat23, y); - rotptsptr->vz += MUL_FIXED(LToVMat.mat33, z); - rotptsptr->vz += Global_ODB_Ptr->ObView.vz; - } - shapeitemptr += 3; - rotptsptr->vy = MUL_FIXED(rotptsptr->vy,87381); - rotptsptr++; - - } - } - else - { - /* KJL 14:33:24 11/27/97 - experiment to get rid of tears */ - for(numitems = shapeinstrptr->sh_numitems; numitems!=0; numitems--) - { - x = shapeitemptr[ix]; - y = shapeitemptr[iy]; - z = shapeitemptr[iz]; - - x += Global_ODB_Ptr->ObWorld.vx - Global_VDB_Ptr->VDB_World.vx; - y += Global_ODB_Ptr->ObWorld.vy - Global_VDB_Ptr->VDB_World.vy; - z += Global_ODB_Ptr->ObWorld.vz - Global_VDB_Ptr->VDB_World.vz; - - rotptsptr->vx = MUL_FIXED(LToVMat.mat11, x); - rotptsptr->vx += MUL_FIXED(LToVMat.mat21, y); - rotptsptr->vx += MUL_FIXED(LToVMat.mat31, z); - - rotptsptr->vy = MUL_FIXED(LToVMat.mat12, x); - rotptsptr->vy += MUL_FIXED(LToVMat.mat22, y); - rotptsptr->vy += MUL_FIXED(LToVMat.mat32, z); - - rotptsptr->vz = MUL_FIXED(LToVMat.mat13, x); - rotptsptr->vz += MUL_FIXED(LToVMat.mat23, y); - rotptsptr->vz += MUL_FIXED(LToVMat.mat33, z); - shapeitemptr += 3; - rotptsptr->vy = MUL_FIXED(rotptsptr->vy,87381); - rotptsptr++; - } - - } - - #if SupportMorphing - } - #endif - - -} - - -#endif /* StandardShapeLanguage */ - - - - - - - -/* - - WideMul2NarrowDiv - - This function takes two pairs of integers, adds their 64-bit products - together, divides the summed product with another integer and then returns - the result of that divide, which is also an integer. - - It is not inlined for Watcom C, although the functions it calls ARE. - -*/ - -int WideMul2NarrowDiv(int a, int b, int c, int d, int e) - -{ - - LONGLONGCH f; - LONGLONGCH g; - - - MUL_I_WIDE(a, b, &f); - MUL_I_WIDE(c, d, &g); - ADD_LL_PP(&f, &g); - - return NarrowDivide(&f, e); - -} - - - - - -/* - - Square Root - - Returns the Square Root of a 32-bit number - -*/ - -#if (SupportFPMathsFunctions || SupportFPSquareRoot) -#else - - -int SqRoot32(int A) - -{ - - unsigned int edx = A; - unsigned int ecx; - - unsigned int ax = 0; - unsigned int bx = 0; - unsigned int di = 0; - - - for(ecx = 15; ecx!=0; ecx--) { - - bx <<= 1; - if(edx & 0x80000000) bx |= 1; - edx <<= 1; - - bx <<= 1; - if(edx & 0x80000000) bx |= 1; - edx <<= 1; - - ax += ax; - di = ax; - di += di; - - if(bx > di) { - - di++; - ax++; - - bx -= di; - - } - - } - - bx <<= 1; - if(edx & 0x80000000) bx |= 1; - edx <<= 1; - - bx <<= 1; - if(edx & 0x80000000) bx |= 1; - edx <<= 1; - - ax += ax; - di = ax; - di += di; - - if(bx > di) { - - ax++; - - } - - return ((int)ax); - -} - - -#endif /* SupportFPMathsFunctions */ - - - - - - -/* - - Calculate Plane Normal from three POP's - - The three input vectors are treated as POP's and used to make two vectors. - These are then crossed to create the normal. - - Make two vectors; (2-1) & (3-1) - Cross them - Normalise the vector - Find the magnitude of the vector - Divide each component by the magnitude - -*/ - -void MakeNormal(VECTORCH *v1, VECTORCH *v2, VECTORCH *v3, VECTORCH *v4) - -{ - - -#if SupportFPMathsFunctions - - - VECTORCHF vect0; - VECTORCHF vect1; - VECTORCHF n; - - - /* vect0 = v2 - v1 */ - - vect0.vx = v2->vx - v1->vx; - vect0.vy = v2->vy - v1->vy; - vect0.vz = v2->vz - v1->vz; - - /* vect1 = v3 - v1 */ - - vect1.vx = v3->vx - v1->vx; - vect1.vy = v3->vy - v1->vy; - vect1.vz = v3->vz - v1->vz; - - - /* nx = v0y.v1z - v0z.v1y */ - - n.vx = (vect0.vy * vect1.vz) - (vect0.vz * vect1.vy); - - /* ny = v0z.v1x - v0x.v1z */ - - n.vy = (vect0.vz * vect1.vx) - (vect0.vx * vect1.vz); - - /* nz = v0x.v1y - v0y.v1x */ - - n.vz = (vect0.vx * vect1.vy) - (vect0.vy * vect1.vx); - - - FNormalise(&n); - - f2i(v4->vx, n.vx * ONE_FIXED); - f2i(v4->vy, n.vy * ONE_FIXED); - f2i(v4->vz, n.vz * ONE_FIXED); - - - #if 0 - textprint("Magnitude of v4 = %d\n", Magnitude(v4)); - WaitForReturn(); - #endif - - - -#else /* SupportFPMathsFunctions */ - - - LONGLONGCH x; - LONGLONGCH y; - LONGLONGCH z; - LONGLONGCH tmp; - VECTORCH vect0; - VECTORCH vect1; - LONGLONGCH max_abs_xyz64; - LONGLONGCH abs_xyz[3]; - int s, shift; - - - /* vect0 = v2 - v1 */ - - vect0.vx = v2->vx - v1->vx; - vect0.vy = v2->vy - v1->vy; - vect0.vz = v2->vz - v1->vz; - - /* vect1 = v3 - v1 */ - - vect1.vx = v3->vx - v1->vx; - vect1.vy = v3->vy - v1->vy; - vect1.vz = v3->vz - v1->vz; - - - /* nx = v0y.v1z - v0z.v1y */ - - #if 0 - x = - (long long)vect0.vy * (long long)vect1.vz - -(long long)vect0.vz * (long long)vect1.vy; - #endif - - MUL_I_WIDE(vect0.vy, vect1.vz, &x); - MUL_I_WIDE(vect0.vz, vect1.vy, &tmp); - SUB_LL_MM(&x, &tmp); - - - /* ny = v0z.v1x - v0x.v1z */ - - #if 0 - y = - (long long)vect0.vz * (long long)vect1.vx - -(long long)vect0.vx * (long long)vect1.vz; - #endif - - MUL_I_WIDE(vect0.vz, vect1.vx, &y); - MUL_I_WIDE(vect0.vx, vect1.vz, &tmp); - SUB_LL_MM(&y, &tmp); - - - /* nz = v0x.v1y - v0y.v1x */ - - #if 0 - z = - (long long)vect0.vx * (long long)vect1.vy - -(long long)vect0.vy * (long long)vect1.vx; - #endif - - MUL_I_WIDE(vect0.vx, vect1.vy, &z); - MUL_I_WIDE(vect0.vy, vect1.vx, &tmp); - SUB_LL_MM(&z, &tmp); - - - /* Before we can normalise we must bring these vectors down to 14-bits */ - - #if 0 - abs_xyz[0] = x; - if(abs_xyz[0] < 0) abs_xyz[0] = -abs_xyz[0]; - - abs_xyz[1] = y; - if(abs_xyz[1] < 1) abs_xyz[1] = -abs_xyz[1]; - - abs_xyz[2] = z; - if(abs_xyz[2] < 0) abs_xyz[2] = -abs_xyz[2]; - - #endif - - EQUALS_LL(&abs_xyz[0], &x); - s = CMP_LL(&abs_xyz[0], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[0]); - - EQUALS_LL(&abs_xyz[1], &y); - s = CMP_LL(&abs_xyz[1], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[1]); - - EQUALS_LL(&abs_xyz[2], &z); - s = CMP_LL(&abs_xyz[2], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[2]); - - MaxLONGLONGCH(&abs_xyz[0], 3, &max_abs_xyz64); - - shift = FindShift64(&max_abs_xyz64, &ll_one14); - - #if 0 - x >>= shift; - y >>= shift; - z >>= shift; - #endif - - ASR_LL(&x, shift); - ASR_LL(&y, shift); - ASR_LL(&z, shift); - - /* Watcom specific copying of lower 32-bits of LONGLONGCH values */ - - v4->vx = x.lo32; - v4->vy = y.lo32; - v4->vz = z.lo32; - - - - /* Normalise the vector */ - - #if 0 - textprint("v4 = %d,%d,%d\n", x.lo32, y.lo32, z.lo32); - textprint("v4 = %d,%d,%d\n", v4->vx, v4->vy, v4->vz); - #endif - - Normalise(v4); - - #if 0 - textprint(" - v4 = %d,%d,%d\n", v4->vx, v4->vy, v4->vz); - #endif - -#endif /* SupportFPMathsFunctions */ - -} - - -/* - - Normalise a vector. - - The returned vector is a fixed point unit vector. - - WARNING! - - The vector must be no larger than 2<<14 because of the square root. - Because this is an integer function, small components produce errors. - - e.g. - - (100,100,0) - - m=141 (141.42) - - nx = 100 * ONE_FIXED / m = 46,479 - ny = 100 * ONE_FIXED / m = 46,479 - nz = 0 - - New m ought to be 65,536 but in fact is 65,731 i.e. 0.29% too large. - -*/ - -void Normalise(VECTORCH *nvector) - -{ - - -#if SupportFPMathsFunctions - - - VECTORCHF n; - float m; - - - n.vx = nvector->vx; - n.vy = nvector->vy; - n.vz = nvector->vz; - - m = 65536.0/sqrt((n.vx * n.vx) + (n.vy * n.vy) + (n.vz * n.vz)); - - f2i(nvector->vx, (n.vx * m) ); - f2i(nvector->vy, (n.vy * m) ); - f2i(nvector->vz, (n.vz * m) ); - - -#else /* SupportFPMathsFunctions */ - - - int m, s; - int xsq, ysq, zsq; - - LONGLONGCH max_abs_xyz64; - - LONGLONGCH abs_xyz[3]; - - int shift; - - - /* Before we can normalise we must bring these vectors down to 14-bits */ - - IntToLL(&abs_xyz[0], &nvector->vx); - s = CMP_LL(&abs_xyz[0], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[0]); - - IntToLL(&abs_xyz[1], &nvector->vy); - s = CMP_LL(&abs_xyz[1], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[1]); - - IntToLL(&abs_xyz[2], &nvector->vz); - s = CMP_LL(&abs_xyz[2], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[2]); - - MaxLONGLONGCH(&abs_xyz[0], 3, &max_abs_xyz64); - - - #if 0 - textprint("value to shift = %d, %d\n", max_abs_xyz64.lo32, max_abs_xyz64.hi32); - #endif - - shift = FindShift64(&max_abs_xyz64, &ll_one14); - - #if 0 - textprint("shift = %d\n", shift); - #endif - - nvector->vx >>= shift; - nvector->vy >>= shift; - nvector->vz >>= shift; - - - /* Normalise */ - - xsq = nvector->vx * nvector->vx; - ysq = nvector->vy * nvector->vy; - zsq = nvector->vz * nvector->vz; - - m = SqRoot32(xsq + ysq + zsq); - - if(m == 0) m = 1; /* Just in case */ - - nvector->vx = WideMulNarrowDiv(nvector->vx, ONE_FIXED, m); - nvector->vy = WideMulNarrowDiv(nvector->vy, ONE_FIXED, m); - nvector->vz = WideMulNarrowDiv(nvector->vz, ONE_FIXED, m); - - -#endif /* SupportFPMathsFunctions */ - - -} - - - - - - - -void Normalise2d(VECTOR2D *nvector) - -{ - - -#if SupportFPMathsFunctions - - - VECTOR2DF n; - float m; - - - n.vx = nvector->vx; - n.vy = nvector->vy; - - m = sqrt((n.vx * n.vx) + (n.vy * n.vy)); - - nvector->vx = (n.vx * ONE_FIXED) / m; - nvector->vy = (n.vy * ONE_FIXED) / m; - - -#else /* SupportFPMathsFunctions */ - - - int m, s; - int xsq, ysq; - LONGLONGCH max_abs_xy64; - LONGLONGCH abs_xy[2]; - int shift; - - - /* Before we can normalise we must bring these vectors down to 14-bits */ - - IntToLL(&abs_xyz[0], &nvector->vx); - s = CMP_LL(&abs_xyz[0], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[0]); - - IntToLL(&abs_xyz[1], &nvector->vy); - s = CMP_LL(&abs_xyz[1], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[1]); - - MaxLONGLONGCH(&abs_xy[0], 2, &max_abs_xy64); - - - #if 0 - textprint("value to shift = %d, %d\n", max_abs_xyz64.lo32, max_abs_xyz64.hi32); - #endif - - shift = FindShift64(&max_abs_xy64, &ll_one14); - - #if 0 - textprint("shift = %d\n", shift); - #endif - - nvector->vx >>= shift; - nvector->vy >>= shift; - - - /* Normalise */ - - xsq = nvector->vx * nvector->vx; - ysq = nvector->vy * nvector->vy; - - m = SqRoot32(xsq + ysq); - - if(m == 0) m = 1; /* Just in case */ - - nvector->vx = WideMulNarrowDiv(nvector->vx, ONE_FIXED, m); - nvector->vy = WideMulNarrowDiv(nvector->vy, ONE_FIXED, m); - - -#endif /* SupportFPMathsFunctions */ - - -} - - - - - - - -#if SupportFPMathsFunctions - -void FNormalise(VECTORCHF *n) - -{ - - float m; - - - m = sqrt((n->vx * n->vx) + (n->vy * n->vy) + (n->vz * n->vz)); - - n->vx /= m; - n->vy /= m; - n->vz /= m; - -} - -void FNormalise2d(VECTOR2DF *n) - -{ - - float m; - - - m = sqrt((n->vx * n->vx) + (n->vy * n->vy)); - - n->vx /= m; - n->vy /= m; - -} - -#endif /* SupportFPMathsFunctions */ - - -/* - - Return the magnitude of a vector - -*/ - -int Magnitude(VECTORCH *v) - -{ - - -#if SupportFPMathsFunctions - - - - VECTORCHF n; - int m; - - - n.vx = v->vx; - n.vy = v->vy; - n.vz = v->vz; - - f2i(m, sqrt((n.vx * n.vx) + (n.vy * n.vy) + (n.vz * n.vz))); - - return m; - - -#else /* SupportFPMathsFunctions */ - - - VECTORCH vtemp; - LONGLONGCH max_abs_xyz64; - LONGLONGCH abs_xyz[3]; - int shift; - int m; - int xsq, ysq, zsq; - int s; - - - /* - - Before we can square and add the components we must bring these vectors - down to 14-bits - - */ - - IntToLL(&abs_xyz[0], &v->vx); - s = CMP_LL(&abs_xyz[0], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[0]); - - IntToLL(&abs_xyz[1], &v->vy); - s = CMP_LL(&abs_xyz[1], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[1]); - - IntToLL(&abs_xyz[2], &v->vz); - s = CMP_LL(&abs_xyz[2], &ll_zero); - if(s < 0) NEG_LL(&abs_xyz[2]); - - MaxLONGLONGCH(&abs_xyz[0], 3, &max_abs_xyz64); - - shift = FindShift64(&max_abs_xyz64, &ll_one14); - - CopyVector(v, &vtemp); - - vtemp.vx >>= shift; - vtemp.vy >>= shift; - vtemp.vz >>= shift; - - xsq = vtemp.vx * vtemp.vx; - ysq = vtemp.vy * vtemp.vy; - zsq = vtemp.vz * vtemp.vz; - - m = SqRoot32(xsq + ysq + zsq); - - m <<= shift; - - return m; - - -#endif /* SupportFPMathsFunctions */ - - -} - - - - - - - - - - -/* - - 64-bit Square Root returns 32-bit result - - All 64-bit operations are now done using the type LONGLONGCH whose format - varies from platform to platform, although it is always 64-bits in size. - - NOTE: - - Function currently not available to Watcom C users - A Floating point version is STRONGLY advised for the PC anyway - -*/ - -#if 0 -int SqRoot64(LONGLONGCH *A) - -{ - -#if 0 - - unsigned long long edx = *A; - - unsigned int eax = 0; - unsigned int ebx = 0; - unsigned int edi = 0; - - unsigned int ecx; - - - unsigned long long TopBit = 0x8000000000000000LL; - - for(ecx = 31; ecx != 0; ecx--) { - - ebx <<= 1; - if(edx & TopBit) ebx |= 1; - edx <<= 1; - - ebx <<= 1; - if(edx & TopBit) ebx |= 1; - edx <<= 1; - - eax += eax; - edi = eax; - edi += edi; - - if(ebx > edi) { - - edi++; - eax++; - ebx -= edi; - - } - - } - - ebx <<= 1; - if(edx & TopBit) ebx |= 1; - edx <<= 1; - - ebx <<= 1; - if(edx & TopBit) ebx |= 1; - edx <<= 1; - - eax += eax; - edi = eax; - edi += edi; - - if(ebx > edi) { - - eax++; - - } - - return eax; - -#endif - - return (0); - -} - -#endif /* for #if 0 */ - -/* - - Shift the 64-bit value until is LTE the limit - - Return the shift value - -*/ - -int FindShift64(LONGLONGCH *value, LONGLONGCH *limit) - -{ - - int shift = 0; - int s; - LONGLONGCH value_tmp; - - - EQUALS_LL(&value_tmp, value); - - s = CMP_LL(&value_tmp, &ll_zero); - if(s < 0) NEG_LL(&value_tmp); - - - while(GT_LL(&value_tmp, limit)) { - - shift++; - - ASR_LL(&value_tmp, 1); - - } - - return shift; - -} - - -/* - - MaxLONGLONGCH - - Return a pointer to the largest value of a long long array - -*/ - -void MaxLONGLONGCH(LONGLONGCH *llarrayptr, int llarraysize, LONGLONGCH *llmax) - -{ - - int i; - - - EQUALS_LL(llmax, &ll_zero); - - for(i = llarraysize; i!=0; i--) { - - if(LT_LL(llmax, llarrayptr)) { - - EQUALS_LL(llmax, llarrayptr); - - } - - llarrayptr++; - - } - -} - - - - - - - - - - - - -/* - - Some operators derived from the 64-bit CMP function. - - These were first defined for pcwatcom\plspecfn.h and transferred as and - when needed to other platforms. - -*/ - - -/* - - GT_LL - - To express if(a > b) - - use - - if(GT_LL(a, b)) - -*/ - -int GT_LL(LONGLONGCH *a, LONGLONGCH *b) - -{ - - int s = CMP_LL(a, b); /* a-b */ - - - if(s > 0) return (Yes); - - else return (No); - -} - - -/* - - LT_LL - - To express if(a < b) - - use - - if(LT_LL(a, b)) - -*/ - -int LT_LL(LONGLONGCH *a, LONGLONGCH *b) - -{ - - int s = CMP_LL(a, b); /* a-b */ - - - if(s < 0) return (Yes); - - else return (No); - -} - - - - -/* - - Copy Clip Point Function - -*/ - -void CopyClipPoint(CLIP_POINT *cp1, CLIP_POINT *cp2) - -{ - - cp2->ClipPoint.vx = cp1->ClipPoint.vx; - cp2->ClipPoint.vy = cp1->ClipPoint.vy; - cp2->ClipPoint.vz = cp1->ClipPoint.vz; - - cp2->ClipNormal.vx = cp1->ClipNormal.vx; - cp2->ClipNormal.vy = cp1->ClipNormal.vy; - cp2->ClipNormal.vz = cp1->ClipNormal.vz; - - cp2->ClipTexel.uuu = cp1->ClipTexel.uuu; - cp2->ClipTexel.vee = cp1->ClipTexel.vee; - - cp2->ClipInt = cp1->ClipInt; - cp2->ClipZBuffer = cp1->ClipZBuffer; - -} - - -/* - - Matrix Rotatation of a Vector - Inline Version - - Overwrite the Source Vector with the Rotated Vector - - x' = v.c1 - y' = v.c2 - z' = v.c3 - -*/ - -void RotVect(VECTORCH *v, MATRIXCH *m) - -{ - - int x, y, z; - - x = MUL_FIXED(m->mat11, v->vx); - x += MUL_FIXED(m->mat21, v->vy); - x += MUL_FIXED(m->mat31, v->vz); - - y = MUL_FIXED(m->mat12, v->vx); - y += MUL_FIXED(m->mat22, v->vy); - y += MUL_FIXED(m->mat32, v->vz); - - z = MUL_FIXED(m->mat13, v->vx); - z += MUL_FIXED(m->mat23, v->vy); - z += MUL_FIXED(m->mat33, v->vz); - - v->vx = x; - v->vy = y; - v->vz = z; - -} - - - -/* - - Dot Product Function - Inline Version - - It accepts two pointers to vectors and returns an int result - -*/ - -int _Dot(VECTORCH *vptr1, VECTORCH *vptr2) - -{ - - int dp; - - dp = MUL_FIXED(vptr1->vx, vptr2->vx); - dp += MUL_FIXED(vptr1->vy, vptr2->vy); - dp += MUL_FIXED(vptr1->vz, vptr2->vz); - - return(dp); - -} - - -/* - - Make a Vector - Inline Version - - v3 = v1 - v2 - -*/ - -void MakeV(VECTORCH *v1, VECTORCH *v2, VECTORCH *v3) - -{ - - v3->vx = v1->vx - v2->vx; - v3->vy = v1->vy - v2->vy; - v3->vz = v1->vz - v2->vz; - -} - -/* - - Add a Vector. - - v2 = v2 + v1 - -*/ - -void AddV(VECTORCH *v1, VECTORCH *v2) - -{ - - v2->vx += v1->vx; - v2->vy += v1->vy; - v2->vz += v1->vz; - -} diff --git a/3dc/win95/shpanim.h b/3dc/win95/shpanim.h deleted file mode 100644 index 869cc41..0000000 --- a/3dc/win95/shpanim.h +++ /dev/null @@ -1,201 +0,0 @@ -#ifndef _shp_anim_h -#define _shp_anim_h 1 - - -#ifdef __cplusplus - - extern "C" { - -#endif - - -/* - - Structures for animating shapes (not morphing) - - I am using standard types to organise the - sequences as an enum would force a complete - recompile each time it changed - -*/ - -typedef struct shapeanimationframe -{ - - // Public variables - - - - // Private variables - - int * vertices; - int * item_normals; - - -} SHAPEANIMATIONFRAME; - - -typedef struct shapeanimationsequence -{ - - // Public variables - - int radius; - - int max_x; - int max_y; - int max_z; - - int min_x; - int min_y; - int min_z; - - - // Private variables - - unsigned long num_frames; - SHAPEANIMATIONFRAME * anim_frames; - -// unsigned long num_interpolated_frames_per_frame; - // 0 for none - - int * vertex_normals; - -} SHAPEANIMATIONSEQUENCE; - - -typedef struct shapeanimationheader -{ - - // Public variables - - - // Private variables - - unsigned long num_sequences; - - SHAPEANIMATIONSEQUENCE * anim_sequences; - - int num_shapes_using_this; //number of shapes sharing the same shapeanimationheader - -} SHAPEANIMATIONHEADER; - - - -typedef struct shapeanimationcontroldata -{ - - // Public variables - - // 16.16 fixed point - unsigned long seconds_per_frame; - // default is ONE_FIXED / 8 - - unsigned long sequence_no; - // default is 0 - - // if you're not interested in setting a start and an end frame - // then set the flag 'default_start_and_end_frames' below - unsigned long start_frame; - unsigned long end_frame; - // no default values - - unsigned long default_start_and_end_frames : 1; - // default is on - - unsigned long reversed : 1; - // default is off - - unsigned long stop_at_end : 1; - // default is off - - - - // Private variables - - unsigned long empty : 1; - unsigned long stop_now : 1; - unsigned long pause_at_end : 1; - - // if start_frame == end_frame - // then do not stop unless it has done at least one frame - unsigned long done_a_frame : 1; - - SHAPEANIMATIONSEQUENCE * sequence; - - signed long current_frame; - signed long time_to_next_frame; - -} SHAPEANIMATIONCONTROLDATA; - - -typedef struct shapeanimationcontroller -{ - - // Public variables - - SHAPEANIMATIONCONTROLDATA current; - - SHAPEANIMATIONCONTROLDATA next; - - unsigned long finished : 1; - - - // Private variables - - unsigned long playing : 1; - - SHAPEANIMATIONHEADER * anim_header; - -} SHAPEANIMATIONCONTROLLER; - - - - -////////////////////////////////////////////////////////////////////////////////// -///////////////////////////// Funtions ///////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// - -struct displayblock; -struct shapeheader; - -// This sets the current animation (and the next to empty) -unsigned int SetShapeAnimationSequence (struct displayblock *, SHAPEANIMATIONCONTROLDATA *); -unsigned int SetOrphanedShapeAnimationSequence (SHAPEANIMATIONCONTROLLER * sac, SHAPEANIMATIONCONTROLDATA * sacd); - -// This sets the next animation (if the current is empty it will set the current) -unsigned int SetNextShapeAnimationSequence (struct displayblock *, SHAPEANIMATIONCONTROLDATA *); - -// stop_now == 1 will cause the function to ignore the end_frame value -// set end_frame to -1 for no change to the ending frame of the sequence -void SetCurrentShapeAnimationToStop (struct displayblock *, unsigned long stop_now, signed long end_frame); - -SHAPEANIMATIONCONTROLDATA const * GetCurrentShapeAnimationSequenceData (struct displayblock *); -SHAPEANIMATIONCONTROLDATA const * GetNextShapeAnimationSequenceData (struct displayblock *); - -// pause_now == 1 will cause the function to ignore the end_frame value -// set end_frame to -1 for no change to the ending frame of the sequence -void PauseCurrentShapeAnimation (struct displayblock *, unsigned long pause_now, signed long end_frame); -void RestartCurrentShapeAnimation (struct displayblock *); - -// Please use these functions, whenever you create a block of each type -void InitShapeAnimationController (SHAPEANIMATIONCONTROLLER *, struct shapeheader *); -void InitShapeAnimationControlData (SHAPEANIMATIONCONTROLDATA *); - - - - -// These are for the system - -void DoAllShapeAnimations (); - -void CopyAnimationFrameToShape (SHAPEANIMATIONCONTROLDATA *sacd, struct displayblock * dptr); - -#ifdef __cplusplus - - }; - -#endif - - -#endif
\ No newline at end of file diff --git a/3dc/win95/smacker.c b/3dc/win95/smacker.c deleted file mode 100644 index 9b46f83..0000000 --- a/3dc/win95/smacker.c +++ /dev/null @@ -1,775 +0,0 @@ -/* KJL 15:25:20 8/16/97 - * - * smacker.c - functions to handle FMV playback - * - */ -#include "3dc.h" -#include "module.h" -#include "inline.h" -#include "stratdef.h" -#include "gamedef.h" -#include "smacker.h" -#include "avp_menus.h" -#include "avp_userprofile.h" -#include "d3_func.h" - -#define UseLocalAssert 1 -#include "ourasert.h" - -int VolumeOfNearestVideoScreen; -int PanningOfNearestVideoScreen; - -extern char *ScreenBuffer; -extern LPDIRECTSOUND DSObject; -extern int GotAnyKey; -extern void DirectReadKeyboard(void); -extern IMAGEHEADER ImageHeaderArray[]; -#if MaxImageGroups>1 -extern int NumImagesArray[]; -#else -extern int NumImages; -#endif - -void PlayFMV(char *filenamePtr); -static int NextSmackerFrame(Smack *smackHandle); -static UpdatePalette(Smack *smackHandle); - -static int GetSmackerPixelFormat(DDPIXELFORMAT *pixelFormatPtr); -void FindLightingValueFromFMV(unsigned short *bufferPtr); -void FindLightingValuesFromTriggeredFMV(unsigned char *bufferPtr, FMVTEXTURE *ftPtr); - -int SmackerSoundVolume=ONE_FIXED/512; -int MoviesAreActive; -int IntroOutroMoviesAreActive=1; - -int FmvColourRed; -int FmvColourGreen; -int FmvColourBlue; - -void PlayFMV(char *filenamePtr) -{ - Smack* smackHandle; - int playing = 1; - - if (!IntroOutroMoviesAreActive) return; - - /* use Direct sound */ - SmackSoundUseDirectSound(DSObject); - /* open smacker file */ - smackHandle = SmackOpen(filenamePtr,SMACKTRACKS,SMACKAUTOEXTRA); - if (!smackHandle) - { - char message[100]; - sprintf(message,"Unable to access file: %s\n",filenamePtr); - MessageBox(NULL,message,"AvP Error",MB_OK+MB_SYSTEMMODAL); - exit(0x111); - return; - } - - while(playing) - { - CheckForWindowsMessages(); - if (!SmackWait(smackHandle)) - playing = NextSmackerFrame(smackHandle); - - /* do something else */ -// *(ScreenBuffer + 300*640 + smackHandle->FrameNum) = 255; - - FlipBuffers(); - #if ALLOW_SKIP_INTRO - DirectReadKeyboard(); - if (GotAnyKey) playing = 0; - #endif - } - /* close file */ - SmackClose(smackHandle); -} - - - - -static int NextSmackerFrame(Smack *smackHandle) -{ - /* do we have to change the palette? */ -// if (smackHandle->NewPalette) UpdatePalette(smackHandle); - - /* unpack frame */ - extern DDPIXELFORMAT DisplayPixelFormat; - SmackToBuffer(smackHandle,(640-smackHandle->Width)/2,(480-smackHandle->Height)/2,640*2,480,(void*)ScreenBuffer,GetSmackerPixelFormat(&DisplayPixelFormat)); - SmackDoFrame(smackHandle); - - /* are we at the last frame yet? */ - if ((smackHandle->FrameNum==(smackHandle->Frames-1))) return 0; - - /* next frame, please */ - SmackNextFrame(smackHandle); - return 1; -} - -Smack* SmackHandle[4]; -#define FMV_ON 0 - -void InitFMV(void) -{ -#if FMV_ON -// char *filenamePtr = "fmvs/hugtest.smk";//"dd64_64.smk";//nintendo.smk";//"trailer.smk";//"m_togran.smk"; - - /* use Direct sound */ -// SmackSoundUseDirectSound(DSObject); - - /* open smacker file */ - SmackHandle[0] = SmackOpen("fmvs/tyrargo.smk",SMACKTRACKS,SMACKAUTOEXTRA); - SmackHandle[1] = SmackOpen("fmvs/final.smk",SMACKTRACKS,SMACKAUTOEXTRA); - SmackHandle[2] = SmackOpen("fmvs/hugtest.smk",SMACKTRACKS,SMACKAUTOEXTRA); - SmackHandle[3] = SmackOpen("fmvs/alien.smk",SMACKTRACKS,SMACKAUTOEXTRA); - -#endif -} - -int NextFMVFrame(void*bufferPtr, int x, int y, int w, int h, int fmvNumber) -{ -#if FMV_ON - int smackerFormat; - - if(!SmackHandle[fmvNumber]) return 0; - - if (SmackWait(SmackHandle[fmvNumber])) return 0; - - /* unpack frame */ - { - extern D3DINFO d3d; - smackerFormat = GetSmackerPixelFormat(&(d3d.TextureFormat[d3d.CurrentTextureFormat].ddsd.ddpfPixelFormat)); - } - if (smackerFormat) w*=2; -// if (fmvNumber==0) FindLightingValueFromFMV((unsigned short *)bufferPtr); - SmackToBuffer(SmackHandle[fmvNumber],x,y,w,h,(void*)bufferPtr,smackerFormat); - - SmackDoFrame(SmackHandle[fmvNumber]); -// textprint("at frame %d\n",SmackHandle->FrameNum); - - /* next frame, please */ - SmackNextFrame(SmackHandle[fmvNumber]); -#endif - return 1; - -} - -void UpdateFMVPalette(PALETTEENTRY *FMVPalette, int fmvNumber) -{ - unsigned char *c; - int i; - if(!SmackHandle[fmvNumber]) return; - c=SmackHandle[fmvNumber]->Palette; - - for(i=0;i<256;i++) - { - FMVPalette[i].peRed=(*c++); - FMVPalette[i].peGreen=(*c++); - FMVPalette[i].peBlue=(*c++); - } -} - - -void CloseFMV(void) -{ -#if FMV_ON - extern void KillFMVTexture(void); - if(SmackHandle[0]) SmackClose(SmackHandle[0]); - if(SmackHandle[1]) SmackClose(SmackHandle[1]); - if(SmackHandle[2]) SmackClose(SmackHandle[2]); - if(SmackHandle[3]) SmackClose(SmackHandle[3]); - KillFMVTexture(); -#endif -} - -static int GetSmackerPixelFormat(DDPIXELFORMAT *pixelFormatPtr) -{ - - if( (pixelFormatPtr->dwFlags & DDPF_RGB) && !(pixelFormatPtr->dwFlags & DDPF_PALETTEINDEXED8) ) - { - int m; - int redShift=0; - - m = pixelFormatPtr->dwRBitMask; - LOCALASSERT(m); - while(!(m&1)) m>>=1; - while(m&1) - { - m>>=1; - redShift++; - } - - if(redShift == 5) - { - /* Red componant is 5. */ - int greenShift=0; - m = pixelFormatPtr->dwGBitMask; - LOCALASSERT(m); - while(!(m&1)) m>>=1; - while(m&1) - { - m>>=1; - greenShift++; - } - if(greenShift == 5) - { - /* Green componant is 5. */ - int blueShift=0; - m = pixelFormatPtr->dwBBitMask; - LOCALASSERT(m); - while(!(m&1)) m>>=1; - while(m&1) - { - m>>=1; - blueShift++; - } - if(blueShift == 5) - { - /* Blue componant is 5. */ - return SMACKBUFFER555; - } - else - { - /* Blue componant is 6. */ - // not supported - LOCALASSERT("Smacker does not support this pixel format"==0); - return SMACKBUFFER555; - //return SMACKBUFFER556; - } - } - else - { - /* Green componant is 6. */ - return SMACKBUFFER565; - } - } - else - { - /* Red componant is 6. */ - // not supported - LOCALASSERT("Smacker does not support this pixel format"==0); - return SMACKBUFFER555; - //return SMACKBUFFER655; - } - } - else - { - return 0; - } -} - - - - - - - - - - - -void StartMenuMusic(void) -{ - char *filenamePtr = "fmvs/introsound.smk"; - - /* use Direct sound */ - SmackSoundUseDirectSound(DSObject); - - /* open smacker file */ - SmackHandle[0] = SmackOpen(filenamePtr,SMACKTRACKS|SMACKNEEDVOLUME|SMACKNEEDPAN,SMACKAUTOEXTRA); -} - -void PlayMenuMusic(void) -{ - if(!SmackHandle[0]) return; - - SmackVolumePan(SmackHandle[0],SMACKTRACKS,SmackerSoundVolume*256,32768); - - if (SmackWait(SmackHandle[0])) return; - - /* unpack frame */ - SmackDoFrame(SmackHandle[0]); - - /* next frame, please */ - SmackNextFrame(SmackHandle[0]); -} -void EndMenuMusic(void) -{ - if(!SmackHandle[0]) return; - - SmackClose(SmackHandle[0]); -} - - -void FindLightingValueFromFMV(unsigned short *bufferPtr) -{ - unsigned int totalRed=0; - unsigned int totalBlue=0; - unsigned int totalGreen=0; - - int pixels = 128*96;//64*48;//256*192; - do - { - int source = (int)(*bufferPtr++); - totalBlue += source&31; - source>>=5; - totalGreen += source&63; - source>>=6; - totalRed += source&31; - } - while(--pixels); - FmvColourRed = totalRed*4/24; - FmvColourGreen = totalGreen*4/48; - FmvColourBlue = totalBlue*4/24; - -} - - -void FindLightingValueFromCentredFMV(unsigned short *bufferPtr) -{ - unsigned int totalRed=0; - unsigned int totalBlue=0; - unsigned int totalGreen=0; - - int x,y; - - for (y=32; y<32+48; y++) - for (x=32; x<32+64; x++) - { - int source = (int)(*(unsigned short*)(bufferPtr+x+y*128)); - totalBlue += source&31; - source>>=5; - totalGreen += source&63; - source>>=6; - totalRed += source&31; - } - FmvColourRed = totalRed*4/24; - FmvColourGreen = totalGreen*4/48; - FmvColourBlue = totalBlue*4/24; - -} - - - - - -/* KJL 12:45:23 10/08/98 - FMVTEXTURE stuff */ -#define MAX_NO_FMVTEXTURES 10 -FMVTEXTURE FMVTexture[MAX_NO_FMVTEXTURES]; -int NumberOfFMVTextures; - -void ScanImagesForFMVs(void) -{ - extern void SetupFMVTexture(FMVTEXTURE *ftPtr); - int i; - IMAGEHEADER *ihPtr; - NumberOfFMVTextures=0; - - #if MaxImageGroups>1 - for (j=0; j<MaxImageGroups; j++) - { - if (NumImagesArray[j]) - { - ihPtr = &ImageHeaderArray[j*MaxImages]; - for (i = 0; i<NumImagesArray[j]; i++, ihPtr++) - { - #else - { - if(NumImages) - { - ihPtr = &ImageHeaderArray[0]; - for (i = 0; i<NumImages; i++, ihPtr++) - { - #endif - char *strPtr; - if(strPtr = strstr(ihPtr->ImageName,"FMVs")) - { - Smack *smackHandle; - char filename[30]; - { - char *filenamePtr = filename; - do - { - *filenamePtr++ = *strPtr; - } - while(*strPtr++!='.'); - - *filenamePtr++='s'; - *filenamePtr++='m'; - *filenamePtr++='k'; - *filenamePtr=0; - } - - smackHandle = SmackOpen(filename,SMACKTRACKS|SMACKNEEDVOLUME|SMACKNEEDPAN,SMACKAUTOEXTRA); - if (smackHandle) - { - FMVTexture[NumberOfFMVTextures].IsTriggeredPlotFMV = 0; - } - else - { - FMVTexture[NumberOfFMVTextures].IsTriggeredPlotFMV = 1; - } - - { - FMVTexture[NumberOfFMVTextures].SmackHandle = smackHandle; - FMVTexture[NumberOfFMVTextures].ImagePtr = ihPtr; - FMVTexture[NumberOfFMVTextures].StaticImageDrawn=0; - SetupFMVTexture(&FMVTexture[NumberOfFMVTextures]); - NumberOfFMVTextures++; - } - } - } - } - } - - -} - -void UpdateAllFMVTextures(void) -{ - extern void UpdateFMVTexture(FMVTEXTURE *ftPtr); - int i = NumberOfFMVTextures; - - while(i--) - { - UpdateFMVTexture(&FMVTexture[i]); - } - -} - -void ReleaseAllFMVTextures(void) -{ - extern void UpdateFMVTexture(FMVTEXTURE *ftPtr); - int i = NumberOfFMVTextures; - - while(i--) - { - FMVTexture[i].MessageNumber = 0; - if(FMVTexture[i].SmackHandle) - { - SmackClose(FMVTexture[i].SmackHandle); - FMVTexture[i].SmackHandle=0; - } - if (FMVTexture[i].SrcTexture) - { - ReleaseD3DTexture(FMVTexture[i].SrcTexture); - FMVTexture[i].SrcTexture=0; - } - if (FMVTexture[i].SrcSurface) - { - ReleaseDDSurface(FMVTexture[i].SrcSurface); - FMVTexture[i].SrcSurface=0; - } - if (FMVTexture[i].DestTexture) - { - ReleaseD3DTexture(FMVTexture[i].DestTexture); - FMVTexture[i].DestTexture = 0; - } - } - -} - - -int NextFMVTextureFrame(FMVTEXTURE *ftPtr, void *bufferPtr) -{ - int smackerFormat; - int w = 128; - - { - extern D3DINFO d3d; - smackerFormat = GetSmackerPixelFormat(&(d3d.TextureFormat[d3d.CurrentTextureFormat].ddsd.ddpfPixelFormat)); - } - if (smackerFormat) w*=2; - - if (MoviesAreActive && ftPtr->SmackHandle) - { - int volume = MUL_FIXED(SmackerSoundVolume*256,GetVolumeOfNearestVideoScreen()); - SmackVolumePan(ftPtr->SmackHandle,SMACKTRACKS,volume,PanningOfNearestVideoScreen); - ftPtr->SoundVolume = SmackerSoundVolume; - - if (SmackWait(ftPtr->SmackHandle)) return 0; - /* unpack frame */ - SmackToBuffer(ftPtr->SmackHandle,0,0,w,96,bufferPtr,smackerFormat); - - SmackDoFrame(ftPtr->SmackHandle); - - /* are we at the last frame yet? */ - if (ftPtr->IsTriggeredPlotFMV && (ftPtr->SmackHandle->FrameNum==(ftPtr->SmackHandle->Frames-1)) ) - { - SmackClose(ftPtr->SmackHandle); - ftPtr->SmackHandle = 0; - ftPtr->MessageNumber = 0; - } - else - { - /* next frame, please */ - SmackNextFrame(ftPtr->SmackHandle); - } - ftPtr->StaticImageDrawn=0; - } - else if (!ftPtr->StaticImageDrawn || smackerFormat) - { - int i = w*96/4; - unsigned int seed = FastRandom(); - int *ptr = (int*)bufferPtr; - do - { - seed = ((seed*1664525)+1013904223); - *ptr++ = seed; - } - while(--i); - ftPtr->StaticImageDrawn=1; - } - FindLightingValuesFromTriggeredFMV((unsigned char*)bufferPtr,ftPtr); - return 1; - -} - -void UpdateFMVTexturePalette(FMVTEXTURE *ftPtr) -{ - unsigned char *c; - int i; - - if (MoviesAreActive && ftPtr->SmackHandle) - { - c=ftPtr->SmackHandle->Palette; - - for(i=0;i<256;i++) - { - ftPtr->SrcPalette[i].peRed=(*c++); - ftPtr->SrcPalette[i].peGreen=(*c++); - ftPtr->SrcPalette[i].peBlue=(*c++); - } - } - else - { - { - unsigned int seed = FastRandom(); - for(i=0;i<256;i++) - { - int l = (seed&(seed>>24)&(seed>>16)); - seed = ((seed*1664525)+1013904223); - ftPtr->SrcPalette[i].peRed=l; - ftPtr->SrcPalette[i].peGreen=l; - ftPtr->SrcPalette[i].peBlue=l; - } - } - } -} - -extern void StartTriggerPlotFMV(int number) -{ - int i = NumberOfFMVTextures; - char buffer[25]; - - if (CheatMode_Active != CHEATMODE_NONACTIVE) return; - - sprintf(buffer,"FMVs//message%d.smk",number); - { - FILE* file=fopen(buffer,"rb"); - if(!file) - { - return; - } - fclose(file); - } - while(i--) - { - if (FMVTexture[i].IsTriggeredPlotFMV) - { - if(FMVTexture[i].SmackHandle) - { - SmackClose(FMVTexture[i].SmackHandle); - } - - FMVTexture[i].SmackHandle = SmackOpen(&buffer,SMACKTRACKS|SMACKNEEDVOLUME|SMACKNEEDPAN,SMACKAUTOEXTRA); - FMVTexture[i].MessageNumber = number; - } - } -} -extern void StartFMVAtFrame(int number, int frame) -{ - int i = NumberOfFMVTextures; - - StartTriggerPlotFMV(number); - - while(i--) - { - if (FMVTexture[i].IsTriggeredPlotFMV) - { - if(FMVTexture[i].SmackHandle) - { - SmackSoundOnOff(FMVTexture[i].SmackHandle,0); // turn off sound so that it is synched - SmackGoto(FMVTexture[i].SmackHandle,frame); - SmackSoundOnOff(FMVTexture[i].SmackHandle,1); // turn on sound so that it is synched -// SmackNextFrame(FMVTexture[i].SmackHandle); - } - } - } - -} -extern void GetFMVInformation(int *messageNumberPtr, int *frameNumberPtr) -{ - int i = NumberOfFMVTextures; - - while(i--) - { - if (FMVTexture[i].IsTriggeredPlotFMV) - { - if(FMVTexture[i].SmackHandle) - { - *messageNumberPtr = FMVTexture[i].MessageNumber; - *frameNumberPtr = FMVTexture[i].SmackHandle->FrameNum; - return; - } - } - } - - *messageNumberPtr = 0; - *frameNumberPtr = 0; -} - - -extern void InitialiseTriggeredFMVs(void) -{ - int i = NumberOfFMVTextures; - while(i--) - { - if (FMVTexture[i].IsTriggeredPlotFMV) - { - if(FMVTexture[i].SmackHandle) - { - SmackClose(FMVTexture[i].SmackHandle); - FMVTexture[i].MessageNumber = 0; - } - - FMVTexture[i].SmackHandle = 0; - } - } -} - -void FindLightingValuesFromTriggeredFMV(unsigned char *bufferPtr, FMVTEXTURE *ftPtr) -{ - unsigned int totalRed=0; - unsigned int totalBlue=0; - unsigned int totalGreen=0; - #if 0 - int pixels = 128*96;//64*48;//256*192; - do - { - unsigned char source = (*bufferPtr++); - totalBlue += ftPtr->SrcPalette[source].peBlue; - totalGreen += ftPtr->SrcPalette[source].peGreen; - totalRed += ftPtr->SrcPalette[source].peRed; - } - while(--pixels); - #else - int pixels = 128*96/4;//64*48;//256*192; - unsigned int *source = (unsigned int*) (bufferPtr); - do - { - int s = *source++; - { - int t = s&255; - totalBlue += ftPtr->SrcPalette[t].peBlue; - totalGreen += ftPtr->SrcPalette[t].peGreen; - totalRed += ftPtr->SrcPalette[t].peRed; - } - #if 0 - s >>=8; - { - int t = s&255; - totalBlue += ftPtr->SrcPalette[t].peBlue; - totalGreen += ftPtr->SrcPalette[t].peGreen; - totalRed += ftPtr->SrcPalette[t].peRed; - } - s >>=8; - { - int t = s&255; - totalBlue += ftPtr->SrcPalette[t].peBlue; - totalGreen += ftPtr->SrcPalette[t].peGreen; - totalRed += ftPtr->SrcPalette[t].peRed; - } - s >>=8; - { - int t = s; - totalBlue += ftPtr->SrcPalette[t].peBlue; - totalGreen += ftPtr->SrcPalette[t].peGreen; - totalRed += ftPtr->SrcPalette[t].peRed; - } - #endif - } - while(--pixels); - #endif - FmvColourRed = totalRed/48*16; - FmvColourGreen = totalGreen/48*16; - FmvColourBlue = totalBlue/48*16; - -} - -extern int NumActiveBlocks; -extern DISPLAYBLOCK *ActiveBlockList[]; -#include "showcmds.h" -int GetVolumeOfNearestVideoScreen(void) -{ - extern VIEWDESCRIPTORBLOCK *Global_VDB_Ptr; - int numberOfObjects = NumActiveBlocks; - int leastDistanceRecorded = 0x7fffffff; - VolumeOfNearestVideoScreen = 0; - - { - extern char LevelName[]; - if (!_stricmp(LevelName,"invasion_a")) - { - VolumeOfNearestVideoScreen = ONE_FIXED; - PanningOfNearestVideoScreen = ONE_FIXED/2; - } - } - - while (numberOfObjects) - { - DISPLAYBLOCK* objectPtr = ActiveBlockList[--numberOfObjects]; - STRATEGYBLOCK* sbPtr = objectPtr->ObStrategyBlock; - - if (sbPtr) - { - if (sbPtr->I_SBtype == I_BehaviourVideoScreen) - { - int dist; - VECTORCH disp; - - disp.vx = objectPtr->ObWorld.vx - Global_VDB_Ptr->VDB_World.vx; - disp.vy = objectPtr->ObWorld.vy - Global_VDB_Ptr->VDB_World.vy; - disp.vz = objectPtr->ObWorld.vz - Global_VDB_Ptr->VDB_World.vz; - - dist = Approximate3dMagnitude(&disp); - if (dist<leastDistanceRecorded && dist<ONE_FIXED) - { - leastDistanceRecorded = dist; - VolumeOfNearestVideoScreen = ONE_FIXED + 1024 - dist/2; - if (VolumeOfNearestVideoScreen>ONE_FIXED) VolumeOfNearestVideoScreen = ONE_FIXED; - - { - VECTORCH rightEarDirection; - #if 0 - rightEarDirection.vx = Global_VDB_Ptr->VDB_Mat.mat11; - rightEarDirection.vy = Global_VDB_Ptr->VDB_Mat.mat12; - rightEarDirection.vz = Global_VDB_Ptr->VDB_Mat.mat13; - Normalise(&disp); - #else - rightEarDirection.vx = Global_VDB_Ptr->VDB_Mat.mat11; - rightEarDirection.vy = 0; - rightEarDirection.vz = Global_VDB_Ptr->VDB_Mat.mat31; - disp.vy=0; - Normalise(&disp); - Normalise(&rightEarDirection); - #endif - PanningOfNearestVideoScreen = 32768 + DotProduct(&disp,&rightEarDirection)/2; - } - } - } - } - } - PrintDebuggingText("Volume: %d, Pan %d\n",VolumeOfNearestVideoScreen,PanningOfNearestVideoScreen); - return VolumeOfNearestVideoScreen; -}
\ No newline at end of file diff --git a/3dc/win95/smacker.h b/3dc/win95/smacker.h deleted file mode 100644 index 3fd364a..0000000 --- a/3dc/win95/smacker.h +++ /dev/null @@ -1,43 +0,0 @@ -/* KJL 15:25:20 8/16/97 - * - * smacker.h - functions to handle FMV playback - * - */ -#include "smack.h" - -extern void PlayFMV(char *filenamePtr); -extern void StartMenuMusic(void); -extern void PlayMenuMusic(void); -extern void EndMenuMusic(void); - - - -typedef struct -{ - IMAGEHEADER *ImagePtr; - Smack *SmackHandle; - int SoundVolume; - int IsTriggeredPlotFMV; - int StaticImageDrawn; - - int MessageNumber; - - LPDIRECTDRAWSURFACE SrcSurface; - LPDIRECT3DTEXTURE SrcTexture; - LPDIRECT3DTEXTURE DestTexture; - PALETTEENTRY SrcPalette[256]; - - int RedScale; - int GreenScale; - int BlueScale; - -} FMVTEXTURE; - - -extern int NextFMVTextureFrame(FMVTEXTURE *ftPtr, void *bufferPtr); -extern void UpdateFMVTexturePalette(FMVTEXTURE *ftPtr); -extern void InitialiseTriggeredFMVs(void); -extern void StartTriggerPlotFMV(int number); - -extern void StartFMVAtFrame(int number, int frame); -extern void GetFMVInformation(int *messageNumberPtr, int *frameNumberPtr); diff --git a/3dc/win95/vssver.scc b/3dc/win95/vssver.scc Binary files differdeleted file mode 100644 index e1862dd..0000000 --- a/3dc/win95/vssver.scc +++ /dev/null diff --git a/3dc/win95/win_func.cpp b/3dc/win95/win_func.cpp deleted file mode 100644 index 6be299e..0000000 --- a/3dc/win95/win_func.cpp +++ /dev/null @@ -1,334 +0,0 @@ -/**** - -Windows functionality that is definitely -not project specific. - -****/ - -// To link code to main C functions - -extern "C" { - -#include "3dc.h" -#include "inline.h" - -// For modifications necessary to make Alt-Tabbing -// behaviour (WM_ACTIVATEAPP) work full screen. -// This is necessary to support full screen -// ActiveMovie play. - -#define SupportAltTab Yes - -// Globals - -static HANDLE RasterThread; - -// Externs - -extern BOOL bActive; - -// These function are here solely to provide a clean -// interface layer, since Win32 include files are fully -// available in both C and C++. -// All functions linking to standard windows code are -// in win_func.cpp or win_proj.cpp, and all DirectX -// interface functions -// should be in dd_func.cpp (in the Win95 directory) -// or d3_func.cpp, dp_func.cpp, ds_func.cpp etc. -// Project specific platfrom functionality for Win95 -// should be in project/win95, in files called -// dd_proj.cpp etc. - - -// GetTickCount is the standard windows return -// millisecond time function, which isn't actually -// accurate to a millisecond. In order to get FRI -// to work properly with GetTickCount at high frame -// rates, you will have to switch KalmanTimer to Yes -// at the start of io.c to turn on a filtering algorithm -// in the frame counter handler. -// Alternately, we can use the mm function -// timeGetTime to get the time accurate to a millisecond. -// There is still enough variation in this to make -// the kalman filter probably worthwhile, however. - -long GetWindowsTickCount(void) - -{ - #if 0 - return GetTickCount(); - #else - return timeGetTime(); - #endif -} - -// This function is set up using a PeekMessage check, -// with a return on a failure of GetMessage, on the -// grounds that it might be more stable than just -// GetMessage. But then again, maybe not. -// PM_NOREMOVE means do not take this message out of -// the queue. The while loop is designed to ensure -// that all messages are sent through to the Windows -// Procedure are associated with a maximum of one frame's -// delay in the main engine cycle, ensuring that e.g. -// keydown messages do not build up in the queue. - -// if necessary, one could extern this flag -// to determine if a task-switch has occurred which might -// have trashed a static display, to decide whether to -// redraw the screen. After doing so, one should reset -// the flag - -BOOL g_bMustRedrawScreen = FALSE; - -void CheckForWindowsMessages(void) -{ - MSG msg; - extern signed int MouseWheelStatus; - - MouseWheelStatus = 0; - - // Initialisation for the current embarassingly primitive mouse - // handler... - - do - { - while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) - { - if (!GetMessage(&msg, NULL, 0, 0)) - return; - - TranslateMessage(&msg); - DispatchMessage(&msg); - - #if (!SupportAltTab) - // Panic - if (!bActive) - { - // Dubious hack... - #if 0 - ExitSystem(); - #else - ReleaseDirect3D(); - exit(0x00); - #endif - } - #endif - } - - // JH 13/2/98 - if the app is not active we should not return from the message lopp - // until the app is re-activated - - if (!bActive) - { - ResetFrameCounter(); - Sleep(0); - g_bMustRedrawScreen = TRUE; - } - } - while (!bActive); -} - - - - -// Experimental functions to handle a separate -// thread to run rasterisation on hardware at low -// priority. - -// Note that the RenderD3DScene function does not need -// to call ExitThread explictly - the return at the -// end of the function will do this for this, giving -// thread exit code equal to the return value from -// the function. - -/* - Note that this assumes DrawPerFrame mode!!! - necessary for some hardware accelerators anyway - (deferred texturing problem!!!) -*/ - -BOOL SpawnRasterThread() - -{ - DWORD RasterThreadId; - // Stack size of new thread in bytes. - // For the moment, we will set it to - // 128K, the normal size for the engine - // process. - // Note that this is in bytes. - // Note that stack size should grow as - // necessary. We hope. - DWORD StackSize = 128 * 1024; - - - // Create the thread - RasterThread = CreateThread( - NULL, // no security - StackSize, // default stack size - (LPTHREAD_START_ROUTINE) RenderD3DScene, - 0, // no argument for function - 0, // default creation flags - &RasterThreadId); // get thread ID - - if (RasterThread == NULL) - { - #if debug - ReleaseDirect3D(); - exit(0xabab); - #else - return FALSE; - #endif - } - - #if 1 - // Set the priority on the thread to - // below normal, since we want this thread - // to be unimportant --- it is only monitoring - // the hardware rasteriser. Hopefully. - // Note that this priority value maybe should - // be THREAD_PRIORITY_LOWEST or THREAD_PRIORITY_IDLE, - // or maybe we shouldn't call this function at all. - // Also, we must have a THREAD_SET_INFORMATION - // access right associated with the thread for this - // to work. Hopefully, this should be the default - // when using CreateThread. - SetThreadPriority(RasterThread, - THREAD_PRIORITY_NORMAL); - #endif - - return TRUE; -} - -BOOL WaitForRasterThread() - -{ - BOOL RetVal; - DWORD ThreadStatus; - int i; - - // Note that if this is to work the - // rasterisation thread must have a - // THREAD_QUERY_INFORMATION access right, - // but we believe CreateThread should supply - // this as a default. - - // Note!!! At some stage we may want to put a - // delay loop in the statement below, in the - // time honoured Saturn fashion, depending on how - // much impact calling GetExitCodeThread has on the - // rest of the system - hopefully not much... - - do - { - RetVal = GetExitCodeThread(RasterThread, - &ThreadStatus); - } - while ((RetVal == TRUE) && - (ThreadStatus == STILL_ACTIVE)); - - // Failed to get a status report on the thread - if (RetVal == FALSE) - { - #if debug - ReleaseDirect3D(); - exit(0xabbb); - #else - return FALSE; - #endif - } - - return TRUE; -} - - -/* - Pick up processor types, - either from assembler test (note - I have asm to do this, but it must - be converted from as / Motorola format - to masm / Intel), or (more likely) from - a text file left by the launcher, which - can use GetProcessorType from the - mssetup api -*/ - -#ifdef __WATCOMC__ - -unsigned int GetCPUId(void); -#pragma aux GetCPUId = "mov eax,1" "cpuid" value [edx] modify [eax ebx ecx]; - -#elif defined(_MSC_VER) - -static unsigned int GetCPUId(void) -{ - unsigned int retval; - _asm - { - mov eax,1 - _emit 0x0f ; CPUID (00001111 10100010) - This is a Pentium - ; specific instruction which gets information on the - _emit 0xa2 ; processor. A Pentium family processor should set - ; bits 11-8 of eax to 5. - mov retval,edx - } - return retval; -} - -#else - -#error "Unknown compiler" - -#endif - - -PROCESSORTYPES ReadProcessorType(void) -{ - SYSTEM_INFO SystemInfo; - int ProcessorType; - PROCESSORTYPES RetVal; - - GetSystemInfo(&SystemInfo); - - ProcessorType = SystemInfo.dwProcessorType; - - switch (ProcessorType) - { - case PROCESSOR_INTEL_386: - RetVal = PType_OffBottomOfScale; - break; - - case PROCESSOR_INTEL_486: - RetVal = PType_486; - break; - - case PROCESSOR_INTEL_PENTIUM: - if (GetCPUId() & 0x00800000) - RetVal = PType_PentiumMMX; - else - RetVal = PType_Pentium; - break; - - #if 0 - case PROCESSOR_INTEL_SOMETHING: - RetVal = PType_Klamath; - break; - #endif - - default: - RetVal = PType_OffTopOfScale; - break; - } - - return RetVal; -} - - - -// End of extern C declaration - -}; - - - - diff --git a/3dc/win95/wpchunk.cpp b/3dc/win95/wpchunk.cpp deleted file mode 100644 index c26a5a6..0000000 --- a/3dc/win95/wpchunk.cpp +++ /dev/null @@ -1,575 +0,0 @@ -#include "wpchunk.hpp" - -//macro for helping to force inclusion of chunks when using libraries -FORCE_CHUNK_INCLUDE_IMPLEMENT(wpchunk) - -ChunkWaypoint::ChunkWaypoint() -{ - index=-1; - NumWPLinks=0; - WayLinks=0; - NumModLinks=0; - ModLinks=0; - flags=0; - spare2=0; -} -ChunkWaypoint::~ChunkWaypoint() -{ - if(WayLinks) delete [] WayLinks; - if(ModLinks) delete [] ModLinks; -} -ModuleLink::~ModuleLink() -{ - if(module_name) delete module_name; -} - -RIF_IMPLEMENT_DYNCREATE("WAYPOINT",Module_Waypoint_Chunk) - - -#if UseOldChunkLoader -Module_Waypoint_Chunk::Module_Waypoint_Chunk(Chunk_With_Children* parent,const char* data,size_t datasize) -:Chunk(parent,"WAYPOINT") -{ - NumWaypoints=*(int*)data; - data+=4; - if(NumWaypoints) - Waypoints=new ChunkWaypoint[NumWaypoints]; - else - Waypoints=0; - - for(int i=0;i<NumWaypoints;i++) - { - ChunkWaypoint* cw=&Waypoints[i]; - cw->index=i; - - cw->min=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - cw->max=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - cw->centre=*(ChunkVector*)data; - data+=sizeof(ChunkVector); - - cw->flags=*(int*)data; - data+=4; - cw->spare2=*(int*)data; - data+=4; - - cw->NumWPLinks=*(int*)data; - data+=4; - - if(cw->NumWPLinks) - cw->WayLinks=new WaypointLink[cw->NumWPLinks]; - else - cw->WayLinks=0; - - for(int j=0;j<cw->NumWPLinks;j++) - { - cw->WayLinks[j]=*(WaypointLink*)data; - data+=sizeof(WaypointLink); - } - - cw->NumModLinks=*(int*)data; - data+=4; - - if(cw->NumModLinks) - cw->ModLinks=new ModuleLink[cw->NumModLinks]; - else - cw->ModLinks=0; - - for(j=0;j<cw->NumModLinks;j++) - { - ModuleLink* ml=&cw->ModLinks[j]; - ml->module_name=new char[strlen(data)+1]; - strcpy(ml->module_name,data); - data+=(strlen(data)+4)&~3; - ml->flags=*(int*)data; - data+=4; - } - - - } - - spare1=*(int*)data; - data+=4; - spare2=*(int*)data; - data+=4; -} -#else -Module_Waypoint_Chunk::Module_Waypoint_Chunk(Chunk_With_Children* parent,const char* data,size_t datasize) -:Chunk(parent,"WAYPOINT") -{ - NumWaypoints=*(int*)data; - data+=4; - - NumGroundWaypoints=0; - NumAlienWaypoints=0; - AlienWaypoints=0; - GroundWaypoints=0; - - if(NumWaypoints) - Waypoints=new ChunkWaypoint[NumWaypoints]; - else - Waypoints=0; - - if(NumWaypoints) - { - int first_ground_waypoint=-1; - for(int i=0;i<NumWaypoints;i++) - { - ChunkWaypoint* cw=&Waypoints[i]; - cw->index=i; - - cw->min=*(ChunkVectorInt*)data; - data+=sizeof(ChunkVectorInt); - cw->max=*(ChunkVectorInt*)data; - data+=sizeof(ChunkVectorInt); - cw->centre=*(ChunkVectorInt*)data; - data+=sizeof(ChunkVectorInt); - - cw->flags=*(int*)data; - data+=4; - cw->spare2=*(int*)data; - data+=4; - - cw->NumWPLinks=*(int*)data; - data+=4; - - if(cw->NumWPLinks) - cw->WayLinks=new WaypointLink[cw->NumWPLinks]; - else - cw->WayLinks=0; - - for(int j=0;j<cw->NumWPLinks;j++) - { - cw->WayLinks[j]=*(WaypointLink*)data; - data+=sizeof(WaypointLink); - } - - cw->NumModLinks=*(int*)data; - data+=4; - - if(cw->NumModLinks) - cw->ModLinks=new ModuleLink[cw->NumModLinks]; - else - cw->ModLinks=0; - - for(j=0;j<cw->NumModLinks;j++) - { - ModuleLink* ml=&cw->ModLinks[j]; - ml->module_name=new char[strlen(data)+1]; - strcpy(ml->module_name,data); - data+=(strlen(data)+4)&~3; - ml->flags=*(int*)data; - data+=4; - } - - if(cw->flags & WaypointFlag_FirstGroundWaypoint) - { - first_ground_waypoint=i; - cw->flags &=~WaypointFlag_FirstGroundWaypoint; - } - } - - if(first_ground_waypoint>=0) - { - GroundWaypoints=&Waypoints[first_ground_waypoint]; - NumGroundWaypoints=NumWaypoints-first_ground_waypoint; - } - NumAlienWaypoints=NumWaypoints-NumGroundWaypoints; - if(NumAlienWaypoints) - { - AlienWaypoints=&Waypoints[0]; - } - - - } - - - spare1=*(int*)data; - data+=4; - spare2=*(int*)data; - data+=4; - -} -#endif - -Module_Waypoint_Chunk::Module_Waypoint_Chunk(Chunk_With_Children* parent) -:Chunk(parent,"WAYPOINT") -{ - NumWaypoints=0; - Waypoints=0; - - NumAlienWaypoints=0; - AlienWaypoints=0; - - NumGroundWaypoints=0; - GroundWaypoints=0; - - - spare1=0; - spare2=0; -} - -Module_Waypoint_Chunk::~Module_Waypoint_Chunk() -{ - if(Waypoints) - delete [] Waypoints; -} - -size_t Module_Waypoint_Chunk::size_chunk() -{ - chunk_size=16; - for(int i=0;i<NumWaypoints;i++) - { - chunk_size+=16+3*sizeof(ChunkVectorInt); - chunk_size+=sizeof(WaypointLink)*Waypoints[i].NumWPLinks; - for(int j=0;j<Waypoints[i].NumModLinks;j++) - { - chunk_size+=4; - chunk_size+=(strlen(Waypoints[i].ModLinks[j].module_name)+4)&~3; - } - } - return chunk_size; -} - -void Module_Waypoint_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - - *(int*)data_start=NumWaypoints; - data_start+=4; - - for(int i=0;i<NumWaypoints;i++) - { - ChunkWaypoint* cw=&Waypoints[i]; - - *(ChunkVectorInt*)data_start=cw->min; - data_start+=sizeof(ChunkVectorInt); - *(ChunkVectorInt*)data_start=cw->max; - data_start+=sizeof(ChunkVectorInt); - *(ChunkVectorInt*)data_start=cw->centre; - data_start+=sizeof(ChunkVectorInt); - - if(i==NumAlienWaypoints) - { - //mark start of marine waypoints - *(int*)data_start=cw->flags | WaypointFlag_FirstGroundWaypoint; - } - else - { - *(int*)data_start=cw->flags; - } - data_start+=4; - - *(int*)data_start=cw->spare2; - data_start+=4; - - *(int*)data_start=cw->NumWPLinks; - data_start+=4; - - for(int j=0;j<cw->NumWPLinks;j++) - { - *(WaypointLink*)data_start=cw->WayLinks[j]; - data_start+=sizeof(WaypointLink); - } - - *(int*)data_start=cw->NumModLinks; - data_start+=4; - - for(j=0;j<cw->NumModLinks;j++) - { - ModuleLink* ml=&cw->ModLinks[j]; - strcpy(data_start,ml->module_name); - data_start+=(strlen(ml->module_name)+4)&~3; - *(int*)data_start=ml->flags; - data_start+=4; - } - - } -} - -void Module_Waypoint_Chunk::TransferWaypointData(Module_Waypoint_Chunk* mwc_from) -{ - if(!mwc_from)return; - if(!mwc_from->NumWaypoints)return; - if(mwc_from==this)return; - - if(mwc_from->NumWaypoints) - { - ChunkWaypoint* new_wp=new ChunkWaypoint[NumWaypoints+mwc_from->NumWaypoints]; - //first take alien waypoints from this chunk - for(int i=0;i<NumAlienWaypoints;i++) - { - new_wp[i]=AlienWaypoints[i]; - //set pointers to zero so the memory doesn't get deallocated when the old - //waypoint array is deleted - AlienWaypoints[i].WayLinks=0; - AlienWaypoints[i].ModLinks=0; - } - - //copy alien waypoints from other chunk - - for(i=0;i<mwc_from->NumAlienWaypoints;i++) - { - ChunkWaypoint* cw=&new_wp[i+NumAlienWaypoints]; - *cw=mwc_from->AlienWaypoints[i]; - //set pointers to zero so the memory doesn't get deallocated when the old - //waypoint chunk is deleted - mwc_from->AlienWaypoints[i].WayLinks=0; - mwc_from->AlienWaypoints[i].ModLinks=0; - - //adjust the indeces - cw->index+=NumAlienWaypoints; - for(int j=0;j<cw->NumWPLinks;j++) - { - cw->WayLinks[j].index+=NumAlienWaypoints; - } - } - NumAlienWaypoints+=mwc_from->NumAlienWaypoints; - - //now take ground waypoints from this chunk - for(i=0;i<NumGroundWaypoints;i++) - { - new_wp[NumAlienWaypoints+i]=GroundWaypoints[i]; - //set pointers to zero so the memory doesn't get deallocated when the old - //waypoint array is deleted - GroundWaypoints[i].WayLinks=0; - GroundWaypoints[i].ModLinks=0; - } - - //copy ground waypoints from other chunk - - for(i=0;i<mwc_from->NumGroundWaypoints;i++) - { - ChunkWaypoint* cw=&new_wp[i+NumAlienWaypoints+NumGroundWaypoints]; - *cw=mwc_from->GroundWaypoints[i]; - //set pointers to zero so the memory doesn't get deallocated when the old - //waypoint chunk is deleted - mwc_from->GroundWaypoints[i].WayLinks=0; - mwc_from->GroundWaypoints[i].ModLinks=0; - - //adjust the indeces - cw->index+=NumGroundWaypoints; - for(int j=0;j<cw->NumWPLinks;j++) - { - cw->WayLinks[j].index+=NumGroundWaypoints; - } - } - NumGroundWaypoints+=mwc_from->NumGroundWaypoints; - - NumWaypoints+=mwc_from->NumWaypoints; - //replace pointer to waypoints - delete [] Waypoints; - Waypoints=new_wp; - } - - if(NumAlienWaypoints) - AlienWaypoints=&Waypoints[0]; - else - AlienWaypoints=0; - - if(NumGroundWaypoints) - GroundWaypoints=&Waypoints[NumAlienWaypoints]; - else - GroundWaypoints=0; - - - delete mwc_from; - -} -/////////////////////////////////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("AIMODMAS",AI_Module_Master_Chunk) - -AI_Module_Master_Chunk::AI_Module_Master_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"AIMODMAS") -{ -} - -AI_Module_Master_Chunk::AI_Module_Master_Chunk(Object_Module_Data_Chunk* parent) -:Chunk(parent,"AIMODMAS") -{ -} - - -size_t AI_Module_Master_Chunk::size_chunk() -{ - chunk_size=12; - return chunk_size; -} - -void AI_Module_Master_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; -} - -AI_Module_Slave_Chunk* AddModuleSlaveChunk(Object_Chunk* oc,Object_Chunk* master) -{ - Object_Module_Data_Chunk* omdc=0; - omdc=(Object_Module_Data_Chunk*)oc->lookup_single_child("MODULEDT"); - if(!omdc) - omdc=new Object_Module_Data_Chunk(oc); - - Chunk* child_chunk=omdc->lookup_single_child("AIMODSLA"); - - if(child_chunk) - delete child_chunk; - - return new AI_Module_Slave_Chunk(omdc,master); - -} - -void AI_Module_Master_Chunk::AddModule(Object_Chunk* oc) -{ - if(ModuleList.contains(oc)) return; - if(oc==get_my_object_chunk()) return; - - Object_Module_Data_Chunk* omdc=0; - omdc=(Object_Module_Data_Chunk*)oc->lookup_single_child("MODULEDT"); - - if(omdc) - { - List<Chunk*> chlist; - omdc->lookup_child("AIMODMAS",chlist); - if(chlist.size()) - { - //if the module being added is a master , add all its slaves as well - AI_Module_Master_Chunk* ammc=(AI_Module_Master_Chunk*)chlist.first_entry(); - for(LIF<Object_Chunk*> oblif(&ammc->ModuleList);!oblif.done();oblif.next()) - { - if(!ModuleList.contains(oblif()) && oblif()!=get_my_object_chunk()) - { - ModuleList.add_entry(oblif()); - //create new slave chunks for the modules being added - AddModuleSlaveChunk(oblif(),get_my_object_chunk()); - } - } - delete ammc; - } - } - - //add this module - ModuleList.add_entry(oc); - AddModuleSlaveChunk(oc,get_my_object_chunk()); - - //see if there are any waypoints to copy - if(omdc) - { - Module_Waypoint_Chunk* mwc_from=(Module_Waypoint_Chunk*)omdc->lookup_single_child("WAYPOINT"); - if(mwc_from) - { - Module_Waypoint_Chunk* mwc_to=0; - - mwc_to=(Module_Waypoint_Chunk*)parent->lookup_single_child("WAYPOINT"); - if(!mwc_to) - mwc_to=new Module_Waypoint_Chunk(parent); - - mwc_to->TransferWaypointData(mwc_from); - - - } - } - -} - -Object_Chunk* AI_Module_Master_Chunk::get_my_object_chunk() -{ - return (Object_Chunk*)((Object_Module_Data_Chunk*)parent)->parent; -} - -/////////////////////////////////////////////////////////////////////////////// - -RIF_IMPLEMENT_DYNCREATE("AIMODSLA",AI_Module_Slave_Chunk) - -#if UseOldChunkLoader -AI_Module_Slave_Chunk::AI_Module_Slave_Chunk(Object_Module_Data_Chunk* parent,const char* data,size_t) -:Chunk(parent,"AIMODSLA") -{ - MasterModule=0; - MasterModuleName=new char[strlen(data)+1]; - strcpy(MasterModuleName,data); - MasterModuleIndex=0; -} -#else -AI_Module_Slave_Chunk::AI_Module_Slave_Chunk(Chunk_With_Children* parent,const char* data,size_t) -:Chunk(parent,"AIMODSLA") -{ - MasterModule=0; - MasterModuleIndex=*(int*)data; -} -#endif - -AI_Module_Slave_Chunk::AI_Module_Slave_Chunk(Object_Module_Data_Chunk* parent,Object_Chunk* _MasterModule) -:Chunk(parent,"AIMODSLA") -{ - MasterModule=_MasterModule; - MasterModuleIndex=MasterModule->object_data.index_num; -} - -AI_Module_Slave_Chunk::~AI_Module_Slave_Chunk() -{ - #if UseOldChunkLoader - delete [] MasterModuleName; - #endif -} - -size_t AI_Module_Slave_Chunk::size_chunk() -{ - chunk_size=16; - return chunk_size; -} - -void AI_Module_Slave_Chunk::fill_data_block(char* data_start) -{ - strncpy (data_start, identifier, 8); - data_start += 8; - *((int *) data_start) = chunk_size; - data_start += 4; - *((int *) data_start) = MasterModuleIndex; - data_start += 4; - - -} - -void AI_Module_Slave_Chunk::post_input_processing() -{ - #if !UseOldChunkLoader - File_Chunk* fc=(File_Chunk*)GetRootChunk(); - if(!strcmp(fc->identifier,"REBINFF2")) - { - Object_Chunk* oc=fc->get_object_by_index(MasterModuleIndex); - if(oc) - { - Object_Module_Data_Chunk* omdc=(Object_Module_Data_Chunk*)oc->lookup_single_child("MODULEDT"); - if(!omdc) - { - return; - } - - List<Chunk*> chlist; - omdc->lookup_child("AIMODMAS",chlist); - if(!chlist.size()) - { - //master module doesn't have a master module chunk - return; - } - AI_Module_Master_Chunk* ammc=(AI_Module_Master_Chunk*)chlist.first_entry(); - ammc->ModuleList.add_entry(get_my_object_chunk()); - MasterModule=oc; - return; - - } - } - #endif -} - -Object_Chunk* AI_Module_Slave_Chunk::get_my_object_chunk() -{ - return (Object_Chunk*)((Object_Module_Data_Chunk*)parent)->parent; -} diff --git a/3dc/win95/wpchunk.hpp b/3dc/win95/wpchunk.hpp deleted file mode 100644 index dbd34c4..0000000 --- a/3dc/win95/wpchunk.hpp +++ /dev/null @@ -1,107 +0,0 @@ -#ifndef wpchunk_hpp -#define wpchunk_hpp 1 - -#include "chunk.hpp" -#include "chnktype.hpp" -#include "obchunk.hpp" - -struct WaypointLink -{ - int index; - int flags; -}; - -struct ModuleLink -{ - ~ModuleLink(); - - char* module_name; - int flags; -}; - -#define WaypointFlag_CentreDefinedByUser 0x80000000 -#define WaypointFlag_FirstGroundWaypoint 0x40000000 -struct ChunkWaypoint -{ - ChunkWaypoint(); - ~ChunkWaypoint(); - - int index; - ChunkVectorInt min,max; //relative to centre - ChunkVectorInt centre; //relative to world - - int NumWPLinks; - WaypointLink* WayLinks; - - int NumModLinks; - ModuleLink* ModLinks; - - int flags,spare2; - -}; - -class Module_Waypoint_Chunk : public Chunk -{ - public : - Module_Waypoint_Chunk(Chunk_With_Children*,const char *,size_t); - Module_Waypoint_Chunk(Chunk_With_Children*); - ~Module_Waypoint_Chunk(); - - virtual size_t size_chunk(); - virtual void fill_data_block(char* data_start); - - //Copies waypoint data and deletes the old waypoint_chunk - void TransferWaypointData(Module_Waypoint_Chunk*); - - int NumWaypoints; - ChunkWaypoint* Waypoints; - - ChunkWaypoint* AlienWaypoints; - ChunkWaypoint* GroundWaypoints; - - short NumAlienWaypoints; - short NumGroundWaypoints; - - int spare1; - int spare2; -}; - -class AI_Module_Master_Chunk : public Chunk -{ - public : - AI_Module_Master_Chunk(Chunk_With_Children*,const char*,size_t); - AI_Module_Master_Chunk(Object_Module_Data_Chunk*); - - virtual size_t size_chunk(); - virtual void fill_data_block(char* data_start); - - void AddModule(Object_Chunk*); - Object_Chunk* get_my_object_chunk(); - - List<Object_Chunk*> ModuleList; -}; - -class AI_Module_Slave_Chunk : public Chunk -{ - public : - AI_Module_Slave_Chunk(Chunk_With_Children*,const char*,size_t); - AI_Module_Slave_Chunk(Object_Module_Data_Chunk*,Object_Chunk*); - ~AI_Module_Slave_Chunk(); - - virtual size_t size_chunk(); - virtual void fill_data_block(char* data_start); - virtual void post_input_processing(); - - Object_Chunk* get_my_object_chunk(); - - Object_Chunk* MasterModule; - #if UseOldChunkLoader - char* MasterModuleName; - #endif - int MasterModuleIndex; -}; - - -#endif - - diff --git a/3dc/win95/zbuffer.c b/3dc/win95/zbuffer.c deleted file mode 100644 index b33ea85..0000000 --- a/3dc/win95/zbuffer.c +++ /dev/null @@ -1,91 +0,0 @@ -/***************************************************************************/ -/* Creation of Z-Buffer */ -/***************************************************************************/ -/* - * D3DAppICreateZBuffer - * Create a Z-Buffer of the appropriate depth and attach it to the back - * buffer. - */ -BOOL -D3DAppICreateZBuffer(int w, int h, int driver) -{ - DDSURFACEDESC ddsd; - DWORD devDepth; - /* - * Release any Z-Buffer that might be around just in case. - */ - RELEASE(d3dappi.lpZBuffer); - - /* - * If this driver does not do z-buffering, don't create a z-buffer - */ - if (!d3dappi.Driver[driver].bDoesZBuffer) - return TRUE; - - memset(&ddsd, 0 ,sizeof(DDSURFACEDESC)); - ddsd.dwSize = sizeof( ddsd ); - ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS | - DDSD_ZBUFFERBITDEPTH; - ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER; - ddsd.dwHeight = h; - ddsd.dwWidth = w; - /* - * If this is a hardware D3D driver, the Z-Buffer MUST end up in video - * memory. Otherwise, it MUST end up in system memory. - */ - if (d3dappi.Driver[driver].bIsHardware) - ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY; - else - ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY; - /* - * Get the Z buffer bit depth from this driver's D3D device description - */ - devDepth = d3dappi.Driver[driver].Desc.dwDeviceZBufferBitDepth; - if (devDepth & DDBD_32) - ddsd.dwZBufferBitDepth = 32; - else if (devDepth & DDBD_24) - ddsd.dwZBufferBitDepth = 24; - else if (devDepth & DDBD_16) - ddsd.dwZBufferBitDepth = 16; - else if (devDepth & DDBD_8) - ddsd.dwZBufferBitDepth = 8; - else { - D3DAppISetErrorString("Unsupported Z-buffer depth requested by device.\n"); - return FALSE; - } - LastError = d3dappi.lpDD->lpVtbl->CreateSurface(d3dappi.lpDD, &ddsd, - &d3dappi.lpZBuffer, - NULL); - if(LastError != DD_OK) { - D3DAppISetErrorString("CreateSurface for Z-buffer failed.\n%s", - D3DAppErrorToString(LastError)); - goto exit_with_error; - } - /* - * Attach the Z-buffer to the back buffer so D3D will find it - */ - LastError = - d3dappi.lpBackBuffer->lpVtbl->AddAttachedSurface(d3dappi.lpBackBuffer, - d3dappi.lpZBuffer); - if(LastError != DD_OK) { - D3DAppISetErrorString("AddAttachedBuffer failed for Z-Buffer.\n%s", - D3DAppErrorToString(LastError)); - goto exit_with_error; - } - /* - * Find out if it ended up in video memory (FYI). - */ - LastError = D3DAppIGetSurfDesc(&ddsd, d3dappi.lpZBuffer); - if (LastError != DD_OK) { - D3DAppISetErrorString("Failed to get surface description of Z buffer.\n%s", - D3DAppErrorToString(LastError)); - goto exit_with_error; - } - d3dappi.bZBufferInVideo = - (ddsd.ddsCaps.dwCaps & DDSCAPS_VIDEOMEMORY) ? TRUE : FALSE; - return TRUE; - -exit_with_error: - RELEASE(d3dappi.lpZBuffer); - return FALSE; -} |
