I am writing a program using c++ opencv and a console window. I want to be able to have a help menu where the user can input desired threshold values. The problem I have is the inputs only work if the image window is selected and not if the console window is selected. The inputs are not in main, there in void onNewDepthSample( as seen below. I want to get inputs when the console window is selected, they work fine when an image window is selected. A short sample of the code is below:
void changeItems()
{
int input = 0;
cout << "Welcome: Here is where to set up the proper image quality\n";
cout << "Press 'h' for the help menu and 'x' to leave the loop\n";
char keyInputs = 'a';
while(keyInputs != 'x')
{
cin >> keyInputs;
if( keyInputs == 'h' )
{
cout << "help menu\n";
}
}
cout << "Leaving the loop";
changeValues = 0;
}
void onNewDepthSample(DepthNode node, DepthNode::NewSampleReceivedData data)
{
//printf("Z#%u: %d\n",g_dFrames,data.vertices.size());
int p[3];
int circleTemp[6000] ={0};
int circleTempVal = 0;
int resultsTotalAfterRemove = 0;
int resultsTotalAfterRemoveVideo = 0;
float robotx = 0;
float roboty = 0;
char * cCoordinates = new char[100];
char * cDepth = new char[100];
p[0] = CV_IMWRITE_JPEG_QUALITY;
p[1] = 100;
p[2] = 0;
int32_t w, h;
FrameFormat_toResolution(data.captureConfiguration.frameFormat,&w,&h);
if(changeValues != 0)
{
changeItems();
}
Related
I am making a simple windows console application, to try and make an old school game I guess.
I have a function to get key presses , like that :
char GetKeyPressed()
{
BYTE keys[256] = {0};
for (size_t i = 0; i < 256; i++)
{
keys[i] = GetAsyncKeyState(i);
// solution :
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
}
for (size_t i = 0; i < 256; i++)
{
if (keys[i] != 0)
{
// printf("key value : 0x%02x\n", (int)i);
return i;
}
}
return 0;
}
I works fine.
The issue is :
if I start the game in an existing terminal, every key pressed during the game, was also an input in in the original terminal 'current line', even if it's not visible to me ( because the game redraws the content of the console).
When exiting the game, I can see the original content of the terminal prompt + all my inputs during the game run.
Is there a way to 'take ownership' of the inputs ? or prevent them in anyway to end up inside the command line ?
.... some time later ...
I boiled it down to this example :
#include <windows.h>
#include <iostream>
static bool QUIT = false;
void GetKeyPressed()
{
char keys[256] = {0};
for (int i = 0; i < 256; i++)
{
keys[i] = GetAsyncKeyState(i); // & 0x01;
// solution :
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
if (keys[i])
{
if (i == 0x51) // 'q'
{
std::cout << "QUITTING !!!!" << std::endl;
QUIT = true;
return;
}
}
}
}
int main()
{
std::cout << "Program Started" << std::endl;
while (!QUIT)
{
GetKeyPressed();
}
return 0;
}
The problem still persist. Pressing 'q' to quit the program leaves the letter q in the command line ... I don't get it.
compiled with : g++ -o example example.cpp
After searching for a while , I found this function :
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
I execute it after each GetAsyncKeyState(n);
I'm coding a C++ program that makes a certain movement with the mouse by itself when I press the left mouse button, it has F1, F2, F3 keys and each key has a different movement, and then I press the left mouse button to execute that movement , but what is happening is that I have to hold down the F1 key and the left mouse button at the same time for it to work, I wanted to press the F1 key just once and then just hold down the left mouse button !
#include <iostream>
#include <string>
#include <Windows.h>
#include "patterns.h"
#define getLen(x) (sizeof(x)/sizeof(x[0]))
using namespace std;
typedef struct $ {
string name;
long **pattner;
int len;
int rpm;
}weapon_t;
weapon_t *LoadWeapon(string name, long recoil[][2], int len, int rpm);
float GetK(float dpi, float sensi);
DWORD GetTime(float rpm);
void ExecControl(weapon_t gun);
float K;
int main()
{
K = GetK(800, 0.95);
weapon_t *ak47 = LoadWeapon("AK-47", ak47_pattern, getLen(ak47_pattern), 600);
weapon_t *m4a4 = LoadWeapon("M4A4", m4a4_pattern, getLen(m4a4_pattern), 666);
weapon_t *ump45 = LoadWeapon("UMP-45", ump45_pattern, getLen(ump45_pattern), 666);
weapon_t* m4a1s = LoadWeapon("M4A1S", m4a1s_pattern, getLen(m4a1s_pattern), 600);
weapon_t* famas = LoadWeapon("FAMAS", famas_pattern, getLen(famas_pattern), 600);
while (true) {
if (GetAsyncKeyState(VK_F1)) {
ExecControl(*ak47);
}
if (GetAsyncKeyState(VK_F2)) {
ExecControl(*m4a4);
}
if (GetAsyncKeyState(VK_F3)) {
ExecControl(*m4a1s);
}
if (GetAsyncKeyState(VK_F4)) {
ExecControl(*ump45);
}
if (GetAsyncKeyState(VK_F5)) {
ExecControl(*famas);
}
Sleep(150);
}
return 0;
}
void ExecControl(weapon_t gun) {
system("cls");
cout << "Weapon:\t" << gun.name << "\nShots:\t" << gun.len << "\nVelocity:\t" << gun.rpm << "\n\n\n";
DWORD delay = GetTime(gun.rpm);
int index = 0;
while (GetAsyncKeyState(VK_LBUTTON) && index != gun.len) {
mouse_event(MOUSEEVENTF_MOVE, long(gun.pattner[index][0] * K), long(gun.pattner[index][1] * K), 0, 0);
index++;
Sleep(delay);
}
index = 0;
}
weapon_t *LoadWeapon(string name, long recoil[][2], int len, int rpm) {
int i;
weapon_t *gun = new weapon_t();
gun->name = name;
gun->len = len;
gun->rpm = rpm;
gun->pattner = new long*[len];
for (i = 0; i < len; i++) {
gun->pattner[i] = new long[2];
}
for (i = 0; i < len; i++) {
gun->pattner[i][0] = recoil[i][0];
gun->pattner[i][1] = recoil[i][1];
}
return gun;
}
float GetK(float dpi, float sensi) {
return (1140 / (dpi*sensi));
}
DWORD GetTime(float rpm) {
return DWORD((60 / rpm) * 1000);
}
The problem is that your code is looking at the mouse left button only while any F1..F5 key is currently held down, and then you are not looking at the keyboard again until the left button is released or the current gun is exhausted.
You need a different approach, such as a state machine. Keep track of the current gun that is equipped at any given time. On each iteration of the main loop, check for state changes first (ie, check if any F1..F5 key is held down, and if so then equip the associated gun), and then act on the current state (ie, regardless of the keyboard state, if the left button is down, and a gun is equipped, then advance the gun to its next position). Let the loop handle the repetitive work for you. This will allow you to check the keyboard for gun changes while the left button is held down.
Try something more like this:
#include <iostream>
#include <string>
#include <Windows.h>
#include "patterns.h"
#define getLen(x) (sizeof(x)/sizeof(x[0]))
using namespace std;
typedef struct $ {
string name;
long **pattner;
int len;
int rpm;
}weapon_t;
weapon_t* LoadWeapon(string name, long recoil[][2], int len, int rpm);
float GetK(float dpi, float sensi);
DWORD GetTime(float rpm);
float K = GetK(800, 0.95);
int main()
{
weapon_t *ak47 = LoadWeapon("AK-47", ak47_pattern, getLen(ak47_pattern), 600);
weapon_t *m4a4 = LoadWeapon("M4A4", m4a4_pattern, getLen(m4a4_pattern), 666);
weapon_t *ump45 = LoadWeapon("UMP-45", ump45_pattern, getLen(ump45_pattern), 666);
weapon_t *m4a1s = LoadWeapon("M4A1S", m4a1s_pattern, getLen(m4a1s_pattern), 600);
weapon_t *famas = LoadWeapon("FAMAS", famas_pattern, getLen(famas_pattern), 600);
weapon_t* guns[] = {ak47, m4a4, m4a1s, ump45, famas};
int gun_keys[] = {VK_F1, VK_F2, VK_F3, VK_F4, VK_F5};
weapon_t *gun = nullptr;
int gun_index = -1;
DWORD gun_delay = 150;
bool is_mouse_down = false;
while (true) {
for(int i = 0; i < 5; ++i) {
if (GetAsyncKeyState(gun_key[i]) && (gun != guns[i])) {
gun = guns[i];
system("cls");
cout << "Weapon:\t" << gun->name << "\nShots:\t" << gun->len << "\nVelocity:\t" << gun->rpm << "\n\n\n";
gun_delay = GetTime(gun->rpm);
gun_index = 0;
break;
}
}
if (GetAsyncKeyState(VK_LBUTTON) < 0) {
if (!is_mouse_down) {
is_mouse_down = true;
if (gun != nullptr)
gun_index = 0;
}
if (gun != nullptr && gun_index != gun->len) {
mouse_event(MOUSEEVENTF_MOVE, long(gun->pattner[gun_index][0] * K), long(gun->pattner[gun_index][1] * K), 0, 0);
++gun_index;
Sleep(gun_delay);
continue;
}
}
else
is_mouse_down = false;
Sleep(150);
}
return 0;
}
weapon_t* LoadWeapon(string name, long recoil[][2], int len, int rpm) {
weapon_t *gun = new weapon_t();
gun->name = name;
gun->len = len;
gun->rpm = rpm;
gun->pattner = new long*[len];
for (int i = 0; i < len; i++) {
gun->pattner[i] = new long[2];
gun->pattner[i][0] = recoil[i][0];
gun->pattner[i][1] = recoil[i][1];
}
return gun;
}
float GetK(float dpi, float sensi) {
return (1140 / (dpi*sensi));
}
DWORD GetTime(float rpm) {
return DWORD((60 / rpm) * 1000);
}
Im working in code which can create coronal, saggital, and axial image from dicom file, but In the same time I dont need to display renderWindow to user, and this is my code:
int main(int argc, char* argv[])
{
// Verify input arguments
if ( argc != 2 )
{
std::cout << "Usage: " << argv[0]
<< " FolderName" << std::endl;
return EXIT_FAILURE;
}
std::string folder = argv[1];
//std::string folder = "C:\\VTK\\vtkdata-5.8.0\\Data\\DicomTestImages";
// Read all the DICOM files in the specified directory.
vtkSmartPointer<vtkDICOMImageReader> reader =
vtkSmartPointer<vtkDICOMImageReader>::New();
reader->SetDirectoryName(folder.c_str());
reader->Update();
// Visualize
vtkSmartPointer<vtkImageViewer2> imageViewer =
vtkSmartPointer<vtkImageViewer2>::New();
imageViewer->SetInputConnection(reader->GetOutputPort());
imageViewer->SetSlice(0);
imageViewer->Render();
for(int k = 0; k < 3; k++){
cout<< k << endl;
if(k == 0){
imageViewer->SetSliceOrientationToYZ();
}else if(k == 1){
imageViewer->SetSliceOrientationToXZ();
}else{
imageViewer->SetSliceOrientationToXY();
}
int _MinSlice = imageViewer->GetSliceMin();
int _MaxSlice = imageViewer->GetSliceMax();
// Screenshot
vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter =
vtkSmartPointer<vtkWindowToImageFilter>::New();
vtkSmartPointer<vtkPNGWriter> writer =
vtkSmartPointer<vtkPNGWriter>::New();
for (int i = _MinSlice; i < _MaxSlice; i++){
vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter =
vtkSmartPointer<vtkWindowToImageFilter>::New();
vtkSmartPointer<vtkPNGWriter> writer =
vtkSmartPointer<vtkPNGWriter>::New();
windowToImageFilter->SetInput(imageViewer->GetRenderWindow());
windowToImageFilter->ReadFrontBufferOff(); // read from the back buffer
windowToImageFilter->Update();
std::string filename = "img/" + std::to_string(k) + "/" + std::to_string(i) + ".png";
char *y = new char[filename.length() + 1];
std::strcpy(y, filename.c_str());
writer->SetFileName(y);
writer->SetInputConnection(windowToImageFilter->GetOutputPort());
writer->Write();
imageViewer->SetSlice(i);
imageViewer->Render();
}
}
return EXIT_SUCCESS;
}
my issue is when try imageViewer->SetRenderWindow(NULL); Or imageViewer->GetRenderWindow()->Delete(); its will remove renderWindow instance, and code will be break, so that how I can keep renderWindow work in background without display it to user?
Thanks
You can use SetShowWindow(bool) or ShowWindowOff(), these methods are inherited from vtkWindow. Doing so should not stop the rendering pipeline (you can probably still use windowToImageFilter) but tbh I did not test it. Let us know if it worked.
I use a C++\CLR project in Visual Studio 2017.At the time i try to manipulate the memory so i create a hack for a no name game and try to manipulate the game.
My problem is that I try to create a random integer and for that i use the function rand() in combination with firstSetRand srand().
using namespace System;
int * randomName()
{
srand((unsigned)time(0));
int i = 1;
static int name[5];
for (int i = 1; i < 5; i++)
{
name[i] = 97 + rand() % 122;
}
std::cout << name << std::endl;
return name;
}
This is my function for the random counts and here i call it:
int main(array<System::String ^> ^args)
{
while (true)
{
switch (inputCheat) //check which case match with the user input
{
case 4:
Console::WriteLine("test: ");
random:: randomName(firstSetRand);
//WriteProcessMemory(handle, (LPVOID)localName, &inputNumber, sizeof(), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
}
}
Sleep(200);
}
The problem is because that´s a while(true) loop and I call the function multiple times. And I don't know how to make that srand() function is only called once time i get always the same random number.
I am coming from Java. In Java i would do the whole code in a class and than i would write the variable in the constructor but i think that's not possible in C++. Because when i do the whole code in a class i get the error:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main##YAHXZ) AssaultCubeHack C:\Users\schup\source\repos\AssaultCubeHack\AssaultCubeHack\MSVCRTD.lib(exe_main.obj) 1
Here is the full code of my project:
// AssaultCubeWithClr.cpp: Hauptprojektdatei.
#include "stdafx.h"
using namespace System;
struct InitRandHelper
{
InitRandHelper() { srand((unsigned)time(0)); }
};
int * randomName()
{
static InitRandHelper init;
int i = 1;
static int name[5];
for (int i = 1; i < 5; i++)
{
name[i] = 97 + rand() % 122;
}
std::cout << name << std::endl;
return name;
}
void StartText()
{
//Text to See in the Console
Console::ForegroundColor = System::ConsoleColor::Green;
Console::WriteLine("Welcome to my Cheat for AssaultCube!");
Console::WriteLine("------------------------------------");
Console::WriteLine("1. For More Health type in: 1.");
Console::WriteLine("2. For More Ammo type in: 2");
Console::WriteLine("3. For More Armor type in: 3");
Console::WriteLine("4. For Turn on Name changer: 4");
}
int main(array<System::String ^> ^args)
{
DWORD playerBaseAdress = 0x00509b74;
DWORD offsePrimaryAmmo = 0x128;
DWORD offsetPistolAmmo = 0x13C;
DWORD offsetArmor = 0xFC;
DWORD offsetHealth = 0xF8;
DWORD offsetRoll = 0x0080;
DWORD baseforName = 0x005028FC;
static bool firstSetRand = true;
int inputCheat;
int inputNumber;
DWORD processId;
DWORD localPlayer;
DWORD localName;
DWORD primaryAmmo;
DWORD pistolAmmo;
DWORD health;
DWORD armor;
DWORD roll;
bool firstExecute = true;
HWND hwnd = FindWindowA(NULL, "AssaultCube"); //Find Window with Name AssaultCube
StartText(); //function call
while (true)
{
if (hwnd == NULL) //Check if the game exists
{
if (firstExecute == true)
{
Console::ForegroundColor = System::ConsoleColor::Red;
Console::WriteLine("ERROR: The Game couldn´t found!");
firstExecute = false;
}
}
else
{
GetWindowThreadProcessId(hwnd, &processId); //Get Process id from the Window
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, false, processId);
if (handle == NULL) //check if process id exsits
{
Console::ForegroundColor = System::ConsoleColor::Red;
Console::WriteLine("ERROR: Wrong Process Id!");
Console::ForegroundColor = System::ConsoleColor::Green;
}
else
{
ReadProcessMemory(handle, (LPCVOID)playerBaseAdress, &localPlayer, sizeof(playerBaseAdress), NULL); //Read the local adresse and save it in localPlayer
ReadProcessMemory(handle, (LPCVOID)baseforName, &localName, sizeof(playerBaseAdress), NULL);
primaryAmmo = localPlayer + offsePrimaryAmmo;
pistolAmmo = localPlayer + offsetPistolAmmo;
health = localPlayer + offsetHealth;
armor = localPlayer + offsetArmor;
roll = localPlayer + offsetRoll;
std::cin >> inputCheat; //wait for user input
switch (inputCheat) //check which case match with the user input
{
case 1:
Console::WriteLine("Write how much Health you want: ");
std::cin >> inputNumber;
WriteProcessMemory(handle, (LPVOID)health, &inputNumber, sizeof(inputNumber), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
case 2:
Console::WriteLine("Write how much Ammo you want: ");
std::cin >> inputNumber;
WriteProcessMemory(handle, (LPVOID)primaryAmmo, &inputNumber, sizeof(inputNumber), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
case 3:
Console::WriteLine("Write how much Armor you want: ");
std::cin >> inputNumber;
WriteProcessMemory(handle, (LPVOID)armor, &inputNumber, sizeof(inputNumber), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
case 4:
Console::WriteLine("Random Number: ");
randomName();
//WriteProcessMemory(handle, (LPVOID)localName, &inputNumber, sizeof(), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
case 5:
Console::WriteLine("test: ");
std::cin >> inputNumber;
WriteProcessMemory(handle, (LPVOID)roll, &inputNumber, sizeof(inputNumber), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
default:
Console::ForegroundColor = System::ConsoleColor::Red;
Console::WriteLine("ERROR: Wrong Entry!");
Console::WriteLine("Try a other input :D");
Console::ForegroundColor = System::ConsoleColor::Green;
break;
}
}
}
Sleep(200);
}
return 0;
}
Here you can see it doesn't work.
Solution 1
You can use a function static variable for that.
static bool firstTime = true;
if ( firstTime )
{
srand((unsigned)time(0));
firstTime = false;
}
Solution 2
If you don't want to pay the price of the check for each call of the function, you can use a helper class/struct.
struct InitRandHelper
{
InitRandHelper() { srand((unsigned)time(0)); }
};
int* randomName()
{
// Initialize the random number generator.
static InitRandHelper init;
int i = 1;
static int name[5];
for (int i = 1; i < 5; i++)
{
name[i] = 97 + rand() % 122;
}
std::cout << name << std::endl;
return name;
}
Solution 3
Call srand in main before the while loop begins.
int main(array<System::String ^> ^args)
{
srand((unsigned)time(0));
while (true)
{
switch (inputCheat) //check which case match with the user input
{
case 4:
Console::WriteLine("test: ");
random:: randomName(firstSetRand);
//WriteProcessMemory(handle, (LPVOID)localName, &inputNumber, sizeof(), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
}
}
Sleep(200);
}
and remove the call from random::randomName.
okay here the answer i found. Ther problem is this line:
std::cout << name << std::endl;
The Ouput in the console is not the value rather its the adress from the array. To do it proper i have to it so:
int i = 1;
static int name[5];
for (int i = 1; i < 5; i++)
{
name[i] = 97 + rand() % 122;
std::cout << name[i] << std::endl; //this line is the right thing to do it
}
return name;
I am starting with SDL, and I was reading the introduction, and I am trying the drawPixel method they have. What I am doing is a ppm viewer, so far I have the rgb values in an array and are correctly stored (i checked them by printing the array and making sure they correspond to their position in the ppm file) and I want to use SDL to draw the picture. So far the code I've written is (this is the main.cpp file, if ppm.hpp and ppm.cpp are needed please tell me so to add them)
#include <iostream>
#include <SDL/SDL.h>
#include "ppm.hpp"
using namespace std;
void drawPixel (SDL_Surface*, Uint8, Uint8, Uint8, int, int);
int main (int argc, char** argv) {
PPM ppm ("res/cake.ppm");
if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) < 0) {
cerr << "Unable to init SDL: " << SDL_GetError() << endl;
exit(1);
}
atexit(SDL_Quit); // to automatically call SDL_Quit() when the program terminates
SDL_Surface* screen;
screen = SDL_SetVideoMode(ppm.width(), ppm.height(), 32, SDL_SWSURFACE);
if (screen == nullptr) {
cerr << "Unable to set " << ppm.width() << "x" << ppm.height() << " video: " << SDL_GetError() << endl;
exit(1);
}
for (int i = 0; i < ppm.width(); i++) {
for(int j = 0; j < ppm.height(); j++) {
drawPixel(screen, ppm.red(i,j), ppm.green(i,j), ppm.blue(i,j), i, j);
}
}
return 0;
}
void drawPixel (SDL_Surface* screen, Uint8 R, Uint8 G, Uint8 B, int x, int y) {
Uint32 color = SDL_MapRGB(screen->format, R, G, B);
if (SDL_MUSTLOCK(screen)) {
if (SDL_LockSurface(screen) < 0) {
return;
}
}
switch (screen->format->BytesPerPixel) {
case 1: { // Assuming 8-bpp
Uint8* bufp;
bufp = (Uint8*)screen->pixels + y * screen->pitch + x;
*bufp = color;
}
break;
case 2: { // Probably 15-bpp or 16-bpp
Uint16 *bufp;
bufp = (Uint16*)screen->pixels + y * screen->pitch / 2 + x;
*bufp = color;
}
break;
case 3: { // Slow 24-bpp mode, usually not used
Uint8* bufp;
bufp = (Uint8*)screen->pixels + y * screen->pitch + x;
*(bufp + screen->format->Rshift / 8) = R;
*(bufp + screen->format->Gshift / 8) = G;
*(bufp + screen->format->Bshift / 8) = B;
}
break;
case 4: { // Probably 32-bpp
Uint32* bufp;
bufp = (Uint32*)screen->pixels + y * screen->pitch / 4 + x;
*bufp = color;
}
break;
}
if (SDL_MUSTLOCK(screen)) {
SDL_UnlockSurface(screen);
}
SDL_UpdateRect(screen, x, y, 1, 1);
}
The drawPixel is as is provided by the introduction, now the ppm file I am trying to use is called cake.ppm and its 720x540, however when I build and run this code, I get the application is not responding. I tried it on a smaller ppm file which is 426x299 and it showed a window with colors being put on the window.
Why is it not working on the cake.ppm file and on others it works? Is it due to size?
When I try the ppm file, the second one 426x299 or other ppm files, the colors come totally different, why is that?
When I run the app, after the pixels are put, the window closes, how can I keep it?
Attempting at a file squares.ppm, here is what it should be:
But this is what I'm getting