How to get face coordinates? - java

On the topic of creating custom 3D models, I found this answer. It remains incomprehensible to me how the coordinates of the texture and points mix.
Here's question.
If this is some kind of global concept, and not a feature of building 3D in Java, then I will be glad to mention any literature where these things are well covered. For convenience, I give an example of a code where getting the coordinates of the faces is covered with darkness for me. Thank!
float[] points =
{
50, 0, 0, // v0 (iv0 = 0)
45, 10, 0, // v1 (iv1 = 1)
55, 10, 0 // v2 (iv2 = 2)
};
float[] texCoords =
{
0.5f, 0.5f, // t0 (it0 = 0)
0.0f, 1.0f, // t1 (it1 = 1)
1.0f, 1.0f // t2 (it2 = 2)
};
int[] faces =
{
0, 0, 2, 2, 1, 1, // iv0, it0, iv2, it2, iv1, it1 (front face)
0, 0, 1, 1, 2, 2 // iv0, it0, iv1, it1, iv2, it2 back face
};

Found the literature with the answers. If anyone is interested, here is the link.a link

Related

javafx shape3d texturing: Don't strectch the image

I'm working now with javafx to build a maze and I want the walls to be textured with some seamless texture (that can be repeated). The maze is randomly generated so I don't know the size of any walls. I started by using a PhongMaterial with the desired texture, but it expand the image to fill the whole wall (a Box), so my texture is totally stretched. Is there any way to force the Material to replicate the texture as needed ?
The code is like:
Image img = new Image(new FileInputStream("img.jpg"), 400, 400, true, false);
Material mat = new PhongMaterial(Color.WHITE, img, null, null, null);
Box w = new Box(100,10,10);
w.setMaterial(mat);
Something like an ImagePattern seems a good idea, but there is no Material that accept it.
Thanks in advance for any help
As #fabian mentioned, Box is not suitable for customizing the texture. By default the image you set as diffuse map will be applied for each of its six faces, and, as you already discovered, this means that it will stretch the image to accommodate the different sides.
Using the FXyz library, we can easily try the Carbon-Kevlar pattern. But obviously we have to select a size for it. Like 100 x 30.
#Override
public void start(Stage primaryStage) {
Box box = new Box(100, 30, 50);
PhongMaterial material = new PhongMaterial();
Patterns pattern = new Patterns(100, 30);
material.setDiffuseMap(pattern.createPattern(Patterns.CarbonPatterns.CARBON_KEVLAR, false));
box.setMaterial(material);
Scene scene = new Scene(new Group(box), 500, 400, true, SceneAntialiasing.BALANCED);
primaryStage.setScene(scene);
primaryStage.show();
}
While the texture fits perfectly fine the front face with dimensions 100x30, this image is distorted to fit in the same way the other faces 50x50 and 100x50.
Solution 1
We can try to generate our own Box, so we can decide how to apply the diffuse map.
Creating a TriangleMesh for a cuboid is easy in terms of vertices and faces or normals.
The tricky part is setting the texture coordinates. In the following snippet I set them based on one of the different possible 2D net images of the 3D cuboid:
public MeshView createCuboid(float w, float h, float d) {
float hw = w / 2f;
float hh = h / 2f;
float hd = d / 2f;
float points[] = {
hw, hh, hd,
hw, hh, -hd,
hw, -hh, hd,
hw, -hh, -hd,
-hw, hh, hd,
-hw, hh, -hd,
-hw, -hh, hd,
-hw, -hh, -hd};
float L = 2 * w + 2 * d;
float H = h + 2 * d;
float tex[] = {
d / L, 0f,
(d + w) / L, 0f,
0f, d / H,
d / L, d / H,
(d + w) / L, d / H,
(2 * d + w) / L, d / H,
1f, d / H,
0f, (d + h) / H,
d / L, (d + h) / H,
(d + w) / L, (d + h) / H,
(2 *d + w) / L, (d + h) / H,
1f, (d + h) / H,
d / L, 1f,
(d + w) / L, 1f};
float normals[] = {
1f, 0f, 0f,
-1f, 0f, 0f,
0f, 1f, 0f,
0f, -1f, 0f,
0f, 0f, 1f,
0f, 0f, -1f,
};
int faces[] = {
0, 0, 10, 2, 0, 5, 1, 0, 9,
2, 0, 5, 3, 0, 4, 1, 0, 9,
4, 1, 7, 5, 1, 8, 6, 1, 2,
6, 1, 2, 5, 1, 8, 7, 1, 3,
0, 2, 13, 1, 2, 9, 4, 2, 12,
4, 2, 12, 1, 2, 9, 5, 2, 8,
2, 3, 1, 6, 3, 0, 3, 3, 4,
3, 3, 4, 6, 3, 0, 7, 3, 3,
0, 4, 10, 4, 4, 11, 2, 4, 5,
2, 4, 5, 4, 4, 11, 6, 4, 6,
1, 5, 9, 3, 5, 4, 5, 5, 8,
5, 5, 8, 3, 5, 4, 7, 5, 3};
TriangleMesh mesh = new TriangleMesh();
mesh.setVertexFormat(VertexFormat.POINT_NORMAL_TEXCOORD);
mesh.getPoints().addAll(points);
mesh.getTexCoords().addAll(tex);
mesh.getNormals().addAll(normals);
mesh.getFaces().addAll(faces);
return new MeshView(mesh);
}
Now we can generate the image, but using the net dimensions:
#Override
public void start(Stage primaryStage) {
MeshView box = createCuboid(100, 30, 50);
PhongMaterial material = new PhongMaterial();
Patterns pattern = new Patterns(300, 160);
material.setDiffuseMap(pattern.createPattern(Patterns.CarbonPatterns.CARBON_KEVLAR, false));
box.setMaterial(material);
box.getTransforms().addAll(rotateX, rotateY);
Scene scene = new Scene(new Group(box), 500, 400, true, SceneAntialiasing.BALANCED);
primaryStage.setScene(scene);
primaryStage.show();
}
Note that the image is not distorted anymore.
You can play with its size to get a more fine or dense pattern (with a bigger image pattern).
Note that you can find this Cuboid primitive in the FXyz library, among many other 3D primitives.
Also you can find different texture modes (density maps, images, patterns...)

Trying to draw a model with Gouraud shading in jogl for desktop, but is flat

I already have a drawn model, but it has flat shading (for what I understand it should be smooth by default...)
This is the initial config:
private void SetLightningAndMaterials(){
//float[] lightPos = {1, 1, 1, 0};
float[] lightPos = {0, 0, 1, 0};
float[] lightColorDiffuse = {1, 1, 1, 1};
float[] lightColorAmbient = {0.2f, 0.2f, 0.2f, 1};
gl.glShadeModel(GL.GL_SMOOTH);
gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, lightPos, 0);
gl.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, lightColorDiffuse, 0);
gl.glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, lightColorAmbient, 0);
gl.glEnable(GL.GL_LIGHT1);
gl.glEnable(GL.GL_LIGHTING);
gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, ambientColour, 0);
gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mesh.colour, 0);
gl.glEnable(GL.GL_LIGHTING);
gl.glEnable(GL.GL_LIGHT0);
float[] noAmbient =
{ 0.1f, 0.1f, 0.1f, 1f }; // low ambient light
float[] spec =
{ 1f, 0.6f, 0f, 1f }; // low ambient light
float[] diffuse =
{ 0.5f, 0.5f, 0.5f, 1f };
gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, noAmbient, 0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, spec, 0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, diffuse, 0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, new float[]{0,0,10,1}, 0);
}
And this is how I draw the model:
public void Draw(GL gl, GLU glu){
Vec3d normal;
MassPoint vertex1, vertex2, vertex3;
int faceIndex=0;
Face surfaceFace;
for (faceIndex=0; faceIndex<surfaceFaces.size();faceIndex++){
surfaceFace = surfaceFaces.get(faceIndex);
surfaceFace.recalculateNormal();
vertex1 = surfaceFace.vertex1;
vertex2 = surfaceFace.vertex2;
vertex3 = surfaceFace.vertex3;
normal = surfaceFace.normal;
gl.glBegin(gl.GL_TRIANGLES);
gl.glNormal3d(normal.x, normal.y, normal.z);
gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, colour, 0);
gl.glVertex3d(vertex1.position.x, vertex1.position.y, vertex1.position.z);
gl.glVertex3d(vertex2.position.x, vertex2.position.y, vertex2.position.z);
gl.glVertex3d(vertex3.position.x, vertex3.position.y, vertex3.position.z);
gl.glEnd();
}
}
I want to believe there's an easy way of solving this without having to create a shader (I don't have any idea how to set these in Java).
I'm using JOGL 1 by the way, and is probably an old version (the imports are like javax.media.opengl.*).
I managed to solve the problem. For smoothness to work, the drawing expects 3 normals (one per vertex), I was only passing 1 normal (one per face).
Here's the new code for the drawing:
public void Draw(GL gl, GLU glu) {
Vec3d[] normalsPerVertex = new Vec3d[3];
MassPoint vertex1, vertex2, vertex3;
int faceIndex=0;
Face surfaceFace;
for (faceIndex=0; faceIndex<surfaceFaces.size();faceIndex++){
surfaceFace = surfaceFaces.get(faceIndex);
vertex1=surfaceFace.vertex1;
normalsPerVertex[0] = vertex1.CalcNormal();
vertex2=surfaceFace.vertex2;
normalsPerVertex[1] = vertex2.CalcNormal();
vertex3=surfaceFace.vertex3;
normalsPerVertex[2] = vertex3.CalcNormal();
gl.glBegin(GL.GL_TRIANGLES);
gl.glNormal3d(normalsPerVertex[0].x, normalsPerVertex[0].y, normalsPerVertex[0].z);
gl.glVertex3d(vertex1.position.x, vertex1.position.y, vertex1.position.z);
gl.glNormal3d(normalsPerVertex[1].x, normalsPerVertex[1].y, normalsPerVertex[1].z);
gl.glVertex3d(vertex2.position.x, vertex2.position.y, vertex2.position.z);
gl.glNormal3d(normalsPerVertex[2].x, normalsPerVertex[2].y, normalsPerVertex[2].z);
gl.glVertex3d(vertex3.position.x, vertex3.position.y, vertex3.position.z);
gl.glEnd();
}
}
The calculated normal for each vertex is the media of all the faces connected to that vertex. Here's the code for that:
public Vec3d CalcNormal() {
Vec3d normalMedia = new Vec3d();
for (Face face : facesRelated) {
face.recalculateNormal();
normalMedia.add(face.normal);
}
normalMedia.mul(1d/facesRelated.size());
return normalMedia;
}
Hope this helps someone else.

Vertex Attribute Arrays\not receiving vertex data in LWJGL

Cannot seem to get Vertex Attribute Arrays working properly for per vertex data.
Here's the SSCCE:
private static void createDisplay(int w, int h) {
try {
Display.create();
Display.setDisplayMode(new DisplayMode(w, h));
}
catch (LWJGLException e) {
e.printStackTrace();
}
float size = 1;
float aspect = (float) Display.getWidth() / Display.getHeight();
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(-size * aspect, size * aspect, -size, size, -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
}
public static void main(String[] args) {
createDisplay(1200, 800);
GL11.glViewport(0, 0, Display.getWidth(), Display.getHeight());
ShaderManager.createShader("2Dv", new File("src/Shaders/2D.vert"), SHADER_VERT);
ShaderManager.createShader("2Df", new File("src/Shaders/2D.frag"), SHADER_FRAG);
ShaderManager.createProgram("2D", "2Dv", "2Df");
// Shader compiles and links correctly.
ShaderManager.useProgram("2D");
// Calls glUseProgram(programID);
float[] vertexData = new float[] {-0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f};
int vao = GL30.glGenVertexArrays();
if (vao == 0)
System.exit(-1);
GL30.glBindVertexArray(vao);
int vertexBuffer = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertexBuffer);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, BufferUtil.asDirectFloatBuffer(vertexData), GL15.GL_DYNAMIC_DRAW);
// GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
// GL11.glVertexPointer(2, GL11.GL_FLOAT, 2 * 4, 0);
int loc = ShaderManager.currentProgram.getAttribute("vertex");
if (loc == -1)
Debug.log(Debug.INSTANCE_MANAGEMENT, "Attribute [", "", "] not found in Shader [",
ShaderManager.currentProgram.toString(), "].");
else {
GL20.glVertexAttribPointer(loc, 2, GLCONST.TYPE_FLOAT, false, 2 * 4, 0);
GL20.glEnableVertexAttribArray(loc);
}
GL30.glBindVertexArray(0);
GL11.glColor3f(1, 0, 0);
GL11.glClearColor(0.5f, 0.5f, 0.8f, 1);
int indexBuffer = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, BufferUtil.asDirectFloatBuffer(new float[] {0, 1, 2, 3}),
GL15.GL_DYNAMIC_DRAW);
while (!Display.isCloseRequested()) {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL30.glBindVertexArray(vao);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
GL11.glDrawElements(GL11.GL_QUADS, 4, GL11.GL_UNSIGNED_INT, 0);
GL30.glBindVertexArray(0);
Display.update();
int error = GL11.glGetError();
if (error != GL11.GL_NO_ERROR)
System.out.println(GLU.gluErrorString(error));
}
}
The problem lies in the usage of vertex Attribute arrays. The old code I used was:
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GL11.glVertexPointer(2, GL11.GL_FLOAT, 2 * 4, 0);
The new version is:
int loc = ShaderManager.currentProgram.getAttribute("vertex");//Call to glGetAttribLocation();
if (loc == -1){
System.exit(-1);
}
GL20.glVertexAttribPointer(loc, 2, GL11.GL_FLOAT, false, 2 * 4, 0);
GL20.glEnableVertexAttribArray(loc);
The original code was the commented 2 lines. Upon running, this correctly sent vertex data to gl_Vertex and rendered a square of size 1.
The new code shuld send vertex data to the vertex attribute, but it gets nothing.
When the original code is uncommented and both old and new code used, both gl_Vertex and vertex attribute get vertex data.
What is going wrong here?
So I figured out the problem after a while. The problem is due to an AMD driver bug when using a OpenGL 3.0+ core profile.
The "vertex" attribute array was assigned a location of 1.
The bug occurs when the attribute array 0 is unused. Nothing is rendered if array 0 is not enabled.
To fix this probelm I simply explicitly assigned "vertex" to location 0.
layout(location = 0) in vec4 vertex;

Repeating Texture on Model/Mesh

When I just draw texture on SpriteBatch and set TextureWrap.Repeat everything is OK. But now I have 3D scene and I want have ground and texture must be repeated on model/mesh and this just don' t work.
public static StillModel createPlainMesh(float xs, float zs, Texture texture) {
final Mesh mesh = new Mesh(true, 4, 6, new VertexAttribute(
Usage.Position, 3, "a_position"), new VertexAttribute(
Usage.TextureCoordinates, 2, "a_texCoords"));
mesh.setVertices(new float[]
{ xs, 0f, zs, 0, 0,
xs, 0f, -zs, 0, 1,
-xs, 0f, zs, 1, 0,
-xs, 0f, -zs , 1,1
});
mesh.setIndices(new short[] { 0, 1, 2, 1, 2, 3 });
final StillModel model = new StillModel(new StillSubMesh(
"ground", mesh, GL10.GL_TRIANGLES, new Material()));
texture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
model.setMaterial(new Material("material", new TextureAttribute(texture, 0, "s_tex")));
return model;
}
I have this code. I use setWrap(TextureWrap.Repeat, TextureWrap.Repeat), but textures are still streched. I don't know why, but it looks terrible.
I solved it. If you want repeat texture on model, You must modify this:
mesh.setVertices(new float[]
{ xs, 0f, zs, 0, 0,
xs, 0f, -zs, 0, 1,
-xs, 0f, zs, 1, 0,
-xs, 0f, -zs , 1,1
});
Modify Texture Coords - change to for example 20 if You want repeat it 20times
Example:
mesh.setVertices(new float[]
{ xs, 0f, zs, 0, 0,
xs, 0f, -zs, 0, 20,
-xs, 0f, zs, 20, 0,
-xs, 0f, -zs , 20,20
});

Eclipse reporting errors on arrays for Android

I'm trying to get a 3D array initialized for a game I'm working on, after multiple syntax changes I couldn't figure out how to get it to work! What I started with was:
public class AnimationView extends SurfaceView implements SurfaceHolder.Callback {//Create bitmaps.
Bitmap bitmapGoal = BitmapFactory.decodeResource(this.getResources(), R.drawable.goal);
Bitmap bitmapOrig = BitmapFactory.decodeResource(this.getResources(), R.drawable.ball);
Bitmap bitmap = Bitmap.createScaledBitmap(bitmapOrig, 150, 150, true);
//initialize the canvas.
private Canvas c;
private int score[] = {0, 0, 0, 0};
public int numBalls = 1;
//we support up to 4 balls. thus each array is 4 bit.
private int ballX[] = {0, 200, 400, 600};
private double ballY[] = {0, 0, 0, 0};
private double dirV[] = {0, 0, 0, 0};
private int dirH[] = {30, 30, 30, 30};
private static final int SCALE = 10;
private double elasticity = .6;
private int rotationNow[] = {5, 5, 5, 5};
private int rotationDraw[] = {0, 0, 0, 0};
class AnimationThread extends Thread {
//Are we running currently?
private boolean mRun;
//layer 1 is how many balls, 4 layers deep.
//layer 2 is which ball we're talking about, either 1, 2, 3, or 4 layers deep, depending on layer 1.
//layer 3 is the bounds of the ball, dependent on how many there are total.
//layer 3 is formatted x-min, x-max, y-min, y-max
int[][][] bounds = new int[][][] {
{ {0, c.getWidth() - bitmap.getWidth(), 0, c.getHeight() - bitmap.getHeight()}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} },
//end first layer
{ {0, c.getWidth() / 2 - bitmap.getWidth(), 0, c.getHeight() - bitmap.getHeight()}, {c.getWidth() / 2, c.getWidth() - bitmap.getWidth(), 0, c.getHeight() - bitmap.getHeight()}, {0, 0, 0, 0}, {0, 0, 0, 0} },
//end second layer
{ {0, c.getWidth() / 3 - bitmap.getWidth(), 0, c.getHeight() - bitmap.getHeight()}, {c.getWidth() / 3, c.getWidth() * 2 / 3 - bitmap.getWidth(), 0, c.getHeight() - bitmap.getHeight()}, {c.getWidth() * 2 / 3, c.getWidth() - bitmap.getWidth(), 0, c.getHeight() - bitmap.getHeight()}, {0, 0, 0, 0} },
//end third layer
{ {0, c.getWidth() / 2, 0, c.getHeight() / 2}, {c.getWidth() / 2, c.getWidth(), 0, c.getHeight() / 2}, {0, c.getWidth() / 2, c.getHeight() / 2, c.getHeight()}, {c.getWidth() / 2, c.getWidth(), c.getHeight() / 2, c.getHeight()} }
//end fourth, and final layer!
};
Sorry about the weird formatting error. I know this doesn't help anything. There is a new line between ymax and int[][][].
You don't exactly need to look through it and understand, but this compiled and then errored out during execution. So then I tried to make a simple 3D array, I started with:
int[][][] bounds = new int[1][1][1];
bounds[0][0][0] = 0;
Eclipse had it's red squiggly under the semi-colon on the first line. Saying
'Syntax error on token ";", { expected after this token'
This is where it gets frustrating. Because that exact same code copy/pasted into a regular Java program works fine, but I can NOT get it to work inside an Android project. I then simplified some stuff, to this:
int[] bounds = new int[1];
bounds[0] = 0;
Exact same error, exact same place! Why Eclipse?? I also tried it with "int bounds[][][]" as opposed to "int[][][] bounds" but no difference, still same error.
I've rebooted my computer, cleaned my project multiple times, restarted Eclipse. I'm out of ideas. Do you have any??
Well, seems like the problem is not before, but after the code you pasted.
this assignment - bounds[0][0][0] = 0; is probably not in any method and this is illegal. When Eclipse sees an expression that need to be inside a method, it expects the line above to be the method declaration, so it expects '{' as a beginning of a method block, and not ';'
Ok, I feel ridiculous. After being very, very confused at why the variable couldn't initialize and why the very simple code then wouldn't compile. It turns out, though the canvas and bitmaps were available, it was infact them returning null values into the array.
So I got it working now.
Also, for my first question here, I was extremely impressed with the speediness of the solutions. Thanks a ton!
int[][][] bounds = new int[1][1][1];
bounds[0][0][0] = 0;
I copied these two lines and seem to be compiling fine.
I think you might have forgot to comment the earlier declaration of bounds . (or) you might be missing braces or something like that

Categories

Resources