Beispiel #1
0
Renderer::Renderer()
	: m_pos(0),
	m_numParticles(0),
	m_pointSize(1.0f),
	m_particleRadius(0.125f * 0.5f),
	//m_program(0),
	m_vbo(0),
	m_colorVBO(0),
	mWindowW(1024),
	mWindowH(768),
	mFov(60.0f),
	m_downSample(1),
	m_imageTex(0),
	m_postprocessingTex(0),
	m_depthTex(0),
	m_imageFbo(0),
	m_postprocessingFbo(0)
	  //m_indexBuffer(0)
{
	txParticle = LoadTexture("data/water.bmp");
	m_displayTexProg = new GLSLProgram(passThruVS, texture2DPS);
	m_postprocessing = new GLSLProgram(passThruVS, postprocessingPS);
    _initGL();
}
Beispiel #2
0
bool ParticleSystemClass::Initialize(ID3D11Device* device, WCHAR* textureFilename)
{
	bool result;

	result = LoadTexture(device, textureFilename); //load the texture that is used for the particles
	if(!result)
	{
		return false;
	}

	result = InitializeParticleSystem();
	if(!result)
	{
		return false;
	}

	result = InitializeBuffers(device);
	if(!result)
	{
		return false;
	}

	return true;
}
Beispiel #3
0
bool StaticMeshComponent::Initialise(ID3D11Device* device, char* modelFilename, WCHAR* textureFilename)
{
	bool result;
	
	result = LoadModel(modelFilename);
	if (!result)
	{
		return false;
	}

	result = InitialiseBuffers(device);
	if (!result)
	{
		return false;
	}

	result = LoadTexture(device, textureFilename);
	if (!result)
	{
		return false;
	}

	return true;
}
Beispiel #4
0
bool CWall::create(IDirect3DDevice9* pDevice,
	float iwidth,
	float iheight,
	float idepth,
	Type type){
	m_width = iwidth;
	m_depth = idepth;
	m_height = iheight;
	if (FAILED(D3DXCreateBox(pDevice, iwidth, iheight, idepth, &m_pMesh, 0))) return false;

	LPD3DXMESH newMesh = convertMesh(pDevice, m_pMesh);
	if (newMesh == nullptr){
		m_pMesh->Release();
		return false;
	}
	switch (type){
	case Plane:
		textureFile = PLANE_TEXTURE;
		effectFile = PLANE_EFFECT;
		break;
	case Edge:
		effectFile = EDGE_EFFECT;
		textureFile = EDGE_TEXTURE;
		break;
	}
	m_texture = LoadTexture(pDevice, textureFile);
	m_effect = LoadShader(pDevice, effectFile);


	if (m_texture == nullptr || m_effect == nullptr)
		return false;
	m_pMesh->Release();
	m_pMesh = newMesh;

	return true;
}
Beispiel #5
0
////////////////////////////////////////
//		PUBLIC UTILITY FUNCTIONS
////////////////////////////////////////
unsigned int TextureManager::GetTexture(string fileName)
{
	Texture* texture = nullptr;
	map<string,Texture*>::iterator iter = m_textureMap.find(fileName);

	if(iter == m_textureMap.end())
	{
		if(LoadTexture(fileName))
		{
			texture = m_textureMap[fileName];
		}
		else
		{
			LOG("Couldn't load texture: " << fileName);
			texture = m_textureMap[TextureManager::DEFAULT_TEXTURE_FILENAME];
		}
	}
	else
	{
		texture = m_textureMap[fileName];
	}

	return reinterpret_cast<unsigned int>(texture);
}
// Create the plane, including its geometry, texture mapping, normal, and colour
void CCubemap::Create(string sPositiveX, string sNegativeX, string sPositiveY, string sNegativeY, string sPositiveZ, string sNegativeZ)
{
	int iWidth, iHeight;

	// Generate an OpenGL texture ID for this texture
	glGenTextures(1, &m_uiTexture);
	glBindTexture(GL_TEXTURE_CUBE_MAP, m_uiTexture);

	// Load the six sides
	BYTE *pbImagePosX, *pbImageNegX, *pbImagePosY, *pbImageNegY, *pbImagePosZ, *pbImageNegZ;

	LoadTexture(sPositiveX, &pbImagePosX, iWidth, iHeight);
	LoadTexture(sNegativeX, &pbImageNegX, iWidth, iHeight);
	LoadTexture(sPositiveY, &pbImagePosY, iWidth, iHeight);
	LoadTexture(sNegativeY, &pbImageNegY, iWidth, iHeight);
	LoadTexture(sPositiveZ, &pbImagePosZ, iWidth, iHeight);
	LoadTexture(sNegativeZ, &pbImageNegZ, iWidth, iHeight);

	glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGB, iWidth, iHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, pbImagePosX);
	glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGB, iWidth, iHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, pbImageNegX);
	glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGB, iWidth, iHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, pbImagePosY);
	glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGB, iWidth, iHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, pbImageNegY);
	glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGB, iWidth, iHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, pbImagePosZ);
	glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGB, iWidth, iHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, pbImageNegZ);

	delete[] pbImagePosX;
	delete[] pbImageNegX;
	delete[] pbImagePosY;
	delete[] pbImageNegY;
	delete[] pbImagePosZ;
	delete[] pbImageNegZ;

	glGenSamplers(1, &m_uiSampler);
	glSamplerParameteri(m_uiSampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glSamplerParameteri(m_uiSampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

	glSamplerParameteri(m_uiSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glSamplerParameteri(m_uiSampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glSamplerParameteri(m_uiSampler, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

	glGenerateMipmap(GL_TEXTURE_CUBE_MAP);

}
void ClassDemoApp::Setup() {
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("SoundInvaders", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

#ifdef _WINDOWS
	glewInit();
#endif
	done = false;

	program = new ShaderProgram(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
//	program = new ShaderProgram(RESOURCE_FOLDER"vertex.glsl", RESOURCE_FOLDER"fragment.glsl");
	spritetexture = LoadTexture("p1_front.png");
	font = LoadTexture("Capword.png");
	hitSound = Mix_LoadWAV("Get_Rupee.wav");
	shootSound = Mix_LoadWAV("Trident.wav");
	death1Sound = Mix_LoadWAV("Boss_Hit.wav");
	death2Sound = Mix_LoadWAV("Boss_Death.wav");
	music = Mix_LoadMUS("Dark_World.ogg");

	projectionMatrix.setOrthoProjection(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f);

	lives = 10;
	spaceship = new Spaceship(program, 0.21f, 0.21f, LoadTexture("Zelda.png"));
	invaders = new Invaders(program, 0.21f, 0.21f, LoadTexture("Links.png"), LoadTexture("Arrow.png"));
	tank = new Tank(program, 0.19f, 0.19f, LoadTexture("Ganon.png"), LoadTexture("Trident.png"));
	highscore = 0;
	state = STATE_MAIN_MENU;

	musicTicks = 16;
	Mix_PlayMusic(music, -1);
}
Beispiel #8
0
void Setup() {
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("Rob Chiarelli's Pong V", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);

	glViewport(0, 0, 800, 600);
	glMatrixMode(GL_PROJECTION);
	glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0);

	ball.textureID = LoadTexture("green_panel.png");
	paddle1.textureID = LoadTexture("green_panel.png");
	paddle2.textureID = LoadTexture("green_panel.png");
	top.textureID = LoadTexture("green_panel.png");
	bottom.textureID = LoadTexture("green_panel.png");
	space.textureID = LoadTexture("grey_button02.png");

	srand(time(NULL));

	ball.setSize(0.1, 0.1);
	ball.setPosition(0.0, 0.0, 0.0);
	ball.setMovement(2.0, rand() % 50 - 25);
	//The ball is set to move right at a random angle between 
	//-25 and 25 degrees for maximum playability

	paddle1.setSize(0.1, 0.5);
	paddle1.setPosition(-1.2, 0.0, 0.0);
	paddle1.setMovement(2.0, 0);

	paddle2.setSize(0.1, 0.5);
	paddle2.setPosition(1.2, 0.0, 0.0);
	paddle2.setMovement(2.0, 0);

	top.setSize(2.66, 0.1);
	top.setPosition(0.0, 1.0, 0.0);

	bottom.setSize(2.66, 0.1);
	bottom.setPosition(0.0, -1.0, 0.0);

	space.setSize(1.0, 0.3);
	space.setPosition(0.0, 0.8, 0.0);
}
Beispiel #9
0
// Gameplay Screen Initialization logic
void InitGameplayScreen(void)
{
    // TODO: Initialize GAMEPLAY screen variables here!
    framesCounter = 0;
    finishScreen = 0;
    
    // MAP LAODING
        // TODO: Read .bmp file propierly in order to get image width & height
    Color *mapPixels = malloc(GRID_WIDTH*GRID_HEIGHT * sizeof(Color));
    mapPixels = GetImageData(LoadImage("assets/gameplay_screen/maps/map.bmp"));
    
    maxTriangles = 0;
    maxPlatforms = 0;
    
    for (int i=0; i<GRID_WIDTH*GRID_HEIGHT; i++)
    {
        /*
        printf("r: %i\n", mapPixels[i].r);
        printf("g: %i\n", mapPixels[i].g);
        printf("b: %i\n\n", mapPixels[i].b);
        */
        if (mapPixels[i].r == 255 && mapPixels[i].g == 0 && mapPixels[i].b == 0) maxTriangles++;
        else if (mapPixels[i].r == 0 && mapPixels[i].g == 255 && mapPixels[i].b == 0) maxPlatforms++;
    }
    
    triangles = malloc(maxTriangles * sizeof(TriangleObject));
    platforms = malloc(maxPlatforms * sizeof(SquareObject));
    
    int trianglesCounter=0;
    int platformsCounter=0;
    
    
    for (int y=0; y<GRID_HEIGHT; y++)
    {
        for (int x=0; x<GRID_WIDTH; x++)
        {
            if (mapPixels[y*GRID_WIDTH+x].r == 255 && mapPixels[y*GRID_WIDTH+x].g == 0 && mapPixels[y*GRID_WIDTH+x].b == 0) 
            {
                InitializeTriangle(&triangles[trianglesCounter], (Vector2){x, y});
                trianglesCounter++;
            }
            else if (mapPixels[y*GRID_WIDTH+x].r == 0 && mapPixels[y*GRID_WIDTH+x].g == 255 && mapPixels[y*GRID_WIDTH+x].b == 0) 
            {
                InitializePlatform(&platforms[platformsCounter], (Vector2){x, y});
                platformsCounter++;
            }
        }
    }
    
    free(mapPixels);
    
    //DEBUGGING && TESTING variables
    pause = FALSE;
    srand(time(NULL)); 
    
    // Textures loading
    player.texture = LoadTexture("assets/gameplay_screen/cube_main.png");
    triangleTexture = LoadTexture("assets/gameplay_screen/triangle_main.png");
    platformTexture = LoadTexture("assets/gameplay_screen/platform_main.png");
    player.pEmitter.texture = LoadTexture("assets/gameplay_screen/particle_main.png");
    
    bg = LoadTexture("assets/gameplay_screen/bg_main.png");
    
    // Sound loading
    InitAudioDevice();
    PlayMusicStream("assets/gameplay_screen/music/Flash_Funk_MarshmelloRemix.ogg");
    PauseMusicStream();
    SetMusicVolume(0.5f);
    
    // Did player win?
    startGame = FALSE;
    
    /*
    player.texture = LoadTexture("assets/gameplay_screen/debug.png");
    triangleTexture = LoadTexture("assets/gameplay_screen/debug.png");
    platformTexture = LoadTexture("assets/gameplay_screen/debug.png");
    player.pEmitter.texture = LoadTexture("assets/gameplay_screen/particle_main.png");
    */
    
    // Camera initialization
    mainCamera = (Camera2D){Vector2Right(), (Vector2){6.5f, 6.5f}, Vector2Zero(), TRUE};
    
    // Gravity initialization
    gravity = (GravityForce){Vector2Up(), 1.5f};
    
    // Ground position and coordinate
    groundCoordinadeY = GetScreenHeight()/CELL_SIZE-1;
    groundPositionY = GetOnGridPosition((Vector2){0, groundCoordinadeY}).y;
    
    // Player initialization
    InitializePlayer(&player, (Vector2){4, groundCoordinadeY-1}, (Vector2){0, 15}, 0.35f*GAME_SPEED);
    
    /*
    // Triangles initialization
    InitializeTriangle(&triangles[0], (Vector2){40, groundCoordinadeY-1});
    InitializeTriangle(&triangles[1], (Vector2){50, groundCoordinadeY-1});
    InitializeTriangle(&triangles[2], (Vector2){85, groundCoordinadeY-1});
    
    // Platforms initialization
    InitializePlatform(&platforms[0], (Vector2){20, groundCoordinadeY-1});
    InitializePlatform(&platforms[1], (Vector2){21, groundCoordinadeY-1});
    InitializePlatform(&platforms[2], (Vector2){22, groundCoordinadeY-1});
    InitializePlatform(&platforms[3], (Vector2){23, groundCoordinadeY-2});
    InitializePlatform(&platforms[4], (Vector2){24, groundCoordinadeY-2});
    */
}
Beispiel #10
0
//----------------------------------------------------------------------------------
// Main entry point
//----------------------------------------------------------------------------------
int main(void) 
{
	// Initialization (Note windowTitle is unused on Android)
	//---------------------------------------------------------
    InitWindow(screenWidth, screenHeight, "KOALA SEASONS");

    // Load global data here (assets that must be available in all screens, i.e. fonts)
    font = LoadFont("resources/graphics/mainfont.png");

    atlas01 = LoadTexture("resources/graphics/atlas01.png");
    atlas02 = LoadTexture("resources/graphics/atlas02.png");
    
#if defined(PLATFORM_WEB) || defined(PLATFORM_RPI) || defined(PLATFORM_ANDROID)
    colorBlend = LoadShader("resources/shaders/glsl100/base.vs", "resources/shaders/glsl100/blend_color.fs");
#else
    colorBlend = LoadShader("resources/shaders/glsl330/base.vs", "resources/shaders/glsl330/blend_color.fs");
#endif

    InitAudioDevice();
    
    // Load sounds data
    fxJump = LoadSound("resources/audio/jump.ogg");
    fxDash = LoadSound("resources/audio/dash.ogg");
    fxEatLeaves = LoadSound("resources/audio/eat_leaves.ogg");
    fxHitResin = LoadSound("resources/audio/resin_hit.ogg");
    fxWind = LoadSound("resources/audio/wind_sound.ogg");
    fxDieSnake = LoadSound("resources/audio/snake_die.ogg");
    fxDieDingo = LoadSound("resources/audio/dingo_die.ogg");
    fxDieOwl = LoadSound("resources/audio/owl_die.ogg");
    
    
    music = LoadMusicStream("resources/audio/jngl.xm");
    PlayMusicStream(music);
    SetMusicVolume(music, 1.0f);

    // Define and init first screen
    // NOTE: currentScreen is defined in screens.h as a global variable
    currentScreen = TITLE;

    InitLogoScreen();
    //InitOptionsScreen();
    InitTitleScreen();
    InitGameplayScreen();
    InitEndingScreen();

#if defined(PLATFORM_WEB)
    emscripten_set_main_loop(UpdateDrawFrame, 0, 1);
#else
    SetTargetFPS(60);   // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------
    
    // Main game loop
    while (!WindowShouldClose()) UpdateDrawFrame();
#endif

    // De-Initialization
    //--------------------------------------------------------------------------------------
    UnloadEndingScreen();
    UnloadTitleScreen();
    UnloadGameplayScreen();
    UnloadLogoScreen();
    
    UnloadTexture(atlas01);
    UnloadTexture(atlas02);
    UnloadFont(font);
    
    UnloadShader(colorBlend);   // Unload color overlay blending shader
    
    UnloadSound(fxJump);
    UnloadSound(fxDash);
    UnloadSound(fxEatLeaves);
    UnloadSound(fxHitResin);
    UnloadSound(fxWind);
    UnloadSound(fxDieSnake);
    UnloadSound(fxDieDingo);
    UnloadSound(fxDieOwl);
    
    UnloadMusicStream(music);
    
    CloseAudioDevice();         // Close audio device

    CloseWindow();              // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}
Beispiel #11
0
// Gameplay Screen Initialization logic
void InitLivingroomScreen(void)
{
    ResetPlayer();
    
    // Reset Screen variables
    monsterHover = false;
    monsterCheck = -1;
    msgState = 0;
    msgCounter = 0;
    lettersCounter = 0;
    for (int i = 0; i < 256; i++) msgBuffer[i] = '\0';
    
    framesCounter = 0;
    finishScreen = 0;
    
    background = LoadTexture("resources/textures/background_livingroom.png");
    
    // Initialize doors
    doorLeft.position = (Vector2) { -45, 140};
    doorLeft.facing = 0;
    doorLeft.locked = true;
    doorLeft.frameRec =(Rectangle) {((doors.width/3)*doorLeft.facing), doors.height/2, doors.width/3, doors.height/2};
    doorLeft.bound = (Rectangle) { doorLeft.position.x, doorLeft.position.y, doors.width/3, doors.height/2};
    doorLeft.selected = false;
    
    doorCenter.position = (Vector2) { 830, 108 };
    doorCenter.facing = 1;
    doorCenter.locked = true;
    doorCenter.frameRec =(Rectangle) {((doors.width/3)*doorCenter.facing), doors.height/2, doors.width/3, doors.height/2};
    doorCenter.bound = (Rectangle) { doorCenter.position.x, doorCenter.position.y, doors.width/3, doors.height/2};
    doorCenter.selected = false;

    // Monster init: lamp
    candle.position = (Vector2){ 154, 256 };
    candle.texture = LoadTexture("resources/textures/monster_candle.png");
    candle.currentFrame = 0;
    candle.framesCounter = 0;
    candle.numFrames = 4;
    candle.bounds = (Rectangle){ candle.position.x + 90, candle.position.y + 30, 185, 340 };
    candle.frameRec = (Rectangle) { 0, 0, candle.texture.width/candle.numFrames, candle.texture.height };
    candle.selected = false;
    candle.active = false;
    candle.spooky = false;
    
    // Monster init: arc
    picture.position = (Vector2){ 504, 164 };
    picture.texture = LoadTexture("resources/textures/monster_picture.png");
    picture.currentFrame = 0;
    picture.framesCounter = 0;
    picture.numFrames = 4;
    picture.bounds = (Rectangle){ picture.position.x + 44, picture.position.y, 174, 264 };
    picture.frameRec = (Rectangle) { 0, 0, picture.texture.width/picture.numFrames, picture.texture.height };
    picture.selected = false;
    picture.active = false;
    picture.spooky = true;
    
    // Monster init: phone
    phone.position = (Vector2){ 1054, 404 };
    phone.texture = LoadTexture("resources/textures/monster_phone.png");
    phone.currentFrame = 0;
    phone.framesCounter = 0;
    phone.numFrames = 4;
    phone.bounds = (Rectangle){ phone.position.x + 64, phone.position.y +120, 100, 160 };
    phone.frameRec = (Rectangle) { 0, 0, phone.texture.width/phone.numFrames, phone.texture.height };
    phone.selected = false;
    phone.active = false;
    phone.spooky = true;
}
Beispiel #12
0
int main()
{    
    // Initialization
    //--------------------------------------------------------------------------------------
    int screenWidth = 800;
    int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "Floppy Bird");
    
    InitAudioDevice();      // Initialize audio device
    
    Sound coin = LoadSound("resources/coin.wav");
    Sound jump = LoadSound("resources/jump.wav");
    
    Texture2D background = LoadTexture("resources/background.png");
    Texture2D tubes = LoadTexture("resources/tubes.png");
    Texture2D floppy = LoadTexture("resources/floppy.png");
    
    Vector2 floppyPos = { 80, screenHeight/2 - floppy.height/2 };
    
    Vector2 tubesPos[MAX_TUBES];
    int tubesSpeedX = 2;
    
    for (int i = 0; i < MAX_TUBES; i++)
    {
        tubesPos[i].x = 400 + 280*i;
        tubesPos[i].y = -GetRandomValue(0, 120);
    }
    
    Rectangle tubesRecs[MAX_TUBES*2];
    bool tubesActive[MAX_TUBES];
    
    for (int i = 0; i < MAX_TUBES*2; i += 2)
    {
        tubesRecs[i].x = tubesPos[i/2].x;
        tubesRecs[i].y = tubesPos[i/2].y;
        tubesRecs[i].width = tubes.width;
        tubesRecs[i].height = 255;
        
        tubesRecs[i+1].x = tubesPos[i/2].x;
        tubesRecs[i+1].y = 600 + tubesPos[i/2].y - 255;
        tubesRecs[i+1].width = tubes.width;
        tubesRecs[i+1].height = 255;
        
        tubesActive[i/2] = true;
    }
 
    int backScroll = 0;
    
    int score = 0;
    int hiscore = 0;
    
    bool gameover = false;
    bool superfx = false;
    
    SetTargetFPS(60);
    //---------------------------------------------------------------------------------------
    
    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update
        //----------------------------------------------------------------------------------
        backScroll--;
        
        if (backScroll <= -800) backScroll = 0; 
        
        for (int i = 0; i < MAX_TUBES; i++) tubesPos[i].x -= tubesSpeedX;
        
        for (int i = 0; i < MAX_TUBES*2; i += 2)
        {
            tubesRecs[i].x = tubesPos[i/2].x;
            tubesRecs[i+1].x = tubesPos[i/2].x;
        }

        if (IsKeyDown(KEY_SPACE) && !gameover) floppyPos.y -= 3;
        else floppyPos.y += 1;
        
        if (IsKeyPressed(KEY_SPACE) && !gameover) PlaySound(jump);
        
        // Check Collisions
        for (int i = 0; i < MAX_TUBES*2; i++)
        {
            if (CheckCollisionCircleRec((Vector2){ floppyPos.x + floppy.width/2, floppyPos.y + floppy.height/2 }, floppy.width/2, tubesRecs[i])) 
            {
                gameover = true;
            }
            else if ((tubesPos[i/2].x < floppyPos.x) && tubesActive[i/2] && !gameover)
            {
                score += 100;
                tubesActive[i/2] = false;
                PlaySound(coin);
                
                superfx = true;
                
                if (score > hiscore) hiscore = score;
            }
        }
        
        if (gameover && IsKeyPressed(KEY_ENTER))
        {
            for (int i = 0; i < MAX_TUBES; i++)
            {
                tubesPos[i].x = 400 + 280*i;
                tubesPos[i].y = -GetRandomValue(0, 120);
            }
    
            for (int i = 0; i < MAX_TUBES*2; i += 2)
            {
                tubesRecs[i].x = tubesPos[i/2].x;
                tubesRecs[i].y = tubesPos[i/2].y;
                
                tubesRecs[i+1].x = tubesPos[i/2].x;
                tubesRecs[i+1].y = 600 + tubesPos[i/2].y - 255;
                
                tubesActive[i/2] = true;
            }
        
            floppyPos.x = 80;
            floppyPos.y = screenHeight/2 - floppy.height/2;
            
            gameover = false;
            score = 0;
        }
        
        //----------------------------------------------------------------------------------
        
        // Draw
        //----------------------------------------------------------------------------------
        BeginDrawing();
        
            ClearBackground(RAYWHITE);
            
            DrawTexture(background, backScroll, 0, WHITE);
            DrawTexture(background, screenWidth + backScroll, 0, WHITE);
            
            if (!gameover)
            {
                DrawTextureEx(floppy, floppyPos, 0, 1.0, WHITE);
                //DrawCircleLines(floppyPos.x + floppy.width/2, floppyPos.y + floppy.height/2, floppy.width/2, RED);
            }
            
            for (int i = 0; i < MAX_TUBES; i++)
            {
                if (tubesPos[i].x <= 800) DrawTextureEx(tubes, tubesPos[i], 0, 1.0, WHITE);
            
                //DrawRectangleLines(tubesRecs[i*2].x, tubesRecs[i*2].y, tubesRecs[i*2].width, tubesRecs[i*2].height, RED);
                //DrawRectangleLines(tubesRecs[i*2 + 1].x, tubesRecs[i*2 + 1].y, tubesRecs[i*2 + 1].width, tubesRecs[i*2 + 1].height, RED);
            }
            
            DrawText(FormatText("%04i", score), 20, 20, 40, PINK);
            DrawText(FormatText("HI-SCORE: %04i", hiscore), 20, 70, 20, VIOLET); 
            
            if (gameover)
            {
                DrawText("GAME OVER", 100, 180, 100, MAROON);
                DrawText("PRESS ENTER to RETRY!", 280, 280, 20, RED);    
            }
            
            if (superfx)
            {
                DrawRectangle(0, 0, screenWidth, screenHeight, GOLD);
                superfx = false;
            }
        
        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    UnloadTexture(background);  // Texture unloading
    UnloadTexture(tubes);       // Texture unloading
    UnloadTexture(floppy);      // Texture unloading
    
    UnloadSound(coin);          // Unload sound data
    UnloadSound(jump);          // Unload sound data
    
    CloseAudioDevice();         // Close audio device
    
    CloseWindow();              // Close window and OpenGL context
    //--------------------------------------------------------------------------------------
    
    return 0;
}
void CBspMapResourceProvider::LoadTextures(const CBspFile& bspFile, CPakFile& pakFile)
{
	const Bsp::TextureArray& textures(bspFile.GetTextures());
	m_materials.resize(textures.size());
	for(uint32 i = 0; i < textures.size(); i++)
	{
		const Bsp::TEXTURE& texture(textures[i]);

		auto resultMaterial = BspMapMaterialPtr(new CBspMapMaterial());
		m_materials[i] = resultMaterial;

		ShaderMap::const_iterator shaderIterator = m_shaders.find(texture.name);
		if(shaderIterator == m_shaders.end())
		{
			//Create a basic material with this texture
			std::string fullName;
			if(!pakFile.TryCompleteFileName(texture.name, fullName))
			{
				continue;
			}

			LoadTexture(fullName.c_str(), pakFile);

			{
				auto pass = BspMapPassPtr(new CBspMapPass());
				pass->SetTexture(GetTexture(fullName.c_str()));
				pass->SetTextureSource(CBspMapPass::TEXTURE_SOURCE_DIFFUSE);
				pass->SetBlendingFunction(Palleon::TEXTURE_COMBINE_MODULATE);
				resultMaterial->AddPass(pass);
			}

			{
				auto pass = BspMapPassPtr(new CBspMapPass());
				pass->SetTextureSource(CBspMapPass::TEXTURE_SOURCE_LIGHTMAP);
				pass->SetBlendingFunction(Palleon::TEXTURE_COMBINE_MODULATE);
				resultMaterial->AddPass(pass);
			}
		}
		else
		{
			const QUAKE_SHADER& shader = shaderIterator->second;

			resultMaterial->SetIsSky(shader.isSky);

			for(QuakeShaderPassArray::const_iterator passIterator(shader.passes.begin());
				passIterator != shader.passes.end(); passIterator++)
			{
				const QUAKE_SHADER_PASS& passData(*passIterator);
				if(passData.mapName.length() < 4) continue;

				auto pass = BspMapPassPtr(new CBspMapPass());

				{
					Palleon::TEXTURE_COMBINE_MODE blendingFunction = Palleon::TEXTURE_COMBINE_MODULATE;
					switch(passData.blendFunc)
					{
					case QUAKE_SHADER_BLEND_BLEND:
						blendingFunction = Palleon::TEXTURE_COMBINE_LERP;
						break;
					case QUAKE_SHADER_BLEND_ADD:
						blendingFunction = Palleon::TEXTURE_COMBINE_ADD;
						break;
					case QUAKE_SHADER_BLEND_FILTER:
						blendingFunction = Palleon::TEXTURE_COMBINE_MODULATE;
						break;
					}
					pass->SetBlendingFunction(blendingFunction);
				}

				if(passData.mapName == "$lightmap")
				{
					pass->SetTextureSource(CBspMapPass::TEXTURE_SOURCE_LIGHTMAP);
				}
				else
				{
					std::string fileName(passData.mapName.begin(), passData.mapName.begin() + passData.mapName.length() - 4);
					
					std::string fullName;
					if(!pakFile.TryCompleteFileName(fileName.c_str(), fullName))
					{
						continue;
					}

					LoadTexture(fullName.c_str(), pakFile);
					pass->SetTexture(GetTexture(fullName.c_str()));
					pass->SetTextureSource(CBspMapPass::TEXTURE_SOURCE_DIFFUSE);
				}

				for(unsigned int i = 0; i < passData.tcMods.size(); i++)
				{
					const QUAKE_SHADER_TCMOD& tcMod(passData.tcMods[i]);
					BspMapTcModPtr result;
					switch(tcMod.type)
					{
					case QUAKE_SHADER_TCMOD_SCROLL:
						result = BspMapTcModPtr(new CBspMapTcMod_Scroll(
									tcMod.params[0],
									tcMod.params[1]));
						break;
					case QUAKE_SHADER_TCMOD_SCALE:
						result = BspMapTcModPtr(new CBspMapTcMod_Scale(
									tcMod.params[0],
									tcMod.params[1]));
						break;
					case QUAKE_SHADER_TCMOD_ROTATE:
						result = BspMapTcModPtr(new CBspMapTcMod_Rotate(
									tcMod.params[0]));
						break;
					case QUAKE_SHADER_TCMOD_TURB:
						result = BspMapTcModPtr(new CBspMapTcMod_Turb(
									tcMod.params[1],
									tcMod.params[3]));
						break;
					case QUAKE_SHADER_TCMOD_STRETCH:
						{
							BSPMAPWAVEPARAMS wave;
							wave.type		= BSPMAPWAVEPARAMS::WAVE_SIN;
							wave.base		= tcMod.params[0];
							wave.amplitude	= tcMod.params[1];
							wave.phase		= tcMod.params[2];
							wave.freq		= tcMod.params[3];
							result = BspMapTcModPtr(new CBspMapTcMod_Stretch(wave));
						}
						break;
					default:
						continue;
						break;
					}
					pass->AddTcMod(result);
				}

				resultMaterial->AddPass(pass);

				if(resultMaterial->GetPassCount() == CBspMapMaterial::MAX_PASS)
				{
					break;
				}
			}
		}
	}
}
Beispiel #14
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	

	SDL_Event event;
	bool done = false;
#ifdef _WINDOWS
	glewInit();
#endif

	Matrix projectionMatrix;
	Matrix modelMatrix;
	Matrix viewMatrix;

	ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");



	GLuint dogTexture = LoadTexture("dog.png");
	GLuint ballTexture = LoadTexture("ball.png");
	GLuint boneTexture = LoadTexture("bone.png");

	projectionMatrix.setOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f);
	glUseProgram(program.programID);

	float lastFrameTicks = 0.0f;

	double movement = 0.0;

	double ballBounce = 0.0;

	bool bounceHigh = false;

	bool firstHit = false;

	const Uint8 *keys = SDL_GetKeyboardState(NULL);

	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		

		glClear(GL_COLOR_BUFFER_BIT);
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);
		glBindTexture(GL_TEXTURE_2D, ballTexture);

		float ticks = (float)SDL_GetTicks() / 1000.0f;

		float elapsed = ticks - lastFrameTicks;
			
		lastFrameTicks = ticks;

		if (firstHit == false){
			movement = movement + elapsed;
		}

		//makes the ball bounce
		if ((ballBounce * 0.75) >= 1){
			bounceHigh = true;
		}

		if ((ballBounce * 0.75) <= -1){
			bounceHigh = false;
		}
		
		if (bounceHigh == false){
			ballBounce = ballBounce + elapsed;
		}
		else if (bounceHigh == true){
			ballBounce = ballBounce - elapsed;
		}

		
		float vertices[] = { -1.4 + (movement * 0.25), -0.4 + (ballBounce * 0.25), -0.4 + (movement * 0.25), -0.4 + (ballBounce * 0.25),
			-0.4 + (movement * 0.25), 0.4 + (ballBounce * 0.25), -1.4 + (movement * 0.25), -0.4 + (ballBounce * 0.25),
			-0.4 + (movement * 0.25), 0.4 + (ballBounce * 0.25), -1.4 + (movement * 0.25), 0.4 + (ballBounce * 0.25) };
		
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);


		if (keys[SDL_SCANCODE_A]) {
			--p1X;
		}
		else if (keys[SDL_SCANCODE_D]) {
			++p1X;
		}

		if (keys[SDL_SCANCODE_W]) {
			++p1Y;
		}
		else if (keys[SDL_SCANCODE_S]) {
			--p1Y;
		}

		glBindTexture(GL_TEXTURE_2D, dogTexture);

		float vertices2[] = { -2.5 + (p1X * 0.001), -0.5 + (p1Y * 0.001), -1.5 + (p1X * 0.001), -0.5 + (p1Y * 0.001),
			-1.5 + (p1X * 0.001), 0.5 + (p1Y * 0.001), -2.5 + (p1X * 0.001), -0.5 + (p1Y * 0.001),
			-1.5 + (p1X * 0.001), 0.5 + (p1Y * 0.001), -2.5 + (p1X * 0.001), 0.5 + (p1Y * 0.001) };


		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords2[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords2);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);


		if (keys[SDL_SCANCODE_J]) {
			--p2X;
		}
		else if (keys[SDL_SCANCODE_L]) {
			++p2X;
		}

		if (keys[SDL_SCANCODE_I]) {
			++p2Y;
		}
		else if (keys[SDL_SCANCODE_K]) {
			--p2Y;
		}

		glBindTexture(GL_TEXTURE_2D, dogTexture);

		float vertices3[] = { 1.5 + (p2X * 0.001), -0.5 + (p2Y * 0.001), 2.5 + (p2X * 0.001), -0.5 + (p2Y * 0.001),
			2.5 + (p2X * 0.001), 0.5 + (p2Y * 0.001), 1.5 + (p2X * 0.001), -0.5 + (p2Y * 0.001),
			2.5 + (p2X * 0.001), 0.5 + (p2Y * 0.001), 1.5 + (p2X * 0.001), 0.5 + (p2Y * 0.001) };

		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices3);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords3[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords3);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);
		SDL_GL_SwapWindow(displayWindow);

		//collision
		if ((vertices[11] <= vertices2[5] && vertices[11] >= vertices2[3])
			|| (vertices[1] <= vertices2[5] && vertices[1] >= vertices2[3])
			&& vertices[10] == vertices2[4])
		{
			firstHit = true;
			movement = movement + elapsed;
		}
		else if ((vertices[5] <= vertices3[11] && vertices[5] >= vertices3[1])
			|| (vertices[3] <= vertices3[11] && vertices[3] >= vertices3[1])
			&& vertices[4] == vertices3[10])
		{
			firstHit = true;
			movement = movement - elapsed;
		}

		if (vertices[10] <= vertices2[4])
		{
			std::cout << "Player 2 Wins" << std::endl;
		}

		else if (vertices[4] >= vertices3[10])
		{
			std::cout << "Player 1 Wins" << std::endl;
		}
	}

	SDL_Quit();
	return 0;
}
static SDL_bool
WatchJoystick(SDL_Joystick * joystick)
{
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    SDL_Texture *background, *button, *axis, *marker;
    const char *name = NULL;
    SDL_bool retval = SDL_FALSE;
    SDL_bool done = SDL_FALSE, next=SDL_FALSE;
    SDL_Event event;
    SDL_Rect dst;
    int s, _s;
    Uint8 alpha=200, alpha_step = -1;
    Uint32 alpha_ticks;
    char mapping[4096], temp[4096];
    MappingStep *step;
    MappingStep steps[] = {
        {342, 132,  0.0,  MARKER_BUTTON, "x", -1, -1, -1, -1, ""},
        {387, 167,  0.0,  MARKER_BUTTON, "a", -1, -1, -1, -1, ""},
        {431, 132,  0.0,  MARKER_BUTTON, "b", -1, -1, -1, -1, ""},
        {389, 101,  0.0,  MARKER_BUTTON, "y", -1, -1, -1, -1, ""},
        {174, 132,  0.0,  MARKER_BUTTON, "back", -1, -1, -1, -1, ""},
        {233, 132,  0.0,  MARKER_BUTTON, "guide", -1, -1, -1, -1, ""},
        {289, 132,  0.0,  MARKER_BUTTON, "start", -1, -1, -1, -1, ""},        
        {116, 217,  0.0,  MARKER_BUTTON, "dpleft", -1, -1, -1, -1, ""},
        {154, 249,  0.0,  MARKER_BUTTON, "dpdown", -1, -1, -1, -1, ""},
        {186, 217,  0.0,  MARKER_BUTTON, "dpright", -1, -1, -1, -1, ""},
        {154, 188,  0.0,  MARKER_BUTTON, "dpup", -1, -1, -1, -1, ""},
        {77,  40,   0.0,  MARKER_BUTTON, "leftshoulder", -1, -1, -1, -1, ""},
        {91, 0,    0.0,  MARKER_BUTTON, "lefttrigger", -1, -1, -1, -1, ""},
        {396, 36,   0.0,  MARKER_BUTTON, "rightshoulder", -1, -1, -1, -1, ""},
        {375, 0,    0.0,  MARKER_BUTTON, "righttrigger", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_BUTTON, "leftstick", -1, -1, -1, -1, ""},
        {305, 230,  0.0,  MARKER_BUTTON, "rightstick", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_AXIS,   "leftx", -1, -1, -1, -1, ""},
        {75,  154,  90.0, MARKER_AXIS,   "lefty", -1, -1, -1, -1, ""},        
        {305, 230,  0.0,  MARKER_AXIS,   "rightx", -1, -1, -1, -1, ""},
        {305, 230,  90.0, MARKER_AXIS,   "righty", -1, -1, -1, -1, ""},
    };

    /* Create a window to display joystick axis position */
    window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }
    
    background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
    button = LoadTexture(screen, "button.bmp", SDL_TRUE);
    axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);
    SDL_RaiseWindow(window);

    /* scale for platforms that don't give you the window size you asked for. */
    SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);

    /* Print info about the joystick we are watching */
    name = SDL_JoystickName(joystick);
    SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick),
           name ? name : "Unknown Joystick");
    SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n",
           SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
           SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
    
    SDL_Log("\n\n\
    ====================================================================================\n\
    Press the buttons on your controller when indicated\n\
    (Your controller may look different than the picture)\n\
    If you want to correct a mistake, press backspace or the back button on your device\n\
    To skip a button, press SPACE or click/touch the screen\n\
    To exit, press ESC\n\
    ====================================================================================\n");
    
    /* Initialize mapping with GUID and name */
    SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, SDL_arraysize(temp));
    SDL_snprintf(mapping, SDL_arraysize(mapping), "%s,%s,platform:%s,",
        temp, name ? name : "Unknown Joystick", SDL_GetPlatform());

    /* Loop, getting joystick events! */
    for(s=0; s<SDL_arraysize(steps) && !done;) {
        /* blank screen, set up for drawing this frame. */
        step = &steps[s];
        SDL_strlcpy(step->mapping, mapping, SDL_arraysize(step->mapping));
        step->axis = -1;
        step->button = -1;
        step->hat = -1;
        step->hat_value = -1;
        SDL_SetClipboardText("TESTING TESTING 123");
        
        switch(step->marker) {
            case MARKER_AXIS:
                marker = axis;
                break;
            case MARKER_BUTTON:
                marker = button;
                break;
            default:
                break;
        }
        
        dst.x = step->x;
        dst.y = step->y;
        SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h);
        next=SDL_FALSE;

        SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);

        while (!done && !next) {
            if (SDL_GetTicks() - alpha_ticks > 5) {
                alpha_ticks = SDL_GetTicks();
                alpha += alpha_step;
                if (alpha == 255) {
                    alpha_step = -1;
                }
                if (alpha < 128) {
                    alpha_step = 1;
                }
            }
            
            SDL_RenderClear(screen);
            SDL_RenderCopy(screen, background, NULL, NULL);
            SDL_SetTextureAlphaMod(marker, alpha);
            SDL_SetTextureColorMod(marker, 10, 255, 21);
            SDL_RenderCopyEx(screen, marker, NULL, &dst, step->angle, NULL, 0);
            SDL_RenderPresent(screen);
            
            if (SDL_PollEvent(&event)) {
                switch (event.type) {
                case SDL_JOYAXISMOTION:
                    if (event.jaxis.value > 20000 || event.jaxis.value < -20000) {
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].axis == event.jaxis.axis) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->axis = event.jaxis.axis;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":a%u,", event.jaxis.axis);
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    }
                    
                    break;
                case SDL_JOYHATMOTION:
                        if (event.jhat.value == SDL_HAT_CENTERED) {
                            break;  /* ignore centering, we're probably just coming back to the center from the previous item we set. */
                        }
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].hat == event.jhat.hat && steps[_s].hat_value == event.jhat.value) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->hat = event.jhat.hat;
                            step->hat_value = event.jhat.value;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":h%u.%u,", event.jhat.hat, event.jhat.value );
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    break;
                case SDL_JOYBALLMOTION:
                    break;
                case SDL_JOYBUTTONUP:
                    for (_s = 0; _s < s; _s++) {
                        if (steps[_s].button == event.jbutton.button) {
                            break;
                        }
                    }
                    if (_s == s) {
                        step->button = event.jbutton.button;
                        SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                        SDL_snprintf(temp, SDL_arraysize(temp), ":b%u,", event.jbutton.button);
                        SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                        s++;
                        next=SDL_TRUE;
                    }
                    break;
                case SDL_FINGERDOWN:
                case SDL_MOUSEBUTTONDOWN:
                    /* Skip this step */
                    s++;
                    next=SDL_TRUE;
                    break;
                case SDL_KEYDOWN:
                    if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
                        /* Undo! */
                        if (s > 0) {
                            SDL_strlcpy(mapping, step->mapping, SDL_arraysize(step->mapping));
                            s--;
                            next = SDL_TRUE;
                        }
                        break;
                    }
                    if (event.key.keysym.sym == SDLK_SPACE) {
                        /* Skip this step */
                        s++;
                        next=SDL_TRUE;
                        break;
                    }
                    
                    if ((event.key.keysym.sym != SDLK_ESCAPE)) {
                        break;
                    }
                    /* Fall through to signal quit */
                case SDL_QUIT:
                    done = SDL_TRUE;
                    break;
                default:
                    break;
                }
            }
        }

    }

    if (s == SDL_arraysize(steps) ) {
        SDL_Log("Mapping:\n\n%s\n\n", mapping);
        /* Print to stdout as well so the user can cat the output somewhere */
        printf("%s\n", mapping);
    }
    
    while(SDL_PollEvent(&event)) {};
    
    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
    return retval;
}
Beispiel #16
0
//-------------------------------------------------------------------------------
int CMaterialManager::CreateMaterial(
	AssetHelper::MeshHelper* pcMesh,const aiMesh* pcSource)
{
#if 1//???
	ai_assert(0 != pcMesh);
	ai_assert(0 != pcSource);

//	ID3DXFROMWINEBuffer* piBuffer;


	// extract all properties from the ASSIMP material structure
	const aiMaterial* pcMat = mr->GetAsset()->pcScene->mMaterials[pcSource->mMaterialIndex];

	//
	// DIFFUSE COLOR --------------------------------------------------
	//
	if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_DIFFUSE,
		(aiColor4D*)&pcMesh->vDiffuseColor))
	{
		pcMesh->vDiffuseColor.x = 1.0f;
		pcMesh->vDiffuseColor.y = 1.0f;
		pcMesh->vDiffuseColor.z = 1.0f;
		pcMesh->vDiffuseColor.w = 1.0f;
	}
	//
	// SPECULAR COLOR --------------------------------------------------
	//
	if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_SPECULAR,
		(aiColor4D*)&pcMesh->vSpecularColor))
	{
		pcMesh->vSpecularColor.x = 1.0f;
		pcMesh->vSpecularColor.y = 1.0f;
		pcMesh->vSpecularColor.z = 1.0f;
		pcMesh->vSpecularColor.w = 1.0f;
	}
	//
	// AMBIENT COLOR --------------------------------------------------
	//
	if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_AMBIENT,
		(aiColor4D*)&pcMesh->vAmbientColor))
	{
		pcMesh->vAmbientColor.x = 0.0f;
		pcMesh->vAmbientColor.y = 0.0f;
		pcMesh->vAmbientColor.z = 0.0f;
		pcMesh->vAmbientColor.w = 1.0f;
	}
	//
	// EMISSIVE COLOR -------------------------------------------------
	//
	if(AI_SUCCESS != aiGetMaterialColor(pcMat,AI_MATKEY_COLOR_EMISSIVE,
		(aiColor4D*)&pcMesh->vEmissiveColor))
	{
		pcMesh->vEmissiveColor.x = 0.0f;
		pcMesh->vEmissiveColor.y = 0.0f;
		pcMesh->vEmissiveColor.z = 0.0f;
		pcMesh->vEmissiveColor.w = 1.0f;
	}

	//
	// Opacity --------------------------------------------------------
	//
	if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_OPACITY,&pcMesh->fOpacity))
	{
		pcMesh->fOpacity = 1.0f;
	}

	//
	// Shading Model --------------------------------------------------
	//
	bool bDefault = false;
	if(AI_SUCCESS != aiGetMaterialInteger(pcMat,AI_MATKEY_SHADING_MODEL,(int*)&pcMesh->eShadingMode ))
	{
		bDefault = true;
		pcMesh->eShadingMode = aiShadingMode_Gouraud;
	}


	//
	// Shininess ------------------------------------------------------
	//
	if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_SHININESS,&pcMesh->fShininess))
	{
		// assume 15 as default shininess
		pcMesh->fShininess = 15.0f;
	}
	else if (bDefault)pcMesh->eShadingMode  = aiShadingMode_Phong;


	//
	// Shininess strength ------------------------------------------------------
	//
	if(AI_SUCCESS != aiGetMaterialFloat(pcMat,AI_MATKEY_SHININESS_STRENGTH,&pcMesh->fSpecularStrength))
	{
		// assume 1.0 as default shininess strength
		pcMesh->fSpecularStrength = 1.0f;
	}

	aiString szPath;

	aiTextureMapMode mapU(aiTextureMapMode_Wrap),mapV(aiTextureMapMode_Wrap);

	bool bib =false;
	if (pcSource->mTextureCoords[0])
	{

		//
		// DIFFUSE TEXTURE ------------------------------------------------
		//
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_DIFFUSE(0),&szPath))
		{
			LoadTexture(&pcMesh->piDiffuseTexture,&szPath);

			aiGetMaterialInteger(pcMat,AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0),(int*)&mapU);
			aiGetMaterialInteger(pcMat,AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0),(int*)&mapV);
		}

		//
		// SPECULAR TEXTURE ------------------------------------------------
		//
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_SPECULAR(0),&szPath))
		{
			LoadTexture(&pcMesh->piSpecularTexture,&szPath);
		}

		//
		// OPACITY TEXTURE ------------------------------------------------
		//
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_OPACITY(0),&szPath))
		{
			LoadTexture(&pcMesh->piOpacityTexture,&szPath);
		}
		else
		{
			int flags = aiTextureFlags_IgnoreAlpha;//???0;
			aiGetMaterialInteger(pcMat,AI_MATKEY_TEXFLAGS_DIFFUSE(0),&flags);

			// try to find out whether the diffuse texture has any
			// non-opaque pixels. If we find a few, use it as opacity texture
			if ((pcMesh->piDiffuseTexture!=-1) && !(flags & aiTextureFlags_IgnoreAlpha) && HasAlphaPixels(pcMesh->piDiffuseTexture))
			{
				int iVal;

				// NOTE: This special value is set by the tree view if the user
				// manually removes the alpha texture from the view ...
				if (AI_SUCCESS != aiGetMaterialInteger(pcMat,"no_a_from_d",0,0,&iVal))
				{
					pcMesh->piOpacityTexture = pcMesh->piDiffuseTexture;
//					pcMesh->piOpacityTexture->AddRef();
				}
			}
		}

		//
		// AMBIENT TEXTURE ------------------------------------------------
		//
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_AMBIENT(0),&szPath))
		{
			LoadTexture(&pcMesh->piAmbientTexture,&szPath);

		}

		//
		// EMISSIVE TEXTURE ------------------------------------------------
		//
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_EMISSIVE(0),&szPath))
		{
			LoadTexture(&pcMesh->piEmissiveTexture,&szPath);
		}

		//
		// Shininess TEXTURE ------------------------------------------------
		//
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_SHININESS(0),&szPath))
		{
			LoadTexture(&pcMesh->piShininessTexture,&szPath);
		}

		//
		// Lightmap TEXTURE ------------------------------------------------
		//
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_LIGHTMAP(0),&szPath))
		{
			LoadTexture(&pcMesh->piLightmapTexture,&szPath);
		}


		//
		// NORMAL/HEIGHT MAP ------------------------------------------------
		//
		bool bHM = false;
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_NORMALS(0),&szPath))
		{
			LoadTexture(&pcMesh->piNormalTexture,&szPath);
		}
		else
		{
			if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_TEXTURE_HEIGHT(0),&szPath))
			{
				LoadTexture(&pcMesh->piNormalTexture,&szPath);
			}
			else bib = true;
			bHM = true;
		}

		// normal/height maps are sometimes mixed up. Try to detect the type
		// of the texture automatically
		if (pcMesh->piNormalTexture!=-1)
		{
			HMtoNMIfNecessary(pcMesh->piNormalTexture, &pcMesh->piNormalTexture,bHM);
		}
	}

	// check whether a global background texture is contained
	// in this material. Some loaders set this value ...
	if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_GLOBAL_BACKGROUND_IMAGE,&szPath))
	{
//		CBackgroundPainter::Instance().SetTextureBG(szPath.data);
	}

	// BUGFIX: If the shininess is 0.0f disable phong lighting
	// This is a workaround for some meshes in the DX SDK (e.g. tiny.x)
	// FIX: Added this check to the x-loader, but the line remains to
	// catch other loader doing the same ...
	if (0.0f == pcMesh->fShininess){
		pcMesh->eShadingMode = aiShadingMode_Gouraud;
	}

	int two_sided = 0;
	aiGetMaterialInteger(pcMat,AI_MATKEY_TWOSIDED,&two_sided);
	pcMesh->twosided = (two_sided != 0);

	// check whether we have already a material using the same
	// shader. This will decrease loading time rapidly ...
	for (unsigned int i = 0; i < mr->GetAsset()->pcScene->mNumMeshes;++i)
	{
		if (mr->GetAsset()->pcScene->mMeshes[i] == pcSource)
		{
			break;
		}
		AssetHelper::MeshHelper* pc = mr->GetAsset()->apcMeshes[i];

		if  ((pcMesh->piDiffuseTexture !=-1 ? true : false) !=
			(pc->piDiffuseTexture !=-1 ? true : false))
			continue;
		if  ((pcMesh->piSpecularTexture !=-1 ? true : false) !=
			(pc->piSpecularTexture !=-1 ? true : false))
			continue;
		if  ((pcMesh->piAmbientTexture !=-1 ? true : false) !=
			(pc->piAmbientTexture !=-1 ? true : false))
			continue;
		if  ((pcMesh->piEmissiveTexture !=-1 ? true : false) !=
			(pc->piEmissiveTexture !=-1 ? true : false))
			continue;
		if  ((pcMesh->piNormalTexture !=-1 ? true : false) !=
			(pc->piNormalTexture !=-1 ? true : false))
			continue;
		if  ((pcMesh->piOpacityTexture !=-1 ? true : false) !=
			(pc->piOpacityTexture !=-1 ? true : false))
			continue;
		if  ((pcMesh->piShininessTexture !=-1 ? true : false) !=
			(pc->piShininessTexture !=-1 ? true : false))
			continue;
		if  ((pcMesh->piLightmapTexture !=-1 ? true : false) !=
			(pc->piLightmapTexture !=-1 ? true : false))
			continue;
		if ((pcMesh->eShadingMode != aiShadingMode_Gouraud ? true : false) !=
			(pc->eShadingMode != aiShadingMode_Gouraud ? true : false))
			continue;

		if ((pcMesh->fOpacity != 1.0f ? true : false) != (pc->fOpacity != 1.0f ? true : false))
			continue;

		if (pcSource->HasBones() != mr->GetAsset()->pcScene->mMeshes[i]->HasBones())
			continue;

		// we can reuse this material
		if (pc->piEffect!=-1)
		{
			pcMesh->piEffect = pc->piEffect;
			pc->bSharedFX = pcMesh->bSharedFX = true;
//			pcMesh->piEffect->AddRef();
			return 2;
		}
	}
	m_iShaderCount++;

	//if(mr->m_piDefaultEffect==-1)
	if(0)
	{
typedef struct _D3DXFROMWINEMACRO
{
    LPCSTR Name;
    LPCSTR Definition;

} D3DXFROMWINEMACRO, *LPD3DXFROMWINEMACRO;

	D3DXFROMWINEMACRO sMacro[64];

	// build macros for the HLSL compiler
	unsigned int iCurrent = 0;
	if (pcMesh->piDiffuseTexture!=-1)
	{
		sMacro[iCurrent].Name = "AV_DIFFUSE_TEXTURE";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;

		if (mapU == aiTextureMapMode_Wrap)
			sMacro[iCurrent].Name = "AV_WRAPU";
		else if (mapU == aiTextureMapMode_Mirror)
			sMacro[iCurrent].Name = "AV_MIRRORU";
		else // if (mapU == aiTextureMapMode_Clamp)
			sMacro[iCurrent].Name = "AV_CLAMPU";

		sMacro[iCurrent].Definition = "1";
		++iCurrent;


		if (mapV == aiTextureMapMode_Wrap)
			sMacro[iCurrent].Name = "AV_WRAPV";
		else if (mapV == aiTextureMapMode_Mirror)
			sMacro[iCurrent].Name = "AV_MIRRORV";
		else // if (mapV == aiTextureMapMode_Clamp)
			sMacro[iCurrent].Name = "AV_CLAMPV";

		sMacro[iCurrent].Definition = "1";
		++iCurrent;
	}
	if (pcMesh->piSpecularTexture!=-1)
	{
		sMacro[iCurrent].Name = "AV_SPECULAR_TEXTURE";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;
	}
	if (pcMesh->piAmbientTexture!=-1)
	{
		sMacro[iCurrent].Name = "AV_AMBIENT_TEXTURE";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;
	}
	if (pcMesh->piEmissiveTexture!=-1)
	{
		sMacro[iCurrent].Name = "AV_EMISSIVE_TEXTURE";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;
	}
	char buff[32];
	if (pcMesh->piLightmapTexture!=-1)
	{
		sMacro[iCurrent].Name = "AV_LIGHTMAP_TEXTURE";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;

		int idx;
		if(AI_SUCCESS == aiGetMaterialInteger(pcMat,AI_MATKEY_UVWSRC_LIGHTMAP(0),&idx) && idx >= 1 && pcSource->mTextureCoords[idx])	{
			sMacro[iCurrent].Name = "AV_TWO_UV";
			sMacro[iCurrent].Definition = "1";
			++iCurrent;

			sMacro[iCurrent].Definition = "IN.TexCoord1";
		}
		else sMacro[iCurrent].Definition = "IN.TexCoord0";
		sMacro[iCurrent].Name = "AV_LIGHTMAP_TEXTURE_UV_COORD";

		++iCurrent;float f= 1.f;
		aiGetMaterialFloat(pcMat,AI_MATKEY_TEXBLEND_LIGHTMAP(0),&f);
		stx_snprintf(buff,32,"%f",f);

		sMacro[iCurrent].Name = "LM_STRENGTH";
		sMacro[iCurrent].Definition = buff;
		++iCurrent;
	}
	if ((pcMesh->piNormalTexture!=-1) && !bib)
	{
		sMacro[iCurrent].Name = "AV_NORMAL_TEXTURE";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;
	}
	if (pcMesh->piOpacityTexture!=-1)
	{
		sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;

		if (pcMesh->piOpacityTexture == pcMesh->piDiffuseTexture)
		{
			sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE_REGISTER_MASK";
			sMacro[iCurrent].Definition = "a";
			++iCurrent;
		}
		else
		{
			sMacro[iCurrent].Name = "AV_OPACITY_TEXTURE_REGISTER_MASK";
			sMacro[iCurrent].Definition = "r";
			++iCurrent;
		}
	}

	if (pcMesh->eShadingMode  != aiShadingMode_Gouraud  && !mr->m_sOptions.bNoSpecular)
	{
		sMacro[iCurrent].Name = "AV_SPECULAR_COMPONENT";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;

		if (pcMesh->piShininessTexture!=-1)
		{
			sMacro[iCurrent].Name = "AV_SHININESS_TEXTURE";
			sMacro[iCurrent].Definition = "1";
			++iCurrent;
		}
	}
	if (1.0f != pcMesh->fOpacity)
	{
		sMacro[iCurrent].Name = "AV_OPACITY";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;
	}

	if( pcSource->HasBones())
	{
		sMacro[iCurrent].Name = "AV_SKINNING";
		sMacro[iCurrent].Definition = "0";//???"1";
		++iCurrent;
	}
/*
	// If a cubemap is active, we'll need to lookup it for calculating
	// a physically correct reflection
	if (CBackgroundPainter::TEXTURE_CUBE == CBackgroundPainter::Instance().GetMode())
	{
		sMacro[iCurrent].Name = "AV_SKYBOX_LOOKUP";
		sMacro[iCurrent].Definition = "1";
		++iCurrent;
	}*/
	sMacro[iCurrent].Name = 0;
	sMacro[iCurrent].Definition = 0;

	//Construct defines from sMacro and compine with mr->m_szMaterialShader string
	std::string extra;

	unsigned int iiCurrent = 0;
	while
	((sMacro[iiCurrent].Name != 0)&&
	(sMacro[iiCurrent].Definition != 0))
	{
		extra.append("#define ");
		extra.append(sMacro[iiCurrent].Name);
		extra.append(" ");
		extra.append(sMacro[iiCurrent].Definition);
		extra.append(";\n");
		iiCurrent++;
	}


	// compile the shader
#if 1
	const char *ShaderName = mr->m_szShaderName.c_str();

	//LOG_PRINT("ShaderName=%s\n", ShaderName);

	ShaderID shd=MeshRendererShadersFactory::GetShader(ShaderName, "main", "main");

	//LOG_PRINT("m_SimpleShader=%s\n", m_SimpleShader);
#elif 0
	const char *m_SimpleShader = MeshRendererShadersFactory::GetShader("SimpleShader");
	mr->m_piDefaultEffect=IRenderer::GetRendererInstance()->addHLSLShader(
		m_SimpleShader,
		"main",
		"main");//D1???
#elif 0
	mr->m_piDefaultEffect=IRenderer::GetRendererInstance()->addHLSLShader(
		g_szMaterialShader.c_str(),
		"MaterialVShader_D1",
		"MaterialPShaderSpecular_D1",0,0,extra.c_str());//D1???
#elif 0
			mr->m_piDefaultEffect=IRenderer::GetRendererInstance()->addHLSLShader(
		g_szDefaultShader.c_str(),
		"DefaultVShader",
		"DefaultPShaderSpecular_D1",0,0,extra.c_str());//D1???
#endif
//mr->m_piMaterialEffect=mr->m_piDefaultEffect;
#if 1
    FormatDesc Fmt[] = {
#if 0
{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
{ 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
{ 0, 24, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
{ 0, 28, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 },
{ 0, 40, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 },
{ 0, 52, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
{ 0, 60, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
{ 0, 68, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
{ 0, 72, D3DDECLTYPE_UBYTE4N, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
#else
	{0, TYPE_VERTEX, FORMAT_FLOAT, 3},
	{0, TYPE_TEXCOORD, FORMAT_FLOAT, 2},
	/*
	{0, TYPE_NORMAL, FORMAT_FLOAT, 3},
	{0, TYPE_TEXCOORD, FORMAT_FLOAT, 3},//???
	{0, TYPE_TEXCOORD, FORMAT_FLOAT, 2},
	{0, TYPE_TEXCOORD, FORMAT_FLOAT, 4},//???
	{0, TYPE_TEXCOORD, FORMAT_FLOAT, 4}//???
	*/
#endif
    };
	//mr->m_DefaultVertexDecl = IRenderer::GetRendererInstance()->addVertexFormat(Fmt, elementsOf(Fmt), mr->m_piDefaultEffect);//???
#endif
	}
	if(0)//-1== mr->m_piMaterialEffect)
	{

		// get the name of the material and use it in the log message
		if(AI_SUCCESS == aiGetMaterialString(pcMat,AI_MATKEY_NAME,&szPath) &&
			'\0' != szPath.data[0])
		{
			std::string sz = "[ERROR] Unable to load material: ";
			sz.append(szPath.data);
			//CLogDisplay::Instance().AddEntry(sz);
		}
		else
		{
			//CLogDisplay::Instance().AddEntry("Unable to load material: UNNAMED");
		}
		return 0;
	} else
	{
		/*
		// use Fixed Function effect when working with shaderless cards
		if( mr->m_sCaps.PixelShaderVersion < D3DPS_VERSION(2,0))
		{
			////LOG_PRINT("mr->m_piDefaultEffect=%d\n",mr->m_piDefaultEffect);
			IRenderer::GetRendererInstance()->SetTechnique( MaterialFX_FFh);
		}*/
	}

//	if( piBuffer) piBuffer->Release();
	LOG_FNLN;
	LOG_PRINT("ShaderName=%d\n",mr->m_szShaderName.c_str());
	ShaderID shd = MeshRendererShadersFactory::GetShader(mr->m_szShaderName.c_str(), "main", "main");
	IRenderer::GetRendererInstance()->setShader(shd);

	// now commit all constants to the shader
	//
	// This is not necessary for shared shader. Shader constants for
	// shared shaders are automatically recommited before the shader
	// is being used for a particular mesh

	if (1.0f != pcMesh->fOpacity)
	{
		//???IRenderer::GetRendererInstance()->SetFloat("TRANSPARENCY",pcMesh->fOpacity);
	}
	if (pcMesh->eShadingMode  != aiShadingMode_Gouraud && !mr->m_sOptions.bNoSpecular)
	{
		IRenderer::GetRendererInstance()->SetFloat("SPECULARITY",pcMesh->fShininess);//???
		IRenderer::GetRendererInstance()->SetFloat("SPECULAR_STRENGTH",pcMesh->fSpecularStrength);
	}

	IRenderer::GetRendererInstance()->SetVector("DIFFUSE_COLOR",&pcMesh->vDiffuseColor);
	//IRenderer::GetRendererInstance()->SetVector("SPECULAR_COLOR",&pcMesh->vSpecularColor);
	IRenderer::GetRendererInstance()->SetVector("AMBIENT_COLOR",&pcMesh->vAmbientColor);
	IRenderer::GetRendererInstance()->SetVector("EMISSIVE_COLOR",&pcMesh->vEmissiveColor);

	if (pcMesh->piDiffuseTexture!=-1)
	{
		IRenderer::GetRendererInstance()->SetTexture("DIFFUSE_SAMPLER",pcMesh->piDiffuseTexture);
	}
	if (pcMesh->piOpacityTexture!=-1)
	{
		IRenderer::GetRendererInstance()->SetTexture("OPACITY_SAMPLER",pcMesh->piOpacityTexture);
	}
	if (pcMesh->piSpecularTexture!=-1)
	{
		IRenderer::GetRendererInstance()->SetTexture("SPECULAR_SAMPLER",pcMesh->piSpecularTexture);
	}
	if (pcMesh->piAmbientTexture!=-1)
	{
		IRenderer::GetRendererInstance()->SetTexture("AMBIENT_SAMPLER",pcMesh->piAmbientTexture);
	}
	if (pcMesh->piEmissiveTexture!=-1)
	{
		IRenderer::GetRendererInstance()->SetTexture("EMISSIVE_SAMPLER",pcMesh->piEmissiveTexture);
	}
	if (pcMesh->piNormalTexture!=-1)
	{
		IRenderer::GetRendererInstance()->SetTexture("NORMAL_SAMPLER",pcMesh->piNormalTexture);
	}
	if (pcMesh->piShininessTexture!=-1)
	{
		IRenderer::GetRendererInstance()->SetTexture("SHININESS_SAMPLER",pcMesh->piShininessTexture);
	}
	if (pcMesh->piLightmapTexture!=-1)
	{
		IRenderer::GetRendererInstance()->SetTexture("LIGHTMAP_SAMPLER",pcMesh->piLightmapTexture);
	}
/*
	if (CBackgroundPainter::TEXTURE_CUBE == CBackgroundPainter::Instance().GetMode()){
		IRenderer::GetRendererInstance()->SetTexture("lw_tex_envmap",CBackgroundPainter::Instance().GetTexture());
	}*/
#endif
	return 1;
}
Beispiel #17
0
void Tile::SetTexture( std::string fileName )
{
	LoadTexture(fileName);
	SetColour(fileName);
}
void CreateHeightFieldMesh (NewtonCollision* collision, Entity* ent)
{
	int width;
	int height;
	dFloat hScale;
	dFloat vScale;
	unsigned short* elevations;
	NewtonCollisionInfoRecord collisionInfo;

	// keep the compiler happy
	memset (&collisionInfo, 0, sizeof (NewtonCollisionInfoRecord));
	NewtonCollisionGetInfo (collision, &collisionInfo);

	// get the info from the collision mesh and create a visual mesh
	width = collisionInfo.m_heightField.m_width;
	height = collisionInfo.m_heightField.m_height;
	elevations = collisionInfo.m_heightField.m_elevation;
	vScale = collisionInfo.m_heightField.m_verticalScale;
	hScale = collisionInfo.m_heightField.m_horizonalScale;

	// allocate space to store vertex data
	ent->m_vertexCount = width * height;
	ent->m_vertex = (dFloat*) malloc (3 * width * height * sizeof (dFloat));
	ent->m_normal = (dFloat*) malloc (3 * width * height * sizeof (dFloat));
	ent->m_uv = (dFloat*) malloc (2 * width * height * sizeof (dFloat));



	// scan the height field and convert every cell into two triangles
	for (int z = 0; z < height; z ++) {
		int z0;
		int z1;
		z0 = ((z - 1) < 0) ? 0 : z - 1;
		z1 = ((z + 1) > (height - 1)) ? height - 1 : z + 1 ;
		for (int x = 0; x < width; x ++) {
			int x0;
			int x1;

			x0 = ((x - 1) < 0) ? 0 : x - 1;
			x1 = ((x + 1) > (width - 1)) ? width - 1 : x + 1 ;

			dVector p0 (hScale * x0, elevations[z * width + x1] * vScale, hScale * z);
			dVector p1 (hScale * x1, elevations[z * width + x0] * vScale, hScale * z);
			dVector x10 (p1 - p0);

			dVector q0 (hScale * x, elevations[z0 * width + x] * vScale, hScale * z0);
			dVector q1 (hScale * x, elevations[z1 * width + x] * vScale, hScale * z1);
			dVector z10 (q1 - q0);

			dVector normal (z10 * x10);
			normal = normal.Scale (dSqrt (1.0f / (normal % normal)));
			dVector point (hScale * x, elevations[z * width + x] * vScale, hScale * z);

			ent->m_vertex[(z * width + x) * 3 + 0] = point.m_x;
			ent->m_vertex[(z * width + x) * 3 + 1] = point.m_y;
			ent->m_vertex[(z * width + x) * 3 + 2] = point.m_z;

			ent->m_normal[(z * width + x) * 3 + 0] = normal.m_x;
			ent->m_normal[(z * width + x) * 3 + 1] = normal.m_y;
			ent->m_normal[(z * width + x) * 3 + 2] = normal.m_z;

			ent->m_uv[(z * width + x) * 2 + 0] = x * TEXTURE_SCALE;
			ent->m_uv[(z * width + x) * 2 + 1] = z * TEXTURE_SCALE;
		}
	}

	
	// since the bitmap sample is 256 x 256, i fix into a single 16 bit index vertex array with
	ent->m_subMeshCount = 1;
	ent->m_subMeshes = (Entity::SubMesh*) malloc (sizeof (Entity::SubMesh));

	// allocate space to the index list
	ent->m_subMeshes[0].m_textureHandle = LoadTexture ("grassAndDirt.tga");
	ent->m_subMeshes[0].m_indexCount = (width - 1) * (height - 1) * 6;
	ent->m_subMeshes[0].m_indexArray = (unsigned short*) malloc (ent->m_subMeshes[0].m_indexCount * sizeof (unsigned short));

	// now following the grid pattern and create and index list
	int index;
	int vertexIndex;

	index = 0;
	vertexIndex = 0;
	for (int z = 0; z < height - 1; z ++) {
		vertexIndex = z * width;
		for (int x = 0; x < width - 1; x ++) {

			ent->m_subMeshes[0].m_indexArray[index + 0] = GLushort (vertexIndex);
			ent->m_subMeshes[0].m_indexArray[index + 1] = GLushort (vertexIndex + width);
			ent->m_subMeshes[0].m_indexArray[index + 2] = GLushort (vertexIndex + 1);
			index += 3;

			ent->m_subMeshes[0].m_indexArray[index + 0] = GLushort (vertexIndex + 1);
			ent->m_subMeshes[0].m_indexArray[index + 1] = GLushort (vertexIndex + width);
			ent->m_subMeshes[0].m_indexArray[index + 2] = GLushort (vertexIndex + width + 1);
			index += 3;
			vertexIndex ++;
		}
	}

	// Optimize the mesh for hardware rendering if possible
	ent->OptimizeMesh();

/*
	dVector boxP0; 
	dVector boxP1; 
	// get the position of the aabb of this geometry
	dMatrix matrix (ent->m_curRotation, ent->m_curPosition);
	NewtonCollisionCalculateAABB (collision, &matrix[0][0], &boxP0.m_x, &boxP1.m_x); 

	// place the origin of the visual mesh at the center of the height field
	matrix.m_posit = (boxP0 + boxP1).Scale (-0.5f);
	matrix.m_posit.m_w = 1.0f;
	ent->m_curPosition = matrix.m_posit;
	ent->m_prevPosition = matrix.m_posit;


	// create the level rigid body
	body = NewtonCreateBody(world, collision);

	// release the collision tree (this way the application does not have to do book keeping of Newton objects
	NewtonReleaseCollision (world, collision);


	// save the pointer to the graphic object with the body.
	NewtonBodySetUserData (body, ent);

	// set the global position of this body
	NewtonBodySetMatrix (body, &matrix[0][0]); 


	// set the destructor for this object
//	NewtonBodySetDestructorCallback (body, Destructor);

	// get the position of the aabb of this geometry
	NewtonCollisionCalculateAABB (collision, &matrix[0][0], &boxP0.m_x, &boxP1.m_x); 

	// add some extra padding the world size
	boxP0.m_x -=  10.0f;
	boxP0.m_y -=  10.0f;
	boxP0.m_z -=  10.0f;
	boxP1.m_x +=  10.0f;
	boxP1.m_y += 400.0f;
	boxP1.m_z +=  10.0f;

	// set the world size
	NewtonSetWorldSize (world, &boxP0.m_x, &boxP1.m_x); 
	return body;
*/
}
/* simple display function for GLUT */
void display(void)
{
        GLfloat mat_red[] = {1.0, 0.0, 0.0, 0.0};
        GLfloat mat_green[] = {0.0, 1.0, 0.0, 0.0};
        GLfloat mat_blue[]  = {0.0, 0.0, 1.0, 0.0};
        GLfloat mat_black[] = {0.0, 0.0, 0.0, 0.0};

        /* light placed at infinity in the direcion <10,10,10>*/
        GLfloat light_position[] = {light1_x, light1_y, light1_z, 0.0}; 

        /* this will be your shadow matrix.  You need to specify what this contains.
         * OpenGL has a funky ordering for rows and columns
         * use this ordering for rows and columns.  The identity matrix with Mr,c = M3,3 = 0;
         */
        m[0]= 1; m[4]= 0; m[8] = -(light1_x/light1_z); m[12]= 0;
        m[1]= 0; m[5]= 1; m[9] = -(light1_y/light1_z); m[13]= 0;
        m[2]= 0; m[6]= 0; m[10]= 0;                    m[14]= 0;
        m[3]= 0; m[7]= 0; m[11]= 0;                    m[15]= 1;

        /* replaces the matrix in the top of the stack with the identity matrix */
        glLoadIdentity(); 

        /* multiplies the current matrix by a tranformation matrix that puts the eyepoint 
         * at <eye_x,eye_y,eye_z>, center of the image at <0,0,0>, 
	 * and up vector of <0,0,1> (z-axis).
         */
        gluLookAt(eye_x,eye_y,eye_z, 0,0,0, 0,0,1); 

        /* move light0 to 'light_position' */
        glLightfv(GL_LIGHT0, GL_POSITION, light_position); 

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        /* draw checkered floor */
        /* enable textures */
        glEnable(GL_TEXTURE_2D);
        /* set texture mode */
        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
        /* set current texture to 'texName' */
        glBindTexture(GL_TEXTURE_2D, texName);

	/* to load texture image */
	LoadTexture();

        /* draw polygon floor */
        glBegin(GL_QUADS);
                /* z=-0.01 so that the floor doesn't overlap your shadows
                 * glTexCoord fixes a point in the texture to the vertex that follows it.
                 */
                glTexCoord2f(0.0, 0.0); glVertex3f(-4.0, -4.0, -0.01); 
                glTexCoord2f(0.0, 1.0); glVertex3f(-4.0,  4.0, -0.01);
                glTexCoord2f(1.0, 1.0); glVertex3f( 4.0,  4.0, -0.01);
                glTexCoord2f(1.0, 0.0); glVertex3f( 4.0, -4.0, -0.01);
        glEnd();
        glFlush();
        /* disable textures so that we can draw other polys w/o the texture */
        glDisable(GL_TEXTURE_2D); 

	/* draw unit cone of radius of 1 and height 1 */
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_blue);

	/* draw all objects with colors */
	draw_scene(0);
	/* draw all objects shadows */
	draw_scene(1);

        glFlush();

}
BouncyBee::BouncyBee(TileMap *tm, SDL_Renderer *renderTarget_) : Enemy(tm, renderTarget_)
{	
	dx = 0;
    dy = 0;

	targX = 860;
	targY = 154;

    maxSpeed = 1.8;
	moveSpeed = maxSpeed;
    maxFallSpeed = 0;
	fallSpeed = maxFallSpeed;

    width = 52;
    height = 40;
    cwidth = 52;
    cheight = 40;

    maxHealth = 1;
    health = maxHealth;
    damage = 1;

    dead = false;
    flinching = false;
	active = false;
	triggerState = false;

	triggerBox = NULL;

	//load sprites
    numAnimations = 2;
    frameNumbers = NULL;
    frameNumbers = new int[numAnimations];
    int tempNums[2] = {1, 2};
    for (int i=0; i<numAnimations; i++)
        frameNumbers[i] = tempNums[i];

    sprite_rects = NULL;
    sprite_rects = new SDL_Rect*[numAnimations];
    for (int i=0; i<numAnimations; i++)
    {
        sprite_rects[i] = NULL;
        sprite_rects[i] = new SDL_Rect[frameNumbers[i]];
        //printf("DEBUG: frameNumbers[%d] = %d\n", i, frameNumbers[i]);
    }

	animationTexture = LoadTexture("./Resources/Sprites/Enemies/GoS_BouncyBeeSprites.bmp", renderTarget);
    if (animationTexture)
        printf("DEBUG: Loaded bouncy bee textures\n");
    for (int i=0; i<numAnimations; i++)
    {
        for (int j=0; j<frameNumbers[i]; j++)
        {
        	sprite_rects[i][j].x = j*width;
            sprite_rects[i][j].y = i*height;
            sprite_rects[i][j].w = width;
            sprite_rects[i][j].h = height;
        }
    }

    currentAction = IDLE;
    animation.setFrames(animationTexture, sprite_rects[currentAction], frameNumbers[currentAction]);
    animation.setDelay(-1);
    width = sprite_rects[currentAction][animation.getFrame()].w;

	bee_sound = new AudioPlayer("./Resources/SFX/BMOGame_BouncyBeeIntro.wav", false);

    right = true;
    facingRight = right;
}
Beispiel #21
0
void World::PlaceBlocks() {
    
    Entity * projectile = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 0.0f, TILEHEIGHT * 6.0, -4.0f, 0.0f);
    projectiles.push_back(projectile);
    Entity * projectile2 = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 0.0f, TILEHEIGHT * 7.0, -4.0f, 0.0f);
    projectiles.push_back(projectile2);
    
    for ( size_t j = 0; j < RAINDROPS; j++ ) {
        Entity * raindrop = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 0.0f, TILEHEIGHT * 4.0, 0.0, -3.33);
        rain.push_back(raindrop);
    }
    
    float randX, randY;
    
    for ( size_t i = 0; i < BLOCKS; i++ ) {
        randX = (rand() % 16 - 8) / 10.0;
        randY = (rand() % 1600) / 10.0;
        Entity * cloud = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 0.0, TILEHEIGHT * 2, randX, randY);
        blocks.push_back(cloud);
    }
    
    Entity * minus1 = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 3.0f, TILEHEIGHT * 0.0, 0.05, 0.0);
    statics.push_back(minus1);
    Entity * plus1 = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 3.0f, TILEHEIGHT * 1.0, 0.05, 0.0);
    statics.push_back(plus1);
    
    // bubbles
    Entity * outofbounds = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 3.0f, TILEHEIGHT * 2.0, 0.05, 0.0);
    statics.push_back(outofbounds);
    Entity * outofbounds2 = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 3.0f, TILEHEIGHT * 2.0, 0.05, 0.0);
    statics.push_back(outofbounds2);
    
    // miniatures
    Entity * outofbounds1 = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 1.0f, TILEHEIGHT * 1.0, 0.05, 0.0);
    statics.push_back(outofbounds1);
    Entity * outofbounds3 = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 1.0f, TILEHEIGHT * 1.0, 0.05, 0.0);
    statics.push_back(outofbounds3);
    
    Entity * panelRight = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 10.0f, TILEHEIGHT * 0.0, 0.93, 0.0);
    panelRight->height = TILEHEIGHT * 7.0;
    statics.push_back(panelRight);
    
    Entity * panelLeft = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 11.0f, TILEHEIGHT * 0.0, -0.93, 0.0);
    panelLeft->height = TILEHEIGHT * 7.0;
    statics.push_back(panelLeft);
    
    // Menu items
    
    Entity * players = new Entity(LoadTexture(menuSheet), TILEWIDTH * 0.0f, TILEHEIGHT * 0.2, 0.0f, 0.0f);
    players->width = TILEWIDTH * 10.0;
    players->height = TILEHEIGHT * 8.0;
    menuItems.push_back(players);
    Entity * s = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 3.0f, TILEHEIGHT * 3.0, 0.0, 0.0);
    menuItems.push_back(s);
    Entity * s1 = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 3.0f, TILEHEIGHT * 4.0, 0.0, 0.0);
    menuItems.push_back(s1);
    Entity * decor = new Entity(LoadTexture(menuSheet), TILEWIDTH * 10.5f, TILEHEIGHT * 0.0, 0.94, 0.0);
    decor->height = TILEHEIGHT * 10.0f;
    decor->width = TILEWIDTH * 3.0f;
    menuItems.push_back(decor);
    
    Entity * v = new Entity(LoadTexture(spriteSheet), TILEWIDTH * 10.0f, TILEHEIGHT * 7.0, 0.0, 0.4);
    v->width = TILEWIDTH * 3.5f;
    v->height = TILEHEIGHT * 2.0f;
    menuItems.push_back(v);
    
    // Buttons
    for ( int k = 0; k < 6; k++ ) {
        Entity * b = new Entity(LoadTexture(spriteSheet), TILEWIDTH * (4.0f + k), TILEHEIGHT * 6.0, -0.95f, 0.0f);
        buttons.push_back(b);
        
    }
    
    for ( int l = 0; l < 6; l++ ) {
        Entity * b2 = new Entity(LoadTexture(spriteSheet), TILEWIDTH * (4.0f + l), TILEHEIGHT * 8.0, 0.95, 0.0f);
        buttons.push_back(b2);
        
    }

}
Beispiel #22
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("Simon Project 1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL); // SDL Window, title, position,position,width,height, type of graphics?
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);

	glClearColor(0.5, 0.5, 0.0, .9);//Green-color

	//Setup
	glViewport(0, 0, 800, 600);
	glMatrixMode(GL_PROJECTION);
	glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);
	glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0);

	//LoadTextures
	GLuint paddleID = LoadTexture("pngs/paddle.png");
	GLuint ballID = LoadTexture("pngs/ball.png");
	GLuint leftwinID = LoadTexture24("pngs/leftwin.png");
	GLuint rightwinID = LoadTexture24("pngs/rightwin.png");
	//Init Entities
	initBall(ballID);
	initPaddleLeft(paddleID);
	initPaddleRight(paddleID);
	initRightwin(rightwinID);
	initLeftwin(leftwinID);

	//Time
	float lastFrameTicks = 0.0;
	
	SDL_Event event;
	bool done = false;
	while (!done) {
		glClear(GL_COLOR_BUFFER_BIT);
		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;

		//Read Input and Update World
		while (SDL_PollEvent(&event)) { // a lot of events could cue up, no?, could also get all keyboard states and check for those. I think I like that better. - specially for pong
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		const Uint8 *keys = SDL_GetKeyboardState(NULL);
		if (keys[SDL_SCANCODE_UP]) {
			paddleright.y += elapsed*paddleright.velocity_y;
			if (paddleright.y > (1 - .2)){ paddleright.y = 1 - .2; }
		}
		else if (keys[SDL_SCANCODE_DOWN]) {
			paddleright.y -= elapsed*paddleright.velocity_y;
			if (paddleright.y < (-1 + .2)){ paddleright.y = -1 + .2; }
		}
		if (keys[SDL_SCANCODE_W]) {
			paddleleft.y += elapsed*paddleleft.velocity_y;
			if (paddleleft.y >(1 - .2)){ paddleleft.y = 1 - .2; }
		}
		else if (keys[SDL_SCANCODE_S]) {
			paddleleft.y -= elapsed*paddleleft.velocity_y;
			if (paddleleft.y < (-1 + .2)){ paddleleft.y = -1 + .2; }
		}

		updateBall(elapsed);
		isWin();

		//Render World
		ball.Draw();
		paddleleft.Draw();
		paddleright.Draw();
		if (rightwin)
		{
			endGame();
			rightwinE.Draw();
		}
		if (leftwin)
		{
			endGame();
			leftwinE.Draw();
		}

		SDL_GL_SwapWindow(displayWindow);//Swaps old modelview with new one?
	}

	SDL_Quit();
	return 0;
}
Beispiel #23
0
void Element::InitializeElements()
{
	_texture = LoadTexture("../../../Assets/Gui/box.png");
}
Beispiel #24
0
Texture::Texture(const char *filename)
{
	m_textureID = LoadTexture(filename, &m_width, &m_height);
}
Beispiel #25
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("Shunman Tse Assignment 1 - My Scene", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);

	bool done = false;

	SDL_Event event;

	// Basic setup for the rendering pipeline
	glViewport(0, 0, 800, 600);
	glMatrixMode(GL_PROJECTION);
	glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);

	// Load Textures
	GLuint spinningLollipop = LoadTexture("lollipopRed.png");
	GLuint asteroid = LoadTexture("meteorBig.png");
	GLuint player = LoadTexture("player.png");
	GLuint enemy = LoadTexture("enemyShip.png");

	// Set up timing variables
	float lastFrameTicks = 0.0f;
	float starRotation = 0.0f;
	float asteroidRotation = 0.0f;
	float asteroid2Rotation = 45.0f;

	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}

		// Keeping time in the while loop
		float ticks = (float)SDL_GetTicks()/ 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;

		// Clear screen
		glClearColor(0.5f, 0.4f, 0.7f, 1.0f); // Purple Screen
		//glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // White Screen
		glClear(GL_COLOR_BUFFER_BIT);

		//-- Natural Elements 
		// Spinning Candy Star (top left)
		starRotation += (elapsed * 20.0f);
		DrawSprite(spinningLollipop, -1.1, 0.8, starRotation, 0.3);

		// Asteroids
		asteroidRotation += (elapsed * 30.0f);
		DrawSprite(asteroid, 0.0, -0.4, asteroidRotation, 0.4); 

		asteroid2Rotation += (elapsed * 35.0f);
		DrawSprite(asteroid, 0.6, -0.2, asteroid2Rotation, 0.3); 
		DrawSprite(asteroid, -0.6, -0.2, asteroid2Rotation, 0.3);
		DrawSprite(asteroid, 1.2, -0.2, 0, 0.5);
		DrawSprite(asteroid, -1.2, -0.2, 180, 0.5);
			
		//-- Player Forces
		// 2 Player Ships (bottom)
		DrawSprite(player, -0.5, -0.8, 0, 0.2);
		DrawSprite(player, 0.5, -0.8, 0, 0.2);

		//-- Enemy Forces
		// 5 Enemy Ships (top)
		DrawSprite(enemy, 0.0, 0.0, 0, 0.2);
		DrawSprite(enemy, 0.2, 0.2, 0, 0.2);
		DrawSprite(enemy, -0.2, 0.2, 0, 0.2);
		DrawSprite(enemy, 0.6, 0.4, 0, 0.2);
		DrawSprite(enemy, -0.6, 0.4, 0, 0.2);

		// Rainbow Capital Ship (triangle with vertex colors)
		// Resize the ship accordingly
		glLoadIdentity();
		glScalef(0.1, 0.1, 0.1);
		glTranslatef(0.0, 6.5, 0.0);

		// Array of vertex position data
		GLfloat capitalShip [] = { 0.0, 3.0, 1.0, 3.0, 3.0, 2.0, 2.0, 1.0, 1.0, -2.0, 0.0, -3.0, -1.0, -2.0, -2.0, 1.0, -3.0, 2.0, -1.0, 3.0 }; // 10 points 
		glVertexPointer(2, GL_FLOAT, 0, capitalShip);
		glEnableClientState(GL_VERTEX_ARRAY);

		// Array of Vertex Color Data
		GLfloat capitalShipColors[] = { 
			1.0, 0.0, 0.0,
			1.0, 0.0, 0.0,
			0.0, 0.0, 1.0,
			0.5, 0.5, 0.5,
			0.0, 1.0, 0.0,
			1.0, 1.0, 1.0,
			0.0, 1.0, 0.0,
			0.5, 0.5, 0.5,
			0.0, 0.0, 1.0,
			1.0, 0.0, 0.0 };
		glColorPointer(3, GL_FLOAT, 0, capitalShipColors);
		glEnableClientState(GL_COLOR_ARRAY);
		glDrawArrays(GL_POLYGON, 0, 10);
		glDisableClientState(GL_COLOR_ARRAY);
		
		SDL_GL_SwapWindow(displayWindow);
	}

	SDL_Quit();
	return 0;
}
Beispiel #26
0
int main(int argc, char *argv[])
{
	// Initializing and loading variables
	SDL_Window *window = nullptr;
	SDL_Renderer *renderTarget = nullptr;
	int currentTime = 0; 
	int prevTime = 0; 
	float delta = 0.0f;
	const Uint8 *keyState;
	SDL_Rect camerRect = { 0, 0, 640, 480 };
	int levelWidth, levelHeight;

	SDL_Init(SDL_INIT_VIDEO);
	
	if(IMG_Init(imgFlags) != imgFlags)
		std::cout << "Error: " << IMG_GetError() << std::endl;

	int data = 10;
	window = SDL_CreateWindow("SDL CodingMadeEasy Series", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
	renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

	Player player1(renderTarget, "image.png", 0, 0, 3, 4);
	Player player2(renderTarget, "image.png", 500, 300, 3, 4);

	SDL_Texture *texture = LoadTexture("rect.png", renderTarget);
	SDL_QueryTexture(texture, NULL, NULL, &levelWidth, &levelHeight);

	bool isRunning = true; 
	SDL_Event ev;

	while(isRunning)
	{
		prevTime = currentTime; 
		currentTime = SDL_GetTicks(); 
		delta = (currentTime - prevTime) / 1000.0f;
		while(SDL_PollEvent(&ev) != 0)
		{
			// Getting the events
			if(ev.type == SDL_QUIT)
				isRunning = false;
		}

		keyState = SDL_GetKeyboardState(NULL);

		player1.Update(delta, keyState); 
		player2.Update(delta, keyState);


		camerRect.x = player1.GetOriginX() - 320; 
		camerRect.y = player1.GetOriginY() - 240;

		if(camerRect.x < 0)
			camerRect.x = 0; 
		if(camerRect.y < 0)
			camerRect.y = 0;

		if(camerRect.x + camerRect.w >= levelWidth)
			camerRect.x = levelWidth - 640; 
		if(camerRect.y + camerRect.h >= levelHeight)
			camerRect.y = levelHeight - 480;


		player1.IntersectsWith(player2);

		SDL_RenderClear(renderTarget);
		SDL_RenderCopy(renderTarget, texture, &camerRect, NULL);
		player1.Draw(renderTarget, camerRect); 
		player2.Draw(renderTarget, camerRect);
		SDL_RenderPresent(renderTarget);
	}

	SDL_DestroyWindow(window);
	SDL_DestroyRenderer(renderTarget);
	SDL_DestroyTexture(texture);

	texture = nullptr;

	window = nullptr;
	renderTarget = nullptr;

	IMG_Quit();
	SDL_Quit();

	return 0;
}
void ResourceManager::LoadResource()
{
	LoadTexture();
	LoadSound();
	m_bIsReady = true;
}
Beispiel #28
0
Texture3D::Texture3D(int width, int height, int depth, const char *data, Format format, int stride /*= -1*/, Type type) :
	_id(0)
{
	SetGLType(type);
	LoadTexture(width, height, depth, data, format, stride);
}
Beispiel #29
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	#ifdef _WINDOWS
		glewInit();
	#endif

	SDL_Event event;
	bool done = false;

	ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	GLuint blank = LoadTexture("blank.png");

	Matrix projectionMatrix;
	Matrix modelMatrix;
	Matrix viewMatrix;
	projectionMatrix.setOrthoProjection(-1.7777f, 1.7777f, -1.0f, 1.0f, -1.0f, 1.0f);
	float portWidth = 640;
	float portHeight = 320;

	float lastFrameTicks = 0.0f;
	float ballPosx = .0f;
	float ballPosy = 0.0f;
	float ballAngle = 180.0f;
	float ballSpeed = 2.0f;
	float paddlePos1 = 0.0f;
	float paddlePos2 = 0.0f;
	float paddleSpeed = 0.0015f;
	float server = 0.0f;


	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		const Uint8 *keys = SDL_GetKeyboardState(NULL); 
//player1 input
		if (keys[SDL_SCANCODE_W]){
			paddlePos1 += paddleSpeed;
			if (paddlePos1 + 0.2 >= 1)
				paddlePos1 = 1 - 0.2;
		}
		else if (keys[SDL_SCANCODE_S]){
			paddlePos1 += -1 * paddleSpeed;
			if (paddlePos1 - 0.2 <= -1)
			paddlePos1 = -1 + 0.2;
		}
		
//player2 input		
		if (keys[SDL_SCANCODE_O]){
			paddlePos2 += paddleSpeed;
			if (paddlePos2 + 0.2 >= 1)
				paddlePos2 = 1 - 0.2;
		}
		else if (keys[SDL_SCANCODE_L]){
			paddlePos2 += -1 * paddleSpeed;
			if (paddlePos2 - 0.2 <= -1)
				paddlePos2 = -1 + 0.2;
		}

//update
		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;

		if (abs(ballAngle) - 90 <= 20 && abs(ballAngle) -90 >= -20)
			ballSpeed = 4;
		else
			ballSpeed = 2;

		float dist = elapsed*ballSpeed;
		ballPosx += cos(ballAngle * PI / 180)*dist;
		ballPosy += sin(ballAngle * PI / 180)*dist;		



//collison test
		if (ballPosy >= 1){
			ballAngle = -1 * ballAngle;
			ballPosy = 1;
		}
		else if (ballPosy <= -1){
			ballAngle = -1 * ballAngle;
			ballPosy = -1;
		}

		if (ballPosx <= -1.5 && ballPosx >= -1.6 && ballPosy <= paddlePos1 + 0.2 && ballPosy >= paddlePos1 - 0.2){
			if (ballPosy > paddlePos1 + 0.1 || ballPosy < paddlePos1 - 0.1){
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle + 20;
				else
					ballAngle = -180 - ballAngle - 20;
			}
			else if (ballPosy > paddlePos1 + 0.175 || ballPosy < paddlePos1 - 0.175){
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle + 15;
				else
					ballAngle = -180 - ballAngle - 15;
			}
			else {
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle;
				else
					ballAngle = -180 - ballAngle;
			}
			ballPosx = -1.5;
		}
		else if (ballPosx >= 1.5 && ballPosx <= 1.6 && ballPosy <= paddlePos2 + 0.2 && ballPosy >= paddlePos2 - 0.2){
			if (ballPosy > paddlePos2 + 0.1 || ballPosy < paddlePos2 - 0.1){
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle - 20;
				else
					ballAngle = -180 - ballAngle + 20;
			}
			else if (ballPosy > paddlePos2 + 0.175 || ballPosy < paddlePos2 - 0.175){
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle - 15;
				else
					ballAngle = -180 - ballAngle + 15;
			}
			else {
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle;
				else
					ballAngle = -180 - ballAngle;
			}
			ballPosx = 1.5;
		}

//victory condition test
		if (ballPosx <= -1.8){
			ballPosx = 0;
			ballPosy = 0;
			ballAngle = 0;
			paddlePos1 = 0;
			paddlePos2 = 0;
			server = 1;
		}
		else if (ballPosx >= 1.8){
			ballPosx = 0;
			ballPosy = 0;
			ballAngle = 180;
			paddlePos1 = 0;
			paddlePos2 = 0;
			server = -1;
		}


//render
		glViewport(0, 0, portWidth, portHeight);
		float verticesBall[] = { -0.03f, -0.03f, 
								0.03f, 0.03f, 
								-0.03f, 0.03f, 
								0.03f, 0.03f, 
								-0.03f, -0.03f, 
								0.03f, -0.03f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesBall);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoordsBall[] = { 0.0, 1.0f, 
								1.0f, 0.0f, 
								0.0f, 0.0f, 
								1.0, 0.0, 
								0.0, 1.0, 
								1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordsBall);
		glEnableVertexAttribArray(program.texCoordAttribute);

		glBindTexture(GL_TEXTURE_2D, blank);

		modelMatrix.identity();
		modelMatrix.Translate(ballPosx,ballPosy,0.0);
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		float verticesPad1[] = { -0.1f, -0.2f,
			0.0f, 0.2f,
			-0.1f, 0.2f,
			0.0f, 0.2f,
			-0.1f, -0.2f,
			0.0f, -0.2f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesPad1);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoordsPad1[] = { 0.0, 1.0f,
			1.0f, 0.0f,
			0.0f, 0.0f,
			1.0, 0.0,
			0.0, 1.0,
			1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordsPad1);
		glEnableVertexAttribArray(program.texCoordAttribute);


		modelMatrix.identity();
		modelMatrix.Translate(-1.5, paddlePos1, 0.0);
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		float verticesPad2[] = { 0.1f, -0.2f,
			0.0f, 0.2f,
			0.1f, 0.2f,
			0.0f, 0.2f,
			0.1f, -0.2f,
			0.0f, -0.2f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesPad2);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoordsPad2[] = { 0.0, 1.0f,
			1.0f, 0.0f,
			0.0f, 0.0f,
			1.0, 0.0,
			0.0, 1.0,
			1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordsPad2);
		glEnableVertexAttribArray(program.texCoordAttribute);
		

		modelMatrix.identity();
		modelMatrix.Translate(1.5, paddlePos2, 0.0);
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		if (server){
			float verticesfl[] = { -0.025f, 0.0f,
				0.025f, 0.1f,
				-0.025f, 0.1f,
				0.025f, 0.1f,
				-0.025f, 0.0f,
				0.0f, 0.0f };
			glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesfl);
			glEnableVertexAttribArray(program.positionAttribute);

			float texCoordsfl[] = { 0.0, 1.0f,
				1.0f, 0.0f,
				0.0f, 0.0f,
				1.0, 0.0,
				0.0, 1.0,
				1.0, 1.0 };
			glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordsfl);
			glEnableVertexAttribArray(program.texCoordAttribute);


			modelMatrix.identity();
			modelMatrix.Translate(server, -1, 0.0);
			program.setModelMatrix(modelMatrix);
			program.setProjectionMatrix(projectionMatrix);
			program.setViewMatrix(viewMatrix);

			glDrawArrays(GL_TRIANGLES, 0, 6);
			glDisableVertexAttribArray(program.positionAttribute);
			glDisableVertexAttribArray(program.texCoordAttribute);
		}

		SDL_GL_SwapWindow(displayWindow);
		glClear(GL_COLOR_BUFFER_BIT);

	}


	/*Game app;
	while (!app.UpdateAndRender()) {}*/

	//SDL_Quit();
	return 0;
}
Beispiel #30
0
void GameWorld::initCPS()
{
	GLuint texId = 0;
	if (!LoadTexture(CIRCLE_PARTICLE_TEX_FILE, texId, GL_BGRA, GL_RGBA)) {
		printf("load texture fail:\s\n", CIRCLE_PARTICLE_TEX_FILE);
	}