Ejemplo n.º 1
0
int SearObject::shutdown() {
  assert(m_initialised == true);

  // Clean up OpenGL bits
  contextDestroyed(true);

  StaticObjectList::const_iterator I = m_static_objects.begin();
  StaticObjectList::const_iterator Iend = m_static_objects.end();
  for (; I != Iend; ++I) {
    StaticObject* so = *I;
    assert(so);
    int id, mask_id;
    // Clean up textures
    if (so->getTexture(0, id, mask_id) == 0) {
      RenderSystem::getInstance().releaseTexture(id);
      RenderSystem::getInstance().releaseTexture(mask_id);
    }
    delete so;
  }

  m_static_objects.clear();

  m_initialised = false;
  return 0;
}
Ejemplo n.º 2
0
void SearObject::render(bool select_mode) {
  StaticObjectList::const_iterator I = m_static_objects.begin();
  StaticObjectList::const_iterator Iend = m_static_objects.end();
  for (; I != Iend; ++I) {
    StaticObject* so = *I;
    assert(so);
    so->render(select_mode);
  }
}
Ejemplo n.º 3
0
void SearObject::contextDestroyed(bool check) {
  StaticObjectList::const_iterator I = m_static_objects.begin();
  StaticObjectList::const_iterator Iend = m_static_objects.end();
  for (; I != Iend; ++I) {
    StaticObject* so = *I;
    assert(so);
    so->contextDestroyed(check);
  }
}
Ejemplo n.º 4
0
void SearObject::contextCreated() {
  StaticObjectList::const_iterator I = m_static_objects.begin();
  StaticObjectList::const_iterator Iend = m_static_objects.end();
  for (; I != Iend; ++I) {
    StaticObject* so = *I;
    assert(so);
    so->contextCreated();
  }
}
Ejemplo n.º 5
0
StaticObject* CreationTool::CreateStaticModel(XMFLOAT3 position, ModelData data)
{
	StaticObject* object = new StaticObject(mModelImporter, data.filename);
	object->SetPosition(position);
	object->SetMaterials(Material(Colors::White));
	object->SetName(data.name);
	object->SetDefualtScale(data.defaultScale);
	return object;
}
Ejemplo n.º 6
0
void SetOn_OffFlag( StaticObject& light, StaticObject::Lights::Flag2 flag )
{
	bool IsLight = light.checkFlag( flag );

	//라이트 off 상태면
	if( !IsLight )
		light.resetFlag( flag );   //라이트 on
	//라이트 on 상태면
	else
		light.setFlag( flag );   //라이트 off
}
Ejemplo n.º 7
0
void IceWorld::loadPhase2(irr::IrrlichtDevice * device){
	//Unload the terrains from the scene
	clearTerrains();

	//Make sure the previous phase is no longer considered loaded
	phase1Loaded = false;

	//Get the references
	irr::scene::ISceneManager *smgr = device->getSceneManager();
	irr::video::IVideoDriver *driver = device->getVideoDriver();

	//Set the random seed
	srand(1);

	//Reset the player position
	player->changePosition(irr::core::vector3df(0, 0, 0));

	//Make an array for the spawn order
	int spawnOrder[10] = {1, 1, 2, 1, 2, 3, 1, 1, 3, 2};

	//Set up the enemy positions
	irr::f32 x = 0; irr::f32 y = 0; irr::f32 z = 500;
	for(int i = 0; i < 20; i++){
		//Deside which enemy to place
		if(spawnOrder[i] == 1){
			BasicEnemy *basicEnemy = new BasicEnemy(player, irr::core::vector3df(x, y, z), device->getTimer(), smgr);
		} else if(spawnOrder[i] == 2){
			FastEnemy *fastEnemy = new FastEnemy(player, irr::core::vector3df(x, y, z), device->getTimer(), smgr);
		} else if(spawnOrder[i] == 3){
			StrongEnemy *strongEnemy = new StrongEnemy(player, irr::core::vector3df(x, y, z), device->getTimer(), smgr);
		}
		z += 1500 + (player->getMovementSpeed() * 2.7f);
	}

	//Add some gems to the level
	x = 0; y = 0; z = 1200;
	for(int i = 0; i < 3; i++){
		y = (irr::f32)(rand() % 40 + 1) - 20;
		BronzeGem *gem = new BronzeGem(irr::core::vector3df(x, y, z), smgr);
		gem->moveAwayFromPlayer(true, Game::getCurrentPlayer()->getMovementSpeed());
		z += (rand() % 3000 + 1000) + (player->getMovementSpeed() * 2.7f);
	}

	//Add some asteroids to the level
	x = 0; y = 0; z = 2000;
	for(int i = 0; i < 14; i++){
		y = (irr::f32)(rand() % 70 + 1) - 35;
		StaticObject *Obsticle = new StaticObject(irr::core::vector3df(x, y, z), "Assets/Environment/Asteroid/Asteroid1.obj", "Assets/Environment/Asteroid/AsteroidTextureA.jpg", device->getSceneManager(), true);
		Obsticle->moveAwayFromPlayer(true, Game::getCurrentPlayer()->getMovementSpeed());
		z += (rand() % 500 + 500) + (player->getMovementSpeed() * 2.7f);
	}

	phase2Loaded = true;
}
Ejemplo n.º 8
0
void SetOff_OnFlag( StaticObject& light, StaticObject::Lights::Flag2 flag )
{
	//라이트 1 플래그 변화
	bool IsLight = light.checkFlag( flag );

	//라이트 off 상태면
	if( IsLight )
		light.resetFlag( flag );   //라이트 on
	//라이트 on 상태면
	else
		light.setFlag( flag );   //라이트 off
}
Ejemplo n.º 9
0
const double getWrappingUnitDist(const StaticObject& obj1, const StaticObject& obj2) {

   pair<double,double> pos1 = obj1.getUnitPos();
   pair<double,double> pos2 = obj2.getUnitPos();

   double x = std::abs(pos1.first - pos2.first);
   if(x > .5)
      x = 1 - x;

   double y = std::abs(pos1.second - pos2.second);
   if(y > .5)
      y = 1 - y;

   return std::sqrt(x*x + y*y);
}
Ejemplo n.º 10
0
void violetland::HUD::getButtonArea(AREA area, SDL_Rect* screenRect)
{
	screenRect->x = screenRect->y = screenRect->w = screenRect->h = 0;
	StaticObject* pObj = NULL;
	switch (area)
	{
	case AREA_CHAR:
		pObj = m_char;
		break;
	case AREA_RELOAD:
		pObj = m_reload;
		break;
	case AREA_GRENADE:
		pObj = m_grenade;
		break;
	case AREA_SHOOT:
		pObj = m_shoot;
		break;
	case AREA_WASD:
		pObj = m_wasd;
		break;
	default:
		memset(screenRect, 0, sizeof(screenRect));
		return;
	}

	float left = pObj->getLeft();
	float right = pObj->getRight();
	float top = pObj->getTop();
	float bottom = pObj->getBottom();

	screenRect->x = (int)(left);
	screenRect->y = (int)(top);
	screenRect->w = (int)(right - left);
	screenRect->h = (int)(bottom - top);

	if (area == AREA_WASD || area == AREA_SHOOT)
	{
		int indent = m_videoManager->RegularText->getIndent();
		screenRect->x -= indent;
		screenRect->y -= indent;
		screenRect->w += indent * 2;
		screenRect->h += indent * 2;
	}
}
Ejemplo n.º 11
0
const unsigned getWrappingDistSq(const StaticObject& obj1, const StaticObject& obj2) {

   pair<double,double> pos1 = obj1.getUnitPos();
   pair<double,double> pos2 = obj2.getUnitPos();

   double x = std::abs(pos1.first - pos2.first);
   if(x > .5)
      x = 1 - x;

   double y = std::abs(pos1.second - pos2.second);
   if(y > .5)
      y = 1 - y;

   x *= UNIVERSE_WIDTH * UNIVERSE_TOTAL_SCALE;
   y *= UNIVERSE_HEIGHT * UNIVERSE_TOTAL_SCALE;

   return static_cast<unsigned>(x*x + y*y);
}
Ejemplo n.º 12
0
int SearObject::load(const std::string &filename) {
  bool big_endian = false;

  FILE *fp = fopen(filename.c_str(), "rb");
  if (fp == 0) {
    fprintf(stderr, "[SearObject] Error opening %s for reading\n", filename.c_str());
    return 1;
  }

  SearObjectHeader soh;
  if (fread(&soh, sizeof(SearObjectHeader), 1, fp) != 1) {
    // Error reading header
    fprintf(stderr, "[SearObject] Error reading SearObject header in %s\n", filename.c_str());
    fclose(fp);
    return 1;
  }
  
  // Check Magic
  if (strncmp(soh.magic, "SEARSTAT", 8)) {
   fprintf(stderr, "[SearObject] Bad magic - unknown file format.\n");
   fclose(fp);
   return 1;
  }

  // Check Endianess
  // Does this check actually work? Or should we convert into a chars and
  // compare char order instead?
  if (soh.byte_order == 0x00FF) {
    big_endian = true;
    printf("[SearObject] Swapping byte order\n");
    swap_bytes_uint32_t(soh.num_meshes);
  }

  // Check Version
  if (soh.version != 1) {
    fprintf(stderr, "[SearObject] SearObject Version %d is unsupported. Version %d expected.\n", soh.version, 1);
    fclose(fp);
    return 1;
  } 

  SearObjectMesh som;
  TextureID tex_id = NO_TEXTURE_ID;
  TextureID tex_mask_id = NO_TEXTURE_ID;
  uint32_t *uptr;
  float *fptr;
  int c,x,y;

  for (uint32_t i = 0; i < soh.num_meshes; ++i) {
    if (fread(&som, sizeof(SearObjectMesh), 1, fp) != 1) {
      fprintf(stderr, "[SearObject] Error reading SearObject Mesh in %s\n", filename.c_str());
      fclose(fp);
      return 1;
    }

    if (big_endian) {
      swap_bytes_uint32_t(som.num_vertices);
      swap_bytes_uint32_t(som.num_faces);
      for (x = 0; x < 4; ++x) {
        for (y = 0; y < 4; ++y) {
          swap_bytes_float(som.mesh_transform[x][y]);
          swap_bytes_float(som.texture_transform[x][y]);
        }
      }

      for (x = 0; x < 4; ++x) {
        swap_bytes_float(som.ambient[x]);
        swap_bytes_float(som.diffuse[x]);
        swap_bytes_float(som.specular[x]);
        swap_bytes_float(som.emissive[x]);
      }
      swap_bytes_float(som.shininess);
    }

    StaticObject* so = new StaticObject();
    so->init();
   
    so->setNumPoints(som.num_vertices);
    so->setNumFaces(som.num_faces);

    // Does this use all 256 chars, or only up to 256?
    som.texture_map[255] = '\0'; // Make sure the string is null-terminated
    std::string tex_name(som.texture_map);

    // See if config file has a mapping
    m_config.clean(tex_name);
    if (m_config.findItem(tex_name, KEY_texture_map_0)) {
      tex_name = (std::string)m_config.getItem(tex_name, KEY_texture_map_0);
    }

    // Get texture ids
    tex_id =  RenderSystem::getInstance().requestTexture(tex_name);
    tex_mask_id =  RenderSystem::getInstance().requestTexture(tex_name, true);
    so->setTexture(0, tex_id, tex_mask_id);   

    // Set transform matrices
    so->getMatrix().setMatrix(som.mesh_transform);
    so->getTexMatrix().setMatrix(som.texture_transform);

    // Set Materials
    so->setAmbient(som.ambient);
    so->setDiffuse(som.diffuse);
    so->setSpecular(som.specular);
    so->setEmission(som.emissive);
    so->setShininess(som.shininess);

    // Read in the vertex data array 
    so->createVertexData(som.num_vertices * 3);
    fread(so->getVertexDataPtr(), sizeof(float), som.num_vertices * 3, fp);
    if (big_endian) {
      fptr = so->getVertexDataPtr();
      c = som.num_vertices * 3;
      while (c--) swap_bytes_float(*fptr++);
    }

    so->createNormalData(som.num_vertices * 3);
    fread(so->getNormalDataPtr(), sizeof(float), som.num_vertices * 3, fp);
    if (big_endian) {
      fptr = so->getNormalDataPtr();
      c = som.num_vertices * 3;
      while (c--) swap_bytes_float(*fptr++);
    }

    so->createTextureData(som.num_vertices * 2);
    fread(so->getTextureDataPtr(), sizeof(float), som.num_vertices * 2, fp);
    if (big_endian) {
      fptr = so->getTextureDataPtr();
      c = som.num_vertices * 2;
      while (c--) swap_bytes_float(*fptr++);
    }

    if (som.num_faces > 0) {
      so->createIndices(som.num_faces * 3);
      fread(so->getIndicesPtr(), sizeof(uint32_t), som.num_faces * 3, fp);
      if (big_endian) {
        uptr = (uint32_t*)so->getIndicesPtr();
        c = som.num_faces * 3;
        while (c--) swap_bytes_uint32_t(*uptr++);
      }
    }

    m_static_objects.push_back(so);
  }  

  fclose(fp);

  return 0;
}
Ejemplo n.º 13
0
int main()
{
	Player geko("Geko", glm::vec3(10.0, 10.0, 10.0));


	// Start Konifguration - Window, Context, Camera and Callbacks //
	glfwInit();

	Window testWindow(500, 50, 800, 600, "testWindow");
	glfwMakeContextCurrent(testWindow.getWindow());

	cam.setKeySpeed(2.0);
	cam.setNearFar(0.01, 100);

	//Callback for Camera and Player
	glfwSetKeyCallback(testWindow.getWindow(), key_callback);

	glewInit();

	// Shader  and Renderer Initialization //
	//Shader for Objects
	VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/Vertex-Shaders/TextureShader3D.vert")));
	FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/Fragment-Shaders/TextureShader3D.frag")));
	ShaderProgram shader(vs, fs);

	//Shader for a Skybox
	VertexShader vsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.vert")));
	FragmentShader fsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.frag")));
	ShaderProgram shaderSkybox(vsSkybox, fsSkybox);

	//Renderer with context
	OpenGL3Context context;
	Renderer renderer(context);

	//Level and Scene
	Level testLevel("testLevel");
	Scene testScene("testScene");
	testLevel.addScene(&testScene);
	testLevel.changeScene("testScene");

	//Add Camera to scenegraph
	testScene.getScenegraph()->addCamera(&cam);
	testScene.getScenegraph()->getCamera("PlayerViewCam");
	testScene.getScenegraph()->setActiveCamera("PlayerViewCam");

	//Set all InputMaps and set one InputMap active
	iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera()));
	iH.changeActiveInputMap("Object");
	iH.getActiveInputMap()->update(geko);

	// ==============================================================
	// == Object (ant, afraid) ======================================
	// ==============================================================
	Teapot teaAnt;
	Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp");
	//AntMesh antMesh;
	//Node aiNodeFlick("Flick");

	//aiNodeFlick.addGeometry(&teaAnt);
	//aiNodeFlick.addTexture(&texCV);

	//testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNodeFlick);

	//AI ant_Flick;
	//ant_Flick.setAntAfraid();
	//aiNodeFlick.ssetObject(&ant_Flick);

	// ==============================================================
	// == Object (ant, aggressiv) ===================================
	// ==============================================================
	AntMesh antMesh;
	//Node aiNodeFlack("Flack");

	//aiNodeFlack.addGeometry(&teaAnt);
	//aiNodeFlack.addGeometry(&antMesh);
	//aiNodeFlack.addTexture(&texCV);

	//testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNodeFlack);

	//AI ant_Flack;
	//ant_Flack.setAntAggressiv();
	//aiNodeFlack.setObject(&ant_Flack);

	// ==============================================================
	// == Object (Tree) =============================================
	// ==============================================================

	Texture texBrick((char*)RESOURCES_PATH "/brick.bmp");
	//TreeMesh treeMesh;
	Teapot teaTree;
	TreeMesh treeMesh;

	Node treeNode("CookieTree");
	StaticObject tree;
	tree.setTree();

	treeNode.setObject(&tree);
	treeNode.addTexture(&texCV);
	treeNode.addGeometry(&treeMesh);
	glm::vec3 posFood(10.0, 0.0, -5.0);
	treeNode.addTranslation(posFood);
	treeNode.getBoundingSphere()->radius = 2.0;

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode);

	// ==============================================================
	// == Player ====================================================
	// ==============================================================

	Teapot teaPlayer;
	GekoMesh gekomesh;
	//	Texture texBrick((char*)RESOURCES_PATH "/brick.bmp");

	Node playerNode("Player");
	playerNode.addTexture(&texBrick);
	playerNode.setObject(&geko);
	//playerNode.addGeometry(&teaPlayer);
	playerNode.addGeometry(&gekomesh);
	playerNode.setCamera(&cam);
	geko.setPosition(glm::vec3(10.0, 0.0, 10.0));

	//Add the node to the Scene
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode);

	// ==============================================================
	// == Questsystem ====================================================
	// ==============================================================
	//QuestHandler questhandler;

	Quest questCollect(1);
	questCollect.setActive(true);
	Goal_Collect goalCollect(1);
	Goal_Collect goalCollect3(3);
	questCollect.addGoal(&goalCollect);
	questCollect.addGoal(&goalCollect3);

	Quest questCollect2(2);
	questCollect2.setActive(true);
	Goal_Collect goalCollect2(2);
	questCollect2.addGoal(&goalCollect2);

	goalCollect.setGoalCount(50);
	goalCollect2.setGoalCount(50);
	goalCollect3.setGoalCount(50);

	goalCollect.setItemType(ItemType::BRANCH);
	goalCollect2.setItemType(ItemType::BRANCH);
	goalCollect3.setItemType(ItemType::COOKIE);

	testLevel.getQuestHandler()->addQuest(&questCollect);
	testLevel.getQuestHandler()->addQuest(&questCollect2);
	/*questhandler.addQuest(&questCollect);
	questhandler.addQuest(&questCollect2);*/

	//std::cout << "GRÖßE DES QUESTHANDLERS : " << questhandler.getQuests().size() << std::endl;


	// ==============================================================
	// == Collision, FightSystem=====================================
	// ==============================================================

	// Bounding Box creation for the objects and collision test //
	CollisionTest collision;


	FightSystem fight;

	//===================================================================//
	//==================Setting up the Observers========================//
	//==================================================================//
	ObjectObserver aiObserver(&testLevel);
	//ant_Flick.addObserver(&aiObserver);
	//ant_Flack.addObserver(&aiObserver);

	ObjectObserver playerObserver(&testLevel);
	geko.addObserver(&playerObserver);

	CollisionObserver colObserver(&testLevel);
	collision.addObserver(&colObserver);

	GravityObserver gravityObserver(&testLevel);
	collision.addObserver(&gravityObserver);

	SoundObserver soundObserver(&testLevel);

	// ==============================================================
	// == Object (Anthome) ==========================================
	// ==============================================================

	//TreeMesh treeMesh;
	AntHomeMesh homeMesh;

	Node homeNode("AntHome");
	StaticObject home;
	//home.setTree();

	homeNode.setObject(&home);
	homeNode.addTexture(&texBrick);
	homeNode.addGeometry(&homeMesh);
	glm::vec3 posHome(1.0, 0.0, 1.0);
	homeNode.addTranslation(posHome);
	homeNode.getBoundingSphere()->radius = 0.5;

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&homeNode);

	glm::vec3 posFood2(10.0, 0.0, -5.0);
	glm::vec3 posSpawn(3.0, 0.0, 3.0);
	glm::vec3 posDefaultPlayer(0.0, 0.0, 0.0);

	DecisionTree *aggressivedecisionTree = new DecisionTree();
	aggressivedecisionTree->setAntTreeAggressiv();

	DecisionTree *afraidDecisionTree = new DecisionTree();
	afraidDecisionTree->setAntTreeAfraid();

	Graph<AStarNode, AStarAlgorithm>* antAggressiveGraph = new Graph<AStarNode, AStarAlgorithm>();
	antAggressiveGraph->setExampleAntAfraid(posSpawn, posFood2, posDefaultPlayer);

	Graph<AStarNode, AStarAlgorithm>* antAfraidGraph = new Graph<AStarNode, AStarAlgorithm>();
	antAfraidGraph->setExampleAntAfraid(posSpawn, posFood, posDefaultPlayer);

	//AntHome antHome(posSpawn, antMesh, &texCV, &texCV, aggressivedecisionTree, antAggressiveGraph, afraidDecisionTree, antAfraidGraph);
	////antHome.generateGuards(5, &aiObserver);
	//antHome.generateWorkers(1, &aiObserver);
	SoundFileHandler sfh(1000);
	AntHome antHome(posSpawn, &sfh, antMesh, &soundObserver, &playerObserver, &texCV, &texCV, aggressivedecisionTree, antAggressiveGraph, afraidDecisionTree, antAfraidGraph);
	antHome.generateWorkers(5, testScene.getScenegraph()->getRootNode());
	antHome.addAntsToSceneGraph(testScene.getScenegraph()->getRootNode());


	collision.collectNodes(testScene.getScenegraph()->getRootNode());
	float lastTime = glfwGetTime();
	int i = 0;
	while (!glfwWindowShouldClose(testWindow.getWindow()))
	{
		i++;
		if (i == 30){
			i++;
		}
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		float currentTime = glfwGetTime();
		float deltaTime = currentTime - lastTime;
		lastTime = currentTime;
		collision.update();

		antHome.updateAnts();
		antHome.printPosWorkers();

		/*	ant_Flick.update();
		ant_Flack.update();*/

		geko.update();
		geko.setDeltaTime(currentTime);

		renderer.renderScene(testScene, testWindow);

	}

	glfwDestroyWindow(testWindow.getWindow());
	glfwTerminate();

	return 0;
}
Ejemplo n.º 14
0
//===================================================================//
//==================Main Method=====================================//
//==================================================================//
int main()
{

	//===================================================================//
	//==================Things you need to start with====================//
	//==================================================================//
	glfwInit();

	Window testWindow(500, 50, 800, 600, "testWindow");
	glfwMakeContextCurrent(testWindow.getWindow());

	// Callback
	glfwSetKeyCallback(testWindow.getWindow(), key_callback);

	cam.setKeySpeed(2.0);
	cam.setNearFar(0.01, 100);

	glewInit();

	OpenGL3Context context;
	//renderer = new Renderer(context);
	Renderer renderer(context);

	//===================================================================//
	//==================Shaders for your program========================//
	//==================================================================//
	VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/Vertex-Shaders/TextureShader3D.vert")));
	FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/Fragment-Shaders/TextureShader3D.frag")));
	ShaderProgram shader(vs, fs);

	VertexShader vsGBuffer(loadShaderSource(SHADERS_PATH + std::string("/GBuffer/GBuffer.vert")));
	FragmentShader fsGBuffer(loadShaderSource(SHADERS_PATH + std::string("/GBuffer/GBuffer.frag")));
	ShaderProgram shaderGBuffer(vsGBuffer, fsGBuffer);

	VertexShader vsSfq(loadShaderSource(SHADERS_PATH + std::string("/ScreenFillingQuad/ScreenFillingQuad.vert")));
	FragmentShader fsSfq(loadShaderSource(SHADERS_PATH + std::string("/ScreenFillingQuad/ScreenFillingQuad.frag")));
	ShaderProgram shaderSFQ(vsSfq, fsSfq);



	FBO fboGBuffer(WINDOW_WIDTH, WINDOW_HEIGHT, 3, true, false);

	ParticleSystem* particle = new ParticleSystem(glm::vec3(0, 0, 0), (char*)RESOURCES_PATH "/XML/ComicCloudEffect.xml");
	particle->m_type = ParticleType::FIGHT;
	ParticleSystem* particle2 = new ParticleSystem(glm::vec3(0, 0, 0), (char*)RESOURCES_PATH "/XML/SwarmOfFliesEffect.xml");
	particle2->m_type = ParticleType::SWARMOFFLIES;
	ParticleSystem* particleFire = new ParticleSystem(glm::vec3(0, 0, 0), (char*)RESOURCES_PATH "/XML/Fire.xml");
	particleFire->m_type = ParticleType::FIRE;

	Node particleNode("ParticleNode");
	particleNode.addParticleSystem(particle2);
	particleNode.setCamera(&cam);
	particleNode.setParticleActive(true);

	Node particleNodeFire("ParticleNodeFire");
	particleNodeFire.addParticleSystem(particleFire);
	particleNodeFire.setCamera(&cam);
	particleNodeFire.setParticleActive(true);

	//===================================================================//
	//==================A Graph for the AI-Unit=========================//
	//==================================================================//

	glm::vec3 posFood(10.0, 0.0, -5.0);
	glm::vec3 posSpawn(3.0, 0.0, 3.0);
	Graph<AStarNode, AStarAlgorithm> testGraph;

	//===================================================================//
	//==================A Decision-Tree for the AI-Unit==================//
	//==================================================================//

	DecisionTree defaultTree;
	defaultTree.setAntTreeAggressiv();


	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: AI==============================//

	Teapot teaAnt;

	Texture texPlayer((char*)RESOURCES_PATH "/Mesh/Snake.jpg");
	SoundFileHandler sfh = SoundFileHandler(1000);

	AStarNode defaultASNode();
	Ant ant_Flick;
	ant_Flick.setAntAfraid();

	AntMesh ant;

	Node aiNode("Flick");
	aiNode.addGeometry(&ant);
	aiNode.addTexture(&texPlayer);
	aiNode.addTranslation(ant_Flick.getPosition().x, ant_Flick.getPosition().y, ant_Flick.getPosition().z);
	aiNode.setObject(&ant_Flick);
	ant_Flick.setSoundHandler(&sfh);

	ant_Flick.setSourceName(MOVESOUND_AI, "AIFootsteps", RESOURCES_PATH "/Sound/Footsteps.wav");
	sfh.disableLooping("AIFootsteps");
	ant_Flick.setSourceName(DEATHSOUND_AI, "AIDeath", RESOURCES_PATH "/Sound/death.wav");
	sfh.disableLooping("AIDeath");
	ant_Flick.setSourceName(EATSOUND_AI, "AIEssen", RESOURCES_PATH "/Sound/Munching.wav");
	sfh.disableLooping("AIEssen");
	ant_Flick.setSourceName(DEATHSOUND_FLIES_AI, "Flies", RESOURCES_PATH "/Sound/Fliege_kurz.wav");
	sfh.setGain("Flies", 7.0);

	Rect screenFillingQuad;
	screenFillingQuad.loadBufferData();



	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: Player===========================//
	Teapot teaPlayer;
	Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp");

	GekoMesh gekoMesh;
	geko.setExp(0.0);
	geko.setLevelThreshold(100.0);
	geko.setLevel(0);

	Node playerNode("Player");

	playerNode.addGeometry(&gekoMesh);
	playerNode.setObject(&geko);
	playerNode.addTexture(&texCV);

	sfh.generateSource(posFood, RESOURCES_PATH "/Sound/Rascheln.wav");
	geko.setSoundHandler(&sfh);
	geko.setSourceName(MOVESOUND, "SpielerFootsteps", RESOURCES_PATH "/Sound/Rascheln.wav");
	//geko.setSourceName(BACKGROUNDMUSIC, "Hintergrund", RESOURCES_PATH "/Sound/jingle2.wav");
	geko.setSourceName(FIGHTSOUND, "Kampfsound", RESOURCES_PATH "/Sound/punch.wav");
	geko.setSourceName(EATSOUND, "Essen", RESOURCES_PATH "/Sound/Munching.wav");
	geko.setSourceName(QUESTSOUND, "Quest", RESOURCES_PATH "/Sound/jingle.wav");
	geko.setSourceName(ITEMSOUND, "Item", RESOURCES_PATH "/Sound/itempickup.wav");
	geko.setSourceName(FIRESOUND, "Fire", RESOURCES_PATH "/Sound/Feuer_kurz.wav");

	sfh.disableLooping("Essen");
	sfh.disableLooping("Quest");
	sfh.disableLooping("Item");
	//sfh.generateSource("Feuer",posFood, RESOURCES_PATH "/Sound/Feuer kurz.wav");

	playerNode.setCamera(&cam);

	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: Tree===========================//

	StaticObject treeStatic;
	treeStatic.setTree();

	TreeMesh tree;
	Node treeNode("Tree");
	treeNode.addGeometry(&tree);
	treeNode.setObject(&treeStatic);
	treeNode.addTranslation(posFood);
	treeNode.getBoundingSphere()->radius = 3.0;

	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: Plane===========================//

	StaticObject terrainObject;
	terrainObject.setClassType(ClassType::TERRAIN);

	Plane terrain;
	Texture terrainTex((char*)RESOURCES_PATH "/Grass.jpg");

	Node terrainNode("Plane");
	terrainNode.addGeometry(&terrain);
	terrainNode.addTexture(&terrainTex);
	terrainNode.setObject(&terrainObject);
	terrainNode.addTranslation(0.0, -0.75, 0.0);
	terrainNode.addRotation(90.0f, glm::vec3(1.0, 0.0, 0.0));
	terrainNode.addScale(20.0, 20.0, 20.0);

	//===================================================================//
	//==================Setting up the Level and Scene==================//
	//==================================================================//

	Level testLevel("testLevel");
	Scene testScene("testScene");
	testLevel.addScene(&testScene);
	testLevel.changeScene("testScene");
	testLevel.getFightSystem()->setParticle(particle);

	//==================Add Camera to Scene============================//
	testScene.getScenegraph()->addCamera(&cam);
	testScene.getScenegraph()->setActiveCamera("PlayerViewCam");

	//==================Set Input-Maps and activate one================//
	iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera()));
	iH.changeActiveInputMap(MapType::OBJECT);
	iH.getActiveInputMap()->update(geko);

	//==================Add Objects to the Scene=======================//
	//==================Update the Bounding-Sphere 1st time============//
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNode);

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode);

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&terrainNode);

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode);

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&particleNode);
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&particleNodeFire);
	testScene.getScenegraph()->addParticleSystem(particle);
	testScene.getScenegraph()->addParticleSystem(particle2);
	testScene.getScenegraph()->addParticleSystem(particleFire);

	// ==============================================================
	// == Questsystem ====================================================
	// ==============================================================
	//QuestHandler questhandler;


	/*Quest questCollect(1);


	questCollect.setActive(true);
	Goal_Collect goalCollect(1);
	Goal_Collect goalCollect3(3);
	questCollect.addGoal(&goalCollect);
	questCollect.addGoal(&goalCollect3);

	ExpReward expReward(1);
	expReward.setExp(100);
	questCollect.addReward(&expReward);

	Item cookie2(100);
	cookie2.setName("Cookie100");
	cookie2.setTypeId(ItemType::COOKIE);
	ItemReward itemReward(2);
	itemReward.addItem(&cookie2);

	questCollect.addReward(&itemReward);

	Quest questCollect2(2);
	questCollect2.setActive(true);
	Goal_Collect goalCollect2(2);
	questCollect2.addGoal(&goalCollect2);
	questCollect2.addReward(&expReward);
	questCollect2.addReward(&itemReward);

	goalCollect.setGoalCount(50);
	goalCollect2.setGoalCount(50);
	goalCollect3.setGoalCount(50);

	goalCollect.setItemType(ItemType::BRANCH);
	goalCollect2.setItemType(ItemType::BRANCH);
	goalCollect3.setItemType(ItemType::COOKIE);

	testLevel.getQuestHandler()->addQuest(&questCollect);
	testLevel.getQuestHandler()->addQuest(&questCollect2);*/

	Quest questKillAnt(1);
	Quest questEatAnt(2);
	Quest questCollectCookie(3);
	Quest questCollectBranch(4);

	Goal_Kill killAnt(1);
	Goal_Eaten eatAnt(2);
	Goal_Collect collectCookie(3);
	Goal_Collect collectBranch(4);

	questKillAnt.addGoal(&killAnt);
	questEatAnt.addGoal(&eatAnt);
	questCollectCookie.addGoal(&collectCookie);
	questCollectBranch.addGoal(&collectBranch);

	killAnt.setGoalCount(1);
	eatAnt.setGoalCount(1);
	collectCookie.setGoalCount(1);
	collectBranch.setGoalCount(1);

	collectBranch.setItemType(ItemType::BRANCH);
	collectCookie.setItemType(ItemType::COOKIE);

	ExpReward expReward(1);
	expReward.setExp(100);

	questKillAnt.addReward(&expReward);
	questEatAnt.addReward(&expReward);
	questCollectCookie.addReward(&expReward);
	questCollectBranch.addReward(&expReward);

	QuestGraph questGraph;
	QuestGraphNode nodeStart;
	nodeStart.setQuest(&questKillAnt);
	questGraph.addNode(&nodeStart);
	questKillAnt.setActive(true);

	QuestGraphNode nodeSecond;
	nodeSecond.setQuest(&questEatAnt);
	nodeSecond.setParent(&nodeStart);
	questGraph.addNode(&nodeSecond);

	QuestGraphNode nodeThird;
	nodeThird.setQuest(&questCollectCookie);
	nodeThird.setParent(&nodeSecond);
	questGraph.addNode(&nodeThird);

	QuestGraphNode nodeFourth;
	nodeFourth.setQuest(&questCollectBranch);
	nodeFourth.setParent(&nodeThird);
	questGraph.addNode(&nodeFourth);

	testLevel.getQuestHandler()->addQuest(&questKillAnt);
	testLevel.getQuestHandler()->addQuest(&questEatAnt);
	testLevel.getQuestHandler()->addQuest(&questCollectBranch);
	testLevel.getQuestHandler()->addQuest(&questCollectCookie);

	testLevel.getQuestHandler()->setGraph(&questGraph);


	//===================================================================//
	//==================Setting up the Collision=========================//
	//==================================================================//
	CollisionTest collision;
	collision.collectNodes(testScene.getScenegraph()->getRootNode());


	//===================================================================//
	//==================Setting up the Observers========================//
	//==================================================================//
	ObjectObserver aiObserver(&testLevel);
	SoundObserver soundAIObserver(&testLevel);
	ant_Flick.addObserver(&aiObserver);
	ant_Flick.addObserver(&soundAIObserver);

	ObjectObserver playerObserver(&testLevel);
	SoundObserver soundPlayerObserver(&testLevel);
	geko.addObserver(&playerObserver);
	geko.addObserver(&soundPlayerObserver);

	CollisionObserver colObserver(&testLevel);
	collision.addObserver(&colObserver);
	collision.addObserver(&soundPlayerObserver);

	GravityObserver gravityObserver(&testLevel);
	collision.addObserver(&gravityObserver);

	QuestObserver questObserver(&testLevel);
	/*questCollect.addObserver(&questObserver);
	questCollect2.addObserver(&questObserver);
	questCollect.addObserver(&soundPlayerObserver);
	questCollect2.addObserver(&soundPlayerObserver);

	goalCollect.addObserver(&questObserver);
	goalCollect2.addObserver(&questObserver);
	goalCollect3.addObserver(&questObserver);*/
	questKillAnt.addObserver(&questObserver);
	questEatAnt.addObserver(&questObserver);
	questCollectCookie.addObserver(&questObserver);
	questCollectBranch.addObserver(&questObserver);

	killAnt.addObserver(&questObserver);
	eatAnt.addObserver(&questObserver);
	collectCookie.addObserver(&questObserver);
	collectBranch.addObserver(&questObserver);

	testLevel.getFightSystem()->addObserver(&questObserver);



	//===================================================================//
	//==================Setting up the Gravity===========================//
	//==================================================================//
	Gravity gravity;
	playerNode.addGravity(&gravity);
	aiNode.addGravity(&gravity);

	//===================================================================//
	//==================The Render-Loop==================================//
	//==================================================================//
	float lastTime = glfwGetTime();

	sfh.playSource("Feuer");
	sfh.playSource("Hintergrund");
	sfh.setGain("Hintergrund", 0.5f);

	//===================================================================//
	//==================The Particle-System==============================//
	//==================================================================//
	//Effect* smBla = new Effect();
	//smBla->loadEffect((char*)RESOURCES_PATH "/XML/ComicCloudEffect.xml");
	//ParticleSystem* particle = new ParticleSystem(glm::vec3(0, 0, -10), smBla);
	//	ParticleSystem* particle = new ParticleSystem(glm::vec3(0, 0, 0), (char*)RESOURCES_PATH "/XML/ComicCloudEffect.xml");

	//===================================================================//
	//==================The GUI=========================================//
	//==================================================================//


	//========================================================================================================
	//SETUP GUI
	//Texture bricks((char*)RESOURCES_PATH "/bricks_diffuse.png");
	//hud = new GUI("testGUI", HUD_WIDTH, HUD_HEIGHT);
	//hud->setPosition((WINDOW_WIDTH / 2) - (HUD_WIDTH / 2), WINDOW_HEIGHT - HUD_HEIGHT);
	//hud->setCollapsable(false);
	//hud->setTitleBarVisible(false);
	//hud->setBackgroundAlpha(0.5f);
	//hud->setResizable(false);
	//hud->setUseScrollbar(false);
	//hud->setMoveable(false);

	//int hp = playerNode.getPlayer()->getHealth();
	//int hpMax = 10;
	//int exp = playerNode.getPlayer()->getExp();
	//int expMax = playerNode.getPlayer()->getLevelThreshold();

	//GuiElement::ProgressBar *hpBar = new GuiElement::ProgressBar(&hp, hpMax, 300, glm::fvec4(1.0f, 0.0f, 0.0f, 1.0f));
	//hud->addElement(hpBar);
	//hud->addElement(new GuiElement::SameLine());
	//hud->addElement(new GuiElement::Text("HP"));

	//GuiElement::ProgressBar *expBar = new GuiElement::ProgressBar(&exp, expMax, 300, glm::fvec4(1.0f, 0.9960784f, 0.9529411f, 1.0f));
	//hud->addElement(expBar);
	//hud->addElement(new GuiElement::SameLine());
	//hud->addElement(new GuiElement::Text("EXP"));

	//hud->addElement(new GuiElement::Spacing());
	//hud->addElement(new GuiElement::Separator());
	//hud->addElement(new GuiElement::Spacing());
	//hud->addElement(new GuiElement::Text("LVL"));

	//int level = playerNode.getPlayer()->getLvl();
	//hud->addElement(new GuiElement::SameLine());
	//GuiElement::IntBox *lvlBox = new GuiElement::IntBox(&level, glm::fvec4(1.0f, 1.0f, 1.0f, 1.0f), glm::fvec4(0.7f, 0.7f, 0.7f, 1.0f));
	//hud->addElement(lvlBox);

	//hud->addElement(new GuiElement::SameLine());
	//GuiElement::PushButton *inventoryButton = new GuiElement::PushButton("Inventory");
	//hud->addElement(inventoryButton);
	//hud->addElement(new GuiElement::SameLine());
	//GuiElement::PushButton *questButton = new GuiElement::PushButton("Quests");
	//hud->addElement(questButton);

	//questWindow = new GuiElement::NestedWindow();
	//questWindow->hide();
	//GuiElement::Header *quest1 = new GuiElement::Header("Test the Quest");
	//quest1->addElement(new GuiElement::Text("Quest description here bla bla bla"));
	//GuiElement::Header *quest2 = new GuiElement::Header("Testwindow Questwindow");
	//quest2->addElement(new GuiElement::Text("Quest description here too bla bla bla"));
	//questWindow->addElement(quest1);
	//questWindow->addElement(quest2);
	//questWindow->setName("Quests");
	//questWindow->setCollapsable(false);
	//questWindow->setPosition(WINDOW_WIDTH - QUEST_WIDTH, (WINDOW_HEIGHT / 2) - (QUEST_HEIGHT / 2));
	//questWindow->setSize(QUEST_WIDTH, QUEST_HEIGHT);
	//hud->addNestedWindow(questWindow);

	//inventoryWindow = new GuiElement::NestedWindow();
	//inventoryWindow->hide();

	//inventoryWindow->setName("Inventory");
	//inventoryWindow->setCollapsable(false);
	//inventoryWindow->setResizable(false);
	//inventoryWindow->setPosition(WINDOW_WIDTH - QUEST_WIDTH, (WINDOW_HEIGHT / 2) - (QUEST_HEIGHT / 2));
	//inventoryWindow->setSize(QUEST_WIDTH, QUEST_HEIGHT);
	//hud->addNestedWindow(inventoryWindow);

	//std::map<std::string, Texture*> *inventoryItems = new std::map<std::string, Texture*>();
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem1"), &bricks));
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem2"), &bricks));
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem3"), &bricks));
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem4"), &bricks));
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem5"), &bricks));
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem6"), &bricks));
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem7"), &bricks));
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem8"), &bricks));
	//inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem9"), &bricks));
	//GuiElement::Inventory *inventory = new GuiElement::Inventory(inventoryItems, 6);
	//inventoryWindow->addElement(inventory);
	
//	PlayerGUI playerGUI(HUD_WIDTH, HUD_HEIGHT, WINDOW_HEIGHT, WINDOW_WIDTH, QUEST_HEIGHT, QUEST_WIDTH, playerNode.getPlayer());


	float testFloat = float(0.0f);
	float testFloat2 = float(0.0f);

	/*testLevel.addGUI(hud);
	testLevel.getGUI("testGUI")->m_windowName;*/

	while (!glfwWindowShouldClose(testWindow.getWindow()))
	{

		//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		float currentTime = glfwGetTime();
		float deltaTime = currentTime - lastTime;
		lastTime = currentTime;

		fboGBuffer.bind();
		glClearColor(0.5, 0.5, 0.5, 1.0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		shaderGBuffer.bind();
		shaderGBuffer.sendMat4("viewMatrix", cam.getViewMatrix());
		shaderGBuffer.sendMat4("projectionMatrix", cam.getProjectionMatrix());
		
		testScene.render(shaderGBuffer);


		ant_Flick.update();
		geko.update();
		geko.deleteKeyInput();
		geko.setDeltaTime(currentTime);
		collision.update();

		//TEST
		//particle->update(cam);
		//particle->render(cam);

		shaderGBuffer.unbind();
	
		fboGBuffer.unbind();

		//ScreenFillingQuad Render Pass
		shaderSFQ.bind();
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		shaderSFQ.sendSampler2D("fboTexture", fboGBuffer.getColorTexture(2));

		screenFillingQuad.renderGeometry();
		shaderSFQ.unbind();

		glfwSwapBuffers(testWindow.getWindow());
		glfwPollEvents();
	}



	glfwDestroyWindow(testWindow.getWindow());
	glfwTerminate();


	return 0;

}
Ejemplo n.º 15
0
//===================================================================//
//==================Main Method=====================================//
//==================================================================//
int main()
{

	//===================================================================//
	//==================Things you need to start with====================//
	//==================================================================//
	glfwInit();

	Window testWindow(500, 50, 800, 600, "Demo");
	glfwMakeContextCurrent(testWindow.getWindow());

	// Callback
	glfwSetKeyCallback(testWindow.getWindow(), key_callback);

	cam.setKeySpeed(2.0);
	cam.setNearFar(0.01, 100);

	glewInit();

	OpenGL3Context context;
	//renderer = new Renderer(context);
	Renderer renderer(context);

	//===================================================================//
	//==================Shaders for your program========================//
	//==================================================================//
	VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/Vertex-Shaders/TextureShader3D.vert")));
	FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/Fragment-Shaders/TextureShader3D.frag")));
	ShaderProgram shader(vs, fs);

	VertexShader vsGBuffer(loadShaderSource(SHADERS_PATH + std::string("/GBuffer/GBuffer.vert")));
	FragmentShader fsGBuffer(loadShaderSource(SHADERS_PATH + std::string("/GBuffer/GBuffer.frag")));
	ShaderProgram shaderGBuffer(vsGBuffer, fsGBuffer);

	VertexShader vsSfq(loadShaderSource(SHADERS_PATH + std::string("/ScreenFillingQuad/ScreenFillingQuad.vert")));
	FragmentShader fsSfq(loadShaderSource(SHADERS_PATH + std::string("/ScreenFillingQuad/ScreenFillingQuad.frag")));
	ShaderProgram shaderSFQ(vsSfq, fsSfq);

	VertexShader vsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.vert")));
	FragmentShader fsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.frag")));
	ShaderProgram shaderSkybox(vsSkybox, fsSkybox);

	FBO fboGBuffer(WINDOW_WIDTH, WINDOW_HEIGHT, 3, true, false);

	SoundFileHandler sfh = SoundFileHandler(1000);

	Rect screenFillingQuad;
	screenFillingQuad.loadBufferData();

	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: Terrain===========================//

	StaticObject terrainObject;
	terrainObject.setClassType(ClassType::TERRAIN);

	Texture terrainTex((char*)RESOURCES_PATH "/Grass2.jpg");

	Terrain terrain2((char*)RESOURCES_PATH "/heightmap.jpg", 0.0f, 0.0f);
	Node terrainNode2("Terrain");
	terrainNode2.addGeometry(&terrain2);
	terrainNode2.addTexture(&terrainTex);
	terrainNode2.setObject(&terrainObject);


	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: Player===========================//

	Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp");

	GekoMesh gekoMesh;
	geko.setExp(0.0);
	geko.setLevelThreshold(100.0);
	geko.setLevel(0);

	Node playerNode("Player");

	playerNode.addGeometry(&gekoMesh);
	playerNode.setObject(&geko);
	playerNode.addTexture(&texCV);

	sfh.generateSource(glm::vec3(geko.getPosition()), RESOURCES_PATH "/Sound/Rascheln.wav");
	geko.setSoundHandler(&sfh);
	geko.setSourceName(MOVESOUND, "SpielerFootsteps", RESOURCES_PATH "/Sound/Rascheln.wav");
	//geko.setSourceName(BACKGROUNDMUSIC, "Hintergrund", RESOURCES_PATH "/Sound/jingle2.wav");
	geko.setSourceName(FIGHTSOUND, "Kampfsound", RESOURCES_PATH "/Sound/punch.wav");
	geko.setSourceName(EATSOUND, "Essen", RESOURCES_PATH "/Sound/Munching.wav");
	geko.setSourceName(QUESTSOUND, "Quest", RESOURCES_PATH "/Sound/jingle.wav");
	geko.setSourceName(ITEMSOUND, "Item", RESOURCES_PATH "/Sound/itempickup.wav");
	geko.setSourceName(FIRESOUND, "Fire", RESOURCES_PATH "/Sound/Feuer_kurz.wav");

	sfh.disableLooping("Essen");
	sfh.disableLooping("Quest");
	sfh.disableLooping("Item");
	geko.setPosition(glm::vec4(terrain2.getResolutionX() / 2.0f, 10.0f, terrain2.getResolutionY() / 2.0f, 1.0));
	//sfh.generateSource("Feuer",posFood, RESOURCES_PATH "/Sound/Feuer kurz.wav");
	playerNode.setCamera(&cam);

	//===================================================================//
	//==================Setting up the Level and Scene==================//
	//==================================================================//

	Level testLevel("testLevel");
	Scene testScene("testScene");
	testLevel.addScene(&testScene);
	testLevel.changeScene("testScene");
	testLevel.setTerrain(&terrain2);

	//==================Add Camera to Scene============================//
	testScene.getScenegraph()->addCamera(&cam);
	testScene.getScenegraph()->setActiveCamera("PlayerViewCam");

	//==================Set Input-Maps and activate one================//
	iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera()));
	iH.changeActiveInputMap(MapType::OBJECT);
	iH.getActiveInputMap()->update(geko);

	//==================Add Objects to the Scene=======================//
	//==================Update the Bounding-Sphere 1st time============//
	/*Node translateNode("Translate");
	translateNode.addTranslation(glm::vec3(terrain2.getResolutionX() / 2.0f, 0.0, terrain2.getResolutionY() / 2.0f));*/

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&terrainNode2);
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode);
	//testScene.getScenegraph()->getRootNode()->addChildrenNode(&translateNode);
	//testScene.getScenegraph()->getRootNode()->getChildrenNode("Translate")->addChildrenNode(&playerNode);



	//===================================================================//
	//==================Setting up the Observers========================//
	//==================================================================//

	ObjectObserver playerObserver(&testLevel);
	SoundObserver soundPlayerObserver(&testLevel);
	geko.addObserver(&playerObserver);
	geko.addObserver(&soundPlayerObserver);


	// ==============================================================
	// == Object (Forest) ==========================================
	// ==============================================================
	TreeMesh tree;

	glm::vec3 tmp;
	std::stringstream name;
	for (int i = 0; i<TreeData::forest1.size(); i++)
	{
		name << "Forest1Tree" << i;
		std::string stringname = name.str();
		StaticObject *treeStatic = new StaticObject();
		treeStatic->setTree(50 / TreeData::forest1.size());
		Node *treeNode = new Node(stringname);
		treeNode->addGeometry(&tree);
		treeNode->setObject(treeStatic);
		tmp.x = TreeData::forest1[i].x;
		tmp.z = TreeData::forest1[i].z;
		tmp.y = terrain2.getHeight(glm::vec2(tmp.x, tmp.z));
		treeNode->addTranslation(tmp);
		treeNode->getBoundingSphere()->radius = 2.5;
		testScene.getScenegraph()->getRootNode()->addChildrenNode(treeNode);
		name.str("");
	}
	for (int i = 0; i<TreeData::forest2.size(); i++)
	{
		name << "Forest2Tree" << i;
		std::string stringname = name.str();
		StaticObject *treeStatic = new StaticObject();
		treeStatic->setTree(50 / TreeData::forest2.size());
		Node *treeNode = new Node(stringname);
		treeNode->addGeometry(&tree);
		treeNode->setObject(treeStatic);

		tmp.x = TreeData::forest2[i].x;
		tmp.z = TreeData::forest2[i].z;
		tmp.y = terrain2.getHeight(glm::vec2(tmp.x, tmp.z));
		treeNode->addTranslation(tmp);
		treeNode->getBoundingSphere()->radius = 2.5;
		testScene.getScenegraph()->getRootNode()->addChildrenNode(treeNode);
		name.str("");
	}

	// ==============================================================
	// == Object (Anthome) ==========================================
	// ==============================================================
	glm::vec3 posFood(10.0, 0.0, -5.0);
	glm::vec3 posFood2((terrain2.getResolutionX() / 2.0f) + 10.0, 0.0, (terrain2.getResolutionY() / 2.0f) - 5.0);
	glm::vec3 posSpawn(terrain2.getResolutionX() / 2.0f, 10.0, terrain2.getResolutionY() / 2.0f);
	glm::vec3 posDefaultPlayer(0.0, 0.0, 0.0);
	AntMesh antMesh;

	DecisionTree *aggressivedecisionTree = new DecisionTree();
	aggressivedecisionTree->setAntTreeAggressiv();

	DecisionTree *afraidDecisionTree = new DecisionTree();
	afraidDecisionTree->setAntTreeAfraid();

	Graph<AStarNode, AStarAlgorithm>* antAggressiveGraph = new Graph<AStarNode, AStarAlgorithm>();
	antAggressiveGraph->setExampleAntAggressiv(posSpawn, posFood2, posDefaultPlayer);

	Graph<AStarNode, AStarAlgorithm>* antAfraidGraph = new Graph<AStarNode, AStarAlgorithm>();
	antAfraidGraph->setExampleAntAfraid2(posSpawn, posDefaultPlayer);

	AntHome antHome(posSpawn, antMesh, &playerObserver, &texCV, &texCV, aggressivedecisionTree, antAggressiveGraph, afraidDecisionTree, antAfraidGraph);
	//antHome.generateGuards(5, &aiObserver, testScene.getScenegraph()->getRootNode());
	antHome.generateWorkers(5, testScene.getScenegraph()->getRootNode());
	/*antHome.addAntsToSceneGraph(testScene.getScenegraph()->getRootNode());*/





	//===================================================================//
	//==================Setting up the Collision=========================//
	//==================================================================//
	CollisionTest collision;
	collision.collectNodes(testScene.getScenegraph()->getRootNode());

	CollisionObserver colObserver(&testLevel);
	collision.addObserver(&colObserver);
	collision.addObserver(&soundPlayerObserver);

	GravityObserver gravityObserver(&testLevel);
	collision.addObserver(&gravityObserver);



	//===================================================================//
	//==================Setting up the Gravity===========================//
	//==================================================================//
	Gravity gravity;
	playerNode.addGravity(&gravity);

	//===================================================================//
	//==================Setting up the Gravity===========================//
	//==================================================================//
	PlayerGUI playerGUI(HUD_WIDTH, HUD_HEIGHT, WINDOW_HEIGHT, WINDOW_WIDTH, QUEST_HEIGHT, QUEST_WIDTH, playerNode.getPlayer());

	//===================================================================//
	//==================The Render-Loop==================================//
	//==================================================================//
	float lastTime = glfwGetTime();

	sfh.playSource("Hintergrund");
	sfh.setGain("Hintergrund", 0.5f);


	//TODO adjust the Rotation,to match the Terrain
	glm::vec4 tmpPos;
	glm::vec3 normalFromTerrain;
	glm::vec3 rotateAxis;
	glm::vec4 viewDirFromPlayer;
	glm::vec3 up(0.0, 1.0, 0.0);
	float lengthFromNormal;
	float lengthFromUp;
	float phi;



	while (!glfwWindowShouldClose(testWindow.getWindow()))
	{


		float currentTime = glfwGetTime();
		float deltaTime = currentTime - lastTime;
		lastTime = currentTime;


		//===================================================================//
		//==================Update your Objects per Frame here =============//
		//==================================================================//
		collision.update();


		//===================================================================//
		//==================Input and update for the Player==================//
		//==================================================================//

		geko.update();
		geko.setDeltaTime(currentTime);

		tmpPos = testScene.getScenegraph()->searchNode("Player")->getPlayer()->getPosition();
		viewDirFromPlayer = testScene.getScenegraph()->searchNode("Player")->getPlayer()->getViewDirection();
		//ToDo calculate Normal funktioniert evtl falsch
		normalFromTerrain = terrain2.calculateNormal(tmpPos.x, tmpPos.z);
		rotateAxis = glm::cross(glm::vec3(viewDirFromPlayer), normalFromTerrain );
	//	lengthFromNormal = glm::length(normalFromTerrain);
	//	lengthFromUp = glm::length(up);
		normalFromTerrain = glm::normalize(normalFromTerrain);
		up = glm::normalize(up);
		phi = glm::dot(up, normalFromTerrain);
		phi = glm::atan(phi) * (180 / glm::pi<float>());
	//	phi = glm::acos(glm::dot(normalFromTerrain, up) / (lengthFromNormal * lengthFromUp));
		//ToDo Rotation überschreibt die frühere Rotation
		testScene.getScenegraph()->searchNode("Player")->addRotation(phi, rotateAxis);

		antHome.updateAnts();

		//===================================================================//
		//==================Render your Objects==============================//
		//==================================================================//
		//renderer.renderScene(testScene, testWindow);


		fboGBuffer.bind();
		glClearColor(0.5, 0.5, 0.5, 0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		shaderGBuffer.bind();
		shaderGBuffer.sendMat4("viewMatrix", cam.getViewMatrix());
		shaderGBuffer.sendMat4("projectionMatrix", cam.getProjectionMatrix());

		testScene.render(shaderGBuffer);


		shaderGBuffer.unbind();
		fboGBuffer.unbind();

		//ScreenFillingQuad Render Pass
		shaderSFQ.bind();
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		shaderSFQ.sendSampler2D("fboTexture", fboGBuffer.getColorTexture(2));

		screenFillingQuad.renderGeometry();
		shaderSFQ.unbind();

		renderer.renderGUI(*playerGUI.getHUD(), testWindow);
		glfwSwapBuffers(testWindow.getWindow());
		glfwPollEvents();


	}



	glfwDestroyWindow(testWindow.getWindow());
	glfwTerminate();


	return 0;

}
Ejemplo n.º 16
0
//===================================================================//
//==================Main Method=====================================//
//==================================================================//
int main()
{

	//===================================================================//
	//==================Things you need to start with====================//
	//==================================================================//
	glfwInit();

	Window testWindow(500, 50, 800, 600, "testWindow");
	glfwMakeContextCurrent(testWindow.getWindow());

	cam.setCenter(glm::vec4(0.0, 10.0, 20.0, 1.0));
	cam.setName("StrategyCam");
	cam.setKeySpeed(2.0);
	cam.setNearFar(0.0001, 100);

	glfwSetKeyCallback(testWindow.getWindow(), key_callback);
	glfwSetScrollCallback(testWindow.getWindow(), mouseScroll_callback);

	glewInit();

	OpenGL3Context context;
	Renderer renderer(context);

	//===================================================================//
	//==================Shaders for your program========================//
	//==================================================================//
	VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/TextureShader3D/TextureShader3D.vert")));
	FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/TextureShader3D/TextureShader3D.frag")));
	ShaderProgram shader(vs, fs);


	//===================================================================//
	//==================A Graph for the AI-Unit=========================//
	//==================================================================//

	glm::vec3 posFood(10.0, 0.0, -5.0);
	glm::vec3 posSpawn(10.0, 0.0, 60.0);
	Graph<AStarNode, AStarAlgorithm> testGraph;
//	testGraph.setExampleGraph2(posSpawn, posFood, geko.getPosition());

	//===================================================================//
	//==================A Decision-Tree for the AI-Unit==================//
	//==================================================================//

	DecisionTree defaultTree;
	defaultTree.setAntTreeAggressiv();


	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: AI==============================//

	Teapot teaAnt;

	Texture texPlayer((char*)RESOURCES_PATH "/Snake.jpg");
	SoundFileHandler sfh = SoundFileHandler(1000);

	//AStarNode defaultASNode("Default");
	//AI ant_Flick(&defaultTree, &defaultASNode, &aiNode);
	AI ant_Flick;
	//ant_Flick.setAntAfraid();
	/*ant_Flick.setGraph(&testGraph);
	ant_Flick.setPosition(posSpawn);
	ant_Flick.setPosHome(testGraph.searchNode("Spawn"));*/
	//ant_Flick.addFoodNodes(testGraph.searchNode("Food"));

	AntMesh ant;

	Node aiNode("Flick");
	aiNode.addGeometry(&ant);
	aiNode.addTexture(&texPlayer);
//	aiNode.addScale(0.3, 0.3, 0.3);
	//aiNode.addTranslation(ant_Flick.getPosition().x, ant_Flick.getPosition().y, ant_Flick.getPosition().z);
	aiNode.setObject(&ant_Flick);
	//aiNode.setSoundHandler(&sfh);
//	aiNode.setSourceName("Ameise1", RESOURCES_PATH "/Sound/Footsteps.wav");




	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: Player===========================//
	Teapot teaPlayer;
	Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp");

	GekoMesh gekoMesh;
	geko.setExp(0.0);
	geko.setLevelThreshold(100.0);
	geko.setLevel(0);

	Node playerNode("Player");

	playerNode.addGeometry(&gekoMesh);
	playerNode.setObject(&geko);
	playerNode.addTexture(&texCV);
//	playerNode.addScale(0.5, 0.5, 0.5);
//	playerNode.addTranslation(20.0, 0.0, 20.0);

	geko.setSoundHandler(&sfh);
	geko.setSourceName(MOVESOUND, "SpielerFootsteps", RESOURCES_PATH "/Sound/rascheln.wav");
	geko.setSourceName(BACKGROUNDMUSIC, "Hintergrund", RESOURCES_PATH "/Sound/jingle2.wav");
	geko.setSourceName(FIGHTSOUND, "Kampfsound", RESOURCES_PATH "/Sound/Cookies kurz.wav");
	geko.setSourceName(EATSOUND, "Essen", RESOURCES_PATH "/Sound/Munching.wav");
	geko.setSourceName(QUESTSOUND, "Quest", RESOURCES_PATH "/Sound/jingle.wav");
	geko.setSourceName(ITEMSOUND, "Item", RESOURCES_PATH "/Sound/itempickup.wav");
	sfh.disableLooping("Essen");
	sfh.disableLooping("Kampfsound");
	sfh.disableLooping("Quest");
	sfh.disableLooping("Item");
	sfh.generateSource("Feuer",posFood, RESOURCES_PATH "/Sound/Feuer kurz.wav");



	playerNode.setCamera(&cam);

	// ==============================================================
	// == Items =====================================================
	// ==============================================================
	/*Item cookie(1);
	cookie.setName("Cookie");
	cookie.setTypeId(ItemType::COOKIE);
	Item cookie2(2);
	cookie.setName("Cookie");
	cookie.setTypeId(ItemType::COOKIE);
	Item branch(3);
	branch.setName("Branch");
	branch.setTypeId(ItemType::BRANCH);
*/


	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: Tree===========================//

	TreeMesh tree;

	glm::vec3 trees[5] = { glm::vec3(16.0, 0.0, 76.0), glm::vec3(23.0, 0.0, 74.0), glm::vec3(21.5, 0.0, 78.5), glm::vec3(15.0, 0.0, 81.5), glm::vec3(27.5, 0.0, 88.5), };

	StaticObject treeStatic;
	treeStatic.setTree();
//	treeStatic.setObjectType(ObjectType::TREE);
	Node treeNode("Tree");
	treeNode.addGeometry(&tree);
	treeNode.setObject(&treeStatic);

	//treeNode.addScale(10.0, 10.0, 10.0);
	treeNode.addTranslation(trees[0]);

	treeNode.getBoundingSphere()->radius = 3.0;

	StaticObject treeStatic2;
	treeStatic2.setTree();
	Node treeNode2("Tree2");
	treeNode2.addGeometry(&tree);
	treeNode2.setObject(&treeStatic2);
	treeNode2.addTranslation(trees[1]);
	treeNode2.getBoundingSphere()->radius = 3.0;

	StaticObject treeStatic3;
	treeStatic3.setTree();
	Node treeNode3("Tree3");
	treeNode3.addGeometry(&tree);
	treeNode3.setObject(&treeStatic3);
	treeNode3.addTranslation(trees[2]);
	treeNode3.getBoundingSphere()->radius = 3.0;

	StaticObject treeStatic4;
	treeStatic4.setTree();
	Node treeNode4("Tree4");
	treeNode4.addGeometry(&tree);
	treeNode4.setObject(&treeStatic4);
	treeNode4.addTranslation(trees[3]);
	treeNode4.getBoundingSphere()->radius = 3.0;

	StaticObject treeStatic5;
	treeStatic5.setTree();
	Node treeNode5("Tree5");
	treeNode5.addGeometry(&tree);
	treeNode5.setObject(&treeStatic5);
	treeNode5.addTranslation(trees[4]);
	treeNode5.getBoundingSphere()->radius = 3.0;

	//treeStatic.getInventory()->addItem(&cookie, 25);
	//treeStatic.getInventory()->addItem(&branch, 10);

	//===================================================================//
	//==================Object declarations - Geometry, Texture, Node=== //
	//==========================Object: Plane===========================//

	Plane terrain;
	Texture terrainTex((char*)RESOURCES_PATH "/Grass.jpg");

	Node terrainNode("Plane");
	terrainNode.addGeometry(&terrain);
	terrainNode.addTexture(&terrainTex);
	terrainNode.addTranslation(0.0, -0.75, 0.0);
	terrainNode.addRotation(90.0f, glm::vec3(1.0, 0.0, 0.0));
	terrainNode.addScale(100.0, 100.0, 100.0);

	//===================================================================//
	//==================Setting up the Level and Scene==================//
	//==================================================================//

	Level testLevel("testLevel");
	Scene testScene("testScene");
	testLevel.addScene(&testScene);
	testLevel.changeScene("testScene");

	//==================Add Camera to Scene============================//
	testScene.getScenegraph()->addCamera(&cam);
	testScene.getScenegraph()->setActiveCamera("StrategyCam");

	//==================Set Input-Maps and activate one================//
	iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera()));
	iH.changeActiveInputMap("Strategy");

	//==================Add Objects to the Scene=======================//
	//==================Update the Bounding-Sphere 1st time============//
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNode);

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode);

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&terrainNode);

	testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode);
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode2);
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode3);
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode4);
	testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode5);



	// ==============================================================
	// == Questsystem ====================================================
	// ==============================================================
	//QuestHandler questhandler;

	//testLevel.getQuestHandler()->getGraph()->setExampleGraph();
	Quest questCollect(1);
	questCollect.setActive(true);
	Goal_Collect goalCollect(1);
	Goal_Collect goalCollect3(3);
	questCollect.addGoal(&goalCollect);
	questCollect.addGoal(&goalCollect3);

	ExpReward expReward(1);
	expReward.setExp(100);
	questCollect.addReward(&expReward);

	Quest questCollect2(2);
	questCollect2.setActive(true);
	Goal_Collect goalCollect2(2);
	questCollect2.addGoal(&goalCollect2);
	questCollect2.addReward(&expReward);

	goalCollect.setGoalCount(50);
	goalCollect2.setGoalCount(50);
	goalCollect3.setGoalCount(50);

	goalCollect.setItemType(ItemType::BRANCH);
	goalCollect2.setItemType(ItemType::BRANCH);
	goalCollect3.setItemType(ItemType::COOKIE);

	testLevel.getQuestHandler()->addQuest(&questCollect);
	testLevel.getQuestHandler()->addQuest(&questCollect2);

	//===================================================================//
	//==================Setting up the Collision=========================//
	//==================================================================//
	CollisionTest collision;
	collision.collectNodes(testScene.getScenegraph()->getRootNode());

	//===================================================================//
	//==================Setting up the Observers========================//
	//==================================================================//
	ObjectObserver aiObserver(&testLevel);
	SoundObserver soundAIObserver(&testLevel);
	ant_Flick.addObserver(&aiObserver);
	ant_Flick.addObserver(&soundAIObserver);

	ObjectObserver playerObserver(&testLevel);
	SoundObserver soundPlayerObserver(&testLevel);
	geko.addObserver(&playerObserver);
	geko.addObserver(&soundPlayerObserver);

	CollisionObserver colObserver(&testLevel);
	collision.addObserver(&colObserver);
	collision.addObserver(&soundPlayerObserver);

	GravityObserver gravityObserver(&testLevel);
	collision.addObserver(&gravityObserver);

	QuestObserver questObserver(&testLevel);
	questCollect.addObserver(&questObserver);
	questCollect2.addObserver(&questObserver);
	questCollect.addObserver(&soundPlayerObserver);
	questCollect2.addObserver(&soundPlayerObserver);
	
	goalCollect.addObserver(&questObserver);
	goalCollect2.addObserver(&questObserver);
	goalCollect3.addObserver(&questObserver);

	testLevel.getFightSystem()->addObserver(&questObserver);



	//===================================================================//
	//==================Setting up the Gravity===========================//
	//==================================================================//
	Gravity gravity;
	playerNode.addGravity(&gravity);
	aiNode.addGravity(&gravity);

	//===================================================================//
	//==================The Render-Loop==================================//
	//==================================================================//
	float lastTime = glfwGetTime();

	Node* tmp = testLevel.getActiveScene()->getScenegraph()->searchNode("Plane");
	tmp->getNodeName();

	sfh.updateListenerPosition(glm::vec3(10.0, 3.0, -5.0));
	sfh.playSource("Feuer");
	sfh.playSource("Hintergrund");
	sfh.setGain("Hintergrund", 0.5f);
	while (!glfwWindowShouldClose(testWindow.getWindow()))
	{
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		float currentTime = glfwGetTime();
		float deltaTime = currentTime - lastTime;
		lastTime = currentTime;
		
		mouse_callback(testWindow.getWindow());

		
		//===================================================================//
		//==================Update your Objects per Frame here =============//
		//==================================================================//
		collision.update();

		//ant_Flick.updateState();
		ant_Flick.update();


		//===================================================================//
		//==================Input and update for the Player==================//
		//==================================================================//

		playKey_callback(testWindow.getWindow());
		//geko.update(deltaTime);

		//===================================================================//
		//==================Render your Objects==============================//
		//==================================================================//
		glEnable(GL_DEPTH_TEST);

		shader.bind();
		shader.sendMat4("viewMatrix", cam.getViewMatrix());
		shader.sendMat4("projectionMatrix", cam.getProjectionMatrix());

		testScene.render(shader);
		shader.unbind();


		glfwSwapBuffers(testWindow.getWindow());
		glfwPollEvents();

	}

	glfwDestroyWindow(testWindow.getWindow());
	glfwTerminate();

	
	return 0;

}
Ejemplo n.º 17
0
void violet::HUD::drawInventory(Player* player) {
	int topBasePoint = m_videoManager->RegularText->getIndent()
			+ (m_videoManager->RegularText->getHeight()) * 4;

	VideoMode screen = m_videoManager->getVideoMode();
	const int barLeft = screen.Width / 25;
	const int barLen = screen.Width / 15;
	const int barHeight = m_videoManager->RegularText->getHeight() / 10;

	GLfloat bcolor[] = { 1.0f, 1.0f, 1.0f, 0.0f };
	GLfloat fcolor1[] = { 1.0f, 1.0f, 1.0f, 1.0f };
	GLfloat fcolor2[] = { 1.0f, 1.0f, 1.0f, 1.0f };

	const float baseScale = m_videoManager->Scale * 0.2;

	const int dataLeft = barLeft + 25 * m_videoManager->Scale;

	// TODO: cache weapon image inside this class
	StaticObject* wpnImg = new StaticObject(barLeft,
		m_videoManager->RegularText->getIndent() + m_videoManager->RegularText->getHeight(),
		128, 128,
		player->getWeapon()->getDroppedTex(), false);
	wpnImg->Scale = baseScale;

	glDisable(GL_TEXTURE_2D);
	wpnImg->RMask = wpnImg->GMask = wpnImg->BMask = 1.0f;
	wpnImg->draw(false, false);
	glEnable(GL_TEXTURE_2D);
	wpnImg->RMask = wpnImg->GMask = wpnImg->BMask = 0;
	wpnImg->draw(false, false);

	delete wpnImg;

	std::ostringstream oss;
	oss << player->getWeapon()->Ammo << '/' << player->getWeapon()->AmmoClipSize;
	m_videoManager->RegularText->draw(oss.str(), dataLeft,
		m_videoManager->RegularText->getIndent() + m_videoManager->RegularText->getHeight(),
		TextManager::LEFT, TextManager::MIDDLE);

	m_inventoryImg[0]->draw(false, false, barLeft,
		m_videoManager->RegularText->getIndent() + m_videoManager->RegularText->getHeight() * 2,
		0.0f, baseScale);

	oss.str("");
	oss << player->Grenades;
	m_videoManager->RegularText->draw(oss.str(), dataLeft,
		m_videoManager->RegularText->getIndent() + m_videoManager->RegularText->getHeight() * 2,
		TextManager::LEFT, TextManager::MIDDLE);

	m_inventoryImg[1]->draw(false, false, barLeft,
		m_videoManager->RegularText->getIndent() + m_videoManager->RegularText->getHeight() * 3,
		0.0f, baseScale);

	oss.str("");
	oss << player->Teleports;
	m_videoManager->RegularText->draw(oss.str(), dataLeft,
		m_videoManager->RegularText->getIndent() + m_videoManager->RegularText->getHeight() * 3,
		TextManager::LEFT, TextManager::MIDDLE);

	int bonusN = 0;
	for (int i = PLAYER_BONUS_FIRST; i < PLAYER_BONUS_COUNT; i++) {
		if (player->bonusTimes[i] > 0) {
			const int y = topBasePoint + bonusN * 132 * baseScale;
			m_bonusImg[(PlayerBonusType) i]->draw(false, false, barLeft, y, 0,
					baseScale);
			drawBar(barLeft + 25 * m_videoManager->Scale, y, barLen, barHeight,
					player->bonusTimes[i] / 15000.0f, bcolor, fcolor1, fcolor2);
			bonusN++;
		}
	}
}
Ejemplo n.º 18
0
int LibModelFile::init(const std::string &filename) {
  assert(m_initialised == false);

  std::string object;
  if (m_config.readFromFile(filename)) {
    if (m_config.findItem(SECTION_model, KEY_filename)) {
      object = (std::string)m_config.getItem(SECTION_model, KEY_filename);
    } else {
      fprintf(stderr, "[LibModelFile] Error: No md3 filename specified.\n");
      return 1;
    }
  } else {
    fprintf(stderr, "[LibModelFile] Error reading %s as varconf file. Trying as .md3 file.\n",
            filename.c_str());
    object = filename;
  }
  // Initialise transform matrix
  float matrix[4][4];
  for (int j = 0; j < 4; ++j) {
    for (int i = 0; i < 4; ++i) {
      if (i == j) matrix[j][i] = 1.0f;
      else matrix[j][i] = 0.0f;
    }
  }
  if (m_config.findItem(SECTION_model, KEY_rotation)) {
    const std::string &str=(std::string)m_config.getItem(SECTION_model, KEY_rotation);
    float w,x,y,z;
    sscanf(str.c_str(), "%f;%f;%f;%f", &w, &x, &y, &z);
    WFMath::Quaternion q(w,x,y,z);
    QuatToMatrix(q, matrix);
  }
  if (m_config.findItem(SECTION_model, KEY_scale)) {
    double s = (double)m_config.getItem(SECTION_model, KEY_scale);
    for (int i = 0; i < 4; ++i) matrix[i][i] *= s;
  }

  System::instance()->getFileHandler()->getFilePath(object);

  // Load md3 file
//  if (debug) printf("[LibModelFile] Loading: %s\n", object.c_str());

  libmd3_file *modelFile = libmd3_file_load(object.c_str());
  if (!modelFile) {
    fprintf(stderr, "[LibModelFile] Error loading %s file\n", object.c_str());
    return 1;
  }

  for (int i = 0; i < modelFile->header->mesh_count; ++i) {
    libmd3_unpack_normals(&modelFile->meshes[i]);
  }

  // Get mesh data
  libmd3_mesh *meshp = modelFile->meshes;
  for (int i = 0; i < modelFile->header->mesh_count; ++i, ++meshp) {
    StaticObject* so = new StaticObject();
    so->init();

    // Get Texture data from Mesh
    int texture_id = NO_TEXTURE_ID;
    int texture_mask_id = NO_TEXTURE_ID;
    if (meshp->mesh_header->skin_count != 0) {
      std::string name = (const char*)(meshp->skins[0].name);
      m_config.clean(name);

      // Check for texture name overrides in vconf file
      // Backwards compatibility.
      if (m_config.findItem(name, KEY_filename)) {
        name = (std::string)m_config.getItem(name, KEY_filename);
      }
      // Check for texture name overrides in vconf file
      // New method
      if (m_config.findItem(name, KEY_texture_map_0)) {
        name = (std::string)m_config.getItem(name, KEY_texture_map_0);
      }
      // Request Texture ID
      texture_id = RenderSystem::getInstance().requestTexture(name);
      texture_mask_id = RenderSystem::getInstance().requestTexture(name, true);

      float m[4];
      if (m_config.findItem(name, KEY_ambient)) {
        const std::string &str = (std::string)m_config.getItem(name, KEY_ambient);
        sscanf(str.c_str(), "%f;%f;%f;%f", &m[0], &m[1], &m[2], &m[3]);
        so->setAmbient(m); 
      }
      if (m_config.findItem(name, KEY_diffuse)) {
        const std::string &str = (std::string)m_config.getItem(name, KEY_diffuse);
        sscanf(str.c_str(), "%f;%f;%f;%f", &m[0], &m[1], &m[2], &m[3]);
        so->setDiffuse(m); 
      }
      if (m_config.findItem(name, KEY_specular)) {
        const std::string &str = (std::string)m_config.getItem(name, KEY_specular);
        sscanf(str.c_str(), "%f;%f;%f;%f", &m[0], &m[1], &m[2], &m[3]);
        so->setSpecular(m); 
      }
      if (m_config.findItem(name, KEY_emission)) {
        const std::string &str = (std::string)m_config.getItem(name, KEY_emission);
        sscanf(str.c_str(), "%f;%f;%f;%f", &m[0], &m[1], &m[2], &m[3]);
        so->setEmission(m); 
      }
      if (m_config.findItem(name, KEY_shininess)) {
        so->setShininess((double)m_config.getItem(name, KEY_shininess));
      }
      
    }
    // Set the transform
    so->getMatrix().setMatrix(matrix);
    // Set the textures
    so->setTexture(0, texture_id, texture_mask_id);
    so->setNumPoints(meshp->mesh_header->vertex_count);
    so->setNumFaces(meshp->mesh_header->triangle_count);

    // Copy data into array.
    so->createVertexData(meshp->mesh_header->vertex_count * 3);
    float *ptr = so->getVertexDataPtr();
    for (int i = 0; i < meshp->mesh_header->vertex_count * 3; ++i) {
      ptr[i] = default_scale * (float)meshp->vertices[i];
    }  
 
    so->copyTextureData(meshp->texcoords, meshp->mesh_header->vertex_count * 2);
    so->copyNormalData(meshp->normals, meshp->mesh_header->vertex_count * 3);

    so->copyIndices(meshp->triangles, meshp->mesh_header->triangle_count * 3);

    m_static_objects.push_back(so);
  }

  libmd3_file_free(modelFile);


  bool ignore_minus_z = false;

  Scaling scale = SCALE_NONE;
  Alignment align = ALIGN_NONE;
  bool process_model = false;

  if (m_config.findItem(SECTION_model, KEY_ignore_minus_z)) {
    if ((bool)m_config.getItem(SECTION_model, KEY_ignore_minus_z)) {
      process_model = true;
      ignore_minus_z = true;
    }
  }
  if (m_config.findItem(SECTION_model, KEY_z_align)) {
    if ((bool)m_config.getItem(SECTION_model, KEY_z_align)) {
      process_model = true;
      align = ALIGN_Z;
    }
  }
  if (m_config.findItem(SECTION_model, KEY_scale_isotropic)) {
    if ((bool)m_config.getItem(SECTION_model, KEY_scale_isotropic)) {
      process_model = true;
      scale = SCALE_ISOTROPIC;
    }
  }
  else if (m_config.findItem(SECTION_model, KEY_scale_isotropic_x)) {
    if ((bool)m_config.getItem(SECTION_model, KEY_scale_isotropic_x)) {
      process_model = true;
      scale = SCALE_ISOTROPIC_Z;
    }
  }
  else if (m_config.findItem(SECTION_model, KEY_scale_isotropic_y)) {
    if ((bool)m_config.getItem(SECTION_model, KEY_scale_isotropic_y)) {
      process_model = true;
      scale = SCALE_ISOTROPIC_Y;
    }
  }
  else if (m_config.findItem(SECTION_model, KEY_scale_isotropic_z)) {
    if ((bool)m_config.getItem(SECTION_model, KEY_scale_isotropic_z)) {
      process_model = true;
      scale = SCALE_ISOTROPIC_Z;
    }
  }
  if (m_config.findItem(SECTION_model, KEY_scale_anisotropic)) {
    if ((bool)m_config.getItem(SECTION_model, KEY_scale_anisotropic)) {
      process_model = true;
      scale = SCALE_ANISOTROPIC;
    }
  }
  
  if (process_model == true) {
    scale_object(m_static_objects, scale, align, ignore_minus_z);
  }


  contextCreated();

  m_initialised = true;
  return 0;
}