DWORD WINAPI HudHandler2(LPVOID) { CIniReader iniReader("nfsu2_res.ini"); while (true) { Sleep(0); if ((GetAsyncKeyState(VK_F2) & 1)) { bHudMode = !bHudMode; iniReader.WriteInteger("MAIN", "HudMode", bHudMode); while ((GetAsyncKeyState(VK_F2) & 0x8000) > 0) { Sleep(0); } } if (!bHudMode) { Sleep(1); if (*(float*)0x51AEAB != hud_position_x) { injector::WriteMemory<float>(0x79AC10 + 0x4, hud_multiplier_x, true); injector::WriteMemory<float>(0x79AC14 + 0x4, hud_multiplier_y, true); injector::WriteMemory<float>(0x51B3CB - 0x520, hud_position_x, true); injector::WriteMemory<float>(0x5368C8 - 0x460, hud_position_x, true); injector::WriteMemory<float>(0x536A99 - 0x460, hud_position_x, true); injector::WriteMemory<float>(0x536CC9 - 0x460, hud_position_x, true); injector::WriteMemory<float>(0x537011 - 0x460, hud_position_x, true); injector::WriteMemory<float>(0x48B640 - 0xA0, hud_position_x, true); injector::WriteMemory<float>(0x50B4F5 - 0x5C0, hud_position_x, true); injector::WriteMemory<float>(0x797D50 + 0x1C, hud_position_x, true); MinimapPosX = hud_position_x; MinimapPosY = 240.0f; injector::WriteMemory<float>(0x536A99 - 0x460, MinimapPosX, true); //minimap injector::WriteMemory<float>(0x536AA4 - 0x460, MinimapPosY, true); //minimap } } else { Sleep(1); if (*(unsigned char*)0x874E58 != 1) { if (*(float*)0x51AEAB == hud_position_x) { injector::WriteMemory<float>(0x79AC10 + 0x4, hud_multiplier_x / 1.7f, true); injector::WriteMemory<float>(0x79AC14 + 0x4, hud_multiplier_y / 1.7f, true); injector::WriteMemory<float>(0x51B3CB - 0x520, hud_position_x * 2.0f + 290.0f * ((float)ResX * (1.0f / 1920.0f)), true); injector::WriteMemory<float>(0x5368C8 - 0x460, hud_position_x * 2.0f + 290.0f * ((float)ResX * (1.0f / 1920.0f)), true); injector::WriteMemory<float>(0x536A99 - 0x460, hud_position_x * 2.0f + 290.0f * ((float)ResX * (1.0f / 1920.0f)), true); injector::WriteMemory<float>(0x536CC9 - 0x460, hud_position_x * 2.0f + 290.0f * ((float)ResX * (1.0f / 1920.0f)), true); injector::WriteMemory<float>(0x537011 - 0x460, hud_position_x * 2.0f + 290.0f * ((float)ResX * (1.0f / 1920.0f)), true); injector::WriteMemory<float>(0x48B640 - 0xA0, hud_position_x * 2.0f + 290.0f * ((float)ResX * (1.0f / 1920.0f)), true); injector::WriteMemory<float>(0x50B4F5 - 0x5C0, hud_position_x * 2.0f + 290.0f * ((float)ResX * (1.0f / 1920.0f)), true); injector::WriteMemory<float>(0x797D50 + 0x1C, hud_position_x * 2.0f + 290.0f * ((float)ResX * (1.0f / 1920.0f)), true); MinimapPosX = (hud_position_x * 2.0f) * 1.7f * 1.07f; MinimapPosY = 550.0f; injector::WriteMemory<float>(0x536A99 - 0x460, MinimapPosX, true); //minimap injector::WriteMemory<float>(0x536AA4 - 0x460, MinimapPosY, true); //minimap } } else { if (*(float*)0x51AEAB != hud_position_x) { injector::WriteMemory<float>(0x79AC10 + 0x4, hud_multiplier_x, true); injector::WriteMemory<float>(0x79AC14 + 0x4, hud_multiplier_y, true); injector::WriteMemory<float>(0x51B3CB - 0x520, hud_position_x, true); injector::WriteMemory<float>(0x5368C8 - 0x460, hud_position_x, true); injector::WriteMemory<float>(0x536A99 - 0x460, hud_position_x, true); injector::WriteMemory<float>(0x536CC9 - 0x460, hud_position_x, true); injector::WriteMemory<float>(0x537011 - 0x460, hud_position_x, true); injector::WriteMemory<float>(0x48B640 - 0xA0, hud_position_x, true); injector::WriteMemory<float>(0x50B4F5 - 0x5C0, hud_position_x, true); injector::WriteMemory<float>(0x797D50 + 0x1C, hud_position_x, true); MinimapPosX = hud_position_x; MinimapPosY = 240.0f; injector::WriteMemory<float>(0x536A99 - 0x460, MinimapPosX, true); //minimap injector::WriteMemory<float>(0x536AA4 - 0x460, MinimapPosY, true); //minimap } } } } return 0; }
//----------Die KI der Einheiten---------------------------------------------------------------- void UnitKI(LPOBJEKT lpObjekt) { // Erst prüfen, ob Objekt zerstört wurde, falls ja->Funktion abbrechen if (CheckIfDestroyed(lpObjekt) == true) return; // Je nach Objekttyp KI aufrufen switch(lpObjekt->typ) { // Das Schiff des Spielers case UD_PLAYERSHIP: { // Aktuelle Position und Energie des PlayerShip in externe Variabeln speichern PlayerShipPosX = lpObjekt->x; PlayerShipPosY = lpObjekt->y; PlayerShipEnergy = lpObjekt->energie; // Das Schiff mit dem Vektor des vorigen Frames bewegen MoveDiagonal(lpObjekt); // Den Bewegungsvektor verkleinern (Schiff wird langsamer, wenn nicht beschleunigt) if (VectorLength(lpObjekt->v) > 0) { lpObjekt->v[0] = lpObjekt->v[0]*0.8; lpObjekt->v[1] = lpObjekt->v[1]*0.9; } // Schiff nach links bewegen if(GetAsyncKeyState(VK_LEFT)) { lpObjekt->v[0] -= 1; if (GetTickCount() - lpObjekt->timer > 75 && lpObjekt->akt_bild > 0) { lpObjekt->akt_bild--; lpObjekt->timer = GetTickCount(); } } // Schiff nach rechts bewegen if(GetAsyncKeyState(VK_RIGHT)) { lpObjekt->v[0] += 1; if (GetTickCount() - lpObjekt->timer > 75 && lpObjekt->akt_bild < lpObjekt->bild->anz_anim) { lpObjekt->akt_bild++; lpObjekt->timer = GetTickCount(); } } // Schiff nach oben bewegen if(GetAsyncKeyState(VK_UP)) { lpObjekt->v[1] -= 0.5f; } // Schiff nach unten bewegen if(GetAsyncKeyState(VK_DOWN)) { lpObjekt->v[1] += 0.5f; } // Prüfen, ob der Bewegungsvektor zu lang ist und ggf. auf maximale Länge kürzen if (VectorLength(lpObjekt->v) >= lpObjekt->s) { lpObjekt->v[0] = ((lpObjekt->v[0])/(VectorLength(lpObjekt->v)))*lpObjekt->s; lpObjekt->v[1] = ((lpObjekt->v[1])/(VectorLength(lpObjekt->v)))*lpObjekt->s; } // Prüfen, ob Schiff nicht mehr im Bildschirm-Bereich und korrigieren falls nötig // Linker Rand if (lpObjekt->x < 0) lpObjekt->x = 0; // Rechter Rand if ((lpObjekt->x + lpObjekt->bild->breite) > RESOLUTION_X) lpObjekt->x = (float)(RESOLUTION_X - lpObjekt->bild->breite); // Oberer Rand if ((lpObjekt->y) < (ScrollY)) lpObjekt->y = ScrollY; // Unterer Rand if ((lpObjekt->y + lpObjekt->bild->hoehe) > (ScrollY + RESOLUTION_Y)) lpObjekt->y = ((float)(ScrollY + RESOLUTION_Y)) - (lpObjekt->bild->hoehe); // Position etwas nach oben setzen (Raumschiff bewegt sich nach oben mit dem Scrolling) lpObjekt->y -= 1; // Langsames zurückneigen des Schiffes, wenn es sich nicht nach links/rechts bewegt if (abs(lpObjekt->v[0]) < 0.2) // Zurückneigen nur, falls fast keine Bewegung in X-Richtung { if ((GetTickCount() - ZurueckNeigenTimer) > 100) { if (lpObjekt->akt_bild < 3) lpObjekt->akt_bild++; if (lpObjekt->akt_bild > 3) lpObjekt->akt_bild--; ZurueckNeigenTimer = GetTickCount(); } } // Rakete erstellen, falls CTRL gedrückt und genug Zeit seit letzer Rakete verstrichen iRocketTimer += fFrameTime; if (iRocketTimer > WeaponShotSpeed) iRocketTimer = WeaponShotSpeed; if (GetAsyncKeyState(VK_CONTROL) && iRocketTimer >= WeaponShotSpeed) { // Eine Rakete abschiessen kostet Punkte Score -= 20; if (Score < 0) Score = 0; // Rakete mit Sound erstellen CreateObjekt(lpObjekt->x + 24, lpObjekt->y - 20, 0, 0, ChosenWeaponType); iRocketTimer = 0; PlaySoundOnce(SoundArray[1], 0, DSBVOLUME_MAX); } return; } // Ende UD_PLAYERSHIP // Ein Meteorit case UD_STONE64: { lpObjekt->y += lpObjekt->s; lpObjekt->LifeTime -= dwFrameTime; return; } // Ende UD_STONE64 // Das erste Monster (Ein Wurm) case UD_MONSTER1A: { if (lpObjekt->zustand == OZ_GO) MoveDiagonal(lpObjekt); return; } // Ende UD_MONSTER1A // Das zweiter Monster (Eine Schnecke) case UD_MONSTER1B: { if (lpObjekt->zustand == OZ_GO) MoveDiagonal(lpObjekt); // Mit einer kleinen Wahrscheinlichkeit einen Schuss erzeugen if((rand()%200)==1) CreateObjekt(lpObjekt->x + 32, lpObjekt->y + 65, PlayerShipPosX, PlayerShipPosY - 100, UD_SCHUSS); return; } // Ende UD_MONSTER1B // Der Schuss von Gegner Nr.2 (UD_MONSTER1B) case UD_SCHUSS: { if (lpObjekt->zustand == OZ_GO) MoveDiagonal(lpObjekt); return; } // Ende UD_EXTRA // 2000 Extra-Punkte case UD_EXTRA: { // Prüfen, ob das Spielerschiff dieses Objekt berührt hat und wenn ja--> // Extra-Punkte berechnen if (((PlayerShipPosX + 64) > lpObjekt->x) && (PlayerShipPosX < (lpObjekt->x + 32)) && ((PlayerShipPosY + 64) > lpObjekt->y) && (PlayerShipPosY < (lpObjekt->y + 32))) { Score += 2000; lpObjekt->zustand = OZ_DEAD; } return; } // Ende UD_EXTRA //------B L O C K S------------------- // Ein grosses Hindernis case UD_BLOCK1: { // Damit Objekt nie zerstört wird (+ um Variabel-Überläufe zu verhindern) lpObjekt->energie = 1; return; } //Ende UD_BLOCK1 // Ein Stein im Hintergrund case UD_BACK64A: { // Damit Objekt nie zerstört wird (+ um Variabel-Überläufe zu verhindern) lpObjekt->energie = 1; return; } // Ende UD_BACK64A //------E F F E K T E------------------------- // Die verschiedenen Explosionen (Verschieden gross) case UD_EXP16: case UD_EXP32: case UD_EXP64: { lpObjekt->LifeTime -= dwFrameTime; return; } // Ende UD_EXP16/32/64 //------W A F F E N------------------- // Die Standard-Rakete case UD_STDROCKET: { lpObjekt->y -= lpObjekt->s; lpObjekt->LifeTime -= dwFrameTime; return; } // Ende UD_STDROCKET } // Ende switch(lpObjekt->typ) } // Ende UnitKI()
LRESULT WINAPI DoAppSwitch( WPARAM wParam, LPARAM lParam ) { HWND hwndActive; MSG msg; // FIXME: Is loading timing OK? LoadCoolSwitchSettings(); if (!CoolSwitch) return 0; // Already in the loop. if (switchdialog || Esc) return 0; hwndActive = GetActiveWindow(); // Nothing is active so exit. if (!hwndActive) return 0; if (lParam == VK_ESCAPE) { Esc = TRUE; windowCount = 0; EnumWindowsZOrder(EnumerateCallback, 0); if (windowCount < 2) return 0; RotateTasks(GetAsyncKeyState(VK_SHIFT) < 0); hwndActive = GetActiveWindow(); if (hwndActive == NULL) { Esc = FALSE; return 0; } } // Capture current active window. SetCapture( hwndActive ); switch (lParam) { case VK_TAB: if( !CreateSwitcherWindow(User32Instance) ) goto Exit; if( !GetDialogFont() ) goto Exit; if( !ProcessHotKey() ) goto Exit; break; case VK_ESCAPE: break; default: goto Exit; } // Main message loop: while (1) { for (;;) { if (PeekMessageW( &msg, 0, 0, 0, PM_NOREMOVE )) { if (!CallMsgFilterW( &msg, MSGF_NEXTWINDOW )) break; /* remove the message from the queue */ PeekMessageW( &msg, 0, msg.message, msg.message, PM_REMOVE ); } else WaitMessage(); } switch (msg.message) { case WM_KEYUP: { PeekMessageW( &msg, 0, msg.message, msg.message, PM_REMOVE ); if (msg.wParam == VK_MENU) { CompleteSwitch(TRUE); } else if (msg.wParam == VK_RETURN) { CompleteSwitch(TRUE); } else if (msg.wParam == VK_ESCAPE) { TRACE("DoAppSwitch VK_ESCAPE 2\n"); CompleteSwitch(FALSE); } goto Exit; //break; } case WM_SYSKEYDOWN: { PeekMessageW( &msg, 0, msg.message, msg.message, PM_REMOVE ); if (HIWORD(msg.lParam) & KF_ALTDOWN) { if ( msg.wParam == VK_TAB ) { if (Esc) break; if (GetKeyState(VK_SHIFT) < 0) { MoveLeft(); } else { MoveRight(); } } else if ( msg.wParam == VK_ESCAPE ) { if (!Esc) break; RotateTasks(GetKeyState(VK_SHIFT) < 0); } else if ( msg.wParam == VK_LEFT ) { MoveLeft(); } else if ( msg.wParam == VK_RIGHT ) { MoveRight(); } else if ( msg.wParam == VK_UP ) { MoveUp(); } else if ( msg.wParam == VK_DOWN ) { MoveDown(); } } break; } case WM_LBUTTONUP: PeekMessageW( &msg, 0, msg.message, msg.message, PM_REMOVE ); ProcessMouseMessage(msg.message, msg.lParam); goto Exit; default: if (PeekMessageW( &msg, 0, msg.message, msg.message, PM_REMOVE )) { TranslateMessage(&msg); DispatchMessageW(&msg); } break; } } Exit: ReleaseCapture(); if (switchdialog) DestroyWindow(switchdialog); if (Esc) DestroyAppWindows(); switchdialog = NULL; selectedWindow = 0; windowCount = 0; Esc = FALSE; return 0; }
static LRESULT CALLBACK Desk_WndProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static const UINT msgs [] = { BB_DRAGTODESKTOP, BB_REDRAWGUI, 0 }; static bool button_down, dblclk; int n; switch (uMsg) { //==================== case WM_CREATE: hDesktopWnd = hwnd; MakeSticky(hwnd); MessageManager_Register(hwnd, msgs, true); init_DeskDropTarget(hwnd); Desk_SetPosition(); break; //==================== case WM_DESTROY: exit_DeskDropTarget(hwnd); MessageManager_Register(hwnd, msgs, false); RemoveSticky(hwnd); break; case WM_NCPAINT: // dbg_printf("ncpaint: %x %x %x %x", hwnd, uMsg, wParam, lParam); // keep the window on bottom Desk_SetPosition(); break; case WM_SETTINGCHANGE: if (SPI_SETDESKWALLPAPER == wParam) InvalidateRect(hwnd, NULL, FALSE); break; //==================== case WM_CLOSE: break; //==================== case WM_MOUSEACTIVATE: return MA_NOACTIVATE; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: case WM_XBUTTONDOWN: dblclk = false; button_down = true; if (uMsg == WM_LBUTTONDOWN) { n = 0; goto post_click_2; } break; case WM_MOUSEMOVE: break; case WM_LBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_MBUTTONDBLCLK: dblclk = true; button_down = true; break; case WM_LBUTTONUP: n = dblclk ? 7 : 1; goto post_click; case WM_RBUTTONUP: n = 2; goto post_click; case WM_MBUTTONUP: n = 3; goto post_click; case WM_XBUTTONUP: switch (HIWORD(wParam)) { case XBUTTON1: n = 4; goto post_click; case XBUTTON2: n = 5; goto post_click; case XBUTTON3: n = 6; goto post_click; } break; post_click: if (false == button_down) break; button_down = dblclk = false; post_click_2: wParam &= (MK_CONTROL|MK_SHIFT); if (0x8000 & GetAsyncKeyState(VK_MENU)) wParam |= MK_ALT; PostMessage(BBhwnd, BB_DESKCLICK, wParam, n); break; //==================== case WM_PAINT: { PAINTSTRUCT ps; HDC hdc_scrn; HDC hdc_bmp; HGDIOBJ other; hdc_scrn = BeginPaint(hwnd, &ps); if (Root.bmp) { hdc_bmp = CreateCompatibleDC(hdc_scrn); other = SelectObject(hdc_bmp, Root.bmp); BitBltRect(hdc_scrn, hdc_bmp, &ps.rcPaint); SelectObject(hdc_bmp, other); DeleteDC(hdc_bmp); } else { PaintDesktop(hdc_scrn); } EndPaint(hwnd, &ps); break; } //==================== case WM_ERASEBKGND: return TRUE; //==================== case BB_DRAGTODESKTOP: return get_drop_command((const char *)lParam, wParam); case BB_REDRAWGUI: if (wParam & BBRG_DESK) Desk_new_background("style"); break; //==================== default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; }
bool getMouseButton(MouseButton button) { return (GetAsyncKeyState(Imp::WinKey[static_cast<i32>(button)])) != 0; }
//----------------------------------------------------------------------------- // Purpose: // Input : pView - // nFlags - // point - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool Marker3D::OnMouseMove2D(CMapView2D *pView, UINT nFlags, CPoint point) { CMapDoc *pDoc = pView->GetDocument(); if (!pDoc) { return false; } bool bCursorSet = false; unsigned int uConstraints = 0; if ((GetAsyncKeyState(VK_MENU) & 0x8000)) { uConstraints |= Tool3D::constrainNosnap; } // // Make sure the point is visible. // if (m_bLButtonDown) { pView->ToolScrollToPoint(point); } // // Convert to some odd coordinate space that the base tools code uses. // CPoint ptHitTest = point; ptHitTest.x += pView->GetScrollPos(SB_HORZ); ptHitTest.y += pView->GetScrollPos(SB_VERT); // // Convert to world coords. // Vector vecWorld; pView->ClientToWorld(vecWorld, point); point.x = vecWorld[axHorz]; point.y = vecWorld[axVert]; // // Update status bar position display. // char szBuf[128]; m_pDocument->Snap(vecWorld); sprintf(szBuf, " @%.0f, %.0f ", vecWorld[axHorz], vecWorld[axVert]); SetStatusText(SBI_COORDS, szBuf); // // If we are currently dragging the marker, update that operation based on // the current cursor position and keyboard state. // if (IsTranslating()) { if (UpdateTranslation(point, uConstraints, CSize(0,0))) { pDoc->ToolUpdateViews(CMapView2D::updTool); pDoc->Update3DViews(); } // Don't change the cursor while dragging - it should remain a cross. bCursorSet = true; SetCursor(AfxGetApp()->LoadStandardCursor(IDC_CROSS)); } else if (!IsEmpty()) { // Don't change the cursor while dragging - it should remain a cross. bCursorSet = true; SetCursor(AfxGetApp()->LoadStandardCursor(IDC_CROSS)); } if (!bCursorSet) { SetCursor(s_hcurEntity); } return true; }
static void QueryInput( int windowWidth, int windowHeight, int windowPosX, int windowPosY, InputState* stateStorage ) { if( !HasFocus() ) { return; } memset( &stateStorage->romanCharKeys, 0, sizeof(bool) * 32 ); for( int keyIndex = 0; keyIndex < 26; ++keyIndex ) { const int asciiStart = (int)'a'; int keyChar = asciiStart + keyIndex; if( keyChar >= 'a' && keyChar <= 'z' ) { keyChar -= ( 'a' - 'A' ); } short keystate = GetAsyncKeyState( keyChar ); stateStorage->romanCharKeys[ keyIndex ] = ( 1 << 16 ) & keystate; } memset( &stateStorage->spcKeys, 0, sizeof(bool) * 8 ); stateStorage->spcKeys[ InputState::CTRL ] = ( 1 << 16 ) & GetAsyncKeyState( VK_CONTROL ); stateStorage->spcKeys[ InputState::BACKSPACE ] = ( 1 << 16 ) & GetAsyncKeyState( VK_BACK ); stateStorage->spcKeys[ InputState::TAB ] = ( 1 << 16 ) & GetAsyncKeyState( VK_TAB ); stateStorage->spcKeys[ InputState::DEL ] = ( 1 << 16 ) & GetAsyncKeyState( VK_DELETE ); stateStorage->spcKeys[ InputState::SPACE ] = ( 1 << 16 ) & GetAsyncKeyState( VK_SPACE ); memcpy( &stateStorage->keysPressedSinceLastUpdate, keypressHistory, 24 ); memset( &keypressHistory, 0, KEY_HISTORY_LEN ); keypressHistoryIndex = 0; POINT mousePosition; GetCursorPos( &mousePosition ); stateStorage->mouseX = ( (float)(mousePosition.x - windowPosX)) / ( (float)windowWidth / 2.0f ) - 1.0f; stateStorage->mouseY = ( ( (float)(mousePosition.y - windowPosY)) / ( (float)windowHeight / 2.0f ) - 1.0f) * -1.0f; stateStorage->mouseButtons[ InputState::MOUSE_BUTTONS::LEFT ] = ( 1 << 16 ) & GetAsyncKeyState( VK_LBUTTON ); stateStorage->mouseButtons[ InputState::MOUSE_BUTTONS::MIDDLE ] = ( 1 << 16 ) & GetAsyncKeyState( VK_MBUTTON ); stateStorage->mouseButtons[ InputState::MOUSE_BUTTONS::RIGHT ] = ( 1 << 16 ) & GetAsyncKeyState( VK_RBUTTON ); XINPUT_STATE state; DWORD queryResult; memset( &state, 0, sizeof( XINPUT_STATE ) ) ; queryResult = XInputGetState( 0, &state ); if( queryResult == ERROR_SUCCESS ) { //Note: polling of the sticks results in the range not quite reaching 1.0 in the positive direction //it is like this to avoid branching on greater or less than 0.0 stateStorage->leftStick_x = ((float)state.Gamepad.sThumbLX / 32768.0f ); stateStorage->leftStick_y = ((float)state.Gamepad.sThumbLY / 32768.0f ); stateStorage->rightStick_x = ((float)state.Gamepad.sThumbRX / 32768.0f ); stateStorage->rightStick_y = ((float)state.Gamepad.sThumbRY / 32768.0f ); stateStorage->leftTrigger = ((float)state.Gamepad.bLeftTrigger / 255.0f ); stateStorage->rightTrigger = ((float)state.Gamepad.bRightTrigger / 255.0f ); stateStorage->leftBumper = state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER; stateStorage->rightBumper = state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER; stateStorage->button1 = state.Gamepad.wButtons & XINPUT_GAMEPAD_A; stateStorage->button2 = state.Gamepad.wButtons & XINPUT_GAMEPAD_B; stateStorage->button3 = state.Gamepad.wButtons & XINPUT_GAMEPAD_X; stateStorage->button4 = state.Gamepad.wButtons & XINPUT_GAMEPAD_Y; stateStorage->specialButtonLeft = state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK; stateStorage->specialButtonRight = state.Gamepad.wButtons & XINPUT_GAMEPAD_START; } else { //TODO: Clear input? } }
//This function processes any Windows messages we get. Keyboard, OnClose, etc LRESULT CALLBACK ProcessMessages(HWND__ *hWnd,unsigned int Msg, WPARAM wParam, LPARAM lParam) { uint16_t MouseOver; switch (Msg) { case WM_DEADCHAR: case WM_CHAR: lastchar = (int)wParam; switch (lastchar){ case VK_RETURN: //Reroute ENTER key for compatilbity purposes lastchar=10; break; case VK_BACK: //Reroute BACKSPACE key for compatilbity purposes lastchar=127; break; } return 0; case WM_KEYDOWN: //Here we handle non-character input switch (wParam){ case VK_LEFT: lastchar = KEY_LEFT; break; case VK_RIGHT: lastchar = KEY_RIGHT; break; case VK_UP: lastchar = KEY_UP; break; case VK_DOWN: lastchar = KEY_DOWN; break; case VK_NEXT: lastchar = KEY_NPAGE; break; case VK_PRIOR: lastchar = KEY_PPAGE; break; case VK_F1: lastchar = KEY_F(1); break; case VK_F2: lastchar = KEY_F(2); break; case VK_F3: lastchar = KEY_F(3); break; case VK_F4: lastchar = KEY_F(4); break; case VK_F5: lastchar = KEY_F(5); break; case VK_F6: lastchar = KEY_F(6); break; case VK_F7: lastchar = KEY_F(7); break; case VK_F8: lastchar = KEY_F(8); break; case VK_F9: lastchar = KEY_F(9); break; case VK_F10: lastchar = KEY_F(10); break; case VK_F11: lastchar = KEY_F(11); break; case VK_F12: lastchar = KEY_F(12); break; default: break; }; return 0; case WM_KEYUP: if (!GetAsyncKeyState(VK_LMENU) && alt_down){ // LeftAlt hack if (int code = end_alt_code()) lastchar = code; } return 0; case WM_SYSCHAR: add_alt_code((char)wParam); return 0; case WM_SYSKEYDOWN: if (GetAsyncKeyState(VK_LMENU) && !alt_down){ // LeftAlt hack begin_alt_code(); } break; case WM_SETCURSOR: MouseOver = LOWORD(lParam); if (OPTIONS["HIDE_CURSOR"] == "hide") { if (MouseOver==HTCLIENT && CursorVisible) { CursorVisible = false; ShowCursor(false); } else if (MouseOver!=HTCLIENT && !CursorVisible) { CursorVisible = true; ShowCursor(true); } } else if (!CursorVisible) { CursorVisible = true; ShowCursor(true); } break; case WM_ERASEBKGND: return 1; // Don't erase background case WM_PAINT: BitBlt(WindowDC, 0, 0, WindowWidth, WindowHeight, backbuffer, 0, 0,SRCCOPY); ValidateRect(WindowHandle,NULL); return 0; case WM_DESTROY: exit(0); // A messy exit, but easy way to escape game loop }; return DefWindowProcA(hWnd, Msg, wParam, lParam); }
LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg == WM_TRAY) { if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK) { ToggleState(); if (lParam == WM_LBUTTONDBLCLK && !(GetAsyncKeyState(VK_SHIFT)&0x8000)) { SendMessage(hwnd, WM_OPENCONFIG, 0, 0); } } else if (lParam == WM_MBUTTONDOWN) { ShellExecute(NULL, L"open", inipath, NULL, NULL, SW_SHOWNORMAL); } else if (lParam == WM_RBUTTONDOWN) { ShowContextMenu(hwnd); } else if (lParam == NIN_BALLOONUSERCLICK) { hide = 0; SendMessage(hwnd, WM_COMMAND, SWM_UPDATE, 0); } else if (lParam == NIN_BALLOONTIMEOUT) { if (hide) { RemoveTray(); } } } else if (msg == WM_UPDATESETTINGS) { UpdateLanguage(); // Reload hooks if (ENABLED()) { UnhookSystem(); HookSystem(); } // Reload config language if (!wParam && IsWindow(g_cfgwnd)) { SendMessage(g_cfgwnd, WM_UPDATESETTINGS, 0, 0); } } else if (msg == WM_ADDTRAY) { hide = 0; UpdateTray(); } else if (msg == WM_HIDETRAY) { hide = 1; RemoveTray(); } else if (msg == WM_OPENCONFIG && (lParam || !hide)) { OpenConfig(wParam); } else if (msg == WM_CLOSECONFIG) { CloseConfig(); } else if (msg == WM_TASKBARCREATED) { tray_added = 0; UpdateTray(); } else if (msg == WM_COMMAND) { int wmId=LOWORD(wParam), wmEvent=HIWORD(wParam); if (wmId == SWM_TOGGLE) { ToggleState(); } else if (wmId == SWM_HIDE) { hide = 1; RemoveTray(); } else if (wmId == SWM_UPDATE) { if (MessageBox(NULL,l10n->update_dialog,APP_NAME,MB_ICONINFORMATION|MB_YESNO|MB_TOPMOST|MB_SETFOREGROUND) == IDYES) { OpenUrl(APP_URL); } } else if (wmId == SWM_CONFIG) { SendMessage(hwnd, WM_OPENCONFIG, 0, 0); } else if (wmId == SWM_ABOUT) { SendMessage(hwnd, WM_OPENCONFIG, 4, 0); } else if (wmId == SWM_EXIT) { DestroyWindow(hwnd); } } else if (msg == WM_QUERYENDSESSION && msghook) { showerror = 0; UnhookSystem(); } else if (msg == WM_DESTROY) { showerror = 0; UnhookSystem(); RemoveTray(); PostQuitMessage(0); } else if (msg == WM_LBUTTONDOWN || msg == WM_MBUTTONDOWN || msg == WM_RBUTTONDOWN) { // Hide cursorwnd if clicked on, this might happen if it wasn't hidden by hooks.c for some reason ShowWindow(hwnd, SW_HIDE); } return DefWindowProc(hwnd, msg, wParam, lParam); }
/*static unsigned int WINAPI NetworkThread( void * param ) { while(1) { ::Sleep(1); gServerLogic.net_->Update(); } }*/ void PlayGameServer() { r3d_assert(gServerLogic.ginfo_.IsValid()); switch(gServerLogic.ginfo_.mapId) { default: r3dError("invalid map id\n"); break; case GBGameInfo::MAPID_Editor_Particles: r3dGameLevel::SetHomeDir("WorkInProgress\\Editor_Particles"); break; case GBGameInfo::MAPID_ServerTest: r3dGameLevel::SetHomeDir("WorkInProgress\\ServerTest"); break; case GBGameInfo::MAPID_WZ_Colorado: r3dGameLevel::SetHomeDir("WZ_Colorado"); break; case GBGameInfo::MAPID_UB_Cliffside: r3dGameLevel::SetHomeDir("WZ_Cliffside"); break; case GBGameInfo::MAPID_UB_CaliWood: r3dGameLevel::SetHomeDir("CaliWood"); break; case GBGameInfo::MAPID_UB_Valley: r3dGameLevel::SetHomeDir("UB_Valley"); break; case GBGameInfo::MAPID_UB_Area51: r3dGameLevel::SetHomeDir("UB_Deserto"); break; case GBGameInfo::MAPID_UB_CryZ: r3dGameLevel::SetHomeDir("UB_CryZ"); break; case GBGameInfo::MAPID_UB_Terra: r3dGameLevel::SetHomeDir("UB_Terra"); break; case GBGameInfo::MAPID_UB_Mega: r3dGameLevel::SetHomeDir("UB_Mega"); break; } r3dResetFrameTime(); GameWorld_Create(); u_srand(timeGetTime()); GameWorld().Init(OBJECTMANAGER_MAXOBJECTS, OBJECTMANAGER_MAXSTATICOBJECTS); ServerDummyWorld.Init(OBJECTMANAGER_MAXOBJECTS, OBJECTMANAGER_MAXSTATICOBJECTS); g_pPhysicsWorld = new PhysXWorld; g_pPhysicsWorld->Init(); r3dTerrain::SetNeedShaders( false ); LoadLevel_Objects( 1.f ); gCollectionsManager.Init( 0, 1 ); r3dOutToLog( "NavMesh.Load...\n" ); gAutodeskNavMesh.Init(); r3dResetFrameTime(); GameWorld().Update(); ServerDummyWorld.Update(); r3dGameLevel::SetStartGameTime(r3dGetTime()); r3dOutToLog("server main loop started\n"); r3dResetFrameTime(); gServerLogic.OnGameStart(); gKeepAliveReporter.SetStarted(true); // _beginthreadex ( NULL, 0, NetworkThread, NULL, 0, NULL ); while(1) { ::Sleep(20); // limit to 100 FPS char text[64] ={0}; sprintf(text,"WarZ Game Server [Running..] id:%d curPeer:%d players:%d/%d",gServerLogic.ginfo_.gameServerId,gServerLogic.curPeersConnected,gServerLogic.curPlayers_,gServerLogic.ginfo_.maxPlayers); SetConsoleTitle(text); gServerLogic.net_->Update(); r3dEndFrame(); r3dStartFrame(); //if(GetAsyncKeyState(VK_F1)&0x8000) r3dError("r3dError test"); //if(GetAsyncKeyState(VK_F2)&0x8000) r3d_assert(false && "r3d_Assert test"); gKeepAliveReporter.Tick(gServerLogic.curPlayers_); gServerLogic.Tick(); gServerLogic.UpdateNetId(); gMasterServerLogic.Tick(); if(gMasterServerLogic.IsMasterDisconnected()) { r3dOutToLog("Master Server disconnected, exiting\n"); gKeepAliveReporter.SetStarted(false); return; } GameWorld().StartFrame(); GameWorld().Update(); // fire few ticks of temporary world update, just for safety (physics init and stuff) static int TempWorldUpdateN = 0; if(TempWorldUpdateN < 20) { TempWorldUpdateN++; ServerDummyWorld.Update(); } // start physics after game world update right now, as gameworld will move some objects around if necessary g_pPhysicsWorld->StartSimulation(); g_pPhysicsWorld->EndSimulation(); #if ENABLE_AUTODESK_NAVIGATION const float t1 = r3dGetTime(); gAutodeskNavMesh.Update(); const float t2 = r3dGetTime() - t1; bool showSpd = (GetAsyncKeyState('Q') & 0x8000) && (GetAsyncKeyState('E') & 0x8000); bool showKys = false; //(GetAsyncKeyState('Q') & 0x8000) && (GetAsyncKeyState('R') & 0x8000); extern int _zstat_NumZombies; extern int _zstat_NavFails; extern int _zstat_Disabled; if(showKys) { gAutodeskNavMesh.perfBridge.Dump(); r3dOutToLog("NavMeshUpdate %f sec, z:%d, bad:%d, f:%d\n", t2, _zstat_NumZombies, _zstat_Disabled, _zstat_NavFails); } if(showSpd) { r3dOutToLog("NavMeshUpdate %f sec, z:%d, bad:%d, f:%d\n", t2, _zstat_NumZombies, _zstat_Disabled, _zstat_NavFails); } #ifndef _DEBUG if((t2 > (1.0f / 60.0f))) { r3dOutToLog("!!!! NavMeshUpdate %f sec, z:%d, bad:%d, f:%d\n", t2, _zstat_NumZombies, _zstat_Disabled, _zstat_NavFails); //gAutodeskNavMesh.perfBridge.Dump(); //r3dOutToLog("!!!! NavMeshUpdate %f sec, z:%d, bad:%d, f:%d, navPend:%d\n", t2, _zstat_NumZombies, _zstat_Disabled, _zstat_NavFails, _zstat_UnderProcess); } #endif #endif // ENABLE_AUTODESK_NAVIGATION GameWorld().EndFrame(); if(gServerLogic.gameFinished_) break; } // set that we're finished gKeepAliveReporter.SetStarted(false); gMasterServerLogic.FinishGame(); gServerLogic.DumpPacketStatistics(); gCollectionsManager.Destroy(); GameWorld_Destroy(); ServerDummyWorld.Destroy(); return; }
void DirectXHook::drawChatInterface() { auto& console = GameConsole::Instance(); if ((console.getMsSinceLastConsoleOpen() > 10000 && !console.showChat && !console.showConsole) || (GetAsyncKeyState(VK_TAB) & 0x8000 && !console.showChat && !console.showConsole)) { return; } int x = (int)(0.05 * *horizontalRes); int y = (int)(0.65 * *verticalRes); int inputTextBoxWidth = (int)(0.5 * *horizontalRes); int inputTextBoxHeight = normalSizeFontHeight + (int)(0.769 * normalSizeFontHeight); int horizontalSpacing = (int)(0.012 * inputTextBoxWidth); int verticalSpacingBetweenEachLine = (int)(0.154 * normalSizeFontHeight); int verticalSpacingBetweenLinesAndInputBox = (int)(1.8 * normalSizeFontHeight); int verticalSpacingBetweenTopOfInputBoxAndFont = (inputTextBoxHeight - normalSizeFontHeight) / 2; size_t maxCharsPerLine = 105; if (console.showChat) { int tempX = x; std::string helpText = "Press ` or F1 to open console."; drawText(tempX + horizontalSpacing, y + verticalSpacingBetweenTopOfInputBoxAndFont, COLOR_WHITE, helpText.c_str(), normalSizeFont); } y -= verticalSpacingBetweenLinesAndInputBox; if (console.showChat || console.showConsole) { // Display current input drawBox(x, y, inputTextBoxWidth, inputTextBoxHeight, COLOR_WHITE, COLOR_BLACK); drawText(x + horizontalSpacing, y + verticalSpacingBetweenTopOfInputBoxAndFont, COLOR_WHITE, console.currentInput.currentInput.c_str(), normalSizeFont); // START: Line showing where the user currently is in the input field. if (console.getMsSinceLastConsoleBlink() > 300) { console.consoleBlinking = !console.consoleBlinking; console.lastTimeConsoleBlink = GetTickCount(); } if (!console.consoleBlinking) { std::string currentInput = console.currentInput.currentInput; char currentChar; int width = 0; if (currentInput.length() > 0) { currentChar = currentInput[console.currentInput.currentPointerIndex]; width = getTextWidth(currentInput.substr(0, console.currentInput.currentPointerIndex).c_str(), normalSizeFont) - 3; } else { width = -3; } drawText(x + horizontalSpacing + width, y + verticalSpacingBetweenTopOfInputBoxAndFont, COLOR_WHITE, "|", normalSizeFont); } // END: Line showing where the user currently is in the input field. } y -= verticalSpacingBetweenLinesAndInputBox; // Draw text from chat or console for (int i = console.selectedQueue->startIndexForScrolling; i < console.selectedQueue->numOfLinesToShow + console.selectedQueue->startIndexForScrolling; i++) { std::string line = console.selectedQueue->queue.at(i); if (line.size() > maxCharsPerLine) { std::vector<std::string> linesWrapped = std::vector < std::string > {}; for (size_t i = 0; i < line.size(); i += maxCharsPerLine) { linesWrapped.push_back(line.substr(i, maxCharsPerLine)); } for (int i = linesWrapped.size() - 1; i >= 0; i--) { drawText(x, y, COLOR_WHITE, linesWrapped.at(i).c_str(), normalSizeFont); y -= normalSizeFontHeight + verticalSpacingBetweenEachLine; } } else { drawText(x, y, COLOR_WHITE, line.c_str(), normalSizeFont); y -= normalSizeFontHeight + verticalSpacingBetweenEachLine; } } }
//------------------------------------------------------------ void ofAppNoWindow::runAppViaInfiniteLoop(ofBaseApp * appPtr) { static ofEventArgs voidEventArgs; ofAppPtr = appPtr; if(ofAppPtr) { ofAppPtr->setup(); ofAppPtr->update(); } #if defined TARGET_OSX || defined TARGET_LINUX // for keyboard set_conio_terminal_mode(); #endif #ifdef OF_USING_POCO ofNotifyEvent( ofEvents().setup, voidEventArgs ); ofNotifyEvent( ofEvents().update, voidEventArgs ); #endif ofLogNotice()<< "***\n***\n*** ofAppNoWindow running a headerless openFrameworks app\n" "***\n*** keyboard input works here\n" "***\n*** press Esc or Ctrl-C to quit\n" "***\n"; // Register signal handler to handle kill signal signalHandler.setupSignalHandlers(); while (true) { if (nFrameCount != 0 && bFrameRateSet == true) { diffMillis = ofGetElapsedTimeMillis() - prevMillis; if (diffMillis > millisForFrame) { ; // we do nothing, we are already slower than target frame } else { int waitMillis = millisForFrame - diffMillis; #ifdef TARGET_WIN32 Sleep(waitMillis); //windows sleep in milliseconds #else usleep(waitMillis * 1000); //mac sleep in microseconds - cooler :) #endif } } prevMillis = ofGetElapsedTimeMillis(); // you have to measure here /// listen for escape #ifdef TARGET_WIN32 if (GetAsyncKeyState(VK_ESCAPE)) OF_EXIT_APP(0); #endif #if defined TARGET_OSX || defined TARGET_LINUX while ( kbhit() ) { int key = getch(); if ( key == 27 ) { if(ofAppPtr) { ofAppPtr->exit(); } exitApp(); } if (key == 'q' || key == 'Q') { if(ofAppPtr) { ofAppPtr->exit(); } exitApp(); } else if ( key == /* ctrl-c */ 3 ) { if(ofAppPtr) { ofAppPtr->exit(); } ofLogNotice()<< "Ctrl-C pressed\n"; exitApp(); } else { ofAppPtr->keyPressed( key ); } } #endif /// update if (ofAppPtr) ofAppPtr->update(); #ifdef OF_USING_POCO ofNotifyEvent( ofEvents().update, voidEventArgs); #endif // Check for exit signal if (signalHandler.gotExitSignal()) { if(ofAppPtr) { ofAppPtr->exit(); } exitApp(); } // -------------- fps calculation: timeNow = ofGetElapsedTimef(); double diff = timeNow-timeThen; if( diff > 0.00001 ) { fps = 1.0 / diff; frameRate *= 0.9f; frameRate += 0.1f*fps; } lastFrameTime = diff; timeThen = timeNow; // -------------- nFrameCount++; // increase the overall frame count } }
void FPSCamera::Update(float timestep) { // Track mouse motion int2 mousePos; GetCursorPos((POINT *)&mousePos); int2 mouseMove = mousePos - m_mousePosPrev; m_mousePosPrev = mousePos; // Handle mouse rotation if (m_mbuttonActivate == MBUTTON_None || m_mbuttonCur == m_mbuttonActivate) { m_yaw -= m_rotateSpeed * mouseMove.x; m_yaw = modPositive(m_yaw, 2.0f*pi); m_pitch -= m_rotateSpeed * mouseMove.y; m_pitch = clamp(m_pitch, -0.5f*pi, 0.5f*pi); } // Retrieve controller state XINPUT_STATE controllerState = {}; float2 controllerLeftStick(0.0f), controllerRightStick(0.0f); float controllerLeftTrigger = 0.0f, controllerRightTrigger = 0.0f; if (m_controllerPresent) { // Look out for disconnection if (XInputGetState(0, &controllerState) == ERROR_SUCCESS) { // Decode axes and apply dead zones controllerLeftTrigger = float(max(0, controllerState.Gamepad.bLeftTrigger - XINPUT_GAMEPAD_TRIGGER_THRESHOLD)) / float(255 - XINPUT_GAMEPAD_TRIGGER_THRESHOLD); controllerRightTrigger = float(max(0, controllerState.Gamepad.bRightTrigger - XINPUT_GAMEPAD_TRIGGER_THRESHOLD)) / float(255 - XINPUT_GAMEPAD_TRIGGER_THRESHOLD); controllerLeftStick = float2(controllerState.Gamepad.sThumbLX, controllerState.Gamepad.sThumbLY); float lengthLeft = length(controllerLeftStick); if (lengthLeft > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) controllerLeftStick = (controllerLeftStick / lengthLeft) * (lengthLeft - XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) / float(32768 - XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE); else controllerLeftStick = float2(0.0f); controllerRightStick = float2(controllerState.Gamepad.sThumbRX, controllerState.Gamepad.sThumbRY); float lengthRight = length(controllerRightStick); if (lengthRight > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) controllerRightStick = (controllerRightStick / lengthRight) * (lengthRight - XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) / float(32768 - XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE); else controllerRightStick = float2(0.0f); } else { m_controllerPresent = false; } } // Handle controller rotation if (m_controllerPresent) { m_yaw -= m_controllerRotateSpeed * controllerRightStick.x * abs(controllerRightStick.x) * timestep; m_yaw = modPositive(m_yaw, 2.0f*pi); m_pitch += m_controllerRotateSpeed * controllerRightStick.y * abs(controllerRightStick.y) * timestep; m_pitch = clamp(m_pitch, -0.5f*pi, 0.5f*pi); } UpdateOrientation(); // Handle translation // !!!UNDONE: acceleration based on how long you've been holding the button, // to make fine motions easier? float moveStep = timestep * m_moveSpeed; // !!!UNDONE: move keyboard tracking into an input system that respects focus, etc. if (GetAsyncKeyState(VK_SHIFT) || (controllerState.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER)) moveStep *= 3.0f; if (GetAsyncKeyState('W')) m_pos -= m_viewToWorld[2].xyz * moveStep; if (GetAsyncKeyState('S')) m_pos += m_viewToWorld[2].xyz * moveStep; if (GetAsyncKeyState('A')) m_pos -= m_viewToWorld[0].xyz * moveStep; if (GetAsyncKeyState('D')) m_pos += m_viewToWorld[0].xyz * moveStep; if (GetAsyncKeyState('E')) m_pos += m_viewToWorld[1].xyz * moveStep; if (GetAsyncKeyState('C')) m_pos -= m_viewToWorld[1].xyz * moveStep; if (m_controllerPresent) { float3 localVelocity(0.0f); localVelocity.x = controllerLeftStick.x * abs(controllerLeftStick.x); localVelocity.y = square(controllerRightTrigger) - square(controllerLeftTrigger); localVelocity.z = -controllerLeftStick.y * abs(controllerLeftStick.y); m_pos += xfmVector(localVelocity, m_viewToWorld) * (moveStep * m_controllerMoveSpeed); } // Calculate remaining matrices setTranslation(&m_viewToWorld, m_pos); UpdateWorldToClip(); }
void CubeMan_Light::Update() { GameObject::Update(); float tick = (float)GameManager::GetTick(); jumpTime += tick; if ( ( GetAsyncKeyState('A') & 0x8000 ) != 0 ) { rotationAngle -= ( rotationSpeed * tick ); } else if ( ( GetAsyncKeyState('D') & 0x8000 ) != 0 ) { rotationAngle += ( rotationSpeed * tick ); } if ( ( GetAsyncKeyState('W') & 0x8000 ) != 0 ) { position += ( direction * moveSpeed * tick ); bool wasPressed = keyState[FORWARD]; if ( wasPressed == false ) { //처음 눌렀다. AnimationOnOff(true); } keyState[FORWARD] = true; } else { bool wasPressed = keyState[FORWARD]; if ( wasPressed == true ) { //키를 땐 직후다 AnimationOnOff(false); } keyState[FORWARD] = false; } if ( ( GetAsyncKeyState('S') & 0x8000 ) != 0 ) { position -= ( direction * moveSpeed * tick ); bool wasPressed = keyState[BACKWARD]; if ( wasPressed == false ) { //처음 눌렀다. AnimationOnOff(true); } keyState[BACKWARD] = true; } else { bool wasPressed = keyState[BACKWARD]; if ( wasPressed == true ) { //키를 땐 직후다 AnimationOnOff(false); } keyState[BACKWARD] = false; } if ( ( GetAsyncKeyState('N') & 0x8000 ) != 0 ) { SetNextTexture(); } if ( ( GetAsyncKeyState(VK_SPACE) & 0x8000 ) != 0 && isJumping == false ) { isJumping = true; jumpTime = 0.0f; } D3DXMATRIX scale, rotation, translation; D3DXMatrixScaling(&scale, scaleVector.x, scaleVector.y, scaleVector.z); D3DXMatrixRotationY(&rotation, rotationAngle); world = scale * rotation; D3DXVECTOR3 baseDirection(0, 0, 1); D3DXVec3TransformCoord(&direction, &baseDirection, &world); if ( isJumping ) { position.y = jumpStart + jumpPower * jumpTime - 4.9f/*0.5f * ( 9.8f ) */* jumpTime * jumpTime; if ( position.y < 0.0f ) { isJumping = false; jumpStart = 0.0f; position.y = 0.0f; } } D3DXMatrixTranslation(&translation, position.x, position.y, position.z); world *= translation; root->Update(&world); }
void Update(float deltaTime) { GetCamera().rebuildView(); if (jumping) jumping = GetCamera().jump(GetTime().getGameTime()); //cam.setPosY(mTerrain.getPosY(cam.getPos().x, cam.getPos().z)); GetCamera().keyMsg(deltaTime); //Light rotation mLight.rot(GetTime().getGameTime(), deltaTime, GetCamera().getLook(), GetCamera().getPos()); //Light attributes mLight.keyMsg(deltaTime); //Cube rotation if (funRot) { if (newCube) mTowers.back().rotate(GetTime().getGameTime()); else mTowers.front().rotate(GetTime().getGameTime()); } if (GetAsyncKeyState('B') & 0x8000) { if (newCube) mTowers.back().scaleTower(1.0f); else mTowers.front().scaleTower(1.0f); } if (GetAsyncKeyState('N') & 0x8000) { if (newCube) mTowers.back().scaleTower(2.0f); else mTowers.front().scaleTower(2.0f); } if (GetAsyncKeyState('M') & 0x8000) { if (newCube) mTowers.back().scaleTower(3.0f); else mTowers.front().scaleTower(3.0f); } if (GetAsyncKeyState('P') & 0x8000 && newCube) mTowers.back().move(GetCamera().getPos()); if (GetAsyncKeyState('L') & 0x8000) { if (newCube) mTowers.back().setUV(deltaTime*0.1f, true); else mTowers.front().setUV(deltaTime*0.1f, true); } if (GetAsyncKeyState('K') & 0x8000) { if (newCube) mTowers.back().setUV(deltaTime*0.1f, false); else mTowers.front().setUV(deltaTime*0.1f, false); } fxU.setSpecial(GetCamera().getPos(), mLight, mLight.lightType); fire.setEyePos(GetCamera().getPos()); fire.update(deltaTime, GetTime().getGameTime()); rain.setEyePos(GetCamera().getPos()); rain.setEmitPos(D3DXVECTOR3(GetCamera().getPos().x, GetCamera().getPos().y+50, GetCamera().getPos().z)); rain.update(deltaTime, GetTime().getGameTime()); for(int i = 0; i < mTowers.size(); i++) mTowers.at(i).Update(GetTime().getGameTime(), 3); //mCubes.at(0).WaypointMove(deltaTime, &land); for(int i = 0; i < mCubes.size(); i++) mCubes[i].update(deltaTime, &land); pWave->update(); }
LRESULT kGUISystemWin::Event(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; int key; int newtick,deltatick; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: return DefWindowProc(hWnd, message, wParam, lParam); break; case WM_PAINT: // Get the Windows update region // while(kGUI::GetInDraw()==true || kGUI::GetInThread()==true); // kGUI::SetInDraw(true); GetUpdateRect(hWnd, &m_UpdateWinRect, FALSE); hdc = BeginPaint(hWnd, &ps); Draw(hWnd,m_UpdateWinRect.left,m_UpdateWinRect.right,m_UpdateWinRect.top,m_UpdateWinRect.bottom); EndPaint(hWnd, &ps); // kGUI::SetInDraw(false); break; case WM_TIMER: newtick=GetTickCount(); deltatick=newtick-m_lasttickcount; if(deltatick<0) deltatick=0; m_lasttickcount=newtick; #if DEBUGPRINT kGUI::Trace("Delta tick=%d\n",deltatick); #endif kGUI::Tick(deltatick); if(GetAsyncKeyState(VK_LSHIFT) || GetAsyncKeyState(VK_RSHIFT)) kGUI::SetKeyShift(true); else kGUI::SetKeyShift(false); if(GetAsyncKeyState(VK_CONTROL)) kGUI::SetKeyControl(true); else kGUI::SetKeyControl(false); if(kGUI::GetTempMouse()>=0) { int t=kGUI::GetTempMouse(); kGUI::SetTempMouse(t-1); if(!t) kGUI::SetMouseCursor(MOUSECURSOR_DEFAULT); } if(kGUI::GetMouseCursor()!=MOUSECURSOR_DEFAULT) /* if not default arrow */ kGUI::ChangeMouse(); kGUI::UpdateInput(); m_mousewheeldelta=0; // while(kGUI::GetInDraw()==true || kGUI::GetInThread()==true); // kGUI::SetInDraw(true); Draw(hWnd,0,0,0,0); // kGUI::SetInDraw(false); /* is the application shutting down? */ if(kGUI::IsAppClosed()==true) DestroyWindow(hWnd); else SetTimer(hWnd, 0, 1000 / FRAMES_PER_SECOND, NULL); break; case WM_DESTROY: /* sometimes this event get's called more than once, so allow only once! */ if(m_waskilled==false) { m_waskilled=true; AppClose(); kGUI::Close(); PostQuitMessage(0); WSACleanup(); } break; case WM_MOUSEWHEEL: //values are increments of 120 m_mousewheeldelta = GET_WHEEL_DELTA_WPARAM(wParam)/120; kGUI::SetMouse(m_mousex,m_mousey,m_mousewheeldelta,m_mouseleftbutton,m_mouserightbutton); break; case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MOUSEMOVE: if(kGUI::GetMouseCursor()!=MOUSECURSOR_DEFAULT) /* if not default arrow */ kGUI::ChangeMouse(); m_mousex=GET_X_LPARAM(lParam); m_mousey=GET_Y_LPARAM(lParam); m_mouseleftbutton=(wParam&MK_LBUTTON)!=0; m_mouserightbutton=(wParam&MK_RBUTTON)!=0; /* this tells windows to keep updating me even if the mouse is moved off of */ /* my window area */ if(m_mouseleftbutton || m_mouserightbutton) SetCapture(hWnd); else ReleaseCapture(); kGUI::SetMouse(m_mousex,m_mousey,m_mousewheeldelta,m_mouseleftbutton,m_mouserightbutton); kGUI::Tick(0); kGUI::UpdateInput(); return DefWindowProc(hWnd, message, wParam, lParam); break; case WM_CHAR: key=(int)wParam; switch(key) { case 1: //'ctrl-a' key=GUIKEY_SELECTALL; break; case 3: //'ctrl-c' key=GUIKEY_COPY; break; case 6: //'ctrl-f' key=GUIKEY_FIND; break; // case 8: //'ctrl-h' // key=GUIKEY_REPLACE; // break; case 22: //'ctrl-v' key=GUIKEY_PASTE; break; case 24: //'ctrl-x' key=GUIKEY_CUT; break; case 26: //'ctrl-z' key=GUIKEY_UNDO; break; case 187: //'ctrl +' key=GUIKEY_CTRL_PLUS; break; case 189: //'ctrl -' key=GUIKEY_CTRL_MINUS; break; case VK_BACK: key=GUIKEY_BACKSPACE; break; case VK_RETURN: key=GUIKEY_RETURN; break; case VK_TAB: if(GetAsyncKeyState(VK_LSHIFT) || GetAsyncKeyState(VK_RSHIFT)) key=GUIKEY_SHIFTTAB; else key=GUIKEY_TAB; break; case VK_ESCAPE: key=GUIKEY_ESC; break; case VK_SHIFT: case VK_CONTROL: key=0; break; } if(key) kGUI::KeyPressed(key); break; case WM_KEYDOWN: key=ConvertKey((int)wParam,0); if(key) kGUI::KeyPressed(key); key=ConvertKey((int)wParam,(int)wParam); if(key) kGUI::SetKeyState(key,true); break; case WM_KEYUP: key=ConvertKey((int)wParam,(int)wParam); if(key) kGUI::SetKeyState(key,false); break; default: return DefWindowProc(hWnd, message, wParam, lParam); break; } return 0; }
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { POINT mousePos; int dx = 0; int dy = 0; switch( msg ) { case WM_LBUTTONDOWN: if( wParam & MK_LBUTTON ) { SetCapture(hwnd); mOldMousePos.x = ( short )LOWORD(lParam); mOldMousePos.y = ( short )HIWORD(lParam); gui.UpdateMouse(mOldMousePos.x,mOldMousePos.y,true); } return 0; case WM_LBUTTONUP: ReleaseCapture(); return 0; case WM_RBUTTONDOWN: if( wParam & MK_RBUTTON ) { SetCapture(hwnd); mOldMousePos.x = ( short )LOWORD(lParam); mOldMousePos.y = ( short )HIWORD(lParam); POINT d; d.x = ( short )LOWORD(lParam); d.y = ( short )HIWORD(lParam); //qtc.TEST(vp, d, qtc.getBLS(), 5, md3dDevice); if(gui.GetButton(PLACE_TOWER)->GetPressed()) { D3DXVECTOR3 res = qtc.PlaceATower(vp, d); if (res != D3DXVECTOR3(-99,-99,-99)) { mTowers.push_back(Tower()); mTowers.back().init(md3dDevice, D3DXVECTOR3(7.5f, 7.5f, 7.5f), res); newCube = true; nrOfTowers.resize(mTowers.size()); currentTower = (int)nrOfTowers.size()-1; gui.GetButton(PLACE_TOWER)->SetPressed(false); } } //cam.setLens(0.30f*(gameTime.getDeltaTime()*20), (float)SCREEN_WIDTH/SCREEN_HEIGHT, 1.0f, 1000.0f); } return 0; case WM_RBUTTONUP: GetCamera().setLens(0.30f*pi, (float)SCREEN_WIDTH/SCREEN_HEIGHT, 1.0f, 1000.0f); ReleaseCapture(); return 0; case WM_MOUSEMOVE: if( wParam & MK_LBUTTON || wParam & MK_RBUTTON ) { mousePos.x = ( short )LOWORD(lParam); mousePos.y = ( short )HIWORD(lParam); dx = mousePos.x - mOldMousePos.x; dy = mousePos.y - mOldMousePos.y; GetCamera().rotateY( dx * 0.0087266f ); GetCamera().pitch( dy * 0.0087266f ); mOldMousePos = mousePos; } return 0; case WM_KEYDOWN: if(wParam == VK_CONTROL) GetCamera().crouch(); if(wParam == VK_SPACE) { if (!jumping) GetCamera().setJump(GetTime().getGameTime()); jumping = true; } if (GetAsyncKeyState('F') & 0x8000) { if (funRot) funRot = false; else funRot = true; } if (GetAsyncKeyState('R') & 0x8000) { if (grid) grid = false; else grid = true; } if (GetAsyncKeyState('O') & 0x8000) { if(!newCube) { Tower c; mTowers.push_back(c); mTowers.back().init(md3dDevice, D3DXVECTOR3(1.0f, 1.0f, 1.0f), GetCamera().getPos()); newCube = true; nrOfTowers.resize(mTowers.size()); currentTower = (int)nrOfTowers.size()-1; } else newCube = false; } if (GetAsyncKeyState('Z') & 0x8000) { if(newCube) nrOfTowers[currentTower] = 0; else nrOfTowers[0] = 0; } if (GetAsyncKeyState('X') & 0x8000) { if(newCube) nrOfTowers[currentTower] = 3; else nrOfTowers[0] = 3; } if (GetAsyncKeyState('C') & 0x8000) { if(newCube) nrOfTowers[currentTower] = 6; else nrOfTowers[0] = 6; } if (GetAsyncKeyState('Q') & 0x8000) { pWave->CalldmgCalc(1,10000,"Fire"); pWave->CalldmgCalc(0,10000,"Fire"); } return 0; // WM_DESTROY is sent when the window is being destroyed. case WM_DESTROY: DestroyWindow(g_Hwnd); PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, msg, wParam, lParam); }
void entrypoint( void ) { // full screen #ifdef SETRESOLUTION if( ChangeDisplaySettings(&screenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) return; #endif // create window HWND hWnd = CreateWindow( "static",0,WS_POPUP|WS_VISIBLE|WS_MAXIMIZE,0,0,0,0,0,0,0,0); HDC hDC = GetDC(hWnd); // initalize opengl if( !SetPixelFormat(hDC,ChoosePixelFormat(hDC,&pfd),&pfd) ) return; HGLRC tempOpenGLContext; tempOpenGLContext = wglCreateContext(hDC); wglMakeCurrent(hDC, tempOpenGLContext); // create openGL functions for (int i=0; i<NUM_GL_NAMES; i++) glFP[i] = (GenFP)wglGetProcAddress(glnames[i]); HGLRC hRC = wglCreateContextAttribsARB(hDC, NULL, glAttribs); // Remove temporary context and set new one wglMakeCurrent(NULL, NULL); wglDeleteContext(tempOpenGLContext); wglMakeCurrent(hDC, hRC); // init intro intro_init(); // open audio device waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL); // create music block mzk_init(); // prepare and play music block header[0].lpData = (char *)myMuzikBlock[0]; header[1].lpData = (char *)myMuzikBlock[1]; header[0].dwBufferLength = AUDIO_BUFFER_SIZE * MZK_NUMCHANNELS * 2; header[1].dwBufferLength = AUDIO_BUFFER_SIZE * MZK_NUMCHANNELS * 2; waveOutPrepareHeader(hWaveOut, &(header[0]), sizeof(WAVEHDR)); waveOutWrite(hWaveOut, &(header[0]), sizeof(WAVEHDR)); waveOutPrepareHeader(hWaveOut, &(header[1]), sizeof(WAVEHDR)); waveOutWrite(hWaveOut, &(header[1]), sizeof(WAVEHDR)); timer.wType = TIME_SAMPLES; do { MSG msg; PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); ShowCursor(0); waveOutGetPosition(hWaveOut, &timer, sizeof(timer)); DWORD t = timer.u.sample; intro_do(t); //SwapBuffers ( hDC ); wglSwapLayerBuffers( hDC, WGL_SWAP_MAIN_PLANE ); // Try to unprepare header if (waveOutUnprepareHeader(hWaveOut, &(header[nextPlayBlock]), sizeof(WAVEHDR)) != WAVERR_STILLPLAYING) { mzk_prepare_block(myMuzikBlock[nextPlayBlock]); waveOutPrepareHeader(hWaveOut, &(header[nextPlayBlock]), sizeof(WAVEHDR)); waveOutWrite(hWaveOut, &(header[nextPlayBlock]), sizeof(WAVEHDR)); nextPlayBlock = 1 - nextPlayBlock; } } while ( !(GetAsyncKeyState(VK_ESCAPE) || GetAsyncKeyState(VK_F4))); sndPlaySound(0,0); ExitProcess(0); }
void Projekt::DrawScene() { //--------------------------------------------------------------------------- // Render scene to shadow map //--------------------------------------------------------------------------- mShadowMap->BindDsvAndSetNullRenderTarget(mDirect3D->GetImmediateContext()); drawSceneToShadowMap(); mDirect3D->GetImmediateContext()->RSSetState(0); // Restore back and depth buffer and viewport to the OM stage ID3D11RenderTargetView* renderTargets[1] = {mDirect3D->GetRenderTargetView()}; mDirect3D->GetImmediateContext()->OMSetRenderTargets(1, renderTargets, mDirect3D->GetDepthStencilView()); mDirect3D->GetImmediateContext()->ClearRenderTargetView(mDirect3D->GetRenderTargetView(), reinterpret_cast<const float*>(&Colors::LightSteelBlue)); mDirect3D->GetImmediateContext()->ClearDepthStencilView(mDirect3D->GetDepthStencilView(), D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0); mDirect3D->GetImmediateContext()->RSSetViewports(1, &mDirect3D->GetScreenViewport()); // Possible Wireframe render state if (GetAsyncKeyState('E') & 0x8000) mDirect3D->GetImmediateContext()->RSSetState(WireFrameRS); XMMATRIX shadowTransform = XMLoadFloat4x4(&mShadowTransform); //--------------------------------------------------------------------------- // Draw terrain //--------------------------------------------------------------------------- //mTerrain.Draw(mDirect3D->GetImmediateContext(), mCam, mDirLights); mTerrain.DrawShadowed(mDirect3D->GetImmediateContext(), *mPlayer.GetCamera(), mDirLights, mShadowMap->getDepthMapSRV(), &shadowTransform); // -------------------------------------------------------------------------- // Camera matrices XMMATRIX view = mPlayer.GetCamera()->getViewMatrix(); XMMATRIX proj = mPlayer.GetCamera()->getProjMatrix(); XMMATRIX viewproj = mPlayer.GetCamera()->getViewProjMatrix(); float blendFactor[] = {0.0f, 0.0f, 0.0f, 0.0f}; // Set per frame constants Effects::BasicFX->SetDirLights(mDirLights); Effects::BasicFX->SetEyePosW(mPlayer.GetCamera()->getPosition()); Effects::BasicFX->setShadowMap(mShadowMap->getDepthMapSRV()); Effects::BasicFX->SetCubeMap(mSky->cubeMapSRV()); Effects::NormalMapFX->SetDirLights(mDirLights); Effects::NormalMapFX->SetEyePosW(mPlayer.GetCamera()->getPosition()); Effects::NormalMapFX->setShadowMap(mShadowMap->getDepthMapSRV()); Effects::NormalMapFX->SetCubeMap(mSky->cubeMapSRV()); XMMATRIX world; XMMATRIX worldInvTranspose; XMMATRIX worldViewProj; // Transform NDC space [-1,+1]^2 to texture space [0,1]^2 XMMATRIX toTexSpace( 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.0f, 1.0f); // Vertex size & offset UINT stride = sizeof(Vertex::Basic32); UINT offset = 0; // Draw player //mPlayer.Draw(mDirect3D->GetImmediateContext(), mDirLights, //mShadowMap->getDepthMapSRV(), &shadowTransform); //--------------------------------------------------------------------------- // Draw opaque objects //--------------------------------------------------------------------------- // Bind information about primitive type, and set input layout mDirect3D->GetImmediateContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); mDirect3D->GetImmediateContext()->IASetInputLayout(InputLayouts::Basic32); // Set our effect technique to use ID3DX11EffectTechnique* activeTech = Effects::BasicFX->DirLights3FogTexTech; ID3DX11EffectTechnique* activeSkinnedTech = Effects::NormalMapFX->DirLights3TexTech; D3DX11_TECHNIQUE_DESC techDesc; //-------------------------------------------------------------------------------- // Draw opaque tessellated objects //-------------------------------------------------------------------------------- Effects::BasicTessFX->SetDirLights(mDirLights); Effects::BasicTessFX->SetEyePosW(mPlayer.GetCamera()->getPosition()); Effects::BasicTessFX->setShadowMap(mShadowMap->getDepthMapSRV()); Effects::BasicTessFX->SetCubeMap(mSky->cubeMapSRV()); mDirect3D->GetImmediateContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST); mDirect3D->GetImmediateContext()->IASetInputLayout(InputLayouts::PosNormalTexTan); activeTech = Effects::BasicTessFX->TessDirLights3FogTexTech; activeTech->GetDesc(&techDesc); for (UINT p = 0; p < techDesc.Passes; ++p) { for (UINT mIndex = 0; mIndex < mGenericInstances.size(); ++mIndex) { if (mGenericInstances[mIndex].isVisible) { world = XMLoadFloat4x4(&mGenericInstances[mIndex].world); worldInvTranspose = MathHelper::InverseTranspose(world); worldViewProj = world*view*proj; Effects::BasicTessFX->SetWorld(world); Effects::BasicTessFX->SetWorldInvTranspose(worldInvTranspose); Effects::BasicTessFX->SetWorldViewProj(worldViewProj); Effects::BasicTessFX->SetWorldViewProjTex(worldViewProj*toTexSpace); Effects::BasicTessFX->setShadowTransform(world*shadowTransform); Effects::BasicTessFX->SetTexTransform(XMMatrixScaling(1.0f, 1.0f, 1.0f)); Effects::BasicTessFX->SetMinTessDistance(20.0f); Effects::BasicTessFX->SetMaxTessDistance(200.0f); Effects::BasicTessFX->SetMinTessFactor(0.0f); Effects::BasicTessFX->SetMaxTessFactor(3.0f); Effects::BasicTessFX->setFogStart(GameSettings::Instance()->Fog()->fogStart); Effects::BasicTessFX->setFogRange(GameSettings::Instance()->Fog()->fogRange); Effects::BasicTessFX->setFogColor(Colors::Silver); for (UINT i = 0; i < mGenericInstances[mIndex].model->meshCount; ++i) { UINT matIndex = mGenericInstances[mIndex].model->meshes[i].MaterialIndex; Effects::BasicTessFX->SetMaterial(mGenericInstances[mIndex].model->mat[matIndex]); Effects::BasicTessFX->SetDiffuseMap(mGenericInstances[mIndex].model->diffuseMapSRV[matIndex]); //Effects::BasicTessFX->SetNormalMap(mGenericInstances[mIndex].model->normalMapSRV[matIndex]); activeTech->GetPassByIndex(p)->Apply(0, mDirect3D->GetImmediateContext()); mGenericInstances[mIndex].model->meshes[i].draw(mDirect3D->GetImmediateContext()); } } } } // FX sets tessellation stages, but it does not disable them. So do that here // to turn off tessellation. mDirect3D->GetImmediateContext()->HSSetShader(0, 0, 0); mDirect3D->GetImmediateContext()->DSSetShader(0, 0, 0); mDirect3D->GetImmediateContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); mDirect3D->GetImmediateContext()->IASetInputLayout(InputLayouts::PosNormalTexTanSkinned); // Skinned objects activeSkinnedTech->GetDesc(&techDesc); for (UINT p = 0; p < techDesc.Passes; ++p) { for (UINT mIndex = 0; mIndex < mGenSkinnedInstances.size(); ++mIndex) { if (mGenSkinnedInstances[mIndex].isVisible) { world = XMLoadFloat4x4(&mGenSkinnedInstances[mIndex].world); worldInvTranspose = MathHelper::InverseTranspose(world); worldViewProj = world*view*proj; Effects::NormalMapFX->SetWorld(world); Effects::NormalMapFX->SetWorldInvTranspose(worldInvTranspose); Effects::NormalMapFX->SetWorldViewProj(worldViewProj); Effects::NormalMapFX->SetWorldViewProjTex(worldViewProj*toTexSpace); Effects::NormalMapFX->setShadowTransform(world*shadowTransform); Effects::NormalMapFX->SetTexTransform(XMMatrixScaling(1.0f, 1.0f, 1.0f)); Effects::NormalMapFX->setFogStart(GameSettings::Instance()->Fog()->fogStart); Effects::NormalMapFX->setFogRange(GameSettings::Instance()->Fog()->fogRange); Effects::NormalMapFX->setBoneTransforms(&mGenSkinnedInstances[mIndex].FinalTransforms[0], mGenSkinnedInstances[mIndex].FinalTransforms.size()); Effects::BasicTessFX->setFogColor(Colors::Silver); for (UINT i = 0; i < mGenSkinnedInstances[mIndex].model->numMeshes; ++i) { UINT matIndex = mGenSkinnedInstances[mIndex].model->meshes[i].MaterialIndex; Effects::NormalMapFX->SetMaterial(mGenSkinnedInstances[mIndex].model->mat[matIndex]); Effects::NormalMapFX->SetDiffuseMap(mGenSkinnedInstances[mIndex].model->diffuseMapSRV[matIndex]); Effects::NormalMapFX->setNormalMap(mGenSkinnedInstances[mIndex].model->normalMapSRV[matIndex]); activeSkinnedTech->GetPassByIndex(p)->Apply(0, mDirect3D->GetImmediateContext()); mGenSkinnedInstances[mIndex].model->meshes[i].draw(mDirect3D->GetImmediateContext()); } } } } //--------------------------------------------------------------------------- // Draw particle systems //--------------------------------------------------------------------------- mFire.setEyePos(mPlayer.GetCamera()->getPosition()); mFire.draw(mDirect3D->GetImmediateContext(), *mPlayer.GetCamera()); mDirect3D->GetImmediateContext()->OMSetBlendState(0, blendFactor, 0xffffffff); // restore default //--------------------------------------------------------------------------- // Draw sky //--------------------------------------------------------------------------- mSky->draw(mDirect3D->GetImmediateContext(), *mPlayer.GetCamera()); // Unbind shadow map and AmbientMap as a shader input because we are going to render // to it next frame. These textures can be at any slot, so clear all slots. ID3D11ShaderResourceView* nullSRV[16] = { 0 }; mDirect3D->GetImmediateContext()->PSSetShaderResources(0, 16, nullSRV); // Restore default states mDirect3D->GetImmediateContext()->RSSetState(0); mDirect3D->GetImmediateContext()->OMSetDepthStencilState(0, 0); mDirect3D->GetImmediateContext()->OMSetBlendState(0, blendFactor, 0xffffffff); HR(mDirect3D->GetSwapChain()->Present(0, 0)); }
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: // register interest in raw data here rid.dwFlags = RIDEV_INPUTSINK; rid.usUsagePage = 1; rid.usUsage = 6; rid.hwndTarget = hWnd; RegisterRawInputDevices(&rid, 1, sizeof(rid)); return DefWindowProc(hWnd, message, wParam, lParam); case WM_USER_HKLISTEN: g_acceptHotKey = true; break; case WM_INPUT: { if (!g_acceptHotKey) break; UINT dwSize; if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)) == -1) { break; } LPBYTE lpb = new BYTE[dwSize]; if (lpb == NULL) { break; } if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize) { delete[] lpb; break; } PRAWINPUT raw = (PRAWINPUT)lpb; if (raw->data.keyboard.Message == WM_KEYDOWN) { if (raw->data.keyboard.VKey == g_hotKey) { if (GetAsyncKeyState(VK_MENU) && GetAsyncKeyState(VK_CONTROL)) { LPWSTR sName = new wchar_t[1024]; GetWindowText(g_hComboSection, sName, 1023); PopupData * pD = new PopupData(); pD->parent = hWnd; pD->instance = hInst; pD->sname = sName; CreateThread(NULL, // default security attributes 0, // default stack size PopupThread,// start address (in Popup.cpp) pD, // pass PopupData 0, &popupThreadID ); g_acceptHotKey = false; } } } break; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code that uses hdc here... EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
bool IsKeyPressed(Key key) { int vkey = 0; switch (key) { default: vkey = 0; break; case Key::A: vkey = 'A'; break; case Key::B: vkey = 'B'; break; case Key::C: vkey = 'C'; break; case Key::D: vkey = 'D'; break; case Key::E: vkey = 'E'; break; case Key::F: vkey = 'F'; break; case Key::G: vkey = 'G'; break; case Key::H: vkey = 'H'; break; case Key::I: vkey = 'I'; break; case Key::J: vkey = 'J'; break; case Key::K: vkey = 'K'; break; case Key::L: vkey = 'L'; break; case Key::M: vkey = 'M'; break; case Key::N: vkey = 'N'; break; case Key::O: vkey = 'O'; break; case Key::P: vkey = 'P'; break; case Key::Q: vkey = 'Q'; break; case Key::R: vkey = 'R'; break; case Key::S: vkey = 'S'; break; case Key::T: vkey = 'T'; break; case Key::U: vkey = 'U'; break; case Key::V: vkey = 'V'; break; case Key::W: vkey = 'W'; break; case Key::X: vkey = 'X'; break; case Key::Y: vkey = 'Y'; break; case Key::Z: vkey = 'Z'; break; case Key::Num0: vkey = '0'; break; case Key::Num1: vkey = '1'; break; case Key::Num2: vkey = '2'; break; case Key::Num3: vkey = '3'; break; case Key::Num4: vkey = '4'; break; case Key::Num5: vkey = '5'; break; case Key::Num6: vkey = '6'; break; case Key::Num7: vkey = '7'; break; case Key::Num8: vkey = '8'; break; case Key::Num9: vkey = '9'; break; case Key::Escape: vkey = VK_ESCAPE; break; case Key::LControl: vkey = VK_LCONTROL; break; case Key::LShift: vkey = VK_LSHIFT; break; case Key::LAlt: vkey = VK_LMENU; break; case Key::LSystem: vkey = VK_LWIN; break; case Key::RControl: vkey = VK_RCONTROL; break; case Key::RShift: vkey = VK_RSHIFT; break; case Key::RAlt: vkey = VK_RMENU; break; case Key::RSystem: vkey = VK_RWIN; break; case Key::Menu: vkey = VK_APPS; break; case Key::LBracket: vkey = VK_OEM_4; break; case Key::RBracket: vkey = VK_OEM_6; break; case Key::SemiColon: vkey = VK_OEM_1; break; case Key::Comma: vkey = VK_OEM_COMMA; break; case Key::Period: vkey = VK_OEM_PERIOD; break; case Key::Quote: vkey = VK_OEM_7; break; case Key::Slash: vkey = VK_OEM_2; break; case Key::BackSlash: vkey = VK_OEM_5; break; case Key::Tilde: vkey = VK_OEM_3; break; case Key::Equal: vkey = VK_OEM_PLUS; break; case Key::Dash: vkey = VK_OEM_MINUS; break; case Key::Space: vkey = VK_SPACE; break; case Key::Return: vkey = VK_RETURN; break; case Key::BackSpace: vkey = VK_BACK; break; case Key::Tab: vkey = VK_TAB; break; case Key::PageUp: vkey = VK_PRIOR; break; case Key::PageDown: vkey = VK_NEXT; break; case Key::End: vkey = VK_END; break; case Key::Home: vkey = VK_HOME; break; case Key::Insert: vkey = VK_INSERT; break; case Key::Delete: vkey = VK_DELETE; break; case Key::Add: vkey = VK_ADD; break; case Key::Subtract: vkey = VK_SUBTRACT; break; case Key::Multiply: vkey = VK_MULTIPLY; break; case Key::Divide: vkey = VK_DIVIDE; break; case Key::Left: vkey = VK_LEFT; break; case Key::Right: vkey = VK_RIGHT; break; case Key::Up: vkey = VK_UP; break; case Key::Down: vkey = VK_DOWN; break; case Key::Numpad0: vkey = VK_NUMPAD0; break; case Key::Numpad1: vkey = VK_NUMPAD1; break; case Key::Numpad2: vkey = VK_NUMPAD2; break; case Key::Numpad3: vkey = VK_NUMPAD3; break; case Key::Numpad4: vkey = VK_NUMPAD4; break; case Key::Numpad5: vkey = VK_NUMPAD5; break; case Key::Numpad6: vkey = VK_NUMPAD6; break; case Key::Numpad7: vkey = VK_NUMPAD7; break; case Key::Numpad8: vkey = VK_NUMPAD8; break; case Key::Numpad9: vkey = VK_NUMPAD9; break; case Key::F1: vkey = VK_F1; break; case Key::F2: vkey = VK_F2; break; case Key::F3: vkey = VK_F3; break; case Key::F4: vkey = VK_F4; break; case Key::F5: vkey = VK_F5; break; case Key::F6: vkey = VK_F6; break; case Key::F7: vkey = VK_F7; break; case Key::F8: vkey = VK_F8; break; case Key::F9: vkey = VK_F9; break; case Key::F10: vkey = VK_F10; break; case Key::F11: vkey = VK_F11; break; case Key::F12: vkey = VK_F12; break; case Key::F13: vkey = VK_F13; break; case Key::F14: vkey = VK_F14; break; case Key::F15: vkey = VK_F15; break; case Key::Pause: vkey = VK_PAUSE; break; } return (GetAsyncKeyState(vkey) & 0x8000) != 0; }
void Bonus (Score_t* score) { if (GetAsyncKeyState ('1') && score->points >= 50) {HP+=1.0; score->points -= 50;}; }
bool getKey(Key key) { return (GetAsyncKeyState(Imp::WinKey[static_cast<i32>(key)])) != 0; }
void keyEvent(rdr::U32 keysym, bool down, bool jap) { //vnclog.Print(LL_INTWARN, " keysym 0x%x",keysym); if (keysym>=XK_dead_grave && keysym <=XK_dead_belowdot)// && down) { keysymDead=keysym; vnclog.Print(LL_INTWARN, " ************** DEAD KEY"); //we have a dead key //Record dead key return; } if ((keysym >= 32 && keysym <= 126) || (keysym >= 160 && keysym <= 255)) { if (keysymDead!=0 && down) { vnclog.Print(LL_INTWARN, " Compose dead 0x%x 0x%x",keysymDead,keysym); switch (keysymDead) { case XK_dead_grave: switch(keysym) { case XK_A: keysym=XK_Agrave;break; case XK_E: keysym=XK_Egrave;break; case XK_I: keysym=XK_Igrave;break; case XK_O: keysym=XK_Ograve;break; case XK_U: keysym=XK_Ugrave;break; case XK_a: keysym=XK_agrave;break; case XK_e: keysym=XK_egrave;break; case XK_i: keysym=XK_igrave;break; case XK_o: keysym=XK_ograve;break; case XK_u: keysym=XK_ugrave;break; } case XK_dead_acute: switch(keysym) { case XK_A: keysym=XK_Aacute;break; case XK_E: keysym=XK_Eacute;break; case XK_I: keysym=XK_Iacute;break; case XK_O: keysym=XK_Oacute;break; case XK_U: keysym=XK_Uacute;break; case XK_a: keysym=XK_aacute;break; case XK_e: keysym=XK_eacute;break; case XK_i: keysym=XK_iacute;break; case XK_o: keysym=XK_oacute;break; case XK_u: keysym=XK_uacute;break; case XK_y: keysym=XK_yacute;break; case XK_Y: keysym=XK_Yacute;break; } case XK_dead_circumflex: switch(keysym) { case XK_A: keysym=XK_Acircumflex;break; case XK_E: keysym=XK_Ecircumflex;break; case XK_I: keysym=XK_Icircumflex;break; case XK_O: keysym=XK_Ocircumflex;break; case XK_U: keysym=XK_Ucircumflex;break; case XK_a: keysym=XK_acircumflex;break; case XK_e: keysym=XK_ecircumflex;break; case XK_i: keysym=XK_icircumflex;break; case XK_o: keysym=XK_ocircumflex;break; case XK_u: keysym=XK_ucircumflex;break; } case XK_dead_tilde: switch(keysym) { case XK_A : keysym=XK_Ntilde;break; case XK_O : keysym=XK_Otilde;break; case XK_a : keysym=XK_atilde;break; case XK_n : keysym=XK_ntilde;break; case XK_o : keysym=XK_otilde;break; } case XK_dead_diaeresis: switch(keysym) { case XK_A: keysym=XK_Adiaeresis;break; case XK_E: keysym=XK_Ediaeresis;break; case XK_I: keysym=XK_Idiaeresis;break; case XK_O: keysym=XK_Odiaeresis;break; case XK_U: keysym=XK_Udiaeresis;break; case XK_a: keysym=XK_adiaeresis;break; case XK_e: keysym=XK_ediaeresis;break; case XK_i: keysym=XK_idiaeresis;break; case XK_o: keysym=XK_odiaeresis;break; case XK_u: keysym=XK_udiaeresis;break; case XK_y: keysym=XK_ydiaeresis;break; } case XK_dead_cedilla: switch(keysym) { case XK_C: keysym=XK_Ccedilla;break; case XK_c: keysym=XK_ccedilla;break; } } keysymDead=0; vnclog.Print(LL_INTWARN, " Composed 0x%x",keysym); } // ordinary Latin-1 character SHORT s = VkKeyScan(keysym); // [v1.0.2-jp1 fix] yak!'s patch // This break Other keyboards, we need an easy way of fixing this if (jap) { if (keysym==XK_kana_WO) { s = 0x0130; } else if (keysym==XK_backslash) { s = 0x00e2; } else if (keysym==XK_yen) { s = 0x00dc; } } //vnclog.Print(LL_INTWARN, " SHORT s %i",s); if (s == -1) { if (down) { vnclog.Print(LL_INTWARN, "down"); // not a single keypress - try synthesizing dead chars. { vnclog.Print(LL_INTWARN, " Found key"); //Lookup ascii representation int ascii=0; #if 0 // 11 Dec 2008 jdp disabled since the viewer is sending unicode now for (ascii=0;ascii<256;ascii++) { if (keysym==ascii_to_x[ascii]) break; } #endif ascii = keysym; if (ascii <= 255) { rdr::U8 a0=ascii/100; ascii=ascii%100; rdr::U8 a1=ascii/10; ascii=ascii%10; rdr::U8 a2=ascii; KeyStateModifier shift(VK_SHIFT); KeyStateModifier lshift(VK_LSHIFT); KeyStateModifier rshift(VK_RSHIFT); if (vncService::IsWin95()) { shift.release(); } else { lshift.release(); rshift.release(); } vnclog.Print(LL_INTWARN, " Simulating ALT+%d%d%d\n", a0, a1 ,a2); keybd_event(VK_MENU,MapVirtualKey( VK_MENU, 0 ), 0 ,0); /** Pressing the Alt+NNN combinations without leading zero (for example, Alt+20, Alt+130, Alt+221) will insert characters from the Extended ASCII (or MS DOS ASCII, or OEM) table. The character glyphs contained by this table depend on the language of Windows. See the table below for the list of characters that can be inserted through the Alt+NNN combinations (without leading zero) in English Windows. Pressing the Alt+0NNN combinations will insert the ANSI characters corresponding to the activate keyboard layout. Please see Windows Character Map utility (charmap.exe) for the possible Alt+0NNN combinations. Finally, the Alt+00NNN combinations (two leading zeros) will insert Unicode characters. The Unicode codes of characters are displayed in Charmap. **/ // jdp 11 December 2008 - Need the leading 0! keybd_event(VK_NUMPAD0, MapVirtualKey(VK_NUMPAD0, 0), 0, 0); keybd_event(VK_NUMPAD0, MapVirtualKey(VK_NUMPAD0, 0),KEYEVENTF_KEYUP,0); keybd_event(VK_NUMPAD0+a0, MapVirtualKey(VK_NUMPAD0+a0, 0), 0, 0); keybd_event(VK_NUMPAD0+a0, MapVirtualKey(VK_NUMPAD0+a0, 0),KEYEVENTF_KEYUP,0); keybd_event(VK_NUMPAD0+a1, MapVirtualKey(VK_NUMPAD0+a1, 0),0,0); keybd_event(VK_NUMPAD0+a1, MapVirtualKey(VK_NUMPAD0+a1, 0),KEYEVENTF_KEYUP, 0); keybd_event(VK_NUMPAD0+a2, MapVirtualKey(VK_NUMPAD0+a2, 0) ,0, 0); keybd_event(VK_NUMPAD0+a2, MapVirtualKey(VK_NUMPAD0+a2, 0),KEYEVENTF_KEYUP, 0); keybd_event(VK_MENU, MapVirtualKey( VK_MENU, 0 ),KEYEVENTF_KEYUP, 0); return; } } vnclog.Print(LL_INTWARN, "ignoring unrecognised Latin-1 keysym 0x%x",keysym); } return; } /*if (s == -1) { vnclog.Print(LL_INTWARN, "ignoring unrecognised Latin-1 keysym %d\n", keysym); keybd_event( VK_MENU, MapVirtualKey(VK_MENU, 0),0, 0); keybd_event( VK_MENU, MapVirtualKey(VK_MENU, 0),KEYEVENTF_KEYUP, 0); return; }*/ BYTE vkCode = LOBYTE(s); // 18 March 2008 jdp // Correct the keymask shift state to cope with the capslock state BOOL capslockOn = (GetKeyState(VK_CAPITAL) & 1) != 0; BYTE modifierState = HIBYTE(s); modifierState = capslockOn ? modifierState ^ 1 : modifierState; KeyStateModifier ctrl(VK_CONTROL); KeyStateModifier alt(VK_MENU); KeyStateModifier shift(VK_SHIFT); KeyStateModifier lshift(VK_LSHIFT); KeyStateModifier rshift(VK_RSHIFT); if (down) { if (modifierState & 2) ctrl.press(); if (modifierState & 4) alt.press(); if (modifierState & 1) { shift.press(); } else { // [v1.0.2-jp1 fix] Even if "SHIFT + SPACE" are pressed, "SHIFT" is valid if (vkCode == 0x20){ } else{ if (vncService::IsWin95()) { shift.release(); } else { lshift.release(); rshift.release(); } } } } vnclog.Print(LL_INTINFO, "latin-1 key: keysym %d(0x%x) vkCode 0x%x down %d capslockOn %d\n", keysym, keysym, vkCode, down, capslockOn); doKeyboardEvent(vkCode, down ? 0 : KEYEVENTF_KEYUP); } else { // see if it's a recognised keyboard key, otherwise ignore it if (vkMap.find(keysym) == vkMap.end()) { vnclog.Print(LL_INTWARN, "ignoring unknown keysym %d\n",keysym); return; } BYTE vkCode = vkMap[keysym]; DWORD flags = 0; if (extendedMap[keysym]) flags |= KEYEVENTF_EXTENDEDKEY; if (!down) flags |= KEYEVENTF_KEYUP; // vnclog.Print(LL_INTINFO, // "keyboard key: keysym %d(0x%x) vkCode 0x%x ext %d down %d\n", // keysym, keysym, vkCode, extendedMap[keysym], down); if (down && (vkCode == VK_DELETE) && ((GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0) && ((GetAsyncKeyState(VK_MENU) & 0x8000) != 0) && vncService::IsWinNT()) { vnclog.Print(LL_INTINFO, "CAD\n"); // If running under Vista and started from Session0 in Application mode if (vncService::VersionMajor()>=6 && vncService::RunningFromExternalService() ) { vnclog.Print(LL_INTINFO, "Vista and runnning as system -> CAD\n"); // Try to run the special Vista cad.exe file... HANDLE ThreadHandle2; DWORD dwTId; ThreadHandle2 = CreateThread(NULL, 0, Cadthread, NULL, 0, &dwTId); CloseHandle(ThreadHandle2); } else if (vncService::VersionMajor()>=6) { vnclog.Print(LL_INTINFO, "Vista and runnning as user -> Taskmgr\n"); WinExec("taskmgr.exe", SW_SHOWNORMAL); } else if (vncService::VersionMajor()<6 && vncService::RunningFromExternalService() ) { vnclog.Print(LL_INTINFO, "Not Vista and runnning as system, use old method\n"); vncService::SimulateCtrlAltDel(); } else if (vncService::VersionMajor()<6) { vnclog.Print(LL_INTINFO, "Not Vista and runnning as user -> Taskmgr\n"); WinExec("taskmgr.exe", SW_SHOWNORMAL); } return; } if (vncService::IsWin95()) { switch (vkCode) { case VK_RSHIFT: vkCode = VK_SHIFT; break; case VK_RCONTROL: vkCode = VK_CONTROL; break; case VK_RMENU: vkCode = VK_MENU; break; } } doKeyboardEvent(vkCode, flags); } }
void InputMoveComponent::update( float dt ) { auto comp = parent->getComponent<TransformComponent>(); comp->setTranslation( comp->getTranslation() + glm::vec3( 0, (GetAsyncKeyState('W')?1:0) - (GetAsyncKeyState('S')?1:0), (GetAsyncKeyState('D')?1:0) - (GetAsyncKeyState('A')?1:0) )*4.0f*dt ); }
static BOOL CALLBACK DirProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { static int dontsetdefstyle; page *thispage = g_this_page; char *dir = g_usrvars[thispage->parms[4]]; int browse_text = thispage->parms[3]; if (uMsg == WM_NOTIFY_INIGO_MONTOYA) { GetUIText(IDC_DIR,dir); validate_filename(dir); #ifdef NSIS_CONFIG_LOG #if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT) build_g_logfile(); #endif if (GetUIItem(IDC_CHECK1) != NULL) log_dolog = IsDlgButtonChecked(hwndDlg,IDC_CHECK1); #endif } if (uMsg == WM_INITDIALOG) { HWND hDir = GetUIItem(IDC_DIR); #ifdef NSIS_CONFIG_LOG if (GetAsyncKeyState(VK_SHIFT)&0x8000) { HWND h=GetUIItem(IDC_CHECK1); SetUITextFromLang(IDC_CHECK1,LANG_LOG_INSTALL_PROCESS); ShowWindow(h,SW_SHOWNA); } #endif if (validpathspec(dir) && !skip_root(dir)) addtrailingslash(dir); // workaround for bug #1209843 // // m_curwnd is only updated once WM_INITDIALOG returns. // my_SetWindowText triggers an EN_CHANGE message that // triggers a WM_IN_UPDATEMSG message that uses m_curwnd // to get the selected directory (GetUIText). // because m_curwnd is still outdated, dir varialble is // filled with an empty string. by default, dir points // to $INSTDIR. // // to solve this, m_curwnd is manually set to the correct // window handle. m_curwnd=hwndDlg; my_SetWindowText(hDir,dir); SetUITextFromLang(IDC_BROWSE,this_page->parms[2]); SetUITextFromLang(IDC_SELDIRTEXT,this_page->parms[1]); SetActiveCtl(hDir); { typedef HRESULT (WINAPI *SHAutoCompletePtr)(HWND, DWORD); SHAutoCompletePtr fSHAutoComplete; fSHAutoComplete = (SHAutoCompletePtr) myGetProcAddress(MGA_SHAutoComplete); if (fSHAutoComplete) { fSHAutoComplete(hDir, SHACF_FILESYSTEM); } } } if (uMsg == WM_COMMAND) { int id=LOWORD(wParam); if (id == IDC_DIR && HIWORD(wParam) == EN_CHANGE) { uMsg = WM_IN_UPDATEMSG; } if (id == IDC_BROWSE) { static char bt[NSIS_MAX_STRLEN]; BROWSEINFO bi = {0,}; ITEMIDLIST *idlist; bi.hwndOwner = hwndDlg; bi.pszDisplayName = g_tmp; bi.lpfn = BrowseCallbackProc; bi.lParam = (LPARAM)dir; bi.lpszTitle = GetNSISString(bt, browse_text); bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE; idlist = SHBrowseForFolder(&bi); if (idlist) { // free idlist CoTaskMemFree(idlist); addtrailingslash(dir); if (g_header->install_directory_auto_append && dir == state_install_directory) // only append to $INSTDIR (bug #1174184) { const char *post_str = ps_tmpbuf; GetNSISStringTT(g_header->install_directory_auto_append); // display name gives just the folder name if (lstrcmpi(post_str, g_tmp)) { mystrcat(dir, post_str); } } dontsetdefstyle++; SetUITextNT(IDC_DIR,dir); } else { uMsg = WM_IN_UPDATEMSG; } } } if (uMsg == WM_IN_UPDATEMSG || uMsg == WM_NOTIFY_START) { static char s[NSIS_MAX_STRLEN]; int error = 0; int available_set = 0; unsigned total, available; GetUIText(IDC_DIR,dir); if (!is_valid_instpath(dir)) error = NSIS_INSTDIR_INVALID; /** * This part is tricky. We need to make sure a few things: * * 1. GetDiskFreeSpaceEx is always called at least once for large HD. * Even if skip_root() returned NULL (e.g. "C:"). * Note that trimslashtoend() will nullify "C:". * 2. GetDiskFreeSpaceEx is called with the deepest valid directory. * e.g. C:\drive when the user types C:\drive\folder1\folder2. * This makes sure NTFS mount points are treated properly (#1946112). * 3. `s' stays valid after the loop for GetDiskFreeSpace. * This means there is no cutting beyond what skip_root() returns. * Or `s' could be recreated when GetDiskFreeSpace is called. * 4. If GetDiskFreeSpaceEx doesn't exist, GetDiskFreeSpace is used. * 5. Both functions require a trailing backslash * 6. `dir' is never modified. * */ mystrcpy(s,dir); // Test for and use the GetDiskFreeSpaceEx API { BOOL (WINAPI *GDFSE)(LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER) = myGetProcAddress(MGA_GetDiskFreeSpaceExA); if (GDFSE) { ULARGE_INTEGER available64; ULARGE_INTEGER a, b; char *p; WORD *pw = NULL; while ((char *) pw != s) // trimslashtoend() cut the entire string { if (GDFSE(s, &available64, &a, &b)) { #ifndef _NSIS_NO_INT64_SHR available = (int)(available64.QuadPart >> 10); #else available = (int)(Int64ShrlMod32(available64.QuadPart, 10)); #endif available_set++; break; } if (pw) // if pw was set, remove the backslash so trimslashtoend() will cut a new one *pw = 0; p = trimslashtoend(s); // trim last backslash pw = (LPWORD) (p - 1); *pw = CHAR2_TO_WORD('\\', 0); // bring it back, but make the next char null } } } if (!available_set) { DWORD spc, bps, fc, tc; char *root; // GetDiskFreeSpaceEx accepts any path, but GetDiskFreeSpace accepts only the root mystrcpy(s,dir); root=skip_root(s); if (root) *root=0; // GetDiskFreeSpaceEx is not available if (GetDiskFreeSpace(s, &spc, &bps, &fc, &tc)) { available = (int)MulDiv(bps * spc, fc, 1 << 10); available_set++; } } total = (unsigned) sumsecsfield(size_kb); if (available_set && available < total) error = NSIS_INSTDIR_NOT_ENOUGH_SPACE; if (LANG_STR_TAB(LANG_SPACE_REQ)) { SetSizeText(IDC_SPACEREQUIRED,LANG_SPACE_REQ,total); if (available_set) SetSizeText(IDC_SPACEAVAILABLE,LANG_SPACE_AVAIL,available); else SetUITextNT(IDC_SPACEAVAILABLE,""); } g_exec_flags.instdir_error = error; #ifdef NSIS_SUPPORT_CODECALLBACKS if (!error) error = ExecuteCallbackFunction(CB_ONVERIFYINSTDIR); #endif if (thispage->flags & PF_DIR_NO_BTN_DISABLE) error = 0; EnableNext(!error); if (!error && !dontsetdefstyle) SetNextDef(); dontsetdefstyle = 0; }
bool Application::IsKeyPressed(unsigned short key) { return ((GetAsyncKeyState(key) & 0x8001) != 0); }
void OBSAPIInterface::HandleHotkeys() { List<DWORD> hitKeys; DWORD modifiers = 0; if(GetAsyncKeyState(VK_MENU) & 0x8000) modifiers |= HOTKEYF_ALT; if(GetAsyncKeyState(VK_CONTROL) & 0x8000) modifiers |= HOTKEYF_CONTROL; if(GetAsyncKeyState(VK_SHIFT) & 0x8000) modifiers |= HOTKEYF_SHIFT; OSEnterMutex(App->hHotkeyMutex); for(UINT i=0; i<hotkeys.Num(); i++) { HotkeyInfo &info = hotkeys[i]; DWORD hotkeyVK = LOBYTE(info.hotkey); DWORD hotkeyModifiers = HIBYTE(info.hotkey); hotkeyModifiers &= ~(HOTKEYF_EXT); //changed so that it allows hotkeys to be pressed even if extra modiifers are pushed bool bModifiersMatch = ((hotkeyModifiers & modifiers) == hotkeyModifiers);//(hotkeyModifiers == modifiers); if(hotkeyModifiers && !hotkeyVK) //modifier-only hotkey { if((hotkeyModifiers & modifiers) == hotkeyModifiers) { if(!info.bHotkeyDown) { PostMessage(hwndMain, OBS_CALLHOTKEY, TRUE, info.hotkeyID); info.bDownSent = true; info.bHotkeyDown = true; } continue; } } else { if(bModifiersMatch) { short keyState = GetAsyncKeyState(hotkeyVK); bool bDown = (keyState & 0x8000) != 0; bool bWasPressed = (keyState & 0x1) != 0; if(bDown || bWasPressed) { if(!info.bHotkeyDown && info.bModifiersDown) //only triggers the hotkey if the actual main key was pressed second { PostMessage(hwndMain, OBS_CALLHOTKEY, TRUE, info.hotkeyID); info.bDownSent = true; } info.bHotkeyDown = true; if(bDown) continue; } } } info.bModifiersDown = bModifiersMatch; if(info.bHotkeyDown) //key up { if(info.bDownSent) { PostMessage(hwndMain, OBS_CALLHOTKEY, FALSE, info.hotkeyID); info.bDownSent = false; } info.bHotkeyDown = false; } } OSLeaveMutex(App->hHotkeyMutex); }
// Program entry point function. int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); g_appStartupTime = timeGetTime(); CefMainArgs main_args(hInstance); CefRefPtr<ClientApp> app(new ClientApp); // Execute the secondary process, if any. int exit_code = CefExecuteProcess(main_args, app.get()); if (exit_code >= 0) return exit_code; // Retrieve the current working directory. if (_getcwd(szWorkingDir, MAX_PATH) == NULL) szWorkingDir[0] = 0; // Parse command line arguments. The passed in values are ignored on Windows. AppInitCommandLine(0, NULL); CefSettings settings; // Populate the settings based on command line arguments. AppGetSettings(settings, app); // Check command if (CefString(&settings.cache_path).length() == 0) { CefString(&settings.cache_path) = AppGetCachePath(); } // Initialize CEF. CefInitialize(main_args, settings, app.get()); HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_CEFCLIENT, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance, settings.locale); // If the shift key is not pressed, look for the index.html file if (GetAsyncKeyState(VK_SHIFT) == 0) { // Get the full pathname for the app. We look for the index.html // file relative to this location. wchar_t appPath[MAX_PATH]; wchar_t *pathRoot; GetModuleFileName(NULL, appPath, MAX_PATH); // Strip the .exe filename (and preceding "\") from the appPath // and store in pathRoot pathRoot = wcsrchr(appPath, '\\'); // Look for .\dev\src\index.html first wcscpy(pathRoot, L"\\dev\\src\\index.html"); // If the file exists, use it if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) { wcscpy(szInitialUrl, appPath); } if (!wcslen(szInitialUrl)) { // Look for .\www\index.html next wcscpy(pathRoot, L"\\www\\index.html"); if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) { wcscpy(szInitialUrl, appPath); } } } if (!wcslen(szInitialUrl)) { // If we got here, either the startup file couldn't be found, or the user pressed the // shift key while launching. Prompt to select the index.html file. OPENFILENAME ofn = {0}; ofn.lStructSize = sizeof(ofn); ofn.lpstrFile = szInitialUrl; ofn.nMaxFile = MAX_PATH; ofn.lpstrFilter = L"Web Files\0*.htm;*.html\0\0"; ofn.lpstrTitle = L"Please select the " APP_NAME L" index.html file."; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER; if (!GetOpenFileName(&ofn)) { // User cancelled, exit the app CefShutdown(); return 0; } } // Perform application initialization if (!InitInstance (hInstance, nCmdShow)) return FALSE; // Temporary localization hack. Default to English. Check for French. DWORD menuId = IDC_CEFCLIENT; if (settings.locale.str && (settings.locale.length > 0) && (CefString(settings.locale.str) == CefString("fr-FR"))) { menuId = IDC_CEFCLIENT_FR; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(menuId)); int result = 0; if (!settings.multi_threaded_message_loop) { // Run the CEF message loop. This function will block until the application // recieves a WM_QUIT message. CefRunMessageLoop(); } else { MSG msg; // Run the application message loop. while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } result = static_cast<int>(msg.wParam); } OnBeforeShutdown(); // Shut down CEF. CefShutdown(); return result; }
BOOL TRecvDlg::EvCommand(WORD wNotifyCode, WORD wID, LPARAM hWndCtl) { switch (wID) { case IDOK: if (openFlg && ::IsDlgButtonChecked(hWnd, QUOTE_CHECK)) { CHARRANGE cr; editSub.SendMessageW(EM_EXGETSEL, 0, (LPARAM)&cr); // GT_SELECTION + GT_USECRLF の組み合わせには、バグがあるため、使えない → 自前で "\r" -> "\r\n" に変換 DynBuf buf(MAX_UDPBUF); editSub.ExGetText(buf.Buf(), buf.Size(), (cr.cpMin == cr.cpMax ? GT_DEFAULT : GT_SELECTION)); int i=0, j=0; for ( ; buf.Buf()[i] && j < MAX_UDPBUF; i++, j++) { if ((msg.msgBuf[j] = buf.Buf()[i]) == '\r') { msg.msgBuf[++j] = '\n'; } } msg.msgBuf[j] = 0; } else *msg.msgBuf = 0; ::PostMessage(GetMainWnd(), WM_SENDDLG_OPEN, (WPARAM)hWnd, (LPARAM)&msg); return TRUE; case IDCANCEL: if ((GetAsyncKeyState(VK_ESCAPE) & 0x8000) == 0) { if (fileObj && fileObj->conInfo) return EvCommand(0, FILE_BUTTON, 0), TRUE; if (timerID == 0) ::PostMessage(GetMainWnd(), WM_RECVDLG_EXIT, 0, (LPARAM)this); else TWin::Show(SW_HIDE); } return TRUE; case MISC_ACCEL: case HIDE_ACCEL: ::PostMessage(GetMainWnd(), WM_COMMAND, wID, 0); return TRUE; case ALLSELECT_ACCEL: editSub.SendMessage(EM_SETSEL, 0, (LPARAM)-1); return TRUE; case OPEN_BUTTON: if (openFlg) return TRUE; if (msg.command & IPMSG_PASSWORDOPT) { TPasswordDlg dlg(cfg, this); if (dlg.Exec() != TRUE) return TRUE; if (cfg->PasswdLogCheck) logmng->WriteRecvMsg(&msg, hosts, shareInfo); } openFlg = TRUE; editSub.ShowWindow(SW_SHOW); ::ShowWindow(GetDlgItem(QUOTE_CHECK), SW_SHOW); ::ShowWindow(GetDlgItem(OPEN_BUTTON), SW_HIDE); ::EnableWindow(GetDlgItem(OPEN_BUTTON), FALSE); if (shareInfo) SetFileButton(this, FILE_BUTTON, shareInfo), EvSize(SIZE_RESTORED, 0, 0); if (msg.command & IPMSG_SECRETOPT) { char buf[MAX_LISTBUF]; wsprintf(buf, "%ld", msg.packetNo); packetNo = msgMng->MakeMsg(readMsgBuf, IPMSG_READMSG|(msg.command & IPMSG_READCHECKOPT), buf); msgMng->UdpSend(msg.hostSub.addr, msg.hostSub.portNo, readMsgBuf); if (msg.command & IPMSG_READCHECKOPT) timerID = ::SetTimer(hWnd, IPMSG_RECV_TIMER, cfg->RetryMSec, NULL); } return TRUE; case FILE_BUTTON: if (fileObj && fileObj->conInfo) { if (fileObj->hThread) ::SuspendThread(fileObj->hThread); int ret = MessageBoxU8(GetLoadStrU8(IDS_TRANSSTOP), MSG_STR, MB_OKCANCEL); if (fileObj->hThread) ::ResumeThread(fileObj->hThread); if (ret == IDOK) if (fileObj->conInfo) EndRecvFile(TRUE); } else if (fileObj) { TSaveCommonDlg dlg(shareInfo, cfg, this); if (dlg.Exec()) { memset(fileObj, 0, sizeof(RecvFileObj)); strncpyz(fileObj->saveDir, cfg->lastSaveDir, MAX_PATH_U8); SaveFile(); } } break; case MENU_SAVEPOS: if ((cfg->RecvSavePos = !cfg->RecvSavePos) != 0) { GetWindowRect(&rect); cfg->RecvXpos = rect.left; cfg->RecvYpos = rect.top; } cfg->WriteRegistry(CFG_WINSIZE); return TRUE; case MENU_SAVESIZE: GetWindowRect(&rect); cfg->RecvXdiff = (rect.right - rect.left) - (orgRect.right - orgRect.left); cfg->RecvYdiff = (rect.bottom - rect.top) - (orgRect.bottom - orgRect.top); cfg->WriteRegistry(CFG_WINSIZE); return TRUE; case MENU_NORMALSIZE: GetWindowRect(&rect); MoveWindow(rect.left, rect.top, orgRect.right - orgRect.left, orgRect.bottom - orgRect.top, TRUE); return TRUE; case MENU_EDITFONT: case MENU_HEADFONT: CHOOSEFONT cf; LOGFONT tmpFont, *targetFont; targetFont = wID == MENU_EDITFONT ? &cfg->RecvEditFont : &cfg->RecvHeadFont; memset(&cf, 0, sizeof(cf)); cf.lStructSize = sizeof(cf); cf.hwndOwner = hWnd; cf.lpLogFont = &(tmpFont = *targetFont); cf.Flags = CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT | CF_SHOWHELP; cf.nFontType = SCREEN_FONTTYPE; if (::ChooseFont(&cf)) { *targetFont = tmpFont; SetFont(); ::InvalidateRgn(hWnd, NULL, TRUE); } cfg->WriteRegistry(CFG_FONT); return TRUE; case MENU_DEFAULTFONT: cfg->RecvHeadFont = orgFont; cfg->RecvEditFont = orgFont; SetFont(); ::InvalidateRgn(hWnd, NULL, TRUE); cfg->WriteRegistry(CFG_FONT); return TRUE; } return FALSE; }