opengl y-axis not scaling with x or z - java

I'm not really sure how to even describe this problem so please excuse the terrible title. I have a simple model ( it is actually a tile but I made it a cube to better illustrate the issue ) that is 2 units high, wide and deep. To draw a continuous field of these I simply increment X and Z by 2 appropriately and they all render nicely next to one another. If I want to create a step up so my flat field has a new level to it I add 2 to the Y value for a segment of the field expecting that the bottom of the top level would then align perfectly with the top of the lower level.
What actually happens is the top level renders a fair distance above the lower level. Why? What would cause this? I ran some tests and found that I'd have to increment Y by a number somewhere between 0.6 and 0.7 for the bottom to align properly with the top.
I thought maybe it was the viewport but I think that is fine. The models don't look warped. Has anyone run into something like this before?
See the attached image for an example of what I'm talking about. The red line illustrates this strange separation of the top and bottom layers.
The Render function
public void draw() throws Exception {
float x = 0;
double y = 0;
float z = 0;
int cidx = 0;
boolean firstCube = true;
glfwSwapBuffers(window); // swap the color buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
//calc rotate camera
if (updatecamera == true){
updateCamera();
}
glUseProgram(shader.iProgram);
//some lighting...
Vector4f lp = new Vector4f(lightX, lightY, lightZ,1.0f);
//float[] lp = {xa, ya + 100, za - 120,1.0f}; //set light source to same as camera eye for now.
shader.setUniform(iLightCam, camera);
shader.setUniform(iLightVec, lp);
//get picking ray
if (worldClicked == true){
pick = makeRay(pick, cursorX, (DISPLAY_HEIGHT - ((DISPLAY_HEIGHT - VP_HEIGHT) / 2)) - cursorY);
}
for(Iterator<Quad> qd = quads.iterator(); qd.hasNext(); ) {
//init cull check
frust.cullIn = 0;
frust.cullOut = 0;
quad = qd.next();
pickthisQuad = false;
firstCube = true; //the first cube is used to set the values of the Quad OBB.
for(Iterator<Cube> i = quad.cubes.iterator(); i.hasNext(); ) {
cb = i.next();
x = cb.x;
z = cb.z;
//y = cb.y;
//testing odd Y behaviour
if ( y == 0) {
y = lightX;
}else{
y = 0;
}
System.out.println(" y: " + y);
//init
model.setIdentity();
//ROTATE
//set translate
vTrans.set(transx + x, (float) (transy + y), transz + z);
Matrix4f.translate(vTrans, model1, model);
vTrans.set(-(transx + x), (float) (-transy + y), -(transz + z));
Matrix4f.translate(vTrans, model, model);
Matrix4f.rotate((float) Math.toRadians(rotY), new Vector3f(0,1,0), model, model);
vTrans.set((transx + x), (float) (transy + y), (transz + z));
Matrix4f.translate(vTrans, model, model);
Matrix4f.mul(model, camera, modelview);
shader.setUniform(iModelView, modelview);
Matrix3f norm = new Matrix3f();
norm.m00 = modelview.m00;
norm.m01 = modelview.m01;
norm.m02 = modelview.m02;
norm.m10 = modelview.m10;
norm.m11 = modelview.m11;
norm.m12 = modelview.m12;
norm.m20 = modelview.m20;
norm.m21 = modelview.m21;
norm.m22 = modelview.m22;
shader.setUniform(iNorm, norm);
shader.setUniform(iProj, projection);
shader.setUniform(iCam, camera);
shader.setUniform(iModel, model);
test_renderFrustumandCrosslines();
manageTextures(cb);
render();
cidx++;
}//cubes
cidx = 0;
}//quads
/**
* TESTING
*/
glUseProgram(shaderLine.iProgram);
Matrix4f mvp = new Matrix4f();
mvp.setIdentity();
Matrix4f.mul(projection, camera, mvp);
shaderLine.setUniform(iMVPLine, mvp);
renderLine();
renderCross();
worldClicked = false;
glFinish();
}

Is there any special thoughts about the 2 first translates in the rotation code? The x ans z translations will cancel each other out but not the y axis. Which could be the source of the problem.
vTrans.set(transx + x, (float) (transy + y), transz + z);
Matrix4f.translate(vTrans, model1, model);
vTrans.set(-(transx + x), (float) (-transy + y), -(transz + z));
Matrix4f.translate(vTrans, model, model);
What happens if you remove these 4 lines? You still do the translation after the rotation.

Related

How should I be implementing a view clipping plane in a 3D Engine?

This project is written entirely from scratch in Java. I've just been bored ever since Covid started, so I wanted something that would take up my time, and teach me something cool. I've been stuck on this problem for about a week now though. When I try to use my near plane clipping method it skews the new vertices to the opposite side of the screen, but sometimes times it works just fine.
Failure Screenshot
Success Screenshot
So my thought is maybe that since it works sometimes, I'm just not doing the clipping at the correct time in the pipeline?
I start by face culling and lighting,
Then I apply a Camera View Transformation to the Vertices,
Then I clip on the near plane
Finally I apply the projection matrix and Clip any remaining off screen Triangles
Code:
This calculates the intersection points. Sorry if it's messy or to long I'm not very experienced in coding, my major is physics, not CS.
public Vertex vectorIntersectPlane(Vector3d planePos, Vector3d planeNorm, Vector3d lineStart, Vector3d lineEnd){
float planeDot = planeNorm.dotProduct(planePos);
float startDot = lineStart.dotProduct(planeNorm);
float endDot = lineEnd.dotProduct(planeNorm);
float midPoint = (planeDot - startDot) / (endDot - startDot);
Vector3d lineStartEnd = lineEnd.sub(lineStart);
Vector3d lineToIntersect = lineStartEnd.scale(midPoint);
return new Vertex(lineStart.add(lineToIntersect));
}
public float distanceFromPlane(Vector3d planePos, Vector3d planeNorm, Vector3d vert){
float x = planeNorm.getX() * vert.getX();
float y = planeNorm.getY() * vert.getY();
float z = planeNorm.getZ() * vert.getZ();
return (x + y + z - (planeNorm.dotProduct(planePos)));
}
//When a triangle gets clipped it has 4 possible outcomes
// 1 it doesn't actually need clipping and gets returned
// 2 it gets clipped into 1 new triangle, for testing these are red
// 3 it gets clipped into 2 new triangles, for testing 1 is green, and 1 is blue
// 4 it is outside the view planes and shouldn't be rendered
public void clipTriangles(){
Vector3d planePos = new Vector3d(0, 0, ProjectionMatrix.fNear, 1f);
Vector3d planeNorm = Z_AXIS.clone();
final int length = triangles.size();
for(int i = 0; i < length; i++) {
Triangle t = triangles.get(i);
if(!t.isDraw())
continue;
Vector3d[] insidePoint = new Vector3d[3];
int insidePointCount = 0;
Vector3d[] outsidePoint = new Vector3d[3];
int outsidePointCount = 0;
float d0 = distanceFromPlane(planePos, planeNorm, t.getVerticesVectors()[0]);
float d1 = distanceFromPlane(planePos, planeNorm, t.getVerticesVectors()[1]);
float d2 = distanceFromPlane(planePos, planeNorm, t.getVerticesVectors()[2]);
//Storing distances from plane and counting inside outside points
{
if (d0 >= 0){
insidePoint[insidePointCount] = t.getVerticesVectors()[0];
insidePointCount++;
}else{
outsidePoint[outsidePointCount] = t.getVerticesVectors()[0];
outsidePointCount++;
}
if (d1 >= 0){
insidePoint[insidePointCount] = t.getVerticesVectors()[1];
insidePointCount++;
}else{
outsidePoint[outsidePointCount] = t.getVerticesVectors()[1];
outsidePointCount++;
}
if (d2 >= 0){
insidePoint[insidePointCount] = t.getVerticesVectors()[2];
insidePointCount++;
}else{
outsidePoint[outsidePointCount] = t.getVerticesVectors()[2];
}
}
//Triangle has 1 point still inside view, remove original triangle add new clipped triangle
if (insidePointCount == 1) {
t.dontDraw();
Vertex newVert1 = vectorIntersectPlane(planePos, planeNorm, insidePoint[0], outsidePoint[0]);
Vertex newVert2 = vectorIntersectPlane(planePos, planeNorm, insidePoint[0], outsidePoint[1]);
vertices.add(newVert1);
vertices.add(newVert2);
//Triangles are stored with vertex references instead of the actual vertex object.
Triangle temp = new Triangle(t.getVertKeys()[0], vertices.size() - 2, vertices.size() - 1, vertices);
temp.setColor(1,0,0, t.getBrightness(), t.getAlpha());
triangles.add(temp);
continue;
}
//Triangle has two points inside remove original add two new clipped triangles
if (insidePointCount == 2) {
t.dontDraw();
Vertex newVert1 = vectorIntersectPlane(planePos, planeNorm, insidePoint[0], outsidePoint[0]);
Vertex newVert2 = vectorIntersectPlane(planePos, planeNorm, insidePoint[1], outsidePoint[0]);
vertices.add(newVert1);
vertices.add(newVert2);
Triangle temp = new Triangle(t.getVertKeys()[0], t.getVertKeys()[1], vertices.size() - 1, vertices);
temp.setColor(0, 1, 0, t.getBrightness(), t.getAlpha());
triangles.add(temp);
temp = new Triangle(t.getVertKeys()[0], t.getVertKeys()[1], vertices.size() - 2, vertices);
temp.setColor(0, 0, 1, t.getBrightness(), t.getAlpha());
triangles.add(temp);
continue;
}
}
}
I figured out the problem, The new clipped triangles were not being given the correct vertex references. they were just being given the first vertex of the triangle irregardless of if that was inside the view or not.

Trouble converting jbox2d angle to slick2d angle

UPDATE
Slick and JBox use radians that go in opposite directions, that's why I was having trouble.
I am making a game using JBox2D and Slick2D (per the title). So, because I couldn't find anything online about it, I wrote a bunch of code from scratch to convert between them. However, it seems as though the angles are different, even though both documentations say they use radians.
Here is my code:
//In the update function
angle = (float) (angle % 2*Math.PI);
mass = player.getMass();
position = player.getPosition();
if(input.isKeyDown(inputLeft)){
angle-=0.015f*turnBlocks.size()/mass; //turning, pt1
} else if(input.isKeyDown(inputRight)){
angle+=0.015f*turnBlocks.size()/mass;
}
player.setTransform(position, angle); //turning, pt2
if(input.isKeyDown(inputForward)){
float xv = (float)(0.25f * Math.sin(angle) *
thrustBlocks.size() / mass); //Converting angle to vector
float yv = (float)(0.25f * Math.cos(angle) *
thrustBlocks.size() / mass);
Vec2 curVel = player.getLinearVelocity();
xv = xv + curVel.x;
yv = yv + curVel.y;
player.setLinearVelocity(new Vec2(xv, yv));
}
and
//In the render function
g.setColor(Color.gray);
for(int mass = 0; mass < massBlocks.size(); mass++){
float boxx = (float)massBlocks.get(mass)[0];
float boxy = (float)massBlocks.get(mass)[1];
int[] slicklist = tr.toSlick(position.x+boxx, position.y+boxy);
boxx = (float)slicklist[0];
boxy = (float)slicklist[1];
float[] ps = {boxx-tr.xscale/2, boxy-tr.yscale/2,
boxx+tr.xscale/2, boxy-tr.yscale/2,
boxx+tr.xscale/2, boxy+tr.yscale/2,
boxx-tr.xscale/2, boxy+tr.yscale/2};
Polygon p = new Polygon(ps);
//turning, pt3
g.fill(p.transform(Transform.createRotateTransform(radAngle, slickx, slicky)));
}
When I run the above code (with the rest of it), I get the player block(s) moving in the direction it shows it is facing. However, the collision in Jbox2D is out of sync. Here is the pattern I have found:
1 unit = pi/4 in slick
Slick direction:
7___0___1
6___.___2
5___4___3
Jbox Direction:
5___0___3
2___.___6
7___4___1
Really, I have no idea what is going on. Can somebody help?
Okay. It turns out that even thought Slick's transform and JBox's angle are both radians, They go in opposite directions. So, I made the below code with the .getWorldPosition instead of transform.
float localJBoxX = thrustBlocks.get(count)[0];
float localJBoxY = thrustBlocks.get(count)[1];
float[] localEndCoords = {localJBoxX+0.5f, localJBoxY+0.5f,
localJBoxX-0.5f, localJBoxY+0.5f,
localJBoxX-0.5f, localJBoxY-0.5f,
localJBoxX+0.5f, localJBoxY-0.5f};
float[] slickCoords = new float[localEndCoords.length];
for(byte point = 0; point<localEndCoords.length/2; point++){
Vec2 localPoint = new Vec2(localEndCoords[point*2], localEndCoords[point*2+1]);
slickCoords[point*2] = (float)tr.toSlick(player.getWorldPoint(localPoint).x, player.getWorldPoint(localPoint).y)[0];
slickCoords[point*2+1] = (float)tr.toSlick(player.getWorldPoint(localPoint).x, player.getWorldPoint(localPoint).y)[1];
}
Polygon box = new Polygon(slickCoords);
g.fill(box.transform(new Transform())); //as to return a shape

Orthogonal Projection - Fit Object to Screen?

Im programming with opengl (lwjgl) and building my own mini-library. My Camera, which takes the projection type, builds its projection matrix like this:
this.aspect = (float) Display.getWidth() / (float) Display.getHeight();
this.top = (float) (Math.tan(Math.toRadians(fov) / 2));
this.bottom = -top;
this.right = top * aspect;
this.left = -right;
if(type == AGLProjectionType.PERSPECTIVE){
float aspect = 800.0f / 600.0f;
final double f = (1.0 / Math.tan(Math.toRadians(fov / 2.0)));
projection = new Matrix4f();
projection.m00 = (float) (f / aspect);
projection.m11 = (float) f;
projection.m22 = (far + near) / (near - far);
projection.m23 = -1;
projection.m32 = (2 * far + near) / (near - far);
projection.m33 = 0;
}
else if(type == AGLProjectionType.ORTHOGONAL){
projection.m00 = 2 / (right - left);
projection.m03 = -(right + left) / (right - left);
projection.m11 = 2 / (top - bottom);
projection.m13 = -(top + bottom) / (top - bottom);
projection.m22 = -2 / (far - near);
}
So far so good.
Now, the VBO input, so the raw meshes of objects - for example a quad - i keep in the normalized dimension, so values in the range of [ -1 | 1 ].
If i want to scale it, i scale the model matrix to a value, and to move it i translate the model matrix.
My Problem is: That are all relative values. If i say "matrix.scale(0.5f, 0.5f, 0.5f)" the object will take the half of its previous size. But what if for example i want to have an object with 500 pixel width? How can i calculate this? Or if i want the object to be Screen.width / heiht, and x = -Screen.width * 0.5 and y = -Screen.height * 0.5 - so an object wich fills out the screen and has his position in the upper left corner of the screen? I have to calculate something with help of the projection matrix - right? But how?
Not exactly what you are asking, but maybe it helps. With this code the camera is set so that screen coordinates match world coordinates and the lower left corner of the viewport is zero for X and Y. Orthogonal projection.
case TwoD:
{
projectionMatrix.resetToZero();
projectionMatrix._11 = 2.0f/(float)this.viewPort.Width;
projectionMatrix._22 = 2.0f/(float)this.viewPort.Height;
projectionMatrix._33 = -2.0f/(this.farClip-this.nearClip);
projectionMatrix._43 = -1* this.nearClip;
projectionMatrix._44 = 1.0f;
float tx = -0.5f* (float)this.viewPort.Width;
float ty = -0.5f* (float)this.viewPort.Height;
float tz = this.nearClip +0.1f; //why +0.1f >> so that an object with Z = 0 is still displayed
viewMatrix.setIdetity();
viewMatrix._22 = 1.0f;
viewMatrix._41 = tx;
viewMatrix._42 = ty;
viewMatrix._43 = -tz;
break;
}
As for your question: You would have to put your desired screen coordinates trough the inverse of the view-projection matrix. And you would have to add the depth information on the way as you are going from 2D to 3D. I am sorry, but I cant help you with the math for that.

Flat, 3D triangle, made out of voxels

I have a problem that I can't seem to get a working algorithm for, I've been trying to days and get so close but yet so far.
I want to draw a triangle defined by 3 points (p0, p1, p2). This triangle can be any shape, size, and orientation. The triangle must also be filled inside.
Here's a few things I've tried and why they've failed:
1
Drawing lines along the triangle from side to side
Failed because the triangle would have holes and would not be flat due to the awkwardness of drawing lines across the angled surface with changing locations
2
Iterate for an area and test if the point falls past the plane parallel to the triangle and 3 other planes projected onto the XY, ZY, and XZ plane that cover the area of the triangle
Failed because for certain triangles (that have very close sides) there would be unpredictable results, e.g. voxels floating around not connected to anything
3
Iterate for an area along the sides of the triangle (line algorithm) and test to see if a point goes past a parallel plane
Failed because drawing a line from p0 to p1 is not the same as a line from p1 to p0 and any attempt to rearrange either doesn't help, or causes more problems. Asymmetry is the problem with this one.
This is all with the intent of making polygons and flat surfaces. 3 has given me the most success and makes accurate triangles, but when I try to connect these together everything falls apart and I get issues with things not connecting, asymmetry, etc. I believe 3 will work with some tweaking but I'm just worn out from trying to make this work for so long and need help.
There's a lot of small details in my algorithms that aren't really relevant so I left them out. For number 3 it might be a problem with my implementation and not the algorithm itself. If you want code I'll try and clean it up enough to be understandable, it will take me a few minutes though. But I'm looking for algorithms that are known to work. I can't seem to find any voxel shape making algorithms anywhere, I've been doing everything from scratch.
EDIT:
Here's the third attempt. It's a mess, but I tried to clean it up.
// Point3i is a class I made, however the Vector3fs you'll see are from lwjgl
public void drawTriangle (Point3i r0, Point3i r1, Point3i r2)
{
// Util is a class I made with some useful stuff inside
// Starting values for iteration
int sx = (int) Util.min(r0.x, r1.x, r2.x);
int sy = (int) Util.min(r0.y, r1.y, r2.y);
int sz = (int) Util.min(r0.z, r1.z, r2.z);
// Ending values for iteration
int ex = (int) Util.max(r0.x, r1.x, r2.x);
int ey = (int) Util.max(r0.y, r1.y, r2.y);
int ez = (int) Util.max(r0.z, r1.z, r2.z);
// Side lengths
float l0 = Util.distance(r0.x, r1.x, r0.y, r1.y, r0.z, r1.z);
float l1 = Util.distance(r2.x, r1.x, r2.y, r1.y, r2.z, r1.z);
float l2 = Util.distance(r0.x, r2.x, r0.y, r2.y, r0.z, r2.z);
// Calculate the normal vector
Vector3f nn = new Vector3f(r1.x - r0.x, r1.y - r0.y, r1.z - r0.z);
Vector3f n = new Vector3f(r2.x - r0.x, r2.y - r0.y, r2.z - r0.z);
Vector3f.cross(nn, n, n);
// Determines which direction we increment for
int iz = n.z >= 0 ? 1 : -1;
int iy = n.y >= 0 ? 1 : -1;
int ix = n.x >= 0 ? 1 : -1;
// Reorganize for the direction of iteration
if (iz < 0) {
int tmp = sz;
sz = ez;
ez = tmp;
}
if (iy < 0) {
int tmp = sy;
sy = ey;
ey = tmp;
}
if (ix < 0) {
int tmp = sx;
sx = ex;
ex = tmp;
}
// We're we want to iterate over the end vars so we change the value
// by their incrementors/decrementors
ex += ix;
ey += iy;
ez += iz;
// Maximum length
float lmax = Util.max(l0, l1, l2);
// This is a class I made which manually iterates over a line, I already
// know that this class is working
GeneratorLine3d g0, g1, g2;
// This is a vector for the longest side
Vector3f v = new Vector3f();
// make the generators
if (lmax == l0) {
v.x = r1.x - r0.x;
v.y = r1.y - r0.y;
v.z = r1.z - r0.z;
g0 = new GeneratorLine3d(r0, r1);
g1 = new GeneratorLine3d(r0, r2);
g2 = new GeneratorLine3d(r2, r1);
}
else if (lmax == l1) {
v.x = r1.x - r2.x;
v.y = r1.y - r2.y;
v.z = r1.z - r2.z;
g0 = new GeneratorLine3d(r2, r1);
g1 = new GeneratorLine3d(r2, r0);
g2 = new GeneratorLine3d(r0, r1);
}
else {
v.x = r2.x - r0.x;
v.y = r2.y - r0.y;
v.z = r2.z - r0.z;
g0 = new GeneratorLine3d(r0, r2);
g1 = new GeneratorLine3d(r0, r1);
g2 = new GeneratorLine3d(r1, r2);
}
// Absolute values for the normal
float anx = Math.abs(n.x);
float any = Math.abs(n.y);
float anz = Math.abs(n.z);
int i, o;
int si, so;
int ii, io;
int ei, eo;
boolean maxx, maxy, maxz,
midy, midz, midx,
minx, miny, minz;
maxx = maxy = maxz =
midy = midz = midx =
minx = miny = minz = false;
// Absolute values for the longest side vector
float rnx = Math.abs(v.x);
float rny = Math.abs(v.y);
float rnz = Math.abs(v.z);
int rmid = Util.max(rnx, rny, rnz);
if (rmid == rnz) midz = true;
else if (rmid == rny) midy = true;
midx = !midz && !midy;
// Determine the inner and outer loop directions
if (midz) {
if (any > anx)
{
maxy = true;
si = sy;
ii = iy;
ei = ey;
}
else {
maxx = true;
si = sx;
ii = ix;
ei = ex;
}
}
else {
if (anz > anx) {
maxz = true;
si = sz;
ii = iz;
ei = ez;
}
else {
maxx = true;
si = sx;
ii = ix;
ei = ex;
}
}
if (!midz && !maxz) {
minz = true;
so = sz;
eo = ez;
}
else if (!midy && !maxy) {
miny = true;
so = sy;
eo = ey;
}
else {
minx = true;
so = sx;
eo = ex;
}
// GeneratorLine3d is iterable
Point3i p1;
for (Point3i p0 : g0) {
// Make sure the two 'mid' coordinate correspond for the area inside the triangle
if (midz)
do p1 = g1.hasNext() ? g1.next() : g2.next();
while (p1.z != p0.z);
else if (midy)
do p1 = g1.hasNext() ? g1.next() : g2.next();
while (p1.y != p0.y);
else
do p1 = g1.hasNext() ? g1.next() : g2.next();
while (p1.x != p0.x);
eo = (minx ? p0.x : miny ? p0.y : p0.z);
so = (minx ? p1.x : miny ? p1.y : p1.z);
io = eo - so >= 0 ? 1 : -1;
for (o = so; o != eo; o += io) {
for (i = si; i != ei; i += ii) {
int x = maxx ? i : midx ? p0.x : o;
int y = maxy ? i : midy ? p0.y : o;
int z = maxz ? i : midz ? p0.z : o;
// isPassing tests to see if a point goes past a plane
// I know it's working, so no code
// voxels is a member that is an arraylist of Point3i
if (isPassing(x, y, z, r0, n.x, n.y, n.z)) {
voxels.add(new Point3i(x, y, z));
break;
}
}
}
}
}
You could use something like Besenham's line algorithm, but extended into three dimensions. The two main ideas we want to take from it are:
rotate the initial line so its slope isn't too steep.
for any given x value, find an integer value that is closest to the ideal y value.
Just as Bresenham's algorithm prevents gaps by performing an initial rotation, we'll avoid holes by performing two initial rotations.
Get the normal vector and point that represent the plane your triangle lies on. Hint: use the cross product of (line from p0 to p1) and (line from p0 to p2) for the vector, and use any of your corner points for the point.
You want the plane to be sufficiently not-steep, to avoid holes. You must satisfy these conditions:
-1 >= norm.x / norm.y >= 1
-1 >= norm.z / norm.y >= 1
Rotate your normal vector and initial points 90 degrees about the x axis and 90 degrees about the z axis until these conditions are satisfied. I'm not sure how to do this in the fewest number of rotations, but I'm fairly sure you can satisfy these conditions for any plane.
Create a function f(x,z) which represents the plane your rotated triangle now lies on. It should return the Y value of any pair of X and Z values.
Project your triangle onto the XZ plane (i.e., set all the y values to 0), and use your favorite 2d triangle drawing algorithm to get a collection of x-and-z coordinates.
For each pixel value from step 4, pass the x and z values into your function f(x,z) from step 3. Round the result to the nearest integer, and store the x, y, and z values as a voxel somewhere.
If you performed any rotations in step 2, perform the opposite of those rotations in reverse order on your voxel collection.
Start with a function that checks for triangle/voxel intersection. Now you can scan a volume and find the voxels that intersect the triangle - these are the ones you're interested in. This is a lousy algorithm but is also a regression test for anything else you try. This test is easy to implement using SAT (separating axis theorem) and considering the triangle a degenerate volume (1 face, 3 edges) and considering the voxels symmetry (only 3 face normals).
I use octtrees, so my preferred method is to test a triangle against a large voxel and figure out which of the 8 child octants it intersects. Then use recursion on the intersected children until the desired level of subdivision is attained. Hint: at most 6 of the children can be intersected by the triangle and often fewer than that. This is tricky but will produce the same results as the first method but much quicker.
Rasterization in 3d is probably fastest, but IMHO is even harder to guarantee no holes in all cases. Again, use the first method for comparison.

Translate Java 3D coordinates to 2D screen coordinates

I'm working with a Java 3D application called "Walrus" that is used to display directed graphs. The code already has a feature to highlight a node and draw label adjacent in graph given its screen coordinates.
Upon rotating the screen, the node is no more highlighted.
What I have is the node coordinates in 3D. I need to draw label to it.
Code for highlight using 3D coordinates
Point3d p = new Point3d();
m_graph.getNodeCoordinates(node, p);
PointArray array = new PointArray(1, PointArray.COORDINATES);
array.setCoordinate(0, p);
m_parameters.putModelTransform(gc);
gc.setAppearance(m_parameters.getPickAppearance());
How can I draw Label with 3D coordinates( Raster graphics throws error Renderer: Error creating immediate mode Canvas3D graphics context )
How can I convert 3D coordinates to 2D screen and use existing code to draw label at 2D screen point
Thanks,
Dakshina
I have an algorithm/method for converting [x,y,z] into [x,y] with the depth parameter:
The x value is : (int) (x - (z / depth * x))
The y value is : (int) (y - (z / depth * y))
Essentially, the depth is the focal point. The vanishing point will be at [0,0,depth].
Here's what i used to convert my 3D coordinates into perspective 2D, x2 and y2 being the 2dimensional coordinates, xyz being the 3D coordinates.
use these formulas:
x2 = cos(30)*x - cos(30)*y
y2 = sin(30)*x + sin(30)*y + z
I picked the angle 30 as it is easy for perspective purposes, also used in Isometric grids for drawing 3D on 2D papers. As the z axe will be the vertical one, x and y are the ones at 60 degrees from it right and left. Isometric Grid Picture.
I'm still working on rotation, but without altering the axes, just coordinate rotation in 3D.
Enjoy.
I found the solution.
This is the function to display Text3D at image 2D coordinates
public void drawLabel(GraphicsContext3D gc, double x, double y, int zOffset, String s) {
boolean frontBufferRenderingState = gc.getFrontBufferRendering();
gc.setBufferOverride(true);
gc.setFrontBufferRendering(true);
Point3d eye = getEye();
double labelZ = zOffset * LABEL_Z_OFFSET_SCALE
+ LABEL_Z_SCALE * eye.z + LABEL_Z_OFFSET;
double xOffset = LABEL_X_OFFSET * m_pixelToMeterScale;
double yOffset = LABEL_Y_OFFSET * m_pixelToMeterScale;
Point3d p = new Point3d(x + xOffset, y + yOffset, 0.0);
{
// Project given (x, y) coordinates to the plane z=labelZ.
// Convert from image-plate to eye coordinates.
p.x -= eye.x;
p.y -= eye.y;
double inversePerspectiveScale = 1.0 - labelZ / eye.z;
p.x *= inversePerspectiveScale;
p.y *= inversePerspectiveScale;
// Convert from eye to image-plate coordinates.
p.x += eye.x;
p.y += eye.y;
}
Transform3D scale = new Transform3D();
scale.set(LABEL_SCALE);
Vector3d t = new Vector3d(p.x, p.y, labelZ);
Transform3D translation = new Transform3D();
translation.set(t);
translation.mul(scale);
Transform3D transform = new Transform3D(m_imageToVworld);
transform.mul(translation);
gc.setModelTransform(transform);
//-----------------
int fontSize=(int)(10*m_magnification);
if(fontSize>20)
fontSize=20;
//---------------
// XXX: Courier may not be available on all systems.
Text2D text = new Text2D(s, new Color3f(1.0f, 1.0f, 1.0f),
"Courier", fontSize, Font.BOLD);
gc.draw(text);
gc.flush(true);
// NOTE: Resetting the model transform here is very important.
// For some reason, not doing this causes the immediate
// following frame to render incorrectly (but subsequent
// frames will render correctly). In some ways, this
// makes sense, because most rendering code assumes that
// GraphicsContext3D has been set to some reasonable
// transform.
gc.setModelTransform(m_objectTransform);
gc.setFrontBufferRendering(frontBufferRenderingState);
}
This is the function to take 3D coordinates and convert them to image 2D coordinates and render using above function
private boolean displayOnScreenLabel(int node, String label) {
boolean success = false;
try {
Transform3D transform = m_parameters.getObjectToEyeTransform();
Point3d nodeC = new Point3d();
m_graph.getNodeCoordinates(node, nodeC);
transform.transform(nodeC);
Point3d eye = m_parameters.getEye();
double perspectiveScale = 1.0 / (1.0 - nodeC.z / eye.z);
double centerX = eye.x + nodeC.x * perspectiveScale;
double centerY = eye.y + nodeC.y * perspectiveScale;
GraphicsContext3D gc = m_canvas.getGraphicsContext3D();
m_parameters.drawLabel(gc, centerX, centerY, m_labelZOffsetCounter++, label);
success = true;
} catch (final java.lang.OutOfMemoryError error) {
JOptionPane.showMessageDialog(m_frame, "The 3D Graphics is unable to find enough memory on your system. Kill the application!", "Out Of Memory!", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
success = false;
}
return success;
}

Categories