コード例 #1
0
ファイル: tileset.cpp プロジェクト: johnjianfang/megaglestng
void Tileset::load(const string &dir, Checksum *checksum, Checksum *tilesetChecksum,
		std::map<string,vector<pair<string, string> > > &loadedFileList) {
	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

	random.init(time(NULL));

	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

	string name= lastDir(dir);
	tileset_name = name;
	string currentPath = dir;
	endPathWithSlash(currentPath);
	string path= currentPath + name + ".xml";
	string sourceXMLFile = path;

	checksum->addFile(path);
	tilesetChecksum->addFile(path);
	checksumValue.addFile(path);

	try {
		char szBuf[8096]="";
		snprintf(szBuf,8096,Lang::getInstance().get("LogScreenGameLoadingTileset","",true).c_str(),formatString(name).c_str());
		Logger::getInstance().add(szBuf, true);

		Renderer &renderer= Renderer::getInstance();

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		//printf("About to load tileset [%s]\n",path.c_str());
		//parse xml
		XmlTree xmlTree;
		xmlTree.load(path,Properties::getTagReplacementValues());
		loadedFileList[path].push_back(make_pair(currentPath,currentPath));

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		const XmlNode *tilesetNode= xmlTree.getRootNode();

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		//surfaces
		const XmlNode *surfacesNode= tilesetNode->getChild("surfaces");
		int partsize= 0;
		for(int i=0; i < surfCount; ++i) {

			const XmlNode *surfaceNode;
			if(surfacesNode->hasChildAtIndex("surface",i)){
				surfaceNode= surfacesNode->getChild("surface", i);
			}
			else {
				// cliff texture does not exist, use texture 2 instead
				surfaceNode= surfacesNode->getChild("surface", 2);
			}

			if(surfaceNode->hasAttribute("partsize")){
				partsize=surfaceNode->getAttribute("partsize",true)->getIntValue();
			}
			else{
				partsize=0;
			}

			if(partsize==0){
				int childCount= surfaceNode->getChildCount();
				surfPixmaps[i].resize(childCount);
				surfProbs[i].resize(childCount);

				for(int j = 0; j < childCount; ++j) {
					surfPixmaps[i][j] = NULL;
				}

				for(int j = 0; j < childCount; ++j) {
					const XmlNode *textureNode= surfaceNode->getChild("texture", j);
					if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) {
						surfPixmaps[i][j] = new Pixmap2D();
						surfPixmaps[i][j]->init(3);
						surfPixmaps[i][j]->load(textureNode->getAttribute("path")->getRestrictedValue(currentPath));
					}
					loadedFileList[textureNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(sourceXMLFile,textureNode->getAttribute("path")->getRestrictedValue()));

					surfProbs[i][j]= textureNode->getAttribute("prob")->getFloatValue();
				}
			}
			else {
				// read single big texture and cut it into pieces
				const XmlNode *textureNode= surfaceNode->getChild("texture", 0);
				Pixmap2D *pixmap=new Pixmap2D();
				pixmap->init(3);
				pixmap->load(textureNode->getAttribute("path")->getRestrictedValue(currentPath));
				loadedFileList[textureNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(sourceXMLFile,textureNode->getAttribute("path")->getRestrictedValue()));
				int width=pixmap->getW();
				int heith=pixmap->getW();
				assert(width==heith);
				assert(width%64==0);
				assert(width%partsize==0);
				int parts=width/partsize;
				int numberOfPieces=parts*parts;
				partsArray[i]=parts;
				surfPixmaps[i].resize(numberOfPieces);
				surfProbs[i].resize(numberOfPieces);
				int j=0;
				for(int x = 0; x < parts; ++x) {
					for(int y = 0; y < parts; ++y) {
						surfPixmaps[i][j] = new Pixmap2D();
						surfPixmaps[i][j]->init(partsize,partsize,3);
						surfPixmaps[i][j]->copyImagePart(x*partsize,y*partsize,pixmap);
						surfProbs[i][j]=-1;
						j++;
					}
				}
			}
		}

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		//object models
		const XmlNode *objectsNode= tilesetNode->getChild("objects");
		for(int i=0; i<objCount; ++i){
			const XmlNode *objectNode= objectsNode->getChild("object", i);
			int childCount= objectNode->getChildCount();

			int objectHeight = 0;
			bool walkable = objectNode->getAttribute("walkable")->getBoolValue();
			if(walkable == false) {
				const XmlAttribute *heightAttribute = objectNode->getAttribute("height",false);
				if(heightAttribute != NULL) {
					objectHeight = heightAttribute->getIntValue();
				}
			}

			objectTypes[i].init(childCount, i, walkable,objectHeight);
			for(int j=0; j<childCount; ++j) {
				const XmlNode *modelNode= objectNode->getChild("model", j);
				const XmlAttribute *pathAttribute= modelNode->getAttribute("path");
				TilesetModelType* tmt=objectTypes[i].loadModel(pathAttribute->getRestrictedValue(currentPath),&loadedFileList, sourceXMLFile);
				loadedFileList[pathAttribute->getRestrictedValue(currentPath)].push_back(make_pair(sourceXMLFile,pathAttribute->getRestrictedValue()));

				if(modelNode->hasAttribute("anim-speed") == true) {
					int animSpeed= modelNode->getAttribute("anim-speed")->getIntValue();
					tmt->setAnimSpeed(animSpeed);
				}

				if(modelNode->hasChild("particles")){
					const XmlNode *particleNode= modelNode->getChild("particles");
					bool particleEnabled= particleNode->getAttribute("value")->getBoolValue();
					if(particleEnabled){
						for(int k=0; k<particleNode->getChildCount(); ++k){
							const XmlNode *particleFileNode= particleNode->getChild("particle-file", k);
							string path= particleFileNode->getAttribute("path")->getRestrictedValue();
							ObjectParticleSystemType *objectParticleSystemType= new ObjectParticleSystemType();
							objectParticleSystemType->load(particleFileNode, dir, currentPath + path,
									&Renderer::getInstance(), loadedFileList, sourceXMLFile,"");
							loadedFileList[currentPath + path].push_back(make_pair(sourceXMLFile,particleFileNode->getAttribute("path")->getRestrictedValue()));

							tmt->addParticleSystem(objectParticleSystemType);
						}
					}
				}

				//rotationAllowed
				if(modelNode->hasAttribute("rotationAllowed") == true) {
					tmt->setRotationAllowed(modelNode->getAttribute("rotationAllowed")->getBoolValue());
				}
				else if(modelNode->hasChild("rotationAllowed")){
					const XmlNode *rotationAllowedNode= modelNode->getChild("rotationAllowed");
					tmt->setRotationAllowed(rotationAllowedNode->getAttribute("value")->getBoolValue());
				}
				else{
					tmt->setRotationAllowed(true);
				}

				//smoothTwoFrameAnim
				if(modelNode->hasAttribute("smoothTwoFrameAnim") == true) {
					tmt->setSmoothTwoFrameAnim(modelNode->getAttribute("smoothTwoFrameAnim")->getBoolValue());
				}
				else{
					tmt->setSmoothTwoFrameAnim(false);
				}
			}
		}

		// Now free up the pixmap memory
		for(int i=0; i<objCount; ++i){
			objectTypes[i].deletePixels();
		}

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		//ambient sounds
		ambientSounds.load(dir, tilesetNode->getChild("ambient-sounds"), loadedFileList, sourceXMLFile);

		//parameters
		const XmlNode *parametersNode= tilesetNode->getChild("parameters");

		//water
		const XmlNode *waterNode= parametersNode->getChild("water");
		waterTex= renderer.newTexture3D(rsGame);
		if(waterTex) {
			waterTex->setMipmap(false);
			waterTex->setWrapMode(Texture::wmRepeat);
		}
		waterEffects= waterNode->getAttribute("effects")->getBoolValue();

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		int waterFrameCount= waterNode->getChildCount();
		if(waterTex) {
			waterTex->getPixmap()->init(waterFrameCount, 4);
		}
		for(int i=0; i<waterFrameCount; ++i){
			const XmlNode *waterFrameNode= waterNode->getChild("texture", i);
			if(waterTex) {
				waterTex->getPixmap()->loadSlice(waterFrameNode->getAttribute("path")->getRestrictedValue(currentPath), i);
			}
			loadedFileList[waterFrameNode->getAttribute("path")->getRestrictedValue(currentPath)].push_back(make_pair(sourceXMLFile,waterFrameNode->getAttribute("path")->getRestrictedValue()));
		}

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		//fog
		const XmlNode *fogNode= parametersNode->getChild("fog");
		fog= fogNode->getAttribute("enabled")->getBoolValue();
		if(fog){
			fogMode= fogNode->getAttribute("mode")->getIntValue(1, 2);
			fogDensity= fogNode->getAttribute("density")->getFloatValue();
			fogColor.x= fogNode->getAttribute("color-red")->getFloatValue(0.f, 1.f);
			fogColor.y= fogNode->getAttribute("color-green")->getFloatValue(0.f, 1.f);
			fogColor.z= fogNode->getAttribute("color-blue")->getFloatValue(0.f, 1.f);
		}

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		//sun and moon light colors
		const XmlNode *sunLightColorNode= parametersNode->getChild("sun-light");
		sunLightColor.x= sunLightColorNode->getAttribute("red")->getFloatValue();
		sunLightColor.y= sunLightColorNode->getAttribute("green")->getFloatValue();
		sunLightColor.z= sunLightColorNode->getAttribute("blue")->getFloatValue();

		const XmlNode *moonLightColorNode= parametersNode->getChild("moon-light");
		moonLightColor.x= moonLightColorNode->getAttribute("red")->getFloatValue();
		moonLightColor.y= moonLightColorNode->getAttribute("green")->getFloatValue();
		moonLightColor.z= moonLightColorNode->getAttribute("blue")->getFloatValue();

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		//weather
		const XmlNode *weatherNode= parametersNode->getChild("weather");
		float sunnyProb= weatherNode->getAttribute("sun")->getFloatValue(0.f, 1.f);
		float rainyProb= weatherNode->getAttribute("rain")->getFloatValue(0.f, 1.f) + sunnyProb;

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

#ifdef USE_STREFLOP
		float rnd= streflop::fabs(static_cast<streflop::Simple>(random.randRange(-1.f, 1.f)));
#else
		float rnd= fabs(random.randRange(-1.f, 1.f));
#endif

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

		if(rnd < sunnyProb) {
			weather= wSunny;
		}
		else if(rnd < rainyProb) {
			weather= wRainy;
		}
		else {
			weather= wSnowy;
		}

		//printf("==> Weather is: %d rnd = %f [sun: %f rainyProb: %f]",weather,rnd,sunnyProb,rainyProb);

		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);

	}
	//Exception handling (conversions and so on);
	catch(const exception &e) {
		SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,e.what());
		throw megaglest_runtime_error("Error: " + path + "\n" + e.what());
	}

    Lang &lang = Lang::getInstance();
    lang.loadTilesetStrings(name);
}
コード例 #2
0
ファイル: display.cpp プロジェクト: johnjianfang/megaglestng
Vec4f Display::getColor() const {
	if(currentColor < 0 || currentColor >= colorCount) {
		throw megaglest_runtime_error("currentColor >= colorCount");
	}
	return colors[currentColor];
}
コード例 #3
0
ファイル: display.cpp プロジェクト: johnjianfang/megaglestng
void Display::setUpImage(int i, const Texture2D *image)
{
	if(i>=upCellCount) throw megaglest_runtime_error("i>=upCellCount in Display::setUpImage");
	upImages[i]= image;
	calculateUpDimensions(i);
}
コード例 #4
0
ファイル: renderer.cpp プロジェクト: Ishmaru/megaglest-source
void Renderer::checkExtension(const string &extension, const string &msg) {
	if(isGlExtensionSupported(extension.c_str()) == false) {
		string str= "OpenGL extension not supported: " + extension +  ", required for " + msg;
		throw megaglest_runtime_error(str);
	}
}
コード例 #5
0
ファイル: renderer.cpp プロジェクト: Ishmaru/megaglest-source
void Renderer::init() {
	assertGl();

	GraphicsFactory *gf= GraphicsInterface::getInstance().getFactory();
	if(gf == NULL) {
		gf= new GraphicsFactoryGl();
		GraphicsInterface::getInstance().setFactory(gf);
	}

	Config &config = Config::getInstance();
	if(config.getBool("CheckGlCaps")){

		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);

		checkGlCaps();
	}

	if(glActiveTexture == NULL) {
		char szBuf[8096]="";
		snprintf(szBuf,8096,"Error: glActiveTexture == NULL\nglActiveTexture is only supported if the GL version is 1.3 or greater,\nor if the ARB_multitexture extension is supported!");
		throw megaglest_runtime_error(szBuf);
	}

	modelRenderer= gf->newModelRenderer();
	textureManager= gf->newTextureManager();
	particleRenderer= gf->newParticleRenderer();

	//resources
	particleManager= gf->newParticleManager();

	modelManager = gf->newModelManager();
	modelManager->setTextureManager(textureManager);

	//red tex
	customTextureRed= textureManager->newTexture2D();
	customTextureRed->getPixmap()->init(1, 1, 3);
	customTextureRed->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.f, 0.f));

	//blue tex
	customTextureBlue= textureManager->newTexture2D();
	customTextureBlue->getPixmap()->init(1, 1, 3);
	customTextureBlue->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.f, 1.f));

	//green tex
	customTextureGreen= textureManager->newTexture2D();
	customTextureGreen->getPixmap()->init(1, 1, 3);
	customTextureGreen->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.5f, 0.f));

	//yellow tex
	customTextureYellow= textureManager->newTexture2D();
	customTextureYellow->getPixmap()->init(1, 1, 3);
	customTextureYellow->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 0.f));

	//white tex
	customTextureWhite= textureManager->newTexture2D();
	customTextureWhite->getPixmap()->init(1, 1, 3);
	customTextureWhite->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 1.f));

	//cyan tex
	customTextureCyan= textureManager->newTexture2D();
	customTextureCyan->getPixmap()->init(1, 1, 3);
	customTextureCyan->getPixmap()->setPixel(0, 0, Vec3f(0.f, 1.f, 0.8f));

	//orange tex
	customTextureOrange= textureManager->newTexture2D();
	customTextureOrange->getPixmap()->init(1, 1, 3);
	customTextureOrange->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 0.f));

	//magenta tex
	customTextureMagenta= textureManager->newTexture2D();
	customTextureMagenta->getPixmap()->init(1, 1, 3);
	customTextureMagenta->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 1.f));

	glClearColor(red, green, blue, alpha);  //backgroundcolor constant 0.3
    //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /* once the GL context is valid : */
    //GLint alpha_bits;
    //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
    //printf("#1 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);

	glEnable(GL_TEXTURE_2D);
	glFrontFace(GL_CW);
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_ALPHA_TEST);
	//glAlphaFunc(GL_GREATER, 0.5f);
	glAlphaFunc(GL_GREATER, 0.0f);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);

	Vec4f diffuse= Vec4f(1.0f, 1.0f, 1.0f, 1.0f);
	Vec4f ambient= Vec4f(0.3f, 0.3f, 0.3f, 1.0f);
	Vec4f specular= Vec4f(0.1f, 0.1f, 0.1f, 1.0f);

	glLightfv(GL_LIGHT0,GL_AMBIENT, ambient.ptr());
	glLightfv(GL_LIGHT0,GL_DIFFUSE, diffuse.ptr());
	glLightfv(GL_LIGHT0,GL_SPECULAR, specular.ptr());

	glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
	glEnable(GL_COLOR_MATERIAL);

	assertGl();
}
コード例 #6
0
BaseThread::~BaseThread() {

	//printf("In ~BaseThread Line: %d uniqueID [%s]\n",__LINE__,uniqueID.c_str());
	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s]\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str());

	//BaseThread *base_thread = dynamic_cast<BaseThread *>(this);
	if(this->getStarted() == false) {
		time_t elapsed = time(NULL);
		for(;this->getStarted() == false &&
    		difftime((long int)time(NULL),elapsed) <= 3;) {
			sleep(5);
		}
	}

	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s]\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str());
	bool ret = shutdownAndWait();
	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s] ret [%d] END\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str(),ret);

	//printf("In ~BaseThread Line: %d uniqueID [%s]\n",__LINE__,uniqueID.c_str());

	MutexSafeWrapper safeMutexMasterList(&mutexMasterThreadList);

	//printf("In ~BaseThread Line: %d uniqueID [%s]\n",__LINE__,uniqueID.c_str());

	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s] ret [%d] END\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str(),ret);

	//printf("In ~BaseThread Line: %d uniqueID [%s]\n",__LINE__,uniqueID.c_str());

	if(masterThreadList.find(this) == masterThreadList.end()) {
		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s] ret [%d] END\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str(),ret);

		char szBuf[8096]="";
		snprintf(szBuf,8096,"invalid thread delete for ptr: %p",this);
		throw megaglest_runtime_error(szBuf);
	}
	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s] ret [%d] END\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str(),ret);

	//printf("In ~BaseThread Line: %d uniqueID [%s]\n",__LINE__,uniqueID.c_str());

	masterThreadList[this]--;
	if(masterThreadList[this] <= 0) {
		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s] ret [%d] END\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str(),ret);
		masterThreadList.erase(this);
	}

	//printf("In ~BaseThread Line: %d uniqueID [%s]\n",__LINE__,uniqueID.c_str());

	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s] ret [%d] END\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str(),ret);

	safeMutexMasterList.ReleaseLock();

	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] uniqueID [%s] ret [%d] END\n",__FILE__,__FUNCTION__,__LINE__,uniqueID.c_str(),ret);


	delete mutexRunning;
	mutexRunning = NULL;
	delete mutexQuit;
	mutexQuit = NULL;
	delete mutexBeginExecution;
	mutexBeginExecution = NULL;
	delete mutexDeleteSelfOnExecutionDone;
	mutexDeleteSelfOnExecutionDone = NULL;
	delete mutexThreadObjectAccessor;
	mutexThreadObjectAccessor = NULL;
    delete mutexThreadOwnerValid;
    mutexThreadOwnerValid = NULL;
    delete mutexExecutingTask;
    mutexExecutingTask = NULL;
	delete mutexStarted;
	mutexStarted = NULL;

	//printf("In ~BaseThread Line: %d uniqueID [%s] [%p]\n",__LINE__,uniqueID.c_str(),this);
}
コード例 #7
0
// =====================================================
// 	class MenuStateOptions
// =====================================================
MenuStateOptionsSound::MenuStateOptionsSound(Program *program, MainMenu *mainMenu, ProgramState **parentUI):
	MenuState(program, mainMenu, "config")
{
	try {
		containerName = "Options";
		this->parentUI=parentUI;
		Lang &lang= Lang::getInstance();
		Config &config= Config::getInstance();
		this->console.setOnlyChatMessagesInStoredLines(false);

		int leftLabelStart=50;
		int leftColumnStart=leftLabelStart+280;
		//int rightLabelStart=450;
		//int rightColumnStart=rightLabelStart+280;
		int buttonRowPos=50;
		int buttonStartPos=170;
		//int captionOffset=75;
		//int currentLabelStart=leftLabelStart;
		//int currentColumnStart=leftColumnStart;
		//int currentLine=700;
		int lineOffset=30;
		int tabButtonWidth=200;
		int tabButtonHeight=30;

		mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox");
		mainMessageBox.init(lang.getString("Ok"));
		mainMessageBox.setEnabled(false);
		mainMessageBoxState=0;

		buttonAudioSection.registerGraphicComponent(containerName,"buttonAudioSection");
		buttonAudioSection.init(0, 700,tabButtonWidth,tabButtonHeight+20);
		buttonAudioSection.setFont(CoreData::getInstance().getMenuFontVeryBig());
		buttonAudioSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D());
		buttonAudioSection.setText(lang.getString("Audio"));
		// Video Section
		buttonVideoSection.registerGraphicComponent(containerName,"labelVideoSection");
		buttonVideoSection.init(200, 720,tabButtonWidth,tabButtonHeight);
		buttonVideoSection.setFont(CoreData::getInstance().getMenuFontVeryBig());
		buttonVideoSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D());
		buttonVideoSection.setText(lang.getString("Video"));
		//currentLine-=lineOffset;
		//MiscSection
		buttonMiscSection.registerGraphicComponent(containerName,"labelMiscSection");
		buttonMiscSection.init(400, 720,tabButtonWidth,tabButtonHeight);
		buttonMiscSection.setFont(CoreData::getInstance().getMenuFontVeryBig());
		buttonMiscSection.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D());
		buttonMiscSection.setText(lang.getString("Misc"));
		//NetworkSettings
		buttonNetworkSettings.registerGraphicComponent(containerName,"labelNetworkSettingsSection");
		buttonNetworkSettings.init(600, 720,tabButtonWidth,tabButtonHeight);
		buttonNetworkSettings.setFont(CoreData::getInstance().getMenuFontVeryBig());
		buttonNetworkSettings.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D());
		buttonNetworkSettings.setText(lang.getString("Network"));

		//KeyboardSetup
		buttonKeyboardSetup.registerGraphicComponent(containerName,"buttonKeyboardSetup");
		buttonKeyboardSetup.init(800, 720,tabButtonWidth,tabButtonHeight);
		buttonKeyboardSetup.setFont(CoreData::getInstance().getMenuFontVeryBig());
		buttonKeyboardSetup.setFont3D(CoreData::getInstance().getMenuFontVeryBig3D());
		buttonKeyboardSetup.setText(lang.getString("Keyboardsetup"));

		int currentLine=650; // reset line pos
		int currentLabelStart=leftLabelStart; // set to right side
		int currentColumnStart=leftColumnStart; // set to right side

		//soundboxes
		labelSoundFactory.registerGraphicComponent(containerName,"labelSoundFactory");
		labelSoundFactory.init(currentLabelStart, currentLine);
		labelSoundFactory.setText(lang.getString("SoundAndMusic"));

		listBoxSoundFactory.registerGraphicComponent(containerName,"listBoxSoundFactory");
		listBoxSoundFactory.init(currentColumnStart, currentLine, 100);
		listBoxSoundFactory.pushBackItem("None");
		listBoxSoundFactory.pushBackItem("OpenAL");

		listBoxSoundFactory.setSelectedItem(config.getString("FactorySound"));
		currentLine-=lineOffset;

		labelVolumeFx.registerGraphicComponent(containerName,"labelVolumeFx");
		labelVolumeFx.init(currentLabelStart, currentLine);
		labelVolumeFx.setText(lang.getString("FxVolume"));

		listBoxVolumeFx.registerGraphicComponent(containerName,"listBoxVolumeFx");
		listBoxVolumeFx.init(currentColumnStart, currentLine, 80);
		currentLine-=lineOffset;

		labelVolumeAmbient.registerGraphicComponent(containerName,"labelVolumeAmbient");
		labelVolumeAmbient.init(currentLabelStart, currentLine);

		listBoxVolumeAmbient.registerGraphicComponent(containerName,"listBoxVolumeAmbient");
		listBoxVolumeAmbient.init(currentColumnStart, currentLine, 80);
		labelVolumeAmbient.setText(lang.getString("AmbientVolume"));
		currentLine-=lineOffset;

		labelVolumeMusic.registerGraphicComponent(containerName,"labelVolumeMusic");
		labelVolumeMusic.init(currentLabelStart, currentLine);

		listBoxVolumeMusic.registerGraphicComponent(containerName,"listBoxVolumeMusic");
		listBoxVolumeMusic.init(currentColumnStart, currentLine, 80);
		labelVolumeMusic.setText(lang.getString("MusicVolume"));
		//currentLine-=lineOffset;

		for(int i=0; i<=100; i+=5){
			listBoxVolumeFx.pushBackItem(intToStr(i));
			listBoxVolumeAmbient.pushBackItem(intToStr(i));
			listBoxVolumeMusic.pushBackItem(intToStr(i));
		}
		listBoxVolumeFx.setSelectedItem(intToStr(config.getInt("SoundVolumeFx")/5*5));
		listBoxVolumeAmbient.setSelectedItem(intToStr(config.getInt("SoundVolumeAmbient")/5*5));
		listBoxVolumeMusic.setSelectedItem(intToStr(config.getInt("SoundVolumeMusic")/5*5));

		//currentLine-=lineOffset/2;



		//////////////////////////////////////////////////////////////////
		///////// RIGHT SIDE
		//////////////////////////////////////////////////////////////////

		//currentLine=700; // reset line pos
		//currentLabelStart=rightLabelStart; // set to right side
		//currentColumnStart=rightColumnStart; // set to right side


		// buttons
		buttonOk.registerGraphicComponent(containerName,"buttonOk");
		buttonOk.init(buttonStartPos, buttonRowPos, 100);
		buttonOk.setText(lang.getString("Save"));
		buttonReturn.setText(lang.getString("Return"));

		buttonReturn.registerGraphicComponent(containerName,"buttonAbort");
		buttonReturn.init(buttonStartPos+110, buttonRowPos, 100);

		GraphicComponent::applyAllCustomProperties(containerName);
	}
	catch(exception &e) {
		SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error loading options: %s\n",__FILE__,__FUNCTION__,__LINE__,e.what());
		throw megaglest_runtime_error(string("Error loading options msg: ") + e.what());
	}
}
コード例 #8
0
Pixmap3D* TGAReader3D::read(ifstream& in, const string& path, Pixmap3D* ret) const {
	//printf("In [%s] line: %d\n",__FILE__,__LINE__);
//	try {
		assert(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false);
		//read header
		TargaFileHeader fileHeader;
		in.read((char*)&fileHeader, sizeof(TargaFileHeader));
		static bool bigEndianSystem = Shared::PlatformByteOrder::isBigEndian();
		if(bigEndianSystem == true) {
			fileHeader.bitsPerPixel = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.bitsPerPixel);
			fileHeader.colourMapDepth = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.colourMapDepth);
			fileHeader.colourMapLength = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.colourMapDepth);
			fileHeader.colourMapOrigin = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.colourMapOrigin);
			fileHeader.colourMapType = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.colourMapType);
			fileHeader.dataTypeCode = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.dataTypeCode);
			fileHeader.height = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.height);
			fileHeader.idLength = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.idLength);
			fileHeader.imageDescriptor = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.imageDescriptor);
			fileHeader.width = Shared::PlatformByteOrder::fromCommonEndian(fileHeader.width);
		}

		if (!in.good()) {
			throw megaglest_runtime_error(path + " could not be read",true);
		}

		//check that we can load this tga file
		if(fileHeader.idLength!=0){
			throw megaglest_runtime_error(path + ": id field is not 0",true);
		}

		if(fileHeader.dataTypeCode!=tgaUncompressedRgb && fileHeader.dataTypeCode!=tgaUncompressedBw){
			throw megaglest_runtime_error(path + ": only uncompressed BW and RGB targa images are supported",true);
		}

		//check bits per pixel
		if(fileHeader.bitsPerPixel!=8 && fileHeader.bitsPerPixel!=24 && fileHeader.bitsPerPixel!=32){
			throw megaglest_runtime_error(path + ": only 8, 24 and 32 bit targa images are supported",true);
		}

		const int h = fileHeader.height;
		const int w = fileHeader.width;
		const int d = ret->getD();
		const int slice = ret->getSlice();
		const int fileComponents= fileHeader.bitsPerPixel/8;
		const int picComponents = (ret->getComponents()==-1)?fileComponents:ret->getComponents();
		//std::cout << "TGA-Components: Pic: " << picComponents << " old: " << (ret->getComponents()) << " File: " << fileComponents << " slice:" << ret->getSlice() << std::endl;
		if(ret->getPixels() == NULL){
			ret->init(w,h,d, picComponents);
		}
		uint8* pixels = ret->getPixels();
		if(slice > 0) {
			pixels = &pixels[slice*w*h*picComponents];
		}
		//read file
		for(int i=0; i<h*w*picComponents; i+=picComponents){
			uint8 r=0, g=0, b=0, a=0, l=0;

			if(fileComponents==1){
				in.read((char*)&l,1);
				if(bigEndianSystem == true) {
					l = Shared::PlatformByteOrder::fromCommonEndian(l);
				}

				r= l;
				g= l;
				b= l;
				a= 255;
			}
			else{
				in.read((char*)&b, 1);
				if(bigEndianSystem == true) {
					b = Shared::PlatformByteOrder::fromCommonEndian(b);
				}

				in.read((char*)&g, 1);
				if(bigEndianSystem == true) {
					g = Shared::PlatformByteOrder::fromCommonEndian(g);
				}

				in.read((char*)&r, 1);
				if(bigEndianSystem == true) {
					r = Shared::PlatformByteOrder::fromCommonEndian(r);
				}

				if(fileComponents==4){
					in.read((char*)&a, 1);
					if(bigEndianSystem == true) {
						a = Shared::PlatformByteOrder::fromCommonEndian(a);
					}

				} else {
					a= 255;
				}
				l= (r+g+b)/3;
			}
			//if (!in.good()) {
			//	return NULL;
			//}

			switch(picComponents){
			case 1:
				pixels[i]= l;
				break;
			case 3:
				pixels[i]= r;
				pixels[i+1]= g;
				pixels[i+2]= b;
				break;
			case 4:
				pixels[i]= r;
				pixels[i+1]= g;
				pixels[i+2]= b;
				pixels[i+3]= a;
			break;
			}
		}
		/*for(int i = 0; i < w*h*picComponents; ++i) {
			if (i%39 == 0) std::cout << std::endl;
			int first = pixels[i]/16;
			if (first < 10)
				std:: cout << first;
			else
				std::cout << (char)('A'+(first-10));
			first = pixels[i]%16;
			if (first < 10)
				std:: cout << first;
			else
				std::cout << (char)('A'+(first-10));
			std::cout << " ";
		}*/

//	}
//	catch(exception& ex) {
//		char szBuf[8096]="";
//		snprintf(szBuf,8096,"Error in [%s] on line: %d msg: %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,ex.what());
//		throw megaglest_runtime_error(szBuf);
//	}

	return ret;
}
コード例 #9
0
// =====================================================
//	class FontManager
// =====================================================
FontManager::FontManager() {
    if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) {
        throw megaglest_runtime_error("Loading graphics in headless server mode not allowed!");
    }
    fonts.clear();
}
コード例 #10
0
vector<Unit*> Selection::getUnitsForGroup(int groupIndex) {
	if(groupIndex < 0 || groupIndex >= maxGroups) {
		throw megaglest_runtime_error("Invalid value for groupIndex = " + intToStr(groupIndex));
	}
	return groups[groupIndex];
}
コード例 #11
0
void UnitParticleSystemType::load(const XmlNode *particleSystemNode, const string &dir,
		RendererInterface *renderer, std::map<string,vector<pair<string, string> > > &loadedFileList,
		string parentLoader, string techtreePath) {

	ParticleSystemType::load(particleSystemNode, dir, renderer, loadedFileList,
			parentLoader,techtreePath);
	
	//shape
	angle= 0.0f;
	if(particleSystemNode->hasChild("shape")){
		const XmlNode *shapeNode= particleSystemNode->getChild("shape");
		shape= UnitParticleSystem::strToShape(shapeNode->getAttribute("value")->getRestrictedValue());
		if(shape == UnitParticleSystem::sConical){
			angle= shapeNode->getChild("angle")->getAttribute("value")->getFloatValue();
		}
	} else {
		shape = UnitParticleSystem::sLinear;
	}
	if(shape != UnitParticleSystem::sSpherical){
		//direction
		const XmlNode *directionNode= particleSystemNode->getChild("direction");
		direction.x= directionNode->getAttribute("x")->getFloatValue();
		direction.y= directionNode->getAttribute("y")->getFloatValue();
		direction.z= directionNode->getAttribute("z")->getFloatValue();
		if((shape == UnitParticleSystem::sConical) && (0.0 == direction.length()))
			throw megaglest_runtime_error("direction cannot be zero");
		// ought to warn about 0 directions generally
	}

	//emission rate fade
	if(particleSystemNode->hasChild("emission-rate-fade")){
		const XmlNode *emissionRateFadeNode= particleSystemNode->getChild("emission-rate-fade");
		emissionRateFade= emissionRateFadeNode->getAttribute("value")->getFloatValue();
	} else {
		emissionRateFade = 0;
	}
	
	//radius
	const XmlNode *radiusNode= particleSystemNode->getChild("radius");
	radius= radiusNode->getAttribute("value")->getFloatValue();
	
	// min radius
	if(particleSystemNode->hasChild("min-radius")){
		const XmlNode *minRadiusNode= particleSystemNode->getChild("min-radius");
		minRadius= minRadiusNode->getAttribute("value")->getFloatValue();
		if(minRadius > radius)
			throw megaglest_runtime_error("min-radius cannot be bigger than radius");
	} else {
		minRadius = 0;
	}
	if((minRadius == 0) && (shape == UnitParticleSystem::sConical)) {
		minRadius = 0.001f; // fudge it so we aren't generating particles that are exactly centred
		if(minRadius > radius)
			radius = minRadius;
	}

	//relative
    const XmlNode *relativeNode= particleSystemNode->getChild("relative");
    relative= relativeNode->getAttribute("value")->getBoolValue();
    

    //relativeDirection
    if(particleSystemNode->hasChild("relativeDirection")){
    	const XmlNode *relativeDirectionNode= particleSystemNode->getChild("relativeDirection");
    	relativeDirection= relativeDirectionNode->getAttribute("value")->getBoolValue();
    }
    else{
    	relativeDirection=true;
    }
    
    if(particleSystemNode->hasChild("static-particle-count")){
	    //staticParticleCount
		const XmlNode *staticParticleCountNode= particleSystemNode->getChild("static-particle-count");
		staticParticleCount= staticParticleCountNode->getAttribute("value")->getIntValue();
    }
    else{
    	staticParticleCount=0;
    }
    
    //isVisibleAtNight
	if(particleSystemNode->hasChild("isVisibleAtNight")){
		const XmlNode *isVisibleAtNightNode= particleSystemNode->getChild("isVisibleAtNight");
		isVisibleAtNight= isVisibleAtNightNode->getAttribute("value")->getBoolValue();
	}
	else {
		isVisibleAtNight=true;
	}

    //isVisibleAtDay
	if(particleSystemNode->hasChild("isVisibleAtDay")){
		const XmlNode *isVisibleAtDayNode= particleSystemNode->getChild("isVisibleAtDay");
		isVisibleAtDay= isVisibleAtDayNode->getAttribute("value")->getBoolValue();
	}
	else {
		isVisibleAtDay=true;
	}

    //isDaylightAffected
	if(particleSystemNode->hasChild("isDaylightAffected")){
		const XmlNode *node= particleSystemNode->getChild("isDaylightAffected");
		isDaylightAffected= node->getAttribute("value")->getBoolValue();
	}
	else {
		isDaylightAffected=false;
	}

	//radiusBasedStartenergy
	if(particleSystemNode->hasChild("radiusBasedStartenergy")){
		const XmlNode *isVisibleAtDayNode= particleSystemNode->getChild("radiusBasedStartenergy");
		radiusBasedStartenergy= isVisibleAtDayNode->getAttribute("value")->getBoolValue();
	}
	else{
		radiusBasedStartenergy= true;
	}

	//fixed
	const XmlNode *fixedNode= particleSystemNode->getChild("fixed");
	fixed= fixedNode->getAttribute("value")->getBoolValue();

	// delay
	if(particleSystemNode->hasChild("delay")) {
		const XmlNode* delayNode = particleSystemNode->getChild("delay");
		const float delay_secs = delayNode->getAttribute("value")->getFloatValue();
		if(delay_secs < 0)
			throw megaglest_runtime_error("particle effect delay cannot be negative");
		delay = (int)delay_secs * GameConstants::updateFps;
	} else{
		delay= 0;
	}

	// lifetime
	if(particleSystemNode->hasChild("lifetime")) {
		const XmlNode* lifetimeNode = particleSystemNode->getChild("lifetime");
		const float lifetime_secs = lifetimeNode->getAttribute("value")->getFloatValue();
		if(lifetime_secs < 0 && lifetime_secs != -1)
			throw megaglest_runtime_error("particle effect lifetime cannot be negative (-1 means inherited from parent particle)");
		lifetime = (int)lifetime_secs * GameConstants::updateFps;
	} else{
		lifetime= -1; //default
	}
}
コード例 #12
0
//====================================================================
TextFTGL::TextFTGL(FontTextHandlerType type) : Text(type) {

	//throw megaglest_runtime_error("FTGL!");
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",0);
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/arphic/uming.ttc",0); // Chinese
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/arphic/ukai.ttc",0); // Chinese
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ttf-sil-doulos/DoulosSILR.ttf",0); // Russian / Cyrillic
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ttf-sil-charis/CharisSILR.ttf",0); // Russian / Cyrillic
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf",0); // Russian / Cyrillic
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/takao/TakaoPGothic.ttf",0); // Japanese
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ttf-sil-scheherazade/ScheherazadeRegOT.ttf",0); // Arabic
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/linux-libertine/LinLibertine_Re.ttf",0); // Hebrew
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/unifont/unifont.ttf",0); // Czech?
	//setenv("MEGAGLEST_FONT","/usr/share/fonts/truetype/ttf-liberation/LiberationSans-Regular.ttf",0); // Czech?


	fontFile = findFont();
	//ftFont = new FTBufferFont(fontFile);
	//ftFont = new FTGLPixmapFont(fontFile);
	//ftFont = new FTGLExtrdFont(fontFile);
	//ftFont = new FTGLPolygonFont("/usr/share/fonts/truetype/arphic/uming.ttc");

	//ftFont = new FTGLPixmapFont("/usr/share/fonts/truetype/arphic/uming.ttc");
	if(type == ftht_2D) {
		ftFont = new FTGLPixmapFont(fontFile);
		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("2D font [%s]\n",fontFile);
	}
	else if(type == ftht_3D) {
		ftFont = new FTGLTextureFont(fontFile);
		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("3D font [%s]\n",fontFile);
	}
	else {
		throw megaglest_runtime_error("font render type not set to a known value!");
	}

	if(ftFont->Error())	{
		printf("FTGL: error loading font: %s\n", fontFile);
		delete ftFont; ftFont = NULL;
		free((void*)fontFile);
		fontFile = NULL;
		throw megaglest_runtime_error(string("FTGL: error loading font: ") + string(fontFile));
	}
	free((void*)fontFile);
	fontFile = NULL;

	const unsigned int defSize = 24;
	ftFont->FaceSize(defSize,TextFTGL::faceResolution);

	GLenum error = glGetError();
	if(error != GL_NO_ERROR) {
		printf("\n[%s::%s] Line %d Error = %d [%s] for size = %d res = %d\n",__FILE__,__FUNCTION__,__LINE__,error,gluErrorString(error),defSize,TextFTGL::faceResolution);
		fflush(stdout);
	}

	if(ftFont->Error())	{
		char szBuf[8096]="";
		snprintf(szBuf,8096,"FTGL: error setting face size, #%d",ftFont->Error());
		throw megaglest_runtime_error(szBuf);
	}
	//ftFont->UseDisplayList(false);
	//ftFont->CharMap(ft_encoding_gb2312);
	//ftFont->CharMap(ft_encoding_big5);
	if(ftFont->CharMap(ft_encoding_unicode) == false) {
		throw megaglest_runtime_error("FTGL: error setting encoding");
	}

	if(ftFont->Error())	{
		char szBuf[8096]="";
		snprintf(szBuf,8096,"FTGL: error setting encoding, #%d",ftFont->Error());
		throw megaglest_runtime_error(szBuf);
	}
}
コード例 #13
0
float TextFTGL::LineHeight(const char* str, const int len) {
	//FTBBox box = ftFont->BBox(str);
	//printf("String [%s] lineheight = %f upper_y = %f lower_y = %f\n",str,ftFont->LineHeight(),box.Upper().Y(),box.Lower().Y());


	//printf("ftFont->Ascender():%f ftFont->Descender()*-1 = %f ftFont->LineHeight() = %f\n",ftFont->Ascender(),ftFont->Descender()*-1 , ftFont->LineHeight());
	//return ftFont->Ascender() + ftFont->Descender()*-1 - ftFont->LineHeight();
	//return ftFont->LineHeight();

	//static float result = -1000;
	float result = -1000;
	if(result == -1000) {
		FTBBox box = ftFont->BBox(TextFTGL::langHeightText.c_str());

		GLenum error = glGetError();
		if(error != GL_NO_ERROR) {
			printf("\n[%s::%s] Line %d Error = %d [%s] for text [%s]\n",__FILE__,__FUNCTION__,__LINE__,error,gluErrorString(error),str);
			fflush(stdout);
		}

		result = box.Upper().Yf()- box.Lower().Yf();
		if(result == 0) {
			result = ftFont->LineHeight();

			GLenum error = glGetError();
			if(error != GL_NO_ERROR) {
				printf("\n[%s::%s] Line %d Error = %d [%s] for text [%s]\n",__FILE__,__FUNCTION__,__LINE__,error,gluErrorString(error),str);
				fflush(stdout);
			}
		}
		//printf("ftFont->BBox(''yW'')%f\n",result);
	}
//	else {
//		FTBBox box = ftFont->BBox(TextFTGL::langHeightText.c_str());
//
//		GLenum error = glGetError();
//		if(error != GL_NO_ERROR) {
//			printf("\n[%s::%s] Line %d Error = %d [%s] for text [%s]\n",__FILE__,__FUNCTION__,__LINE__,error,gluErrorString(error),str);
//			fflush(stdout);
//		}
//
//		int newresult = box.Upper().Y()- box.Lower().Y();
//		if(newresult == 0) {
//			newresult = ftFont->LineHeight();
//
//			GLenum error = glGetError();
//			if(error != GL_NO_ERROR) {
//				printf("\n[%s::%s] Line %d Error = %d [%s] for text [%s]\n",__FILE__,__FUNCTION__,__LINE__,error,gluErrorString(error),str);
//				fflush(stdout);
//			}
//		}
//
//		printf("Height for [%s] result [%d] [%d]\n",str,result,newresult);
//	}
	if(ftFont->Error())	{
		char szBuf[8096]="";
		snprintf(szBuf,8096,"FTGL: error trying to get lineheight, #%d",ftFont->Error());
		throw megaglest_runtime_error(szBuf);
	}

	return result;
//	printf("For str [%s] LineHeight = %f, result = %f\n",str, ftFont->LineHeight(),result);
//	return result;

	//float urx = box.Upper().X();
	//float llx = box.Lower().X();
	//float llx, lly, llz, urx, ury, urz;
	//ftFont->BBox(str, llx, lly, llz, urx, ury, urz);
	//return  ury - lly;

	//Short_t halign = fTextAlign/10;
	//Short_t valign = fTextAlign - 10*halign;
	//Float_t dx = 0, dy = 0;
//	switch (halign) {
//	  case 1 : dx =  0    ; break;
//	  case 2 : dx = -urx/2; break;
//	  case 3 : dx = -urx  ; break;
//	}
//	switch (valign) {
//	  case 1 : dy =  0    ; break;
//	  case 2 : dy = -ury/2; break;
//	  case 3 : dy = -ury  ; break;
//	}

	//printf("For str [%s] advance = %f, urx = %f, llx = %f\n",str, ftFont->Advance(str, len),urx,llx);
	//return urx;

}
コード例 #14
0
void TextFTGL::init(string fontName, string fontFamilyName, int fontSize) {
	cleanupFont();
	fontFile = findFont(fontName.c_str(),fontFamilyName.c_str());

	//ftFont = new FTBufferFont(fontFile);
	//ftFont = new FTGLPixmapFont(fontFile);
	//ftFont = new FTGLExtrdFont(fontFile);
	//ftFont = new FTGLPolygonFont("/usr/share/fonts/truetype/arphic/uming.ttc");
	//ftFont = new FTGLPixmapFont("/usr/share/fonts/truetype/arphic/uming.ttc");

	if(type == ftht_2D) {
		ftFont = new FTGLPixmapFont(fontFile);
		//printf("2D font [%s]\n",fontFile);
	}
	else if(type == ftht_3D) {
		ftFont = new FTGLTextureFont(fontFile);

		//ftFont = new FTBufferFont(fontFile);
		//ftFont = new FTGLExtrdFont(fontFile);
		//ftFont = new FTGLPolygonFont("/usr/share/fonts/truetype/arphic/uming.ttc");

		//printf("3D font [%s]\n",fontFile);
	}
	else {
		throw megaglest_runtime_error("font render type not set to a known value!");
	}

	if(ftFont->Error())	{
		printf("FTGL: error loading font: %s\n", fontFile);
		delete ftFont; ftFont = NULL;
		if(fontFile) {
			free((void*)fontFile);
		}
		fontFile = NULL;
		throw megaglest_runtime_error("FTGL: error loading font");
	}
	free((void*)fontFile);
	fontFile = NULL;

	if(fontSize <= 0) {
		fontSize = 24;
	}
	ftFont->FaceSize(fontSize,TextFTGL::faceResolution);

	GLenum error = glGetError();
	if(error != GL_NO_ERROR) {
		printf("\n[%s::%s] Line %d Error = %d [%s] for size = %d res = %d\n",__FILE__,__FUNCTION__,__LINE__,error,gluErrorString(error),fontSize,TextFTGL::faceResolution);
		fflush(stdout);
	}

	if(ftFont->Error())	{
		char szBuf[8096]="";
		snprintf(szBuf,8096,"FTGL: error setting face size, #%d",ftFont->Error());
		throw megaglest_runtime_error(szBuf);
	}

	//ftFont->UseDisplayList(false);
	//ftFont->CharMap(ft_encoding_gb2312);
	//ftFont->CharMap(ft_encoding_big5);
	if(ftFont->CharMap(ft_encoding_unicode) == false) {
		throw megaglest_runtime_error("FTGL: error setting encoding");
	}
	if(ftFont->Error())	{
		char szBuf[8096]="";
		snprintf(szBuf,8096,"FTGL: error setting encoding, #%d",ftFont->Error());
		throw megaglest_runtime_error(szBuf);
	}

	// Create a string containing common characters
	// and preload the chars without rendering them.
	string preloadText = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890-=!@#$%^&*()_+:\"{}[]/?.,<>\\';";
	ftFont->Advance(preloadText.c_str());

	error = glGetError();
	if(error != GL_NO_ERROR) {
		printf("\n[%s::%s] Line %d Error = %d [%s] for text [%s]\n",__FILE__,__FUNCTION__,__LINE__,error,gluErrorString(error),preloadText.c_str());
		fflush(stdout);
	}

	if(ftFont->Error())	{
		char szBuf[8096]="";
		snprintf(szBuf,8096,"FTGL: error advancing(a), #%d",ftFont->Error());
		throw megaglest_runtime_error(szBuf);
	}
}