I am having banding issues with gradient related textures in my game and I can't seem to find what's the cause and how to solve it.
Here's what I am talking about: On the left is a gradient in my game, whereas on the right is a gradient generated in a gradient generator application(Tint). We can clearly see banding issues.
To create my gradient, I used this code to generate a Texture used to create an Image that I scale to fill the user's screen.
Pixmap pix = new Pixmap(2, 2, Pixmap.Format.RGBA8888);
pix.setColor(colorSchemes[backgroundColorScheme.ordinal()].getTopColor());
pix.fillRectangle(0,0,2,1);
pix.setColor(colorSchemes[backgroundColorScheme.ordinal()].getBottomColor());
pix.fillRectangle(0,1,2,1);
Texture texture = new Texture(pix);
texture.setFilter(Texture.TextureFilter.Linear,
Texture.TextureFilter.Linear);
pix.dispose();
I also have another issue with banding when I try to add fog-like actors on top of the background to animate it a bit. I scale them, change their opacity and move them around and again I get banding issues as highlighted in the picture below.
I am trying to replicate a background effect like in this game
https://www.youtube.com/watch?v=_vBczzj3NAU
I have this code in my render screen render loop:
#Override
public void render (float delta) {
Gdx.gl.glClearColor(0,0,0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
}
Any ideas on how I can solve those issues? Any help would be greatly appreciated.
Increasing the number of bits per color channel (I believe the default is 5 bits) to 8 bits fixed the banding problem for me.
In AndroidLauncher.java
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.r = config.g = config.b = config.a = 8;
In DesktopLauncher.java
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.r = config.g = config.b = config.a = 8;
Related
The past few days I've been trying to figure out a display bug I don't understand. I've been working on a simple 2d platformer with box2d and orthogonal Tiled maps. So far so good, the physics work and using the b2d debug renderer I can assert proper player fixture and camera movement through the level.
Now next step I've tried to load textures to display sprites instead of debug shapes. This is where I stumble. I can load animations for my player body/fixture, but when I use the setCenter() method to center the texture on the fixture it is always out of center.
I've tried approaches via halving texture witdths and heights hoping to center the texture on the player fixture but I get the exact same off position rendering. I've played aorund with world/camera/screen unit coordinates but the misalignement persists.
I'm creating the player in my Player class with the following code.
First I define the player in box2d:
//define player's physical behaviour
public void definePlayer() {
//definitions to later use in a body
BodyDef bdef = new BodyDef();
bdef.position.set(120 / Constants.PPM, 60 / Constants.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
//Define needed components of the player's main fixture
FixtureDef fdef = new FixtureDef();
PolygonShape shape = new PolygonShape();
shape.setAsBox(8 / Constants.PPM, 16 / Constants.PPM); //size of the player hitbox
//set the player's category bit
fdef.filter.categoryBits = Constants.PLAYER_BIT;
//set which category bits the player should collide with. If not mentioned here, no collision occurrs
fdef.filter.maskBits = Constants.GROUND_BIT |
Constants.GEM_BIT |
Constants.BRICK_BIT |
Constants.OBJECT_BIT |
Constants.ENEMY_BIT |
Constants.TREASURE_CHEST_BIT |
Constants.ENEMY_HEAD_BIT |
Constants.ITEM_BIT;
fdef.shape = shape;
b2body.createFixture(fdef).setUserData(this);
}
Then I call the texture Region to be drawn in the Player class constructor:
//define in box2d
definePlayer();
//set initial values for the player's location, width and height, initial animation.
setBounds(0, 0, 64 / Constants.PPM, 64 / Constants.PPM);
setRegion(playerStand.getKeyFrame(stateTimer, true));
And finally, I update() my player:
public void update(float delta) {
//center position of the sprite on its body
// setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);
setCenter(b2body.getPosition().x, b2body.getPosition().y);
setRegion(getFrame(delta));
//set all the boolean flags during update cycles approprietly. DO NOT manipulate b2bodies
//while the simulation happens! therefore, only set flags there, and call the appropriate
//methods outside the simulation step during update
checkForPitfall();
checkIfAttacking();
}
And my result is
this, facing right
and this, facing left
Update:
I've been trying to just run
setCenter(b2body.getPosition().x, b2body.getPosition().y);
as suggested, and I got the following result:
facing right and facing left.
The sprite texture flip code is as follows:
if((b2body.getLinearVelocity().x < 0 || !runningRight) && !region.isFlipX()) {
region.flip(true, false);
runningRight = false;
} else if ((b2body.getLinearVelocity().x > 0 || runningRight) && region.isFlipX()) {
region.flip(true, false);
runningRight = true;
}
I'm testing if either the boolean flag for facing right is set or the x-axis velocity of my player b2body has a positive/negative value and if my texture region is already flipped or not and then use libGDX's flip() accordingly. I should not be messing with fixture coords anywhere here, hence my confusion.
The coordinates of box2d fixtures are offsets from the position, the position isn't necessarily the center (although it could be depending on your shape definition offsets). So in your case i think the position is actually the lower left point of the box2d polygon shape.
In which case you don't need to adjust for width and height because sprites are also drawn from bottom left position. So all you need is ;
setPosition(b2body.getPosition().x , b2body.getPosition().y );
I'm guessing you flip the box2d body when the player looks left the position of the shape is now bottom right so the sprite offset of width/2 and height/2 is from the bottom right instead. So specifically when you are looking left you need an offset of
setPosition(b2body.getPosition().x - getWidth() , b2body.getPosition().y );
I think looking right will be fixed from this, but i don't know for sure how you handle looking left in terms of what you do to the body, but something is done because the offset changes entirely as shown in your capture. If you aren't doing some flipping you could add how you handle looking right to the question.
EDIT
It seems the answer was that the sprite wasn't centered in the sprite sheet and this additional space around the sprite caused the visual impression of being in the wrong place (see comments).
I have a line actor that might have other object that intersect with it, And I need to crop out that part.
Above is the image actor
this rectangle is also a image actor might appear randomly along the lines.
And this is the sample of the result I wanted to get. I need advice on how to achieve this with libgdx.
[EDIT]
As suggest I am trying to use fbo to draw into a buffer. Below is the code I am currently working on.
#Override
public void draw(Batch batch, float parentAlpha) {
fbo.begin();
getStage().getViewport().apply();
Gdx.gl.glClearColor(0f,0f,0f,0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.draw(trLine,position.x,position.y);
batch.flush();
fbo.end();
getStage().getViewport().apply();
batch.draw(fbo.getColorBufferTexture(),0,0);
}
I am able to buffer the draw into the buffer and draw it later but it happen to be different size. below is the code for creation and dispose of fbo. and it is outside of the draw loop.
fbo = new FrameBuffer(Pixmap.Format.RGBA8888,getStage().getViewport().getWidth(),getStage().getViewport().getHeight(),false,true);
[SOLVED FBO]
Below is the coding that have working fbo but the blending is not working as expected. Will keep trying until it works.
fbo.begin();
Gdx.gl.glClearColor(0f,0f,0f,0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(trLine,position.x,position.y);
batch.end();
int srcFunc = batch.getBlendSrcFunc();
int dstFunc = batch.getBlendDstFunc();
batch.enableBlending();
batch.begin();
batch.setBlendFunction(GL20.GL_ONE, GL20.GL_FUNC_REVERSE_SUBTRACT);
for(int i = 0 ; i < cropRectangles.size() ; i++){ batch.draw(cropTexture.get(i),cropRectangles.get(i).x,cropRectangles.get(i).y);
}
batch.end();
fbo.end();
getStage().getViewport().apply();
//reset blending before drawing the desire result
batch.begin();
batch.setBlendFunction(srcFunc, dstFunc);
batch.draw(fbo.getColorBufferTexture(),0,0);
batch.end();
But the output is not getting any blending effect. it is still a rectangle with filled white color.
[SOLVED FULL CODE]
I finally apply the equation correctly and able to reset it so it doesn't affect other things that I draw after this.
fbo.begin();
Gdx.gl.glClearColor(0f,0f,0f,0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(trLine,position.x,position.y);
batch.end();
int srcFunc = batch.getBlendSrcFunc();
int dstFunc = batch.getBlendDstFunc();
batch.enableBlending();
batch.begin();
batch.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA);
Gdx.gl.glBlendEquation(GL20.GL_FUNC_REVERSE_SUBTRACT);
for(int i = 0 ; i < cropRectangles.size() ; i++){
batch.draw(cropTexture.get(i),cropRectangles.get(i).x,cropRectangles.get(i).y);
}
batch.end();
batch.flush();
fbo.end();
Gdx.gl.glBlendEquation(GL20.GL_FUNC_ADD);
getStage().getViewport().apply();
batch.begin();
batch.setBlendFunction(srcFunc, dstFunc);
batch.draw(fbo.getColorBufferTexture(),0,0);
batch.end();
You can use blend mode to achieve this.Your rectangle should have 2 parts.
Outer part and transparent part.
Outer part is your actual part going to be draw as usual.
Transparent part will be another rectangle with a full alpha and you should use blending for this part.
Visual Blending Tool
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
This mode clearing intersection area, it seems like correct mode .
You can easly find example usages of blending in libgdx.
SpriteBatch sb = (SpriteBatch)batch;
// draw our destination image
sb.draw(dst, 0, 0);
sb.end();
// remember SpriteBatch's current functions
int srcFunc = sb.getBlendSrcFunc();
int dstFunc = sb.getBlendDstFunc();
// Let's enable blending
sb.enableBlending();
sb.begin();
// blend them
sb.setBlendFunction(GL20.GL_ONE, GL20.ONE_MINUS_SRC_ALPHA);
sb.draw(src, 0, 0);
// Reset
sb.end();
sb.begin();
sb.setBlendFunction(srcFunc, dstFunc);
Additionally you must change blend equation as well.
And its not unique for sprite batch so we need to change for all game.
//Equation for effect you want
Gdx.gl.glBlendEquation(GL20.GL_FUNC_REVERSE_SUBTRACT);
//After draw you should also reset this
Gdx.gl.glBlendEquation(GL20.GL_FUNC_ADD);
Now we should take this drawn to FrameBufferObject because transparent area will show background color of your spritebatch.
If it's okey for you then it's done but you want to see another texture at this transparent area like background image or something then we have one more step.
You should read this article for whats the purpose of FBO(FrameBufferObject)
Frame Buffer from official wiki
You need to use this for merge your sprites and transparent areas so you can use those as whole image and see through background images from transparent area.
Maybe using second viewport or sprite batch would be easier and much more efficient according to your game.
One solution for this situation, fill that rectangle with solid background color(i mean make one rectangle inside that rectangle ring). It will cropped out that part.
I am using a custom shader on cocos2dx 3.1 trying to accomplish an special effect on a sprite used as a background (has to cover the whole screen)
However If i do not use the shader, the sprite is perfectly scaled and positioned, but when i do use it its show way smaller and on the bottom left.
Here is how i load the sprite
this->background_image = Sprite::create(image_name->GetText());
// Add background shader
if (this->background_image)
{
const GLchar *shaderSource = (const GLchar*) CCString::createWithContentsOfFile("OverlayShader.fsh")->getCString();
GLProgram * p = new GLProgram();
p->initWithByteArrays(ccPositionTextureA8Color_vert, shaderSource);
p->link();
p->updateUniforms();
this->background_image->setGLProgram(p);
}
// Classroom will be streched to cover all of the game screen
Size bgImgSize = this->background_image->getContentSize();
Size windowSize = Director::getInstance()->getWinSize();
float xScaleFactor = windowSize.width/bgImgSize.width;
float yScaleFactor = (windowSize.height-MARGIN_SPACE+10)/bgImgSize.height;
this->background_image->setScale(xScaleFactor, yScaleFactor);
this->background_image->setPosition(Vec2(windowSize.width/2.0f,windowSize.height/2.0f + ((MARGIN_SPACE-10)/2.0)));
this->background_image->retain();
And this is the shader im trying to use (a simple one, once this works ill change it to a photoshop-overlay style one)
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
void main()
{
vec4 v_orColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);
float gray = dot(v_orColor.rgb, vec3(0.299, 0.587, 0.114));
gl_FragColor = vec4(gray, gray, gray, v_orColor.a);
}
My question is, what am i doing wrong? The first thing that comes to my mind is that the attribute pointers used on the vertex shader are not correct, but now i am using the default vertex shader.
I found the solution on another post, so i'll just quote it and link to that post:
Found the solution. The vert shader should not use the MVP matrix so I
loaded ccPositionTextureColor_noMVP_vert instead of
ccPositionTextureA8Color_vert.
Weird y-position offset using custom frag shader (Cocos2d-x)
I've been looking for the solution for some time and haven't yet found it. One of the functions of my app is to load an image and then to change its shape - e.g. I load a normal rectangular image, and then there are 2-3 buttons - change the image to a circle, triangular or some other shape. Is sth like that even possible with Bitmaps? I found a lot of interesting things about Nokia imaging SDK, but all the shape stuff i found was LensBlurEffect, which isn't exactly what i need.
If someone could point me in the right direction, I would be really grateful!
Thank You in advance for help!
Best regards,
Roman
I'm working on filters that draws shapes using Nokia Imaging SDK. To solve your problem, I created sample project that uses Nokia Imaging SDK's blend filter and my custom shape filters.
Actually you can do the same thing with shape image as David refers (background is black, foreground white) instead of using my custom filters (EllipseShapeFilter above example code).
Here is sample code;
var ellipseImage = new WriteableBitmap(1024, 768);
Rect origin = new Rect(new Point(512, 384), new Size(512, 384));
uint white = 0xff000000 | (255 << 16) | (255 << 8) | 255;
var image = LoadFromResources(new Uri(#"/BlendImageSample;component/Assets/Sample.jpg", UriKind.Relative));
using (var ellipseSource = new BitmapImageSource(ellipseImage.AsBitmap()))
using (var ellipse = new EllipseShapeFilter(ellipseSource, white, origin))
{
ellipseImage = await new WriteableBitmapRenderer(ellipse, ellipseImage).RenderAsync();
}
ImageViewer.Source = ellipseImage;
using (var backgroundSource = new BitmapImageSource(ellipseImage.AsBitmap()))
using (var foregroundSource = new BitmapImageSource(image.AsBitmap()))
using (var filterEffect = new FilterEffect(backgroundSource))
{
using (BlendFilter blendFilter = new BlendFilter())
{
blendFilter.ForegroundSource = foregroundSource;
blendFilter.BlendFunction = BlendFunction.Darken;
filterEffect.Filters = new[] { blendFilter };
var OutputBitmap = new WriteableBitmap(image.PixelWidth, image.PixelHeight);
var result = await new WriteableBitmapRenderer(filterEffect, OutputBitmap).RenderAsync();
ImageViewer.Source = result;
}
}
Github - BlendImageSample
Well the bitmap is always going to be rectangular, there is nothing you can do about that.
What you can do is make some pixels transparent, thus making the bitmap appear of a different shape.
One way to do this using the Nokia Imaging SDK is to use the BlendFilter to blend a transparent image (I suggest just a ColorImageSource) over the original image. You can provide different masks to create different "shapes."
I am drawing a PNG image to an HTML canvas and I have implemented a filter system to allow convolute filters to be executed against the image data before it is blitted to the canvas.
Does anyone have an idea how to create a glow effect using either a convolute kernel / matrix (I'm not sure what the terminology is but I'm talking about these: http://www.html5rocks.com/en/tutorials/canvas/imagefilters/) or by other means such as using the globalCompositeOperation (https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html)?
I am aware that you can start with a low opacity and a scaled image then increase opacity while scaling the image down a bit. This works to create a sort-of glow effect but only around the edge of an image.
In an ideal world it would be great to be able to designate areas of the image that have glow using a secondary glow texture. Any ideas on either scenario? :)
Hope the following is along the lines of what you were looking to do, I think it turned out pretty well. So I used the filter library code from the article, and just created a new glow filter for the library, since his code was done pretty well to begin with. Here is a Live Demo showing the glow effect in action.
This is the filter code that you need to add to the library
Filters.glow = function(pixels, passes, image, glowPasses){
for(var i=0; i < passes; i++){
pixels = Filters.convolute(pixels,
[1/9, 1/9, 1/9,
1/9, 1/9, 1/9,
1/9, 1/9, 1/9 ]);
}
var tempCanvas = document.createElement("canvas"),
glowCanvas = document.createElement("canvas"),
tCtx = tempCanvas.getContext("2d"),
gCtx = glowCanvas.getContext("2d");
tempCanvas.width = glowCanvas.width = pixels.width;
tempCanvas.height = tempCanvas.height = pixels.height;
tCtx.putImageData(pixels, 0, 0);
gCtx.drawImage(image, 0, 0);
gCtx.globalCompositeOperation = "lighter";
for(i = 0; i < glowPasses; i++){
gCtx.drawImage(tempCanvas,0,0);
}
return Filters.getPixels(glowCanvas);
}
And this is how you would use the above filter.
var glowImage = document.images[1],
glowMask = document.images[0],
c = document.getElementById("canvas"),
ctx = c.getContext("2d");
window.onload = function() {
var pData = Filters.filterImage(Filters.glow, glowImage, 5, glowMask, 2);
c.width = pData.width;
c.height = pData.height;
ctx.putImageData(pData, 0, 0);
}
You need to provide it with 2 images. The first is the image you want the glow to appear on, and the second is the actual glow mask that is applied to the image. You can then specify how many blur passes to perform, which makes the glow more prominent, and how many glow passes to perform, which add the glow to the image. I use the lighter global composition for the canvas which alpha blends it.
This article is a pretty great resource on creating a glow effect, its also where I got the graphics in order to test my results against theirs.