DirectX set color of single pixel
Asked Answered
H

1

6

I read in another thread, that I can read a single pixel with Texture.Lock / Unlock, but I need to write the pixels back to the texture after reading them, this is my code so far

unsigned int readPixel(LPDIRECT3DTEXTURE9 pTexture, UINT x, UINT y)
{
    D3DLOCKED_RECT rect;
    ZeroMemory(&rect, sizeof(D3DLOCKED_RECT));
    pTexture->LockRect(0, &rect, NULL, D3DLOCK_READONLY);
    unsigned char *bits = (unsigned char *)rect.pBits;
    unsigned int pixel = (unsigned int)&bits[rect.Pitch * y + 4 * x];
    pTexture->UnlockRect(0);
    return pixel;
}

So my questions are:

- How to write the pixels back to the texture?  
- How to get the ARGB values from this unsigned int? 

((BYTE)x >> 8/16/24) didnt work for me (the returned value from the function was 688)

Huckaby answered 19/3, 2011 at 18:39 Comment(2)
out of curiosity, why do you need to do this?Arcuate
you should know that the performance of this kind of locking is just cockroach level. (in 2002 by my tests it was performing at 0.5 FPS, today may be faster but you're still crippling yourself doing this kind of things.)Maurene
E
5

1) One way is to use a memcpy:

memcpy( &bits[rect.Pitch * y + 4 * x]), &pixel, 4 );

2) There are a number of different ways. The simplest is to define a struct as follows:

struct ARGB
{
    char b;
    char g;
    char r;
    char a;
};

Then change your pixel loading code to the following:

ARGB pixel;
memcpy( &pixel, &bits[rect.Pitch * y + 4 * x]), 4 );

char red = pixel.r;

You can also obtain all the values using masks and shifts. e.g

unsigned char a = (intPixel >> 24);
unsigned char r = (intPixel >> 16) & 0xff;
unsigned char g = (intPixel >>  8) & 0xff;
unsigned char b = (intPixel)       & 0xff;
Empery answered 20/3, 2011 at 23:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.