void InitializeGame(void)
{
  try {
    #ifndef NDEBUG 
      #define GAMEDLL _fnmApplicationExe.FileDir()+"Game"+_strModExt+"D.dll"
    #else
      #define GAMEDLL _fnmApplicationExe.FileDir()+"Game"+_strModExt+".dll"
    #endif
    CTFileName fnmExpanded;
    ExpandFilePath(EFP_READ, CTString(GAMEDLL), fnmExpanded);

    CPrintF(TRANS("Loading game library '%s'...\n"), (const char *)fnmExpanded);
    HMODULE hGame = LoadLibraryA(fnmExpanded);
    if (hGame==NULL) {
      ThrowF_t("%s", GetWindowsError(GetLastError()));
    }
    CGame* (*GAME_Create)(void) = (CGame* (*)(void))GetProcAddress(hGame, "GAME_Create");
    if (GAME_Create==NULL) {
      ThrowF_t("%s", GetWindowsError(GetLastError()));
    }
    _pGame = GAME_Create();

  } catch (char *strError) {
    FatalError("%s", strError);
  }
  // init game - this will load persistent symbols
  _pGame->Initialize(CTString("Data\\DedicatedServer.gms"));
}
// set socket to non-blocking mode
void CCommunicationInterface::SetNonBlocking_t(void)
{
  if (cci_hSocket==INVALID_SOCKET) {
    ASSERT(FALSE);
    return;
  }

#ifdef PLATFORM_WIN32
  ULONG ulArgNonBlocking = 1;
  if (ioctlsocket(cci_hSocket, FIONBIO, &ulArgNonBlocking) == SOCKET_ERROR) {
    ThrowF_t(TRANS("Cannot set socket to non-blocking mode. %s"), 
      (const char*)GetSocketError(WSAGetLastError()));
  }
#else
  int flags = fcntl(cci_hSocket, F_GETFL);
  int failed = flags;
  if (failed != -1) {
      flags |= O_NONBLOCK;
      failed = fcntl(cci_hSocket, F_SETFL, flags);
  }

  if (failed == -1) {
    ThrowF_t(TRANS("Cannot set socket to non-blocking mode. %s"), 
      (const char*)GetSocketError(WSAGetLastError()));
  }
#endif

};
예제 #3
0
// get a GUID from system
static void GetGUID(UBYTE aub[16])
{
  HINSTANCE hOle32Lib = NULL;
  CoCreateGuid_t *pCoCreateGuid = NULL;

  try {
    // load ole32
    hOle32Lib = ::LoadLibrary( "ole32.dll");
    if( hOle32Lib == NULL) {
      ThrowF_t(TRANS("Cannot load ole32.dll."));
    }

    // find GUID function
    pCoCreateGuid = (CoCreateGuid_t*)GetProcAddress(hOle32Lib, "CoCreateGuid");
    if (pCoCreateGuid==NULL) {
      ThrowF_t(TRANS("Cannot find CoCreateGuid()."));
    }

    // create the guid
    HRESULT hres = pCoCreateGuid(&aub[0]);

    // check for success
    if (hres!=S_OK) {
      ThrowF_t(TRANS("CoCreateGuid(): Error 0x%08x"), hres);
    }

    // free the ole32 library
    FreeLibrary(hOle32Lib);

  } catch(char *strError) {
    FatalError(TRANS("Cannot make GUID for a player:\n%s"), strError);
  }
}
예제 #4
0
// initialize game and load settings
void Initialize(const CTFileName &fnGameSettings)
{
  try {
    #ifndef NDEBUG 
      #define GAMEDLL "Bin\\Debug\\GameMPD.dll"
    #else
      #define GAMEDLL "Bin\\GameMP.dll"
    #endif
    CTFileName fnmExpanded;
    ExpandFilePath(EFP_READ, CTString(GAMEDLL), fnmExpanded);
    HMODULE hGame = LoadLibraryA(fnmExpanded);
    if (hGame==NULL) {
      ThrowF_t("%s", GetWindowsError(GetLastError()));
    }
    CGame* (*GAME_Create)(void) = (CGame* (*)(void))GetProcAddress(hGame, "GAME_Create");
    if (GAME_Create==NULL) {
      ThrowF_t("%s", GetWindowsError(GetLastError()));
    }
    _pGame = GAME_Create();

  } catch (char *strError) {
    FatalError("%s", strError);
  }
  // init game - this will load persistent symbols
  _pGame->Initialize(fnGameSettings);

}
예제 #5
0
// initialize/end the decoding support engine(s)
void CSoundDecoder::InitPlugins(void)
{
  try {
    // load vorbis
    if (_hOV==NULL) {
#ifndef NDEBUG
//안태훈 수정 시작	//(Exception Check & Fix)(0.1)
  #define VORBISLIB "vorbisfile.dll"
//  #define VORBISLIB "vorbisfile_d.dll"
//안태훈 수정 끝	//(Exception Check & Fix)(0.1)
#else
  #define VORBISLIB "vorbisfile.dll"
#endif
      _hOV = ::LoadLibrary(VORBISLIB);
    }
    if( _hOV == NULL) {
      ThrowF_t(TRANS("Cannot load vorbisfile.dll."));
    }
    // prepare function pointers
    OV_SetFunctionPointers_t();

    // if all successful, enable mpx playing
    _bOVEnabled = TRUE;
    CPrintF(TRANS("  vorbisfile.dll loaded, ogg playing enabled\n"));

  } catch (char *strError) {
    CPrintF(TRANS("OGG playing disabled: %s\n"), strError);
  }

  try {
    // load amp11lib
    if (_hAmp11lib==NULL) {
      _hAmp11lib = ::LoadLibrary( "amp11lib.dll");
    }
    if( _hAmp11lib == NULL) {
      ThrowF_t(TRANS("Cannot load amp11lib.dll."));
    }
    // prepare function pointers
    AMP11_SetFunctionPointers_t();

    // initialize amp11lib before calling any of its functions
    palInitLibrary();

    // if all successful, enable mpx playing
    _bAMP11Enabled = TRUE;
    CPrintF(TRANS("  amp11lib.dll loaded, mpx playing enabled\n"));

  } catch (char *strError) {
    CPrintF(TRANS("MPX playing disabled: %s\n"), strError);
  }
}
// get address of this host
void CCommunicationInterface::GetLocalAddress_t(ULONG &ulHost, ULONG &ulPort)
{
  ulHost = 0;
  ulPort = 0;
  if (cci_hSocket==INVALID_SOCKET) {
    ASSERT(FALSE);
    return;
  }

  // get socket local port and address
  sockaddr_in sin;
  socklen_t iSize = sizeof(sin);
  if (getsockname(cci_hSocket, (sockaddr*)&sin, &iSize) == SOCKET_ERROR) {
    ThrowF_t(TRANS("Cannot get local address on socket. %s"), 
      (const char*)GetSocketError(WSAGetLastError()));
  }

#ifdef PLATFORM_WIN32
  ulHost = ntohl(sin.sin_addr.S_un.S_addr);
#else
  ulHost = ntohl(sin.sin_addr.s_addr);
#endif

  ulPort = ntohs(sin.sin_port);
}
// update the broadcast input buffer - handle any incoming connection requests
void CCommunicationInterface::Broadcast_Update_t() {
	CPacket* ppaConnectionRequest;
	BOOL bIsAlready;
	BOOL bFoundEmpty;
	ULONG iClient;
	UBYTE ubDummy=65;

	
	// while there is a connection request packet in the input buffer
	while ((ppaConnectionRequest = cm_ciBroadcast.ci_pbReliableInputBuffer.GetConnectRequestPacket()) != NULL) {
		// see if there is a client already connected at that address and port
		bIsAlready = FALSE;
		for (iClient=1;iClient<SERVER_CLIENTS;iClient++) {
			if (cm_aciClients[iClient].ci_adrAddress.adr_ulAddress == ppaConnectionRequest->pa_adrAddress.adr_ulAddress &&
					cm_aciClients[iClient].ci_adrAddress.adr_uwPort == ppaConnectionRequest->pa_adrAddress.adr_uwPort) {
					bIsAlready = TRUE;
					break;
			}
		}
		// if the client is already connected then just ignore the packet - else, connect it
		if (!bIsAlready) {
			// find an empty client structure
			bFoundEmpty = FALSE;
			for (iClient=1;iClient<SERVER_CLIENTS;iClient++) {
				if (cm_aciClients[iClient].ci_bUsed == FALSE) {
					bFoundEmpty = TRUE;
					// we have an empty slot, so fill it for the client
					cm_aciClients[iClient].ci_adrAddress.adr_ulAddress = ppaConnectionRequest->pa_adrAddress.adr_ulAddress;
					cm_aciClients[iClient].ci_adrAddress.adr_uwPort = ppaConnectionRequest->pa_adrAddress.adr_uwPort;
					// generate the ID
					UWORD uwID = _pTimer->GetHighPrecisionTimer().tv_llValue&0x0FFF;
					if (uwID==0 || uwID==SLASHSLASH) {
						uwID+=1;
					}										
					cm_aciClients[iClient].ci_adrAddress.adr_uwID = (uwID<<4)+iClient;
					// form the connection response packet
					ppaConnectionRequest->pa_adrAddress.adr_uwID = SLASHSLASH;
					ppaConnectionRequest->pa_ubReliable = UDP_PACKET_RELIABLE | UDP_PACKET_RELIABLE_HEAD | UDP_PACKET_RELIABLE_TAIL | UDP_PACKET_CONNECT_RESPONSE;
					// return it to the client
					ppaConnectionRequest->WriteToPacket(&(cm_aciClients[iClient].ci_adrAddress.adr_uwID),sizeof(cm_aciClients[iClient].ci_adrAddress.adr_uwID),ppaConnectionRequest->pa_ubReliable,cm_ciBroadcast.ci_ulSequence++,ppaConnectionRequest->pa_adrAddress.adr_uwID,sizeof(cm_aciClients[iClient].ci_adrAddress.adr_uwID));
					cm_ciBroadcast.ci_pbOutputBuffer.AppendPacket(*ppaConnectionRequest,TRUE);
					cm_aciClients[iClient].ci_bUsed = TRUE;
					return;
				}
			}

			// if none found
			if (!bFoundEmpty) {
				// error
				ThrowF_t(TRANS("Server: Cannot accept new clients, all slots used!\n"));
			}
	
		}
	}


};
예제 #8
0
// initialize game and load settings
void Initialize(const CTFileName &fnGameSettings)
{
  try {
#ifndef NDEBUG 

#	ifdef	WORLD_EDITOR
#		define GAMEDLL "GameMPD.dll"
#	else
#		define GAMEDLL "Bin\\Debug\\GameMPD.dll"
#	endif

#else
#	ifdef	WORLD_EDITOR
	#define GAMEDLL "GameMP.dll"
#	else	// WORLD_EDITOR
    #define GAMEDLL "Bin\\GameMP.dll"
#	endif	// WORLD_EDITOR
#endif
    CTFileName fnmExpanded;
#ifndef		WORLD_EDITOR
    ExpandFilePath(EFP_READ, CTString(GAMEDLL), fnmExpanded);
#else
	fnmExpanded = _fnmApplicationPath + _fnmApplicationExe.FileDir() + GAMEDLL;
#endif

	HMODULE hGame = LoadLibrary(fnmExpanded);
    if (hGame==NULL) {
      ThrowF_t("%s", GetWindowsError(GetLastError()));
    }
    CGame* (*GAME_Create)(void) = (CGame* (*)(void))GetProcAddress(hGame, "GAME_Create");
    if (GAME_Create==NULL) {
      ThrowF_t("%s", GetWindowsError(GetLastError()));
    }
    _pGame = GAME_Create();

  } catch (char *strError) {
    FatalError("%s", strError);
  }
  // init game - this will load persistent symbols
  // 수정된 더미. [3/2/2011 rumist]
  _pGame->Initialize(fnGameSettings, FALSE );

}
// create an inet-family socket
void CCommunicationInterface::CreateSocket_t()
{
  ASSERT(cci_hSocket==INVALID_SOCKET);
  // open the socket
  cci_hSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	cci_bBound = FALSE;
  if (cci_hSocket == INVALID_SOCKET) {
    ThrowF_t(TRANS("Cannot open socket. %s"), (const char*)GetSocketError(WSAGetLastError()));
  }

};
예제 #10
0
void CTStream::ExpectID_t(const CChunkID &cidExpected) // throws char *
{
	CChunkID cidToCompare;

	Read_t( &cidToCompare.cid_ID[0], CID_LENGTH);
	if( !(cidToCompare == cidExpected))
	{
		ThrowF_t(TRANS("Chunk ID validation failed.\nExpected ID \"%s\" but found \"%s\"\n"),
      cidExpected.cid_ID, cidToCompare.cid_ID);
	}
}
예제 #11
0
void CTStream::ExpectKeyword_t(const CTString &strKeyword) // throw char *
{
  // check that the keyword is present
  const INDEX total = (INDEX)strlen(strKeyword);
  for(INDEX iKeywordChar=0; iKeywordChar<total; iKeywordChar++) {
    SBYTE chKeywordChar;
    (*this)>>chKeywordChar;
    if (chKeywordChar!=strKeyword[iKeywordChar]) {
      ThrowF_t(TRANS("Expected keyword %s not found"), (const char *) strKeyword);
    }
  }
}
예제 #12
0
/*
 * Remove application path from a file name.
 */
void CTFileName::RemoveApplicationPath_t(void) // throws char *
{
    // remove the path string from beginning of the string
    BOOL bHadRightPath = RemovePrefix(_fnmApplicationPath);
    if (_fnmMod!="") {
        RemovePrefix(_fnmApplicationPath+_fnmMod);
    }
    // if it had wrong path
    if (!bHadRightPath) {
        // throw error
        ThrowF_t(TRANS("File '%s' has got wrong path!\nAll files must reside in directory '%s'."),
                 str_String, (CTString&)_fnmApplicationPath);
    }
}
/*
 *  Initialize client
 */
void CCommunicationInterface::Client_Init_t(char* strServerName)
{
  CTSingleLock slComm(&cm_csComm, TRUE);

  ASSERT(cci_bInitialized);
  ASSERT(!cci_bClientInitialized);

  // retrieve server address from server name
  ULONG ulServerAddress = StringToAddress(strServerName);
  // if lookup failed
  if (ulServerAddress==INADDR_NONE) {
    ThrowF_t(TRANS("Host '%s' not found!\n"), strServerName);
  }

  // call client init with server address
  Client_Init_t(ulServerAddress);
};
// bind socket to the given address
void CCommunicationInterface::Bind_t(ULONG ulLocalHost, ULONG ulLocalPort)
{
  if (cci_hSocket==INVALID_SOCKET) {
    ASSERT(FALSE);
    return;
  }

  sockaddr_in sin;
  sin.sin_family = AF_INET;
  sin.sin_port = htons(ulLocalPort);
  sin.sin_addr.s_addr = htonl(ulLocalHost);

  // bind socket to server address/port
  if (bind(cci_hSocket, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR) {
    ThrowF_t(TRANS("Cannot bind socket. %s"), (const char*)GetSocketError(WSAGetLastError()));
  }
  cci_bBound = TRUE;
};
예제 #15
0
// throws char *
void CTStream::GetLine_t(char *strBuffer, SLONG slBufferSize, char cDelimiter /*='\n'*/ )
{
  // check parameters
  ASSERT(strBuffer!=NULL && slBufferSize>0);
  // check that the stream can be read
  ASSERT(IsReadable());
  // letters slider
  INDEX iLetters = 0;
  // test if EOF reached
  if(AtEOF()) {
    ThrowF_t(TRANS("EOF reached, file %s"), (const char *) strm_strStreamDescription);
  }
  // get line from istream
  FOREVER
  {
    char c;
    Read_t(&c, 1);

    if(AtEOF()) {
      // cut off
      strBuffer[ iLetters] = 0;
      break;
    }

    // don't read "\r" characters but rather act like they don't exist
    if( c != '\r') {
      strBuffer[ iLetters] = c;
      // stop reading when delimiter loaded
      if( strBuffer[ iLetters] == cDelimiter) {
        // convert delimiter to zero
        strBuffer[ iLetters] = 0;
        // jump over delimiter
        //Seek_t(1, SD_CUR);
        break;
      }
      // jump to next destination letter
      iLetters++;
    }
    // test if maximum buffer lenght reached
    if( iLetters==slBufferSize) {
      return;
    }
  }
}
예제 #16
0
// start pasring fnParseFile file (may include mesh,skeleton,animset,...)
BOOL StartParser(CTString fnParseFile)
{
  CTFileName fnFull;
  fnFull = _fnmApplicationPath + fnParseFile;

  yyin = NULL;
  astrText.PopAll();
  astrText.Clear();
  // initialize pre-parsing variables
  yyin = fopen(fnFull, "r");
  // reset include depth ptr
  include_stack_ptr = 0;
  strCurentFileName = fnFull;

  _yy_iIndex = 0;
  _yy_jIndex = 0;
  _yy_iLine = 1;

  // load data
  try
  {
    if (yyin==NULL) {
      ThrowF_t("Cannot open file '%s'!", (const char*)fnParseFile );
    }

    yyrestart(yyin);
    yyparse();
 
    fclose(yyin);
  }
  // if an error in parsing occured
  catch(char *strError)
  {
    WarningMessage(strError);
    // AfxMessageBox(strError);
    theApp.ErrorMessage(strError);
    if(yyin!=NULL) fclose(yyin);
    return FALSE;
  }
return TRUE;
}
static void LoadingHook_t(CProgressHookInfo *pphi)
{
  // measure time since last call
  static CTimerValue tvLast(0I64);
  CTimerValue tvNow = _pTimer->GetHighPrecisionTimer();

  if (!_bRunning) {
    ThrowF_t(TRANS("User break!"));
  }
  // if not first or final update, and not enough time passed
  if (pphi->phi_fCompleted!=0 && pphi->phi_fCompleted!=1 &&
     (tvNow-tvLast).GetSeconds() < REFRESHTIME) {
    // do nothing
    return;
  }
  tvLast = tvNow;

  // print status text
  CTString strRes;
  printf("\r                                                                      ");
  printf("\r%s : %3.0f%%\r", pphi->phi_strDescription, pphi->phi_fCompleted*100);
}
예제 #18
0
/* Unpack from stream to stream. */
void CCompressor::UnpackStream_t(CTMemoryStream &strmSrc, CTStream &strmDst) // throw char *
{
  // read the header
  SLONG slSizeDst, slSizeSrc;
  strmSrc>>slSizeDst;
  strmSrc>>slSizeSrc;
  // get the buffer of source stream
  UBYTE *pubSrc = strmSrc.mstrm_pubBuffer + strmSrc.mstrm_slLocation;
  // allocate buffer for decompression
  UBYTE *pubDst = (UBYTE*)AllocMemory(slSizeDst);
  // compress there
  BOOL bOk = Unpack(pubSrc, slSizeSrc, pubDst, slSizeDst);
  // if failed
  if (!bOk) {
    // report error
    FreeMemory(pubDst);
    ThrowF_t(TRANS("Error while unpacking a stream."));
  }

  // write the uncompressed data to destination
  strmDst.Write_t(pubDst, slSizeDst);
  strmDst.SetPos_t(0);
  FreeMemory(pubDst);
}
예제 #19
0
void CCompressor::PackStream_t(CTMemoryStream &strmSrc, CTStream &strmDst) // throw char *
{
  // get the buffer of source stream
  UBYTE *pubSrc = strmSrc.mstrm_pubBuffer + strmSrc.mstrm_slLocation;
  SLONG slSizeSrc = strmSrc.GetStreamSize();
  // allocate buffer for compression
  SLONG slSizeDst = NeededDestinationSize(slSizeSrc);
  UBYTE *pubDst = (UBYTE*)AllocMemory(slSizeDst);
  // compress there
  BOOL bOk = Pack(pubSrc, slSizeSrc, pubDst, slSizeDst);
  // if failed
  if (!bOk) {
    // report error
    FreeMemory(pubDst);
    ThrowF_t(TRANS("Error while packing a stream."));
  }

  // write the header to destination
  strmDst<<slSizeSrc;
  strmDst<<slSizeDst;
  // write the compressed data to destination
  strmDst.Write_t(pubDst, slSizeDst);
  FreeMemory(pubDst);
}
예제 #20
0
void UnDiff_t(void)
{
  // start at beginning
  UBYTE *pubOld = _pubOld;
  UBYTE *pubNew = _pubNew;
  SLONG slSizeOldStream = 0;
  SLONG slSizeOutStream = 0;
  // get header with size of files
  if (*(SLONG*)pubNew!=DIFF) {
    ThrowF_t(TRANS("Not a DIFF stream!"));
  }
  pubNew+=sizeof(SLONG);
  slSizeOldStream = *(SLONG*)pubNew; pubNew+=sizeof(SLONG);
  slSizeOutStream = *(SLONG*)pubNew; pubNew+=sizeof(SLONG);
  ULONG ulCRC =  *(ULONG*)pubNew; pubNew+=sizeof(ULONG);

  CRC_Start(_ulCRC);

  if (slSizeOldStream!=_slSizeOld) {
    ThrowF_t(TRANS("Invalid DIFF stream!"));
  }
  // while not end of diff file
  while (pubNew<_pubNew+_slSizeNew) {
    // read block type
    UBYTE ubType = *(pubNew++);
    switch(ubType) {
    // if block type is 'copy from old file'
    case DIFF_OLD: {
      // get data offset and size
      SLONG slOffsetOld = *(SLONG*)pubNew;  pubNew+=sizeof(SLONG);
      SLONG slSizeOld = *(SLONG*)pubNew;    pubNew+=sizeof(SLONG);
      // copy it from there
      (*_pstrmOut).Write_t(_pubOld+slOffsetOld, slSizeOld);
      CRC_AddBlock(_ulCRC, _pubOld+slOffsetOld, slSizeOld);
                   } break;
    // if block type is 'copy from new file'
    case DIFF_NEW: {
      // get data size
      SLONG slSizeNew = *(SLONG*)pubNew;    pubNew+=sizeof(SLONG);
      // copy it from there
      (*_pstrmOut).Write_t(pubNew, slSizeNew);
      CRC_AddBlock(_ulCRC, pubNew, slSizeNew);
      pubNew+=slSizeNew;
                   } break;
    // if block type is 'xor between an old block and a new block'
    case DIFF_XOR: {
      // get data offset and sizes
      SLONG slOffsetOld = *(SLONG*)pubNew;  pubNew+=sizeof(SLONG);
      SLONG slSizeOld = *(SLONG*)pubNew;    pubNew+=sizeof(SLONG);
      SLONG slSizeNew = *(SLONG*)pubNew;    pubNew+=sizeof(SLONG);

      // xor it
      SLONG slSizeXor = Min(slSizeOld, slSizeNew);
      UBYTE *pub0 = _pubOld+slOffsetOld;
      UBYTE *pub1 = pubNew;

      for (INDEX i=0; i<slSizeXor; i++) {
        *(pub1++) ^= *(pub0++);
      }

      // copy the xor-ed data
      (*_pstrmOut).Write_t(pubNew, slSizeNew);
      CRC_AddBlock(_ulCRC, pubNew, slSizeNew);
      pubNew+=slSizeNew;
                   } break;
    default:
      ThrowF_t(TRANS("Invalid DIFF block type!"));
    }
  }

  CRC_Finish(_ulCRC);

//printf("CRC is (%lu), expected (%lu).\n", _ulCRC, ulCRC);

  if (_ulCRC!=ulCRC) {
    ThrowF_t(TRANS("CRC error in DIFF!"));
  }
}
예제 #21
0
void MakeDiff_t(void)
{
  // write header with size of files
  (*_pstrmOut).WriteID_t("DIFF");
  (*_pstrmOut)<<_slSizeOld<<_slSizeNew<<_ulCRC;

  // find first entities in blocks
  UBYTE *pubOldEnts = FindFirstEntity(_pubOld, _slSizeOld);
  UBYTE *pubNewEnts = FindFirstEntity(_pubNew, _slSizeNew);
  if (pubOldEnts==NULL || pubNewEnts==NULL) {
    ThrowF_t(TRANS("Invalid stream for Diff!"));
  }

  // make arrays of entity offsets
  UBYTE *pubEntEndOld;
  MakeInfos(_aebiOld, _pubOld, _slSizeOld, pubOldEnts, pubEntEndOld);
  UBYTE *pubEntEndNew;
  MakeInfos(_aebiNew, _pubNew, _slSizeNew, pubNewEnts, pubEntEndNew);

  // emit chunk before entities by xor
  EmitXor_t(0, pubOldEnts-_pubOld, 0, pubNewEnts-_pubNew);

  // for each entity in new
  for(INDEX ieibNew = 0; ieibNew<_aebiNew.Count(); ieibNew++) {
    EntityBlockInfo &ebiNew = _aebiNew[ieibNew];
    // find same in old file
    INDEX ieibOld = -1;
    for(INDEX i=0; i<_aebiOld.Count(); i++) {
      if (_aebiOld[i].ebi_ulID==ebiNew.ebi_ulID) {
        ieibOld = i;
        break;
      }
    }
    BOOL bDone = FALSE;

    // if found
    if (ieibOld>=0) {
      EntityBlockInfo &ebiOld = _aebiOld[ieibOld];

      // if same
      if ( ebiOld.ebi_slSize==ebiNew.ebi_slSize) {
        if (memcmp(_pubOld+ebiOld.ebi_slOffset, 
        _pubNew+ebiNew.ebi_slOffset, ebiNew.ebi_slSize)==0) {
          //CPrintF("Same blocks\n");
          // emit copy from old
          EmitOld_t(ebiOld.ebi_slOffset, ebiOld.ebi_slSize);
          bDone = TRUE;
        } else {
          //CPrintF("Different blocks\n");
        }
      } else {
        //CPrintF("Different sizes\n");
      }

      if (!bDone) {
        // emit xor
        EmitXor_t(
          ebiOld.ebi_slOffset, ebiOld.ebi_slSize,
          ebiNew.ebi_slOffset, ebiNew.ebi_slSize);
        bDone = TRUE;
      }
    } else {
      //CPrintF("Not found\n");
    }
    if (!bDone) 
    {
      // emit from new
      EmitNew_t(ebiNew.ebi_slOffset, ebiNew.ebi_slSize);
      bDone = TRUE;
    }
  }

  // emit chunk after entities by xor
  EmitXor_t(
    pubEntEndOld-_pubOld, _pubOld+_slSizeOld-pubEntEndOld,
    pubEntEndNew-_pubNew, _pubNew+_slSizeNew-pubEntEndNew);
}
CDlgCreateNormalTexture::CDlgCreateNormalTexture( CTFileName fnInputFile, CWnd* pParent /*=NULL*/)
	: CDialog(CDlgCreateNormalTexture::IDD, pParent)
{
  //{{AFX_DATA_INIT(CDlgCreateNormalTexture)
	m_strCreatedTextureName = _T("");
	m_strSizeInPixels = _T("");
	m_bCreateMipmaps = FALSE;
	//}}AFX_DATA_INIT

  m_bSourcePictureValid = FALSE;
  m_bPreviewWindowsCreated = FALSE;
  m_ptdCreated = NULL;
  
  CTFileName fnTexFileName = fnInputFile.FileDir() + fnInputFile.FileName() + ".tex";
  // remember source and created texture name
  m_fnSourceFileName  = fnInputFile;
  m_fnCreatedFileName = fnTexFileName;
  // set initial values for create mip maps flag and size for create texture dialog
  m_bCreateMipmaps  = AfxGetApp()->GetProfileInt(L"Creating textures", L"Create mipmaps", 1);
  m_mexCreatedWidth = AfxGetApp()->GetProfileInt(L"Creating textures", L"Mex width",  -1);
  _bWasForced32     = FALSE;

  try
  {
    // if can't get picture file information
    CImageInfo iiImageInfo;
    if (iiImageInfo.GetGfxFileInfo_t( m_fnSourceFileName)==UNSUPPORTED_FILE)
    {
      // throw error
      ThrowF_t("File '%s' has unsupported file format", 
        (CTString&)(_fnmApplicationPath+m_fnSourceFileName));
    }
    // get dimensions
    m_pixSourceWidth  = iiImageInfo.ii_Width;
    m_pixSourceHeight = iiImageInfo.ii_Height;
    // test if dimensions are at power of 2
    if( (((1<<((int)Log2(m_pixSourceWidth)))  != m_pixSourceWidth)) ||
        (((1<<((int)Log2(m_pixSourceHeight))) != m_pixSourceHeight))) {
      ThrowF_t( "Picture %s has wrong dimensions (%d,%d).\n"
                "Both width and height must be at power of 2.",
                (CTString&)m_fnSourceFileName, m_pixSourceWidth, m_pixSourceHeight);
    }
  }
  catch(char *err_str)
  {
    AfxMessageBox( CString(err_str));
    return;
  }
  m_bSourcePictureValid = TRUE;

  // try to
  try
  { // obtain texture with the same name (if already exists)
    CTextureData *pTD = _pTextureStock->Obtain_t( fnTexFileName);
    pTD->Reload();
    // now pick up initial number of mip levels
    m_bCreateMipmaps = pTD->td_ctFineMipLevels>1;
    // remember existing texture's width in mexels
    m_mexCreatedWidth = pTD->GetWidth();
    // remember existing texture's flags
    _bWasForced32 = pTD->td_ulFlags & TEX_32BIT;
    // release texture
    _pTextureStock->Release( pTD);
  }
  // if texture can't be obtained
  catch( char *err_str)
  { // never mind
    (void) err_str;
  }

  m_wndViewCreatedTexture.m_bForce32 = FALSE;
  if( _bWasForced32) m_wndViewCreatedTexture.m_bForce32 = TRUE;
  RefreshCreatedTexture();
  // set created texture name
  m_strCreatedTextureName = fnTexFileName;
  // prepare string telling size of source picture
  char strSize[ 64];
  sprintf( strSize, "%d x %d", m_pixSourceWidth, m_pixSourceHeight);
  m_strSizeInPixels = strSize;
} 
예제 #23
0
void CObject3D::LoadAny3DFormat_t(
  const CTFileName &fnmFileName,
  const FLOATmatrix3D &mTransform,
  enum LoadType ltLoadType/*= LT_NORMAL*/)
{
#if USE_E3D
  BOOL bWasOn = _bBatchLoading;
  try {
    if (!_bBatchLoading) {
      BatchLoading_t(TRUE);
    }
    // call file load with file's full path name
    CTString strFile = _fnmApplicationPath+fnmFileName;
    char acFile[MAX_PATH];
    wsprintf(acFile,"%s",strFile);
    e3_LoadFile(_hwnd, acFile);
    _pe3Scene=e3_GetScene(_hwnd);    
    // if scene is successefuly loaded
    if(_pe3Scene != NULL)
    {
      _pe3Object = _pe3Scene->GetObject3d( 0);
      // use different methods to convert into Object3D
      switch( ltLoadType)
      {
      case LT_NORMAL:
        FillConversionArrays_t(mTransform);
        ConvertArraysToO3D();
        break;
      case LT_OPENED:
        FillConversionArrays_t(mTransform);
        RemapVertices(TRUE);
        ConvertArraysToO3D();
        break;
      case LT_UNWRAPPED:
        FLOATmatrix3D mOne;
        mOne.Diagonal(1.0f);
        FillConversionArrays_t(mOne);
        if( avTextureVertices.Count() == 0)
        {
    		  ThrowF_t("Unable to import mapping from 3D object because it doesn't contain mapping coordinates.");
        }

        RemapVertices(FALSE);
        ConvertArraysToO3D();
        break;
      }
      ClearConversionArrays();
    }
    else 
    {
		  ThrowF_t("Unable to load 3D object: %s", (const char *)fnmFileName);
    }
  
    if (!bWasOn) {
      BatchLoading_t(FALSE);
    }
  } catch (char *) {
    if (!bWasOn) {
      BatchLoading_t(FALSE);
    }
    throw;
  }
#endif
}
예제 #24
0
// decoder that streams from file
CSoundDecoder::CSoundDecoder(const CTFileName &fnm, UBYTE *pubHeader/*=NULL*/, SLONG slHeaderSize/*=0*/)
{
  sdc_pogg = NULL;
  sdc_pmpeg = NULL;

  CTFileName fnmExpanded;
  INDEX iFileType = ExpandFilePath(EFP_READ, fnm, fnmExpanded);

  // if ogg
  if (fnmExpanded.FileExt()==".ogg") {
    if (!_bOVEnabled) {
      return;
    }
    sdc_pogg = new CDecodeData_OGG;
    sdc_pogg->ogg_fFile = NULL;
    sdc_pogg->ogg_vfVorbisFile = NULL;
    sdc_pogg->ogg_slOffset = 0;
    sdc_pogg->ogg_slSize = 0;
    INDEX iZipHandle = 0;

    try {
      // if in zip
      if (iFileType==EFP_BASEZIP || iFileType==EFP_MODZIP) {
        // open it
        iZipHandle = UNZIPOpen_t(fnmExpanded);

        CTFileName fnmZip;
        SLONG slOffset;
        SLONG slSizeCompressed;
        SLONG slSizeUncompressed;
        BOOL bCompressed;
        UNZIPGetFileInfo(iZipHandle, fnmZip, slOffset, slSizeCompressed, slSizeUncompressed, bCompressed);

        // if compressed
        if (bCompressed) {
          ThrowF_t(TRANS("encoded audio in archives must not be compressed!\n"));
        }
        // open ogg file
        sdc_pogg->ogg_fFile = fopen(fnmZip, "rb");
        // if error
        if (sdc_pogg->ogg_fFile==0) {
          ThrowF_t(TRANS("cannot open archive '%s'"), (const char*)fnmZip);
        }
        // remember offset and size
        sdc_pogg->ogg_slOffset = slOffset;
        sdc_pogg->ogg_slSize = slSizeUncompressed;
        fseek(sdc_pogg->ogg_fFile, slOffset, SEEK_SET);

      // if not in zip
      } else if (iFileType==EFP_FILE) {
        // open ogg file
        sdc_pogg->ogg_fFile = fopen(fnmExpanded, "rb");
        // if error
        if (sdc_pogg->ogg_fFile==0) {
          ThrowF_t(TRANS("cannot open encoded audio file"));
        }
        // remember offset and size
        sdc_pogg->ogg_slOffset = 0;

        fseek(sdc_pogg->ogg_fFile, 0, SEEK_END);
        sdc_pogg->ogg_slSize = ftell(sdc_pogg->ogg_fFile);
        fseek(sdc_pogg->ogg_fFile, 0, SEEK_SET);
      // if not found
      } else {
        ThrowF_t(TRANS("file not found"));
      }

      // initialize decoder
      sdc_pogg->ogg_vfVorbisFile = new OggVorbis_File;
      int iRes = pov_open_callbacks(sdc_pogg, sdc_pogg->ogg_vfVorbisFile, NULL, 0, ovcCallbacks);

      // if error
      if (iRes!=0) {
        ThrowF_t(TRANS("cannot open ogg decoder"));
      }

      // get info on the file
      vorbis_info *pvi = pov_info(sdc_pogg->ogg_vfVorbisFile, -1);

      // remember it's format
      WAVEFORMATEX form;
      form.wFormatTag=WAVE_FORMAT_PCM;
      form.nChannels=pvi->channels;
      form.nSamplesPerSec=pvi->rate;
      form.wBitsPerSample=16;
      form.nBlockAlign=form.nChannels*form.wBitsPerSample/8;
      form.nAvgBytesPerSec=form.nSamplesPerSec*form.nBlockAlign;
      form.cbSize=0;

      // check for stereo
      if (pvi->channels!=2) {
        ThrowF_t(TRANS("not stereo"));
      }
    
      sdc_pogg->ogg_wfeFormat = form;

    } catch (char*strError) {
      CPrintF(TRANS("Cannot open encoded audio '%s' for streaming: %s\n"), (const char*)fnm, (const char*)strError);
      if (sdc_pogg->ogg_vfVorbisFile!=NULL) {
        delete sdc_pogg->ogg_vfVorbisFile;
        sdc_pogg->ogg_vfVorbisFile = NULL;
      }
      if (sdc_pogg->ogg_fFile!=NULL) {
        fclose(sdc_pogg->ogg_fFile);
        sdc_pogg->ogg_fFile = NULL;
      }
      if (iZipHandle!=0) {
        UNZIPClose(iZipHandle);
      }
      Clear();
      return;
    }
    if (iZipHandle!=0) {
      UNZIPClose(iZipHandle);
    }

  // if mp3
  } else if (fnmExpanded.FileExt()==".mp3") {

    if (!_bAMP11Enabled) {
      return;
    }

    sdc_pmpeg = new CDecodeData_MPEG;
    sdc_pmpeg->mpeg_hMainFile = 0;
    sdc_pmpeg->mpeg_hFile = 0;
    sdc_pmpeg->mpeg_hDecoder = 0;
    INDEX iZipHandle = 0;

    try {
      // if in zip
      if (iFileType==EFP_BASEZIP || iFileType==EFP_MODZIP) {
        // open it
        iZipHandle = UNZIPOpen_t(fnmExpanded);

        CTFileName fnmZip;
        SLONG slOffset;
        SLONG slSizeCompressed;
        SLONG slSizeUncompressed;
        BOOL bCompressed;
        UNZIPGetFileInfo(iZipHandle, fnmZip, slOffset, slSizeCompressed, slSizeUncompressed, bCompressed);

        // if compressed
        if (bCompressed) {
          ThrowF_t(TRANS("encoded audio in archives must not be compressed!\n"));
        }
        // open the zip file
        sdc_pmpeg->mpeg_hMainFile = palOpenInputFile(fnmZip);
        // if error
        if (sdc_pmpeg->mpeg_hMainFile==0) {
          ThrowF_t(TRANS("cannot open archive '%s'"), (const char*)fnmZip);
        }
        // open the subfile
        sdc_pmpeg->mpeg_hFile = palOpenSubFile(sdc_pmpeg->mpeg_hMainFile, slOffset, slSizeUncompressed);
        // if error
        if (sdc_pmpeg->mpeg_hFile==0) {
          ThrowF_t(TRANS("cannot open encoded audio file"));
        }

      // if not in zip
      } else if (iFileType==EFP_FILE) {
        // open mpx file
        sdc_pmpeg->mpeg_hFile = palOpenInputFile(fnmExpanded);
        // if error
        if (sdc_pmpeg->mpeg_hFile==0) {
          ThrowF_t(TRANS("cannot open mpx file"));
        }
      // if not found
      } else {
        ThrowF_t(TRANS("file not found"));
      }

      // get info on the file
      int layer, ver, freq, stereo, rate;
      if (!palGetMPXHeader(sdc_pmpeg->mpeg_hFile, &layer, &ver, &freq, &stereo, &rate)) {
        ThrowF_t(TRANS("not a valid mpeg audio file."));
      }

      // remember it's format
      WAVEFORMATEX form;
      form.wFormatTag=WAVE_FORMAT_PCM;
      form.nChannels=stereo?2:1;
      form.nSamplesPerSec=freq;
      form.wBitsPerSample=16;
      form.nBlockAlign=form.nChannels*form.wBitsPerSample/8;
      form.nAvgBytesPerSec=form.nSamplesPerSec*form.nBlockAlign;
      form.cbSize=0;

      // check for stereo
      if (!stereo) {
        ThrowF_t(TRANS("not stereo"));
      }
    
      sdc_pmpeg->mpeg_wfeFormat = form;

      // initialize decoder
      sdc_pmpeg->mpeg_hDecoder = palOpenDecoder(sdc_pmpeg->mpeg_hFile);

      // if error
      if (sdc_pmpeg->mpeg_hDecoder==0) {
        ThrowF_t(TRANS("cannot open mpx decoder"));
      }
    } catch (char*strError) {
      CPrintF(TRANS("Cannot open mpx '%s' for streaming: %s\n"), (const char*)fnm, (const char*)strError);
      if (iZipHandle!=0) {
        UNZIPClose(iZipHandle);
      }
      Clear();
      return;
    }

    if (iZipHandle!=0) {
      UNZIPClose(iZipHandle);
    }
    sdc_pmpeg->mpeg_fSecondsLen = palDecGetLen(sdc_pmpeg->mpeg_hDecoder);
  }
}
/*
 *  Open client remote
 */
void CCommunicationInterface::Client_OpenNet_t(ULONG ulServerAddress)
{
  CTSingleLock slComm(&cm_csComm, TRUE);
	CPacket* ppaInfoPacket;
	CPacket* ppaReadPacket;
	UBYTE ubDummy=65;
	UBYTE ubReliable;

  // check for reconnection
  static ULONG ulLastServerAddress = (ULONG) -1;
  BOOL bReconnecting = ulServerAddress == ulLastServerAddress;
  ulLastServerAddress = ulServerAddress;

  const INDEX iRefresh = 100; // (in miliseconds)
  // determine connection timeout
  INDEX ctRetries = bReconnecting?(180*1000/iRefresh):3;

  // start waiting for server's response
  if (ctRetries>1) {
    SetProgressDescription(TRANS("waiting for server"));
    CallProgressHook_t(0.0f);
  }

	

	// form the connection request packet
	ppaInfoPacket = new CPacket;
	ubReliable = UDP_PACKET_RELIABLE | UDP_PACKET_RELIABLE_HEAD | UDP_PACKET_RELIABLE_TAIL | UDP_PACKET_CONNECT_REQUEST;
	ppaInfoPacket->pa_adrAddress.adr_ulAddress = ulServerAddress;
	ppaInfoPacket->pa_adrAddress.adr_uwPort = net_iPort;
	ppaInfoPacket->pa_ubRetryNumber = 0;
	ppaInfoPacket->WriteToPacket(&ubDummy,1,ubReliable,cm_ciLocalClient.ci_ulSequence++,SLASHSLASH,1);

	cm_ciLocalClient.ci_pbOutputBuffer.AppendPacket(*ppaInfoPacket,TRUE);

	// set client destination address to server address
	cm_ciLocalClient.ci_adrAddress.adr_ulAddress = ulServerAddress;
	cm_ciLocalClient.ci_adrAddress.adr_uwPort = net_iPort;
	
  // for each retry
  for(INDEX iRetry=0; iRetry<ctRetries; iRetry++) {
		// send/receive and juggle the buffers
		if (Client_Update() == FALSE) {
			break;
		}

		// if there is something in the input buffer
		if (cm_ciLocalClient.ci_pbReliableInputBuffer.pb_ulNumOfPackets > 0) {
			ppaReadPacket = cm_ciLocalClient.ci_pbReliableInputBuffer.GetFirstPacket();
			// and it is a connection confirmation
			if (ppaReadPacket->pa_ubReliable &&  UDP_PACKET_CONNECT_RESPONSE) {
				// the client has succedeed to connect, so read the uwID from the packet
				cm_ciLocalClient.ci_adrAddress.adr_ulAddress = ulServerAddress;
				cm_ciLocalClient.ci_adrAddress.adr_uwPort = net_iPort;
				cm_ciLocalClient.ci_adrAddress.adr_uwID = *((UWORD*) (ppaReadPacket->pa_pubPacketData + MAX_HEADER_SIZE));
				cm_ciLocalClient.ci_bUsed = TRUE;
				cm_ciLocalClient.ci_bClientLocal = FALSE;
				cm_ciLocalClient.ci_pciOther = NULL;

				cm_ciLocalClient.ci_pbReliableInputBuffer.RemoveConnectResponsePackets();

				delete ppaReadPacket;

				// finish waiting
				CallProgressHook_t(1.0f);		    
				return;
			}
		}

    _pTimer->Sleep(iRefresh);
    CallProgressHook_t(FLOAT(iRetry%10)/10);
	}
	
	cci_bBound = FALSE;
	ThrowF_t(TRANS("Client: Timeout receiving UDP port"));
};
예제 #26
0
static void FailFunction_t(const char *strName) {
  ThrowF_t(TRANS("Required function %s not found."), strName);
}
예제 #27
0
/*
 * Read current world state from stream.
 */
void CWorld::ReadState_t( CTStream *istr) // throw char *
{
  _pfWorldEditingProfile.StartTimer(CWorldEditingProfile::PTI_READSTATE);
  // must be in 24bit mode when managing entities
  CSetFPUPrecision FPUPrecision(FPT_24BIT);

  CTmpPrecachingNow tpn;
  _bReadEntitiesByID = FALSE;

  SetProgressDescription(TRANS("loading models"));
  CallProgressHook_t(0.0f);
  wo_slStateDictionaryOffset = istr->DictionaryReadBegin_t();
  istr->DictionaryPreload_t();
  CallProgressHook_t(1.0f);
  istr->ExpectID_t("WSTA"); // world state

  // read the version number
  INDEX iSavedVersion;
  (*istr)>>iSavedVersion;
  // if the version number is the newest
  if(iSavedVersion==WORLDSTATEVERSION_CURRENT) {
    // read current version
    ReadState_new_t(istr);

  // if the version number is not the newest
  } else {

    // if the version can be converted
    if(iSavedVersion==WORLDSTATEVERSION_CURRENT-1) {
      // show warning
//      WarningMessage(
//        "World state version was %d (old).\n"
//        "Auto-converting to version %d.",
//        iSavedVersion, WORLDSTATEVERSION_CURRENT);
      // read previous version
      ReadState_old_t(istr);
    // if the version can be converted
    } else if(iSavedVersion==WORLDSTATEVERSION_CURRENT-2) {
      // show warning
      WarningMessage(
        TRANS("World state version was %d (very old).\n"
        "Auto-converting to version %d."),
        iSavedVersion, WORLDSTATEVERSION_CURRENT);
      // read previous version
      ReadState_veryold_t(istr);
    } else {
      // report error
      ThrowF_t(
        TRANS("World state version is %d (unsupported).\n"
        "Current supported version is %d."),
        iSavedVersion, WORLDSTATEVERSION_CURRENT);
    }
  }
  istr->DictionaryReadEnd_t();

  SetProgressDescription(TRANS("precaching"));
  CallProgressHook_t(0.0f);
  // precache data needed by entities
  if( gam_iPrecachePolicy==PRECACHE_SMART) {
    PrecacheEntities_t();
  }
  CallProgressHook_t(1.0f);

  _pfWorldEditingProfile.StopTimer(CWorldEditingProfile::PTI_READSTATE);
}