jmonkeyengine movement too fast for collision detection - java

I am making a Java game using JMonkeyEngine and I have followed the tutorial on their site to shoot balls (bullets) at a wall. I get how everything works, but when I increase the velocity of the bullet, it passes straight through the wall.
Now I know the reason why this is happening (because the bullet moves too fast per frame for collision to register). I also know how to solve for this and I have found the following method on their website (JMonkeyEngine).
setCcdMotionThreshold(0f)
But can anyone tell me how this is implemented or where I can find a sample of someone using this?

Introduction
Continuous collision detection (ccd) deals with the bullet vs paper problem. Where a fast moving object is one side of a thin object at one timestep and the other side at the next time step leading to the physics engine believing that no collision has occurred at all. Continuous collision detection on the other hand doesn't use time steps at all. It creates a swept volume over the entire period of the timestep and finds if that swept volume collides with anything. This is both expensive and inaccurate (because a simple circular collision shape is used for this rather than the full collision shape).
Usage
Continuous collision detection is set on a per object basic, you can have objects that use ccd and objects that don't in the same scene at the same time, ccd is set on a physics object as shown below
RigidBodyControl physicsObject = new RigidBodyControl(mass);
physicsObject.setCcdMotionThreshold(expectedWidthOfThinObject);
physicsObject.setCcdSweptSphereRadius(radiusOfSphereThatWillFullyContainObject);
You want to set expectedWidthOfThinObject as high you can get away
with; remember ccd is expensive and inaccurate. Setting it as zero will turn ccd off
You want to set radiusOfSphereThatWillFullyContainObject as small as possible while fully containing the object
Full example
The following source code will show the difference between using Continuous Collision Detection and using the standard collision detection. It fires two sets of balls, one fast and one slow and turns ccd on and off at 5 second intervals. The slow balls always collide with the paper, the fast ones only when ccd is turned on.
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.font.BitmapText;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;
public class BulletTest extends SimpleApplication {
public static void main(String args[]) {
BulletTest app = new BulletTest();
app.start();
}
/** Prepare the Physics Application State (jBullet) */
private BulletAppState bulletAppState;
/** Prepare Materials */
Material wall_mat;
Material slow_mat;
Material fast_mat;
Material floor_mat;
private RigidBodyControl brick_phy;
private static final Box box;
private static final Sphere sphere;
private RigidBodyControl floor_phy;
private static final Box floor;
/** dimensions used for wall */
private static final float brickLength = 2f;
private static final float brickWidth = 0.015f;
private static final float brickHeight = 1f;
static {
/** Initialize the cannon ball geometry */
sphere = new Sphere(32, 32, 0.1f, true, false);
/** Initialize the brick geometry */
box = new Box(brickWidth, brickHeight, brickLength);
/** Initialize the floor geometry */
floor = new Box(10f, 0.1f, 5f);
}
#Override
public void simpleInitApp() {
/** Set up Physics Game */
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
//bulletAppState.getPhysicsSpace().enableDebug(assetManager);
/** Configure cam to look at scene */
cam.setLocation(new Vector3f(0, 4f, 6f));
cam.lookAt(new Vector3f(2, 2, 0), Vector3f.UNIT_Y);
/** Initialize the scene, materials, and physics space */
initMaterials();
initWall();
initFloor();
setUpHUDText();
}
public static final float FIREPERIOD=0.5f;
double fireTimer=0;
public static final float SWEEPPERIOD=5f;
double sweepTimer=0;
boolean continuouslySweeping=true;
#Override
public void simpleUpdate(float tpf) {
fireTimer+=tpf;
sweepTimer+=tpf;
if (sweepTimer>SWEEPPERIOD){
sweepTimer=0;
continuouslySweeping=!continuouslySweeping;
}
hudText.setText("ContinouslySweeping=" + continuouslySweeping + "(" + (int)(SWEEPPERIOD-sweepTimer) + ")" );
if (fireTimer>FIREPERIOD){
fireTimer=0;
makeCannonBall(new Vector3f(-4,3,0),new Vector3f(6,4,0),slow_mat,continuouslySweeping); //slow arcing ball
makeCannonBall(new Vector3f(-4,3,-0.5f),new Vector3f(10,1,0),fast_mat,continuouslySweeping); //fast straight ball
}
}
public BitmapText hudText;
private void setUpHUDText(){
hudText = new BitmapText(guiFont, false);
hudText.setSize(guiFont.getCharSet().getRenderedSize()); // font size
hudText.setColor(ColorRGBA.White); // font color
hudText.setText("ContinouslySweeping=true"); // the text
hudText.setLocalTranslation(300, hudText.getLineHeight(), 0); // position
guiNode.attachChild(hudText);
}
/** Initialize the materials used in this scene. */
public void initMaterials() {
wall_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
wall_mat.setColor("Color", ColorRGBA.Blue);
fast_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
fast_mat.setColor("Color", ColorRGBA.Red);
slow_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
slow_mat.setColor("Color", ColorRGBA.Green);
floor_mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
floor_mat.setColor("Color", ColorRGBA.Gray);
}
/** Make a solid floor and add it to the scene. */
public void initFloor() {
Geometry floor_geo = new Geometry("Floor", floor);
floor_geo.setMaterial(floor_mat);
floor_geo.setLocalTranslation(0, -0.1f, 0);
this.rootNode.attachChild(floor_geo);
/* Make the floor physical with mass 0.0f! */
floor_phy = new RigidBodyControl(0.0f);
floor_geo.addControl(floor_phy);
bulletAppState.getPhysicsSpace().add(floor_phy);
}
/** This loop builds a wall out of individual bricks. */
public void initWall() {
Vector3f location=new Vector3f(2,2,0);
Geometry brick_geo = new Geometry("brick", box);
brick_geo.setMaterial(wall_mat);
rootNode.attachChild(brick_geo);
/** Position the brick geometry */
brick_geo.setLocalTranslation(location);
//paper thin objects will fall down, mass 0 clamps it in position
brick_phy = new RigidBodyControl(0);
/** Add physical brick to physics space. */
brick_geo.addControl(brick_phy);
bulletAppState.getPhysicsSpace().add(brick_phy);
}
public void makeCannonBall(Vector3f startPoint, Vector3f initialVelocity, Material material, boolean continuouslySwept) {
/** Create a cannon ball geometry and attach to scene graph. */
Geometry ball_geo = new Geometry("cannon ball", sphere);
ball_geo.setMaterial(material);
rootNode.attachChild(ball_geo);
/** Position the cannon ball */
ball_geo.setLocalTranslation(startPoint);
/** Make the ball physcial with a mass > 0.0f */
RigidBodyControl ball_phy = new RigidBodyControl(1f);
/** Add physical ball to physics space. */
ball_geo.addControl(ball_phy);
bulletAppState.getPhysicsSpace().add(ball_phy);
/** Accelerate the physcial ball to shoot it. */
ball_phy.setLinearVelocity(initialVelocity);
if (continuouslySwept){
ball_phy.setCcdMotionThreshold(0.015f);
ball_phy.setCcdSweptSphereRadius(0.01f);
}
}
}
With continuous detection on both sets of balls bounce of as expected (balls entering from the top left):
With continuous detection off the fast set of balls (red) passes through the paper as if it wasn't there (and very occasionally a slow one (green) does too):
NB: this code is loosely based on the hello physics code with added functionality from advanced physics

Related

Why does my custom Swing component repaint faster when I move the mouse? (Java)

I am trying to make a 2D game with Java and Swing, and the window refreshes too slow. But if I move the mouse or press keys, the window refreshes as fast as it should!
Here is a GIF showing how the window refreshes quickly only when I move the mouse.
Why does the window refresh slowly like that? Why does the mouse and keyboard affect its refresh rate? How, if possible, do I make it refresh quickly all the time?
Background Info
I use a javax.swing.Timer to update the game state every 1/25 seconds, after which it calls repaint() on the game panel to redraw the scene.
I understand that a Timer might not always delay for exactly 1/25 of a second.
I also understand that calling repaint() just requests the window to be repainted ASAP and does not repaint the window immediately.
My graphics card does not support OpenGL 2+ or hardware accelerated 3D graphics, which is why I am not using libgdx or JME for game development.
System Info
Operating system: Linux Mint 19 Tara
JDK version: OpenJDK 11.0.4
Graphics card: Intel Corporation 82945G/GZ
Research
This Stack Overflow user describes the same problem I have, but the author reportedly solved the issue by calling repaint() repeatedly on a separate timer. I tried this, and it does make the window refresh somewhat faster, but even then it is a slower than I want. In this case, wiggling the mouse on the window still improves the refresh rate. Therefore, it seems like that post did not truly solve the issue.
Another Stack Overflow user also encountered the issue, but they use a continuous while-loop instead of a Timer for their game loop. Apparently, this user solved the problem by using Thread.sleep() in their while loop. However, my code accomplishes the delay using a Timer, so I do not know how Thread.sleep() could solve my problem, or even where I would put it.
I've read through Painting with AWT and Swing to figure out whether I just misunderstood the concept of repainting, but nothing in that document elucidates the issue for me. I call repaint() whenever the game updates, and the window only refreshes quickly when mouse or keyboard input is happening.
I have searched the web for several days now trying to find an answer, but nothing seems to help!
Code
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
class Game {
public static final int screenWidth = 160;
public static final int screenHeight = 140;
/**
* Create and show the GUI.
*/
private static void createAndShowGUI() {
/* Create the GUI. */
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.getContentPane().add(new GamePanel());
frame.pack();
/* Show the GUI. */
frame.setVisible(true);
}
/**
* Run the game.
*
* #param args the list of command-line arguments
*/
public static void main(String[] args) {
/* Schedule the GUI to be created on the EDT. */
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
}
/**
* A GamePanel widget updates and shows the game scene.
*/
class GamePanel extends JPanel {
private Square square;
/**
* Create a game panel and start its update-and-draw cycle
*/
public GamePanel() {
super();
/* Set the size of the game screen. */
setPreferredSize(
new Dimension(
Game.screenWidth,
Game.screenHeight));
/* Create the square in the game world. */
square = new Square(0, 0, 32, 32, Square.Direction.LEFT);
/* Update the scene every 40 milliseconds. */
Timer timer = new Timer(40, (e) -> updateScene());
timer.start();
}
/**
* Paint the game scene using a graphics context.
*
* #param g the graphics context
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
/* Clear the screen. */
g.setColor(Color.WHITE);
g.fillRect(0, 0, Game.screenWidth, Game.screenHeight);
/* Draw all objects in the scene. */
square.draw(g);
}
/**
* Update the game state.
*/
private void updateScene() {
/* Update all objects in the scene. */
square.update();
/* Request the scene to be repainted. */
repaint();
}
}
/**
* A Square is a game object which looks like a square.
*/
class Square {
public static enum Direction { LEFT, RIGHT };
private int x;
private int y;
private int width;
private int height;
private Direction direction;
/**
* Create a square game object.
*
* #param x the square's x position
* #param y the square's y position
* #param width the square's width (in pixels)
* #param height the square's height (in pixels)
* #param direction the square's direction of movement
*/
public Square(int x,
int y,
int width,
int height,
Direction direction) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.direction = direction;
}
/**
* Draw the square using a graphics context.
*
* #param g the graphics context
*/
public void draw(Graphics g) {
g.setColor(Color.RED);
g.fillRect(x, y, width, height);
g.setColor(Color.BLACK);
g.drawRect(x, y, width, height);
}
/**
* Update the square's state.
*
* The square slides horizontally
* until it reaches the edge of the screen,
* at which point it begins sliding in the
* opposite direction.
*
* This should be called once per frame.
*/
public void update() {
if (direction == Direction.LEFT) {
x--;
if (x <= 0) {
direction = Direction.RIGHT;
}
} else if (direction == Direction.RIGHT) {
x++;
if (x + width >= Game.screenWidth) {
direction = Direction.LEFT;
}
}
}
}
I guess you probably cannot solve your issue by enabling OpenGL, since your gpu does not support it, a possible silly workaround could be to fire a kind of event manually in each timer's iteration.
/* Update the scene every 40 milliseconds. */
final Robot robot = new Robot();
Timer timer = new Timer(40, (e) -> {
robot.mouseRelease(0); //some event
updateScene();
});
timer.start();
(And the only place you can Thread.sleep() in a Swing Application is inside a SwingWorker's doInBackground method. If you call it in EDT the whole GUI will freeze since events cannot take place.)
I ran into the same issue. The solution is quite simple. Call revalidate() immediately after you call repaint():
private void updateScene() {
/* Update all objects in the scene. */
square.update();
/* Request the scene to be repainted. */
repaint();
revalidate(); // <-- this will now repaint as fast as you wanted it to
}

JMonkey Endless Terrain Example: How to change the render distance

The Jmoneky Engine gives example code for endless randomly generated Terrain. My Problem is, the code has no comments or indicators to edit the View distance. I am trying to use this example code to build a game, but it looks really bad if the render distance is so short you can see the bottom of the world(void)
The Code:
public class TerrainFractalGridTest extends SimpleApplication {
private Material mat_terrain;
private TerrainGrid terrain;
private float grassScale = 64;
private float dirtScale = 16;
private float rockScale = 128;
public static void main(final String[] args) {
TerrainFractalGridTest app = new TerrainFractalGridTest();
app.start();
}
private CharacterControl player3;
private FractalSum base;
private PerturbFilter perturb;
private OptimizedErode therm;
private SmoothFilter smooth;
private IterativeFilter iterate;
#Override
public void simpleInitApp() {
this.flyCam.setMoveSpeed(100f);
ScreenshotAppState state = new ScreenshotAppState();
this.stateManager.attach(state);
// TERRAIN TEXTURE material
this.mat_terrain = new Material(this.assetManager, "Common/MatDefs/Terrain/HeightBasedTerrain.j3md");
// Parameters to material:
// regionXColorMap: X = 1..4 the texture that should be appliad to state X
// regionX: a Vector3f containing the following information:
// regionX.x: the start height of the region
// regionX.y: the end height of the region
// regionX.z: the texture scale for the region
// it might not be the most elegant way for storing these 3 values, but it packs the data nicely :)
// slopeColorMap: the texture to be used for cliffs, and steep mountain sites
// slopeTileFactor: the texture scale for slopes
// terrainSize: the total size of the terrain (used for scaling the texture)
// GRASS texture
Texture grass = this.assetManager.loadTexture("Textures/Terrain/splat/grass.jpg");
grass.setWrap(WrapMode.Repeat);
this.mat_terrain.setTexture("region1ColorMap", grass);
this.mat_terrain.setVector3("region1", new Vector3f(15, 200, this.grassScale));
// DIRT texture
Texture dirt = this.assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg");
dirt.setWrap(WrapMode.Repeat);
this.mat_terrain.setTexture("region2ColorMap", dirt);
this.mat_terrain.setVector3("region2", new Vector3f(0, 20, this.dirtScale));
// ROCK texture
Texture rock = this.assetManager.loadTexture("Textures/Terrain/Rock2/rock.jpg");
rock.setWrap(WrapMode.Repeat);
this.mat_terrain.setTexture("region3ColorMap", rock);
this.mat_terrain.setVector3("region3", new Vector3f(198, 260, this.rockScale));
this.mat_terrain.setTexture("region4ColorMap", rock);
this.mat_terrain.setVector3("region4", new Vector3f(198, 260, this.rockScale));
this.mat_terrain.setTexture("slopeColorMap", rock);
this.mat_terrain.setFloat("slopeTileFactor", 32);
this.mat_terrain.setFloat("terrainSize", 513);
this.base = new FractalSum();
this.base.setRoughness(0.7f);
this.base.setFrequency(1.0f);
this.base.setAmplitude(1.0f);
this.base.setLacunarity(2.12f);
this.base.setOctaves(8);
this.base.setScale(0.02125f);
this.base.addModulator(new NoiseModulator() {
#Override
public float value(float... in) {
return ShaderUtils.clamp(in[0] * 0.5f + 0.5f, 0, 1);
}
});
FilteredBasis ground = new FilteredBasis(this.base);
this.perturb = new PerturbFilter();
this.perturb.setMagnitude(0.119f);
this.therm = new OptimizedErode();
this.therm.setRadius(5);
this.therm.setTalus(0.011f);
this.smooth = new SmoothFilter();
this.smooth.setRadius(1);
this.smooth.setEffect(0.7f);
this.iterate = new IterativeFilter();
this.iterate.addPreFilter(this.perturb);
this.iterate.addPostFilter(this.smooth);
this.iterate.setFilter(this.therm);
this.iterate.setIterations(1);
ground.addPreFilter(this.iterate);
this.terrain = new TerrainGrid("terrain", 33, 129, new FractalTileLoader(ground, 256f));
this.terrain.setMaterial(this.mat_terrain);
this.terrain.setLocalTranslation(0, 0, 0);
this.terrain.setLocalScale(2f, 1f, 2f);
this.rootNode.attachChild(this.terrain);
TerrainLodControl control = new TerrainGridLodControl(this.terrain, this.getCamera());
control.setLodCalculator(new DistanceLodCalculator(33, 2.7f)); // patch size, and a multiplier
this.terrain.addControl(control);
this.getCamera().setLocation(new Vector3f(0, 300, 0));
this.viewPort.setBackgroundColor(new ColorRGBA(0.7f, 0.8f, 1f, 1f));
}
#Override
public void simpleUpdate(final float tpf) {
}}
So following what J Atkin said about Terrain Grid, I found a endless terrain example that is a terrain grid. The Cells loaded class is protected, which means I have to extends it in the class to access it. In Jmonkey, the main class has to extend a simple application in order to run. Java doesn't allow multiple extensions, therefor I build a second class to allow access.
public class ViewTerrain extends TerrainGrid{
public void setView(int numberofcells){
super.cellsLoaded = numberofcells;
}
}
problem I am having with this class is that I don't know how to keep the original declaration IE.
this.terrain = new TerrainGrid("terrain", 65, 257, new ImageTileLoader(assetManager, new Namer() {
public String getName(int x, int y) {
return "Scenes/TerrainMountains/terrain_" + x + "_" + y + ".png";
}
}));
Looking at the source it seems TerrainGrid dynamically redefines an internal TerrainQuad tree based upon which grid the camera is in and the surrounding grid tiles. It would seem to me that you should define these tiles to be the size of the area you would like visible at any one time. Try updating patchSize in the constructor to be larger.

Java collision detection between two Shape objects?

I would like to know the best way to tell if a Shape object intersects another shape.
Currently I have collision detection in my game sorted out as long as it involves a Shape intersecting a Rectangle or vice versa. The problem I'm having is that the intersects() method in the Shape class can only take a Rectangle or a Point as a parameter, not another Shape. Is there an efficient way to test if two Shape objects are overlapping in any way?
One way I tried was using a for loop to generate an area of points to test if they were in the shape, and then building an array of Point objects to send to the other shape to test, but this significantly dropped my framerate because of all of the unnecessary comparisons.
I looked and looked for something similar on here but didn't find anything really. Sorry in advance if this is a repeat.
Not tested, but why not:
import java.awt.geom.Area;
...
public static boolean testIntersection(Shape shapeA, Shape shapeB) {
Area areaA = new Area(shapeA);
areaA.intersect(new Area(shapeB));
return !areaA.isEmpty();
}
Area implements Shape, but adds some potentially useful methods
You can also use the bounds of the shape itself and then compare the bounds:
public boolean collidesWith(Shape other) {
return shape.getBounds2D().intersects(other.getBounds2D());
}
This is a bit nicer on the eyes.
Even though user2221343 already answered Monkeybro10's question, I thought it might be helpful in some cases to know, that the outline of a shape might play a role if you use his described technique:
For example, if you draw two polygons, the collision of them won't be detected if it occurs only on the exact outline of the polygons. Only, if the areas that are included inside the polygons' outlines will overlap, the collision is detected.
If you fill two polygons, but don't draw them, the collision will be detected even on the outline of the visible area.
I wrote a small example to show what I mean. Either uncomment the draw or fill command, and rise the second polygon vertically by one pixel by uncommenting the given line. Run the code and watch the result in the JFrame. If the second Polygon is risen, and both polygons are only visible by the "fill" command, they intersect with their outlines and collision is detected. If the second polygon is not risen, and both polygons are visible by the "draw" command, they intersect with their outlines but collision is not detected:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.geom.Area;
import javax.swing.JFrame;
public class Test {
private JFrame frame;
private Polygon polygon1;
private Polygon polygon2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame(){
private static final long serialVersionUID = 1L;
#Override
public void paint(Graphics g){
super.paint(g);
doDrawing(g);
}
};
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int nShape1 = 4;
int xPoly1[] = {30,50,50,30};
int yPoly1[] = {30,30,50,50};
polygon1 = new Polygon(xPoly1,yPoly1,nShape1);
int nShape2 = 4;
int xPoly2[] = {35,55,55,35};
int yPoly2[] = {50,50,70,70};
// uncomment next line to rise second polygon vertically by one pixel
//yPoly2[] = {49,49,69,69};
polygon2 = new Polygon(xPoly2,yPoly2,nShape2);
}
public synchronized void doDrawing(Graphics g){
g.setColor(new Color(255,0,0));
// if you draw the polygon, collision on the exact outline won't be detected.
// uncomment draw or fill command to see what I mean.
g.drawPolygon(polygon1);
g.fillPolygon(polygon1);
g.setColor(new Color(0,0,255));
// if you draw the polygon, collision on the exact outline won't be detected.
// uncomment draw or fill command to see what I mean.
g.drawPolygon(polygon2);
g.fillPolygon(polygon2);
Area area = new Area(polygon1);
area.intersect(new Area(polygon2));
if(!area.isEmpty()){
System.out.println("intersects: yes");
}
else{
System.out.println("intersects: no");
}
}
}
If you think the area intersect is too expensive, you could first do a bounds check:
shapeA.getBounds().intersects(shapeB.getBounds())
If this passes, then do the area intersect check.
if( myShape.getBounds().intersects(otherShape.getBounds()) ){
Area a = new Area(myShape);
a.intersect(new Area(otherShape));
if(!a.isEmpty()){
// do something
}
}

JMonkeyEngine : Collision detection on dynamically loaded models

I am learning JME3 and I managed to create my own height map and modifying some of the example code, etc. Now, I created a very simple 4-wall roofless room with Blender, exported it as a Wavefront .Obj file and loaded it unto my scene (I attacked it to the terrain node.
Now, my terrain has a collision detection applied so the player can move and jump around, but it can also walk right through the walls of my model. All the examples I can find loads an already pre-built scene, and I'm still clueless as to why the player goes right through the loaded model?
Sorry for the big code, but I couldn't see how else I could do otherwise. The physics is applied at the section /** 6. Add physics: */ :
public class Main extends SimpleApplication
implements ActionListener {
private BulletAppState bulletAppState;
private RigidBodyControl landscape;
private CharacterControl player;
private Vector3f walkDirection = new Vector3f();
private boolean left = false, right = false, up = false, down = false;
private TerrainQuad terrain;
private Material mat_terrain;
public static void main(String[] args) {
AppSettings settings = new AppSettings(true);
settings.setResolution(1366, 768);
settings.setFullscreen(true);
Main app = new Main();
app.setSettings(settings);
app.setShowSettings(false);
app.start();
}
#Override
public void simpleInitApp() {
/** Set up Physics */
bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
//bulletAppState.getPhysicsSpace().enableDebug(assetManager);
flyCam.setMoveSpeed(200);
setUpKeys();
/** 1. Create terrain material and load four textures into it. */
mat_terrain = new Material(assetManager, "Common/MatDefs/Terrain/Terrain.j3md");
/** 1.1) Add ALPHA map (for red-blue-green coded splat textures) */
mat_terrain.setTexture("Alpha", assetManager.loadTexture("Textures/terrain/island_1_alpha1.png"));
/** 1.2) Add GRASS texture into the red layer (Tex1). */
Texture grass = assetManager.loadTexture("Textures/Terrain/splat/grass.jpg");
grass.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("Tex1", grass);
mat_terrain.setFloat("Tex1Scale", 64f);
/** 1.3) Add DIRT texture into the green layer (Tex2) */
Texture dirt = assetManager.loadTexture("Textures/rocks.jpg");
dirt.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("Tex2", dirt);
mat_terrain.setFloat("Tex2Scale", 32f);
/** 1.4) Add ROAD texture into the blue layer (Tex3) */
Texture rock = assetManager.loadTexture("Textures/Terrain/splat/dirt.jpg");
rock.setWrap(WrapMode.Repeat);
mat_terrain.setTexture("Tex3", rock);
mat_terrain.setFloat("Tex3Scale", 128f);
/** 2. Create the height map */
AbstractHeightMap heightmap = null;
Texture heightMapImage = assetManager.loadTexture("Textures/terrain/island_1.png");
heightmap = new ImageBasedHeightMap(heightMapImage.getImage());
heightmap.load();
/** 3. We have prepared material and heightmap.
* Now we create the actual terrain:
* 3.1) Create a TerrainQuad and name it "my terrain".
* 3.2) A good value for terrain tiles is 64x64 -- so we supply 64+1=65.
* 3.3) We prepared a heightmap of size 512x512 -- so we supply 512+1=513.
* 3.4) As LOD step scale we supply Vector3f(1,1,1).
* 3.5) We supply the prepared heightmap itself.
*/
terrain = new TerrainQuad("my terrain", 65, 513, heightmap.getHeightMap());
/** 4. We give the terrain its material, position & scale it, and attach it. */
terrain.setMaterial(mat_terrain);
terrain.setLocalTranslation(0, -170, 0);
terrain.setLocalScale(2f, 1f, 2f);
rootNode.attachChild(terrain);
/** 4.5. Load some models */
Spatial building = assetManager.loadModel("Models/building1.obj");
Material mat_default = new Material(assetManager, "Common/MatDefs/Misc/ShowNormals.j3md");
building.setMaterial(mat_default);
building.setLocalTranslation(90, 117, 90);
building.setLocalScale(5f, 5f, 5f);
terrain.attachChild(building);
/** 4.6. Load Sky */
rootNode.attachChild(SkyFactory.createSky(assetManager, "Textures/Sky/Bright/BrightSky.dds", false));
/** 4.7. Load water */
// we create a water processor
SimpleWaterProcessor waterProcessor = new SimpleWaterProcessor(assetManager);
waterProcessor.setReflectionScene(rootNode);
// we set the water plane
Vector3f waterLocation = new Vector3f(0, -58, 0);
waterProcessor.setPlane(new Plane(Vector3f.UNIT_Y, waterLocation.dot(Vector3f.UNIT_Y)));
viewPort.addProcessor(waterProcessor);
// we set wave properties
waterProcessor.setWaterDepth(50); // transparency of water
waterProcessor.setDistortionScale(0.05f); // strength of waves
waterProcessor.setWaveSpeed(0.05f); // speed of waves
// we define the wave size by setting the size of the texture coordinates
Quad quad = new Quad(1000, 1000);
quad.scaleTextureCoordinates(new Vector2f(10f, 10f));
// we create the water geometry from the quad
Geometry water = new Geometry("water", quad);
water.setLocalRotation(new Quaternion().fromAngleAxis(-FastMath.HALF_PI, Vector3f.UNIT_X));
water.setLocalTranslation(-500, -58, 500);
water.setShadowMode(ShadowMode.Receive);
water.setMaterial(waterProcessor.getMaterial());
rootNode.attachChild(water);
/** 5. The LOD (level of detail) depends on were the camera is: */
List<Camera> cameras = new ArrayList<Camera>();
cameras.add(getCamera());
TerrainLodControl control = new TerrainLodControl(terrain, cameras);
terrain.addControl(control);
/** 6. Add physics: */
// We set up collision detection for the scene by creating a
// compound collision shape and a static RigidBodyControl with mass zero.*/
CollisionShape terrainShape = CollisionShapeFactory.createMeshShape(terrain);
landscape = new RigidBodyControl(terrainShape, 0);
terrain.addControl(landscape);
terrain.addControl(new RigidBodyControl(CollisionShapeFactory.createMeshShape(building), 0));
// We set up collision detection for the player by creating
// a capsule collision shape and a CharacterControl.
// The CharacterControl offers extra settings for
// size, stepheight, jumping, falling, and gravity.
// We also put the player in its starting position.
CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(1.5f, 6f, 1);
player = new CharacterControl(capsuleShape, 0.05f);
player.setJumpSpeed(50);
player.setFallSpeed(70);
player.setGravity(100);
player.setPhysicsLocation(new Vector3f(50, 100, 100));
// We attach the scene and the player to the rootnode and the physics space,
// to make them appear in the game world.
bulletAppState.getPhysicsSpace().add(terrain);
bulletAppState.getPhysicsSpace().add(player);
}
/** We over-write some navigational key mappings here, so we can
* add physics-controlled walking and jumping: */
private void setUpKeys() {
inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_A));
inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_D));
inputManager.addMapping("Up", new KeyTrigger(KeyInput.KEY_W));
inputManager.addMapping("Down", new KeyTrigger(KeyInput.KEY_S));
inputManager.addMapping("Jump", new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addListener(this, "Left");
inputManager.addListener(this, "Right");
inputManager.addListener(this, "Up");
inputManager.addListener(this, "Down");
inputManager.addListener(this, "Jump");
}
/** These are our custom actions triggered by key presses.
* We do not walk yet, we just keep track of the direction the user pressed. */
public void onAction(String binding, boolean value, float tpf) {
if (binding.equals("Left")) {
if (value) {
left = true;
} else {
left = false;
}
} else if (binding.equals("Right")) {
if (value) {
right = true;
} else {
right = false;
}
} else if (binding.equals("Up")) {
if (value) {
up = true;
} else {
up = false;
}
} else if (binding.equals("Down")) {
if (value) {
down = true;
} else {
down = false;
}
} else if (binding.equals("Jump")) {
player.jump();
}
}
/**
* This is the main event loop--walking happens here.
* We check in which direction the player is walking by interpreting
* the camera direction forward (camDir) and to the side (camLeft).
* The setWalkDirection() command is what lets a physics-controlled player walk.
* We also make sure here that the camera moves with player.
*/
#Override
public void simpleUpdate(float tpf) {
Vector3f camDir = cam.getDirection().clone().multLocal(0.6f);
Vector3f camLeft = cam.getLeft().clone().multLocal(0.4f);
walkDirection.set(0, 0, 0);
if (left) {
walkDirection.addLocal(camLeft);
}
if (right) {
walkDirection.addLocal(camLeft.negate());
}
if (up) {
walkDirection.addLocal(camDir);
}
if (down) {
walkDirection.addLocal(camDir.negate());
}
player.setWalkDirection(walkDirection);
cam.setLocation(player.getPhysicsLocation());
}
}
So, why isn't my model applied to the collision detection?
I have found the answer, here. The solution to the problem is this :
Create a CollisionShape. Create a PhysicsControl by supplying the
CollisionShape and mass. E.g. com.jme3.bullet.control.RigidBodyControl
Add the PhysicsControl to the Spatial. Add the PhysicsControl to the
physicsSpace object. Attach the Spatial to the rootNode, as usual.
(Optional) Implement the PhysicsCollisionListener interface to respond
to PhysicsCollisionEvents if desired.
Therefore, replace
terrain.attachChild(building);
by
rootNode.attachChild(building);
and adding
bulletAppState.getPhysicsSpace().add(building);

JOGL creating window using NEWT - examples?

I have been looking at using JOGL to create some things and have been looking through what documentation I can find.
Brief tutorials they all mention how using the JOGL version of canvas can have performance issues and instead you should use NEWT. However each and every tutorial / FAQ then goes on to use the canvas! Or simply specify a few tiny snippets of methods to create a window using NEWT but which (on my machine at least) I cannot get to correctly run.
Does anyone have a good source of examples of how to correctly implement creating and rendering to a window in JOGL using the NEWT method? I'm not even sure how it functions compared to the Canvas so an explanation of the differences between the two and a typical layout of methods to create / manage / render to a window would be ideal.
Just a little lost and cannot find anything useful. Hope someone's come across something before!
This tutorial helped me a lot, see chapter 3.9 - Yet Another Tutorial on JOGL.
Also documentation is useful. Take a look at the attached example, please.
JOGL2NewtDemo.java
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import com.jogamp.newt.event.WindowAdapter;
import com.jogamp.newt.event.WindowEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;
/**
* A program that draws with JOGL in a NEWT GLWindow.
*
*/
public class JOGL2NewtDemo {
private static String TITLE = "JOGL 2 with NEWT"; // window's title
private static final int WINDOW_WIDTH = 640; // width of the drawable
private static final int WINDOW_HEIGHT = 480; // height of the drawable
private static final int FPS = 60; // animator's target frames per second
static {
GLProfile.initSingleton(); // The method allows JOGL to prepare some Linux-specific locking optimizations
}
/**
* The entry main() method.
*/
public static void main(String[] args) {
// Get the default OpenGL profile, reflecting the best for your running platform
GLProfile glp = GLProfile.getDefault();
// Specifies a set of OpenGL capabilities, based on your profile.
GLCapabilities caps = new GLCapabilities(glp);
// Create the OpenGL rendering canvas
GLWindow window = GLWindow.create(caps);
// Create a animator that drives canvas' display() at the specified FPS.
final FPSAnimator animator = new FPSAnimator(window, FPS, true);
window.addWindowListener(new WindowAdapter() {
#Override
public void windowDestroyNotify(WindowEvent arg0) {
// Use a dedicate thread to run the stop() to ensure that the
// animator stops before program exits.
new Thread() {
#Override
public void run() {
if (animator.isStarted())
animator.stop(); // stop the animator loop
System.exit(0);
}
}.start();
}
});
window.addGLEventListener(new JOGL2Renderer());
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setTitle(TITLE);
window.setVisible(true);
animator.start(); // start the animator loop
}
}
JOGL2Renderer.java
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
/**
* Class handles the OpenGL events to render graphics.
*
*/
public class JOGL2Renderer implements GLEventListener {
private double theta = 0.0f; // rotational angle
/**
* Called back by the drawable to render OpenGL graphics
*/
#Override
public void display(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2(); // get the OpenGL graphics context
gl.glClear(GL.GL_COLOR_BUFFER_BIT); // clear background
gl.glLoadIdentity(); // reset the model-view matrix
// Rendering code - draw a triangle
float sine = (float)Math.sin(theta);
float cosine = (float)Math.cos(theta);
gl.glBegin(GL.GL_TRIANGLES);
gl.glColor3f(1, 0, 0);
gl.glVertex2d(-cosine, -cosine);
gl.glColor3f(0, 1, 0);
gl.glVertex2d(0, cosine);
gl.glColor3f(0, 0, 1);
gl.glVertex2d(sine, -sine);
gl.glEnd();
update();
}
/**
* Update the rotation angle after each frame refresh
*/
private void update() {
theta += 0.01;
}
/*... Other methods leave blank ...*/
}
take a look at JOGL's junit tests, they cover large parts of the NEWT API.

Categories