I'm writing a C++ algorithm that returns an X,Y position on a 2D texture. Using the X,Y value I wish to find the u,v texture coordinates of a 3D object (already mapped in software).
I have these calculations:
u = X/texture_width
v = texture_height - Y/texture_height
However the values calculated can not be found under vt in my obj file.
Help would be appreciated, many thanks.
Assuming that your (u,v) coordinates are supposed to be within the range [0,1] x [0,1], your computation is not quite right. It should be
u = X/texture_width
v = 1 - Y/texture_height
Given an image pixel coordinate (X,Y), this will compute the corresponding texture (u,v) coordinate. However, if you pick a random image pixel and convert its (X,Y) coordinate into a (u,v) coordinate, this coordinate will most likely not show up in the list of vt
entries in the OBJ file.
The reason is that (u,v) coordinates in the OBJ file are only specified at the corners of the faces of your 3D object. The coordinates that you compute from image pixels likely lie in the interior of the faces.
Assuming your OBJ file represents a triangle mesh with positions and texture coordinates, the entries for faces will look something like this:
f p1/t1 p2/t2 p3/t3
where p1
, p2
, p3
are position indices and t1
, t2
, t3
are texture coordinate indices.
To find whether your computed (u,v) coordinate maps to a given triangle, you'll need to
vt
entries with the indices t1
, t2
, t3
,If you repeat this check for all f
entries of the OBJ file, you'll find the triangle(s) which the given image pixel maps to. If you don't find any matches then the pixel does not appear on the surface of the object.