SAssPiece* CAssParser::LoadPiece(SAssModel* model, aiNode* node, const LuaTable& metaTable)
{
	//! Create new piece
	++model->numPieces;
	SAssPiece* piece = new SAssPiece;
	piece->type = MODELTYPE_OTHER;
	piece->node = node;
	piece->model = model;
	piece->isEmpty = (node->mNumMeshes == 0);

	if (node->mParent) {
		piece->name = std::string(node->mName.data);
	} else {
		//FIXME is this really smart?
		piece->name = "root"; //! The real model root
	}

	//! find a new name if none given or if a piece with the same name already exists
	if (piece->name.empty()) {
		piece->name = "piece";
	}
	ModelPieceMap::const_iterator it = model->pieces.find(piece->name);
	if (it != model->pieces.end()) {
		char buf[64];
		int i = 0;
		while (it != model->pieces.end()) {
			SNPRINTF(buf, 64, "%s%02i", piece->name.c_str(), i++);
			it = model->pieces.find(buf);
		}
		piece->name = buf;
	}
	LOG_S(LOG_SECTION_PIECE, "Converting node '%s' to piece '%s' (%d meshes).",
			node->mName.data, piece->name.c_str(), node->mNumMeshes);

	//! Load additional piece properties from metadata
	const LuaTable& pieceTable = metaTable.SubTable("pieces").SubTable(piece->name);
	if (pieceTable.IsValid()) {
		LOG_S(LOG_SECTION_PIECE, "Found metadata for piece '%s'",
				piece->name.c_str());
	}

	//! Load transforms
	LoadPieceTransformations(piece, pieceTable);

	//! Update piece min/max extents
	for (unsigned meshListIndex = 0; meshListIndex < node->mNumMeshes; meshListIndex++) {
		unsigned int meshIndex = node->mMeshes[meshListIndex];
		SAssModel::MinMax& minmax = model->mesh_minmax[meshIndex];
		piece->mins.x = std::min(piece->mins.x, minmax.mins.x);
		piece->mins.y = std::min(piece->mins.y, minmax.mins.y);
		piece->mins.z = std::min(piece->mins.z, minmax.mins.z);
		piece->maxs.x = std::max(piece->maxs.x, minmax.maxs.x);
		piece->maxs.y = std::max(piece->maxs.y, minmax.maxs.y);
		piece->maxs.z = std::max(piece->maxs.z, minmax.maxs.z);
	}


	//! Check if piece is special (ie, used to set Spring model properties)
	if (strcmp(node->mName.data, "SpringHeight") == 0) {
		//! Set the model height to this nodes Z value
		if (!metaTable.KeyExists("height")) {
			model->height = piece->offset.z;
			LOG_S(LOG_SECTION_MODEL,
					"Model height of %f set by special node 'SpringHeight'",
					model->height);
		}
		--model->numPieces;
		delete piece;
		return NULL;
	}
	if (strcmp(node->mName.data, "SpringRadius") == 0) {
		if (!metaTable.KeyExists("midpos")) {
			model->relMidPos = float3(piece->offset.x, piece->offset.z, piece->offset.y); //! Y and Z are swapped because this piece isn't rotated
			LOG_S(LOG_SECTION_MODEL,
					"Model midpos of (%f,%f,%f) set by special node 'SpringRadius'",
					model->relMidPos.x, model->relMidPos.y, model->relMidPos.z);
		}
		if (!metaTable.KeyExists("radius")) {
			if (piece->maxs.x <= 0.00001f) {
				model->radius = piece->scale.x; //! the blender import script only sets the scale property
			} else {
				model->radius = piece->maxs.x; //! use the transformed mesh extents
			}
			LOG_S(LOG_SECTION_MODEL,
					"Model radius of %f set by special node 'SpringRadius'",
					model->radius);
		}
		--model->numPieces;
		delete piece;
		return NULL;
	}


	//! Get vertex data from node meshes
	for (unsigned meshListIndex = 0; meshListIndex < node->mNumMeshes; ++meshListIndex) {
		unsigned int meshIndex = node->mMeshes[meshListIndex];
		LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "Fetching mesh %d from scene",
				meshIndex);
		aiMesh* mesh = model->scene->mMeshes[meshIndex];
		std::vector<unsigned> mesh_vertex_mapping;
		//! extract vertex data
		LOG_SL(LOG_SECTION_PIECE, L_DEBUG,
				"Processing vertices for mesh %d (%d vertices)",
				meshIndex, mesh->mNumVertices);
		LOG_SL(LOG_SECTION_PIECE, L_DEBUG,
				"Normals: %s Tangents/Bitangents: %s TexCoords: %s",
				(mesh->HasNormals() ? "Y" : "N"),
				(mesh->HasTangentsAndBitangents() ? "Y" : "N"),
				(mesh->HasTextureCoords(0) ? "Y" : "N"));

		// FIXME add piece->vertices.reserve()
		for (unsigned vertexIndex= 0; vertexIndex < mesh->mNumVertices; ++vertexIndex) {
			SAssVertex vertex;

			//! vertex coordinates
			//LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "Fetching vertex %d from mesh", vertexIndex);
			const aiVector3D& aiVertex = mesh->mVertices[vertexIndex];
			vertex.pos.x = aiVertex.x;
			vertex.pos.y = aiVertex.y;
			vertex.pos.z = aiVertex.z;

			//LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "vertex position %d: %f %f %f", vertexIndex, vertex.pos.x, vertex.pos.y, vertex.pos.z);

			//! vertex normal
			LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "Fetching normal for vertex %d",
					vertexIndex);
			const aiVector3D& aiNormal = mesh->mNormals[vertexIndex];
			vertex.hasNormal = !IS_QNAN(aiNormal);
			if (vertex.hasNormal) {
				vertex.normal.x = aiNormal.x;
				vertex.normal.y = aiNormal.y;
				vertex.normal.z = aiNormal.z;
				//LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "vertex normal %d: %f %f %f",vertexIndex, vertex.normal.x, vertex.normal.y,vertex.normal.z);
			}

			//! vertex tangent, x is positive in texture axis
			if (mesh->HasTangentsAndBitangents()) {
				LOG_SL(LOG_SECTION_PIECE, L_DEBUG,
						"Fetching tangent for vertex %d", vertexIndex );
				const aiVector3D& aiTangent = mesh->mTangents[vertexIndex];
				const aiVector3D& aiBitangent = mesh->mBitangents[vertexIndex];
				vertex.hasTangent = !IS_QNAN(aiBitangent) && !IS_QNAN(aiTangent);

				const float3 tangent(aiTangent.x, aiTangent.y, aiTangent.z);
				//LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "vertex tangent %d: %f %f %f",vertexIndex, tangent.x, tangent.y,tangent.z);
				piece->sTangents.push_back(tangent);

				const float3 bitangent(aiBitangent.x, aiBitangent.y, aiBitangent.z);
				//LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "vertex bitangent %d: %f %f %f",vertexIndex, bitangent.x, bitangent.y,bitangent.z);
				piece->tTangents.push_back(bitangent);
			}

			//! vertex texcoords
			if (mesh->HasTextureCoords(0)) {
				vertex.textureX = mesh->mTextureCoords[0][vertexIndex].x;
				vertex.textureY = mesh->mTextureCoords[0][vertexIndex].y;
				//LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "vertex texcoords %d: %f %f", vertexIndex, vertex.textureX, vertex.textureY);
			}

			mesh_vertex_mapping.push_back(piece->vertices.size());
			piece->vertices.push_back(vertex);
		}

		//! extract face data
		// FIXME add piece->vertexDrawOrder.reserve()
		LOG_SL(LOG_SECTION_PIECE, L_DEBUG,
				"Processing faces for mesh %d (%d faces)",
				meshIndex, mesh->mNumFaces);
		for (unsigned faceIndex = 0; faceIndex < mesh->mNumFaces; ++faceIndex) {
			const aiFace& face = mesh->mFaces[faceIndex];
			//! get the vertex belonging to the mesh
			for (unsigned vertexListID = 0; vertexListID < face.mNumIndices; ++vertexListID) {
				unsigned int vertexID = mesh_vertex_mapping[face.mIndices[vertexListID]];
				//LOG_SL(LOG_SECTION_PIECE, L_DEBUG, "face %d vertex %d", faceIndex, vertexID);
				piece->vertexDrawOrder.push_back(vertexID);
			}
		}
	}

	//! collision volume for piece (not sure about these coords)
	// FIXME add metatable tags for this!!!!
	const float3 cvScales = piece->maxs - piece->mins;
	const float3 cvOffset = (piece->maxs - piece->offset) + (piece->mins - piece->offset);
	//const float3 cvOffset(piece->offset.x, piece->offset.y, piece->offset.z);
	piece->colvol = new CollisionVolume("box", cvScales, cvOffset, CollisionVolume::COLVOL_HITTEST_CONT);

	//! Get parent name from metadata or model
	if (pieceTable.KeyExists("parent")) {
		piece->parentName = pieceTable.GetString("parent", "");
	} else if (node->mParent) {
		if (node->mParent->mParent) {
			piece->parentName = std::string(node->mParent->mName.data);
		} else { //! my parent is the root, which gets renamed
			piece->parentName = "root";
		}
	} else {
		piece->parentName = "";
	}

	LOG_S(LOG_SECTION_PIECE, "Loaded model piece: %s with %d meshes",
			piece->name.c_str(), node->mNumMeshes);

	//! Verbose logging of piece properties
	LOG_S(LOG_SECTION_PIECE, "piece->name: %s", piece->name.c_str());
	LOG_S(LOG_SECTION_PIECE, "piece->parent: %s", piece->parentName.c_str());

	//! Recursively process all child pieces
	for (unsigned int i = 0; i < node->mNumChildren; ++i) {
		LoadPiece(model, node->mChildren[i], metaTable);
	}

	model->pieces[piece->name] = piece;
	return piece;
}
Example #2
0
/*-----------------------------------------------------------------*/
void
allocGlobal (symbol * sym)
{

  /* symbol name is internal name  */
  if (!sym->level)              /* local statics can come here */
    SNPRINTF (sym->rname, sizeof(sym->rname),
              "%s%s", port->fun_prefix, sym->name);

  /* add it to the operandKey reset */
  if (!isinSet (operKeyReset, sym)) {
    addSet(&operKeyReset, sym);
  }

  /* if this is a literal e.g. enumerated type */
  /* put it in the data segment & do nothing   */
  if (IS_LITERAL (sym->etype))
    {
      SPEC_OCLS (sym->etype) = data;
      return;
    }

  /* if this is a function then assign code space    */
  if (IS_FUNC (sym->type))
    {
      SPEC_OCLS (sym->etype) = code;
      /* if this is an interrupt service routine
         then put it in the interrupt service array */
      if (FUNC_ISISR (sym->type) && !options.noiv
          && (FUNC_INTNO (sym->type) != INTNO_UNSPEC))
            {
          if (interrupts[FUNC_INTNO (sym->type)])
            werror (E_INT_DEFINED,
                    FUNC_INTNO (sym->type),
                    interrupts[FUNC_INTNO (sym->type)]->name);
          else
            interrupts[FUNC_INTNO (sym->type)] = sym;

          /* automagically extend the maximum interrupts */
          if (FUNC_INTNO (sym->type) >= maxInterrupts)
            maxInterrupts = FUNC_INTNO (sym->type) + 1;
            }
      /* if it is not compiler defined */
      if (!sym->cdef)
        allocIntoSeg (sym);

      return;
    }

  /* if this is a bit variable and no storage class */
  if (IS_SPEC(sym->type) && SPEC_NOUN (sym->type) == V_BIT)
      /*&& SPEC_SCLS (sym->etype) == S_BIT*/
    {
      SPEC_OCLS (sym->type) = bit;
      allocIntoSeg (sym);
      return;
    }

  if(!TARGET_IS_PIC16 || (TARGET_IS_PIC16 && sym->level))
  /* register storage class ignored changed to FIXED */
  if (SPEC_SCLS (sym->etype) == S_REGISTER)
    SPEC_SCLS (sym->etype) = S_FIXED;

  /* if it is fixed, then allocate depending on the */
  /* current memory model, same for automatics      */
  if (SPEC_SCLS (sym->etype) == S_FIXED ||
      (TARGET_IS_PIC16 && (SPEC_SCLS (sym->etype) == S_REGISTER) && (sym->level==0)) ||
      SPEC_SCLS (sym->etype) == S_AUTO) {
    if (port->mem.default_globl_map != xdata) {
      /* set the output class */
      SPEC_OCLS (sym->etype) = port->mem.default_globl_map;
      /* generate the symbol  */
      allocIntoSeg (sym);
      return;
    } else {
      SPEC_SCLS (sym->etype) = S_XDATA;
    }
  }

  allocDefault (sym);
  return;
}
/*
Constructor.
Loading precalculated data.
*/
CPathEstimator::CPathEstimator(CPathFinder* pf, unsigned int BSIZE, unsigned int mmOpt, string name) :
pathFinder(pf),
BLOCK_SIZE(BSIZE),
BLOCK_PIXEL_SIZE(BSIZE * SQUARE_SIZE),
BLOCKS_TO_UPDATE(SQUARES_TO_UPDATE / (BLOCK_SIZE * BLOCK_SIZE) + 1),
moveMathOptions(mmOpt)
{
	//Gives the changes in (x,z) when moved one step in given direction.
	//(Need to be placed befor pre-calculations)
	directionVector[PATHDIR_LEFT].x = 1;
	directionVector[PATHDIR_LEFT].y = 0;
	directionVector[PATHDIR_LEFT_UP].x = 1;
	directionVector[PATHDIR_LEFT_UP].y = 1;
	directionVector[PATHDIR_UP].x = 0;
	directionVector[PATHDIR_UP].y = 1;
	directionVector[PATHDIR_RIGHT_UP].x = -1;
	directionVector[PATHDIR_RIGHT_UP].y = 1;
	directionVector[PATHDIR_RIGHT].x = -1;
	directionVector[PATHDIR_RIGHT].y = 0;
	directionVector[PATHDIR_RIGHT_DOWN].x = -1;
	directionVector[PATHDIR_RIGHT_DOWN].y = -1;
	directionVector[PATHDIR_DOWN].x = 0;
	directionVector[PATHDIR_DOWN].y = -1;
	directionVector[PATHDIR_LEFT_DOWN].x = 1;
	directionVector[PATHDIR_LEFT_DOWN].y = -1;

	goalSqrOffset.x=BLOCK_SIZE/2;
	goalSqrOffset.y=BLOCK_SIZE/2;

	//Creates the block-map and the vertices-map.
	nbrOfBlocksX = gs->mapx / BLOCK_SIZE;
	nbrOfBlocksZ = gs->mapy / BLOCK_SIZE;
	nbrOfBlocks = nbrOfBlocksX * nbrOfBlocksZ;

	blockState = new BlockInfo[nbrOfBlocks];
	nbrOfVertices = moveinfo->moveData.size() * nbrOfBlocks * PATH_DIRECTION_VERTICES;
	vertex = new float[nbrOfVertices];
	openBlockBufferPointer=openBlockBuffer;

	int i;
	for(i = 0; i < nbrOfVertices; i++)
		vertex[i] = PATHCOST_INFINITY;

	//Initialize blocks.
	int x, z;
	for(z = 0; z < nbrOfBlocksZ; z++){
		for(x = 0; x < nbrOfBlocksX; x++) {
			int blocknr = z * nbrOfBlocksX + x;
			blockState[blocknr].cost = PATHCOST_INFINITY;
			blockState[blocknr].options = 0;
			blockState[blocknr].parentBlock.x = -1;
			blockState[blocknr].parentBlock.y = -1;
			blockState[blocknr].sqrCenter = new int2[moveinfo->moveData.size()];
		}
	}

	//Pre-read/calculate data.
	PrintLoadMsg("Reading estimate path costs");
	if(!ReadFile(name)) {
		//Generate text-message.
		char calcMsg[1000], buffer[10];
		strcpy(calcMsg, "Analyzing map accessability \"");
		SNPRINTF(buffer,10,"%d",BLOCK_SIZE);
		strcat(calcMsg, buffer);
		strcat(calcMsg, "\"");
		PrintLoadMsg(calcMsg);
		//Calculating block-center-offsets.
		for(z = 0; z < nbrOfBlocksZ; z++) {
			for(x = 0; x < nbrOfBlocksX; x++) {
				vector<MoveData*>::iterator mi;
				for(mi = moveinfo->moveData.begin(); mi < moveinfo->moveData.end(); mi++) {
					FindOffset(**mi, x, z);
				}
			}
		}

		//Calculating vectors.
		vector<MoveData*>::iterator mi;
		for(mi = moveinfo->moveData.begin(); mi < moveinfo->moveData.end(); mi++) {
			//Generate text-message.
			char calcMsg[10000];
			sprintf(calcMsg,"Calculating estimate path costs \"%i\" %i/%i",BLOCK_SIZE,(*mi)->pathType,moveinfo->moveData.size());
			PrintLoadMsg(calcMsg);
			if(net) net->Update();	//prevent timeout 
			//Calculate
			for(z = 0; z < nbrOfBlocksZ; z++) {
				for(x = 0; x < nbrOfBlocksX; x++) {
					CalculateVertices(**mi, x, z);
				}
			}
		}
		WriteFile(name);
	}

	//As all vertexes are bidirectional and having equal values
	//in both directions, only one value are needed to be stored.
	//This vector helps getting the right vertex.
	//(Need to be placed after pre-calculations)
	directionVertex[PATHDIR_LEFT] = PATHDIR_LEFT;
	directionVertex[PATHDIR_LEFT_UP] = PATHDIR_LEFT_UP;
	directionVertex[PATHDIR_UP] = PATHDIR_UP;
	directionVertex[PATHDIR_RIGHT_UP] = PATHDIR_RIGHT_UP;
	directionVertex[PATHDIR_RIGHT] = int(PATHDIR_LEFT) - PATH_DIRECTION_VERTICES;
	directionVertex[PATHDIR_RIGHT_DOWN] = int(PATHDIR_LEFT_UP) - (nbrOfBlocksX * PATH_DIRECTION_VERTICES) - PATH_DIRECTION_VERTICES;
	directionVertex[PATHDIR_DOWN] = int(PATHDIR_UP) - (nbrOfBlocksX * PATH_DIRECTION_VERTICES);
	directionVertex[PATHDIR_LEFT_DOWN] = int(PATHDIR_RIGHT_UP) - (nbrOfBlocksX * PATH_DIRECTION_VERTICES) + PATH_DIRECTION_VERTICES;

	pathCache=new CPathCache(nbrOfBlocksX,nbrOfBlocksZ);
}
void CCommanderScript::Update(void)
{
	if (gs->frameNum != 0) {
		return;
	}

	if (gameSetup) {
		TdfParser p("gamedata/SIDEDATA.TDF");

		// make a map of all side names  (assumes contiguous sections)
		std::map<string, string> sideMap;
		char sideText[64];
		for (int side = 0;
				 SNPRINTF(sideText, sizeof(sideText), "side%i", side),
				 p.SectionExist(sideText); // the test
				 side++) {
			const string sideName =
				StringToLower(p.SGetValueDef("arm", string(sideText) + "\\name"));
			sideMap[sideName] = sideText;
		}

		// setup the teams
		for (int a = 0; a < gs->activeTeams; ++a) {

			// don't spawn a commander for the gaia team
			if (gs->useLuaGaia && a == gs->gaiaTeamID)
				continue;

			CTeam* team = gs->Team(a);
			if (team->gaia) continue;

			// remove the pre-existing storage except for a small amount
			float ms=team->metalStorage,es=team->energyStorage;
			team->metalStorage  = 20;
			team->energyStorage  = 20;

			// create a GlobalAI if required
			if (!gameSetup->aiDlls[a].empty() &&
			    (gu->myPlayerNum == team->leader)) {
				globalAI->CreateGlobalAI(a, gameSetup->aiDlls[a].c_str());
			}

			std::map<string, string>::const_iterator it = sideMap.find(team->side);

			if (it != sideMap.end()) {
				const string& sideSection = it->second;
				const string cmdrType =
					p.SGetValueDef("armcom", sideSection + "\\commander");

				// make sure the commander has the right amount of storage
//				UnitDef* ud = unitDefHandler->GetUnitByName(cmdrType);
//				ud->metalStorage  = team->metalStorage;
//				ud->energyStorage = team->energyStorage;

				CUnit* unit =
					unitLoader.LoadUnit(cmdrType, team->startPos, a, false, 0, NULL);

				team->lineageRoot = unit->id;
				unit->SetMetalStorage(ms);
				unit->SetEnergyStorage(es);
			}

			// now remove the pre-existing storage except for a small amount
//			team->metalStorage  = (team->metalStorage  / 2) + 20;
//			team->energyStorage = (team->energyStorage / 2) + 20;
		}
	}
	else {
		TdfParser p("gamedata/SIDEDATA.TDF");
		const string s0 = p.SGetValueDef("armcom", "side0\\commander");
		const string s1 = p.SGetValueDef("corcom", "side1\\commander");

		TdfParser p2;
		CReadMap::OpenTDF(stupidGlobalMapname, p2);

		float x0, x1, z0, z1;
		p2.GetDef(x0, "1000", "MAP\\TEAM0\\StartPosX");
		p2.GetDef(z0, "1000", "MAP\\TEAM0\\StartPosZ");
		p2.GetDef(x1, "1200", "MAP\\TEAM1\\StartPosX");
		p2.GetDef(z1, "1200", "MAP\\TEAM1\\StartPosZ");

		unitLoader.LoadUnit(s0, float3(x0, 80.0f, z0), 0, false, 0, NULL);
		unitLoader.LoadUnit(s1, float3(x1, 80.0f, z1), 1, false, 0, NULL);
	}
}
Example #5
0
void CSm3ReadMap::Initialize (const char *mapname)
{
	try {
		string lmsg = "Loading " + string(mapname);
		PrintLoadMsg(lmsg.c_str());
		GLint tu;
		glGetIntegerv(GL_MAX_TEXTURE_UNITS, &tu);

		renderer = SAFE_NEW terrain::Terrain;

		renderer->config.cacheTextures=false;

		renderer->config.forceFallbackTexturing = !!configHandler.GetInt("SM3ForceFallbackTex", 0);

		if (!renderer->config.forceFallbackTexturing && GLEW_ARB_fragment_shader && GLEW_ARB_shading_language_100) {
			renderer->config.useBumpMaps = true;
			renderer->config.anisotropicFiltering = 0.0f;
		}

		renderer->config.useStaticShadow = false;

		renderer->config.terrainNormalMaps = false;
		renderer->config.normalMapLevel = 3;

		if (shadowHandler->drawShadows)
			renderer->config.useShadowMaps = true;

		if (!mapInfo->sm3.minimap.empty()) {
			CBitmap bmp;
			if(bmp.Load(mapInfo->sm3.minimap))
				minimapTexture=bmp.CreateTexture(true);
		}

/*		int numStages=atoi(mapDefParser.SGetValueDef("0", "map\\terrain\\numtexturestages").c_str());
		int maxStages=configHandler.GetInt("SM3MaxTextureStages", 10);
		if (numStages > maxStages) {
			renderer->config.cacheTextures = true;
			renderer->config.cacheTextureSize = 256;
		//	renderer->config.detailMod
		}
*/
		Sm3LoadCB loadcb;
		terrain::LightingInfo lightInfo;
		lightInfo.ambient = mapInfo->light.groundAmbientColor;
		terrain::StaticLight light;
		light.color = mapInfo->light.groundSunColor;
		light.directional = false;
		light.position = mapInfo->light.sunDir *1000000;
		lightInfo.staticLights.push_back (light);
		renderer->Load (GetMapDefParser(), &lightInfo, &loadcb);

		height = width = renderer->GetHeightmapWidth ()-1;

		// Set global map info
		gs->mapx=width;
		gs->mapy=height;
		gs->mapSquares = width*height;
		gs->hmapx=width/2;
		gs->hmapy=height/2;
		gs->pwr2mapx=next_power_of_2(width);
		gs->pwr2mapy=next_power_of_2(height);

		float3::maxxpos=width*SQUARE_SIZE-1;
		float3::maxzpos=height*SQUARE_SIZE-1;

		CReadMap::Initialize();

		const TdfParser& mapDefParser = GetMapDefParser();
		if (mapDefParser.SectionExist("map\\featuretypes")) {
			int numTypes = atoi(mapDefParser.SGetValueDef("0", "map\\featuretypes\\numtypes").c_str());
			for (int a=0;a<numTypes;a++) {
				char loc[100];
				SNPRINTF(loc, 100, "map\\featuretypes\\type%d", a);
				featureTypes.push_back (SAFE_NEW std::string(mapDefParser.SGetValueDef("TreeType0", loc)));
			}
		}
		LoadFeatureData();

		groundDrawer = SAFE_NEW CSm3GroundDrawer (this);
	}
	catch(content_error& e)
	{
		ErrorMessageBox(e.what(), "Error:", MBF_OK);
	}
}
Example #6
0
/** Print out a stacktrace. */
static void Stacktrace(LPEXCEPTION_POINTERS e, HANDLE hThread = INVALID_HANDLE_VALUE) {
	PIMAGEHLP_SYMBOL pSym;
	STACKFRAME sf;
	HANDLE process, thread;
	DWORD dwModBase, Disp;
	BOOL more = FALSE;
	int count = 0;
	char modname[MAX_PATH];

	pSym = (PIMAGEHLP_SYMBOL)GlobalAlloc(GMEM_FIXED, 16384);

	BOOL suspended = FALSE;
	CONTEXT c;
	if (e) {
		c = *e->ContextRecord;
		thread = GetCurrentThread();
	} else {
		SuspendThread(hThread);
		suspended = TRUE;
		memset(&c, 0, sizeof(CONTEXT));
		c.ContextFlags = CONTEXT_FULL;
		// FIXME: This does not work if you want to dump the current thread's stack
		if (!GetThreadContext(hThread, &c)) {
			ResumeThread(hThread);
			return;
		}
		thread = hThread;
	}

	ZeroMemory(&sf, sizeof(sf));
	sf.AddrPC.Offset = c.Eip;
	sf.AddrStack.Offset = c.Esp;
	sf.AddrFrame.Offset = c.Ebp;
	sf.AddrPC.Mode = AddrModeFlat;
	sf.AddrStack.Mode = AddrModeFlat;
	sf.AddrFrame.Mode = AddrModeFlat;

	process = GetCurrentProcess();

	// use globalalloc to reduce risk for allocator related deadlock
	char* printstrings = (char*)GlobalAlloc(GMEM_FIXED, 0);

	bool containsOglDll = false;
	while (true) {
		more = StackWalk(
			IMAGE_FILE_MACHINE_I386, // TODO: fix this for 64 bit windows?
			process,
			thread,
			&sf,
			&c,
			NULL,
			SymFunctionTableAccess,
			SymGetModuleBase,
			NULL
		);
		if (!more || sf.AddrFrame.Offset == 0) {
			break;
		}

		dwModBase = SymGetModuleBase(process, sf.AddrPC.Offset);

		if (dwModBase) {
			GetModuleFileName((HINSTANCE)dwModBase, modname, MAX_PATH);
		} else {
			strcpy(modname, "Unknown");
		}

		pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
		pSym->MaxNameLength = MAX_PATH;

		char *printstringsnew = (char *)GlobalAlloc(GMEM_FIXED, (count + 1) * BUFFER_SIZE);
		memcpy(printstringsnew, printstrings, count * BUFFER_SIZE);
		GlobalFree(printstrings);
		printstrings = printstringsnew;

		if (SymGetSymFromAddr(process, sf.AddrPC.Offset, &Disp, pSym)) {
			// This is the code path taken on VC if debugging syms are found.
			SNPRINTF(printstrings + count * BUFFER_SIZE, BUFFER_SIZE, "(%d) %s(%s+%#0lx) [0x%08lX]", count, modname, pSym->Name, Disp, sf.AddrPC.Offset);
		} else {
			// This is the code path taken on MinGW, and VC if no debugging syms are found.
			SNPRINTF(printstrings + count * BUFFER_SIZE, BUFFER_SIZE, "(%d) %s [0x%08lX]", count, modname, sf.AddrPC.Offset);
		}

		// OpenGL lib names (ATI): "atioglxx.dll" "atioglx2.dll"
		containsOglDll = containsOglDll || strstr(modname, "atiogl");
		// OpenGL lib names (Nvidia): "nvoglnt.dll" "nvoglv32.dll" "nvoglv64.dll" (last one is a guess)
		containsOglDll = containsOglDll || strstr(modname, "nvogl");

		++count;
	}

	if (containsOglDll) {
		PRINT("This stack trace indicates a problem with your graphic card driver. "
		      "Please try upgrading or downgrading it. "
		      "Specifically recommended is the latest driver, and one that is as old as your graphic card. "
		      "Make sure to use a driver removal utility, before installing other drivers.");
	}

	if (suspended) {
		ResumeThread(hThread);
	}

	for (int i = 0; i < count; ++i) {
		PRINT("%s", printstrings + i * BUFFER_SIZE);
	}

	GlobalFree(printstrings);

	GlobalFree(pSym);
}
Example #7
0
bool PortParameters::FillParametersStr(char *pParameters, int size, bool detail)
{
  int len;

  len = SNPRINTF(pParameters, size, "PortName=%s",
                 (maskExplicit & m_portName) ? portName : (detail ? phPortName : "-"));

  if (len < 0)
    return FALSE;

  pParameters += len;
  size -= len;

  if (maskExplicit & m_realPortName) {
    len = SNPRINTF(pParameters, size, ",RealPortName=%s", realPortName);

    if (len < 0)
      return FALSE;

    pParameters += len;
    size -= len;
  }

  for (int i = 0 ; i < sizeof(bits)/sizeof(bits[0]) ; i++) {
    DWORD bit = bits[i].bit;

    if (!GetDwPtr(bit))
      continue;

    const char *pName = GetBitName(bit);

    if (pName) {
      const DWORD *pBit;

      if ((maskExplicit & bit) != 0)
        pBit = GetDwPtr(bit);
      else
      if (detail)
        pBit = GetDwPtrDefault(bit);
      else
        continue;

      if (pBit == NULL)
        continue;

      if (bits[i].type == Bit::FLAG) {
        len = SNPRINTF(pParameters, size, ",%s=%s", pName, *pBit ? "yes" : "no");
      }
      else
      if (bits[i].type == Bit::PIN) {
        const char *pVal = NULL;

        switch (*pBit & ~C0C_PIN_NEGATIVE) {
          case C0C_PIN_RRTS:  pVal = "rrts";  break;
          case C0C_PIN_RDTR:  pVal = "rdtr";  break;
          case C0C_PIN_ROUT1: pVal = "rout1"; break;
          case C0C_PIN_ROUT2: pVal = "rout2"; break;
          case C0C_PIN_ROPEN: pVal = "ropen"; break;
          case C0C_PIN_LRTS:  pVal = "lrts";  break;
          case C0C_PIN_LDTR:  pVal = "ldtr";  break;
          case C0C_PIN_LOUT1: pVal = "lout1"; break;
          case C0C_PIN_LOUT2: pVal = "lout2"; break;
          case C0C_PIN_LOPEN: pVal = "lopen"; break;
          case C0C_PIN_ON:    pVal = "on";    break;
        }

        if (pVal == NULL)
          continue;

        len = SNPRINTF(pParameters, size, ",%s=%s%s", pName, (*pBit & C0C_PIN_NEGATIVE) == 0 ? "" : "!", pVal);
      }
      else
      if (bits[i].type == Bit::PROBABILITY) {
          if (*pBit == 0) {
            len = SNPRINTF(pParameters, size, ",%s=0", pName);
          } else {
            char strVal[11] = "";
            char digits[11];

            SNPRINTF(digits, sizeof(digits)/sizeof(digits[0]), "%ld", (unsigned long)*pBit);

            for (int i = lstrlen(digits) ; i ; i--) {
              if (digits[i - 1] > '0')
                break;

              digits[i - 1] = 0;
            }

            const char *p = digits;

            for (DWORD one = C0C_PROBABILITY_ONE/10 ; one > 0 ; one /= 10) {
              if (one > *pBit) {
                lstrcat(strVal, "0");
              }
              else
              if (*p) {
                char sc[2];

                sc[0] = *p++;
                sc[1] = 0;
                lstrcat(strVal, sc);
              }
              else {
                break;
              }
            }

            len = SNPRINTF(pParameters, size, ",%s=0.%s", pName, strVal);
          }
      }
      else
      if (bits[i].type == Bit::UNSIGNED) {
        len = SNPRINTF(pParameters, size, ",%s=%lu", pName, (unsigned long)*pBit);
      }

      if (len < 0)
        return FALSE;

      pParameters += len;
      size -= len;
    }
  }

  return TRUE;
}
std::string
PyMeshAttributes_ToString(const MeshAttributes *atts, const char *prefix)
{
    std::string str;
    char tmpStr[1000];

    if(atts->GetLegendFlag())
        SNPRINTF(tmpStr, 1000, "%slegendFlag = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%slegendFlag = 0\n", prefix);
    str += tmpStr;
    const char *lineStyle_values[] = {"SOLID", "DASH", "DOT", "DOTDASH"};
    SNPRINTF(tmpStr, 1000, "%slineStyle = %s%s  # SOLID, DASH, DOT, DOTDASH\n", prefix, prefix, lineStyle_values[atts->GetLineStyle()]);
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%slineWidth = %d\n", prefix, atts->GetLineWidth());
    str += tmpStr;
    const unsigned char *meshColor = atts->GetMeshColor().GetColor();
    SNPRINTF(tmpStr, 1000, "%smeshColor = (%d, %d, %d, %d)\n", prefix, int(meshColor[0]), int(meshColor[1]), int(meshColor[2]), int(meshColor[3]));
    str += tmpStr;
    const char *meshColorSource_names = "Foreground, MeshCustom";
    switch (atts->GetMeshColorSource())
    {
      case MeshAttributes::Foreground:
          SNPRINTF(tmpStr, 1000, "%smeshColorSource = %sForeground  # %s\n", prefix, prefix, meshColorSource_names);
          str += tmpStr;
          break;
      case MeshAttributes::MeshCustom:
          SNPRINTF(tmpStr, 1000, "%smeshColorSource = %sMeshCustom  # %s\n", prefix, prefix, meshColorSource_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    const char *opaqueColorSource_names = "Background, OpaqueCustom";
    switch (atts->GetOpaqueColorSource())
    {
      case MeshAttributes::Background:
          SNPRINTF(tmpStr, 1000, "%sopaqueColorSource = %sBackground  # %s\n", prefix, prefix, opaqueColorSource_names);
          str += tmpStr;
          break;
      case MeshAttributes::OpaqueCustom:
          SNPRINTF(tmpStr, 1000, "%sopaqueColorSource = %sOpaqueCustom  # %s\n", prefix, prefix, opaqueColorSource_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    const char *opaqueMode_names = "Auto, On, Off";
    switch (atts->GetOpaqueMode())
    {
      case MeshAttributes::Auto:
          SNPRINTF(tmpStr, 1000, "%sopaqueMode = %sAuto  # %s\n", prefix, prefix, opaqueMode_names);
          str += tmpStr;
          break;
      case MeshAttributes::On:
          SNPRINTF(tmpStr, 1000, "%sopaqueMode = %sOn  # %s\n", prefix, prefix, opaqueMode_names);
          str += tmpStr;
          break;
      case MeshAttributes::Off:
          SNPRINTF(tmpStr, 1000, "%sopaqueMode = %sOff  # %s\n", prefix, prefix, opaqueMode_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    SNPRINTF(tmpStr, 1000, "%spointSize = %g\n", prefix, atts->GetPointSize());
    str += tmpStr;
    const unsigned char *opaqueColor = atts->GetOpaqueColor().GetColor();
    SNPRINTF(tmpStr, 1000, "%sopaqueColor = (%d, %d, %d, %d)\n", prefix, int(opaqueColor[0]), int(opaqueColor[1]), int(opaqueColor[2]), int(opaqueColor[3]));
    str += tmpStr;
    const char *smoothingLevel_names = "None, Fast, High";
    switch (atts->GetSmoothingLevel())
    {
      case MeshAttributes::None:
          SNPRINTF(tmpStr, 1000, "%ssmoothingLevel = %sNone  # %s\n", prefix, prefix, smoothingLevel_names);
          str += tmpStr;
          break;
      case MeshAttributes::Fast:
          SNPRINTF(tmpStr, 1000, "%ssmoothingLevel = %sFast  # %s\n", prefix, prefix, smoothingLevel_names);
          str += tmpStr;
          break;
      case MeshAttributes::High:
          SNPRINTF(tmpStr, 1000, "%ssmoothingLevel = %sHigh  # %s\n", prefix, prefix, smoothingLevel_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    if(atts->GetPointSizeVarEnabled())
        SNPRINTF(tmpStr, 1000, "%spointSizeVarEnabled = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%spointSizeVarEnabled = 0\n", prefix);
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%spointSizeVar = \"%s\"\n", prefix, atts->GetPointSizeVar().c_str());
    str += tmpStr;
    const char *pointType_names = "Box, Axis, Icosahedron, Octahedron, Tetrahedron, "
        "SphereGeometry, Point, Sphere";
    switch (atts->GetPointType())
    {
      case MeshAttributes::Box:
          SNPRINTF(tmpStr, 1000, "%spointType = %sBox  # %s\n", prefix, prefix, pointType_names);
          str += tmpStr;
          break;
      case MeshAttributes::Axis:
          SNPRINTF(tmpStr, 1000, "%spointType = %sAxis  # %s\n", prefix, prefix, pointType_names);
          str += tmpStr;
          break;
      case MeshAttributes::Icosahedron:
          SNPRINTF(tmpStr, 1000, "%spointType = %sIcosahedron  # %s\n", prefix, prefix, pointType_names);
          str += tmpStr;
          break;
      case MeshAttributes::Octahedron:
          SNPRINTF(tmpStr, 1000, "%spointType = %sOctahedron  # %s\n", prefix, prefix, pointType_names);
          str += tmpStr;
          break;
      case MeshAttributes::Tetrahedron:
          SNPRINTF(tmpStr, 1000, "%spointType = %sTetrahedron  # %s\n", prefix, prefix, pointType_names);
          str += tmpStr;
          break;
      case MeshAttributes::SphereGeometry:
          SNPRINTF(tmpStr, 1000, "%spointType = %sSphereGeometry  # %s\n", prefix, prefix, pointType_names);
          str += tmpStr;
          break;
      case MeshAttributes::Point:
          SNPRINTF(tmpStr, 1000, "%spointType = %sPoint  # %s\n", prefix, prefix, pointType_names);
          str += tmpStr;
          break;
      case MeshAttributes::Sphere:
          SNPRINTF(tmpStr, 1000, "%spointType = %sSphere  # %s\n", prefix, prefix, pointType_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    if(atts->GetShowInternal())
        SNPRINTF(tmpStr, 1000, "%sshowInternal = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%sshowInternal = 0\n", prefix);
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%spointSizePixels = %d\n", prefix, atts->GetPointSizePixels());
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%sopacity = %g\n", prefix, atts->GetOpacity());
    str += tmpStr;
    return str;
}
std::string
PyViewerClientAttributes_ToString(const ViewerClientAttributes *atts, const char *prefix)
{
    std::string str;
    char tmpStr[1000];

    const char *renderingType_names = "None, Image, Data";
    switch (atts->GetRenderingType())
    {
      case ViewerClientAttributes::None:
          SNPRINTF(tmpStr, 1000, "%srenderingType = %sNone  # %s\n", prefix, prefix, renderingType_names);
          str += tmpStr;
          break;
      case ViewerClientAttributes::Image:
          SNPRINTF(tmpStr, 1000, "%srenderingType = %sImage  # %s\n", prefix, prefix, renderingType_names);
          str += tmpStr;
          break;
      case ViewerClientAttributes::Data:
          SNPRINTF(tmpStr, 1000, "%srenderingType = %sData  # %s\n", prefix, prefix, renderingType_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    SNPRINTF(tmpStr, 1000, "%sid = %d\n", prefix, atts->GetId());
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%stitle = \"%s\"\n", prefix, atts->GetTitle().c_str());
    str += tmpStr;
    {   const intVector &windowIds = atts->GetWindowIds();
        SNPRINTF(tmpStr, 1000, "%swindowIds = (", prefix);
        str += tmpStr;
        for(size_t i = 0; i < windowIds.size(); ++i)
        {
            SNPRINTF(tmpStr, 1000, "%d", windowIds[i]);
            str += tmpStr;
            if(i < windowIds.size() - 1)
            {
                SNPRINTF(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        SNPRINTF(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    SNPRINTF(tmpStr, 1000, "%simageWidth = %d\n", prefix, atts->GetImageWidth());
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%simageHeight = %d\n", prefix, atts->GetImageHeight());
    str += tmpStr;
    SNPRINTF(tmpStr, 1000, "%simageResolutionPcnt = %g\n", prefix, atts->GetImageResolutionPcnt());
    str += tmpStr;
    if(atts->GetExternalClient())
        SNPRINTF(tmpStr, 1000, "%sexternalClient = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%sexternalClient = 0\n", prefix);
    str += tmpStr;
    return str;
}
Example #10
0
static char *
parseIvalAst (ast *node, int *inCodeSpace) {
#define LEN 4096
    char *buffer = NULL;
    char *left, *right;

    if (IS_AST_VALUE(node)) {
        value *val = AST_VALUE(node);
        symbol *sym = IS_AST_SYM_VALUE(node) ? AST_SYMBOL(node) : NULL;
        if (inCodeSpace && val->type
                && (IS_FUNC(val->type) || IS_CODE(getSpec(val->type))))
        {
            *inCodeSpace = 1;
        }
        if (inCodeSpace && sym
                && (IS_FUNC(sym->type)
                    || IS_CODE(getSpec(sym->type))))
        {
            *inCodeSpace = 1;
        }

        DEBUGprintf ("%s: AST_VALUE\n", __FUNCTION__);
        if (IS_AST_LIT_VALUE(node)) {
            buffer = Safe_alloc(LEN);
            SNPRINTF(buffer, LEN, "0x%lx", AST_ULONG_VALUE (node));
        } else if (IS_AST_SYM_VALUE(node)) {
            assert ( AST_SYMBOL(node) );
            /*
            printf ("sym %s: ", AST_SYMBOL(node)->rname);
            printTypeChain(AST_SYMBOL(node)->type, stdout);
            printTypeChain(AST_SYMBOL(node)->etype, stdout);
            printf ("\n---sym %s: done\n", AST_SYMBOL(node)->rname);
            */
            buffer = Safe_strdup(AST_SYMBOL(node)->rname);
        } else {
            assert ( !"Invalid values type for initializers in AST." );
        }
    } else if (IS_AST_OP(node)) {
        DEBUGprintf ("%s: AST_OP\n", __FUNCTION__);
        switch (node->opval.op) {
        case CAST:
            assert (node->right);
            buffer = parseIvalAst(node->right, inCodeSpace);
            DEBUGprintf ("%s: %s\n", __FUNCTION__, buffer);
            break;
        case '&':
            assert ( node->left && !node->right );
            buffer = parseIvalAst(node->left, inCodeSpace);
            DEBUGprintf ("%s: %s\n", __FUNCTION__, buffer);
            break;
        case '+':
            assert (node->left && node->right );
            left = parseIvalAst(node->left, inCodeSpace);
            right = parseIvalAst(node->right, inCodeSpace);
            buffer = Safe_alloc(LEN);
            SNPRINTF(buffer, LEN, "(%s + %s)", left, right);
            DEBUGprintf ("%s: %s\n", __FUNCTION__, buffer);
            Safe_free(left);
            Safe_free(right);
            break;
        case '[':
            assert ( node->left && node->right );
            assert ( IS_AST_VALUE(node->left) && AST_VALUE(node->left)->sym );
            right = parseIvalAst(node->right, inCodeSpace);
            buffer = Safe_alloc(LEN);
            SNPRINTF(buffer, LEN, "(%s + %u * %s)",
                    AST_VALUE(node->left)->sym->rname, getSize(AST_VALUE(node->left)->type), right);
            Safe_free(right);
            DEBUGprintf ("%s: %s\n", __FUNCTION__, &buffer[0]);
            break;
        default:
            assert ( !"Unhandled operation in initializer." );
            break;
        }
    } else {
        assert ( !"Invalid construct in initializer." );
    }

    return (buffer);
}
Example #11
0
/* Note about usage of this function : Create dummy gd_region, gd_segment, file_control,
 * unix_db_info, sgmnt_addrs, and allocate mutex_struct (and NUM_CRIT_ENTRY * mutex_que_entry),
 * mutex_spin_parms_struct, and node_local in shared memory. Initialize the fields as in
 * jnlpool_init(). Pass the address of the dummy region as argument to this function.
 */
boolean_t grab_lock(gd_region *reg, boolean_t is_blocking_wait, uint4 onln_rlbk_action)
{
	unix_db_info 		*udi;
	sgmnt_addrs		*csa;
	enum cdb_sc		status;
	mutex_spin_parms_ptr_t	mutex_spin_parms;
	char			scndry_msg[OUT_BUFF_SIZE];
#	ifdef DEBUG
	DCL_THREADGBL_ACCESS;

	SETUP_THREADGBL_ACCESS;
#	endif
	udi = FILE_INFO(reg);
	csa = &udi->s_addrs;
	assert(!csa->hold_onto_crit);
	assert(!csa->now_crit);
	if (!csa->now_crit)
	{
		assert(0 == crit_count);
		crit_count++;	/* prevent interrupts */
		DEBUG_ONLY(locknl = csa->nl);	/* for DEBUG_ONLY LOCK_HIST macro */
		mutex_spin_parms = (mutex_spin_parms_ptr_t)((sm_uc_ptr_t)csa->critical + JNLPOOL_CRIT_SPACE);
		/* This assumes that mutex_spin_parms_t is located immediately after the crit structures */
		/* As of 10/07/98, crashcnt field in mutex_struct is not changed by any function for the dummy  region */
		if (is_blocking_wait)
			status = mutex_lockw(reg, mutex_spin_parms, 0);
		else
			status = mutex_lockwim(reg, mutex_spin_parms, 0);
		DEBUG_ONLY(locknl = NULL);	/* restore "locknl" to default value */
		if (status != cdb_sc_normal)
		{
			crit_count = 0;
			switch(status)
			{
				case cdb_sc_critreset: /* As of 10/07/98, this return value is not possible */
					rts_error_csa(CSA_ARG(NULL) VARLSTCNT(4) ERR_CRITRESET, 2, REG_LEN_STR(reg));
				case cdb_sc_dbccerr:
					rts_error_csa(CSA_ARG(NULL) VARLSTCNT(4) ERR_DBCCERR, 2, REG_LEN_STR(reg));
				case cdb_sc_nolock:
					return FALSE;
				default:
					assertpro(FALSE && status);
			}
			return FALSE;
		}
		/* There is only one case we know of when csa->nl->in_crit can be non-zero and that is when a process holding
		 * crit gets kill -9ed and another process ends up invoking "secshr_db_clnup" which in turn clears the
		 * crit semaphore (making it available for waiters) but does not also clear csa->nl->in_crit since it does not
		 * hold crit at that point. But in that case, the pid reported in csa->nl->in_crit should be dead. Check that.
		 */
		assert((0 == csa->nl->in_crit) || (FALSE == is_proc_alive(csa->nl->in_crit, 0)));
		csa->nl->in_crit = process_id;
		CRIT_TRACE(crit_ops_gw);		/* see gdsbt.h for comment on placement */
		crit_count = 0;
		if (jnlpool.repl_inst_filehdr->file_corrupt && !jgbl.onlnrlbk)
		{	/* Journal pool indicates an abnormally terminated online rollback. Cannot continue until the rollback
			 * command is re-run to bring the journal pool/file and instance file to a consistent state.
			 */
			SNPRINTF(scndry_msg, OUT_BUFF_SIZE, "Instance file header has file_corrupt field set to TRUE");
			/* No need to do rel_lock before rts_error (mupip_exit_handler will do it for us) - BYPASSOK rts_error */
			rts_error_csa(CSA_ARG(NULL) VARLSTCNT(8) ERR_REPLREQROLLBACK, 2, LEN_AND_STR(udi->fn),
					ERR_TEXT, 2, LEN_AND_STR(scndry_msg));
		}
		/* If ASSERT_NO_ONLINE_ROLLBACK, then no concurrent online rollbacks can happen at this point. So, the jnlpool
		 * should be in in sync. There are two exceptions. If this is GT.CM GNP Server and the last client disconnected, the
		 * server invokes gtcmd_rundown which in-turn invokes gds_rundown thereby running down all active databases at this
		 * point but leaves the journal pool up and running. Now, if an online rollback is attempted, it increments the
		 * onln_rlbk_cycle in the journal pool, but csa->onln_rlbk_cycle is not synced yet. So, the grab_crit done in t_end
		 * will NOT detect a concurrent online rollback and it doesn't need to because the rollback happened AFTER the
		 * rundown. Assert that this is the only case we know of for the cycles to be out-of-sync. In PRO
		 * jnlpool_ctl->onln_rlbk_cycle is used only by the replication servers (which GT.CM is not) and so even if it
		 * continues with an out-of-sync csa->onln_rlbk_cycle, t_end logic does the right thing. The other exception is if
		 * GT.M initialized journal pool while opening database (belonging to a different instance) in gvcst_init (for
		 * anticipatory freeze) followed by an online rollback which increments the jnlpool_ctl->onln_rlbk_cycle but leaves
		 * the repl_csa->onln_rlbk_cycle out-of-sync. At this point, if a replicated database is open for the first time,
		 * we'll reach t_end to commit the update but will end up failing the below assert due to the out-of-sync
		 * onln_rlbk_cycle. So, assert accordingly. Note : even though the cycles are out-of-sync they are not an issue for
		 * GT.M because it always relies on the onln_rlbk_cycle from csa->nl and not from repl_csa. But, we don't remove the
		 * assert as it is valuable for replication servers (Source, Receiver and Update Process).
		 */
		assert((ASSERT_NO_ONLINE_ROLLBACK != onln_rlbk_action)
		       || (csa->onln_rlbk_cycle == jnlpool.jnlpool_ctl->onln_rlbk_cycle) || IS_GTCM_GNP_SERVER_IMAGE
		       || (jnlpool_init_needed && INST_FREEZE_ON_ERROR_POLICY));
		if ((HANDLE_CONCUR_ONLINE_ROLLBACK == onln_rlbk_action)
		    && (csa->onln_rlbk_cycle != jnlpool.jnlpool_ctl->onln_rlbk_cycle))
		{
			assert(is_src_server);
			SYNC_ONLN_RLBK_CYCLES;
			gtmsource_onln_rlbk_clnup(); /* side-effect : sets gtmsource_state */
			rel_lock(reg); /* caller knows to disconnect and re-establish the connection */
		}
	}
	return TRUE;
}
Example #12
0
std::string CTooltipConsole::MakeUnitString(const CUnit* unit)
{
    string custom = eventHandler.WorldTooltip(unit, NULL, NULL);
    if (!custom.empty()) {
        return custom;
    }

    std::string s;

    const bool enemyUnit = (teamHandler->AllyTeam(unit->team) != gu->myAllyTeam) &&
                           !gu->spectatingFullView;

    const UnitDef* unitDef = unit->unitDef;
    const UnitDef* decoyDef = enemyUnit ? unitDef->decoyDef : NULL;
    const UnitDef* effectiveDef =
        !enemyUnit ? unitDef : (decoyDef ? decoyDef : unitDef);
    const CTeam* team = NULL;

    // don't show the unit type if it is not known
    const unsigned short losStatus = unit->losStatus[gu->myAllyTeam];
    const unsigned short prevMask = (LOS_PREVLOS | LOS_CONTRADAR);
    if (enemyUnit &&
            !(losStatus & LOS_INLOS) &&
            ((losStatus & prevMask) != prevMask)) {
        return "Enemy unit";
    }


    // show the player name instead of unit name if it has FBI tag showPlayerName
    if (effectiveDef->showPlayerName) {
        team = teamHandler->Team(unit->team);
        s = team->GetControllerName();
    } else {
        if (!decoyDef) {
            s = unit->tooltip;
        } else {
            s = decoyDef->humanName + " - " + decoyDef->tooltip;
        }
    }


    // don't show the unit health and other info if it has
    // the FBI tag hideDamage and is not on our ally team or
    // is not in LOS
    if (!enemyUnit || (!effectiveDef->hideDamage && (losStatus & LOS_INLOS))) {
        if (!decoyDef) {
            const float cost = unit->metalCost + (unit->energyCost / 60.0f);
            s += MakeUnitStatsString(
                     unit->health, unit->maxHealth,
                     unit->currentFuel, unitDef->maxFuel,
                     unit->experience, cost, unit->maxRange,
                     unit->metalMake,  unit->metalUse,
                     unit->energyMake, unit->energyUse);
        } else {
            // display adjusted decoy stats
            const float cost = decoyDef->metalCost + (decoyDef->energyCost / 60.0f);
            const float healthScale = (decoyDef->health / unitDef->health);
            float fuelScale;
            if (unitDef->maxFuel > 0.0f) {
                fuelScale = (decoyDef->maxFuel / unitDef->maxFuel);
            } else {
                fuelScale = 0.0f;
            }

            // get the adjusted resource stats
            float metalMake, energyMake, metalUse, energyUse;
            GetDecoyResources(unit, metalMake, metalUse, energyMake, energyUse);

            s += MakeUnitStatsString(
                     unit->health * healthScale, unit->maxHealth * healthScale,
                     unit->currentFuel * fuelScale, decoyDef->maxFuel,
                     unit->experience, cost, decoyDef->maxWeaponRange,
                     metalMake,  metalUse,
                     energyMake, energyUse);
        }
    }

    if (gs->cheatEnabled) {
        char buf[32];
        SNPRINTF(buf, 32, DARKBLUE "  [TechLevel %i]", unit->unitDef->techLevel);
        s += buf;
    }

    return s;
}
Example #13
0
bool LightingTechnique::Init()
{
    if (!Technique::Init()) {
        return false;
    }

    if (!AddShader(GL_VERTEX_SHADER, "lighting.vs")) {
        return false;
    }

    if (!AddShader(GL_TESS_CONTROL_SHADER, "lighting.cs")) {
        return false;
    }

    if (!AddShader(GL_TESS_EVALUATION_SHADER, "lighting.es")) {
        return false;
    }

    if (!AddShader(GL_FRAGMENT_SHADER, "lighting.fs")) {
        return false;
    }
    
    if (!Finalize()) {
        return false;
    }

    m_VPLocation = GetUniformLocation("gVP");
    m_WorldMatrixLocation = GetUniformLocation("gWorld");
    m_colorTextureLocation = GetUniformLocation("gColorMap");
    m_eyeWorldPosLocation = GetUniformLocation("gEyeWorldPos");
    m_dirLightLocation.Color = GetUniformLocation("gDirectionalLight.Base.Color");
    m_dirLightLocation.AmbientIntensity = GetUniformLocation("gDirectionalLight.Base.AmbientIntensity");
    m_dirLightLocation.Direction = GetUniformLocation("gDirectionalLight.Direction");
    m_dirLightLocation.DiffuseIntensity = GetUniformLocation("gDirectionalLight.Base.DiffuseIntensity");
    m_matSpecularIntensityLocation = GetUniformLocation("gMatSpecularIntensity");
    m_matSpecularPowerLocation = GetUniformLocation("gSpecularPower");
    m_numPointLightsLocation = GetUniformLocation("gNumPointLights");
    m_numSpotLightsLocation = GetUniformLocation("gNumSpotLights");
    m_TLLocation = GetUniformLocation("gTessellationLevel");

    if (m_dirLightLocation.AmbientIntensity == INVALID_UNIFORM_LOCATION ||
        m_VPLocation == INVALID_UNIFORM_LOCATION ||
        m_WorldMatrixLocation == INVALID_UNIFORM_LOCATION ||
        m_colorTextureLocation == INVALID_UNIFORM_LOCATION ||
        m_eyeWorldPosLocation == INVALID_UNIFORM_LOCATION ||
        m_dirLightLocation.Color == INVALID_UNIFORM_LOCATION ||
        m_dirLightLocation.DiffuseIntensity == INVALID_UNIFORM_LOCATION ||
        m_dirLightLocation.Direction == INVALID_UNIFORM_LOCATION ||
        m_matSpecularIntensityLocation == INVALID_UNIFORM_LOCATION ||
        m_matSpecularPowerLocation == INVALID_UNIFORM_LOCATION ||
        m_numPointLightsLocation == INVALID_UNIFORM_LOCATION ||
        m_numSpotLightsLocation == INVALID_UNIFORM_LOCATION ||
        m_TLLocation == INVALID_UNIFORM_LOCATION) {
        return false;
    }

    for (unsigned int i = 0 ; i < ARRAY_SIZE_IN_ELEMENTS(m_pointLightsLocation) ; i++) {
        char Name[128];
        memset(Name, 0, sizeof(Name));
        SNPRINTF(Name, sizeof(Name), "gPointLights[%d].Base.Color", i);
        m_pointLightsLocation[i].Color = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gPointLights[%d].Base.AmbientIntensity", i);
        m_pointLightsLocation[i].AmbientIntensity = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gPointLights[%d].Position", i);
        m_pointLightsLocation[i].Position = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gPointLights[%d].Base.DiffuseIntensity", i);
        m_pointLightsLocation[i].DiffuseIntensity = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gPointLights[%d].Atten.Constant", i);
        m_pointLightsLocation[i].Atten.Constant = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gPointLights[%d].Atten.Linear", i);
        m_pointLightsLocation[i].Atten.Linear = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gPointLights[%d].Atten.Exp", i);
        m_pointLightsLocation[i].Atten.Exp = GetUniformLocation(Name);

        if (m_pointLightsLocation[i].Color == INVALID_UNIFORM_LOCATION ||
            m_pointLightsLocation[i].AmbientIntensity == INVALID_UNIFORM_LOCATION ||
            m_pointLightsLocation[i].Position == INVALID_UNIFORM_LOCATION ||
            m_pointLightsLocation[i].DiffuseIntensity == INVALID_UNIFORM_LOCATION ||
            m_pointLightsLocation[i].Atten.Constant == INVALID_UNIFORM_LOCATION ||
            m_pointLightsLocation[i].Atten.Linear == INVALID_UNIFORM_LOCATION ||
            m_pointLightsLocation[i].Atten.Exp == INVALID_UNIFORM_LOCATION) {
            return false;
        }
    }

    for (unsigned int i = 0 ; i < ARRAY_SIZE_IN_ELEMENTS(m_spotLightsLocation) ; i++) {
        char Name[128];
        memset(Name, 0, sizeof(Name));
        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Base.Base.Color", i);
        m_spotLightsLocation[i].Color = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Base.Base.AmbientIntensity", i);
        m_spotLightsLocation[i].AmbientIntensity = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Base.Position", i);
        m_spotLightsLocation[i].Position = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Direction", i);
        m_spotLightsLocation[i].Direction = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Cutoff", i);
        m_spotLightsLocation[i].Cutoff = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Base.Base.DiffuseIntensity", i);
        m_spotLightsLocation[i].DiffuseIntensity = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Base.Atten.Constant", i);
        m_spotLightsLocation[i].Atten.Constant = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Base.Atten.Linear", i);
        m_spotLightsLocation[i].Atten.Linear = GetUniformLocation(Name);

        SNPRINTF(Name, sizeof(Name), "gSpotLights[%d].Base.Atten.Exp", i);
        m_spotLightsLocation[i].Atten.Exp = GetUniformLocation(Name);

        if (m_spotLightsLocation[i].Color == INVALID_UNIFORM_LOCATION ||
            m_spotLightsLocation[i].AmbientIntensity == INVALID_UNIFORM_LOCATION ||
            m_spotLightsLocation[i].Position == INVALID_UNIFORM_LOCATION ||
            m_spotLightsLocation[i].Direction == INVALID_UNIFORM_LOCATION ||
            m_spotLightsLocation[i].Cutoff == INVALID_UNIFORM_LOCATION ||
            m_spotLightsLocation[i].DiffuseIntensity == INVALID_UNIFORM_LOCATION ||
            m_spotLightsLocation[i].Atten.Constant == INVALID_UNIFORM_LOCATION ||
            m_spotLightsLocation[i].Atten.Linear == INVALID_UNIFORM_LOCATION ||
            m_spotLightsLocation[i].Atten.Exp == INVALID_UNIFORM_LOCATION) {
            return false;
        }
    }

    return true;
}
Example #14
0
/*-----------------------------------------------------------------*/
void
allocParms (value * val)
{
  value *lval;
  int pNum = 1;

  for (lval = val; lval; lval = lval->next, pNum++)
    {
      /* check the declaration */
      checkDecl (lval->sym, 0);

      /* if this a register parm then allocate
         it as a local variable by adding it
         to the first block we see in the body */
      if (IS_REGPARM (lval->etype))
        continue;

      /* mark it as my parameter */
      lval->sym->ismyparm = 1;
      lval->sym->localof = currFunc;

      /* if automatic variables r 2b stacked */
      if (options.stackAuto || IFFUNC_ISREENT (currFunc->type))
        {
          if (lval->sym)
            lval->sym->onStack = 1;

          /* choose which stack 2 use   */
          /*  use xternal stack */
          if (options.useXstack)
            {
              /* PENDING: stack direction support */
              SPEC_OCLS (lval->etype) = SPEC_OCLS (lval->sym->etype) = xstack;
              SPEC_STAK (lval->etype) = SPEC_STAK (lval->sym->etype) = lval->sym->stack =
                xstackPtr - getSize (lval->type);
              xstackPtr -= getSize (lval->type);
            }
          else
            {                   /* use internal stack   */
              SPEC_OCLS (lval->etype) = SPEC_OCLS (lval->sym->etype) = istack;
              if (port->stack.direction > 0)
                {
                  SPEC_STAK (lval->etype) = SPEC_STAK (lval->sym->etype) = lval->sym->stack =
                    stackPtr - (FUNC_REGBANK (currFunc->type) ? port->stack.bank_overhead : 0) -
                    getSize (lval->type) -
                    (FUNC_ISISR (currFunc->type) ? port->stack.isr_overhead : 0);
                  stackPtr -= getSize (lval->type);
                }
              else
                {
                  /* This looks like the wrong order but it turns out OK... */
                  /* PENDING: isr, bank overhead, ... */
                  SPEC_STAK (lval->etype) = SPEC_STAK (lval->sym->etype) = lval->sym->stack =
                    stackPtr +
                    ((IFFUNC_ISBANKEDCALL (currFunc->type) && !SPEC_STAT(getSpec(currFunc->etype)))? port->stack.banked_overhead : 0) +
                    (FUNC_ISISR (currFunc->type) ? port->stack.isr_overhead : 0) +
                    0;
                  stackPtr += getSize (lval->type);
                }
            }
          allocIntoSeg (lval->sym);
        }
      else
        { /* allocate them in the automatic space */
          /* generate a unique name  */
          SNPRINTF (lval->sym->rname, sizeof(lval->sym->rname),
                    "%s%s_PARM_%d", port->fun_prefix, currFunc->name, pNum);
          strncpyz (lval->name, lval->sym->rname, sizeof(lval->name));

          /* if declared in specific storage */
          if (allocDefault (lval->sym))
            {
              SPEC_OCLS (lval->etype) = SPEC_OCLS (lval->sym->etype);
              continue;
            }

          /* otherwise depending on the memory model */
          SPEC_OCLS (lval->etype) = SPEC_OCLS (lval->sym->etype) =
              port->mem.default_local_map;
          if (options.model == MODEL_SMALL)
            {
              /* note here that we put it into the overlay segment
                 first, we will remove it from the overlay segment
                 after the overlay determination has been done */
              if (!options.noOverlay)
                {
                  SPEC_OCLS (lval->etype) = SPEC_OCLS (lval->sym->etype) =
                    overlay;
                }
            }
          else if (options.model == MODEL_MEDIUM)
            {
              SPEC_SCLS (lval->etype) = S_PDATA;
            }
          else
            {
              SPEC_SCLS (lval->etype) = S_XDATA;
            }
          allocIntoSeg (lval->sym);
        }
    }
  return;
}
Example #15
0
void CWaitCommandsAI::SquadWait::UpdateText()
{
	static char buf[64];
	SNPRINTF(buf, sizeof(buf), "%i/%i", (int)waitUnits.size(), squadCount);
	stateText = buf;
}
Example #16
0
/*-----------------------------------------------------------------*/
void
allocLocal (symbol * sym)
{
  /* generate an unique name */
  SNPRINTF (sym->rname, sizeof(sym->rname),
            "%s%s_%s_%d_%d",
            port->fun_prefix,
            currFunc->name, sym->name, sym->level, sym->block);

  sym->islocal = 1;
  sym->localof = currFunc;

  /* if this is a static variable */
  if (IS_STATIC (sym->etype))
    {
      allocGlobal (sym);
      sym->allocreq = 1;
      return;
    }

  /* if volatile then */
  if (IS_VOLATILE (sym->etype))
    sym->allocreq = 1;

  /* this is automatic           */

  /* if it's to be placed on the stack */
  if (options.stackAuto || reentrant) {
    sym->onStack = 1;
    if (options.useXstack) {
      /* PENDING: stack direction for xstack */
      SPEC_OCLS (sym->etype) = xstack;
      SPEC_STAK (sym->etype) = sym->stack = (xstackPtr + 1);
      xstackPtr += getSize (sym->type);
    } else {
      SPEC_OCLS (sym->etype) = istack;
      if (port->stack.direction > 0) {
        SPEC_STAK (sym->etype) = sym->stack = (stackPtr + 1);
        stackPtr += getSize (sym->type);
      } else {
        stackPtr -= getSize (sym->type);
        SPEC_STAK (sym->etype) = sym->stack = stackPtr;
      }
    }
    allocIntoSeg (sym);
    return;
  }

  /* else depending on the storage class specified */

  /* if this is a function then assign code space    */
  if (IS_FUNC (sym->type))
    {
      SPEC_OCLS (sym->etype) = code;
      return;
    }

  /* if this is a bit variable and no storage class */
  if (IS_SPEC(sym->type) && SPEC_NOUN (sym->type) == V_BIT)
    {
      SPEC_SCLS (sym->type) = S_BIT;
      SPEC_OCLS (sym->type) = bit;
      allocIntoSeg (sym);
      return;
    }

  if ((SPEC_SCLS (sym->etype) == S_DATA) || (SPEC_SCLS (sym->etype) == S_REGISTER))
    {
      SPEC_OCLS (sym->etype) = (options.noOverlay ? data : overlay);
      allocIntoSeg (sym);
      return;
    }

  if (allocDefault (sym))
    {
      return;
    }

  /* again note that we have put it into the overlay segment
     will remove and put into the 'data' segment if required after
     overlay  analysis has been done */
  if (options.model == MODEL_SMALL) {
      SPEC_OCLS (sym->etype) =
        (options.noOverlay ? port->mem.default_local_map : overlay);
  } else {
      SPEC_OCLS (sym->etype) = port->mem.default_local_map;
  }
  allocIntoSeg (sym);
}
Example #17
0
std::string
PyFontAttributes_ToString(const FontAttributes *atts, const char *prefix)
{
    std::string str;
    char tmpStr[1000];

    const char *font_names = "Arial, Courier, Times";
    switch (atts->GetFont())
    {
      case FontAttributes::Arial:
          SNPRINTF(tmpStr, 1000, "%sfont = %sArial  # %s\n", prefix, prefix, font_names);
          str += tmpStr;
          break;
      case FontAttributes::Courier:
          SNPRINTF(tmpStr, 1000, "%sfont = %sCourier  # %s\n", prefix, prefix, font_names);
          str += tmpStr;
          break;
      case FontAttributes::Times:
          SNPRINTF(tmpStr, 1000, "%sfont = %sTimes  # %s\n", prefix, prefix, font_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    SNPRINTF(tmpStr, 1000, "%sscale = %g\n", prefix, atts->GetScale());
    str += tmpStr;
    if(atts->GetUseForegroundColor())
        SNPRINTF(tmpStr, 1000, "%suseForegroundColor = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%suseForegroundColor = 0\n", prefix);
    str += tmpStr;
    const unsigned char *color = atts->GetColor().GetColor();
    SNPRINTF(tmpStr, 1000, "%scolor = (%d, %d, %d, %d)\n", prefix, int(color[0]), int(color[1]), int(color[2]), int(color[3]));
    str += tmpStr;
    if(atts->GetBold())
        SNPRINTF(tmpStr, 1000, "%sbold = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%sbold = 0\n", prefix);
    str += tmpStr;
    if(atts->GetItalic())
        SNPRINTF(tmpStr, 1000, "%sitalic = 1\n", prefix);
    else
        SNPRINTF(tmpStr, 1000, "%sitalic = 0\n", prefix);
    str += tmpStr;
    return str;
}