Conditional operator in HLSL's pass - if-statement

According to
http://msdn.microsoft.com/en-us/library/windows/desktop/bb509610(v=vs.85).aspx
HLSL supports conditional operator (since version 2.0? I am using 4_0)
I need to set blending state before each Draw call. In FX file I'm doing this:
BlendState BlendNone
{
AlphaToCoverageEnable = FALSE;
BlendEnable[0] = FALSE;
};
BlendState BlendSrcAlphaOne
{
BlendEnable[0] = TRUE;
SrcBlend = SRC_ALPHA;
DestBlend = INV_SRC_ALPHA;
BlendOp = ADD;
RenderTargetWriteMask[0] = 0x0F;
};
BlendState BlendSrcAlphaOneMinusSrcAlpha
{
BlendEnable[0] = TRUE;
SrcBlend = SRC_ALPHA;
DestBlend = ONE;
BlendOp = ADD;
RenderTargetWriteMask[0] = 0x0F;
};
int g_Blend;
technique10 Render
{
pass P0
{
SetVertexShader( CompileShader( vs_4_0, VS() ) );
SetGeometryShader( CompileShader( gs_4_0, GS() ) );
SetPixelShader( CompileShader( ps_4_0, PS() ) );
SetRasterizerState(rsCullNone);
SetDepthStencilState( EnableDepth, 0 );
if (g_Blend == 0)
{
SetBlendState( BlendNone, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
}
else if (g_Blend == 1)
{
SetBlendState( BlendSrcAlphaOne, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
}
else if (g_Blend == 2)
{
SetBlendState( BlendSrcAlphaOneMinusSrcAlpha, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
}
}
}
This does not compile with error:
error X3000: syntax error: unexpected token 'if'
If I move the whole block into a separate function like:
void setBlend()
{
if (g_Blend == 0)
{
SetBlendState( BlendNone, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
}
else if (g_Blend == 1)
{
SetBlendState( BlendSrcAlphaOne, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
}
else if (g_Blend == 2)
{
SetBlendState( BlendSrcAlphaOneMinusSrcAlpha, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
}
}
technique10 Render
{
pass P0
{
SetVertexShader( CompileShader( vs_4_0, VS() ) );
SetGeometryShader( CompileShader( gs_4_0, GS() ) );
SetPixelShader( CompileShader( ps_4_0, PS() ) );
SetRasterizerState(rsCullNone);
SetDepthStencilState( EnableDepth, 0 );
setBlend();
}
}
it doesn't compile with error:
error X3000: this FX API is not available in this part your program (SetBlendState)
So, is if supported in HLSL?

Ok, after lots of attempts and reading
http://msdn.microsoft.com/en-us/library/windows/desktop/bb205052(v=vs.85).aspx#Blend
This compiles:
BlendState blendStates[3]
{
{
AlphaToCoverageEnable = FALSE;
BlendEnable[0] = FALSE;
},
{
BlendEnable[0] = TRUE;
SrcBlend = SRC_ALPHA;
DestBlend = INV_SRC_ALPHA;
BlendOp = ADD;
RenderTargetWriteMask[0] = 0x0F;
},
{
BlendEnable[0] = TRUE;
SrcBlend = SRC_ALPHA;
DestBlend = ONE;
BlendOp = ADD;
RenderTargetWriteMask[0] = 0x0F;
}
};
int g_Blend;
technique10 Render
{
pass P0
{
SetVertexShader( CompileShader( vs_4_0, VS() ) );
SetGeometryShader( CompileShader( gs_4_0, GS() ) );
SetPixelShader( CompileShader( ps_4_0, PS() ) );
SetRasterizerState(rsCullNone);
SetDepthStencilState( EnableDepth, 0 );
SetBlendState( blendStates[g_Blend], float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
}
}
SetBlendState is not strictly a function call and conditional operators are not allowed inside the pass {}. However it's allowed to pass array of state objects with index instead of just state objects.

Related

GIF dramatically lowers FPS

Today I finally figured out what I needed to do to animate my GIF but now that I have it animated the FPS on my program lowered dramatically. I have my GIF in a serperate function so it doesn't have to reload every texture whenever I try to update the frames of the GIF. I also plan on loading more GIFs if there is a way to fix my FPS drop issue so I need a way to reduce lag on all of them. Is there any easy way to fix this?
My code:
LUtil.cpp:
#include "LUtil.h"
#include <IL/il.h>
#include <IL/ilu.h>
#include "LSpriteSheet.h"
int add = 0;
int zoom = 0;
double leftzoom = -SCREEN_WIDTH;
double topzoom = -SCREEN_HEIGHT;
double rightzoom = SCREEN_WIDTH;
double bottomzoom = SCREEN_HEIGHT;
float sy = 0.f;
int scroll = 0;
GLfloat gCameraX = 0.f, gCameraY = 0.f, gCameraZ = 0.f;
//Sprite texture
LSpriteSheet gArrowSprites;
LSpriteSheet gSamusSprites;
LSpriteSheet jSamusSprites;
bool initGL()
{
//Initialize GLEW
GLenum glewError = glewInit();
if( glewError != GLEW_OK )
{
printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
return false;
}
//Make sure OpenGL 2.1 is supported
if( !GLEW_VERSION_2_1 )
{
printf( "OpenGL 2.1 not supported!\n" );
return false;
}
//Set the viewport
glViewport( 0.f, -0.f, SCREEN_WIDTH, SCREEN_HEIGHT );
//Initialize Projection Matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( leftzoom, rightzoom, bottomzoom, topzoom, 1.0, -1.0 );
//Initialize Modelview Matrix
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPushMatrix();
//Initialize clear color
glClearColor( 0.f, 0.f, 0.f, 1.f );
//Enable texturing
glEnable( GL_TEXTURE_2D );
glEnable( GL_BLEND );
glDisable( GL_DEPTH_TEST );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
//Check for error
GLenum error = glGetError();
if( error != GL_NO_ERROR )
{
printf( "Error initializing OpenGL! %s\n", gluErrorString(error));
return false;
}
//Initialize DevIL
ilInit();
ilClearColour( 255, 255, 255, 000 );
//Check for error
ILenum ilError = ilGetError();
if( ilError != IL_NO_ERROR )
{
printf( "Error initializing DevIL! %s\n", iluErrorString(ilError) );
return false;
}
return true;
}
LFRect clip;
bool loadMedia()
{
//Load texture
if( !gArrowSprites.loadTextureFromFile( "Textures/SamusM.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
clip = { 0.f, 0.f, 330.f, 355.f };
//Top left
clip.x = 0.f;
clip.y = 0.f;
gArrowSprites.addClipSprite( clip );
//Top right
clip = {0.f, 0.f, 310.f, 480.f};
clip.x = 331.f;
clip.y = 0.f;
gArrowSprites.addClipSprite( clip );
clip = {0.f, 0.f, 330.f, 125.f};
//Bottom left
clip.x = 0.f;
clip.y = 355.f;
gArrowSprites.addClipSprite( clip );
clip = { 0.f, 0.f, 330.f, 355.f };
//Top left
clip.x = 0.f;
clip.y = 480.f;
gArrowSprites.addClipSprite( clip );
//Top right
clip = {0.f, 0.f, 310.f, 480.f};
clip.x = 331.f;
clip.y = 480.f;
gArrowSprites.addClipSprite( clip );
clip = {0.f, 0.f, 330.f, 125.f};
//Bottom left
clip.x = 0.f;
clip.y = 835.f;
gArrowSprites.addClipSprite( clip );
//Generate VBO
if( !gArrowSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
if( !jSamusSprites.loadTextureFromFile( "Textures/SamusAran.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
clip = { 0.f, 0.f, 375.f, 562.f };
//Top left
clip.x = 0.f;
clip.y = 0.f;
jSamusSprites.addClipSprite( clip );
if( !jSamusSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
return true;
}
bool textureLoaded = false;
bool loadGif(){
if(textureLoaded == false){
if( !gSamusSprites.loadTextureFromFile( "Textures/SamusG.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
textureLoaded = true;
}
sy += 214.f;
if(sy == 8988.f){
sy = 0.f;
}
clip = {0.f, 0.f, 213.f, 214.f};
clip.x = 0.f;
clip.y = sy;
gSamusSprites.addClipSprite( clip );
if( !gSamusSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
return true;
}
void update()
{
}
void render()
{
//Clear color buffer
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPushMatrix();
if(add == 0){
if(zoom < 100){
double const f_zoom = 1.0 - 0.01 * zoom;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(leftzoom * f_zoom, rightzoom * f_zoom, bottomzoom * f_zoom, topzoom * f_zoom, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
if(zoom < -102){
double const f_zoom = 1.0 + 0.01 * zoom;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(leftzoom * f_zoom, rightzoom * f_zoom, bottomzoom * f_zoom, topzoom * f_zoom, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
glTranslatef( -1080.f, -782.f, 0.f );
gArrowSprites.renderSprite( 0 );
//Render top right arrow
glTranslatef( +1080.f, +782.f, 0.f );
glTranslatef( 1085.f, -120.f, 0.f );
gArrowSprites.renderSprite( 1 );
//Render bottom left arrow
glTranslatef( -1085.f, +120.f, 0.f );
glTranslatef( 0.f, 885.f ,0.f );
gArrowSprites.renderSprite( 2 );
glTranslatef(0.f, -885.f, 0.f);
jSamusSprites.renderSprite( 0 );
glTranslatef( -620.f, -855.f, 0.f );
glTranslatef( 620.f, 0.f , 0.f );
gSamusSprites.renderSprite( 0 );
}
if(add == 1){
if(zoom < 100){
double const f_zoom = 1.0 - 0.01 * zoom;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(leftzoom * f_zoom, rightzoom * f_zoom, bottomzoom * f_zoom, topzoom * f_zoom, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
if(zoom < -102){
double const f_zoom = 1.0 + 0.01 * zoom;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(leftzoom * f_zoom, rightzoom * f_zoom, bottomzoom * f_zoom, topzoom * f_zoom, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
glTranslatef( -1080.f, -782.f, 0.f );
gArrowSprites.renderSprite( 3 );
glTranslatef( +1080.f, +782.f, 0.f );
glTranslatef( 1085.f, -120.f, 0.f );
gArrowSprites.renderSprite( 4 );
glTranslatef( -1085.f, +120.f, 0.f );
glTranslatef( 0.f, 885.f ,0.f );
gArrowSprites.renderSprite( 5 );
glTranslatef(0.f, -885.f, 0.f);
jSamusSprites.renderSprite( 0 );
glTranslatef( -620.f, -855.f, 0.f );
glTranslatef( 620.f, 0.f , 0.f );
gSamusSprites.renderSprite( 0 );
}
glLoadIdentity();
glutSwapBuffers();
}
void handleKeys( unsigned char key, int x, int y )
{
//If the user presses q
if( key == 'q' && add == 0 )
{
add++;
}
else if( key == 'q' && add == 1)
{
add--;
}
//Update the sprite rectangles so the texture change takes effect
if( key == 27 ) {
exit(0);
}
if(key == 'a') {
gCameraX += 8.f;
}
else if (key == 'd') {
gCameraX -= 8.f;
}
else if (key == 'w') {
gCameraY += 8.f;
}
else if (key == 's') {
gCameraY -= 8.f;
}
else if (key == '+' && zoom != 99) {
zoom += 1;
}
else if (key == '-' && zoom != -101) {
zoom -= 1;
}
//Take saved matrix off the stack and reset it
glMatrixMode( GL_MODELVIEW );
glPopMatrix();
glLoadIdentity();
//Move camera to position
glTranslatef( gCameraX, gCameraY, gCameraZ );
//Save default matrix again with camera translation
glPushMatrix();
}
Main.cpp:
#include "LUtil.h"
void runMainLoop( int val );
void runGifLoop( int val2 );
int main( int argc, char* args[] )
{
glutInit( &argc, args );
glutInitContextVersion( 2, 1 );
glutInitDisplayMode( GLUT_DOUBLE );
glutInitWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );
glutCreateWindow( "Samus" );
if( !initGL() )
{
printf( "Unable to initialize graphics library!\n" );
return 1;
}
if( !loadMedia() )
{
printf( "Unable to load media!\n" );
return 2;
}
glutKeyboardFunc( handleKeys );
glutDisplayFunc( render );
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, 0 );
glutTimerFunc( 1000 / SCREEN_FPS, runGifLoop, 0 );
glutMainLoop();
return 0;
}
void runMainLoop( int val )
{
update();
render();
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, val );
}
void runGifLoop( int val2 )
{
loadGif();
glutTimerFunc( 1000 / SCREEN_FPS, runGifLoop, val2 );
}

How to animate my GIF tilesheet (OpenGL, DevIL, C++)

I'm trying to animate a gif in my window by making it scroll to each frame on my tilesheet but it currently stays on only one frame. I assume it's because I'm not limiting the fps on the gif but I have no clue how to do that. Anyone?
#max66 I'm trying to obtain an animation by doing this. I'm trying to make it go down the y axis on the texture(which is a sprite tile sheet) which works without the if statement so far but it freezes on the last frame.
My (newish) code:
#include "LUtil.h"
#include <IL/il.h>
#include <IL/ilu.h>
#include "LSpriteSheet.h"
int add = 0;
int zoom = 0;
int factor = 0;
int factor2 = 0;
float y = 0.f;
int scroll = 0;
GLfloat gCameraX = 0.f, gCameraY = 0.f, gCameraZ = 0.f;
//Sprite texture
LSpriteSheet gArrowSprites;
LSpriteSheet gSamusSprites;
bool initGL()
{
//Initialize GLEW
GLenum glewError = glewInit();
if( glewError != GLEW_OK )
{
printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
return false;
}
//Make sure OpenGL 2.1 is supported
if( !GLEW_VERSION_2_1 )
{
printf( "OpenGL 2.1 not supported!\n" );
return false;
}
//Set the viewport
glViewport( 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT );
//Initialize Projection Matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 5.0, -5.0 );
//Initialize Modelview Matrix
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPushMatrix();
//Initialize clear color
glClearColor( 0.f, 0.f, 0.f, 1.f );
//Enable texturing
glEnable( GL_TEXTURE_2D );
glEnable( GL_BLEND );
glDisable( GL_DEPTH_TEST );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
//Check for error
GLenum error = glGetError();
if( error != GL_NO_ERROR )
{
printf( "Error initializing OpenGL! %s\n", gluErrorString(error));
return false;
}
//Initialize DevIL
ilInit();
ilClearColour( 255, 255, 255, 000 );
//Check for error
ILenum ilError = ilGetError();
if( ilError != IL_NO_ERROR )
{
printf( "Error initializing DevIL! %s\n", iluErrorString(ilError) );
return false;
}
return true;
}
bool loadMedia()
{
//Load texture
if( !gArrowSprites.loadTextureFromFile( "SamusM.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
LFRect clip = { 0.f, 0.f, 330.f, 355.f };
//Top left
clip.x = 0.f;
clip.y = 0.f;
gArrowSprites.addClipSprite( clip );
//Top right
clip = {0.f, 0.f, 310.f, 480.f};
clip.x = 331.f;
clip.y = 0.f;
gArrowSprites.addClipSprite( clip );
clip = {0.f, 0.f, 330.f, 125.f};
//Bottom left
clip.x = 0.f;
clip.y = 355.f;
gArrowSprites.addClipSprite( clip );
clip = { 0.f, 0.f, 330.f, 355.f };
//Top left
clip.x = 0.f;
clip.y = 480.f;
gArrowSprites.addClipSprite( clip );
//Top right
clip = {0.f, 0.f, 310.f, 480.f};
clip.x = 331.f;
clip.y = 480.f;
gArrowSprites.addClipSprite( clip );
clip = {0.f, 0.f, 330.f, 125.f};
//Bottom left
clip.x = 0.f;
clip.y = 835.f;
gArrowSprites.addClipSprite( clip );
//Generate VBO
if( !gArrowSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
if( !gSamusSprites.loadTextureFromFile( "SamusG.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
while(scroll != 40){
y += 214.f;
scroll++;
if(scroll == 40){
scroll = 0;
}
}
clip = {0.f, 0.f, 213.f, 214.f};
clip.x = 0.f;
clip.y = y;
gSamusSprites.addClipSprite( clip );
if( !gSamusSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
return true;
}
void update()
{
}
void render()
{
//Clear color buffer
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPushMatrix();
if(add == 0){
if(zoom < 101){
double const f_zoom = 1.0 + 0.1 * zoom;
glScaled(f_zoom, f_zoom, f_zoom);
}
if(zoom < -10){
double const f_zoom = 1.0 - 0.1 * zoom;
glScaled(f_zoom, f_zoom, f_zoom);
}
glTranslatef( -100.f, 178.f, 0.f );
gArrowSprites.renderSprite( 0 );
//Render top right arrow
glTranslatef( +100.f, -178.f, 0.f );
glTranslatef( 1240.f, 240.f, 0.f );
gArrowSprites.renderSprite( 1 );
//Render bottom left arrow
glTranslatef( -1240.f, +240.f, 0.f );
glTranslatef( 620.f, 500.f ,0.f );
gArrowSprites.renderSprite( 2 );
glTranslatef( -620.f, -500.f, 0.f );
glTranslatef( 620.f, 0.f , 0.f );
gSamusSprites.renderSprite( 0 );
}
if(add == 1){
if(zoom < 101){
double const f_zoom = 1.0 + 0.1 * zoom;
glScaled(f_zoom, f_zoom, f_zoom);
}
if(zoom < -10){
double const f_zoom = 1.0 - 0.1 * zoom;
glScaled(f_zoom, f_zoom, f_zoom);
}
glTranslatef( -100.f, 178.f, 0.f );
gArrowSprites.renderSprite( 3 );
glTranslatef( +100.f, -178.f, 0.f );
glTranslatef( 1240.f, 240.f, 0.f );
gArrowSprites.renderSprite( 4 );
glTranslatef( -1240.f, +240.f, 0.f );
glTranslatef( 620.f, 500.f ,0.f );
gArrowSprites.renderSprite( 5 );
}
glLoadIdentity();
glutSwapBuffers();
}
void handleKeys( unsigned char key, int x, int y )
{
//If the user presses q
if( key == 'q' && add == 0)
{
add++;
}
else if( key == 'q' && add == 1)
{
add--;
}
//Update the sprite rectangles so the texture change takes effect
if( key == 27 ) {
exit(0);
}
if(key == 'a') {
gCameraX += 8.f;
factor--;
factor2++;
}
else if (key == 'd') {
gCameraX -= 8.f;
factor++;
factor2--;
}
else if (key == 'w') {
gCameraY += 8.f;
}
else if (key == 's') {
gCameraY -= 8.f;
}
else if (key == '+' && zoom != 100) {
zoom += 1;
if(factor >= 19) {
gCameraX -= 64.f;
}
if(factor2 >= 33){
gCameraX += 16.f;
}
else{
gCameraX -= 64.f;
gCameraY -= 50.f;
}
}
else if (key == '-' && zoom != -9) {
zoom -= 1;
if(factor >= 19){
gCameraX += 64.f;
}
if(factor2 >= 33){
gCameraX -= 32.f;
}
else{
gCameraX += 64.f;
gCameraY += 50.f;
}
}
//Take saved matrix off the stack and reset it
glMatrixMode( GL_MODELVIEW );
glPopMatrix();
glLoadIdentity();
//Move camera to position
glTranslatef( gCameraX, gCameraY, gCameraZ );
//Save default matrix again with camera translation
glPushMatrix();
}
EDIT: I just tried adjusting the y coordinate value in the for loop and nothing was happening so I tried removing the if statement and still nothing. But if I adjust the y value at the top of my file the texture will change. So why isn't my loop adding to my y value?
I suppose it's because in your for
for(int scroll; scroll > 40; scroll++){
you declare the scroll variable but you don't initialize it.
So scroll start with an undefined value that can be greather than 40.
Solution (I suppose): initialize scroll.
p.s.: sorry for my bad English.
--- EDIT 2016.05.23 ---
Look at this code
while(scroll != 40){
y += 214.f;
scroll++;
if(scroll == 40){
scroll = 0;
}
}
clip = {0.f, 0.f, 213.f, 214.f};
clip.x = 0.f;
clip.y = y;
gSamusSprites.addClipSprite( clip );
If scrool reach the while with a value different from 40, the while never exit and you only increment (forever) y.
I suppose you intention was to call gSamusSprites.addClipSprite() (or a similar function) for every iteration of the while.
I suppose your intention was to iterate the cycle only 40 times and exit.
If my suppositions are correct, you can try something like [caution: not tested]
clip = {0.f, 0.f, 213.f, 214.f};
for (scroll = 0; scroll < 40; ++scroll, clip.y += 214.f )
gSamusSprites.addClipSprite( clip ); // or a different function?

Opengl macos fail

I have problem. I wrote the code on clear opengl and c++ without any libraries(glut, glew...) but it doesnt work.
Function displayCB display polygon with
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-0.5f, -0.5f);
glVertex2f( 0.5f, -0.5f);
glVertex2f( 0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
and dont display two polygone with
glColor3f(1.0f, 0.0f, 0.0f);
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glVertex3f( 0.0f, 1.0f, 0.0f); // Top
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glEnd(); // Finished Drawing The Triangle
glTranslatef(3.0f,0.0f,0.0f); // Move Right 3 Units
glBegin(GL_QUADS); // Draw A Quad
glVertex3f(-1.0f, 1.0f, 0.0f); // Top Left
glVertex3f( 1.0f, 1.0f, 0.0f); // Top Right
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glEnd();
Can you help me?
COMPILE WITH: g++ -g -o opengl1 opengl1.cxx -lGLU -lGL -lX11
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/time.h>
#define GL_GLEXT_PROTOTYPES
#define GLX_GLXEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
struct MyWin
{
Display *display;
Window win;
bool displayed;
int width;
int height;
};
const int WIN_XPOS = 256;
const int WIN_YPOS = 64;
const int WIN_XRES = 600;
const int WIN_YRES = 600;
const int NUM_SAMPLES = 4;
MyWin Win;
double elapsedMsec( const struct timeval &start, const struct timeval &stop )
{
return ( ( stop.tv_sec - start.tv_sec ) * 1000.0 +
( stop.tv_usec - start.tv_usec ) / 1000.0 );
}
double elapsedUsec( const struct timeval &start, const struct timeval &stop )
{
return ( ( stop.tv_sec - start.tv_sec ) * 1000000.0 +
( stop.tv_usec - start.tv_usec ) );
}
/// check() - Check for GL errors, and report any queued
void check( const char hdr[] = "" )
{
int err;
while ( ( err = glGetError() ) != GL_NO_ERROR )
fprintf( stderr, "OpenGL Error at %s: %s\n", hdr, gluErrorString(err) );
}
void displayCB()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
//---------------------------------------------------
// FIXME: Insert GL draw code here
//---------------------------------------------------
glColor3f(1.0f, 0.0f, 0.0f);
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glVertex3f( 0.0f, 1.0f, 0.0f); // Top
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glEnd(); // Finished Drawing The Triangle
glTranslatef(3.0f,0.0f,0.0f); // Move Right 3 Units
glBegin(GL_QUADS); // Draw A Quad
glVertex3f(-1.0f, 1.0f, 0.0f); // Top Left
glVertex3f( 1.0f, 1.0f, 0.0f); // Top Right
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glEnd();
// glBegin(GL_POLYGON);
// glVertex2f(-0.5f, -0.5f);
// glVertex2f( 0.5f, -0.5f);
// glVertex2f( 0.5f, 0.5f);
// glVertex2f(-0.5f, 0.5f);
// glEnd();
// Display it
glXSwapBuffers( Win.display, Win.win );
check( "displayCB()" );
}
//----------------------------------------------------------------------------
void keyboardCB( KeySym sym, unsigned char key, int x, int y,
bool &setting_change )
{
switch ( tolower( key ) )
{
case 27:
// ESCape - We're done!
exit (0);
break;
case 'k':
printf( "You hit the 'k' key\n" );
break;
case 0:
switch ( sym )
{
case XK_Left :
printf( "You hit the Left Arrow key\n" );
break;
case XK_Right :
printf( "You hit the Right Arrow key\n" );
break;
}
break;
}
}
//----------------------------------------------------------------------------
void reshapeCB( int width, int height )
{
Win.width = width;
Win.height = height;
}
//----------------------------------------------------------------------------
XVisualInfo *chooseVisual( Display *display )
{
int attribs [ 100 ] ;
int n = 0 ;
// Request 24-bit color with alpha
attribs [n++] = GLX_RGBA ;
attribs [n++] = GLX_RED_SIZE ; attribs [n++] = 8 ;
attribs [n++] = GLX_GREEN_SIZE ; attribs [n++] = 8 ;
attribs [n++] = GLX_BLUE_SIZE ; attribs [n++] = 8 ;
// Request 24-bit depth buffer
attribs [n++] = GLX_DEPTH_SIZE ; attribs [n++] = 24 ;
// Request 4 multisamples per pixel
attribs [n++] = GLX_SAMPLE_BUFFERS ; attribs [n++] = 1 ;
attribs [n++] = GLX_SAMPLES ; attribs [n++] = NUM_SAMPLES ;
// Request double-buffering
attribs [n++] = GLX_DOUBLEBUFFER ;
attribs [n++] = None ;
return glXChooseVisual( display, DefaultScreen( display ), attribs );
}
//----------------------------------------------------------------------------
void createWindow()
{
// Init X and GLX
Win.displayed = false;
Display *display = Win.display = XOpenDisplay( ":0.0" );
if ( !display )
printf( "Cannot open X display\n" );
int screen = DefaultScreen( display );
Window root_win = RootWindow( display, screen );
if ( !glXQueryExtension( display, 0, 0 ) )
printf( "X Server doesn't support GLX extension\n" );
// Pick a visual
XVisualInfo *visinfo = chooseVisual( display );
if ( visinfo == 0 )
printf( "glXChooseVisual failed\n" );
// Describe the visual
printf( "Window Visual 0x%.2x\n", unsigned( visinfo->visualid ) );
// Create the X window
XSetWindowAttributes winAttr ;
winAttr.event_mask = StructureNotifyMask | KeyPressMask ;
winAttr.background_pixmap = None ;
winAttr.background_pixel = 0 ;
winAttr.border_pixel = 0 ;
winAttr.colormap = XCreateColormap( display, root_win,
visinfo->visual, AllocNone );
unsigned int mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
Window win = Win.win = XCreateWindow ( display, root_win,
WIN_XPOS, WIN_YPOS,
WIN_XRES, WIN_YRES, 0,
visinfo->depth, InputOutput,
visinfo->visual, mask, &winAttr ) ;
XStoreName( Win.display, win, "My GLX Window");
// Create an OpenGL context and attach it to our X window
GLXContext context = glXCreateContext( display, visinfo, NULL, 1 ) ;
if ( ! glXMakeCurrent( display, win, context ) )
printf( "glXMakeCurrent failed.\n" );
if ( ! glXIsDirect ( display, glXGetCurrentContext() ) )
printf( "Indirect GLX rendering context obtained\n" );
// Display the window
XMapWindow( display, win );
if ( ! glXMakeCurrent( display, win, context ) )
printf( "glXMakeCurrent failed.\n" );
check( "createWindow()" );
printf( "Window Size = %d x %d\n", WIN_XRES, WIN_YRES );
printf( "Window Samples = %d\n", NUM_SAMPLES );
}
//----------------------------------------------------------------------------
void processXEvents( Atom wm_protocols, Atom wm_delete_window )
{
bool setting_change = false;
while ( XEventsQueued( Win.display, QueuedAfterFlush ) )
{
XEvent event;
XNextEvent( Win.display, &event );
if( event.xany.window != Win.win )
continue;
switch ( event.type )
{
case MapNotify:
{
Win.displayed = true;
break;
}
case ConfigureNotify:
{
XConfigureEvent &cevent = event.xconfigure;
reshapeCB( cevent.width, cevent.height );
break;
}
case KeyPress:
{
char chr;
KeySym symbol;
XComposeStatus status;
XLookupString( &event.xkey, &chr, 1, &symbol, &status );
keyboardCB( symbol, chr, event.xkey.x, event.xkey.y,
setting_change );
break;
}
case ClientMessage:
{
if ( event.xclient.message_type == wm_protocols &&
Atom( event.xclient.data.l[0] ) == wm_delete_window )
{
//printf( "Received WM_DELETE_WINDOW\n" );
exit(0);
}
break;
}
}
}
}
//----------------------------------------------------------------------------
void mainLoop()
{
// Register to receive window close events (the "X" window manager button)
Atom wm_protocols = XInternAtom( Win.display, "WM_PROTOCOLS" , False);
Atom wm_delete_window = XInternAtom( Win.display, "WM_DELETE_WINDOW", False);
XSetWMProtocols( Win.display, Win.win, &wm_delete_window, True );
while (1)
{
// Redraw window (after it's mapped)
if ( Win.displayed )
displayCB();
// Update frame rate
static timeval last_xcheck = {0,0};
struct timeval now;
gettimeofday( &now, 0 );
// Check X events every 1/10 second
if ( elapsedMsec( last_xcheck, now ) > 100 )
{
processXEvents( wm_protocols, wm_delete_window );
last_xcheck = now;
}
}
}
//----------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
// Init globals
Win.width = WIN_XRES, Win.height = WIN_YRES;
// Create context and window
createWindow();
// Init OpenGL
glViewport ( 0, 0, Win.width, Win.height );
glColorMask ( 1,1,1,1 );
glClearColor( 0,0,1,1 );
glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// Go
printf( "Valid keys: Left, Right, k, ESC\n" );
printf( "Press ESC to quit\n" );
mainLoop();
return 0;
}
There are three problems here.
First: you haven't set up a GL viewport (e.g, using glFrustum() or gluPerspective()), so the perspective matrix isn't set up appropriately to do 3D graphics. As such, trying to draw a model in 3D won't work properly.
Second: The code that you've got here is written against the X11 windowing system, not Mac OS X. While it'll compile and sort-of-run on Mac OS, it will not run natively, nor will it perform particularly well. You will really want to use some interface which allows you to interface with the native Mac OS X GL implementation, such as SDL, GLUT/GLEW, or AGL.
(Keep in mind that there is no such thing as using GL "without libraries". OpenGL is itself a library, as is libX11; there's nothing at all wrong with using extra utility libraries to cut out some of the OS-specific setup and make your application easier to port.)
Third: You are currently learning how to use OpenGL immediate mode, which was used prior to OpenGL 3.0. Modern OpenGL — that is, OpenGL 3.0 or later, as well as OpenGL ES — uses a significantly different API which has very little in common with immediate mode. I'd strongly recommend that you skip immediate mode entirely; it's a dead technology at this point. There are a number of good tutorials out there for OpenGL 3+, including:
http://www.opengl-tutorial.org/
http://www.arcsynthesis.org/gltut/
https://open.gl/

Directx11: remove alpha blending for specific sprite

Background:
- I've been spending the last 6 weeks trying to learn Directx 11 programming.
I'm currently rendering dds images on-screen following this book
http://www.amazon.co.uk/Beginning-Directx-11-Game-Programming/dp/1435458958/ref=sr_1_1?ie=UTF8&qid=1346510304&sr=8-1
I am trying to draw 2D sprites upon a 2D background which in itself also is a 2D sprite. Problem is that these two lines
d3dDevice_->CreateBlendState( &blendDesc, &alphaBlendState_ );
d3dContext_->OMSetBlendState( alphaBlendState_, blendFactor, 0xFFFFFFFF );
to enable the alpha transparency in the dds images. I like to have the option to blend sprites but right now every sprites is blended with my blue background thus resulting in blu logos, icons etc.
How do I make the Alpha Blending ignore a specific image in directx 11?
Since the background sprite is the first to be drawn I can't activate the Blending later in the code when rendering the other sprites without every sprite turning blue.
thanks in advance :)
EDIT:
I've been working on this issue for the past 3 weeks and still no solution. Everytime the blend state is enabled in the DeviceContext is seems to apply to every texture drawn on the screen no matter the order of rendering.
Here is the source code of the header file:
class GameSpriteDemo : public Dx11DemoBase
{
public:
GameSpriteDemo( );
virtual ~GameSpriteDemo( );
bool LoadContent( );
void UnloadContent( );
void Update( float dt );
void Render( );
void DisableBlending();
ID3D11ShaderResourceView* getColorMap(int);
int UniqSpriteAmount();
// text rendering system
private:
bool DrawString( char* message, float startX, float startY );
private:
ID3D11VertexShader* solidColorVS_;
ID3D11VertexShader* solidColorVS_2;
ID3DX11Effect* effect_;
vector<ID3D11VertexShader*> solidColorVShaders;
ID3D11PixelShader* solidColorPS_;
ID3D11PixelShader* solidColorPS_2;
ID3D11InputLayout* inputLayout_;
ID3D11InputLayout* inputLayout2;
ID3D11Buffer* vertexBuffer_;
vector<ID3D11Buffer*> vertexBuffers;
ID3D11ShaderResourceView* colorMap_;
vector<ID3D11ShaderResourceView*> colorMaps;
ID3D11SamplerState* colorMapSampler_;
vector<ID3D11SamplerState*> colorSamplers;
ID3D11BlendState* alphaBlendState_;
ID3D11BlendState* alphaBlendStateOff;
vector<LPCTSTR> elements2D;
vector<GameSprite> sprites_;
ID3D11Buffer* mvpCB_;
XMMATRIX vpMatrix_;
};
#endif
Here is the source code of the cpp file: (the Base Class DxD11DemoClass is not needed since it only sets up SwapChain and D3DContext)
bool GameSpriteDemo::LoadContent( )
{
// add sprite textures to the engine, giving them index 0, 1, 2... etc.
elements2D.push_back("placeholder3.dds");
elements2D.push_back("cav.dds");
elements2D.push_back("Stats.dds");
// create sprites
XMFLOAT2 sprite1Pos( 0.0f, 500.0f);
GameSprite sprite1(getDevice(), "placeholder3.dds", 0, sprite1Pos, 0.0f);
XMFLOAT2 sprite1Scale( 0.5f, 0.5f );
XMFLOAT2 mini(0.8f, 0.6f);
sprite1.SetScale(mini);
sprites_.push_back(sprite1);
XMFLOAT2 sprite2Pos( 200.0f, 100.0f );
GameSprite sprite2(getDevice(), "Stats.dds", 2, sprite2Pos, 2.0f);
// sprites_.push_back(sprite2);
XMFLOAT2 sprite3Pos( 290.0f, 300.0f );
GameSprite sprite3(getDevice(), "cav.dds", 1, sprite3Pos, 2.0f);
sprite3.SetScale(sprite1Scale);
sprites_.push_back(sprite3);
// create vertex buffers, colorMaps and colorSamplers
for (int i = 0; i <= elements2D.size(); i++) {
solidColorVShaders.push_back(solidColorVS_);
colorMaps.push_back(colorMap_);
colorSamplers.push_back(colorMapSampler_);
vertexBuffers.push_back(vertexBuffer_);
}
// continue
ID3DBlob* vsBuffer = 0;
bool compileResult = CompileD3DShader( "TextureMap.fx", "VS_Main", "vs_4_0", &vsBuffer );
if( compileResult == false )
{
DXTRACE_MSG( "Error compiling the vertex shader!" );
return false;
}
HRESULT d3dResult;
d3dResult = d3dDevice_->CreateVertexShader( vsBuffer->GetBufferPointer( ),
vsBuffer->GetBufferSize( ), 0, &solidColorVShaders[0] );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Error creating the vertex shader!" );
if( vsBuffer )
vsBuffer->Release( );
return false;
}
D3D11_INPUT_ELEMENT_DESC solidColorLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
unsigned int totalLayoutElements = ARRAYSIZE( solidColorLayout );
d3dResult = d3dDevice_->CreateInputLayout( solidColorLayout, totalLayoutElements,
vsBuffer->GetBufferPointer( ), vsBuffer->GetBufferSize( ), &inputLayout_ );
vsBuffer->Release( );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Error creating the input layout!" );
return false;
}
ID3DBlob* psBuffer = 0;
compileResult = CompileD3DShader( "TextureMap.fx", "PS_Main", "ps_4_0", &psBuffer );
if( compileResult == false )
{
DXTRACE_MSG( "Error compiling pixel shader!" );
return false;
}
d3dResult = d3dDevice_->CreatePixelShader( psBuffer->GetBufferPointer( ),
psBuffer->GetBufferSize( ), 0, &solidColorPS_ );
psBuffer->Release( );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Error creating pixel shader!" );
return false;
}
// create ColorMap, ColorSampler and VertexBuffer for each unique sprite
D3D11_SAMPLER_DESC colorMapDesc;
D3D11_BUFFER_DESC vertexDesc;
D3D11_SUBRESOURCE_DATA resourceData;
for (int j = 0; j < elements2D.size(); j++) {
d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_,
elements2D[j], 0, 0, &colorMaps[j], 0 );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Failed to load the texture image!" );
return false;
}
ZeroMemory( &colorMapDesc, sizeof( colorMapDesc ) );
colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
colorMapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX;
d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc, &colorSamplers[j] );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Failed to create color map sampler state!" );
return false;
}
float Width = sprites_[j].getWidth();
float Height = sprites_[j].getHeight();
VertexPos vertices[] =
{
{ XMFLOAT3( Width, Height, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
{ XMFLOAT3( Width, -Height, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
{ XMFLOAT3( -Width, -Height, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
{ XMFLOAT3( -Width, -Height, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
{ XMFLOAT3( -Width, Height, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
{ XMFLOAT3( Width, Height, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
};
ZeroMemory( &vertexDesc, sizeof( vertexDesc ) );
vertexDesc.Usage = D3D11_USAGE_DEFAULT;
vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexDesc.ByteWidth = sizeof( VertexPos ) * 6;
ZeroMemory( &resourceData, sizeof( resourceData ) );
resourceData.pSysMem = vertices;
d3dResult = d3dDevice_->CreateBuffer( &vertexDesc, &resourceData, &vertexBuffers[j] );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Failed to create vertex buffer!" );
return false;
}
}
// end of foor loop
// create text fonts
d3dResult = D3DX11CreateShaderResourceViewFromFile( d3dDevice_,
"font.dds", 0, 0, &colorMap_, 0 );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Failed to load the texture image!" );
return false;
}
D3D11_SAMPLER_DESC colorMapDesc2;
ZeroMemory( &colorMapDesc2, sizeof( colorMapDesc2 ) );
colorMapDesc2.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
colorMapDesc2.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
colorMapDesc2.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
colorMapDesc2.ComparisonFunc = D3D11_COMPARISON_NEVER;
colorMapDesc2.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
colorMapDesc2.MaxLOD = D3D11_FLOAT32_MAX;
d3dResult = d3dDevice_->CreateSamplerState( &colorMapDesc2, &colorMapSampler_ );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Failed to create color map sampler state!" );
return false;
}
D3D11_BUFFER_DESC vertexDesc2;
ZeroMemory( &vertexDesc2, sizeof( vertexDesc2 ) );
vertexDesc2.Usage = D3D11_USAGE_DYNAMIC;
vertexDesc2.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexDesc2.BindFlags = D3D11_BIND_VERTEX_BUFFER;
const int sizeOfSprite = sizeof( VertexPos ) * 6;
const int maxLetters = 24;
vertexDesc2.ByteWidth = sizeOfSprite * maxLetters;
d3dResult = d3dDevice_->CreateBuffer( &vertexDesc2, 0, &vertexBuffer_ );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Failed to create vertex buffer!" );
return false;
}
// end of font creation
D3D11_BUFFER_DESC constDesc;
ZeroMemory( &constDesc, sizeof( constDesc ) );
constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constDesc.ByteWidth = sizeof( XMMATRIX );
constDesc.Usage = D3D11_USAGE_DEFAULT;
d3dResult = d3dDevice_->CreateBuffer( &constDesc, 0, &mvpCB_ );
if( FAILED( d3dResult ) )
{
return false;
}
XMMATRIX view = XMMatrixIdentity( );
XMMATRIX projection = XMMatrixOrthographicOffCenterLH( 0.0f, 1366.0f, 0.0f, 768.0f, 0.1f, 100.0f );
vpMatrix_ = XMMatrixMultiply( view, projection );
D3D11_BLEND_DESC blendDesc;
ZeroMemory( &blendDesc, sizeof( blendDesc ) );
blendDesc.RenderTarget[0].BlendEnable = TRUE;
blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE;
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
d3dDevice_->CreateBlendState( &blendDesc, &alphaBlendState_ );
// create the disabled blend state
blendDesc.RenderTarget[0].BlendEnable = FALSE;
d3dDevice_->CreateBlendState( &blendDesc, &alphaBlendStateOff );
d3dContext_->OMSetBlendState( alphaBlendState_, blendFactor, 0xFFFFFFFF );
// holy shit here we go again
ID3DBlob* vsBuffer2 = 0;
compileResult = CompileD3DShader( "TextMap.fx", "VS_Main", "vs_4_0", &vsBuffer2 );
if( compileResult == false )
{
DXTRACE_MSG( "Error compiling the vertex shader!" );
return false;
}
d3dResult = d3dDevice_->CreateVertexShader( vsBuffer2->GetBufferPointer( ),
vsBuffer2->GetBufferSize( ), 0, &solidColorVS_2 );
ID3DBlob* psBuffer2 = 0;
compileResult = CompileD3DShader( "TextureMap.fx", "PS_Main", "ps_4_0", &psBuffer2 );
if( compileResult == false )
{
DXTRACE_MSG( "Error compiling pixel shader!" );
return false;
}
d3dResult = d3dDevice_->CreatePixelShader( psBuffer2->GetBufferPointer( ),
psBuffer2->GetBufferSize( ), 0, &solidColorPS_2 );
psBuffer2->Release( );
return true;
}
void GameSpriteDemo::UnloadContent( )
{
if( colorMapSampler_ ) colorMapSampler_->Release( );
if( colorMap_ ) colorMap_->Release( );
if( solidColorVShaders[0] ) solidColorVShaders[0]->Release( );
if( solidColorPS_ ) solidColorPS_->Release( );
if( inputLayout_ ) inputLayout_->Release( );
if( vertexBuffer_ ) vertexBuffer_->Release( );
if( mvpCB_ ) mvpCB_->Release( );
if( alphaBlendState_ ) alphaBlendState_->Release( );
if( alphaBlendStateOff ) alphaBlendStateOff->Release( );
colorMapSampler_ = 0;
colorMap_ = 0;
solidColorVShaders[0] = 0;
solidColorPS_ = 0;
inputLayout_ = 0;
vertexBuffer_ = 0;
mvpCB_ = 0;
alphaBlendState_ = 0;
alphaBlendStateOff = 0;
}
void GameSpriteDemo::Update( float dt )
{
// Nothing to update
}
bool GameSpriteDemo::DrawString( char* message, float startX, float startY )
{
// Size in bytes for a single sprite.
const int sizeOfSprite = sizeof( VertexPos ) * 6;
// Demo's dynamic buffer setup for max of 24 letters.
const int maxLetters = 24;
int length = strlen( message );
// Clamp for strings too long.
if( length > maxLetters )
length = maxLetters;
// Char's width on screen.
float charWidth = 32.0f / (1366.0f*1.0f);
// Char's height on screen.
float charHeight = 32.0f / (768.0f*1.0f);
// Char's texel width.
float texelWidth = 32.0f / 896.0f;
// verts per-triangle (3) * total triangles (2) = 6.
const int verticesPerLetter = 6;
D3D11_MAPPED_SUBRESOURCE mapResource;
HRESULT d3dResult = d3dContext_->Map( vertexBuffer_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapResource );
if( FAILED( d3dResult ) )
{
DXTRACE_MSG( "Failed to map resource!" );
return false;
}
// Point to our vertex buffer's internal data.
VertexPos *spritePtr = ( VertexPos* )mapResource.pData;
const int indexA = static_cast<char>( 'A' );
const int indexZ = static_cast<char>( 'Z' );
const int index_a = static_cast<char>( 'a' );
for( int i = 0; i < length; ++i )
{
float thisStartX = startX + ( charWidth * static_cast<float>( i ) );
float thisEndX = thisStartX + charWidth;
float thisEndY = startY + charHeight;
spritePtr[0].pos = XMFLOAT3( thisEndX, thisEndY, 1.0f );
spritePtr[1].pos = XMFLOAT3( thisEndX, startY, 1.0f );
spritePtr[2].pos = XMFLOAT3( thisStartX, startY, 1.0f );
spritePtr[3].pos = XMFLOAT3( thisStartX, startY, 1.0f );
spritePtr[4].pos = XMFLOAT3( thisStartX, thisEndY, 1.0f );
spritePtr[5].pos = XMFLOAT3( thisEndX, thisEndY, 1.0f );
int texLookup = 0;
int letter = static_cast<char>( message[i] );
if (letter == index_a) {
texLookup = (indexZ - indexA) + 2;
}
else if( letter < indexA || letter > indexZ )
{
// Grab one index past Z, which is a blank space in the texture.
texLookup = ( indexZ - indexA ) + 1;
}
else
{
// A = 0, B = 1, Z = 25, etc.
texLookup = ( letter - indexA );
}
float tuStart = 0.0f + ( texelWidth * static_cast<float>( texLookup ) );
float tuEnd = tuStart + texelWidth;
spritePtr[0].tex0 = XMFLOAT2( tuEnd, 0.0f );
spritePtr[1].tex0 = XMFLOAT2( tuEnd, 1.0f );
spritePtr[2].tex0 = XMFLOAT2( tuStart, 1.0f );
spritePtr[3].tex0 = XMFLOAT2( tuStart, 1.0f );
spritePtr[4].tex0 = XMFLOAT2( tuStart, 0.0f );
spritePtr[5].tex0 = XMFLOAT2( tuEnd, 0.0f );
spritePtr += 6;
}
d3dContext_->Unmap( vertexBuffer_, 0 );
d3dContext_->Draw( 6 * length, 0 );
return true;
}
void GameSpriteDemo::Render( )
{
if( d3dContext_ == 0 )
return;
float clearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
d3dContext_->ClearRenderTargetView( backBufferTarget_, clearColor );
unsigned int stride = sizeof( VertexPos );
unsigned int offset = 0;
d3dContext_->IASetInputLayout( inputLayout_ );
d3dContext_->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
d3dContext_->VSSetShader( solidColorVShaders[0], 0, 0 );
d3dContext_->PSSetShader( solidColorPS_, 0, 0 );
XMMATRIX world;
XMMATRIX mvp;
int index;
for (int k = 0; k < sprites_.size(); k++) {
index = sprites_[k].getIndex();
d3dContext_->IASetVertexBuffers( 0, 1, &vertexBuffers[index], &stride, &offset );
d3dContext_->PSSetShaderResources( 0, 1, &colorMaps[index] );
d3dContext_->PSSetSamplers( 0, 1, &colorSamplers[index] );
world = sprites_[k].GetWorldMatrix();
mvp = XMMatrixMultiply( world, vpMatrix_ );
mvp = XMMatrixTranspose( mvp );
d3dContext_->UpdateSubresource( mvpCB_, 0, 0, &mvp, 0, 0 );
d3dContext_->VSSetConstantBuffers( 0, 1, &mvpCB_ );
d3dContext_->Draw( 6, 0 );
}
// render text
DisableBlending();
d3dContext_->IASetVertexBuffers( 0, 1, &vertexBuffer_, &stride, &offset );
d3dContext_->PSSetShaderResources( 0, 1, &colorMap_ );
d3dContext_->PSSetSamplers( 0, 1, &colorMapSampler_ );
d3dContext_->VSSetShader( solidColorVS_2, 0, 0 );
d3dContext_->PSSetShader( solidColorPS_2, 0, 0 );
DrawString( "PROTOTYPE TEXT", -0.2f, 0.0f );
swapChain_->Present( 0, 0 );
}
ID3D11ShaderResourceView* GameSpriteDemo::getColorMap(int index) {
return colorMaps[index];
}
// this functions disables the alpha blending
void GameSpriteDemo::DisableBlending() {
float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
d3dContext_->OMSetBlendState( alphaBlendStateOff, blendFactor, 0xFFFFFFFF );
}
Screen of the results when drawing with blending enabled
http://i49.tinypic.com/33kao9v.jpg
and here is the HLSL code for the two FX files I'm using (the first for the sprites, the second for the text)
TextureMap.fx
cbuffer cbChangesPerFrame : register( b0 )
{
matrix mvp_;
};
Texture2D colorMap_ : register( t0 );
SamplerState colorSampler_ : register( s0 );
struct VS_Input
{
float4 pos : POSITION;
float2 tex0 : TEXCOORD0;
};
struct PS_Input
{
float4 pos : SV_POSITION;
float2 tex0 : TEXCOORD0;
};
PS_Input VS_Main( VS_Input vertex )
{
PS_Input vsOut = ( PS_Input )0;
vsOut.pos = mul( vertex.pos, mvp_ );
vsOut.tex0 = vertex.tex0;
return vsOut;
}
float4 PS_Main( PS_Input frag ) : SV_TARGET
{
return colorMap_.Sample( colorSampler_, frag.tex0 );
}
TextMap.fx
Texture2D colorMap_ : register( t0 );
SamplerState colorSampler_ : register( s0 );
struct VS_Input
{
float4 pos : POSITION;
float2 tex0 : TEXCOORD0;
};
struct PS_Input
{
float4 pos : SV_POSITION;
float2 tex0 : TEXCOORD0;
};
PS_Input VS_Main( VS_Input vertex )
{
PS_Input vsOut = ( PS_Input )0;
vsOut.pos = vertex.pos;
vsOut.tex0 = vertex.tex0;
return vsOut;
}
float4 PS_Main( PS_Input frag ) : SV_TARGET
{
return colorMap_.Sample( colorSampler_, frag.tex0 );
}
I have wondered maybe to use pixel shaders to perform alpha blending for specific 2D images but my first attempts has not worked at all.
Hope someone can find a solution somehow :)
and thanks again for the help.

Directx 9 Basic Terrain Creation w/Vertices

I'm trying to create terrain using indexed primitives...I've written a class to handle the graphics, however, I can't get the textured terrain to appear on the screen...The following are the source and header files associated with this process...please ignore skybox functions...
graphics.h:
#pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include <d3dx9tex.h>
#include <string>
#include "Camera.h"
class CGraphics
{
public:
CGraphics(IDirect3DDevice9 *device);
~CGraphics(void);
IDirect3DDevice9 *m_d3ddev;
LPDIRECT3DVERTEXBUFFER9 m_vertexBuffer;
LPDIRECT3DVERTEXBUFFER9 m_terrainVertexBuffer;
LPDIRECT3DINDEXBUFFER9 m_terrainIndexBuffer;
LPDIRECT3DTEXTURE9 m_textures[6];
LPDIRECT3DTEXTURE9 m_terrainTexture;
int m_numVertices;
int m_numFaces;
bool SkyBox(void);
void UpdateSkyBox(void);
bool Terrain(D3DXVECTOR3 minB, D3DXVECTOR3 maxB, int numCellsW, int numCellsL);
void RenderTerrain(void);
private:
void RenderSkyBox(void);
};
graphics.cpp:
#include "Graphics.h"
#include "3D Shapes.h"
#include "assert.h"
CGraphics::CGraphics(IDirect3DDevice9 *device) : m_d3ddev(device), m_vertexBuffer(0)
{
for(unsigned int i = 0; i < sizeof(LPDIRECT3DTEXTURE9)/sizeof(m_textures); i++)
{
m_textures[i] = 0;
m_terrainVertexBuffer = NULL;
m_terrainIndexBuffer = NULL;
}
}
CGraphics::~CGraphics(void)
{
if(m_vertexBuffer)
{
delete m_vertexBuffer;
m_vertexBuffer=0;
}
if(m_d3ddev)
{
m_d3ddev->Release();
m_d3ddev=0;
}
if(m_terrainVertexBuffer){
m_terrainVertexBuffer->Release();
m_terrainVertexBuffer=0;
}
if(m_terrainIndexBuffer){
m_terrainIndexBuffer->Release();
m_terrainIndexBuffer=0;
}
}
bool CGraphics::SkyBox(void)
{
HRESULT hr;
hr = m_d3ddev->CreateVertexBuffer(sizeof(TEXTUREVERTEX) * 24, 0, CUSTOMFVF, D3DPOOL_MANAGED,
&m_vertexBuffer, NULL);
if(FAILED(hr))
{
MessageBox(NULL, L"Failed to 'Create Vertex Buffer for SkyBox'", L"ERROR", MB_OK);
return false;
}
void* pVertices = NULL;
m_vertexBuffer->Lock(0, sizeof(TEXTUREVERTEX)*24, (void**)&pVertices, 0);
memcpy(pVertices, skyBox, sizeof(TEXTUREVERTEX)*24);
m_vertexBuffer->Unlock();
hr = D3DXCreateTextureFromFileA(m_d3ddev, fileF.c_str(), &m_textures[0]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileB.c_str(), &m_textures[1]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileL.c_str(), &m_textures[2]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileR.c_str(), &m_textures[3]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileTop.c_str(), &m_textures[4]);
hr |= D3DXCreateTextureFromFileA(m_d3ddev, fileBottom.c_str(), &m_textures[5]);
if ( FAILED(hr) )
{
MessageBox(NULL, L"Failed to open 1 or more images files!", L"Error Opening Texture Files", MB_OK);
return false;
}
return true;
}
void CGraphics::UpdateSkyBox(void)
{
D3DXMATRIX matView, matSave, matWorld;
m_d3ddev->GetTransform(D3DTS_VIEW, &matSave);
matView = matSave;
matView._41 = 0.0f; matView._42 = -0.4f; matView._43 = 0.0f;
m_d3ddev->SetTransform(D3DTS_VIEW, &matView);
D3DXMatrixIdentity(&matWorld);
m_d3ddev->SetTransform(D3DTS_WORLD, &matWorld);
RenderSkyBox();
m_d3ddev->SetTransform(D3DTS_VIEW, &matSave);
}
void CGraphics::RenderSkyBox(void)
{
m_d3ddev->SetRenderState(D3DRS_ZENABLE, false);
m_d3ddev->SetRenderState(D3DRS_ZWRITEENABLE, false);
m_d3ddev->SetRenderState(D3DRS_LIGHTING, false);
m_d3ddev->SetSamplerState( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP );
m_d3ddev->SetSamplerState( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP );
m_d3ddev->SetFVF(CUSTOMFVF);
m_d3ddev->SetStreamSource(0, m_vertexBuffer, 0, sizeof(TEXTUREVERTEX));
for(unsigned int i = 0; i < 6; i ++)
{
m_d3ddev->SetTexture(0, m_textures[i]);
m_d3ddev->DrawPrimitive(D3DPT_TRIANGLESTRIP, i*4, 2);
}
m_d3ddev->SetRenderState(D3DRS_ZENABLE, true);
m_d3ddev->SetRenderState(D3DRS_ZWRITEENABLE, true);
m_d3ddev->SetRenderState(D3DRS_LIGHTING, true);
}
bool CGraphics::Terrain(D3DXVECTOR3 minB, D3DXVECTOR3 maxB, int numCellsW, int numCellsL)
{
HRESULT hr = D3DXCreateTextureFromFileA(m_d3ddev, (LPCSTR)texFileTerrain.c_str(), &m_terrainTexture);
if(FAILED(hr))
{
MessageBox(NULL, L"Could not 'Load Texture(Terrain)'", L"ERROR", MB_OK);
return false;
}
TERRAIN terra = {minB,maxB,numCellsW,numCellsL,numCellsW+1,numCellsL+1,(maxB.x - minB.x)/numCellsW,
(maxB.z - minB.z)/numCellsL,
terra.vertices = new VERTEXARRAY[terra.numVertsX*terra.numVertsZ],
};
m_numVertices = terra.numVertsX*terra.numVertsZ;
m_numFaces = terra.numCellsX*terra.numCellsZ*2;
DWORD *indices = new DWORD[terra.numCellsX*terra.numCellsZ*6];
for(int i = 0; i < sizeof(indices); i++)
{
indices[i] = 0;
}
D3DXVECTOR3 pos(minB.x, 0, minB.z);
int vIter = 0;
for(int z = 0; z < terra.numVertsZ; z++)
{
for(int x = 0; x < terra.numVertsX; x++)
{
terra.vertices[vIter].x = 0;
terra.vertices[vIter].y = 0;
terra.vertices[vIter].z = 0;
terra.vertices[vIter].tu = 0;
terra.vertices[vIter].tv = 0;
vIter++;
}
}
double curTexPosZ = 1.0;
vIter=0;
for(double z = 0; z < (double)terra.numVertsZ; z++)
{
pos.x = minB.x;
curTexPosZ = (double)((double)terra.numCellsZ - z) / (double)(terra.numCellsZ);
for(double x = 0; x < terra.numVertsX; x++)
{
terra.vertices[vIter].x = pos.x;
terra.vertices[vIter].y = pos.y;
terra.vertices[vIter].z = pos.z;
//terra.vertices[vIter].color = D3DCOLOR_ARGB(0,255,255,255);
terra.vertices[vIter].tu = (float)(x / (double)terra.numCellsX);
terra.vertices[vIter].tv = (float)curTexPosZ;
pos.x += terra.stepX;
vIter++;
}
pos.z += terra.stepZ;
}
assert(vIter <= terra.numVertsX*terra.numVertsZ);
vIter = 0;
int iPos =0;
for(int z =0; z< terra.numCellsZ; z++)
{
for(int x = 0; x< terra.numCellsX; x++)
{
indices[iPos] = vIter; iPos++;
indices[iPos] = vIter+terra.numVertsX; iPos++;
indices[iPos] = vIter+terra.numVertsX+1; iPos++;
indices[iPos] = vIter; iPos++;
indices[iPos] = vIter+terra.numVertsX+1; iPos++;
indices[iPos] = vIter+1; iPos++;
vIter++;
}
vIter++;
}
assert(vIter <= terra.numCellsX*terra.numCellsZ*6);
void* pVoid;
hr = m_d3ddev->CreateVertexBuffer(sizeof(VERTEXARRAY)*terra.numVertsX*terra.numVertsZ,0,
CUSTOMFVF,D3DPOOL_MANAGED,&m_terrainVertexBuffer,NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
hr = m_terrainVertexBuffer->Lock(0, 0, (void**)&pVoid, NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Lock Vertex Buffer", L"ERROR", MB_OK);
return false;
}
memcpy(pVoid, terra.vertices, sizeof(terra.vertices));
m_terrainVertexBuffer->Unlock();
hr = m_d3ddev->CreateIndexBuffer(sizeof(DWORD)*sizeof(indices),0,
D3DFMT_INDEX16, D3DPOOL_MANAGED, &m_terrainIndexBuffer, NULL);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Index Buffer", L"ERROR", MB_OK);
return false;
}
hr = m_terrainIndexBuffer->Lock(0, 0, (void**)&pVoid, 0);
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
memcpy(pVoid, indices, sizeof(indices));
if(FAILED(hr)){
MessageBox(NULL, L"Could not Create Vertex Buffer", L"ERROR", MB_OK);
return false;
}
m_terrainIndexBuffer->Unlock();
return true;
}
void CGraphics::RenderTerrain(void)
{
m_d3ddev->SetFVF(CUSTOMFVF);
m_d3ddev->SetTexture(0, m_terrainTexture);
m_d3ddev->SetStreamSource(0, m_terrainVertexBuffer, 0, sizeof(VERTEXARRAY));
m_d3ddev->SetIndices(m_terrainIndexBuffer);
m_d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP, 0, 0, m_numVertices, 0, m_numFaces);
}
3D Shapes:
#pragma once
#define CUSTOMFVF (D3DFVF_XYZ | D3DFVF_TEX1)
struct TEXTUREVERTEX {
float x, y, z, tu, tv;
};
TEXTUREVERTEX skyBox[] = {
// Front quad, NOTE: All quads face inward
{-10.0f, -10.0f, 10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, 10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, 10.0f, 1.0f, 0.0f },
// Back quad
{ 10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, {-10.0f, -10.0f, -10.0f, 1.0f, 1.0f },{-10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Left quad
{-10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, {-10.0f, -10.0f, 10.0f, 1.0f, 1.0f }, {-10.0f, 10.0f, 10.0f, 1.0f, 0.0f },
// Right quad
{ 10.0f, -10.0f, 10.0f, 0.0f, 1.0f }, { 10.0f, 10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, -10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Top quad
{-10.0f, 10.0f, 10.0f, 0.0f, 1.0f }, {-10.0f, 10.0f, -10.0f, 0.0f, 0.0f }, { 10.0f, 10.0f, 10.0f, 1.0f, 1.0f }, { 10.0f, 10.0f, -10.0f, 1.0f, 0.0f },
// Bottom quad
{-10.0f, -10.0f, -10.0f, 0.0f, 1.0f }, {-10.0f, -10.0f, 10.0f, 0.0f, 0.0f }, { 10.0f, -10.0f, -10.0f, 1.0f, 1.0f },{ 10.0f, -10.0f, 10.0f, 1.0f, 0.0f }
};
std::string fileF("skybox_front.jpg");
std::string fileB("skybox_back.jpg");
std::string fileL("skybox_left.jpg");
std::string fileR("skybox_right.jpg");
std::string fileTop("skybox_top.jpg");
std::string fileBottom("skybox_bottom.jpg");
struct VERTEXARRAY {
float x, y, z, tu, tv;
};
struct TERRAIN {
D3DXVECTOR3 minBounds; // minimum bounds (x, y, z)
D3DXVECTOR3 maxBounds; // maximum bounds (x, y, z)
int numCellsX; // # of cells in the x direction
int numCellsZ; // # of cells in the z direction
int numVertsX; // # of vertices in the x direction
int numVertsZ; // # of vertices in the z direction
float stepX; // space between vertices in the x direction
float stepZ; // space between vertices in the z direction
VERTEXARRAY *vertices; // vertex array pointer (stores the position for each vertex
};
std::string texFileTerrain("sunset.jpg");
I've looked through countless tutorials and samples online and found no solution. I imagine the problem I'm having is related to the settings, I must be overlooking something...any ideas would be appreciated...thanks in advance!