From e482f32da326bf3516e8a51aeded37ce020c5211 Mon Sep 17 00:00:00 2001 From: Bill Meltsner Date: Sat, 4 Feb 2012 17:18:57 -0500 Subject: [PATCH] Allow vertices in either clockwise or counter-clockwise order for newPolygonShape (fixes issue #326) --- src/modules/physics/box2d/Physics.cpp | 60 ++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 11 deletions(-) diff --git a/src/modules/physics/box2d/Physics.cpp b/src/modules/physics/box2d/Physics.cpp index 24af9063f..958b80ea4 100644 --- a/src/modules/physics/box2d/Physics.cpp +++ b/src/modules/physics/box2d/Physics.cpp @@ -93,29 +93,67 @@ namespace box2d int Physics::newPolygonShape(lua_State * L) { int argc = lua_gettop(L); - int vcount = (int)argc/2; - // 3 vertices - love::luax_assert_argc(L, 2 * 3); + if (argc%2 != 0) + return luaL_error(L, "Number of vertices must be a multiple of two."); + // 3 to 8 (b2_maxPolygonVertices) vertices + int vcount = argc / 2; + if (vcount < 3) + luaL_error(L, "Expected a minimum of 3 vertices, got %d.", vcount); + else if (vcount > b2_maxPolygonVertices) + luaL_error(L, "Expected a maximum of %d vertices, got %d.", b2_maxPolygonVertices, vcount); b2PolygonShape* s = new b2PolygonShape(); - b2Vec2 * vecs = new b2Vec2[vcount]; + bool reverse = false; + b2Vec2 edge1; + b2Vec2 vecs[b2_maxPolygonVertices]; - for (int i = 0;i 1) + { + b2Vec2 edge2 = vecs[i] - vecs[i-1]; + if (b2Cross(edge1, edge2) < 0.0f) + reverse = true; + edge1 = edge2; + } + } + } + + if (reverse) + { + for (int i = 0, j = vcount-1; i < j; ++i, --j) + { + b2Vec2 swap = vecs[i]; + vecs[i] = vecs[j]; + vecs[j] = swap; + } } s->Set(vecs, vcount); - PolygonShape * p = new PolygonShape(s); - delete[] vecs; luax_newtype(L, "PolygonShape", PHYSICS_POLYGON_SHAPE_T, (void*)p); - return 1; }