Example #1
0
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// Here we initialize our multitexturing functions
	glActiveTextureARB		= (PFNGLACTIVETEXTUREARBPROC)		wglGetProcAddress("glActiveTextureARB");
	glMultiTexCoord2fARB	= (PFNGLMULTITEXCOORD2FARBPROC)		wglGetProcAddress("glMultiTexCoord2fARB");

	// We should have our multitexturing functions defined and ready to go now, but let's make sure
	// that the current version of OpenGL is installed on the machine.  If the extension functions
	// could not be found, our function pointers will be NULL.
	if(!glActiveTextureARB || !glMultiTexCoord2fARB)
	{
		// Print a error message and quit.
		MessageBox(g_hWnd, "Your current setups does not support multitexturing", "Error", MB_OK);
		PostQuitMessage(0);
	}

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *


	// Here we read read in the height map from the .raw file and put it in our
	// g_HeightMap array.  We also pass in the size of the .raw file (1024).
	LoadRawFile("Terrain.raw", MAP_SIZE * MAP_SIZE, g_HeightMap);	

	glEnable(GL_DEPTH_TEST);							// Enables depth testing
	glEnable(GL_TEXTURE_2D);							// Enable texture mapping
	glEnable(GL_CULL_FACE);								// Turn on back face culling

	CreateTexture(g_Texture[0],			"Terrain.bmp"); // Load the terrain texture
	CreateTexture(g_Texture[1],			"Detail.bmp");
	CreateTexture(g_Texture[BACK_ID],	"Back.bmp");	// Load the Sky box Back texture
	CreateTexture(g_Texture[FRONT_ID],	"Front.bmp");	// Load the Sky box Front texture
	CreateTexture(g_Texture[BOTTOM_ID], "Bottom.bmp");	// Load the Sky box Bottom texture
	CreateTexture(g_Texture[TOP_ID],	"Top.bmp");		// Load the Sky box Top texture
	CreateTexture(g_Texture[LEFT_ID],	"Left.bmp");	// Load the Sky box Left texture
	CreateTexture(g_Texture[RIGHT_ID],	"Right.bmp");	// Load the Sky box Right texture

	// Give our camera a decent starting point in the world
	g_Camera.PositionCamera( 280, 35, 225,  281, 35, 225,  0, 1, 0);
}
Example #2
0
int COpenGLView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CView::OnCreate(lpCreateStruct) == -1)
		return -1;

	// TODO:  Add your specialized creation code here
	m_pDC = new CClientDC(this);
// 	SetTimer(1,50,NULL);
	camPos[0]=0;
	camPos[1]=0;
	camPos[2]=-250;
	camRot[0]=30;
	camRot[1]=135;
	camRot[2]=0;
	InitializeOpenGL(m_pDC);
	return 0;
}
void FsOpenWindow(int x0,int y0,int wid,int hei,int useDoubleBuffer)
{
	// Note 2012/03/08 RegisterClassW and CreateWindowW doesn't seem to work.
	WNDCLASSA wc;
	HINSTANCE inst=GetModuleHandleA(NULL);

	wc.style=CS_OWNDC|CS_BYTEALIGNWINDOW;
	wc.lpfnWndProc=(WNDPROC)WindowFunc;
	wc.cbClsExtra=0;
	wc.cbWndExtra=0;
	wc.hInstance=(HINSTANCE)inst;
	wc.hIcon=LoadIconA(inst,"MAINICON");
	wc.hCursor=LoadCursor(NULL,IDC_ARROW);
	wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName=NULL;
	wc.lpszClassName=WINCLASS;
	if(0!=RegisterClassA(&wc))
	{
		doubleBuffer=useDoubleBuffer;


		RECT rc;
		rc.left  =x0;
		rc.top   =y0;
		rc.right =(unsigned long)(x0+wid-1);
		rc.bottom=(unsigned long)(y0+hei-1);
		AdjustWindowRect(&rc,WINSTYLE,FALSE);
		wid  =rc.right-rc.left+1;
		hei  =rc.bottom-rc.top+1;

		fsWin32Internal.hWnd=CreateWindowA(WINCLASS,WINNAME,WINSTYLE,x0,y0,wid,hei,NULL,NULL,inst,NULL);
		if(NULL!=fsWin32Internal.hWnd)
		{
			InitializeOpenGL(fsWin32Internal.hWnd);

			ShowWindow(fsWin32Internal.hWnd,SW_SHOWNORMAL);
			UpdateWindow(fsWin32Internal.hWnd);
		}
		else
		{
			printf("Could not open window.\n");
			exit(1);
		}
	}
}
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect

//////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** ////////////////////

	// First we need to actually load the .ASE file.  We just pass in an address to
	// our t3DModel structure and the file name string we want to load ("Statue.Ase").

	g_LoadASE.ImportASE(&g_3DModel, FILE_NAME);			// Load our .Ase file into our model structure

	// Depending on how many textures we found, load each one (Assuming .BMP)
	// If you want to load other files than bitmaps, you will need to adjust CreateTexture().
	// Below, we go through all of the materials and check if they have a texture map to load.
	// Otherwise, the material just holds the color information and we don't need to load a texture.

	// Go through all the materials
	for(int i = 0; i < g_3DModel.numOfMaterials; i++)
	{
		// Check to see if there is a file name to load in this material
		if(strlen(g_3DModel.pMaterials[i].strFile) > 0)
		{
			// Use the name of the texture file to load the bitmap, with a texture ID (i).
			// We pass in our global texture arrow, the name of the texture, and an ID to reference it.	
			CreateTexture(g_Texture, g_3DModel.pMaterials[i].strFile, i);			
		}

		// Set the texture ID for this material
		g_3DModel.pMaterials[i].texureId = i;
	}

	// Here, we turn on a lighting and enable lighting.  We don't need to
	// set anything else for lighting because we will just take the defaults.
	// We also want color, so we turn that on

	glEnable(GL_LIGHT0);							// Turn on a light with defaults set
	glEnable(GL_LIGHTING);							// Turn on lighting
	glEnable(GL_COLOR_MATERIAL);					// Allow color

//////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** ////////////////////

}
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect

//////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** ////////////////////

	// Below we call our init function for our camera.  We pass in the
	// starting position of our last tutorial where we are looking dead
	// on at the color triangle.  I added .5 to the Y since the last tutorial.
	// Remember, we only need to init this stuff ONCE, then we never call this again.

						// Position        View		   Up Vector
	g_Camera.PositionCamera(0, 0.5f, 6,   0, 0.5f, 0,   0, 1, 0);

//////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** ////////////////////

}
Example #6
0
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// After we initialize OpenGL, we want to create our font.  I chose "Arial".
	// We also can pass in a font height.  The width will be chosen according to the height.
	// This then returns the base pointer to the display list for our font.  (Should be 1)
	// We need to be sure and use this to free our display list in DestroyFont().

	g_FontListID = CreateOpenGLFont("Arial", FONT_HEIGHT);

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

}
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// This is where we load all of our textures.  We are loading
	// just one in this case, but you can add many more if you want.
	// We pass in our global textureArray, our file we want to load, 
	// and the texture ID we want associated with it.

	// Load "Image.tga" into OpenGL as a texture
	CreateTexture(g_Texture, "Image.tga", 0);			

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

}
Example #8
0
void Init(HWND hWnd)
{
    g_hWnd = hWnd;										// Assign the window handle to a global window handle
    GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
    InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

    // Here we initialize our multi-texturing functions
    glActiveTextureARB		= (PFNGLACTIVETEXTUREARBPROC)		wglGetProcAddress("glActiveTextureARB");
    glMultiTexCoord2fARB	= (PFNGLMULTITEXCOORD2FARBPROC)		wglGetProcAddress("glMultiTexCoord2fARB");

    // Make sure our multi-texturing extensions were loaded correctly
    if(!glActiveTextureARB || !glMultiTexCoord2fARB)
    {
        // Print an error message and quit.
        MessageBox(g_hWnd, "Your current setup does not support multitexturing", "Error", MB_OK);
        PostQuitMessage(0);
    }

    // Tell OpenGL our light's position
    glLightfv( GL_LIGHT0, GL_POSITION, g_LightPosition );

    // This turns the background to a dark grey/black.
    glClearColor(0.2f, 0.2f, 0.2f, 1.0f);

    // Turn on our light and enable color along with the light
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);

    // Here we allocate memory for our depth texture that will store our light's view.
    // We must set the channels and type for the texture as GL_DEPTH_COMPONENT.
    CreateRenderTexture(g_Texture, SHADOW_WIDTH, SHADOW_HEIGHT, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, SHADOW_ID);

    // Set the camera:		Position		View		 Up Vector
    g_Camera.PositionCamera(0, 9, 12,     0, 2.5, -2,     0, 1, 0);

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *


}
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect
		
	// Below we read in the 6 texture maps used for the sky box.
	// The ID's are important, so don't mix them up.  There is a
	// texture for every side of the box.

	CreateTexture(g_Texture, "Back.bmp",	BACK_ID		);
	CreateTexture(g_Texture, "Front.bmp",	FRONT_ID	);
	CreateTexture(g_Texture, "Bottom.bmp",	BOTTOM_ID	);
	CreateTexture(g_Texture, "Top.bmp",		TOP_ID		);
	CreateTexture(g_Texture, "Left.bmp",	LEFT_ID		);
	CreateTexture(g_Texture, "Right.bmp",	RIGHT_ID	);

	// Give our camera a decent starting point in the world
	g_Camera.PositionCamera( 0, 0, 0,	0, 0, 1,	0, 1, 0);
}
Example #10
0
/*
===========================
Init
Use this for initialization
===========================
*/
void Init( HWND hwnd ) {
	/* Window initialization */
	ghwnd = hwnd;
	GetClientRect( ghwnd, &gRect );                // get rect into our handy global rect
	InitializeOpenGL( gRect.right, gRect.bottom ); // initialise openGL

	/* OpenGL settings */
	glShadeModel( GL_SMOOTH );							           // enable smooth shading
	glClearColor( 1.0f, 0.0f, 1.0f, 0.5f );				           // black background
	glClearDepth( 1.0f );								           // depth buffer setup
	glEnable( GL_DEPTH_TEST );							           // enables depth testing
	glDepthFunc( GL_LEQUAL );							           // the type of depth testing to do
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );           // really nice perspective calculations
	glEnable( GL_LIGHTING );
	glClearStencil( 0 );
	glEnable( GL_TEXTURE_2D );							           // enable texturing!
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); // specify texture calculation

	/* Also, do any other setting ov variables here for your app if you wish */
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); // linear filtering
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // linear filtering
}
Example #11
0
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// Let's init our GLSL functions and make sure this computer can run the program.
	InitGLSL();

	// Here we pass in our vertex and fragment shader files to our shader object.
	g_Shader.InitShaders("morph.vert", "morph.frag");

	// Now we want to get the variable "time" in the morph.vert file so we can update it.
	g_TimeLoc = g_Shader.GetVariable("time");

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *


}
Example #12
0
    bool RenderPass::Initialize(Framework::Window* window)
    {
        if(window)
            SetWindow(window);
        
        if(!m_window)
            return false;

        if(!m_initialized && !(*m_referenceCounter))
        {
            *m_referenceCounter = 1;

            auto sdlWindow = (SDL_Window*)m_window->GetSDLWindow();
            m_glContext = SDL_GL_CreateContext(sdlWindow);
            if(!m_glContext)
            {
                // SDL_GetError(); to ErrorLog
                return false;
            }

            auto glewError = glewInit();
            if(glewError != GLEW_OK)
            {
                // ErrorLog
                return false;
            }

            if(!InitializeOpenGL())
            {
                // ErrorLog
                return false;
            }

            m_initialized = true;
        }

        return m_glContext != NULL;
    }
Example #13
0
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
	
	// Here we read read in the height map from the .raw file and put it in our
	// g_HeightMap array.  We also pass in the size of the .raw file (1024).

	LoadRawFile("Terrain.raw", MAP_SIZE * MAP_SIZE, g_HeightMap);	

	// Here we set the camera in a obscure position to get a 
	// good outside view of the terrain.  

	// Give our camera a decent starting point in the world
	g_Camera.PositionCamera(1200, 300, 1150,  1199, 300, 1150,  0, 1, 0);

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

}
Example #14
0
RenderContext *RenderInit(GameAssets *assets, MemorySegment memory) {
    AllocMemory(&memory, sizeof(RenderContext));

    RenderContext *ctx = (RenderContext*)memory.base;
    ctx->initialized = 0;
    ctx->rendering = 0;
    ctx->memory = memory;

    InitializeOpenGL(assets);
    LoadTextures(assets, ctx);

    // Allocate memory buffer
    u32 vertex_size = sizeof(RenderVertex) * 4;
    u32 available_memory = (memory.size - memory.used) / vertex_size;
    MemorySegment vertex_segment = AllocMemory(&memory, available_memory);

    ctx->entriesMax = available_memory / vertex_size;
    ctx->entriesCount = 0;
    ctx->vertexBuffer = vertex_segment;

    ctx->initialized = 1;
    return ctx;
}
Example #15
0
void Scene3D::Init(HWND* wnd, Input* in, Camera* cam)
{
	hwnd = wnd;
	input = in;
	//Camera
	camera = cam;
	camera->Init(0.0f, 4.0f, 7.0f, 0.0f, 0.0f, 0.0f);
	//OpenGL settings
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
	glClearStencil(0);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations#
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	speed = 4.0f;
	sensitivity = 10.0f;
	GetClientRect(*hwnd, &screenRect);	//get rect into our handy global rect
	InitializeOpenGL(screenRect.right, screenRect.bottom); // initialise openGL
	application_ = new Application(in);
}
Example #16
0
static LONG WINAPI WindowFunc(HWND hWnd,UINT msg,WPARAM wp,LPARAM lp)
{
	switch(msg)
	{
	case WM_QUERYNEWPALETTE:
	case WM_PALETTECHANGED:
		if(NULL!=fsWin32Internal.hPlt)
		{
			SelectPalette(fsWin32Internal.hDC,fsWin32Internal.hPlt,FALSE);
			RealizePalette(fsWin32Internal.hDC);
		}
		return DefWindowProc(hWnd,msg,wp,lp);
	case WM_CREATE:
		fsWin32Internal.hDC=GetDC(hWnd);
		YsSetPixelFormat(fsWin32Internal.hDC);
		fsWin32Internal.hRC=wglCreateContext(fsWin32Internal.hDC);
		wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC);
		if(0==doubleBuffer)
		{
			glDrawBuffer(GL_FRONT);
		}
		InitializeOpenGL(hWnd);
		break;
	case WM_SIZE:
		wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC);
		break;
	case WM_PAINT:
		wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC);
		exposure=1;
		return DefWindowProc(hWnd,msg,wp,lp);
	case WM_COMMAND:
		break;
	case WM_DESTROY:
		exit(1);
		break;
	case WM_MOUSEWHEEL:
		{
			int step;
			step=HIWORD(wp);
			if(step>=0x8000)
			{
				step-=0x10000;
			}
			step/=WHEEL_DELTA;
			if(step>0)
			{
				while(step>0)
				{
					if(nKeyBufUsed<NKEYBUF)
					{
						keyBuffer[nKeyBufUsed++]=FSKEY_WHEELUP;
					}
					step--;
				}
			}
			else if(step<0)
			{
				while(step<0)
				{
					if(nKeyBufUsed<NKEYBUF)
					{
						keyBuffer[nKeyBufUsed++]=FSKEY_WHEELDOWN;
					}
					step++;
				}
			}
		}
		break;
	case WM_SYSKEYDOWN:
		if((lp & (1<<29))!=0 && // Alt
		  (wp==VK_MENU ||
		   wp==VK_OEM_1 ||
		   wp==VK_OEM_PLUS ||
		   wp==VK_OEM_COMMA ||
		   wp==VK_OEM_MINUS ||
		   wp==VK_OEM_PERIOD ||
		   wp==VK_OEM_2 ||
		   wp==VK_OEM_3 ||
		   wp==VK_OEM_4 ||
		   wp==VK_OEM_5 ||
		   wp==VK_OEM_6 ||
		   wp==VK_OEM_7 ||
		   wp==VK_OEM_8 ||
#ifdef VK_OEM_AX
		   wp==VK_OEM_AX ||
#endif
		   wp==VK_OEM_102 ||
		   wp=='0' ||
		   wp=='1' ||
		   wp=='2' ||
		   wp=='3' ||
		   wp=='4' ||
		   wp=='5' ||
		   wp=='6' ||
		   wp=='7' ||
		   wp=='8' ||
		   wp=='9' ||
		   wp=='A' ||
		   wp=='B' ||
		   wp=='C' ||
		   wp=='D' ||
		   wp=='E' ||
		   wp=='F' ||
		   wp=='G' ||
		   wp=='H' ||
		   wp=='I' ||
		   wp=='J' ||
		   wp=='K' ||
		   wp=='L' ||
		   wp=='M' ||
		   wp=='N' ||
		   wp=='O' ||
		   wp=='P' ||
		   wp=='Q' ||
		   wp=='R' ||
		   wp=='S' ||
		   wp=='T' ||
		   wp=='U' ||
		   wp=='V' ||
		   wp=='W' ||
		   wp=='X' ||
		   wp=='Y' ||
		   wp=='Z' ||
		   wp==VK_ESCAPE ||
		   wp==VK_F1 ||
		   wp==VK_F2 ||
		   wp==VK_F3 ||
		   /* wp==VK_F4 || */
		   wp==VK_F5 ||
		   wp==VK_F6 ||
		   wp==VK_F7 ||
		   wp==VK_F8 ||
		   wp==VK_F9 ||
		   wp==VK_F10 ||
		   wp==VK_F11 ||
		   wp==VK_F12 ||
		   wp==VK_RETURN ||
		   wp==VK_NUMLOCK ||
		   wp==VK_NUMPAD0 ||
		   wp==VK_NUMPAD1 ||
		   wp==VK_NUMPAD2 ||
		   wp==VK_NUMPAD3 ||
		   wp==VK_NUMPAD4 ||
		   wp==VK_NUMPAD5 ||
		   wp==VK_NUMPAD6 ||
		   wp==VK_NUMPAD7 ||
		   wp==VK_NUMPAD8 ||
		   wp==VK_NUMPAD9 ||
		   wp==VK_DECIMAL ||
		   wp==VK_DIVIDE ||
		   wp==VK_MULTIPLY ||
		   wp==VK_SUBTRACT ||
		   wp==VK_ADD))
		{
			int keyCode;
			keyCode=fsKeyMapper.VkToFsKey(wp);
			if(keyCode!=0 && nKeyBufUsed<NKEYBUF)
			{
				keyBuffer[nKeyBufUsed++]=keyCode;
			}
			return 0;
		}
		return DefWindowProc(hWnd,msg,wp,lp);
	case WM_SYSKEYUP:
		return 0;
	case WM_KEYDOWN:
		if(nKeyBufUsed<NKEYBUF)
		{
			int keyCode;
			keyCode=fsKeyMapper.VkToFsKey(wp);
			if(keyCode!=0)
			{
				keyBuffer[nKeyBufUsed++]=keyCode;
			}
		}
		break;
	case WM_CHAR:
		if(nCharBufUsed<NKEYBUF)
		{
			charBuffer[nCharBufUsed++]=wp;
		}
		break;
	case WM_ERASEBKGND:
		return 1;

	case WM_LBUTTONDOWN:
	case WM_LBUTTONUP:
	case WM_MBUTTONDOWN:
	case WM_MBUTTONUP:
	case WM_RBUTTONDOWN:
	case WM_RBUTTONUP:
	case WM_MOUSEMOVE:
		if(nMosBufUsed<NKEYBUF)
		{
			int eventType;
			switch(msg)
			{
			default:
				eventType=FSMOUSEEVENT_NONE;
				break;
			case WM_LBUTTONDOWN:
				eventType=FSMOUSEEVENT_LBUTTONDOWN;
				break;
			case WM_LBUTTONUP:
				eventType=FSMOUSEEVENT_LBUTTONUP;
				break;
			case WM_MBUTTONDOWN:
				eventType=FSMOUSEEVENT_MBUTTONDOWN;
				break;
			case WM_MBUTTONUP:
				eventType=FSMOUSEEVENT_MBUTTONUP;
				break;
			case WM_RBUTTONDOWN:
				eventType=FSMOUSEEVENT_RBUTTONDOWN;
				break;
			case WM_RBUTTONUP:
				eventType=FSMOUSEEVENT_RBUTTONUP;
				break;
			case WM_MOUSEMOVE:
				eventType=FSMOUSEEVENT_MOVE;
				break;
			}

			int lb=((wp & MK_LBUTTON)!=0);
			int mb=((wp & MK_MBUTTON)!=0);
			int rb=((wp & MK_RBUTTON)!=0);
			unsigned int shift=((wp & MK_SHIFT)!=0);
			unsigned int ctrl=((wp & MK_CONTROL)!=0);
			int mx=LOWORD(lp);
			int my=HIWORD(lp);

			if(eventType==FSMOUSEEVENT_MOVE &&
			   0<nMosBufUsed &&
			   mosBuffer[nMosBufUsed-1].eventType==FSMOUSEEVENT_MOVE &&
			   mosBuffer[nMosBufUsed-1].lb==lb &&
			   mosBuffer[nMosBufUsed-1].mb==mb &&
			   mosBuffer[nMosBufUsed-1].rb==rb &&
			   mosBuffer[nMosBufUsed-1].shift==shift &&
			   mosBuffer[nMosBufUsed-1].ctrl==ctrl)
			{
				mosBuffer[nMosBufUsed-1].mx=mx;
				mosBuffer[nMosBufUsed-1].my=my;
				break;
			}

			mosBuffer[nMosBufUsed].eventType=eventType;
			mosBuffer[nMosBufUsed].lb=lb;
			mosBuffer[nMosBufUsed].mb=mb;
			mosBuffer[nMosBufUsed].rb=rb;
			mosBuffer[nMosBufUsed].shift=shift;
			mosBuffer[nMosBufUsed].ctrl=ctrl;
			mosBuffer[nMosBufUsed].mx=mx;
			mosBuffer[nMosBufUsed].my=my;
			nMosBufUsed++;
		}
		break;

	default:
		return DefWindowProc(hWnd,msg,wp,lp);
	}
	return 1;
}
Example #17
0
void FsOpenWindow(int x0,int y0,int wid,int hei,int useDoubleBuffer)
{
	if(NULL!=fsWin32Internal.hWnd)
	{
		MessageBoxA(fsWin32Internal.hWnd,"Error! Window already exists.","Error!",MB_OK);
		exit(1);
	}

	// Note 2012/03/08 RegisterClassW and CreateWindowW doesn't seem to work.
	WNDCLASSA wc;
	HINSTANCE inst=GetModuleHandleA(NULL);

	wc.style=CS_OWNDC|CS_BYTEALIGNWINDOW;
	wc.lpfnWndProc=(WNDPROC)WindowFunc;
	wc.cbClsExtra=0;
	wc.cbWndExtra=0;
	wc.hInstance=(HINSTANCE)inst;
	wc.hIcon=LoadIconA(inst,"MAINICON");
	wc.hCursor=LoadCursor(NULL,IDC_ARROW);
	wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName=NULL;
	wc.lpszClassName=WINCLASS;
	if(0!=RegisterClassA(&wc))
	{
		doubleBuffer=useDoubleBuffer;


		RECT rc;
		rc.left  =x0;
		rc.top   =y0;
		rc.right =(unsigned long)(x0+wid-1);
		rc.bottom=(unsigned long)(y0+hei-1);
		AdjustWindowRect(&rc,WINSTYLE,FALSE);
		wid  =rc.right-rc.left+1;
		hei  =rc.bottom-rc.top+1;

#ifdef _UNICODE
		// What's the point of using CreateWindowA?  Another weird Microsoft logic here.
		static wchar_t buf[256];
		const char *windowNameA=(const char *)WINNAME;
		for(int i=0; i<255 && 0!=windowNameA[i]; ++i)
		{
			buf[i]=windowNameA[i];
			buf[i+1]=0;
		}
		const char *windowNameUsed=(const char *)buf;
#else
		const char *windowNameUsed=(const char *)WINNAME;
#endif

		fsWin32Internal.hWnd=CreateWindowA(WINCLASS,windowNameUsed,WINSTYLE,x0,y0,wid,hei,NULL,NULL,inst,NULL);
		if(NULL!=fsWin32Internal.hWnd)
		{
			InitializeOpenGL(fsWin32Internal.hWnd);

			ShowWindow(fsWin32Internal.hWnd,SW_SHOWNORMAL);
			UpdateWindow(fsWin32Internal.hWnd);

			FsPassedTime();  // Reset Timer
		}
		else
		{
			printf("Could not open window.\n");
			exit(1);
		}
	}
}
Example #18
0
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect

	// Here we open the config file and init some variables
	ifstream fin("Config.ini");
	string strLevel = "";
	string strTemp = "";

	// Check if the file was not found or could not be opened
	if(fin.fail())
	{
		// Display an error message and quit the program if file wasn't found
		MessageBox(g_hWnd, "Could not find Config.ini file!", "Error", MB_OK);
		PostQuitMessage(0);
		return;
	}

	// Read in the name of the level that will be loaded 
	fin >> strLevel >> strLevel;


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
	
	// Now we need to read in the gamma level for our lightmaps
	fin >> strTemp  >> g_Gamma;

	// Initialize the multitexturing function pointers
	glActiveTextureARB		 = (PFNGLACTIVETEXTUREARBPROC)	 wglGetProcAddress("glActiveTextureARB");
    glClientActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)   wglGetProcAddress("glClientActiveTextureARB");

	// Here we make sure that the functions were loaded properly
	if(!glActiveTextureARB || !glClientActiveTextureARB)
	{
		// Display an error message and quit
		MessageBox(g_hWnd, "Your video card doesn't support multitexturing", "Error", MB_OK);
		PostQuitMessage(0);
	}

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// Close the file
	fin.close();

	// Here we load the level and get the result (true == success)
	bool bResult = g_Level.LoadBSP(strLevel.c_str());

	// Make sure the file was found and we received a success
	if(bResult == false)
	{
		// Quit the application
		PostQuitMessage(0);
		return;
	}

	// Position the camera to the starting point since we have
	// not read in the entities yet, which gives the starting points.
	g_Camera.PositionCamera( 80, 288, 16,	80, 288, 17,	0, 1, 0);

	// Turn on depth testing and texture mapping
	glEnable(GL_DEPTH_TEST);	
	glEnable(GL_TEXTURE_2D);

	// Enable front face culling, since that's what Quake3 does
	glCullFace(GL_FRONT);
 	glEnable(GL_CULL_FACE);
}
Example #19
0
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect

	// Here we initialize our multitexturing functions
	glActiveTextureARB		= (PFNGLACTIVETEXTUREARBPROC)		wglGetProcAddress("glActiveTextureARB");
	glMultiTexCoord2fARB	= (PFNGLMULTITEXCOORD2FARBPROC)		wglGetProcAddress("glMultiTexCoord2fARB");

	// We should have our multitexturing functions defined and ready to go now, but let's make sure
	// that the current version of OpenGL is installed on the machine.  If the extension functions
	// could not be found, our function pointers will be NULL.
	if(!glActiveTextureARB || !glMultiTexCoord2fARB)
	{
		// Print an error message and quit.
		MessageBox(g_hWnd, "Your current setup does not support multitexturing", "Error", MB_OK);
		PostQuitMessage(0);
	}


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// If we have loaded the mulitextures correctly, then we can now test to see
	// if the video card supports hardware accelerated fog.  We do the same things
	// for every extension.  First we tell wglGetProcAddress() which extension
	// we want, which then returns a function pointer.  Afterwards, the function
	// pointer is checked to make sure the current video card drivers or setup
	// support it.

	// Find the correct function pointer that houses the fog coordinate function
	glFogCoordfEXT	= (PFNGLFOGCOORDFEXTPROC) wglGetProcAddress("glFogCoordfEXT");

	// Before trying to use this function pointer, we need to make sure it was
	// given a valid address.  If not, then we need to quit because something is wrong.
	if(!glFogCoordfEXT)
	{
		// Print an error message and quit.
		MessageBox(g_hWnd, "Your current setup does not support volumetric fog", "Error", MB_OK);
		PostQuitMessage(0);
	}

	// It is assumed that by getting here, we should be able to do volumetric fog
	// with this video card.  Now comes the setup and initialization.  Just like
	// when we create normal fog, we need to turn on GL_FOG, give a fog color,
	// as well as give the start and end distance for the thickness of the fog.
	// The new information that will need to be given will be to glFogi().
	// The new flags we defined tell OpenGL that we want per vertex fog.
	// Notice that we don't use GL_FOG_DENSITY.  It doesn't seem to have any effect.

	// Pick a tan color for our fog with a full alpha
	float fogColor[4] = {0.8f, 0.8f, 0.8f, 1.0f};

	glEnable(GL_FOG);						// Turn on fog
	glFogi(GL_FOG_MODE, GL_LINEAR);			// Set the fog mode to LINEAR (Important)
	glFogfv(GL_FOG_COLOR, fogColor);		// Give OpenGL our fog color
	glFogf(GL_FOG_START, 0.0);				// Set the start position for the depth at 0
	glFogf(GL_FOG_END, 50.0);				// Set the end position for the detph at 50

	// Now we tell OpenGL that we are using our fog extension for per vertex
	// fog calculations.  For each vertex that needs fog applied to it we must
	// use the glFogCoordfEXT() function with a depth value passed in.
	// These flags are defined in main.h and are not apart of the normal opengl headers.
	glFogi(GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT);


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *


	// Here we read in the height map from the .raw file and put it in our
	// g_HeightMap array.  We also pass in the size of the .raw file (1024).
	LoadRawFile("Terrain.raw", MAP_SIZE * MAP_SIZE, g_HeightMap);	

	glEnable(GL_DEPTH_TEST);							// Enables depth testing
	glEnable(GL_TEXTURE_2D);							// Enable texture mapping
	glEnable(GL_CULL_FACE);								// Turn on back face culling

	CreateTexture(g_Texture[0],			"Terrain.bmp"); // Load the terrain texture
	CreateTexture(g_Texture[1],			"Detail.bmp");
	CreateTexture(g_Texture[BACK_ID],	"Back.bmp");	// Load the Sky box Back texture
	CreateTexture(g_Texture[FRONT_ID],	"Front.bmp");	// Load the Sky box Front texture
	CreateTexture(g_Texture[BOTTOM_ID], "Bottom.bmp");	// Load the Sky box Bottom texture
	CreateTexture(g_Texture[TOP_ID],	"Top.bmp");		// Load the Sky box Top texture
	CreateTexture(g_Texture[LEFT_ID],	"Left.bmp");	// Load the Sky box Left texture
	CreateTexture(g_Texture[RIGHT_ID],	"Right.bmp");	// Load the Sky box Right texture

	// Give our camera a decent starting point in the world
	g_Camera.PositionCamera( 280, 35, 225,  281, 35, 225,  0, 1, 0);
}
Example #20
0
int WINAPI WinMain( HINSTANCE hinstance,
	HINSTANCE hprevinstance,
	LPSTR lpcmdline,
	int ncmdshow)
{
	WNDCLASS	winclass;	// this will hold the class we create
	HWND		hwnd;		// generic window handle
	MSG			msg;		// generic message

	// first fill in the window class stucture
	winclass.style			= CS_HREDRAW | CS_VREDRAW;                  
	winclass.lpfnWndProc	= WindowProc;
	winclass.cbClsExtra		= 0;
	winclass.cbWndExtra		= 0;
	winclass.hInstance		= hinstance;
	winclass.hIcon			= LoadIcon(NULL, IDI_APPLICATION);
	winclass.hCursor		= LoadCursor(NULL, IDC_ARROW);
	winclass.hbrBackground  = (HBRUSH)GetStockObject(BLACK_BRUSH);
	winclass.lpszMenuName	= NULL;
	winclass.lpszClassName	= "WindowCreation";

	// register the window class
	if (!RegisterClass(&winclass))
		return(0);

	// create the window
	if (!(hwnd = CreateWindow( "WindowCreation", // class
		TITLE,	     // title
		WS_OVERLAPPEDWINDOW | WS_VISIBLE,
		0,
		0,
		//Set the size of the window to the size of the screen 
		600,
		400,
		//GetSystemMetrics(SM_CXSCREEN),
		//GetSystemMetrics(SM_CYSCREEN),
		NULL,	   // handle to parent 
		NULL,	   // handle to menu
		hinstance,	// instance
		NULL)))	// creation parms
		return(0);
#ifdef USEOPENGL
	InitializeOpenGL(hwnd, 600, 400);
#else
	InitializeDX(hwnd, 600, 400);
#endif
	
	//
// 	SayHello hello222;
// 	hello222.DisplayHelloMessage();

	// enter main event loop
	bool quit = false;
	while(!quit)
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{ 
			// test if this is a quit
			if (msg.message == WM_QUIT) quit = true;

			// translate any accelerator keys
			TranslateMessage(&msg);
			// send the message to the window proc
			DispatchMessage(&msg);
		} // end if
		else {
			/************************************************************************/
			/* do some main logic control                                                                     */
			/************************************************************************/
/**
try
{
	//throw ErrorException(1,"this is my error",__FILE__, __LINE__);
}
catch (ErrorException& e)
{
	ErrorManager* log = ErrorManager::GetInstance();
	log->Create("testlog.txt");
	log->Output("**Error**");
	log->LogException(e);
	log->Output("*********");
	log->Close();
}
*/
#ifdef USEOPENGL
			RenderOpenGL();
#else
			RenderDX();
#endif

			
		}

	} // end while

	// return to Windows like this
	return(msg.wParam);

} // end WinMain
Example #21
0
int main (int argc, const char** argv)
{
	if (argc < 2)
	{
		printf ("USAGE: glsloptimizer testfolder\n");
		return 1;
	}

	bool hasOpenGL = InitializeOpenGL ();
	glslopt_ctx* ctx[2] = {
		glslopt_initialize(true),
		glslopt_initialize(false),
	};

	std::string baseFolder = argv[1];

	clock_t time0 = clock();

	static const char* kTypeName[2] = { "vertex", "fragment" };
	size_t tests = 0;
	size_t errors = 0;
	for (int type = 0; type < 2; ++type)
	{
		std::string testFolder = baseFolder + "/" + kTypeName[type];

		static const char* kAPIName[2] = { "OpenGL ES 2.0", "OpenGL" };
		static const char* kApiIn [2] = {"-inES.txt", "-in.txt"};
		static const char* kApiIR [2] = {"-irES.txt", "-ir.txt"};
		static const char* kApiOut[2] = {"-outES.txt", "-out.txt"};
		for (int api = 0; api < 2; ++api)
		{
			printf ("\n** running %s tests for %s...\n", kTypeName[type], kAPIName[api]);
			StringVector inputFiles = GetFiles (testFolder, kApiIn[api]);

			size_t n = inputFiles.size();
			for (size_t i = 0; i < n; ++i)
			{
				std::string inname = inputFiles[i];
				//if (inname != "ast-in.txt")
				//	continue;
				std::string hirname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiIR[api];
				std::string outname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiOut[api];
				bool ok = TestFile (ctx[api], type==0, inname, testFolder + "/" + inname, testFolder + "/" + hirname, testFolder + "/" + outname, api==0, hasOpenGL);
				if (!ok)
				{
					++errors;
				}
				++tests;
			}
		}
	}
	clock_t time1 = clock();
	float timeDelta = float(time1-time0)/CLOCKS_PER_SEC;

	if (errors != 0)
		printf ("\n**** %i tests (%.2fsec), %i !!!FAILED!!!\n", tests, timeDelta, errors);
	else
		printf ("\n**** %i tests (%.2fsec) succeeded\n", tests, timeDelta);
	
	// 3.25s
	// with builtin call linking, 3.84s

	for (int i = 0; i < 2; ++i)
		glslopt_cleanup (ctx[i]);

	return errors ? 1 : 0;
}
Example #22
0
int main (int argc, const char** argv)
{
	if (argc < 2)
	{
		printf ("USAGE: hlsl2glsltest testfolder\n");
		return 1;
	}

	bool hasOpenGL = InitializeOpenGL ();
	if (!hasOpenGL)
		printf("NOTE: will not check GLSL with actual driver (no GL/GLSL)\n");
	
	clock_t time0 = clock();
	
	Hlsl2Glsl_Initialize ();

	std::string baseFolder = argv[1];

	size_t tests = 0;
	size_t errors = 0;
	for (int type = 0; type < NUM_RUN_TYPES; ++type)
	{
		printf ("TESTING %s...\n", kTypeName[type]);
		const ETargetVersion version1 = kTargets1[type];
		const ETargetVersion version2 = kTargets2[type];
		const ETargetVersion version3 = kTargets3[type];
		std::string testFolder = baseFolder + "/" + kTypeName[type];
		StringVector inputFiles = GetFiles (testFolder, "-in.txt");

		size_t n = inputFiles.size();
		tests += n;
		for (size_t i = 0; i < n; ++i)
		{
			std::string inname = inputFiles[i];
			//if (inname != "_zzz-in.txt")
			//	continue;
			const bool preprocessorTest = (inname.find("pp-") == 0);
			bool ok = true;
			
			printf ("test %s\n", inname.c_str());
			if (type == BOTH) {
				ok = TestCombinedFile(testFolder + "/" + inname, version1, hasOpenGL);
				if (ok && version2 != ETargetVersionCount)
					ok = TestCombinedFile(testFolder + "/" + inname, version2, hasOpenGL);
			} else {
				ok = TestFile(TestRun(type), testFolder + "/" + inname, version1, 0, hasOpenGL);
				if (!preprocessorTest)
				{
					if (ok && version2 != ETargetVersionCount)
						ok = TestFile(TestRun(type), testFolder + "/" + inname, version2, ETranslateOpEmitGLSL120ArrayInitWorkaround, hasOpenGL);
					if (ok && version3 != ETargetVersionCount)
						ok = TestFile(TestRun(type), testFolder + "/" + inname, version3, 0, hasOpenGL);
				}
			}
			
			if (!ok)
				++errors;
		}		
	}

	clock_t time1 = clock();
	float t = float(time1-time0) / float(CLOCKS_PER_SEC);
	if (errors != 0)
		printf ("%i tests, %i FAILED, %.2fs\n", (int)tests, (int)errors, t);
	else
		printf ("%i tests succeeded, %.2fs\n", (int)tests, t);
	
	Hlsl2Glsl_Shutdown();
	CleanupOpenGL();

	return errors ? 1 : 0;
}
Example #23
0
bool Display::CreateNewWindow() {
	RegisterWindowClass();

	// Center Window on Display
	int posX = ( GetSystemMetrics(SM_CXSCREEN) / 2 ) - ( mScreenWidth / 2 );
	int posY = ( GetSystemMetrics(SM_CYSCREEN) / 2 ) - ( mScreenHeight / 2 );

	DWORD wndStyle = WS_OVERLAPPEDWINDOW;

	if ( mFullscreen == 1 ){
		DEVMODE fsSettings;
		memset( &fsSettings, 0, sizeof( DEVMODE ) );
		fsSettings.dmSize				= sizeof( DEVMODE );
		fsSettings.dmPelsHeight			= mScreenHeight;
		fsSettings.dmPelsWidth			= mScreenWidth;
		fsSettings.dmBitsPerPel			= mScreenDepth;
		fsSettings.dmDisplayFrequency	= 60;
		fsSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;

		long result = ChangeDisplaySettings( &fsSettings, CDS_FULLSCREEN );
		if ( result != DISP_CHANGE_SUCCESSFUL ) {
			DebugMessage( "Error: Could not initialize fullscreen mode.", 1 );
			if ( result == DISP_CHANGE_BADDUALVIEW )
				DebugMessage( "Fullscreen was unsuccessful: System is DualView capable.", 1 );
			if ( result == DISP_CHANGE_BADFLAGS )
				DebugMessage( "Fullscreen was unsuccessful: An invalid set of flags were passed in.", 1 );
			if ( result == DISP_CHANGE_BADMODE )
				DebugMessage( "Fullscreen was unsuccessful: The system does not support Fullscreen.", 1 );
			if ( result == DISP_CHANGE_BADPARAM )
				DebugMessage( "Fullscreen was unsuccessful: An invalid parameter was passed in.", 1 );
			if ( result == DISP_CHANGE_FAILED )
				DebugMessage( "Fullscreen was unsuccessful: The GPU does not support Fullscreen.", 1 );
			if ( result == DISP_CHANGE_NOTUPDATED )
				DebugMessage( "Fullscreen was unsuccessful: Unable to write settings to the registry.", 1 );
			if ( result == DISP_CHANGE_RESTART )
				DebugMessage( "Fullscreen was unsuccessful: Restart Required for changes to take effect.", 1 );
		} else {
			wndStyle	= WS_POPUP;
			posX		= 0;
			posY		= 0;
		}
	}

	DebugMessage( "Creating Window...", 3 );
	hWnd = CreateWindowEx(	NULL, mWinClassName, mWinTitle, wndStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 
							posX, posY, mScreenWidth, mScreenHeight, NULL, NULL, hInstance, NULL );
	if ( !hWnd )
		FatalError( "Could Not Create Window." );

	DebugMessage( "Showing Window...", 3 );

	PIXELFORMATDESCRIPTOR pfd = {
		sizeof( PIXELFORMATDESCRIPTOR ), 1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA, mScreenDepth,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 1, 0,
		PFD_MAIN_PLANE, 0, 0, 0, 0
	};

	hDC = GetDC( hWnd );
	if ( !hDC )
		FatalError( "Could not create a GL Device Context." );

	int pixelFormat = ChoosePixelFormat( hDC, &pfd );
	if ( !pixelFormat )
		FatalError( "Pixel Format Invalid." );

	if ( !SetPixelFormat( hDC, pixelFormat, &pfd ) )
		FatalError( "Could not set Pixel Format." );

	hRC = wglCreateContext( hDC );
	if( !hRC )
		FatalError( "Could not create a GL rendering Context." );

	if( !wglMakeCurrent( hDC, hRC ) )
		FatalError( "Could not set Rendering Context" );

	ShowWindow( hWnd, SW_SHOW );
	SetForegroundWindow( hWnd );
	SetFocus( hWnd );
	ResizeGLScene();
	InitializeOpenGL();
	return true;
}
Example #24
0
int main() 
{
    try {

    // Camera settings
	Camera camera;
	glm::vec3 vrp(0.0f, 0.0f, 10.0f);
	glm::vec3 vpn(0.0f, 0.0f, 1.0f);
	glm::vec3 vup(0.0f, 1.0f, 0.0f);
	glm::vec3 prp(0.0f, 0.0f, 100.0f);
	float F = 10.0f;
	float B = -80.0f;
	glm::vec2 lower_left(-20.0f, -20.0f);
	glm::vec2 upper_right(20.0f, 20.0f);
	camera = Camera(vrp, vpn, vup, prp, lower_left, upper_right, F, B);
	
	// Examples
	int curves = 4;    // Amount of examples
	BezierRow G[curves];
	G[0] = BezierRow(glm::vec3(-15.0f, -15.0f, 0.0f),
					 glm::vec3(-10.0f, 25.0f, 0.0f),
					 glm::vec3(10.0f, 25.0f, 0.0f),
					 glm::vec3(15.0f, -15.0f, 0.0f));
	G[1] = BezierRow(glm::vec3(-20.0f, 0.0f, 0.0f),
					 glm::vec3(-1.0f, 55.0f, 0.0f),
					 glm::vec3(1.0f, -55.0f, 0.0f),
					 glm::vec3(20.0f, 0.0f, 0.0f));
	G[2] = BezierRow(glm::vec3(-1.0f, -5.0f, 0.0f),
					 glm::vec3(-60.0f, 5.0f, 0.0f),
					 glm::vec3(60.0f,  5.0f, 0.0f),
					 glm::vec3(1.0f,  -5.0f, 0.0f));
	G[3] = BezierRow(glm::vec3(-10.0f, -5.0f, 0.0f),
					 glm::vec3(60.0f,   5.0f, 0.0f),
					 glm::vec3(-60.0f,  5.0f, 0.0f),
					 glm::vec3(10.0f,  -5.0f, 0.0f));

	int currentfigure = 3; // Set figure between 4 different examples

	// Decide whether to use sampling or subdivision
	int decider = 1;

	int Npoint = 0;
	std::vector<glm::vec3> points;

	// Sampling
	if(decider == 0){
	float t = 0.0f;
	float step = 12.0f;
	sampling(G[currentfigure], t, step, points);
	Npoint = step*2;
	}

	// Subdivision
	else if(decider == 1){
	DLB /= 8.0f;	
	DRB /= 8.0f;
	int n = 3; 				// Amount of curves (smoothness)
 	int npow = pow(2, n+1); // Amount of points
	subdivide(G[currentfigure], n, points);
	Npoint = npow;
	}
	else{
		printf("No method chosen\n"); return 1;
	}




	glm::mat4x4 CTM = camera.CurrentTransformationMatrix();
	std::cout << "CTM = " << std::endl << CTM << std::endl;


	// Initialize the graphics
	InitializeGLFW();
	GLFWwindow* Window = CreateWindow(WindowWidth, WindowHeight, WindowTitle.c_str());
	InitializeGLEW();
	InitializeOpenGL();
	glfwSwapBuffers(Window);

	// Read and Compile the vertex program vertextransform.vert
	GLuint vertexprogID = CreateGpuProgram("vertextransform.vert", GL_VERTEX_SHADER);

        // Read and Compile the fragment program linefragment.frag
	GLuint linefragmentprogID = CreateGpuProgram("linefragment.frag", GL_FRAGMENT_SHADER);

	// Create a lineshader program and Link it with the vertex and linefragment programs
	GLuint lineshaderID = CreateShaderProgram(vertexprogID, linefragmentprogID);
	
	// Now comes the OpenGL core part

	// This is where the curve is initialized
        // User data is in the global variable curveVertices, and the number of entries
	// is in Ncurvevertices

    // Make a VertexArrayObject - it is used by the VertexArrayBuffer, and it must be declared!
	GLuint CurveVertexArrayID;
	glGenVertexArrays(1, &CurveVertexArrayID);
	glBindVertexArray(CurveVertexArrayID);

	// Make a curvevertexbufferObject - it uses the previous VertexArrayBuffer!
	GLuint curvevertexbuffer;
	glGenBuffers(1, &curvevertexbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, curvevertexbuffer);




	// Give our vertices to OpenGL.
	glBufferData(GL_ARRAY_BUFFER, Npoint * 3 * sizeof(float), &points[0], GL_STATIC_DRAW);
	

    // Validate the shader program
	ValidateShader(lineshaderID, "Validating the lineshader");

	// Get locations of Uniforms
	GLuint curvevertextransform   = glGetUniformLocation(lineshaderID, "CTM");
	GLuint curvefragmentcolor     = glGetUniformLocation(lineshaderID, "Color");	




	// Initialize Attributes
	GLuint curvevertexattribute = glGetAttribLocation(lineshaderID, "VertexPosition");
	glVertexAttribPointer(curvevertexattribute, 3, GL_FLOAT, GL_FALSE, 0, 0);

	// The main loop
	while (!glfwWindowShouldClose(Window)) {
	    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	    glUseProgram(lineshaderID);
		glm::mat4x4 CTM = camera.CurrentTransformationMatrix();
		glUniformMatrix4fv(curvevertextransform, 1, GL_FALSE, &CTM[0][0]);
		glUniform3f(curvefragmentcolor, 0.2f, 0.2f, 0.2f);

		glEnableVertexAttribArray(curvevertexattribute);
		glBindVertexArray(CurveVertexArrayID);  // This is very important! There are two "binds"!
		glDrawArrays(GL_LINES, 0, Npoint);

		glDisableVertexAttribArray(curvevertexattribute);
	    glUseProgram(0);

	    glfwSwapBuffers(Window);
	    std::stringstream errormessage;
	    errormessage << "End of loop: " << "assignment5.cpp" << ": " << __LINE__ << ": ";
	    ErrorCheck(errormessage.str());

	    glfwPollEvents();
	}
    }
    catch (std::exception const& exception) {
	std::cerr << "Exception: " << exception.what() << std::endl;
    }

    glfwTerminate();

    return 0;
}
Example #25
0
int main (int argc, const char** argv)
{
	if (argc < 2)
	{
		printf ("USAGE: hlsl2glsltest testfolder\n");
		return 1;
	}

	bool hasOpenGL = InitializeOpenGL ();
	
	clock_t time0 = clock();
	
	Hlsl2Glsl_Initialize ();

	std::string baseFolder = argv[1];

	static const char* kTypeName[2] = { "vertex", "fragment" };
	size_t tests = 0;
	size_t errors = 0;
	for (int type = 0; type < 2; ++type)
	{
		printf ("testing %s...\n", kTypeName[type]);
		std::string testFolder = baseFolder + "/" + kTypeName[type];
		StringVector inputFiles = GetFiles (testFolder, "-in.txt");

		size_t n = inputFiles.size();
		tests += n;
		for (size_t i = 0; i < n; ++i)
		{
			std::string inname = inputFiles[i];
			printf ("test %s\n", inname.c_str());
			std::string outname = inname.substr (0,inname.size()-7) + "-out.txt";
			std::string outnameES = inname.substr (0,inname.size()-7) + "-outES.txt";
			bool ok = TestFile (type==0,
				testFolder + "/" + inname,
				testFolder + "/" + outname,
				false,
				hasOpenGL);
			if (ok)
			{
				ok = TestFile (type==0,
					testFolder + "/" + inname,
					testFolder + "/" + outnameES,
					true,
					false);
			}
			if (!ok)
			{
				++errors;
			}
		}
	}
	clock_t time1 = clock();
	float t = float(time1-time0) / float(CLOCKS_PER_SEC);
	if (errors != 0)
		printf ("%i tests, %i FAILED, %.2fs\n", tests, errors, t);
	else
		printf ("%i tests succeeded, %.2fs\n", tests, t);

	return errors ? 1 : 0;
}
 GL4RenderSystem::GL4RenderSystem() noexcept
 {
     InitializeOpenGL();
 }
Example #27
0
void ImageDrawingArea::on_realize()
{
    Gtk::GL::DrawingArea::on_realize();

    InitializeOpenGL();
}
Example #28
0
void Init(HWND hWnd)
{
    g_hWnd = hWnd;										// Assign the window handle to a global window handle
    GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
    InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect

    // Here we initialize our multitexturing functions
    glActiveTextureARB		= (PFNGLACTIVETEXTUREARBPROC)		wglGetProcAddress("glActiveTextureARB");
    glMultiTexCoord2fARB	= (PFNGLMULTITEXCOORD2FARBPROC)		wglGetProcAddress("glMultiTexCoord2fARB");

    // Check to see if our multi-texture extensions were loaded
    if(!glActiveTextureARB || !glMultiTexCoord2fARB)
    {
        // Print an error message and quit.
        MessageBox(g_hWnd, "Your current setup does not support multitexturing", "Error", MB_OK);
        PostQuitMessage(0);
    }

    // Find the correct function pointer that houses the fog coordinate function
    glFogCoordfEXT	= (PFNGLFOGCOORDFEXTPROC) wglGetProcAddress("glFogCoordfEXT");

    // Before trying to use this function pointer, we need to make sure it was
    // given a valid address.  If not, then we need to quit because something is wrong.
    if(!glFogCoordfEXT)
    {
        // Print an error message and quit.
        MessageBox(g_hWnd, "Your current setup does not support volumetric fog", "Error", MB_OK);
        PostQuitMessage(0);
    }

    // Pick a tan color for our fog with a full alpha
    float fogColor[4] = {0.2f, 0.2f, 0.9f, 1.0f};

    glEnable(GL_FOG);						// Turn on fog
    glFogi(GL_FOG_MODE, GL_LINEAR);			// Set the fog mode to LINEAR (Important)
    glFogfv(GL_FOG_COLOR, fogColor);		// Give OpenGL our fog color
    glFogf(GL_FOG_START, 0.0);				// Set the start position for the depth at 0
    glFogf(GL_FOG_END, 50.0);				// Set the end position for the detph at 50

    // Now we tell OpenGL that we are using our fog extension for every vertex
    glFogi(GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT);

    // Here we read in the height map from the .raw file and put it in our
    // g_HeightMap array.  We also pass in the size of the .raw file (1024).
    LoadRawFile("Terrain.raw", MAP_SIZE * MAP_SIZE, g_HeightMap);

    glEnable(GL_DEPTH_TEST);							// Enables depth testing
    glEnable(GL_TEXTURE_2D);							// Enable texture mapping
    glEnable(GL_CULL_FACE);								// Turn on back face culling

    CreateTexture(g_Texture[0],			"Terrain.bmp"); // Load the terrain texture
    CreateTexture(g_Texture[1],			"Detail.bmp");  // Load the detail-terrain texture
    CreateTexture(g_Texture[BACK_ID],	"Back.bmp");	// Load the Sky box Back texture
    CreateTexture(g_Texture[FRONT_ID],	"Front.bmp");	// Load the Sky box Front texture
    CreateTexture(g_Texture[BOTTOM_ID], "Bottom.bmp");	// Load the Sky box Bottom texture
    CreateTexture(g_Texture[TOP_ID],	"Top.bmp");		// Load the Sky box Top texture
    CreateTexture(g_Texture[LEFT_ID],	"Left.bmp");	// Load the Sky box Left texture
    CreateTexture(g_Texture[RIGHT_ID],	"Right.bmp");	// Load the Sky box Right texture


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
    CreateTexture(g_Texture[WATER_ID],	"Water.bmp");	// Load the water texture
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *


    // Give our camera a decent starting point in the world
    g_Camera.PositionCamera( 280, 40, 225,  281, 40, 225,  0, 1, 0);
}
Example #29
0
// Main function
int main(int argc, char * argv[])
{
	/*{
		PointerState test;

		test.UpdateButtonState(0) = true;
		test.UpdateButtonState(1) = true;
		test.UpdateButtonState(2) = true;

		PointerState test2(test);

		test2.UpdateButtonState(2) = false;

		std::cout << test.GetButtonState(2) << &std::endl;
		std::cout << test2.GetButtonState(2) << &std::endl;

		return 0;
	}*/
#if 0
	{
		std::function<void()> Test = []() { std::cout << "Hi from anon func.\n"; };
		//std::function<ConceptString(const std::vector<ConceptId> &)> Test = [](const std::vector<ConceptId> & Parameters){ return ConceptString({FindConcept("<"), GetParameterIfExists(Parameters, 0), FindConcept(">")}); };

		// Call Test()
		//Test();

		printf("size of func %ld\n", sizeof(Test));

		return 0;
	}
#endif







	// Set env vars
	std::string GoPath;		// This has to exist even after putenv() call because putenv simply adds a pointer rather than copying the value
	std::string Path = "PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/go/bin";
	{
		// Initialize the value of GoPath
		GoPath = "GOPATH=";
		// Get current working directory
		{
			auto cwd = getcwd(nullptr, 0);
			if (nullptr == cwd) {
				printf("Fatal Error: getcwd() failed.");
				exit(1);
			}

			printf("Current-working-dir is '%s' (should be the folder where README.md is).\n", cwd);
			GoPath = GoPath + cwd + "/GoLand";
			GoPath += ":";
			GoPath = GoPath + cwd + "/GoLanding";
			Path = Path + ":" + cwd + "/GoLand/bin";
			free(cwd);
		}

		putenv(const_cast<char *>("DYLD_INSERT_LIBRARIES="));		// HACK: Const cast
		putenv(const_cast<char *>("TERM=xterm"));		// HACK: Const cast
		putenv(const_cast<char *>(GoPath.c_str()));		// HACK: Const cast
		// HACK: Add go/bin to $PATH by hardcoding the whole PATH for OS X
		putenv(const_cast<char *>(Path.c_str()));		// HACK: Const cast
	}

	glfwInit();
	// Verify the GLFW library and header versions match
	{
		int Major, Minor, Revision;
		glfwGetVersion(&Major, &Minor, &Revision);

		bool Match = (GLFW_VERSION_MAJOR == Major && GLFW_VERSION_MINOR == Minor && GLFW_VERSION_REVISION == Revision);

		if (!Match)
		{
			std::cerr << "Error: GLFW library and header versions do not match." << std::endl;

			throw 0;
		}
		else
		{
			std::cout << "Using GLFW " << Major << "." << Minor << "." << Revision << "." << std::endl;
		}
	}

	// Open main window
	{
		GLFWvidmode DesktopMode;
		glfwGetDesktopMode(&DesktopMode);

		glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 32);

		const bool Fullscreen = static_cast<bool>(0);
		const Vector2n WindowDimensons(1536, 960);

		if (!Fullscreen) {
			glfwOpenWindow(WindowDimensons.X(), WindowDimensons.Y(), DesktopMode.RedBits, DesktopMode.GreenBits, DesktopMode.BlueBits, 0, 0, 0, GLFW_WINDOW);
			glfwSetWindowPos((DesktopMode.Width - WindowDimensons.X()) / 2, (DesktopMode.Height - WindowDimensons.Y()) / 2);		// Center the window
		} else {
			glfwOpenWindow(DesktopMode.Width, DesktopMode.Height, DesktopMode.RedBits, DesktopMode.GreenBits, DesktopMode.BlueBits, 0, 0, 0, GLFW_FULLSCREEN);
			glfwEnable(GLFW_MOUSE_CURSOR);
		}

		{
			std::ostringstream x;
			x << "CPU Count: " << glfwGetNumberOfProcessors() << std::endl
			  << "GL Renderer: " << glGetString(GL_VENDOR) << " " << glGetString(GL_RENDERER) << " " << glGetString(GL_VERSION) << std::endl
			  << "GLFW_ACCELERATED: " << glfwGetWindowParam(GLFW_ACCELERATED) << std::endl
			  << "GLFW_RED_BITS: " << glfwGetWindowParam(GLFW_RED_BITS) << std::endl
			  << "GLFW_GREEN_BITS: " << glfwGetWindowParam(GLFW_GREEN_BITS) << std::endl
			  << "GLFW_BLUE_BITS: " << glfwGetWindowParam(GLFW_BLUE_BITS) << std::endl
			  << "GLFW_ALPHA_BITS: " << glfwGetWindowParam(GLFW_ALPHA_BITS) << std::endl
			  << "GLFW_DEPTH_BITS: " << glfwGetWindowParam(GLFW_DEPTH_BITS) << std::endl
			  << "GLFW_STENCIL_BITS: " << glfwGetWindowParam(GLFW_STENCIL_BITS) << std::endl
			  << "GLFW_REFRESH_RATE: " << glfwGetWindowParam(GLFW_REFRESH_RATE) << std::endl
			  << "GLFW_FSAA_SAMPLES: " << glfwGetWindowParam(GLFW_FSAA_SAMPLES) << std::endl;
			std::cout << x.str();
		}

		{
			//glfwSetWindowTitle("Conception");
			glfwSwapInterval(1);					// Set Vsync
			glfwDisable(GLFW_AUTO_POLL_EVENTS);

			glfwEnable(GLFW_KEY_REPEAT);
			glfwDisable(GLFW_SYSTEM_KEYS);
		}
	}

	{
		InputManager InputManager;
		g_InputManager = &InputManager;

		ConceptionApp MainApp(InputManager);
		//LiveEditorApp MainApp(InputManager);
		//ConceptionTestApp MainApp(InputManager);
		//MultitouchTestApp MainApp(InputManager);
		//SentienceApp MainApp(InputManager);

		glfwSetWindowTitle(MainApp.GetTitle().c_str());

		// Perform the layout of UI widgets
		MainApp.Layout();

		// OpenGL settings
		InitializeOpenGL();

		std::cout << std::endl;		// Done loading

		// Main loop
		while (glfwGetWindowParam(GLFW_OPENED))
		{
			auto CurrentTime = glfwGetTime();
			static auto LastTime = CurrentTime;
			auto TimePassed = CurrentTime - LastTime;
			LastTime = CurrentTime;

			// DEBUG: Moved to top of loop to enable debug printing from input handling code
			glClear(GL_COLOR_BUFFER_BIT);		// Clear frame

			// Process input
			{
				// Populate InputEventQueue
				if (MainApp.ShouldRedrawRegardless())
					glfwPollEvents();
				else {
					glfwWaitEvents();
					//if (glfwGetTime() - LastTime >= 1) printf("Slept for %f secs\n", glfwGetTime() - LastTime);
					LastTime = glfwGetTime();
				}
				//InputManager.ProcessTimePassed(TimePassed);

				MainApp.ProcessEventQueue(InputManager.ModifyInputEventQueue());
				MainApp.ProcessTimePassed(TimePassed);
			}

			// Render
			{
				// DEBUG: Moved to top of loop to enable debug printing from input handling code
				///glClear(GL_COLOR_BUFFER_BIT);		// Clear frame

				MainApp.Render();
			}

			// Display new frame
			glfwSwapBuffers();
			//glFinish();

			///printf("%f ms frame\n", TimePassed * 1000);

			// Use less CPU in background
			if (!glfwGetWindowParam(GLFW_ACTIVE))
			{
				glfwSleep(0.100);
			}
		}
	}

	// Clean up
	OglUtilsKillFont();
	glfwTerminate();

	std::cout << "\nReturning 0 from main().\n";
	return 0;
}
Example #30
0
void Init(HWND hWnd)
{
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
	
	// Initialize the camera position
	g_Camera.PositionCamera(0, 3.5f, 30,	0, 0, 0,	0, 1, 0);

	// Here we load the world from a .3ds file
	g_Load3DS.Import3DS(&g_World, FILE_NAME);

	// Go through all the materials
	for(int i = 0; i < g_World.numOfMaterials; i++)
	{
		// Check to see if there is a file name to load in this material
		if(strlen(g_World.pMaterials[i].strFile) > 0)
		{
			// Use the name of the texture file to load the bitmap, with a texture ID (i).
			// We pass in our global texture array, the name of the texture, and an ID to reference it.	
			CreateTexture(g_Texture[i], g_World.pMaterials[i].strFile);			
		}

		// Set the texture ID for this material
		g_World.pMaterials[i].texureId = i;
	}

	// The first thing that needs to happen before creating our octree is to find
	// the total width of the initial root node.  Now we pass in our t3DModel object
	// to GetSceneDimensions(), instead of vertices and a vertex count, as done
	// in the last octree tutorials.  This will store the initial root node cube width.
	g_Octree.GetSceneDimensions(&g_World);

	// Since our model structures stores multiple objects, we can't easily access the
	// total triangle count in the scene with out manually going through and counting the total.
	// This is what we do below.  With the result, we pass this into our CreateNode() function.
	int TotalTriangleCount = g_Octree.GetSceneTriangleCount(&g_World);

	// To create the first node we need the world data, the total triangle count in the scene,
	// along with the initial root node center and width.  This function will then recursively
	// subdivide the rest of the world, according to the global restrictions.
	g_Octree.CreateNode(&g_World, TotalTriangleCount, g_Octree.GetCenter(), g_Octree.GetWidth());

	// The octree should be created by now.  To better increase our efficiency we use display
	// lists for every end node.  This way, we just have to call a display list ID to draw
	// a node, verses the slow loops we normal had.  Vertex arrays are also used to optimize
	// our rendering of the octree.

	// Below we get the display list base ID and store it in the root node.  This should return 1
	// since we don't use display lists anywhere before this.  Notice that we use our global
	// variable that stores our end node count to pass in the total amount of list ID's needed.
	// If you are unfamiliar with displays, basically what you do is section off a certain
	// amount of ID's, and then you are returns a base pointer to the start of those ID's.
	// You can use the ID's from the base pointer to the base pointer ID + the number of
	// ID's that were saved off for that base pointer.  Each of the ID's correspond to a
	// bunch of OpenGL commands.  That means that each end node has it's own ID that
	// corresponds to a bunch of OpenGL commands.  So, for instance, if pass in a bunch
	// of vertices to OpenGL, we can assign this action to a display list.  That way we
	// just call a display list ID to perform that action.  Think of it as a function.
	// You just need to call a function to do a bunch of tasks, which eliminates extra
	// code, and also is saved on the video card for faster processing.  
	g_Octree.SetDisplayListID( glGenLists(g_EndNodeCount) );

	// Now we go through every single end node and create a display list for them all.
	// That way, when we draw the end node, we just use it's display list ID to render
	// the node, instead of looping through all the objects and manually give the verts to opengl.
	// The parameters for this function is the node (starting with the root node), 
	// the world data and current display list base ID.  The base ID is stored in the root
	// node's ID, so we just pass that in.  The reason we do this is because, if you create
	// other display lists before you create the octree, you don't want to assume the octree
	// ID's go from 1 to the end node count.  By passing in the base ID, we then will add
	// this ID to other nodes.  Right now, when they are created they are assigned the
	// end node count at the time upon creating them.  This will make more sense when looking
	// at the octree code.
	g_Octree.CreateDisplayList(&g_Octree, &g_World, g_Octree.GetDisplayListID());

	// Hide our cursor since we are using first person camera mode
	ShowCursor(FALSE);

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	glEnable(GL_LIGHT0);								// Turn on a light with defaults set
	glEnable(GL_LIGHTING);								// Turn on lighting
	glEnable(GL_COLOR_MATERIAL);						// Allow color
}