Example #1
0
App::App(bool showDebugWindow)
	: mKeyboard(nullptr)
	, mRoot(nullptr)
	, mSceneMgr(nullptr)
	, mWindow(nullptr)
	, mSmallWindow(nullptr)
	, mShutdown(false)
	, mScene(nullptr)
	, mRift(nullptr)
	, mTracker(nullptr)
	, mVideoPlayerLeft(nullptr), mVideoPlayerRight(nullptr)
    , mDebugDrawer(nullptr)
    , mDynamicsWorld(nullptr)
{
	std::cout << "Creating Ogre application:" << std::endl;

	showDebugWindow = false; // overrides the command line option

	initARLib(showDebugWindow);
	initOgre(showDebugWindow);
    initBullet(showDebugWindow); // enable debug drawer if we also have a debug window
	initOIS();

    mScene = new Scene(mRift, mTracker, mRoot,
		mWindow, mSmallWindow, mSceneMgr, 
		mDynamicsWorld, mKeyboard,
		mVideoPlayerLeft, mVideoPlayerRight);
	mRoot->startRendering();
}
Example #2
0
Bullet* BulletManage::createBullet(int type,int rotation){
	auto bullet = Bullet::create();
	bullet->initBullet(type,rotation);
	bullet->setPosition(ccp(400,20));
	bulletPool.pushBack(bullet);
	return bullet;
}
Example #3
0
struct bullet_llist* add_to_bullet_list(int row, int col, signed short horz_velocity, int add_to_end)
{
    if(NULL == bullet_head)
    {
	return (create_bullet_list(row, col, horz_velocity));
    }

    struct bullet_llist *ptr = (struct bullet_llist*)malloc(sizeof(struct bullet_llist));
    if(NULL == ptr)
    {
	printf("\n Node creation failed \n");
	return NULL;
    }
    ptr->val = (BULLET*)malloc(sizeof(BULLET)); 
    ptr->old_val = (BULLET*)malloc(sizeof(BULLET)); 
    ptr->next = NULL;

    initBullet(ptr->val, row, col, horz_velocity);
    updateOldBullet(ptr);

    if(add_to_end)
    {
	bullet_curr->next = ptr;
	bullet_curr = ptr;
    }
    else
    {
	ptr->next = bullet_head;
	bullet_head = ptr;
    }
    bullet_listSize++;
    return ptr;
}
Example #4
0
int RigidObject::update(long elapsedTime)
{
	PhysicsObject::update(elapsedTime);
	if (!physInit) initBullet(collisionName, collisionGroup, collisionMask);
	if (!physInit) return -1;
	
	return 0;
}
Example #5
0
void shotBullet(void)
{
  int entry;

  entry = allocBullet();
  if (entry >= 0) {
//    initBullet(entry, glutGet(GLUT_ELAPSED_TIME));
    initBullet(entry, lastTime);
  }
}
Example #6
0
Bullet* Bullet::createBullet(Attacker attacker,int type,int level)
{
    auto ret = new (std::nothrow) Bullet;
    if (ret && ret->initBullet(attacker,type,level))
    {
        ret->autorelease();
        return ret;
    }

    delete ret;
    return nullptr;
}
Example #7
0
//------------------------------------------------------------------------------
// fireControl() -- Starts/stops gun firing;
//    'trigger' will start or stop firing;
//    if 'burst' is true, only a single burst is fired;
//    returns true if gun is now firing
//------------------------------------------------------------------------------
bool Gun::fireControl(const bool trigger, const bool burst)
{
   if (trigger && isGunArmed()) {
      // Start firing ...
      fire = true;
      initBullet();
      if (burst) shortBurstTimer = shortBurstTime;
      else shortBurstTimer = 0;
   }
   else {
      // Stop firing ...
      burstFrame(); // clear the gun of bullets to be fired
      fire = false;
      shortBurstTimer = 0;
   }
   return fire;
}
Example #8
0
struct bullet_llist* create_bullet_list(int row, int col, signed short horz_velocity)
{
    struct bullet_llist *ptr = (struct bullet_llist*)malloc(sizeof(struct bullet_llist));
    if(NULL == ptr)
    {
	printf("\n Node creation failed \n");
	return NULL;
    }
    ptr->val = (BULLET*)malloc(sizeof(BULLET)); 
    ptr->old_val = (BULLET*)malloc(sizeof(BULLET)); 
    ptr->next = NULL;

    initBullet(ptr->val, row, col, horz_velocity);
    updateOldBullet(ptr);

    bullet_listSize++;
    bullet_head = ptr;
    bullet_curr = ptr;
    return ptr;
}
//prototype
int main(void){

	bool done = false;
	bool redraw = true;
	const int FPS = 60;
	bool isGameOver = false;
	
	//object variables
	spaceShip ship;
	Bullet bullets[NUM_BULLETS];
	Comet comets[NUM_COMETS];

	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *eventQueue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_FONT *font18 = NULL;

	

	
	//check if allegro is initialised <allegro_native_dialog.h>
	if(!al_init()){ 
		return -1;
	}

	display = al_create_display(WIDTH,HEIGHT);
	

	//check if display was created
	if(!display){
		return -1;
	}

	al_init_primitives_addon();
	al_install_keyboard();
	al_init_font_addon();
	al_init_ttf_addon();

	eventQueue = al_create_event_queue();
	timer= al_create_timer(1.0/FPS);

	srand(time(NULL)); // gives the rand() some value
	initShip(ship);
	initBullet(bullets, NUM_BULLETS);
	initComet(comets, NUM_COMETS);

	font18 = al_load_font("arial.ttf",18,0);
	
	al_register_event_source(eventQueue, al_get_keyboard_event_source());
	al_register_event_source(eventQueue, al_get_timer_event_source(timer));
	al_register_event_source(eventQueue, al_get_display_event_source(display)); //event os display resize closing, moving

	al_start_timer(timer);

	while(!done){
	
		ALLEGRO_EVENT ev;
		al_wait_for_event(eventQueue, &ev);

		if (ev.type==ALLEGRO_EVENT_TIMER){
			redraw=true;
			if(keys[UP]){
				moveShipUp(ship);
			}
			if(keys[DOWN]){
				moveShipDown(ship);
			}
			if(keys[LEFT]){
				moveShipLeft(ship);
			}
			if(keys[RIGHT]){
				moveShipRight(ship);
			}

			if(!isGameOver){
				updateBullet(bullets,NUM_BULLETS);
				startComet(comets, NUM_COMETS);
				updateComet(comets, NUM_COMETS);
				collideBullet(bullets,NUM_BULLETS, comets, NUM_BULLETS, ship);
				collideComet(comets, NUM_COMETS, ship);
			
				if (ship.lives <= 0){
					isGameOver = true;
				}
			}

			
		}
		// when clicling on red X icon to close the game
		else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE){
			done=true;
		
		}
		else if (ev.type==ALLEGRO_EVENT_KEY_DOWN){
			switch(ev.keyboard.keycode){
				case ALLEGRO_KEY_ESCAPE:
					done=true;
					break;
				case ALLEGRO_KEY_UP:
					keys[UP]=true;
					break;
				case ALLEGRO_KEY_DOWN:
					keys[DOWN]=true;
					break;
				case ALLEGRO_KEY_LEFT:
					keys[LEFT]=true;
					break;
				case ALLEGRO_KEY_RIGHT:
					keys[RIGHT]=true;
					break;
				case ALLEGRO_KEY_SPACE:
					keys[SPACE]=true;
					fireBullet(bullets, NUM_BULLETS, ship);
					break;
			}
		}
		else if (ev.type==ALLEGRO_EVENT_KEY_UP){
			switch(ev.keyboard.keycode){
				//make sure when exiting the program exit with esc button
				case ALLEGRO_KEY_ESCAPE:
					done=true;
					break;
				case ALLEGRO_KEY_UP:
					keys[UP]=false;
					break;
				case ALLEGRO_KEY_DOWN:
					keys[DOWN]=false;
					break;
				case ALLEGRO_KEY_LEFT:
					keys[LEFT]=false;
					break;
				case ALLEGRO_KEY_RIGHT:
					keys[RIGHT]=false;
					break;
				case ALLEGRO_KEY_SPACE:
					keys[SPACE]=false;
					break;
			}
		}
		if (redraw && al_is_event_queue_empty(eventQueue)){ // I only draw the screen if there no more event
			redraw=false;

			if(!isGameOver){			
				drawShip(ship);
				drawBullet(bullets,NUM_BULLETS);
				drawComet(comets, NUM_COMETS);

				al_draw_textf(font18, al_map_rgb(255,0,255), 5, 5, 0, "Player has %i lives left. Player has destroyed %i objects", ship.lives, ship.score);
			}
			else{
				al_draw_textf(font18, al_map_rgb(0,255,255),WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Game Over, Pal. Final Score: %i", ship.score);
			}

			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0)); //that prevents the filled rectangle draw imga just like snake style	
	
		}
		
		//make sure when exiting the program exit with esc button
		
		// when clicling on red X icon to close the game
		}

	//al_rest(5.0);
	al_destroy_display(display);
//hadouken

return 0;
}
Example #10
0
void shipSimulate(struct GameObject *go, double dt) {
    if (go->type == SHIP) {
        struct Ship *ship = (struct Ship *)(go->objData);
        struct ParticleSystem *eps=(struct ParticleSystem *)(ship->engines->objData);
        struct ParticleSystem *rps=(struct ParticleSystem *)(ship->rengines->objData);
        struct Pair targVel;
        double dotProduct, worstDotProduct, bestDotProduct, fthrust, rthrust;
        bestDotProduct = (ship->warpLimit)*(ship->warpLimit);
        worstDotProduct = -bestDotProduct;
        targVel.x = (ship->warpLimit)*cos(CONVERT_TO_RAD*go->angle);
        targVel.y = (ship->warpLimit)*sin(CONVERT_TO_RAD*go->angle);
        dotProduct = targVel.x*go->vel.x + targVel.y*go->vel.y;
        rthrust = (dotProduct-worstDotProduct)/(bestDotProduct-worstDotProduct);
        fthrust = 1-rthrust;
        if (ship->thrusters) {
            eps->overallFade = 1.0;
            eps->intensity=0.9*pow( fthrust, 0.5 );
            go->force.x+=fthrust*(ship->speed)*cos(CONVERT_TO_RAD*go->angle)*go->mass;
            go->force.y+=fthrust*(ship->speed)*sin(CONVERT_TO_RAD*go->angle)*go->mass;
        } else {
            eps->overallFade=0.75;
        }

        if (ship->retro) {
            rps->overallFade = 1.0;
            rps->intensity=0.9*pow( rthrust, 0.5 );
            go->force.x-=rthrust*(ship->speed)*cos(CONVERT_TO_RAD*go->angle)*go->mass;
            go->force.y-=rthrust*(ship->speed)*sin(CONVERT_TO_RAD*go->angle)*go->mass;
        } else {
            rps->overallFade=0.75;
        }

        double targetAngVel = 0;
        ship->currentTorque = 0;
        if (!ship->tempInvince) {
            if (ship->turnLeft) targetAngVel += ship->turnSpeed;
            if (ship->turnRight) targetAngVel += -ship->turnSpeed;
            ship->currentTorque = (targetAngVel - go->angVel) * go->moi/dt;
            go->torque += ship->currentTorque;
        }

        if (ship->firingBullet) {
            if (ship->heat == 0) {
                struct GameObject *bo = initBullet();
                struct Bullet *bullet = (struct Bullet *)bo->objData;
                double firingXVel = (bullet->speed)*cos(CONVERT_TO_RAD*go->angle);
                double firingYVel = (bullet->speed)*sin(CONVERT_TO_RAD*go->angle);

                bo->vel.x = go->vel.x + firingXVel;
                bo->vel.y = go->vel.y + firingYVel;

                bo->pos.x = go->pos.x + SHIP_SIZE*cos(CONVERT_TO_RAD*go->angle);
                bo->pos.y = go->pos.y + SHIP_SIZE*sin(CONVERT_TO_RAD*go->angle);

                go->force.x	+= (go->vel.x-bo->vel.x)*bo->mass/dt;
                go->force.y	+= (go->vel.y-bo->vel.y)*bo->mass/dt;

                ship->heat+=5;
                hashAdd(gameObjects,(void*)bo);
            }
        }

        double vel = sqrt((go->vel.x)*(go->vel.x)+(go->vel.y)*(go->vel.y));
        if (vel > ship->warpLimit) {
            go->vel.x*=ship->warpLimit/vel;
            go->vel.y*=ship->warpLimit/vel;
        }

        ship->engines->angle = go->angle;
        ship->rengines->angle = 180+go->angle;
        ship->engines->pos = go->pos;
        ship->engines->pos.x-=cos(CONVERT_TO_RAD*go->angle)*SHIP_SIZE/2;
        ship->engines->pos.y-=sin(CONVERT_TO_RAD*go->angle)*SHIP_SIZE/2;
        ship->rengines->pos = go->pos;
        ship->rengines->pos.x+=cos(CONVERT_TO_RAD*go->angle)*SHIP_SIZE;
        ship->rengines->pos.y+=sin(CONVERT_TO_RAD*go->angle)*SHIP_SIZE;
        ship->engines->vel = go->vel;
        ship->rengines->vel = go->vel;
        ship->tractorBeam->pos = go->pos;

        if (ship->engageTractor) {
            if (!ship->tractor) {
                struct GameObject *other, *bestOther;
                bestOther = NULL;
                struct HashElement *cursor = NULL;
                int i;
                struct Pair vect;
                double dist, bestDist;
                bestDist = RAND_MAX;
                for (i=0; i<gameObjects->numBuckets; i++) {
                    cursor = gameObjects->buckets[i].head;
                    while(cursor!=NULL) {
                        other = ((GP)(cursor->obj));
                        if ((other->type != BULLET) && other->phased<=0) {
                            vect.x = other->pos.x - go->pos.x;
                            vect.y = other->pos.y - go->pos.y;
                            dist = getLength(vect);
                            if (dist<bestDist && dist > 2*SHIP_SIZE) {
                                bestDist = dist;
                                bestOther = other;
                            }
                        }
                        cursor = cursor->next;
                    }
                }
                ship->tractorLength = bestDist;
                ship->tractoredObject = bestOther;
                ship->tractor = bestOther!=NULL;
            }
        }

        struct ParticleSystem *tps=(struct ParticleSystem *)(ship->tractorBeam->objData);

        if (ship->releaseTractor) {
            ship->tractor = 0;
            ship->tractoredObject = NULL;
            tps->overallFade = 0.75;
        }

        if (ship->tractoredObject!=NULL) {
            struct Pair vect, nvect, fvect;

            double dist;
            vect.x = ship->tractoredObject->pos.x-go->pos.x;
            vect.y = ship->tractoredObject->pos.y-go->pos.y;
            dist = getLength(vect);
            if (dist<1.0) {
                ship->tractorBeam->angle = 180+atan2(vect.y,vect.x)/(CONVERT_TO_RAD);
                tps->overallFade = 1.0;
                tps->intensity = 0.5;

                tps->speed = 4*dist;
                nvect.x = vect.x/dist;
                nvect.y = vect.y/dist;
                fvect.x = 10*(ship->tractorLength-dist)*nvect.x;
                fvect.y = 10*(ship->tractorLength-dist)*nvect.y;
                ship->tractoredObject->force.x+=fvect.x;
                ship->tractoredObject->force.y+=fvect.y;
                go->force.x-=fvect.x;
                go->force.y-=fvect.y;
            }
            else {
                ship->tractoredObject = NULL;
                tps->overallFade = 0.75;
            }
        }
        else {
            tps->overallFade = 0.75;
        }

        applyMomentum(go,dt);
        if (toroidalWrap(go,aspectRatio*2,2)) {
            ship->tractoredObject = NULL;
        }
        applyCooldown(&(ship->heat));
        applyCooldown(&(ship->tempInvince));

    }
}
Example #11
0
int Server::run(const char * ini)
{
	readServerData(ini);

	//clients = new Client[maxPlayers];
	clients = vector<Client*>();
	clients.reserve(maxPlayers);
	for (int i = 0; i < maxPlayers; i++) {
		clients.push_back(new Client());
		clients[i]->setID(i);
	}
		
	double elapsedTime = 0.0;
	double timePerFrame = 1000.0 / updateRate;
	double timePerRenderFrame = 1000.0 / renderRefreshRate;
	static double timeSinceLastRender = 0.0;
	long lastTime = 0;

	double targetSleep = 0.0;
	double sleepRemainder = 0.0;
	double startSleep = 0.0;
	double sleepTime = 0.0;

	loadConfig();
	initSDL();
	initGlew();
	initBullet();
	initGLContexts();
	initObjects();
	
	running = true;
	HANDLE listenThreadHandle = HostListener::start();

	loadResources();
	loadLevel("asdf");

	while (running) {
		frameCount++;
		if (GetAsyncKeyState(VK_ESCAPE) && (GetForegroundWindow() == consoleWindow) &&
			MessageBox(0, "Shutdown the Server?", "Rune Server Shutdown", MB_YESNO) == IDYES) break;

		lastTime = lastTime = SDL_GetTicks();

		serverEventsTCP->clearSendBuffer();
		serverEventsTCP->clearReceiveBuffer();
		serverEventsUDP->clearSendBuffer();
		serverEventsUDP->clearReceiveBuffer();

		//Get all commands from clients
		for (int i = 0; i < maxPlayers; i++) {
			DataBuffer * temp;
			aquireClientsMutex(i);
				temp = clients[i]->popReceiveData();
				if (!clients[i]->isConnected() && playerObjects->at(i) != NULL) {
					int index = -1;
					int x = 0;
					for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
						if (playerObjects->at(i) == iter->second) {
							index = x;
							break;
						}
						x++;
					}
					/*for (int x = 0; x < gameObjects->size(); x++) {
						if (playerObjects->at(i) == gameObjects->at(x))
							index = x;
					}*/
					gameObjects->remove(playerObjects->at(i)->getNetID());
					delete playerObjects->at(i);
					playerObjects->at(i) = NULL;
					//gameObjects->erase(gameObjects->begin() + index);
					serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(index));
				}
			releaseClientsMutex(i);
			serverEventsTCP->appendToReceiveBuffer(temp);
		}

		//Receive All UDP Events
		sockaddr_in * originAddress = NULL;
		DataBuffer * udpBuffer = UDPManager::recvDatagram(&originAddress);
		while (udpBuffer != NULL) {
			//origin Address matches client address?
			unsigned long packetFrameCount = 0;
			memcpy(&packetFrameCount, udpBuffer->getData(), 4);

			int clientID = getClientIDByAddress(originAddress->sin_addr.s_addr, originAddress->sin_port);
			if (clientID == -1) {
				int asdfadsfasdf = 123123;
			}
			else {
				//compare clientFrameCount to client->frameCount
				unsigned long clientFrameCount;
				aquireClientsMutex(clientID);
					clientFrameCount = clients[clientID]->getFrameCount();
				releaseClientsMutex(clientID);

				if (packetFrameCount < clientFrameCount) {
					//discard
					printf("Packet from Client %d discarded\n", clientID);
				}
				else {
					serverEventsUDP->appendToReceiveBuffer(udpBuffer->getData() + 4, udpBuffer->getSize() - 4);
					aquireClientsMutex(clientID);
						clients[clientID]->setFrameCount(packetFrameCount);
					releaseClientsMutex(clientID);
				}

			}
			
			delete udpBuffer; udpBuffer = NULL;
			delete originAddress; originAddress = NULL;
			udpBuffer = UDPManager::recvDatagram(&originAddress);
		}

		NetworkFunctions::translateReceivedEvents(serverEventsTCP);
		NetworkFunctions::translateReceivedEvents(serverEventsUDP);
		
		//Execute my own gamelogic commands
		SDL_Event e;
		while (SDL_PollEvent(&e)) { 
			if (e.key.keysym.sym == SDLK_ESCAPE)
						running = false;
			if (e.key.keysym.sym == SDLK_m) {
				((RigidObject*)gameObjects->getValue(2))->setPosition(5, 10, 0);
				((RigidObject*)gameObjects->getValue(3))->setPosition(0, 10, 0);
				((RigidObject*)gameObjects->getValue(4))->setPosition(-5, 10, 0);
				((RigidObject*)gameObjects->getValue(2))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(3))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(4))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(2))->setGravity(0, -9.81f*4.0f, 0);
				((RigidObject*)gameObjects->getValue(3))->setGravity(0, -9.81f*4.0f, 0);
				((RigidObject*)gameObjects->getValue(4))->setGravity(0, -9.81f*4.0f, 0);
				printf("reset boxes\n");
			}
		}

		//if (update((long)(elapsedTime + sleepTime)) == -1) break;

		//dynamicsWorld->stepSimulation((float)(elapsedTime + sleepTime)*0.001f, 50, (float)(elapsedTime + sleepTime)*0.001f);
		dynamicsWorld->stepSimulation(1.0f / 64.0f, 100, 1.0f / 64.0f); //1.0f/(float)Settings::getMaxFPS());

		list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin();
		while (iter != gameObjects->end())
		{
			iter->second->update(elapsedTime);
			if (!iter->second->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(iter->second->getNetID()));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == iter->second) {
						playerObjects->at(p) = NULL;
					}
				}

				GameObject * tempObject = iter->second;
				iter = gameObjects->erase(iter);
				delete tempObject;
			}
			else iter++;
		}

		/*for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
			iter->second->update(elapsedTime);
			if (!iter->second->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(iter->second->getNetID()));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == iter->second) {
						playerObjects->at(p) = NULL;
					}
				}

				gameObjects->remove(iter->first, iter->second);
				delete (*gameObjects)[i];
				gameObjects->erase(gameObjects->begin() + i);
				i--;
			}
		}*/

		/*for (int i = 0; i < (int)gameObjects->size(); i++) {
			(*gameObjects)[i]->update(elapsedTime);
			if (!(*gameObjects)[i]->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(i));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == (*gameObjects)[i]) {
						playerObjects->at(p) = NULL;
					}
				}
				delete (*gameObjects)[i];
				gameObjects->erase(gameObjects->begin() + i);
				i--;
			}
		}*/
		
		//Update each client
		//for (int i = 0; i < gameObjects->size(); i++)
		//	serverEvents->appendToSendBuffer(NetworkFunctions::createUpdateObjectBuffer(i));

		for (int i = 0; i < maxPlayers; i++) {
			aquireClientsMutex(i);
				if (clients[i]->isConnected()) {
					if (clients[i]->requiresSynch()) {
						synchClient(i);
						clients[i]->setSynch(false);
					}
					else {
						clients[i]->pushSendData(serverEventsTCP->getSendBuffer(), serverEventsTCP->getSendBufferSize());
					}
				}
			releaseClientsMutex(i);
		}
		
		for (int i = 0; i < maxPlayers; i++) {
			aquireClientsMutex(i);
			if (clients[i]->isConnected()) {
				//unsigned long clientPortUDP = clients[i]->getPortUDP();
				if (!clients[i]->requiresSynch()) {
					serverEventsUDP->clearSendBuffer();
					for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
						if (playerObjects->at(i) != iter->second /* && dont force player */) {
							DataBuffer * temp = NetworkFunctions::createUpdateObjectBuffer(iter->second->getNetID());
							serverEventsUDP->appendToSendBuffer(temp);
						}
					}
					UDPManager::sendDatagram(serverEventsUDP->getSendBuffer(), serverEventsUDP->getSendBufferSize(), clients[i]->getIPAddress(), clients[i]->getPortUDP(), frameCount);
				}
			}
			releaseClientsMutex(i);
		}

		/*timeSinceLastRender += elapsedTime;
		if (timeSinceLastRender >= timePerRenderFrame) {
			timeSinceLastRender = 0.0;
			renderFrame();
		}*/
		renderFrame();

		//Update Rate Calculations
		//Framerate Limit Calculations
		elapsedTime = SDL_GetTicks() - lastTime;
		targetSleep = timePerFrame - elapsedTime + sleepRemainder;
		if (targetSleep > 0) sleepRemainder = targetSleep - (Uint32)targetSleep;

		//Sleep(1000.0 / 64.0);
		
		startSleep = SDL_GetTicks();
		while ((Uint32)(startSleep + targetSleep) > SDL_GetTicks());
		sleepTime = SDL_GetTicks() - startSleep;
	}

	cout << "Shutting Down\n";
	HostThread::stopAll();
	HostListener::stop();
	UDPManager::cleanup();
	WSACleanup();
	WaitForSingleObject(listenThreadHandle, INFINITE);

	saveConfig();

	cleanupObjects();
	//saveConfig();
	killBullet();
		
	//delete [] clients;
	
	return 0;
}
//prototype
int main(void){

	bool done = false;
	bool redraw = true;
	const int FPS = 60;

	//object variables
	spaceShip ship;
	Bullet bullets[5];

	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *eventQueue = NULL;
	ALLEGRO_TIMER *timer = NULL;

	
	//check if allegro is initialised <allegro_native_dialog.h>
	if(!al_init()){ 
		return -1;
	}

	display = al_create_display(WIDTH,HEIGHT);
	

	//check if display was created
	if(!display){
		return -1;
	}

	al_init_primitives_addon();
	al_install_keyboard();
	//to capture keyboard events
	eventQueue = al_create_event_queue();
	timer = al_create_timer(1.0 / FPS);


	initShip(ship);
	initBullet(bullets,NUM_BULLETS);

	//register the keyboard to eventQueue
	al_register_event_source(eventQueue,al_get_keyboard_event_source());
	al_register_event_source(eventQueue,al_get_timer_event_source(timer));
	al_register_event_source(eventQueue,al_get_display_event_source(display));

	al_start_timer(timer);

	while(!done){
		ALLEGRO_EVENT ev;
		al_wait_for_event(eventQueue,&ev);
		if(ev.type == ALLEGRO_EVENT_TIMER){
			redraw=true;

			if(keys[UP]){
				moveShipUp(ship);
			}
			if(keys[DOWN]){
				moveShipDown(ship);
			}
			if(keys[LEFT]){
				moveShipLeft(ship);
			}
			if(keys[RIGHT]){
				moveShipRight(ship);
			}

			updateBullet(bullets,NUM_BULLETS);
		
		}
		else if(ev.type  == ALLEGRO_EVENT_DISPLAY_CLOSE){
			done=true;
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_DOWN){
			switch(ev.keyboard.keycode){
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = true;
				fireBullet(bullets, NUM_BULLETS, ship);
				break;

			}
		}

		else if(ev.type == ALLEGRO_EVENT_KEY_UP){
			switch(ev.keyboard.keycode){
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = false;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = false;
				break;
			}
		}

		if(redraw && al_is_event_queue_empty(eventQueue)){
			redraw = false;
			drawShip(ship);
			//without updating the bullets they will be only create a static spot in the screen, limited to n number of bullets
			drawBullet(bullets,NUM_BULLETS);
			// when clicling on red X icon to close the game
			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0)); //that prevents the filled rectangle draw imga just like snake style	
		}
		//make sure when exiting the program exit with esc button
		
		}

	//al_rest(5.0);
	al_destroy_display(display);
//hadouken

return 0;
}
Example #13
0
HeightFieldObject::HeightFieldObject(string t, string s, glm::vec3 position, glm::vec3 direction, glm::vec3 up, float * heightData, int width, int length, float offsetY, int colGroup, int colMask) : RigidObject("", t, s, position, direction, up, "heightField", colGroup, colMask)
{
	this->heightData = 0;
	model = Model::loadHeightFieldModel(heightData, width, length);
	initBullet(heightData, width, length, offsetY, colGroup, colMask);
}
Example #14
0
int main( void )
{
	//init bullet
	initBullet();
	// Initialise GLFW
	if( !glfwInit() )
	{
		fprintf( stderr, "Failed to initialize GLFW\n" );
		return -1;
	}
	glfwWindowHint(GLFW_SAMPLES, 4);
//	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
//	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
//	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	//screen resolution GLFW
	const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
	int  w = mode->width;
	int  h = mode->height;

	if(MessageBox(NULL, L"Would you like to run in fullscreen?", L"Fullscreen", MB_ICONQUESTION | MB_YESNO) == IDYES) 
	{
		window = glfwCreateWindow( w, h, "Ray Tracing - Alfonso Oricchio", glfwGetPrimaryMonitor(), NULL);
		printf("fullscreen\n");
	}
	else
	{
		window = glfwCreateWindow( WINDOW_WIDTH, WINDOW_HEIGHT, "Ray Tracing - Alfonso Oricchio", NULL, NULL);
		printf("window\n");
	}
	// Open a window and create its OpenGL context
	
	if( window == NULL ){
		fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);

	// Initialize GLEW
	glewExperimental = true; // Needed for core profile
	if (glewInit() != GLEW_OK) {
		fprintf(stderr, "Failed to initialize GLEW\n");
		return -1;
	}

	// Ensure we can capture the escape key being pressed below
	glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
	glfwSetCursorPos(window, WINDOW_WIDTH/2, WINDOW_HEIGHT/2);

	// Dark blue background
	glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

	// Enable depth test
	glEnable(GL_DEPTH_TEST);
	// Accept fragment if it closer to the camera than the former one
	glDepthFunc(GL_LESS); 
	// Cull triangles which normal is not towards the camera
	//glEnable(GL_CULL_FACE);

	GLuint VertexArrayID;
	glGenVertexArrays(1, &VertexArrayID);
	glBindVertexArray(VertexArrayID);
	
		// Create and compile our GLSL program from the shaders
	GLuint depthProgramID = LoadShaders( "DepthRTT.vertexshader", "DepthRTT.fragmentshader" );

	// Get a handle for our "MVP" uniform
	GLuint depthMatrixID = glGetUniformLocation(depthProgramID, "depthMVP");
	
	// The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer.
	GLuint FramebufferName = 0;
	glGenFramebuffers(1, &FramebufferName);
	glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);

	// Depth texture. Slower than a depth buffer, but you can sample it later in your shader
	GLuint depthTexture;
	glGenTextures(1, &depthTexture);
	glBindTexture(GL_TEXTURE_2D, depthTexture);
	glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT16, 1024, 1024, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
		 
	glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0);

	// No color output in the bound framebuffer, only depth.
	glDrawBuffer(GL_NONE);

	// Always check that our framebuffer is ok
	if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
		return false;
	/***********************************************************/
		// The quad's FBO. Used only for visualizing the shadowmap.
	static const GLfloat g_quad_vertex_buffer_data[] = { 
		-1.0f, -1.0f, 0.0f,
		 1.0f, -1.0f, 0.0f,
		-1.0f,  1.0f, 0.0f,
		-1.0f,  1.0f, 0.0f,
		 1.0f, -1.0f, 0.0f,
		 1.0f,  1.0f, 0.0f,
	};

	GLuint quad_vertexbuffer;
	glGenBuffers(1, &quad_vertexbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW);

	// Create and compile our GLSL program from the shaders
	GLuint quad_programID = LoadShaders( "Passthrough.vertexshader", "SimpleTexture.fragmentshader" );
	GLuint texID = glGetUniformLocation(quad_programID, "texture");
	/**********************************************************/


		// Create and compile our GLSL program from the shaders
	GLuint programID = LoadShaders( "TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader" );



	// Get a handle for our "MVP" uniform
	GLuint MatrixID = glGetUniformLocation(programID, "MVP");
	GLuint ViewMatrixID = glGetUniformLocation(programID, "V");
	GLuint ModelMatrixID = glGetUniformLocation(programID, "M");
	GLuint DepthBiasID = glGetUniformLocation(programID, "DepthBiasMVP");
	GLuint ShadowMapID = glGetUniformLocation(programID, "shadowMap");
	
	// Get a handle for our "LightPosition" uniform
	GLuint lightInvDirID = glGetUniformLocation(programID, "LightInvDirection_worldspace");

	//CUBO1
	addBox(2,2,2,0,0,0,1.0);

	//CUBO2
	addBox2(2,2,2,0,6,0,1.0);
	//FLOOR
	initFloor();

	//WALL
	initWall();
	//BALL
	addScene();

	do{
		world->stepSimulation(1/60.f);
		if (glfwGetKey( window, GLFW_KEY_SPACE ) == GLFW_PRESS){
			btRigidBody* ball = addBall(1.0,CamGetPosition().x,CamGetPosition().y,CamGetPosition().z,2.0);
			ball->setLinearVelocity(btVector3((CamGetDirection().x*50),(CamGetDirection().y*50),(CamGetDirection().z*50)));	
		}
		// Render to our framebuffer
		glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
		glViewport(0,0,1024,1024); // Render on the whole framebuffer, complete from the lower left corner to the upper right

		// Clear the screen
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		//////////////////////////////
		// Use our shader
		//SHADOW RENDER
		glUseProgram(depthProgramID);

		glm::vec3 lightInvDir = glm::vec3(0.5f,2,2);

		// Compute the MVP matrix from the light's point of view
		glm::mat4 depthProjectionMatrix = glm::ortho<float>(-10,10,-10,10,-10,20);
		glm::mat4 depthViewMatrix = glm::lookAt(lightInvDir, glm::vec3(0,0,0), glm::vec3(0,1,0));
		// or, for spot light :
		//glm::vec3 lightPos(5, 20, 20);
		//glm::mat4 depthProjectionMatrix = glm::perspective<float>(45.0f, 1.0f, 2.0f, 50.0f);
		//glm::mat4 depthViewMatrix = glm::lookAt(lightPos, lightPos-lightInvDir, glm::vec3(0,1,0));

		glm::mat4 depthModelMatrix = glm::mat4(1.0);
		glm::mat4 depthMVP = depthProjectionMatrix * depthViewMatrix * depthModelMatrix;

		// Send our transformation to the currently bound shader, 
		// in the "MVP" uniform
		glUniformMatrix4fv(depthMatrixID, 1, GL_FALSE, &depthMVP[0][0]);

		// CUBE1 -------------------------------------------------------------------------
		renderBox(bodies[0],true); //just a cube not really needed
		//CUBE2 --------------------------------------------------------------------------
		renderBox2(bodies[1],true); //just a cube not really needed
		//FLOOR --------------------------------------------------------------------------
		renderPlane(bodies[2],true); //floor 
		//WALL ---------------------------------------------------------------------------
		renderWall(bodies[3],true); //back wall
		//CASTLE -------------------------------------------------------------------------
		renderScene(true); //castle, main scene
		//BALL ---------------------------------------------------------------------------
		int iv;
		for(iv = 4; iv < bodies.size();iv++)
			{
				renderBall(bodies[iv],(iv - 4),true); //"cannon balls" shooted from the camera 
			}
		
		

		
		//////////////////////////////
		//STANDARD RENDER
		// Compute the MVP matrix from keyboard and mouse input
		// Clear the screen
		// Render to the screen
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glViewport(0,0,1024,768); // Render on the whole framebuffer, complete from the lower left corner to the upper right

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		
		// Use our shader
		glUseProgram(programID);

		computeMatricesFromInputs();
		glm::mat4 ProjectionMatrix = getProjectionMatrix();
		glm::mat4 ViewMatrix = getViewMatrix();
		glm::mat4 ModelMatrix = glm::mat4(1.0);
		glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;		
		
				
		glm::mat4 biasMatrix(
			0.5, 0.0, 0.0, 0.0, 
			0.0, 0.5, 0.0, 0.0,
			0.0, 0.0, 0.5, 0.0,
			0.5, 0.5, 0.5, 1.0
		);

		glm::mat4 depthBiasMVP = biasMatrix*depthMVP;

// Send our transformation to the currently bound shader, 
		// in the "MVP" uniform
		glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
		glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix[0][0]);
		glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]);
		glUniformMatrix4fv(DepthBiasID, 1, GL_FALSE, &depthBiasMVP[0][0]);

		glUniform3f(lightInvDirID, lightInvDir.x, lightInvDir.y, lightInvDir.z);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, depthTexture);
		glUniform1i(ShadowMapID, 0);

		// CUBE1 -------------------------------------------------------------------------
		renderBox(bodies[0],false); //just a cube not really needed
		//CUBE2 --------------------------------------------------------------------------
		renderBox2(bodies[1],false); //just a cube not really needed
		//FLOOR --------------------------------------------------------------------------
		renderPlane(bodies[2],false); //floor 
		//WALL ---------------------------------------------------------------------------
		renderWall(bodies[3],false); //back wall
		//CASTLE -------------------------------------------------------------------------
		renderScene(false); //castle, main scene
		//BALL ---------------------------------------------------------------------------
	//	int iv;
		for(iv = 4; iv < bodies.size();iv++)
			{ 
				renderBall(bodies[iv],(iv - 4),false); //"cannon balls" shooted from the camera 
			}
		
	/*--------------------------------------------------*/
	// Optionally render the shadowmap (for debug only)

		// Render only on a corner of the window (or we we won't see the real rendering...)
		glViewport(0,0,512,512);

		// Use our shader
		glUseProgram(quad_programID);

		// Bind our texture in Texture Unit 0
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, depthTexture);
		// Set our "renderedTexture" sampler to user Texture Unit 0
		glUniform1i(texID, 0);

		// 1rst attribute buffer : vertices
		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
		glVertexAttribPointer(
			0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
			3,                  // size
			GL_FLOAT,           // type
			GL_FALSE,           // normalized?
			0,                  // stride
			(void*)0            // array buffer offset
		);

		// Draw the triangle !
		// You have to disable GL_COMPARE_R_TO_TEXTURE above in order to see anything !
		//glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles
		glDisableVertexAttribArray(0);

	/*--------------------------------------------------*/
		// Swap buffers
		glfwSwapBuffers(window);
		glfwPollEvents();

	} // Check if the ESC key was pressed or the window was closed
	while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
		   glfwWindowShouldClose(window) == 0 );



	deleteALL();
	glDeleteProgram(programID);
	glDeleteVertexArrays(1, &VertexArrayID);
	// Close OpenGL window and terminate GLFW
	glfwTerminate();

	return 0;
}
Example #15
0
PropObject::PropObject(string m, string t, string s, glm::vec3 position, glm::vec3 direction, glm::vec3 up, string path, int colGroup, int colMask) : RigidObject(m, t, s, position, direction, up, path, colGroup, colMask)
{
	initBullet(path, colGroup, colMask);
}
HeightFieldObject::HeightFieldObject(string t, string s, glm::vec2 position, float * heightData, int width, float offsetY, int colGroup, int colMask) : RigidObject(t, s, position, 0.0f, glm::vec2(1.0f, 1.0f), 0.0f, "heightField", colGroup, colMask)
{
	this->heightData = 0;
	initBullet(heightData, width, offsetY, colGroup, colMask);
}