Changing the Coordinate System in LibGDX (Java) - java

LibGDX has a coordinate system where (0,0) is at the bottom-left. (like this image: http://i.stack.imgur.com/jVrJ0.png)
This has me beating my head against a wall, mainly because I'm porting a game I had already made with the usual coordinate system (where 0,0 is in the Top Left Corner).
My question: Is there any simple way of changing this coordinate system?

If you use a Camera (which you should) changing the coordinate system is pretty simple:
camera= new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
If you use TextureRegions and/or a TextureAtlas, all you need to do in addition to that is call region.flip(false, true).
The reasons we use y-up by default (which you can easily change as illustrated above) are as follows:
your simulation code will most likely use a standard euclidian coordinate system with y-up
if you go 3D you have y-up
The default coordinate system is a right handed one in OpenGL, with y-up. You can of course easily change that with some matrix magic.
The only two places in libgdx where we use y-down are:
Pixmap coordinates (top upper left origin, y-down)
Touch event coordinates which are given in window coordinates (top upper left origin, y-down)
Again, you can easily change the used coordinate system to whatever you want using either Camera or a tiny bit of matrix math.

Just to expand a little on what badlogic said above, if you are using a TextureAtlas (with TextureRegions) you need to flip them, as badlogic said, in addition to the camera work. If you are using a TextureAtlas, you can use this code right after loading your atlas:
String textureFile = "data/textures.txt";
atlas = new TextureAtlas(Gdx.files.internal(textureFile), Gdx.files.internal("data"));
// Let's flip all the regions. Required for y=0 is TOP
Array<AtlasRegion> tr = atlas.getRegions();
for (int i = 0; i < tr.size; i++) {
TextureRegion t = tr.get(i);
t.flip(false, true);
}

If you want to hide the transformation and not think about it after setting it up once, you can make a class that inherits all of the functionalities you need, but first transforms the coordinates before passing it to its parent class's function. Unfortunately, this would take a lot of time.
You could alternatively make a method that does the simple y' = height - y transformation on the whole Coordinate object (or whatever it is you're using), and call it once before each operation.

Interesting graphics library, I would say. I found this assessment from the link below:
Another issue was that different coordinate systems were used in different parts of Libgdx. Sometimes the origin of the axes was in the
bottom left corner with the y-axis pointing upwards and sometimes in
the top left corner of the sprite pointing downwards. When drawing
Meshes the origin was even in the center of the screen. This caused
quite a bit of confusion and extra work to get everything in the
correct place on the screen.
http://www.csc.kth.se/utbildning/kandidatexjobb/datateknik/2011/rapport/ahmed_rakiv_OCH_aule_jonas_K11072.pdf

I just made a class that extends SpriteBatch that overides certain methods adding y = Gdx.graphics.getHeight() - y - height. Simple but effective.

I was able to get textures and fonts rendering correctly using the suggested flipped coordinate system via OrthographicCamera. Here's what I did:
private SpriteBatch batch;
private BitmapFont font;
private OrthographicCamera cam;
private Texture tex;
#Override
public void create () {
batch = new SpriteBatch();
font = new BitmapFont(true);
font.setColor(Color.WHITE);
cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
tex = new Texture("badlogic.jpg");
}
#Override
public void dispose() {
batch.dispose();
font.dispose();
tex.dispose();
}
#Override
public void render () {
cam.update();
batch.setProjectionMatrix(cam.combined);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Test", 50, 50);
batch.draw(tex, 100, 100, tex.getWidth(), tex.getHeight(), 0, 0, tex.getWidth(), tex.getHeight(), false, true);
batch.end();
}
Important things to notice are:
The BitmapFont constructor, the boolean flips the font
For batch.draw() you need to use all those parameters because you need a boolean flipY at the end to flip the texture (I may extend SpriteBatch or make a utility method to avoid passing so many parameters all the time.)
Notice batch.setProjectionMatrix(cam.combined); in render()
Now we will see if I am back here later tonight doing edits to fix any other issues or discoveries with doing all this.

Related

Sprites not fitting according to different screen resolutions on Libdx

I'm testing my sprite that has the game title, and on my Motorola Moto G 2nd generation the dimensions of the sprite looks good but I'm testing also on my mothers phone, a Samsung GT-S5830i, and the height of the sprite looks stretched out.
I'm also trying to understand the concept of Viewport (I'm using the StretchViewport), but I don't know if I'm doing right. My game are designed for mobile, not desktop.
I did that to my SplashScreen:
this.gameTitle = new Sprite(new Texture(Gdx.files.internal("images/GameTitle.png")));
this.gameTitle.setSize(Configuration.DEVICE_WIDTH - 50, this.gameTitle.getHeight() * Configuration.DEVICE_HEIGHT / Configuration.DEVICE_WIDTH);
The DEVICE_HEIGTH and DEVICE_WIDTH are constants about the dimension of the screen. And the "-50" is a margin to the sprite
In my Viewport I used the real size of the screen for the dimensions, or should I use a virtual dimension? But how it works?
This is a part of my main class, what can I change?
// Create the Orthografic camera
this.orthoCamera = new OrthographicCamera(Configuration.DEVICE_WIDTH, Configuration.DEVICE_HEIGHT);
this.orthoCamera.setToOrtho(false, Configuration.VIRTUAL_GAME_WIDTH, Configuration.VIRTUAL_GAME_HEIGHT);
this.orthoCamera.position.set(this.orthoCamera.viewportWidth / 2f, this.orthoCamera.viewportHeight / 2f, 0);
this.orthoCamera.update();
// Combine SpriteBatch with the camera
this.spriteBatch.setTransformMatrix(this.orthoCamera.combined);
// Create the ViewPort
this.viewPort = new ExtendViewport(Configuration.DEVICE_WIDTH, Configuration.DEVICE_HEIGHT);
I updated my viewport to the ExtendViewport as you said.
Main class render method:
public void render() {
super.render();
// Update Orthographic camera
this.orthoCamera.update();
// Combine SpriteBatch with the camera
this.spriteBatch.setTransformMatrix(this.orthoCamera.combined);
}
Screen class render method:
#Override
public void render(float delta) {
// OpenGL clear screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(Gdx.gl.GL_COLOR_BUFFER_BIT | Gdx.gl.GL_DEPTH_BUFFER_BIT);
// SpriteBatch begins
this.game.spriteBatch.begin();
// Display the ClimbUp logo
this.gameTitle.draw(this.game.spriteBatch);
this.character.draw(this.game.spriteBatch);
// SpriteBatch ends
this.game.spriteBatch.end();
}
If you don't want stuff to look distorted on some devices and you don't want black bars (which none of your customers will like), you need to use an ExtendViewport instead of StretchViewport. And the dimensions you give it should be virtual dimensions based on whatever units you would like to work with.
For example, assuming a landscape orientation game, you could use 800 x 480 as virtual dimensions, and then you know that anything within that area (in world units) will be shown on the screen and you can design your game for that. On narrower devices (4:3 ratio) there will be more than 480 vertical units shown, and on wider devices (16:9 ratio) there will be more than 800 horizontal units shown.
There's one other option that avoids black bars and distortion, and that's FillViewport. But I think in general that's not a good option because you have no easy way to predict how much of your virtual dimensions are going to get cropped off.
Based on your edited question, here's what I would change in your code:
//No need to create your own camera. ExtendViewport creates its own.
// Pointless to call this now before resize method is called. Call this in render
//XXX this.spriteBatch.setTransformMatrix(this.orthoCamera.combined);
//This is where you give the viewport its minimum virtual dimensions
this.viewPort = new ExtendViewport(Configuration.VIRTUAL_GAME_WIDTH, Configuration.VIRTUAL_GAME_HEIGHT);
//Get reference to the viewport's camera for use with your sprite batch:
this.orthoCamera = (OrthographicCamera) this.viewport.getCamera();
Then in the resize method:
orthoCamera.setPosition(/*wherever you want it*/);
viewport.update(width, height, false); //these are actual device width and height that are provided by the resize method parameters.
You might want to position your camera in relation to the size calculated by the viewport. Then you should omit the setPosition line above, and instead calculate it after calling viewport.update. For example if you want 0,0 in the bottom left of the screen:
viewport.update(width, height, false);
orthoCamera.setPosition(orthoCamera.viewportWidth/2f, orthoCamera.viewportHeight/2f);
In your render method you can put this before spriteBatch.begin():
orthoCamera.update(); //good idea to call this right before applying to SpriteBatch, in case you've moved it.
spriteBatch.setProjectionMatrix(orthoCamera.combined);

libGDX draw a text using a decals to 3d facing camera

I have a working code for drawing decals:
Init:
Decal decal = Decal.newDecal(1, 1,
new TextureRegion(new Texture(Gdx.files.internal("2d/gui/badlogic.jpg"))) );
decal.setPosition(10, 10, 10);
decal.setScale(3);
decals.add(decal);
Draw method:
for (int i = 0; i < decals.size; i++) {
Decal decal = decals.get(i);
decal.lookAt(stage3d.getCamera().position, stage3d.getCamera().up);
batch.add(decal);
}
batch.flush();
I have a working code for writing text in 3d:
Draw method:
spriteBatch.setProjectionMatrix(tmpMat4.set(camera.combined).mul(textTransform));
spriteBatch.begin();
font.draw(spriteBatch, "Testing 1 2 3", 0, 0);
spriteBatch.end();
But I have a trouble to make a facing text.
Thank you
I wouldn't try the Decal method because it's not set up for text. SpriteBatch is already set up for text.
(The Decal method could theoretically perform better because you wouldn't need a separate draw call for each string of text. However, you would have to roll your own version of BitmapFont and BitmapFontCache that is compatible with Decals. Of course, if you did that, you could submit a pull request and get it added to libgdx.)
That SpriteBatch code looks familar. :) Basically what you need to do is modify the textTransform matrix to cause it to rotate an object to face the camera. SpriteBatch is set up to draw flat stuff that is facing the Z direction. So you need to rotate a Z vector to face the camera.
First you will want a Vector3 that you can reuse.
private static Vector3 tmpVec3 = new Vector3();
Then you want to find the vector that points from the center of the text to the camera. I'm assuming you are storing the text's position in 3D space in a Vector3 called textPosition here:
tmpVec3.set(camera.position).sub(textPosition);
//tmpVec3 is now a vector pointing from the text to the camera.
Now you can position the object's matrix and then rotate it to face the camera like this:
textTransform.setToTranslation(textPosition).rotate(Vector3.Z, tmpVec3);
Now you can use the textTransform as in the code you posted. Make sure you set the BitmapFont's alignment to HAlignment.center or the text will rotate about the left end of the string of text instead of the center. You also probably want to set the integer parameter to false for drawing in 3D.

LibGDX - Drawing to a FrameBuffer does not work

So I'm trying to make custom buttons, for which I need to combine different parts of the button background. To do this I figured using a FrameBuffer would work, however it did not give viable results. Therefore I attempted to test my FrameBuffer drawing method, by writing a simple test method, which returns a texture that is drawn to the display at every render() call. This method is here (note that it is a test method, so it may be a little poorly optimized):
private Texture test()
{
BitmapFont f = ReverseBlade.fontTitle;
f.setColor(Color.LIGHT_GRAY);
FrameBuffer fbo = new FrameBuffer(Format.RGBA8888, (int)f.getBounds("Hi").width, (int)f.getBounds("Hi").height, false);
Batch b = ReverseBlade.batch;
OrthographicCamera c = new OrthographicCamera(fbo.getWidth(), fbo.getHeight());
c.setToOrtho(false);
c.update();
b.setProjectionMatrix(c.combined);
fbo.begin();
b.begin();
f.draw(b, "Hi", 0, 0);
b.end();
fbo.end();
Texture t = fbo.getColorBufferTexture();
fbo.dispose();
b.setProjectionMatrix(ReverseBlade.camera.combined);
return t;
}
However, nothing is displayed. The screen is dark... I have tried without the camera and multiple other variations that I can no longer remember. What am I doing wrong?
Half Solution
What I ended up having to do is to make a new Matrix4 object for the FrameBuffer like this:
Matrix4 m = new Matrix4();
m.setToOrtho2D(0, 0, fbo.getWidth(), fbo.getHeight());
batch.setProjectionMatrix(m);
However, this makes everything that is drawn be upside down, like this:
I think the fbo.dispose() call is destroying more than you want.
See the source and notice where it destroys the colorTexture, which is the result of getColorBufferTexture().
I think this could be considered a bug in Libgdx. The color texture is generally something that should have a very different lifetime than the FBO, so cleaning up the texture seems a bit too aggressive. However, trying to figure out which cases to clean the texture up is probably complicated.....
So following what I added with the Half Solution, all I had to do was create a new Sprite object with the texture from the FBo and call flip(false, true)!
May be this is a workaround to dispose() the framebuffer and keeping the texture alive. I do the following:
public class TextureSaveFBO extends FrameBuffer {
static final Texture DUMMY = new Texture(1, 1, Format.RGB565) {
public void dispose() {
};
};
public TextureSaveFBO(Format format, int width, int height,
boolean hasDepth) {
super(format, width, height, hasDepth);
}
#Override
public void dispose() {
// prevents the real texture of dispose()
Texture t = colorTexture;
colorTexture = DUMMY;
super.dispose();
colorTexture = t;
}
}
Just a precisation:
OrthographicCamera c = new OrthographicCamera(fbo.getWidth(), fbo.getHeight());
c.setToOrtho(false);
This is potentially harmful unless you know what you are doing: c.setOrtho(false) does the following:
Sets this camera to an orthographic projection using a viewport fitting the screen resolution, centered at (Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2), with the y-axis pointing up or down.
So even if you specified in the OrthographicCamera's constructor that you want the viewport to be of the frame buffer size, you are overwriting that with the following call to a viewport covering the screen size and centered to the screen center.
You should probably do:
camera.setToOrtho(false, fbo.getWidth(), fbo.getHeight());
Issue solved since LibGDX 1.6.5.
It's now possible to override disposeColorBuffer method to not dispose rendered texture.

libgdx create texture from overlay using pixmap

I am trying to create a method which returns a texture modified by an overlay using libgdx and PixMap.
Assuming I have 2 images:
A Base Image in FileHandle textureInput
And an overlay image in FileHandle overLay
It should produce this texture:
So it should use the RGB values from the textureInput and the alpha values from the overLay and create the final image. I believe I can do this using the Pixmap class but I just can't seem to find exactly how.
Here is what I gather should be the structure of the method:
public Texture getOverlayTexture(FileHandle overLay, FileHandle textureInput){
Pixmap inputPix = new Pixmap(textureInput);
Pixmap overlayPix = new Pixmap(overLay);
Pixmap outputPix = new Pixmap(inputPix.getWidth(), inputPix.getHeight(), Format.RGBA8888);
// go over the inputPix and add each byte to the outputPix
// but only where the same byte is not alpha in the overlayPix
Texture outputTexture = new Texture(outputPix, Format.RGBA8888, false);
inputPix.dispose();
outputPix.dispose();
overlayPix.dispose();
return outputTexture;
}
I am just looking for a bit of direction as to where to go from here. Any help is really appreciated. I apologize if this question is too vague or if my approach is entirely off.
Thanks!
I finally found the way to do this.
How my game is setup is that each item draws itself. They are handed a spritebatch and can do stuff with it. I did it that way various reasons. There is an item manager containing a list of items. Each item has various attributes. Each item has it's own render method along with other independent methods. Here is what finally worked:
A normal item's render method which does not use any alpha masking:
public void render(SpriteBatch batch, int renderLayer) {
if(renderLayer == Integer.parseInt(render_layer)){ // be in the correct render layer
batch.draw(item.region,
item.position.x, // position.x
item.position.y, // position.y
0, //origin x
0, //origin y
item.region.getRegionWidth() , //w
item.region.getRegionHeight(), //h
item.t_scale, //scale x
item.t_scale, //scale y
item.manager.radiansToDegrees(item.rotation)); //angle
}
}
So it is handed a spritebatch that it draws to with the correct image, location, scale, and rotation, and that is that.
After playing around with what I found here: https://gist.github.com/mattdesl/6076846 for a while, this finally worked for an item who needs to use alpha masking:
public void render(SpriteBatch batch, int renderLayer) {
if(renderLayer == Integer.parseInt(render_layer)){
batch.enableBlending();
//draw the alpha mask
drawAlphaMask(batch, item.position.x, item.position.y, item.region.getRegionWidth(), item.region.getRegionHeight());
//draw our foreground elements
drawForeground(batch, item.position.x, item.position.y, item.region.getRegionWidth(), item.region.getRegionHeight());
batch.disableBlending();
}
}
There is a TextureRegion named alphaMask which contains a black shape.
It can be any image, but let's say in this instance its this shape / image:
Here is the function called above that uses that image:
private void drawAlphaMask(SpriteBatch batch, float x, float y, float width, float height) {
//disable RGB color, only enable ALPHA to the frame buffer
Gdx.gl.glColorMask(false, false, false, true);
// Get these values so I can be sure I set them back to how it was
dst = batch.getBlendDstFunc();
src = batch.getBlendSrcFunc();
//change the blending function for our alpha map
batch.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ZERO);
//draw alpha mask sprite
batch.draw(alphaRegion,
x, // position.x
y, // position.y
0, // origin x
0, // origin y
alphaRegion.getRegionWidth(), // w
alphaRegion.getRegionHeight(), // h
item.t_scale, // scale x
item.t_scale, // scale y
item.manager.radiansToDegrees(item.rotation)); // angle
//flush the batch to the GPU
batch.flush();
}
There are a variety of "materials" to apply to any shape. In any instance one of them is assigned to the spriteRegion variable. Let's say right now it is this:
So the drawForeground method called above uses that image like this:
private void drawForeground(SpriteBatch batch, float clipX, float clipY, float clipWidth, float clipHeight) {
//now that the buffer has our alpha, we simply draw the sprite with the mask applied
Gdx.gl.glColorMask(true, true, true, true);
batch.setBlendFunction(GL10.GL_DST_ALPHA, GL10.GL_ONE_MINUS_DST_ALPHA);
batch.draw(spriteRegion,
clipX, // corrected center position.x
clipY, // corrected center position.y
0, //origin x
0, //origin y
spriteRegion.getRegionWidth() , //w
spriteRegion.getRegionHeight(), //h
item.t_scale, //scale x
item.t_scale, //scale y
item.manager.radiansToDegrees(item.rotation)); //angle
//remember to flush before changing GL states again
batch.flush();
// set it back to however it was before
batch.setBlendFunction(src, dst);
}
That all worked right away in the desktop build, and can produce "Brick Beams" (or whatever) in the game nicely:
However in Android and GWT builds (because after all, I am using libgdx) it did not incorporate the alpha mask, and instead rendered the full brick square.
After a lot of looking around I found this: https://github.com/libgdx/libgdx/wiki/Integrating-libgdx-and-the-device-camera
And so to fix this in Android I modified the MainActivity.java onCreate method like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
cfg.r = 8;
cfg.g = 8;
cfg.b = 8;
cfg.a = 8;
initialize(new SuperContraption("android"), cfg);
if (graphics.getView() instanceof SurfaceView) {
SurfaceView glView = (SurfaceView) graphics.getView();
// force alpha channel - I'm not sure we need this as the GL surface
// is already using alpha channel
glView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
}
}
And that fixes it for Android.
I still cannot figure out how to make it work properly in gwt, as I cannot figure out how to tell libgdx to tell GWT to tell webGl to go ahead and pay attention to the alpha channel. I'm interested in how to do something like this in an easier or less expensive way (though this seems to work fine).
If anyone knows how to make this work with GWT, please post as another answer.
Here is the non-working GWT build if you want to see the texture issue:
https://supercontraption.com/assets/play/index.html

libgdx coordinate system differences between rendering and touch input

I have a screen (BaseScreen implements the Screen interface) that renders a PNG image. On click of the screen, it moves the character to the position touched (for testing purposes).
public class DrawingSpriteScreen extends BaseScreen {
private Texture _sourceTexture = null;
float x = 0, y = 0;
#Override
public void create() {
_sourceTexture = new Texture(Gdx.files.internal("data/character.png"));
}
.
.
}
During rendering of the screen, if the user touched the screen, I grab the coordinates of the touch, and then use these to render the character image.
#Override
public void render(float delta) {
if (Gdx.input.justTouched()) {
x = Gdx.input.getX();
y = Gdx.input.getY();
}
super.getGame().batch.draw(_sourceTexture, x, y);
}
The issue is the coordinates for drawing the image start from the bottom left position (as noted in the LibGDX Wiki) and the coordinates for the touch input starts from the upper left corner. So the issue I'm having is that I click on the bottom right, it moves the image to the top right. My coordinates may be X 675 Y 13, which on touch would be near the top of the screen. But the character shows at the bottom, since the coordinates start from the bottom left.
Why is what? Why are the coordinate systems reversed? Am I using the wrong objects to determine this?
To detect collision I use camera.unproject(vector3). I set vector3 as:
x = Gdx.input.getX();
y = Gdx.input.getY();
z=0;
Now I pass this vector in camera.unproject(vector3). Use x and y of this vector to draw your character.
You're doing it right. Libgdx generally provides coordinate systems in their "native" format (in this case the native touch screen coordinates, and the default OpenGL coordinates). This doesn't create any consistency but it does mean the library doesn't have to get in between you and everything else. Most OpenGL games use a camera that maps relatively arbitrary "world" coordinates onto the screen, so the world/game coordinates are often very different from screen coordinates (so consistency is impossible). See Changing the Coordinate System in LibGDX (Java)
There are two ways you can work around this. One is transform your touch coordinates. The other is to use a different camera (a different projection).
To fix the touch coordinates, just subtract the y from the screen height. That's a bit of a hack. More generally you want to "unproject" from the screen into the world (see the
Camera.unproject() variations). This is probably the easiest.
Alternatively, to fix the camera see "Changing the Coordinate System in LibGDX (Java)", or this post on the libgdx forum. Basically you define a custom camera, and then set the SpriteBatch to use that instead of the default.:
// Create a full-screen camera:
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Set it to an orthographic projection with "y down" (the first boolean parameter)
camera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.update();
// Create a full screen sprite renderer and use the above camera
batch = new SpriteBatch(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.setProjectionMatrix(camera.combined);
While fixing the camera works, it is "swimming upstream" a bit. You'll run into other renderers (ShapeRenderer, the font renderers, etc) that will also default to the "wrong" camera and need to be fixed up.
I had same problem , i simply did this.
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
screenY = (int) (gheight - screenY);
return true;
}
and every time you want to take input from user dont use Gdx.input.getY();
instead use (Gdx.graphics.getHeight()-Gdx.input.getY())
that worked for me.
The link below discusses this problem.
Projects the given coords in world space to screen coordinates.
You need to use the method project(Vector3 worldCoords) in class com.badlogic.gdx.graphics.Camera.
private Camera camera;
............
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Create an instance of the vector and initialize it with the coordinates of the input event handler.
Vector3 worldCoors = new Vector3(screenX, screenY, 0);
Projects the worldCoors given in world space to screen coordinates.
camera.project(worldCoors);
Use projected coordinates.
world.hitPoint((int) worldCoors.x, (int) worldCoors.y);
OnTouch();
return true;
}

Categories