Ejemplo n.º 1
0
void ccContourExtractorDlg::init()
{
	if (m_glWindow)
	{
		//already initialized
		assert(false);
		return;
	}

	connect(nextPushButton, SIGNAL(clicked()), &m_loop, SLOT(quit()));
	//connect(nextPushButton, SIGNAL(clicked()), this, SLOT(accept()));
	connect(skipPushButton, SIGNAL(clicked()), this,    SLOT(onSkipButtonClicked()));
	nextPushButton->setFocus();

	//create 3D window
	{
		QWidget* glWidget = 0;
		CreateGLWindow(m_glWindow, glWidget, false, true);
		assert(m_glWindow && glWidget);

		ccGui::ParamStruct params = m_glWindow->getDisplayParameters();
		//black (text) & white (background) display by default
		params.backgroundCol = ccColor::white;
		params.textDefaultCol = ccColor::black;
		params.pointsDefaultCol = ccColor::black;
		params.drawBackgroundGradient = false;
		params.decimateMeshOnMove = false;
		params.displayCross = false;
		params.colorScaleUseShader = false;
		m_glWindow->setDisplayParameters(params,true);
		m_glWindow->setPerspectiveState(false,true);
		m_glWindow->setInteractionMode(ccGLWindow::INTERACT_PAN | ccGLWindow::INTERACT_ZOOM_CAMERA | ccGLWindow::INTERACT_CLICKABLE_ITEMS);
		m_glWindow->setPickingMode(ccGLWindow::NO_PICKING);
		m_glWindow->displayOverlayEntities(true);
		viewFrame->setLayout(new QHBoxLayout);
		viewFrame->layout()->addWidget(glWidget);
	}
}
Ejemplo n.º 2
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop
	double	deltaTime;

	{
		long long CountsPerSecond=0;
		QueryPerformanceCounter((LARGE_INTEGER*)&previousTime);
		QueryPerformanceFrequency((LARGE_INTEGER*)&CountsPerSecond); 
		secondsPerCount = 1.0 / (double)CountsPerSecond;
	}

	// Ask The User Which Screen Mode They Prefer
	bFullScreen =  !(MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO);						// Windowed Mode

	// Create Our OpenGL Window
	if (!CreateGLWindow("Engine Programming",x_res,y_res,32,bFullScreen))
		return 0; // Quit If Window Was Not Created

	while(!done)									// Loop That Runs While done=FALSE
	{
		QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
		deltaTime=(double)(currentTime-previousTime)*secondsPerCount;

		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							// ESC or DrawGLScene Signalled A Quit
			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
			}
			
			UpdateGLScene(deltaTime);

			g.rotate_x(-g_Landscape->TotalRot);
			g.rotate_y((float)xDelta/4);
			g_newRot=g_Landscape->TotalRot+(float)yDelta/4;
			g.rotate_x(g_Landscape->TotalRot+(float)yDelta/4);
			xDelta=0;
			yDelta=0;

			if(!keys[VK_SHIFT])
				g_MaxVelocity=vector(0.01,0.01,0.01);
			else
				g_MaxVelocity=vector(0.05,0.05,0.05);

			g_Acceleration=vector(0,0,0);

			if(keys[VK_UP]||keys['W'])
				g_Acceleration.wz=0.01;
			if(keys[VK_DOWN]||keys['S'])
				g_Acceleration.wz=-0.01;
			if(keys[VK_RIGHT]||keys['D'])
				g_Acceleration.wx=-0.01;
			if(keys[VK_LEFT]||keys['A'])
				g_Acceleration.wx=0.01;

			if(keys[VK_UP]||keys['U'])
				g_DominantDirectionalLight->rotate_z(1);
			if(keys[VK_DOWN]||keys['J'])
				g_DominantDirectionalLight->rotate_z(-1);
			if(keys[VK_RIGHT]||keys['K'])
				g_DominantDirectionalLight->rotate_x(-1);
			if(keys[VK_LEFT]||keys['H'])
				g_DominantDirectionalLight->rotate_x(1);

			if(g_Acceleration.wz==0.0)
				g_Velocity.wz=0.0f;
			if(g_Acceleration.wx==0.0f)
				g_Velocity.wx=0.0f;

			g_Velocity+=g_Acceleration*static_cast<float>(deltaTime);
			if(g_Velocity.wx>g_MaxVelocity.wx) g_Velocity.wx=g_MaxVelocity.wx;
			if(g_Velocity.wy>g_MaxVelocity.wy) g_Velocity.wy=g_MaxVelocity.wy;
			if(g_Velocity.wz>g_MaxVelocity.wz) g_Velocity.wz=g_MaxVelocity.wz;
			if(g_Velocity.wx<-g_MaxVelocity.wx) g_Velocity.wx=-g_MaxVelocity.wx;
			if(g_Velocity.wy<-g_MaxVelocity.wy) g_Velocity.wy=-g_MaxVelocity.wy;
			if(g_Velocity.wz<-g_MaxVelocity.wz) g_Velocity.wz=-g_MaxVelocity.wz;
			g.translate(g_Velocity.wx*deltaTime,g_Velocity.wy*deltaTime,g_Velocity.wz*deltaTime);

			if(keys[VK_F2] && !g_bF2Down)
			{
				g_bF2Down=true;
				g_WireFrameMode=!g_WireFrameMode;
			}
			else if(!keys[VK_F2])
				g_bF2Down=false;

			if(keys[VK_F3] && !g_bF3Down)
			{
				g_bF3Down=true;
				g_DrawNormals=!g_DrawNormals;
			}
			else if(!keys[VK_F3])
				g_bF3Down=false;

			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
			}

		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}
Ejemplo n.º 3
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	OPENFILENAMEA ofn;
    char szFileName[MAX_PATH] = "";
	char *fn;
	fn = GetCommandLineA();
	char *realfn = strrchr(fn, ' ')+1;

	if (!CreateGLWindow("MGSView",640,480,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	
    ZeroMemory(&ofn, sizeof(ofn));

    ofn.lStructSize = sizeof(ofn); // SEE NOTE BELOW
    ofn.hwndOwner = hWnd;
    ofn.lpstrFilter = "Konami Model (*.KMD)\0*.kmd\0All Files (*.*)\0*.*\0";
    ofn.lpstrFile = szFileName;
    ofn.nMaxFile = MAX_PATH;
    ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    ofn.lpstrDefExt = "kmd";

    if(GetOpenFileNameA(&ofn)){
		KMD_Load(ofn.lpstrFile);
		//KMD_Load(realfn);
		dl = KMD_DrawPoints();
		//return 0;
	}
	else
		return -1;
	
	ofn.lpstrFilter = "Konami Archive (*.DAR)\0*.dar\0All Files (*.*)\0*.*\0";
	ofn.lpstrDefExt = "dar";
	/*
	if(GetOpenFileNameA(&ofn))
		DAR_LoadTextures(ofn.lpstrFile);
	else
		return -1;
	GetOpenFileNameA(&ofn);
	DAR_LoadTextures(ofn.lpstrFile);
	GetOpenFileNameA(&ofn);
	DAR_LoadTextures(ofn.lpstrFile);
	GetOpenFileNameA(&ofn);
	DAR_LoadTextures(ofn.lpstrFile);*/
	
	//VRAM_Save();
	//return 0;
	//KMD_Export();
	//return 0;
	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			if (active)								// Program Active?
			{
				if(dl){
					DrawGLScene();					// Draw The Scene
					SwapBuffers(hDC);				// Swap Buffers (Double Buffering)
				}
			}			
		}
	}
	
	DrawGLScene();					// Draw The Scene
	OBJExport();
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}
Ejemplo n.º 4
0
int WINAPI WinMain(	HINSTANCE	hInstance,HINSTANCE	hPrevInstance,LPSTR lpCmdLine,	int	nCmdShow)			
{
	MSG		msg;										
	BOOL	done=FALSE;								
	fullscreen=FALSE;
	if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
	{
		return 0;										
	}

	while(!done)										
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))			
		{
			if (msg.message==WM_QUIT)							
			{
				done=TRUE;										
			}
			else												
			{
				TranslateMessage(&msg);								
				DispatchMessage(&msg);							
			}
		}
		else												
		{
				if (active)											
				{
				if (keys[VK_ESCAPE])								
				{
					done=TRUE;										
				}
				else												
				{
					DrawGLScene();										
					SwapBuffers(hDC);				
					if(keys[VK_RIGHT])
					{
						scena.addHangle(-0.7);
					}

					if(keys[VK_LEFT])
					{
						scena.addHangle(0.7);
					}

					if(keys[VK_UP])
					{
						scena.step(1);
					}

					if(keys[VK_DOWN])
					{
						scena.step(-1);
					}
				}
			}

			if (keys[VK_F1])									
			{
				keys[VK_F1]=FALSE;									
				KillGLWindow();										
				fullscreen=!fullscreen;												
				if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
				{
					return 0;										
				}
			}
		}
	}

		KillGLWindow();										
		return (msg.wParam);							
}
Ejemplo n.º 5
0
int WINAPI WinMain(HINSTANCE  hInstance,        // Дескриптор приложения
	HINSTANCE  hPrevInstance,        // Дескриптор родительского приложения
	LPSTR    lpCmdLine,        // Параметры командной строки
	int    nCmdShow)        // Состояние отображения окна
{
	MSG  msg;              // Структура для хранения сообщения Windows
	//BOOL  done=false;            // Логическая переменная для выхода из цикла

	if (MYPRGOGLMAINWINDOWSTART==MYPRGOGLMAINWINDOWSTARTFULLSRCASC)
	{
		// Спрашивает пользователя, какой режим экрана он предпочитает
		if (MessageBox(NULL,TEXT("Хотите ли Вы запустить приложение в полноэкранном режиме?"),TEXT("Запустить в полноэкранном режиме?"),MB_YESNO | MB_ICONQUESTION)==IDNO)
		{
			fullscreen = false;          // Оконный режим
		}
	}
	else
	{
		fullscreen=MYPRGOGLMAINWINDOWSTART;
	}



	// Создать наше OpenGL окно
	if(!CreateGLWindow(MYPRGOGLMAINWINDOWNAME,MYPRGOGLMAINWINDOWWIDTH,MYPRGOGLMAINWINDOWHEIGHT,32,fullscreen))
	{
		return 0;              // Выйти, если окно не может быть создано
	}

	while(!gHalt)                // Цикл продолжается, пока done не равно true
	{
		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))    // Есть ли в очереди какое-нибудь сообщение?
		{
			if( msg.message==WM_QUIT )        // Мы поучили сообщение о выходе?
			{
				gHalt=true;          // Если так, done=true
			}
			else              // Если нет, обрабатывает сообщения
			{
				TranslateMessage(&msg);        // Переводим сообщение
				DispatchMessage(&msg);        // Отсылаем сообщение
			}
		}
		else                // Если нет сообщений
		{
			// Прорисовываем сцену.
			if(active)          // Активна ли программа?
			{
				if(keys[VK_ESCAPE])        // Было ли нажата клавиша ESC?
				{
					gHalt=true;      // ESC говорит об останове выполнения программы
				}
				else            // Не время для выхода, обновим экран.
				{
					my_keyboardTest(keys);
					DrawGLScene();        // Рисуем сцену
					SwapBuffers(hDC);    // Меняем буфер (двойная буферизация)
					
				}
			}
			if(keys[VK_F1])          // Была ли нажата F1?
			{
				keys[VK_F1]=false;        // Если так, меняем значение ячейки массива на false
				KillGLWindow();          // Разрушаем текущее окно
				fullscreen=!fullscreen;      // Переключаем режим
				// Пересоздаём наше OpenGL окно
				if(!CreateGLWindow(MYPRGOGLMAINWINDOWNAME,MYPRGOGLMAINWINDOWWIDTH,MYPRGOGLMAINWINDOWHEIGHT,32,fullscreen))
				{
					gHalt=true;       // Выходим, если это невозможно
				}
			}
		}
	}
	// Shutdown
	my_beforeExit();
	KillGLWindow();                // Разрушаем окно
	return((int)msg.wParam);              // Выходим из программы
}
Ejemplo n.º 6
0
int WINAPI WinMain( HINSTANCE hInstance, // Instance
				   HINSTANCE hPrevInstance,      // Previous Instance
				   LPSTR lpCmdLine,              // Command Line Parameters
				   int nShowCmd )                // Window Show State
{
	MSG msg;			// Windows Message Structure
	BOOL done=FALSE;	// Bool Variable To Exit Loop

	createAILogger();
	logInfo("App fired!");

	// load scene

	if (!Import3DFromFile(basepath+modelname)) return 0;

	logInfo("=============== Post Import ====================");


	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL, "Would You Like To Run In Fullscreen Mode?", "Start Fullscreen?", MB_YESNO|MB_ICONEXCLAMATION)==IDNO)
	{
		fullscreen=FALSE;		// Windowed Mode
	}

	// Create Our OpenGL Window (also calls GLinit und LoadGLTextures)
	if (!CreateGLWindow(windowTitle, 640, 480, 16, fullscreen))
	{
		return 0;
	}




	while(!done)	// Game Loop
	{
		if (PeekMessage(&msg, NULL, 0,0, PM_REMOVE))	// Is There A Message Waiting
		{
			if (msg.message==WM_QUIT)			// Have we received A Quit Message?
			{
				done=TRUE;						// If So done=TRUE
			}
			else
			{
				TranslateMessage(&msg);			// Translate The Message
				DispatchMessage(&msg);			// Dispatch The Message
			}
		}
		else
		{
			// Draw The Scene. Watch For ESC Key And Quit Messaged From DrawGLScene()
			if (active)
			{
				if (keys[VK_ESCAPE])	// Was ESC pressed?
				{
					done=TRUE;			// ESC signalled A quit
				}
				else
				{
					DrawGLScene();		// Draw The Scene
					SwapBuffers(hDC);	// Swap Buffers (Double Buffering)
				}
			}

			if (keys[VK_F1])		// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;	// If so make Key FALSE
				KillGLWindow();		// Kill Our Current Window
				fullscreen=!fullscreen;	// Toggle Fullscreen
				//recreate Our OpenGL Window
				if (!CreateGLWindow(windowTitle, 640, 480, 16, fullscreen))
				{
					return 0;		// Quit if Window Was Not Created
				}
			}
		}
	}

	// *** cleanup ***

	// clear map
	textureIdMap.clear(); //no need to delete pointers in it manually here. (Pointers point to textureIds deleted in next step)

	// clear texture ids
	if (textureIds)
	{
		delete[] textureIds;
		textureIds = NULL;
	}

	// *** cleanup end ***

	// Shutdown
	destroyAILogger();
	KillGLWindow();
	return (msg.wParam);	// Exit The Program
}
Ejemplo n.º 7
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,L"Would You Like To Run In Fullscreen Mode?", L"Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow(L"NeHe's Rotation Tutorial",640,480,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							// ESC or DrawGLScene Signalled A Quit
			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
				if (keys['L'] && !lp)
				{
					lp=TRUE;
					light=!light;
					if (!light)
					{
						glDisable(GL_LIGHTING);
					}
					else
					{
						glEnable(GL_LIGHTING);
					}
				}
				if (!keys['L'])
				{
					lp=FALSE;
				}
				if (keys['F'] && !fp)
				{
					fp=TRUE;
					filter+=1;
					if (filter>2)
					{
						filter=0;
					}
				}
				if (!keys['F'])
				{
					fp=FALSE;
				}
				if (keys[VK_PRIOR])
				{
					z-=0.02f;
				}
				if (keys[VK_NEXT])
				{
					z+=0.02f;
				}
				if (keys[VK_UP])
				{
					xspeed-=0.1f;
				}
				if (keys[VK_DOWN])
				{
					xspeed+=0.1f;
				}
				if (keys[VK_RIGHT])
				{
					yspeed+=0.1f;
				}
				if (keys[VK_LEFT])
				{
					yspeed-=0.1f;
				}

				if (keys[VK_F1])						// Is F1 Being Pressed?
				{
					keys[VK_F1]=FALSE;					// If So Make Key FALSE
					KillGLWindow();						// Kill Our Current Window
					fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
					// Recreate Our OpenGL Window
					if (!CreateGLWindow(L"NeHe's Textures, Lighting & Keyboard Tutorial",640,480,16,fullscreen))
					{
						return 0;						// Quit If Window Was Not Created
					}
				}
			}

			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow(L"NeHe's Rotation Tutorial",640,480,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				}
			}
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}
Ejemplo n.º 8
0
BOOL CreateGLWindow(char *title, int width, int height, int bits, bool fullscreenflag)
{
    GLuint PixelFormat; // holds the results after searching for a match
    HINSTANCE hInstance; // holds the instance of the application
    WNDCLASS wc; // windows class structure
    DWORD dwExStyle; // window extended style
    DWORD dwStyle; // window style
    RECT WindowRect; // grabs rectangle upper left / lower right values
    WindowRect.left = (long)0; // set left value to 0
    WindowRect.right = (long)width; // set right value to requested width
    WindowRect.top = (long)0; // set top value to 0
    WindowRect.bottom = (long)height; // set bottom value to requested height

    fullscreen = fullscreenflag; // set the global fullscreen flag

    hInstance = GetModuleHandle(NULL); // grab an instance for our window
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // redraw on size, and own DC for window.
    wc.lpfnWndProc = (WNDPROC)WndProc; // wndproc handles messages
    wc.cbClsExtra = 0; // no extra window data
    wc.cbWndExtra = 0; // no extra window data
    wc.hInstance = hInstance; // set the instance
    wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // load the default icon
    wc.hCursor = LoadCursor(NULL, IDC_ARROW); // load the arrow pointer
    wc.hbrBackground = NULL; // no background required for GL
    wc.lpszMenuName = NULL; // we don't want a menu
    wc.lpszClassName = "EU07"; // nazwa okna do komunikacji zdalnej
    // // Set The Class Name

    if (!arbMultisampleSupported) // tylko dla pierwszego okna
        if (!RegisterClass(&wc)) // Attempt To Register The Window Class
        {
            ErrorLog("Fail: window class registeration");
            MessageBox(NULL, "Failed to register the window class.", "ERROR",
                       MB_OK | MB_ICONEXCLAMATION);
            return FALSE; // Return FALSE
        }

    if (fullscreen) // Attempt Fullscreen Mode?
    {
        DEVMODE dmScreenSettings; // device mode
        memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // makes sure memory's cleared
        dmScreenSettings.dmSize = sizeof(dmScreenSettings); // size of the devmode structure

        // tolaris-240403: poprawka na odswiezanie monitora
        // locate primary monitor...
        if (Global::bAdjustScreenFreq)
        {
            POINT point;
            point.x = 0;
            point.y = 0;
            MONITORINFOEX monitorinfo;
            monitorinfo.cbSize = sizeof(MONITORINFOEX);
            ::GetMonitorInfo(::MonitorFromPoint(point, MONITOR_DEFAULTTOPRIMARY), &monitorinfo);
            //  ..and query for highest supported refresh rate
            unsigned int refreshrate = 0;
            int i = 0;
            while (::EnumDisplaySettings(monitorinfo.szDevice, i, &dmScreenSettings))
            {
                if (i > 0)
                    if (dmScreenSettings.dmPelsWidth == (unsigned int)width)
                        if (dmScreenSettings.dmPelsHeight == (unsigned int)height)
                            if (dmScreenSettings.dmBitsPerPel == (unsigned int)bits)
                                if (dmScreenSettings.dmDisplayFrequency > refreshrate)
                                    refreshrate = dmScreenSettings.dmDisplayFrequency;
                ++i;
            }
            // fill refresh rate info for screen mode change
            dmScreenSettings.dmDisplayFrequency = refreshrate;
            dmScreenSettings.dmFields = DM_DISPLAYFREQUENCY;
        }
        dmScreenSettings.dmPelsWidth = width; // selected screen width
        dmScreenSettings.dmPelsHeight = height; // selected screen height
        dmScreenSettings.dmBitsPerPel = bits; // selected bits per pixel
        dmScreenSettings.dmFields =
            dmScreenSettings.dmFields | DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

        // Try to set selected mode and get results.  NOTE: CDS_FULLSCREEN gets rid of start bar.
        if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
        {
            // If the mode fails, offer two options.  Quit or use windowed mode.
            ErrorLog("Fail: full screen");
            if (MessageBox(NULL, "The requested fullscreen mode is not supported by\nyour video "
                                 "card. Use windowed mode instead?",
                           "EU07", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
            {
                fullscreen = FALSE; // Windowed Mode Selected.  Fullscreen = FALSE
            }
            else
            {
                // Pop Up A Message Box Letting User Know The Program Is Closing.
                Error("Program will now close.");
                return FALSE; // Return FALSE
            }
        }
    }

    if (fullscreen) // Are We Still In Fullscreen Mode?
    {
        dwExStyle = WS_EX_APPWINDOW; // Window Extended Style
        dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; // Windows Style
        ShowCursor(FALSE); // Hide Mouse Pointer
    }
    else
    {
        dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
        dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; // Windows Style
    }

    AdjustWindowRectEx(&WindowRect, dwStyle, FALSE,
                       dwExStyle); // Adjust Window To True Requested Size

    // Create The Window
    if (NULL ==
        (hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window
                               "EU07", // Class Name
                               title, // Window Title
                               dwStyle | // Defined Window Style
                                   WS_CLIPSIBLINGS | // Required Window Style
                                   WS_CLIPCHILDREN, // Required Window Style
                               0,
                               0, // Window Position
                               WindowRect.right - WindowRect.left, // Calculate Window Width
                               WindowRect.bottom - WindowRect.top, // Calculate Window Height
                               NULL, // No Parent Window
                               NULL, // No Menu
                               hInstance, // Instance
                               NULL))) // Dont Pass Anything To WM_CREATE
    {
        KillGLWindow(); // Reset The Display
        ErrorLog("Fail: window creation");
        MessageBox(NULL, "Window creation error.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE; // Return FALSE
    }

    static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be
        {
         sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
         1, // Version Number
         PFD_DRAW_TO_WINDOW | // Format Must Support Window
             PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
             PFD_DOUBLEBUFFER, // Must Support Double Buffering
         PFD_TYPE_RGBA, // Request An RGBA Format
         bits, // Select Our Color Depth
         0,
         0, 0, 0, 0, 0, // Color Bits Ignored
         0, // No Alpha Buffer
         0, // Shift Bit Ignored
         0, // No Accumulation Buffer
         0, 0, 0, 0, // Accumulation Bits Ignored
         24, // 32Bit Z-Buffer (Depth Buffer)
         0, // No Stencil Buffer
         0, // No Auxiliary Buffer
         PFD_MAIN_PLANE, // Main Drawing Layer
         0, // Reserved
         0, 0, 0 // Layer Masks Ignored
        };

    if (NULL == (hDC = GetDC(hWnd))) // Did We Get A Device Context?
    {
        KillGLWindow(); // Reset The Display
        ErrorLog("Fail: device context");
        MessageBox(NULL, "Can't create a GL device context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE; // Return FALSE
    }

    /*
     Our first pass, Multisampling hasn't been created yet, so we create a window normally
     If it is supported, then we're on our second pass
     that means we want to use our pixel format for sampling
     so set PixelFormat to arbMultiSampleformat instead
    */
    if (!arbMultisampleSupported)
    {
        if (NULL == (PixelFormat =
                         ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format?
        {
            KillGLWindow(); // Reset The Display
            ErrorLog("Fail: pixelformat");
            MessageBox(NULL, "Can't find a suitable pixelformat.", "ERROR",
                       MB_OK | MB_ICONEXCLAMATION);
            return FALSE; // Return FALSE
        }
    }
    else
        PixelFormat = arbMultisampleFormat;

    if (!SetPixelFormat(hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format?
    {
        KillGLWindow(); // Reset The Display
        ErrorLog("Fail: pixelformat");
        MessageBox(NULL, "Can't set the pixelformat.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE; // Return FALSE
    }

    if (NULL == (hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
    {
        KillGLWindow(); // Reset The Display
        ErrorLog("Fail: OpenGL rendering context creation");
        MessageBox(NULL, "Can't create a GL rendering context.", "ERROR",
                   MB_OK | MB_ICONEXCLAMATION);
        return FALSE; // Return FALSE
    }

    if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context
    {
        KillGLWindow(); // Reset The Display
        ErrorLog("Fail: OpenGL rendering context activation");
        MessageBox(NULL, "Can't activate the GL rendering context.", "ERROR",
                   MB_OK | MB_ICONEXCLAMATION);
        return FALSE; // Return FALSE
    }

    /*
    Now that our window is created, we want to queary what samples are available
    we call our InitMultiSample window
    if we return a valid context, we want to destroy our current window
    and create a new one using the multisample interface.
    */
    if (Global::iMultisampling)
        if (!arbMultisampleSupported)
            if ((Global::iMultisampling =
                     InitMultisample(hInstance, hWnd, pfd, 1 << Global::iMultisampling)) != 0)
            {
                // WriteConsoleOnly("Opening second window for multisampling of
                // "+AnsiString(Global::iMultisampling)+" samples.");
                KillGLWindow(); // reset the display
                return CreateGLWindow(title, width, height, bits, fullscreenflag); // rekurencja
            }

    ShowWindow(hWnd, SW_SHOW); // show the window
    SetForegroundWindow(hWnd); // slightly higher priority
    SetFocus(hWnd); // sets keyboard focus to the window
    ReSizeGLScene(width, height); // set up our perspective GL screen

    if (!InitGL()) // initialize our newly created GL Window
    {
        KillGLWindow(); // reset the display
        ErrorLog("Fail: OpenGL initialization");
        MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
        return FALSE; // return FALSE
    }
    return TRUE; // success
}
Ejemplo n.º 9
0
int WINAPI WinMain(HINSTANCE	hInstance,				// 当前窗口实例
	HINSTANCE	hPrevInstance,				// 前一个窗口实例
	LPSTR		lpCmdLine,				// 命令行参数
	int		nCmdShow)				// 窗口显示状态
{

	MSG	msg;								// Windowsx消息结构
	BOOL	done = FALSE;							// 用来退出循环的Bool 变量

	fullscreen = false;
	// 提示用户选择运行模式
	//if (MessageBox(NULL, TEXT("你想在全屏模式下运行么?"), TEXT("设置全屏模式"), MB_YESNO | MB_ICONQUESTION) == IDNO)
	//	fullscreen = FALSE;						// FALSE为窗口模式

	// 创建OpenGL窗口
	if (!CreateGLWindow(TEXT("OpenGL程序框架"), 800, 600, 16, fullscreen))
		return 0;							// 失败退出

	while (!done)							// 保持循环直到 done=TRUE
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))		// 有消息在等待吗?
		{
			if (msg.message == WM_QUIT)			// 收到退出消息?
			{
				done = TRUE;					// 是,则done=TRUE
			}
			else								// 不是,处理窗口消息
			{
				TranslateMessage(&msg);			// 翻译消息
				DispatchMessage(&msg);			// 发送消息
			}
		}
		else								// 如果没有消息
		{
			// 绘制场景。监视ESC键和来自DrawGLScene()的退出消息
			if (active)						// 程序激活的么?
			{
				if (keys[VK_ESCAPE])		// ESC 是否按下
				{
					done = TRUE;			// ESC 发出退出信号
				}
				else						// 不是退出的时候,刷新屏幕
				{
					DrawGLScene();			// 绘制场景
					SwapBuffers(hDC);		// 交换缓存 (双缓存)
				}
			}

			if (keys[VK_F1])				// F1键按下了么
			{
				keys[VK_F1] = FALSE;				// 若是,使对应的Key数组中的值为 FALSE

				KillGLWindow();					// 销毁当前的窗口

				fullscreen = !fullscreen;				// 切换 全屏 / 窗口 模式
				// 重建 OpenGL 窗口
				if (!CreateGLWindow(TEXT("OpenGL 程序框架"), 800, 600, 16, fullscreen))
					return 0;				// 如果窗口未能创建,程序退出
			}
		}
	}

	// 关闭程序
	KillGLWindow();								// 销毁窗口
	return (msg.wParam);							// 退出程序
}
Ejemplo n.º 10
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("JelloPhysic Test",800,600,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							// ESC or DrawGLScene Signalled A Quit

			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
			}
			
			if(keys[VK_F2])
			{
				if(springy == true)
				{
					//add pressure body
						
					SpringBody *sBody = new SpringBody(springI, 1.0f, 150.0f, 5.0f, 300.0f, 15.0f, Vector2(-5.0f, -5.0f), 0.0f, Vector2::One,false);
					sBody->addInternalSpring(0, 14, 300.0f, 10.0f);
					sBody->addInternalSpring(1, 14, 300.0f, 10.0f);
					sBody->addInternalSpring(1, 15, 300.0f, 10.0f);
					sBody->addInternalSpring(1, 5, 300.0f, 10.0f);
					sBody->addInternalSpring(2, 14, 300.0f, 10.0f);
					sBody->addInternalSpring(2, 5, 300.0f, 10.0f);
					sBody->addInternalSpring(1, 5, 300.0f, 10.0f);
					sBody->addInternalSpring(14, 5, 300.0f, 10.0f);
					sBody->addInternalSpring(2, 4, 300.0f, 10.0f);
					sBody->addInternalSpring(3, 5, 300.0f, 10.0f);
					sBody->addInternalSpring(14, 6, 300.0f, 10.0f);
					sBody->addInternalSpring(5, 13, 300.0f, 10.0f);
					sBody->addInternalSpring(13, 6, 300.0f, 10.0f);
					sBody->addInternalSpring(12, 10, 300.0f, 10.0f);
					sBody->addInternalSpring(13, 11, 300.0f, 10.0f);
					sBody->addInternalSpring(13, 10, 300.0f, 10.0f);
					sBody->addInternalSpring(13, 9, 300.0f, 10.0f);
					sBody->addInternalSpring(6, 10, 300.0f, 10.0f);
					sBody->addInternalSpring(6, 9, 300.0f, 10.0f);
					sBody->addInternalSpring(6, 8, 300.0f, 10.0f);
					sBody->addInternalSpring(7, 9, 300.0f, 10.0f);

					// polygons!
					sBody->addTriangle(0, 15, 1);
					sBody->addTriangle(1, 15, 14);
					sBody->addTriangle(1, 14, 5);
					sBody->addTriangle(1, 5, 2);
					sBody->addTriangle(2, 5, 4);
					sBody->addTriangle(2, 4, 3);
					sBody->addTriangle(14, 13, 6);
					sBody->addTriangle(14, 6, 5);
					sBody->addTriangle(12, 11, 10);
					sBody->addTriangle(12, 10, 13);
					sBody->addTriangle(13, 10, 9);
					sBody->addTriangle(13, 9, 6);
					sBody->addTriangle(6, 9, 8);
					sBody->addTriangle(6, 8, 7);
					sBody->finalizeTriangles();

					mWorld->addBody(sBody);
					springBodies.push_back(sBody);

					springy = false;
				}
			}

			if(keys[VK_F3])
			{
				if(pressure == true)
				{
					PressureBody * pressureBody = new PressureBody(ball, 1.0f, 50.0f, 10.0f, 1.0f, 300.0f, 20.0f, Vector2(0, -10), 0, Vector2(0.5f,0.5f),false);

					mWorld->addBody(pressureBody);
					pressureBodies.push_back(pressureBody);

					pressure = false;
				}
			}

			if(keys[VK_F4])
			{
				if(boxy == true)
				{
					FallingBody *fBody = new FallingBody(shape,1.0f, 300.0f, 10.0f,Vector2(0.0f, -5.0f),0.0f , Vector2(2.0f,2.0f),false);
					fBody->addInternalSpring(0, 2, 400.0f, 12.0f);
					fBody->addInternalSpring(1, 3, 400.0f, 12.0f);

					mWorld->addBody(fBody);
					fallingBodies.push_back(fBody);

					boxy = false;
				}
			}

			//calc fps
			CalcFPS();
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window

	return (msg.wParam);							// Exit The Program
}
Ejemplo n.º 11
0
int WINAPI WinMain(	HINSTANCE	hInstance,			
	HINSTANCE	hPrevInstance,		
	LPSTR		lpCmdLine,			
	int			nCmdShow)			
{
	MSG		msg;									
	BOOL	done = FALSE;								


	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
		fullscreen = FALSE;							

	InitVars();                                    

	// Create Our OpenGL Window
	if (!CreateGLWindow("Arkanoid",640,480,16,fullscreen))
	{
		return 0;									
	}
	srand(time(NULL));
	while(!done)									
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	
		{
			if (msg.message == WM_QUIT)				
			{
				done = TRUE;							
			}
			else									
			{
				TranslateMessage(&msg);				
				DispatchMessage(&msg);				
			}
		}
		else										
			if (active)
			{
				if (keys[VK_ESCAPE])	
					done = TRUE;							

				if (keys[78] && (gof)) { done = TRUE; gof = false; } //  78 -- n, 89 -- y
				if (keys[89] && (gof)) { gameOver = TRUE; flag = 0;/*TogglePause();*/  idle(); DrawGLScene(); SwapBuffers(hDC); gof = false; }

				else
				{

					if ( keys[VK_SPACE] ) { bflag = true;}

					if(bflag){

						if (keys[VK_PAUSE]){ TogglePause(); }
						if(pause) {
							DrawGLScene();                      
							SwapBuffers(hDC);
						} else{

							idle();                             
							DrawGLScene();              
							SwapBuffers(hDC);
						}
					} else { 
						DrawLoadScreen (); 
						SwapBuffers(hDC);	
					}

				}

				if (!ProcessKeys()) return 0;
			}
	}

	// Shutdown
	KillGLWindow();									
	glDeleteTextures(4,texture);
	return (msg.wParam);							
}
Ejemplo n.º 12
0
//----------------------------------------------------------------------------------------------------
// Standard windows mainline, this is the program entry point
//
CrtInt32 WINAPI WinMain(	HINSTANCE	hInstance,		
					HINSTANCE	hPrevInstance,	
					LPSTR		lpCmdLine,			
					CrtInt32			nCmdShow)	
{
	(void)hPrevInstance; // Avoid warnings
	(void)nCmdShow; // Avoid warnings
	(void)hInstance; // Avoid warnings

#ifndef NO_DEVIL
	ilInit();
#endif

	MSG		msg;									
	BOOL	done=FALSE;								
	
	// Avoid warnings later
	msg.wParam = 0;

	// Turns on windows heap debugging
#if HEAP_DEBUG
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_CHECK_CRT_DF /*| _CRTDBG_DELAY_FREE_MEM_DF*/);
#endif

	// Ask The User Which Screen Mode They Prefer
	//	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							
	}

	// Set the default screen size
	_CrtRender.SetScreenWidth( 640);
	_CrtRender.SetScreenHeight( 480);

	// Create an OpenGL Window
	if (!CreateGLWindow("Collada Viewer for PC", _CrtRender.GetScreenWidth(), _CrtRender.GetScreenHeight(),32,fullscreen))
	{
		return 0;									
	}
	
	// Turn data dumping (debug) off
	//CrtBool dumpData = CrtFalse; 

	// Initialize the renderer
	// !!!GAC for compatibility with the new COLLADA_FX code, Init now forces UsingCg and UsingVBOs to
	// !!!GAC false.  It also calls CrtInitCg, creating the CG context and calling cgGLRegisterStates.
	// !!!GAC All these things are currently required for the cfx rendering path to work, changing them
	// !!!GAC may cause problems.  This is work in progress and will be much cleaner when the refactor is done.
	
	_CrtRender.Init();
	//_CrtRender.SetRenderDebug( CrtTrue ); 

	// !!!GAC kept for reference, changing these may cause problems with the cfx include path
	//_CrtRender.SetUsingCg( CrtFalse );
	// Turn off VBOs (the GL skinning path doesn't work with VBOs yet)
	_CrtRender.SetUsingVBOs( CrtTrue ); 
	_CrtRender.SetUsingNormalMaps( CrtTrue ); 	
	//_CrtRender.SetRenderDebug( CrtTrue ); 
	//_CrtRender.SetUsingShadowMaps(CrtTrue);

	// We might get a windows-style path on the command line, this can mess up the DOM which expects
	// all paths to be URI's.  This block of code does some conversion to try and make the input
	// compliant without breaking the ability to accept a properly formatted URI.  Right now this only
	// displays the first filename
	char
		file[512],
		*in = lpCmdLine,
		*out = file;
	*out = NULL;
	// If the first character is a ", skip it (filenames with spaces in them are quoted)
	if(*in == '\"')
	{
		in++;
	}
	if(*(in+1) == ':')
	{
		// Second character is a :, assume we have a path with a drive letter and add a slash at the beginning
		*(out++) = '/';
	}
	int i;
	for(i =0; i<512; i++)
	{
		// If we hit a null or a quote, stop copying.  This will get just the first filename.
		if(*in == NULL || *in == '\"')
			break;
		// Copy while swapping backslashes for forward ones
		if(*in == '\\')
		{
			*out = '/';
		}
		else
		{
			*out = *in;
		}
		in++;
		out++;
	}
	
	// Should throw an error if i>= 512, but we don't have error dialongs in the code yet so just let it try to load and fail
	if(i < 511)
		*out = NULL;

	time_t seconds =  time (NULL);
	clock_t clocka = clock ();

	cleaned_file_name = file;
	// Load the file name provided on the command line
	if ( !_CrtRender.Load( cleaned_file_name ))
	{
		exit(0);
	}
	time_t loadtime = time (NULL) - seconds;
	int clockload = (int) clock () - clocka;

	CrtPrint("\nLOAD TIME OF %s\n", file);
	CrtPrint("IS %d SECONDS\n", loadtime);
	CrtPrint("IS %d CLOCK TICKS\n\n", clockload);


	// This block of code shows how to enumerate all the effects, get their parameters and then
	// get their UI information.
#if 1
	{
		// Get the scene and setup to iterate over all the effects stored in the cfxLoader
		CrtScene *scene = _CrtRender.GetScene();
		std::map<std::string, cfxEffect*>::iterator effectIterator;
		effectIterator = scene->cfxEffects.begin();
		// Iterate over all the effects
		while(effectIterator != scene->cfxEffects.end())
		{
			// This is the effect name you would use in a UI
			CrtPrint("Effect name %s\n", effectIterator->first.c_str());
			cfxEffect *thiscfxEffect = effectIterator->second;
			CGeffect thisCGEffect = thiscfxEffect->getEffect();
			CGparameter thisCGParameter = cgGetFirstEffectParameter(thisCGEffect);
			while(thisCGParameter != NULL)
			{
				// This is the parameter name you would use in the UI
				const char *parameterName = cgGetParameterName(thisCGParameter);
				// This is for the example of how to tweek a parameter (doesn't work yet)
				if(CrtCmp(parameterName, "Amplitude"))
				{
					// Capture the parameter and save it in a global, in a GUI you would
					// save this handle in the widget so it would know what to tweek.
					amplitudeGlobalParameter = thisCGParameter;
				}
#if 0
				// This is here for debugging, it iterates over all the annotations and prints them out
				// so you can see what's in them.  Normally this code will be turned off.
				CrtPrint("  Parameter name %s\n",parameterName);
				CGannotation dbgCGAnnotation = cgGetFirstParameterAnnotation(thisCGParameter);
				while(dbgCGAnnotation != NULL)
				{
					const char *annotationName = cgGetAnnotationName(dbgCGAnnotation);
					CrtPrint("      Annotation: %s",annotationName);
					if(cgGetAnnotationType(dbgCGAnnotation) == CG_STRING)
					{
						const char *annotationString = cgGetStringAnnotationValue(dbgCGAnnotation);
						CrtPrint(" value: %s\n",annotationString);
					}
					else if(cgGetAnnotationType(dbgCGAnnotation) == CG_FLOAT)
					{
						int nvalues; 
						const float *value = cgGetFloatAnnotationValues(dbgCGAnnotation, &nvalues);
						CrtPrint(" value: %f\n",*value);  // Assume there is one value
					}
					else
					{
						CrtPrint("\n");
					}
					dbgCGAnnotation = cgGetNextAnnotation(dbgCGAnnotation);
				}
#endif
				// This code looks at the parameter annotations to see if they specify some kind of UI
				// cgGetNamedParameterAnnotation isn't used for this because it is case sensitive and at
				// least some of the annotations FXcomposer uses for UI appear to NOT be case sensitive.
				// This method should collect the parameter values regardless of case, but it has to scan
				// ALL the parameters and do case-blind compares on each one, which is slower.
				// This code currently only collects the annotation values for defining sliders and color pickers.
				const char *UIName		= "unknown";
				const char *UIWidget	= "unknown";
				float UIMin				= -99999.0f;
				float UIMax				= 99999.0f;
				float UIStep			= 0.0f;
				int   nvalues;
				CGannotation thisCGAnnotation = cgGetFirstParameterAnnotation(thisCGParameter);
				// Iterate over all the annotations
				while(thisCGAnnotation != NULL)
				{
					// Get the name of this annotation
					const char *annotationName = cgGetAnnotationName(thisCGAnnotation);
					// Do case-blind compares to see if the annotation is one of the ones used to make UI
					// and save the value if it is.
					if(CrtICmp("UIWidget",annotationName))
					{
						// This is the widget type
						UIWidget = cgGetStringAnnotationValue(thisCGAnnotation);
					}
					if(CrtICmp("UIName",annotationName))
					{
						// This is the name to attach to the widget
						UIName = cgGetStringAnnotationValue(thisCGAnnotation);
					}
					if(CrtICmp("UIMin",annotationName))
					{
						// This is the minimum value for a slider widget
						const float *value = cgGetFloatAnnotationValues(thisCGAnnotation, &nvalues);
						if(nvalues == 1)
							UIMin = *value;
					}
					if(CrtICmp("UIMax",annotationName))
					{
						// This is the maximum value for a slider widget
						const float *value = cgGetFloatAnnotationValues(thisCGAnnotation, &nvalues);
						if(nvalues == 1)
							UIMax = *value;
					}
					if(CrtICmp("UIStep",annotationName))
					{
						// This is the step (minimum change) for a slider widget
						const float *value = cgGetFloatAnnotationValues(thisCGAnnotation, &nvalues);
						if(nvalues == 1)
							UIStep = *value;
					}
					// Get the next annotation
					thisCGAnnotation = cgGetNextAnnotation(thisCGAnnotation);
				}
				// Is the UIWidget a type that we recognize? (just slider and color picker for now)
				// Replace the CrtPrint with the code that generates the UI, remember the UI needs to
				// store thisCGParameter someplace so it can use it to change the parameter later. 
				if(CrtICmp("slider", UIWidget))
				{
					CrtPrint("Parameter %s needs a slider named %s going from %f to %f with step %f\n",parameterName,UIName,UIMin,UIMax, UIStep );
				}
				if(CrtICmp("color", UIWidget))
				{
					CrtPrint("Parameter %s needs a color picker named %s\n",parameterName,UIName);
				}
				// Move on to the next parameter
				thisCGParameter = cgGetNextParameter(thisCGParameter);
			}
			// Move on to the next effect
			effectIterator++;
		}
	}
#endif
	while(!done)									
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	
		{
			if (msg.message==WM_QUIT)				
			{
				done=TRUE;							
			}
			else									
			{
				TranslateMessage(&msg);				
				DispatchMessage(&msg);				
			}
		}
		else										
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							
			}
			else									
			{
				SwapBuffers(hDC);					
				ProcessInput( keys ); 				
			}
		}
	}

	_CrtRender.Destroy();

	// Shutdown
#ifndef NO_DEVIL
	ilShutDown();
#endif
	DestroyGLWindow();								
	return (int)(msg.wParam);						
}
Ejemplo n.º 13
0
// Call ProcessInput once per frame to process input keys
void ProcessInput( bool	keys[] )
{
	// These keys we don't want to auto-repeat, so we clear them in "keys" after handling them once
	if (keys['E'] && amplitudeGlobalParameter)
	{
		float value;
		cgGetParameterValuefc(amplitudeGlobalParameter, 1, &value);
		value += 0.1f;
		cgSetParameter1f(amplitudeGlobalParameter, value);
		keys['E'] = false;
	}
	if (keys['R'] && amplitudeGlobalParameter)
	{
		float value;
		cgGetParameterValuefc(amplitudeGlobalParameter,1, &value);
		value -= 0.1f;
		cgSetParameter1f(amplitudeGlobalParameter, value);
		keys['R'] = false;
	}
	if (keys[VK_TAB] )
	{
		// When 'C' is pressed, change cameras
		_CrtRender.SetNextCamera();
		keys[VK_TAB] = false;
	}

	if ( keys['M'] )
	{
		// Speed up UI by 25%
		AdjustUISpeed(1.25f);  
		keys['M'] = false;
	}
	if ( keys['N'] )
	{
		// Slow down UI by 25%
		AdjustUISpeed(0.75f);  // Go 25% slower
		keys['N'] = false;
	}
	if (keys['Q'])
	{
		if (togglewireframe) {
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
			togglewireframe = FALSE;
		} else {
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
			togglewireframe = TRUE;
		}
		keys['Q'] = false;
	}

	if (keys['K'])
	{
		if (togglehiearchy) {
			_CrtRender.SetShowHiearchy(CrtTrue);	
			togglehiearchy = FALSE;
		} else {
			_CrtRender.SetShowHiearchy(CrtFalse);
			togglehiearchy = TRUE;
		}
		keys['K'] = false;
	}
	if (keys['L'])
	{
		if (togglelighting) {
			glDisable(GL_LIGHTING);
			togglelighting = FALSE;
		} else {
			glEnable(GL_LIGHTING);
			togglelighting = TRUE;
		}
		keys['L'] = false;
	}

	if (keys['P'] )
	{
		if (sAnimationEnable) {
			_CrtRender.SetAnimationPaused( CrtTrue );
			sAnimationEnable = false;
		}
		else { 
			_CrtRender.SetAnimationPaused( CrtFalse ); 
			sAnimationEnable = true;
		}
		keys['P'] = false;
	}
	if (keys[VK_F1])		
	{
		keys[VK_F1]=FALSE;		
		_CrtRender.Destroy();
		DestroyGLWindow();			
		fullscreen=!fullscreen;		
		// Recreate Our OpenGL Window
		if (!CreateGLWindow("Collada Viewer for PC", _CrtRender.GetScreenWidth(), _CrtRender.GetScreenHeight(),32,fullscreen))
		{
			exit(1);
		}
		if ( !_CrtRender.Load( cleaned_file_name ))
		{
			exit(0);
		}

		keys[VK_F1] = false;
	}
	
	// These keys that do a function as long as they are held down, so we don't clear "keys".
	// Remember to scale these functions by time!

	if (keys['S'])
	{
		// UI code to move the camera closer
		_CrtRender.ActiveInstanceCamera->MoveTransform(_CrtRender.GetAnimDelta() * KeyboardTranslateSpeed *0.5f, 0.0f, 0.0f);
	}

	if (keys['W'])
	{
		// UI code to move the camera farther away
		_CrtRender.ActiveInstanceCamera->MoveTransform(- _CrtRender.GetAnimDelta() * KeyboardTranslateSpeed * 0.5f, 0.0f, 0.0f);
	}

	if (keys[VK_SPACE])
	{
		// UI code to move the camera farther up
		_CrtRender.ActiveInstanceCamera->MoveTransform(0.0f, 0.0f, _CrtRender.GetAnimDelta() * KeyboardTranslateSpeed);
	}

	if (keys['X'])
	{
		// UI code to move the camera farther down
		_CrtRender.ActiveInstanceCamera->MoveTransform(0.0f, 0.0f, - _CrtRender.GetAnimDelta() * KeyboardTranslateSpeed);
	}

	if (keys['D'])
	{
		// UI code to move the camera farther right
		_CrtRender.ActiveInstanceCamera->MoveTransform(0.0f, - _CrtRender.GetAnimDelta() * KeyboardTranslateSpeed, 0.0f);
	}

	if (keys['A'])
	{
		// UI code to move the camera farther left
		_CrtRender.ActiveInstanceCamera->MoveTransform(0.0f, _CrtRender.GetAnimDelta() * KeyboardTranslateSpeed, 0.0f);
	}

	if (keys['F'])
	{
		if(togglecullingface == 0)
		{ // turn it front
			glEnable( GL_CULL_FACE );
			glCullFace(GL_FRONT);
			togglecullingface = 1;
		} else if(togglecullingface == 1)
		{ // turn it both
			glDisable( GL_CULL_FACE );
			togglecullingface = 2;
		} else 
		{ // turn it back
			glEnable( GL_CULL_FACE );
			glCullFace(GL_BACK);
			togglecullingface = 0;
		}
		keys['F'] = false;
	}
}
Ejemplo n.º 14
0
int WINAPI WinMain( HINSTANCE hInstance, // Instance
				   HINSTANCE hPrevInstance,      // Previous Instance
				   LPSTR lpCmdLine,              // Command Line Parameters
				   int nShowCmd )                // Window Show State
{
	MSG msg;
	BOOL done=FALSE;

	createAILogger();
	logInfo("App fired!");

	// Check the command line for an override file path.
	int argc;
	LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	if (argv != NULL && argc > 1)
	{
		std::wstring modelpathW(argv[1]);
		modelpath = std::string(modelpathW.begin(), modelpathW.end());
	}

	if (!Import3DFromFile(modelpath)) return 0;

	logInfo("=============== Post Import ====================");

	if (MessageBox(NULL, "Would You Like To Run In Fullscreen Mode?", "Start Fullscreen?", MB_YESNO|MB_ICONEXCLAMATION)==IDNO)
	{
		fullscreen=FALSE;
	}

	if (!CreateGLWindow(windowTitle, 640, 480, 16, fullscreen))
	{
		return 0;
	}

	while(!done)	// Game Loop
	{
		if (PeekMessage(&msg, NULL, 0,0, PM_REMOVE))
		{
			if (msg.message==WM_QUIT)
			{
				done=TRUE;
			}
			else
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
		else
		{
			// Draw The Scene. Watch For ESC Key And Quit Messaged From DrawGLScene()
			if (active)
			{
				if (keys[VK_ESCAPE])
				{
					done=TRUE;
				}
				else
				{
					DrawGLScene();
					SwapBuffers(hDC);
				}
			}

			if (keys[VK_F1])
			{
				keys[VK_F1]=FALSE;
				KillGLWindow();
				fullscreen=!fullscreen;
				if (!CreateGLWindow(windowTitle, 640, 480, 16, fullscreen))
				{
					return 0;
				}
			}
		}
	}

	// *** cleanup ***

	textureIdMap.clear(); //no need to delete pointers in it manually here. (Pointers point to textureIds deleted in next step)

	if (textureIds)
	{
		delete[] textureIds;
		textureIds = NULL;
	}

	// *** cleanup end ***

	destroyAILogger();
	KillGLWindow();
	return (msg.wParam);
}
Ejemplo n.º 15
0
int WINAPI WinMain(	HINSTANCE	hInstance,						// Instance
					HINSTANCE	hPrevInstance,					// Previous Instance
					LPSTR		lpCmdLine,						// Command Line Parameters
					int			nCmdShow)						// Window Show State
{
	MSG		msg;												// Windows Message Structure
	BOOL	done=FALSE;											// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;										// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("NeHe's Token, Extensions, Scissoring & TGA Loading Tutorial",640,480,16,fullscreen))
	{
		return 0;												// Quit If Window Was Not Created
	}

	while(!done)												// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))				// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)							// Have We Received A Quit Message?
			{
				done=TRUE;										// If So done=TRUE
			}
			else												// If Not, Deal With Window Messages
			{
				DispatchMessage(&msg);							// Dispatch The Message
			}
		}
		else													// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;										// ESC or DrawGLScene Signalled A Quit
			}
			else												// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);								// Swap Buffers (Double Buffering)

				if (keys[VK_F1])								// Is F1 Being Pressed?
				{
					keys[VK_F1]=FALSE;							// If So Make Key FALSE
					KillGLWindow();								// Kill Our Current Window
					fullscreen=!fullscreen;						// Toggle Fullscreen / Windowed Mode
					// Recreate Our OpenGL Window
					if (!CreateGLWindow("NeHe's Token, Extensions, Scissoring & TGA Loading Tutorial",640,480,16,fullscreen))
					{
						return 0;								// Quit If Window Was Not Created
					}
				}

				if (keys[VK_UP] && (scroll>0))					// Is Up Arrow Being Pressed?
				{
					scroll-=2;									// If So, Decrease 'scroll' Moving Screen Down
				}

				if (keys[VK_DOWN] && (scroll<32*(maxtokens-9)))	// Is Down Arrow Being Pressed?
				{
					scroll+=2;									// If So, Increase 'scroll' Moving Screen Up
				}
			}
		}
	}

	// Shutdown
	KillGLWindow();												// Kill The Window
	return (msg.wParam);										// Exit The Program
}
Ejemplo n.º 16
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("NeHe's Particle Tutorial",640,480,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	if (fullscreen)									// Are We In Fullscreen Mode
	{
		slowdown=1.0f;								// If So, Speed Up The Particles (3dfx Issue)
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							// ESC or DrawGLScene Signalled A Quit
			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)

				if (keys[VK_ADD] && (slowdown>1.0f)) slowdown-=0.01f;		// Speed Up Particles
				if (keys[VK_SUBTRACT] && (slowdown<4.0f)) slowdown+=0.01f;	// Slow Down Particles

				if (keys[VK_PRIOR])	zoom+=0.1f;		// Zoom In
				if (keys[VK_NEXT])	zoom-=0.1f;		// Zoom Out

				if (keys[VK_RETURN] && !rp)			// Return Key Pressed
				{
					rp=true;						// Set Flag Telling Us It's Pressed
					rainbow=!rainbow;				// Toggle Rainbow Mode On / Off
				}
				if (!keys[VK_RETURN]) rp=false;		// If Return Is Released Clear Flag
				
				if ((keys[' '] && !sp) || (rainbow && (delay>25)))	// Space Or Rainbow Mode
				{
					if (keys[' '])	rainbow=false;	// If Spacebar Is Pressed Disable Rainbow Mode
					sp=true;						// Set Flag Telling Us Space Is Pressed
					delay=0;						// Reset The Rainbow Color Cycling Delay
					col++;							// Change The Particle Color
					if (col>11)	col=0;				// If Color Is To High Reset It
				}
				if (!keys[' '])	sp=false;			// If Spacebar Is Released Clear Flag

				// If Up Arrow And Y Speed Is Less Than 200 Increase Upward Speed
				if (keys[VK_UP] && (yspeed<200)) yspeed+=1.0f;

				// If Down Arrow And Y Speed Is Greater Than -200 Increase Downward Speed
				if (keys[VK_DOWN] && (yspeed>-200)) yspeed-=1.0f;

				// If Right Arrow And X Speed Is Less Than 200 Increase Speed To The Right
				if (keys[VK_RIGHT] && (xspeed<200)) xspeed+=1.0f;

				// If Left Arrow And X Speed Is Greater Than -200 Increase Speed To The Left
				if (keys[VK_LEFT] && (xspeed>-200)) xspeed-=1.0f;

				delay++;							// Increase Rainbow Mode Color Cycling Delay Counter

				if (keys[VK_F1])						// Is F1 Being Pressed?
				{
					keys[VK_F1]=FALSE;					// If So Make Key FALSE
					KillGLWindow();						// Kill Our Current Window
					fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
					// Recreate Our OpenGL Window
					if (!CreateGLWindow("NeHe's Particle Tutorial",640,480,16,fullscreen))
					{
						return 0;						// Quit If Window Was Not Created
					}
				}
			}
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}
Ejemplo n.º 17
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("Slider",1600,1200,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if (active)								// Program Active?
			{
				if (keys[VK_ESCAPE])				// Was ESC Pressed?
				{
					done=TRUE;						// ESC Signalled A Quit
				}


				else								// Not Time To Quit, Update Screen
				{
					DrawGLScene();					// Draw The Scene
					SwapBuffers(hDC);				// Swap Buffers (Double Buffering)
				}

				if (keys['L'] && !lp)				// L Key Being Pressed Not Held?
				{
					lp=TRUE;				// lp Becomes TRUE
					light=!light;				// Toggle Light TRUE/FALSE

					if (!light)				// If Not Light
					{
						glDisable(GL_LIGHTING);		// Disable Lighting
					}
					else					// Otherwise
					{
						glEnable(GL_LIGHTING);		// Enable Lighting
					}
				}

				if (!keys['L'])					// Has L Key Been Released?
				{
					lp=FALSE;				// If So, lp Becomes FALSE
				}

				if (keys['F'] && !fp)				// Is F Key Being Pressed?
				{
					fp=TRUE;				// fp Becomes TRUE
					filter+=1;				// filter Value Increases By One
					if (filter>2)				// Is Value Greater Than 2?
					{
						filter=0;			// If So, Set filter To 0
					}
				}
				if (!keys['F'])					// Has F Key Been Released?
				{
					fp=FALSE;				// If So, fp Becomes FALSE
				}

				if (keys[VK_PRIOR])				// Is Page Up Being Pressed?
				{
					z-=0.02f;				// If So, Move Into The Screen
				}

				if (keys[VK_NEXT])				// Is Page Down Being Pressed?
				{
					z+=0.02f;				// If So, Move Towards The Viewer
				}

				if (keys[VK_UP])				// Is Up Arrow Being Pressed?
				{
					xspeed-=0.01f;				// If So, Decrease xspeed
				}
				if (keys[VK_DOWN])				// Is Down Arrow Being Pressed?
				{
					xspeed+=0.01f;				// If So, Increase xspeed
				}
				if (keys[VK_RIGHT])				// Is Right Arrow Being Pressed?
				{
					yspeed+=0.01f;				// If So, Increase yspeed
				}
				if (keys[VK_LEFT])				// Is Left Arrow Being Pressed?
				{
					yspeed-=0.01f;				// If So, Decrease yspeed
				}
			}

			if (keys[VK_F11])						// Is F1 Being Pressed?
			{
				keys[VK_F11]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("Slider",1600,1200,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				}
			}



		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}
Ejemplo n.º 18
0
BOOL CGLLogoView::SubclassWindow (HWND hWnd)
{
	CWindowImpl <CGLLogoView, CStatic>::SubclassWindow (hWnd);
	if (!CreateGLWindow()) KillGLWindow();
	return TRUE;
}
Ejemplo n.º 19
0
int WINAPI WinMain(HINSTANCE hInstance, // instance
                   HINSTANCE hPrevInstance, // previous instance
                   LPSTR lpCmdLine, // command line parameters
                   int nCmdShow) // window show state
{
    MSG msg; // windows message structure
    BOOL done = FALSE; // bool variable to exit loop
    fullscreen = true;
    DecimalSeparator = '.';
    /* //Ra: tutaj to nie dzia³a - zwraca NULL
     //najpierw ustalmy wersjê OpenGL
     AnsiString glver=((char*)glGetString(GL_VERSION));
     while (glver.LastDelimiter(".")>glver.Pos("."))
      glver=glver.SubString(1,glver.LastDelimiter(".")-1); //obciêcie od drugiej kropki
     try {Global::fOpenGL=glver.ToDouble();} catch (...) {Global::fOpenGL=0.0;}
     Global::bOpenGL_1_5=(Global::fOpenGL>=1.5);
    */
    DeleteFile("errors.txt"); // usuniêcie starego
    Global::LoadIniFile("eu07.ini"); // teraz dopiero mo¿na przejrzeæ plik z ustawieniami
    Global::InitKeys("keys.ini"); // wczytanie mapowania klawiszy - jest na sta³e

    // hunter-271211: ukrywanie konsoli
    if (Global::iWriteLogEnabled & 2)
    {
        AllocConsole();
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);
    }
    AnsiString str = lpCmdLine; // parametry uruchomienia
    if (!str.IsEmpty())
    { // analizowanie parametrów
        TQueryParserComp *Parser;
        Parser = new TQueryParserComp(NULL);
        Parser->TextToParse = lpCmdLine;
        Parser->First();
        while (!Parser->EndOfFile)
        {
            str = Parser->GetNextSymbol().LowerCase();
            if (str == AnsiString("-s"))
            { // nazwa scenerii
                str = Parser->GetNextSymbol().LowerCase();
                strcpy(Global::szSceneryFile, str.c_str());
            }
            else if (str == AnsiString("-v"))
            { // nazwa wybranego pojazdu
                str = Parser->GetNextSymbol().LowerCase();
                Global::asHumanCtrlVehicle = str;
            }
            else if (str == AnsiString("-modifytga"))
            { // wykonanie modyfikacji wszystkich plików TGA
                Global::iModifyTGA = -1; // specjalny tryb wykonania totalnej modyfikacji
            }
            else if (str == AnsiString("-e3d"))
            { // wygenerowanie wszystkich plików E3D
                if (Global::iConvertModels > 0)
                    Global::iConvertModels = -Global::iConvertModels; // specjalny tryb
                else
                    Global::iConvertModels = -7; // z optymalizacj¹, bananami i prawid³owym Opacity
            }
            else
                Error(
                    "Program usage: EU07 [-s sceneryfilepath] [-v vehiclename] [-modifytga] [-e3d]",
                    !Global::iWriteLogEnabled);
        }
        delete Parser; // ABu 050205: tego wczesniej nie bylo
    }
    /* MC: usunalem tymczasowo bo sie gryzlo z nowym parserem - 8.6.2003
        AnsiString csp=AnsiString(Global::szSceneryFile);
        csp=csp.Delete(csp.Pos(AnsiString(strrchr(Global::szSceneryFile,'/')))+1,csp.Length());
        Global::asCurrentSceneryPath=csp;
    */

    fullscreen = Global::bFullScreen;
    WindowWidth = Global::iWindowWidth;
    WindowHeight = Global::iWindowHeight;
    Bpp = Global::iBpp;
    if (Bpp != 32)
        Bpp = 16;
    // create our OpenGL window
    if (!CreateGLWindow(Global::asHumanCtrlVehicle.c_str(), WindowWidth, WindowHeight, Bpp,
                        fullscreen))
        return 0; // quit if window was not created
    SetForegroundWindow(hWnd);
    // McZapkie: proba przeplukania klawiatury
    Console *pConsole = new Console(); // Ra: nie wiem, czy ma to sens, ale jakoœ zainicjowac trzeba
    while (Console::Pressed(VK_F10))
        Error("Keyboard buffer problem - press F10"); // na Windows 98 lubi siê to pojawiaæ
    int iOldSpeed, iOldDelay;
    SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &iOldSpeed, 0);
    SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &iOldDelay, 0);
    SystemParametersInfo(SPI_SETKEYBOARDSPEED, 20, NULL, 0);
    // SystemParametersInfo(SPI_SETKEYBOARDDELAY,10,NULL,0);
    if (!joyGetNumDevs())
        WriteLog("No joystick");
    if (Global::iModifyTGA < 0)
    { // tylko modyfikacja TGA, bez uruchamiania symulacji
        Global::iMaxTextureSize = 64; //¿eby nie zamulaæ pamiêci
        World.ModifyTGA(); // rekurencyjne przegl¹danie katalogów
    }
    else
    {
        if (Global::iConvertModels < 0)
        {
            Global::iConvertModels = -Global::iConvertModels;
            World.CreateE3D("models\\"); // rekurencyjne przegl¹danie katalogów
            World.CreateE3D("dynamic\\", true);
        } // po zrobieniu E3D odpalamy normalnie sceneriê, by j¹ zobaczyæ
        // else
        //{//g³ówna pêtla programu
        Console::On(); // w³¹czenie konsoli
        while (!done) // loop that runs while done=FALSE
        {
            if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // is there a message waiting?
            {
                if (msg.message == WM_QUIT) // have we received a quit message?
                    done = TRUE; // if so
                else // if not, deal with window messages
                {
                    // if (msg.message==WM_CHAR)
                    // World.OnKeyDown(msg.wParam);
                    TranslateMessage(&msg); // translate the message
                    DispatchMessage(&msg); // dispatch the message
                }
            }
            else // if there are no messages
            {
                // draw the scene, watch for quit messages
                // DrawGLScene()
                // if (!pause)
                // if (Global::bInactivePause?Global::bActive:true) //tak nie, bo spada z góry
                if (World.Update()) // Was There A Quit Received?
                    SwapBuffers(hDC); // Swap Buffers (Double Buffering)
                else
                    done = true; //[F10] or DrawGLScene signalled a quit
            }
        }
        Console::Off(); // wy³¹czenie konsoli (komunikacji zwrotnej)
    }
    SystemParametersInfo(SPI_SETKEYBOARDSPEED, iOldSpeed, NULL, 0);
    SystemParametersInfo(SPI_SETKEYBOARDDELAY, iOldDelay, NULL, 0);
    delete pConsole; // deaktywania sterownika
    // shutdown
    KillGLWindow(); // kill the window
    return (msg.wParam); // exit the program
}
Ejemplo n.º 20
0
int  main(int  argc, char  *argv[])

{
	
	BOOL  done = FALSE;
	int  bpp = 16;
	int  i;
	SDL_Event  event;


	/* Initialize the SDL library */
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0){
		printf("Couldn't initialize SDL: %s\n",SDL_GetError());
		exit(255);
	}

	
    if (!CreateGLWindow("Trilogy http://digilander.iol.it/tellaman", 640, 480, 16, fullscreen)) 
		return 0;

	while (!done){

		if (!DrawGLScene())
			done = TRUE;

		glFlush();
		SDL_GL_SwapBuffers();

		SDL_PollEvent(&event);
		switch(event.type){  /* Process the appropiate event type */
		case SDL_KEYDOWN:  /* Handle a KEYDOWN event */         
		{

			if (event.key.keysym.sym == SDLK_ESCAPE){
				SDL_Quit();
				exit(0);
			}
			if (event.key.keysym.sym == SDLK_e)
			{
				emboss=!emboss;
			}				
			if (event.key.keysym.sym == SDLK_m)
			{
				useMultitexture=((!useMultitexture) && multitextureSupported);
			}				
			if (event.key.keysym.sym == SDLK_b)
			{
				bumps=!bumps;
			}				
			if (event.key.keysym.sym == SDLK_f)
			{
				filter++;
				filter%=3;
			}			
			if (event.key.keysym.sym == SDLK_PAGEDOWN)
			{
				z-=0.02f;
			}
			if (event.key.keysym.sym == SDLK_PAGEUP)
			{
				z+=0.02f;
			}
			if (event.key.keysym.sym == SDLK_UP)
			{
				xspeed-=0.01f;
			}
			if (event.key.keysym.sym == SDLK_DOWN)
			{
				xspeed+=0.01f;
			}
			if (event.key.keysym.sym == SDLK_RIGHT)
			{
				yspeed+=0.01f;
			}
			if (event.key.keysym.sym == SDLK_LEFT)
			{
				yspeed-=0.01f;
			}
		}
		break;
		
		
		/*case  SDL_VIDEORESIZE:
		{
			width = event.resize.w;
			height = event.resize.h;
			ReSizeGLScene(width, height);
		}
		break;*/
		
		
		default: /* Report an unhandled event */
			break;
		}
		
	}
	
	SDL_Quit();
	return 0;

}
Ejemplo n.º 21
0
int WINAPI WinMain(	HINSTANCE	hInstance,						// Instance
					HINSTANCE	hPrevInstance,					// Previous Instance
					LPSTR		lpCmdLine,						// Command Line Parameters
					int			nCmdShow)						// Window Show State
{
	MSG		msg;												// Windows Message Structure
	BOOL	done=FALSE;											// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;										// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("NeHe's Line Tutorial",640,480,16,fullscreen))
	{
		return 0;												// Quit If Window Was Not Created
	}

	ResetObjects();												// Set Player / Enemy Starting Positions
	TimerInit();

	while(!done)												// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))				// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)							// Have We Received A Quit Message?
			{
				done=TRUE;										// If So done=TRUE
			}
			else												// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);							// Translate The Message
				DispatchMessage(&msg);							// Dispatch The Message
			}
		}
		else													// If There Are No Messages
		{
			float start=TimerGetTime();							// Grab Timer Value Before We Draw
			
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;										// ESC or DrawGLScene Signalled A Quit
			}
			else												// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);								// Swap Buffers (Double Buffering)
			}

			while(TimerGetTime()<start+float(steps[adjust]*2.0f)) {}	// Waste Cycles On Fast Systems

			if (keys[VK_F1])									// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;								// If So Make Key FALSE
				KillGLWindow();									// Kill Our Current Window
				fullscreen=!fullscreen;							// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("NeHe's Line Tutorial",640,480,16,fullscreen))
				{
					return 0;									// Quit If Window Was Not Created
				}
			}

			if (keys['A'] && !ap)								// If 'A' Key Is Pressed And Not Held
			{
				ap=TRUE;										// ap Becomes TRUE
				anti=!anti;										// Toggle Antialiasing
			}
			if (!keys['A'])										// If 'A' Key Has Been Released
			{
				ap=FALSE;										// ap Becomes FALSE
			}

			if (!gameover && active)							// If Game Isn't Over And Programs Active Move Objects
			{
				for (loop1=0; loop1<(stage*level); loop1++)		// Loop Through The Different Stages
				{
					if ((enemy[loop1].x<player.x) && (enemy[loop1].fy==enemy[loop1].y*40))
					{
						enemy[loop1].x++;						// Move The Enemy Right
					}

					if ((enemy[loop1].x>player.x) && (enemy[loop1].fy==enemy[loop1].y*40))
					{
						enemy[loop1].x--;						// Move The Enemy Left
					}

					if ((enemy[loop1].y<player.y) && (enemy[loop1].fx==enemy[loop1].x*60))
					{
						enemy[loop1].y++;						// Move The Enemy Down
					}

					if ((enemy[loop1].y>player.y) && (enemy[loop1].fx==enemy[loop1].x*60))
					{
						enemy[loop1].y--;						// Move The Enemy Up
					}

					if (delay>(3-level) && (hourglass.fx!=2))	// If Our Delay Is Done And Player Doesn't Have Hourglass
					{
						delay=0;								// Reset The Delay Counter Back To Zero
						for (loop2=0; loop2<(stage*level); loop2++)	// Loop Through All The Enemies
						{
							if (enemy[loop2].fx<enemy[loop2].x*60)	// Is Fine Position On X Axis Lower Than Intended Position?
							{
								enemy[loop2].fx+=steps[adjust];	// If So, Increase Fine Position On X Axis
								enemy[loop2].spin+=steps[adjust];	// Spin Enemy Clockwise
							}
							if (enemy[loop2].fx>enemy[loop2].x*60)	// Is Fine Position On X Axis Higher Than Intended Position?
							{
								enemy[loop2].fx-=steps[adjust];	// If So, Decrease Fine Position On X Axis
								enemy[loop2].spin-=steps[adjust];	// Spin Enemy Counter Clockwise
							}
							if (enemy[loop2].fy<enemy[loop2].y*40)	// Is Fine Position On Y Axis Lower Than Intended Position?
							{
								enemy[loop2].fy+=steps[adjust];	// If So, Increase Fine Position On Y Axis
								enemy[loop2].spin+=steps[adjust];	// Spin Enemy Clockwise
							}
							if (enemy[loop2].fy>enemy[loop2].y*40)	// Is Fine Position On Y Axis Higher Than Intended Position?
							{
								enemy[loop2].fy-=steps[adjust];	// If So, Decrease Fine Position On Y Axis
								enemy[loop2].spin-=steps[adjust];	// Spin Enemy Counter Clockwise
							}
						}
					}

					// Are Any Of The Enemies On Top Of The Player?
					if ((enemy[loop1].fx==player.fx) && (enemy[loop1].fy==player.fy))
					{
						lives--;								// If So, Player Loses A Life

						if (lives==0)							// Are We Out Of Lives?
						{
							gameover=TRUE;						// If So, gameover Becomes TRUE
						}

						ResetObjects();							// Reset Player / Enemy Positions
						PlaySound("Data/Die.wav", NULL, SND_SYNC);	// Play The Death Sound
					}
				}

				if (keys[VK_RIGHT] && (player.x<10) && (player.fx==player.x*60) && (player.fy==player.y*40))
				{
					hline[player.x][player.y]=TRUE;				// Mark The Current Horizontal Border As Filled
					player.x++;									// Move The Player Right
				}
				if (keys[VK_LEFT] && (player.x>0) && (player.fx==player.x*60) && (player.fy==player.y*40))
				{
					player.x--;									// Move The Player Left
					hline[player.x][player.y]=TRUE;				// Mark The Current Horizontal Border As Filled
				}
				if (keys[VK_DOWN] && (player.y<10) && (player.fx==player.x*60) && (player.fy==player.y*40))
				{
					vline[player.x][player.y]=TRUE;				// Mark The Current Verticle Border As Filled
					player.y++;									// Move The Player Down
				}
				if (keys[VK_UP] && (player.y>0) && (player.fx==player.x*60) && (player.fy==player.y*40))
				{
					player.y--;									// Move The Player Up
					vline[player.x][player.y]=TRUE;				// Mark The Current Verticle Border As Filled
				}

				if (player.fx<player.x*60)						// Is Fine Position On X Axis Lower Than Intended Position?
				{
					player.fx+=steps[adjust];					// If So, Increase The Fine X Position
				}
				if (player.fx>player.x*60)						// Is Fine Position On X Axis Greater Than Intended Position?
				{
					player.fx-=steps[adjust];					// If So, Decrease The Fine X Position
				}
				if (player.fy<player.y*40)						// Is Fine Position On Y Axis Lower Than Intended Position?
				{
					player.fy+=steps[adjust];					// If So, Increase The Fine Y Position
				}
				if (player.fy>player.y*40)						// Is Fine Position On Y Axis Lower Than Intended Position?
				{
					player.fy-=steps[adjust];					// If So, Decrease The Fine Y Position
				}
			}
			else												// Otherwise
			{
				if (keys[' '])									// If Spacebar Is Being Pressed
				{
					gameover=FALSE;								// gameover Becomes FALSE
					filled=TRUE;								// filled Becomes TRUE
					level=1;									// Starting Level Is Set Back To One
					level2=1;									// Displayed Level Is Also Set To One
					stage=0;									// Game Stage Is Set To Zero
					lives=5;									// Lives Is Set To Five
				}
			}

			if (filled)											// Is The Grid Filled In?
			{
				PlaySound("Data/Complete.wav", NULL, SND_SYNC);	// If So, Play The Level Complete Sound
				stage++;										// Increase The Stage
				if (stage>3)									// Is The Stage Higher Than 3?
				{
					stage=1;									// If So, Set The Stage To One
					level++;									// Increase The Level
					level2++;									// Increase The Displayed Level
					if (level>3)								// Is The Level Greater Than 3?
					{
						level=3;								// If So, Set The Level To 3
						lives++;								// Give The Player A Free Life
						if (lives>5)							// Does The Player Have More Than 5 Lives?
						{
							lives=5;							// If So, Set Lives To Five
						}
					} 
				}

				ResetObjects();									// Reset Player / Enemy Positions

				for (loop1=0; loop1<11; loop1++)				// Loop Through The Grid X Coordinates
				{
					for (loop2=0; loop2<11; loop2++)			// Loop Through The Grid Y Coordinates
					{
						if (loop1<10)							// If X Coordinate Is Less Than 10
						{
							hline[loop1][loop2]=FALSE;			// Set The Current Horizontal Value To FALSE
						}
						if (loop2<10)							// If Y Coordinate Is Less Than 10
						{
							vline[loop1][loop2]=FALSE;			// Set The Current Vertical Value To FALSE
						}
					}
				}
			}

			// If The Player Hits The Hourglass While It's Being Displayed On The Screen
			if ((player.fx==hourglass.x*60) && (player.fy==hourglass.y*40) && (hourglass.fx==1))
			{
				// Play Freeze Enemy Sound
				PlaySound("Data/freeze.wav", NULL, SND_ASYNC | SND_LOOP);
				hourglass.fx=2;									// Set The hourglass fx Variable To Two
				hourglass.fy=0;									// Set The hourglass fy Variable To Zero
			}

			player.spin+=0.5f*steps[adjust];					// Spin The Player Clockwise
			if (player.spin>360.0f)								// Is The spin Value Greater Than 360?
			{
				player.spin-=360;								// If So, Subtract 360
			}

			hourglass.spin-=0.25f*steps[adjust];				// Spin The Hourglass Counter Clockwise
			if (hourglass.spin<0.0f)							// Is The spin Value Less Than 0?
			{
				hourglass.spin+=360.0f;							// If So, Add 360
			}

			hourglass.fy+=steps[adjust];						// Increase The hourglass fy Variable
			if ((hourglass.fx==0) && (hourglass.fy>6000/level))	// Is The hourglass fx Variable Equal To 0 And The fy
			{													// Variable Greater Than 6000 Divided By The Current Level?
				PlaySound("Data/hourglass.wav", NULL, SND_ASYNC);	// If So, Play The Hourglass Appears Sound
				hourglass.x=rand()%10+1;						// Give The Hourglass A Random X Value
				hourglass.y=rand()%11;							// Give The Hourglass A Random Y Value
				hourglass.fx=1;									// Set hourglass fx Variable To One (Hourglass Stage)
				hourglass.fy=0;									// Set hourglass fy Variable To Zero (Counter)
			}

			if ((hourglass.fx==1) && (hourglass.fy>6000/level))	// Is The hourglass fx Variable Equal To 1 And The fy
			{													// Variable Greater Than 6000 Divided By The Current Level?
				hourglass.fx=0;									// If So, Set fx To Zero (Hourglass Will Vanish)
				hourglass.fy=0;									// Set fy to Zero (Counter Is Reset)
			}

			if ((hourglass.fx==2) && (hourglass.fy>500+(500*level)))	// Is The hourglass fx Variable Equal To 2 And The fy
			{													// Variable Greater Than 500 Plus 500 Times The Current Level?
				PlaySound(NULL, NULL, 0);						// If So, Kill The Freeze Sound
				hourglass.fx=0;									// Set hourglass fx Variable To Zero
				hourglass.fy=0;									// Set hourglass fy Variable To Zero
			}

			delay++;											// Increase The Enemy Delay Counter
		}
	}

	// Shutdown
	KillGLWindow();												// Kill The Window
	return (msg.wParam);										// Exit The Program
}
Ejemplo n.º 22
0
BOOL CreateGLWindow(HWND prnt, HINSTANCE hInst,  WNDPROC WndProc,LPCSTR title, int width, int height, int bits)
{
	HWND     hwnd;
	GLuint   PixelFormat;              // Хранит результат после поиска

	DWORD    dwExStyle;              // Расширенный стиль окна
	DWORD    dwStyle;              // Обычный стиль окна
	
	RECT WindowRect;                // Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;              // Установить левую составляющую в 0
	WindowRect.right=(long)width;              // Установить правую составляющую в Width
	WindowRect.top=(long)0;                // Установить верхнюю составляющую в 0
	WindowRect.bottom=(long)height;              // Установить нижнюю составляющую в Height

	WNDCLASS  wc;                // Структура класса окна
	wc.style    = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;      // Перерисуем при перемещении и создаём скрытый DC
	wc.lpfnWndProc    = WndProc;          // Процедура обработки сообщений
	wc.cbClsExtra    = 0;              // Нет дополнительной информации для окна
	wc.cbWndExtra    = 0;              // Нет дополнительной информации для окна
	wc.hInstance    = hInst;            // Устанавливаем дескриптор
	wc.hIcon    = LoadIcon(NULL, IDI_WINLOGO);        // Загружаем иконку по умолчанию
	wc.hCursor    = LoadCursor(NULL, IDC_ARROW);        // Загружаем указатель мышки
	wc.hbrBackground  = NULL;              // Фон не требуется для GL
	wc.lpszMenuName    = NULL;              // Меню в окне не будет
	wc.lpszClassName  = "OpenGL";            // Устанавливаем имя классу

	//ptC.x=0;
	//ptC.y=0;

	dwExStyle  =   WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;      // Расширенный стиль окна
	dwStyle    =   WS_CHILD | WS_VISIBLE | WS_BORDER | WS_HSCROLL | WS_VSCROLL;        // Обычный стиль окна

	if( !RegisterClass( &wc ) )              // Пытаемся зарегистрировать класс окна
	{
		MessageBox( NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;                // Выход и возвращение функцией значения false
	}

	AdjustWindowRectEx( &WindowRect, dwStyle, false, dwExStyle );      // Подбирает окну подходящие размеры

	if( !( hwnd = CreateWindowEx(  dwExStyle,          // Расширенный стиль для окна
          "OpenGL",          // Имя класса
          title,            // Заголовок окна
          WS_CLIPSIBLINGS |        // Требуемый стиль для окна
          WS_CLIPCHILDREN |        // Требуемый стиль для окна
          dwStyle,          // Выбираемые стили для окна
          0, 0,            // Позиция окна
		  width,    // Вычисление подходящей ширины
          height,    // Вычисление подходящей высоты
          prnt,            // Parent
          NULL,            // Нет меню
          hInst,          // Дескриптор приложения
          NULL ) ) )          // Не передаём ничего до WM_CREATE (???)
	{
		KillGLWindow();                // Восстановить экран
		MessageBox( NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;                // Вернуть false
	}

	hGWnd=hwnd;
	hGInst=hInst;
	
	static  PIXELFORMATDESCRIPTOR pfd=   // pfd сообщает Windows каким будет вывод на экран каждого пикселя
	{
		sizeof(PIXELFORMATDESCRIPTOR),   // Размер дескриптора данного формата пикселей
		1,                               // Номер версии
		PFD_DRAW_TO_WINDOW |             // Формат для Окна
		PFD_SUPPORT_OPENGL |             // Формат для OpenGL
		PFD_DOUBLEBUFFER,                // Формат для двойного буфера
		PFD_TYPE_RGBA,                   // Требуется RGBA форма
		bits,                            // Выбирается бит глубины цвета
		0, 0, 0, 0, 0, 0,                // Игнорирование цветовых битов
		0,                               // Нет буфера прозрачности
		0,                               // Сдвиговый бит игнорируется
		0,                               // Нет буфера накопления
		0, 0, 0, 0,                      // Биты накопления игнорируются
		32,                              // 32 битный Z-буфер (буфер глубины)
		0,                               // Нет буфера трафарета
		0,                               // Нет вспомогательных буферов
		PFD_MAIN_PLANE,                  // Главный слой рисования
		0,                               // Зарезервировано
		0, 0, 0                          // Маски слоя игнорируются
	};

	if( !( hGDC = GetDC( hwnd ) ) )       // Можем ли мы получить Контекст Устройства?
	{
		KillGLWindow();                  // Восстановить экран
		MessageBox( NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;                    // Вернуть false
	}

	if(!arbMultisampleSupported)
	{
		if( !( PixelFormat = ChoosePixelFormat( hGDC, &pfd ) ) )        // Найден ли подходящий формат пикселя?
		{
			KillGLWindow();                                            // Восстановить экран
			MessageBox( NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
			return false;                                              // Вернуть false
		}

	}
	else
	{
		PixelFormat = arbMultisampleFormat;
	}

	if( !SetPixelFormat( hGDC, PixelFormat, &pfd ) )   // Возможно ли установить Формат Пикселя?
	{
		KillGLWindow();                               // Восстановить экран
		MessageBox( NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;                                 // Вернуть false
	}

	if( !( hGRC = wglCreateContext( hGDC ) ) )          // Возможно ли установить Контекст Рендеринга?
	{
		KillGLWindow();                               // Восстановить экран
		MessageBox( NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
		return false;                                 // Вернуть false
	}

	if( !wglMakeCurrent( hGDC, hGRC ) )  // Попробовать активировать Контекст Рендеринга
	{
		KillGLWindow();                // Восстановить экран
		MessageBox( NULL, "Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;                  // Вернуть false
	}

	if(!arbMultisampleSupported && CHECK_FOR_MULTISAMPLE)
	{
	
		if(InitMultisample(wc.hInstance,hwnd,pfd))
		{
			KillGLWindow();
			return CreateGLWindow(prnt, hInst, WndProc, title, width, height, 32);
		}
	}

	ShowWindow( hwnd, SW_SHOW );              // Показать окно
	SetForegroundWindow( hwnd );              // Слегка повысим приоритет
	SetFocus( hwnd );                         // Установить фокус клавиатуры на наше окно
	ReSizeGLScene( width, height );           // Настроим перспективу для нашего OpenGL экрана.

	if( !InitGL() )                           // Инициализация только что созданного окна
	{
		KillGLWindow();                       // Восстановить экран
		MessageBox( NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
		return false;                         // Вернуть false
	}

	return true;                              // Всё в порядке!
}
Ejemplo n.º 23
0
BOOL CreateGLWindow(LPCSTR title,int width,int height,int bits,bool fullscreenflag)
{
	static bool firstStartFunc=true;
	
	static GLuint    PixelFormat=0;              // Хранит результат после поиска

	WNDCLASS  wc;                // Структура класса окна
	DWORD    dwExStyle;              // Расширенный стиль окна
	DWORD    dwStyle;              // Обычный стиль окна
	RECT WindowRect;                // Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;              // Установить левую составляющую в 0
	WindowRect.right=(long)width;              // Установить правую составляющую в Width
	WindowRect.top=(long)0;                // Установить верхнюю составляющую в 0
	WindowRect.bottom=(long)height;              // Установить нижнюю составляющую в Height
	fullscreen=fullscreenflag;              // Устанавливаем значение глобальной переменной fullscreen

	hInstance=GetModuleHandle(NULL);        // Считаем дескриптор нашего приложения
	wc.style=CS_HREDRAW | CS_VREDRAW | CS_OWNDC;      // Перерисуем при перемещении и создаём скрытый DC
	wc.lpfnWndProc=(WNDPROC)WndProc;          // Процедура обработки сообщений
	wc.cbClsExtra=0;              // Нет дополнительной информации для окна
	wc.cbWndExtra=0;              // Нет дополнительной информации для окна
	wc.hInstance=hInstance;            // Устанавливаем дескриптор
	wc.hIcon=LoadIcon(NULL,IDI_WINLOGO);        // Загружаем иконку по умолчанию
	wc.hCursor=LoadCursor(NULL,IDC_ARROW);        // Загружаем указатель мышки
	wc.hbrBackground=NULL;              // Фон не требуется для GL
	wc.lpszMenuName=NULL;              // Меню в окне не будет
	wc.lpszClassName=DEF_WINDOWCLASSNAME;            // Устанавливаем имя классу

	if(!RegisterClass(&wc))              // Пытаемся зарегистрировать класс окна
	{
		MessageBox(NULL,TEXT("Failed To Register The Window Class."),TEXT("ERROR"),MB_OK | MB_ICONEXCLAMATION);
		return false;                // Выход и возвращение функцией значения false
	}

	if (fullscreen)                // Полноэкранный режим?
	{
		DEVMODE dmScreenSettings;            // Режим устройства
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));    // Очистка для хранения установок
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);      // Размер структуры Devmode
		dmScreenSettings.dmPelsWidth=width;        // Ширина экрана
		dmScreenSettings.dmPelsHeight=height;        // Высота экрана
		dmScreenSettings.dmBitsPerPel=bits;        // Глубина цвета
		dmScreenSettings.dmFields=DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;// Режим Пикселя
		// Пытаемся установить выбранный режим и получить результат.  Примечание: CDS_FULLSCREEN убирает панель управления.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// Если переключение в полноэкранный режим невозможно, будет предложено два варианта: оконный режим или выход.
			if (MessageBox(NULL,TEXT("The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?"),TEXT("NeHe GL"),MB_YESNO | MB_ICONEXCLAMATION)==IDYES )
			{
				fullscreen = false;          // Выбор оконного режима (fullscreen = false)
			}
			else
			{
				// Выскакивающее окно, сообщающее пользователю о закрытие окна.
				MessageBox(NULL,TEXT("Program Will Now Close."),TEXT("ERROR"), MB_OK | MB_ICONSTOP );
				return false;            // Выход и возвращение функцией false
			}
		}
	}
	if(fullscreen)                  // Мы остались в полноэкранном режиме?
	{
		dwExStyle=WS_EX_APPWINDOW;          // Расширенный стиль окна
		dwStyle=WS_POPUP;            // Обычный стиль окна
		ShowCursor(false);              // Скрыть указатель мышки
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;      // Расширенный стиль окна
		dwStyle=WS_OVERLAPPEDWINDOW;        // Обычный стиль окна
	}
	AdjustWindowRectEx(&WindowRect,dwStyle,false,dwExStyle);      // Подбирает окну подходящие размеры
	if(!(hWnd=CreateWindowEx(dwExStyle,          // Расширенный стиль для окна
		DEF_WINDOWCLASSNAME,          // Имя класса
		title,            // Заголовок окна
		WS_CLIPSIBLINGS |        // Требуемый стиль для окна
		WS_CLIPCHILDREN |        // Требуемый стиль для окна
		dwStyle,          // Выбираемые стили для окна
		0,0,            // Позиция окна
		WindowRect.right-WindowRect.left,    // Вычисление подходящей ширины
		WindowRect.bottom-WindowRect.top,    // Вычисление подходящей высоты
		NULL,            // Нет родительского
		NULL,            // Нет меню
		hInstance,          // Дескриптор приложения
		NULL)))          // Не передаём ничего до WM_CREATE (???)
	{
		KillGLWindow();                // Восстановить экран
		MessageBox(NULL,TEXT("Window Creation Error."),TEXT("ERROR"),MB_OK | MB_ICONEXCLAMATION);
		return false;                // Вернуть false
	}
	if(!(hDC=GetDC(hWnd)))              // Можем ли мы получить Контекст Устройства?
	{
		KillGLWindow();                // Восстановить экран
		MessageBox(NULL,TEXT("Can't Create A GL Device Context."),TEXT("ERROR"),MB_OK | MB_ICONEXCLAMATION);
		return false;                // Вернуть false
	}

	static  PIXELFORMATDESCRIPTOR pfd=            // pfd сообщает Windows каким будет вывод на экран каждого пикселя
		{
			sizeof(PIXELFORMATDESCRIPTOR),            // Размер дескриптора данного формата пикселей
			1,                  // Номер версии
			PFD_DRAW_TO_WINDOW |              // Формат для Окна
			PFD_SUPPORT_OPENGL |              // Формат для OpenGL	(****************************************************************************************************************************)
			PFD_DOUBLEBUFFER,              // Формат для двойного буфера
			PFD_TYPE_RGBA,                // Требуется RGBA формат
			bits,                  // Выбирается бит глубины цвета
			0, 0, 0, 0, 0, 0,              // Игнорирование цветовых битов
			0,                  // Нет буфера прозрачности
			0,                  // Сдвиговый бит игнорируется
			0,                  // Нет буфера накопления
			0, 0, 0, 0,                // Биты накопления игнорируются
			32,                  // 32 битный Z-буфер (буфер глубины)
			1,                  // Нет!!!ЕСТЬ!!! буфера трафарета				(***************************************************************************************************************************)
			0,                  // Нет вспомогательных буферов
			PFD_MAIN_PLANE,                // Главный слой рисования
			0,                  // Зарезервировано
			0, 0, 0                  // Маски слоя игнорируются
		};


	if (firstStartFunc)
	{
		if(!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))        // Найден ли подходящий формат пикселя?
		{
			KillGLWindow();                // Восстановить экран
			MessageBox(NULL,TEXT("Can't Find A Suitable PixelFormat."),TEXT("ERROR"),MB_OK | MB_ICONEXCLAMATION);
			return false;                // Вернуть false
		}
	}
	
	
	if(!SetPixelFormat(hDC,PixelFormat,&pfd))          // Возможно ли установить Формат Пикселя?
	{
		KillGLWindow();                // Восстановить экран
		MessageBox(NULL,TEXT("Can't Set The PixelFormat."),TEXT("ERROR"),MB_OK | MB_ICONEXCLAMATION);
		return false;                // Вернуть false
	}

	//DescribePixelFormat(hDC,PixelFormat,sizeof(tek_pf),&tek_pf);

	

	if(!(hRC=wglCreateContext(hDC)))          // Возможно ли установить Контекст Рендеринга?
	{
		KillGLWindow();                // Восстановить экран
		MessageBox(NULL,TEXT("Can't Create A GL Rendering Context."),TEXT("ERROR"),MB_OK | MB_ICONEXCLAMATION);
		return false;                // Вернуть false
	}
	
	if(!wglMakeCurrent(hDC,hRC))            // Попробовать активировать Контекст Рендеринга
	{
		KillGLWindow();                // Восстановить экран
		MessageBox(NULL,TEXT("Can't Activate The GL Rendering Context."),TEXT("ERROR"),MB_OK | MB_ICONEXCLAMATION);
		return false;                // Вернуть false
	}


	if (firstStartFunc)
	{
		//включение мультисемплинга
		//проверка поддержки расширения
		if (glewInit()==GLEW_OK)
		{
			if (glewIsSupported("GL_ARB_multisample"))
			{
				// Эти атрибуты – биты, которые мы хотим протестировать в нашем типе
				// Все довольно стандартно, только одно на чем мы хотим
				// действительно сфокусироваться - это SAMPLE BUFFERS ARB и WGL SAMPLES
				// Они выполнят главную проверку на предмет: есть или нет
				// у нас поддержка множественной выборки
				int iAttributes[] = {
					WGL_DRAW_TO_WINDOW_ARB,GL_TRUE, // Истинна, если формат пикселя может быть использован в окне
					WGL_SUPPORT_OPENGL_ARB,GL_TRUE, // Истинна, если поддерживается OpenGL
					WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, // Полная аппаратная поддержка
					WGL_COLOR_BITS_ARB,24,          // Цветность
					WGL_ALPHA_BITS_ARB,8,           // Размерность альфа-канала
					WGL_DEPTH_BITS_ARB,16,          // Глубина буфера глубины
					WGL_STENCIL_BITS_ARB,0,         // Глубина буфера шаблона
					WGL_DOUBLE_BUFFER_ARB,GL_TRUE,  // Истина, если используется двойная буферизация
					WGL_SAMPLE_BUFFERS_ARB,GL_TRUE, // Что мы и хотим
					WGL_SAMPLES_ARB, MULTISAMPLE_LEVEL ,            // проверка на 4x тип
					0,0};
				int pixelFormat_;
				int level=MULTISAMPLE_LEVEL;
				pixelFormat_=selectMaxMultisampleLevel(hDC,iAttributes,&level);
				if (pixelFormat_!=-1)
				{
					PixelFormat=pixelFormat_;
					KillGLWindow();
					firstStartFunc=false;
					return CreateGLWindow(title,width,height,bits,fullscreenflag);
				}
			}
		}
	}
	else
		firstStartFunc=true;






	ShowWindow(hWnd,SW_SHOW);              // Показать окно
	SetForegroundWindow(hWnd);              // Слегка повысим приоритет
	SetFocus(hWnd);                // Установить фокус клавиатуры на наше окно
	ReSizeGLScene(width,height);              // Настроим перспективу для нашего OpenGL экрана.
	if(!InitGL())                  // Инициализация только что созданного окна
	{
		KillGLWindow();                // Восстановить экран
		MessageBox(NULL,TEXT("Initialization Failed."),TEXT("ERROR"),MB_OK | MB_ICONEXCLAMATION);
		return false;                // Вернуть false
	}



	



	return true;                  // Всё в порядке!
}
Ejemplo n.º 24
0
int WINAPI WinMain(HINSTANCE	hInstance,			// Instance
	HINSTANCE	hPrevInstance,						// Previous Instance
	LPSTR		lpCmdLine,							// Command Line Parameters
	int			nCmdShow)							// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	bDone = FALSE;							// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL, MSG_RUNINFULLSCREEN,
		MSG_STARTFULLSCREEN, MB_YESNO | MB_ICONQUESTION) == IDNO)
	{
		g_bFullscreen = FALSE;						// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow(WINDOW_TITLE, WINDOW_WIDTH,
		WINDOW_HEIGHT, WINDOW_BIT, g_bFullscreen))
	{
		return 0;										// Quit If Window Was Not Created
	}

	while (!bDone)										// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message == WM_QUIT)					// Have We Received A Quit Message?
			{
				bDone = TRUE;							// If So done=TRUE
			}
			else										// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);					// Translate The Message
				DispatchMessage(&msg);					// Dispatch The Message
			}
		}
		else											// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if (g_bActive)								// Program Active?
			{
				if (g_bKeysArr[VK_ESCAPE])				// Was ESC Pressed?
				{
					bDone = TRUE;						// ESC Signalled A Quit
				}
				else									// Not Time To Quit, Update Screen
				{
					if (!g_bPause)
					{
						DrawGLScene();						// Draw The Scene
						SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
					}
					
					/*--- Handle 'L' key ---*/
					if (g_bKeysArr['L'] && !g_bLPress)	// L key being pressed not held?
					{
						g_bLPress = TRUE;				// Become TRUE
						g_bLight = !g_bLight;			// Toggle light TRUE/FALSE
						if (!g_bLight)
						{
							glDisable(GL_LIGHTING);		// Disable lighting
						}
						else
						{
							glEnable(GL_LIGHTING);		// Enable lighting
						}
					}
					if (!g_bKeysArr['L'])				// Has L key been released?
					{
						g_bLPress = FALSE;				// If so, become FALSE
					}
					/*--- Handle 'F' key ---*/
					if (g_bKeysArr['F'] && !g_bFPress)	// Is F key being pressed not held?
					{
						g_bFPress = TRUE;
						g_uFilter += 1;
						if (g_uFilter >= NUMBER_FILTER)
						{
							g_uFilter = 0;
						}
					}
					if (!g_bKeysArr['F'])
					{
						g_bFPress = FALSE;
					}
					/*--- Handle 'B' key ---*/
					if (g_bKeysArr['B'] && !g_bBPress)
					{
						g_bBPress = TRUE;
						g_bBlend = !g_bBlend;
						if (g_bBlend)
						{
							glEnable(GL_BLEND);
							glDisable(GL_DEPTH_TEST);
						}
						else
						{
							glDisable(GL_BLEND);
							glEnable(GL_DEPTH_TEST);
						}
					}
					if (!g_bKeysArr['B'])
					{
						g_bBPress = FALSE;
					}
					/*--- Handle 'T' key ---*/
					if (g_bKeysArr['T'] && !g_bTPress)
					{
						g_bTPress = TRUE;
						g_bTwinkle = !g_bTwinkle;
					}
					if (!g_bKeysArr['T'])
					{
						g_bTPress = FALSE;
					}
					/*--- Handle 'P' key ---*/
					if (g_bKeysArr['P'] && !g_bPPress)
					{
						g_bPPress = TRUE;
						g_bPause = !g_bPause;
					}
					if (!g_bKeysArr['P'])
					{
						g_bPPress = FALSE;
					}
				}
			}

			if (g_bKeysArr[VK_F1])						// Is F1 Being Pressed?
			{
				g_bKeysArr[VK_F1] = FALSE;				// If So Make Key FALSE
				KillGLWindow();							// Kill Our Current Window
				g_bFullscreen = !g_bFullscreen;			// Toggle Full screen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow(WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BIT, g_bFullscreen))
				{
					return 0;							// Quit If Window Was Not Created
				}
			}
	
			// Handle move left-right
			if (g_bKeysArr[VK_LEFT])
			{
				g_bKeysArr[VK_LEFT] = FALSE;
				g_MoveX -= (float)cos(g_RotateY * PIOVER180) * 0.05f;
				g_MoveZ += (float)sin(g_RotateY * PIOVER180) * 0.05f;
			}
			if (g_bKeysArr[VK_RIGHT])
			{
				g_bKeysArr[VK_RIGHT] = FALSE;

				g_MoveX += (float)cos(g_RotateY * PIOVER180) * 0.05f;
				g_MoveZ -= (float)sin(g_RotateY * PIOVER180) * 0.05f;
			}
			// Handle move forward
			if (g_bKeysArr[VK_UP])
			{
				g_bKeysArr[VK_UP] = FALSE;
				g_MoveX -= (float)sin(g_RotateY * PIOVER180) * 0.05f;
				g_MoveZ -= (float)cos(g_RotateY * PIOVER180) * 0.05f;
				// Foot step
				//if (g_Walkbiasangle >= (TWO_PI - 1))
				//{
				//	g_Walkbiasangle = 0.0f;
				//}
				//else
				//{
				//	g_Walkbiasangle += g_WalkbiasAngleDelta;
				//}
				//g_MoveY = (float)sin(g_Walkbiasangle * PIOVER180) / 20.0f;
				//g_MoveY += (float)sin(g_RotateX * PIOVER180) * 0.05f;
				//g_MoveZ -= (float)cos(g_RotateX * PIOVER180) * 0.05f;
			}
			// Handle move backward
			if (g_bKeysArr[VK_DOWN])
			{
				g_bKeysArr[VK_DOWN] = FALSE;
				g_MoveX += (float)sin(g_RotateY * PIOVER180) * 0.05f;
				g_MoveZ += (float)cos(g_RotateY * PIOVER180) * 0.05f;
				// Foot step
				//if (g_Walkbiasangle <= 1.0f)
				//{
				//	g_Walkbiasangle = (TWO_PI - 1);
				//}
				//else
				//{
				//	g_Walkbiasangle -= g_WalkbiasAngleDelta;
				//}
				//g_MoveY = (float)sin(g_Walkbiasangle * PIOVER180) / 20.0f;
				//g_MoveY -= (float)sin(g_RotateX * PIOVER180) * 0.05f;
				//g_MoveZ += (float)cos(g_RotateX * PIOVER180) * 0.05f;
			}
			//// Handle move forward-backward
			//if (g_bKeysArr[VK_ADD])
			//{
			//	g_bKeysArr[VK_ADD] = FALSE;
			//	g_MoveZ -= g_MDeltaZ;
			//}
			// Handle rotate follow Y asix
			if (g_bKeysArr[VK_INSERT])
			{
				g_bKeysArr[VK_INSERT] = FALSE;
				g_RotateY += g_RDeltaY;
			}
			//if (g_bKeysArr[VK_DELETE])
			//{
			//	g_bKeysArr[VK_DELETE] = FALSE;
			//	g_RotateX -= g_RDeltaX;
			//}
			// Handle rotate follow X asix
			if (g_bKeysArr[VK_HOME])
			{
				g_bKeysArr[VK_HOME] = FALSE;
				g_RotateX += g_RDeltaX;
			}
			// Handle rotate follow X asix
			if (g_bKeysArr[VK_END])
			{
				g_bKeysArr[VK_END] = FALSE;
				g_RotateX -= g_RDeltaX;
			}
			// Handle rotate follow Y axis
			if (g_bKeysArr[VK_PRIOR])
			{
				g_bKeysArr[VK_PRIOR] = FALSE;
				g_RotateY -= g_RDeltaY;
			}
			//if (g_bKeysArr[VK_NEXT])
			//{
			//	g_bKeysArr[VK_NEXT] = FALSE;
			//	g_RotateZ -= g_RDeltaZ;
			//	//g_MoveZ += 0.02f;
			//}
			//if (g_bKeysArr[VK_SUBTRACT])
			//{
			//	g_bKeysArr[VK_SUBTRACT] = FALSE;
			//	g_MoveZ += g_MDeltaZ;
			//}

			//if (g_bKeysArr[VK_TAB])
			//{
			//	g_bKeysArr[VK_TAB] = FALSE;
			//}

			// Handle move left-right
			if (g_bKeysArr['A'])
			{
				g_bKeysArr['A'] = FALSE;
				g_fTextPosX -= 0.0051f;
			}
			if (g_bKeysArr['D'])
			{
				g_bKeysArr['D'] = FALSE;
				g_fTextPosX += 0.0051f;
			}
			// Handle move up-down
			if (g_bKeysArr['W'])
			{
				g_bKeysArr['W'] = FALSE;
				g_fTextPosY += 0.005f;
			}
			if (g_bKeysArr['S'])
			{
				g_bKeysArr['S'] = FALSE;
				g_fTextPosY -= 0.005f;
			}
		}
	}

	// Shutdown
	KillGLWindow();										// Kill The Window
	return (msg.wParam);								// Exit The Program
}
Ejemplo n.º 25
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("MotorCycle",800,600,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							// ESC or DrawGLScene Signalled A Quit
			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
			}

			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("MotorCycle",800,600,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				}
			}
			if (keys[VK_UP])
			{
				lookupdown+= 1.0f;
				//glTranslatef(xtrans, ytrans, 0.0f);
			}

			if (keys[VK_DOWN])
			{
				lookupdown-= 1.0f;
			}
			if (keys[VK_RIGHT])
			{
				heading += 1.0f;
				yrot = heading;
			}

			if (keys[VK_LEFT])
			{
				heading -= 1.0f;	
				yrot = heading;
			}
			if (keys['F'])
			{

				xpos -= (float)sin(heading*piover180) * 0.05f;
				zpos -= (float)cos(heading*piover180) * 0.05f;
				if (walkbiasangle >= 359.0f)
				{
					walkbiasangle = 0.0f;
				}
				else
				{
					walkbiasangle+= 10;
				}
				walkbias = (float)sin(walkbiasangle * piover180)/20.0f;
			}

			if (keys['B'])
			{
				xpos += (float)sin(heading*piover180) * 0.05f;
				zpos += (float)cos(heading*piover180) * 0.05f;
				if (walkbiasangle <= 1.0f)
				{
					walkbiasangle = 359.0f;
				}
				else
				{
					walkbiasangle-= 10;
				}
				walkbias = (float)sin(walkbiasangle * piover180)/20.0f;
			}
/*
			if (keys['Z'] && !zp)
			{
				zp = true;
				if(zout)
				{
					zoom += 5.0f;
					zout = false;
				}
				else
				{
					zoom -= 5.0f;
					zout = true;
				}
			}
			if(!keys['Z'])
				zp = false;
*/
			if (keys[VK_NEXT])
			{

				xpos -= (float)sin(heading*piover180) * 0.05f;
				zpos -= (float)cos(heading*piover180) * 0.05f;
				if (walkbiasangle >= 359.0f)
				{
					walkbiasangle = 0.0f;
				}
				else
				{
					walkbiasangle+= 10;
				}
				walkbias = (float)sin(walkbiasangle * piover180)/20.0f;
			}

			if (keys[VK_PRIOR])
			{
				xpos += (float)sin(heading*piover180) * 0.05f;
				zpos += (float)cos(heading*piover180) * 0.05f;
				if (walkbiasangle <= 1.0f)
				{
					walkbiasangle = 359.0f;
				}
				else
				{
					walkbiasangle-= 10;
				}
				walkbias = (float)sin(walkbiasangle * piover180)/20.0f;
			}

			if(keys['C'])
			{
				heading = 0;
				xpos = 0;
				zpos = 0;
				zoom = 0;
				yrot = 0;				// Y Rotation
				walkbias = 0;
				walkbiasangle = 0;
				lookupdown = 0.0f;
				wire = 0;
				perspective = 1;
				wp = false;
				pp = false;
				op = false;
				zp = false;
				zout = true;
				DrawGLScene();
			}
			if(keys['W'] && !wp)
			{
				wp = true;
				if(wire == 0)
					wire = 1;
				else
					wire = 0;
			}
			if(!keys['W'])
			{
				wp = false;
			}
			if(keys['P'] && !pp)
			{
				pp = true;
				perspective = 1;
			}
			if(!keys['P'])
				pp = false;
			if(keys['O'] && !op)
			{
				op = true;
				perspective = 0;
			}
			if(!keys['O'])
				op = false;
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}
Ejemplo n.º 26
0
//
// keyPressed
//
void keyPressed(KeySym key)
{

    switch(key)
    {
    case XK_Tab:
        ToggleViewMode();
        break;

    case XK_Down:

        Toggle_MenuItems(1);


        break;

    case XK_Up:
        Toggle_MenuItems(-1);

        break;

    case XK_Return:
    case XK_space:

        if (Set_MenuMode())
        {
            done = true;

            return;
        } // end of the if

        if (ant_globals->menu_mode == MENU_HELP_MODE)
        {
            // ShowCursor
        } // end of the if
        else if (ant_globals->menu_mode == MENU_RUN_MODE)
        {
            // Show Cursor
        }  // end of if -else

        break;

    case XK_Escape:
        //done = true;

        // draw the scene
        Handle_Esc();
        break;

    case XK_P:
    case XK_p:

        if (ant_globals->menu_mode == MENU_RUN_MODE) {
            TogglePaused();
        } // end of the if

        break;

    case XK_Q:
    case XK_q:
        done = true;
        break;

    case XK_F1:
        KillGLWindow();
        GLWin.fs = !GLWin.fs;
        CreateGLWindow("glAnts", SCREEN_WIDTH, SCREEN_HEIGHT, 24, GLWin.fs);
        break;

    };

} // end of the function
int WINAPI WinMain(	HINSTANCE	hInstance,				// Instance
			HINSTANCE	hPrevInstance,					// Previous Instance
			LPSTR		lpCmdLine,						// Command Line Parameters
			int		nCmdShow)							// Window Show State
{

	MSG	msg;											// Windows Message Structure
	BOOL	done=FALSE;									// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;								// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("Project",640,480,16,fullscreen))
	{
		return 0;										// Quit If Window Was Not Created
	}

	while(!done)										// Loop That Runs Until done=TRUE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))		// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)					// Have We Received A Quit Message?
			{
				done=TRUE;								// If So done=TRUE
			}
			else										// If Not, Deal With Window Messages
			{

				TranslateMessage(&msg);					// Translate The Message
				DispatchMessage(&msg);					// Dispatch The Message
			}
		}
		else											// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if (active)									// Program Active?
			{
				if (keys[VK_ESCAPE])					// Was ESC Pressed?
				{
					done=TRUE;							// ESC Signalled A Quit
				}
				else									// Not Time To Quit, Update Screen
				{
					DrawGLScene();						// Draw The Scene
					SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
				}
			}
			if (keys[VK_F1])							// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;						// If So Make Key FALSE
				KillGLWindow();							// Kill Our Current Window
				fullscreen=!fullscreen;					// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("Project",640,480,16,fullscreen))
				{
					return 0;							// Quit If Window Was Not Created
				}
			}
		}
	}
	// Shutdown
	KillGLWindow();										// Kill The Window
	return (msg.wParam);								// Exit The Program
}
Ejemplo n.º 28
0
//
// main
//
int main(int argc, char **argv)
{
    int i;

    char buffer[80];

    XEvent event;
    KeySym key;

    done = False;

    // default to windowed mode
    GLWin.fs = FULLSCREEN_MODE;

    CreateGLWindow("glAnts", SCREEN_WIDTH, SCREEN_HEIGHT, 24, GLWin.fs);

    /* wait for events*/
    while (!done)
    {
        /* handle the events in the queue */
        while (XPending(GLWin.dpy) > 0)
        {
            XNextEvent(GLWin.dpy, &event);
            switch (event.type)
            {
            case Expose:
                if (event.xexpose.count != 0)
                    break;



                Run_Anim();

                break;

            case ConfigureNotify:
                /* call resizeGLScene only if our window-size changed */
                if ((event.xconfigure.width != GLWin.width) ||
                        (event.xconfigure.height != GLWin.height))
                {
                    GLWin.width = event.xconfigure.width;
                    GLWin.height = event.xconfigure.height;

                    printf("Resize event\n");

                    ResizeGLScene(event.xconfigure.width,
                                  event.xconfigure.height);
                }
                break;



            case ButtonPress:

                // exit on mouse press

                // done = True;
                break;

            case KeyPress:

                if (ant_globals->menu_mode == MENU_SETTINGS_MODE)
                {

                    key = XLookupKeysym(&event.xkey, 0);


                    Cmd_KeyPress(key);

                    // handle fullscreen press differently
                    if (key == XK_F1)
                        break;

                    // process the key
                    Cmd_Keys(key);

                    XLookupString(&event, buffer, 10, &key, 0 ) ;
                    Alpha_Keys(buffer);

                }  else {

                    key = XLookupKeysym(&event.xkey, 0);
                    keyPressed(key);
                    keys[event.xkey.keycode] = true;

                } // end of the if

                break;

            case KeyRelease:

                if (ant_globals->menu_mode == MENU_SETTINGS_MODE) {

                } else {

                    keys[event.xkey.keycode] = false;

                } // end of the - if


                break;

            case ClientMessage:
                if (*XGetAtomName(GLWin.dpy, event.xclient.message_type) ==
                        *"WM_PROTOCOLS")
                {
                    printf("Exiting glants...\n");
                    done = True;
                }
                break;
            default:
                break;
            }
        }

        // Check for key pressed in the camera
        HandleCameraKeys(keys);

        // run the gambit------
        Run_Anim();

    }
    KillGLWindow();

    return 0;

} // end of main //
Ejemplo n.º 29
0
int WINAPI WinMain(HINSTANCE	hInstance,			// 当前窗口实例
					HINSTANCE	hPrevInstance,		// 前一个窗口实例
					LPSTR		lpCmdLine,			// 命令行参数
					int			nCmdShow)			// 窗口显示状态
{
	MSG		msg;									// Windowsx消息结构
	BOOL	done=FALSE;								// 用来退出循环的Bool 变量

	// 提示用户选择运行模式
	if (MessageBox(NULL,"你想在全屏模式下运行么?", "设置全屏模式",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// FALSE为窗口模式
	}

	// 创建OpenGL窗口
	if (!CreateGLWindow("NeHe's OpenGL 程序框架",640,480,16,fullscreen))
	{
		return 0;									// 失败退出
	}

	while(!done)									// 保持循环直到 done=TRUE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// 有消息在等待吗?
		{
			if (msg.message==WM_QUIT)				// 收到退出消息?
			{
				done=TRUE;							// 是,则done=TRUE
			}
			else									// 不是,处理窗口消息
			{
				TranslateMessage(&msg);				// 翻译消息
				DispatchMessage(&msg);				// 发送消息
			}
		}
		else										// 如果没有消息
		{
			// 绘制场景。监视ESC键和来自DrawGLScene()的退出消息
			if (active)								// 程序激活的么?
			{
				if (keys[VK_ESCAPE])				// ESC 按下了么?
				{
					done=TRUE;						// ESC 发出退出信号
				}
				else								// 不是退出的时候,刷新屏幕
				{
					DrawGLScene();					// 绘制场景
					SwapBuffers(hDC);				// 交换缓存 (双缓存)
					if (keys['L'] && !lp)
					{
						lp = true;
						light = !light;
						if (!light)
						{
							glDisable(GL_LIGHTING);
						}
						else
						{
							glEnable(GL_LIGHTING);
						}
					}
					if (!keys['L'])
					{
						lp = FALSE;
					}

					if (keys['F'] && !fp)
					{
						fp = true;
						g_filter += 1;
						if (g_filter > 2)
						{
							g_filter = 0;
						}
					}
					if (!keys['F'])
					{
						fp = FALSE;
					}
					if (keys[VK_PRIOR])
					{
						g_z -= 0.02f;
					}
					if (keys[VK_NEXT])
					{
						g_z += 0.02f;
					}
					if (keys[VK_UP])
					{
						g_xSpeed -= 0.01f;
					}
					if (keys[VK_DOWN])
					{
						g_xSpeed += 0.01f;
					}
					if (keys[VK_RIGHT])
					{
						g_ySpeed += 0.01f;
					}
					if (keys[VK_LEFT])
					{
						g_ySpeed -= 0.01f;
					}

					if (keys['B'] && !g_bp)
					{
						g_bp = true;
						g_blend = !g_blend;
						if (g_blend)
						{
							glEnable(GL_BLEND);
							glDisable(GL_DEPTH_TEST);
						}
						else
						{
							glDisable(GL_BLEND);
							glEnable(GL_DEPTH_TEST);
						}
					}

					if (!keys['B'])
					{
						g_bp = false;
					}
				}
			}

			if (keys[VK_F1])						// F1键按下了么?
			{
				keys[VK_F1]=FALSE;					// 若是,使对应的Key数组中的值为 FALSE
				KillGLWindow();						// 销毁当前的窗口
				fullscreen=!fullscreen;				// 切换 全屏 / 窗口 模式
				// 重建 OpenGL 窗口
				if (!CreateGLWindow("NeHe's OpenGL 程序框架",640,480,16,fullscreen))
				{
					return 0;						// 如果窗口未能创建,程序退出
				}
			}
		}
	}

	// 关闭程序
	KillGLWindow();									// 销毁窗口
	return (msg.wParam);							// 退出程序
}
Ejemplo n.º 30
0
int main(int argc, char *argv[])
{
  Uint8* keys; 
  int done=0; 

  SM.LoadSound("eerie.wav");
  SM.LoadSound("indicator.wav");
  SM.LoadSound("static.mp3");
  SM.LoadMusic("UNREAL.S3M");
  

  // Create a new OpenGL window with the title "Cone3D Basecode" at
  // 640x480x32, fullscreen and check for errors along the way
  if(CreateGLWindow("SDL & OpenGL", 640, 480, 16, 0) == 0){
      printf("Could not initalize OpenGL :(\n\n");
      KillGLWindow();
      return 0;
  }


  // Hide the mouse cursor
  //SDL_ShowCursor(0);

  // This is the main loop for the entire program and it will run until done==TRUE
  int changeit = 1;
  int reset = 1;

  makeMickey();
  while(!done){

    // Draw the scene
    if (changeit == 1)
       {
       DrawGLScene();
       changeit = 0;
       }

    // And poll for events
    SDL_Event event;
    while ( SDL_PollEvent(&event) ) {
      switch (event.type) {
      case SDL_KEYDOWN:
      case SDL_KEYUP:
	  handleKey(event.key);
	  break;
        
      case SDL_MOUSEMOTION:
	  SDL_PeepEvents (&event,9,SDL_GETEVENT,SDL_MOUSEMOTION);
	  handleMouseMotion(event.motion);
          if (reset == 1)
             {
             xpos = 0;
             ypos = 0;
             reset = 0;
             }
          //this affects the screen.
          changeit = 1;
	  break;
      case SDL_MOUSEBUTTONDOWN:
      case SDL_MOUSEBUTTONUP:
	  handleMouseButtons(event.button);
	  break;
        case SDL_QUIT:
          // then we're done and we'll end this program
          done=1;
          break;
        default:
          break;
      }// switch

    }// while 

    // Get the state of the keyboard keys
    keys = SDL_GetKeyState(NULL);

    // and check if ESCAPE has been pressed. If so then quit
    if(keys[SDLK_ESCAPE]) done=1;
  }// while done

  // Kill the GL & SDL screens
  
  KillGLWindow();
  // And quit
  return 0;
}