Same GLUT application using single and double buffer? - c

Can I have a GLUT program with one of the windows with single buffer while the other uses double buffer?
The display mode can be set using the glutInitDisplayMode() but how to set it differently to different windows?
I tried using the glutSetWindow(), but either one of the two windows does not work.

glutInitDisplayMode sets the mode that will be used for the next window that is created. Therefore you can call it multiple times, once for each window:
glutInitDisplayMode(GLUT_DOUBLE);
int id0 = glutCreateWindow("double buffered");
glutInitDisplayMode(GLUT_SINGLE);
int id1 = glutCreateWindow("single buffered");
Alternatively, you can temporarily turn off double buffering by directly drawing onto the front buffer.
glDrawBuffer(GL_FRONT);
// ... single buffered drawing ...
glDrawBuffer(GL_BACK); // switch back to double buffered

Related

How to get the "output" (console screen buffer) Handle for GetConsoleMode() in Windows?

I want to do GetConsoleMode() on both input and output because I want to change some flags.
Input is pretty straightforward:
HANDLE hStdin;
DWORD fdwSaveOldMode;
hStdin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hStdin, &fdwSaveOldMode)
The output, on the other hand, doesn't seem as easy. One would think that just putting STD_OUTPUT_HANDLE would be enough, but the "help" pages talk about having to make and set your own buffer.
This, and a page about handles mention:
Specify the CONOUT$ value in a call to CreateFile to open a handle to a console's active screen buffer.
Sounds like a clue, but frankly, I'm unsure what this even means. Can someone show me how to do it properly? Why is output so different than input?
Thank you!
One would think that just putting STD_OUTPUT_HANDLE would be enough
It is. The "Clearing the Screen" example has a snippet demonstrating setting console output modes, and it uses GetStdHandle():
HANDLE hStdOut;
hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
// Fetch existing console mode so we correctly add a flag and not turn off others
DWORD mode = 0;
if (!GetConsoleMode(hStdOut, &mode))
{
return ::GetLastError();
}
// Hold original mode to restore on exit to be cooperative with other command-line apps.
const DWORD originalMode = mode;
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
// Try to set the mode.
if (!SetConsoleMode(hStdOut, mode))
{
return ::GetLastError();
}
Some cases where GetStdHandle wouldn't work together with console-specific functions would be if the application isn't console-mode (you can get a console in a GUI-mode application by calling AllocConsole) or if stdout was redirected.
In those cases, you'd need to open a console handle via CreateFile and the special filename "CONOUT$". That will always access a console, if one is associated with your process, even in case stdout is not mapped to that console.

How to print response to AT commands in Arduino serial port?

I want to print the response to AT command. I'm sending AT command but I'm not getting any response in the Arduino serial port. It's giving -1 instead of OK.
#include "SoftwareSerial.h"
String ssid = "connectify-krish";
String password = "12345678";
String myword= "";
SoftwareSerial esp(10, 11);
void setup() {
Serial.begin(9600);
esp.begin(9600);
esp.write("AT");
Serial.println(esp.read());
}
void loop() {}
As already pointed out in the comments you are not terminating the AT command line, so the modem will never respond to this.
Make sure you read V.250 and learn the difference between an AT command and an AT command line. ATI is an AT command, and "ATI I I\r" is a command line invoking this command three times in a row. Notice by the way in this example that you will get just one single Final result code for all three of them, i.e. the Final result code is a response to a complete command line and not to individual command invocations.
Then after fixing the sending of the command you must implement proper handling of the response. This includes reading and parsing what the modem sends back as a response to the sent command line. See this answer for the code structure and implementation hints.
As you've been told, terminate your AT commands with a carriage return character \r. Also you current code will read only a byte of the response, and thats if the response has even arrived since you included no delay at all. To communicate with the ESP interactively with the Serial monitor, I'd recommend using this:
#include <SoftwareSerial.h>
SoftwareSerial esp(10, 11);
void setup(){
Serial.begin(9600);
esp.begin(9600);
}
void loop()
{
while (Serial.available()) // forward data from monitor to esp
esp.write(Serial.read());
while (esp.available()) // forward data from esp to monitor
Serial.write(esp.read());
}
This basically makes your Arduino a conduit for communication between your PC and the ESP. You can send commands to the ESP with the Serial monitor and get their results immediately. Its great for testing commands. Just remember to set the serial monitor to BOTH NL & CR; this will serve you well for commands as well as any HTTP requests you send, as it appends \r\n to everything you send.
If you do want to write a sketch to talk to the ESP, you must provide some delay after sending a command to wait for the module to process the command and respond. The delay varies depending on the command, at least 500ms. The usual procedure is to define a timeout period for each command, depending on how long its expected to take, after which you 'give up' if there's no response yet. There are lots of libraries on GitHub that involve talking to some device using AT commands; study them to learn their techniques.

Real time display of .jpeg in byte array using C

I am working on a project where I have a server that sends an encrypted jpeg to a client which then decrypts it. Currently the image is stored in a byte array on the receiver end before it is written to the current directory.
void decryptionFunction(){
uint8 *plaintext; /* Pointer to buffer that contains decrypted jpeg
data*/
uint32 plaintext_len;
int k = 0;
while(1){
/*Decryption happens here... malloc() buffer and set *plaintext
equal to it*/
char buffer[32];
snprintf(buffer, sizeof(char) *32 "file%i.jpeg", k);
FILE *fp;
fp = fopen(buffer, "wb");
fwrite(plaintext, 1, plaintext_len, fp);
fclose(fp);
k++;
free(plaintext);
}
}
Each time the while loop completes a new image is placed in the buffer and then writes the image to the current directory. This all works fine, however I would like to display the image somehow instead of writing it to the current directory. Is there a way to do this in C? I have currently thought about streaming it from the receiver to VLC using some protocol, but that seems a little more complicated than what I am wanting.
Ideally, I would like to just display the image from the buffer and refresh the display each time through the while loop.
Thanks for any input.
There are many different libraries to display an image. One lite/simple is NxV. You can also use QT.
I found a solution that will work for right now. I decided to use the OpenCV library which has deprecated C functions to handle image display.
void decryptionFunction(){
uint8 *plaintext; /* Pointer to buffer that contains decrypted jpeg
data*/
uint32 plaintext_len;
int k = 0;
while(1){
/*Decryption happens here... malloc() buffer and set *plaintext
equal to it*/
CvMat matbox = cvMat(240, 320, CV_8UC1, plaintext);
IplImage *img;
img = cvDecodeImage(&matbox, 1);
cvNamedWindow("test", CV_WINDOW_AUTOSIZE);
cvShowImage("test", img);
cvWaitKey(100);
cvReleaseImage(&img);
free(plaintext);
}
}
While these functions are deprecated and can be cut at any time, for the time being they do exactly what I want. The buffer contains compressed jpeg data, and in order for it to be shown in the window, it has to be decoded into a raw format. I am still looking for a C implementation that can do exactly this that isn't deprecated.
You can maybe use the display program which is part of the ImageMagick suite which is installed on most Linux distros and is also available for OSX and Windows.
Basically, at the command line, you do:
display image.png
and it shows the image. It can display PNG, JPEG, TIFF and around 150 other formats. If your image changes, or you want to display a different one, you can do the following and it will look up the first instance of display and tell it to refresh with the new image:
display -remote image2.jpg
It can also take the image from its stdin as long as you tell it what type of file is coming, so it will work just as well like this:
cat image.jpg | display jpg:-
So you could effectively use popen() to start display and then send your image buffer to its stdin and then, when your image changes, run it again with the added -remote parameter to make it look up the first displayed image and refresh it rather than opening another display.
There are many options to resize the image before display, overlay it on a solid background or texture and so on if you run man display.

Drawing in a graphics window from a second thread in C

I am creating my first graphics program in C, using Codeblocks. I am trying to run two graphics loops simultaneously using two threads. One is for keyboard controls and the other is to move a rectangle vertically.
I have been trying to pass a graphics command from ObstacleHandler to the graphics window that main opens, using this condensed bit of code. When I run it, it will just crash as soon as it tries to draw the rectangle. If I initalise a window from the ObstacleHandler and then draw the rectangle, it will be fine. However, I need ObstacleHandler to draw the rectangle in the window that is initalised by the main.
Working example of the issue:
#include <pthread.h>
#include <semaphore.h>
#define NUM_THREADS 2
void *ObstacleHandler(void *threadid)
{
filled_rectangle(100, 120, 100, 120);
update_display();
pthread_exit(NULL);
return 0;
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
long t;
for(t=0;t<NUM_THREADS;t++)
{
printf("In main: creating thread %ld\n", t + 1);
}
pthread_create(&threads[1], NULL, ObstacleHandler, (void *)1);
initwindow(640, 480);
pthread_exit(NULL);
return 0;
}
The window has to be opened using the main function as the keyboard commands are in there. I cannot move them to the ObstacleHandler as that thread will be moving the obstacle.
Also, is there a way that you can have two graphics windows open and each one has a unique identification? I.e graph1 & graph2.
I am using allegro as the graphics library. However, not in the sample code.
I am new to programming so...! Any help would be appreciated!
Thanks
I use Borland/Embarcadero VCL so this could not be your case !!!
but my experience is that if you are accessing any Windows Visual stuff from different then owner window thread then somethings goes terribly wrong in the OS that creates:
visual artifacts
random unrelated crashes
unexpected behavior of the whole Application
this apply for any:
winapi call related to visual components of the window
drawing to window
any access to visual components (like adding line to memo,changing color of something,...)
I code win32 apps and this behavior is present on XP/SP3 x86,W7 x86,W7 x64(WoW64). I did not test different OS versions but suspect this behavior is present also there ...
What to do?
create your global message que
just a list of command you want to support
threads will fill your que
just add appropriate command to que like: redraw window, draw line ...,add to log ...
main window will read and execute it
inside OnTimer or OnIdle event
[Notes]
If you use threads to enhance rendering speed then you should render to thread local bitmap instead and when done add command to copy its contents to target visual component. Do not forget that the que has to be thread safe so add locks to it !!!

How can I have skinnier pthreads?

I have a really basic ncurses program to monitor machine statistics and launch remote xterms. It just sits on a window all day and helps me choose a not-heavily-loaded machine to work on. It works fine, and I love it dearly. But it's really fat. Much fatter than it needs to be, I think.
The program basically is as follows:
void * run(void * task) {
// once per minute:
popen( /* stats checking command */ )
// save output to global var
pclose
}
int main() {
// setup ncurses with halfdelay
for ( /* each machine */ )
pthread_create(somethread, NULL, run, (void *)somestruct);
while ( ( c = getch() ) != 'q' )
for ( /* each machine */ )
// print machine stats
// maybe launch an xterm
// die gracefully
}
And as stated above, it works just fine. The problem is that each thread has all the ncurses baloney tucked in private memory leading to one very fat process with a boatload of wasted bits.
The question, then, is this: how can I re-write or re-arrange this program so that each pthread doesn't carry around all the unnecessary ncurses stuff?
Side-question: You'll have to really sell me on it, but does anyone know of a better method than ncurses to do this? I want the stats on fixed positions in the terminal window, not scrolling text.

Resources