void
CMSWindowsServerTaskBarReceiver::showStatus()
{
	// create the window
	createWindow();

	// lock self while getting status
	lock();

	// get the current status
	std::string status = getToolTip();

	// get the connect clients, if any
	const CClients& clients = getClients();

	// done getting status
	unlock();

	// update dialog
	HWND child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_STATUS);
	SendMessage(child, WM_SETTEXT, 0, (LPARAM)status.c_str());
	child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_CLIENTS);
	SendMessage(child, LB_RESETCONTENT, 0, 0);
	for (CClients::const_iterator index = clients.begin();
							index != clients.end(); ) {
		const char* client = index->c_str();
		if (++index == clients.end()) {
			SendMessage(child, LB_ADDSTRING, 0, (LPARAM)client);
		}
		else {
			SendMessage(child, LB_INSERTSTRING, (WPARAM)-1, (LPARAM)client);
		}
	}

	if (!IsWindowVisible(m_window)) {
		// position it by the mouse
		POINT cursorPos;
		GetCursorPos(&cursorPos);
		RECT windowRect;
		GetWindowRect(m_window, &windowRect);
		int  x = cursorPos.x;
		int  y = cursorPos.y;
		int fw = GetSystemMetrics(SM_CXDLGFRAME);
		int fh = GetSystemMetrics(SM_CYDLGFRAME);
		int ww = windowRect.right  - windowRect.left;
		int wh = windowRect.bottom - windowRect.top;
		int sw = GetSystemMetrics(SM_CXFULLSCREEN);
		int sh = GetSystemMetrics(SM_CYFULLSCREEN);
		if (fw < 1) {
			fw = 1;
		}
		if (fh < 1) {
			fh = 1;
		}
		if (x + ww - fw > sw) {
			x -= ww - fw;
		}
		else {
			x -= fw;
		}
		if (x < 0) {
			x = 0;
		}
		if (y + wh - fh > sh) {
			y -= wh - fh;
		}
		else {
			y -= fh;
		}
		if (y < 0) {
			y = 0;
		}
		SetWindowPos(m_window, HWND_TOPMOST, x, y, ww, wh,
							SWP_SHOWWINDOW);
	}
}
Esempio n. 2
0
void
CMSWindowsClientTaskBarReceiver::showStatus()
{
	// create the window
	createWindow();

	// lock self while getting status
	lock();

	// get the current status
	std::string status = getToolTip();

	// done getting status
	unlock();

	// update dialog
	HWND child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_STATUS);
	SendMessage(child, WM_SETTEXT, 0, (LPARAM)status.c_str());

	if (!IsWindowVisible(m_window)) {
		// position it by the mouse
		POINT cursorPos;
		GetCursorPos(&cursorPos);
		RECT windowRect;
		GetWindowRect(m_window, &windowRect);
		int  x = cursorPos.x;
		int  y = cursorPos.y;
		int fw = GetSystemMetrics(SM_CXDLGFRAME);
		int fh = GetSystemMetrics(SM_CYDLGFRAME);
		int ww = windowRect.right  - windowRect.left;
		int wh = windowRect.bottom - windowRect.top;
		int sw = GetSystemMetrics(SM_CXFULLSCREEN);
		int sh = GetSystemMetrics(SM_CYFULLSCREEN);
		if (fw < 1) {
			fw = 1;
		}
		if (fh < 1) {
			fh = 1;
		}
		if (x + ww - fw > sw) {
			x -= ww - fw;
		}
		else {
			x -= fw;
		}
		if (x < 0) {
			x = 0;
		}
		if (y + wh - fh > sh) {
			y -= wh - fh;
		}
		else {
			y -= fh;
		}
		if (y < 0) {
			y = 0;
		}
		SetWindowPos(m_window, HWND_TOPMOST, x, y, ww, wh,
							SWP_SHOWWINDOW);
	}
}
Esempio n. 3
0
int main(int argc, char *argv[])
{
	if(argc >= 2)
	{
		if(strcmp(argv[1],"-h") == 0 || strcmp(argv[1],"--help") == 0)
		{
			printf("\nConway\n");
			printf("Copyright 2015 Harley Wiltzer\n\n");
			printf("conway:\t\tOpen conway with a random color\n");
			printf("conway 1:\tOpen conway blue theme\n");
			printf("conway 2:\tOpen conway red theme\n");
			printf("conway 3:\tOpen conway green theme\n");
			printf("conway 4:\tOpen conway yellow theme\n");
			printf("conway 5:\tOpen conway light blue theme\n");
			printf("conway 6:\tOpen conway orange theme\n");
			printf("conway 7:\tOpen conway white theme\n");
			printf("\n");
			printf("While running conway...\n");
			printf("=======================\n");
			printf("q:\t\tClose conway\n");
			printf("space:\t\tActivate/Kill cell\n");
			printf("enter:\t\tStart ticking\n");
			printf("h:\t\tMove cursor left\n");
			printf("j:\t\tMove cursor down\n");
			printf("k:\t\tMove cursor up\n");
			printf("l:\t\tMove cursor right\n");
			printf("d:\t\tClear all cells\n");
			printf("=:\t\tIncrease the amount of ticks by 10\n");
			printf("-:\t\tDecrease the amount of ticks by 10\n");
			printf("+:\t\tIncrease the amount of ticks by 1\n");
			printf("_:\t\tDecrease the amount of ticks by 1\n");
			return 0;
		}
	}
	int i, c;
	
	initCurses();
	showSplash();
	totalTicks = 0;	
	refresh();
	getch();

	win = createWindow(WIN_WIDTH,rows,0,cols - WIN_WIDTH - 1);
	cols = cols - WIN_WIDTH - 1;
	xs = rows;
	ys = cols / 2;
	area = rows * cols;
	game = createWindow(cols - 1,rows,0,0);
	ticks = DEFAULT_TICKS;
	
	int cells[area / 2];
	for(i = 0; i < area/2; i++)
	{
		cells[i] = 0;
	}

	x = y = row = col = 0;
	if(has_colors() == 0) wprintw(game,"NO COLORS\n");

	if(argc < 2)
	{
		srand(time(NULL));
		color = rand()%7 + 1;
	}
	else
	{
		if(atoi(argv[1]) > 7 || atoi(argv[1]) < 1)
		{
			srand(time(NULL));
			color = rand()%7 + 1;
		}
		else 
		{
			color = atoi(argv[1]);
		}
	}

	x = ys/2;
	y = xs/2;
	wmove(game,y, x * 2);
	x = 2;
	y = 2;
	wrefresh(game);
	updateWin(cells,area/2);
	wmove(game,y,x * 2);

	x = ys/2;
	y = xs/2;

	wmove(game,y,x * 2);

	while((ch = getch()) != 'q')
	{
		wclear(game);
		wclear(win);
		int r, c;
		
		render(cells,area/2);	
		wmove(game,y, x * 2);

		switch(ch)
		{
			case 'h':
				if (x % ys == 0) break;
				x -= 1;
				wmove(game,y, x * 2);
				wrefresh(game);
				break;
			case 'j':
				if ((y + 1) % xs == 0) break;
				y += 1;
				wmove(game,y, x * 2);
				wrefresh(game);
				break;
			case 'k':
				if (y % xs == 0) break;
				y -= 1;
				wmove(game,y, x * 2);
				wrefresh(game);
				break;
			case 'l':
				if((x+1)%ys == 0) break;
				x += 1;
				wmove(game,y, x * 2);
				wrefresh(game);
				break;
			case ' ':
				cells[y * ys + x] = !cells[y * ys + x];
				if(cells[y * ys + x]) drawCell(x,y);
				else eraseCell(x,y);
				updateWin(cells,area/2);
				break;
			case '\n':
				update(cells, area/2);
				break;
			case 'd':
				memset(cells,0,area/2);
				int q;
				for(q = 0; q < area/2; q++)
				{
					cells[q] = 0;
				}
				totalTicks = 0;
				render(cells, area/2);
				updateWin(cells,area/2);
				break;
			case '=':
				ticks += 10;
				updateWin(cells,area/2);
				break;
			case '-':
				if(ticks >= 20) ticks -= 10;
				updateWin(cells,area/2);
				break;
			case '+':
				ticks++;
				updateWin(cells,area/2);
				break;
			case '_':
				if(ticks > 2) ticks--;
				updateWin(cells, area/2);
				break;
			default:
				break;
		}
		updateWin(cells,area/2);
		wrefresh(game);
	}
	destroyWindow(game);
	destroyWindow(win);
	endwin();
	return 0;
}
Esempio n. 4
0
myGazeHaptic::myGazeHaptic(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	createWindow();
}
Esempio n. 5
0
/*
=====================
	initSystem
=====================
*/
BOOL initSystem() {

	//get game directory path (Ex: D:\Games\Netrix)
	//
	GetCurrentDirectory( MAX_PATH, k_system.szStartDir );

	N_InitTrace();

	//init Win32 system
	//
	initWin32();

	//System
	//
	k_system.pLeftGame	= NULL;
	k_system.pRightGame	= NULL;
	k_system.gameType	= GNO;
	k_system.pause		= FALSE;
	k_system.flags		= 0;
	k_system.dwAccumTime	= 0;
	k_system.dwTime		= 0;
	
	//Maps
	//
	k_system.cMaps	= 0;
	k_system.pMaps	= NULL;
	k_system.idMap	= -1;
	
	//Bots
	//
	k_system.cBots	= 0;
	k_system.pBots	= NULL;
	k_system.idBotLeft	= -1;
	k_system.idBotRight	= -1;
	
	//Paths
	//
	k_system.pPaths	= NULL;
	k_system.cPaths	= 0;
	
	//HWND
	//
	k_system.hwnd		= NULL;
	k_system.hwndLeft	= NULL;
	k_system.hwndRight	= NULL;
	
	k_system.cPlayers	= 0;

	initRandom();

	cfInitTable();

	//resources
	//
	loadResources();
	
	//init bot system
	//
	botInit();

	//Skins
	//
	loadSkin( &k_system.hSkinRgnLeft, &k_system.hSkinBitmapLeft,
		&k_system.cxSkinLeft, &k_system.cySkinLeft, IDR_SKIN_LEFT );

	loadSkin( &k_system.hSkinRgnRight, &k_system.hSkinBitmapRight,
		&k_system.cxSkinRight, &k_system.cySkinRight, IDR_SKIN_RIGHT );

	createWindow();
	
	//GUI
	//
	populateGUI();

	if( !initGraphics( NEUTRAL ) )
		return FALSE;

	if( !initGraphics( LEFTGAME ) )
		return FALSE;

	updateWindow( CGF_DRAWLEFT );
	
	//winmm
	timeBeginPeriod( 1 );
	
	return TRUE;
}
Esempio n. 6
0
Window::Window(const ConstructionData &ctorData) :
		_windowHandle(createWindow(ctorData, this)),
		_surface(_windowHandle.get()),
		_inputSource(_windowHandle.get())
{
}
Esempio n. 7
0
bool CDDApplication::createMainWindow()
{
	// Create a main game window
	return createWindow("DiabloDream");
}
Esempio n. 8
0
BOOL winapiwrapper::createWindow()
{

	return(createWindow("mywrapperdefclass",0,0,800,600));

}
Esempio n. 9
0
int main(int, char**)
{
	// Timing
	unsigned int lastUpdate;
	unsigned int thisUpdate;
	unsigned int dt = 0;

	// FPS
	int frames = 0;
	int fps = 0;
	int lastFPSUpdate;

	// Pixel buffer
	PixelBuffer pixelBuffer(width, height);

	// SDL structures
	SDL_Event event;
	SDL_Window* window;
	SDL_Renderer* renderer;
	SDL_Texture* renderTexture;

	// Seed random number generator
	srand((unsigned int)time(0));

	// Initialise SDL
	SDL_Init(SDL_INIT_EVERYTHING);

	// Initilialise timing
	lastUpdate = thisUpdate = SDL_GetTicks();
	lastFPSUpdate = lastUpdate;

	// Create window
	window = createWindow(TITLE_FORMAT, width, height);

	// Create renderer
	renderer = createRenderer(window);

	// Create render texture
	renderTexture = createTexture(renderer, width, height);

	// Set window values
    //int width  = INITIAL_WIDTH;
    //int height = INITIAL_HEIGHT;

	// Create and initialise managers
	BallManager ballManager(width, height);

	// Create some balls
	ballManager.createBalls(INITIAL_BALLS);

	// Start main loop
	bool running = true;
	bool rendering_enabled = true;
    bool movement_enabled  = true;

	while (running)
	{
		const SDL_Rect screenRect = {0, 0, width, height};

		// Update timer
		thisUpdate = SDL_GetTicks();
		dt = thisUpdate - lastUpdate;

		// Handle all events
		while (SDL_PollEvent(&event))
		{
			// End when the user closes the window or presses esc
			if (event.type == SDL_QUIT ||
				(event.type == SDL_KEYDOWN && event.key.keysym.scancode == SDL_SCANCODE_ESCAPE))
			{
				running = false;
			}

			// Handle keyboard input
			if (event.type == SDL_KEYDOWN)
			{
				// Toggle rendering when player presses R
				if (event.key.keysym.sym == SDLK_r)
				{
					// Disable rendering
					rendering_enabled = !rendering_enabled;

					// Clear screen to white
                    pixelBuffer.clear(0xFFFFFFFF);

					// Update render texture
					SDL_UpdateTexture(renderTexture, &screenRect, pixelBuffer.getBuffer(), width * 4);

					// Render texture to screen
					SDL_RenderCopy(renderer, renderTexture, &screenRect, &screenRect);

					// Flip screen buffer
					SDL_RenderPresent(renderer);
				}
				// Toggle movement when player presses M
				else if (event.key.keysym.sym == SDLK_m)
				{
                    movement_enabled = !movement_enabled;
				}
				// Add 10 balls when user presses right arrow
				else if (event.key.keysym.scancode == SDL_SCANCODE_RIGHT)
				{
					ballManager.createBalls(100);
				}
				// Remove 10 balls when user presses left arrow
				else if (event.key.keysym.scancode == SDL_SCANCODE_LEFT)
				{
					ballManager.destroyBalls(100);
				}
			}
		}

		// Update game
        float delta = dt*GAME_SPEED;

        if(movement_enabled)
        {
            process_collisions(width, height, ballManager.balls());
            process_movement(delta, ballManager.balls());
            process_gravity(delta, ballManager.balls());
        }

        // Clear window
        SDL_RenderClear(renderer);

		if (rendering_enabled)
		{
			// Clear buffer
            pixelBuffer.clear(CLEAR_COLOUR);

			// Run rendering system
            process_rendering(&pixelBuffer, ballManager.balls());

			// Blit buffer to screen renderer
			SDL_UpdateTexture(renderTexture, &screenRect, pixelBuffer.getBuffer(), width * 4);

			// Render texture to screen
			SDL_RenderCopy(renderer, renderTexture, &screenRect, &screenRect);

			// Flip screen buffer
			SDL_RenderPresent(renderer);
		}

		// Update last time
		lastUpdate = thisUpdate;

		// Average FPS calculations
		frames++;
		if (thisUpdate - lastFPSUpdate >= 1000)
		{
			// Update FPS counters
			fps = frames;
			frames = 0;
			lastFPSUpdate = thisUpdate;
		}

		// Update window title
		{
			const int titleBufferLen = 256;
			char titleBuffer[titleBufferLen];

			// Format window title
			const char* renderingEnabled = (rendering_enabled ? "Enabled" : "Disabled");
			const char* movementEnabled = (true ? "Enabled" : "Disabled");
			snprintf(titleBuffer, titleBufferLen, TITLE_FORMAT, ballManager.ballCount(), fps, renderingEnabled, movementEnabled);

			// Set window title
			SDL_SetWindowTitle(window, titleBuffer);
		}
	}

	// Clean up
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	SDL_Quit();

	return 0;
}
JSValue JSDOMWindow::showModalDialog(ExecState* exec)
{
    String url = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0));
    JSValue dialogArgs = exec->argument(1);
    String featureArgs = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(2));

    Frame* frame = impl()->frame();
    if (!frame)
        return jsUndefined();
    Frame* lexicalFrame = toLexicalFrame(exec);
    if (!lexicalFrame)
        return jsUndefined();
    Frame* dynamicFrame = toDynamicFrame(exec);
    if (!dynamicFrame)
        return jsUndefined();

    if (!DOMWindow::canShowModalDialogNow(frame) || !domWindowAllowPopUp(dynamicFrame))
        return jsUndefined();

    HashMap<String, String> features;
    DOMWindow::parseModalDialogFeatures(featureArgs, features);

    const bool trusted = false;

    // The following features from Microsoft's documentation are not implemented:
    // - default font settings
    // - width, height, left, and top specified in units other than "px"
    // - edge (sunken or raised, default is raised)
    // - dialogHide: trusted && boolFeature(features, "dialoghide"), makes dialog hide when you print
    // - help: boolFeature(features, "help", true), makes help icon appear in dialog (what does it do on Windows?)
    // - unadorned: trusted && boolFeature(features, "unadorned");

    FloatRect screenRect = screenAvailableRect(frame->view());

    WindowFeatures wargs;
    wargs.width = WindowFeatures::floatFeature(features, "dialogwidth", 100, screenRect.width(), 620); // default here came from frame size of dialog in MacIE
    wargs.widthSet = true;
    wargs.height = WindowFeatures::floatFeature(features, "dialogheight", 100, screenRect.height(), 450); // default here came from frame size of dialog in MacIE
    wargs.heightSet = true;

    wargs.x = WindowFeatures::floatFeature(features, "dialogleft", screenRect.x(), screenRect.right() - wargs.width, -1);
    wargs.xSet = wargs.x > 0;
    wargs.y = WindowFeatures::floatFeature(features, "dialogtop", screenRect.y(), screenRect.bottom() - wargs.height, -1);
    wargs.ySet = wargs.y > 0;

    if (WindowFeatures::boolFeature(features, "center", true)) {
        if (!wargs.xSet) {
            wargs.x = screenRect.x() + (screenRect.width() - wargs.width) / 2;
            wargs.xSet = true;
        }
        if (!wargs.ySet) {
            wargs.y = screenRect.y() + (screenRect.height() - wargs.height) / 2;
            wargs.ySet = true;
        }
    }

    wargs.dialog = true;
    wargs.resizable = WindowFeatures::boolFeature(features, "resizable");
    wargs.scrollbarsVisible = WindowFeatures::boolFeature(features, "scroll", true);
    wargs.statusBarVisible = WindowFeatures::boolFeature(features, "status", !trusted);
    wargs.menuBarVisible = false;
    wargs.toolBarVisible = false;
    wargs.locationBarVisible = false;
    wargs.fullscreen = false;

    Frame* dialogFrame = createWindow(exec, lexicalFrame, dynamicFrame, frame, url, "", wargs, dialogArgs);
    if (!dialogFrame)
        return jsUndefined();

    JSDOMWindow* dialogWindow = toJSDOMWindow(dialogFrame, currentWorld(exec));
    dialogFrame->page()->chrome()->runModal();

    Identifier returnValue(exec, "returnValue");
    if (dialogWindow->allowsAccessFromNoErrorMessage(exec)) {
        PropertySlot slot;
        // This is safe, we have already performed the origin security check and we are
        // not interested in any of the DOM properties of the window.
        if (dialogWindow->JSGlobalObject::getOwnPropertySlot(exec, returnValue, slot))
            return slot.getValue(exec, returnValue);
    }
    return jsUndefined();
}
Esempio n. 11
0
BOOL winapiwrapper::createWindow(int x, int y, int nWidth, int nHeight)
{

	return(createWindow("mywrapperdefclass",x,y,nWidth,nHeight));

}
JSValue JSDOMWindow::open(ExecState* exec)
{
    String urlString = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0));
    AtomicString frameName = exec->argument(1).isUndefinedOrNull() ? "_blank" : ustringToAtomicString(exec->argument(1).toString(exec));
    WindowFeatures windowFeatures(valueToStringWithUndefinedOrNullCheck(exec, exec->argument(2)));

    Frame* frame = impl()->frame();
    if (!frame)
        return jsUndefined();
    Frame* lexicalFrame = toLexicalFrame(exec);
    if (!lexicalFrame)
        return jsUndefined();
    Frame* dynamicFrame = toDynamicFrame(exec);
    if (!dynamicFrame)
        return jsUndefined();

    Page* page = frame->page();

    // Because FrameTree::find() returns true for empty strings, we must check for empty framenames.
    // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
    if (!domWindowAllowPopUp(dynamicFrame) && (frameName.isEmpty() || !frame->tree()->find(frameName)))
        return jsUndefined();

    // Get the target frame for the special cases of _top and _parent.  In those
    // cases, we can schedule a location change right now and return early.
    bool topOrParent = false;
    if (frameName == "_top") {
        frame = frame->tree()->top();
        topOrParent = true;
    } else if (frameName == "_parent") {
        if (Frame* parent = frame->tree()->parent())
            frame = parent;
        topOrParent = true;
    }
    if (topOrParent) {
        String completedURL;
        if (!urlString.isEmpty())
            completedURL = completeURL(exec, urlString).string();

        if (!shouldAllowNavigation(exec, frame))
            return jsUndefined();

        const JSDOMWindow* targetedWindow = toJSDOMWindow(frame, currentWorld(exec));
        if (!completedURL.isEmpty() && (!protocolIsJavaScript(completedURL) || (targetedWindow && targetedWindow->allowsAccessFrom(exec)))) {
            bool userGesture = processingUserGesture();

            // For whatever reason, Firefox uses the dynamicGlobalObject to
            // determine the outgoingReferrer.  We replicate that behavior
            // here.
            String referrer = dynamicFrame->loader()->outgoingReferrer();

            frame->redirectScheduler()->scheduleLocationChange(completedURL, referrer, !lexicalFrame->script()->anyPageIsProcessingUserGesture(), false, userGesture);
        }
        return toJS(exec, frame->domWindow());
    }

    // In the case of a named frame or a new window, we'll use the createWindow() helper
    FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0,
                         windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0);
    DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect);

    windowFeatures.x = windowRect.x();
    windowFeatures.y = windowRect.y();
    windowFeatures.height = windowRect.height();
    windowFeatures.width = windowRect.width();

    frame = createWindow(exec, lexicalFrame, dynamicFrame, frame, urlString, frameName, windowFeatures, JSValue());

    if (!frame)
        return jsUndefined();

    return toJS(exec, frame->domWindow());
}
//-----------------------------------------------------------------------------
// Description: Function to enable multisampling AA.
// Parameters:
// Returns:
// Notes: 
//-----------------------------------------------------------------------------
void FWWin32GLWindow::enableAA()
{
	if(mAAPixelFormat)
		return;

	// try to get extension
	PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 
		(PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");

	// just return if not available
	if(!wglChoosePixelFormatARB)
		return;

	int				iPixelFormat;
	BOOL			bValid;
	unsigned int	iNumFormats;

	float			fAttributes[] =
	{
		0.f,
		0.f,
	};

	int iAttributes[] =
	{
		WGL_DRAW_TO_WINDOW_ARB,	GL_TRUE,
		WGL_SUPPORT_OPENGL_ARB,	GL_TRUE,
		WGL_ACCELERATION_ARB,	WGL_FULL_ACCELERATION_ARB,
		WGL_COLOR_BITS_ARB,		mDispInfo.mColorBits,
		WGL_ALPHA_BITS_ARB,		mDispInfo.mAlphaBits, 
		WGL_DEPTH_BITS_ARB,		mDispInfo.mDepthBits,
		WGL_STENCIL_BITS_ARB,	mDispInfo.mStencilBits,
		WGL_DOUBLE_BUFFER_ARB,	GL_TRUE,
		WGL_SAMPLE_BUFFERS_ARB,	GL_TRUE,
		WGL_SAMPLES_ARB,		4,
		0,						0,
	};

	// see if 4x multisampling is supported
	bValid = wglChoosePixelFormatARB(mHDc, iAttributes, fAttributes, 1, &iPixelFormat, &iNumFormats);

	if(bValid && iNumFormats >= 1)
	{
		// we got a valid format, so delete the current ogl context and recreate it

		mDontQuit = true;
		destroyWindow();
		mAAPixelFormat = iPixelFormat;
		createWindow();
		mDontQuit = false;
		return;
	}

	// see if 2x multisampling is supported
	iAttributes[19] = 2;
	bValid = wglChoosePixelFormatARB(mHDc, iAttributes, fAttributes, 1, &iPixelFormat, &iNumFormats);

	if(bValid && iNumFormats >= 1)
	{
		// we got a valid format, so delete the current ogl context and recreate it

		mDontQuit = true;
		destroyWindow();
		mAAPixelFormat = iPixelFormat;
		createWindow();
		mDontQuit = false;
		return;
	}

	// couldn't create AA buffer
	mDispInfo.mAntiAlias = false;
}
Esempio n. 14
0
Renderer::Renderer() : videoInit_(false), window_(nullptr), context_(nullptr)
#ifdef OCULUSVR
    , hmd_(nullptr), renderTex_(0), depthTex_(0), framebuffer_(0)
#endif
{
    if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
    {
        throwSDLError();
    }

    videoInit_ = true;

#ifdef __APPLE__
    // Apple's drivers don't support the compatibility profile on GL >v2.1
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#endif
    // 32 crashes mysteriously on my laptop
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    Config& config = Core::get().config();

    int multisamples = config.getInt("Renderer.multisamples", 16);

    if(multisamples != 0)
    {
        // Enable MSAA
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multisamples);
    }

    createWindow();

    context_ = SDL_GL_CreateContext(window_);

    if(context_ == nullptr)
    {
        throwSDLError();
    }

#ifdef _MSC_VER
    GLenum glewErr = glewInit();

    if(glewErr != GLEW_OK)
    {
        string err("Unable to initialize GLEW: ");
        err.append((const char*)glewGetErrorString(glewErr));
        throw runtime_error(err);
    }
#endif

    fieldOfView_ = config.getFloat("Renderer.fieldOfView", 90.0);

    string textureFiltering = config.getString("Renderer.textureFiltering", "trilinear");

    if(textureFiltering == "bilinear")
    {
        textureMinFilter_ = GL_LINEAR_MIPMAP_NEAREST;
    }
    else if(textureFiltering == "trilinear")
    {
        textureMinFilter_ = GL_LINEAR_MIPMAP_LINEAR;
    }
    else
    {
        throw runtime_error("Bad value for Renderer.textureFiltering");
    }

    textureMaxAnisotropy_ = static_cast<GLfloat>(config.getFloat("Renderer.anisotropyLevel", 0.0));

    if(textureMaxAnisotropy_ != 0.0f)
    {
#ifdef _MSC_VER
        if(!GLEW_EXT_texture_filter_anisotropic)
        {
            throw runtime_error("Anisotropic filtering not supported");
        }
#endif

        GLfloat driverMaxAnisotropy;
        glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &driverMaxAnisotropy);

        if(textureMaxAnisotropy_ < 0.0f || textureMaxAnisotropy_ > driverMaxAnisotropy)
        {
            throw runtime_error("Bad value for Renderer.maxAnisotropyLevel");
        }
    }

    renderHitGeometry_ = config.getBool("Renderer.renderHitGeometry", false);
}
Esempio n. 15
0
EGLView::EGLView()
{
	createWindow();
	initEgl();
}
Esempio n. 16
0
void Tutorial::initGlut()
{
  switch (_tutorialID) {
  case 1:
  case 2:
  case 3:
    _pGameCamera = nullptr;
  case 4:
  case 5:
  case 6:
  case 7:
  case 8:
  case 9:
  case 10:
  case 11:
  case 12:
  case 13:
  case 14:
    setWindowSize(WINDOW_WIDTH_1_14, WINDOW_HEIGHT_1_14);
    _pGameCamera = new Camera(WINDOW_WIDTH_1_14, WINDOW_HEIGHT_1_14);
    break;
  case 15:
    setWindowSize(WINDOW_WIDTH_15_17, WINDOW_HEIGHT_15_17);
    _pGameCamera = new Camera(WINDOW_WIDTH_15_17, WINDOW_HEIGHT_15_17);
    break;
  case 16:
    setWindowSize(WINDOW_WIDTH_16, WINDOW_HEIGHT_16);
    _pGameCamera = new Camera(WINDOW_WIDTH_16, WINDOW_HEIGHT_16);
    break;
  case 17:
  case 18:
  case 19:
  case 20:
  case 21:
  case 22:
  case 23:
    return;

  default:
    setWindowSize(WINDOW_WIDTH_1_14, WINDOW_HEIGHT_1_14);
    _pGameCamera = new Camera(WINDOW_WIDTH_1_14, WINDOW_HEIGHT_1_14);
    break;
  }

  setWindowLocation();
  createWindow(_tutorialID);


  glutDisplayFunc(renderFunction);
  glutIdleFunc(idleFunction);
  glutSpecialFunc(specialKeyboardCB);
  glutKeyboardFunc(keyboardCB);
  glutPassiveMotionFunc(passiveMouseCB);

  if (_tutorialID == 15 || _tutorialID == 17) {
    glutGameModeString("1920x1080@24");
    glutEnterGameMode();
  }
  else if (_tutorialID == 16) {
    glutGameModeString("1280x1024@24");
  }
}
Esempio n. 17
0
bool Window_Win32::createWindow( const std::string &titlewstring )
{
 	return createWindow( m_windowPosX, m_windowPosY, m_windowWidth, m_windowHeight, titlewstring );
}
 void createRenderingTarget() {
   createWindow(glm::uvec2(1280, 800), glm::ivec2(100, 100));
 }
Esempio n. 19
0
File: main.cpp Progetto: huxs/dcfx
int main(int argc, char** argv)
{
#if 1    
    uint32_t width = 1280;
    uint32_t height = 720;
#else    
    uint32_t width = 1920;
    uint32_t height = 1080;
#endif
    
    HWND hwnd = createWindow(width, height);

    input::initialize(hwnd);

    RenderDevice renderer((void*)hwnd, glm::ivec2(width, height));

    RendererEx r(&renderer);
    
    dcfx::ProgramHandle program = asset::loadVSFSProgram(renderer.m_context,
							 "../../dcfx/assets/shaders/gl/mesh.vert",
							 "../../dcfx/assets/shaders/gl/mesh.frag");
    // Sponza model
    Model model;
    model.create(renderer.m_context, "../../dcfx/assets/models/sponza.obj");

    for(uint32_t i = 0; i < model.m_meshes.size(); ++i)
    {
	Mesh* mesh = &model.m_meshes[i];

	RenderObject object;
	object.m_bounds = mesh->m_bounds;
	object.m_vertexBuffer = mesh->m_vertexBuffer;
	object.m_indexBuffer = mesh->m_indexBuffer;
	object.m_program = program;
	object.m_material = model.m_materials[mesh->m_materialIndex];
	object.m_offset = 0;
	object.m_count = mesh->m_numIndices;

	renderer.addRenderObject(object, mesh->m_bounds);
    }

    // Create camera
    LookAt lookAt;
    lookAt.m_pos = glm::vec3(0,0,0);
    lookAt.m_distance = 10.0f;
    
    PerspectiveCamera camera;
    camera.initialize(glm::vec3(-918.825623, 1060.502686, -35.351444), 45.0f, glm::vec2(width, height), 0.25f, 5000.0f);

    camera.m_orient.yawGlobal(-90.0f);
    
    renderer.m_camera = &camera;

    // Set Directional light.
    DirectionalLight sunLight;
    sunLight.m_orient.yaw(90.0f);
    sunLight.m_orient.pitch(120.0f);
    sunLight.m_color = glm::vec3(1.0, 0.8, 0.3);
    r.setDirectionalLight(sunLight);

    __int64 cntsPerSec = 0;
    QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec);
    float secsPerCnt = 1.0f / (float)cntsPerSec;

    __int64 prevTimeStamp = 0;
    QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp);

    int inputMode = 0;
    
    MSG msg;
    msg.message = WM_NULL;
    while (!g_exit)
    {
	{
	    TimedBlock b(0);
	    
	    WaitForInputIdle(GetCurrentProcess(), 16);

	    while (0 != PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) )
	    {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	    }

	    __int64 currTimeStamp = 0;
	    QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp);
	    float dt = (currTimeStamp - prevTimeStamp) * secsPerCnt;
	    prevTimeStamp = currTimeStamp;

	    input::getState();

	    // Select input mode
	    if(input::isKeyPressedAndReleased(DIK_F1))
	    {
		inputMode = 0;
	    }	
	    if(input::isKeyPressedAndReleased(DIK_F2))
	    {
		inputMode = 1;
	    }
	
	    if(inputMode == 0)
	    {
		camera.firstPerson(dt);
	    }
	    else if(inputMode == 1)
	    {
		camera.lookAt(&lookAt, dt);
	    }

	    r.render(dt);
	}

	r.setCPUFrameTime(g_Counters[0]);

	renderer.frame();
    }

    renderer.m_context->deleteProgram(program);
    
    model.destroy(renderer.m_context);

    input::shutdown();
    
    DestroyWindow(hwnd);

    return 0;
}
Esempio n. 20
0
int main() {
    createWindow(640, 480);
    int framecnt = 0;

    Image* img = loadTGAImage("cat.tga");
    if(img == NULL) {
        printf("ERROR: Could not open image file\n");
        exit(1);
    }
    Image* font = loadTGAImage("font.tga");
    if(font == NULL) {
        printf("ERROR: Could not load font file\n");
        exit(1);
    }

    int mousePos[2] = {0, 0};

    while(1) {
        KeyEvent ev;
        profileBlockStart("eventHandling");
        while(pollEvent(&ev)) {
            switch(ev.type) {
            case KEY_DOWN:
                printf("Keycode: %d\n", ev.key);
                if(ev.key == 53) {
                    goto endGame;
                }
                break;
            case MOUSE_MOVE:
                mousePos[0] = ev.posx;
                mousePos[1] = ev.posy;
                break;
            }
        }
        profileBlockEnd("eventHandling");
        Image* fb = getFramebuffer();
        profileBlockStart("clearFramebuffer");
        Color backColor = color(0, 30, 140, 40);
        clear(fb, &backColor);
        profileBlockEnd("clearFramebuffer");

        profileBlockStart("paintCats");
        for(int i = 0; i < 300; i++) {
            paint(PAINT_OVER, img, fb, (int)(fb->width / 2 + (i * 0.7) * sin(i * 1.221 + framecnt * 0.004)),
                  (int)(fb->height / 2 + (i * 0.7) * cos(i * 1.221 + framecnt * 0.004)));
        }
        profileBlockEnd("paintCats");

        profileBlockStart("paintText");
        Color textColor = color(255, 200, 250, 255);
        textColor.a = (framecnt * 32) % 256;
        drawText(fb, font, &textColor, "Hello world!", mousePos[0], mousePos[1]);
        drawButton(fb, font, "Click here!", 120, 200);

        profileBlockEnd("paintText");

        profileBlockStart("flush");
        flushFramebuffer();
        profileBlockEnd("flush");
        framecnt++;
    }

endGame:
    saveProfile("_profile.json");
    deleteImage(img);
    closeWindow();
}
Esempio n. 21
0
HWND createDummyWindow(int origin_x, int origin_y) {
	if (!registerDummyWindow())
		return NULL;
	return createWindow(_CONTEXT_PRIVATE_CLASS_NAME, origin_x, origin_y, 1, 1, false, false, NULL);
}
Esempio n. 22
0
int _glfwPlatformCreateWindow(_GLFWwindow* window,
                              const _GLFWwndconfig* wndconfig,
                              const _GLFWctxconfig* ctxconfig,
                              const _GLFWfbconfig* fbconfig)
{
    int status;

    if (!createWindow(window, wndconfig))
        return GLFW_FALSE;

    if (ctxconfig->api != GLFW_NO_API)
    {
        if (!_glfwCreateContext(window, ctxconfig, fbconfig))
            return GLFW_FALSE;

#if defined(_GLFW_WGL)
        status = _glfwAnalyzeContext(window, ctxconfig, fbconfig);

        if (status == _GLFW_RECREATION_IMPOSSIBLE)
            return GLFW_FALSE;

        if (status == _GLFW_RECREATION_REQUIRED)
        {
            // Some window hints require us to re-create the context using WGL
            // extensions retrieved through the current context, as we cannot
            // check for WGL extensions or retrieve WGL entry points before we
            // have a current context (actually until we have implicitly loaded
            // the vendor ICD)

            // Yes, this is strange, and yes, this is the proper way on WGL

            // As Windows only allows you to set the pixel format once for
            // a window, we need to destroy the current window and create a new
            // one to be able to use the new pixel format

            // Technically, it may be possible to keep the old window around if
            // we're just creating an OpenGL 3.0+ context with the same pixel
            // format, but it's not worth the added code complexity

            // First we clear the current context (the one we just created)
            // This is usually done by glfwDestroyWindow, but as we're not doing
            // full GLFW window destruction, it's duplicated here
            _glfwPlatformMakeContextCurrent(NULL);

            // Next destroy the Win32 window and WGL context (without resetting
            // or destroying the GLFW window object)
            _glfwDestroyContext(window);
            destroyWindow(window);

            // ...and then create them again, this time with better APIs
            if (!createWindow(window, wndconfig))
                return GLFW_FALSE;
            if (!_glfwCreateContext(window, ctxconfig, fbconfig))
                return GLFW_FALSE;
        }
#endif // _GLFW_WGL
    }
    
    if (wndconfig->fullscreen)
    {
        _glfwPlatformShowWindow(window);
        if (!enterFullscreenMode(window))
            return GLFW_FALSE;
    }

    return GLFW_TRUE;
}
Esempio n. 23
0
void create_vulkan_renderer_backend(ReaperRoot& root, VulkanBackend& backend)
{
    REAPER_PROFILE_SCOPE("Vulkan", MP_RED1);
    log_info(root, "vulkan: creating backend");

    log_debug(root, "vulkan: loading {}", REAPER_VK_LIB_NAME);
    backend.vulkanLib = dynlib::load(REAPER_VK_LIB_NAME);

    vulkan_load_exported_functions(backend.vulkanLib);
    vulkan_load_global_level_functions();

    std::vector<const char*> extensions = {VK_KHR_SURFACE_EXTENSION_NAME, REAPER_VK_SWAPCHAIN_EXTENSION_NAME};

#if defined(REAPER_DEBUG)
    extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
#endif

    log_info(root, "vulkan: using {} instance level extensions", extensions.size());
    for (auto& e : extensions)
        log_debug(root, "- {}", e);

    vulkan_instance_check_extensions(extensions);

    std::vector<const char*> layers;

#if defined(REAPER_DEBUG) && !defined(REAPER_PLATFORM_WINDOWS)
    layers.push_back("VK_LAYER_LUNARG_standard_validation");
#endif

    log_info(root, "vulkan: using {} instance level layers", layers.size());
    for (auto& layer : layers)
        log_debug(root, "- {}", layer);

    vulkan_instance_check_layers(layers);

    VkApplicationInfo application_info = {
        VK_STRUCTURE_TYPE_APPLICATION_INFO, // VkStructureType            sType
        nullptr,                            // const void                *pNext
        "MyGame",                           // const char                *pApplicationName
        VK_MAKE_VERSION(
            REAPER_VERSION_MAJOR, REAPER_VERSION_MINOR, REAPER_VERSION_PATCH), // uint32_t applicationVersion
        "Reaper",                                                              // const char                *pEngineName
        VK_MAKE_VERSION(REAPER_VERSION_MAJOR, REAPER_VERSION_MINOR, REAPER_VERSION_PATCH), // uint32_t engineVersion
        REAPER_VK_API_VERSION // uint32_t                   apiVersion
    };

    uint32_t layerCount = static_cast<uint32_t>(layers.size());
    uint32_t extensionCount = static_cast<uint32_t>(extensions.size());

    VkInstanceCreateInfo instance_create_info = {
        VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,          // VkStructureType            sType
        nullptr,                                         // const void*                pNext
        0,                                               // VkInstanceCreateFlags      flags
        &application_info,                               // const VkApplicationInfo   *pApplicationInfo
        layerCount,                                      // uint32_t                   enabledLayerCount
        (layerCount > 0 ? &layers[0] : nullptr),         // const char * const        *ppEnabledLayerNames
        extensionCount,                                  // uint32_t                   enabledExtensionCount
        (extensionCount > 0 ? &extensions[0] : nullptr), // const char * const        *ppEnabledExtensionNames
    };

    Assert(vkCreateInstance(&instance_create_info, nullptr, &backend.instance) == VK_SUCCESS,
           "cannot create Vulkan instance");

    vulkan_load_instance_level_functions(backend.instance);

#if defined(REAPER_DEBUG)
    log_debug(root, "vulkan: attaching debug callback");
    vulkan_setup_debug_callback(root, backend);
#endif

    WindowCreationDescriptor windowDescriptor;
    windowDescriptor.title = "Vulkan";
    windowDescriptor.width = 800;
    windowDescriptor.height = 600;
    windowDescriptor.fullscreen = false;

    log_info(root,
             "vulkan: creating window: size = {}x{}, title = '{}', fullscreen = {}",
             windowDescriptor.width,
             windowDescriptor.height,
             windowDescriptor.title,
             windowDescriptor.fullscreen);
    IWindow* window = createWindow(windowDescriptor);

    root.renderer->window = window;

    log_debug(root, "vulkan: creating presentation surface");
    vulkan_create_presentation_surface(backend.instance, backend.presentInfo.surface, window);

    log_debug(root, "vulkan: choosing physical device");
    vulkan_choose_physical_device(root, backend, backend.physicalDeviceInfo);

    log_debug(root, "vulkan: creating logical device");
    vulkan_create_logical_device(root, backend);

    SwapchainDescriptor swapchainDesc;
    swapchainDesc.preferredImageCount = 2; // Double buffering
    swapchainDesc.preferredFormat = {VK_FORMAT_B8G8R8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR};
    swapchainDesc.preferredExtent = {windowDescriptor.width, windowDescriptor.height};

    configure_vulkan_wm_swapchain(root, backend, swapchainDesc, backend.presentInfo);
    create_vulkan_wm_swapchain(root, backend, backend.presentInfo);

    // create_vulkan_display_swapchain(root, backend);

    log_info(root, "vulkan: ready");
}
// Open the X window to sample from
bool InputWindowXWin::openLocalWindow()
{
   int i;

   mXDisplay = XOpenDisplay(mXDisplayString.c_str());    // Open display on given XDisplay
   if (NULL == mXDisplay)
   {
      vprDEBUG(vprDBG_ERROR, vprDBG_CRITICAL_LVL)
         <<  clrOutNORM(clrRED, "ERROR")
         << ": [gadget::InputWindowXWin::openTheWindow()] "
         << "Failed to open display '" << mXDisplayString << "'" << std::endl
         << vprDEBUG_FLUSH;
      return 0;
   }

   mScreen = DefaultScreen(mXDisplay);

   XVisualInfo vTemplate, *vis_infos;
   long vMask = VisualScreenMask;
   vTemplate.screen = mScreen;
   int nVisuals;

   vis_infos = XGetVisualInfo(mXDisplay, vMask, &vTemplate, &nVisuals);

   // Verify that we got at least one visual from XGetVisualInfo(3).
   if ( vis_infos != NULL && nVisuals >= 1 )
   {
      XVisualInfo* p_visinfo;

      // Try to find a visual with color depth of at least 8 bits.  Having
      // such a visual ensures that the input windows at least have a
      // black background.
      for ( i = 0, p_visinfo = vis_infos; i < nVisuals; i++, p_visinfo++ )
      {
         if ( p_visinfo->depth >= 8 )
         {
            mVisual = p_visinfo;
            break;
         }
      }

      // If we couldn't find a visual with at least 8-bit color, just use the
      // first one in the list.
      if ( i == nVisuals )
      {
          mVisual = vis_infos;
      }
   }
   // If we didn't get a matching visual, we're in trouble.
   else
   {
      vprDEBUG(vprDBG_ERROR,vprDBG_CRITICAL_LVL)
         <<  clrOutNORM(clrRED,"ERROR")
         << ": [gadget::InputWindowXWin::openTheWindow()] find visual failed"
         << std::endl << vprDEBUG_FLUSH;
      return 0;
   }

   mSWA.colormap = XCreateColormap(mXDisplay,
                                   RootWindow(mXDisplay, mVisual->screen),
                                   mVisual->visual, AllocNone);
   mSWA.background_pixel = BlackPixel(mXDisplay, mScreen);
   mSWA.border_pixel = WhitePixel(mXDisplay, mScreen);
   const unsigned int event_mask =
      ExposureMask | StructureNotifyMask | KeyPressMask | KeyReleaseMask |
      ButtonPressMask | ButtonReleaseMask | ButtonMotionMask |
      PointerMotionMask | StructureNotifyMask;
   mSWA.event_mask = event_mask;

   mXWindow = createWindow(DefaultRootWindow(mXDisplay), 1);
   createEmptyCursor(mXDisplay, mXWindow);

   setHints(mXWindow, const_cast<char*>(mInstName.c_str()),
            const_cast<char*>(mInstName.c_str()) , "VRJInputWindow", "VRJ Input Windows");

   XSelectInput(mXDisplay, mXWindow, event_mask);
   XMapWindow(mXDisplay, mXWindow);
   XFlush(mXDisplay);
   XRaiseWindow(mXDisplay, mXWindow);
   XClearWindow(mXDisplay, mXWindow);    // Try to clear the background

   vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)
      << "[gadget::InputWindowXWin::openTheWindow()] done." << std::endl
      << vprDEBUG_FLUSH;

   XFree(vis_infos);

   return 1;
}
Esempio n. 25
0
void
CMSWindowsClientTaskBarReceiver::runMenu(int x, int y)
{
	// do popup menu.  we need a window to pass to TrackPopupMenu().
	// the SetForegroundWindow() and SendMessage() calls around
	// TrackPopupMenu() are to get the menu to be dismissed when
	// another window gets activated and are just one of those
	// win32 weirdnesses.
	createWindow();
	SetForegroundWindow(m_window);
	HMENU menu = GetSubMenu(m_menu, 0);
	SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE);
	HMENU logLevelMenu = GetSubMenu(menu, 3);
	CheckMenuRadioItem(logLevelMenu, 0, 6,
							CLOG->getFilter() - kERROR, MF_BYPOSITION);
	int n = TrackPopupMenu(menu,
							TPM_NONOTIFY |
							TPM_RETURNCMD |
							TPM_LEFTBUTTON |
							TPM_RIGHTBUTTON,
							x, y, 0, m_window, NULL);
	SendMessage(m_window, WM_NULL, 0, 0);

	// perform the requested operation
	switch (n) {
	case IDC_TASKBAR_STATUS:
		showStatus();
		break;

	case IDC_TASKBAR_LOG:
		copyLog();
		break;

	case IDC_TASKBAR_SHOW_LOG:
		ARCH->showConsole(true);
		break;

	case IDC_TASKBAR_LOG_LEVEL_ERROR:
		CLOG->setFilter(kERROR);
		break;

	case IDC_TASKBAR_LOG_LEVEL_WARNING:
		CLOG->setFilter(kWARNING);
		break;

	case IDC_TASKBAR_LOG_LEVEL_NOTE:
		CLOG->setFilter(kNOTE);
		break;

	case IDC_TASKBAR_LOG_LEVEL_INFO:
		CLOG->setFilter(kINFO);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG:
		CLOG->setFilter(kDEBUG);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG1:
		CLOG->setFilter(kDEBUG1);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG2:
		CLOG->setFilter(kDEBUG2);
		break;

	case IDC_TASKBAR_QUIT:
		quit();
		break;
	}
}
Esempio n. 26
0
void gep::Renderer::initialize()
{
    m_pDebugRenderer = new DebugRenderer();
    createWindow();
    initD3DDevice();

    g_globalManager.getLogging()->logMessage("Using DirectX Version: %d.%d sdk %d", D3D11_MAJOR_VERSION, D3D11_MINOR_VERSION, D3D11_SDK_VERSION);

    // Create the dummy 2d texture
    {
        m_pDummyTexture = createTexture2D("dummy texture 2d", new DummyTexture2DLoader(), TextureMode::Static);
        m_pDummyTexture->createEmpty(4, 4, ImageFormat::RGBA8);
        auto& dummyData = m_pDummyTexture->getImageData().getData()[0];
        for(uint32 i = 0; i < 4 * 4 * 4; i+=4)
        {
            dummyData[i] = 0xFF;   //R
            dummyData[i+1] = 0;    //G
            dummyData[i+2] = 0xFF; //B
            dummyData[i+3] = 0xFF; //A
        }
        m_pDummyTexture->setHasData(true);
        m_pDummyTexture->finalize();
        g_globalManager.getResourceManager()->registerResourceType("Texture2D", m_pDummyTexture);
    }

    // Creates the dummy shader
    {
        m_pDummyShader = createShader();
        m_pDummyShader->setLoader(new ShaderFileLoader("data/base/dummy.fx"));
        m_pDummyShader->getLoader()->loadResource(m_pDummyShader);
        m_pDummyShader->finalize();
        g_globalManager.getResourceManager()->registerResourceType("Shader", m_pDummyShader);
    }

    // Register the font resource type (no fallback)
    g_globalManager.getResourceManager()->registerResourceType("Font", nullptr);

    // load engine resources
    m_pDefaultFont = g_globalManager.getResourceManager()->loadResource<Font>(FontFileLoader("data/base/dejavusans.ttf", 11), LoadAsync::No);
    m_pFontShader = g_globalManager.getResourceManager()->loadResource<Shader>(ShaderFileLoader("data/base/font.fx"), LoadAsync::No);

    g_globalManager.getResourceManager()->finalizeResourcesWithFlags(ResourceFinalize::FromRenderer);

    m_fontPosition = ShaderConstant<vec2>("position", m_pFontShader);
    m_fontColor = ShaderConstant<Color>("color", m_pFontShader);
    m_fontScreenSize = ShaderConstant<vec2>("targetSize", m_pFontShader);
    m_fontTexture = ShaderConstant<Texture2D>("diffuse", m_pFontShader);
    m_fontScreenSize.set(vec2((float)m_settings.screenResolution.x,
                              (float)m_settings.screenResolution.y));

    // text billboard
    m_pTextBillboardShader = g_globalManager.getResourceManager()->loadResource<Shader>(ShaderFileLoader("data/base/fontBillboard.fx"), LoadAsync::No);
    m_textBillboardView = ShaderConstant<mat4>("View", m_pTextBillboardShader);
    m_textBillboardProjection = ShaderConstant<mat4>("Projection", m_pTextBillboardShader);
    m_textBillboardPosition = ShaderConstant<vec3>("position", m_pTextBillboardShader);
    m_textBillboardColor = ShaderConstant<Color>("color", m_pTextBillboardShader);
    m_textBillboardTexture = ShaderConstant<Texture2D>("diffuse", m_pTextBillboardShader);
    m_textBillboardScreenSize = ShaderConstant<vec2>("targetSize", m_pTextBillboardShader);
    m_textBillboardScreenSize.set(vec2((float)m_settings.screenResolution.x,
                                       (float)m_settings.screenResolution.y));
    {
        auto aspectRatio = float(m_settings.screenResolution.x) / float(m_settings.screenResolution.y);
        m_projection = mat4::projectionMatrix(60.0f, aspectRatio, 0.1f, 10000.0f);
    }
    m_view = mat4::lookAtMatrix(vec3(300, 0, 205), vec3(0, 0, 150), vec3(0,0,1));

    {
        Vertexbuffer::DataChannel dataChannels[] =
        { Vertexbuffer::DataChannel::POSITION_2D,
        Vertexbuffer::DataChannel::TEXCOORD0 };
        m_pFontBuffer = new Vertexbuffer(m_pd3dDevice, dataChannels, Vertexbuffer::Primitive::Triangle, Vertexbuffer::Usage::Dynamic);
    }

    {
        Vertexbuffer::DataChannel dataChannels[] =
        {
            Vertexbuffer::DataChannel::POSITION
        };
        m_pLinesBuffer = new Vertexbuffer(m_pd3dDevice, dataChannels, Vertexbuffer::Primitive::Line, Vertexbuffer::Usage::Dynamic);
    }

    {
        Vertexbuffer::DataChannel dataChannels[] =
        {
            Vertexbuffer::DataChannel::POSITION_2D
        };
        m_pLines2DBuffer = new Vertexbuffer(m_pd3dDevice, dataChannels, Vertexbuffer::Primitive::Line, Vertexbuffer::Usage::Dynamic);
    }

    {
        m_pDummyModel = createModel();
        m_pDummyModel->loadFile("data/base/dummy.thModel");
        m_pDummyModel->setLoader(ModelDummyLoader().moveToHeap());
        m_pDummyModel->getLoader()->loadResource(m_pDummyModel);
        m_pDummyModel->getMaterial(0).setShader(m_pDummyShader->makeResourcePtrFromThis<Shader>());
        m_pDummyModel->finalize();
        g_globalManager.getResourceManager()->registerResourceType("Model", m_pDummyModel);
    }

    //Loading additional resources
    m_pLightingShader = g_globalManager.getResourceManager()->loadResource<Shader>(ShaderFileLoader("data/shaders/lighting.fx"));
    m_pLightingAnimatedShader = g_globalManager.getResourceManager()->loadResource<Shader>(ShaderFileLoader("data/shaders/lightingAnimated.fx"));
    m_pLinesShader = g_globalManager.getResourceManager()->loadResource<Shader>(ShaderFileLoader("data/base/lines.fx"));
    m_pWireframeShader = g_globalManager.getResourceManager()->loadResource<Shader>(ShaderFileLoader("data/shaders/wireframe.fx"));
    m_lineColor = ShaderConstant<Color>("Color", m_pLinesShader);
    m_lineView = ShaderConstant<mat4>("View", m_pLinesShader);
    m_lineProjection = ShaderConstant<mat4>("Projection", m_pLinesShader);

    m_pLines2DShader = g_globalManager.getResourceManager()->loadResource<Shader>(ShaderFileLoader("data/base/lines2D.fx"));
    m_line2DColor = ShaderConstant<Color>("Color", m_pLines2DShader);
    m_lines2DScreenSize = ShaderConstant<vec2>("targetSize", m_pLines2DShader);
    m_lines2DScreenSize.set(vec2((float)m_settings.screenResolution.x,
                                 (float)m_settings.screenResolution.y));

    #ifdef _DEBUG
    const GUID ID_ID3DUserDefinedAnnotation = { 0xb2daad8b, 0x03d4, 0x4dbf, { 0x95, 0xeb,  0x32,  0xab,  0x4b,  0x63,  0xd0,  0xab } };
    m_pDeviceContext->QueryInterface(ID_ID3DUserDefinedAnnotation, (void**)&m_pUserDefinedAnnotation);
    if(m_pUserDefinedAnnotation == nullptr || !m_pUserDefinedAnnotation->GetStatus())
    {
        GEP_RELEASE_AND_NULL(m_pUserDefinedAnnotation);
        HMODULE pModule = LoadLibraryA("d3d9.dll");
        D3DPREF_BeginEvent = (D3DPERF_BeginEvent_Func)GetProcAddress(pModule, "D3DPERF_BeginEvent");
        D3DPREF_EndEvent = (D3DPERF_EndEvent_Func)GetProcAddress(pModule, "D3DPERF_EndEvent");
    }
    #endif

}
Esempio n. 27
0
void Application::newConnection()
{
	QLocalSocket *socket = m_localServer->nextPendingConnection();

	if (!socket)
	{
		return;
	}

	socket->waitForReadyRead(1000);

	MainWindow *window = (getWindows().isEmpty() ? NULL : getWindow());
	QString data;
	QTextStream stream(socket);
	stream >> data;

	const QStringList encodedArguments = QString(QByteArray::fromBase64(data.toUtf8())).split(QLatin1Char(' '));
	QStringList decodedArguments;

	for (int i = 0; i < encodedArguments.count(); ++i)
	{
		decodedArguments.append(QString(QByteArray::fromBase64(encodedArguments.at(i).toUtf8())));
	}

	m_commandLineParser.parse(decodedArguments);

	const QString session = m_commandLineParser.value(QLatin1String("session"));
	const bool isPrivate = m_commandLineParser.isSet(QLatin1String("privatesession"));

	if (session.isEmpty())
	{
		if (!window || !SettingsManager::getValue(QLatin1String("Browser/OpenLinksInNewTab")).toBool() || (isPrivate && !window->getWindowsManager()->isPrivate()))
		{
			window = createWindow(isPrivate);
		}
	}
	else
	{
		const SessionInformation sessionData = SessionsManager::getSession(session);

		if (sessionData.isClean || QMessageBox::warning(NULL, tr("Warning"), tr("This session was not saved correctly.\nAre you sure that you want to restore this session anyway?"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
		{
			for (int i = 0; i < sessionData.windows.count(); ++i)
			{
				createWindow(isPrivate, false, sessionData.windows.at(i));
			}
		}
	}

	if (window)
	{
		if (m_commandLineParser.positionalArguments().isEmpty())
		{
			window->triggerAction(ActionsManager::NewTabAction);
		}
		else
		{
			const QStringList urls = m_commandLineParser.positionalArguments();

			for (int i = 0; i < urls.count(); ++i)
			{
				window->openUrl(urls.at(i));
			}
		}
	}

	delete socket;

	if (window)
	{
		window->raise();
		window->activateWindow();

		if (m_isHidden)
		{
			setHidden(false);
		}
		else
		{
			window->storeWindowState();
			window->restoreWindowState();
		}
	}
}
Esempio n. 28
0
void OMW::Engine::prepareEngine (Settings::Manager & settings)
{
    mEnvironment.setStateManager (
        new MWState::StateManager (mCfgMgr.getUserDataPath() / "saves", mContentFiles.at (0)));

    createWindow(settings);

    osg::ref_ptr<osg::Group> rootNode (new osg::Group);
    mViewer->setSceneData(rootNode);

    mVFS.reset(new VFS::Manager(mFSStrict));

    VFS::registerArchives(mVFS.get(), mFileCollections, mArchives, true);

    mResourceSystem.reset(new Resource::ResourceSystem(mVFS.get()));
    mResourceSystem->getSceneManager()->setUnRefImageDataAfterApply(false); // keep to Off for now to allow better state sharing
    mResourceSystem->getSceneManager()->setFilterSettings(
        Settings::Manager::getString("texture mag filter", "General"),
        Settings::Manager::getString("texture min filter", "General"),
        Settings::Manager::getString("texture mipmap", "General"),
        Settings::Manager::getInt("anisotropy", "General"),
        NULL
    );

    // Create input and UI first to set up a bootstrapping environment for
    // showing a loading screen and keeping the window responsive while doing so

    std::string keybinderUser = (mCfgMgr.getUserConfigPath() / "input_v3.xml").string();
    bool keybinderUserExists = boost::filesystem::exists(keybinderUser);
    if(!keybinderUserExists)
    {
        std::string input2 = (mCfgMgr.getUserConfigPath() / "input_v2.xml").string();
        if(boost::filesystem::exists(input2)) {
            boost::filesystem::copy_file(input2, keybinderUser);
            keybinderUserExists = boost::filesystem::exists(keybinderUser);
        }
    }

    // find correct path to the game controller bindings
    const std::string localdefault = mCfgMgr.getLocalPath().string() + "/gamecontrollerdb.txt";
    const std::string globaldefault = mCfgMgr.getGlobalPath().string() + "/gamecontrollerdb.txt";
    std::string gameControllerdb;
    if (boost::filesystem::exists(localdefault))
        gameControllerdb = localdefault;
    else if (boost::filesystem::exists(globaldefault))
        gameControllerdb = globaldefault;
    else
        gameControllerdb = ""; //if it doesn't exist, pass in an empty string

    MWInput::InputManager* input = new MWInput::InputManager (mWindow, mViewer, mScreenCaptureHandler, keybinderUser, keybinderUserExists, gameControllerdb, mGrab);
    mEnvironment.setInputManager (input);

    std::string myguiResources = (mResDir / "mygui").string();
    osg::ref_ptr<osg::Group> guiRoot = new osg::Group;
    guiRoot->setNodeMask(MWRender::Mask_GUI);
    rootNode->addChild(guiRoot);
    MWGui::WindowManager* window = new MWGui::WindowManager(mViewer, guiRoot, mResourceSystem.get(),
                mCfgMgr.getLogPath().string() + std::string("/"), myguiResources,
                mScriptConsoleMode, mTranslationDataStorage, mEncoding, mExportFonts, mFallbackMap,
                Version::getOpenmwVersionDescription(mResDir.string()));
    mEnvironment.setWindowManager (window);

    // Create sound system
    mEnvironment.setSoundManager (new MWSound::SoundManager(mVFS.get(), mUseSound));

    if (!mSkipMenu)
    {
        std::string logo = mFallbackMap["Movies_Company_Logo"];
        if (!logo.empty())
            window->playVideo(logo, true);
    }

    // Create the world
    mEnvironment.setWorld( new MWWorld::World (mViewer, rootNode, mResourceSystem.get(),
        mFileCollections, mContentFiles, mEncoder, mFallbackMap,
        mActivationDistanceOverride, mCellName, mStartupScript, mResDir.string()));
    mEnvironment.getWorld()->setupPlayer();
    input->setPlayer(&mEnvironment.getWorld()->getPlayer());

    window->setStore(mEnvironment.getWorld()->getStore());
    window->initUI();
    window->renderWorldMap();

    //Load translation data
    mTranslationDataStorage.setEncoder(mEncoder);
    for (size_t i = 0; i < mContentFiles.size(); i++)
      mTranslationDataStorage.loadTranslationData(mFileCollections, mContentFiles[i]);

    Compiler::registerExtensions (mExtensions);

    // Create script system
    mScriptContext = new MWScript::CompilerContext (MWScript::CompilerContext::Type_Full);
    mScriptContext->setExtensions (&mExtensions);

    mEnvironment.setScriptManager (new MWScript::ScriptManager (mEnvironment.getWorld()->getStore(),
        mVerboseScripts, *mScriptContext, mWarningsMode,
        mScriptBlacklistUse ? mScriptBlacklist : std::vector<std::string>()));

    // Create game mechanics system
    MWMechanics::MechanicsManager* mechanics = new MWMechanics::MechanicsManager;
    mEnvironment.setMechanicsManager (mechanics);

    // Create dialog system
    mEnvironment.setJournal (new MWDialogue::Journal);
    mEnvironment.setDialogueManager (new MWDialogue::DialogueManager (mExtensions, mVerboseScripts, mTranslationDataStorage));

    // scripts
    if (mCompileAll)
    {
        std::pair<int, int> result = mEnvironment.getScriptManager()->compileAll();
        if (result.first)
            std::cout
                << "compiled " << result.second << " of " << result.first << " scripts ("
                << 100*static_cast<double> (result.second)/result.first
                << "%)"
                << std::endl;
    }
    if (mCompileAllDialogue)
    {
        std::pair<int, int> result = MWDialogue::ScriptTest::compileAll(&mExtensions, mWarningsMode);
        if (result.first)
            std::cout
                << "compiled " << result.second << " of " << result.first << " dialogue script/actor combinations a("
                << 100*static_cast<double> (result.second)/result.first
                << "%)"
                << std::endl;
    }
}
TfiltersPage::TfiltersPage(HWND IhwndParent,IffDecoder *Ideci,int dialogId) :TconfPage(IhwndParent,Ideci)
{
 createWindow(dialogId);
}
void
CMSWindowsServerTaskBarReceiver::runMenu(int x, int y)
{
	// do popup menu.  we need a window to pass to TrackPopupMenu().
	// the SetForegroundWindow() and SendMessage() calls around
	// TrackPopupMenu() are to get the menu to be dismissed when
	// another window gets activated and are just one of those
	// win32 weirdnesses.
	createWindow();
	SetForegroundWindow(m_window);
	HMENU menu = GetSubMenu(m_menu, 0);
	SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE);
	HMENU logLevelMenu = GetSubMenu(menu, 3);
	CheckMenuRadioItem(logLevelMenu, 0, 6,
							CLOG->getFilter() - CLog::kERROR, MF_BYPOSITION);
	int n = TrackPopupMenu(menu,
							TPM_NONOTIFY |
							TPM_RETURNCMD |
							TPM_LEFTBUTTON |
							TPM_RIGHTBUTTON,
							x, y, 0, m_window, NULL);
	SendMessage(m_window, WM_NULL, 0, 0);

	// perform the requested operation
	switch (n) {
	case IDC_TASKBAR_STATUS:
		showStatus();
		break;

	case IDC_TASKBAR_LOG:
		copyLog();
		break;

	case IDC_TASKBAR_SHOW_LOG:
		ARCH->showConsole(true);
		break;

	case IDC_RELOAD_CONFIG:
		EVENTQUEUE->addEvent(CEvent(getReloadConfigEvent(),
							IEventQueue::getSystemTarget()));
		break;

	case IDC_FORCE_RECONNECT:
		EVENTQUEUE->addEvent(CEvent(getForceReconnectEvent(),
							IEventQueue::getSystemTarget()));
		break;

	case ID_SYNERGY_RESETSERVER:
		EVENTQUEUE->addEvent(CEvent(getResetServerEvent(),
							IEventQueue::getSystemTarget()));
		break;

	case IDC_TASKBAR_LOG_LEVEL_ERROR:
		CLOG->setFilter(CLog::kERROR);
		break;

	case IDC_TASKBAR_LOG_LEVEL_WARNING:
		CLOG->setFilter(CLog::kWARNING);
		break;

	case IDC_TASKBAR_LOG_LEVEL_NOTE:
		CLOG->setFilter(CLog::kNOTE);
		break;

	case IDC_TASKBAR_LOG_LEVEL_INFO:
		CLOG->setFilter(CLog::kINFO);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG:
		CLOG->setFilter(CLog::kDEBUG);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG1:
		CLOG->setFilter(CLog::kDEBUG1);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG2:
		CLOG->setFilter(CLog::kDEBUG2);
		break;

	case IDC_TASKBAR_QUIT:
		quit();
		break;
	}
}