From 19e9c4b0ca2234ef5f151ffa968ae1431f47836a Mon Sep 17 00:00:00 2001 From: Alex Bilger Date: Fri, 13 Nov 2026 11:00:28 +0100 Subject: [PATCH 1/2] [AnimationLoop] Support static equilibrium in FreeMotionAnimationLoop --- .../animationloop/FreeMotionAnimationLoop.cpp | 194 +++++++++++++----- .../animationloop/FreeMotionAnimationLoop.h | 21 +- .../Backward/StaticSolverWithConstraints.scn | 99 +++++++++ .../StaticSolverWithConstraints_simple.scn | 47 +++++ 4 files changed, 300 insertions(+), 61 deletions(-) create mode 100644 examples/Component/IntegrationScheme/Backward/StaticSolverWithConstraints.scn create mode 100644 examples/Component/IntegrationScheme/Backward/StaticSolverWithConstraints_simple.scn diff --git a/Sofa/Component/AnimationLoop/src/sofa/component/animationloop/FreeMotionAnimationLoop.cpp b/Sofa/Component/AnimationLoop/src/sofa/component/animationloop/FreeMotionAnimationLoop.cpp index 6325c91d4b3..e62aee06162 100644 --- a/Sofa/Component/AnimationLoop/src/sofa/component/animationloop/FreeMotionAnimationLoop.cpp +++ b/Sofa/Component/AnimationLoop/src/sofa/component/animationloop/FreeMotionAnimationLoop.cpp @@ -68,8 +68,9 @@ using sofa::helper::ScopedAdvancedTimer; using DefaultConstraintSolver = sofa::component::constraint::lagrangian::solver::BlockGaussSeidelConstraintSolver; -FreeMotionAnimationLoop::FreeMotionAnimationLoop() : - d_solveVelocityConstraintFirst(initData(&d_solveVelocityConstraintFirst , false, "solveVelocityConstraintFirst", "solve separately velocity constraint violations before position constraint violations")) +FreeMotionAnimationLoop::FreeMotionAnimationLoop() + : d_solveConstraints(initData(&d_solveConstraints, true, "solveConstraints", "If true, constraints are solved. Otherwise, they are ignored.")) + , d_constraintsStateVariables(initData(&d_constraintsStateVariables , ConstraintsStateVariables("posVel"), "constraintsStateVariables", "State variables on which the constraints are expressed and corrected: position only (statics), position and velocity, or velocity only")) , d_threadSafeVisitor(initData(&d_threadSafeVisitor, false, "threadSafeVisitor", "If true, do not use realloc and free visitors in fwdInteractionForceField.")) , d_parallelCollisionDetectionAndFreeMotion(initData(&d_parallelCollisionDetectionAndFreeMotion, false, "parallelCollisionDetectionAndFreeMotion", "If true, executes free motion step and collision detection step in parallel.")) , d_parallelODESolving(initData(&d_parallelODESolving, false, "parallelODESolving", "If true, solves all the ODEs in parallel during the free motion step.")) @@ -77,6 +78,19 @@ FreeMotionAnimationLoop::FreeMotionAnimationLoop() : { d_parallelCollisionDetectionAndFreeMotion.setGroup("Multithreading"); d_parallelODESolving.setGroup("Multithreading"); + + this->addUpdateCallback("validateConstraintSolver", {&d_solveConstraints}, [this](const core::DataTracker& ) + { + if (d_solveConstraints.getValue()) + { + validateConstraintSolver(); + if (l_constraintSolver) + { + l_constraintSolver->init(); + } + } + return this->getComponentState(); + }, {}); } FreeMotionAnimationLoop::~FreeMotionAnimationLoop() @@ -94,40 +108,11 @@ void FreeMotionAnimationLoop::init() MultiVecDeriv df(&vop, core::vec_id::write_access::dforce); df.realloc(&vop, !d_threadSafeVisitor.getValue(), true); - if (!l_constraintSolver) + if (d_solveConstraints.getValue() && !l_constraintSolver) { - l_constraintSolver.set(this->getContext()->get(core::objectmodel::BaseContext::SearchDown)); - if (!l_constraintSolver) - { - if (const auto constraintSolver = sofa::core::objectmodel::New()) - { - getContext()->addObject(constraintSolver); - constraintSolver->setName( this->getContext()->getNameHelper().resolveName(constraintSolver->getClassName(), {})); - constraintSolver->f_printLog.setValue(this->f_printLog.getValue()); - l_constraintSolver.set(constraintSolver); - - msg_warning() << "A ConstraintSolver is required by " << this->getClassName() << " but has not been found:" - " a default " << constraintSolver->getClassName() << " is automatically added in the scene for you. To remove this warning, add" - " a ConstraintSolver in the scene. The list of available constraint solvers is: " - << core::ObjectFactory::getInstance()->listClassesDerivedFrom(); - } - else - { - msg_fatal() << "A ConstraintSolver is required by " << this->getClassName() << " but has not been found:" - " a default " << DefaultConstraintSolver::GetClass()->className << " could not be automatically added in the scene. To remove this error, add" - " a ConstraintSolver in the scene. The list of available constraint solvers is: " - << core::ObjectFactory::getInstance()->listClassesDerivedFrom(); - this->d_componentState.setValue(sofa::core::objectmodel::ComponentState::Invalid); - return; - } - } - else - { - msg_info() << "Constraint solver found: '" << l_constraintSolver->getPathName() << "'"; - } + validateConstraintSolver(); } - if (d_parallelCollisionDetectionAndFreeMotion.getValue() || d_parallelODESolving.getValue()) { initTaskScheduler(); @@ -136,9 +121,29 @@ void FreeMotionAnimationLoop::init() this->d_componentState.setValue(sofa::core::objectmodel::ComponentState::Valid); } +void FreeMotionAnimationLoop::parse(BaseObjectDescription* arg) +{ + CollisionAnimationLoop::parse(arg); + + if (arg->getAttribute("solveVelocityConstraintFirst") && !d_constraintsStateVariables.isSet()) + { + const auto value = arg->getAttributeAsInt("solveVelocityConstraintFirst", 0); + if (value == 0) + { + d_constraintsStateVariables.setValue(ConstraintsStateVariables("posVel")); + } + else + { + d_constraintsStateVariables.setValue(ConstraintsStateVariables("vel")); + } + } +} void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal dt) { + if (isComponentStateInvalid()) + return; + auto node = dynamic_cast(this->l_node.get()); dmsg_info() << "################### step begin ###################"; @@ -153,15 +158,31 @@ void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal d MultiVecCoord pos(&vop, core::vec_id::write_access::position ); MultiVecDeriv vel(&vop, core::vec_id::write_access::velocity ); - MultiVecCoord freePos(&vop, core::vec_id::write_access::freePosition ); - MultiVecDeriv freeVel(&vop, core::vec_id::write_access::freeVelocity ); + + const auto solveConstraints = d_solveConstraints.getValue(); + MultiVecCoord freePos(&vop, solveConstraints ? core::vec_id::write_access::freePosition : core::vec_id::write_access::position); + MultiVecDeriv freeVel(&vop, solveConstraints ? core::vec_id::write_access::freeVelocity : core::vec_id::write_access::velocity ); core::ConstraintParams cparams(*params); cparams.setX(freePos); cparams.setV(freeVel); - cparams.setDx(l_constraintSolver->getDx()); - cparams.setLambda(l_constraintSolver->getLambda()); - cparams.setOrder(d_solveVelocityConstraintFirst.getValue() ? core::ConstraintOrder::VEL : core::ConstraintOrder::POS_AND_VEL); + if (l_constraintSolver) + { + cparams.setDx(l_constraintSolver->getDx()); + cparams.setLambda(l_constraintSolver->getLambda()); + } + switch (d_constraintsStateVariables.getValue()) + { + case ConstraintsStateVariables("pos"): + cparams.setOrder(core::ConstraintOrder::POS); + break; + case ConstraintsStateVariables("posVel"): + cparams.setOrder(core::ConstraintOrder::POS_AND_VEL); + break; + case ConstraintsStateVariables("vel"): + cparams.setOrder(core::ConstraintOrder::VEL); + break; + } MultiVecDeriv dx(&vop, core::vec_id::write_access::dx); dx.realloc(&vop, !d_threadSafeVisitor.getValue(), true); @@ -171,18 +192,25 @@ void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal d // This solver will work in freePosition and freeVelocity vectors. // We need to initialize them if it's not already done. + if (solveConstraints) { SCOPED_TIMER("MechanicalVInitVisitor"); MechanicalVInitVisitor< core::V_COORD >(params, core::vec_id::write_access::freePosition, core::vec_id::read_access::position, true).execute(node); MechanicalVInitVisitor< core::V_DERIV >(params, core::vec_id::write_access::freeVelocity, core::vec_id::read_access::velocity, true).execute(node); + + MechanicalVOpVisitor(params, core::vec_id::write_access::freePosition, core::vec_id::read_access::position).setMapped(true).execute(node); + MechanicalVOpVisitor(params, core::vec_id::write_access::freeVelocity, core::vec_id::read_access::velocity).setMapped(true).execute(node); } // This animation loop works with lagrangian constraints. Forces derive from the constraints. // Therefore we notice the States that they have to consider them in the total accumulation of // forces. - for (auto* state : node->getTreeObjects()) + if (solveConstraints) { - state->addToTotalForces(cparams.lambda().getId(state)); + for (auto* state : node->getTreeObjects()) + { + state->addToTotalForces(cparams.lambda().getId(state)); + } } @@ -220,6 +248,7 @@ void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal d dmsg_info() << "updateInternal performed - beginVisitor called" ; + if (solveConstraints) { SCOPED_TIMER("MechanicalComputeGeometricStiffness"); MechanicalComputeGeometricStiffness geometricStiffnessVisitor(&mop.mparams, cparams.lambda()); @@ -229,19 +258,24 @@ void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal d computeFreeMotionAndCollisionDetection(params, cparams, dt, pos, freePos, freeVel, &mop); // Solve constraints - if (l_constraintSolver) + if (solveConstraints && l_constraintSolver) { SCOPED_TIMER("ConstraintSolver"); - if (cparams.constOrder() == core::ConstraintOrder::VEL ) + const auto constOrder = cparams.constOrder(); + if (constOrder == core::ConstraintOrder::VEL ) { l_constraintSolver->solveConstraint(&cparams, vel); pos.eq(pos, vel, dt); //position += velocity * dt } - else + else if (constOrder == core::ConstraintOrder::POS_AND_VEL) { l_constraintSolver->solveConstraint(&cparams, pos, vel); } + else if (constOrder == core::ConstraintOrder::POS) + { + l_constraintSolver->solveConstraint(&cparams, pos); + } { SCOPED_TIMER("ProjectAndPropagateDx"); @@ -255,6 +289,14 @@ void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal d mechanicalvisitor::MechanicalResetForceVisitor resetForceVisitor(params, sofa::core::vec_id::write_access::externalForce); node->execute(&resetForceVisitor); + if (cparams.constOrder() == core::ConstraintOrder::POS) + { + SCOPED_TIMER("ProjectAndPropagateX"); + + mop.projectPosition(pos); + mop.propagateX(pos); + } + else { SCOPED_TIMER("ProjectAndPropagateXAndV"); @@ -297,8 +339,8 @@ void FreeMotionAnimationLoop::step(const sofa::core::ExecParams* params, SReal d void FreeMotionAnimationLoop::computeFreeMotionAndCollisionDetection(const sofa::core::ExecParams* params, const core::ConstraintParams& cparams, SReal dt, - sofa::core::MultiVecId pos, - sofa::core::MultiVecId freePos, + sofa::core::MultiVecCoordId pos, + sofa::core::MultiVecCoordId freePos, sofa::core::MultiVecDerivId freeVel, simulation::common::MechanicalOperations* mop) { @@ -362,8 +404,8 @@ void FreeMotionAnimationLoop::computeFreeMotionAndCollisionDetection(const sofa: } void FreeMotionAnimationLoop::computeFreeMotion(const sofa::core::ExecParams* params, const core::ConstraintParams& cparams, SReal dt, - sofa::core::MultiVecId pos, - sofa::core::MultiVecId freePos, + sofa::core::MultiVecCoordId pos, + sofa::core::MultiVecCoordId freePos, sofa::core::MultiVecDerivId freeVel, simulation::common::MechanicalOperations* mop) { @@ -371,20 +413,60 @@ void FreeMotionAnimationLoop::computeFreeMotion(const sofa::core::ExecParams* pa { SCOPED_TIMER("FreeMotion"); - simulation::SolveVisitor freeMotion(params, dt, true, d_parallelODESolving.getValue()); + simulation::SolveVisitor freeMotion(params, dt, d_solveConstraints.getValue(), d_parallelODESolving.getValue()); node->execute(&freeMotion); } - mop->projectResponse(freeVel); - mop->propagateDx(freeVel, true); + if (cparams.constOrder() == core::ConstraintOrder::POS) + { + mop->projectPosition(freePos); + mop->propagateX(freePos); + } + else + { + mop->projectResponse(freeVel); + mop->propagateDx(freeVel, true); + + if (cparams.constOrder() == sofa::core::ConstraintOrder::POS_AND_VEL && d_solveConstraints.getValue()) + { + SCOPED_TIMER("freePosEqPosPlusFreeVelDt"); + MechanicalVOpVisitor freePosEqPosPlusFreeVelDt(params, freePos, pos, freeVel, dt); + freePosEqPosPlusFreeVelDt.setMapped(true); + node->executeVisitor(&freePosEqPosPlusFreeVelDt); + } + } +} - if (cparams.constOrder() == sofa::core::ConstraintOrder::POS || - cparams.constOrder() == sofa::core::ConstraintOrder::POS_AND_VEL) +void FreeMotionAnimationLoop::validateConstraintSolver() +{ + l_constraintSolver.set(this->getContext()->get(core::objectmodel::BaseContext::SearchDown)); + if (!l_constraintSolver) + { + if (const auto constraintSolver = sofa::core::objectmodel::New()) + { + getContext()->addObject(constraintSolver); + constraintSolver->setName( this->getContext()->getNameHelper().resolveName(constraintSolver->getClassName(), {})); + constraintSolver->f_printLog.setValue(this->f_printLog.getValue()); + l_constraintSolver.set(constraintSolver); + + msg_warning() << "A ConstraintSolver is required by " << this->getClassName() << " but has not been found:" + " a default " << constraintSolver->getClassName() << " is automatically added in the scene for you. To remove this warning, add" + " a ConstraintSolver in the scene. The list of available constraint solvers is: " + << core::ObjectFactory::getInstance()->listClassesDerivedFrom(); + } + else + { + msg_fatal() << "A ConstraintSolver is required by " << this->getClassName() << " but has not been found:" + " a default " << DefaultConstraintSolver::GetClass()->className << " could not be automatically added in the scene. To remove this error, add" + " a ConstraintSolver in the scene. The list of available constraint solvers is: " + << core::ObjectFactory::getInstance()->listClassesDerivedFrom(); + this->d_componentState.setValue(sofa::core::objectmodel::ComponentState::Invalid); + return; + } + } + else { - SCOPED_TIMER("freePosEqPosPlusFreeVelDt"); - MechanicalVOpVisitor freePosEqPosPlusFreeVelDt(params, freePos, pos, freeVel, dt); - freePosEqPosPlusFreeVelDt.setMapped(true); - node->executeVisitor(&freePosEqPosPlusFreeVelDt); + msg_info() << "Constraint solver found: '" << l_constraintSolver->getPathName() << "'"; } } diff --git a/Sofa/Component/AnimationLoop/src/sofa/component/animationloop/FreeMotionAnimationLoop.h b/Sofa/Component/AnimationLoop/src/sofa/component/animationloop/FreeMotionAnimationLoop.h index c930a8b53b2..820c1ee0df7 100644 --- a/Sofa/Component/AnimationLoop/src/sofa/component/animationloop/FreeMotionAnimationLoop.h +++ b/Sofa/Component/AnimationLoop/src/sofa/component/animationloop/FreeMotionAnimationLoop.h @@ -43,8 +43,17 @@ class SOFA_COMPONENT_ANIMATIONLOOP_API FreeMotionAnimationLoop : public sofa::si public: void step (const sofa::core::ExecParams* params, SReal dt) override; void init() override; + void parse ( BaseObjectDescription* arg ) override; - Data d_solveVelocityConstraintFirst; ///< solve separately velocity constraint violations before position constraint violations + MAKE_SELECTABLE_ITEMS(ConstraintsStateVariables, + sofa::helper::Item{.key = "pos", .description = "Position"}, + sofa::helper::Item{.key = "posVel", .description = "Position and velocity"}, + sofa::helper::Item{.key = "vel", .description = "Velocity"}, + ); + + Data d_solveConstraints; ///< If true, constraints are solved. Otherwise, they are ignored. + core::objectmodel::lifecycle::DeprecatedData d_solveVelocityConstraintFirst {this, "v26.12", "v27.06", "solveVelocityConstraintFirst", "You should now use the Data 'constraintsStateVariables'"}; + Data d_constraintsStateVariables; Data d_threadSafeVisitor; ///< If true, do not use realloc and free visitors in fwdInteractionForceField. Data d_parallelCollisionDetectionAndFreeMotion; ///< If true, executes free motion step and collision detection step in parallel. Data d_parallelODESolving; ///< If true, solves all the ODEs in parallel during the free motion step. @@ -57,16 +66,18 @@ class SOFA_COMPONENT_ANIMATIONLOOP_API FreeMotionAnimationLoop : public sofa::si SingleLink l_constraintSolver; void computeFreeMotionAndCollisionDetection(const sofa::core::ExecParams* params, const core::ConstraintParams& cparams, SReal dt, - sofa::core::MultiVecId pos, - sofa::core::MultiVecId freePos, + sofa::core::MultiVecCoordId pos, + sofa::core::MultiVecCoordId freePos, sofa::core::MultiVecDerivId freeVel, simulation::common::MechanicalOperations* mop); void computeFreeMotion(const sofa::core::ExecParams* params, const core::ConstraintParams& cparams, SReal dt, - sofa::core::MultiVecId pos, - sofa::core::MultiVecId freePos, + sofa::core::MultiVecCoordId pos, + sofa::core::MultiVecCoordId freePos, sofa::core::MultiVecDerivId freeVel, simulation::common::MechanicalOperations* mop); + + void validateConstraintSolver(); }; } // namespace sofa::component::animationloop diff --git a/examples/Component/IntegrationScheme/Backward/StaticSolverWithConstraints.scn b/examples/Component/IntegrationScheme/Backward/StaticSolverWithConstraints.scn new file mode 100644 index 00000000000..4fdc89d4e42 --- /dev/null +++ b/examples/Component/IntegrationScheme/Backward/StaticSolverWithConstraints.scn @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Component/IntegrationScheme/Backward/StaticSolverWithConstraints_simple.scn b/examples/Component/IntegrationScheme/Backward/StaticSolverWithConstraints_simple.scn new file mode 100644 index 00000000000..cea021d75ce --- /dev/null +++ b/examples/Component/IntegrationScheme/Backward/StaticSolverWithConstraints_simple.scn @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 5eb1fe4f7438dd1b8664e97595931cde8d20c420 Mon Sep 17 00:00:00 2001 From: Alex Bilger Date: Sat, 28 Nov 2026 17:03:17 +0100 Subject: [PATCH 2/2] [IntegrationScheme.Backward] FIX StaticEquilibriumIntegrationScheme to evaluate forces on xResult. --- .../StaticEquilibriumIntegrationScheme.cpp | 14 ++- ...taticEquilibriumIntegrationScheme_test.cpp | 85 +++++++++++++++++++ 2 files changed, 95 insertions(+), 4 deletions(-) diff --git a/Sofa/Component/IntegrationScheme/Backward/src/sofa/component/integrationscheme/backward/StaticEquilibriumIntegrationScheme.cpp b/Sofa/Component/IntegrationScheme/Backward/src/sofa/component/integrationscheme/backward/StaticEquilibriumIntegrationScheme.cpp index 35121f1f162..6cdccb180ef 100644 --- a/Sofa/Component/IntegrationScheme/Backward/src/sofa/component/integrationscheme/backward/StaticEquilibriumIntegrationScheme.cpp +++ b/Sofa/Component/IntegrationScheme/Backward/src/sofa/component/integrationscheme/backward/StaticEquilibriumIntegrationScheme.cpp @@ -53,8 +53,13 @@ void StaticEquilibriumIntegrationScheme::doSetupIntegrationStep(const core::Exec { SOFA_UNUSED(dt); SOFA_UNUSED(params); - SOFA_UNUSED(vResult); - SOFA_UNUSED(xResult); + + // The state being solved is xResult/vResult (e.g. freePosition/freeVelocity when called from + // a FreeMotionAnimationLoop), not necessarily position/velocity. Make the mechanical + // parameters consistent with it, so that any operation relying on mparams.x()/v() works on it. + m_mop->mparams.setX(xResult); + m_mop->mparams.setV(vResult); + simulation::common::VectorOperations::realloc(*m_vop, m_systemUnknown, "dx", this, true); simulation::common::VectorOperations::realloc(*m_vop, m_r0, "r0", this, true); } @@ -85,8 +90,9 @@ void StaticEquilibriumIntegrationScheme::computeRHS(bool firstIteration) //TODO deal with that. SCOPED_TIMER("ComputeForce"); m_mop->mparams.setImplicit(true); // this solver is implicit - // compute the net forces at the beginning of the time step - m_mop->computeForce(m_mappingGraph, f, true, true, nullptr); //f = Kx + Bv + // compute the forces on the state being solved (xResult), which is not necessarily the + // position (e.g. freePosition when called from a FreeMotionAnimationLoop) + m_mop->computeForce(m_mappingGraph, f, m_xResult, m_vResult, true, true, nullptr); m_mop->projectResponse(m_mappingGraph,f); // b is projected to the constrained space diff --git a/Sofa/Component/IntegrationScheme/Backward/tests/StaticEquilibriumIntegrationScheme_test.cpp b/Sofa/Component/IntegrationScheme/Backward/tests/StaticEquilibriumIntegrationScheme_test.cpp index 0c1edb1f94b..207f7bfa0bd 100644 --- a/Sofa/Component/IntegrationScheme/Backward/tests/StaticEquilibriumIntegrationScheme_test.cpp +++ b/Sofa/Component/IntegrationScheme/Backward/tests/StaticEquilibriumIntegrationScheme_test.cpp @@ -24,6 +24,9 @@ #include #include #include +#include +#include +#include #include #include @@ -133,3 +136,85 @@ TEST_F(StaticEquilibriumIntegrationSchemeTest, Residuals) { EXPECT_NEAR(actual_force_residual_norm, expected_force_residual_norm, 1e-3) << "The actual force residual norm doesn't match the expected one."; } + +/** + * The integration scheme must solve the static equilibrium on the state vectors it is given + * (xResult, vResult), which are not necessarily position and velocity. For example, + * FreeMotionAnimationLoop calls it with freePosition and freeVelocity. + * + * Forces and residual must be evaluated on xResult. If they were evaluated on position instead, + * the residual would never change along the Newton iterations, and xResult would not converge + * toward the equilibrium. + * + * The result obtained in freePosition is compared to the result obtained in position. + */ +TEST_F(StaticEquilibriumIntegrationSchemeTest, ResultInFreePosition) +{ + using DataTypes = sofa::defaulttype::Vec3Types; + using VecCoord = DataTypes::VecCoord; + using VecDeriv = DataTypes::VecDeriv; + + staticSolver->d_maxNbIterationsNewton.setValue(10); + staticSolver->d_residualThreshold.setValue(0.0_sreal); + + sofa::simulation::node::initRoot(root.get()); + + auto* state = dynamic_cast*>(root->getObject("mo")); + ASSERT_NE(state, nullptr); + + const VecCoord initialPosition = state->read(sofa::core::vec_id::read_access::position)->getValue(); + const VecDeriv initialVelocity = state->read(sofa::core::vec_id::read_access::velocity)->getValue(); + ASSERT_FALSE(initialPosition.empty()); + + // The free state starts from the current state, as in FreeMotionAnimationLoop + state->write(sofa::core::vec_id::write_access::freePosition)->setValue(initialPosition); + state->write(sofa::core::vec_id::write_access::freeVelocity)->setValue(initialVelocity); + + const auto* params = sofa::core::ExecParams::defaultInstance(); + + // Solve the static equilibrium in freePosition + staticSolver->integrate(params, 1_sreal, + sofa::core::vec_id::write_access::freePosition, + sofa::core::vec_id::write_access::freeVelocity); + const SReal residualInFreePosition = std::sqrt(staticSolver->d_currentResidual.getValue()); + + const VecCoord freePosition = state->read(sofa::core::vec_id::read_access::freePosition)->getValue(); + + // position must not have been modified + { + const VecCoord& position = state->read(sofa::core::vec_id::read_access::position)->getValue(); + ASSERT_EQ(position.size(), initialPosition.size()); + for (std::size_t i = 0; i < position.size(); ++i) + { + EXPECT_EQ(position[i], initialPosition[i]) << "position has been modified at node " << i; + } + } + + // freePosition must have moved toward the equilibrium + SReal maxDisplacement = 0; + for (std::size_t i = 0; i < freePosition.size(); ++i) + { + maxDisplacement = std::max(maxDisplacement, (freePosition[i] - initialPosition[i]).norm()); + } + EXPECT_GT(maxDisplacement, 1_sreal) << "freePosition did not move"; + + // Reference: solve the same static equilibrium in position + staticSolver->integrate(params, 1_sreal, + sofa::core::vec_id::write_access::position, + sofa::core::vec_id::write_access::velocity); + const SReal residualInPosition = std::sqrt(staticSolver->d_currentResidual.getValue()); + + const VecCoord& position = state->read(sofa::core::vec_id::read_access::position)->getValue(); + + EXPECT_NEAR(residualInFreePosition, residualInPosition, 1e-10); + EXPECT_LT(residualInFreePosition, 1e-3) << "The Newton iterations did not converge in freePosition"; + + ASSERT_EQ(position.size(), freePosition.size()); + for (std::size_t i = 0; i < position.size(); ++i) + { + for (std::size_t c = 0; c < DataTypes::spatial_dimensions; ++c) + { + EXPECT_NEAR(freePosition[i][c], position[i][c], 1e-8) << "node " << i << ", coordinate " << c; + } + } +}