1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 #include <box2dtools.hxx>
11 #include <config_box2d.h>
14 #include <shapemanager.hxx>
15 #include <attributableshape.hxx>
16 #include <basegfx/polygon/b2dpolypolygontools.hxx>
17 #include <basegfx/polygon/b2dpolygontools.hxx>
18 #include <basegfx/polygon/b2dpolygontriangulator.hxx>
20 #include <svx/svdobj.hxx>
21 #include <svx/svdoashp.hxx>
22 #include <svx/svdpage.hxx>
24 #include <svx/unoapi.hxx>
27 #define BOX2D_SLIDE_SIZE_IN_METERS 100.00f
28 constexpr double fDefaultStaticBodyBounciness(0.1);
30 namespace box2d::utils
34 double calculateScaleFactor(const ::basegfx::B2DVector
& rSlideSize
)
36 double fWidth
= rSlideSize
.getX();
37 double fHeight
= rSlideSize
.getY();
39 // Scale factor is based on whatever is the larger
40 // value between slide width and height
42 return BOX2D_SLIDE_SIZE_IN_METERS
/ fWidth
;
44 return BOX2D_SLIDE_SIZE_IN_METERS
/ fHeight
;
47 b2BodyType
getBox2DInternalBodyType(const box2DBodyType eType
)
52 case BOX2D_STATIC_BODY
:
54 case BOX2D_KINEMATIC_BODY
:
55 return b2_kinematicBody
;
56 case BOX2D_DYNAMIC_BODY
:
57 return b2_dynamicBody
;
61 box2DBodyType
getBox2DLOBodyType(const b2BodyType eType
)
67 return BOX2D_STATIC_BODY
;
68 case b2_kinematicBody
:
69 return BOX2D_KINEMATIC_BODY
;
71 return BOX2D_DYNAMIC_BODY
;
75 b2Vec2
convertB2DPointToBox2DVec2(const basegfx::B2DPoint
& aPoint
, const double fScaleFactor
)
77 return { static_cast<float>(aPoint
.getX() * fScaleFactor
),
78 static_cast<float>(aPoint
.getY() * -fScaleFactor
) };
81 // expects rTriangleVector to have coordinates relative to the shape's bounding box center
82 void addTriangleVectorToBody(const basegfx::triangulator::B2DTriangleVector
& rTriangleVector
,
83 b2Body
* aBody
, const float fDensity
, const float fFriction
,
84 const float fRestitution
, const double fScaleFactor
)
86 for (const basegfx::triangulator::B2DTriangle
& aTriangle
: rTriangleVector
)
88 b2FixtureDef aFixture
;
89 b2PolygonShape aPolygonShape
;
90 b2Vec2 aTriangleVertices
[3]
91 = { convertB2DPointToBox2DVec2(aTriangle
.getA(), fScaleFactor
),
92 convertB2DPointToBox2DVec2(aTriangle
.getB(), fScaleFactor
),
93 convertB2DPointToBox2DVec2(aTriangle
.getC(), fScaleFactor
) };
95 bool bValidPointDistance
= true;
97 // check whether the triangle has degenerately close points
98 for (int nPointIndexA
= 0; nPointIndexA
< 3; nPointIndexA
++)
100 for (int nPointIndexB
= 0; nPointIndexB
< 3; nPointIndexB
++)
102 if (nPointIndexA
== nPointIndexB
)
105 if (b2DistanceSquared(aTriangleVertices
[nPointIndexA
],
106 aTriangleVertices
[nPointIndexB
])
109 bValidPointDistance
= false;
114 if (bValidPointDistance
)
116 // create a fixture that represents the triangle
117 aPolygonShape
.Set(aTriangleVertices
, 3);
118 aFixture
.shape
= &aPolygonShape
;
119 aFixture
.density
= fDensity
;
120 aFixture
.friction
= fFriction
;
121 aFixture
.restitution
= fRestitution
;
122 aBody
->CreateFixture(&aFixture
);
127 // expects rPolygon to have coordinates relative to it's center
128 void addEdgeShapeToBody(const basegfx::B2DPolygon
& rPolygon
, b2Body
* aBody
, const float fDensity
,
129 const float fFriction
, const float fRestitution
, const double fScaleFactor
)
131 // make sure there's no bezier curves on the polygon
132 assert(!rPolygon
.areControlPointsUsed());
133 basegfx::B2DPolygon aPolygon
= basegfx::utils::removeNeutralPoints(rPolygon
);
135 // value that somewhat defines half width of the quadrilateral
136 // that will be representing edge segment in the box2d world
137 const float fHalfWidth
= 0.1f
;
138 bool bHasPreviousQuadrilateralEdge
= false;
139 b2Vec2 aQuadrilateralVertices
[4];
141 for (sal_uInt32 nIndex
= 0; nIndex
< aPolygon
.count(); nIndex
++)
143 b2FixtureDef aFixture
;
144 b2PolygonShape aPolygonShape
;
146 basegfx::B2DPoint aPointA
;
147 basegfx::B2DPoint aPointB
;
150 // get two adjacent points to create an edge out of
151 aPointA
= aPolygon
.getB2DPoint(nIndex
- 1);
152 aPointB
= aPolygon
.getB2DPoint(nIndex
);
154 else if (aPolygon
.isClosed())
156 // start by connecting the last point to the first one
157 aPointA
= aPolygon
.getB2DPoint(aPolygon
.count() - 1);
158 aPointB
= aPolygon
.getB2DPoint(nIndex
);
160 else // the polygon isn't closed, won't connect last and first points
165 // create a vector that represents the direction of the edge
166 // and make it a unit vector
167 b2Vec2
aEdgeUnitVec(convertB2DPointToBox2DVec2(aPointB
, fScaleFactor
)
168 - convertB2DPointToBox2DVec2(aPointA
, fScaleFactor
));
169 aEdgeUnitVec
.Normalize();
171 // create a unit vector that represents Normal of the edge
172 b2Vec2
aEdgeNormal(-aEdgeUnitVec
.y
, aEdgeUnitVec
.x
);
174 // if there was an edge previously created it should just connect
175 // using it's ending points so that there are no empty spots
176 // between edge segments, if not use wherever aPointA is at
177 if (!bHasPreviousQuadrilateralEdge
)
179 // the point is translated along the edge normal both directions by
180 // fHalfWidth to create a quadrilateral edge
181 aQuadrilateralVertices
[0]
182 = convertB2DPointToBox2DVec2(aPointA
, fScaleFactor
) + fHalfWidth
* aEdgeNormal
;
183 aQuadrilateralVertices
[1]
184 = convertB2DPointToBox2DVec2(aPointA
, fScaleFactor
) + -fHalfWidth
* aEdgeNormal
;
185 bHasPreviousQuadrilateralEdge
= true;
187 aQuadrilateralVertices
[2]
188 = convertB2DPointToBox2DVec2(aPointB
, fScaleFactor
) + fHalfWidth
* aEdgeNormal
;
189 aQuadrilateralVertices
[3]
190 = convertB2DPointToBox2DVec2(aPointB
, fScaleFactor
) + -fHalfWidth
* aEdgeNormal
;
192 // check whether the edge would have degenerately close points
193 bool bValidPointDistance
194 = b2DistanceSquared(aQuadrilateralVertices
[0], aQuadrilateralVertices
[2]) > 0.003f
;
196 if (bValidPointDistance
)
198 // create a quadrilateral shaped fixture to represent the edge
199 aPolygonShape
.Set(aQuadrilateralVertices
, 4);
200 aFixture
.shape
= &aPolygonShape
;
201 aFixture
.density
= fDensity
;
202 aFixture
.friction
= fFriction
;
203 aFixture
.restitution
= fRestitution
;
204 aBody
->CreateFixture(&aFixture
);
206 // prepare the quadrilateral edge for next connection
207 aQuadrilateralVertices
[0] = aQuadrilateralVertices
[2];
208 aQuadrilateralVertices
[1] = aQuadrilateralVertices
[3];
213 void addEdgeShapeToBody(const basegfx::B2DPolyPolygon
& rPolyPolygon
, b2Body
* aBody
,
214 const float fDensity
, const float fFriction
, const float fRestitution
,
215 const double fScaleFactor
)
217 for (const basegfx::B2DPolygon
& rPolygon
: rPolyPolygon
)
219 addEdgeShapeToBody(rPolygon
, aBody
, fDensity
, fFriction
, fRestitution
, fScaleFactor
);
224 box2DWorld::box2DWorld(const ::basegfx::B2DVector
& rSlideSize
)
226 , mfScaleFactor(calculateScaleFactor(rSlideSize
))
227 , mbShapesInitialized(false)
228 , mbHasWorldStepper(false)
229 , mbAlreadyStepped(false)
230 , mnPhysicsAnimationCounter(0)
231 , mpXShapeToBodyMap()
232 , maShapeParallelUpdateQueue()
236 box2DWorld::~box2DWorld() = default;
238 bool box2DWorld::initiateWorld(const ::basegfx::B2DVector
& rSlideSize
)
242 mpBox2DWorld
= std::make_unique
<b2World
>(b2Vec2(0.0f
, -30.0f
));
243 createStaticFrameAroundSlide(rSlideSize
);
252 void box2DWorld::createStaticFrameAroundSlide(const ::basegfx::B2DVector
& rSlideSize
)
254 assert(mpBox2DWorld
);
256 float fWidth
= static_cast<float>(rSlideSize
.getX() * mfScaleFactor
);
257 float fHeight
= static_cast<float>(rSlideSize
.getY() * mfScaleFactor
);
259 // static body for creating the frame around the slide
261 aBodyDef
.type
= b2_staticBody
;
262 aBodyDef
.position
.Set(0, 0);
264 // not going to be stored anywhere, will live
265 // as long as the Box2DWorld does
266 b2Body
* pStaticBody
= mpBox2DWorld
->CreateBody(&aBodyDef
);
268 // create an edge loop that represents slide frame
269 b2Vec2 aEdgePoints
[4];
270 aEdgePoints
[0].Set(0, 0);
271 aEdgePoints
[1].Set(0, -fHeight
);
272 aEdgePoints
[2].Set(fWidth
, -fHeight
);
273 aEdgePoints
[3].Set(fWidth
, 0);
275 b2ChainShape aEdgesChainShape
;
276 aEdgesChainShape
.CreateLoop(aEdgePoints
, 4);
278 // create the fixture for the shape
279 b2FixtureDef aFixtureDef
;
280 aFixtureDef
.shape
= &aEdgesChainShape
;
281 pStaticBody
->CreateFixture(&aFixtureDef
);
284 void box2DWorld::setShapePosition(const css::uno::Reference
<com::sun::star::drawing::XShape
> xShape
,
285 const basegfx::B2DPoint
& rOutPos
)
287 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(xShape
)->second
;
288 pBox2DBody
->setPosition(rOutPos
);
291 void box2DWorld::setShapePositionByLinearVelocity(
292 const css::uno::Reference
<com::sun::star::drawing::XShape
> xShape
,
293 const basegfx::B2DPoint
& rOutPos
, const double fPassedTime
)
295 assert(mpBox2DWorld
);
296 if (fPassedTime
> 0) // this only makes sense if there was an advance in time
298 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(xShape
)->second
;
299 pBox2DBody
->setPositionByLinearVelocity(rOutPos
, fPassedTime
);
303 void box2DWorld::setShapeLinearVelocity(
304 const css::uno::Reference
<com::sun::star::drawing::XShape
> xShape
,
305 const basegfx::B2DVector
& rVelocity
)
307 assert(mpBox2DWorld
);
308 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(xShape
)->second
;
309 pBox2DBody
->setLinearVelocity(rVelocity
);
312 void box2DWorld::setShapeAngle(const css::uno::Reference
<com::sun::star::drawing::XShape
> xShape
,
315 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(xShape
)->second
;
316 pBox2DBody
->setAngle(fAngle
);
319 void box2DWorld::setShapeAngleByAngularVelocity(
320 const css::uno::Reference
<com::sun::star::drawing::XShape
> xShape
, const double fAngle
,
321 const double fPassedTime
)
323 assert(mpBox2DWorld
);
324 if (fPassedTime
> 0) // this only makes sense if there was an advance in time
326 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(xShape
)->second
;
327 pBox2DBody
->setAngleByAngularVelocity(fAngle
, fPassedTime
);
331 void box2DWorld::setShapeAngularVelocity(
332 const css::uno::Reference
<com::sun::star::drawing::XShape
> xShape
,
333 const double fAngularVelocity
)
335 assert(mpBox2DWorld
);
336 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(xShape
)->second
;
337 pBox2DBody
->setAngularVelocity(fAngularVelocity
);
340 void box2DWorld::setShapeCollision(
341 const css::uno::Reference
<com::sun::star::drawing::XShape
> xShape
, bool bCanCollide
)
343 assert(mpBox2DWorld
);
344 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(xShape
)->second
;
345 pBox2DBody
->setCollision(bCanCollide
);
348 void box2DWorld::processUpdateQueue(const double fPassedTime
)
350 while (!maShapeParallelUpdateQueue
.empty())
352 Box2DDynamicUpdateInformation
& aQueueElement
= maShapeParallelUpdateQueue
.front();
354 if (aQueueElement
.mnDelayForSteps
> 0)
356 // it was queued as a delayed action, skip it, don't pop
357 aQueueElement
.mnDelayForSteps
--;
361 switch (aQueueElement
.meUpdateType
)
364 case BOX2D_UPDATE_POSITION_CHANGE
:
365 setShapePositionByLinearVelocity(aQueueElement
.mxShape
,
366 aQueueElement
.maPosition
, fPassedTime
);
368 case BOX2D_UPDATE_POSITION
:
369 setShapePosition(aQueueElement
.mxShape
, aQueueElement
.maPosition
);
371 case BOX2D_UPDATE_ANGLE
:
372 setShapeAngleByAngularVelocity(aQueueElement
.mxShape
, aQueueElement
.mfAngle
,
375 case BOX2D_UPDATE_SIZE
:
377 case BOX2D_UPDATE_VISIBILITY
:
378 setShapeCollision(aQueueElement
.mxShape
, aQueueElement
.mbVisibility
);
380 case BOX2D_UPDATE_LINEAR_VELOCITY
:
381 setShapeLinearVelocity(aQueueElement
.mxShape
, aQueueElement
.maVelocity
);
383 case BOX2D_UPDATE_ANGULAR_VELOCITY
:
384 setShapeAngularVelocity(aQueueElement
.mxShape
, aQueueElement
.mfAngularVelocity
);
386 maShapeParallelUpdateQueue
.pop();
391 void box2DWorld::initiateAllShapesAsStaticBodies(
392 const slideshow::internal::ShapeManagerSharedPtr
& pShapeManager
)
394 assert(mpBox2DWorld
);
396 mbShapesInitialized
= true;
397 auto aXShapeToShapeMap
= pShapeManager
->getXShapeToShapeMap();
399 std::unordered_map
<css::uno::Reference
<css::drawing::XShape
>, bool> aXShapeBelongsToAGroup
;
401 // iterate over the shapes in the current slide and flag them if they belong to a group
402 // will flag the only ones that are belong to a group since std::unordered_map operator[]
403 // defaults the value to false if the key doesn't have a corresponding value
404 for (auto aIt
= aXShapeToShapeMap
.begin(); aIt
!= aXShapeToShapeMap
.end(); aIt
++)
406 slideshow::internal::ShapeSharedPtr pShape
= aIt
->second
;
407 if (pShape
->isForeground())
409 SdrObject
* pTemp
= SdrObject::getSdrObjectFromXShape(pShape
->getXShape());
410 if (pTemp
&& pTemp
->IsGroupObject())
412 // if it is a group object iterate over its children and flag them
413 SdrObjList
* aObjList
= pTemp
->GetSubList();
414 const size_t nObjCount(aObjList
->GetObjCount());
416 for (size_t nObjIndex
= 0; nObjIndex
< nObjCount
; ++nObjIndex
)
418 SdrObject
* pGroupMember(aObjList
->GetObj(nObjIndex
));
419 aXShapeBelongsToAGroup
.insert(
420 std::make_pair(GetXShapeForSdrObject(pGroupMember
), true));
426 // iterate over shapes in the current slide
427 for (auto aIt
= aXShapeToShapeMap
.begin(); aIt
!= aXShapeToShapeMap
.end(); aIt
++)
429 slideshow::internal::ShapeSharedPtr pShape
= aIt
->second
;
430 // only create static bodies for the shapes that do not belong to a group
431 // groups themselves will have one body that represents the whole shape
433 if (pShape
->isForeground() && !aXShapeBelongsToAGroup
[pShape
->getXShape()])
435 Box2DBodySharedPtr pBox2DBody
= createStaticBody(pShape
);
437 mpXShapeToBodyMap
.insert(std::make_pair(pShape
->getXShape(), pBox2DBody
));
438 if (!pShape
->isVisible())
440 // if the shape isn't visible, queue an update for it
441 queueShapeVisibilityUpdate(pShape
->getXShape(), false);
447 bool box2DWorld::hasWorldStepper() const { return mbHasWorldStepper
; }
449 void box2DWorld::setHasWorldStepper(const bool bHasWorldStepper
)
451 mbHasWorldStepper
= bHasWorldStepper
;
454 void box2DWorld::queueDynamicPositionUpdate(
455 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
,
456 const basegfx::B2DPoint
& rOutPos
)
458 Box2DDynamicUpdateInformation aQueueElement
= { xShape
, {}, BOX2D_UPDATE_POSITION_CHANGE
};
459 aQueueElement
.maPosition
= rOutPos
;
460 maShapeParallelUpdateQueue
.push(aQueueElement
);
463 void box2DWorld::queueLinearVelocityUpdate(
464 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
,
465 const basegfx::B2DVector
& rVelocity
, const int nDelayForSteps
)
467 Box2DDynamicUpdateInformation aQueueElement
468 = { xShape
, {}, BOX2D_UPDATE_LINEAR_VELOCITY
, nDelayForSteps
};
469 aQueueElement
.maVelocity
= rVelocity
;
470 maShapeParallelUpdateQueue
.push(aQueueElement
);
473 void box2DWorld::queueDynamicRotationUpdate(
474 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
, const double fAngle
)
476 Box2DDynamicUpdateInformation aQueueElement
= { xShape
, {}, BOX2D_UPDATE_ANGLE
};
477 aQueueElement
.mfAngle
= fAngle
;
478 maShapeParallelUpdateQueue
.push(aQueueElement
);
481 void box2DWorld::queueAngularVelocityUpdate(
482 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
,
483 const double fAngularVelocity
, const int nDelayForSteps
)
485 Box2DDynamicUpdateInformation aQueueElement
486 = { xShape
, {}, BOX2D_UPDATE_ANGULAR_VELOCITY
, nDelayForSteps
};
487 aQueueElement
.mfAngularVelocity
= fAngularVelocity
;
488 maShapeParallelUpdateQueue
.push(aQueueElement
);
491 void box2DWorld::queueShapeVisibilityUpdate(
492 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
, const bool bVisibility
)
494 Box2DDynamicUpdateInformation aQueueElement
= { xShape
, {}, BOX2D_UPDATE_VISIBILITY
};
495 aQueueElement
.mbVisibility
= bVisibility
;
496 maShapeParallelUpdateQueue
.push(aQueueElement
);
499 void box2DWorld::queueShapePositionUpdate(
500 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
,
501 const basegfx::B2DPoint
& rOutPos
)
503 Box2DDynamicUpdateInformation aQueueElement
= { xShape
, {}, BOX2D_UPDATE_POSITION
};
504 aQueueElement
.maPosition
= rOutPos
;
505 maShapeParallelUpdateQueue
.push(aQueueElement
);
508 void box2DWorld::queueShapePathAnimationUpdate(
509 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
,
510 const slideshow::internal::ShapeAttributeLayerSharedPtr
& pAttrLayer
, const bool bIsFirstUpdate
)
512 // Workaround for PathAnimations since they do not have their own AttributeType
513 // - using PosX makes it register a DynamicPositionUpdate -
514 queueShapeAnimationUpdate(xShape
, pAttrLayer
, slideshow::internal::AttributeType::PosX
,
518 void box2DWorld::queueShapeAnimationUpdate(
519 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
,
520 const slideshow::internal::ShapeAttributeLayerSharedPtr
& pAttrLayer
,
521 const slideshow::internal::AttributeType eAttrType
, const bool bIsFirstUpdate
)
525 case slideshow::internal::AttributeType::Visibility
:
526 queueShapeVisibilityUpdate(xShape
, pAttrLayer
->getVisibility());
528 case slideshow::internal::AttributeType::Rotate
:
529 queueDynamicRotationUpdate(xShape
, pAttrLayer
->getRotationAngle());
531 case slideshow::internal::AttributeType::PosX
:
532 case slideshow::internal::AttributeType::PosY
:
533 if (bIsFirstUpdate
) // if it is the first update shape should _teleport_ to the position
534 queueShapePositionUpdate(xShape
, { pAttrLayer
->getPosX(), pAttrLayer
->getPosY() });
536 queueDynamicPositionUpdate(xShape
,
537 { pAttrLayer
->getPosX(), pAttrLayer
->getPosY() });
544 void box2DWorld::queueShapeAnimationEndUpdate(
545 const css::uno::Reference
<com::sun::star::drawing::XShape
>& xShape
,
546 const slideshow::internal::AttributeType eAttrType
)
550 // end updates that change the velocity are delayed for a step
551 // since we do not want them to override the last position/angle
552 case slideshow::internal::AttributeType::Rotate
:
553 queueAngularVelocityUpdate(xShape
, 0.0, 1);
555 case slideshow::internal::AttributeType::PosX
:
556 case slideshow::internal::AttributeType::PosY
:
557 queueLinearVelocityUpdate(xShape
, { 0, 0 }, 1);
564 void box2DWorld::alertPhysicsAnimationEnd(const slideshow::internal::ShapeSharedPtr
& pShape
)
566 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(pShape
->getXShape())->second
;
567 // since the animation ended make the body static
568 makeBodyStatic(pBox2DBody
);
569 pBox2DBody
->setRestitution(fDefaultStaticBodyBounciness
);
570 if (--mnPhysicsAnimationCounter
== 0)
572 // if there are no more physics animation effects going on clean up
573 maShapeParallelUpdateQueue
= {};
574 mbShapesInitialized
= false;
575 // clearing the map will make the box2d bodies get
576 // destroyed if there's nothing else that owns them
577 mpXShapeToBodyMap
.clear();
581 // the physics animation that will take over the lock after this one
582 // shouldn't step the world for an update cycle - since it was already
584 mbAlreadyStepped
= true;
588 void box2DWorld::alertPhysicsAnimationStart(
589 const ::basegfx::B2DVector
& rSlideSize
,
590 const slideshow::internal::ShapeManagerSharedPtr
& pShapeManager
)
593 initiateWorld(rSlideSize
);
595 if (!mbShapesInitialized
)
596 initiateAllShapesAsStaticBodies(pShapeManager
);
598 mnPhysicsAnimationCounter
++;
601 void box2DWorld::step(const float fTimeStep
, const int nVelocityIterations
,
602 const int nPositionIterations
)
604 assert(mpBox2DWorld
);
605 mpBox2DWorld
->Step(fTimeStep
, nVelocityIterations
, nPositionIterations
);
608 double box2DWorld::stepAmount(const double fPassedTime
, const float fTimeStep
,
609 const int nVelocityIterations
, const int nPositionIterations
)
611 assert(mpBox2DWorld
);
613 unsigned int nStepAmount
= static_cast<unsigned int>(std::round(fPassedTime
/ fTimeStep
));
614 // find the actual time that will be stepped through so
615 // that the updates can be processed using that value
616 double fTimeSteppedThrough
= fTimeStep
* nStepAmount
;
618 // do the updates required to simulate other animation effects going in parallel
619 processUpdateQueue(fTimeSteppedThrough
);
621 if (!mbAlreadyStepped
)
623 for (unsigned int nStepCounter
= 0; nStepCounter
< nStepAmount
; nStepCounter
++)
625 step(fTimeStep
, nVelocityIterations
, nPositionIterations
);
630 // just got the step lock from another physics animation
631 // so skipping stepping the world for an update cycle
632 mbAlreadyStepped
= false;
635 return fTimeSteppedThrough
;
638 bool box2DWorld::shapesInitialized() { return mbShapesInitialized
; }
640 bool box2DWorld::isInitialized() const
649 box2DWorld::makeShapeDynamic(const css::uno::Reference
<css::drawing::XShape
>& xShape
,
650 const basegfx::B2DVector
& rStartVelocity
, const double fDensity
,
651 const double fBounciness
)
653 assert(mpBox2DWorld
);
654 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(xShape
)->second
;
655 pBox2DBody
->setDensityAndRestitution(fDensity
, fBounciness
);
656 queueLinearVelocityUpdate(xShape
, rStartVelocity
, 1);
657 return makeBodyDynamic(pBox2DBody
);
660 Box2DBodySharedPtr
makeBodyDynamic(const Box2DBodySharedPtr
& pBox2DBody
)
662 if (pBox2DBody
->getType() != BOX2D_DYNAMIC_BODY
)
664 pBox2DBody
->setType(BOX2D_DYNAMIC_BODY
);
669 Box2DBodySharedPtr
box2DWorld::makeShapeStatic(const slideshow::internal::ShapeSharedPtr
& pShape
)
671 assert(mpBox2DWorld
);
672 Box2DBodySharedPtr pBox2DBody
= mpXShapeToBodyMap
.find(pShape
->getXShape())->second
;
673 return makeBodyStatic(pBox2DBody
);
676 Box2DBodySharedPtr
makeBodyStatic(const Box2DBodySharedPtr
& pBox2DBody
)
678 if (pBox2DBody
->getType() != BOX2D_STATIC_BODY
)
680 pBox2DBody
->setType(BOX2D_STATIC_BODY
);
685 Box2DBodySharedPtr
box2DWorld::createStaticBody(const slideshow::internal::ShapeSharedPtr
& rShape
,
686 const float fDensity
, const float fFriction
)
688 assert(mpBox2DWorld
);
690 ::basegfx::B2DRectangle aShapeBounds
= rShape
->getBounds();
693 aBodyDef
.type
= b2_staticBody
;
694 aBodyDef
.position
= convertB2DPointToBox2DVec2(aShapeBounds
.getCenter(), mfScaleFactor
);
696 slideshow::internal::ShapeAttributeLayerSharedPtr pShapeAttributeLayer
697 = static_cast<slideshow::internal::AttributableShape
*>(rShape
.get())
698 ->getTopmostAttributeLayer();
699 if (pShapeAttributeLayer
&& pShapeAttributeLayer
->isRotationAngleValid())
701 // if the shape's rotation value was altered by another animation effect set it.
702 aBodyDef
.angle
= ::basegfx::deg2rad(-pShapeAttributeLayer
->getRotationAngle());
705 // create a shared pointer with a destructor so that the body will be properly destroyed
706 std::shared_ptr
<b2Body
> pBody(mpBox2DWorld
->CreateBody(&aBodyDef
), [](b2Body
* pB2Body
) {
707 pB2Body
->GetWorld()->DestroyBody(pB2Body
);
710 SdrObject
* pSdrObject
= SdrObject::getSdrObjectFromXShape(rShape
->getXShape());
712 rtl::OUString aShapeType
= rShape
->getXShape()->getShapeType();
714 basegfx::B2DPolyPolygon aPolyPolygon
;
716 // TakeXorPoly() doesn't return beziers for CustomShapes and we want the beziers
717 // so that we can decide the complexity of the polygons generated from them
718 if (aShapeType
== "com.sun.star.drawing.CustomShape")
720 aPolyPolygon
= static_cast<SdrObjCustomShape
*>(pSdrObject
)->GetLineGeometry(true);
724 aPolyPolygon
= pSdrObject
->TakeXorPoly();
727 // make beziers into polygons, using a high degree angle as fAngleBound in
728 // adaptiveSubdivideByAngle reduces complexity of the resulting polygon shapes
729 aPolyPolygon
= aPolyPolygon
.areControlPointsUsed()
730 ? basegfx::utils::adaptiveSubdivideByAngle(aPolyPolygon
, 20)
732 aPolyPolygon
.removeDoublePoints();
734 // make polygon coordinates relative to the center of the shape instead of top left of the slide
735 // since box2d shapes are expressed this way
737 = basegfx::utils::distort(aPolyPolygon
, aPolyPolygon
.getB2DRange(),
738 { -aShapeBounds
.getWidth() / 2, -aShapeBounds
.getHeight() / 2 },
739 { aShapeBounds
.getWidth() / 2, -aShapeBounds
.getHeight() / 2 },
740 { -aShapeBounds
.getWidth() / 2, aShapeBounds
.getHeight() / 2 },
741 { aShapeBounds
.getWidth() / 2, aShapeBounds
.getHeight() / 2 });
743 if (pSdrObject
->IsClosedObj() && !pSdrObject
->IsEdgeObj() && pSdrObject
->HasFillStyle())
745 basegfx::triangulator::B2DTriangleVector aTriangleVector
;
746 // iterate over the polygons of the shape and create representations for them
747 for (const auto& rPolygon
: std::as_const(aPolyPolygon
))
749 // if the polygon is closed it will be represented by triangles
750 if (rPolygon
.isClosed())
752 basegfx::triangulator::B2DTriangleVector
aTempTriangleVector(
753 basegfx::triangulator::triangulate(rPolygon
));
754 aTriangleVector
.insert(aTriangleVector
.end(), aTempTriangleVector
.begin(),
755 aTempTriangleVector
.end());
757 else // otherwise it will be an edge representation (example: smile line of the smiley shape)
759 addEdgeShapeToBody(rPolygon
, pBody
.get(), fDensity
, fFriction
,
760 static_cast<float>(fDefaultStaticBodyBounciness
), mfScaleFactor
);
763 addTriangleVectorToBody(aTriangleVector
, pBody
.get(), fDensity
, fFriction
,
764 static_cast<float>(fDefaultStaticBodyBounciness
), mfScaleFactor
);
768 addEdgeShapeToBody(aPolyPolygon
, pBody
.get(), fDensity
, fFriction
,
769 static_cast<float>(fDefaultStaticBodyBounciness
), mfScaleFactor
);
772 return std::make_shared
<box2DBody
>(pBody
, mfScaleFactor
);
775 box2DBody::box2DBody(std::shared_ptr
<b2Body
> pBox2DBody
, double fScaleFactor
)
776 : mpBox2DBody(std::move(pBox2DBody
))
777 , mfScaleFactor(fScaleFactor
)
781 ::basegfx::B2DPoint
box2DBody::getPosition() const
783 b2Vec2 aPosition
= mpBox2DBody
->GetPosition();
784 double fX
= static_cast<double>(aPosition
.x
) / mfScaleFactor
;
785 double fY
= static_cast<double>(aPosition
.y
) / -mfScaleFactor
;
786 return ::basegfx::B2DPoint(fX
, fY
);
789 void box2DBody::setPosition(const basegfx::B2DPoint
& rPos
)
791 mpBox2DBody
->SetTransform(convertB2DPointToBox2DVec2(rPos
, mfScaleFactor
),
792 mpBox2DBody
->GetAngle());
795 void box2DBody::setPositionByLinearVelocity(const basegfx::B2DPoint
& rDesiredPos
,
796 const double fPassedTime
)
798 // kinematic bodies are not affected by other bodies, but unlike static ones can still have velocity
799 if (mpBox2DBody
->GetType() != b2_kinematicBody
)
800 mpBox2DBody
->SetType(b2_kinematicBody
);
802 ::basegfx::B2DPoint aCurrentPos
= getPosition();
803 // calculate the velocity needed to reach the rDesiredPos in the given time frame
804 ::basegfx::B2DVector aVelocity
= (rDesiredPos
- aCurrentPos
) / fPassedTime
;
806 setLinearVelocity(aVelocity
);
809 void box2DBody::setAngleByAngularVelocity(const double fDesiredAngle
, const double fPassedTime
)
811 // kinematic bodies are not affected by other bodies, but unlike static ones can still have velocity
812 if (mpBox2DBody
->GetType() != b2_kinematicBody
)
813 mpBox2DBody
->SetType(b2_kinematicBody
);
815 double fDeltaAngle
= fDesiredAngle
- getAngle();
817 // temporary hack for repeating animation effects
818 while (fDeltaAngle
> 180
819 || fDeltaAngle
< -180) // if it is bigger than 180 opposite rotation is actually closer
820 fDeltaAngle
+= fDeltaAngle
> 0 ? -360 : +360;
822 double fAngularVelocity
= fDeltaAngle
/ fPassedTime
;
823 setAngularVelocity(fAngularVelocity
);
826 void box2DBody::setLinearVelocity(const ::basegfx::B2DVector
& rVelocity
)
828 b2Vec2 aVelocity
= { static_cast<float>(rVelocity
.getX() * mfScaleFactor
),
829 static_cast<float>(rVelocity
.getY() * -mfScaleFactor
) };
830 mpBox2DBody
->SetLinearVelocity(aVelocity
);
833 void box2DBody::setAngularVelocity(const double fAngularVelocity
)
835 float fBox2DAngularVelocity
= static_cast<float>(basegfx::deg2rad(-fAngularVelocity
));
836 mpBox2DBody
->SetAngularVelocity(fBox2DAngularVelocity
);
839 void box2DBody::setCollision(const bool bCanCollide
)
841 // collision have to be set for each fixture of the body individually
842 for (b2Fixture
* pFixture
= mpBox2DBody
->GetFixtureList(); pFixture
;
843 pFixture
= pFixture
->GetNext())
845 b2Filter aFilter
= pFixture
->GetFilterData();
846 // 0xFFFF means collides with everything
847 // 0x0000 means collides with nothing
848 aFilter
.maskBits
= bCanCollide
? 0xFFFF : 0x0000;
849 pFixture
->SetFilterData(aFilter
);
853 double box2DBody::getAngle() const
855 double fAngle
= static_cast<double>(mpBox2DBody
->GetAngle());
856 return ::basegfx::rad2deg(-fAngle
);
859 void box2DBody::setAngle(const double fAngle
)
861 mpBox2DBody
->SetTransform(mpBox2DBody
->GetPosition(), ::basegfx::deg2rad(-fAngle
));
864 void box2DBody::setDensityAndRestitution(const double fDensity
, const double fRestitution
)
866 // density and restitution have to be set for each fixture of the body individually
867 for (b2Fixture
* pFixture
= mpBox2DBody
->GetFixtureList(); pFixture
;
868 pFixture
= pFixture
->GetNext())
870 pFixture
->SetDensity(static_cast<float>(fDensity
));
871 pFixture
->SetRestitution(static_cast<float>(fRestitution
));
873 // without resetting the massdata of the body, density change won't take effect
874 mpBox2DBody
->ResetMassData();
877 void box2DBody::setRestitution(const double fRestitution
)
879 for (b2Fixture
* pFixture
= mpBox2DBody
->GetFixtureList(); pFixture
;
880 pFixture
= pFixture
->GetNext())
882 pFixture
->SetRestitution(static_cast<float>(fRestitution
));
886 void box2DBody::setType(box2DBodyType eType
)
888 mpBox2DBody
->SetType(getBox2DInternalBodyType(eType
));
891 box2DBodyType
box2DBody::getType() const { return getBox2DLOBodyType(mpBox2DBody
->GetType()); }
894 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */