Beispiel #1
0
void MapBackground::SaveMapTileImage(MapTile* pTile, void* gResult, uint32 gResultLen, bool isJpg)
{
	char szImage[200], szPath[200];
	strcpy(szImage, pTile->szImageUrl);

	char* szName = strrchr(szImage, '/')+1;
	strchr(szName, '.')[0] = 0;

	strcpy(szPath, "tiles/");
	strcat(szPath, szName);

	if (isJpg)
	{
		strcat(szPath, ".jpg");
	}
	else
	{
		strcat(szPath, ".png");
	}

	s3eFile* pFile = s3eFileOpen(szPath, "w");

	if (pFile)
	{
		uint32 x = s3eFileWrite(gResult, 1, gResultLen, pFile);
		s3eFileFlush(pFile);
		s3eFileClose(pFile);
	}
}
Beispiel #2
0
void MapBackground::CreateMapTileImage(MapTile* pMapTile, void* gResult, uint32 gResultLen, bool isJpg)
{
	if (!IsTileVisible(pMapTile))
	{
		return;
	}
	CIwImage image;
	if (!isJpg)
	{
		//pMapTile->pTexture = g_pNotFoundTexture;
		s3eFile* tempfile = s3eFileOpenFromMemory((void*)gResult, gResultLen);
		image.ReadFile(tempfile);

		//image.LoadFromFile("tiles/r0302322130033033130.png");

		if (image.GetWidth())
		{
			pMapTile->pTexture = new CIwTexture;
			pMapTile->pTexture->CopyFromImage(&image);
			pMapTile->pTexture->Upload();
		}

		s3eFileClose(tempfile);
	}
	else
	{
		JPEGImage(gResult, gResultLen, image);
		pMapTile->pTexture = new CIwTexture;
		pMapTile->pTexture->CopyFromImage(&image);
		pMapTile->pTexture->Upload();
	}
}
void RegisterCustomClasses()
{
    // Read file list custom class mappings to known base classes
    s3eFile* cm = s3eFileOpen("_viewertemp/classmap.txt", "rb");
    if (cm)
    {
        // Read lines
        char buffer[0x200];
        int index = 0;
        while (s3eFileReadString(buffer, sizeof(buffer), cm))
        {
            IwTrace(UI, ("Registering custom class factory"));

            int num = sizeof(s_CustomClassRegister) / sizeof(s_CustomClassRegister[0]);
            if (index >= num)
            {
                IwAssertMsg(UI, false, ("No more custom class factories available"));
                break;
            }

            // Mapping of form "class base"
            char className[0x200];
            char baseName[0x200];
            if (sscanf(buffer, "%s %s", className, baseName) == 2)
            {
                // Register class factory
                s_CustomClassRegister[index](className, baseName);

                ++index;
            }
        }

        s3eFileClose(cm);
    }
}
unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
{
	IW_CALLSTACK("CCFileUtils::getFileData");

	s3eFile* pFile = s3eFileOpen(pszFileName, pszMode);
	
    if (! pFile && getIsPopupNotify())
    {    
        IwAssertMsg(GAME, pFile, ("Open file %s Failed. s3eFileError Code : %i", pszFileName, s3eFileGetError()));
    }
    if (! pFile) 
    {
        *pSize = 0;
        return 0;
    }
	int32 fileSize = s3eFileGetSize(pFile);
	*pSize=fileSize;

	static int32* pDataToBeReadBinary;

	pDataToBeReadBinary = (int32*)s3eMallocBase(fileSize);
	memset(pDataToBeReadBinary, 0, fileSize);
	s3eFileRead(pDataToBeReadBinary, fileSize, 1, pFile);
	s3eFileClose(pFile);
	
	return (unsigned char*)pDataToBeReadBinary;
}
Beispiel #5
0
bool CLevel::OpenXmlFile( const char * path, TiXmlDocument * doc )
{
	if ( doc == NULL )
	{
		return false;
	}
	s3eFile * file = s3eFileOpen(path, "r");
	if ( file != NULL )
	{
		s3eFileSeek(file, 0, S3E_FILESEEK_END);
		long len = s3eFileTell( file );
		s3eFileSeek(file, 0, S3E_FILESEEK_SET);

		char * buff = new char[len];
		s3eFileRead(buff, sizeof(char), len, file);

		doc->Parse(buff);

		SAFE_DELETE_ARRAY( buff );
	}
	else
	{
		IwAssertMsg(GAME, false, ("can't open file '%s'", path));
		return false;
	}
	s3eFileClose(file);

	return true;
}
bool CCImage::_initWithPngData(void * pData, int nDatalen)
{
	IW_CALLSTACK("CCImage::_initWithPngData");
	
    bool bRet = false;
	
	s3eFile* pFile = s3eFileOpenFromMemory(pData, nDatalen);
	
	IwAssert(GAME, pFile);
	
	CIwImage    *image		= NULL;
	image = new CIwImage;
	
	image->ReadFile( pFile);
	
    s3eFileClose(pFile);
	
	// init image info
	m_bPreMulti	= true;
	m_bHasAlpha = image->HasAlpha();
	
	unsigned int bytesPerComponent = 3;
	if (m_bHasAlpha)
	{
		bytesPerComponent = 4;
	} 
	m_nHeight = (unsigned int)image->GetHeight();
	m_nWidth = (unsigned int)image->GetWidth();
	m_nBitsPerComponent = (unsigned int)image->GetBitDepth()/bytesPerComponent;
	
	tImageSource imageSource;
	
	imageSource.data    = (unsigned char*)pData;
	imageSource.size    = nDatalen;
	imageSource.offset  = 0;
	
	m_pData = new unsigned char[m_nHeight * m_nWidth * bytesPerComponent];
	
	unsigned int bytesPerRow = m_nWidth * bytesPerComponent;

	if(m_bHasAlpha)
	{
		unsigned char *src = NULL;
		src = (unsigned char *)image->GetTexels();
		
		unsigned char *tmp = (unsigned char *) m_pData;
		
		for(unsigned int i = 0; i < m_nHeight*bytesPerRow; i += bytesPerComponent)
		{
			*(tmp + i + 0)	=  (*(src + i + 0) * *(src + i + 3) + 1) >> 8;
			*(tmp + i + 1)	=  (*(src + i + 1) * *(src + i + 3) + 1) >> 8;					
			*(tmp + i + 2)	=  (*(src + i + 2) * *(src + i + 3) + 1) >> 8;
			*(tmp + i + 3)	=   *(src + i + 3);
		}
		
	}
	else
	{
		for (int j = 0; j < (m_nHeight); ++j)
Beispiel #7
0
void CIwGameFile::Close()
{
	if (File != NULL)
	{
		s3eFileClose(File);
		File = NULL;
	}
}
Beispiel #8
0
	bool Texture2DLoader::loadFromMemory(IResource * outResource, uint64 size, const void* data)
	{
		Texture2D * texPtr = (Texture2D*)outResource;
		assert(texPtr != nullptr);

		CIwImage image;
		s3eFile * f = s3eFileOpenFromMemory((void*)data, (size_t)size);
		image.ReadFile(f);
		s3eFileClose(f);

		return texPtr->uploadToGPU(image);
	}
Beispiel #9
0
    void SimpleAudioEngine::preloadBackgroundMusic(const char* pszFilePath)
	{
		s3eFile *fileHandle = s3eFileOpen(pszFilePath, "rb");
		
		IwAssertMsg(GAME, fileHandle, ("Open file %s Failed. s3eFileError Code : %i", pszFilePath, s3eFileGetError()));
		
		g_AudioFileSize = s3eFileGetSize(fileHandle);
		g_AudioBuffer = (int16*)malloc(g_AudioFileSize);
		memset(g_AudioBuffer, 0, g_AudioFileSize);
		s3eFileRead(g_AudioBuffer, g_AudioFileSize, 1, fileHandle);
		s3eFileClose(fileHandle);
	}
Beispiel #10
0
void Map::ReadJsonFile(char * filename)
{
	cJSON *root;
	char * jsonContent;
	s3eFile* fileHandler;
	fileHandler=s3eFileOpen(filename, "rb");
	if (fileHandler != NULL)
    {
        // Allocate buffer to be filled with the files contents
        int32 fileSize = s3eFileGetSize(fileHandler);
        jsonContent = (char*)s3eMallocBase(fileSize+1);

        // Read data from file
        if (s3eFileRead(&jsonContent[0], fileSize+1, 1, fileHandler) != 1)
        {
            // An kError has occurred, retrieve information for display
			std::cout<<s3eFileGetErrorString()<<std::endl;
        }
        else
        {
            // Data reading has been successful
            jsonContent[fileSize] = '\0';
        }
    }
    else
    {
        // Something went wrong during opening of the file retrieve error for display
		std::cout<<s3eFileGetErrorString()<<std::endl;
    }
	if (fileHandler)
		s3eFileClose(fileHandler);
	root = cJSON_Parse(jsonContent);
	s3eFileFlush(fileHandler);

	_height=cJSON_GetObjectItem(root,"height")->valueint;
	cJSON *layers = cJSON_GetObjectItem(root,"layers");
	_tileHeight=cJSON_GetObjectItem(root,"tileheight")->valueint;
	_tileWidth=cJSON_GetObjectItem(root,"tilewidth")->valueint;
	_width=cJSON_GetObjectItem(root,"width")->valueint;
	_layer_base->Init(cJSON_GetArrayItem(layers,0));
	_layer_middle->Init(cJSON_GetArrayItem(layers,1));
	_layer_maze->Init(cJSON_GetArrayItem(layers,2));
	cJSON *tilesets = cJSON_GetObjectItem(root,"tilesets");
	_tileset_map->Init(cJSON_GetArrayItem(tilesets,0));
	_tileset_maze->Init(cJSON_GetArrayItem(tilesets,1));

	

	_total=_height*_width;
	_size=CIwSVec2(_width*_tileWidth,_height*_tileHeight);

}
    void SimpleAudioEngine::preloadBackgroundMusic(const char* pszFilePath)
	{
		// Changing file path to full path
		std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pszFilePath);
		s3eFile *fileHandle = s3eFileOpen(fullPath.c_str(), "rb");
		
		IwAssertMsg(GAME, fileHandle, ("Open file %s Failed. s3eFileError Code : %i", fullPath.c_str(), s3eFileGetError()));
		
		g_AudioFileSize = s3eFileGetSize(fileHandle);
		g_AudioBuffer = (int16*)malloc(g_AudioFileSize);
		memset(g_AudioBuffer, 0, g_AudioFileSize);
		s3eFileRead(g_AudioBuffer, g_AudioFileSize, 1, fileHandle);
		s3eFileClose(fileHandle);
	}
Beispiel #12
0
CIwMapGame::~CIwMapGame()
{
	std::list<GameStatePair*>::iterator iter = g_gameStates.begin();

	while (iter != g_gameStates.end())
	{
		GameStatePair* pPair = *iter;
		delete pPair->pGameState;
		delete pPair;
		iter++;
	}
	s3eFileFlush(g_pFile);
	s3eFileClose(g_pFile);
}
Sounds::Sound* Sounds::loadSound(const char* filename) {
	Sounds::Sound* sound = new Sounds::Sound();
	s3eFile *fileHandle = s3eFileOpen(filename, "rb");
	if (fileHandle) {
	  strcpy(sound->fileName, filename);
	  sound->fileSize = s3eFileGetSize(fileHandle);
	  sound->buffer = (int16*)s3eMallocBase(sound->fileSize);
	  memset(sound->buffer, 0, sound->fileSize);
	  s3eFileRead(sound->buffer, sound->fileSize, 1, fileHandle);
	  s3eFileClose(fileHandle);
	} else
	  fprintf(stderr, "Error loading sound file: %s.\n", filename);
	return sound;
}
Beispiel #14
0
Buffer loadFile(const char * fname)
{
    s3eFile * file = s3eFileOpen(fname, "rb");
    if(file)
    {
        size_t size = s3eFileGetSize(file);
        Buffer result(size);
        s3eFileRead(result.data(), 1, size, file);
        s3eFileClose(file);
        return result;
    } else {
        IwAssertMsg(AUDIO_UTILS, false, ("failed to open: %s", fname));
        return Buffer();
    }
}
Beispiel #15
0
	void SimpleAudioEngine::preloadEffect(const char* pszFilePath)
	{
		SoundFxMap::iterator it = g_pSoundFxMap->find(pszFilePath) ;
		if( it==g_pSoundFxMap->end() ) {
			s3eFile *fileHandle = s3eFileOpen(pszFilePath, "rb");
		
			IwAssertMsg(GAME, fileHandle, ("Open file %s Failed. s3eFileError Code : %i", pszFilePath, s3eFileGetError()));
		
			int32 fileSize = s3eFileGetSize(fileHandle);
			int16* buff = (int16*)malloc(fileSize);

			(*g_pSoundFxMap)[pszFilePath] = SoundFx(buff,fileSize) ;
			memset(buff, 0, fileSize);
			s3eFileRead(buff, fileSize, 1, fileHandle);
			s3eFileClose(fileHandle);
		}
	}
bool CCSAXParser::parse(const char *pszFile)
{
	bool bRet = false;
	char* buf = NULL;
	s3eFile* file = NULL;
	
	do
	{
		file = s3eFileOpen(pszFile, "r");
		
		if (!file)
		{
			IwAssertMsg(GAME, file, ("Open file %s Failed. s3eFileError Code : %i", pszFile, s3eFileGetError()));
			break;
		}
		
		s3eFileSeek(file, 0, S3E_FILESEEK_END);
		int	size = s3eFileTell(file);
		s3eFileSeek(file, 0,  S3E_FILESEEK_SET);
		buf = new char[size];
		int done =0;
		int len = (int)s3eFileRead(buf, 1, size, file);
		if (XML_Parse(s_pParser, buf, len, 1) == XML_STATUS_ERROR)
		{
			CCLog("GAME: cocos2d: plist err: %s at line %d", XML_ErrorString(XML_GetErrorCode(s_pParser)), XML_GetCurrentLineNumber(s_pParser));
			break;
		}
		
		bRet = true;
		
	} while(0);
	
	// cleanup
	if (file)
	{
		s3eFileClose(file);
	}
	if (buf)
	{
		delete []buf;
	}
	
	return bRet;

}
Beispiel #17
0
CIwMaterial* ResourceManager::load(const char* name, int* w, int* h) {
	int width = 0, height = 0;
	char res[MAX_RES_NAME] = {0};
	sprintf(res, "images/%s/%s", desktop.getDevPath(), name);
	IIter p = imgs->find(res);
	if (p != imgs->end()) {
		if (w != NULL) {
			*w = p->second.width;
		}
		if (h != NULL) {
			*h = p->second.height;
		}
		return p->second.mat;
	}
	CIwTexture* texture = new CIwTexture;
    CIwImage image;
    s3eFile* pFile = s3eFileOpen(res, "rb");
    if (pFile) {
        image.ReadFile(pFile);
		width = image.GetWidth();
		height = image.GetHeight();
        s3eFileClose(pFile);
        texture->CopyFromImage(&image);
        texture->Upload();
    } else {
		delete texture;
		texture = NULL;
	}
	CIwMaterial* mat = new CIwMaterial;
	mat->SetTexture(texture);
	SImg s;
	s.texture = texture;
	s.mat = mat;
	s.width = width;
	s.height = height;
	imgs->insert(IPair(string(res), s));
	if (w != NULL) {
		*w = width;
	}
	if (h != NULL) {
		*h = height;
	}
	return mat;
}
	void SimpleAudioEngine::preloadEffect(const char* pszFilePath)
	{
		// Changing file path to full path
		std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(pszFilePath);
		SoundFxMap::iterator it = g_pSoundFxMap->find(fullPath) ;
		if( it==g_pSoundFxMap->end() ) {
			s3eFile *fileHandle = s3eFileOpen(fullPath.c_str(), "rb");
		
			IwAssertMsg(GAME, fileHandle, ("Open file %s Failed. s3eFileError Code : %i", fullPath.c_str(), s3eFileGetError()));
		
			int32 fileSize = s3eFileGetSize(fileHandle);
			int16* buff = (int16*)malloc(fileSize);

			(*g_pSoundFxMap)[fullPath] = SoundFx(buff,fileSize) ;
			memset(buff, 0, fileSize);
			s3eFileRead(buff, fileSize, 1, fileHandle);
			s3eFileClose(fileHandle);
		}
	}
	void SimpleAudioEngine::preloadEffect(const char* pszFilePath)
	{
		SoundFxMap::iterator it = g_pSoundFxMap->find(pszFilePath) ;
		if( it==g_pSoundFxMap->end() ) {
#if 0
			CIwResHandlerWAV * wav_handler = new CIwResHandlerWAV();

			class OpenSoundData: public CIwSoundData
			{
			public:

				int16 * GetBuffer()
				{
					return (int16*)m_Samples;
				}
			};
			OpenSoundData * res = (OpenSoundData*)dynamic_cast<CIwSoundData*>(wav_handler->Build(pszFilePath));
			
			int32 data_size = res->GetBufferSize();
			int16* buff = (int16*)malloc(data_size);
			memcpy(buff, res->GetBuffer(), data_size);
			(*g_pSoundFxMap)[pszFilePath] = SoundFx(buff, data_size);

			delete res;
			delete wav_handler;

#else
			s3eFile *fileHandle = s3eFileOpen(pszFilePath, "rb");
		
			IwAssertMsg(GAME, fileHandle, ("Open file %s Failed. s3eFileError Code : %i", pszFilePath, s3eFileGetError()));
		
			int32 fileSize = s3eFileGetSize(fileHandle);
			int16* buff = (int16*)malloc(fileSize);

			(*g_pSoundFxMap)[pszFilePath] = SoundFx(buff,fileSize) ;
			memset(buff, 0, fileSize);
			s3eFileRead(buff, fileSize, 1, fileHandle);
			s3eFileClose(fileHandle);
#endif
		}
	}
Beispiel #20
0
void MapBackground::CreateMapTileImage2(MapTile* pMapTile, char* szPath, bool isJpg)
{
	if (!IsTileVisible(pMapTile))
	{
		return;
	}
	CIwImage image;
	if (!isJpg)
	{
		image.LoadFromFile(szPath);
		if (image.GetWidth())
		{
			pMapTile->pTexture = new CIwTexture;
			pMapTile->pTexture->CopyFromImage(&image);
			pMapTile->pTexture->Upload();
		}
	}
	else
	{
		s3eFile* pFile = s3eFileOpen(szPath, "r");

		if (pFile)
		{
			uint32 gResultLen = s3eFileGetSize(pFile);
			void* gResult = (void*)s3eMalloc(gResultLen + 1);

			uint32 test = s3eFileRead(gResult, sizeof(char), gResultLen, pFile);
			gResultLen = test;
			s3eFileClose(pFile);

			JPEGImage(gResult, gResultLen, image);
			pMapTile->pTexture = new CIwTexture;
			pMapTile->pTexture->CopyFromImage(&image);
			pMapTile->pTexture->Upload();

			delete gResult;
		}
	}
}
uint32 ResourceManager::RegisterAudio(std::string audioName)
{
    s3eFile *fileHandle = s3eFileOpen(audioName.c_str(), "rb");

    if(fileHandle == null)
    {
        std::string errMsg = "Unknown audio resource requested: '";
        errMsg += audioName + "'";
        s3eDebugAssertShow(S3E_MESSAGE_CONTINUE, errMsg.c_str());
        return 0;
    }

    int soundSize = s3eFileGetSize(fileHandle);
    int16 *soundData = (int16*)s3eMallocBase(soundSize);  
    memset(soundData, 0, soundSize);
    s3eFileRead(soundData, soundSize, 1, fileHandle);  
    s3eFileClose(fileHandle);

    int handle = audioData->size();
    audioData->push_back(soundData);
    audioSizes->push_back(soundSize);

    return handle;
}
bool GAFAsset::initWithImageData(const std::string& jsonPath)
{
	if (!s3eFileCheckExists(jsonPath.c_str()))
	{
		GAFLOGERROR("CAN NOT create GAFAsset : %s does not exists", jsonPath.c_str());
		return false;
	}
	GAFData aConfigData;
	//std::string fp = CCFileUtils::sharedFileUtils()->fullPathForFilename(jsonPath.c_str());
	std::string fp = jsonPath;
	s3eFile * file = s3eFileOpen (fp.c_str(), "rb");
	if (!file)
	{
		GAFLOGERROR("CAN NOT create GAFAsset : can not open %s.", fp.c_str());
		return false;
	}
	
	aConfigData.setSize(s3eFileGetSize(file));
	aConfigData.setBytes(new unsigned char[aConfigData.size()]);
	s3eFileRead(aConfigData.bytes(), aConfigData.size(), 1, file);
	s3eFileClose(file);
	aConfigData.setDeleteData(true);

	if (!aConfigData.bytes())
	{
		GAFLOGERROR("Can not get data from json file : %s", jsonPath.c_str());
		return NULL;
	}

	if (!aConfigData.bytes())
	{
		GAFLOGWARN("can not init GAFAsset - invalid anImageData");
		return false;
	}
	
	CCDictionary* configDictionary = CCJSONConverter::sharedConverter()->dictionaryFrom( (const char *)aConfigData.bytes());
	
	CCString *versionNode               = (CCString*)configDictionary->objectForKey(kVersionKey);
	
	if (!isAssetVersionPlayable(versionNode->getCString()))
	{
		return false;
	}
	CCArray *animationConfigFrames      = (CCArray *)configDictionary->objectForKey(kAnimationConfigFramesKey);
	CCArray *interactionObjectNodes     = (CCArray *)configDictionary->objectForKey(kInteractionObjectsKey);
	CCArray *standObjectsNodes          = (CCArray *)configDictionary->objectForKey(kStandObjectsKey);
	CCArray *textureAtlasNode           = (CCArray *)configDictionary->objectForKey(kTextureAtlasKey);
	CCArray *animationSequences         = (CCArray *)configDictionary->objectForKey(kAnimationSequencesKey);
	
	CCDictionary *objectNodes           = (CCDictionary *)configDictionary->objectForKey(kAnimationObjectsKey);
	CCDictionary *masksNodes            = (CCDictionary *)configDictionary->objectForKey(kAnimationMasksKey);
	CCDictionary *namedPartsNodes       = (CCDictionary *)configDictionary->objectForKey(kAnimationNamedPartsKey);

	
	if (!animationConfigFrames || !textureAtlasNode|| !objectNodes)
	{
		GAFLOGERROR("Error while creating GAFAsset. Required subnodes in dictionary are missing.");
		return false;
	}
	
	CC_SAFE_RELEASE(_textureAtlas);
	
	if (!textureAtlasNode->count())
	{
		return false;
	}

	CCDictionary * atlasDictionary = (CCDictionary *)textureAtlasNode->objectAtIndex(0);
	float atlasScale = atlasScaleFromAtlasConfig(atlasDictionary);
	for (int i = 1; i < textureAtlasNode->count(); ++i)
	{
		CCDictionary * a = (CCDictionary *)textureAtlasNode->objectAtIndex(i);
		float as = atlasScaleFromAtlasConfig(a);
		if ( fabs(atlasScale - _currentDeviceScale) > fabs(as - _currentDeviceScale))
		{
			atlasDictionary = a;
			atlasScale = as;
		}
	}
	
	_usedAtlasContentScaleFactor = atlasScale;
	CCArray * atlasesInfo = (CCArray *)atlasDictionary->objectForKey(kAtlasInfoKey);
	if (!atlasesInfo)
	{
		GAFLOGERROR("Error while creating GAFAsset.atlasesInfo subnode is missing in atlasDictionary.");
		return false;
	}
	
	_textureAtlas = GAFTextureAtlas::create(fp.c_str(), atlasDictionary);
	if (!_textureAtlas)
	{
		GAFLOGERROR("Failed to initialize GAFAsset. GAFTextureAtlas could not be created.");
		return false;
	}
	CC_SAFE_RETAIN(_textureAtlas);
	
	if (_objects != objectNodes)
	{
		CC_SAFE_RELEASE(_objects);
		_objects = objectNodes;
		CC_SAFE_RETAIN(_objects);
	}
	
	if (_masks != masksNodes)
	{
		CC_SAFE_RELEASE(_masks);
		_masks	  = masksNodes;
		CC_SAFE_RETAIN(_masks);
	}
	
	if (_namedParts != namedPartsNodes)
	{
		CC_SAFE_RELEASE(_namedParts);
		_namedParts	  = namedPartsNodes;
		CC_SAFE_RETAIN(_namedParts);
	}
	
	if (interactionObjectNodes)
	{
		CC_SAFE_RELEASE(_interactionObjects);
		_interactionObjects = CCArray::create();
		CC_SAFE_RETAIN(_interactionObjects);
		
		for (unsigned int i = 0; i < interactionObjectNodes->count(); ++i)
		{
			CCDictionary * dict = (CCDictionary*)interactionObjectNodes->objectAtIndex(i);
			
			GAFInteractionObject * interObject = GAFInteractionObject::create(dict);
			if (interObject)
			{
				_interactionObjects->addObject(interObject);
			}
		}
	}
	
	if (standObjectsNodes)
	{
		CC_SAFE_RELEASE(_standObjects);
		_standObjects = CCArray::create();
		CC_SAFE_RETAIN(_standObjects);
		
		for (unsigned int i = 0; i < standObjectsNodes->count(); ++i)
		{
			CCDictionary * dict = (CCDictionary*)standObjectsNodes->objectAtIndex(i);
			
			GAFActionObject * interObject = GAFActionObject::create(dict);
			if (interObject)
			{
				_standObjects->addObject(interObject);
			}
		}
	}
	
	loadFramesFromConfigDictionary(configDictionary);
	
	if (animationSequences)
	{
		loadAnimationSequences(animationSequences);
	}
	configDictionary->removeAllObjects();
	return true;
}
Beispiel #23
0
int main()
{
    // Initialise the 2D graphics system
    Iw2DInit();

    // Create an image from a PNG file
    CIw2DImage* image = Iw2DCreateImage("textures/Tiles.png");
		
	//Avatar bits
	AnimationData testData;
	testData.animationName = "Up";
	testData.animationPosition = 0;
	testData.frameHeight = 64;
	testData.frameWidth = 32;
	testData.numberOfFrames = 4;

	AnimationData testData2;
	testData2.animationName = "Right";
	testData2.animationPosition = 64;
	testData2.frameHeight = 64;
	testData2.frameWidth = 32;
	testData2.numberOfFrames = 4;

	Animation* animation = new Animation("textures/AvatarTest.png",testData);
	Animation* animation2 = new Animation("textures/AvatarTest.png",testData2);

	s3eFile* file = s3eFileOpen("tilemaps/tilemapdemo.json", "rb");
	int len = s3eFileGetSize(file);
	char* rawTileJSON = new char[len];
	if (file != NULL)
	{
		if (s3eFileRead(rawTileJSON, len, 1, file) != 1)
		{
			s3eFileGetError();
			s3eDebugOutputString(s3eFileGetErrorString());
		}
		s3eFileClose(file);
	}
	else
	{
		s3eFileGetError();
		s3eDebugOutputString(s3eFileGetErrorString());
	}

	cJSON *root = cJSON_Parse(rawTileJSON);
	int gridHeight = cJSON_GetObjectItem(root,"height")->valueint;
	int gridWidth = cJSON_GetObjectItem(root,"width")->valueint;
	int tileWidth = cJSON_GetObjectItem(root,"tileheight")->valueint;
	int tileHeight = cJSON_GetObjectItem(root,"tilewidth")->valueint;
	cJSON *layers = cJSON_GetObjectItem(root,"layers");

	cJSON *tileData;
	int i;
	for (i = 0; i<cJSON_GetArraySize(layers); i++)
	{
		cJSON *layer = cJSON_GetArrayItem(layers,i);
		tileData = cJSON_GetObjectItem(layer,"data");
	}



    // Loop forever, until the user or the OS performs some action to quit the app
    while (!s3eDeviceCheckQuitRequest())
    {
        // Clear the drawing surface
        Iw2DSurfaceClear(0xff000000);

		int x,y,tileIndex,tileType;
		for( y = 0; y < gridHeight; y++)
		{
			for(x = 0; x < gridWidth; x++)
			{
				tileIndex = (y * gridWidth) + x;
				tileType = cJSON_GetArrayItem(tileData,tileIndex)->valueint -1;
				// Draw an image
				Iw2DDrawImageRegion(image, CIwFVec2(x*tileWidth,y*tileHeight),CIwFVec2(tileWidth,tileHeight),CIwFVec2(tileType*tileWidth,0),CIwFVec2(tileWidth,tileHeight));
			}
		}
		animation->render(50,50);
		animation2->render(150,200);
        // Show the drawing surface
        Iw2DSurfaceShow();
		
        // Yield to the OS
        s3eDeviceYield(0);
    }

	cJSON_Delete(root);

    // Clean-up
	delete rawTileJSON;
    delete image;
	delete animation;
	delete animation2;
    Iw2DTerminate();

    return 0;
}
void	CIwGamePlatformFileMarm::Close(CxFile file)
{
	s3eFileClose((s3eFile*)file);
}
Beispiel #25
0
AKRESULT s3eIOHook::Close(AkFileDesc & in_fileDesc)
{
	return s3eFileClose( (s3eFile *)in_fileDesc.hFile ) == S3E_RESULT_SUCCESS ? AK_Success : AK_Fail;
}
bool COggVorbisFileHelper::init( std::string fin_str,bool bResample /*= true*/,int nResQuality/*=0*/, char* pData /*= NULL*/, uint32 iSize /*= 0*/)
{
	cleanup();

#if defined(HAVE_PTHREAD)
	pthread_mutex_lock(&mutex1);
#endif	

	nSoundChannel = s3eSoundGetFreeChannel();
	if(nSoundChannel == -1)
	{
		m_strLastError.clear();
		m_strLastError = "Cannot open a sound channel.";
		s3eDebugTracePrintf("%s\n",m_strLastError.c_str());
		cleanup();
#if defined(HAVE_PTHREAD)
		pthread_mutex_unlock(&mutex1);
#endif
		return false;
	}
	s3eSoundChannelRegister(nSoundChannel, S3E_CHANNEL_GEN_AUDIO, GenerateAudioCallback, this);
	s3eSoundChannelRegister(nSoundChannel, S3E_CHANNEL_END_SAMPLE, EndSampleCallback, this);

	ov_callbacks callbacks;
	callbacks.read_func = read_func;
	callbacks.seek_func = seek_func;
	callbacks.close_func = close_func;
	callbacks.tell_func = tell_func;

	if (pData != NULL)
	{
		oggvorbis_filein = s3eFileOpenFromMemory(pData, iSize);
	}
	else
	{
		if(false /*oggvorbis_filein != NULL*/)
		{
			if(s3eFileClose(oggvorbis_filein) == S3E_RESULT_ERROR)
			{
				m_strLastError.clear();
				m_strLastError = "Cannot close old file"; 
				s3eDebugTracePrintf("%s\n",m_strLastError.c_str());
				cleanup();
#if defined(HAVE_PTHREAD)
				pthread_mutex_unlock(&mutex1);
#endif
				return false;
			}
		}
		oggvorbis_filein = s3eFileOpen(fin_str.c_str(),"rb");
	}
	

	if(oggvorbis_filein == NULL)
	{
		m_strLastError.clear();
		m_strLastError = "Cannot open file " + fin_str; 
		s3eDebugTracePrintf("%s\n",m_strLastError.c_str());
		cleanup();
#if defined(HAVE_PTHREAD)
		pthread_mutex_unlock(&mutex1);
#endif
		return false;
	}

	if(ov_open_callbacks(oggvorbis_filein, &vf, NULL, 0, callbacks) < 0)
	{
		m_strLastError.clear();
		m_strLastError = "Input does not appear to be an Ogg bitstream.";
		s3eDebugTracePrintf("%s\n",m_strLastError.c_str());
		cleanup();
#if defined(HAVE_PTHREAD)
		pthread_mutex_unlock(&mutex1);
#endif
		return false;
	}

	/* Throw the comments plus a few lines about the bitstream we're
		decoding */
	{
		char **ptr=ov_comment(&vf,-1)->user_comments;
		vorbis_info *vi=ov_info(&vf,-1);
		//while(*ptr)
		//{
		//	fprintf(stderr,"%s\n",*ptr);
		//	++ptr;
		//}
		total_samples = ov_pcm_total(&vf,-1);
		time_length = ov_time_total_func(&vf,-1);
		nChannels = vi->channels;
		nRate	= vi->rate;

		s3eSoundChannelSetInt(nSoundChannel, S3E_CHANNEL_RATE, nRate);
		nOutputRate = s3eSoundGetInt(S3E_SOUND_OUTPUT_FREQ);

	
		int gcd = GCD(nRate, nOutputRate);
		nW = nRate  / gcd;
		nL = nOutputRate / gcd;


		dResampleFactor = (float)nOutputRate / (float)vi->rate;	// 0 - 4.0 ?

		int err;
		bEnableResampling = bResample;
		nResampleQuality = nResQuality;

		if(bEnableResampling)
		{
			if(res_contL)	speex_resampler_destroy(res_contL);
			res_contL =  speex_resampler_init(1,nRate,nOutputRate,nResampleQuality,&err);

			
			if(res_contR) speex_resampler_destroy(res_contR);
			res_contR =  speex_resampler_init(1,nRate,nOutputRate,nResampleQuality,&err);

			if(err != RESAMPLER_ERR_SUCCESS)
			{
				m_strLastError.clear();
				m_strLastError = "Cannot start resampler.";
				s3eDebugTracePrintf("%s\n",m_strLastError.c_str());
				cleanup();
#if defined(HAVE_PTHREAD)
				pthread_mutex_unlock(&mutex1);
#endif
				return false;
			}
		}
		else
		{
			int fs = min(nRate, nOutputRate);
			double fc = (fs/2) / (double)nOutputRate; // half the input sample rate (eg nyquist limit of input)
			// Generate filter coefficients
			wsfirLP(dFilterCoefficients, nFilterCoefficients, W_BLACKMAN, fc);

			if(dResampleFactor != 1)
				s3eDebugErrorShow(S3E_MESSAGE_CONTINUE,"Resample factor not 1 but resampling disabled");
		}


		s3eDebugTracePrintf("\nBitstream is %d channel, %ldHz\n",vi->channels,vi->rate);
		s3eDebugTracePrintf("\nDecoded length: %ld samples\n",(long)total_samples);
		s3eDebugTracePrintf("Encoded by: %s\n\n",ov_comment(&vf,-1)->vendor);
		s3eDebugTracePrintf("Resampling by rational factor %d / %d", nW, nL);
	}

	bStopDecoding = false;
	nStatus = OH_READY;
#if defined(HAVE_PTHREAD)
	pthread_mutex_unlock(&mutex1);
#endif
	return true;
}
Beispiel #27
0
//-------------------------------------------------------------------------
CIwSoundData* CIwSoundWAV::Create(const CIwStringL& pathname, void* buffer, u_int file_size)
{
    IW_CALLSTACK("CIwSoundWAV::Create")

    CIwSoundData* pData = NULL; // Object to return

    // Open file
    s3eFile* pFile = NULL;
	
	if (buffer != NULL)
		pFile = s3eFileOpenFromMemory(buffer, file_size);
	else
		pFile = IwFileOpenPrefixed(pathname.c_str(), "rb");

    IwAssertMsg(SOUND, pFile, ("Could not load file %s", pathname.c_str()));
    if (!pFile)
        return NULL;

    // Read RIFF header - Gives the file size and checks that this is a WAVE
    // file as expected
    IwRIFFHeader riffHeader;
    if ((s3eFileRead(&riffHeader, sizeof(IwRIFFHeader), 1, pFile) != 1)
        || (strncmp(riffHeader.typeID, "RIFF", 4) != 0)
        || (strncmp(riffHeader.subTypeID, "WAVE", 4) != 0))
    {
        IwAssertMsg(SOUND, false, ("Invalid header in %s (RIFF Header)", pathname.c_str()));
        s3eFileClose(pFile);
        return NULL;
    }

    // Read in RIFF chunks until we reach the end of the file
    // Read the RIFF chunk header. This tells us what type of chunk follows.
    IwRIFFChunkHeader chunkHeader;
    bool readData = false;
    uint32 fileSize = s3eFileGetSize(pFile);

    while (ReadChunkHeader(chunkHeader, *(s3eFile*)pFile))
    {
        uint32 chunkStartPos = s3eFileTell(pFile);

        // Next action depends on chunk type. The order of this is important and we may fail
        // if an unexpected chunk type is found
        if (!strncmp(chunkHeader.typeID, "fmt ", 4))
        {
            // Read WAVE info chunk
            if (!ReadChunkFormat(pathname, chunkHeader, pData, *(s3eFile*)pFile))
            {
                s3eFileClose(pFile);
                return NULL;
            }
        }
        else if (!strncmp(chunkHeader.typeID, "data", 4))
        {
            if (!ReadChunkData(pathname, chunkHeader, pData, *(s3eFile*)pFile))
            {
                s3eFileClose(pFile);
                return NULL;
            }
            readData = true;
        }
        else if (!strncmp(chunkHeader.typeID, "fact", 4))
        {
            if (!ReadChunkFact(pathname, chunkHeader, pData, *(s3eFile*)pFile))
            {
                s3eFileClose(pFile);
                return NULL;
            }
        }
        else
        {
            // Unknown chunk type
            // Make a proper string from the chunk type info
            char typeID[5];
            strncpy(typeID, chunkHeader.typeID, 4);
            typeID[4] = 0;  // Terminate

            const char* g_IgnoreTypes = "LIST" //LIST is just copyright info etc.
                "DISP";  //DISP seems to be info about what package exported it

            IwAssertMsg(SOUND, strstr(g_IgnoreTypes, typeID), ("Unhandled chunk type '%s' in %s. Ignoring this data.", typeID, pathname.c_str()));
        }

        // Exit if at end of file
        if (chunkStartPos + chunkHeader.length >= fileSize)
            break;

        // Move to next chunk
        s3eFileSeek(pFile, chunkStartPos + chunkHeader.length, S3E_FILESEEK_SET);
    }

    // Check that we have read the sample data
    IwAssertMsg(SOUND, readData, ("No data chunk read in %s", pathname.c_str()));
    s3eFileClose(pFile);
    return pData;
}
bool CCImage::_initWithPngData(void * pData, int nDatalen)
{
	IW_CALLSTACK("CCImage::_initWithPngData");
	
    bool bRet = false;
	
	s3eFile* pFile = s3eFileOpenFromMemory(pData, nDatalen);
	
	IwAssert(GAME, pFile);
	
	png_byte pngsig[PNGSIGSIZE];
	
	bool is_png = false;
	
	s3eFileRead((char*)pngsig, PNGSIGSIZE, 1, pFile);
	
	is_png = png_sig_cmp(pngsig, 0, PNGSIGSIZE) == 0 ? true : false;
	
	if (!is_png)
		return false;
	
	png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	
	if (!pngPtr)
		return false;
	
	png_infop infoPtr = png_create_info_struct(pngPtr);
	
	if (!infoPtr)
		return false;
	
	png_bytep* rowPtrs = NULL;
	m_pData = NULL;
	
	if (setjmp(png_jmpbuf(pngPtr))) {
		png_destroy_read_struct(&pngPtr, &infoPtr,(png_infopp)0);
		if (rowPtrs != NULL) delete [] rowPtrs;
		if (m_pData != NULL) delete [] m_pData;
		
		CCLog("ERROR: An error occured while reading the PNG file");
		
		return false;
	}
	
	png_set_read_fn(pngPtr, pFile, userReadData);
	png_set_sig_bytes(pngPtr, PNGSIGSIZE);
	png_read_info(pngPtr, infoPtr);
	
	
	png_uint_32 bitdepth   = png_get_bit_depth(pngPtr, infoPtr);
	png_uint_32 channels   = png_get_channels(pngPtr, infoPtr);
	png_uint_32 color_type = png_get_color_type(pngPtr, infoPtr);
	
	// Convert palette color to true color
	if (color_type ==PNG_COLOR_TYPE_PALETTE)
		png_set_palette_to_rgb(pngPtr);
	
	// Convert low bit colors to 8 bit colors
	if (png_get_bit_depth(pngPtr, infoPtr) < 8)
	{
		if (color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA)
			png_set_gray_1_2_4_to_8(pngPtr);
		else
			png_set_packing(pngPtr);
	}

	if (png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS))
		png_set_tRNS_to_alpha(pngPtr);
	
	// Convert high bit colors to 8 bit colors
	if (bitdepth == 16)
		png_set_strip_16(pngPtr);
	
	// Convert gray color to true color
	if (color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA)
		png_set_gray_to_rgb(pngPtr);
	
	// Update the changes
	png_read_update_info(pngPtr, infoPtr);
	
	// init image info
	m_bPreMulti	= true;
	
	unsigned int bytesPerComponent = png_get_channels(pngPtr, infoPtr);
	
	m_bHasAlpha = (bytesPerComponent == 4 ? true : false);
	
	m_nHeight = (unsigned int)png_get_image_height(pngPtr, infoPtr);
	m_nWidth = (unsigned int) png_get_image_width(pngPtr, infoPtr);
	
	m_nBitsPerComponent = (unsigned int)png_get_bit_depth(pngPtr, infoPtr);
	
	m_pData = new unsigned char[m_nHeight * m_nWidth * bytesPerComponent];
	
	unsigned int bytesPerRow = m_nWidth * bytesPerComponent;
	
	{
		unsigned char *ptr = m_pData;
		rowPtrs = new png_bytep[m_nHeight];
				
		for (int i = 0; i < m_nHeight; i++) {
			
			int q = (i) * bytesPerRow;
			
			rowPtrs[i] = (png_bytep)m_pData + q;
		}
		
		png_read_image(pngPtr, rowPtrs);
		
		delete[] (png_bytep)rowPtrs;
		png_destroy_read_struct(&pngPtr, &infoPtr,(png_infopp)0);
		
		s3eFileClose(pFile);
		pFile = 0;
	}
	
	// premultiplay if alpha
	if(m_bHasAlpha)
		for(unsigned int i = 0; i < m_nHeight*bytesPerRow; i += bytesPerComponent){
			*(m_pData + i + 0)	=  (*(m_pData + i + 0) * *(m_pData + i + 3) + 1) >> 8;
			*(m_pData + i + 1)	=  (*(m_pData + i + 1) * *(m_pData + i + 3) + 1) >> 8;					
			*(m_pData + i + 2)	=  (*(m_pData + i + 2) * *(m_pData + i + 3) + 1) >> 8;
			*(m_pData + i + 3)	=   *(m_pData + i + 3);
	}
	

	
	bRet = true;
    return bRet;
}
int COggVorbisFileHelper::close_func(void *datasource)
{
	return s3eFileClose((s3eFile*)datasource);
}
Beispiel #30
0
void Map::ReadJsonFile(char * filename)
{
	m_filename=filename;
	cJSON *root;
	char * jsonContent;
	s3eFile* fileHandler;
	fileHandler=s3eFileOpen(filename, "rb");
	if (fileHandler != NULL)
    {
        // Allocate buffer to be filled with the files contents
        int32 fileSize = s3eFileGetSize(fileHandler);
        jsonContent = (char*)s3eMallocBase(fileSize+1);

        // Read data from file
        if (s3eFileRead(&jsonContent[0], fileSize+1, 1, fileHandler) != 1)
        {
            // An kError has occurred, retrieve information for display
			std::cout<<s3eFileGetErrorString()<<std::endl;
        }
        else
        {
            // Data reading has been successful
            jsonContent[fileSize] = '\0';
        }
    }
    else
    {
        // Something went wrong during opening of the file retrieve error for display
		std::cout<<s3eFileGetErrorString()<<std::endl;
    }
	if (fileHandler)
		s3eFileClose(fileHandler);
	root = cJSON_Parse(jsonContent);
	s3eFileFlush(fileHandler);

	_height=cJSON_GetObjectItem(root,"height")->valueint;
	cJSON *layers = cJSON_GetObjectItem(root,"layers");
	_tileHeight=cJSON_GetObjectItem(root,"tileheight")->valueint;
	_tileWidth=cJSON_GetObjectItem(root,"tilewidth")->valueint;
	_width=cJSON_GetObjectItem(root,"width")->valueint;
	_layer_base->Init(cJSON_GetArrayItem(layers,0));
	_layer_middle->Init(cJSON_GetArrayItem(layers,1));
	_layer_maze->Init(cJSON_GetArrayItem(layers,2));
	cJSON *tilesets = cJSON_GetObjectItem(root,"tilesets");
	_tileset_map->Init(cJSON_GetArrayItem(tilesets,0));
	_tileset_maze->Init(cJSON_GetArrayItem(tilesets,1));

	cJSON * properties=cJSON_GetObjectItem(root,"properties");
	int propSize=cJSON_GetArraySize(properties);
	for(int i=propSize-1;i!=-1;i--)
	{
		cJSON * prop=cJSON_GetArrayItem(properties,i);
		char* propString=prop->valuestring;

		char* name=prop->string;

		char* chars_array = strtok(propString, ",");
		if(CharCMP(name,"Block",sizeof("Block")))
		{
			while(chars_array)
			{
				_EventBlock.append(atoi(chars_array));
				chars_array = strtok(NULL, ",");
			}
		}
		else if(CharCMP(name,"BG",sizeof("BG")))
		{
			_BGImage=Iw2DCreateImageResource(propString);
		}
		else if(CharCMP(name,"Door",sizeof("Door")))
		{
			while(chars_array)
			{
				m_doors.append(atoi(chars_array));
				chars_array = strtok(NULL, ",");
			}
		}
		else if(CharCMP(name,"EndPoint",sizeof("EndPoint")))
		{
			_EndPos[0]=atoi(chars_array);
			chars_array = strtok(NULL, ",");
			_EndPos[1]=atoi(chars_array);
		}
		else if(CharCMP(name,"StartPoint",sizeof("StartPoint")))
		{
			_StartPos[0]=atoi(chars_array);
			chars_array = strtok(NULL, ",");
			_StartPos[1]=atoi(chars_array);
		}
		else if(CharCMP(name,"emaze",sizeof("emaze")))
		{
			while(chars_array)
			{
				mapEndIndex.append(atoi(chars_array));
				chars_array = strtok(NULL, ",");
			}
		}
		else if(CharCMP(name,"etmaze",sizeof("etmaze")))
		{
			while(chars_array)
			{
				mazeEndIndex.append(atoi(chars_array));
				chars_array = strtok(NULL, ",");
			}
		}
		else if(CharCMP(name,"smaze",sizeof("smaze")))
		{
			while(chars_array)
			{
				mapStartIndex.append(atoi(chars_array));
				chars_array = strtok(NULL, ",");
			}
		}
		else if(CharCMP(name,"stmaze",sizeof("stmaze")))
		{
			while(chars_array)
			{
				mazeStartIndex.append(atoi(chars_array));
				chars_array = strtok(NULL, ",");
			}
		}
	}

	_total=_height*_width;
	_size=CIwSVec2(_width*_tileWidth,_height*_tileHeight);

}