December 9, 2016

Box2dLights crash

Recently I started to use Box2dLights again and encountered frequent crashes resulting in the following output:
Program: C:\Program Files\Java\jdk1.8.0_112\bin\java.exe
File: ./Box2D/Collision/b2DynamicTree.h, Line 209
Expression: r.LengthSquared() > 0.0f


The cause is Box2dLight trying to raycast with identical start and end points in PositionalLight:
    protected void updateMesh() {
        for (int i = 0; i < rayNum; i++) {
            m_index = i;
            f[i] = 1f;
            tmpEnd.x = endX[i] + start.x;
            mx[i] = tmpEnd.x;
            tmpEnd.y = endY[i] + start.y;
            my[i] = tmpEnd.y;
            if (rayHandler.world != null && !xray) {
                rayHandler.world.rayCast(ray, start, tmpEnd);
            }
        }
        setMesh();
    }


Patching the light class with a simple check solved the issue:
            if (rayHandler.world != null && !xray && !start.equals(tmpEnd)) {
                rayHandler.world.rayCast(ray, start, tmpEnd);
            }


Instead of calling equals you could also directly call
NumberUtils.floatToIntBits