AndreAhmed - 10 months ago 46

C Question

I have a 16bit RGB565 and I have the result from dot product and its 0->1.

I would like to map the dot product value from light source to the normal vector in a mesh to 16bit color value. so I have a dot produc from 0>1 and I would like to modulate the color which is 16bit RGB565

`uint16_t floatToRGB565(float input)`

{

uint8_t x = input*255;

uint8_t r = (x&248u);//0xff-0x07, 5msb mask

uint8_t g = (x&252u);//0xff-0x03, 6msb mask

uint8_t b = (x&248u);//0xff-0x07, 6msb mask

return (r<<8)|(g<<3)|(b>>3);// assuming r is at msb

}

dp = Dot_Product_3D((vector_3d_ptr)&normal,

(vector_3d_ptr)&light_source);

// test if light ray is reflecting off surface

if (dp > 0)

{

float intens ;

uint16_t colorMod;

int r,g,b;

float Red, Green, Blue, result;

intensity = ambient_light + dp;

if (intensity > 1)

intensity = 1;

if (intensity < 0)

intensity = 0;

r = the_object->polys[curr_poly].color >> 11;

g = (the_object->polys[curr_poly].color >>5)&0x00FF;

b = the_object->polys[curr_poly].color & 0x0000FF;

Red = r*intensity;

Green = g*intensity;

Blue = b*intensity;

result = (int)(Red * 31) << 11 | (int)(Green * 63) << 5 | (int)(Blue * 31);

colorMod = floatToRGB565(result);

the_object->polys[curr_poly].shade = colorMod;

// printf("\nintensity of polygon %d is %f",curr_poly,intensity);

} // end if light is reflecting off surface

else{

int r,g,b;

float Red, Green, Blue, result;

float colorModulate;

uint16_t colorMod;

r = the_object->polys[curr_poly].color >> 11;

g = (the_object->polys[curr_poly].color >>5)&0x00FF;

b = the_object->polys[curr_poly].color & 0x0000FF;

Red = r*ambient_light;

Green = g*ambient_light;

Blue = b*ambient_light;

colorModulate = (int)(Red * 31) << 11 | (int)(Green * 63) << 5 | (int)(Blue * 31);

colorMod = floatToRGB565(colorModulate);

the_object->polys[curr_poly].shade = colorMod;

}

} // end if use flat shading

Answer Source

**dot product returns range**`<-1,+1>`

but your condition

`dp>0`

handles it so that should not be the problem.`float`

to RGB565 conversionYou are missing some checks I would do it like this:

`uint16_t floatToRGB565(float input) { uint8_t x = float(input*63.0); // just to be sure it would not be rounded to int before multiplication if (x>63) x=63; if (x<0) x=0; // avoid overflow/underflow you never know with floats ... uint8_t r = x>>1; uint8_t g = x; uint8_t b = x>>1; return (r<<11)|(g<<5)|(b); // assuming r is at msb }`