Trying To Render Scene To FBO Returns White - lwjgl

So this is what I'm trying to do. I'm trying to make a 2d game using LWJGL that has a dynamically generated terrain using images as tiles. It works fine, but when I try to do a zoom, the tiles get a dark shade on the edges and I get an extra pixel in-between tiles. Here's a screenshot of before and after zoom:
Before and After Zoom Screenshot: http://postimage.org/image/rhuc9744/
I've looked and looked, and from what little I've gathered on the internet, I think the gist is that zoom is causing pixel-precision issues which gets worse after blending. I saw a blog saying I can overlap some pixels between tiles, but it seems too complicated. I've tried all blending options, and none of them worked. So I figured, I should just render all the tiles into a buffer, an FBO, and then apply it as one big texture, so even when I zoom, I won't see dark edges because it would all be just one giant picture. So I've read a lot of tutorials on FBO, but most if not all of them are meant for 3D, which I actually got working. The problem is when I apply it to 2d ortho. The code breaks and all I get is a white box. I've been stuck on this problem for days, and I can't seem to find an answer using google. Here's a sample code I'm t trying to get working:
package com.helgravis;
import static org.lwjgl.opengl.EXTFramebufferObject.GL_COLOR_ATTACHMENT0_EXT;
import static org.lwjgl.opengl.EXTFramebufferObject.GL_DEPTH_ATTACHMENT_EXT;
import static org.lwjgl.opengl.EXTFramebufferObject.GL_FRAMEBUFFER_EXT;
import static org.lwjgl.opengl.EXTFramebufferObject.GL_RENDERBUFFER_EXT;
import static org.lwjgl.opengl.EXTFramebufferObject.glBindFramebufferEXT;
import static org.lwjgl.opengl.EXTFramebufferObject.glBindRenderbufferEXT;
import static org.lwjgl.opengl.EXTFramebufferObject.glFramebufferRenderbufferEXT;
import static org.lwjgl.opengl.EXTFramebufferObject.glFramebufferTexture2DEXT;
import static org.lwjgl.opengl.EXTFramebufferObject.glGenFramebuffersEXT;
import static org.lwjgl.opengl.EXTFramebufferObject.glGenRenderbuffersEXT;
import static org.lwjgl.opengl.EXTFramebufferObject.glRenderbufferStorageEXT;
import static org.lwjgl.opengl.GL11.GL_INT;
import static org.lwjgl.opengl.GL11.GL_RGBA;
import static org.lwjgl.opengl.GL11.GL_RGBA8;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D;
import static org.lwjgl.opengl.GL11.glBindTexture;
import static org.lwjgl.opengl.GL11.glGenTextures;
import static org.lwjgl.opengl.GL11.glTexImage2D;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.Hashtable;
import javax.swing.JPanel;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
public class AnFBOExample
{
private int width, height, canvasWidth = 800, canvasHeight = 600;
private String title;
private boolean bFullscreen;
public int FRAMERATE = 60;
public int framebufferID;
public int framebufferTextureID, spriteTextureID;
public int depthRenderBufferID;
public int fboWidth = 100, fboHeight = 100;
public AnFBOExample()
{
bFullscreen = false;
}
public AnFBOExample(boolean bFullscreen)
{
this.bFullscreen = bFullscreen;
}
public void setTitle(String title)
{
this.title = title;
if(Display.isCreated())
Display.setTitle(title);
}
public String getTitle()
{
return title;
}
public void setResolution(int x, int y)
{
width = x;
height = y;
}
public void setCanvasSize(int x, int y)
{
canvasWidth = x;
canvasHeight = y;
}
private boolean initDisplayMode() throws Exception
{
if(bFullscreen)
Display.setFullscreen(true);
try
{
DisplayMode[] dm = org.lwjgl.util.Display.getAvailableDisplayModes(width, height, -1, -1, -1, -1, 60, 60);
org.lwjgl.util.Display.setDisplayMode(dm, new String[] {
"width=" + width,
"height=" + height,
"freq=" + FRAMERATE,
"bpp="+ org.lwjgl.opengl.Display.getDisplayMode().getBitsPerPixel()
}
);
return true;
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Unable to enter fullscreen, continuing in windowed mode");
}
return false;
}
public void init() throws Exception
{
try
{
initDisplayMode();
Display.create();
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glAlphaFunc(GL11.GL_GREATER, 0.5f);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, canvasWidth, canvasHeight, 0, -1, 1);
int framebufferID = glGenFramebuffersEXT();
int colorTextureID = glGenTextures();
int depthRenderBufferID = glGenRenderbuffersEXT();
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebufferID);
glBindTexture(GL_TEXTURE_2D, colorTextureID);
GL11.glTexParameteri(GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, fboWidth, fboHeight, 0, GL_RGBA, GL_INT, (java.nio.ByteBuffer) null);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,GL_COLOR_ATTACHMENT0_EXT,GL_TEXTURE_2D, colorTextureID, 0);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthRenderBufferID);
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL14.GL_DEPTH_COMPONENT24, fboWidth, fboHeight);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,GL_DEPTH_ATTACHMENT_EXT,GL_RENDERBUFFER_EXT, depthRenderBufferID);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
BufferedImage image = loadImage("resources/lamp.png");
spriteTextureID = getTexture(image);
}
catch(LWJGLException le)
{
le.printStackTrace();
}
}
public void draw()
{
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebufferID);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glPushMatrix();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, spriteTextureID);
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(0, 1f);
GL11.glVertex2f(0, 50f);
GL11.glTexCoord2f(1f, 1f);
GL11.glVertex2f(50f, 50f);
GL11.glTexCoord2f(1f, 0);
GL11.glVertex2f(50f, 0);
}
GL11.glEnd();
GL11.glPopMatrix();
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glPushMatrix();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, framebufferTextureID);
GL11.glTranslatef(100f, 100f, 0);
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(0, 1f);
GL11.glVertex2f(0, 100f);
GL11.glTexCoord2f(1f, 1f);
GL11.glVertex2f(100f, 100f);
GL11.glTexCoord2f(1f, 0);
GL11.glVertex2f(100f, 0);
}
GL11.glEnd();
GL11.glPopMatrix();
Display.update();
Display.sync(FRAMERATE);
}
public void draw2()
{
// glBindTexture(GL_TEXTURE_2D, 0);
// glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebufferID);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glPushMatrix();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, spriteTextureID);
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(0, 1f);
GL11.glVertex2f(0, 50f);
GL11.glTexCoord2f(1f, 1f);
GL11.glVertex2f(50f, 50f);
GL11.glTexCoord2f(1f, 0);
GL11.glVertex2f(50f, 0);
}
GL11.glEnd();
GL11.glPopMatrix();
// glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
// GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
// GL11.glPushMatrix();
// GL11.glEnable(GL11.GL_TEXTURE_2D);
// GL11.glBindTexture(GL11.GL_TEXTURE_2D, framebufferTextureID);
// GL11.glTranslatef(100f, 100f, 0);
// GL11.glBegin(GL11.GL_QUADS);
// {
// GL11.glTexCoord2f(0, 0);
// GL11.glVertex2f(0, 0);
// GL11.glTexCoord2f(0, 1f);
// GL11.glVertex2f(0, 100f);
// GL11.glTexCoord2f(1f, 1f);
// GL11.glVertex2f(100f, 100f);
// GL11.glTexCoord2f(1f, 0);
// GL11.glVertex2f(100f, 0);
// }
// GL11.glEnd();
// GL11.glPopMatrix();
//
// Display.update();
// Display.sync(FRAMERATE);
}
public void cleanup()
{
Display.destroy();
}
public void run()
{
while(!Thread.interrupted())
{
progress();
handleEvents();
draw();
//draw2();
}
}
public void handleEvents()
{
while(Keyboard.next())
if(Keyboard.getEventKey() == Keyboard.KEY_ESCAPE)
quit();
if(Display.isCloseRequested())
quit();
}
public void quit()
{
System.exit(0);
}
public void progress()
{
//Add game logic here
}
protected static boolean waitForImage(Image image, Component c)
{
Image[] images = new Image[1];
images[0] = image;
return waitForImages(images, c);
}
protected static boolean waitForImages(Image[] images, Component c)
{
MediaTracker tracker = new MediaTracker(c);
for(int i=0; i<images.length; i++)
tracker.addImage(images[i], 0);
try
{
tracker.waitForAll();
}
catch(InterruptedException ie) {}
return !tracker.isErrorAny();
}
public static BufferedImage loadImage(String imageFile) throws Exception
{
Image image = null;
JPanel buffer = new JPanel();
image = buffer.getToolkit().getImage(imageFile);
waitForImage(image, buffer);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.drawImage(image, 0, 0, width, height, buffer);
g2d.dispose();
return bufferedImage;
}
public int getTexture(BufferedImage image) throws Exception
{
return getTexture(image,
GL11.GL_TEXTURE_2D,
GL11.GL_RGBA,
GL11.GL_LINEAR,
GL11.GL_LINEAR);
}
public int getTexture(String resourceName,
int target,
int dstPixelFormat,
int minFilter,
int magFilter) throws Exception
{
BufferedImage bufferedImage = loadImage(resourceName);
return getTexture(bufferedImage, target, dstPixelFormat, minFilter, magFilter);
}
private int createTextureID()
{
ByteBuffer temp = ByteBuffer.allocateDirect(4 * 1);
temp.order(ByteOrder.nativeOrder());
IntBuffer tmp = temp.asIntBuffer();
GL11.glGenTextures(tmp);
return tmp.get(0);
}
public int getTexture(BufferedImage bufferedImage,
int target,
int dstPixelFormat,
int minFilter,
int magFilter) throws Exception
{
int srcPixelFormat = 0;
int textureID = createTextureID();
GL11.glBindTexture(target, textureID);
if(bufferedImage.getColorModel().hasAlpha())
srcPixelFormat = GL11.GL_RGBA;
else
srcPixelFormat = GL11.GL_RGB;
ByteBuffer textureBuffer = convertImageData(bufferedImage);
if(target == GL11.GL_TEXTURE_2D)
{
GL11.glTexParameteri(target, GL11.GL_TEXTURE_MIN_FILTER, minFilter);
GL11.glTexParameteri(target, GL11.GL_TEXTURE_MAG_FILTER, magFilter);
}
GL11.glTexImage2D(target,
0,
dstPixelFormat,
get2Fold(bufferedImage.getWidth()),
get2Fold(bufferedImage.getHeight()),
0,
srcPixelFormat,
GL11.GL_UNSIGNED_BYTE,
textureBuffer);
return textureID;
}
private int get2Fold(int fold)
{
int ret = 2;
while (ret < fold)
ret *= 2;
return ret;
}
#SuppressWarnings("rawtypes")
private ByteBuffer convertImageData(BufferedImage bufferedImage)
{
ComponentColorModel glAlphaColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8,8,8,8},
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
ComponentColorModel glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8,8,8,0},
false,
false,
ComponentColorModel.OPAQUE,
DataBuffer.TYPE_BYTE);
ByteBuffer imageBuffer = null;
WritableRaster raster;
BufferedImage texImage;
int texWidth = 2;
int texHeight = 2;
while (texWidth < bufferedImage.getWidth())
texWidth *= 2;
while (texHeight < bufferedImage.getHeight())
texHeight *= 2;
if(bufferedImage.getColorModel().hasAlpha())
{
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 4, null);
texImage = new BufferedImage(glAlphaColorModel, raster, false, new Hashtable());
}
else
{
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 3, null);
texImage = new BufferedImage(glColorModel, raster, false, new Hashtable());
}
Graphics g = texImage.getGraphics();
g.setColor(new Color(0f,0f,0f,0f));
g.fillRect(0,0,texWidth,texHeight);
g.drawImage(bufferedImage,0,0,null);
byte[] data = ((DataBufferByte) texImage.getRaster().getDataBuffer()).getData();
imageBuffer = ByteBuffer.allocateDirect(data.length);
imageBuffer.order(ByteOrder.nativeOrder());
imageBuffer.put(data, 0, data.length);
imageBuffer.flip();
return imageBuffer;
}
public static void main(String args[]) throws Exception
{
AnFBOExample window = new AnFBOExample(false);
window.setResolution(800, 600);
window.setCanvasSize(800, 600);
window.init();
window.setTitle("FBO Test");
window.run();
}
}
The code loads an image in resource/lamp.png, which can be any .png file, and tries to render it to an FBO, then applies it as a texture in a 2d quad. For some reason, I only get a white blank quad when I try to bind the FBO as a texture. I'm not sure if I'm not rendering to the FBO properly, or I'm not binding it correctly. You can check the method draw() so you know what I'm talking about. Like I said, I've been stuck in this problem for day, so any help would be very much appreciated.
resources/lamp.png: http://s3.postimage.org/rhpdn5ms/lamp.png?noCache=1315464566

framebufferTextureID, shouldn't it be colourTextureID?

Related

LWJGL glDrawArrays doesn't draw

I'm kinda new to the LWJGL library and im trying to draw a simple triangle. Only my code seems okay with it won't draw my triangle. It also gives no errors or anything else. I searched everywhere but found no solution at all. Anyone with a solution?
Code:
public class Cube {
private int width, height;
private int ID, bufferID;
private int count;
private float[] vertices;
public Cube() {
vertices = new float[] {
0, 0, 0,
1, 0, 0,
0, 1, 0,
};
count = vertices.length / 3;
FloatBuffer buffer = BufferUtils.createFloatBuffer(vertices.length);
buffer.put(vertices);
buffer.flip();
ID = GL30.glGenVertexArrays();
GL30.glBindVertexArray(ID);
bufferID = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, bufferID);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
GL20.glEnableVertexAttribArray(0);
GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0);
GL30.glBindVertexArray(0);
GL20.glDisableVertexAttribArray(0);
}
public void render() {
GL30.glBindVertexArray(ID);
GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, count);
GL30.glBindVertexArray(0);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
public class Launcher {
public static void main(String[] args) {
Window window = new Window("Cube Wave", 800, 600);
window.setBackground(1, 0, 1);
window.setup();
}
}
public class Window {
private String title;
private int width, height;
private Vector3f color;
private long window;
private ArrayList<Cube> cubes = new ArrayList<Cube>();
public Window(String title, int width, int height) {
this.title = title;
this.width = width;
this.height = height;
setBackground(0, 0, 0);
}
public void setup() {
if (!glfwInit()) {
return;
}
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(width, height, title, NULL, NULL);
if (window == NULL) {
return;
}
GLFWVidMode monitor = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, (monitor.width() - width) / 2, (monitor.height() - height) / 2);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
GL.createCapabilities();
glfwShowWindow(window);
loop();
}
public long getWindow() {
return window;
}
public void loop() {
init();
glClearColor(color.x, color.y, color.z, 1.0f);
while(!closed()) {
tick();
render();
}
}
public void render() {
for(Cube cube : cubes) {
cube.render();
}
glfwSwapBuffers(window);
}
public void tick() {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
public void init() {
cubes.add(new Cube());
}
public boolean closed() {
return glfwWindowShouldClose(window);
}
public void setBackground(float r, float g, float b) {
color = new Vector3f(r, g, b);
}
}
It seems that you have a mistake in your render function.
Below is an example for how to use glDrawArrays in a render function.
public void render() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
// bind the VBO and enable the attribute
GL30.glBindVertexArray(ID);
GL20.glEnableVertexAttribArray(0);
GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, count);
// disable the VBO and disable the attribute
GL20.glDisableVertexAttribArray(0);
GL30.glBindVertexArray(0);
}
Also it is considered best practice to unbind buffers when you are done with them. So your initialization function should look like this.
public Cube() {
// ... vertex stuff
ID = GL30.glGenVertexArrays();
GL30.glBindVertexArray(ID);
bufferID = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, bufferID);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0);
// unbind both the Array Buffer and the Vertex Array
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL30.glBindVertexArray(0);
}
You can find a more in depth discussion and example of this from the lwjgl wiki

How does LibGDX FitViewport keep aspect ratio after resizing?

I am a little bit confused why my FitViewport is not keeping the aspect ratio when resizing the window.
I thought that it should always keep the aspect ratio and then fill up the screen with black bars for areas which are not used.
However for me it is not keeping the aspect ratio and circles become ellipsis f.e. (see screenshots).
Code when creating my game renderer (32 and 18 are my world units)
viewport = new FitViewport(32, 18);
camera = viewport.getCamera();
visibleArea = new Rectangle(0, 0, viewport.getScreenWidth(), viewport.getScreenHeight());
scissors = new Rectangle();
Code when resizing the window
public void resize(int width, int height) {
Gdx.app.debug(TAG, "Resizing to " + width + " x " + height);
viewport.update(width, height);
visibleArea.set(0, 0, viewport.getScreenWidth(), viewport.getScreenHeight());
Render method
public void render(float alpha) {
viewport.calculateScissors(batch.getTransformMatrix(), visibleArea, scissors);
ScissorStack.pushScissors(scissors);
viewport.apply();
setView(camera.combined, visibleArea.x, visibleArea.y, visibleArea.width, visibleArea.height);
batch.begin();
// ...
batch.end();
ScissorStack.popScissors();
}
correct aspect ratio on startup
wrong aspect ratio on resize
Okay the problem actually was with my framebuffer light method (prepareLightFrameBuffer) which also had a call to batch.begin(); and batch.end().
It seems like this messes up the view (or resets it to something?). To solve the issue I just applied the viewport again and set the view again in the render method (Note: I also have a stage so I think that viewport.apply() has to be called here and also in the stage.render() method).
Here is the complete code of the GameRenderer if anyone is interested. I guess somehow it could be simplified but I am no OpenGL/Matrix expert so I have no idea how to do it :)
package com.lok.game;
import java.util.Comparator;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.tiled.TiledMapImageLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.lok.game.ecs.components.AnimationComponent;
import com.lok.game.ecs.components.CollisionComponent;
import com.lok.game.ecs.components.MapRevelationComponent;
import com.lok.game.ecs.components.SizeComponent;
import com.lok.game.map.Map;
import com.lok.game.map.Map.Portal;
import com.lok.game.map.MapManager;
public class GameRenderer extends OrthogonalTiledMapRenderer {
private final static String TAG = GameRenderer.class.getName();
private static class yPositionComparator implements Comparator<Entity> {
private final ComponentMapper<SizeComponent> sizeComponentMapper;
private yPositionComparator(ComponentMapper<SizeComponent> sizeComponentMapper) {
this.sizeComponentMapper = sizeComponentMapper;
}
#Override
public int compare(Entity o1, Entity o2) {
if (o1 == o2) {
return 0;
} else if (o1 == null) {
return -1;
} else if (o2 == null) {
return 1;
}
return sizeComponentMapper.get(o1).boundingRectangle.y > sizeComponentMapper.get(o2).boundingRectangle.y ? -1 : 1;
}
}
private SizeComponent cameraLockEntitySizeComponent;
private MapRevelationComponent cameraLockEntityRevelationComponent;
private Map map;
private TiledMapTileLayer groundLayer;
private final Array<TiledMapTileLayer> backgroundLayers;
private final Array<TiledMapTileLayer> foregroundLayers;
private TiledMapImageLayer lightMapLayer;
private final yPositionComparator entityComparator;
private final ComponentMapper<SizeComponent> sizeComponentMapper;
private final ComponentMapper<AnimationComponent> animationComponentMapper;
private final Camera camera;
private final Viewport viewport;
private final Rectangle visibleArea;
private final Rectangle scissors;
private final ShapeRenderer shapeRenderer;
private FrameBuffer frameBuffer;
private final AtlasRegion lightTexture;
private final AtlasRegion shadowTexture;
public GameRenderer() {
super(null, MapManager.WORLD_UNITS_PER_PIXEL);
if (Gdx.app.getLogLevel() == Application.LOG_DEBUG) {
Gdx.app.debug(TAG, "Creating in debug mode");
shapeRenderer = new ShapeRenderer();
} else {
Gdx.app.debug(TAG, "Creating in non-debug mode");
shapeRenderer = null;
}
viewport = new FitViewport(32, 18);
camera = viewport.getCamera();
visibleArea = new Rectangle();
scissors = new Rectangle();
this.backgroundLayers = new Array<TiledMapTileLayer>();
this.foregroundLayers = new Array<TiledMapTileLayer>();
this.sizeComponentMapper = ComponentMapper.getFor(SizeComponent.class);
this.animationComponentMapper = ComponentMapper.getFor(AnimationComponent.class);
this.entityComparator = new yPositionComparator(sizeComponentMapper);
final TextureAtlas textureAtlas = AssetManager.getManager().getAsset("lights/lights.atlas", TextureAtlas.class);
lightTexture = textureAtlas.findRegion("light");
shadowTexture = textureAtlas.findRegion("shadow");
frameBuffer = null;
}
public void setMap(Map map) {
this.map = map;
super.setMap(map.getTiledMap());
this.backgroundLayers.clear();
this.foregroundLayers.clear();
this.lightMapLayer = null;
for (MapLayer mapLayer : map.getTiledMap().getLayers()) {
if (mapLayer instanceof TiledMapTileLayer) {
if ("ground".equals(mapLayer.getName())) {
groundLayer = (TiledMapTileLayer) mapLayer;
} else if (mapLayer.getName().startsWith("background")) {
backgroundLayers.add((TiledMapTileLayer) mapLayer);
} else {
foregroundLayers.add((TiledMapTileLayer) mapLayer);
}
} else if (mapLayer instanceof TiledMapImageLayer) {
lightMapLayer = (TiledMapImageLayer) mapLayer;
}
}
}
public void resize(int width, int height) {
Gdx.app.debug(TAG, "Resizing with " + width + "x" + height + " from viewport " + viewport.getScreenWidth() + "x" + viewport.getScreenHeight());
viewport.update(width, height, false);
visibleArea.set(0, 0, viewport.getWorldWidth(), viewport.getWorldHeight());
Gdx.app.debug(TAG, "To viewport " + viewport.getScreenWidth() + "x" + viewport.getScreenHeight());
if (frameBuffer != null) {
frameBuffer.dispose();
}
try {
frameBuffer = FrameBuffer.createFrameBuffer(Pixmap.Format.RGBA8888, viewport.getScreenWidth(), viewport.getScreenHeight(), false);
} catch (GdxRuntimeException e) {
frameBuffer = FrameBuffer.createFrameBuffer(Pixmap.Format.RGB565, viewport.getScreenWidth(), viewport.getScreenHeight(), false);
}
}
public void lockCameraToEntity(Entity entity) {
if (entity == null) {
cameraLockEntitySizeComponent = null;
cameraLockEntityRevelationComponent = null;
} else {
cameraLockEntityRevelationComponent = entity.getComponent(MapRevelationComponent.class);
cameraLockEntitySizeComponent = entity.getComponent(SizeComponent.class);
if (cameraLockEntitySizeComponent == null) {
throw new GdxRuntimeException("Trying to lock camera to an entity without size component: " + entity);
}
}
}
private void interpolateEntities(float alpha) {
for (Entity entity : map.getEntities()) {
final SizeComponent sizeComp = sizeComponentMapper.get(entity);
final float invAlpha = 1.0f - alpha;
sizeComp.interpolatedPosition.x = sizeComp.interpolatedPosition.x * invAlpha + sizeComp.boundingRectangle.x * alpha;
sizeComp.interpolatedPosition.y = sizeComp.interpolatedPosition.y * invAlpha + sizeComp.boundingRectangle.y * alpha;
}
}
public void render(float alpha) {
AnimatedTiledMapTile.updateAnimationBaseTime();
interpolateEntities(alpha);
map.getEntities().sort(entityComparator);
if (cameraLockEntitySizeComponent != null) {
camera.position.set(cameraLockEntitySizeComponent.interpolatedPosition, 0);
visibleArea.setCenter(cameraLockEntitySizeComponent.interpolatedPosition);
}
prepareLightFrameBuffer();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
viewport.apply();
setView(camera.combined, visibleArea.x, visibleArea.y, visibleArea.width, visibleArea.height);
batch.begin();
viewport.calculateScissors(batch.getTransformMatrix(), visibleArea, scissors);
ScissorStack.pushScissors(scissors);
if (groundLayer != null) {
renderTileLayer(groundLayer);
}
for (Entity entity : map.getEntities()) {
renderEntityShadow(entity);
}
for (TiledMapTileLayer layer : backgroundLayers) {
renderTileLayer(layer);
}
for (Entity entity : map.getEntities()) {
renderEntity(entity);
}
for (TiledMapTileLayer layer : foregroundLayers) {
renderTileLayer(layer);
}
batch.end();
applyLightFrameBuffer();
if (Gdx.app.getLogLevel() == Application.LOG_DEBUG) {
renderDebugInformation();
}
ScissorStack.popScissors();
}
private void renderEntityShadow(Entity entity) {
final AnimationComponent animationComp = animationComponentMapper.get(entity);
if (animationComp.animation != null) {
final SizeComponent sizeComp = sizeComponentMapper.get(entity);
if (!viewBounds.overlaps(sizeComp.boundingRectangle)) {
return;
}
if (cameraLockEntityRevelationComponent != null && !Intersector.overlaps(cameraLockEntityRevelationComponent.revelationCircle, sizeComp.boundingRectangle)) {
return;
}
batch.draw(shadowTexture, sizeComp.interpolatedPosition.x, sizeComp.interpolatedPosition.y - sizeComp.boundingRectangle.height * 0.2f, sizeComp.boundingRectangle.width,
sizeComp.boundingRectangle.height * 0.5f);
}
}
private void renderEntity(Entity entity) {
final AnimationComponent animationComp = animationComponentMapper.get(entity);
if (animationComp.animation != null) {
final SizeComponent sizeComp = sizeComponentMapper.get(entity);
if (!viewBounds.overlaps(sizeComp.boundingRectangle)) {
return;
}
if (cameraLockEntityRevelationComponent != null && !Intersector.overlaps(cameraLockEntityRevelationComponent.revelationCircle, sizeComp.boundingRectangle)) {
return;
}
final TextureRegion keyFrame = animationComp.animation.getKeyFrame(animationComp.animationTime, true);
batch.draw(keyFrame, sizeComp.interpolatedPosition.x, sizeComp.interpolatedPosition.y, sizeComp.boundingRectangle.width, sizeComp.boundingRectangle.height);
}
}
private void prepareLightFrameBuffer() {
if (cameraLockEntityRevelationComponent != null) {
frameBuffer.begin();
final Color mapBackgroundColor = map.getBackgroundColor();
Gdx.gl.glClearColor(mapBackgroundColor.r, mapBackgroundColor.g, mapBackgroundColor.b, mapBackgroundColor.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
setView(camera.combined, visibleArea.x, visibleArea.y, visibleArea.width, visibleArea.height);
batch.begin();
if (lightMapLayer != null) {
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
renderImageLayer(lightMapLayer);
}
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
final Rectangle boundingRectangle = cameraLockEntitySizeComponent.boundingRectangle;
batch.draw(lightTexture, cameraLockEntitySizeComponent.interpolatedPosition.x + boundingRectangle.width * 0.5f - cameraLockEntityRevelationComponent.revelationRadius, // x
cameraLockEntitySizeComponent.interpolatedPosition.y + boundingRectangle.height * 0.5f - cameraLockEntityRevelationComponent.revelationRadius, // y
cameraLockEntityRevelationComponent.revelationRadius * 2f, cameraLockEntityRevelationComponent.revelationRadius * 2f);
batch.end();
frameBuffer.end();
}
}
private void applyLightFrameBuffer() {
if (cameraLockEntityRevelationComponent != null) {
batch.setProjectionMatrix(batch.getProjectionMatrix().idt());
batch.setBlendFunction(GL20.GL_ZERO, GL20.GL_SRC_COLOR);
batch.begin();
batch.draw(frameBuffer.getColorBufferTexture(), -1, 1, 2, -2);
batch.end();
}
}
private void renderDebugInformation() {
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(Color.RED);
for (Rectangle rect : map.getCollisionAreas()) {
shapeRenderer.rect(rect.x, rect.y, rect.width, rect.height);
}
for (Entity entity : map.getEntities()) {
final CollisionComponent collisionComponent = entity.getComponent(CollisionComponent.class);
final SizeComponent sizeComp = sizeComponentMapper.get(entity);
if (collisionComponent != null) {
shapeRenderer.setColor(Color.RED);
shapeRenderer.rect(sizeComp.interpolatedPosition.x + collisionComponent.rectOffset.x, sizeComp.interpolatedPosition.y + collisionComponent.rectOffset.y,
collisionComponent.collisionRectangle.width, collisionComponent.collisionRectangle.height);
}
if (sizeComp != null) {
shapeRenderer.setColor(Color.BLUE);
shapeRenderer.rect(sizeComp.interpolatedPosition.x, sizeComp.interpolatedPosition.y, sizeComp.boundingRectangle.width, sizeComp.boundingRectangle.height);
}
}
shapeRenderer.setColor(Color.BLUE);
for (Portal portal : map.getPortals()) {
shapeRenderer.rect(portal.getArea().x, portal.getArea().y, portal.getArea().width, portal.getArea().height);
}
if (cameraLockEntityRevelationComponent != null) {
shapeRenderer.setColor(Color.WHITE);
shapeRenderer.circle(cameraLockEntitySizeComponent.interpolatedPosition.x + cameraLockEntitySizeComponent.boundingRectangle.width * 0.5f,
cameraLockEntitySizeComponent.interpolatedPosition.y + cameraLockEntitySizeComponent.boundingRectangle.height * 0.5f,
cameraLockEntityRevelationComponent.revelationCircle.radius, 64);
}
shapeRenderer.end();
}
#Override
public void dispose() {
Gdx.app.debug(TAG, "Disposing Gamerenderer");
super.dispose();
if (shapeRenderer != null) {
shapeRenderer.dispose();
}
if (frameBuffer != null) {
frameBuffer.dispose();
}
}
}

Libgdx collision using box2d working for desktop but failed to collide in Android emulator

My code for collision of a dynamic body to a static body works perfectly for desktop , but when running in Android emulator it can not able to detect collision ,Dynamic body goes down without collision.
I used Libgdx version : 1.5.0 .
Code :
package com.kg.game;
import java.util.Random;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
public class MyGdxGame extends ApplicationAdapter implements InputProcessor {
private static final float VIEWPORT_WIDTH = 10;
private static final float BALL_RADIUS = 0.15f;
private static final int MAX_BALLS = 200;
private World world;
private Body[] ballModels;
private Texture bottleTexture;
private Texture ballTexture;
private Sprite[] ballSprites;
private Texture whiteTexture;
private Sprite groundSprite;
private SpriteBatch batch;
private BitmapFont font;
private OrthographicCamera camera;
private final Random rand = new Random();
float w;
float h;
Box2DDebugRenderer debugRenderer;
private final TweenManager tweenManager = new TweenManager();
#Override
public void create() {
debugRenderer = new Box2DDebugRenderer();
world = new World(new Vector2(0, -10), true);
createGround();
createBalls();
batch = new SpriteBatch();
font = new BitmapFont();
font.setColor(Color.BLACK);
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(VIEWPORT_WIDTH, VIEWPORT_WIDTH * h / w);
camera.position.set(0, (VIEWPORT_WIDTH * h / w) / 2, 0);
camera.update();
createSprites();
Gdx.input.setInputProcessor(new InputAdapter() {
#Override
public boolean touchDown(int x, int y, int pointer, int button) {
restart();
return true;
}
});
restart();
}
private void createGround() {
BodyDef bd = new BodyDef();
bd.position.set(0, 0);
bd.type = BodyType.StaticBody;
PolygonShape shape = new PolygonShape();
shape.setAsBox(100, 4);
FixtureDef fd = new FixtureDef();
fd.density = 1;
fd.friction = 0.5f;
fd.restitution = 0.5f;
fd.shape = shape;
world.createBody(bd).createFixture(fd);
shape.dispose();
}
private void createBalls() {
BodyDef ballBodyDef = new BodyDef();
ballBodyDef.type = BodyType.DynamicBody;
CircleShape shape = new CircleShape();
shape.setRadius(BALL_RADIUS);
FixtureDef fd = new FixtureDef();
fd.density = 1;
fd.friction = 0.5f;
fd.restitution = 0.5f;
fd.shape = shape;
ballModels = new Body[MAX_BALLS];
for (int i = 0; i < MAX_BALLS; i++) {
ballModels[i] = world.createBody(ballBodyDef);
ballModels[i].createFixture(fd);
}
shape.dispose();
}
private void createSprites() {
ballTexture = new Texture(Gdx.files.internal("ball.png"));
ballTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
ballSprites = new Sprite[MAX_BALLS];
for (int i = 0; i < MAX_BALLS; i++) {
ballSprites[i] = new Sprite(ballTexture);
ballSprites[i].setSize(BALL_RADIUS * 2, BALL_RADIUS * 2);
ballSprites[i].setOrigin(BALL_RADIUS, BALL_RADIUS);
}
whiteTexture = new Texture(Gdx.files.internal("ground.png"));
groundSprite = new Sprite(whiteTexture);
groundSprite.setSize(100, 4);
groundSprite.setPosition(-VIEWPORT_WIDTH / 2, 0);
groundSprite.setColor(Color.BLACK);
}
private float elapsed = 0;
#Override
public void render() {
tweenManager.update(1 / 60f);
world.step(1 / 60f, 10, 10);
debugRenderer.render(world, camera.combined);
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
GL20 gl = Gdx.gl20;
gl.glClearColor(1, 1, 1, 1);
gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// Update
for (int i = 0; i < MAX_BALLS; i++) {
Vector2 ballPos = ballModels[i].getPosition();
ballSprites[i].setPosition(ballPos.x - ballSprites[i].getWidth()
/ 2, ballPos.y - ballSprites[i].getHeight() / 2);
ballSprites[i].setRotation(ballModels[i].getAngle()
* MathUtils.radiansToDegrees);
}
// Render
batch.setProjectionMatrix(camera.combined);
batch.begin();
groundSprite.draw(batch);
for (int i = 0; i < MAX_BALLS; i++)
ballSprites[i].draw(batch);
batch.end();
// batch.getProjectionMatrix().setToOrtho2D(0, 0, w, h);
batch.begin();
font.draw(batch, "Touch the screen to restart", 5, h - 5);
batch.end();
}
#Override
public void dispose() {
bottleTexture.dispose();
ballTexture.dispose();
batch.dispose();
font.dispose();
world.dispose();
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return true;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
private void restart() {
Vector2 vec = new Vector2();
for (int i = 0; i < MAX_BALLS; i++) {
float tx = rand.nextFloat() * 1.0f - 0.5f;
float ty = VIEWPORT_WIDTH * h / w;
float angle = rand.nextFloat() * MathUtils.PI * 2;
ballModels[i].setActive(false);
ballModels[i].setLinearVelocity(vec.set(0, 0));
ballModels[i].setAngularVelocity(0);
ballModels[i].setTransform(vec.set(tx, ty), angle);
}
tweenManager.killAll();
Tween.call(new TweenCallback() {
private int idx = 0;
#Override
public void onEvent(int type, BaseTween<?> source) {
if (idx < ballModels.length) {
ballModels[idx].setAwake(true);
ballModels[idx].setActive(true);
idx += 1;
}
}
}).repeat(-1, 0.1f).start(tweenManager);
}
}
Screensots :
this is an idea, looking at the proportions of your images, I think the error may be out there, I would look at these lines:
groundSprite.setSize(100, 4); //<--especially here
groundSprite.setPosition(-VIEWPORT_WIDTH / 2, 0); //<--especially here
.
private void createGround() {
BodyDef bd = new BodyDef();
bd.position.set(0, 0); //<--especially here
bd.type = BodyType.StaticBody;
PolygonShape shape = new PolygonShape();
shape.setAsBox(100, 4); //<--especially here
especially the position and size, if it is standing in the same place, with the change of screen "device".
You tried to render debug? I see out there, if so, you can see your object in the emulated device?
I hope I understand, but not if that be the error

Why does my Player follow the OrthographicCamera

My game renders a tiledmap. I let the OrthographicCamera change its position.x to the right and can see the background (the tiledmap) scroll. This is fine.
But other Objects (the player and some balls) do (visually) change their position corresponding to the camera. They should not move, because only the camera moves.
package com.me.drop;
import java.util.Iterator;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxNativesLoader;
import com.badlogic.gdx.utils.TimeUtils;
public class MyTestGame extends Game {
Texture dropImage;
Texture bucketImage;
Sound dropSound;
Music rainMusic;
SpriteBatch batch;
OrthographicCamera camera;
Rectangle bucket;
Array<Rectangle> raindrops;
long lastDropTime;
Animator animator = new Animator();
Body animatorBody;
private Physics physics;
public Environment environment;
// public PerspectiveCamera cam;
public Model model;
public ModelBatch modelBatch;
public ModelInstance instance;
static final int WIDTH = 1600;
static final int HEIGHT = 960;
public final static float ORTHO_SCALE=1;
public final static float WORLD_SCALE=32;
Ball balls[] = new Ball[10];
Spieler player;
#Override
public void create() {
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
glViewport = new Rectangle(0, 0, WIDTH, HEIGHT);
// load the images for the droplet and the bucket, 64x64 pixels each
dropImage = new Texture(Gdx.files.internal("droplet.png"));
bucketImage = new Texture(Gdx.files.internal("bucket.png"));
// load the drop sound effect and the rain background "music"
dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));
// start the playback of the background music immediately
rainMusic.setLooping(true);
rainMusic.play();
// create the camera and the SpriteBatch
camera = new OrthographicCamera();
//camera.setToOrtho(false, 400, 240);
camera.setToOrtho(false, 800/ORTHO_SCALE, 480/ORTHO_SCALE);
batch = new SpriteBatch();
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createBox(5f, 5f, 5f,
new Material(ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
instance = new ModelInstance(model);
// Box2d
physics = Physics.getInstance();
// floor
physics.initFloor(0f, 0f, camera.viewportWidth, 0f);
// ceiling
// physics.initFloor(0f, camera.viewportHeight, camera.viewportWidth, 10f);
// left Wall
physics.initFloor(0f, 0f, 0f, camera.viewportHeight);
// right Wall
physics.initFloor(camera.viewportWidth, 0f, 0f, camera.viewportHeight);
float x = 150;
float y = camera.viewportHeight;
for (int i = 0; i < balls.length; i++) {
if (i%10==0) {
x += 10;
y = camera.viewportHeight / 2;
}
y += x;
balls[i] = new Ball(x, y , 20f , 20f, 0.4f, 0.8f);
}
player = new Spieler(50, camera.viewportHeight, 60f, 120f);
loadBackground();
}
TiledMapRenderer tileRenderer;
public void loadBackground() {
TiledMap map = new TmxMapLoader().load("maps/mymap.tmx");
System.out.println(map.getTileSets().toString());
float unitScale = 1 / 1;
tileRenderer = new OrthogonalTiledMapRenderer(map, unitScale);
physics.createFixturesForMap(map);
}
private Rectangle glViewport;
//#Override
public void render() {
GL10 gl = Gdx.graphics.getGL10();
// Camera --------------------- /
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glViewport((int) glViewport.x, (int) glViewport.y,
(int) glViewport.width, (int) glViewport.height);
//
// tell the camera to update its matrices.
camera.update();
camera.apply(gl);
// tell the SpriteBatch to render in the
// coordinate system specified by the camera.
batch.setProjectionMatrix(camera.combined);
// background
tileRenderer.setView(camera);
tileRenderer.render();
for (Ball b : balls)
b.render();
player.render();
grabUserAction();
// Box2d
physics.step();
updateObjects();
physics.debugRenderer.render(physics.world, camera.combined);
}
private void grabUserAction() {
// process user input
if(Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
bucket.x = touchPos.x - 64 / 2;
}
Vector2 vel = this.player.getBody().getLinearVelocity();
Vector2 pos = this.player.getBody().getPosition();
// apply left impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Keys.LEFT)) { // && vel.x > -MAX_VELOCITY) {
// this.animatorBody.localPoint2.x -= 200 *
// Gdx.graphics.getDeltaTime();
pos.x -= 2 * Gdx.graphics.getDeltaTime();
this.player.getBody().setTransform(pos, 0);
// this.animatorBody.applyLinearImpulse(0, -0.8f, pos.x, pos.y,
// true);
// this.animatorBody.applyLinearImpulse(-5000, 0, pos.x, pos.y,
// true);
}
// apply right impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Keys.RIGHT)) { // && vel.x < MAX_VELOCITY) {
// this.animatorBody.localPoint2.x += 200 *
// Gdx.graphics.getDeltaTime();
pos.x += 2 * Gdx.graphics.getDeltaTime();
this.player.getBody().setTransform(pos, 0);
// this.animatorBody.applyLinearImpulse(5000, 0, pos.x, pos.y,
// true);
}
if (Gdx.input.isKeyPressed(Keys.UP)) {
Vector2 impuls = new Vector2(0, 500f);
this.player.getBody().applyLinearImpulse(impuls, player.getBody().getWorldCenter(),true);
// this.animatorBody.applyAngularImpulse(-5.0f, true);
//(impulse, wake);(new b2Vec2(0.0, -3.0), Body.GetWorldCenter());
}
if (Gdx.input.isKeyPressed(Keys.D)) {
this.camera.position.x += 2;
this.camera.update();
}
else if (Gdx.input.isKeyPressed(Keys.A)) {
this.camera.position.x -= 2;
this.camera.update();
}
}
private void updateObjects() {
Array<Body> array = new Array<Body>();
physics.world.getBodies(array);
Iterator<Body> bi = array.iterator();
while (bi.hasNext()){
Body b = bi.next();
// Get the body's user data - in this example, our user
// data is an instance of the Entity class
IObject e = (IObject) b.getUserData();
if (e != null) {
// Update the entities/sprites position and angle
e.setPosition((b.getPosition().x - e.getWidth()/2/WORLD_SCALE) * WORLD_SCALE
, (b.getPosition().y - e.getHeight()/2/WORLD_SCALE) * WORLD_SCALE);
// We need to convert our angle from radians to degrees
//e.setRotation(MathUtils.radiansToDegrees * b.getAngle());
}
}
}
#Override
public void dispose() {
// dispose of all the native resources
dropImage.dispose();
bucketImage.dispose();
dropSound.dispose();
rainMusic.dispose();
batch.dispose();
// modelBatch.dispose();
model.dispose();
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
//
// Vector3 oldpos = new Vector3(camera.position);
// camera.setToOrtho(false,
// width/WORLD_SCALE,
// height/WORLD_SCALE);
// camera.translate(oldpos.x-camera.position.x,oldpos.y-camera.position.y);
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
super.resume();
}
}

SwingWorker gui repaint

Im trying to use the SwingWorker to update my gui without calling repaint().
I want the SwigWorker to update the status of each GridGraphic[i][j] and the have the gui be repsonsive to the changes without calling repaint().
GridGraphic.java
import java.awt.*;
import javax.swing.*;
public class GridGraphic extends JComponent {
private int intensity = 0;
public GridGraphic() {
//setBorder(BorderFactory.createLineBorder(Color.BLUE));
}
public void paintComponent(Graphics g) {
//paints the GridGraphic black
if (intensity == 0){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
}
//paints the GridGraphic black with a yellow dot
else if (intensity == 5){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.YELLOW);
g.fillOval(3, 3, getWidth()/2, getHeight()/2);
}
}
public Dimension getPreferredSize() {
return new Dimension(10, 10);
}
public void setAgent(){
intensity = 5;
}
public void setDefault(){
intensity = 0;
}
public int getIntensity(){
return intensity;
}
}