Box2D libgdx polygon shape - libgdx

How come this works fine:
Vector2[] vertexArray = new Vector2[3];
vertexArray[0] = new Vector2(0f, 0f);
vertexArray[1] = new Vector2(1f, 1f);
vertexArray[2] = new Vector2(2f, 5f);
polygonShape.set(vertexArray);
and this gives a runtime error
Vector2[] vertexArray = new Vector2[3];
vertexArray[0] = new Vector2(0f, 0f);
vertexArray[1] = new Vector2(1f, 1f);
vertexArray[2] = new Vector2(2f, 2f);
polygonShape.set(vertexArray);
Error:
AL lib: (EE) alc_cleanup: 1 device not closed
Assertion failed!
Program: C:\Program Files\Java\jre1.8.0_25\bin\javaw.exe
File: /var/lib/jenkins/workspace/libgdx/extensions/gdx-box2d/gdx-box2d/jni/Box2D/Collision/Shapes/b2PolygonShape.cpp, Line 223
Expression: false
It does not make any sense. First code works fine and the triangle is drawn, but the second code does not. Can someone please explain what I'm doing wrong...

The vertices (0,0), (1,1), (2,2) are all in a straight line - they don't make a polygon. This causes an assertion to trigger, as shown in the error message (b2PolygonShape.cpp, Line 223)

Related

Few Vertices of mesh gets stick to the origin when making a soft body (sphere) and translating in libgdx?

I am trying to make a soft body by making a sphere and taking all the meshParts from it and making a soft body from that sphere.
and when I render it in libgdx I use a model of sphere so that the soft body is visible which translate as the soft body moves but few vertices are sticked to the spawn location (origin)
can anyone suggest me what am I doing wrong ?
this is my create method :
ModelBuilder modelBuilder1;
modelBuilder1 = new ModelBuilder();
final Material material = new Material(ColorAttribute.createDiffuse(Color.RED));
final long attributes = VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal;
final Model sphere = modelBuilder1.createSphere(2f, 2f, 2f, 24, 24, material, attributes);
meshPart = sphere.meshParts.get(0);
indexMap = BufferUtils.newShortBuffer(meshPart.size);
positionOffset = meshPart.mesh.getVertexAttribute(VertexAttributes.Usage.Position).offset;
normalOffset = meshPart.mesh.getVertexAttribute(VertexAttributes.Usage.Normal).offset;
softBodyBall = new btSoftBody(worldInfo, meshPart.mesh.getVerticesBuffer(), meshPart.mesh.getVertexSize(), positionOffset, 3, meshPart.mesh.getIndicesBuffer(), meshPart.offset, meshPart.size, indexMap, 0);
softBodyBall.setPose(true, false);
dynamicsWorld.addSoftBody(softBodyBall);
btSoftBody.Material pm = softBodyBall.appendMaterial();
softBodyBall.generateBendingConstraints(2, pm);
pm.setKLST(0.9f);
pm.setFlags(0);
softBodyBall.generateBendingConstraints(2, pm);
softBodyBall.setConfig_piterations(7);
softBodyBall.setConfig_kDF(0.2f);
softBodyBall.randomizeConstraints();
softBodyBall.setTotalMass(1);
softBodyBall.translate(new Vector3(1, 5, 1));
instance = new ModelInstance(sphere);
and this is my render method
softBodyBall.getVertices(meshPart.mesh.getVerticesBuffer(), softBodyBall.getNodeCount(), meshPart.mesh.getVertexSize(), 0);
softBodyBall.getWorldTransform(instance.transform);
final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime());
dynamicsWorld.stepSimulation(delta, 5, 1f / 30f);
batch.begin(camera);
batch.render(instance,environment);
batch.render(instances, environment);
batch.end();
here is the image how it looks like :
https://drive.google.com/file/d/1-9UjdlyIAotZPgrLKaoG0Dm5UEVLdzY1/view?usp=sharing
Found it.
needed to render each vertices.
softBodyBall.getVertices(meshPart.mesh.getVerticesBuffer(), meshPart.mesh.getVertexSize(), positionOffset, normalOffset,
meshPart.mesh.getIndicesBuffer(), meshPart.offset, meshPart.size, indexMap, 0);
this instead of
softBodyBall.getVertices(meshPart.mesh.getVerticesBuffer(), softBodyBall.getNodeCount(), meshPart.mesh.getVertexSize(), 0);

libgdx box2d occassional crash on createBody

My game crashes with this message:
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000066bcbd0d, pid=13948, tid=12700
# [...]
#
# Problematic frame:
# C [gdx-box2d64.dll+0xbd0d]
From log file:
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j com.badlogic.gdx.physics.box2d.World.jniCreateBody(JIFFFFFFFFZZZZZF)J+0
j com.badlogic.gdx.physics.box2d.World.createBody(Lcom/badlogic/gdx/physics/box2d/BodyDef;)Lcom/badlogic/gdx/physics/box2d/Body;+80
j de.tennoxlab.cellolution.Food.<init>(Lde/tennoxlab/cellolution/CellWorld;FFZZ)V+115
j de.tennoxlab.cellolution.CellWorld.generateFood(IFFFFZ)V+54
J 89 C2 de.tennoxlab.cellolution.CellWorld.update()V (159 bytes) # 0x00000000024623b4 [0x0000000002461c60+0x754]
j de.tennoxlab.cellolution.Cellolution.render()V+40
j com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop()V+698
j com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run()V+27
v ~StubRoutines::call_stub
Full log: http://pastebin.com/QjY3msYS
From all the other posts with similar crashes it is probably some world modification when it shouldn't happen.
The crash occurs during the creation of new Food objects:
// generateFood() - called during World.update
for (int i = 0; i < count; i++) {
float x = minX + (float) Math.random() * (maxX - minX);
float y = minY + (float) Math.random() * (maxY - minY);
Gdx.app.debug("World", "Generating food piece "+i);
this.foods.add(new Food(this, x, y, animateGrowth, this.renderable));
}
in the Food constructor:
// in Food(...) constructor
BodyDef bodyDef = new BodyDef(); //TODO: set to sleep on init?
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(x, y);
bodyDef.linearDamping = 0.5f;
bodyDef.angularDamping = 1f;
Gdx.app.debug("Food", "Init body with " + bodyDef + " at " + x + "," + y);
foodBody = world.box2dWorld.createBody(bodyDef); // <== HERE IS WHERE THE CRASH HAPPENS
CircleShape shape = new CircleShape();
shape.setRadius(getSizeFromEnergy());
fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.2f;
fixture = foodBody.createFixture(fixtureDef);
fixture.setUserData(this);
shape.dispose();
But it only happens occassionally, sometimes after minutes of gameplay (when the generateFood code was executed successfully hundreds of times). So I thought, the crash must have something to do with what happens with the world BEFORE the Food generation. So I started enabling and disabling code, until I found out, that the crash only happens, when after the destruction of box2d bodies of my Cell objects:
public void update() { // Cell.update - called during World.update
if (this.energy <= 0) {
world.cells.remove(this);
Vector2 pos = cellBody.getPosition();
Gdx.app.debug("Cell", "Destroying " + cellBody+" at "+pos.x+","+pos.y);
world.box2dWorld.destroyBody(cellBody); // -> Without this line, the crashes don't happen!
return;
}
}
Here's the log:
World: Generating food piece 99
Food: Init body with com.badlogic.gdx.physics.box2d.BodyDef#72aff016 at -28.201607,-56.101532
World: Removing cell: de.tennoxlab.cellolution.Cell#7cbb6f2c
Cell: Destroying com.badlogic.gdx.physics.box2d.Body#757ff1ad at -51.92446,-56.464954
World: Removing cell: de.tennoxlab.cellolution.Cell#7cbb6f2c
Cell: Destroying com.badlogic.gdx.physics.box2d.Body#757ff1ad at -51.92446,-56.464954
World: Generating 100 new food pieces
World: Generating food piece 0
Food: Init body with com.badlogic.gdx.physics.box2d.BodyDef#3828ef8f at 14.653984,96.249084
[...]
World: Generating food piece 21
Food: Init body with com.badlogic.gdx.physics.box2d.BodyDef#2b91d887 at -15.35305,13.934067
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000066bcbd0d, pid=9792, tid=13288
#
I solved it myself. It was a nasty little bug like in probably all the other problems like that.
As you can see in the log file, the same Cell is deleted twice:
World: Removing cell: de.tennoxlab.cellolution.Cell#7cbb6f2c
Cell: Destroying com.badlogic.gdx.physics.box2d.Body#757ff1ad at -51.92446,-56.464954
World: Removing cell: de.tennoxlab.cellolution.Cell#7cbb6f2c
Cell: Destroying com.badlogic.gdx.physics.box2d.Body#757ff1ad at -51.92446,-56.464954
When I realised that I quickly found the issue: I have been adding the Player cell to the list twice, thus updating it twice, destroying it twice - which box2d obviously didn't like.
As these 'solutions' to crashes like these don't really help if you got this crash yourself (because your bug will be something else), I can only suggest trying to figure out the problem by rigorious debugging. (I added tons of debug log lines everywhere and examined the output - for many hours...) Because mistakes like these happen. For some more frequently, for some less frequently, but they happen.
Something else I want to add: box2d crash messages are really unhelpful. It is really hard to find out, what **really* caused the crash. That sucks. I wish there would be more debugging information, more safety checks and stuff like that in the library itself (or libgdx, maybe).
I'm really looking forward to more of those (seemingly) unsolvable bugs/crashes during the ongoing developement of the game :Z
You already solved your problem but if someone stubles upon this thread: In my case the issue was, that a Box2D world was disposed twice.

RayTest failing when there is a transform

I have a problem getting ray testing working in bullet physics.
The raytest only works for objects which have an identity transform. If there is any translation, then the ray test is calculated wrong. This is the code:
[code]
btTransform trans;
trans.setIdentity();
trans.setFromOpenGLMatrix(matrix.m);
btDefaultMotionState* motionState = new btDefaultMotionState(trans);
btRigidBody::btRigidBodyConstructionInfo rbInfo(
0, motionState, m_pVertexBuffer->GetBulletShape(), btVector3(0,0,0));
btRigidBody* body = new btRigidBody(rbInfo);
g_physics.GetWorld()->addRigidBody(body);
....
g_physics.GetWorld()->updateAabbs();
g_physics.GetWorld()->computeOverlappingPairs();
btVector3 btStart(x1, y1, z1);
btVector3 btEnd(x2, y2, z2);
btCollisionWorld::ClosestRayResultCallback ray(btStart, btEnd);
// Perform raycast
g_physics.GetWorld()->rayTest(btStart, btEnd, ray);
if (ray.hasHit())
{
btEnd = ray.m_hitPointWorld;
}
[/code]
Now, my game is using the z-axis as up, but that shouldn't be a problem as the ray is also entered as z up.

Flex-AS3 weired issue with Point

I was trying to convert global coordinates to local coordinates of a UIComplenent in my flex project using below code using below code
var gp:Point = new Point(e.stageX,e.stageY); //global point
var lp:Point = uic.globalToLocal(gp); //local point
uic is UIComponent in which I have subclass of Sprite for drawing something
I have set the sprite's mouseEnabled and mouseChildren to false to not interrupt the mouse event.
above code is within uic's mousemove event where I was tracing the gp and lp gp was giving correct value and suprisingly lp was giving negetive values. when I move the move to the top left corner of uic i expect lp to be 0,0 but it is giving the -width of of uic. I broke my head for hours and ended up finding an alternate by using offsets. Infact my original code was much simpler like this which was same issue
var lp:Point = new Point(e.localX,e.localY);
I am not sure what exactly is causing this problem. the workaround had lot of issues and it creating a mess in my rest of the algorithms.
Just now I found even more interesting thing (which is actually weird). for some reason I went and create a new lp2
var lp2:Point = new Point(e.localX,e.localY);
now surprisingly it was giving correct values as expected and I went back and changed the code as
var gp:Point = new Point(e.stageX,e.stageY); //global point
var lp:Point = uic.globalToLocal(gp); //local point
var lp2:Point = new Point(e.localX,e.localY);
var lp2:Point = uic.globalToLocal(gp);
now it is expected to have all the lp, lp2 and lp3 variables to be same but weiredly lp two is giving wrong value and lp2 and lp3 were giving correct. I am suspecting using the variable lp has something to do. I am not sure about that but above proves it so right now I am using lp2.
does any one know why is this behavior? is it a bug? or am I overseen something?
Admittedly, I didn't look at your previous questions before leaving my comment :) I take it your questions seem to leave people quite perplex... It's probably due to the way you present them as totally abstract behaviors.
Taking the example above, I'm not sure you're going the right way about the globalToLocal method.
My understanding of globalToLocal is that given a Point and a DisplayObject, globalToLocal will return the position of the Point in relation to the DisplayObject.
var pt:Point = new Point ( 10, 20 ); // x, y in relation to the Stage
var shape:Shape = new Shape();
shape.x = 10;
shape.y = 30;
// x, y should trace 0 , 10 , which is the position of the
//point in relation to shape.
pt = shape.globalToLocal(pt );
//or if you prefer to declare a new variable
var pointToShape:Point = shape.globalToLocal(pt );
In your example you state that you're trying to get the local coordinates of uic , your UIComponent , when in fact you're only returning the values of your Mouse position in relation to uic. Then you state:
"now it is expected to have all the lp, lp2 and lp3 variables to be the same "
No , because you keep redeclaring your variables:
var lp2:Point = new Point(e.localX,e.localY);
//the next declaration/statement cancels the previous one
var lp2:Point = uic.globalToLocal(gp);
Please note that once a variable has been declared , it is not necessary to redeclare it in subsequent statements. In the example above , there's no relationships between the two lp2 declaration, you may as well write:
var x:int = 10;
x = 20;
x = whatever;// each statement practically cancels the previous one.

Fourier Transform + emgucv

Can anybody tell me what is the problem in this code...
Basically I am trying to compute the dft of the image and show it as an image on my screen.
Image<Gray, float> GreyOriginalImage = new Image<Gray, float>(strFileName);
Matrix<float> imageMat = new Matrix<float>( CvInvoke.cvGetOptimalDFTSize( GreyOriginalImage.Rows ) , CvInvoke.cvGetOptimalDFTSize( GreyOriginalImage.Cols ) );
GreyOriginalImage.CopyTo( imageMat.GetSubRect( GreyOriginalImage.ROI ) );
CvInvoke.cvDFT( imageMat , imageMat , Emgu.CV.CvEnum.CV_DXT.CV_DXT_FORWARD , imageMat.Rows );
GreyFourierImage = new Image<Gray, float>( imageMat.Rows , imageMat.Cols );
imageMat.CopyTo( GreyFourierImage );
ImageBox2.Image = GreyFourierImage;
imageBox2.Show();
The problem is that the code hangs up while executing and no image gets shown....
I am using Visual studio 2010 with emgu cv.
Well I've gone over your code and debugged it the problem line is here:
imageMat.CopyTo( GreyFourierImage );
You are trying to copy imageMat which is a float[,] array to an image float[,,*] I'm sure you can figure out that this just doesn't work and is why the program hangs.
Here is the code that splits the Imaginary and Real parts from cvDFT:
Image<Gray, float> image = new Image<Gray, float>(open.FileName);
IntPtr complexImage = CvInvoke.cvCreateImage(image.Size, Emgu.CV.CvEnum.IPL_DEPTH.IPL_DEPTH_32F, 2);
CvInvoke.cvSetZero(complexImage); // Initialize all elements to Zero
CvInvoke.cvSetImageCOI(complexImage, 1);
CvInvoke.cvCopy(image, complexImage, IntPtr.Zero);
CvInvoke.cvSetImageCOI(complexImage, 0);
Matrix<float> dft = new Matrix<float>(image.Rows, image.Cols, 2);
CvInvoke.cvDFT(complexImage, dft, Emgu.CV.CvEnum.CV_DXT.CV_DXT_FORWARD, 0);
//The Real part of the Fourier Transform
Matrix<float> outReal = new Matrix<float>(image.Size);
//The imaginary part of the Fourier Transform
Matrix<float> outIm = new Matrix<float>(image.Size);
CvInvoke.cvSplit(dft, outReal, outIm, IntPtr.Zero, IntPtr.Zero);
//Show The Data
CvInvoke.cvShowImage("Real", outReal);
CvInvoke.cvShowImage("Imaginary ", outIm);
Cheers,
Chris