Forum Stats

  • 3,837,493 Users
  • 2,262,264 Discussions
  • 7,900,305 Comments

Discussions

QuadArrays won't take lightning

Tobias Ronge
Tobias Ronge Member Posts: 2
edited Dec 28, 2016 10:07AM in Java 3D

Hello all.

I have a problem with a Java3D project where my ground object turns completetly illuminated instead of being lit according to my directional light. The spheres in my scene are, however, correctly lit. I have generated normals and checked them.

Here is my code (I apologize for it being not very well structured):

package svets;import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.GraphicsConfiguration;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;import javax.media.j3d.Appearance;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.Bounds;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.DirectionalLight;
import javax.media.j3d.Light;
import javax.media.j3d.Locale;
import javax.media.j3d.Material;
import javax.media.j3d.PhysicalBody;
import javax.media.j3d.PhysicalEnvironment;
import javax.media.j3d.QuadArray;
import javax.media.j3d.Shape3D;
import javax.media.j3d.Texture;
import javax.media.j3d.TextureAttributes;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.media.j3d.ViewPlatform;
import javax.media.j3d.VirtualUniverse;
import javax.vecmath.Color3f;
import javax.vecmath.Point2f;
import javax.vecmath.Point3d;
import javax.vecmath.Point3f;
import javax.vecmath.Tuple2f;
import javax.vecmath.Vector2f;
import javax.vecmath.Vector3f;import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.GeometryInfo;
import com.sun.j3d.utils.geometry.NormalGenerator;
import com.sun.j3d.utils.geometry.Sphere;
import com.sun.j3d.utils.image.TextureLoader;
import com.sun.j3d.utils.picking.PickIntersection;
import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.picking.PickTool;
import com.sun.j3d.utils.picking.behaviors.PickMouseBehavior;
import com.sun.j3d.utils.universe.SimpleUniverse;
import com.sun.j3d.utils.universe.Viewer;
import com.sun.j3d.utils.universe.ViewingPlatform;public class Main extends Applet implements KeyListener, MouseListener{
private static final long serialVersionUID = 4118752675729892756L;

// Map
private float[][] map;
private QuadArray[][] ground;
public final int MAP_SIZE = 64;
private static final float[] tcoords = {0.0f,0.0f,0.0f,1.0f,1.0f,1.0f,1.0f,0.0f};

// Camera
private float x = 32.0f, y = 3.0f, z = 32.0f, a=0.0f;
private float speed = 1.0f;

// Car
private float car_x = 16f, car_y = 0.0f, car_z = 16f;
private float car_x_target = 16f, car_z_target = 16f;
private TransformGroup tg_car;
private boolean marked = false;
private float car_width = 0.2f, car_length = 0.2f;
private Sphere car;

// Keys
private boolean isDownW = false, isDownS = false, isDownA = false, isDownD = false, isDownK=false,isDownL=false;;

private Transform3D transform;
private Canvas3D c;
private VirtualUniverse universe;
private BranchGroup scene;
private BoundingSphere bounds;public Main()
{
setLayout(new BorderLayout());
GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
c = new Canvas3D(config);
add("Center",c);
c.addKeyListener(this);
c.addMouseListener(this); transform = new Transform3D();
//transform.setTranslation(new Vector3f(x,y,z)); universe = new VirtualUniverse(); ViewPlatform viewPlatform = new ViewPlatform();
Transform3D transRot = new Transform3D();
Transform3D transRotBase = new Transform3D();
Transform3D tgMove = new Transform3D();

transRot.rotX(-Math.PI/4);
transform.mul(transRot); ViewingPlatform viewingPlatform = new ViewingPlatform(3);
viewingPlatform.getMultiTransformGroup().getTransformGroup(0).setTransform(tgMove);
viewingPlatform.getMultiTransformGroup().getTransformGroup(1).setTransform(transRotBase);
viewingPlatform.getMultiTransformGroup().getTransformGroup(2).setTransform(transform);
viewingPlatform.setViewPlatform(viewPlatform);
Canvas3D[] canvas3DArray = new Canvas3D[0];
Viewer viewer = new Viewer(canvas3DArray, new PhysicalBody(), new PhysicalEnvironment(), false);
viewer.setViewingPlatform(viewingPlatform);
Locale locale = new Locale(universe);
viewer.getView().addCanvas3D(c);
c.setVisible(true);
scene = createSceneGraph(); // Create materials
Appearance planeAppearance = new Appearance();

Material mat = new Material();
//mat.setAmbientColor(new Color3f(1.0f,1.0f,1.0f));
mat.setDiffuseColor(new Color3f(0.7f,0.7f,0.7f));
mat.setSpecularColor(new Color3f(0.7f,0.7f,0.7f));
mat.setLightingEnable(true);
planeAppearance.setMaterial(mat);

Texture tex = new TextureLoader("GrassGreenTexture0001.jpg",this).getTexture();

planeAppearance.setTexture(tex);

TextureAttributes texAtt = new TextureAttributes();
Transform3D transTex = new Transform3D();
transTex.setScale(1.0f);
texAtt.setTextureTransform(transTex);
planeAppearance.setTextureAttributes(texAtt);


// Create map
map = new float[MAP_SIZE+1][MAP_SIZE+1];
for(int i=0;i<MAP_SIZE+1;i++){
  for(int j=0;j<MAP_SIZE+1;j++){
   map[i][j] = 0;
  }
}
map[32][32] = 1.5f;
map[33][32] = 1f;
map[32][33] = 1f;
map[33][33] = 0.5f;
for(int i=0;i<MAP_SIZE;i++)
  map[0][i] = 1.5f;
map[1][0] = 1.5f;
map[MAP_SIZE-1][0] = 1.5f;
for(int i=0;i<MAP_SIZE+1;i++)
  map[MAP_SIZE][i] = 1.5f;

//PolygonAttributes p = new PolygonAttributes(); 
//p.setPolygonMode(PolygonAttributes.POLYGON_LINE);
//planeAppearance.setPolygonAttributes(p); //Color3f planeColor = new Color3f (1.0f, 1.0f, 1.0f);
//ColoringAttributes planeCA = new ColoringAttributes (planeColor, 1);
//planeAppearance.setColoringAttributes(planeCA);

NormalGenerator ng = new NormalGenerator();

// Create ground
ground = new QuadArray[MAP_SIZE][MAP_SIZE]; for(int i=0;i<MAP_SIZE;i++){
  for(int j=0;j<MAP_SIZE;j++){
   ground[i][j] = new QuadArray(4,QuadArray.COORDINATES | QuadArray.NORMALS | QuadArray.TEXTURE_COORDINATE_2);
   ground[i][j].setCoordinate(0, new Point3f(i, map[i][j], j));
   ground[i][j].setCoordinate(1, new Point3f(i, map[i][j+1], j+1));
   ground[i][j].setCoordinate(2, new Point3f(i+1, map[i+1][j+1], j+1));
   ground[i][j].setCoordinate(3, new Point3f(i+1, map[i+1][j],j));   Shape3D geo;

    ground[i][j].setTextureCoordinates(0,0,tcoords);
    GeometryInfo gi = new GeometryInfo(ground[i][j]);
    ng.generateNormals(gi);
    ground[i][j].setNormals(0, gi.getNormals());
    geo = new Shape3D(ground[i][j],planeAppearance);
  
   geo.setBounds(bounds);
   geo.setBoundsAutoCompute(false);
   scene.addChild(geo);
  }
} // Finalize
TransformGroup tempGroup = new TransformGroup();
scene.addChild(tempGroup);
tempGroup.addChild(viewingPlatform); ExamplePickBehavior behavior = new ExamplePickBehavior(c, scene, bounds);
scene.addChild(behavior);

locale.addBranchGraph(scene);


// Create viewport
new MainFrame(this,1024,768);
while(true){
  try {
   Thread.sleep(50);
  
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 
  if(isDownW){
   z -= speed*(float)Math.sin(Math.PI/2+a);
   x += speed*(float)Math.cos(Math.PI/2+a);
  }
  if(isDownS){
   z += speed*(float)Math.sin(Math.PI/2+a);
   x -= speed*(float)Math.cos(Math.PI/2+a);
  }
  if(isDownA){
   z -= speed*Math.sin(-a);
   x -= speed*Math.cos(-a);
  }
  if(isDownD){
   z += speed*Math.sin(-a);
   x += speed*Math.cos(-a);
  }
  if(isDownK){
   a+=0.1f;
   transRotBase.rotY(a);
  }
  if(isDownL){
   a-=0.1f;
   transRotBase.rotY(a);
  }
 
  tgMove.setTranslation(new Vector3f(x,y,z));
 
  if(Math.sqrt(Math.pow(car_x-car_x_target, 2)+Math.pow(car_z-car_z_target,2))>0.05){
   float a = (float) Math.atan(Math.abs(car_z-car_z_target)/Math.abs(car_x-car_x_target));
   if(car_z>car_z_target){
    car_z -= 0.05*Math.sin(a);
   } else {
    car_z += 0.05*Math.sin(a);
   }
   if(car_x>car_x_target){
    car_x -= 0.05*Math.cos(a);
   } else {
    car_x += 0.05*Math.cos(a);
   }   if(car_z-(int)car_z>=car_x-(int)car_x){
    Point2f p_a=new Point2f((int)car_x,(int)car_z),p_b=new Point2f((int)car_x+1,(int)car_z+1),p_c=new Point2f ((int)car_x,(int)car_z+1),p_p=new Point2f(car_x,car_z);;
    Vector3f v = getBarycentricCoordinates(p_a,p_b,p_c,p_p);
    car_y = v.x*map[(int)car_x][(int)car_z] + v.y*map[(int)car_x+1][(int)car_z+1] + v.z*map[(int)car_x][(int)car_z+1];
   } else {
    Point2f p_a=new Point2f((int)car_x,(int)car_z),p_b=new Point2f((int)car_x+1,(int)car_z),p_c=new Point2f ((int)car_x+1,(int)car_z+1),p_p=new Point2f(car_x,car_z);
    Vector3f v = getBarycentricCoordinates(p_a,p_b,p_c,p_p);
    car_y = v.x*map[(int)car_x][(int)car_z] + v.y*map[(int)car_x+1][(int)car_z] + v.z*map[(int)car_x+1][(int)car_z+1];
   }
  
  }
 
  Transform3D transform_car = new Transform3D();
  transform_car.setTranslation(new Vector3f(car_x,car_y,car_z));
  tg_car.setTransform(transform_car);
 
  viewingPlatform.getMultiTransformGroup().getTransformGroup(0).setTransform(tgMove);
  viewingPlatform.getMultiTransformGroup().getTransformGroup(1).setTransform(transRotBase);
  viewingPlatform.getMultiTransformGroup().getTransformGroup(2).setTransform(transform);
}

}private BranchGroup createSceneGraph(){
BranchGroup objRoot = new BranchGroup();
Sphere s = new Sphere(0.5f);
objRoot.addChild(s);

car = new Sphere(0.1f);

Transform3D carTransform = new Transform3D();
carTransform.setTranslation(new Vector3f(16f,0,16f));
tg_car = new TransformGroup(carTransform);
tg_car.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
tg_car.addChild(car);
objRoot.addChild(tg_car);

Color3f light1color = new Color3f(0.5f,0.5f,0.5f);

bounds = new BoundingSphere(new Point3d(0.0f,0.0f,0.0f), 100.0f);

Vector3f light1direction = new Vector3f(0.0f,-1.0f,0.0f);
DirectionalLight light1 = new DirectionalLight(light1color,light1direction);
light1.setInfluencingBounds(bounds);
light1.setBoundsAutoCompute(false);
light1.setCapability(Light.ALLOW_INFLUENCING_BOUNDS_READ);
objRoot.addChild(light1); return objRoot;
}public static void main( String[] args ) {
new Main();
}
@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyChar()=='a'){
  isDownA = true;
}
if(arg0.getKeyChar()=='d'){
  isDownD = true;
}
if(arg0.getKeyChar()=='z'){
  y += speed;
}
if(arg0.getKeyChar()=='x'){
  y -= speed;
}
if(arg0.getKeyChar()=='s'){
 
  isDownS = true;
}
if(arg0.getKeyChar()=='w'){
  isDownW = true;
}
if(arg0.getKeyChar()=='k'){
 
  isDownK = true;
}
if(arg0.getKeyChar()=='l'){
  isDownL = true;
}}
@Override
public void keyReleased(KeyEvent arg0) {
if(arg0.getKeyChar()=='a'){
  isDownA = false;
}
if(arg0.getKeyChar()=='d'){
  isDownD = false;
}
if(arg0.getKeyChar()=='s'){
  isDownS = false;
}
if(arg0.getKeyChar()=='w'){
  isDownW = false;
}
if(arg0.getKeyChar()=='k'){
 
  isDownK = false;
}
if(arg0.getKeyChar()=='l'){
  isDownL = false;
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
@}@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub

@}@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

@}@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

@}@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
@}@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}private Vector2f subtractVectors(Tuple2f v1, Tuple2f v2){
Vector2f t = new Vector2f();
t.setX(v1.x-v2.x);
t.setY(v1.y-v2.y);
return t;
}private Vector3f getBarycentricCoordinates(Tuple2f a,Tuple2f b,Tuple2f c,Tuple2f p){
Vector2f v0 = subtractVectors(b,a);
Vector2f v1 = subtractVectors(c,a);
Vector2f v2 = subtractVectors(p,a);
float d00 = v0.dot(v0);
float d01 = v0.dot(v1);
float d11 = v1.dot(v1);
float d20 = v2.dot(v0);
float d21 = v2.dot(v1);
float denom = d00 * d11 - d01 * d01;
float v = (d11 * d20 - d01 * d21) / denom;
    float w = (d00 * d21 - d01 * d20) / denom;
    float u = 1.0f - v - w;
    return new Vector3f(u,v,w);
}private class ExamplePickBehavior extends PickMouseBehavior
@{    @SuppressWarnings("deprecation")
public ExamplePickBehavior(Canvas3D canvas, BranchGroup bg, Bounds bounds)
    {
        super(canvas, bg, bounds);
        setSchedulingBounds(bounds);        pickCanvas.setMode(PickTool.GEOMETRY_INTERSECT_INFO);
        // allows PickIntersection objects to be returned
    }    public void updateScene(int xpos, int ypos)
    {
     System.out.println("xpos: "+xpos+" ypos: "+ypos);
        pickCanvas.setShapeLocation(xpos, ypos);
        // register mouse pointer location on the screen (canvas)        Point3d eyePos = pickCanvas.getStartPosition();
        // get the viewer's eye location        PickResult pickResult = null;
        pickResult = pickCanvas.pickClosest();        if (pickResult != null) {
            PickIntersection pi = pickResult.getClosestIntersection(eyePos);
            // get the closest intersect to the eyePos point
            Point3d intercept = pi.getPointCoordinatesVW();
            System.out.println(intercept);
           
            if(intercept.x > car_x-car_width/2-0.01 && intercept.x < car_x+car_width/2+0.01
              && intercept.z > car_z-car_length/2-0.01 && intercept.z < car_z+car_length/2+0.01
    
              ){
             marked = true;
             System.out.println("Hit!");
            } else if (marked){
             car_x_target = (float) intercept.x;
             car_z_target = (float) intercept.z;
            
            }
            // extract the intersection pt in scene coords space
            // use the intersection pt in some way...
        }
    } // end of updateScene(  )
} // end of ExamplePickBehavior class
}

I'm thankful for all the help I can get.

Answers

This discussion has been closed.