Box2d源码学习<十>形状(下):圆形和多边形的实现

本系列博客是由扭曲45原创,欢迎转载,转载时注明出处,http://blog.csdn.net/cg0206/article/details/8303010

我们今天就来看看另外两个形状的实现。

1、圆形,有坐标和半径,(有点废话了,没有坐标和半径的能叫圆吗?)。圆形不能是空心的,必须是实心的。下面我们就来看看圆形是如何实现的。在b2CircleShape.h文件中,我们来看看源码。

[cpp]  view plain copy
  1. //  圆形状 ,继承自b2Shape  
  2. class b2CircleShape : public b2Shape  
  3. {  
  4. public:  
  5.     /************************************************************************** 
  6.     * 功能描述:圆形构造函数 
  7.     * 参数说明:(void) 
  8.     * 返 回 值:(void) 
  9.     ***************************************************************************/  
  10.     b2CircleShape();  
  11.     /************************************************************************** 
  12.     * 功能描述:用soa块分配器克隆一个具体的形状【实现b2shape】 
  13.     * 参数说明: allocator :soa分配器对象指针 
  14.     * 返 回 值: (void) 
  15.     ***************************************************************************/  
  16.     b2Shape* Clone(b2BlockAllocator* allocator) const;  
  17.     /************************************************************************** 
  18.     * 功能描述:获取形状的子对象的数量 
  19.     * 参数说明: (void) 
  20.     * 返 回 值: 子对象数量 
  21.     ***************************************************************************/  
  22.     int32 GetChildCount() const;  
  23.     /************************************************************************** 
  24.     * 功能描述:在这个形状中测试这个点的密封性,只适合用于凸的形状 
  25.     * 参数说明: xf : 形状的变换 
  26.                  p  : world坐标中的一个点 
  27.     * 返 回 值: true : 密封 
  28.                  false:敞开 
  29.     ***************************************************************************/  
  30.     bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;  
  31.     /************************************************************************** 
  32.     * 功能描述:投射一束光到一个圆形状中 
  33.     * 参数说明: output      :输出光线投射的结果 
  34.                  input       :输入光线投射 
  35.                  transform   :变换应用到此形状中 
  36.                  childeIndex :孩子形状索引 
  37.     * 返 回 值:?++? true : 成功 
  38.                  false:失败 
  39.     ***************************************************************************/  
  40.     bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,  
  41.                 const b2Transform& transform, int32 childIndex) const;  
  42.     /************************************************************************** 
  43.     * 功能描述:给出一个变换,计算一个圆形状的轴对齐包围盒(aabb) 
  44.     * 参数说明: aabb       : 孩子形状的aabb指针 
  45.                  xf         : 一个变换的引用 
  46.                  childIndex : 孩子的索引值 
  47.     * 返 回 值: true : 成功 
  48.                  false:失败 
  49.     ***************************************************************************/  
  50.     void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const;  
  51.   
  52.     /************************************************************************** 
  53.     * 功能描述:用它的大小和密度计算形状的质量 
  54.     * 参数说明: massData   : 计算形状的质量 
  55.                  density    : 密度 
  56.     * 返 回 值: (void) 
  57.     ***************************************************************************/  
  58.     void ComputeMass(b2MassData* massData, float32 density) const;  
  59.     /************************************************************************** 
  60.     * 功能描述:根据既定的方向,得到支撑顶点索引 
  61.                 圆形没有顶点,故永远返回0 
  62.     * 参数说明: d :二维列向量 
  63.     * 返 回 值: 0 
  64.     ***************************************************************************/  
  65.     int32 GetSupport(const b2Vec2& d) const;  
  66.     /************************************************************************** 
  67.     * 功能描述:根据既定的方向,得到支持的顶点 
  68.                 获取支撑点索引,圆形没有顶点,故永远返回0 
  69.     * 参数说明: d :二维列向量 
  70.     * 返 回 值: 0 
  71.     ***************************************************************************/  
  72.     const b2Vec2& GetSupportVertex(const b2Vec2& d) const;  
  73.     /************************************************************************** 
  74.     * 功能描述:获取顶点数量 
  75.     * 参数说明:(void) 
  76.     * 返 回 值: 顶点数量 
  77.     ***************************************************************************/  
  78.     int32 GetVertexCount() const { return 1; }  
  79.     /************************************************************************** 
  80.     * 功能描述:通过索引获得一个顶点,用于b2Distance 
  81.     * 参数说明:(void) 
  82.     * 返 回 值: 坐标点 
  83.     ***************************************************************************/  
  84.     const b2Vec2& GetVertex(int32 index) const;  
  85.     //坐标点  
  86.     b2Vec2 m_p;  
  87. };  
  88. //构造函数  
  89. inline b2CircleShape::b2CircleShape()  
  90. {  
  91.     m_type = e_circle;  
  92.     m_radius = 0.0f;  
  93.     m_p.SetZero();  
  94. }  
  95. //获取支撑点索引,圆形没有顶点,故永远返回0  
  96. inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const  
  97. {  
  98.     B2_NOT_USED(d);  
  99.     return 0;  
  100. }  
  101. //获取支撑点数量  
  102. inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const  
  103. {  
  104.     B2_NOT_USED(d);  
  105.     return m_p;  
  106. }  
  107. //通过索引获得一个顶点,用于b2Distance  
  108. inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const  
  109. {  
  110.     B2_NOT_USED(index);  
  111.     b2Assert(index == 0);  
  112.     return m_p;  
  113. }  


圆形依然是继承自b2Shape,对虚函数进行了重新定义和实现。也许有人会注意到还有三个内联函数是上两个形状所没有的,关于它没有什么用,我们到b2Distance类时会进一步说明,现在留意一下就行。

关于b2CircleShape的实现,我们看下面代码就可:

[cpp]  view plain copy
  1. //用soa块分配器克隆一个具体的形状【实现b2shape】  
  2. b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const  
  3. {  
  4.     void* mem = allocator->Allocate(sizeof(b2CircleShape));  
  5.     b2CircleShape* clone = new (mem) b2CircleShape;  
  6.     *clone = *this;  
  7.     return clone;  
  8. }  
  9. //获取形状的子对象的数量  
  10. int32 b2CircleShape::GetChildCount() const  
  11. {  
  12.     return 1;  
  13. }  
  14. //在这个形状中测试这个点的密封性,只适合用于凸的形状  
  15. bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const  
  16. {  
  17.     b2Vec2 center = transform.p + b2Mul(transform.q, m_p);  
  18.     b2Vec2 d = p - center;  
  19.     return b2Dot(d, d) <= m_radius * m_radius;  
  20. }  
  21.   
  22.   
  23. // 《Collision Detection in Interactive 3D Environments》 by Gino van den Bergen  
  24. // 在3.1.2节,【从 http://download.csdn.net/detail/cg0206/4875309 下载】  
  25. // x = s + a * r  
  26. // norm(x) = radius  
  27. // (关于norm函数,请看 http://zh.wikipedia.org/wiki/范数 或   
  28. // http://en.wikipedia.org/wiki/Norm_(mathematics) )  
  29. bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,  
  30.                             const b2Transform& transform, int32 childIndex) const  
  31. {  
  32.     //消除警告  
  33.     B2_NOT_USED(childIndex);  
  34.     //  
  35.     b2Vec2 position = transform.p + b2Mul(transform.q, m_p);  
  36.     b2Vec2 s = input.p1 - position;  
  37.     float32 b = b2Dot(s, s) - m_radius * m_radius;  
  38.   
  39.     // 解决二元方程  
  40.     b2Vec2 r = input.p2 - input.p1;  
  41.     float32 c =  b2Dot(s, r);  
  42.     float32 rr = b2Dot(r, r);  
  43.     float32 sigma = c * c - rr * b;  
  44.     //检测负的判别式和短线段  
  45.     if (sigma < 0.0f || rr < b2_epsilon)  
  46.     {  
  47.         return false;  
  48.     }  
  49.     //找到线与圆的交叉点  
  50.     float32 a = -(c + b2Sqrt(sigma));  
  51.     // 判断交叉点是否在线段上  
  52.     if (0.0f <= a && a <= input.maxFraction * rr)  
  53.     {  
  54.         a /= rr;  
  55.         output->fraction = a;  
  56.         output->normal = s + a * r;  
  57.         output->normal.Normalize();  
  58.         return true;  
  59.     }  
  60.   
  61.     return false;  
  62. }  
  63.   
  64. //给出一个变换,计算一个圆形状的轴对齐包围盒(aabb)  
  65. void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const  
  66. {  
  67.     //消除警告  
  68.     B2_NOT_USED(childIndex);  
  69.     //获取变换后的变量,并重新设置aabb  
  70.     b2Vec2 p = transform.p + b2Mul(transform.q, m_p);  
  71.     aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius);  
  72.     aabb->upperBound.Set(p.x + m_radius, p.y + m_radius);  
  73. }  
  74. //用它的大小和密度计算形状的质量  
  75. void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const  
  76. {  
  77.     //获取形状的质量、质心  
  78.     massData->mass = density * b2_pi * m_radius * m_radius;  
  79.     massData->center = m_p;  
  80.     // 惯量相对于本地原点  
  81.     massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p));  
  82. }  

这次我们可以看到圆形是有质量、密封性为真的形状。剩下的就不多说了。看注释哈。

2、多边形

我们这里说的多边形是凸多边形,所谓凸多边形就是一条直线与该类多边形相交交点最多不超过两个。同时还是实心的,不能是空心。多边形的顶点范围应该在[3,b2_maxPolygonVertices]内,box2d中定义为8个,你也可以在公共模块的b2Settings.h文件中修改它的值,不过一般不建议那么做。好了,我们就来看看它的实现。

看b2PolygonShape.h文件。

[cpp]  view plain copy
  1. //一个凸多边形  
  2. // 多边形最多有b2_maxPolygonVertices个顶点  
  3. //在大多数情况下你不需要具有太多顶点的多边形  
  4. class b2PolygonShape : public b2Shape  
  5. {  
  6. public:  
  7.     /************************************************************************** 
  8.     * 功能描述:多边形构造函数,初始化数据 
  9.     * 参数说明: (void) 
  10.     * 返 回 值: (void) 
  11.     ***************************************************************************/  
  12.     b2PolygonShape();  
  13.     /************************************************************************** 
  14.     * 功能描述:用soa块分配器克隆一个具体的形状 
  15.     * 参数说明: allocator :soa分配器对象指针 
  16.     * 返 回 值: (void) 
  17.     ***************************************************************************/  
  18.     b2Shape* Clone(b2BlockAllocator* allocator) const;  
  19.   
  20.     /************************************************************************** 
  21.     * 功能描述:获取孩子形状个数,你可以使用它去创建形状 
  22.     * 参数说明: (void) 
  23.     * 返 回 值: 孩子形状个数 
  24.     ***************************************************************************/  
  25.     int32 GetChildCount() const;  
  26.     /************************************************************************** 
  27.     * 功能描述:复制顶点。假定所有的顶点定义了一个凸多边形 
  28.                 它假定了外部每一个边都是从右边开始的 
  29.                 顶点数在【3,b2_maxPolygonVertices】之间 
  30.     * 参数说明: vertices    :顶点数组 
  31.                  vertexCount :顶点数量 
  32.     * 返 回 值: (void) 
  33.     ***************************************************************************/  
  34.     void Set(const b2Vec2* vertices, int32 vertexCount);  
  35.     /************************************************************************** 
  36.     * 功能描述:构建一个包围着顶点轴对齐盒子 
  37.     * 参数说明: hx :半宽 
  38.                  hy :半高 
  39.     * 返 回 值: (void) 
  40.     ***************************************************************************/  
  41.     void SetAsBox(float32 hx, float32 hy);  
  42.     /************************************************************************** 
  43.     * 功能描述:构建一个包围着顶点确定方位的轴对齐盒子 
  44.     * 参数说明: hx    :半宽 
  45.                  hy    :半高 
  46.                  center:盒子的中心点 
  47.                  angle :盒子的旋转角度 
  48.     * 返 回 值: (void) 
  49.     ***************************************************************************/  
  50.     void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle);  
  51.   
  52.     /************************************************************************** 
  53.     * 功能描述:在这个形状中测试这个点的密封性,只适合用于凸的形状 
  54.     * 参数说明: xf : 形状的变换 
  55.                  p  : world坐标中的一个点 
  56.     * 返 回 值: true : 密封 
  57.                  false:敞开 
  58.     ***************************************************************************/  
  59.     bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;  
  60.   
  61.     /************************************************************************** 
  62.     * 功能描述:投射一束光到一个孩子形状中 
  63.     * 参数说明: output      :输出光线投射的结果 
  64.                  input       :输入光线投射 
  65.                  transform   :变换应用到此形状中 
  66.                  childeIndex :孩子形状索引 
  67.     * 返 回 值: true : 成功 
  68.                  false:失败 
  69.     ***************************************************************************/  
  70.     bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,  
  71.                     const b2Transform& transform, int32 childIndex) const;  
  72.   
  73.     /************************************************************************** 
  74.     * 功能描述:给出一个变换,计算一个孩子形状的轴对齐包围盒(aabb) 
  75.     * 参数说明: aabb       : 孩子形状的aabb指针 
  76.                  xf         : 一个变换的引用 
  77.                  childIndex : 孩子的索引值 
  78.     * 返 回 值: (void) 
  79.     ***************************************************************************/  
  80.     void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const;  
  81.   
  82.     /************************************************************************** 
  83.     * 功能描述:用它的大小和密度计算形状的质量 
  84.     * 参数说明: massData   : 计算形状的质量 
  85.                  density    : 密度 
  86.     * 返 回 值: (void) 
  87.     ***************************************************************************/  
  88.     void ComputeMass(b2MassData* massData, float32 density) const;  
  89.     /************************************************************************** 
  90.     * 功能描述:获取顶点数量 
  91.     * 参数说明: (void) 
  92.     * 返 回 值: 顶点数量 
  93.     ***************************************************************************/  
  94.     int32 GetVertexCount() const { return m_vertexCount; }  
  95.     /************************************************************************** 
  96.     * 功能描述:根据顶点索引获取一个顶点 
  97.     * 参数说明: index :索引值 
  98.     * 返 回 值: 顶点 
  99.     ***************************************************************************/  
  100.     const b2Vec2& GetVertex(int32 index) const;  
  101.     //重心坐标  
  102.     b2Vec2 m_centroid;  
  103.     //顶点坐标数组  
  104.     b2Vec2 m_vertices[b2_maxPolygonVertices];  
  105.     //法线数组  
  106.     b2Vec2 m_normals[b2_maxPolygonVertices];  
  107.     //顶点数量  
  108.     int32 m_vertexCount;  
  109. };  
  110.   
  111. //多边形构造函数,初始化数据  
  112. inline b2PolygonShape::b2PolygonShape()  
  113. {  
  114.     m_type = e_polygon;  
  115.     m_radius = b2_polygonRadius;  
  116.     m_vertexCount = 0;  
  117.     m_centroid.SetZero();  
  118. }  
  119. //根据顶点索引获取一个顶点  
  120. inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const  
  121. {  
  122.     //验证index的有效性  
  123.     b2Assert(0 <= index && index < m_vertexCount);  
  124.     return m_vertices[index];  
  125. }  

同样,多边形b2PolygonShape还是继承自b2Shape。b2PolygonShape也对父类中的虚函数进行了定义和实现。关于内联函数也不多说了,我们来看b2PolygonShape的具体实现吧,(有点小激动。。。嘿嘿)看b2PolygonShape.ccp文件。

[cpp]  view plain copy
  1. //用soa块分配器克隆一个具体的形状  
  2. b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const  
  3. {  
  4.     //在内存池中申请一块内存  
  5.     void* mem = allocator->Allocate(sizeof(b2PolygonShape));  
  6.     //在一块已存在的内存上分配对象  
  7.     //这是new的另外一种用法placement new  
  8.     //参照以下链接 http://blog.sina.com.cn/s/blog_69e905cd0100k51b.html  
  9.     //或 http://club.topsage.com/thread-2467284-1-1.html  
  10.     b2PolygonShape* clone = new (mem) b2PolygonShape;  
  11.     *clone = *this;  
  12.     return clone;  
  13. }  
  14. //构建一个包围着顶点轴对齐盒子  
  15. void b2PolygonShape::SetAsBgox(float32 hx, float32 hy)  
  16. {  
  17.     //初始化盒子顶点坐标  
  18.     m_vertexCount = 4;  
  19.     m_vertices[0].Set(-hx, -hy);  
  20.     m_vertices[1].Set( hx, -hy);  
  21.     m_vertices[2].Set( hx,  hy);  
  22.     m_vertices[3].Set(-hx,  hy);  
  23.     m_normals[0].Set(0.0f, -1.0f);  
  24.     m_normals[1].Set(1.0f, 0.0f);  
  25.     m_normals[2].Set(0.0f, 1.0f);  
  26.     m_normals[3].Set(-1.0f, 0.0f);  
  27.     m_centroid.SetZero();  
  28. }  
  29. //构建一个包围着顶点确定方位的轴对齐盒子  
  30. void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle)  
  31. {  
  32.     //初始化盒子顶点坐标  
  33.     m_vertexCount = 4;  
  34.     m_vertices[0].Set(-hx, -hy);  
  35.     m_vertices[1].Set( hx, -hy);  
  36.     m_vertices[2].Set( hx,  hy);  
  37.     m_vertices[3].Set(-hx,  hy);  
  38.     m_normals[0].Set(0.0f, -1.0f);  
  39.     m_normals[1].Set(1.0f, 0.0f);  
  40.     m_normals[2].Set(0.0f, 1.0f);  
  41.     m_normals[3].Set(-1.0f, 0.0f);  
  42.     m_centroid = center;  
  43.     //创建一个变换  
  44.     b2Transform xf;  
  45.     xf.p = center;  
  46.     xf.q.Set(angle);  
  47.     // 变换顶点和法线  
  48.     for (int32 i = 0; i < m_vertexCount; ++i)  
  49.     {  
  50.         m_vertices[i] = b2Mul(xf, m_vertices[i]);  
  51.         m_normals[i] = b2Mul(xf.q, m_normals[i]);  
  52.     }  
  53. }  
  54. //获取孩子形状个数,你可以使用它去创建形状  
  55. int32 b2PolygonShape::GetChildCount() const  
  56. {  
  57.     return 1;  
  58. }  
  59. /************************************************************************** 
  60. * 功能描述:计算重心坐标 
  61.       参见 http://www.cnblogs.com/jun930123/archive/2012/09/10/2678305.html 
  62. * 参数说明: vs   :顶点数组 
  63.              count:顶点数 
  64. * 返 回 值: 重心坐标 
  65. ***************************************************************************/  
  66. static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count)  
  67. {  
  68.     b2Assert(count >= 3);  
  69.   
  70.     b2Vec2 c; c.Set(0.0f, 0.0f);  
  71.     float32 area = 0.0f;  
  72.     //三角形的一个参考点  
  73.     //它的位置并不能改变结构(除了舍入误差)  
  74.     b2Vec2 pRef(0.0f, 0.0f);  
  75. #if 0  
  76.     // This code would put the reference point inside the polygon.  
  77.     for (int32 i = 0; i < count; ++i)  
  78.     {  
  79.         pRef += vs[i];  
  80.     }  
  81.     pRef *= 1.0f / count;  
  82. #endif  
  83.   
  84.     const float32 inv3 = 1.0f / 3.0f;  
  85.   
  86.     for (int32 i = 0; i < count; ++i)  
  87.     {  
  88.         // 三角形顶点  
  89.         b2Vec2 p1 = pRef;  
  90.         b2Vec2 p2 = vs[i];  
  91.         b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0];  
  92.         //三角形两边的向量  
  93.         b2Vec2 e1 = p2 - p1;  
  94.         b2Vec2 e2 = p3 - p1;  
  95.         //计算三角形面积  
  96.         // S = 1/2 * b2Cross(e1,e2)  
  97.         float32 D = b2Cross(e1, e2);  
  98.         float32 triangleArea = 0.5f * D;  
  99.         //获取面积之后  
  100.         area += triangleArea;  
  101.         // 面积加权重心  
  102.         c += triangleArea * inv3 * (p1 + p2 + p3);  
  103.     }  
  104.     //重心  
  105.     b2Assert(area > b2_epsilon);  
  106.     c *= 1.0f / area;  
  107.     return c;  
  108. }  
  109. //复制顶点  
  110. void b2PolygonShape::Set(const b2Vec2* vertices, int32 count)  
  111. {  
  112.     //验证顶点的个数  
  113.     b2Assert(3 <= count && count <= b2_maxPolygonVertices);  
  114.     m_vertexCount = count;  
  115.   
  116.     //拷贝顶点  
  117.     for (int32 i = 0; i < m_vertexCount; ++i)  
  118.     {  
  119.         m_vertices[i] = vertices[i];  
  120.     }  
  121.     // 计算法线,确保每条边的长度都不为0  
  122.     for (int32 i = 0; i < m_vertexCount; ++i)  
  123.     {  
  124.         //获取两个相邻点的索引  
  125.         int32 i1 = i;  
  126.         int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0;  
  127.         //获得边向量  
  128.         b2Vec2 edge = m_vertices[i2] - m_vertices[i1];  
  129.         b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);  
  130.         //计算法线,并标准化  
  131.         m_normals[i] = b2Cross(edge, 1.0f);  
  132.         m_normals[i].Normalize();  
  133.     }  
  134.   
  135. #ifdef _DEBUG  
  136.     //确保多边形是凸的和内部边是从左到右的  
  137.     for (int32 i = 0; i < m_vertexCount; ++i)  
  138.     {  
  139.         int32 i1 = i;  
  140.         int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0;  
  141.         b2Vec2 edge = m_vertices[i2] - m_vertices[i1];  
  142.   
  143.         for (int32 j = 0; j < m_vertexCount; ++j)  
  144.         {  
  145.             //不检查当前边上的顶点  
  146.             if (j == i1 || j == i2)  
  147.             {  
  148.                 continue;  
  149.             }  
  150.               
  151.             b2Vec2 r = m_vertices[j] - m_vertices[i1];  
  152.             //如果这个崩溃,你的多边形不是凸多边形,含有共线的边或者缠绕的顺序不对  
  153.             float32 s = b2Cross(edge, r);  
  154.             b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order");  
  155.         }  
  156.     }  
  157. #endif  
  158.     //计算重心  
  159.     m_centroid = ComputeCentroid(m_vertices, m_vertexCount);  
  160. }  
  161. //在这个形状中测试这个点的密封性,只适合用于凸的形状  
  162. bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const  
  163. {  
  164.     //转置  
  165.     b2Vec2 pLocal = b2MulT(xf.q, p - xf.p);  
  166.     //遍历整个顶点,便用  
  167.     for (int32 i = 0; i < m_vertexCount; ++i)  
  168.     {  
  169.         //判断点积  
  170.         float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);  
  171.         if (dot > 0.0f)  
  172.         {  
  173.             return false;  
  174.         }  
  175.     }  
  176.   
  177.     return true;  
  178. }  
  179. //光线投射  
  180. bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,  
  181.                                 const b2Transform& xf, int32 childIndex) const  
  182. {  
  183.     //消除编译器发出的警告  
  184.     B2_NOT_USED(childIndex);  
  185.     //把光线放进多边形的参照系中  
  186.     b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);  
  187.     b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);  
  188.     b2Vec2 d = p2 - p1;  
  189.     //  
  190.     float32 lower = 0.0f, upper = input.maxFraction;  
  191.   
  192.     int32 index = -1;  
  193.     //遍历所有节点  
  194.     for (int32 i = 0; i < m_vertexCount; ++i)  
  195.     {  
  196.         // p = p1 + a * d  
  197.         // dot(normal, p - v) = 0  
  198.         // dot(normal, p1 - v) + a * dot(normal, d) = 0  
  199.         float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1);  
  200.         float32 denominator = b2Dot(m_normals[i], d);  
  201.   
  202.         if (denominator == 0.0f)  
  203.         {     
  204.             if (numerator < 0.0f)  
  205.             {  
  206.                 return false;  
  207.             }  
  208.         }  
  209.         else  
  210.         {  
  211.             // 注意:  
  212.             // lower < numerator / denominator,其中 denominator < 0  
  213.             // 当 denominator <0 时,我们变换下面的不等式  
  214.             // lower < numerator / denominator <==>denominator * lower > numerator.  
  215.             if (denominator < 0.0f && numerator < lower * denominator)  
  216.             {  
  217.                 // 增加 lower  
  218.                 // 进入这半段  
  219.                 lower = numerator / denominator;  
  220.                 index = i;  
  221.             }  
  222.             else if (denominator > 0.0f && numerator < upper * denominator)  
  223.             {  
  224.                 //减小 upper  
  225.                 //进入余下的半段  
  226.                 upper = numerator / denominator;  
  227.             }  
  228.         }  
  229.         //有时候lower会有最小值b2_epsilon的误差,引起断言。  
  230.         //虽然表面上用最小值b2_epsilon可以使边缘形状工作,但是现在我们将单独处理  
  231.         //if (upper < lower - b2_epsilon)  
  232.         if (upper < lower)  
  233.         {  
  234.             return false;  
  235.         }  
  236.     }  
  237.     //验证lower有效性  
  238.     b2Assert(0.0f <= lower && lower <= input.maxFraction);  
  239.     //  
  240.     if (index >= 0)  
  241.     {  
  242.         output->fraction = lower;  
  243.         output->normal = b2Mul(xf.q, m_normals[index]);  
  244.         return true;  
  245.     }  
  246.   
  247.     return false;  
  248. }  
  249. //给出一个变换,计算一个孩子形状的轴对齐包围盒(aabb)  
  250. void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const  
  251. {  
  252.     B2_NOT_USED(childIndex);  
  253.     //获取上下界限  
  254.     b2Vec2 lower = b2Mul(xf, m_vertices[0]);  
  255.     b2Vec2 upper = lower;  
  256.     //变量所有顶点  
  257.     for (int32 i = 1; i < m_vertexCount; ++i)  
  258.     {  
  259.         b2Vec2 v = b2Mul(xf, m_vertices[i]);  
  260.         lower = b2Min(lower, v);  
  261.         upper = b2Max(upper, v);  
  262.     }  
  263.     //设置aabb  
  264.     b2Vec2 r(m_radius, m_radius);  
  265.     aabb->lowerBound = lower - r;  
  266.     aabb->upperBound = upper + r;  
  267. }  
  268. //计算形状质量  
  269. void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const  
  270. {  
  271.     //多边形质量(mass)、重心(centroid)、惯量(inertia)  
  272.     //ρ是多边形密度,也是在单位面积上的质量。  
  273.     //然后 质量mass = ρ* int(dA);  
  274.     //centroid.x = (1/mass) * ρ*int(x * dA)  
  275.     //centroid.y = (1/mass) * ρ*int(x * dB)  
  276.     //I = ρ*int((x*x+y*y) * dA)  
  277.     //我们可以计算这些部分,将凸多边形每个部分的三角形加起来。  
  278.     //求每部分的三角形,我们可以列一个关于三角形(u,v)坐标的二元方程式  
  279.     // x = x0 + e1x * u + e2x * v  
  280.     // y = y0 + e1y * u + e2y * v  
  281.     //其中 0 <= u && 0 <= v && u + v <= 1  
  282.     //我们将求的 u、v均在[0,1]之间  
  283.     //我们也用到两个向量的叉积【求三角形面积用】:D = cross(e1,e2)  
  284.     //三角形重心 centroid = (1/3) * (p1 + p2 + p3)  
  285.     //其余的推导是计算机代数啦。。。  
  286.     b2Assert(m_vertexCount >= 3);  
  287.   
  288.     b2Vec2 center; center.Set(0.0f, 0.0f);  
  289.     float32 area = 0.0f;  
  290.     float32 I = 0.0f;  
  291.     //s是每个形成的三角形的参考点  
  292.     //它的位置不会影响结果(除了舍入的误差)  
  293.     b2Vec2 s(0.0f, 0.0f);  
  294.     //将参考点s放入多边形内部  
  295.     for (int32 i = 0; i < m_vertexCount; ++i)  
  296.     {  
  297.         s += m_vertices[i];  
  298.     }  
  299.     s *= 1.0f / m_vertexCount;  
  300.   
  301.     const float32 k_inv3 = 1.0f / 3.0f;  
  302.   
  303.     for (int32 i = 0; i < m_vertexCount; ++i)  
  304.     {  
  305.         //三角形顶点  
  306.         b2Vec2 e1 = m_vertices[i] - s;  
  307.         b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i+1] - s : m_vertices[0] - s;  
  308.   
  309.         float32 D = b2Cross(e1, e2);  
  310.   
  311.         float32 triangleArea = 0.5f * D;  
  312.         area += triangleArea;  
  313.         // 面积加权重心  
  314.         center += triangleArea * k_inv3 * (e1 + e2);  
  315.   
  316.         float32 ex1 = e1.x, ey1 = e1.y;  
  317.         float32 ex2 = e2.x, ey2 = e2.y;  
  318.   
  319.         float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2;  
  320.         float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2;  
  321.   
  322.         I += (0.25f * k_inv3 * D) * (intx2 + inty2);  
  323.     }  
  324.     //总计质量  
  325.     massData->mass = density * area;  
  326.     //质心,一般也指重心,从概念上来说是有差别的,但通常我们用混淆了。  
  327.     b2Assert(area > b2_epsilon);  
  328.     center *= 1.0f / area;  
  329.     massData->center = center + s;  
  330.   
  331.     //转动惯量相对于当前的原点(s点)  
  332.     massData->I = density * I;  
  333.     // 移动质心到原始的物体原点  
  334.     massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));  
  335. }  

这段代码中,我们来看看SetAsBox(float32 hx,float32 hy)函数,注意一下我们传入的两个参数分别是这个盒子的宽度的一半和高度的一半,再者就是初始化4个顶点并设置质心。在看看ComputeCentroid函数,我们可以知道这可以获取重心的坐标,这里也可以说是获取质心的坐标,有人要问了,难道质心和重心是一样的吗?答案很明显不是一样的,要不然就不会在同一个物理学科中整出两个概念来了。不过,Box2d中假设质量分布和重力分布是一致的,所以两者是重合的。关于这方面的知识可以百度或者谷歌。点击“多边形重心”将会看到如何求解的博客。

再看设置一个多边形。Set函数通过给定的顶点数组和顶点数量,我们进行连接(按逆时针方向)并判断是否是凸多边形。如不是的话则断言。若是则继续初始化。

对于RayCast函数,还是计算公式,关于公式如何得到的,参照本书《CollisionDetection inInteractive 3D Environments》。计算多边形质量的函数ComputeMass注释里面有详细的解说,我们也不多说了。同时我们可以看到b2PolygonShape形状有质量、密封性为真的形状。

Ok,形状部分。。。oh,on,还有一个问题,没有解决,My God。大家还记得是什么问题吗?

(都知道!!!好吧,我错了。)

下面我们就来说说,在b2Shape类中如果析构函数不是虚函数的话,当我们申请一个父类(b2Shape)指针指向子类对象(如b2CircleShape)后,再来释放父类指针占用的内存的时候,只有父类的析构函数被调用,而子类的析构函数则不会被调用,这就可能引起内存泄漏。如果是父类析构是虚函数的话,则会自低而上的依次调用。


这次真的好了,形状部分,我们将暂时告一段落,晚安,明天还要上班,早点睡啦。。。


ps:

 

以上文章仅是一家之言,若有不妥、错误之处,请大家多多指出。同时也希望能与大家多多交流,共同进步。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值