Slow pixel per pixel rendering with SDL2's textures - c

I am trying to create a image pixel-per-pixel and display it on the screen with SDL. The image has to be refreshed and displayed again ~50 times per second (I am looking for a 50 FPS game). I tried to create a simple program to illustrate what I want to do: I create a 1280 * 720 window and texture which I alternately fill with green and red.
The problem is that the code runs very slowly (~8 FPS). Where did I mess up?
Here's my code
SDL_Texture *display;
SDL_Window *window;
SDL_Renderer *renderer;
int x;
int y;
int a = 255;
int b = 0;
window = SDL_CreateWindow(gl_title, SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, gl_width, gl_height, 0);
renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED |
SDL_RENDERER_TARGETTEXTURE |
SDL_RENDERER_PRESENTVSYNC);
display = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET, gl_width, gl_height);
while (true)
{
SDL_SetRenderTarget(renderer, display);
SDL_SetRenderDrawColor(renderer, a, b, 0, 255);
for (x = 0; x < gl_width; ++x)
{
for (y = 0; y < gl_height; ++y)
{
SDL_RenderDrawPoint(renderer, x, y);
}
}
a = a == 255 ? 0 : 255;
b = b == 255 ? 0 : 255;
SDL_SetRenderTarget(renderer, NULL);
SDL_RenderCopy(renderer, display, NULL, NULL);
SDL_RenderPresent(renderer);
}

Drawing on a screen using a function for every pixel is going to be slow. You can manually write the pixels in a loop and avoid the cost of calling the function every time or use one of the SDL provided functions that do that for you:
SDL_RenderFillRect
SDL_RenderDrawLines
SDL_RenderDrawPoints
SDL_RenderDrawRect

Related

Creating multiple rectangles using SDL_Rect

I'm creating a simulation for Conway's game of life using C and SDL. To represent the alive cells I would like to create multiple rectangles in the window which I have created. Is there any way to call SDL_Rect in a for loop without redefintion of SDL_Rect and output the result of the for loop all on the same renderer? Thank you.
My Code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <SDL.h>
#define main SDL_main
#undef main
double CreateRectanglesX()
{
double x; double x_max = 640; double x_min = 20;
x = rand() / (x_max - x_min) / (double)RAND_MAX + x_min;
return x;
}
double CreateRectanglesY()
{
double y; double y_max = 480; double y_min = 20;
y = rand() / (y_max - y_min) / (double)RAND_MAX + y_min;
return y;
}
int main(int argc, char* argv[])
{
SDL_Init(SDL_INIT_VIDEO); //initializes the SDL/SDL2 window
SDL_Window *screen; //SDL window created with pointer
screen = SDL_CreateWindow("My Program Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_OPENGL);
//definition for pointer - dimensions of SDL window
SDL_Renderer *renderer; //Renderer created with pointer
renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED); //definition for pointer - still to learn
if (screen == NULL) //checks if window exists or not
{
printf("Could not create window: %s\n", SDL_GetError()); //returns error if window doesn't exsit
return 1;
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); //changes color of renderer
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer); //displays the renderer with the changed color
for (int i = 0; i < 5; i++)
{
double x = CreateRectanglesX();
double y = CreateRectanglesY();
printf("%lf %lf", x, y);
SDL_Rect a;
a.x = x;
a.y = y;
a.w = 20;
a.h = 20;
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
SDL_RenderFillRect(renderer, &a);
SDL_RenderPresent(renderer);
}
SDL_Delay(5000); //wait time for window
SDL_DestroyWindow(screen);
SDL_QUIT;
return EXIT_SUCCESS;
}
The mistake was the fact that my random number generation formula with CreateRectanglesX() and CreateRectanglesY was wrong. It was
v = rand() / (x_max - x_min) / RAND_MAX + x_min;
Should have been:
v = rand() * (x_max - x_min) / RAND_MAX + x_min;
Only one rectangle was being displayed because the random numbers being produced with the random generation function were too close (due to wrong formula). Fixing the formula resolved the issue!

How to resize Window to loaded Image?

Is there a way that to resize the window in SDL to fit the loaded image size? currently when you resize it copies what was behind the window.
This is my Load Image Function:
void userImage(SDL_Surface *surface, SDL_Window *window)
{
SDL_Surface *userLoadImage;
char FileLocation[200];
printf( "Please Enter the file location:\n" );
fgets(FileLocation, 200, stdin );
fflush(stdin);
FileLocation[strcspn(FileLocation,"\n")]=0;
char *const picturePath = FileLocation;
userLoadImage = IMG_Load( picturePath );
int width = userLoadImage->w; //Get the width
int height = userLoadImage ->h; //Get the height
printf("image width = %d\n", width);
printf("image width = %d\n", height);
SDL_BlitSurface(userLoadImage, NULL, surface, NULL);
SDL_SetWindowSize( window, width, height);
}
This is the way I fixed it: All i changed was to reassign the window to the surface 'surface = SDL_GetWindowSurface(window);'
void userImage(SDL_Surface *surface, SDL_Window *window)
{
SDL_Surface *userLoadImage;
char FileLocation[200];
printf( "Please Enter the file location:\n" );
fgets(FileLocation, 200, stdin );
fflush(stdin);
FileLocation[strcspn(FileLocation,"\n")]=0;
char *const picturePath = FileLocation;
userLoadImage = IMG_Load( picturePath );
int width = userLoadImage->w; //Get the width
int height = userLoadImage ->h; //Get the height
SDL_SetWindowSize( window, width, height);
surface = SDL_GetWindowSurface(window);
SDL_BlitSurface(userLoadImage, NULL, surface, NULL);
}
Here is an SDL method for scaling a surface that may do what you are looking for:
SDL_Surface* SDL_ScaleSurface(SDL_Surface *Surface, Uint16 Width, Uint16 Height)
{
for(Sint32 y = 0; y < Surface->h; y++) //Run across all Y pixels.
for(Sint32 x = 0; x < Surface->w; x++) //Run across all X pixels.
for(Sint32 o_y = 0; o_y < _stretch_factor_y; ++o_y) //Draw _stretch_factor_y pixels for each Y pixel.
for(Sint32 o_x = 0; o_x < _stretch_factor_x; ++o_x) //Draw _stretch_factor_x pixels for each X pixel.
DrawPixel(_ret, static_cast<Sint32>(_stretch_factor_x * x) + o_x,
static_cast<Sint32>(_stretch_factor_y * y) + o_y, ReadPixel(Surface, x, y));
}
The example, and much more is on this page.

C - Minesweeper AI not clicking tile

The game is Minesweeper. The AI I am trying to implement will take an instance of the game Minesweeper that is already running on a machine (this case Windows 7), get the rectangular dimensions of the windows, compute the location of the window, push it to the foreground of the screen, click the top left square then go through the fancy algorithms to decide which square is a mine and which is clear.
Recently, I have been able to get the handling of the window and cursor correct only after implementing a MessageBox before the first tile is clicked.
With the message box, the program will push the Minesweeper window to the front, generate the message box, after the enter button on the message box is clicked the program will position the cursor on the correct top left square then stop... In the code after the message box, there is a commented out section which, when uncommented, iterates over the entirety of the Minesweeper window and marks it as a mine (flag!) - which tells me it does register the ClickTile correctly for mines - but not clear areas. After this the program is suppose to click the first tile in the top left corner. All that happens is the mouse flickering.
The correct behavior is to push the Minesweeper window to the front, generate the message box, after the message box is clicked, it should click the top left square within the game.
The question is, why is it not registering the LEFTMOUSEDOWN and only the RIGHTMOUSEDOWN in the ClickTile?
UiInfo.h
#ifndef UiInfo_
#define UiInfo_
#include <Windows.h>
struct UiInfo {
float scale;
POINT start;
int tile_size;
};
extern struct UiInfo * ui_info;
void UiInfo_initialize(struct UiInfo * ui_info,
float scale,
POINT start,
int tile_size);
#endif
UiInfo.c
#include "UiInfo.h"
void UiInfo_initialize(struct UiInfo * ui_info,
float scale,
POINT start,
int tile_size) {
ui_info->scale = scale;
ui_info->start = start;
ui_info->tile_size = tile_size;
}
main.c
void ClickTile(int is_mine, int x, int y) {
INPUT input = {0};
int xpos = (int)(ui_info->start.x + ui_info->tile_size * x);
int ypos = (int)(ui_info->start.y + ui_info->tile_size * y);
SetCursorPos(xpos, ypos);
input.type = INPUT_MOUSE;
if(is_mine) {
input.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
}
else {
input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
}
SendInput(1, &input, sizeof(INPUT));
ZeroMemory(&input, sizeof(INPUT));
input.type = INPUT_MOUSE;
if(is_mine) {
input.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
}
else {
input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
}
SendInput(1, &input, sizeof(INPUT));
}
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow) {
float scale;
POINT start;
RECT rect;
int size;
int x,y;
HWND hwnd_minesweeper = FindWindow(NULL, "Minesweeper");
GetWindowRect(hwnd_minesweeper, &rect);
scale = ((float)(rect.right - rect.left)) / ((float)(74 + 18 * 30));
// the point start is located at the center of the tile in the top left
// corner of the minesweeper map
start.x = ((long)scale) * (38 + 9) + rect.left;
start.y = rect.bottom - ((long)scale) * (38 + 15*18 + 9);
size = (int)scale * 18;
ui_info = (struct UiInfo *)malloc(sizeof(struct UiInfo));
UiInfo_initialize(ui_info, scale, start, size);
SetForegroundWindow(hwnd_minesweeper);
MessageBox(NULL, "A", "B", MB_OK);
/*for(y = 0; y < 16; y++) {
for(x = 0; x < 30; x++) {
Sleep(10);
ClickTile(1,x,y);
}
}*/
//Click the mine in the top left corner to start the game
ClickTile(0, 0, 0);
return 0;
}
I'll take three guesses.
Guess Number 1
You need to use a timer to allow your mouse movement and mouse clicks time to take effect. This involves starting a timer on app launch, and then implementing a state machine that generates new mouse events when the timer fires, e.g.
// start the timer in some initialization function
SetTimer( 75, 5, NULL );
// handler function to update the overall state
void CMainFrame::OnTimer(UINT nIDEvent)
{
switch ( m_State )
{
case STATE_IDLE: // do nothing until the user tells us to start
case STATE_DONE: // do nothing after the game is finished
break;
case STATE_START: // the first click to get things started
mouse_event( MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, m_Square[1][1].mousex, m_Square[1][1].mousey, 0, 0 );
mouse_event( MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 );
mouse_event( MOUSEEVENTF_LEFTUP , 0, 0, 0, 0 );
m_State = STATE_MOVING;
break;
case STATE_MOVING: // all the fun happens here
if ( !MakeAMove() )
{
m_State = STATE_DONE;
Invalidate();
}
break;
}
CFrameWnd::OnTimer(nIDEvent);
}
Guess Number 2
The mouse coordinate system is 65536 x 65536 regardless of screen resolution. So you need to scale the mouse coordinates to convert to pixel locations. Here's one way to compute the scale factors
HDC hdc = ::GetDC( NULL );
CDC *dc = CDC::FromHandle( hdc );
CWnd *wnd = dc->GetWindow();
wnd->GetClientRect( &rect );
xscale = 65535.0 / (double)rect.right;
yscale = 65535.0 / (double)rect.bottom;
Guess Number 3
You need to move the mouse to the correct screen coordinates before generating the mouse click event, e.g.
// the following code goes in some initialization function that knows the location of the minesweeper window
// note that screenx and screeny are the pixel coordinates of the center point of each square and these
// are converted to mouse coordinates for each square
for ( y = 1; y <= m_MaxY; y++ )
for ( x = 1; x <= m_MaxX; x++ )
{
m_Square[y][x].mousex = (int)(m_Square[y][x].screenx * xscale + 0.5);
m_Square[y][x].mousey = (int)(m_Square[y][x].screeny * yscale + 0.5);
}
// this code generates a left click in a given square
mouse_event( MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, m_Square[y][x].mousex, m_Square[y][x].mousey, 0, 0 );
mouse_event( MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 );
mouse_event( MOUSEEVENTF_LEFTUP , 0, 0, 0, 0 );

Changes made to image surface aren't reflected when painting

I have a small code snippet which loads an image from a PNG file, then modifies the image data in memory by making a specific color transparent (setting alpha to 0 for that color). Here's the code itself:
static gboolean expose (GtkWidget *widget, GdkEventExpose *event, gpointer userdata)
{
int width, height, stride, x, y;
cairo_t *cr = gdk_cairo_create(widget->window);
cairo_surface_t* image;
char* ptr;
if (supports_alpha)
cairo_set_source_rgba (cr, 1.0, 1.0, 1.0, 0.0); /* transparent */
else
cairo_set_source_rgb (cr, 1.0, 1.0, 1.0); /* opaque white */
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
cairo_paint (cr);
image = cairo_image_surface_create_from_png ("bg.png");
width = cairo_image_surface_get_width (image);
height = cairo_image_surface_get_height (image);
stride = cairo_image_surface_get_stride (image);
cairo_surface_flush (image);
ptr = (unsigned char*)malloc (stride * height);
memcpy (ptr, cairo_image_surface_get_data (image), stride * height);
cairo_surface_destroy (image);
image = cairo_image_surface_create_for_data (ptr, CAIRO_FORMAT_ARGB32, width, height, stride);
cairo_surface_flush (image);
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
char alpha = 0;
unsigned int z = *((unsigned int*)&ptr [y * stride + x * 4]);
if ((z & 0xffffff) == 0xffffff) {
z = (z & ~0xff000000) | (alpha & 0xff000000);
*((unsigned int*) &ptr [y * stride + x * 4]) = z;
}
}
}
cairo_surface_mark_dirty (image);
cairo_surface_write_to_png (image, "image.png");
gtk_widget_set_size_request (GTK_OBJECT (window), width, height);
gtk_window_set_resizable (GTK_OBJECT (window), FALSE);
cairo_set_source_surface (cr, image, 0, 0);
cairo_paint_with_alpha (cr, 0.9);
cairo_destroy (cr);
cairo_surface_destroy (image);
free (ptr);
return FALSE;
}
When I dump the modified data to PNG, transparency is actually there. But when the same data is used as a source surface for painting, there's no transparency. What might be wrong?
Attachments:
image.png - modified data dumped to file for debugging purposes,
demo.png - actual result
bg.png - source image, is omitted due to stackoverflow restrictions, it's simply black rounded rectangle on the white background. Expected result is black translucent rectangle and completely transparent fields, not white, like these on the demo.png.
Setting alpha to 0 means that the color is completely transparent. Since cairo uses pre-multiplied alpha, you have to set the pixel to 0, since otherwise the color components could have higher values than the alpha channels. I think cairo chokes on those super-luminscent pixels.
So instead of this code:
if ((z & 0xffffff) == 0xffffff) {
z = (z & ~0xff000000) | (alpha & 0xff000000);
*((unsigned int*) &ptr [y * stride + x * 4]) = z;
}
You should try the following:
if ((z & 0xffffff) == 0xffffff) {
*((unsigned int*) &ptr [y * stride + x * 4]) = 0;
}
And while we are at it:
Doesn't (z & 0xffffff) == 0xffffff check if the green, blue and alpha channels are all at 100% and ignores the red channel? Are you sure that's really what you want? z == 0xffffffff would be opaque white.
Instead of using unsigned int, it would be better if you used uint32_t for accessing the pixel data. Portability!
Your code assumes that cairo_image_surface_create_from_png() always gives you an image surface with format ARGB32. I don't think that's necessarily always correct and e.g. RGB24 is possible as well.
I think I would do something like this:
for (y = 0; y < height; y++) {
uint32_t row = (uint32_t *) &ptr[y * stride];
for (x = 0; x < width; x++) {
uint32_t px = row[x];
if (is_expected_color(px))
row[x] = 0;
}
}

Multilayer graphics using GDI

I'm using VisualStudio 2010, coding in C++/CLI, and doing all the graphics by GDI. I have a little app that plot continuously a Gaussian curve with some noise added. Every point is added real-time just like I pointed in this post.
Now, my task is to create a little colored area that I can shrink and increase to select a portion of the plot and do some math.
This kind of task is managed by a MouseMove event just like that:
System::Void Form1::pictureBox1_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
//Recalculate the position of the area,
//clean up the old one and redraw a new.
}
It works actually but I'm experiencing a bit graphic "bug".
As you can see, while I'm moving the area, everything under it is been deleted. The grid is here simply because it is static and I'm refreshing it everytime the green area is redrawn.
Actually it is not a bug, for sure it must go like that. To me, it is kinda obvious. I called it like that because it is not what I'm expecting.
I'm asking if there is a way to the green area as if it is upon a different layer. In this way, I would be able to move the green area while the plot is running without being erased.
I tried handling 2 HDC variables and plot the graph and the grid on the first one and the green area on the second one, but it seems not working.
Do you have some nice idea to get through this bad ( to me ) behaviour - maybe with some multilayer thing or some other fancy solutions - or should I give up and waiting for replotting?
Thanks everyone will give me an answer! :)
EDIT:
Here is how I draw my dataseries:
for(int i = 1; i<=1000; i++ ) {
Gauss[i] = safe_cast<float>(Math::Round( a*s*Math::Exp(-Math::Pow(((0.01*1*(i))-portante), 2)/b), 2));
Rumore[i] = safe_cast<float>(Math::Round(r*generatore->NextDouble(), 2));
SelectObject(hdcPictureBox, LinePen);
MoveToEx(hdcPictureBox, i-1+50, 500-convY*(Gauss[i-1]+Rumore[i-1])+50, NULL);
LineTo(hdcPictureBox, i+50, 500-convY*(Gauss[i]+Rumore[i])+50);
e1 = (i+k)%1000; //Buffer
if(i>DXX-54 && i<SXX-54) {
//ErasePen1 = CreatePen(PS_SOLID, 1, RGB(216,191,216));
label1->Text = Convert::ToString(i);
label1->Refresh();
SelectObject(hdcPictureBox, ErasePen1);
}
else {
SelectObject(hdcPictureBox, ErasePen);
}
//HPEN ErasePen1 = CreatePen(PS_SOLID, 1, RGB(216,191,216));
MoveToEx(hdcPictureBox, e1+50, 500-convY*(Gauss[e1]+Rumore[e1])+50, NULL);
LineTo(hdcPictureBox, e1+1+50, 500-convY*(Gauss[e1+1]+Rumore[e1+1])+50);
}
where DXX and SXX are the X-coordinates of areas - DXX starting, SXX ending.
This is how I'm handling the MouseMove. Do_Chan and Do_Clean are essentially the same thing. Do_Clean draws a bigger area with the background color to erase the old area and allowing Do_Chan to draw a new one.
System::Void Form1::pictureBox1_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
if(e->Button == System::Windows::Forms::MouseButtons::Left) {
double span100 = (SXX-DXX)*85/100;
if (e->X > DXX+((SXX-DXX)/2)-15 && e->X < DXX+((SXX-DXX)/2)+15 && (e->Y >30 && e->Y <50)
|| e->X >DXX+((SXX-DXX)/2)-span100/2 && e->X < DXX+((SXX-DXX)/2)+span100/2 && (e->Y >50 && e->Y <550)) {
HBRUSH brush = CreateSolidBrush(RGB(245,255,250));
Do_Clean(hdcPictureBox, DXX, SXX, brush);
double spawn = SXX-DXX;
DXX = e->X - spawn/2;
SXX = e->X + spawn/2;
if(DXX < 50) {
DXX = 51;
}
if(SXX >1050 ) {
SXX = 1049;
}
spawn = SXX - DXX;
CXX = DXX + spawn/2;
HBRUSH brush1 = CreateSolidBrush(RGB(166,251,178));
Do_Chan(hdcPictureBox2, DXX, SXX, brush1);
int k = 4;
int e1 = 0;
for(int i = 1; i<=1000; i++) {
SelectObject(hdcPictureBox, LinePen);
MoveToEx(hdcPictureBox, i-1+50, 500-250*(Gauss[i-1]+Rumore[i-1])+50, NULL);
LineTo(hdcPictureBox, i+50, 500-250*(Gauss[i]+Rumore[i])+50);
e1 = (i+k)%1000; //Buffer
if(i>DXX-54 && i<SXX-54) {
//ErasePen1 = CreatePen(PS_SOLID, 1, RGB(216,191,216));
SelectObject(hdcPictureBox, ErasePen1);
}
else {
SelectObject(hdcPictureBox, ErasePen);
}
//HPEN ErasePen1 = CreatePen(PS_SOLID, 1, RGB(216,191,216));
MoveToEx(hdcPictureBox, e1+50, 500-250*(Gauss[e1]+Rumore[e1])+50, NULL);
LineTo(hdcPictureBox, e1+1+50, 500-250*(Gauss[e1+1]+Rumore[e1+1])+50);
}
}
}
}
As you can see, after I drew the new area, I redraw all the point of the array Gauss+Rumore.
This is how Do_Chan ( Do_Clean is the same ) works:
void Do_Chan(HDC hdc, int dx, int sx, HBRUSH brush) {
//i = 250, y = 50
int y = 50;
int spawn = sx - dx;
HPEN pen = CreatePen(PS_SOLID, 1, RGB(245, 255, 250));
HPEN penC = CreatePen(PS_DOT, 1, RGB(0, 0, 0));
/*Fai il rettangolo */
SelectObject(hdc, pen);
SelectObject(hdc, brush);
POINT punti[4];
punti[0].x = dx;
punti[0].y = y;
punti[1].x = dx +spawn;
punti[1].y = y;
punti[2].x = dx + spawn;
punti[2].y = y+500;
punti[3].x = dx;
punti[3].y = y+500;
Polygon(hdc, punti, 4);
Ellipse(hdc, dx-10, y-20, dx+10, y);
SelectObject(hdc, penC);
MoveToEx(hdc, dx+spawn/2, 50,NULL);
LineTo(hdc, dx+spawn/2, 550);
SelectObject(hdc, pen);
SelectObject(hdc, brush);
Ellipse(hdc, dx-10+spawn/2, y-20, dx+10+spawn/2, y);
SelectObject(hdc, pen);
SelectObject(hdc, brush);
Ellipse(hdc, dx-10+spawn, y-20, dx+10+spawn, y);
//Plot the axis and the grid
}
I have thought of a possible way to do it and every solution had a drawback. For example
creating a thread. It has a drawback of drawing to picturebox dc from a different thread than the one handling the message queue. Not recomended
Another one:
using a timer and for every tick(lets say 16msec) draw. The DXX and SXX will be global variables. In picturebox move event you will only calculate these values(no drawing), also use some critical sections to protect them, and do all the drawing inside tick of timer. This works but you probable encounter some delay if your movement in picturebox is faster than 60fps.
The solution that i came finally was:
Inside your infinite loop:
get the mouse position and state(down or up). In this way you know if the user is dragging the green area and calculate DXX and SXX.
draw three rectangles with FillRect(): from 0 to DXX with picturebox back color, from DXX to SXX with green color and from SXX to the end with picturebox back color to an in memory dc eg hdcMemBackground
draw the grid lines to hdcMemBackground
Use the Point array and the polyline method i told you and in every loop move all your 999 points in the array one place to the left and add one point in the end of the array. To achieve this fill the array once before the infinite loop and inside it do the previous method
BitBlt hdcMemBackground to picturebox dc
Application::DoEvents();
EDIT (some code)
Create your resources once, when form loads, and release them in the end. Your Do_Chan()
creates considerable memory leaks. At form load:
HPEN hLinePenRed = NULL, hLinePenBlack = NULL, hLinePenWhite = NULL, hLinePenBlackDotted = NULL hPenOld; //Global
HBRUSH hBrushGreen = NULL, hBrushWhite = NULL, hBrushOld = NULL; //Global
HBITMAP hBitmap = NULL, hBitmapOld = NULL; //Global
HDC hdcMemBackground = NULL, hdcPicBox = NULL; //Global
//in form load event:
hLinePenRed = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
hLinePenBlack = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
hLinePenWhite = CreatePen(PS_SOLID, 1, RGB(245, 255, 250));
hLinePenBlackDotted = CreatePen(PS_DOT, 1, RGB(0, 0, 0));
hPenOld = SelectObject(hdcMemBackground, hLinePenRed);
hBrushGreen = CreateSolidBrush(RGB(166, 251, 178));
hBrushWhite = CreateSolidBrush(RGB(245, 255, 250));
hBrushOld = SelectObject(hdcMemBackground, hBrushGreen);
HDC hdc = CreateIC(TEXT("DISPLAY"), NULL, NULL, NULL);
hdcPicBox = GetWindowDC(hwndPicBox);
hdcMemBackground= CreateCompatibleDC(hdc);
hBitmap = CreateCompatibleBitmap(hdc, 1050, 550);
hBitmapOld = SelectObject(hdcMemBackground, hBitmap);
DeleteDC(hdc);
In the end when form closes:
SelectObject(hdcMemBackground, hPenOld);
DeleteObject(hLinePenRed);
DeleteObject(hLinePenBlack);
DeleteObject(hLinePenBlackDotted);
DeleteObject(hLinePenWhite);
SelectObject(hdcMemBackground, hBitmapOld);
DeleteObject(hBitmap);
SelectObject(hdcMemBackground, hBrushOld);
DeleteObject(hBrushGreen);
DeleteObject(hBrushWhite);
DeleteDC(hdcMemBackground);
ReleaseDC(hwndPicBox, hdcPicBox);
How to use FillRect and draw ellipses:
RECT rt;
rt.left = 0; rt.top = 0; rt.right = 1050; rt.bottom = 550;
FillRect(hdcMemBackground, &rt, hBrushWhite);
rt.left = DXX; rt.top = 50; rt.right = SXX; rt.bottom = 550;
FillRect(hdcMemBackground, &rt, hBrushGreen);
SelectObject(hdcMemBackground, hBrushGreen);
SelectObject(hdcMemBackground, hLinePenWhite);
Ellipse(hdcMemBackground, dx-10, y-20, dx+10, y);
Ellipse(hdcMemBackground, dx-10+spawn/2, y-20, dx+10+spawn/2, y);
Ellipse(hdcMemBackground, dx-10+spawn, y-20, dx+10+spawn, y);
//Plot the axis and the grid first and then draw the dotted vertical line
SelectObject(hdcMemBackground, hLinePenBlackDotted);
MoveToEx(hdcMemBackground, dx+spawn/2, 50, NULL);
LineTo(hdcMemBackground, dx+spawn/2, 550);
How to find mouse position and mouse state. This code will be at the beginning of each
iteration to see if user dragged the green area and calculate the new DXX, SXX:
/* It is buggy. My mistake
POINT pt;
GetCursorPos(&pt);
ScreenToClient(hwndPicBox, &pt);
if( pt.x >= 0 && pt.x <= picBoxWidth && pt.y >= 0 && pt.y <= picBoxHeight && (GetAsyncKeyState(VK_LBUTTON) & 0x8000) ){ //the mouse is down and inside picturebox
//do your staff
}
*/
Use instead picturebox mouse down, mouse up and mouse move events:
int isScrollingLeft = false; //global, the left circle
int isScrollingRight = false; //global, the right circle
int isScrollingMiddle = false; //global, the middle circle
System::Void Form1::pictureBox1_MouseDown(....){
//check if e.X and e.Y is inside in one of the three circles and set the
//appropriate isScrolling to true
}
System::Void Form1::pictureBox1_MouseMove(....){
if(isScrollingLeft){
//calculate DXX
}
else if(isScrollingRight){
//calculate SXX
}
else if(isScrollingMiddle){ //if you dont scroll this you dont need it
//
}
else{;} //do nothing
}
System::Void Form1::pictureBox1_MouseUp(....){
isScrollingLeft = false;
isScrollingRight = false;
isScrollingMiddle = false; //if you dont scroll this you dont need it
}
The way to move the points one place to the left:
POINT arrayPnt[1000]; //the array of points to be drawn by Polyline()
//the movement
memmove(&arrayPnt[0], &arrayPnt[1], 999 * sizeof(POINT));
//set the last one
arrayPnt[999].x = X;
arrayPnt[999].y = Y;
//Draw the lines
Polyline(hdcMemBackground, &arrayPnt, 1000);
To draw the number i into the label:
HDC hdcLabel1 = NULL; //global
HFONT hFont = NULL, hFontOld = NULL; //global
RECT rtLabel = NULL; //global
char strLabel1[5]; //global
Initialize once at the beggining like everything else
hdcLabel1 = GetWindowDC(label1Hwnd);
SetBkColor(hdcLabel1, RGB(?, ?, ?)); //i believe you use the color of your form
SetTextColor(hdcLabel1, RGB(255, 255, 255));
hFont = CreateFont(21, 0, 0, 0, /* Bold or normal*/FW_NORMAL, /*italic*/0, /*underline*/0, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, TEXT("Arial")); //21 is i believe the 16 size in word
hFontOld = SelectObject(hdcLabel1, hFont);
rtLabel.top = 0; rtLabel.left = 0;
rtLabel.right = label1.Width; rtLabel.bottom = label1.Height;
and in the for loop draw the string into the label1
sprintf(strLabel1, "%d", i); //it is toooo slow. I have to think something better
DrawTextEx(hdcLabel1, strLabel1, -1, &rtLabel, DT_VCENTER | DT_SINGLELINE | DT_LEFT, NULL);
In the end ofcource release resources
SelectObject(hdcLabel1, hFontOld);
DeleteObject(hFont);
hFont = NULL;
ReleaseDC(label1Hwnd, hdcLabel1);
If you have any problems do comment.
valter

Resources