repo_id
stringclasses 205
values | file_path
stringlengths 33
141
| content
stringlengths 1
307k
| __index_level_0__
int64 0
0
|
---|---|---|---|
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/kuka_iiwa_arm/kuka_torque_controller.h | #pragma once
#include "drake/common/drake_copyable.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/controllers/state_feedback_controller_interface.h"
#include "drake/systems/framework/diagram.h"
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
// N.B. Inheritance order must remain fixed for pydrake (#9243).
/**
* Controller that take emulates the kuka_iiwa_arm when operated in torque
* control mode. The controller specifies a stiffness and damping ratio at each
* of the joints. Because the critical damping constant is a function of the
* configuration the damping is non-linear. See
* https://github.com/RobotLocomotion/drake-iiwa-driver/blob/master/kuka-driver/sunrise_1.11/DrakeFRITorqueDriver.java
*
* for details on the low-level controller. Note that the
* input_port_desired_state() method takes a full state for convenient wiring
* with other Systems, but ignores the velocity component.
*
* @system
* name: KukaTorqueController
* input_ports:
* - estimated_state
* - desired_state
* - commanded_torque
* output_ports:
* - control
* @endsystem
*
* @tparam_double_only
*/
template <typename T>
class KukaTorqueController
: public systems::Diagram<T>,
public systems::controllers::StateFeedbackControllerInterface<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(KukaTorqueController)
/// @p plant is aliased and must remain valid for the lifetime of the
/// controller.
KukaTorqueController(
const multibody::MultibodyPlant<T>& plant,
const VectorX<double>& stiffness,
const VectorX<double>& damping);
const systems::InputPort<T>& get_input_port_commanded_torque() const {
return systems::Diagram<T>::get_input_port(
input_port_index_commanded_torque_);
}
const systems::InputPort<T>& get_input_port_estimated_state() const override {
return systems::Diagram<T>::get_input_port(
input_port_index_estimated_state_);
}
const systems::InputPort<T>& get_input_port_desired_state() const override {
return systems::Diagram<T>::get_input_port(input_port_index_desired_state_);
}
const systems::OutputPort<T>& get_output_port_control() const override {
return systems::Diagram<T>::get_output_port(output_port_index_control_);
}
private:
const multibody::MultibodyPlant<T>& plant_;
systems::InputPortIndex input_port_index_estimated_state_;
systems::InputPortIndex input_port_index_desired_state_;
systems::InputPortIndex input_port_index_commanded_torque_;
systems::OutputPortIndex output_port_index_control_;
};
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/kuka_iiwa_arm/kuka_torque_controller.cc | #include "drake/examples/kuka_iiwa_arm/kuka_torque_controller.h"
#include <memory>
#include "drake/systems/controllers/inverse_dynamics.h"
#include "drake/systems/controllers/pid_controller.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/primitives/adder.h"
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
namespace {
using drake::systems::kVectorValued;
using drake::systems::Adder;
using drake::systems::BasicVector;
using drake::systems::Context;
using drake::systems::DiagramBuilder;
using drake::systems::LeafSystem;
using drake::systems::controllers::PidController;
template <typename T>
class StateDependentDamper : public LeafSystem<T> {
public:
StateDependentDamper(const multibody::MultibodyPlant<T>& plant,
const VectorX<double>& stiffness,
const VectorX<double>& damping_ratio)
: plant_(plant), stiffness_(stiffness), damping_ratio_(damping_ratio) {
const int num_q = plant_.num_positions();
const int num_v = plant_.num_velocities();
const int num_x = num_q + num_v;
DRAKE_DEMAND(stiffness.size() == num_v);
DRAKE_DEMAND(damping_ratio.size() == num_v);
this->DeclareInputPort(systems::kUseDefaultName, kVectorValued, num_x);
this->DeclareVectorOutputPort(systems::kUseDefaultName, num_v,
&StateDependentDamper<T>::CalcTorque);
// Make context with default parameters.
plant_context_ = plant_.CreateDefaultContext();
}
private:
const multibody::MultibodyPlant<T>& plant_;
const VectorX<double> stiffness_;
const VectorX<double> damping_ratio_;
// This context is used solely for setting generalized positions and
// velocities in multibody_plant_.
std::unique_ptr<Context<T>> plant_context_;
/**
* Computes joint level damping forces by computing the damping ratio for each
* joint independently as if all other joints were fixed. Note that the
* effective inertia of a joint, when all of the other joints are fixed, is
* given by the corresponding diagonal entry of the mass matrix. The critical
* damping gain for the i-th joint is given by 2*sqrt(M(i,i)*stiffness(i)).
*/
void CalcTorque(const Context<T>& context, BasicVector<T>* torque) const {
const Eigen::VectorXd& x = this->EvalVectorInput(context, 0)->value();
plant_.SetPositionsAndVelocities(plant_context_.get(), x);
const int num_v = plant_.num_velocities();
Eigen::MatrixXd H(num_v, num_v);
plant_.CalcMassMatrixViaInverseDynamics(*plant_context_, &H);
// Compute critical damping gains and scale by damping ratio. Use Eigen
// arrays (rather than matrices) for elementwise multiplication.
Eigen::ArrayXd temp =
H.diagonal().array() * stiffness_.array();
Eigen::ArrayXd damping_gains = 2 * temp.sqrt();
damping_gains *= damping_ratio_.array();
// Compute damping torque.
Eigen::VectorXd v = x.tail(plant_.num_velocities());
torque->get_mutable_value() = -(damping_gains * v.array()).matrix();
}
};
} // namespace
template <typename T>
KukaTorqueController<T>::KukaTorqueController(
const multibody::MultibodyPlant<T>& plant,
const VectorX<double>& stiffness,
const VectorX<double>& damping)
: plant_(plant) {
DiagramBuilder<T> builder;
DRAKE_DEMAND(plant_.num_positions() == stiffness.size());
DRAKE_DEMAND(plant_.num_positions() == damping.size());
const int dim = plant_.num_positions();
/*
torque_in ----------------------------
|
(q, v) ------>|Gravity Comp|------+---> torque_out
| /|
--->|Damping|---------- |
| |
--->| Virtual Spring |---
(q*, v*) ------>|PID with kd=ki=0|
*/
// Adds gravity compensator.
using drake::systems::controllers::InverseDynamics;
auto gravity_comp =
builder.template AddSystem<InverseDynamics<T>>(
&plant_, InverseDynamics<T>::kGravityCompensation);
// Adds virtual springs.
Eigen::VectorXd kd(dim);
Eigen::VectorXd ki(dim);
kd.setZero();
ki.setZero();
auto spring = builder.template AddSystem<PidController<T>>(stiffness, kd, ki);
// Adds virtual damper.
auto damper = builder.template AddSystem<StateDependentDamper<T>>(
plant_, stiffness, damping);
// Adds an adder to sum the gravity compensation, spring, damper, and
// feedforward torque.
auto adder = builder.template AddSystem<Adder<T>>(4, dim);
// Connects the gravity compensation, spring, and damper torques to the adder.
builder.Connect(gravity_comp->get_output_port(0), adder->get_input_port(1));
builder.Connect(spring->get_output_port(0), adder->get_input_port(2));
builder.Connect(damper->get_output_port(0), adder->get_input_port(3));
// Exposes the estimated state port.
// Connects the estimated state to the gravity compensator.
input_port_index_estimated_state_ = builder.ExportInput(
gravity_comp->get_input_port_estimated_state(), "estimated_state");
// Connects the estimated state to the spring.
builder.ConnectInput(input_port_index_estimated_state_,
spring->get_input_port_estimated_state());
// Connects the estimated state to the damper.
builder.ConnectInput(input_port_index_estimated_state_,
damper->get_input_port(0));
// Exposes the desired state port.
input_port_index_desired_state_ = builder.ExportInput(
spring->get_input_port_desired_state(), "desired_state");
// Exposes the commanded torque port.
input_port_index_commanded_torque_ =
builder.ExportInput(adder->get_input_port(0), "commanded_torque");
// Exposes controller output.
output_port_index_control_ = builder.ExportOutput(
adder->get_output_port(), "control");
builder.BuildInto(this);
}
template class KukaTorqueController<double>;
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/kuka_iiwa_arm/iiwa_common.h | #pragma once
#include "drake/common/eigen_types.h"
#include "drake/manipulation/kuka_iiwa/iiwa_constants.h"
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
// These details have moved to files under drake/manipulation/kuka_iiwa.
// These forwarding aliases are placed here for compatibility purposes.
using manipulation::kuka_iiwa::kIiwaArmNumJoints;
using manipulation::kuka_iiwa::get_iiwa_max_joint_velocities;
/// Used to set the feedback gains for the simulated position controlled KUKA.
void SetPositionControlledIiwaGains(Eigen::VectorXd* Kp,
Eigen::VectorXd* Ki,
Eigen::VectorXd* Kd);
/// Used to set the feedback gains for the simulated torque controlled KUKA.
void SetTorqueControlledIiwaGains(Eigen::VectorXd* stiffness,
Eigen::VectorXd* damping_ratio);
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/kuka_iiwa_arm/move_iiwa_ee.cc | /// @file
///
/// Demo of moving the iiwa's end effector in cartesian space. This
/// program creates a plan to move the end effector from the current
/// position to the location specified on the command line. The
/// current calculated position of the end effector is printed before,
/// during, and after the commanded motion.
#include "lcm/lcm-cpp.hpp"
#include <gflags/gflags.h>
#include "drake/common/find_resource.h"
#include "drake/examples/kuka_iiwa_arm/iiwa_common.h"
#include "drake/lcmt_iiwa_status.hpp"
#include "drake/lcmt_robot_plan.hpp"
#include "drake/manipulation/util/move_ik_demo_base.h"
#include "drake/math/rigid_transform.h"
#include "drake/multibody/parsing/package_map.h"
DEFINE_string(urdf, "", "Name of urdf to load");
DEFINE_string(lcm_status_channel, "IIWA_STATUS",
"Channel on which to listen for lcmt_iiwa_status messages.");
DEFINE_string(lcm_plan_channel, "COMMITTED_ROBOT_PLAN",
"Channel on which to send lcmt_robot_plan messages.");
DEFINE_double(x, 0., "x coordinate to move to");
DEFINE_double(y, 0., "y coordinate to move to");
DEFINE_double(z, 0., "z coordinate to move to");
DEFINE_double(roll, 0., "target roll about world x axis for end effector");
DEFINE_double(pitch, 0., "target pitch about world y axis for end effector");
DEFINE_double(yaw, 0., "target yaw about world z axis for end effector");
DEFINE_string(ee_name, "iiwa_link_ee", "Name of the end effector link");
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
namespace {
using manipulation::util::MoveIkDemoBase;
using multibody::PackageMap;
const char kIiwaUrdfUrl[] =
"package://drake_models/iiwa_description/urdf/"
"iiwa14_polytope_collision.urdf";
int DoMain() {
math::RigidTransformd pose(
math::RollPitchYawd(FLAGS_roll, FLAGS_pitch, FLAGS_yaw),
Eigen::Vector3d(FLAGS_x, FLAGS_y, FLAGS_z));
MoveIkDemoBase demo(
!FLAGS_urdf.empty() ? FLAGS_urdf : PackageMap{}.ResolveUrl(kIiwaUrdfUrl),
"base", FLAGS_ee_name, 100);
demo.set_joint_velocity_limits(get_iiwa_max_joint_velocities());
::lcm::LCM lc;
lc.subscribe<lcmt_iiwa_status>(
FLAGS_lcm_status_channel,
[&](const ::lcm::ReceiveBuffer*, const std::string&,
const lcmt_iiwa_status* status) {
Eigen::VectorXd iiwa_q(status->num_joints);
for (int i = 0; i < status->num_joints; i++) {
iiwa_q[i] = status->joint_position_measured[i];
}
demo.HandleStatus(iiwa_q);
if (demo.status_count() == 1) {
std::optional<lcmt_robot_plan> plan = demo.Plan(pose);
if (plan.has_value()) {
lc.publish(FLAGS_lcm_plan_channel, &plan.value());
}
}
});
while (lc.handle() >= 0) { }
return 0;
}
} // namespace
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::kuka_iiwa_arm::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/kuka_iiwa_arm/iiwa_common.cc | #include "drake/examples/kuka_iiwa_arm/iiwa_common.h"
#include <cmath>
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
void SetPositionControlledIiwaGains(Eigen::VectorXd* Kp,
Eigen::VectorXd* Ki,
Eigen::VectorXd* Kd) {
// All the gains are for acceleration, not directly responsible for generating
// torques. These are set to high values to ensure good tracking. These gains
// are picked arbitrarily.
Kp->resize(7);
*Kp << 100, 100, 100, 100, 100, 100, 100;
Kd->resize(Kp->size());
for (int i = 0; i < Kp->size(); i++) {
// Critical damping gains.
(*Kd)[i] = 2 * std::sqrt((*Kp)[i]);
}
*Ki = Eigen::VectorXd::Zero(7);
}
void SetTorqueControlledIiwaGains(Eigen::VectorXd* stiffness,
Eigen::VectorXd* damping_ratio) {
// All the gains are for directly generating torques. These gains are set
// according to the values in the drake-iiwa-driver repository:
// https://github.com/RobotLocomotion/drake-iiwa-driver/blob/master/kuka-driver/sunrise_1.11/DrakeFRITorqueDriver.java NOLINT
// The spring stiffness in Nm/rad.
stiffness->resize(7);
*stiffness << 1000, 1000, 1000, 500, 500, 500, 500;
// A dimensionless damping ratio. See KukaTorqueController for details.
damping_ratio->resize(stiffness->size());
damping_ratio->setConstant(1.0);
}
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/kuka_iiwa_arm/kuka_simulation.cc | /// @file
///
/// Implements a simulation of the KUKA iiwa arm. Like the driver for the
/// physical arm, this simulation communicates over LCM using lcmt_iiwa_status
/// and lcmt_iiwa_command messages. It is intended to be a be a direct
/// replacement for the KUKA iiwa driver and the actual robot hardware.
#include <memory>
#include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/examples/kuka_iiwa_arm/iiwa_common.h"
#include "drake/examples/kuka_iiwa_arm/iiwa_lcm.h"
#include "drake/examples/kuka_iiwa_arm/kuka_torque_controller.h"
#include "drake/geometry/scene_graph.h"
#include "drake/lcmt_iiwa_command.hpp"
#include "drake/lcmt_iiwa_status.hpp"
#include "drake/multibody/parsing/parser.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/controllers/inverse_dynamics_controller.h"
#include "drake/systems/controllers/state_feedback_controller_interface.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/lcm/lcm_interface_system.h"
#include "drake/systems/lcm/lcm_publisher_system.h"
#include "drake/systems/lcm/lcm_subscriber_system.h"
#include "drake/systems/primitives/demultiplexer.h"
#include "drake/systems/primitives/discrete_derivative.h"
#include "drake/visualization/visualization_config_functions.h"
DEFINE_double(simulation_sec, std::numeric_limits<double>::infinity(),
"Number of seconds to simulate.");
DEFINE_string(urdf, "", "Name of urdf to load");
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
DEFINE_bool(torque_control, false, "Simulate using torque control mode.");
DEFINE_double(sim_dt, 3e-3,
"The time step to use for MultibodyPlant model "
"discretization.");
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
namespace {
using multibody::MultibodyPlant;
using multibody::PackageMap;
using systems::Context;
using systems::Demultiplexer;
using systems::StateInterpolatorWithDiscreteDerivative;
using systems::Simulator;
using systems::controllers::InverseDynamicsController;
using systems::controllers::StateFeedbackControllerInterface;
int DoMain() {
systems::DiagramBuilder<double> builder;
// Adds a plant.
auto [plant, scene_graph] = multibody::AddMultibodyPlantSceneGraph(
&builder, FLAGS_sim_dt);
const char* kModelUrl =
"package://drake_models/iiwa_description/"
"urdf/iiwa14_polytope_collision.urdf";
const std::string urdf =
(!FLAGS_urdf.empty() ? FLAGS_urdf : PackageMap{}.ResolveUrl(kModelUrl));
auto iiwa_instance =
multibody::Parser(&plant, &scene_graph).AddModels(urdf).at(0);
plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("base"));
plant.Finalize();
// TODO(sammy-tri) Add a floor.
// Creates and adds LCM publisher for visualization.
auto lcm = builder.AddSystem<systems::lcm::LcmInterfaceSystem>();
visualization::ApplyVisualizationConfig({}, &builder, nullptr, nullptr,
nullptr, nullptr, lcm);
// Since we welded the model to the world above, the only remaining joints
// should be those in the arm.
const int num_joints = plant.num_positions();
DRAKE_DEMAND(num_joints % kIiwaArmNumJoints == 0);
const int num_iiwa = num_joints / kIiwaArmNumJoints;
// Adds a iiwa controller.
StateFeedbackControllerInterface<double>* controller = nullptr;
if (FLAGS_torque_control) {
VectorX<double> stiffness, damping_ratio;
SetTorqueControlledIiwaGains(&stiffness, &damping_ratio);
stiffness = stiffness.replicate(num_iiwa, 1).eval();
damping_ratio = damping_ratio.replicate(num_iiwa, 1).eval();
controller = builder.AddSystem<KukaTorqueController<double>>(
plant, stiffness, damping_ratio);
} else {
VectorX<double> iiwa_kp, iiwa_kd, iiwa_ki;
SetPositionControlledIiwaGains(&iiwa_kp, &iiwa_ki, &iiwa_kd);
iiwa_kp = iiwa_kp.replicate(num_iiwa, 1).eval();
iiwa_kd = iiwa_kd.replicate(num_iiwa, 1).eval();
iiwa_ki = iiwa_ki.replicate(num_iiwa, 1).eval();
controller = builder.AddSystem<InverseDynamicsController<double>>(
plant, iiwa_kp, iiwa_ki, iiwa_kd,
false /* without feedforward acceleration */);
}
// Create the command subscriber and status publisher.
auto command_sub = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<drake::lcmt_iiwa_command>(
"IIWA_COMMAND", lcm));
command_sub->set_name("command_subscriber");
auto command_receiver =
builder.AddSystem<IiwaCommandReceiver>(num_joints);
command_receiver->set_name("command_receiver");
auto plant_state_demux = builder.AddSystem<Demultiplexer>(
2 * num_joints, num_joints);
plant_state_demux->set_name("plant_state_demux");
auto desired_state_from_position = builder.AddSystem<
StateInterpolatorWithDiscreteDerivative>(
num_joints, kIiwaLcmStatusPeriod,
true /* suppress_initial_transient */);
desired_state_from_position->set_name("desired_state_from_position");
auto status_pub = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<lcmt_iiwa_status>(
"IIWA_STATUS", lcm, kIiwaLcmStatusPeriod /* publish period */));
status_pub->set_name("status_publisher");
auto status_sender = builder.AddSystem<IiwaStatusSender>(num_joints);
status_sender->set_name("status_sender");
builder.Connect(command_sub->get_output_port(),
command_receiver->get_message_input_port());
builder.Connect(plant_state_demux->get_output_port(0),
command_receiver->get_position_measured_input_port());
builder.Connect(command_receiver->get_commanded_position_output_port(),
desired_state_from_position->get_input_port());
builder.Connect(desired_state_from_position->get_output_port(),
controller->get_input_port_desired_state());
builder.Connect(plant.get_state_output_port(iiwa_instance),
plant_state_demux->get_input_port(0));
builder.Connect(plant_state_demux->get_output_port(0),
status_sender->get_position_measured_input_port());
builder.Connect(plant_state_demux->get_output_port(1),
status_sender->get_velocity_estimated_input_port());
builder.Connect(command_receiver->get_commanded_position_output_port(),
status_sender->get_position_commanded_input_port());
builder.Connect(plant.get_state_output_port(),
controller->get_input_port_estimated_state());
builder.Connect(controller->get_output_port_control(),
plant.get_actuation_input_port(iiwa_instance));
builder.Connect(controller->get_output_port_control(),
status_sender->get_torque_commanded_input_port());
builder.Connect(controller->get_output_port_control(),
status_sender->get_torque_measured_input_port());
// TODO(sammy-tri) Add a low-pass filter for simulated external torques.
// This would slow the simulation significantly, however. (see #12631)
builder.Connect(
plant.get_generalized_contact_forces_output_port(iiwa_instance),
status_sender->get_torque_external_input_port());
builder.Connect(status_sender->get_output_port(),
status_pub->get_input_port());
// Connect the torque input in torque control
if (FLAGS_torque_control) {
KukaTorqueController<double>* torque_controller =
dynamic_cast<KukaTorqueController<double>*>(controller);
DRAKE_DEMAND(torque_controller != nullptr);
builder.Connect(command_receiver->get_commanded_torque_output_port(),
torque_controller->get_input_port_commanded_torque());
}
auto sys = builder.Build();
Simulator<double> simulator(*sys);
simulator.set_publish_every_time_step(false);
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.Initialize();
// Simulate for a very long time.
simulator.AdvanceTo(FLAGS_simulation_sec);
return 0;
}
} // namespace
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::kuka_iiwa_arm::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/BUILD.bazel | load("//tools/install:install_data.bzl", "install_data")
load("//tools/lint:lint.bzl", "add_lint_tests")
load("//tools/skylark:drake_data.bzl", "models_filegroup")
package(default_visibility = ["//visibility:private"])
models_filegroup(
name = "models",
visibility = ["//visibility:public"],
)
install_data(
name = "install_data",
data = [":models"],
visibility = ["//visibility:public"],
)
add_lint_tests()
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/README.md | This directory contains numerous models that are useful to simulations involving
the KUKA iiwa arm.
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/block_for_pick_and_place_mid_size.urdf | <?xml version="1.0"?>
<robot name="simple_cuboid">
<link name="base_link">
<inertial>
<origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="0.1"/>
<inertia ixx="0.000363" ixy="0" ixz="0" iyy="0.000363" iyz="0" izz="0.00006"/>
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0"/>
<geometry>
<box size="0.06 0.075 0.2"/>
</geometry>
<material name="blue">
<color rgba="0.1 0.8 0.1 0.9"/>
</material>
</visual>
<!--
This places contact spheres on the corners of the visual box and a
*slightly* smaller inset contact box (centered on the visual origin). This
accounts for issues in the contact computation providing stable table
contact *and* supports grasping.
When the box is in stable contact with the ground plane, the corner
spheres will provide fixed contact points (simulating distributed contact
points around the face). However, for arbitrary grip configuration, the
slightly inset box will provide contact with a *slight* offset (in this
case a deviation of 0.0005 m from the visual surface).
-->
<collision>
<geometry>
<box size="0.059 0.089 0.199"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 -0.0375 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 0.0375 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 0.0375 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 -0.0375 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 -0.0375 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision><origin xyz="-0.03 0.0375 0.1" rpy="0 0 0"/><geometry><sphere radius="1e-7"/></geometry>
</collision>
<collision>
<origin xyz="0.03 0.0375 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 -0.0375 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
</link>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/round_table.urdf | <?xml version="1.0"?>
<robot name="round_table">
<link name="table_surface_center"/>
<link name="table_top">
<inertial>
<mass value="1.0"/>
<inertia ixx="0.0225" ixy="0" ixz="0" iyy="0.0225" iyz="0" izz="0.0450"/>
</inertial>
<visual>
<geometry>
<cylinder length="0.017" radius="0.30"/>
</geometry>
<material name="White">
<color rgba="0.9 0.9 0.9 1.0"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.017" radius="0.30"/>
</geometry>
</collision>
</link>
<joint name="table_top_joint" type="fixed">
<origin xyz="0 0 -0.0085"/>
<parent link="table_surface_center"/>
<child link="table_top"/>
</joint>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/block_for_pick_and_place.urdf | <?xml version="1.0"?>
<robot name="simple_cuboid">
<link name="base_link">
<inertial>
<origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="0.1"/>
<inertia ixx="0.000363" ixy="0" ixz="0" iyy="0.000363" iyz="0" izz="0.00006"/>
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0"/>
<geometry>
<box size="0.06 0.06 0.2"/>
</geometry>
<material name="red">
<color rgba="0.8 0.1 0.1 0.9"/>
</material>
</visual>
<!--
This places contact spheres on the corners of the visual box and a
*slightly* smaller inset contact box (centered on the visual origin). This
accounts for issues in the contact computation providing stable table
contact *and* supports grasping.
When the box is in stable contact with the ground plane, the corner
spheres will provide fixed contact points (simulating distributed contact
points around the face). However, for arbitrary grip configuration, the
slightly inset box will provide contact with a *slight* offset (in this
case a deviation of 0.0005 m from the visual surface).
https://github.com/RobotLocomotion/drake/issues/6254 tracks the
difficulty in supporting face-to-face contact.
-->
<collision>
<geometry>
<box size="0.059 0.059 0.199"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 -0.03 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 0.03 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 0.03 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 -0.03 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 -0.03 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 0.03 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 0.03 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 -0.03 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
</link>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/simple_cuboid.urdf | <?xml version="1.0"?>
<robot name="simple_cuboid">
<link name="base_link">
<inertial>
<origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="0.068"/>
<inertia ixx="0.0000408" ixy="0" ixz="0" iyy="0.0000408" iyz="0" izz="0.0000408"/>
</inertial>
<visual><origin xyz="0 0 0" rpy="0 0 0"/>
<geometry><box size="0.06 0.06 0.06"/></geometry><material name="bright green"><color rgba="0.0 0.9 0.0 1"/></material></visual>
<!--
This places contact spheres on the corners of the visual box and a
*slightly* smaller inset contact box (centered on the visual origin). This
accounts for issues in the contact computation providing stable table
contact *and* supports grasping.
When the box is in stable contact with the ground plane, the corner
spheres will provide fixed contact points (simulating distributed contact
points around the face). However, for arbitrary grip configuration, the
slightly inset box will provide contact with a *slight* offset (in this
case a deviation of 0.0005 m from the visual surface).
-->
<collision>
<geometry>
<box size="0.059 0.059 0.056"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 -0.03 -0.03" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 0.03 -0.03" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 0.03 -0.03" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 -0.03 -0.03" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 -0.03 0.03" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 0.03 0.03" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 0.03 0.03" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 -0.03 0.03" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
</link>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/block_for_pick_and_place_large_size.urdf | <?xml version="1.0"?>
<robot name="simple_cuboid">
<link name="base_link">
<inertial>
<origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="0.1"/>
<inertia ixx="0.000363" ixy="0" ixz="0" iyy="0.000363" iyz="0" izz="0.00006"/>
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0"/>
<geometry>
<box size="0.06 0.09 0.2"/>
</geometry>
<material name="green">
<color rgba="0.1 0.1 0.8 0.9"/>
</material>
</visual>
<!--
This places contact spheres on the corners of the visual box and a
*slightly* smaller inset contact box (centered on the visual origin). This
accounts for issues in the contact computation providing stable table
contact *and* supports grasping.
When the box is in stable contact with the ground plane, the corner
spheres will provide fixed contact points (simulating distributed contact
points around the face). However, for arbitrary grip configuration, the
slightly inset box will provide contact with a *slight* offset (in this
case a deviation of 0.0005 m from the visual surface).
-->
<collision>
<geometry>
<box size="0.059 0.089 0.199"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 -0.045 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 0.045 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 0.045 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 -0.045 -0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 -0.045 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.03 0.045 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 0.045 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.03 -0.045 0.1" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
</link>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/yellow_post.urdf | <?xml version="1.0"?>
<robot name="yellow_post">
<link name="base"/>
<joint name="base_joint" type="fixed">
<origin rpy="0 0 0" xyz="0 0 0.0325"/>
<parent link="base"/>
<child link="cylinder_base"/>
</joint>
<link name="cylinder_base">
<inertial>
<origin xyz="0 0 0.025" rpy="0 0 0"/>
<mass value="18.0"/>
<inertia ixx="0.01703125" ixy="0" ixz="0" iyy="0.01703125" iyz="0" izz="0.0003125"/>
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0"/>
<geometry>
<cylinder length="0.065" radius="0.177"/>
</geometry>
<material name="Black">
<color rgba="0.0 0.0 0.0 1.0"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.065" radius="0.177"/>
</geometry>
</collision>
</link>
<joint name="post_joint" type="fixed">
<origin rpy="0 0 0" xyz="0 0 0.51"/>
<parent link="cylinder_base"/>
<child link="post"/>
</joint>
<link name="post">
<inertial>
<origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="2.0"/>
<inertia ixx="0.01703125" ixy="0" ixz="0" iyy="0.01703125" iyz="0" izz="0.0003125"/>
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0"/>
<geometry>
<cylinder length="0.955" radius="0.065"/>
</geometry>
<material name="Yellow">
<color rgba="1.0 1.0 0.0 1.0"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.955" radius="0.065"/>
</geometry>
</collision>
</link>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/simple_cylinder.urdf | <?xml version="1.0"?>
<robot name="simple_cylinder">
<link name="cylinder_base">
<inertial>
<origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="0.088"/>
<inertia ixx="0.0001471708" ixy="0" ixz="0" iyy="0.0001471708" iyz="0" izz="0.000046475"/>
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0"/>
<geometry>
<cylinder length="0.130" radius="0.0325"/>
</geometry>
<material name="bright green">
<color rgba="0.0 0.9 0.0 1"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.130" radius="0.0325"/>
</geometry>
</collision>
</link>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/open_top_box.urdf | <?xml version="1.0"?>
<robot name="open_top_box">
<!--
This model is meant to be a container in which other objects can be dumped.
Origin:
(0, 0, 0) at the center bottom of the bin.
-->
<link name="bin">
<!-- This inertia value is bogus since its inconsequential -->
<inertial>
<origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="0.122"/>
<inertia ixx="0.000360" ixy="0" ixz="0" iyy="0.0000615" iyz="0" izz="0.00036"/>
</inertial>
<!-- Front -->
<visual>
<origin rpy="0 0 0" xyz="0.19 0 0.15"/>
<geometry>
<box size="0.01 0.52 0.3"/>
</geometry>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0.19 0 0.15"/>
<geometry>
<box size="0.01 0.52 0.3"/>
</geometry>
</collision>
<!-- Back -->
<visual>
<origin rpy="0 0 0" xyz="-0.19 0 0.15"/>
<geometry>
<box size="0.01 0.52 0.3"/>
</geometry>
</visual>
<collision>
<origin rpy="0 0 0" xyz="-0.19 0 0.15"/>
<geometry>
<box size="0.01 0.52 0.3"/>
</geometry>
</collision>
<!-- Left -->
<visual>
<origin rpy="0 0 0" xyz="0 0.26 0.15"/>
<geometry>
<box size="0.38 0.01 0.3"/>
</geometry>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0 0.26 0.15"/>
<geometry>
<box size="0.38 0.01 0.3"/>
</geometry>
</collision>
<!-- Right -->
<visual>
<origin rpy="0 0 0" xyz="0 -0.26 0.15"/>
<geometry>
<box size="0.38 0.01 0.3"/>
</geometry>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0 -0.26 0.15"/>
<geometry>
<box size="0.38 0.01 0.3"/>
</geometry>
</collision>
<!-- bottom -->
<visual>
<origin rpy="0 0 0" xyz="0 0 0"/>
<geometry>
<box size="0.38 0.52 0.01"/>
</geometry>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0 0.0 -0.005"/>
<geometry>
<box size="0.38 0.52 0.01"/>
</geometry>
</collision>
</link>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/black_box.urdf | <?xml version="1.0"?>
<robot name="simple_cuboid">
<link name="base_link">
<inertial>
<origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="0.122"/>
<inertia ixx="0.000360" ixy="0" ixz="0" iyy="0.0000615" iyz="0" izz="0.00036"/>
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0"/>
<geometry>
<box size="0.165 0.055 0.180"/>
</geometry>
<material name="blackish">
<color rgba="0.1 0.1 0.1 1.0"/>
</material>
</visual>
<!--
This places contact spheres on the corners of the visual box and a
*slightly* smaller inset contact box (centered on the visual origin). This
accounts for issues in the contact computation providing stable table
contact *and* supports grasping.
When the box is in stable contact with the ground plane, the corner
spheres will provide fixed contact points (simulating distributed contact
points around the face). However, for arbitrary grip configuration, the
slightly inset box will provide contact with a *slight* offset (in this
case a deviation of 0.0005 m from the visual surface).
https://github.com/RobotLocomotion/drake/issues/6254 tracks the
difficulty in supporting face-to-face contact.
-->
<collision>
<geometry>
<box size="0.164 0.054 0.170"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.0825 -0.0275 -0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.0825 0.0275 -0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.0825 0.0275 -0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.0825 -0.0275 -0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<!-- Add some spheres near the center too -->
<collision>
<origin xyz="-0.0 -0.0275 -0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.0 0.0275 -0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.0825 -0.0275 0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.0825 0.0275 0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.0825 0.0275 0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="0.0825 -0.0275 0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.0 -0.0275 0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
<collision>
<origin xyz="-0.0 0.0275 0.09" rpy="0 0 0"/>
<geometry>
<sphere radius="1e-7"/>
</geometry>
</collision>
</link>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/objects/folding_table.urdf | <?xml version="1.0"?>
<robot name="folding_table">
<link name="table_surface_center"/>
<link name="table_top">
<inertial>
<mass value="1.0"/>
<inertia ixx="0.0225" ixy="0" ixz="0" iyy="0.0225" iyz="0" izz="0.0450"/>
</inertial>
<visual>
<geometry>
<box size="0.48 0.37 0.015"/>
</geometry>
<material name="DarkBrown">
<color rgba="0.2 0.165 0.110 1.0"/>
</material>
</visual>
<collision>
<geometry>
<box size="0.48 0.37 0.015"/>
</geometry>
</collision>
</link>
<joint name="table_top_joint" type="fixed">
<origin xyz="0 0 -0.0075"/>
<parent link="table_surface_center"/>
<child link="table_top"/>
</joint>
</robot>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/desk/transcendesk55inch.sdf | <?xml version="1.0"?>
<sdf version="1.7">
<model name="transcendesk">
<!--
To adjust the height of the table, see note below. Also recompute inertia.
-->
<link name="table_base">
<pose>-0.243716 -0.625087 0 0 0 0</pose>
<inertial>
<mass>30</mass>
<!--
The spatial inertia values given below were derived based on the
equation for a cuboid:
https://en.wikipedia.org/wiki/List_of_moments_of_inertia#List_of_3D_inertia_tensors.
Obviously, the table is not a cuboid, meaning the inertia matrix is
imperfect. Having an accurate spatial inertia specification may be
important for us to know when / if a robot mounted on top of the
table will cause the table to tip over. It will also be necessary to
model what happens when a mobile robot bumps into the table.
TODO(Lucy-tri): Compute a more accurate spatial inertia of this table.
-->
<inertia>
<ixx>4.33</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>8.325</iyy>
<iyz>0</iyz>
<izz>5.8</izz>
</inertia>
</inertial>
<kinematic>0</kinematic>
<gravity>1</gravity>
<visual name="right_crossbar">
<pose>0.65 0 0.01 0 0 0</pose>
<geometry>
<box>
<size>0.065 0.61 0.03</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="left_crossbar">
<pose>-0.65 0 0.01 0 0 0</pose>
<geometry>
<box>
<size>0.065 0.61 0.03</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="bottom_right_leg">
<pose>0.65 0.2 0.31 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.076 0.58</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="leg_brace">
<pose>0 0.229 0.42 0 0 0</pose>
<geometry>
<box>
<size>1.25 0.02 0.25</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="bottom_left_leg">
<pose>-0.65 0.2 0.31 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.076 0.58</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<collision name="bottom_left_leg">
<laser_retro>0</laser_retro>
<pose>-0.65 0.2 0.31 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.076 0.58</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="left_crossbar">
<laser_retro>0</laser_retro>
<pose>-0.65 0 0.01 0 0 0</pose>
<geometry>
<box>
<size>0.065 0.61 0.03</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="right_crossbar">
<laser_retro>0</laser_retro>
<pose>0.65 0 0.01 0 0 0</pose>
<geometry>
<box>
<size>0.065 0.61 0.03</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="bottom_right_leg">
<laser_retro>0</laser_retro>
<pose>0.65 0.2 0.31 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.076 0.58</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="leg_brace">
<laser_retro>0</laser_retro>
<pose>0 0.229 0.42 0 0 0</pose>
<geometry>
<box>
<size>1.25 0.02 0.25</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
</link>
<link name="table_upper">
<!--
To adjust the height of the table, adjust the value of the third
parameter in the pose frame, z. Also adjust inertia.
-->
<pose>-0.243716 -0.625087 0.48 0 0 0</pose>
<inertial>
<mass>53.5</mass>
<inertia>
<ixx>5.17741</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>4.84375</iyy>
<iyz>0</iyz>
<izz>4.84375</izz>
</inertia>
</inertial>
<kinematic>0</kinematic>
<visual name="upper_right_leg">
<pose>0.65 0.2 0.375 0 0 0</pose>
<geometry>
<box>
<size>0.03 0.05 0.53</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="upper_left_leg">
<pose>-0.65 0.2 0.375 0 0 0</pose>
<geometry>
<box>
<size>0.03 0.05 0.53</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="tabletop">
<pose>0 0 0.65 0 0 0</pose>
<geometry>
<box>
<size>1.4 0.6 0.03</size>
</box>
</geometry>
<material>
<ambient>0.2 0.2 0.2 1</ambient>
<diffuse>0.3 0.3 0.3 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<collision name="tabletop">
<laser_retro>0</laser_retro>
<pose>0 0 0.65 0 0 0</pose>
<geometry>
<box>
<size>1.4 0.6 0.03</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
</link>
<!--
TODO(Lucy.tri): This joint could be used to simulate the way the table's
height can be adjusted. The limits need to be tuned and other params set.
-->
<joint name="table_height" type="prismatic">
<parent>table_upper</parent>
<child>table_base</child>
<axis>
<xyz>0 0 1</xyz>
<limit>
<lower>-0.3</lower>
<upper>0</upper>
<effort>-1</effort>
<velocity>-1</velocity>
</limit>
<dynamics>
<spring_reference>0</spring_reference>
<spring_stiffness>0</spring_stiffness>
<damping>0</damping>
<friction>0</friction>
</dynamics>
</axis>
</joint>
<!--
N.B. This model used to have <static>true</static>, but this creates
issues in reusability with the current implementation of MBP parsing
(#12227).
-->
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/table/extra_heavy_duty_table.sdf | <?xml version="1.0"?>
<sdf version="1.7">
<model name="extra_heavy_duty_table">
<link name="link">
<inertial>
<mass>53.5</mass>
<!--
The spatial inertia values given below were derived based on the
equation for a cuboid:
https://en.wikipedia.org/wiki/List_of_moments_of_inertia#List_of_3D_inertia_tensors.
Obviously, the table is not a cuboid, meaning the inertia matrix is
imperfect. Having an accurate spatial inertia specification may be
important for us to know when / if a robot mounted on top of the
table will cause the table to tip over. It will also be necessary to
model what happens when a mobile robot bumps into the table.
TODO(lucy-tri): Compute a more accurate spatial inertia of this table.
-->
<inertia>
<ixx>5.177409</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>4.843753753</iyy>
<iyz>0</iyz>
<izz>4.843753753</izz>
</inertia>
</inertial>
<kinematic>0</kinematic>
<visual name="back_right_leg">
<pose>-0.33 -0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="front_left_leg">
<pose>0.33 0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="left_crossbar">
<pose>0.33 0 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.662 0.05</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="right_crossbar">
<pose>-0.33 0 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.662 0.05</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="back_left_leg">
<pose>-0.33 0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="front_right_leg">
<pose>0.33 -0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="back_crossbar">
<pose>0 0.35 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.6112 0.05 0.05</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="front_crossbar">
<pose>0 -0.35 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.6112 0.05 0.05</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="visual1">
<pose>0 0 0.736 0 0 0</pose>
<geometry>
<box>
<size>0.7112 0.762 0.057</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<collision name="front_crossbar">
<laser_retro>0</laser_retro>
<pose>0 -0.35 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.6112 0.05 0.05</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="back_crossbar">
<laser_retro>0</laser_retro>
<pose>0 0.35 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.6112 0.05 0.05</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="left_crossbar">
<laser_retro>0</laser_retro>
<pose>0.33 0 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.662 0.05</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="right_crossbar">
<laser_retro>0</laser_retro>
<pose>-0.33 0 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.662 0.05</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="back_right_leg">
<laser_retro>0</laser_retro>
<pose>-0.33 -0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="front_left_leg">
<laser_retro>0</laser_retro>
<pose>0.33 0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="back_left_leg">
<laser_retro>0</laser_retro>
<pose>-0.33 0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="front_right_leg">
<laser_retro>0</laser_retro>
<pose>0.33 -0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>1</mu>
<mu2>1</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
<collision name="surface">
<laser_retro>0</laser_retro>
<pose>0 0 0.736 0 0 0</pose>
<geometry>
<box>
<size>0.7112 0.762 0.057</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>0.6</mu>
<mu2>0.6</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
</link>
<static>1</static>
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm/models | /home/johnshepherd/drake/examples/kuka_iiwa_arm/models/table/extra_heavy_duty_table_surface_only_collision.sdf | <?xml version="1.0"?>
<sdf version="1.7">
<model name="extra_heavy_duty_table_surface_only_collision">
<!--
This model is identical to the extra heavy duty table in nearly
every respect except that the collision tags are present only for
the surface link. This leads to a large speedup in simulations
involving the table due to a decrease in number of collision
checks needed.
-->
<link name="link">
<inertial>
<mass>53.5</mass>
<!--
The spatial inertia values given below were derived based on the
equation for a cuboid:
https://en.wikipedia.org/wiki/List_of_moments_of_inertia#List_of_3D_inertia_tensors.
Obviously, the table is not a cuboid, meaning the inertia matrix is
imperfect. Having an accurate spatial inertia specification may be
important for us to know when / if a robot mounted on top of the
table will cause the table to tip over. It will also be necessary to
model what happens when a mobile robot bumps into the table.
TODO(lucy-tri): Compute a more accurate spatial inertia of this table.
-->
<inertia>
<ixx>5.177409</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>4.843753753</iyy>
<iyz>0</iyz>
<izz>4.843753753</izz>
</inertia>
</inertial>
<kinematic>0</kinematic>
<visual name="back_right_leg">
<pose>-0.33 -0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="front_left_leg">
<pose>0.33 0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="left_crossbar">
<pose>0.33 0 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.662 0.05</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="right_crossbar">
<pose>-0.33 0 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.662 0.05</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="back_left_leg">
<pose>-0.33 0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="front_right_leg">
<pose>0.33 -0.35 0.381 0 0 0</pose>
<geometry>
<box>
<size>0.05 0.05 0.762</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="back_crossbar">
<pose>0 0.35 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.6112 0.05 0.05</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="front_crossbar">
<pose>0 -0.35 0.13335 0 0 0</pose>
<geometry>
<box>
<size>0.6112 0.05 0.05</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<visual name="visual1">
<pose>0 0 0.736 0 0 0</pose>
<geometry>
<box>
<size>0.7112 0.762 0.057</size>
</box>
</geometry>
<material>
<ambient>0.3 0.3 0.3 1</ambient>
<diffuse>0.7 0.7 0.7 1</diffuse>
<specular>0.01 0.01 0.01 1</specular>
<emissive>0 0 0 1</emissive>
</material>
</visual>
<collision name="surface">
<laser_retro>0</laser_retro>
<pose>0 0 0.736 0 0 0</pose>
<geometry>
<box>
<size>0.7112 0.762 0.057</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>0.6</mu>
<mu2>0.6</mu2>
<fdir1>0 0 0</fdir1>
<slip1>0</slip1>
<slip2>0</slip2>
</ode>
<torsional>
<coefficient>1</coefficient>
<patch_radius>0</patch_radius>
<surface_radius>0</surface_radius>
<use_patch_radius>1</use_patch_radius>
<ode>
<slip>0</slip>
</ode>
</torsional>
</friction>
<bounce>
<restitution_coefficient>0</restitution_coefficient>
<threshold>1e+06</threshold>
</bounce>
<contact>
<collide_without_contact>0</collide_without_contact>
<collide_without_contact_bitmask>1</collide_without_contact_bitmask>
<collide_bitmask>1</collide_bitmask>
<ode>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
<max_vel>0.01</max_vel>
<min_depth>0</min_depth>
</ode>
<bullet>
<split_impulse>1</split_impulse>
<split_impulse_penetration_threshold>-0.01</split_impulse_penetration_threshold>
<soft_cfm>0</soft_cfm>
<soft_erp>0.2</soft_erp>
<kp>1e+13</kp>
<kd>1</kd>
</bullet>
</contact>
</surface>
</collision>
</link>
<frame name="top_center">
<!--
TODO(eric.cousineau): @frame='link' is redundant, but not having it
causes RBT SDFormat parsing code to segfault. Remove this once RBT is
removed.
-->
<pose relative_to="link">0 0 0.7645 0 0 0</pose>
</frame>
<!--
N.B. This model used to have <static>true</static>, but this creates
issues in reusability with the current implementation of MBP parsing
(#12227).
-->
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples/kuka_iiwa_arm | /home/johnshepherd/drake/examples/kuka_iiwa_arm/test/kuka_torque_controller_test.cc | #include "drake/examples/kuka_iiwa_arm/kuka_torque_controller.h"
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/examples/kuka_iiwa_arm/iiwa_common.h"
#include "drake/multibody/parsing/parser.h"
namespace drake {
namespace examples {
namespace kuka_iiwa_arm {
using drake::systems::BasicVector;
namespace {
Eigen::VectorXd CalcGravityCompensationTorque(
const multibody::MultibodyPlant<double>& plant,
const Eigen::VectorXd& q,
Eigen::MatrixXd* H = nullptr) {
// Compute gravity compensation torque.
std::unique_ptr<systems::Context<double>> plant_context =
plant.CreateDefaultContext();
Eigen::VectorXd zero_velocity = Eigen::VectorXd::Zero(kIiwaArmNumJoints);
plant.SetPositions(plant_context.get(), q);
plant.SetVelocities(plant_context.get(), zero_velocity);
if (H) {
plant.CalcMassMatrixViaInverseDynamics(*plant_context, H);
}
multibody::MultibodyForces<double> external_forces(plant);
plant.CalcForceElementsContribution(*plant_context, &external_forces);
return plant.CalcInverseDynamics(*plant_context, zero_velocity,
external_forces);
}
} // namespace
GTEST_TEST(KukaTorqueControllerTest, GravityCompensationTest) {
multibody::MultibodyPlant<double> plant(0.0);
multibody::Parser(&plant).AddModelsFromUrl(
"package://drake_models/iiwa_description/urdf/"
"iiwa14_polytope_collision.urdf");
plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("base"));
plant.Finalize();
// Set stiffness and damping to zero.
VectorX<double> stiffness(kIiwaArmNumJoints);
stiffness.setZero();
VectorX<double> damping(kIiwaArmNumJoints);
damping.setZero();
// Choose an arbitrary state.
VectorX<double> q(7);
q << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;
VectorX<double> v(7);
v << 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1;
VectorX<double> q_des(7);
q_des << -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7;
VectorX<double> v_des(7);
v_des << -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1;
VectorX<double> torque_des(kIiwaArmNumJoints);
torque_des.setZero();
// Compute controller output.
KukaTorqueController<double> controller(plant, stiffness, damping);
std::unique_ptr<systems::Context<double>> context =
controller.CreateDefaultContext();
std::unique_ptr<systems::SystemOutput<double>> output =
controller.AllocateOutput();
VectorX<double> estimated_state_input(2 * kIiwaArmNumJoints);
estimated_state_input << q, v;
VectorX<double> desired_state_input(2 * kIiwaArmNumJoints);
desired_state_input << q_des, v_des;
VectorX<double> desired_torque_input(kIiwaArmNumJoints);
desired_torque_input << torque_des;
controller.get_input_port_estimated_state().FixValue(context.get(),
estimated_state_input);
controller.get_input_port_desired_state().FixValue(context.get(),
desired_state_input);
controller.get_input_port_commanded_torque().FixValue(context.get(),
desired_torque_input);
Eigen::VectorXd expected_torque =
CalcGravityCompensationTorque(plant, q);
// Check output.
controller.CalcOutput(*context, output.get());
const BasicVector<double>* output_vector = output->get_vector_data(0);
EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->value(),
1e-10, MatrixCompareType::absolute));
}
GTEST_TEST(KukaTorqueControllerTest, SpringTorqueTest) {
multibody::MultibodyPlant<double> plant(0.0);
multibody::Parser(&plant).AddModelsFromUrl(
"package://drake_models/iiwa_description/urdf/"
"iiwa14_polytope_collision.urdf");
plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("base"));
plant.Finalize();
// Set nonzero stiffness and zero damping.
VectorX<double> stiffness(kIiwaArmNumJoints);
stiffness << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;
VectorX<double> damping(kIiwaArmNumJoints);
damping.setZero();
// Choose an arbitrary state
VectorX<double> q(7);
q << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;
VectorX<double> v(7);
v << 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1;
VectorX<double> q_des(7);
q_des << -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7;
VectorX<double> v_des(7);
v_des << -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1;
VectorX<double> torque_des(kIiwaArmNumJoints);
torque_des.setZero();
// Compute controller output.
KukaTorqueController<double> controller(plant, stiffness, damping);
std::unique_ptr<systems::Context<double>> context =
controller.CreateDefaultContext();
std::unique_ptr<systems::SystemOutput<double>> output =
controller.AllocateOutput();
VectorX<double> estimated_state_input(2 * kIiwaArmNumJoints);
estimated_state_input << q, v;
VectorX<double> desired_state_input(2 * kIiwaArmNumJoints);
desired_state_input << q_des, v_des;
VectorX<double> desired_torque_input(kIiwaArmNumJoints);
desired_torque_input << torque_des;
controller.get_input_port_estimated_state().FixValue(context.get(),
estimated_state_input);
controller.get_input_port_desired_state().FixValue(context.get(),
desired_state_input);
controller.get_input_port_commanded_torque().FixValue(context.get(),
desired_torque_input);
// Compute gravity compensation torque.
Eigen::VectorXd expected_torque =
CalcGravityCompensationTorque(plant, q);
// Compute spring torque.
expected_torque += -((q - q_des).array() * stiffness.array()).matrix();
// Check output.
controller.CalcOutput(*context, output.get());
const BasicVector<double>* output_vector = output->get_vector_data(0);
EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->value(),
1e-10, MatrixCompareType::absolute));
}
GTEST_TEST(KukaTorqueControllerTest, DampingTorqueTest) {
multibody::MultibodyPlant<double> plant(0.0);
multibody::Parser(&plant).AddModelsFromUrl(
"package://drake_models/iiwa_description/urdf/"
"iiwa14_polytope_collision.urdf");
plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("base"));
plant.Finalize();
// Set arbitrary stiffness and damping.
VectorX<double> stiffness(kIiwaArmNumJoints);
stiffness << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;
VectorX<double> damping(kIiwaArmNumJoints);
damping << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;
// Choose an arbitrary state
VectorX<double> q(7);
q << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7;
VectorX<double> v(7);
v << 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1;
VectorX<double> q_des(7);
q_des << -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7;
VectorX<double> v_des(7);
v_des << -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1;
VectorX<double> torque_des(kIiwaArmNumJoints);
torque_des.setZero();
// Compute controller output.
KukaTorqueController<double> controller(plant, stiffness, damping);
std::unique_ptr<systems::Context<double>> context =
controller.CreateDefaultContext();
std::unique_ptr<systems::SystemOutput<double>> output =
controller.AllocateOutput();
VectorX<double> estimated_state_input(2 * kIiwaArmNumJoints);
estimated_state_input << q, v;
VectorX<double> desired_state_input(2 * kIiwaArmNumJoints);
desired_state_input << q_des, v_des;
VectorX<double> desired_torque_input(kIiwaArmNumJoints);
desired_torque_input << torque_des;
controller.get_input_port_estimated_state().FixValue(context.get(),
estimated_state_input);
controller.get_input_port_desired_state().FixValue(context.get(),
desired_state_input);
controller.get_input_port_commanded_torque().FixValue(context.get(),
desired_torque_input);
// Compute gravity compensation torque and mass matrix.
Eigen::MatrixXd H(kIiwaArmNumJoints, kIiwaArmNumJoints);
Eigen::VectorXd expected_torque =
CalcGravityCompensationTorque(plant, q, &H);
// Compute spring torque.
expected_torque += -((q - q_des).array() * stiffness.array()).matrix();
// Compute damping torque.
Eigen::VectorXd damping_torque(7);
for (int i = 0; i < kIiwaArmNumJoints; i++) {
damping_torque(i) =
-v(i) * damping(i) * 2 * std::sqrt(H(i, i) * stiffness(i));
}
expected_torque += damping_torque;
// Check output.
controller.CalcOutput(*context, output.get());
const BasicVector<double>* output_vector = output->get_vector_data(0);
EXPECT_TRUE(CompareMatrices(expected_torque, output_vector->value(),
1e-10, MatrixCompareType::absolute));
}
} // namespace kuka_iiwa_arm
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_binary",
"drake_cc_library",
)
load(
"//tools/skylark:drake_py.bzl",
"drake_py_binary",
"drake_py_library",
"drake_py_unittest",
)
package(default_visibility = ["//visibility:private"])
filegroup(
name = "demo_data",
srcs = [
":example_scenarios.yaml",
"//examples/pendulum:models",
"@drake_models//:iiwa_description",
"@drake_models//:manipulation_station",
"@drake_models//:wsg_50_description",
],
visibility = ["//:__pkg__"],
)
drake_cc_library(
name = "scenario",
srcs = ["scenario.cc"],
hdrs = ["scenario.h"],
interface_deps = [
"//common:name_value",
"//lcm:drake_lcm_params",
"//manipulation/kuka_iiwa:iiwa_driver",
"//manipulation/schunk_wsg:schunk_wsg_driver",
"//manipulation/util:zero_force_driver",
"//multibody/plant:multibody_plant_config",
"//multibody/parsing:model_directives",
"//systems/analysis:simulator_config",
"//systems/sensors:camera_config",
"//visualization:visualization_config",
],
deps = [
"//common/yaml",
],
)
drake_cc_binary(
name = "hardware_sim_cc",
srcs = ["hardware_sim.cc"],
deps = [
":scenario",
"//common:add_text_logging_gflags",
"//manipulation/kuka_iiwa:iiwa_driver_functions",
"//manipulation/schunk_wsg:schunk_wsg_driver_functions",
"//manipulation/util:apply_driver_configs",
"//manipulation/util:zero_force_driver_functions",
"//multibody/parsing",
"//multibody/plant",
"//systems/analysis:simulator",
"//systems/analysis:simulator_config_functions",
"//systems/lcm:lcm_config_functions",
"//systems/sensors:camera_config_functions",
"//visualization:visualization_config_functions",
],
)
# Binds the C++ hardware_sim program to the data files required for the Demo
# example scenario.
sh_binary(
name = "demo_cc",
srcs = [":hardware_sim_cc"],
args = [
"--scenario_file=examples/hardware_sim/example_scenarios.yaml",
"--scenario_name=Demo",
],
data = [
":demo_data",
],
# Use the runfiles of the ":demo", not of the ":hardware_sim".
env = {"RUNFILES_DIR": "../"},
)
drake_py_library(
name = "hardware_sim_test_common",
testonly = True,
srcs = ["test/hardware_sim_test_common.py"],
deps = [
"@rules_python//python/runfiles",
],
)
drake_py_unittest(
name = "hardware_sim_cc_test",
# Note: It's safe to use lcm in the test because it uses a non-default URL
# and only transmits status messages.
allow_network = ["lcm:meshcat"],
data = [
"test/test_scenarios.yaml",
":demo_cc",
],
shard_count = 4,
deps = [
":hardware_sim_test_common",
],
)
drake_py_binary(
name = "hardware_sim_py",
srcs = ["hardware_sim.py"],
visibility = [
"//bindings/pydrake/visualization:__pkg__",
],
deps = [
"//bindings/pydrake",
],
)
# Binds the Python hardware_sim program to the data files required for the Demo
# example scenario.
drake_py_binary(
name = "demo_py",
srcs = ["hardware_sim.py"],
args = [
"--scenario_file=examples/hardware_sim/example_scenarios.yaml",
"--scenario_name=Demo",
],
data = [
":demo_data",
":hardware_sim_py",
],
deps = [
"//bindings/pydrake",
],
)
drake_py_unittest(
name = "hardware_sim_py_test",
# Note: It's safe to use lcm in the test because it uses a non-default URL
# and only transmits status messages.
allow_network = ["lcm:meshcat"],
data = [
"test/test_scenarios.yaml",
":demo_py",
],
env = {
"_DRAKE_DEPRECATION_IS_ERROR": "1",
},
shard_count = 4,
deps = [
":hardware_sim_test_common",
],
)
drake_py_binary(
name = "robot_commander",
srcs = ["robot_commander.py"],
deps = [
"//bindings/pydrake",
],
)
drake_py_unittest(
name = "robot_commander_test",
data = [
":example_scenarios.yaml",
],
deps = [
":robot_commander",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/README.md |
# Standalone Robot Simulations
This directory contains example programs that illustrate how to use Drake's YAML
configuration fragments to set up and run your own robot simulation.
The example shows how to simulate a robot where joint command messages arrive
from some external source. The simulation publishes simulated joint status
messages and simulated camera image messages.
The same demo is implemented in both Python and C++, for reference.
Note that the demo contains only static scene by default. The robot is
uncommanded and nothing is happening; all you'll see is the scene geometry along
with a display of the contact forces (green arrows). You can run another program
`robot_commander.py` to actuate the robot with a simple motion.
## Running the Python demo from a Drake binary release
The demo is not installed as part of Drake releases. We expect and encourage you
to copy these files into your own projects and customize them there.
(1) Use https://drake.mit.edu/installation.html to install Drake. The ``pip``
installation is a good option. Make sure your ``$PYTHONPATH`` is set correctly
per the instructions.
(2) Copy ``hardware_sim.py`` and ``example_scenarios.yaml`` into a temporary
directory:
* https://raw.githubusercontent.com/RobotLocomotion/drake/master/examples/hardware_sim/hardware_sim.py
* https://raw.githubusercontent.com/RobotLocomotion/drake/master/examples/hardware_sim/example_scenarios.yaml
(3) (Optional) Run the standalone visualizer:
```
python3 -m pydrake.visualization.meldis -w &
```
This command will open a new web browser window, initially showing an empty
scene. This "standalone" visualizer can remain running even as you repeatedly
start and stop the simulation.
(4) Run the simulation.
```
python3 hardware_sim.py --scenario_file=example_scenarios.yaml \
--scenario_name=Demo --scenario_text='{ simulation_duration: 60 }'
```
(5) (Optional) Send actuation commands to the robot.
Copy ``robot_commander.py`` into the temporary directory and run the command in
another terminal:
* https://raw.githubusercontent.com/RobotLocomotion/drake/master/examples/hardware_sim/robot_commander.py
```
python3 robot_commander.py
```
If you didn't launch the visualizer in step (3), look for a log message like
``Meshcat listening for connections at http://localhost:7000`` and click on that
link to open a temporary visualizer (that will disappear when you close the
simulation).
## Running from a Drake source build
To use Python, run these commands:
```
$ cd drake
$ bazel run //tools:meldis -- -w &
$ bazel run //examples/hardware_sim:demo_py
```
To use C++, run these commands:
Run these commands:
```
$ cd drake
$ bazel run //tools:meldis -- -w &
$ bazel run //examples/hardware_sim:demo_cc
```
(Optionally) To actuate the robot, run the command in another terminal:
```
$ bazel run //examples/hardware_sim:robot_commander
```
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/example_scenarios.yaml | # This file is licensed under the MIT-0 License.
# See LICENSE-MIT-0.txt in the current directory.
# This demo simulation shows an IIWA arm with an attached WSG gripper.
Demo:
scene_graph_config:
default_proximity_properties:
compliance_type: "compliant"
directives:
- add_model:
name: amazon_table
file: package://drake_models/manipulation_station/amazon_table_simplified.sdf
- add_weld:
parent: world
child: amazon_table::amazon_table
- add_model:
name: iiwa
file: package://drake_models/iiwa_description/urdf/iiwa14_primitive_collision.urdf
default_joint_positions:
iiwa_joint_1: [-0.2]
iiwa_joint_2: [0.79]
iiwa_joint_3: [0.32]
iiwa_joint_4: [-1.76]
iiwa_joint_5: [-0.36]
iiwa_joint_6: [0.64]
iiwa_joint_7: [-0.73]
- add_frame:
name: iiwa_on_world
X_PF:
base_frame: world
translation: [0, -0.7, 0.1]
rotation: !Rpy { deg: [0, 0, 90] }
- add_weld:
parent: iiwa_on_world
child: iiwa::base
- add_model:
name: wsg
file: package://drake_models/wsg_50_description/sdf/schunk_wsg_50_with_tip.sdf
default_joint_positions:
left_finger_sliding_joint: [-0.02]
right_finger_sliding_joint: [0.02]
- add_frame:
name: wsg_on_iiwa
X_PF:
base_frame: iiwa_link_7
translation: [0, 0, 0.114]
rotation: !Rpy { deg: [90, 0, 90] }
- add_weld:
parent: wsg_on_iiwa
child: wsg::body
lcm_buses:
driver_traffic:
# Use a non-default LCM url to communicate with the robot.
lcm_url: udpm://239.241.129.92:20185?ttl=0
cameras:
oracular_view:
name: camera_0
X_PB:
translation: [1.5, 0.8, 1.25]
rotation: !Rpy { deg: [-120, 5, 125] }
model_drivers:
iiwa: !IiwaDriver
hand_model_name: wsg
lcm_bus: driver_traffic
wsg: !SchunkWsgDriver
lcm_bus: driver_traffic
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/scenario.cc | // This file is licensed under the MIT-0 License.
// See LICENSE-MIT-0.txt in the current directory.
#include "drake/examples/hardware_sim/scenario.h"
#include <utility>
#include "drake/common/yaml/yaml_io.h"
namespace drake {
namespace internal {
// N.B. This is in a cc file to reduce compilation time for the serialization-
// related template classes and functions.
Scenario LoadScenario(
const std::string& filename,
const std::string& scenario_name,
const std::string& scenario_text) {
// Begin with the constructor defaults.
Scenario scenario;
// Add in changes from the scenario file (if given).
if (!filename.empty()) {
scenario = drake::yaml::LoadYamlFile<Scenario>(
filename, {scenario_name}, {std::move(scenario)});
}
// Add in changes from the extra scenario text.
scenario = drake::yaml::LoadYamlString<Scenario>(
scenario_text, std::nullopt /* no name */, {std::move(scenario)});
return scenario;
}
// N.B. This is in a cc file to reduce compilation time for the serialization-
// related template classes and functions.
std::string SaveScenario(
const Scenario& scenario,
const std::string& scenario_name,
bool verbose) {
const auto defaults = verbose ? std::nullopt : std::optional{Scenario{}};
return drake::yaml::SaveYamlString(scenario, {scenario_name}, defaults);
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/hardware_sim.cc | // This file is licensed under the MIT-0 License.
// See LICENSE-MIT-0.txt in the current directory.
/* This program serves as an example of a simulator for hardware, i.e., a
simulator for robots that one might have in their lab. There is no controller
built-in to this program -- it merely sends status and sensor messages, and
listens for command messages.
It is intended to operate in the "no ground truth" regime, i.e, the only LCM
messages it knows about are the ones used by the actual hardware. The one
messaging difference from real life is that we emit visualization messages (for
Meldis) so that you can watch a simulation on your screen while some (separate)
controller operates the robot, without extra hassle.
Drake maintainers should keep this file in sync with hardware_sim.py. */
#include <fstream>
#include <gflags/gflags.h>
#include "drake/common/unused.h"
#include "drake/examples/hardware_sim/scenario.h"
#include "drake/manipulation/kuka_iiwa/iiwa_driver_functions.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_driver_functions.h"
#include "drake/manipulation/util/apply_driver_configs.h"
#include "drake/manipulation/util/zero_force_driver_functions.h"
#include "drake/multibody/parsing/process_model_directives.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/multibody/plant/multibody_plant_config_functions.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/analysis/simulator_config_functions.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/lcm/lcm_config_functions.h"
#include "drake/systems/sensors/camera_config_functions.h"
#include "drake/visualization/visualization_config_functions.h"
DEFINE_string(scenario_file, "",
"Scenario filename, e.g., "
"drake/examples/hardware_sim/example_scenarios.yaml");
DEFINE_string(scenario_name, "",
"Scenario name within the scenario_file, e.g., Demo in the "
"example_scenarios.yaml; scenario names appears as the keys of the "
"YAML document's top-level mapping item");
DEFINE_string(scenario_text, "{}",
"Additional YAML scenario text to load, in order to override values "
"in the scenario_file, e.g., timeouts");
DEFINE_string(graphviz, "",
"Dump the Simulator's Diagram to this file in Graphviz format as a "
"debugging aid");
namespace drake {
namespace {
using internal::Scenario;
using lcm::DrakeLcmInterface;
using multibody::ModelInstanceIndex;
using multibody::parsing::ModelInstanceInfo;
using multibody::parsing::ProcessModelDirectives;
using systems::ApplySimulatorConfig;
using systems::Diagram;
using systems::DiagramBuilder;
using systems::Simulator;
using systems::lcm::ApplyLcmBusConfig;
using systems::lcm::LcmBuses;
using systems::sensors::ApplyCameraConfig;
using visualization::ApplyVisualizationConfig;
/* Class that holds the configuration and data of a simulation. */
class Simulation {
public:
explicit Simulation(const Scenario& scenario)
: scenario_(scenario) {}
/* Performs all of the initial setup of the simulation diagram and context. */
void Setup();
/* Runs the main loop of the simulation until completion criteria are met. */
void Simulate();
/* Provides read-only access to the diagram. */
const Diagram<double>& diagram() { return *diagram_; }
private:
// The scenario passed into the ctor.
const Scenario scenario_;
std::unique_ptr<Diagram<double>> diagram_;
std::unique_ptr<Simulator<double>> simulator_;
};
void Simulation::Setup() {
DiagramBuilder<double> builder;
// Create the multibody plant and scene graph.
auto [sim_plant, scene_graph] = AddMultibodyPlant(
scenario_.plant_config, scenario_.scene_graph_config, &builder);
// Add model directives.
std::vector<ModelInstanceInfo> added_models;
ProcessModelDirectives({scenario_.directives}, &sim_plant, &added_models);
// Now the plant is complete.
sim_plant.Finalize();
// Add LCM buses. (The simulator will handle polling the network for new
// messages and dispatching them to the receivers, i.e., "pump" the bus.)
const LcmBuses lcm_buses = ApplyLcmBusConfig(scenario_.lcm_buses, &builder);
// Add actuation inputs.
ApplyDriverConfigs(scenario_.model_drivers, sim_plant, added_models,
lcm_buses, &builder);
// Add scene cameras.
for (const auto& [yaml_name, camera] : scenario_.cameras) {
unused(yaml_name);
ApplyCameraConfig(camera, &builder, &lcm_buses);
}
// Add visualization.
ApplyVisualizationConfig(scenario_.visualization, &builder, &lcm_buses);
// Build the diagram and its simulator.
diagram_ = builder.Build();
simulator_ = std::make_unique<Simulator<double>>(*diagram_);
ApplySimulatorConfig(scenario_.simulator_config, simulator_.get());
// Sample the random elements of the context.
RandomGenerator random(scenario_.random_seed);
diagram_->SetRandomContext(&simulator_->get_mutable_context(), &random);
}
void Simulation::Simulate() {
simulator_->AdvanceTo(scenario_.simulation_duration);
}
int main() {
const Scenario scenario = internal::LoadScenario(
FLAGS_scenario_file, FLAGS_scenario_name, FLAGS_scenario_text);
Simulation sim(scenario);
sim.Setup();
if (!FLAGS_graphviz.empty()) {
std::ofstream graphviz(FLAGS_graphviz);
std::map<std::string, std::string> options;
options.emplace("plant/split", "I/O");
graphviz << sim.diagram().GetGraphvizString({}, options);
DRAKE_THROW_UNLESS(graphviz.good());
}
sim.Simulate();
return 0;
}
} // namespace
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::main();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/LICENSE-MIT-0.txt | --------------------------------------------------------------------------------
This license applies to certain files within this directory, as noted by a
comment atop the file. Files that do not mention this license are instead
licensed under Drake's default LICENSE.TXT at the root of the repository.
--------------------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/robot_commander.py | """A simple program to actuate the robot, an IIWA arm and a WSG gripper, with a
cyclic motion.
"""
import itertools
import os
import time
import numpy as np
from drake import lcmt_iiwa_command, lcmt_schunk_wsg_command
from pydrake.lcm import DrakeLcm
# Use a non-default LCM url to communicate with the robot.
LCM_URL = "udpm://239.241.129.92:20185?ttl=0"
# The initial positions of the robot. This should be kept in sync with the
# scenario file's "Demo" example.
IIWA_Q0 = np.array([-0.2, 0.79, 0.32, -1.76, -0.36, 0.64, -0.73])
WSG_Q0 = 0.02 # In meters.
# The maximum deflection from IIWA and WSG's initial position, i.e., each joint
# will move between +/- MAX_DEFLECTION. The numbers are selected to avoid
# collisions within the scene.
IIWA_MAX_DEFLECTION = 0.4
WSG_MAX_DEFLECTION = 0.02
# The rate to send the robot commands.
COMMAND_HZ = 20
# How much time for a motion cycle, in seconds.
CYCLE_TIME = 10.0
def main():
lcm = DrakeLcm(LCM_URL)
wsg_command = lcmt_schunk_wsg_command()
wsg_command.force = 20.0
iiwa_command = lcmt_iiwa_command()
iiwa_command.num_joints = 7
for i in itertools.count():
sine = np.sin(2 * np.pi * i / (CYCLE_TIME * COMMAND_HZ))
iiwa_command.joint_position = IIWA_Q0 + sine * IIWA_MAX_DEFLECTION
wsg_command.target_position_mm = 1e3 * (
WSG_Q0 + sine * WSG_MAX_DEFLECTION
)
lcm.Publish(channel="IIWA_COMMAND", buffer=iiwa_command.encode())
lcm.Publish(channel="SCHUNK_WSG_COMMAND", buffer=wsg_command.encode())
time.sleep(1 / COMMAND_HZ)
# When unit testing, just send one command.
if "TEST_SRCDIR" in os.environ:
break
if __name__ == "__main__":
main()
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/hardware_sim.py | # This file is licensed under the MIT-0 License.
# See LICENSE-MIT-0.txt in the current directory.
"""
This program serves as an example of a simulator for hardware, i.e., a
simulator for robots that one might have in their lab. There is no controller
built-in to this program -- it merely sends status and sensor messages, and
listens for command messages.
It is intended to operate in the "no ground truth" regime, i.e, the only LCM
messages it knows about are the ones used by the actual hardware. The one
messaging difference from real life is that we emit visualization messages (for
Meldis) so that you can watch a simulation on your screen while some (separate)
controller operates the robot, without extra hassle.
Drake maintainers should keep this file in sync with both hardware_sim.cc and
scenario.h.
"""
import argparse
import dataclasses as dc
import math
import typing
from pydrake.common import RandomGenerator
from pydrake.common.yaml import yaml_load_typed
from pydrake.lcm import DrakeLcmParams
from pydrake.manipulation import (
ApplyDriverConfigs,
IiwaDriver,
SchunkWsgDriver,
ZeroForceDriver,
)
from pydrake.geometry import (
SceneGraphConfig
)
from pydrake.multibody.plant import (
AddMultibodyPlant,
MultibodyPlantConfig,
)
from pydrake.multibody.parsing import (
ModelDirective,
ModelDirectives,
ProcessModelDirectives,
)
from pydrake.systems.analysis import (
ApplySimulatorConfig,
Simulator,
SimulatorConfig,
)
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.lcm import ApplyLcmBusConfig
from pydrake.systems.sensors import (
ApplyCameraConfig,
CameraConfig,
)
from pydrake.visualization import (
ApplyVisualizationConfig,
VisualizationConfig,
)
@dc.dataclass
class Scenario:
"""Defines the YAML format for a (possibly stochastic) scenario to be
simulated.
"""
# Random seed for any random elements in the scenario. The seed is always
# deterministic in the `Scenario`; a caller who wants randomness must
# populate this value from their own randomness.
random_seed: int = 0
# The maximum simulation time (in seconds). The simulator will attempt to
# run until this time and then terminate.
simulation_duration: float = math.inf
# Simulator configuration (integrator and publisher parameters).
simulator_config: SimulatorConfig = SimulatorConfig(
max_step_size=1e-3,
accuracy=1.0e-2,
target_realtime_rate=1.0)
# Plant configuration (time step and contact parameters).
plant_config: MultibodyPlantConfig = MultibodyPlantConfig()
# SceneGraph configuration.
scene_graph_config: SceneGraphConfig = SceneGraphConfig()
# All of the fully deterministic elements of the simulation.
directives: typing.List[ModelDirective] = dc.field(default_factory=list)
# A map of {bus_name: lcm_params} for LCM transceivers to be used by
# drivers, sensors, etc.
lcm_buses: typing.Mapping[str, DrakeLcmParams] = dc.field(
default_factory=lambda: dict(default=DrakeLcmParams()))
# For actuated models, specifies where each model's actuation inputs come
# from, keyed on the ModelInstance name.
model_drivers: typing.Mapping[str, typing.Union[
IiwaDriver,
SchunkWsgDriver,
ZeroForceDriver,
]] = dc.field(default_factory=dict)
# Cameras to add to the scene (and broadcast over LCM). The key for each
# camera is a helpful mnemonic, but does not serve a technical role. The
# CameraConfig::name field is still the name that will appear in the
# Diagram artifacts.
cameras: typing.Mapping[str, CameraConfig] = dc.field(default_factory=dict)
visualization: VisualizationConfig = VisualizationConfig()
def _load_scenario(*, filename, scenario_name, scenario_text):
"""Implements the command-line handling logic for scenario data.
Returns a `Scenario` object loaded from the given input arguments.
"""
result = yaml_load_typed(
schema=Scenario,
filename=filename,
child_name=scenario_name,
defaults=Scenario())
result = yaml_load_typed(
schema=Scenario,
data=scenario_text,
defaults=result)
return result
def run(*, scenario, graphviz=None):
"""Runs a simulation of the given scenario.
"""
builder = DiagramBuilder()
# Create the multibody plant and scene graph.
sim_plant, scene_graph = AddMultibodyPlant(
plant_config=scenario.plant_config,
scene_graph_config=scenario.scene_graph_config,
builder=builder)
# Add model directives.
added_models = ProcessModelDirectives(
directives=ModelDirectives(directives=scenario.directives),
plant=sim_plant)
# Now the plant is complete.
sim_plant.Finalize()
# Add LCM buses. (The simulator will handle polling the network for new
# messages and dispatching them to the receivers, i.e., "pump" the bus.)
lcm_buses = ApplyLcmBusConfig(
lcm_buses=scenario.lcm_buses,
builder=builder)
# Add actuation inputs.
ApplyDriverConfigs(
driver_configs=scenario.model_drivers,
sim_plant=sim_plant,
models_from_directives=added_models,
lcm_buses=lcm_buses,
builder=builder)
# Add scene cameras.
for _, camera in scenario.cameras.items():
ApplyCameraConfig(
config=camera,
builder=builder,
lcm_buses=lcm_buses)
# Add visualization.
ApplyVisualizationConfig(scenario.visualization, builder, lcm_buses)
# Build the diagram and its simulator.
diagram = builder.Build()
simulator = Simulator(diagram)
ApplySimulatorConfig(scenario.simulator_config, simulator)
# Sample the random elements of the context.
random = RandomGenerator(scenario.random_seed)
diagram.SetRandomContext(simulator.get_mutable_context(), random)
# Visualize the diagram, when requested.
if graphviz is not None:
with open(graphviz, "w", encoding="utf-8") as f:
options = {"plant/split": "I/O"}
f.write(diagram.GetGraphvizString(options=options))
# Simulate.
simulator.AdvanceTo(scenario.simulation_duration)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--scenario_file", required=True,
help="Scenario filename, e.g., "
"drake/examples/hardware_sim/example_scenarios.yaml")
parser.add_argument(
"--scenario_name", required=True,
help="Scenario name within the scenario_file, e.g., Demo in the "
"example_scenarios.yaml; scenario names appears as the keys of "
"the YAML document's top-level mapping item")
parser.add_argument(
"--scenario_text", default="{}",
help="Additional YAML scenario text to load, in order to override "
"values in the scenario_file, e.g., timeouts")
parser.add_argument(
"--graphviz", metavar="FILENAME",
help="Dump the Simulator's Diagram to this file in Graphviz format "
"as a debugging aid")
args = parser.parse_args()
scenario = _load_scenario(
filename=args.scenario_file,
scenario_name=args.scenario_name,
scenario_text=args.scenario_text)
run(scenario=scenario, graphviz=args.graphviz)
if __name__ == "__main__":
main()
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/hardware_sim/scenario.h | // This file is licensed under the MIT-0 License.
// See LICENSE-MIT-0.txt in the current directory.
#pragma once
#include <cstdint>
#include <limits>
#include <map>
#include <string>
#include <variant>
#include <vector>
#include "drake/common/name_value.h"
#include "drake/geometry/scene_graph_config.h"
#include "drake/lcm/drake_lcm_params.h"
#include "drake/manipulation/kuka_iiwa/iiwa_driver.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_driver.h"
#include "drake/manipulation/util/zero_force_driver.h"
#include "drake/multibody/parsing/model_directives.h"
#include "drake/multibody/plant/multibody_plant_config.h"
#include "drake/systems/analysis/simulator_config.h"
#include "drake/systems/sensors/camera_config.h"
#include "drake/visualization/visualization_config.h"
namespace drake {
namespace internal {
/* Defines the YAML format for a (possibly stochastic) scenario to be
simulated.
Drake maintainers should keep this file in sync with hardware_sim.py. */
struct Scenario {
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(random_seed));
a->Visit(DRAKE_NVP(simulation_duration));
a->Visit(DRAKE_NVP(simulator_config));
a->Visit(DRAKE_NVP(plant_config));
a->Visit(DRAKE_NVP(scene_graph_config));
a->Visit(DRAKE_NVP(directives));
a->Visit(DRAKE_NVP(lcm_buses));
a->Visit(DRAKE_NVP(model_drivers));
a->Visit(DRAKE_NVP(cameras));
a->Visit(DRAKE_NVP(visualization));
}
/* Random seed for any random elements in the scenario.
The seed is always deterministic in the `Scenario`; a caller who wants
randomness must populate this value from their own randomness. */
std::uint64_t random_seed{0};
/* The maximum simulation time (in seconds). The simulator will attempt to
run until this time and then terminate. */
double simulation_duration{std::numeric_limits<double>::infinity()};
/* Simulator configuration (integrator and publisher parameters). */
systems::SimulatorConfig simulator_config{
.max_step_size = 1e-3,
.accuracy = 1.0e-2,
.target_realtime_rate = 1.0,
};
/* Plant configuration (time step and contact parameters). */
multibody::MultibodyPlantConfig plant_config;
/* SceneGraph configuration. */
geometry::SceneGraphConfig scene_graph_config;
/* All of the fully deterministic elements of the simulation. */
std::vector<multibody::parsing::ModelDirective> directives;
/* A map of {bus_name: lcm_params} for LCM transceivers to be used by drivers,
sensors, etc. */
std::map<std::string, lcm::DrakeLcmParams> lcm_buses{{"default", {}}};
/* For actuated models, specifies where each model's actuation inputs come
from, keyed on the ModelInstance name. */
using DriverVariant = std::variant<
manipulation::kuka_iiwa::IiwaDriver,
manipulation::schunk_wsg::SchunkWsgDriver,
manipulation::ZeroForceDriver>;
std::map<std::string, DriverVariant> model_drivers;
/* Cameras to add to the scene (and broadcast over LCM). The key for each
camera is a helpful mnemonic, but does not serve a technical role. The
CameraConfig::name field is still the name that will appear in the Diagram
artifacts. */
std::map<std::string, systems::sensors::CameraConfig> cameras;
visualization::VisualizationConfig visualization;
};
/* Returns a C++ representation of the given YAML scenario.
Refer to the gflags descriptions atop hardware_sim.cc for details. */
Scenario LoadScenario(
const std::string& filename,
const std::string& scenario_name,
const std::string& scenario_text = "{}");
/* Returns a YAML representation of this C++ scenario.
@param verbose When saving the scenario, whether or not default values should be
written out to be explicit (true) or omitted (false). Verbosity helps defend
logged testset scenarios against changing defaults. */
std::string SaveScenario(
const Scenario& scenario,
const std::string& scenario_name,
bool verbose = false);
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/hardware_sim | /home/johnshepherd/drake/examples/hardware_sim/test/hardware_sim_test_common.py | """This file contains smoke tests for our hardware_sim program and its sample
config files. The tests are reused for both the C++ and Python regression
tests.
Note that this file is only ever imported; it is never run as a unittest
program itself; we'll use wrapper files named hardware_sim_cc_test and
hardware_sim_py_test to actually run it.
"""
import copy
import os.path
import re
import shlex
import subprocess
import sys
import yaml
from python.runfiles import Create as CreateRunfiles
class HardwareSimTest:
def _find_resource(self, respath):
runfiles = CreateRunfiles()
result = runfiles.Rlocation(respath)
self.assertTrue(result, respath)
self.assertTrue(os.path.exists(result), respath)
return result
def setUp(self):
"""Prior to anything calling this function, our subclass must set our
self._sim_lang to either "cc" or "py".
"""
lang = self._sim_lang
self._simulator = self._find_resource(
f"drake/examples/hardware_sim/hardware_sim_{lang}")
self._example_scenarios = self._find_resource(
"drake/examples/hardware_sim/example_scenarios.yaml")
self._test_scenarios = self._find_resource(
"drake/examples/hardware_sim/test/test_scenarios.yaml")
self._default_extra = {
# For our smoke test, exit fairly quickly.
"simulation_duration": 0.0625,
}
def _dict_to_single_line_yaml(self, *, data):
"""Given a dictionary, returns it as a YAML one-liner."""
result = yaml.dump(data, default_flow_style=True)
result = result.replace("\n", " ").strip()
result = re.sub(r" *", " ", result)
return result
def _run(self, scenario_file, scenario_name, extra=None, graphviz=None):
"""Runs the given scenario for 1 second, checking that it does not
crash. Allows overriding scenario options using the optional `extra`
dictionary"""
merged = copy.deepcopy(self._default_extra)
merged.update(extra or {})
scenario_text = self._dict_to_single_line_yaml(data=merged)
args = [
self._simulator,
f"--scenario_file={scenario_file}",
f"--scenario_name={scenario_name}",
f"--scenario_text={scenario_text}",
]
if graphviz is not None:
args.append(f"--graphviz={graphviz}")
printable_args = " ".join([
shlex.quote(re.sub(r"[^=]*\.runfiles/", "", x))
for x in args
])
print(f"== Running {printable_args}", file=sys.stderr, flush=True)
subprocess.run(args, check=True)
def test_Defaults(self):
"""Tests that the scenario defaults are always valid."""
self._run(self._test_scenarios, "Defaults")
def test_OneOfEverything(self):
"""Tests the OneOfEverything test scenario."""
self._run(self._test_scenarios, "OneOfEverything")
def test_Demo(self):
"""Tests the Demo example."""
self._run(self._example_scenarios, "Demo")
def test_graphviz(self):
out_file = f"{os.environ['TEST_TMPDIR']}/graph.dot"
self.assertFalse(os.path.exists(out_file))
self._run(self._test_scenarios, "Defaults", graphviz=out_file)
with open(out_file, encoding="utf-8") as f:
content = f.read()
self.assertIn("(split)", content)
| 0 |
/home/johnshepherd/drake/examples/hardware_sim | /home/johnshepherd/drake/examples/hardware_sim/test/hardware_sim_cc_test.py | import unittest
from examples.hardware_sim.test.hardware_sim_test_common import HardwareSimTest
class HardwareSimCcTest(HardwareSimTest, unittest.TestCase):
"""Smoke test for our hardware_sim_cc program.
All of the actual test cases are defined in our base class.
"""
def __init__(self, *args, **kwargs):
self._sim_lang = "cc"
super().__init__(*args, **kwargs)
| 0 |
/home/johnshepherd/drake/examples/hardware_sim | /home/johnshepherd/drake/examples/hardware_sim/test/robot_commander_test.py | import unittest
from python.runfiles import Create as CreateRunfiles
from pydrake.common.yaml import yaml_load
import examples.hardware_sim.robot_commander as mut
class RobotCommanderTest(unittest.TestCase):
def setUp(self):
runfiles = CreateRunfiles()
self._example_scenarios = runfiles.Rlocation(
"drake/examples/hardware_sim/example_scenarios.yaml"
)
def test_scenario_parameters(self):
"""Checks the parameters in `robot_commander.py` are consistent with
the ones in `example_scenarios.yaml`.
"""
example_scenarios = yaml_load(filename=self._example_scenarios)
demo = example_scenarios["Demo"]
iiwa_directive = demo["directives"][2]["add_model"]
self.assertEqual(iiwa_directive["name"], "iiwa")
iiwa_q0 = []
for _, qs in iiwa_directive["default_joint_positions"].items():
iiwa_q0.extend(qs)
self.assertListEqual(mut.IIWA_Q0.tolist(), iiwa_q0)
wsg_directive = demo["directives"][5]["add_model"]
self.assertEqual(wsg_directive["name"], "wsg")
wsg_q0 = []
for _, qs in wsg_directive["default_joint_positions"].items():
wsg_q0.extend(qs)
self.assertListEqual([-mut.WSG_Q0, mut.WSG_Q0], wsg_q0)
lcm_url = demo["lcm_buses"]["driver_traffic"]["lcm_url"]
self.assertEqual(mut.LCM_URL, lcm_url)
def test_smoke(self):
"""Runs `robot_commander.main` to check that it doesn't crash. Uses a
nerfed URL to avoid sending network robot commands from a unit test.
"""
old_url = mut.LCM_URL
try:
mut.LCM_URL = "memq://"
mut.main()
finally:
# Set `LCM_URL` back as other test cases depend on it.
mut.LCM_URL = old_url
| 0 |
/home/johnshepherd/drake/examples/hardware_sim | /home/johnshepherd/drake/examples/hardware_sim/test/hardware_sim_py_test.py | import unittest
from examples.hardware_sim.test.hardware_sim_test_common import HardwareSimTest
class HardwareSimPyTest(HardwareSimTest, unittest.TestCase):
"""Smoke test for our hardware_sim_py program.
All of the actual test cases are defined in our base class.
"""
def __init__(self, *args, **kwargs):
self._sim_lang = "py"
super().__init__(*args, **kwargs)
| 0 |
/home/johnshepherd/drake/examples/hardware_sim | /home/johnshepherd/drake/examples/hardware_sim/test/test_scenarios.yaml | # Only ever uses the defaults.
Defaults: {}
# Has at least one example of every kind of top-level option.
# The specific details of the sub-structs are tested elsewhere.
OneOfEverything:
random_seed: 1
simulation_duration: 3.14
simulator_config:
target_realtime_rate: 5.0
plant_config:
stiction_tolerance: 1e-2
scene_graph_config:
default_proximity_properties:
compliance_type: "compliant"
directives:
- add_model:
name: alice
file: package://drake/examples/pendulum/Pendulum.urdf
lcm_buses:
extra_bus: {}
model_drivers:
alice: !ZeroForceDriver {}
cameras:
arbitrary_camera_name:
name: camera_0
lcm_bus: extra_bus
visualization:
lcm_bus: extra_bus
publish_period: 0.125
default_illustration_color:
rgba: [0.8, 0.8, 0.8]
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_binary",
"drake_cc_googletest",
"drake_cc_library",
)
load("//tools/skylark:test_tags.bzl", "vtk_test_tags")
package(default_visibility = ["//visibility:private"])
drake_cc_library(
name = "bouncing_ball_vector",
srcs = ["bouncing_ball_vector.cc"],
hdrs = ["bouncing_ball_vector.h"],
deps = [
"//common:dummy_value",
"//common:essential",
"//common:name_value",
"//common/symbolic:expression",
"//systems/framework:vector",
],
)
drake_cc_library(
name = "bouncing_ball_plant",
srcs = ["bouncing_ball_plant.cc"],
hdrs = ["bouncing_ball_plant.h"],
deps = [
":bouncing_ball_vector",
"//geometry:geometry_ids",
"//geometry:scene_graph",
"//systems/framework:leaf_system",
],
)
drake_cc_binary(
name = "bouncing_ball_run_dynamics",
srcs = ["bouncing_ball_run_dynamics.cc"],
add_test_rule = 1,
test_rule_args = [
"--simulation_time=0.1",
],
test_rule_tags = vtk_test_tags(),
deps = [
":bouncing_ball_plant",
"//geometry:drake_visualizer",
"//geometry:scene_graph",
"//geometry/render_vtk",
"//lcm",
"//systems/analysis:simulator",
"//systems/framework:diagram",
"//systems/lcm:lcm_pubsub_system",
"//systems/primitives:constant_vector_source",
"//systems/sensors:image_to_lcm_image_array_t",
"//systems/sensors:rgbd_sensor",
"@gflags",
],
)
drake_cc_binary(
name = "simple_contact_surface_vis",
srcs = ["simple_contact_surface_vis.cc"],
add_test_rule = 1,
test_rule_args = [
"--simulation_time=0.01",
],
deps = [
"//geometry:drake_visualizer",
"//geometry:scene_graph",
"//lcm",
"//lcmtypes:contact_results_for_viz",
"//systems/analysis:simulator",
"//systems/framework:diagram",
"//systems/lcm:lcm_pubsub_system",
"@gflags",
],
)
filegroup(
name = "models",
srcs = glob([
"**/*.bin",
"**/*.gltf",
"**/*.ktx2",
"**/*.mtl",
"**/*.obj",
"**/*.png",
"**/*.sdf",
"**/*.urdf",
"**/*.xml",
]),
visibility = [
"//:__pkg__",
"//geometry:__pkg__",
"//geometry/render_gl:__pkg__",
"//geometry/render_vtk:__pkg__",
],
)
drake_cc_library(
name = "solar_system",
srcs = ["solar_system.cc"],
hdrs = ["solar_system.h"],
data = [":models"],
deps = [
"//common",
"//geometry:geometry_ids",
"//geometry:geometry_roles",
"//geometry:scene_graph",
"//math:geometric_transform",
"//systems/framework:leaf_system",
],
)
drake_cc_binary(
name = "solar_system_run_dynamics",
srcs = ["solar_system_run_dynamics.cc"],
add_test_rule = 1,
test_rule_args = [
"--simulation_time=0.1",
],
deps = [
":solar_system",
"//geometry:drake_visualizer",
"//geometry:scene_graph",
"//lcm",
"//systems/analysis:simulator",
"//systems/framework:diagram",
"//systems/primitives:constant_vector_source",
"@gflags",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/simple_contact_surface_vis.cc | /** @file
A simple binary for exercising and visualizing computation of ContactSurfaces.
This is decoupled from dynamics so that just the geometric components can be
evaluated in as light-weight a fashion as possible.
This can serve as a test bed for evaluating the various cases of the
ContactSurface-computing algorithms. Simply swap the geometry types (moving
and anchored) and their properties to see the effect on contact surface. */
#include <memory>
#include <unordered_map>
#include <gflags/gflags.h>
#include "drake/common/value.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/geometry/geometry_frame.h"
#include "drake/geometry/geometry_ids.h"
#include "drake/geometry/geometry_instance.h"
#include "drake/geometry/geometry_roles.h"
#include "drake/geometry/kinematics_vector.h"
#include "drake/geometry/proximity_properties.h"
#include "drake/geometry/query_object.h"
#include "drake/geometry/query_results/contact_surface.h"
#include "drake/geometry/scene_graph.h"
#include "drake/geometry/shape_specification.h"
#include "drake/lcm/drake_lcm.h"
#include "drake/lcmt_contact_results_for_viz.hpp"
#include "drake/math/rigid_transform.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/continuous_state.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/lcm/lcm_publisher_system.h"
namespace drake {
namespace examples {
namespace scene_graph {
namespace contact_surface {
using Eigen::Vector3d;
using Eigen::Vector4d;
using geometry::AddRigidHydroelasticProperties;
using geometry::AddCompliantHydroelasticProperties;
using geometry::Box;
using geometry::ContactSurface;
using geometry::Cylinder;
using geometry::DrakeVisualizerd;
using geometry::FrameId;
using geometry::FramePoseVector;
using geometry::GeometryFrame;
using geometry::GeometryId;
using geometry::GeometryInstance;
using geometry::IllustrationProperties;
using geometry::PenetrationAsPointPair;
using geometry::ProximityProperties;
using geometry::QueryObject;
using geometry::Role;
using geometry::SceneGraph;
using geometry::SourceId;
using geometry::Sphere;
using geometry::TriangleSurfaceMesh;
using lcm::DrakeLcm;
using math::RigidTransformd;
using std::make_unique;
using systems::BasicVector;
using systems::Context;
using systems::ContinuousState;
using systems::DiagramBuilder;
using systems::LeafSystem;
using systems::Simulator;
using systems::lcm::LcmPublisherSystem;
DEFINE_double(simulation_time, 10.0,
"Desired duration of the simulation in seconds.");
DEFINE_bool(real_time, true, "Set to false to run as fast as possible");
DEFINE_double(length, 1.0,
"Measure of sphere edge length -- smaller numbers produce a "
"denser, more expensive mesh");
DEFINE_bool(rigid_cylinders, true,
"Set to true, the cylinders are given a rigid "
"hydroelastic representation");
DEFINE_bool(hybrid, false, "Set to true to run hybrid hydroelastic");
DEFINE_bool(polygons, false, "Set to true to get polygonal contact surfaces");
DEFINE_bool(force_full_name, false,
"If true, the message will declare the body names are not unique, "
"forcing the visualizer to use the full model/body names.");
/* To help simulate MultibodyPlant; we're going to assign frames "frame groups"
that correlate with MbP's "model instance indices". We're defining the indices
here and defining the look up table in the function that uses it. */
constexpr int kBallModelInstance = 1;
constexpr int kCylinderModelInstance = 2;
/** Places a ball at the world's origin and defines its velocity as being
sinusoidal in time in the z direction.
@system
name: MovingBall
output_ports:
- geometry_pose
@endsystem
*/
class MovingBall final : public LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MovingBall)
explicit MovingBall(SceneGraph<double>* scene_graph) {
this->DeclareContinuousState(2);
// Add geometry for a ball that moves based on sinusoidal derivatives.
source_id_ = scene_graph->RegisterSource("moving_ball");
frame_id_ = scene_graph->RegisterFrame(
source_id_, GeometryFrame("moving_frame", kBallModelInstance));
geometry_id_ = scene_graph->RegisterGeometry(
source_id_, frame_id_,
make_unique<GeometryInstance>(RigidTransformd(),
make_unique<Sphere>(1.0), "ball"));
ProximityProperties prox_props;
AddCompliantHydroelasticProperties(FLAGS_length, 1e8, &prox_props);
scene_graph->AssignRole(source_id_, geometry_id_, prox_props);
IllustrationProperties illus_props;
illus_props.AddProperty("phong", "diffuse", Vector4d(0.1, 0.8, 0.1, 0.25));
scene_graph->AssignRole(source_id_, geometry_id_, illus_props);
geometry_pose_port_ =
this->DeclareAbstractOutputPort("geometry_pose",
&MovingBall::CalcFramePoseOutput)
.get_index();
}
SourceId source_id() const { return source_id_; }
const systems::OutputPort<double>& get_geometry_pose_output_port() const {
return systems::System<double>::get_output_port(geometry_pose_port_);
}
private:
void DoCalcTimeDerivatives(
const Context<double>& context,
ContinuousState<double>* derivatives) const override {
BasicVector<double>& derivative_values =
dynamic_cast<BasicVector<double>&>(derivatives->get_mutable_vector());
derivative_values.SetAtIndex(0, std::sin(context.get_time()));
}
void CalcFramePoseOutput(const Context<double>& context,
FramePoseVector<double>* poses) const {
RigidTransformd pose;
const double pos_z = context.get_continuous_state().get_vector()[0];
pose.set_translation({0.0, 0.0, pos_z});
*poses = {{frame_id_, pose}};
}
SourceId source_id_;
FrameId frame_id_;
GeometryId geometry_id_;
int geometry_pose_port_{-1};
};
/** A system that evaluates contact surfaces from SceneGraph and outputs a fake
ContactResults with the actual contact surfaces.
@system
name: ContactResultMaker
input_ports:
- query_object
output_ports:
- contact_result
@endsystem
*/
class ContactResultMaker final : public LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ContactResultMaker)
explicit ContactResultMaker(bool use_strict_hydro = true)
: use_strict_hydro_{use_strict_hydro} {
geometry_query_input_port_ =
this->DeclareAbstractInputPort("query_object",
Value<QueryObject<double>>())
.get_index();
contact_result_output_port_ =
this->DeclareAbstractOutputPort("contact_result",
&ContactResultMaker::CalcContactResults)
.get_index();
}
const systems::InputPort<double>& get_geometry_query_port() const {
return systems::System<double>::get_input_port(geometry_query_input_port_);
}
private:
static std::string ModelInstanceName(int frame_group) {
const std::unordered_map<int, std::string> kModelInstanceNames(
{{kBallModelInstance, "MovingBall"},
{kCylinderModelInstance, "FixedCylinders"}});
auto iter = kModelInstanceNames.find(frame_group);
if (iter == kModelInstanceNames.end()) return "DefaultModelInstance";
return iter->second;
}
void CalcContactResults(const Context<double>& context,
lcmt_contact_results_for_viz* results) const {
const auto& query_object =
get_geometry_query_port().Eval<QueryObject<double>>(context);
std::vector<ContactSurface<double>> surfaces;
std::vector<PenetrationAsPointPair<double>> points;
const geometry::HydroelasticContactRepresentation representation =
FLAGS_polygons ? geometry::HydroelasticContactRepresentation::kPolygon
: geometry::HydroelasticContactRepresentation::kTriangle;
if (use_strict_hydro_) {
surfaces = query_object.ComputeContactSurfaces(representation);
} else {
query_object.ComputeContactSurfacesWithFallback(representation, &surfaces,
&points);
}
const int num_surfaces = static_cast<int>(surfaces.size());
const int num_pairs = static_cast<int>(points.size());
auto& message = *results;
message.timestamp = context.get_time() * 1e6; // express in microseconds.
message.num_point_pair_contacts = num_pairs;
message.point_pair_contact_info.resize(num_pairs);
const auto& inspector = query_object.inspector();
// Contact surfaces.
message.num_hydroelastic_contacts = num_surfaces;
message.hydroelastic_contacts.resize(num_surfaces);
for (int i = 0; i < num_surfaces; ++i) {
lcmt_hydroelastic_contact_surface_for_viz& surface_message =
message.hydroelastic_contacts[i];
const auto& surface = surfaces[i];
// We'll simulate MbP's model instance/body paradigm. We have a look up
// function to define a model instance. The body name will be the frame
// name as there is a 1-to-1 correspondence between MbP bodies and
// geometry frames. The geometry will use the name stored in SceneGraph.
const GeometryId id1 = surface.id_M();
const FrameId f_id1 = inspector.GetFrameId(id1);
surface_message.body1_name = inspector.GetName(f_id1);
surface_message.model1_name =
ModelInstanceName(inspector.GetFrameGroup(f_id1));
surface_message.geometry1_name = inspector.GetName(id1);
surface_message.body1_unique = !FLAGS_force_full_name;
surface_message.collision_count1 =
inspector.NumGeometriesForFrameWithRole(inspector.GetFrameId(id1),
Role::kProximity);
const GeometryId id2 = surface.id_N();
const FrameId f_id2 = inspector.GetFrameId(id2);
surface_message.body2_name =
inspector.GetName(inspector.GetFrameId(id2));
surface_message.model2_name =
ModelInstanceName(inspector.GetFrameGroup(f_id2));
surface_message.geometry2_name = inspector.GetName(id2);
surface_message.body2_unique = !FLAGS_force_full_name;
surface_message.collision_count2 =
inspector.NumGeometriesForFrameWithRole(inspector.GetFrameId(id2),
Role::kProximity);
// Fake contact *force* and *moment* data, with some variations across
// different faces to facilitate visualizer testing.
EigenMapView(surface_message.centroid_W) = surface.centroid();
EigenMapView(surface_message.force_C_W) =
Vector3<double>(1.2 * (i + 1), 0, 0);
EigenMapView(surface_message.moment_C_W) =
Vector3<double>(0, 0, 0.5 * (i + 1));
// Write fake quadrature data.
surface_message.num_quadrature_points = surface.num_faces();
surface_message.quadrature_point_data.resize(
surface_message.num_quadrature_points);
for (int j = 0; j < surface_message.num_quadrature_points; ++j) {
lcmt_hydroelastic_quadrature_per_point_data_for_viz&
quad_data_message = surface_message.quadrature_point_data[j];
EigenMapView(quad_data_message.p_WQ) = surface.centroid(j);
EigenMapView(quad_data_message.vt_BqAq_W) =
Vector3d(0, 0.2 + (j * 0.005), 0);
EigenMapView(quad_data_message.traction_Aq_W) =
Vector3d(0, -0.2 - (j * 0.005), 0);
}
// Now write the *real* mesh.
const int num_vertices = surface.num_vertices();
surface_message.num_vertices = num_vertices;
surface_message.p_WV.resize(num_vertices);
surface_message.pressure.resize(num_vertices);
if (surface.is_triangle()) {
const auto& mesh_W = surface.tri_mesh_W();
const auto& e_MN_W = surface.tri_e_MN();
// Write vertices and per vertex pressure values.
for (int v = 0; v < num_vertices; ++v) {
const Vector3d& p_WV = mesh_W.vertex(v);
surface_message.p_WV[v] = {p_WV.x(), p_WV.y(), p_WV.z()};
surface_message.pressure[v] =
ExtractDoubleOrThrow(e_MN_W.EvaluateAtVertex(v));
}
// Write faces.
surface_message.poly_data_int_count = mesh_W.num_triangles() * 4;
surface_message.poly_data.resize(surface_message.poly_data_int_count);
int index = -1;
for (int t = 0; t < mesh_W.num_triangles(); ++t) {
const geometry::SurfaceTriangle& tri = mesh_W.element(t);
surface_message.poly_data[++index] = 3;
surface_message.poly_data[++index] = tri.vertex(0);
surface_message.poly_data[++index] = tri.vertex(1);
surface_message.poly_data[++index] = tri.vertex(2);
}
} else {
const auto& mesh_W = surface.poly_mesh_W();
const auto& e_MN_W = surface.poly_e_MN();
// Write vertices and per vertex pressure values.
for (int v = 0; v < num_vertices; ++v) {
const Vector3d& p_WV = mesh_W.vertex(v);
surface_message.p_WV[v] = {p_WV.x(), p_WV.y(), p_WV.z()};
surface_message.pressure[v] =
ExtractDoubleOrThrow(e_MN_W.EvaluateAtVertex(v));
}
surface_message.poly_data_int_count = mesh_W.face_data().size();
surface_message.poly_data = mesh_W.face_data();
}
}
// Point pairs.
for (int i = 0; i < num_pairs; ++i) {
lcmt_point_pair_contact_info_for_viz& info_message =
message.point_pair_contact_info[i];
info_message.timestamp = message.timestamp;
const PenetrationAsPointPair<double>& pair = points[i];
info_message.body1_name = query_object.inspector().GetName(pair.id_A);
info_message.body1_name = query_object.inspector().GetName(pair.id_B);
// Fake contact *force* data from strictly contact data. Contact point
// is midway between the two contact points and force = normal.
const Vector3d contact_point = (pair.p_WCa + pair.p_WCb) / 2.0;
EigenMapView(info_message.contact_point) = contact_point;
EigenMapView(info_message.contact_force) = pair.nhat_BA_W;
EigenMapView(info_message.normal) = pair.nhat_BA_W;
}
}
int geometry_query_input_port_{-1};
int contact_result_output_port_{-1};
const bool use_strict_hydro_{true};
};
int do_main() {
DiagramBuilder<double> builder;
auto& scene_graph = *builder.AddSystem<SceneGraph<double>>();
// Add the bouncing ball.
auto& moving_ball = *builder.AddSystem<MovingBall>(&scene_graph);
builder.Connect(moving_ball.get_geometry_pose_output_port(),
scene_graph.get_source_pose_port(moving_ball.source_id()));
// Add a large box, such that intersection occurs at the edge.
SourceId source_id = scene_graph.RegisterSource("world");
const double edge_len = 10;
const RigidTransformd X_WB(Eigen::AngleAxisd(M_PI / 4, Vector3d::UnitX()),
Vector3d{0, 0, -sqrt(2.0) * edge_len / 2});
GeometryId ground_id = scene_graph.RegisterAnchoredGeometry(
source_id,
make_unique<GeometryInstance>(
X_WB, make_unique<Box>(edge_len, edge_len, edge_len), "box"));
ProximityProperties rigid_props;
AddRigidHydroelasticProperties(edge_len, &rigid_props);
scene_graph.AssignRole(source_id, ground_id, rigid_props);
IllustrationProperties illustration_box;
illustration_box.AddProperty("phong", "diffuse",
Vector4d{0.5, 0.5, 0.45, 1.0});
scene_graph.AssignRole(source_id, ground_id, illustration_box);
// Add two cylinders to bang into -- if the rigid_cylinders flag is set to
// false, this should crash in strict hydroelastic mode, but report point
// contact in non-strict mode.
// We provide two cylinders affixed to a single frame to more robustly
// exercise the visualization logic; it allows *two* contacts between the
// double-can "body" and the moving ball.
const FrameId can_frame_id = scene_graph.RegisterFrame(
source_id, GeometryFrame("double_can", kCylinderModelInstance));
const RigidTransformd X_WC1(Vector3d{-0.5, 0, 3});
const RigidTransformd X_WC2(Vector3d{0.5, 0, 3});
const GeometryId can1_id = scene_graph.RegisterGeometry(
source_id, can_frame_id, make_unique<GeometryInstance>(
X_WC1, make_unique<Cylinder>(0.5, 1.0), "can1"));
const GeometryId can2_id = scene_graph.RegisterGeometry(
source_id, can_frame_id, make_unique<GeometryInstance>(
X_WC2, make_unique<Cylinder>(0.5, 1.0), "can2"));
ProximityProperties proximity_cylinder;
if (FLAGS_rigid_cylinders) {
AddRigidHydroelasticProperties(0.5, &proximity_cylinder);
}
scene_graph.AssignRole(source_id, can1_id, proximity_cylinder);
scene_graph.AssignRole(source_id, can2_id, proximity_cylinder);
IllustrationProperties illustration_cylinder;
illustration_cylinder.AddProperty("phong", "diffuse",
Vector4d{0.5, 0.5, 0.45, 0.5});
scene_graph.AssignRole(source_id, can1_id, illustration_cylinder);
scene_graph.AssignRole(source_id, can2_id, illustration_cylinder);
// Make and visualize contacts.
auto& contact_results = *builder.AddSystem<ContactResultMaker>(!FLAGS_hybrid);
builder.Connect(scene_graph.get_query_output_port(),
contact_results.get_geometry_query_port());
// Now visualize.
DrakeLcm lcm;
// Visualize geometry.
DrakeVisualizerd::AddToBuilder(&builder, scene_graph, &lcm);
// Visualize contacts.
auto& contact_to_lcm =
*builder.AddSystem(LcmPublisherSystem::Make<lcmt_contact_results_for_viz>(
"CONTACT_RESULTS", &lcm, 1.0 / 64));
builder.Connect(contact_results, contact_to_lcm);
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
systems::Context<double>& diagram_context = simulator.get_mutable_context();
systems::Context<double>& sg_context =
scene_graph.GetMyMutableContextFromRoot(&diagram_context);
scene_graph.get_source_pose_port(source_id).FixValue(
&sg_context,
geometry::FramePoseVector<double>{{can_frame_id, RigidTransformd{}}});
simulator.get_mutable_integrator().set_maximum_step_size(0.002);
simulator.set_target_realtime_rate(FLAGS_real_time ? 1.f : 0.f);
simulator.Initialize();
simulator.AdvanceTo(FLAGS_simulation_time);
return 0;
}
} // namespace contact_surface
} // namespace scene_graph
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::scene_graph::contact_surface::do_main();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/bouncing_ball_vector.cc | #include "drake/examples/scene_graph/bouncing_ball_vector.h"
namespace drake {
namespace examples {
namespace scene_graph {
namespace bouncing_ball {
const int BouncingBallVectorIndices::kNumCoordinates;
const int BouncingBallVectorIndices::kZ;
const int BouncingBallVectorIndices::kZdot;
const std::vector<std::string>&
BouncingBallVectorIndices::GetCoordinateNames() {
static const drake::never_destroyed<std::vector<std::string>> coordinates(
std::vector<std::string>{
"z",
"zdot",
});
return coordinates.access();
}
} // namespace bouncing_ball
} // namespace scene_graph
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/planet_rings.obj | # A set of concentric rings
v 3.221267 -0.038557 -1.046653
v 2.740174 -0.038557 -1.990851
v 1.990851 -0.038557 -2.740173
v 1.046652 -0.038557 -3.221267
v -0.000000 -0.038557 -3.387039
v -1.046652 -0.038557 -3.221267
v -1.990850 -0.038557 -2.740172
v -2.740172 -0.038557 -1.990850
v -3.221266 -0.038557 -1.046652
v -3.387038 -0.038557 -0.000000
v -3.221266 -0.038557 1.046652
v -2.740172 -0.038557 1.990850
v -1.990850 -0.038557 2.740172
v -1.046652 -0.038557 3.221266
v -0.000000 -0.038557 3.387037
v 1.046652 -0.038557 3.221266
v 1.990849 -0.038557 2.740171
v 2.740171 -0.038557 1.990850
v 3.221265 -0.038557 1.046652
v 3.387037 -0.038557 -0.000000
v 3.221267 0.038557 -1.046653
v 2.740174 0.038557 -1.990851
v 1.990851 0.038557 -2.740173
v 1.046652 0.038557 -3.221267
v -0.000000 0.038557 -3.387039
v -1.046652 0.038557 -3.221267
v -1.990850 0.038557 -2.740172
v -2.740172 0.038557 -1.990850
v -3.221266 0.038557 -1.046652
v -3.387038 0.038557 -0.000000
v -3.221266 0.038557 1.046652
v -2.740172 0.038557 1.990850
v -1.990850 0.038557 2.740172
v -1.046652 0.038557 3.221266
v -0.000000 0.038557 3.387037
v 1.046652 0.038557 3.221266
v 1.990849 0.038557 2.740171
v 2.740171 0.038557 1.990850
v 3.221265 0.038557 1.046652
v 3.387037 0.038557 -0.000000
v 2.514818 -0.038557 1.827123
v 2.956347 -0.038557 0.960575
v 1.827124 -0.038557 2.514817
v 0.960575 -0.038557 2.956347
v -0.000000 -0.038557 3.108485
v -0.960576 -0.038557 2.956347
v -1.827124 -0.038557 2.514817
v -2.514818 -0.038557 1.827123
v -2.956348 -0.038557 0.960576
v -3.108486 -0.038557 -0.000000
v -2.956348 -0.038557 -0.960576
v -2.514818 -0.038557 -1.827125
v -1.827124 -0.038557 -2.514820
v -0.960576 -0.038557 -2.956349
v 0.000000 -0.038557 -3.108487
v 0.960576 -0.038557 -2.956349
v 1.827124 -0.038557 -2.514820
v 2.514818 -0.038557 -1.827126
v 2.956349 -0.038557 -0.960576
v 3.108485 -0.038557 -0.000000
v 3.108485 0.038557 -0.000000
v 2.956349 0.038557 -0.960576
v 2.514818 0.038557 -1.827126
v 1.827124 0.038557 -2.514820
v 0.960576 0.038557 -2.956349
v 0.000000 0.038557 -3.108487
v -0.960576 0.038557 -2.956349
v -1.827124 0.038557 -2.514820
v -2.514818 0.038557 -1.827125
v -2.956348 0.038557 -0.960576
v -3.108486 0.038557 -0.000000
v -2.956348 0.038557 0.960576
v -2.514818 0.038557 1.827123
v -1.827124 0.038557 2.514817
v -0.960576 0.038557 2.956347
v -0.000000 0.038557 3.108485
v 0.960575 0.038557 2.956347
v 1.827124 0.038557 2.514817
v 2.514818 0.038557 1.827123
v 2.956347 0.038557 0.960575
v 2.808573 -0.038557 -0.912560
v 2.389116 -0.038557 -1.735793
v 1.735793 -0.038557 -2.389115
v 0.912560 -0.038557 -2.808573
v -0.000000 -0.038557 -2.953108
v -0.912560 -0.038557 -2.808573
v -1.735792 -0.038557 -2.389115
v -2.389114 -0.038557 -1.735792
v -2.808573 -0.038557 -0.912560
v -2.953106 -0.038557 -0.000000
v -2.808573 -0.038557 0.912560
v -2.389114 -0.038557 1.735792
v -1.735792 -0.038557 2.389114
v -0.912560 -0.038557 2.808572
v -0.000000 -0.038557 2.953106
v 0.912560 -0.038557 2.808572
v 1.735791 -0.038557 2.389114
v 2.389113 -0.038557 1.735791
v 2.808572 -0.038557 0.912560
v 2.953105 -0.038557 -0.000000
v 2.808573 0.038557 -0.912560
v 2.389116 0.038557 -1.735793
v 1.735793 0.038557 -2.389115
v 0.912560 0.038557 -2.808573
v -0.000000 0.038557 -2.953108
v -0.912560 0.038557 -2.808573
v -1.735792 0.038557 -2.389115
v -2.389114 0.038557 -1.735792
v -2.808573 0.038557 -0.912560
v -2.953106 0.038557 -0.000000
v -2.808573 0.038557 0.912560
v -2.389114 0.038557 1.735792
v -1.735792 0.038557 2.389114
v -0.912560 0.038557 2.808572
v -0.000000 0.038557 2.953106
v 0.912560 0.038557 2.808572
v 1.735791 0.038557 2.389114
v 2.389113 0.038557 1.735791
v 2.808572 0.038557 0.912560
v 2.953105 0.038557 -0.000000
v 2.192632 -0.038557 1.593041
v 2.577594 -0.038557 0.837511
v 1.593042 -0.038557 2.192631
v 0.837511 -0.038557 2.577594
v -0.000000 -0.038557 2.710241
v -0.837511 -0.038557 2.577594
v -1.593042 -0.038557 2.192631
v -2.192632 -0.038557 1.593041
v -2.577595 -0.038557 0.837511
v -2.710242 -0.038557 -0.000000
v -2.577595 -0.038557 -0.837512
v -2.192632 -0.038557 -1.593042
v -1.593042 -0.038557 -2.192633
v -0.837512 -0.038557 -2.577595
v 0.000000 -0.038557 -2.710243
v 0.837512 -0.038557 -2.577596
v 1.593042 -0.038557 -2.192633
v 2.192632 -0.038557 -1.593043
v 2.577596 -0.038557 -0.837512
v 2.710241 -0.038557 -0.000000
v 2.710241 0.038557 -0.000000
v 2.577596 0.038557 -0.837512
v 2.192632 0.038557 -1.593043
v 1.593042 0.038557 -2.192633
v 0.837512 0.038557 -2.577596
v 0.000000 0.038557 -2.710243
v -0.837512 0.038557 -2.577595
v -1.593042 0.038557 -2.192633
v -2.192632 0.038557 -1.593042
v -2.577595 0.038557 -0.837512
v -2.710242 0.038557 -0.000000
v -2.577595 0.038557 0.837511
v -2.192632 0.038557 1.593041
v -1.593042 0.038557 2.192631
v -0.837511 0.038557 2.577594
v -0.000000 0.038557 2.710241
v 0.837511 0.038557 2.577594
v 1.593042 0.038557 2.192631
v 2.192632 0.038557 1.593041
v 2.577594 0.038557 0.837511
v 2.282537 -0.038557 -0.741641
v 1.941642 -0.038557 -1.410686
v 1.410686 -0.038557 -1.941642
v 0.741641 -0.038557 -2.282537
v 0.000000 -0.038557 -2.400001
v -0.741641 -0.038557 -2.282537
v -1.410685 -0.038557 -1.941642
v -1.941641 -0.038557 -1.410685
v -2.282536 -0.038557 -0.741641
v -2.400001 -0.038557 0.000000
v -2.282536 -0.038557 0.741641
v -1.941641 -0.038557 1.410685
v -1.410685 -0.038557 1.941641
v -0.741641 -0.038557 2.282536
v -0.000000 -0.038557 2.400000
v 0.741641 -0.038557 2.282536
v 1.410685 -0.038557 1.941641
v 1.941641 -0.038557 1.410685
v 2.282536 -0.038557 0.741641
v 2.400000 -0.038557 0.000000
v 2.282537 0.038557 -0.741641
v 1.941642 0.038557 -1.410686
v 1.410686 0.038557 -1.941642
v 0.741641 0.038557 -2.282537
v 0.000000 0.038557 -2.400001
v -0.741641 0.038557 -2.282537
v -1.410685 0.038557 -1.941642
v -1.941641 0.038557 -1.410685
v -2.282536 0.038557 -0.741641
v -2.400001 0.038557 0.000000
v -2.282536 0.038557 0.741641
v -1.941641 0.038557 1.410685
v -1.410685 0.038557 1.941641
v -0.741641 0.038557 2.282536
v -0.000000 0.038557 2.400000
v 0.741641 0.038557 2.282536
v 1.410685 0.038557 1.941641
v 1.941641 0.038557 1.410685
v 2.282536 0.038557 0.741641
v 2.400000 0.038557 0.000000
v 1.308614 -0.038557 0.950764
v 1.538368 -0.038557 0.499846
v 0.950764 -0.038557 1.308613
v 0.499846 -0.038557 1.538368
v -0.000000 -0.038557 1.617535
v -0.499846 -0.038557 1.538368
v -0.950765 -0.038557 1.308613
v -1.308614 -0.038557 0.950764
v -1.538368 -0.038557 0.499846
v -1.617535 -0.038557 -0.000000
v -1.538368 -0.038557 -0.499846
v -1.308614 -0.038557 -0.950765
v -0.950765 -0.038557 -1.308614
v -0.499847 -0.038557 -1.538369
v 0.000000 -0.038557 -1.617536
v 0.499847 -0.038557 -1.538369
v 0.950765 -0.038557 -1.308614
v 1.308614 -0.038557 -0.950765
v 1.538369 -0.038557 -0.499847
v 1.617535 -0.038557 -0.000000
v 1.617535 0.038557 -0.000000
v 1.538369 0.038557 -0.499847
v 1.308614 0.038557 -0.950765
v 0.950765 0.038557 -1.308614
v 0.499847 0.038557 -1.538369
v 0.000000 0.038557 -1.617536
v -0.499847 0.038557 -1.538369
v -0.950765 0.038557 -1.308614
v -1.308614 0.038557 -0.950765
v -1.538368 0.038557 -0.499846
v -1.617535 0.038557 -0.000000
v -1.538368 0.038557 0.499846
v -1.308614 0.038557 0.950764
v -0.950765 0.038557 1.308613
v -0.499846 0.038557 1.538368
v -0.000000 0.038557 1.617535
v 0.499846 0.038557 1.538368
v 0.950764 0.038557 1.308613
v 1.308614 0.038557 0.950764
v 1.538368 0.038557 0.499846
vt 0.648603 0.107966
vt 0.626409 0.064408
vt 0.591842 0.029841
vt 0.548284 0.007647
vt 0.500000 -0.000000
vt 0.451716 0.007647
vt 0.408159 0.029841
vt 0.373591 0.064409
vt 0.351397 0.107966
vt 0.343750 0.156250
vt 0.351397 0.204534
vt 0.373591 0.248091
vt 0.408159 0.282659
vt 0.451716 0.304853
vt 0.500000 0.312500
vt 0.548284 0.304853
vt 0.591841 0.282659
vt 0.626409 0.248091
vt 0.648603 0.204534
vt 0.656250 0.156250
vt 0.375000 0.312500
vt 0.387500 0.312500
vt 0.400000 0.312500
vt 0.412500 0.312500
vt 0.425000 0.312500
vt 0.437500 0.312500
vt 0.450000 0.312500
vt 0.462500 0.312500
vt 0.475000 0.312500
vt 0.487500 0.312500
vt 0.500000 0.312500
vt 0.512500 0.312500
vt 0.525000 0.312500
vt 0.537500 0.312500
vt 0.550000 0.312500
vt 0.562500 0.312500
vt 0.575000 0.312500
vt 0.587500 0.312500
vt 0.600000 0.312500
vt 0.612500 0.312500
vt 0.625000 0.312500
vt 0.375000 0.688440
vt 0.387500 0.688440
vt 0.400000 0.688440
vt 0.412500 0.688440
vt 0.425000 0.688440
vt 0.437500 0.688440
vt 0.450000 0.688440
vt 0.462500 0.688440
vt 0.475000 0.688440
vt 0.487500 0.688440
vt 0.500000 0.688440
vt 0.512500 0.688440
vt 0.525000 0.688440
vt 0.537500 0.688440
vt 0.550000 0.688440
vt 0.562500 0.688440
vt 0.575000 0.688440
vt 0.587500 0.688440
vt 0.600000 0.688440
vt 0.612500 0.688440
vt 0.625000 0.688440
vt 0.648603 0.795466
vt 0.626409 0.751908
vt 0.591842 0.717341
vt 0.548284 0.695147
vt 0.500000 0.687500
vt 0.451716 0.695147
vt 0.408159 0.717341
vt 0.373591 0.751909
vt 0.351397 0.795466
vt 0.343750 0.843750
vt 0.351397 0.892034
vt 0.373591 0.935591
vt 0.408159 0.970159
vt 0.451716 0.992353
vt 0.500000 1.000000
vt 0.548284 0.992353
vt 0.591841 0.970159
vt 0.626409 0.935591
vt 0.648603 0.892034
vt 0.656250 0.843750
vt 0.648603 0.204534
vt 0.626409 0.248091
vt 0.591841 0.282659
vt 0.548284 0.304853
vt 0.500000 0.312500
vt 0.451716 0.304853
vt 0.408159 0.282659
vt 0.373591 0.248091
vt 0.351397 0.204534
vt 0.343750 0.156250
vt 0.351397 0.107966
vt 0.373591 0.064409
vt 0.408159 0.029841
vt 0.451716 0.007647
vt 0.500000 -0.000000
vt 0.548284 0.007647
vt 0.591842 0.029841
vt 0.626409 0.064408
vt 0.648603 0.107966
vt 0.656250 0.156250
vt 0.656250 0.843750
vt 0.648603 0.892034
vt 0.626409 0.935591
vt 0.591841 0.970159
vt 0.548284 0.992353
vt 0.500000 1.000000
vt 0.451716 0.992353
vt 0.408159 0.970159
vt 0.373591 0.935591
vt 0.351397 0.892034
vt 0.343750 0.843750
vt 0.351397 0.795466
vt 0.373591 0.751909
vt 0.408159 0.717341
vt 0.451716 0.695147
vt 0.500000 0.687500
vt 0.548284 0.695147
vt 0.591842 0.717341
vt 0.626409 0.751908
vt 0.648603 0.795466
vt 0.656250 0.843750
vt 0.648603 0.892034
vt 0.626409 0.935591
vt 0.591841 0.970159
vt 0.548284 0.992353
vt 0.500000 1.000000
vt 0.451716 0.992353
vt 0.408159 0.970159
vt 0.373591 0.935591
vt 0.351397 0.892034
vt 0.343750 0.843750
vt 0.351397 0.795466
vt 0.373591 0.751909
vt 0.408159 0.717341
vt 0.451716 0.695147
vt 0.500000 0.687500
vt 0.548284 0.695147
vt 0.591842 0.717341
vt 0.626409 0.751908
vt 0.648603 0.795466
vt 0.375000 0.312500
vt 0.387500 0.312500
vt 0.387500 0.688440
vt 0.375000 0.688440
vt 0.400000 0.312500
vt 0.400000 0.688440
vt 0.412500 0.312500
vt 0.412500 0.688440
vt 0.425000 0.312500
vt 0.425000 0.688440
vt 0.437500 0.312500
vt 0.437500 0.688440
vt 0.450000 0.312500
vt 0.450000 0.688440
vt 0.462500 0.312500
vt 0.462500 0.688440
vt 0.475000 0.312500
vt 0.475000 0.688440
vt 0.487500 0.312500
vt 0.487500 0.688440
vt 0.500000 0.312500
vt 0.500000 0.688440
vt 0.512500 0.312500
vt 0.512500 0.688440
vt 0.525000 0.312500
vt 0.525000 0.688440
vt 0.537500 0.312500
vt 0.537500 0.688440
vt 0.550000 0.312500
vt 0.550000 0.688440
vt 0.562500 0.312500
vt 0.562500 0.688440
vt 0.575000 0.312500
vt 0.575000 0.688440
vt 0.587500 0.312500
vt 0.587500 0.688440
vt 0.600000 0.312500
vt 0.600000 0.688440
vt 0.612500 0.312500
vt 0.612500 0.688440
vt 0.625000 0.312500
vt 0.625000 0.688440
vt 0.648603 0.204534
vt 0.626409 0.248091
vt 0.626409 0.248091
vt 0.648603 0.204534
vt 0.591841 0.282659
vt 0.591841 0.282659
vt 0.548284 0.304853
vt 0.548284 0.304853
vt 0.500000 0.312500
vt 0.500000 0.312500
vt 0.451716 0.304853
vt 0.451716 0.304853
vt 0.408159 0.282659
vt 0.408159 0.282659
vt 0.373591 0.248091
vt 0.373591 0.248091
vt 0.351397 0.204534
vt 0.351397 0.204534
vt 0.343750 0.156250
vt 0.343750 0.156250
vt 0.351397 0.107966
vt 0.351397 0.107966
vt 0.373591 0.064409
vt 0.373591 0.064409
vt 0.408159 0.029841
vt 0.408159 0.029841
vt 0.451716 0.007647
vt 0.451716 0.007647
vt 0.500000 -0.000000
vt 0.500000 -0.000000
vt 0.548284 0.007647
vt 0.548284 0.007647
vt 0.591842 0.029841
vt 0.591842 0.029841
vt 0.626409 0.064408
vt 0.626409 0.064408
vt 0.648603 0.107966
vt 0.648603 0.107966
vt 0.656250 0.156250
vt 0.656250 0.156250
vt 0.656250 0.843750
vt 0.648603 0.892034
vt 0.648603 0.892034
vt 0.656250 0.843750
vt 0.626409 0.935591
vt 0.626409 0.935591
vt 0.591841 0.970159
vt 0.591841 0.970159
vt 0.548284 0.992353
vt 0.548284 0.992353
vt 0.500000 1.000000
vt 0.500000 1.000000
vt 0.451716 0.992353
vt 0.451716 0.992353
vt 0.408159 0.970159
vt 0.408159 0.970159
vt 0.373591 0.935591
vt 0.373591 0.935591
vt 0.351397 0.892034
vt 0.351397 0.892034
vt 0.343750 0.843750
vt 0.343750 0.843750
vt 0.351397 0.795466
vt 0.351397 0.795466
vt 0.373591 0.751909
vt 0.373591 0.751909
vt 0.408159 0.717341
vt 0.408159 0.717341
vt 0.451716 0.695147
vt 0.451716 0.695147
vt 0.500000 0.687500
vt 0.500000 0.687500
vt 0.548284 0.695147
vt 0.548284 0.695147
vt 0.591842 0.717341
vt 0.591842 0.717341
vt 0.626409 0.751908
vt 0.626409 0.751908
vt 0.648603 0.795466
vt 0.648603 0.795466
vt 0.648603 0.892034
vt 0.656250 0.843750
vt 0.626409 0.935591
vt 0.591841 0.970159
vt 0.548284 0.992353
vt 0.500000 1.000000
vt 0.451716 0.992353
vt 0.408159 0.970159
vt 0.373591 0.935591
vt 0.351397 0.892034
vt 0.343750 0.843750
vt 0.351397 0.795466
vt 0.373591 0.751909
vt 0.408159 0.717341
vt 0.451716 0.695147
vt 0.500000 0.687500
vt 0.548284 0.695147
vt 0.591842 0.717341
vt 0.626409 0.751908
vt 0.648603 0.795466
vt 0.375000 0.312500
vt 0.387500 0.312500
vt 0.387500 0.688440
vt 0.375000 0.688440
vt 0.400000 0.312500
vt 0.400000 0.688440
vt 0.412500 0.312500
vt 0.412500 0.688440
vt 0.425000 0.312500
vt 0.425000 0.688440
vt 0.437500 0.312500
vt 0.437500 0.688440
vt 0.450000 0.312500
vt 0.450000 0.688440
vt 0.462500 0.312500
vt 0.462500 0.688440
vt 0.475000 0.312500
vt 0.475000 0.688440
vt 0.487500 0.312500
vt 0.487500 0.688440
vt 0.500000 0.312500
vt 0.500000 0.688440
vt 0.512500 0.312500
vt 0.512500 0.688440
vt 0.525000 0.312500
vt 0.525000 0.688440
vt 0.537500 0.312500
vt 0.537500 0.688440
vt 0.550000 0.312500
vt 0.550000 0.688440
vt 0.562500 0.312500
vt 0.562500 0.688440
vt 0.575000 0.312500
vt 0.575000 0.688440
vt 0.587500 0.312500
vt 0.587500 0.688440
vt 0.600000 0.312500
vt 0.600000 0.688440
vt 0.612500 0.312500
vt 0.612500 0.688440
vt 0.625000 0.312500
vt 0.625000 0.688440
vt 0.648603 0.204534
vt 0.626409 0.248091
vt 0.626409 0.248091
vt 0.648603 0.204534
vt 0.591841 0.282659
vt 0.591841 0.282659
vt 0.548284 0.304853
vt 0.548284 0.304853
vt 0.500000 0.312500
vt 0.500000 0.312500
vt 0.451716 0.304853
vt 0.451716 0.304853
vt 0.408159 0.282659
vt 0.408159 0.282659
vt 0.373591 0.248091
vt 0.373591 0.248091
vt 0.351397 0.204534
vt 0.351397 0.204534
vt 0.343750 0.156250
vt 0.343750 0.156250
vt 0.351397 0.107966
vt 0.351397 0.107966
vt 0.373591 0.064409
vt 0.373591 0.064409
vt 0.408159 0.029841
vt 0.408159 0.029841
vt 0.451716 0.007647
vt 0.451716 0.007647
vt 0.500000 -0.000000
vt 0.500000 -0.000000
vt 0.548284 0.007647
vt 0.548284 0.007647
vt 0.591842 0.029841
vt 0.591842 0.029841
vt 0.626409 0.064408
vt 0.626409 0.064408
vt 0.648603 0.107966
vt 0.648603 0.107966
vt 0.656250 0.156250
vt 0.656250 0.156250
vt 0.656250 0.843750
vt 0.648603 0.892034
vt 0.648603 0.892034
vt 0.656250 0.843750
vt 0.626409 0.935591
vt 0.626409 0.935591
vt 0.591841 0.970159
vt 0.591841 0.970159
vt 0.548284 0.992353
vt 0.548284 0.992353
vt 0.500000 1.000000
vt 0.500000 1.000000
vt 0.451716 0.992353
vt 0.451716 0.992353
vt 0.408159 0.970159
vt 0.408159 0.970159
vt 0.373591 0.935591
vt 0.373591 0.935591
vt 0.351397 0.892034
vt 0.351397 0.892034
vt 0.343750 0.843750
vt 0.343750 0.843750
vt 0.351397 0.795466
vt 0.351397 0.795466
vt 0.373591 0.751909
vt 0.373591 0.751909
vt 0.408159 0.717341
vt 0.408159 0.717341
vt 0.451716 0.695147
vt 0.451716 0.695147
vt 0.500000 0.687500
vt 0.500000 0.687500
vt 0.548284 0.695147
vt 0.548284 0.695147
vt 0.591842 0.717341
vt 0.591842 0.717341
vt 0.626409 0.751908
vt 0.626409 0.751908
vt 0.648603 0.795466
vt 0.648603 0.795466
vt 0.648603 0.892034
vt 0.656250 0.843750
vt 0.626409 0.935591
vt 0.591841 0.970159
vt 0.548284 0.992353
vt 0.500000 1.000000
vt 0.451716 0.992353
vt 0.408159 0.970159
vt 0.373591 0.935591
vt 0.351397 0.892034
vt 0.343750 0.843750
vt 0.351397 0.795466
vt 0.373591 0.751909
vt 0.408159 0.717341
vt 0.451716 0.695147
vt 0.500000 0.687500
vt 0.548284 0.695147
vt 0.591842 0.717341
vt 0.626409 0.751908
vt 0.648603 0.795466
vn 0.951057 0.000000 -0.309015
vn 0.809017 0.000000 -0.587786
vn 0.809017 0.000000 -0.587786
vn 0.951057 0.000000 -0.309015
vn 0.587785 0.000000 -0.809017
vn 0.587785 0.000000 -0.809017
vn 0.309017 0.000000 -0.951057
vn 0.309017 0.000000 -0.951057
vn 0.000000 0.000000 -1.000000
vn 0.000000 0.000000 -1.000000
vn -0.309017 0.000000 -0.951057
vn -0.309017 0.000000 -0.951057
vn -0.587786 0.000000 -0.809017
vn -0.587786 0.000000 -0.809017
vn -0.809017 0.000000 -0.587786
vn -0.809017 0.000000 -0.587786
vn -0.951057 0.000000 -0.309017
vn -0.951057 0.000000 -0.309017
vn -1.000000 0.000000 0.000000
vn -1.000000 0.000000 0.000000
vn -0.951057 0.000000 0.309017
vn -0.951057 0.000000 0.309017
vn -0.809017 0.000000 0.587786
vn -0.809017 0.000000 0.587786
vn -0.587786 0.000000 0.809017
vn -0.587786 0.000000 0.809017
vn -0.309017 0.000000 0.951057
vn -0.309017 0.000000 0.951057
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
vn 0.309017 0.000000 0.951057
vn 0.309017 0.000000 0.951057
vn 0.587786 0.000000 0.809017
vn 0.587786 0.000000 0.809017
vn 0.809017 0.000000 0.587786
vn 0.809017 0.000000 0.587786
vn 0.951057 0.000000 0.309017
vn 0.951057 0.000000 0.309017
vn 1.000000 0.000000 0.000001
vn 1.000000 0.000000 0.000001
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn -1.000000 0.000002 -0.000001
vn -0.951057 0.000000 0.309016
vn -0.951057 0.000000 0.309016
vn -1.000000 0.000002 -0.000001
vn -0.809017 0.000000 0.587786
vn -0.809017 0.000000 0.587786
vn -0.587786 0.000000 0.809017
vn -0.587786 0.000000 0.809017
vn -0.309017 0.000000 0.951057
vn -0.309017 0.000000 0.951057
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
vn 0.309017 0.000000 0.951057
vn 0.309017 0.000000 0.951057
vn 0.587785 0.000000 0.809017
vn 0.587785 0.000000 0.809017
vn 0.809017 0.000000 0.587785
vn 0.809017 0.000000 0.587785
vn 0.951057 -0.000002 0.309016
vn 0.951057 -0.000002 0.309016
vn 1.000000 -0.000000 0.000000
vn 1.000000 -0.000000 -0.000000
vn 0.951057 0.000002 -0.309017
vn 0.951057 0.000002 -0.309017
vn 0.809017 0.000000 -0.587786
vn 0.809017 0.000000 -0.587786
vn 0.587786 0.000000 -0.809017
vn 0.587786 0.000000 -0.809017
vn 0.309017 0.000000 -0.951057
vn 0.309017 0.000000 -0.951057
vn 0.000000 0.000000 -1.000000
vn 0.000000 0.000000 -1.000000
vn -0.309017 0.000000 -0.951057
vn -0.309017 0.000000 -0.951057
vn -0.587785 0.000000 -0.809017
vn -0.587785 0.000000 -0.809017
vn -0.809017 0.000000 -0.587785
vn -0.809017 0.000000 -0.587785
vn -0.951057 0.000002 -0.309016
vn -0.951057 0.000002 -0.309016
vn 0.951057 0.000000 -0.309015
vn 0.809017 0.000000 -0.587786
vn 0.809017 0.000000 -0.587786
vn 0.951057 0.000000 -0.309015
vn 0.587785 0.000000 -0.809017
vn 0.587785 0.000000 -0.809017
vn 0.309016 0.000000 -0.951057
vn 0.309016 0.000000 -0.951057
vn 0.000000 0.000000 -1.000000
vn 0.000000 0.000000 -1.000000
vn -0.309017 0.000000 -0.951057
vn -0.309017 0.000000 -0.951057
vn -0.587786 0.000000 -0.809017
vn -0.587786 0.000000 -0.809017
vn -0.809017 0.000000 -0.587786
vn -0.809017 0.000000 -0.587786
vn -0.951057 0.000000 -0.309017
vn -0.951057 0.000000 -0.309017
vn -1.000000 0.000000 0.000000
vn -1.000000 0.000000 0.000000
vn -0.951057 0.000000 0.309017
vn -0.951057 0.000000 0.309017
vn -0.809017 0.000000 0.587786
vn -0.809017 0.000000 0.587786
vn -0.587786 0.000000 0.809017
vn -0.587786 0.000000 0.809017
vn -0.309017 0.000000 0.951057
vn -0.309017 0.000000 0.951057
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
vn 0.309017 0.000000 0.951057
vn 0.309017 0.000000 0.951057
vn 0.587786 0.000000 0.809017
vn 0.587786 0.000000 0.809017
vn 0.809017 0.000000 0.587786
vn 0.809017 0.000000 0.587786
vn 0.951057 0.000000 0.309017
vn 0.951057 0.000000 0.309017
vn 1.000000 0.000000 0.000001
vn 1.000000 0.000000 0.000001
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn -1.000000 0.000000 -0.000001
vn -0.951057 0.000000 0.309016
vn -0.951057 0.000000 0.309016
vn -1.000000 0.000000 -0.000001
vn -0.809017 0.000000 0.587786
vn -0.809017 0.000000 0.587786
vn -0.587785 0.000000 0.809017
vn -0.587785 0.000000 0.809017
vn -0.309017 0.000000 0.951057
vn -0.309017 0.000000 0.951057
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
vn 0.309017 0.000000 0.951057
vn 0.309017 0.000000 0.951057
vn 0.587785 0.000000 0.809017
vn 0.587785 0.000000 0.809017
vn 0.809017 0.000000 0.587785
vn 0.809017 0.000000 0.587785
vn 0.951057 0.000000 0.309017
vn 0.951057 0.000000 0.309017
vn 1.000000 -0.000000 0.000000
vn 1.000000 -0.000000 0.000000
vn 0.951057 -0.000000 -0.309017
vn 0.951057 -0.000000 -0.309017
vn 0.809017 0.000000 -0.587786
vn 0.809017 0.000000 -0.587786
vn 0.587786 0.000000 -0.809017
vn 0.587786 0.000000 -0.809017
vn 0.309017 0.000000 -0.951057
vn 0.309017 0.000000 -0.951057
vn 0.000000 0.000000 -1.000000
vn 0.000000 0.000000 -1.000000
vn -0.309017 0.000000 -0.951057
vn -0.309017 0.000000 -0.951057
vn -0.587785 0.000000 -0.809017
vn -0.587785 0.000000 -0.809017
vn -0.809017 0.000000 -0.587785
vn -0.809017 0.000000 -0.587785
vn -0.951057 0.000000 -0.309016
vn -0.951057 0.000000 -0.309016
vn 0.951057 0.000000 -0.309016
vn 0.809017 0.000000 -0.587785
vn 0.809017 0.000000 -0.587785
vn 0.951057 0.000000 -0.309016
vn 0.587785 0.000000 -0.809017
vn 0.587785 0.000000 -0.809017
vn 0.309017 0.000000 -0.951057
vn 0.309017 0.000000 -0.951057
vn -0.000000 0.000000 -1.000000
vn -0.000000 0.000000 -1.000000
vn -0.309017 0.000000 -0.951057
vn -0.309017 0.000000 -0.951057
vn -0.587785 0.000000 -0.809017
vn -0.587785 0.000000 -0.809017
vn -0.809017 0.000000 -0.587785
vn -0.809017 0.000000 -0.587785
vn -0.951057 0.000000 -0.309017
vn -0.951057 0.000000 -0.309017
vn -1.000000 0.000000 0.000000
vn -1.000000 0.000000 0.000000
vn -0.951057 0.000000 0.309017
vn -0.951057 0.000000 0.309017
vn -0.809017 0.000000 0.587785
vn -0.809017 0.000000 0.587785
vn -0.587785 0.000000 0.809017
vn -0.587785 0.000000 0.809017
vn -0.309017 0.000000 0.951057
vn -0.309017 0.000000 0.951057
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
vn 0.309017 0.000000 0.951057
vn 0.309017 0.000000 0.951057
vn 0.587785 0.000000 0.809017
vn 0.587785 0.000000 0.809017
vn 0.809017 0.000000 0.587785
vn 0.809017 0.000000 0.587785
vn 0.951057 0.000000 0.309017
vn 0.951057 0.000000 0.309017
vn 1.000000 0.000000 0.000001
vn 1.000000 0.000000 0.000001
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 -0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 -1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 -0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn 0.000000 1.000000 0.000000
vn -1.000000 0.000000 -0.000001
vn -0.951057 0.000000 0.309016
vn -0.951057 0.000000 0.309016
vn -1.000000 0.000000 -0.000001
vn -0.809017 0.000000 0.587786
vn -0.809017 0.000000 0.587786
vn -0.587785 0.000000 0.809017
vn -0.587785 0.000000 0.809017
vn -0.309016 0.000000 0.951057
vn -0.309016 0.000000 0.951057
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
vn 0.309016 0.000000 0.951057
vn 0.309016 0.000000 0.951057
vn 0.587785 0.000000 0.809017
vn 0.587785 0.000000 0.809017
vn 0.809017 0.000000 0.587785
vn 0.809017 0.000000 0.587785
vn 0.951057 0.000000 0.309016
vn 0.951057 0.000000 0.309016
vn 1.000000 -0.000000 0.000000
vn 1.000000 -0.000000 0.000000
vn 0.951057 -0.000000 -0.309017
vn 0.951057 -0.000000 -0.309017
vn 0.809017 0.000000 -0.587786
vn 0.809017 0.000000 -0.587786
vn 0.587786 0.000000 -0.809017
vn 0.587786 0.000000 -0.809017
vn 0.309017 0.000000 -0.951057
vn 0.309017 0.000000 -0.951057
vn 0.000000 0.000000 -1.000000
vn 0.000000 0.000000 -1.000000
vn -0.309017 0.000000 -0.951057
vn -0.309017 0.000000 -0.951057
vn -0.587785 0.000000 -0.809017
vn -0.587785 0.000000 -0.809017
vn -0.809017 0.000000 -0.587785
vn -0.809017 0.000000 -0.587785
vn -0.951057 0.000000 -0.309016
vn -0.951057 0.000000 -0.309016
f 1/21/1 2/22/2 22/43/3 21/42/4
f 2/22/2 3/23/5 23/44/6 22/43/3
f 3/23/5 4/24/7 24/45/8 23/44/6
f 4/24/7 5/25/9 25/46/10 24/45/8
f 5/25/9 6/26/11 26/47/12 25/46/10
f 6/26/11 7/27/13 27/48/14 26/47/12
f 7/27/13 8/28/15 28/49/16 27/48/14
f 8/28/15 9/29/17 29/50/18 28/49/16
f 9/29/17 10/30/19 30/51/20 29/50/18
f 10/30/19 11/31/21 31/52/22 30/51/20
f 11/31/21 12/32/23 32/53/24 31/52/22
f 12/32/23 13/33/25 33/54/26 32/53/24
f 13/33/25 14/34/27 34/55/28 33/54/26
f 14/34/27 15/35/29 35/56/30 34/55/28
f 15/35/29 16/36/31 36/57/32 35/56/30
f 16/36/31 17/37/33 37/58/34 36/57/32
f 17/37/33 18/38/35 38/59/36 37/58/34
f 18/38/35 19/39/37 39/60/38 38/59/36
f 19/39/37 20/40/39 40/61/40 39/60/38
f 20/40/39 1/41/1 21/62/4 40/61/40
f 19/19/41 18/18/42 41/84/43 42/83/44
f 18/18/42 17/17/45 43/85/46 41/84/43
f 17/17/45 16/16/47 44/86/48 43/85/46
f 16/16/47 15/15/49 45/87/50 44/86/48
f 15/15/49 14/14/51 46/88/52 45/87/50
f 14/14/51 13/13/53 47/89/54 46/88/52
f 13/13/53 12/12/55 48/90/56 47/89/54
f 12/12/55 11/11/57 49/91/58 48/90/56
f 11/11/57 10/10/59 50/92/60 49/91/58
f 10/10/59 9/9/61 51/93/62 50/92/60
f 9/9/61 8/8/63 52/94/64 51/93/62
f 8/8/63 7/7/65 53/95/66 52/94/64
f 7/7/65 6/6/67 54/96/68 53/95/66
f 6/6/67 5/5/69 55/97/70 54/96/68
f 5/5/69 4/4/71 56/98/72 55/97/70
f 4/4/71 3/3/73 57/99/74 56/98/72
f 3/3/73 2/2/75 58/100/76 57/99/74
f 2/2/75 1/1/77 59/101/78 58/100/76
f 1/1/77 20/20/79 60/102/80 59/101/78
f 20/20/79 19/19/41 42/83/44 60/102/80
f 40/82/81 21/81/82 62/104/83 61/103/84
f 21/81/82 22/80/85 63/105/86 62/104/83
f 22/80/85 23/79/87 64/106/88 63/105/86
f 23/79/87 24/78/89 65/107/90 64/106/88
f 24/78/89 25/77/91 66/108/92 65/107/90
f 25/77/91 26/76/93 67/109/94 66/108/92
f 26/76/93 27/75/95 68/110/96 67/109/94
f 27/75/95 28/74/97 69/111/98 68/110/96
f 28/74/97 29/73/99 70/112/100 69/111/98
f 29/73/99 30/72/101 71/113/102 70/112/100
f 30/72/101 31/71/103 72/114/104 71/113/102
f 31/71/103 32/70/105 73/115/106 72/114/104
f 32/70/105 33/69/107 74/116/108 73/115/106
f 33/69/107 34/68/109 75/117/110 74/116/108
f 34/68/109 35/67/111 76/118/112 75/117/110
f 35/67/111 36/66/113 77/119/114 76/118/112
f 36/66/113 37/65/115 78/120/116 77/119/114
f 37/65/115 38/64/117 79/121/118 78/120/116
f 38/64/117 39/63/119 80/122/120 79/121/118
f 39/63/119 40/82/81 61/103/84 80/122/120
f 61/103/121 62/104/122 59/124/123 60/123/124
f 62/104/122 63/105/125 58/125/126 59/124/123
f 63/105/125 64/106/127 57/126/128 58/125/126
f 64/106/127 65/107/129 56/127/130 57/126/128
f 65/107/129 66/108/131 55/128/132 56/127/130
f 66/108/131 67/109/133 54/129/134 55/128/132
f 67/109/133 68/110/135 53/130/136 54/129/134
f 68/110/135 69/111/137 52/131/138 53/130/136
f 69/111/137 70/112/139 51/132/140 52/131/138
f 70/112/139 71/113/141 50/133/142 51/132/140
f 71/113/141 72/114/143 49/134/144 50/133/142
f 72/114/143 73/115/145 48/135/146 49/134/144
f 73/115/145 74/116/147 47/136/148 48/135/146
f 74/116/147 75/117/149 46/137/150 47/136/148
f 75/117/149 76/118/151 45/138/152 46/137/150
f 76/118/151 77/119/153 44/139/154 45/138/152
f 77/119/153 78/120/155 43/140/156 44/139/154
f 78/120/155 79/121/157 41/141/158 43/140/156
f 79/121/157 80/122/159 42/142/160 41/141/158
f 80/122/159 61/103/121 60/123/124 42/142/160
f 81/143/161 82/144/162 102/145/163 101/146/164
f 82/144/162 83/147/165 103/148/166 102/145/163
f 83/147/165 84/149/167 104/150/168 103/148/166
f 84/149/167 85/151/169 105/152/170 104/150/168
f 85/151/169 86/153/171 106/154/172 105/152/170
f 86/153/171 87/155/173 107/156/174 106/154/172
f 87/155/173 88/157/175 108/158/176 107/156/174
f 88/157/175 89/159/177 109/160/178 108/158/176
f 89/159/177 90/161/179 110/162/180 109/160/178
f 90/161/179 91/163/181 111/164/182 110/162/180
f 91/163/181 92/165/183 112/166/184 111/164/182
f 92/165/183 93/167/185 113/168/186 112/166/184
f 93/167/185 94/169/187 114/170/188 113/168/186
f 94/169/187 95/171/189 115/172/190 114/170/188
f 95/171/189 96/173/191 116/174/192 115/172/190
f 96/173/191 97/175/193 117/176/194 116/174/192
f 97/175/193 98/177/195 118/178/196 117/176/194
f 98/177/195 99/179/197 119/180/198 118/178/196
f 99/179/197 100/181/199 120/182/200 119/180/198
f 100/181/199 81/183/161 101/184/164 120/182/200
f 99/185/201 98/186/202 121/187/203 122/188/204
f 98/186/202 97/189/205 123/190/206 121/187/203
f 97/189/205 96/191/207 124/192/208 123/190/206
f 96/191/207 95/193/209 125/194/210 124/192/208
f 95/193/209 94/195/211 126/196/212 125/194/210
f 94/195/211 93/197/213 127/198/214 126/196/212
f 93/197/213 92/199/215 128/200/216 127/198/214
f 92/199/215 91/201/217 129/202/218 128/200/216
f 91/201/217 90/203/219 130/204/220 129/202/218
f 90/203/219 89/205/221 131/206/222 130/204/220
f 89/205/221 88/207/223 132/208/224 131/206/222
f 88/207/223 87/209/225 133/210/226 132/208/224
f 87/209/225 86/211/227 134/212/228 133/210/226
f 86/211/227 85/213/229 135/214/230 134/212/228
f 85/213/229 84/215/231 136/216/232 135/214/230
f 84/215/231 83/217/233 137/218/234 136/216/232
f 83/217/233 82/219/235 138/220/236 137/218/234
f 82/219/235 81/221/237 139/222/238 138/220/236
f 81/221/237 100/223/239 140/224/240 139/222/238
f 100/223/239 99/185/201 122/188/204 140/224/240
f 120/225/241 101/226/242 142/227/243 141/228/244
f 101/226/242 102/229/245 143/230/246 142/227/243
f 102/229/245 103/231/247 144/232/248 143/230/246
f 103/231/247 104/233/249 145/234/250 144/232/248
f 104/233/249 105/235/251 146/236/252 145/234/250
f 105/235/251 106/237/253 147/238/254 146/236/252
f 106/237/253 107/239/255 148/240/256 147/238/254
f 107/239/255 108/241/257 149/242/258 148/240/256
f 108/241/257 109/243/259 150/244/260 149/242/258
f 109/243/259 110/245/261 151/246/262 150/244/260
f 110/245/261 111/247/263 152/248/264 151/246/262
f 111/247/263 112/249/265 153/250/266 152/248/264
f 112/249/265 113/251/267 154/252/268 153/250/266
f 113/251/267 114/253/269 155/254/270 154/252/268
f 114/253/269 115/255/271 156/256/272 155/254/270
f 115/255/271 116/257/273 157/258/274 156/256/272
f 116/257/273 117/259/275 158/260/276 157/258/274
f 117/259/275 118/261/277 159/262/278 158/260/276
f 118/261/277 119/263/279 160/264/280 159/262/278
f 119/263/279 120/225/241 141/228/244 160/264/280
f 141/228/281 142/227/282 139/265/283 140/266/284
f 142/227/282 143/230/285 138/267/286 139/265/283
f 143/230/285 144/232/287 137/268/288 138/267/286
f 144/232/287 145/234/289 136/269/290 137/268/288
f 145/234/289 146/236/291 135/270/292 136/269/290
f 146/236/291 147/238/293 134/271/294 135/270/292
f 147/238/293 148/240/295 133/272/296 134/271/294
f 148/240/295 149/242/297 132/273/298 133/272/296
f 149/242/297 150/244/299 131/274/300 132/273/298
f 150/244/299 151/246/301 130/275/302 131/274/300
f 151/246/301 152/248/303 129/276/304 130/275/302
f 152/248/303 153/250/305 128/277/306 129/276/304
f 153/250/305 154/252/307 127/278/308 128/277/306
f 154/252/307 155/254/309 126/279/310 127/278/308
f 155/254/309 156/256/311 125/280/312 126/279/310
f 156/256/311 157/258/313 124/281/314 125/280/312
f 157/258/313 158/260/315 123/282/316 124/281/314
f 158/260/315 159/262/317 121/283/318 123/282/316
f 159/262/317 160/264/319 122/284/320 121/283/318
f 160/264/319 141/228/281 140/266/284 122/284/320
f 161/285/321 162/286/322 182/287/323 181/288/324
f 162/286/322 163/289/325 183/290/326 182/287/323
f 163/289/325 164/291/327 184/292/328 183/290/326
f 164/291/327 165/293/329 185/294/330 184/292/328
f 165/293/329 166/295/331 186/296/332 185/294/330
f 166/295/331 167/297/333 187/298/334 186/296/332
f 167/297/333 168/299/335 188/300/336 187/298/334
f 168/299/335 169/301/337 189/302/338 188/300/336
f 169/301/337 170/303/339 190/304/340 189/302/338
f 170/303/339 171/305/341 191/306/342 190/304/340
f 171/305/341 172/307/343 192/308/344 191/306/342
f 172/307/343 173/309/345 193/310/346 192/308/344
f 173/309/345 174/311/347 194/312/348 193/310/346
f 174/311/347 175/313/349 195/314/350 194/312/348
f 175/313/349 176/315/351 196/316/352 195/314/350
f 176/315/351 177/317/353 197/318/354 196/316/352
f 177/317/353 178/319/355 198/320/356 197/318/354
f 178/319/355 179/321/357 199/322/358 198/320/356
f 179/321/357 180/323/359 200/324/360 199/322/358
f 180/323/359 161/325/321 181/326/324 200/324/360
f 179/327/361 178/328/362 201/329/363 202/330/364
f 178/328/362 177/331/365 203/332/366 201/329/363
f 177/331/365 176/333/367 204/334/368 203/332/366
f 176/333/367 175/335/369 205/336/370 204/334/368
f 175/335/369 174/337/371 206/338/372 205/336/370
f 174/337/371 173/339/373 207/340/374 206/338/372
f 173/339/373 172/341/375 208/342/376 207/340/374
f 172/341/375 171/343/377 209/344/378 208/342/376
f 171/343/377 170/345/379 210/346/380 209/344/378
f 170/345/379 169/347/381 211/348/382 210/346/380
f 169/347/381 168/349/383 212/350/384 211/348/382
f 168/349/383 167/351/385 213/352/386 212/350/384
f 167/351/385 166/353/387 214/354/388 213/352/386
f 166/353/387 165/355/389 215/356/390 214/354/388
f 165/355/389 164/357/391 216/358/392 215/356/390
f 164/357/391 163/359/393 217/360/394 216/358/392
f 163/359/393 162/361/395 218/362/396 217/360/394
f 162/361/395 161/363/397 219/364/398 218/362/396
f 161/363/397 180/365/399 220/366/400 219/364/398
f 180/365/399 179/327/361 202/330/364 220/366/400
f 200/367/401 181/368/402 222/369/403 221/370/404
f 181/368/402 182/371/405 223/372/406 222/369/403
f 182/371/405 183/373/407 224/374/408 223/372/406
f 183/373/407 184/375/409 225/376/410 224/374/408
f 184/375/409 185/377/411 226/378/412 225/376/410
f 185/377/411 186/379/413 227/380/414 226/378/412
f 186/379/413 187/381/415 228/382/416 227/380/414
f 187/381/415 188/383/417 229/384/418 228/382/416
f 188/383/417 189/385/419 230/386/420 229/384/418
f 189/385/419 190/387/421 231/388/422 230/386/420
f 190/387/421 191/389/423 232/390/424 231/388/422
f 191/389/423 192/391/425 233/392/426 232/390/424
f 192/391/425 193/393/427 234/394/428 233/392/426
f 193/393/427 194/395/429 235/396/430 234/394/428
f 194/395/429 195/397/431 236/398/432 235/396/430
f 195/397/431 196/399/433 237/400/434 236/398/432
f 196/399/433 197/401/435 238/402/436 237/400/434
f 197/401/435 198/403/437 239/404/438 238/402/436
f 198/403/437 199/405/439 240/406/440 239/404/438
f 199/405/439 200/367/401 221/370/404 240/406/440
f 221/370/441 222/369/442 219/407/443 220/408/444
f 222/369/442 223/372/445 218/409/446 219/407/443
f 223/372/445 224/374/447 217/410/448 218/409/446
f 224/374/447 225/376/449 216/411/450 217/410/448
f 225/376/449 226/378/451 215/412/452 216/411/450
f 226/378/451 227/380/453 214/413/454 215/412/452
f 227/380/453 228/382/455 213/414/456 214/413/454
f 228/382/455 229/384/457 212/415/458 213/414/456
f 229/384/457 230/386/459 211/416/460 212/415/458
f 230/386/459 231/388/461 210/417/462 211/416/460
f 231/388/461 232/390/463 209/418/464 210/417/462
f 232/390/463 233/392/465 208/419/466 209/418/464
f 233/392/465 234/394/467 207/420/468 208/419/466
f 234/394/467 235/396/469 206/421/470 207/420/468
f 235/396/469 236/398/471 205/422/472 206/421/470
f 236/398/471 237/400/473 204/423/474 205/422/472
f 237/400/473 238/402/475 203/424/476 204/423/474
f 238/402/475 239/404/477 201/425/478 203/424/476
f 239/404/477 240/406/479 202/426/480 201/425/478
f 240/406/479 221/370/441 220/408/444 202/426/480
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/cuboctahedron_with_hole.mtl | # Blender 4.0.2 MTL File: 'None'
# www.blender.org
newmtl checkered_mat
Ns 250.000000
Ka 1.000000 1.000000 1.000000
Ks 0.500000 0.500000 0.500000
Ke 0.000000 0.000000 0.000000
Ni 1.450000
d 1.000000
illum 2
map_Kd rainbow_checker.png
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/bouncing_ball_vector.h | #pragma once
// This file was previously auto-generated, but now is just a normal source
// file in git. However, it still retains some historical oddities from its
// heritage. In general, we do recommend against subclassing BasicVector in
// new code.
#include <cmath>
#include <limits>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <Eigen/Core>
#include "drake/common/drake_bool.h"
#include "drake/common/dummy_value.h"
#include "drake/common/name_value.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/symbolic/expression.h"
#include "drake/systems/framework/basic_vector.h"
namespace drake {
namespace examples {
namespace scene_graph {
namespace bouncing_ball {
/// Describes the row indices of a BouncingBallVector.
struct BouncingBallVectorIndices {
/// The total number of rows (coordinates).
static const int kNumCoordinates = 2;
// The index of each individual coordinate.
static const int kZ = 0;
static const int kZdot = 1;
/// Returns a vector containing the names of each coordinate within this
/// class. The indices within the returned vector matches that of this class.
/// In other words, `BouncingBallVectorIndices::GetCoordinateNames()[i]`
/// is the name for `BasicVector::GetAtIndex(i)`.
static const std::vector<std::string>& GetCoordinateNames();
};
/// Specializes BasicVector with specific getters and setters.
template <typename T>
class BouncingBallVector final : public drake::systems::BasicVector<T> {
public:
/// An abbreviation for our row index constants.
typedef BouncingBallVectorIndices K;
/// Default constructor. Sets all rows to their default value:
/// @arg @c z defaults to 0.0 with unknown units.
/// @arg @c zdot defaults to 0.0 with unknown units.
BouncingBallVector() : drake::systems::BasicVector<T>(K::kNumCoordinates) {
this->set_z(0.0);
this->set_zdot(0.0);
}
// Note: It's safe to implement copy and move because this class is final.
/// @name Implements CopyConstructible, CopyAssignable, MoveConstructible,
/// MoveAssignable
//@{
BouncingBallVector(const BouncingBallVector& other)
: drake::systems::BasicVector<T>(other.values()) {}
BouncingBallVector(BouncingBallVector&& other) noexcept
: drake::systems::BasicVector<T>(std::move(other.values())) {}
BouncingBallVector& operator=(const BouncingBallVector& other) {
this->values() = other.values();
return *this;
}
BouncingBallVector& operator=(BouncingBallVector&& other) noexcept {
this->values() = std::move(other.values());
other.values().resize(0);
return *this;
}
//@}
/// Create a symbolic::Variable for each element with the known variable
/// name. This is only available for T == symbolic::Expression.
template <typename U = T>
typename std::enable_if_t<std::is_same_v<U, symbolic::Expression>>
SetToNamedVariables() {
this->set_z(symbolic::Variable("z"));
this->set_zdot(symbolic::Variable("zdot"));
}
[[nodiscard]] BouncingBallVector<T>* DoClone() const final {
return new BouncingBallVector;
}
/// @name Getters and Setters
//@{
/// z
const T& z() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kZ);
}
/// Setter that matches z().
void set_z(const T& z) {
ThrowIfEmpty();
this->SetAtIndex(K::kZ, z);
}
/// Fluent setter that matches z().
/// Returns a copy of `this` with z set to a new value.
[[nodiscard]] BouncingBallVector<T> with_z(const T& z) const {
BouncingBallVector<T> result(*this);
result.set_z(z);
return result;
}
/// zdot
const T& zdot() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kZdot);
}
/// Setter that matches zdot().
void set_zdot(const T& zdot) {
ThrowIfEmpty();
this->SetAtIndex(K::kZdot, zdot);
}
/// Fluent setter that matches zdot().
/// Returns a copy of `this` with zdot set to a new value.
[[nodiscard]] BouncingBallVector<T> with_zdot(const T& zdot) const {
BouncingBallVector<T> result(*this);
result.set_zdot(zdot);
return result;
}
//@}
/// Visit each field of this named vector, passing them (in order) to the
/// given Archive. The archive can read and/or write to the vector values.
/// One common use of Serialize is the //common/yaml tools.
template <typename Archive>
void Serialize(Archive* a) {
T& z_ref = this->GetAtIndex(K::kZ);
a->Visit(drake::MakeNameValue("z", &z_ref));
T& zdot_ref = this->GetAtIndex(K::kZdot);
a->Visit(drake::MakeNameValue("zdot", &zdot_ref));
}
/// See BouncingBallVectorIndices::GetCoordinateNames().
static const std::vector<std::string>& GetCoordinateNames() {
return BouncingBallVectorIndices::GetCoordinateNames();
}
/// Returns whether the current values of this vector are well-formed.
drake::boolean<T> IsValid() const {
using std::isnan;
drake::boolean<T> result{true};
result = result && !isnan(z());
result = result && !isnan(zdot());
return result;
}
private:
void ThrowIfEmpty() const {
if (this->values().size() == 0) {
throw std::out_of_range(
"The BouncingBallVector vector has been moved-from; "
"accessor methods may no longer be used");
}
}
};
} // namespace bouncing_ball
} // namespace scene_graph
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/sun.sdf | <?xml version="1.0"?>
<sdf xmlns:drake="http://drake.mit.edu" version="1.8">
<!-- Test to load a single body with a .glTF used as visual. -->
<model name="sun_model">
<!-- Add box primitives. -->
<link name="sun">
<pose>0 0 0 0 0 0</pose>
<visual name="visual">
<geometry>
<mesh>
<uri>package://drake/examples/scene_graph/sun.gltf</uri>
<scale>1.0 1.0 1.0</scale>
</mesh>
</geometry>
</visual>
</link>
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/solar_system_run_dynamics.cc | #include <gflags/gflags.h>
#include "drake/examples/scene_graph/solar_system.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/geometry/scene_graph.h"
#include "drake/lcm/drake_lcm.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram_builder.h"
DEFINE_double(simulation_time, 13.0,
"Desired duration of the simulation in seconds.");
namespace drake {
namespace examples {
namespace solar_system {
namespace {
using geometry::SceneGraph;
using geometry::SourceId;
using lcm::DrakeLcm;
int do_main() {
systems::DiagramBuilder<double> builder;
auto scene_graph = builder.AddSystem<SceneGraph<double>>();
scene_graph->set_name("scene_graph");
auto solar_system = builder.AddSystem<SolarSystem>(scene_graph);
solar_system->set_name("SolarSystem");
builder.Connect(solar_system->get_geometry_pose_output_port(),
scene_graph->get_source_pose_port(solar_system->source_id()));
geometry::DrakeVisualizerd::AddToBuilder(&builder, *scene_graph);
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
simulator.get_mutable_integrator().set_maximum_step_size(0.002);
simulator.set_publish_every_time_step(false);
simulator.set_target_realtime_rate(1);
simulator.Initialize();
simulator.AdvanceTo(FLAGS_simulation_time);
return 0;
}
} // namespace
} // namespace solar_system
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::solar_system::do_main();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/solar_system.h | #pragma once
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/geometry/scene_graph.h"
#include "drake/math/rigid_transform.h"
#include "drake/systems/framework/basic_vector.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace solar_system {
// TODO(SeanCurtis-TRI): When textures are available, modify this so that planet
// rotations become apparent as well (and not just revolutions).
/** A model of an orrery -- a simple mechanical model of the solar system.
The orrery contains one sun and multiple orbiting bodies: two planets (Earth
and Mars) each with one moon and multiple satellites for Earth. The idea is
to represent each type of visual geometry in some form. The orrery is
articulated by placing the _frame_ for each body at its parent's origin, and
then displacing the geometry from that origin to its orbital distance. Then
each orbiting frame has a single degree of freedom: its angular position
around its axis of rotation.
- The sun is stationary -- an anchored geometry.
- Earth orbits on the xy-plane. Its moon (Luna) revolves around the earth on
a different arbitrary plane (illustrating transform compositions).
- Three satellites (Convex, Box, and Capsule) revolve around Earth in the same
way as Luna but at different relative angular positions around their axis of
rotation.
- Mars orbits the sun at a farther distance on a plane that is tilted off of
the xy-plane. Its moon (Phobos) orbits around Mars on a plane parallel to
Mars's orbital plane, but in the opposite direction.
- Mars has been given an arbitrary set of rings posed askew. The rings are
declared as a child of mars's geometry.
This system illustrates the following features:
1. Registering anchored geometry.
2. Registering frames as children of other frames.
3. Allocating and calculating the FramePoseVector output for visualization.
4. Exercise all supported SceneGraph geometries in an illustration context.
Illustration of the orrery:
Legend:
Frames | Meaning
:-----------:|:--------------------
S | The sun's frame
E - ◯ | Earth's frame
M - ◍ | Mars's frame
L - ◑ | Luna's (Earth's moon) frame
P - ● | Phobos's (Mars's moon) frame
Oᵢ | Body's orbit in a circular path¹
¹ `i ∈ {e, m, l, p}` for Earth, Mars, Luna, and Phobos, respectively.
Pose Symbol | Meaning
:-----------:|:--------------------
`X_SOₑ` | Earth's orbit Oₑ relative to S
`X_OₑE` | Earth's frame E relative to its orbit Oₑ
`X_OₑOₗ` | Luna's orbit Oₗ relative to Earth's Oₑ
`X_OₗL` | Luna's geometry L relative to its orbit Oₗ
`X_SOₘ` | Mars's orbit Oₘ relative to S
`X_OₘM` | Mars's frame M relative to its orbit Oₘ
`X_OₘOₚ` | Phobos's orbit Oₚ relative to Mars's orbit Oₘ
`X_OₚP` | Phobos's frame P relative to its orbit Oₚ
`X_MR` | Mars's rings R relative to Mars's frame M (not shown in diagram)
```
X_OₑE X_OₗL X_OₘM X_OₚP
↓ ↓ ↓ ↓
E L ▁▁▁ M P
◯ ◑ ╱ ╲ ◍ ●
X_OₑOₗ→├───┘ │ S │ X_OₘOₚ → ├───┘
│ ╲▁▁▁╱ │
│ │ │
└──────────────┤ ← X_SOₑ │
└─────────────────────┘
↑
X_SOₘ
```
The frame of orbit's origin lies at the circle's center and it's z-axis is
perpendicular to the plane of the circle.
@system
name: SolarSystem
output_ports:
- y0
@endsystem
Port `y0` emits geometry poses.
@tparam_double_only
*/
template <typename T>
class SolarSystem : public systems::LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SolarSystem)
explicit SolarSystem(geometry::SceneGraph<T>* scene_graph);
~SolarSystem() override = default;
using MyContext = systems::Context<T>;
using MyContinuousState = systems::ContinuousState<T>;
geometry::SourceId source_id() const { return source_id_; }
const systems::OutputPort<T>& get_geometry_pose_output_port() const;
// The default leaf system zeros out all of the state as "default" behavior.
// This subverts that (as a quick test) to make sure that's the source of my
// problems. The long term solution is to make sure SetDefaultState uses the
// model values if they exist (and zeros otherwise).
// TODO(SeanCurtis-TRI): Kill this override when LeafSystem::SetDefaultState()
// pulls from the models instead of simply zeroing things out.
void SetDefaultState(const systems::Context<T>&,
systems::State<T>*) const override;
private:
// Allocate all of the geometry.
void AllocateGeometry(geometry::SceneGraph<T>* scene_graph);
// Calculate the frame pose set output port value.
void CalcFramePoseOutput(const MyContext& context,
geometry::FramePoseVector<T>* poses) const;
void DoCalcTimeDerivatives(const MyContext& context,
MyContinuousState* derivatives) const override;
static const systems::BasicVector<T>& get_state(
const MyContinuousState& cstate) {
return dynamic_cast<const systems::BasicVector<T>&>(cstate.get_vector());
}
static systems::BasicVector<T>& get_mutable_state(MyContinuousState* cstate) {
return dynamic_cast<systems::BasicVector<T>&>(cstate->get_mutable_vector());
}
static const systems::BasicVector<T>& get_state(const MyContext& context) {
return get_state(context.get_continuous_state());
}
// Geometry source identifier for this system to interact with geometry system
geometry::SourceId source_id_{};
// Port handles
int geometry_pose_port_{-1};
// Solar system specification
const int kBodyCount = 7;
// The ids for each celestial body frame
std::vector<geometry::FrameId> body_ids_;
// The axes around each body revolves (expressed in its parent's frame)
std::vector<Vector3<double>> axes_;
// The translational offset of each body from its parent frame
std::vector<math::RigidTransformd> body_offset_;
};
} // namespace solar_system
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/bouncing_ball_plant.h | #pragma once
#include <memory>
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/examples/scene_graph/bouncing_ball_vector.h"
#include "drake/geometry/geometry_ids.h"
#include "drake/geometry/query_object.h"
#include "drake/geometry/scene_graph.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace scene_graph {
namespace bouncing_ball {
/** A model of a bouncing ball with Hunt-Crossley compliant contact model.
The model supports 1D motion in a 3D world.
@system
name: BouncingBallPlant
input_ports:
- u0
output_ports:
- y0
- y1
@endsystem
Port `u0` accepts a geometry::QueryObject. Ports `y0`, and `y1` emit state and
geometry pose, respectively.
@tparam_double_only
*/
template <typename T>
class BouncingBallPlant : public systems::LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(BouncingBallPlant)
/** Constructor
@param source_id The source id for this plant to interact with
GeoemtrySystem.
@param scene_graph Pointer to the geometry system instance on which
this plant's geometry will be registered. It
must be the same system the source id was
extracted from.
@param p_WB The 2D, projected position vector of the ball
onto the ground plane relative to the world.
*/
BouncingBallPlant(geometry::SourceId source_id,
geometry::SceneGraph<T>* scene_graph,
const Vector2<double>& p_WB);
~BouncingBallPlant() override;
const systems::InputPort<T>& get_geometry_query_input_port() const;
/** Returns the port to output state. */
const systems::OutputPort<T>& get_state_output_port() const;
const systems::OutputPort<T>& get_geometry_pose_output_port() const;
void set_z(systems::Context<T>* context, const T& z) const {
get_mutable_state(context).set_z(z);
}
void set_zdot(systems::Context<T>* context, const T& zdot) const {
get_mutable_state(context).set_zdot(zdot);
}
/** Mass in kg. */
double m() const { return m_; }
/** Stiffness constant in N/m */
double k() const { return k_; }
/** Hunt-Crossley's dissipation factor in s/m. */
double d() const { return d_; }
/** Gravity in m/s^2. */
double g() const { return g_; }
private:
// Calculate the frame pose set output port value.
void CalcFramePoseOutput(const systems::Context<T>& context,
geometry::FramePoseVector<T>* poses) const;
void DoCalcTimeDerivatives(
const systems::Context<T>& context,
systems::ContinuousState<T>* derivatives) const override;
static const BouncingBallVector<T>& get_state(
const systems::ContinuousState<T>& cstate) {
return dynamic_cast<const BouncingBallVector<T>&>(cstate.get_vector());
}
static BouncingBallVector<T>& get_mutable_state(
systems::ContinuousState<T>* cstate) {
return dynamic_cast<BouncingBallVector<T>&>(cstate->get_mutable_vector());
}
BouncingBallVector<T>* get_mutable_state_output(
systems::SystemOutput<T>* output) const {
return dynamic_cast<BouncingBallVector<T>*>(
output->GetMutableVectorData(state_port_));
}
static const BouncingBallVector<T>& get_state(
const systems::Context<T>& context) {
return get_state(context.get_continuous_state());
}
static BouncingBallVector<T>& get_mutable_state(
systems::Context<T>* context) {
return get_mutable_state(&context->get_mutable_continuous_state());
}
// The projected position of the ball onto the ground plane. I.e., it's
// "where the ball bounces".
const Vector2<double> p_WB_;
// The id for the ball's frame.
geometry::FrameId ball_frame_id_;
// The id for the ball's geometry.
geometry::GeometryId ball_id_;
int geometry_pose_port_{-1};
int state_port_{-1};
int geometry_query_port_{-1};
const double diameter_{0.1}; // Ball diameter, just for visualization (m).
const double m_{0.1}; // kg
const double g_{9.81}; // m/s^2
// Stiffness constant [N/m]. Calculated so that under its own weight the ball
// penetrates the plane by 1 mm when the contact force and gravitational
// force are in equilibrium.
const double k_{m_ * g_ / 0.001};
// Hunt-Crossley's dissipation factor.
const double d_{0.0}; // s/m
};
} // namespace bouncing_ball
} // namespace scene_graph
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/solar_system.cc | #include "drake/examples/scene_graph/solar_system.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "drake/common/find_resource.h"
#include "drake/geometry/geometry_frame.h"
#include "drake/geometry/geometry_instance.h"
#include "drake/geometry/geometry_roles.h"
#include "drake/geometry/kinematics_vector.h"
#include "drake/systems/framework/continuous_state.h"
#include "drake/systems/framework/discrete_values.h"
namespace drake {
namespace examples {
namespace solar_system {
using Eigen::AngleAxisd;
using Eigen::Translation3d;
using Eigen::Vector3d;
using Eigen::Vector4d;
using geometry::Box;
using geometry::Capsule;
using geometry::Convex;
using geometry::Cylinder;
using geometry::FrameId;
using geometry::FramePoseVector;
using geometry::GeometryFrame;
using geometry::GeometryId;
using geometry::GeometryInstance;
using geometry::IllustrationProperties;
using geometry::SceneGraph;
using geometry::Mesh;
using geometry::SourceId;
using geometry::Sphere;
using math::RigidTransformd;
using systems::BasicVector;
using systems::Context;
using systems::ContinuousState;
using systems::DiscreteValues;
using std::make_unique;
using std::unique_ptr;
template <typename Shape, typename... ShapeArgs>
unique_ptr<GeometryInstance> MakeShape(const RigidTransformd& pose,
const std::string& name,
const std::optional<Vector4d>& diffuse,
ShapeArgs&&... args) {
auto instance = make_unique<GeometryInstance>(
pose, make_unique<Shape>(std::forward<ShapeArgs>(args)...), name);
IllustrationProperties properties;
if (diffuse.has_value()) {
properties.AddProperty("phong", "diffuse", *diffuse);
}
instance->set_illustration_properties(properties);
return instance;
}
template <typename T>
SolarSystem<T>::SolarSystem(SceneGraph<T>* scene_graph) {
DRAKE_DEMAND(scene_graph != nullptr);
source_id_ = scene_graph->RegisterSource("solar_system");
this->DeclareContinuousState(kBodyCount /* num_q */, kBodyCount /* num_v */,
0 /* num_z */);
AllocateGeometry(scene_graph);
// Now that frames have been registered, allocate the output port.
geometry_pose_port_ =
this->DeclareAbstractOutputPort(systems::kUseDefaultName,
&SolarSystem::CalcFramePoseOutput,
{this->configuration_ticket()})
.get_index();
}
template <typename T>
const systems::OutputPort<T>& SolarSystem<T>::get_geometry_pose_output_port()
const {
return systems::System<T>::get_output_port(geometry_pose_port_);
}
template <typename T>
void SolarSystem<T>::SetDefaultState(const systems::Context<T>&,
systems::State<T>* state) const {
DRAKE_DEMAND(state != nullptr);
ContinuousState<T>& xc = state->get_mutable_continuous_state();
VectorX<T> initial_state;
initial_state.resize(kBodyCount * 2);
// clang-format off
initial_state << 0, // Earth initial position
M_PI / 2, // moon initial position
7 * M_PI / 6, // convexsat initial position
11 * M_PI / 6, // boxsat initial position
M_PI / 6, // capsulesat initial position
M_PI / 2, // Mars initial position
0, // phobos initial position
2 * M_PI / 5, // Earth revolution lasts 5 seconds.
2 * M_PI, // moon revolution lasts 1 second.
2 * M_PI, // convexsat revolution lasts 1 second.
2 * M_PI, // boxsat revolution lasts 1 second.
2 * M_PI, // capsulesat revolution lasts 1 second.
2 * M_PI / 6, // Mars revolution lasts 6 seconds.
2 * M_PI / 1.1; // phobos revolution lasts 1.1 seconds.
// clang-format on
DRAKE_DEMAND(xc.size() == initial_state.size());
xc.SetFromVector(initial_state);
DiscreteValues<T>& xd = state->get_mutable_discrete_state();
for (int i = 0; i < xd.num_groups(); i++) {
BasicVector<T>& s = xd.get_mutable_vector(i);
s.SetFromVector(VectorX<T>::Zero(s.size()));
}
}
// Registers geometry to form an L-shaped arm onto the given frame. The arm is
// defined as shown below:
//
// ◯ ← z = height
// x = 0 │
// ↓ │ height
// ─────────────────────┘ ← z = 0
// ↑
// x = length
//
// The arm's horizontal length is oriented with the x-axis. The vertical length
// is oriented with the z-axis. The origin of the arm is defined at the local
// origin, and the top of the arm is positioned at the given height.
template <class ParentId>
void MakeArm(SourceId source_id, ParentId parent_id, double length,
double height, double radius, const Vector4d& material,
SceneGraph<double>* scene_graph) {
// tilt it horizontally
const math::RigidTransform<double> arm_pose(
AngleAxisd(M_PI / 2, Vector3d::UnitY()), Vector3d(length / 2, 0, 0));
scene_graph->RegisterGeometry(
source_id, parent_id,
MakeShape<Cylinder>(arm_pose, "HorzArm", material, radius, length));
const math::RigidTransform<double> post_pose(Vector3d(length, 0, height / 2));
scene_graph->RegisterGeometry(
source_id, parent_id,
MakeShape<Cylinder>(post_pose, "VertArm", material, radius, height));
}
template <typename T>
void SolarSystem<T>::AllocateGeometry(SceneGraph<T>* scene_graph) {
body_ids_.reserve(kBodyCount);
body_offset_.reserve(kBodyCount);
axes_.reserve(kBodyCount);
Vector4d post_material(0.3, 0.15, 0.05, 1);
const double orrery_bottom = -1.5;
const double pipe_radius = 0.05;
// Allocate the sun.
// NOTE: we don't store the id of the sun geometry because we have no need
// for subsequent access (the same is also true for dynamic geometries).
std::string sun_path =
FindResourceOrThrow("drake/examples/scene_graph/sun.gltf");
scene_graph->RegisterAnchoredGeometry(
source_id_,
MakeShape<Mesh>(RigidTransformd::Identity(), "Sun",
std::nullopt /* diffuse */, sun_path, 1.0 /* scale */));
// The fixed post on which Sun sits and around which all planets rotate.
const double post_height = 1;
const RigidTransformd post_pose(
Translation3d{0, 0, orrery_bottom + post_height / 2});
scene_graph->RegisterAnchoredGeometry(
source_id_, MakeShape<Cylinder>(post_pose, "Post", post_material,
pipe_radius, post_height));
// Allocate the "celestial bodies": two planets orbiting on different planes,
// each with a moon.
// For the full description of the frame labels, see solar_system.h.
// Earth's orbital frame Oe lies directly *below* the sun (to account for the
// orrery arm).
const double kEarthBottom = orrery_bottom + 0.25;
const RigidTransformd X_SOe{Translation3d{0, 0, kEarthBottom}};
FrameId planet_id =
scene_graph->RegisterFrame(source_id_, GeometryFrame("EarthOrbit"));
body_ids_.push_back(planet_id);
body_offset_.push_back(X_SOe);
axes_.push_back(Vector3d::UnitZ());
// The geometry is rigidly affixed to Earth's orbital frame so that it moves
// in a circular path.
const double kEarthOrbitRadius = 3.0;
RigidTransformd X_OeE{Translation3d{kEarthOrbitRadius, 0, -kEarthBottom}};
scene_graph->RegisterGeometry(
source_id_, planet_id,
MakeShape<Sphere>(X_OeE, "Earth", Vector4d(0, 0, 1, 1), 0.25));
// Earth's orrery arm.
MakeArm(source_id_, planet_id, kEarthOrbitRadius, -kEarthBottom, pipe_radius,
post_material, scene_graph);
// Luna's orbital frame Ol is at the center of Earth's geometry (E).
// So, X_OeOl = X_OeE.
const RigidTransformd& X_OeOl = X_OeE;
FrameId luna_id = scene_graph->RegisterFrame(
source_id_, planet_id, GeometryFrame("LunaOrbit"));
body_ids_.push_back(luna_id);
body_offset_.push_back(X_OeOl);
const Vector3d luna_axis_Oe{1, 1, 1};
axes_.push_back(luna_axis_Oe.normalized());
// The geometry is rigidly affixed to Luna's orbital frame so that it moves
// in a circular path.
const double kLunaOrbitRadius = 0.35;
// Pick a position at kLunaOrbitRadius distance from the Earth's origin on
// the plane _perpendicular_ to the moon's normal (<1, 1, 1>).
// luna_position.dot(luna_axis_Oe) will be zero.
Vector3d luna_position =
Vector3d(-1, 0.5, 0.5).normalized() * kLunaOrbitRadius;
RigidTransformd X_OlL{Translation3d{luna_position}};
scene_graph->RegisterGeometry(
source_id_, luna_id,
MakeShape<Sphere>(X_OlL, "Luna", Vector4d(0.5, 0.5, 0.35, 1.0), 0.075));
// Convex satellite orbits Earth in the same revolution as Luna but with
// different initial position. See SetDefaultState().
FrameId convexsat_id = scene_graph->RegisterFrame(
source_id_, planet_id, GeometryFrame("ConvexSatelliteOrbit"));
body_ids_.push_back(convexsat_id);
body_offset_.push_back(X_OeOl);
axes_.push_back(luna_axis_Oe.normalized());
std::string convexsat_absolute_path = FindResourceOrThrow(
"drake/examples/scene_graph/cuboctahedron_with_hole.obj");
scene_graph->RegisterGeometry(
source_id_, convexsat_id,
MakeShape<Convex>(X_OlL, "ConvexSatellite", Vector4d(1, 1, 0, 1),
convexsat_absolute_path, 0.075));
// Box satellite orbits Earth in the same revolution as Luna but with
// different initial position. See SetDefaultState().
FrameId boxsat_id = scene_graph->RegisterFrame(
source_id_, planet_id, GeometryFrame("BoxSatelliteOrbit"));
body_ids_.push_back(boxsat_id);
body_offset_.push_back(X_OeOl);
axes_.push_back(luna_axis_Oe.normalized());
scene_graph->RegisterGeometry(
source_id_, boxsat_id,
MakeShape<Box>(X_OlL, "BoxSatellite", Vector4d(1, 0, 1, 1), 0.15, 0.15,
0.15));
// Capsule satellite orbits Earth in the same revolution as Luna but with
// different initial position. See SetDefaultState().
FrameId capsulesat_id = scene_graph->RegisterFrame(
source_id_, planet_id, GeometryFrame("CapsuleSatelliteOrbit"));
body_ids_.push_back(capsulesat_id);
body_offset_.push_back(X_OeOl);
axes_.push_back(luna_axis_Oe.normalized());
scene_graph->RegisterGeometry(
source_id_, capsulesat_id,
MakeShape<Capsule>(X_OlL, "CapsuleSatellite", Vector4d(0, 1, 1, 1), 0.075,
0.2));
// Mars's orbital frame Om lies directly *below* the sun (to account for the
// orrery arm).
RigidTransformd X_SOm{Translation3d{0, 0, orrery_bottom}};
planet_id =
scene_graph->RegisterFrame(source_id_, GeometryFrame("MarsOrbit"));
body_ids_.push_back(planet_id);
body_offset_.push_back(X_SOm);
Vector3d mars_axis_S{0, 0.1, 1};
axes_.push_back(mars_axis_S.normalized());
// The geometry is rigidly affixed to Mars's orbital frame so that it moves
// in a circular path.
const double kMarsOrbitRadius = 5.0;
const double kMarsSize = 0.24;
RigidTransformd X_OmM{
Translation3d{kMarsOrbitRadius, 0, -orrery_bottom}};
scene_graph->RegisterGeometry(
source_id_, planet_id,
MakeShape<Sphere>(X_OmM, "Mars", Vector4d(0.9, 0.1, 0, 1), kMarsSize));
std::string rings_absolute_path =
FindResourceOrThrow("drake/examples/scene_graph/planet_rings.obj");
Vector3d axis = Vector3d(1, 1, 1).normalized();
RigidTransformd X_MR(AngleAxisd(M_PI / 3, axis), Vector3d{0, 0, 0});
scene_graph->RegisterGeometry(
source_id_, planet_id,
MakeShape<Mesh>(X_OmM * X_MR, "MarsRings", Vector4d(0.45, 0.9, 0, 1),
rings_absolute_path, kMarsSize));
// Mars's orrery arm.
MakeArm(source_id_, planet_id, kMarsOrbitRadius, -orrery_bottom, pipe_radius,
post_material, scene_graph);
// Phobos's orbital frame Op is at the center of Mars (M).
// So, X_OmOp = X_OmM. The normal of the plane is negated so it orbits in the
// opposite direction.
const RigidTransformd& X_OmOp = X_OmM;
FrameId phobos_id = scene_graph->RegisterFrame(source_id_, planet_id,
GeometryFrame("PhobosOrbit"));
body_ids_.push_back(phobos_id);
body_offset_.push_back(X_OmOp);
mars_axis_S << 0, 0, -1;
axes_.push_back(mars_axis_S.normalized());
// The geometry is displaced from the Phobos's frame so that it orbits.
const double kPhobosOrbitRadius = 0.34;
const RigidTransformd X_OpP{Translation3d{kPhobosOrbitRadius, 0, 0}};
scene_graph->RegisterGeometry(
source_id_, phobos_id,
MakeShape<Sphere>(X_OpP, "Phobos", Vector4d(0.65, 0.6, 0.8, 1), 0.06));
DRAKE_DEMAND(static_cast<int>(body_ids_.size()) == kBodyCount);
}
template <typename T>
void SolarSystem<T>::CalcFramePoseOutput(const Context<T>& context,
FramePoseVector<T>* poses) const {
const BasicVector<T>& state = get_state(context);
poses->clear();
for (int i = 0; i < kBodyCount; ++i) {
math::RigidTransform<T> pose(body_offset_[i]);
// Frames only revolve around their origin; it is only necessary to set the
// rotation value.
T rotation{state[i]};
pose.set_rotation(AngleAxis<T>(rotation, axes_[i]));
poses->set_value(body_ids_[i], pose);
}
}
template <typename T>
void SolarSystem<T>::DoCalcTimeDerivatives(
const MyContext& context, MyContinuousState* derivatives) const {
const BasicVector<T>& state = get_state(context);
BasicVector<T>& derivative_vector = get_mutable_state(derivatives);
derivative_vector.SetZero();
derivative_vector.get_mutable_value().head(kBodyCount) =
state.value().tail(kBodyCount);
}
template class SolarSystem<double>;
} // namespace solar_system
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/cuboctahedron_with_hole.obj | # Blender 4.0.2
# www.blender.org
# A shape whose convex hull is a cuboctahedron but with a hole punched through
# it. It has intentionally been given a texture material so that we can observe
# that when this is used as a Convex that:
#
# 1. The whole is filled in.
# 2. The material is rejected.
#
# Note: This *intentionally* doesn't have normals. Using this as Mesh with
# a perception role should cause our parser to be angry about the lack of
# normals.
mtllib cuboctahedron_with_hole.mtl
o cuboctahedron_with_hole
v 0.000000 -1.000000 -1.000000
v 0.000000 -1.000000 1.000000
v 0.000000 1.000000 -1.000000
v 0.000000 1.000000 1.000000
v -1.000000 0.000000 -1.000000
v -1.000000 0.000000 1.000000
v 1.000000 0.000000 -1.000000
v 1.000000 0.000000 1.000000
v -1.000000 -1.000000 0.000000
v -1.000000 1.000000 0.000000
v 1.000000 -1.000000 0.000000
v 1.000000 1.000000 0.000000
vt 0.066861 0.142822
vt 0.008706 0.631991
vt 0.153915 0.863395
vt 0.211084 0.374226
vt 0.574781 0.136605
vt 0.631950 0.625774
vt 0.487727 0.857178
vt 0.429573 0.368009
vt 0.318211 0.010832
vt 0.321026 0.731404
vt 0.741892 0.268596
vt 0.739077 0.989168
vt 0.850439 0.631991
vt 0.995647 0.863395
vt 0.908594 0.142822
s 0
usemtl checkered_mat
f 5/1 9/2 6/3 10/4
f 7/5 12/6 8/7 11/8
f 1/9 11/8 2/10 9/2
f 3/11 10/12 4/13 12/6
f 4/13 3/11 7/5 8/7
f 6/14 5/15 3/11 4/13
f 1/9 9/2 5/1
f 2/10 6/3 9/2
f 3/11 5/15 10/12
f 4/13 10/12 6/14
f 1/9 7/5 11/8
f 2/10 11/8 8/7
f 3/11 12/6 7/5
f 4/13 8/7 12/6
f 8/7 7/5 1/9 2/10
f 2/10 1/9 5/1 6/3
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/bouncing_ball_plant.cc | #include "drake/examples/scene_graph/bouncing_ball_plant.h"
#include <algorithm>
#include <vector>
#include "drake/common/eigen_types.h"
#include "drake/geometry/geometry_frame.h"
#include "drake/geometry/geometry_instance.h"
#include "drake/geometry/geometry_roles.h"
#include "drake/geometry/query_results/penetration_as_point_pair.h"
#include "drake/geometry/shape_specification.h"
namespace drake {
namespace examples {
namespace scene_graph {
namespace bouncing_ball {
using Eigen::Vector4d;
using geometry::FramePoseVector;
using geometry::GeometryFrame;
using geometry::GeometryInstance;
using geometry::IllustrationProperties;
using geometry::PenetrationAsPointPair;
using geometry::PerceptionProperties;
using geometry::ProximityProperties;
using geometry::render::RenderLabel;
using geometry::SceneGraph;
using geometry::SourceId;
using geometry::Sphere;
using math::RigidTransform;
using math::RigidTransformd;
using std::make_unique;
using systems::Context;
template <typename T>
BouncingBallPlant<T>::BouncingBallPlant(SourceId source_id,
SceneGraph<T>* scene_graph,
const Vector2<double>& p_WB)
: p_WB_(p_WB) {
DRAKE_DEMAND(scene_graph != nullptr);
DRAKE_DEMAND(source_id.is_valid());
geometry_query_port_ = this->DeclareAbstractInputPort(
systems::kUseDefaultName, Value<geometry::QueryObject<T>>{})
.get_index();
auto state_index = this->DeclareContinuousState(
BouncingBallVector<T>(), 1 /* num_q */, 1 /* num_v */, 0 /* num_z */);
state_port_ =
this->DeclareStateOutputPort(systems::kUseDefaultName, state_index)
.get_index();
static_assert(BouncingBallVectorIndices::kNumCoordinates == 1 + 1, "");
ball_frame_id_ = scene_graph->RegisterFrame(
source_id, GeometryFrame("ball_frame"));
ball_id_ = scene_graph->RegisterGeometry(
source_id, ball_frame_id_,
make_unique<GeometryInstance>(RigidTransformd::Identity(), /*X_FG*/
make_unique<Sphere>(diameter_ / 2.0),
"ball"));
// Use the default material.
scene_graph->AssignRole(source_id, ball_id_, IllustrationProperties());
scene_graph->AssignRole(source_id, ball_id_, ProximityProperties());
PerceptionProperties perception_properties;
perception_properties.AddProperty("phong", "diffuse",
Vector4d{0.8, 0.8, 0.8, 1.0});
perception_properties.AddProperty("label", "id",
RenderLabel(ball_id_.get_value()));
scene_graph->AssignRole(source_id, ball_id_, perception_properties);
// Allocate the output port now that the frame has been registered.
geometry_pose_port_ = this->DeclareAbstractOutputPort(
systems::kUseDefaultName,
&BouncingBallPlant::CalcFramePoseOutput,
{this->configuration_ticket()})
.get_index();
}
template <typename T>
BouncingBallPlant<T>::~BouncingBallPlant() {}
template <typename T>
const systems::InputPort<T>&
BouncingBallPlant<T>::get_geometry_query_input_port() const {
return systems::System<T>::get_input_port(geometry_query_port_);
}
template <typename T>
const systems::OutputPort<T>&
BouncingBallPlant<T>::get_state_output_port() const {
return systems::System<T>::get_output_port(state_port_);
}
template <typename T>
const systems::OutputPort<T>&
BouncingBallPlant<T>::get_geometry_pose_output_port() const {
return systems::System<T>::get_output_port(geometry_pose_port_);
}
template <typename T>
void BouncingBallPlant<T>::CalcFramePoseOutput(
const Context<T>& context, FramePoseVector<T>* poses) const {
RigidTransform<T> pose = RigidTransform<T>::Identity();
const BouncingBallVector<T>& state = get_state(context);
pose.set_translation({p_WB_.x(), p_WB_.y(), state.z()});
*poses = {{ball_frame_id_, pose}};
}
// Compute the actual physics.
template <typename T>
void BouncingBallPlant<T>::DoCalcTimeDerivatives(
const systems::Context<T>& context,
systems::ContinuousState<T>* derivatives) const {
using std::max;
const BouncingBallVector<T>& state = get_state(context);
BouncingBallVector<T>& derivative_vector = get_mutable_state(derivatives);
const auto& query_object = get_geometry_query_input_port().
template Eval<geometry::QueryObject<T>>(context);
std::vector<PenetrationAsPointPair<T>> penetrations =
query_object.ComputePointPairPenetration();
T fC = 0; // the contact force
if (penetrations.size() > 0) {
for (const auto& penetration : penetrations) {
if (penetration.id_A == ball_id_ || penetration.id_B == ball_id_) {
// Penetration depth, > 0 during penetration.
const T& x = penetration.depth;
// Penetration rate, > 0 implies increasing penetration.
const T& xdot = -state.zdot();
fC = k_ * x * (1.0 + d_ * xdot);
}
}
}
derivative_vector.set_z(state.zdot());
const T fN = max(0.0, fC);
derivative_vector.set_zdot((-m_ * g_ + fN) / m_);
}
template class BouncingBallPlant<double>;
} // namespace bouncing_ball
} // namespace scene_graph
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/scene_graph/bouncing_ball_run_dynamics.cc | #include <memory>
#include <utility>
#include <gflags/gflags.h>
#include "drake/examples/scene_graph/bouncing_ball_plant.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/geometry/geometry_instance.h"
#include "drake/geometry/render_vtk/factory.h"
#include "drake/geometry/scene_graph.h"
#include "drake/geometry/shape_specification.h"
#include "drake/lcm/drake_lcm.h"
#include "drake/math/rigid_transform.h"
#include "drake/math/rotation_matrix.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/lcm/lcm_publisher_system.h"
#include "drake/systems/sensors/image_to_lcm_image_array_t.h"
#include "drake/systems/sensors/pixel_types.h"
#include "drake/systems/sensors/rgbd_sensor.h"
DEFINE_double(simulation_time, 10.0,
"Desired duration of the simulation in seconds.");
DEFINE_bool(render_on, true, "Sets rendering generally enabled (or not)");
DEFINE_bool(color, true, "Sets the enabled camera to render color");
DEFINE_bool(depth, true, "Sets the enabled camera to render depth");
DEFINE_bool(label, true, "Sets the enabled camera to render label");
DEFINE_double(render_fps, 10, "Frames per simulation second to render");
namespace drake {
namespace examples {
namespace scene_graph {
namespace bouncing_ball {
namespace {
using Eigen::Vector3d;
using Eigen::Vector4d;
using geometry::DrakeVisualizerd;
using geometry::GeometryInstance;
using geometry::SceneGraph;
using geometry::GeometryId;
using geometry::HalfSpace;
using geometry::IllustrationProperties;
using geometry::PerceptionProperties;
using geometry::ProximityProperties;
using geometry::render::ColorRenderCamera;
using geometry::render::DepthRenderCamera;
using geometry::render::RenderLabel;
using geometry::RenderEngineVtkParams;
using geometry::SceneGraph;
using geometry::SourceId;
using lcm::DrakeLcm;
using math::RigidTransformd;
using math::RotationMatrixd;
using systems::InputPort;
using systems::sensors::PixelType;
using systems::sensors::RgbdSensor;
using std::make_unique;
int do_main() {
systems::DiagramBuilder<double> builder;
auto scene_graph = builder.AddSystem<SceneGraph<double>>();
scene_graph->set_name("scene_graph");
const std::string render_name("renderer");
scene_graph->AddRenderer(render_name,
MakeRenderEngineVtk(RenderEngineVtkParams()));
// Create two bouncing balls --> two plants. Put the balls at positions
// mirrored over the origin (<0.25, 0.25> and <-0.25, -0.25>, respectively).
// See below for setting the initial *height*.
const SourceId ball_source_id1 = scene_graph->RegisterSource("ball1");
auto bouncing_ball1 = builder.AddSystem<BouncingBallPlant>(
ball_source_id1, scene_graph, Vector2<double>(0.25, 0.25));
bouncing_ball1->set_name("BouncingBall1");
const SourceId ball_source_id2 = scene_graph->RegisterSource("ball2");
auto bouncing_ball2 = builder.AddSystem<BouncingBallPlant>(
ball_source_id2, scene_graph, Vector2<double>(-0.25, -0.25));
bouncing_ball2->set_name("BouncingBall2");
const SourceId global_source = scene_graph->RegisterSource("anchored");
// Add a "ground" halfspace. Define the pose of the half space (H) in the
// world from its normal (Hz_W) and a point on the plane (p_WH). In this case,
// X_WH will be the identity.
Vector3<double> Hz_W(0, 0, 1);
Vector3<double> p_WHo_W(0, 0, 0);
const GeometryId ground_id = scene_graph->RegisterAnchoredGeometry(
global_source,
make_unique<GeometryInstance>(HalfSpace::MakePose(Hz_W, p_WHo_W),
make_unique<HalfSpace>(), "ground"));
scene_graph->AssignRole(global_source, ground_id, ProximityProperties());
scene_graph->AssignRole(global_source, ground_id, IllustrationProperties());
builder.Connect(bouncing_ball1->get_geometry_pose_output_port(),
scene_graph->get_source_pose_port(ball_source_id1));
builder.Connect(scene_graph->get_query_output_port(),
bouncing_ball1->get_geometry_query_input_port());
builder.Connect(bouncing_ball2->get_geometry_pose_output_port(),
scene_graph->get_source_pose_port(ball_source_id2));
builder.Connect(scene_graph->get_query_output_port(),
bouncing_ball2->get_geometry_query_input_port());
DrakeLcm lcm;
DrakeVisualizerd::AddToBuilder(&builder, *scene_graph, &lcm);
if (FLAGS_render_on) {
PerceptionProperties properties;
properties.AddProperty("phong", "diffuse", Vector4d{0.8, 0.8, 0.8, 1.0});
properties.AddProperty("label", "id", RenderLabel(ground_id.get_value()));
scene_graph->AssignRole(global_source, ground_id, properties);
// Create the camera.
const ColorRenderCamera color_camera{
{render_name, {640, 480, M_PI_4}, {0.1, 2.0}, {}}, false};
const DepthRenderCamera depth_camera{color_camera.core(), {0.1, 2.0}};
// We need to position and orient the camera. We have the camera body frame
// B (see rgbd_sensor.h) and the camera frame C (see camera_info.h).
// By default X_BC = I in the RgbdSensor. So, to aim the camera, Cz = Bz
// should point from the camera position to the origin. By points *down* the
// image, so we need to align it in the -Wz direction. So, we compute the
// basis using camera Y-ish in the By ≈ -Wz direction to compute Bx, and
// then use Bx an and Bz to compute By.
const Vector3d p_WB(0.3, -1, 0.25);
// Set rotation looking at the origin.
const Vector3d Bz_W = -p_WB.normalized();
const Vector3d Bx_W = -Vector3d::UnitZ().cross(Bz_W).normalized();
const Vector3d By_W = Bz_W.cross(Bx_W).normalized();
const RotationMatrixd R_WB =
RotationMatrixd::MakeFromOrthonormalColumns(Bx_W, By_W, Bz_W);
const RigidTransformd X_WB(R_WB, p_WB);
auto camera = builder.AddSystem<RgbdSensor>(
scene_graph->world_frame_id(), X_WB, color_camera, depth_camera);
builder.Connect(scene_graph->get_query_output_port(),
camera->query_object_input_port());
// Broadcast the images to Meldis (available after #18862 is finished).
auto image_to_lcm_image_array =
builder.template AddSystem<systems::sensors::ImageToLcmImageArrayT>();
image_to_lcm_image_array->set_name("converter");
systems::lcm::LcmPublisherSystem* image_array_lcm_publisher{nullptr};
if ((FLAGS_color || FLAGS_depth || FLAGS_label)) {
image_array_lcm_publisher =
builder.template AddSystem(systems::lcm::LcmPublisherSystem::Make<
lcmt_image_array>(
"DRAKE_RGBD_CAMERA_IMAGES", &lcm,
1. / FLAGS_render_fps /* publish period */));
image_array_lcm_publisher->set_name("publisher");
builder.Connect(
image_to_lcm_image_array->image_array_t_msg_output_port(),
image_array_lcm_publisher->get_input_port());
}
if (FLAGS_color) {
const auto& port =
image_to_lcm_image_array->DeclareImageInputPort<PixelType::kRgba8U>(
"color");
builder.Connect(camera->color_image_output_port(), port);
}
if (FLAGS_depth) {
const auto& port =
image_to_lcm_image_array
->DeclareImageInputPort<PixelType::kDepth32F>("depth");
builder.Connect(camera->depth_image_32F_output_port(), port);
}
if (FLAGS_label) {
const auto& port =
image_to_lcm_image_array
->DeclareImageInputPort<PixelType::kLabel16I>("label");
builder.Connect(camera->label_image_output_port(), port);
}
}
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
auto init_ball = [&](BouncingBallPlant<double>* system, double z,
double zdot) {
systems::Context<double>& ball_context =
diagram->GetMutableSubsystemContext(*system,
&simulator.get_mutable_context());
system->set_z(&ball_context, z);
system->set_zdot(&ball_context, zdot);
};
init_ball(bouncing_ball1, 0.3, 0.);
init_ball(bouncing_ball2, 0.3, 0.3);
simulator.get_mutable_integrator().set_maximum_step_size(0.002);
simulator.set_target_realtime_rate(1.f);
simulator.Initialize();
simulator.AdvanceTo(FLAGS_simulation_time);
return 0;
}
} // namespace
} // namespace bouncing_ball
} // namespace scene_graph
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::scene_graph::bouncing_ball::do_main();
}
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/fmt_ostream.h | #pragma once
#include <sstream>
#include <string_view>
#include <fmt/ostream.h>
#include "drake/common/fmt.h"
namespace drake {
// Compatibility shim for fmt::streamed.
#if FMT_VERSION >= 90000 || defined(DRAKE_DOXYGEN_CXX)
/** When using fmt >= 9, this is an alias for
<a href="https://fmt.dev/latest/api.html#ostream-api">fmt::streamed</a>.
When using fmt < 9, this uses a polyfill instead.
Within Drake, the nominal use for `fmt::streamed` is when formatting third-party
types that provide `operator<<` support but not `fmt::formatter<T>` support.
Once we stop using `FMT_DEPRECATED_OSTREAM=1`, compilation errors will help you
understand where you are required to use this wrapper. */
template <typename T>
auto fmt_streamed(const T& ref) {
return fmt::streamed(ref);
}
#else // FMT_VERSION
namespace internal {
template <typename T>
struct streamed_ref {
const T& ref;
};
} // namespace internal
template <typename T>
internal::streamed_ref<T> fmt_streamed(const T& ref) {
return {ref};
}
#endif // FMT_VERSION
// Compatibility shim for fmt::ostream_formatter.
#if FMT_VERSION >= 90000
using fmt::ostream_formatter;
#else // FMT_VERSION
/** When using fmt >= 9, this is an alias for fmt::ostream_formatter.
When using fmt < 9, this uses a polyfill instead. */
struct ostream_formatter : fmt::formatter<std::string_view> {
template <typename T, typename FormatContext>
auto format(const T& value,
// NOLINTNEXTLINE(runtime/references) To match fmt API.
FormatContext& ctx) DRAKE_FMT8_CONST {
std::ostringstream output;
output << value;
output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
return fmt::formatter<std::string_view>::format(output.str(), ctx);
}
};
#endif // FMT_VERSION
} // namespace drake
// Formatter specialization for drake::fmt_streamed.
#ifndef DRAKE_DOXYGEN_CXX
#if FMT_VERSION < 90000
namespace fmt {
template <typename T>
struct formatter<drake::internal::streamed_ref<T>> : drake::ostream_formatter {
template <typename FormatContext>
auto format(drake::internal::streamed_ref<T> tag,
// NOLINTNEXTLINE(runtime/references) To match fmt API.
FormatContext& ctx) DRAKE_FMT8_CONST {
return ostream_formatter::format(tag.ref, ctx);
}
};
} // namespace fmt
#endif // FMT_VERSION
#endif // DRAKE_DOXYGEN_CXX
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/string_unordered_set.h | #pragma once
#include <functional>
#include <string>
#include <unordered_set>
#include "drake/common/string_hash.h"
namespace drake {
/** Like `std::unordered_set<std::string>`, but with better defaults than the
plain `std::unordered_set<std::string>` spelling. We need the custom hash and
comparison functions so that `std::string_view` and `const char*` can be used
as lookup keys without copying them to a `std::string`. */
using string_unordered_set =
std::unordered_set<std::string, internal::StringHash, std::equal_to<void>>;
/** Like `std::unordered_multiset<std::string>`, but with better defaults than
the plain `std::unordered_multiset<std::string>` spelling. We need the custom
hash and comparison functions so that `std::string_view` and `const char*` can
be used as lookup keys without copying them to a `std::string`. */
using string_unordered_multiset =
std::unordered_multiset<std::string, internal::StringHash,
std::equal_to<void>>;
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/text_logging.cc | #include "drake/common/text_logging.h"
#include <memory>
#include <mutex>
#include <utility>
#ifdef HAVE_SPDLOG
#include <spdlog/sinks/dist_sink.h>
#include <spdlog/sinks/stdout_sinks.h>
#endif
#include "drake/common/never_destroyed.h"
namespace drake {
#ifdef HAVE_SPDLOG
namespace {
// Returns the default logger. NOTE: This function assumes that it is mutexed,
// as in the initializer of a static local.
std::shared_ptr<logging::logger> onetime_create_log() {
// Check if anyone has already set up a logger named "console". If so, we
// will just return it; if not, we'll create our own default one.
std::shared_ptr<logging::logger> result(spdlog::get("console"));
if (!result) {
// We wrap our stderr sink in a dist_sink so that users can atomically swap
// out the sinks used by all Drake logging, via dist_sink_mt's APIs.
auto wrapper = std::make_shared<spdlog::sinks::dist_sink_mt>();
// We use the stderr_sink_mt (instead of stderr_sink_st) so more than one
// thread can use this logger and have their messages be staggered by line,
// instead of co-mingling their character bytes.
wrapper->add_sink(std::make_shared<spdlog::sinks::stderr_sink_mt>());
result = std::make_shared<logging::logger>("console", std::move(wrapper));
result->set_level(spdlog::level::info);
}
return result;
}
} // namespace
logging::logger* log() {
static const never_destroyed<std::shared_ptr<logging::logger>> g_logger(
onetime_create_log());
return g_logger.access().get();
}
logging::sink* logging::get_dist_sink() {
// Extract the dist_sink_mt from Drake's logger instance.
auto* sink = log()->sinks().empty() ? nullptr : log()->sinks().front().get();
auto* result = dynamic_cast<spdlog::sinks::dist_sink_mt*>(sink);
if (result == nullptr) {
throw std::logic_error(
"drake::logging::get_sink(): error: the spdlog sink configuration has"
"unexpectedly changed.");
}
return result;
}
std::string logging::set_log_level(const std::string& level) {
spdlog::level::level_enum prev_value = drake::log()->level();
spdlog::level::level_enum value{};
if (level == "trace") {
value = spdlog::level::trace;
} else if (level == "debug") {
value = spdlog::level::debug;
} else if (level == "info") {
value = spdlog::level::info;
} else if (level == "warn") {
value = spdlog::level::warn;
} else if (level == "err") {
value = spdlog::level::err;
} else if (level == "critical") {
value = spdlog::level::critical;
} else if (level == "off") {
value = spdlog::level::off;
} else if (level == "unchanged") {
value = prev_value;
} else {
throw std::runtime_error(fmt::format("Unknown spdlog level: {}", level));
}
drake::log()->set_level(value);
switch (prev_value) {
case spdlog::level::trace:
return "trace";
case spdlog::level::debug:
return "debug";
case spdlog::level::info:
return "info";
case spdlog::level::warn:
return "warn";
case spdlog::level::err:
return "err";
case spdlog::level::critical:
return "critical";
case spdlog::level::off:
return "off";
default: {
// N.B. `spdlog::level::level_enum` is not a `enum class`, so the
// compiler does not know that it has a closed set of values. For
// simplicity in linking, we do not use `DRAKE_UNREACHABLE`.
throw std::runtime_error("Should not reach here!");
}
}
}
const char* const logging::kSetLogLevelHelpMessage =
"sets the spdlog output threshold; possible values are "
"'unchanged', "
"'trace', "
"'debug', "
"'info', "
"'warn', "
"'err', "
"'critical', "
"'off'";
void logging::set_log_pattern(const std::string& pattern) {
drake::log()->set_pattern(pattern);
}
const char* const logging::kSetLogPatternHelpMessage =
"sets the spdlog pattern for formatting; for more information, see "
"https://github.com/gabime/spdlog/wiki/3.-Custom-formatting";
#else // HAVE_SPDLOG
logging::logger::logger() {}
logging::sink::sink() {}
logging::logger* log() {
// A do-nothing logger instance.
static logging::logger g_logger;
return &g_logger;
}
logging::sink* logging::get_dist_sink() {
// An empty sink instance.
static logging::sink g_sink;
return &g_sink;
}
std::string logging::set_log_level(const std::string&) {
return "";
}
const char* const logging::kSetLogLevelHelpMessage =
"(Text logging is unavailable.)";
void logging::set_log_pattern(const std::string&) {}
const char* const logging::kSetLogPatternHelpMessage =
"(Text logging is unavailable.)";
#endif // HAVE_SPDLOG
const char* const logging::kSetLogLevelUnchanged = "unchanged";
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/reset_on_copy.h | #pragma once
#include <type_traits>
#include <utility>
namespace drake {
// NOTE(sherm1) to future implementers: if you decide to extend this adapter for
// use with class types, be sure to think carefully about the semantics of copy
// and move and how to explain that to users. Be aware that for class types T,
// the implementation of `T{}` (the default constructor, which may have been
// user-supplied) won't necessarily reset T's members to zero, nor even
// necessarily value-initialize T's members. Also, the "noexcept" reasoning
// below is more than we need with the std::is_scalar<T> restriction, but is
// strictly necessary for class types if you want std::vector to choose move
// construction (content-preserving) over copy construction (resetting).
/// Type wrapper that performs value-initialization on copy construction or
/// assignment.
///
/// Rather than copying the source supplied for copy construction or copy
/// assignment, this wrapper instead value-initializes the destination object.
/// Move assignment and construction preserve contents in the destination as
/// usual, but reset the source to its value-initialized value.
///
/// Only types T that satisfy `std::is_scalar<T>` are currently
/// permitted: integral and floating point types, enums, and pointers.
/// Value initialization means the initialization performed when a variable is
/// constructed with an empty initializer `{}`. For the restricted set of types
/// we support, that just means that numeric types are set to zero and pointer
/// types are set to nullptr. Also, all the methods here are noexcept due to the
/// `std::is_scalar<T>` restriction.
/// See http://en.cppreference.com/w/cpp/language/value_initialization.
///
/// Background:
///
/// It is preferable to use default copy construction for classes whenever
/// possible because it avoids difficult-to-maintain enumeration of member
/// fields in bespoke copy constructors. The presence of fields that must be
/// reset to zero in the copy (counters, for example) prevents use of default
/// copy construction. Similarly, pointers that would be invalid in the copy
/// need to be set to null to avoid stale references. By wrapping those
/// problematic data members in this adapter, default copy construction can
/// continue to be used, with all data members copied properly except the
/// designated ones, which are value-initialized instead. The resetting of the
/// source on move doesn't change semantics since the condition of the source
/// after a move is generally undefined. It is instead opportunistic good
/// hygiene for early detection of bugs, taking advantage of the fact that we
/// know type T can be value-initialized. See reset_after_move for more
/// discussion.
///
/// Example:
///
/// <pre>
/// class Foo {
/// public:
/// DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Foo)
/// Foo() = default;
///
/// private:
/// std::vector<int> items_;
/// reset_on_copy<int> use_count_;
/// };
/// </pre>
///
/// When copying from `Foo`, the new object will contain a copy of `items_`
/// but `use_count_` will be zero. If `Foo` had not used the
/// `reset_on_copy` wrapper, `use_count_` would have been copied also,
/// which we're assuming is not the desired behavior here.
///
/// @warning Even if you initialize a %reset_on_copy member to a non-zero value
/// using an initializer like `reset_on_copy<int> some_member_{5}` it will be
/// _reset_ to zero, not _reinitialized_ to 5 when copied.
///
/// @note Enum types T are permitted, but be aware that they will be reset to
/// zero, regardless of whether 0 is one of the specified enumeration values.
///
/// @tparam T must satisfy `std::is_scalar<T>`.
/// @see reset_after_move
template <typename T>
class reset_on_copy {
public:
static_assert(std::is_scalar_v<T>,
"reset_on_copy<T> is permitted only for integral, "
"floating point, and pointer types T.");
/// Constructs a reset_on_copy<T> with a value-initialized wrapped value.
reset_on_copy() noexcept(std::is_nothrow_default_constructible_v<T>) {}
/// Constructs a %reset_on_copy<T> with a copy of the given value. This is
/// an implicit conversion, so that %reset_on_copy<T> behaves more like
/// the unwrapped type.
// NOLINTNEXTLINE(runtime/explicit)
reset_on_copy(const T& value) noexcept(
std::is_nothrow_copy_constructible_v<T>)
: value_(value) {}
/// Constructs a %reset_on_copy<T> with the given wrapped value, by move
/// construction if possible. This is an implicit conversion, so that
/// %reset_on_copy<T> behaves more like the unwrapped type.
// NOLINTNEXTLINE(runtime/explicit)
reset_on_copy(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>)
: value_(std::move(value)) {}
/// @name Implements copy/move construction and assignment.
/// These make %reset_on_copy objects CopyConstructible, CopyAssignable,
/// MoveConstructible, and MoveAssignable.
//@{
/// Copy constructor just value-initializes instead; the source is ignored.
reset_on_copy(const reset_on_copy&) noexcept(
std::is_nothrow_default_constructible_v<T>) {}
/// Copy assignment just destructs the contained value and then
/// value-initializes it, _except_ for self-assignment which does nothing.
/// The source argument is otherwise ignored.
reset_on_copy& operator=(const reset_on_copy& source) noexcept(
std::is_nothrow_destructible_v<T> &&
std::is_nothrow_default_constructible_v<T>) {
if (this != &source) destruct_and_reset_value();
return *this;
}
/// Move construction uses T's move constructor, then destructs and
/// value initializes the source.
reset_on_copy(reset_on_copy&& source) noexcept(
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_destructible_v<T> &&
std::is_nothrow_default_constructible_v<T>)
: value_(std::move(source.value_)) {
source.destruct_and_reset_value();
}
/// Move assignment uses T's move assignment, then destructs and value
/// initializes the source, _except_ for self-assignment which does nothing.
/// The source argument is otherwise ignored.
reset_on_copy& operator=(reset_on_copy&& source) noexcept(
std::is_nothrow_move_assignable_v<T> &&
std::is_nothrow_destructible_v<T> &&
std::is_nothrow_default_constructible_v<T>) {
if (this != &source) {
value_ = std::move(source);
source.destruct_and_reset_value();
}
return *this;
}
//@}
/// @name Implicit conversion operators to make reset_on_copy<T> act
/// as the wrapped type.
//@{
operator T&() noexcept { return value_; }
operator const T&() const noexcept { return value_; }
//@}
/// @name Dereference operators if T is a pointer type.
/// If type T is a pointer, these exist and return the pointed-to object.
/// For non-pointer types these methods are not instantiated.
//@{
template <typename T1 = T>
std::enable_if_t<std::is_pointer_v<T1>, T> operator->() const noexcept {
return value_;
}
template <typename T1 = T>
std::enable_if_t<std::is_pointer_v<T1>,
std::add_lvalue_reference_t<std::remove_pointer_t<T>>>
operator*() const noexcept {
return *value_;
}
//@}
private:
// Invokes T's destructor if there is one, then value-initializes. Note that
// the noexcept code above assumes exactly this implementation. Don't change
// this to `value_ = T{}` which would introduce an additional dependence on
// the behavior of T's copy assignment operator.
void destruct_and_reset_value() {
value_.~T(); // Invokes destructor if there is one.
new (&value_) T{}; // Placement new; no heap activity.
}
T value_{};
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_loaded_library.h | #pragma once
#include <optional>
#include <string>
namespace drake {
/// This function returns the absolute path of the library with the name
/// `library_name` if that library was loaded in the current running
/// process. Otherwise it returns an empty optional.
std::optional<std::string> LoadedLibraryPath(const std::string& library_name);
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/text_logging.h | #pragma once
/**
@file
This is the entry point for all text logging within Drake.
Once you've included this file, the suggested ways you
should write log messages include:
<pre>
drake::log()->trace("Some trace message: {} {}", something, some_other);
</pre>
Similarly, it provides:
<pre>
drake::log()->debug(...);
drake::log()->info(...);
drake::log()->warn(...);
drake::log()->error(...);
drake::log()->critical(...);
</pre>
If you want to log objects that are expensive to serialize, these macros will
not be compiled if debugging is turned off (-DNDEBUG is set):
<pre>
DRAKE_LOGGER_TRACE("message: {}", something_conditionally_compiled);
DRAKE_LOGGER_DEBUG("message: {}", something_conditionally_compiled);
</pre>
The format string syntax is fmtlib; see https://fmt.dev/latest/syntax.html.
(Note that the documentation link provides syntax for the latest version of
fmtlib; the version of fmtlib used by Drake might be older.)
When formatting an Eigen matrix into a string you must wrap the Eigen object
with fmt_eigen(); see its documentation for details. This holds true whether it
be for logging, error messages, etc.
When logging a third-party type whose only affordance for string output is
`operator<<`, use fmt_streamed(); see its documentation for details. This is
very rare (only a couple uses in Drake so far).
When implementing a string output for a Drake type, eventually this page will
demonstrate how to use fmt::formatter<T>. In the meantime, you can implement
`operator<<` and use drake::ostream_formatter, or else use the macro helper
DRAKE_FORMATTER_AS(). Grep around in Drake's existing code to find examples. */
#include <string>
#include "drake/common/fmt.h"
#ifndef DRAKE_DOXYGEN_CXX
#ifdef HAVE_SPDLOG
#ifndef NDEBUG
// When in Debug builds, before including spdlog we set the compile-time
// minimum log threshold so that spdlog defaults to enabling all log levels.
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
// Provide operative macros only when spdlog is available and Debug is enabled.
#define DRAKE_LOGGER_TRACE(...) \
do { \
/* Capture the drake::log() in a temporary, using a relatively unique */ \
/* variable name to avoid potential variable name shadowing warnings. */ \
::drake::logging::logger* const drake_spdlog_macro_logger_alias = \
::drake::log(); \
if (drake_spdlog_macro_logger_alias->level() <= spdlog::level::trace) { \
SPDLOG_LOGGER_TRACE(drake_spdlog_macro_logger_alias, __VA_ARGS__); \
} \
} while (0)
#define DRAKE_LOGGER_DEBUG(...) \
do { \
/* Capture the drake::log() in a temporary, using a relatively unique */ \
/* variable name to avoid potential variable name shadowing warnings. */ \
::drake::logging::logger* const drake_spdlog_macro_logger_alias = \
::drake::log(); \
if (drake_spdlog_macro_logger_alias->level() <= spdlog::level::debug) { \
SPDLOG_LOGGER_DEBUG(drake_spdlog_macro_logger_alias, __VA_ARGS__); \
} \
} while (0)
#else
// Spdlog is available, but we are doing a non-Debug build.
#define DRAKE_LOGGER_TRACE(...)
#define DRAKE_LOGGER_DEBUG(...)
#endif
#include <spdlog/spdlog.h>
#endif // HAVE_SPDLOG
#endif // DRAKE_DOXYGEN_CXX
#include "drake/common/drake_copyable.h"
namespace drake {
#ifdef HAVE_SPDLOG
namespace logging {
// If we have spdlog, just alias logger into our namespace.
/// The drake::logging::logger class provides text logging methods.
/// See the text_logging.h documentation for a short tutorial.
using logger = spdlog::logger;
/// When spdlog is enabled in this build, drake::logging::sink is an alias for
/// spdlog::sinks::sink. When spdlog is disabled, it is an empty class.
using spdlog::sinks::sink;
/// True only if spdlog is enabled in this build.
constexpr bool kHaveSpdlog = true;
} // namespace logging
#else // HAVE_SPDLOG
// If we don't have spdlog, we need to stub out logger.
namespace logging {
constexpr bool kHaveSpdlog = false;
// A stubbed-out version of `spdlog::logger`. Implements only those methods
// that we expect to use, as spdlog's API does change from time to time.
class logger {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(logger)
logger();
template <typename... Args>
void trace(const char*, const Args&...) {}
template <typename... Args>
void debug(const char*, const Args&...) {}
template <typename... Args>
void info(const char*, const Args&...) {}
template <typename... Args>
void warn(const char*, const Args&...) {}
template <typename... Args>
void error(const char*, const Args&...) {}
template <typename... Args>
void critical(const char*, const Args&...) {}
template <typename T>
void trace(const T&) {}
template <typename T>
void debug(const T&) {}
template <typename T>
void info(const T&) {}
template <typename T>
void warn(const T&) {}
template <typename T>
void error(const T&) {}
template <typename T>
void critical(const T&) {}
};
// A stubbed-out version of `spdlog::sinks::sink`.
class sink {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(sink)
sink();
};
} // namespace logging
#define DRAKE_LOGGER_TRACE(...)
#define DRAKE_LOGGER_DEBUG(...)
#endif // HAVE_SPDLOG
/// Retrieve an instance of a logger to use for logging; for example:
/// <pre>
/// drake::log()->info("potato!")
/// </pre>
///
/// See the text_logging.h documentation for a short tutorial.
logging::logger* log();
namespace logging {
/// (Advanced) Retrieves the default sink for all Drake logs. When spdlog is
/// enabled, the return value can be cast to spdlog::sinks::dist_sink_mt and
/// thus allows consumers of Drake to redirect Drake's text logs to locations
/// other than the default of stderr. When spdlog is disabled, the return
/// value is an empty class.
sink* get_dist_sink();
/// When constructed, logs a message (at "warn" severity); the destructor is
/// guaranteed to be trivial. This is useful for declaring an instance of this
/// class as a function-static global, so that a warning is logged the first
/// time the program encounters some code, but does not repeat the warning on
/// subsequent encounters within the same process.
///
/// For example:
/// <pre>
/// double* SanityCheck(double* data) {
/// if (!data) {
/// static const logging::Warn log_once("Bad data!");
/// return alternative_data();
/// }
/// return data;
/// }
/// </pre>
struct[[maybe_unused]] Warn {
template <typename... Args>
Warn(const char* a, const Args&... b) {
// TODO(jwnimmer-tri) Ideally we would compile-time check our Warn format
// strings without using fmt_runtime here, but I haven't figured out how
// to forward the arguments properly for all versions of fmt.
drake::log()->warn(fmt_runtime(a), b...);
}
};
/// Sets the log threshold used by Drake's C++ code.
/// @param level Must be a string from spdlog enumerations: `trace`, `debug`,
/// `info`, `warn`, `err`, `critical`, `off`, or `unchanged` (not an enum, but
/// useful for command-line).
/// @return The string value of the previous log level. If SPDLOG is disabled,
/// then this returns an empty string.
std::string set_log_level(const std::string& level);
/// The "unchanged" string to pass to set_log_level() so as to achieve a no-op.
extern const char* const kSetLogLevelUnchanged;
/// An end-user help string suitable to describe the effects of set_log_level().
extern const char* const kSetLogLevelHelpMessage;
/// Invokes `drake::log()->set_pattern(pattern)`.
/// @param pattern Formatting for message. For more information, see:
/// https://github.com/gabime/spdlog/wiki/3.-Custom-formatting
void set_log_pattern(const std::string& pattern);
/// An end-user help string suitable to describe the effects of
/// set_log_pattern().
extern const char* const kSetLogPatternHelpMessage;
} // namespace logging
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_deprecated.cc | #include "drake/common/drake_deprecated.h"
#include <cstdlib>
#include <stdexcept>
#include "drake/common/drake_throw.h"
#include "drake/common/text_logging.h"
namespace drake {
namespace internal {
namespace {
// TODO(jwnimmer-tri) Teach pybind11 to map this to Python's DeprecationWarning.
class DeprecationWarning final : public std::runtime_error {
public:
using runtime_error::runtime_error;
};
// Drake's regression tests use this to fail-fast in case Drake is spuriously
// using deprecated self-calls. Note that the same literal string name for the
// environment variable is used for both C++ code and Python code, so keep the
// two in sync.
constexpr char kEnvDrakeDeprecationIsError[] = "_DRAKE_DEPRECATION_IS_ERROR";
} // namespace
WarnDeprecated::WarnDeprecated(std::string_view removal_date,
std::string_view message) {
const bool missing_period = message.empty() || message.back() != '.';
const std::string full_message = fmt::format(
"DRAKE DEPRECATED: {}{} "
"The deprecated code will be removed from Drake on or after {}.",
message, missing_period ? "." : "", removal_date);
const char* const is_error = std::getenv(kEnvDrakeDeprecationIsError);
if (is_error != nullptr && std::string_view(is_error) == "1") {
throw DeprecationWarning(full_message);
} else {
log()->warn(full_message);
}
// If a Drake developer made a mistake, we need to fail-fast but it's better
// to have at least printed the warning first.
DRAKE_THROW_UNLESS(removal_date.size() == 10);
DRAKE_THROW_UNLESS(!message.empty());
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/eigen_autodiff_types.h | #pragma once
/// @file
/// This file contains abbreviated definitions for certain uses of
/// AutoDiffScalar that are commonly used in Drake.
/// @see also eigen_types.h
#ifndef DRAKE_COMMON_AUTODIFF_HEADER
// TODO(soonho-tri): Change to #error.
#warning Do not directly include this file. Include "drake/common/autodiff.h".
#endif
#include <type_traits>
#include <Eigen/Dense>
#include "drake/common/eigen_types.h"
namespace drake {
/// An autodiff variable with a dynamic number of partials.
using AutoDiffXd = Eigen::AutoDiffScalar<Eigen::VectorXd>;
// TODO(hongkai-dai): Recursive template to get arbitrary gradient order.
/// An autodiff variable with `num_vars` partials.
template <int num_vars>
using AutoDiffd = Eigen::AutoDiffScalar<Eigen::Matrix<double, num_vars, 1> >;
/// A vector of `rows` autodiff variables, each with `num_vars` partials.
template <int num_vars, int rows>
using AutoDiffVecd = Eigen::Matrix<AutoDiffd<num_vars>, rows, 1>;
/// A dynamic-sized vector of autodiff variables, each with a dynamic-sized
/// vector of partials.
typedef AutoDiffVecd<Eigen::Dynamic, Eigen::Dynamic> AutoDiffVecXd;
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/string_set.h | #pragma once
#include <functional>
#include <set>
#include <string>
namespace drake {
/** Like `std::set<std::string>`, but with better defaults than the plain
`std::set<std::string>` spelling. We need `std::less<void>` as the comparison
function so that `std::string_view` and `const char*` can be used as lookup keys
without copying them to a `std::string`. */
using string_set = std::set<std::string, std::less<void>>;
/** Like `std::multiset<std::string>`, but with better defaults than the plain
`std::multiset<std::string>` spelling. We need `std::less<void>` as the
comparison function so that `std::string_view` and `const char*` can be used as
lookup keys without copying them to a `std::string`. */
using string_multiset = std::multiset<std::string, std::less<void>>;
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/sha256.cc | #include "drake/common/sha256.h"
#include <istream>
#include <iterator>
#include <utility>
#include <picosha2.h>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
namespace drake {
Sha256 Sha256::Checksum(std::string_view data) {
Sha256 result;
static_assert(sizeof(bytes_) == picosha2::k_digest_size);
picosha2::hash256(data, result.bytes_);
return result;
}
Sha256 Sha256::Checksum(std::istream* stream) {
DRAKE_THROW_UNLESS(stream != nullptr);
Sha256 result;
static_assert(sizeof(bytes_) == picosha2::k_digest_size);
picosha2::hash256(std::istreambuf_iterator<char>(*stream),
std::istreambuf_iterator<char>(), result.bytes_);
return result;
}
namespace {
/* Converts a hex char like '4' to its integer value 4.
On error, overwrites `success` with `false`; otherwise, leaves it unchanged. */
uint8_t ParseNibble(char nibble, bool* success) {
DRAKE_ASSERT(success != nullptr);
if (nibble >= '0' && nibble <= '9') {
return nibble - '0';
}
if (nibble >= 'a' && nibble <= 'f') {
return nibble - 'a' + 10;
}
if (nibble >= 'A' && nibble <= 'F') {
return nibble - 'A' + 10;
}
*success = false;
return 0;
}
/* Converts a two-digit hex string like "a0" to its integer value 0xa0.
On error, overwrites `success` with `false`; otherwise, leaves it unchanged. */
uint8_t ParseByte(std::string_view input, bool* success) {
const uint8_t hi = ParseNibble(input[0], success);
const uint8_t lo = ParseNibble(input[1], success);
return (hi << 4) | lo;
}
} // namespace
std::optional<Sha256> Sha256::Parse(std::string_view sha256) {
std::optional<Sha256> result;
constexpr int kNumBytes = sizeof(result->bytes_);
constexpr int kNumHexDigits = kNumBytes * 2;
if (sha256.size() == kNumHexDigits) {
result.emplace();
bool success = true;
for (size_t i = 0; i < kNumBytes; ++i) {
const size_t offset = 2 * i;
result->bytes_[i] =
ParseByte(sha256.substr(offset, offset + 2), &success);
}
if (!success) {
result.reset();
}
}
return result;
}
std::string Sha256::to_string() const {
return picosha2::bytes_to_hex_string(bytes_);
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/double_overloads.h | /// @file
/// Provides necessary operations on double to have it as a ScalarType in drake.
#pragma once
namespace drake {
/// Provides if-then-else expression for double. The value returned by the
/// if-then-else expression is @p v_then if @p f_cond is @c true. Otherwise, it
/// returns @p v_else.
/// The semantics is similar but not exactly the same as C++'s conditional
/// expression constructed by its ternary operator, @c ?:. In
/// <tt>if_then_else(f_cond, v_then, v_else)</tt>, both of @p v_then and @p
/// v_else are evaluated regardless of the evaluation of @p f_cond. In contrast,
/// only one of @p v_then or @p v_else is evaluated in C++'s conditional
/// expression <tt>f_cond ? v_then : v_else</tt>.
inline double if_then_else(bool f_cond, double v_then, double v_else) {
return f_cond ? v_then : v_else;
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/resource_tool.cc | #include <iostream>
#include <gflags/gflags.h>
#include "drake/common/find_resource.h"
DEFINE_string(
print_resource_path, "",
"Given the relative path of a resource within Drake, e.g., "
"`drake/examples/pendulum/Pendulum.urdf`, find the resource and print its "
"absolute path, e.g., `/home/user/drake/examples/pendulum/Pendulum.urdf`");
DEFINE_bool(
print_resource_root_environment_variable_name, false,
"Print the name of the environment variable that provides the "
"first place where this tool attempts to look. This flag cannot be used "
"in combination with the other flags.");
namespace drake {
namespace {
int main(int argc, char* argv[]) {
gflags::SetUsageMessage("Find Drake-related resources");
gflags::ParseCommandLineFlags(&argc, &argv, true);
// The user must supply exactly one of --print_resource_path or
// --print_resource_root_environment_variable_name.
const int num_commands =
(FLAGS_print_resource_path.empty() ? 0 : 1) +
(FLAGS_print_resource_root_environment_variable_name ? 1 : 0);
if (num_commands != 1) {
gflags::ShowUsageWithFlags(argv[0]);
return 1;
}
if (FLAGS_print_resource_root_environment_variable_name) {
std::cout << drake::kDrakeResourceRootEnvironmentVariableName << "\n";
return 0;
}
const FindResourceResult& result = FindResource(FLAGS_print_resource_path);
if (result.get_absolute_path()) {
std::cout << *result.get_absolute_path() << "\n";
return 0;
}
std::cerr << "resource_tool: " << result.get_error_message().value() << "\n";
return 1;
}
} // namespace
} // namespace drake
int main(int argc, char* argv[]) {
return drake::main(argc, argv);
}
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/timer.cc | #include "common/timer.h"
namespace drake {
SteadyTimer::SteadyTimer() {
Start();
}
void SteadyTimer::Start() {
start_time_ = clock::now();
}
double SteadyTimer::Tick() {
return std::chrono::duration<double>(clock::now() - start_time_).count();
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/BUILD.bazel | load("//tools/install:install.bzl", "install")
load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_binary",
"drake_cc_googletest",
"drake_cc_library",
"drake_cc_package_library",
"drake_cc_test",
)
load(
"//tools/skylark:drake_py.bzl",
"drake_py_binary",
"drake_py_unittest",
)
package(default_visibility = ["//visibility:public"])
drake_cc_package_library(
name = "common",
visibility = ["//visibility:public"],
deps = [
":autodiff",
":bit_cast",
":cond",
":copyable_unique_ptr",
":default_scalars",
":diagnostic_policy",
":double",
":drake_bool",
":drake_export",
":drake_path",
":dummy_value",
":essential",
":extract_double",
":find_resource",
":find_runfiles",
":fmt",
":hash",
":identifier",
":is_approx_equal_abstol",
":is_cloneable",
":is_less_than_comparable",
":name_value",
":network_policy",
":nice_type_name",
":overloaded",
":parallelism",
":pointer_cast",
":polynomial",
":random",
":reset_after_move",
":reset_on_copy",
":scope_exit",
":scoped_singleton",
":sha256",
":sorted_pair",
":string_container",
":temp_directory",
":timer",
":type_safe_index",
":unused",
":value",
],
)
drake_cc_library(
name = "fmt",
srcs = [
"fmt_eigen.cc",
],
hdrs = [
"fmt.h",
"fmt_eigen.h",
"fmt_ostream.h",
],
visibility = ["//common/test_utilities:__pkg__"],
deps = [
"@eigen",
"@fmt",
],
)
# A library of things that EVERYONE should want and MUST EAT.
# Be appropriately hesitant when adding new things here.
drake_cc_library(
name = "essential",
srcs = [
"drake_assert_and_throw.cc",
"drake_deprecated.cc",
"text_logging.cc",
],
hdrs = [
"constants.h",
"drake_assert.h",
"drake_assertion_error.h",
"drake_copyable.h",
"drake_deprecated.h",
"drake_throw.h",
"eigen_types.h",
"never_destroyed.h",
"ssize.h",
"text_logging.h",
],
deps = [
":fmt",
"@eigen",
"@fmt",
"@spdlog",
],
)
drake_cc_library(
name = "bit_cast",
hdrs = ["bit_cast.h"],
)
# Specific traits and operators that are relevant to all ScalarTypes.
drake_cc_library(
name = "cond",
srcs = ["cond.cc"],
hdrs = ["cond.h"],
deps = [
":double",
],
)
drake_cc_library(
name = "drake_bool",
hdrs = [
"drake_bool.h",
],
deps = [
":autodiff",
":cond",
":double",
":essential",
],
)
drake_cc_library(
name = "dummy_value",
hdrs = ["dummy_value.h"],
)
# Drake's specific ScalarType-providing libraries.
drake_cc_library(
name = "double",
srcs = ["double_overloads.cc"],
hdrs = ["double_overloads.h"],
)
drake_cc_library(
name = "autodiff",
hdrs = [
"autodiff.h",
"autodiff_overloads.h",
"autodiffxd.h",
"eigen_autodiff_types.h",
],
deps = [
":cond",
":dummy_value",
":essential",
],
)
drake_cc_library(
name = "diagnostic_policy",
srcs = ["diagnostic_policy.cc"],
hdrs = ["diagnostic_policy.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "extract_double",
hdrs = ["extract_double.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "hash",
srcs = ["hash.cc"],
hdrs = ["hash.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "polynomial",
srcs = ["polynomial.cc"],
hdrs = ["polynomial.h"],
deps = [
":autodiff",
":default_scalars",
":essential",
"//common/symbolic:expression",
],
)
drake_cc_library(
name = "default_scalars",
hdrs = ["default_scalars.h"],
deps = [
":autodiff",
":essential",
"//common/symbolic:expression",
],
)
# Miscellaneous utilities.
drake_cc_library(
name = "drake_export",
hdrs = ["drake_export.h"],
)
drake_cc_library(
name = "identifier",
srcs = ["identifier.cc"],
hdrs = ["identifier.h"],
deps = [
":essential",
":hash",
],
)
DRAKE_RESOURCE_SENTINEL = "//:.drake-find_resource-sentinel"
drake_cc_library(
name = "is_less_than_comparable",
hdrs = [
"is_less_than_comparable.h",
],
deps = [
":unused",
],
)
drake_cc_library(
name = "sorted_pair",
srcs = [
"sorted_pair.cc",
],
hdrs = [
"sorted_pair.h",
],
deps = [
":hash",
":is_less_than_comparable",
],
)
# Provides an anchor for finding resources.
drake_cc_binary(
name = "libdrake_marker.so",
srcs = [
"drake_marker.cc",
"drake_marker.h",
],
linkopts = select({
"//tools/cc_toolchain:linux": ["-Wl,-soname,libdrake_marker.so"],
"//conditions:default": [],
}),
linkshared = 1,
linkstatic = 1,
visibility = ["//visibility:private"],
)
drake_cc_library(
name = "drake_marker_shared_library",
srcs = ["libdrake_marker.so"],
hdrs = ["drake_marker.h"],
install_hdrs_exclude = ["drake_marker.h"],
tags = ["exclude_from_package"],
visibility = ["//tools/install/libdrake:__pkg__"],
)
drake_cc_library(
name = "find_cache",
srcs = ["find_cache.cc"],
hdrs = ["find_cache.h"],
internal = True,
visibility = ["//:__subpackages__"],
interface_deps = [],
deps = [
":essential",
],
)
drake_cc_library(
name = "find_runfiles",
srcs = ["find_runfiles.cc"],
hdrs = ["find_runfiles.h"],
interface_deps = [],
deps = [
":essential",
"@bazel_tools//tools/cpp/runfiles",
],
)
drake_cc_library(
name = "find_resource",
srcs = [
"find_loaded_library.cc",
"find_resource.cc",
],
hdrs = [
"find_loaded_library.h",
"find_resource.h",
],
data = [
DRAKE_RESOURCE_SENTINEL,
],
# for libdrake.so path on linux
linkopts = select({
"//tools/cc_toolchain:linux": ["-ldl"],
"//conditions:default": [],
}),
interface_deps = [
":essential",
],
deps = [
":drake_marker_shared_library",
":find_runfiles",
],
)
drake_cc_library(
name = "drake_path",
srcs = ["drake_path.cc"],
hdrs = ["drake_path.h"],
data = [
DRAKE_RESOURCE_SENTINEL,
],
visibility = ["//tools/install/libdrake:__pkg__"],
interface_deps = [],
deps = [
":find_resource",
],
)
drake_cc_library(
name = "is_approx_equal_abstol",
hdrs = ["is_approx_equal_abstol.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "name_value",
hdrs = ["name_value.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "network_policy",
srcs = ["network_policy.cc"],
hdrs = ["network_policy.h"],
deps = [
":essential",
],
)
# N.B. This library does not have all of its dependencies declared. Instead,
# it defines only the headers such that it can be used by `pydrake` without
# installing the file. (If we just used `install_hdrs_exclude`, the header
# would not make it into `//:drake_shared_library`.)
drake_cc_library(
name = "nice_type_name_override_header",
hdrs = ["nice_type_name_override.h"],
install_hdrs_exclude = ["nice_type_name_override.h"],
tags = ["exclude_from_package"],
visibility = ["//bindings/pydrake/common:__pkg__"],
)
drake_cc_library(
name = "nice_type_name",
srcs = [
"nice_type_name.cc",
"nice_type_name_override.cc",
],
hdrs = [
"nice_type_name.h",
],
interface_deps = [
":essential",
],
deps = [
":nice_type_name_override_header",
],
)
drake_cc_library(
name = "overloaded",
hdrs = ["overloaded.h"],
)
drake_cc_library(
name = "parallelism",
srcs = ["parallelism.cc"],
hdrs = ["parallelism.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "is_cloneable",
hdrs = ["is_cloneable.h"],
)
drake_cc_library(
name = "copyable_unique_ptr",
hdrs = ["copyable_unique_ptr.h"],
deps = [":is_cloneable"],
)
drake_cc_library(
name = "random",
srcs = ["random.cc"],
hdrs = ["random.h"],
interface_deps = [
":copyable_unique_ptr",
":essential",
":extract_double",
],
deps = [
":autodiff",
],
)
drake_cc_library(
name = "reset_after_move",
hdrs = ["reset_after_move.h"],
)
drake_cc_library(
name = "reset_on_copy",
hdrs = ["reset_on_copy.h"],
)
drake_cc_library(
name = "sha256",
srcs = ["sha256.cc"],
hdrs = ["sha256.h"],
interface_deps = [
":essential",
],
deps = [
"@picosha2_internal//:picosha2",
],
)
drake_cc_library(
name = "pointer_cast",
srcs = ["pointer_cast.cc"],
hdrs = ["pointer_cast.h"],
deps = [
":nice_type_name",
],
)
drake_cc_library(
name = "temp_directory",
srcs = ["temp_directory.cc"],
hdrs = ["temp_directory.h"],
interface_deps = [
":essential",
],
deps = [],
)
# This is a Drake-internal utility for use only as a direct dependency
# of executable (drake_cc_binary) targets. Thus, we exclude it from
# the ":common" package library and from libdrake.
drake_cc_library(
name = "add_text_logging_gflags",
srcs = ["add_text_logging_gflags.cc"],
tags = [
"exclude_from_libdrake",
"exclude_from_package",
],
visibility = ["//:__subpackages__"],
deps = [
":essential",
":unused",
"@gflags",
],
alwayslink = 1,
)
drake_cc_library(
name = "type_safe_index",
srcs = ["type_safe_index.cc"],
hdrs = ["type_safe_index.h"],
deps = [
":essential",
":hash",
":nice_type_name",
],
)
drake_cc_library(
name = "unused",
hdrs = ["unused.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "scope_exit",
hdrs = ["scope_exit.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "scoped_singleton",
hdrs = ["scoped_singleton.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "string_container",
hdrs = [
"string_hash.h",
"string_map.h",
"string_set.h",
"string_unordered_map.h",
"string_unordered_set.h",
],
)
drake_cc_library(
name = "timer",
srcs = ["timer.cc"],
hdrs = ["timer.h"],
deps = [
":essential",
],
)
drake_cc_library(
name = "value",
srcs = ["value.cc"],
hdrs = ["value.h"],
deps = [
":copyable_unique_ptr",
":essential",
":hash",
":is_cloneable",
":nice_type_name",
],
)
drake_cc_binary(
name = "resource_tool",
srcs = ["resource_tool.cc"],
deps = [
":add_text_logging_gflags",
":essential",
":find_resource",
],
)
install(
name = "install_drake_marker",
targets = [":libdrake_marker.so"],
)
install(
name = "install",
install_tests = [":test/resource_tool_installed_test.py"],
targets = [
":libdrake_marker.so",
":resource_tool",
],
runtime_dest = "share/drake/common",
data_dest = "share/drake",
guess_data = "WORKSPACE",
allowed_externals = [DRAKE_RESOURCE_SENTINEL],
deps = [
":install_drake_marker",
],
)
# === test/ ===
drake_cc_googletest(
name = "autodiffxd_test",
# The following `autodiffxd_*_test.cc` files were in a single
# `autodiffxd_test.cc`. We found that it takes more than 150 sec to build
# this test. So we split it into multiple .cc files. We observed about
# 8x speed-up.
srcs = [
"test/autodiffxd_abs2_test.cc",
"test/autodiffxd_abs_test.cc",
"test/autodiffxd_acos_test.cc",
"test/autodiffxd_addition_test.cc",
"test/autodiffxd_asin_test.cc",
"test/autodiffxd_atan2_test.cc",
"test/autodiffxd_atan_test.cc",
"test/autodiffxd_cos_test.cc",
"test/autodiffxd_cosh_test.cc",
"test/autodiffxd_division_test.cc",
"test/autodiffxd_exp_test.cc",
"test/autodiffxd_log_test.cc",
"test/autodiffxd_max_test.cc",
"test/autodiffxd_min_test.cc",
"test/autodiffxd_multiplication_test.cc",
"test/autodiffxd_pow_test.cc",
"test/autodiffxd_sin_test.cc",
"test/autodiffxd_sinh_test.cc",
"test/autodiffxd_sqrt_test.cc",
"test/autodiffxd_subtraction_test.cc",
"test/autodiffxd_tan_test.cc",
"test/autodiffxd_tanh_test.cc",
],
copts = [
# The test fixture at //common/ad:standard_operations_test_h requires
# some configuration for the specific autodiff class to be tested.
"-DDRAKE_AUTODIFFXD_DUT=drake::AutoDiffXd",
"-DStandardOperationsTest=AutoDiffXdTest",
],
deps = [
":autodiff",
"//common/ad:standard_operations_test_h",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "autodiffxd_heap_test",
deps = [
":autodiff",
"//common/test_utilities:limit_malloc",
],
)
drake_cc_googletest(
name = "autodiff_overloads_test",
deps = [
":autodiff",
":essential",
":extract_double",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "bit_cast_test",
deps = [
":bit_cast",
],
)
drake_cc_googletest(
name = "ssize_test",
deps = [
":essential",
],
)
drake_cc_googletest(
name = "drake_bool_test",
deps = [
":drake_bool",
"//common/symbolic:expression",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_googletest(
name = "random_test",
deps = [
":autodiff",
":random",
"//common/test_utilities:limit_malloc",
],
)
drake_cc_googletest(
name = "reset_after_move_test",
deps = [
":reset_after_move",
],
)
drake_cc_googletest(
name = "reset_on_copy_test",
deps = [
":reset_on_copy",
],
)
drake_cc_googletest(
name = "sha256_test",
deps = [
":sha256",
":temp_directory",
],
)
drake_cc_googletest(
name = "pointer_cast_test",
deps = [
":pointer_cast",
"//common/test_utilities",
],
)
drake_cc_googletest(
name = "cond_test",
deps = [
":cond",
],
)
drake_cc_googletest(
name = "double_overloads_test",
deps = [
":cond",
":double",
":essential",
],
)
# Functional test of DRAKE_ASSERT at runtime.
drake_cc_googletest(
name = "drake_assert_test",
deps = [
":essential",
],
)
# Same, but with assertions forced enabled.
drake_cc_googletest(
name = "drake_assert_test_enabled",
srcs = ["test/drake_assert_test.cc"],
copts = [
"-DDRAKE_ENABLE_ASSERTS",
"-UDRAKE_DISABLE_ASSERTS",
],
deps = [
":essential",
],
)
# Same, but with assertions forced disabled.
drake_cc_googletest(
name = "drake_assert_test_disabled",
srcs = ["test/drake_assert_test.cc"],
copts = [
"-UDRAKE_ENABLE_ASSERTS",
"-DDRAKE_DISABLE_ASSERTS",
],
deps = [
":essential",
],
)
drake_cc_googletest(
name = "drake_copyable_test",
deps = [
":essential",
],
)
drake_cc_googletest(
name = "is_cloneable_test",
deps = [
":is_cloneable",
],
)
drake_cc_googletest(
name = "copyable_unique_ptr_test",
deps = [
":copyable_unique_ptr",
"//common:unused",
"//common/test_utilities:is_dynamic_castable",
],
)
drake_cc_googletest(
name = "diagnostic_policy_test",
deps = [
":diagnostic_policy",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "drake_deprecated_test",
# Remove spurious warnings from the default build output.
copts = ["-Wno-deprecated-declarations"],
deps = [
":essential",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "drake_throw_test",
deps = [
":essential",
"//common/test_utilities:expect_no_throw",
],
)
drake_cc_googletest(
name = "dummy_value_test",
deps = [
":dummy_value",
],
)
drake_cc_googletest(
name = "eigen_types_test",
deps = [
":essential",
":nice_type_name",
"//common/test_utilities:expect_no_throw",
],
)
drake_cc_googletest(
name = "hash_test",
deps = [
":hash",
],
)
drake_cc_googletest(
name = "identifier_test",
deps = [
":identifier",
":sorted_pair",
"//common/test_utilities:expect_no_throw",
"//common/test_utilities:expect_throws_message",
"@abseil_cpp_internal//absl/container:flat_hash_set",
],
)
drake_cc_googletest(
name = "is_less_than_comparable_test",
deps = [
":is_less_than_comparable",
],
)
drake_cc_googletest(
name = "sorted_pair_test",
deps = [
":sorted_pair",
],
)
drake_cc_googletest(
name = "extract_double_test",
deps = [
":essential",
":extract_double",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "find_cache_test",
deps = [
":find_cache",
":temp_directory",
],
)
drake_cc_googletest(
name = "find_resource_test",
data = [
"test/find_resource_test_data.txt",
],
deps = [
":drake_path",
":find_resource",
"//common/test_utilities:expect_no_throw",
"//common/test_utilities:expect_throws_message",
],
)
# Test library for `find_loaded_library_test`.
drake_cc_binary(
name = "lib_is_real.so",
testonly = 1,
srcs = [
"test/lib_is_real.cc",
],
linkshared = 1,
visibility = ["//visibility:private"],
)
drake_cc_googletest(
name = "find_loaded_library_test",
srcs = [
"test/find_loaded_library_test.cc",
":lib_is_real.so",
],
deps = [
":find_resource",
],
)
drake_cc_googletest(
name = "find_runfiles_test",
data = [
"test/find_resource_test_data.txt",
],
deps = [
":find_runfiles",
":temp_directory",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "find_runfiles_fail_test",
deps = [
":find_runfiles",
],
)
drake_py_unittest(
name = "find_runfiles_subprocess_test",
data = [
":find_runfiles_test",
],
)
drake_cc_googletest(
name = "find_runfiles_stub_test",
srcs = [
"find_runfiles.h",
"find_runfiles_stub.cc",
"test/find_runfiles_stub_test.cc",
],
)
drake_cc_googletest(
name = "fmt_test",
deps = [
":essential",
],
)
drake_cc_googletest(
name = "fmt_eigen_test",
deps = [
":essential",
],
)
drake_cc_googletest(
name = "fmt_ostream_test",
deps = [
":essential",
],
)
drake_cc_googletest(
name = "is_approx_equal_abstol_test",
deps = [
":essential",
":is_approx_equal_abstol",
],
)
drake_cc_googletest(
name = "name_value_test",
deps = [
":name_value",
],
)
drake_cc_googletest(
name = "network_policy_test",
deps = [
":network_policy",
],
)
drake_cc_googletest(
name = "never_destroyed_test",
deps = [
":essential",
],
)
drake_cc_googletest(
name = "nice_type_name_test",
deps = [
":autodiff",
":essential",
":identifier",
":nice_type_name",
":nice_type_name_override_header",
],
)
drake_cc_googletest(
name = "openmp_test",
num_threads = 2,
deps = [
"//common:essential",
],
)
drake_cc_googletest(
name = "overloaded_test",
deps = [
"//common:overloaded",
],
)
drake_cc_googletest(
name = "parallelism_test",
num_threads = 2,
deps = [
":parallelism",
],
)
drake_cc_googletest(
name = "polynomial_test",
deps = [
":essential",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_no_throw",
"//common/test_utilities:random_polynomial_matrix",
],
)
drake_cc_googletest(
name = "string_container_test",
deps = [
":string_container",
"//common/test_utilities:limit_malloc",
],
)
drake_cc_googletest(
name = "temp_directory_test",
# Run each test case in a different process, to avoid environment variable
# changes from one accidentally polluting the others.
shard_count = 3,
deps = [
":temp_directory",
],
)
# This version of text_logging_test is compiled with HAVE_SPDLOG enabled,
# because that is what Drake's WORKSPACE provides for the @spdlog external.
drake_cc_googletest(
name = "text_logging_test",
defines = [
"TEXT_LOGGING_TEST_SPDLOG=1",
],
use_default_main = False,
deps = [
":essential",
],
)
# Likewise (to the above test) for the ostream variation.
drake_cc_googletest(
name = "text_logging_ostream_test",
defines = [
"TEXT_LOGGING_TEST_SPDLOG=1",
],
use_default_main = False,
deps = [
":essential",
],
)
# This version of text_logging_test re-compiles all source files without
# defining HAVE_SPDLOG, to ensure that the no-op stubs behave as desired.
drake_cc_googletest(
name = "text_logging_no_spdlog_test",
srcs = [
"drake_copyable.h",
"fmt.h",
"never_destroyed.h",
"test/text_logging_test.cc",
"text_logging.cc",
"text_logging.h",
],
defines = [
"TEXT_LOGGING_TEST_SPDLOG=0",
],
use_default_main = False,
deps = [
"@fmt",
],
)
# Likewise (to the above test) for the ostream variation.
drake_cc_googletest(
name = "text_logging_ostream_no_spdlog_test",
srcs = [
"drake_copyable.h",
"fmt.h",
"never_destroyed.h",
"test/text_logging_ostream_test.cc",
"text_logging.cc",
"text_logging.h",
],
defines = [
"TEXT_LOGGING_TEST_SPDLOG=0",
],
use_default_main = False,
deps = [
"@fmt",
],
)
drake_cc_googletest(
name = "type_safe_index_test",
deps = [
":type_safe_index",
"//common:sorted_pair",
"//common/test_utilities:expect_no_throw",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "eigen_autodiff_types_test",
deps = [":autodiff"],
)
drake_cc_googletest(
name = "scope_exit_test",
deps = [
":scope_exit",
],
)
drake_cc_googletest(
name = "scoped_singleton_test",
deps = [
":scoped_singleton",
],
)
drake_cc_googletest(
name = "timer_test",
flaky = True,
deps = [
":timer",
],
)
drake_cc_googletest(
name = "drake_cc_googletest_main_test_device",
args = ["--magic_number=1.0"],
)
# Run test/drake_cc_googletest_main_test.py, a unit test written in Python that
# covers the test/drake_cc_googletest_main.cc software.
drake_py_unittest(
name = "drake_cc_googletest_main_test",
args = ["$(location :drake_cc_googletest_main_test_device)"],
data = [":drake_cc_googletest_main_test_device"],
)
drake_py_unittest(
name = "resource_tool_test",
args = [
"$(location :resource_tool)",
],
data = [
"test/resource_tool_test_data.txt",
":resource_tool",
"//examples/pendulum:models",
],
)
drake_cc_googletest(
name = "value_test",
deps = [
":value",
"//common:essential",
"//common/test_utilities:expect_no_throw",
"//common/test_utilities:expect_throws_message",
"//systems/framework/test_utilities:my_vector",
],
)
drake_cc_googletest(
name = "scalar_casting_test",
deps = [
":autodiff",
":extract_double",
"//common/symbolic:expression",
],
)
add_lint_tests(
enable_clang_format_lint = False,
python_lint_extra_srcs = [
":test/resource_tool_installed_test.py",
],
)
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/identifier.cc | #include "drake/common/identifier.h"
#include <atomic>
namespace drake {
namespace internal {
namespace {
// Even though this is a mutable global variable, it does not generate any
// object code for initialization, so it is safe to use even without being
// wrapped within a never_destroyed<>. Note that it is initialized to zero
// at the start of the program via zero-initialization; for details, see
// https://en.cppreference.com/w/cpp/atomic/atomic/atomic.
static std::atomic<int64_t> g_prior_identifier;
} // namespace
int64_t get_new_identifier() {
// Note that 0 is reserved for the uninitialized Identifier created by the
// default constructor, so we have an invariant that get_new_identifier() > 0.
// Overflowing an int64_t is not a hazard we need to worry about.
return ++g_prior_identifier;
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/scope_exit.h | #pragma once
#include <functional>
#include <utility>
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
namespace drake {
/// Helper class to create a scope exit guard -- an object that when destroyed
/// runs `func`. This is useful to apply RAII to third-party code that only
/// supports manual acquire and release operations.
///
/// Example:
///
/// @code
/// void some_function() {
/// void* foo = ::malloc(10);
/// ScopeExit guard([foo]() {
/// ::free(foo);
/// });
///
/// // ...
/// if (condition) { throw std::runtime_error("..."); }
/// // ...
/// }
/// @endcode
///
/// Here, the allocation of `foo` will always be free'd no matter whether
/// `some_function` returns normally or via an exception.
class ScopeExit final {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ScopeExit);
/// Creates a resource that will call `func` when destroyed. Note that
/// `func()` should not throw an exception, since it will typically be
/// invoked during stack unwinding.
explicit ScopeExit(std::function<void()> func) : func_(std::move(func)) {
DRAKE_THROW_UNLESS(func_ != nullptr);
}
/// Invokes the `func` that was passed into the constructor, unless this has
/// been disarmed.
~ScopeExit() {
if (func_) {
func_();
}
}
/// Disarms this guard, so that the destructor has no effect.
void Disarm() { func_ = nullptr; }
private:
std::function<void()> func_;
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_marker.h | #pragma once
/// @file
/// This is an internal (not installed) header. Do not use this outside of
/// `find_resource.cc`.
namespace drake {
namespace internal {
// Provides a concrete object to ensure that this marker library is linked.
// This returns a simple magic constant to ensure the library was loaded
// correctly.
int drake_marker_lib_check();
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/doxygen_cxx.h | /// @defgroup cxx C++ support features
/// @ingroup technical_notes
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/type_safe_index.cc | #include "drake/common/type_safe_index.h"
#include <stdexcept>
#include "drake/common/nice_type_name.h"
namespace drake {
namespace internal {
void ThrowTypeSafeIndexAssertValidFailed(const std::type_info& type,
const char* source) {
throw std::logic_error(fmt::format(
"{} Type \"{}\", has an invalid value; it must lie in the range "
"[0, 2³¹ - 1].",
source, NiceTypeName::Get(type)));
}
void ThrowTypeSafeIndexAssertNoOverflowFailed(const std::type_info& type,
const char* source) {
throw std::logic_error(fmt::format("{} Type \"{}\", has overflowed.", source,
NiceTypeName::Get(type)));
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/copyable_unique_ptr.h | #pragma once
/* Portions copyright (c) 2015 Stanford University and the Authors.
Authors: Michael Sherman
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain a
copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
(Adapted from Simbody's ClonePtr class.)
*/
#include <cstddef>
#include <memory>
#include <utility>
#include "drake/common/drake_assert.h"
#include "drake/common/fmt.h"
namespace drake {
// TODO(SeanCurtis-TRI): Consider extending this to add the Deleter as well.
/** A smart pointer with deep copy semantics.
This is _similar_ to `std::unique_ptr` in that it does not permit shared
ownership of the contained object. However, unlike `std::unique_ptr`,
%copyable_unique_ptr supports copy and assignment operations, by insisting that
the contained object be "copyable". To be copyable, the class must have either
an accessible copy constructor, or it must have an accessible clone method
with signature @code
std::unique_ptr<Foo> Clone() const;
@endcode
where Foo is the type of the managed object. By "accessible" we mean either
that the copy constructor or clone method is public, or
`friend copyable_unique_ptr<Foo>;` appears in Foo's class declaration.
<!-- Developer note: if you change or extend the definition of an acceptable
clone method here, be sure to consider whether drake::is_cloneable should
be changed as well. -->
Generally, the API is modeled as closely as possible on the C++ standard
`std::unique_ptr` API and %copyable_unique_ptr<T> is interoperable with
`unique_ptr<T>` wherever that makes sense. However, there are some differences:
1. It always uses a default deleter.
2. There is no array version.
3. To allow for future copy-on-write optimizations, there is a distinction
between writable and const access, the get() method is modified to return
only a const pointer, with get_mutable() added to return a writable pointer.
Furthermore, dereferencing (operator*()) a mutable pointer will give a
mutable reference (in so far as T is not declared const), and dereferencing
a const pointer will give a const reference.
This class is entirely inline and has no computational or space overhead except
when copying is required; it contains just a single pointer and does no
reference counting.
__Usage__
In the simplest use case, the instantiation type will match the type of object
it references, e.g.:
@code
copyable_unique_ptr<Foo> ptr = make_unique<Foo>(...);
@endcode
In this case, as long `Foo` is deemed compatible, the behavior will be as
expected, i.e., when `ptr` copies, it will contain a reference to a new
instance of `Foo`.
%copyable_unique_ptr can also be used with polymorphic classes -- a
%copyable_unique_ptr, instantiated on a _base_ class, references an
instance of a _derived_ class. When copying the object, we would want the copy
to likewise contain an instance of the derived class. For example:
@code
copyable_unique_ptr<Base> cu_ptr = make_unique<Derived>();
copyable_unique_ptr<Base> other_cu_ptr = cu_ptr; // Triggers a copy.
is_dynamic_castable<Derived>(other_cu_ptr.get()); // Should be true.
@endcode
This works for well-designed polymorphic classes.
@warning Ill-formed polymorphic classes can lead to fatal type slicing of the
referenced object, such that the new copy contains an instance of `Base`
instead of `Derived`. Some mistakes that would lead to this degenerate
behavior:
- The `Base` class's Clone() implementation does not invoke the `Derived`
class's implementation of a suitable virtual method.
<!--
For future developers:
- the copyability of a base class does *not* imply anything about the
copyability of a derived class. In other words, `copyable_unique_ptr<Base>`
can be compilable while `copyable_unique_ptr<Derived>` is not.
- Given the pointer `copyable_unique_ptr<Base> ptr(new Derived())`, even if
this copies "correctly" (such that the copy contains an instance of
`Derived`), this does _not_ imply that `copyable_unique_ptr<Derived>` is
compilable.
-->
@tparam T The type of the contained object, which *must* be copyable as
defined above. May be an abstract or concrete type.
*/
template <typename T>
class copyable_unique_ptr : public std::unique_ptr<T> {
public:
/** @name Constructors */
/**@{*/
/** Default constructor stores a `nullptr`. No heap allocation is performed.
The empty() method will return true when called on a default-constructed
%copyable_unique_ptr. */
copyable_unique_ptr() noexcept : std::unique_ptr<T>() {}
/** Given a raw pointer to a writable heap-allocated object, take over
ownership of that object. No copying occurs. */
explicit copyable_unique_ptr(T* raw) noexcept : std::unique_ptr<T>(raw) {}
/** Constructs a unique instance of T as a copy of the provided model value.
*/
explicit copyable_unique_ptr(const T& value)
: std::unique_ptr<T>(CopyOrNull(&value)) {}
/** Copy constructor is deep; the new %copyable_unique_ptr object contains a
new copy of the object in the source, created via the source object's
copy constructor or `Clone()` method. If the source container is empty this
one will be empty also. */
copyable_unique_ptr(const copyable_unique_ptr& cu_ptr)
: std::unique_ptr<T>(CopyOrNull(cu_ptr.get())) {}
/** Copy constructor from a standard `unique_ptr` of _compatible_ type. The
copy is deep; the new %copyable_unique_ptr object contains a new copy of the
object in the source, created via the source object's copy constructor or
`Clone()` method. If the source container is empty this one will be empty
also. */
template <typename U>
explicit copyable_unique_ptr(const std::unique_ptr<U>& u_ptr)
: std::unique_ptr<T>(CopyOrNull(u_ptr.get())) {}
/** Move constructor is very fast and leaves the source empty. Ownership
is transferred from the source to the new %copyable_unique_ptr. If the source
was empty this one will be empty also. No heap activity occurs. */
copyable_unique_ptr(copyable_unique_ptr&& cu_ptr) noexcept
: std::unique_ptr<T>(cu_ptr.release()) {}
/** Move constructor from a standard `unique_ptr`. The move is very fast and
leaves the source empty. Ownership is transferred from the source to the new
%copyable_unique_ptr. If the source was empty this one will be empty also. No
heap activity occurs. */
explicit copyable_unique_ptr(std::unique_ptr<T>&& u_ptr) noexcept
: std::unique_ptr<T>(u_ptr.release()) {}
/** Move construction from a compatible standard `unique_ptr`. Type `U*` must
be implicitly convertible to type `T*`. Ownership is transferred from the
source to the new %copyable_unique_ptr. If the source was empty this one will
be empty also. No heap activity occurs. */
template <typename U>
explicit copyable_unique_ptr(std::unique_ptr<U>&& u_ptr) noexcept
: std::unique_ptr<T>(u_ptr.release()) {}
/**@}*/
/** @name Assignment */
/**@{*/
/** This form of assignment replaces the currently-held object by
the given source object and takes over ownership of the source object. The
currently-held object (if any) is deleted. */
copyable_unique_ptr& operator=(T* raw) noexcept {
std::unique_ptr<T>::reset(raw);
return *this;
}
/** This form of assignment replaces the currently-held object by a
heap-allocated copy of the source object, created using its copy
constructor or `Clone()` method. The currently-held object (if any) is
deleted. */
copyable_unique_ptr& operator=(const T& ref) {
std::unique_ptr<T>::reset(CopyOrNull(&ref));
return *this;
}
/** Copy assignment from %copyable_unique_ptr replaces the currently-held
object by a copy of the object held in the source container, created using
the source object's copy constructor or `Clone()` method. The currently-held
object (if any) is deleted. If the source container is empty this one will be
empty also after the assignment. Nothing happens if the source and
destination are the same container. */
copyable_unique_ptr& operator=(const copyable_unique_ptr& cu_ptr) {
return operator=(static_cast<const std::unique_ptr<T>&>(cu_ptr));
}
/** Copy assignment from a compatible %copyable_unique_ptr replaces the
currently-held object by a copy of the object held in the source container,
created using the source object's copy constructor or `Clone()` method. The
currently-held object (if any) is deleted. If the source container is empty
this one will be empty also after the assignment. Nothing happens if the
source and destination are the same container. */
template <typename U>
copyable_unique_ptr& operator=(const copyable_unique_ptr<U>& cu_ptr) {
return operator=(static_cast<const std::unique_ptr<U>&>(cu_ptr));
}
/** Copy assignment from a standard `unique_ptr` replaces the
currently-held object by a copy of the object held in the source container,
created using the source object's copy constructor or `Clone()` method. The
currently-held object (if any) is deleted. If the source container is empty
this one will be empty also after the assignment. Nothing happens if the
source and destination are the same container. */
copyable_unique_ptr& operator=(const std::unique_ptr<T>& src) {
if (&src != this) {
// can't be same ptr unless null
DRAKE_DEMAND((get() != src.get()) || !get());
std::unique_ptr<T>::reset(CopyOrNull(src.get()));
}
return *this;
}
/** Copy assignment from a compatible standard `unique_ptr` replaces the
currently-held object by a copy of the object held in the source container,
created using the source object's copy constructor or `Clone()` method. The
currently-held object (if any) is deleted. If the source container is empty
this one will be empty also after the assignment. Nothing happens if the
source and destination are the same container. */
template <typename U>
copyable_unique_ptr& operator=(const std::unique_ptr<U>& u_ptr) {
// can't be same ptr unless null
DRAKE_DEMAND((get() != u_ptr.get()) || !get());
std::unique_ptr<T>::reset(CopyOrNull(u_ptr.get()));
return *this;
}
/** Move assignment replaces the currently-held object by the source object,
leaving the source empty. The currently-held object (if any) is deleted.
The instance is _not_ copied. Nothing happens if the source and destination
are the same containers. */
copyable_unique_ptr& operator=(copyable_unique_ptr&& cu_ptr) noexcept {
std::unique_ptr<T>::reset(cu_ptr.release());
return *this;
}
/** Move assignment replaces the currently-held object by the compatible
source object, leaving the source empty. The currently-held object (if any)
is deleted. The instance is _not_ copied. Nothing happens if the source and
destination are the same containers. */
template <typename U>
copyable_unique_ptr& operator=(copyable_unique_ptr<U>&& cu_ptr) noexcept {
std::unique_ptr<T>::reset(cu_ptr.release());
return *this;
}
/** Move assignment replaces the currently-held object by the source object,
leaving the source empty. The currently-held object (if any) is deleted.
The instance is _not_ copied. Nothing happens if the source and destination
are the same containers. */
copyable_unique_ptr& operator=(std::unique_ptr<T>&& u_ptr) noexcept {
std::unique_ptr<T>::reset(u_ptr.release());
return *this;
}
/** Move assignment replaces the currently-held object by the compatible
source object, leaving the source empty. The currently-held object (if
any) is deleted. The instance is _not_ copied. Nothing happens if the source
and destination are the same containers. */
template <typename U>
copyable_unique_ptr& operator=(std::unique_ptr<U>&& u_ptr) noexcept {
std::unique_ptr<T>::reset(u_ptr.release());
return *this;
}
/**@}*/
/** @name Observers */
/**@{*/
/** Return true if this container is empty, which is the state the container
is in immediately after default construction and various other
operations. */
bool empty() const noexcept { return !(*this); }
/** Return a const pointer to the contained object if any, or `nullptr`.
Note that this is different than `%get()` for the standard smart pointers
like `std::unique_ptr` which return a writable pointer. Use get_mutable()
here for that purpose. */
const T* get() const noexcept { return std::unique_ptr<T>::get(); }
// TODO(SeanCurtis-TRI): Consider adding some debug assertions about whether
// T is const or not. If so, it would be nice to give feedback that calling
// the mutable version makes no sense.
/** Return a writable pointer to the contained object if any, or `nullptr`.
Note that you need write access to this container in order to get write
access to the object it contains.
@warning If %copyable_unique_ptr is instantiated on a const template
parameter (e.g., `copyable_unique_ptr<const Foo>`), then get_mutable()
returns a const pointer. */
T* get_mutable() noexcept { return std::unique_ptr<T>::get(); }
// TODO(15344) We need to shore up this const correctness hole. Rather than an
// is-a relationship, we need some alternative relationship that will provide
// the same functionality but not be upcastable. One possibility is to own
// an unique_ptr and forward various APIs. Another is to implement from
// scratch. The current "is-A" relationship was intended so that the
// copyable_unique_ptr could be used where unique_ptrs are used. What would
// the impact of such a change in the relationship be to Drake and Drake
// users?
/** Return a const reference to the contained object. Note that this is
different from `std::unique_ptr::operator*()` which would return a non-const
reference (if `T` is non-const), even if the container itself is const. For
a const %copyable_unique_ptr will always return a const reference to its
contained value.
@warning Currently %copyable_unique_ptr is a std::unique_ptr. As such, a
const copyable_unique_ptr<Foo> can be upcast to a const unique_ptr<Foo> and
the parent's behavior will provide a mutable reference. This is strongly
discouraged and will break as the implementation of this class changes to
shore up this gap in the const correctness protection.
@pre `this != nullptr` reports `true`. */
const T& operator*() const {
DRAKE_ASSERT(!empty());
return *get();
}
/** Return a writable reference to the contained object (if T is itself not
const). Note that you need write access to this container in order to get
write access to the object it contains.
We *strongly* recommend, that, if dereferencing a %copyable_unique_ptr
without the intention of mutating the underlying value, prefer to dereference
a *const* %copyable_unique_ptr (or use *my_ptr.get()) and not a mutable
%copyable_unique_ptr. As "copy-on-write" behavior is introduced in the
future, this recommended practice will prevent unwanted copies of the
underlying value.
If %copyable_unique_ptr is instantiated on a const template parameter (e.g.,
`copyable_unique_ptr<const Foo>`), then operator*() must return a const
reference.
@pre `this != nullptr` reports `true`. */
T& operator*() {
DRAKE_ASSERT(!empty());
return *get_mutable();
}
/**@}*/
private:
// The can_copy() and can_clone() methods must be defined within the
// copyable_unique_ptr class so that they have the same method access as
// the class does. That way we can use them to determine whether
// copyable_unique_ptr can get access. That precludes using helper classes
// like drake::is_cloneable because those may have different access due to an
// explicit friend declaration giving copyable_unique_ptr<Foo> access to Foo's
// private business. The static_assert below ensures that at least one of
// these must return true.
// SFINAE magic explanation. We're combining several tricks here:
// (1) "..." as a parameter type is a last choice; an exact type match is
// preferred in overload resolution.
// (2) Use a dummy template parameter U that is always just T but defers
// instantiation so that substitution failure is not fatal.
// (3) We construct a non-evaluated copy constructor and Clone method in
// templatized methods to prevent instantiation if the needed method
// doesn't exist or isn't accessible. If instantiation is successful,
// we produce an exact-match method that trumps the "..."-using method.
// (4) Make these constexpr so they can be used in static_assert.
// True iff type T provides a copy constructor that is accessible from
// %copyable_unique_ptr<T>. Invoke with `can_copy(1)`; the argument is used
// to select the right method.
static constexpr bool can_copy(...) { return false; }
// If this instantiates successfully it will be the preferred method called
// when an integer argument is provided.
template <typename U = T>
static constexpr std::enable_if_t<
std::is_same_v<decltype(U(std::declval<const U&>())), U>, bool>
can_copy(int) {
return true;
}
// True iff type T provides a `Clone()` method with the appropriate
// signature (see class documentation) that is accessible from
// %copyable_unique_ptr<T>. Invoke with `can_clone(1)`; the argument is used
// to select the right method.
static constexpr bool can_clone(...) { return false; }
// If this instantiates successfully it will be the preferred method called
// when an integer argument is provide.
template <typename U = T>
static constexpr std::enable_if_t<
std::is_same_v<decltype(std::declval<const U>().Clone()),
std::unique_ptr<std::remove_const_t<U>>>,
bool>
can_clone(int) {
return true;
}
// If src is non-null, clone it; otherwise return nullptr.
// If both can_copy() and can_clone() return true, we will prefer the Clone()
// function over the copy constructor.
// The caller has ownership over the return value.
static T* CopyOrNull(const T* raw) {
constexpr bool check_can_clone = can_clone(1);
constexpr bool check_can_copy = can_copy(1);
static_assert(
check_can_clone || check_can_copy,
"copyable_unique_ptr<T> can only be used with a 'copyable' class T, "
"requiring either a copy constructor or a Clone method of the form "
"'unique_ptr<T> Clone() const'.");
if (raw == nullptr) {
return nullptr;
}
if constexpr (check_can_clone) {
return raw->Clone().release();
} else {
return new T(*raw);
}
}
};
} // namespace drake
DRAKE_FORMATTER_AS(typename T, drake, copyable_unique_ptr<T>, x,
static_cast<const void*>(x.get()))
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/nice_type_name.cc | /* Portions copyright (c) 2014 Stanford University and the Authors.
Authors: Chris Dembia, Michael Sherman
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain a
copy of the License at http://www.apache.org/licenses/LICENSE-2.0. */
#include "drake/common/nice_type_name.h"
#include <algorithm>
#include <array>
#include <initializer_list>
#include <regex>
#include <string>
#include "drake/common/never_destroyed.h"
#include "drake/common/nice_type_name_override.h"
using std::string;
// __GNUG__ is defined both for gcc and clang. See:
// https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html
#if defined(__GNUG__)
/* clang-format off */
#include <cxxabi.h>
#include <cstdlib>
/* clang-format on */
#endif
namespace drake {
// On gcc and clang typeid(T).name() returns an indecipherable mangled string
// that requires processing to become human readable. Microsoft returns a
// reasonable name directly.
string NiceTypeName::Demangle(const char* typeid_name) {
#if defined(__GNUG__)
int status = -100; // just in case it doesn't get set
char* ret = abi::__cxa_demangle(typeid_name, NULL, NULL, &status);
const char* const demangled_name = (status == 0) ? ret : typeid_name;
string demangled_string(demangled_name);
if (ret) std::free(ret);
return demangled_string;
#else
// On other platforms, we hope the typeid name is not mangled.
return typeid_name;
#endif
}
// Given a demangled string, attempt to canonicalize it for platform
// indpendence. We'll remove Microsoft's "class ", "struct ", etc.
// designations, and get rid of all unnecessary spaces.
string NiceTypeName::Canonicalize(const string& demangled) {
using SPair = std::pair<std::regex, string>;
using SPairList = std::initializer_list<SPair>;
// These are applied in this order.
static const never_destroyed<std::vector<SPair>> subs{SPairList{
// Remove unwanted keywords and following space. (\b is word boundary.)
SPair(std::regex("\\b(class|struct|enum|union) "), ""),
// Tidy up anonymous namespace.
SPair(std::regex("[`(]anonymous namespace[')]"), "(anonymous)"),
// Replace Microsoft __int64 with long long.
SPair(std::regex("\\b__int64\\b"), "long long"),
// Temporarily replace spaces we want to keep with "!". (\w is
// alphanumeric or underscore.)
SPair(std::regex("(\\w) (\\w)"), "$1!$2"),
SPair(std::regex(" "), ""), // Delete unwanted spaces.
// Some compilers throw in extra namespaces like "__1" or "__cxx11".
// Delete them.
SPair(std::regex("\\b__[[:alnum:]_]+::"), ""),
SPair(std::regex("!"), " "), // Restore wanted spaces.
// Recognize std::string's full name and abbreviate.
SPair(std::regex("\\bstd::basic_string<char,std::char_traits<char>,"
"std::allocator<char>>"),
"std::string"),
// Recognize Eigen types ...
// ... square matrices ...
SPair(std::regex("\\bEigen::Matrix<([^,<>]*),(-?\\d+),\\2,0,\\2,\\2>"),
"drake::Matrix$2<$1>"),
// ... vectors ...
SPair(std::regex("\\bEigen::Matrix<([^,<>]*),(-?\\d+),1,0,\\2,1>"),
"drake::Vector$2<$1>"),
// ... dynamic-size is "X" not "-1" ...
SPair(std::regex("drake::(Matrix|Vector)-1<"), "drake::$1X<"),
// ... for double, float, and int, prefer native Eigen spellings ...
SPair(std::regex("drake::(Vector|Matrix)(X|\\d+)"
"<((d)ouble|(f)loat|(i)nt)>"),
"Eigen::$1$2$4$5$6"),
// ... AutoDiff.
SPair(std::regex("Eigen::AutoDiffScalar<Eigen::VectorXd>"),
"drake::AutoDiffXd"),
// Recognize Identifier ...
// Change e.g., "drake::Identifier<drake::package::FooTag>" to
// "drake::package::FooId".
SPair(std::regex("\\bdrake::Identifier<([^>]*)Tag>"), "$1Id"),
}};
string canonical(demangled);
for (const auto& sp : subs.access()) {
canonical = std::regex_replace(canonical, sp.first, sp.second);
}
return canonical;
}
string NiceTypeName::RemoveNamespaces(const string& canonical) {
// Removes everything up to and including the last "::" that isn't part of a
// template argument. If the string ends with "::", returns the original
// string unprocessed. We are depending on the fact that namespaces can't be
// templatized to avoid bad behavior for template types where the template
// argument might include namespaces (those should not be touched).
static const never_destroyed<std::regex> regex{"^[^<>]*::"};
const std::string no_namespace =
std::regex_replace(canonical, regex.access(), "");
return no_namespace.empty() ? canonical : no_namespace;
}
std::string NiceTypeName::GetWithPossibleOverride(const void* ptr,
const std::type_info& info) {
internal::NiceTypeNamePtrOverride ptr_override =
internal::GetNiceTypeNamePtrOverride();
if (ptr_override) {
return ptr_override(internal::type_erased_ptr{ptr, info});
} else {
return Get(info);
}
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_assert_and_throw.cc | // This file contains the implementation of both drake_assert and drake_throw.
/* clang-format off to disable clang-format-includes */
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
/* clang-format on */
#include <atomic>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include "drake/common/drake_assertion_error.h"
#include "drake/common/never_destroyed.h"
namespace drake {
namespace internal {
namespace {
// Singleton to manage assertion configuration.
struct AssertionConfig {
static AssertionConfig& singleton() {
static never_destroyed<AssertionConfig> global;
return global.access();
}
std::atomic<bool> assertion_failures_are_exceptions;
};
// Stream into @p out the given failure details; only @p condition may be null.
void PrintFailureDetailTo(std::ostream& out, const char* condition,
const char* func, const char* file, int line) {
out << "Failure at " << file << ":" << line << " in " << func << "()";
if (condition) {
out << ": condition '" << condition << "' failed.";
} else {
out << ".";
}
}
} // namespace
// Declared in drake_assert.h.
void Abort(const char* condition, const char* func, const char* file,
int line) {
std::cerr << "abort: ";
PrintFailureDetailTo(std::cerr, condition, func, file, line);
std::cerr << std::endl;
std::abort();
}
// Declared in drake_throw.h.
void Throw(const char* condition, const char* func, const char* file,
int line) {
std::ostringstream what;
PrintFailureDetailTo(what, condition, func, file, line);
throw assertion_error(what.str().c_str());
}
// Declared in drake_assert.h.
void AssertionFailed(const char* condition, const char* func, const char* file,
int line) {
if (AssertionConfig::singleton().assertion_failures_are_exceptions) {
Throw(condition, func, file, line);
} else {
Abort(condition, func, file, line);
}
}
} // namespace internal
} // namespace drake
// Configures the DRAKE_ASSERT and DRAKE_DEMAND assertion failure handling
// behavior.
//
// By default, assertion failures will result in an ::abort(). If this method
// has ever been called, failures will result in a thrown exception instead.
//
// Assertion configuration has process-wide scope. Changes here will affect
// all assertions within the current process.
//
// This method is intended ONLY for use by pydrake bindings, and thus is not
// declared in any header file, to discourage anyone from using it.
extern "C" void drake_set_assertion_failure_to_throw_exception() {
drake::internal::AssertionConfig::singleton()
.assertion_failures_are_exceptions = true;
}
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/constants.h | #pragma once
namespace drake {
enum class ToleranceType { kAbsolute, kRelative };
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/random.h | #pragma once
#include <memory>
#include <random>
#include <Eigen/Core>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/extract_double.h"
namespace drake {
/// Defines Drake's canonical implementation of the UniformRandomBitGenerator
/// C++ concept (as well as a few conventional extras beyond the concept, e.g.,
/// seeds). This uses the 32-bit Mersenne Twister mt19937 by Matsumoto and
/// Nishimura, 1998. For more information, see
/// https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
class RandomGenerator {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(RandomGenerator)
using result_type = std::mt19937::result_type;
/// Creates a generator using the `default_seed`. Actual creation of the
/// generator is deferred until first use so this constructor is fast and
/// does not allocate any heap memory.
RandomGenerator() = default;
/// Creates a generator using given `seed`.
explicit RandomGenerator(result_type seed) : generator_(CreateEngine(seed)) {}
static constexpr result_type min() { return Engine::min(); }
static constexpr result_type max() { return Engine::max(); }
/// Generates a pseudo-random value.
result_type operator()() {
// Use lazy construction here, so that the default constructor can be fast.
if (generator_ == nullptr) {
generator_ = CreateEngine(default_seed);
}
return (*generator_)();
}
static constexpr result_type default_seed = std::mt19937::default_seed;
private:
using Engine = std::mt19937;
static std::unique_ptr<Engine> CreateEngine(result_type seed);
copyable_unique_ptr<Engine> generator_;
};
/// Drake supports explicit reasoning about a few carefully chosen random
/// distributions.
enum class RandomDistribution {
kUniform = 0, ///< Vector elements are independent and uniformly distributed
/// ∈ [0.0, 1.0).
kGaussian = 1, ///< Vector elements are independent and drawn from a
/// mean-zero, unit-variance normal (Gaussian) distribution.
kExponential = 2, ///< Vector elements are independent and drawn from an
/// exponential distribution with λ=1.0.
};
/**
* Calculates the density (probability density function) of the multivariate
* distribution.
* @param distribution The distribution type.
* @param x The value of the sampled vector.
* @tparam_nonsymbolic_scalar
*
* @note When instantiating this function, the user needs to explicitly pass in
* the scalar type, for example CalcProbabilityDensity<double>(...), the
* compiler might have problem to deduce the scalar type automatically.
*/
template <typename T>
T CalcProbabilityDensity(RandomDistribution distribution,
const Eigen::Ref<const VectorX<T>>& x);
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/string_map.h | #pragma once
#include <functional>
#include <map>
#include <string>
namespace drake {
/** Like `std::map<std::string, T>`, but with better defaults than the plain
`std::map<std::string, T>` spelling. We need `std::less<void>` as the comparison
function so that `std::string_view` and `const char*` can be used as lookup keys
without copying them to a `std::string`. */
template <typename T>
using string_map = std::map<std::string, T, std::less<void>>;
/** Like `std::multimap<std::string, T>`, but with better defaults than the
plain `std::multimap<std::string, T>` spelling. We need `std::less<void>` as the
comparison function so that `std::string_view` and `const char*` can be used as
lookup keys without copying them to a `std::string`. */
template <typename T>
using string_multimap = std::multimap<std::string, T, std::less<void>>;
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/fmt_eigen.cc | // TODO(jwnimmer-tri) Write our own formatting logic instead of using Eigen IO,
// and add customization flags for how to display the matrix data.
#undef EIGEN_NO_IO
#include "drake/common/fmt_eigen.h"
#include <limits>
#include <sstream>
namespace drake {
namespace internal {
template <typename T>
using FormatterEigenRef =
Eigen::Ref<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
std::string FormatEigenMatrix(const FormatterEigenRef<T>& matrix) {
std::stringstream stream;
// We'll print our matrix data using as much precision as we can, so that
// console log output and/or error messages paint the full picture. Sadly,
// the ostream family of floating-point formatters doesn't know how to do
// "shortest round-trip precision". If we set the precision to max_digits,
// then simple numbers like "1.1" print as "1.1000000000000001"; instead,
// we'll use max_digits - 1 to avoid that problem, with the risk of losing
// the last ulps in the printout in case we needed that last digit. This
// will all be fixed once we stop using Eigen IO.
stream.precision(std::numeric_limits<double>::max_digits10 - 1);
stream << matrix;
return stream.str();
}
// Explicitly instantiate for the allowed scalar types in our header.
template std::string FormatEigenMatrix<double>(
const FormatterEigenRef<double>& matrix);
template std::string FormatEigenMatrix<float>(
const FormatterEigenRef<float>& matrix);
template std::string FormatEigenMatrix<std::string>(
const FormatterEigenRef<std::string>& matrix);
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/diagnostic_policy.cc | #include "drake/common/diagnostic_policy.h"
#include <sstream>
#include <stdexcept>
#include <utility>
#include "drake/common/drake_assert.h"
#include "drake/common/text_logging.h"
namespace drake {
namespace internal {
std::string DiagnosticDetail::Format(const std::string& severity) const {
DRAKE_DEMAND(!severity.empty());
std::stringstream ss;
if (filename.has_value()) {
ss << *filename << ":";
if (line.has_value()) {
ss << *line << ":";
}
ss << " ";
}
ss << severity << ": ";
ss << message;
return ss.str();
}
std::string DiagnosticDetail::FormatWarning() const {
return Format("warning");
}
std::string DiagnosticDetail::FormatError() const {
return Format("error");
}
void DiagnosticPolicy::SetActionForWarnings(
std::function<void(const DiagnosticDetail&)> functor) {
on_warning_ = std::move(functor);
}
void DiagnosticPolicy::SetActionForErrors(
std::function<void(const DiagnosticDetail&)> functor) {
on_error_ = std::move(functor);
}
void DiagnosticPolicy::Warning(std::string message) const {
DiagnosticDetail d;
d.message = std::move(message);
this->Warning(d);
}
void DiagnosticPolicy::Error(std::string message) const {
DiagnosticDetail d;
d.message = std::move(message);
this->Error(d);
}
void DiagnosticPolicy::WarningDefaultAction(const DiagnosticDetail& detail) {
log()->warn(detail.FormatWarning());
}
void DiagnosticPolicy::ErrorDefaultAction(const DiagnosticDetail& detail) {
throw std::runtime_error(detail.FormatError());
}
void DiagnosticPolicy::Warning(const DiagnosticDetail& detail) const {
if (on_warning_ == nullptr) {
WarningDefaultAction(detail);
} else {
on_warning_(detail);
}
}
void DiagnosticPolicy::Error(const DiagnosticDetail& detail) const {
if (on_error_ == nullptr) {
ErrorDefaultAction(detail);
} else {
on_error_(detail);
}
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/value.h | #pragma once
#include <memory>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/hash.h"
#include "drake/common/is_cloneable.h"
#include "drake/common/nice_type_name.h"
namespace drake {
#if !defined(DRAKE_DOXYGEN_CXX)
template <typename T>
class Value;
namespace internal {
// A traits type for Value<T>, where use_copy is true when T's copy constructor
// and copy-assignment operator are used and false when T's Clone is used.
template <typename T, bool use_copy>
struct ValueTraitsImpl {};
template <typename T>
using ValueTraits = ValueTraitsImpl<T, std::is_copy_constructible_v<T>>;
// SFINAE type for whether Value<T>(Arg1, Args...) should be a forwarding ctor.
// In our ctor overload that copies into the storage, choose_copy == true.
template <bool choose_copy, typename T, typename Arg1, typename... Args>
using ValueForwardingCtorEnabled = typename std::enable_if_t<
// There must be such a constructor.
std::is_constructible_v<T, Arg1, Args...> &&
// Disable this ctor when given T directly; in that case, we
// should call our Value(const T&) ctor above, not try to copy-
// construct a T(const T&).
!std::is_same_v<T, Arg1> && !std::is_same_v<T&, Arg1> &&
// Only allow real ctors, not POD "constructor"s.
!std::is_fundamental_v<T> &&
// Disambiguate our copy implementation from our clone implementation.
(choose_copy == std::is_copy_constructible_v<T>)>;
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
} // namespace internal
#endif
/// A fully type-erased container class. An AbstractValue stores an object of
/// some type T (where T is declared during at construction time) that at
/// runtime can be passed between functions without mentioning T. Only when
/// the stored T must be accessed does the user need to mention T again.
///
/// (Advanced.) Note that AbstractValue's getters and setters method declare
/// that "If T does not match, a std::logic_error will be thrown with a helpful
/// error message". The code that implements this check uses hashing, so in
/// the extraordinarily unlikely case of a 64-bit hash collision, the error may
/// go undetected in Release builds. (Debug builds have extra checks that will
/// trigger.)
///
/// (Advanced.) Only Value should inherit directly from AbstractValue.
/// User-defined classes with additional features may inherit from Value.
class AbstractValue {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(AbstractValue)
virtual ~AbstractValue();
/// Constructs an AbstractValue using T's default constructor, if available.
/// This is only available for T's that support default construction.
#if !defined(DRAKE_DOXYGEN_CXX)
template <typename T, typename = typename std::enable_if_t<
std::is_default_constructible_v<T>>>
#endif
static std::unique_ptr<AbstractValue> Make();
/// Returns an AbstractValue containing the given @p value.
template <typename T>
static std::unique_ptr<AbstractValue> Make(const T& value);
/// Returns the value wrapped in this AbstractValue as a const reference.
/// The reference remains valid only until this object is set or destroyed.
/// @tparam T The originally declared type of this AbstractValue, e.g., from
/// AbstractValue::Make<T>() or Value<T>::Value(). If T does not match, a
/// std::logic_error will be thrown with a helpful error message.
template <typename T>
const T& get_value() const {
return cast<T>().get_value();
}
/// Returns the value wrapped in this AbstractValue as mutable reference.
/// The reference remains valid only until this object is set or destroyed.
/// @tparam T The originally declared type of this AbstractValue, e.g., from
/// AbstractValue::Make<T>() or Value<T>::Value(). If T does not match, a
/// std::logic_error will be thrown with a helpful error message.
template <typename T>
T& get_mutable_value() {
return cast<T>().get_mutable_value();
}
/// Sets the value wrapped in this AbstractValue.
/// @tparam T The originally declared type of this AbstractValue, e.g., from
/// AbstractValue::Make<T>() or Value<T>::Value(). If T does not match, a
/// std::logic_error will be thrown with a helpful error message.
template <typename T>
void set_value(const T& v) {
cast<T>().set_value(v);
}
/// Returns the value wrapped in this AbstractValue, if T matches the
/// originally declared type of this AbstractValue.
/// @tparam T The originally declared type of this AbstractValue, e.g., from
/// AbstractValue::Make<T>() or Value<T>::Value(). If T does not match,
/// returns nullptr.
template <typename T>
const T* maybe_get_value() const;
/// Returns the mutable value wrapped in this AbstractValue, if T matches the
/// originally declared type of this AbstractValue.
/// @tparam T The originally declared type of this AbstractValue, e.g., from
/// AbstractValue::Make<T>() or Value<T>::Value(). If T does not match,
/// returns nullptr.
template <typename T>
T* maybe_get_mutable_value();
/// Returns a copy of this AbstractValue.
virtual std::unique_ptr<AbstractValue> Clone() const = 0;
/// Copies the value in @p other to this value. If other is not compatible
/// with this object, a std::logic_error will be thrown with a helpful error
/// message.
virtual void SetFrom(const AbstractValue& other) = 0;
/// Returns typeid of the contained object of type T. If T is polymorphic,
/// this returns the typeid of the most-derived type of the contained object.
virtual const std::type_info& type_info() const = 0;
/// Returns typeid(T) for this Value<T> object. If T is polymorphic, this
/// does NOT reflect the typeid of the most-derived type of the contained
/// object; the result is always the base type T.
virtual const std::type_info& static_type_info() const = 0;
/// Returns a human-readable name for the underlying type T. This may be
/// slow but is useful for error messages. If T is polymorphic, this returns
/// the typeid of the most-derived type of the contained object.
std::string GetNiceTypeName() const;
protected:
#if !defined(DRAKE_DOXYGEN_CXX)
// Use a struct argument (instead of a bare size_t) so that no code
// tries to convert a single-element numeric initializer_list to
// a `const AbstractValue&`. (This works around a bug in GCC 5.)
struct Wrap {
size_t value{};
};
explicit AbstractValue(Wrap hash) : type_hash_(hash.value) {}
#endif
private:
template <typename T>
bool is_maybe_matched() const;
template <typename T>
const Value<T>& cast() const;
template <typename T>
Value<T>& cast();
template <typename T>
[[noreturn]] void ThrowCastError() const;
[[noreturn]] void ThrowCastError(const std::string&) const;
// The TypeHash<T>::value supplied by the Value<T> constructor.
const size_t type_hash_;
};
/// A container class for an arbitrary type T (with some restrictions). This
/// class inherits from AbstractValue and therefore at runtime can be passed
/// between functions without mentioning T.
///
/// Example:
/// @code
/// void print_string(const AbstractValue& arg) {
/// const std::string& message = arg.get_value<std::string>();
/// std::cerr << message;
/// }
/// void meow() {
/// const Value<std::string> value("meow");
/// print_string(value);
/// }
/// @endcode
///
/// (Advanced.) User-defined classes with additional features may subclass
/// Value, but should take care to override Clone().
///
/// @tparam T Must be copy-constructible or cloneable. Must not be a pointer,
/// array, nor have const, volatile, or reference qualifiers.
template <typename T>
class Value : public AbstractValue {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Value)
static_assert(std::is_same_v<T, internal::remove_cvref_t<T>>,
"T should not have const, volatile, or reference qualifiers.");
static_assert(!std::is_pointer_v<T> && !std::is_array_v<T>,
"T cannot be a pointer or array.");
/// Constructs a Value<T> using T's default constructor, if available.
/// This is only available for T's that support default construction.
#if !defined(DRAKE_DOXYGEN_CXX)
template <typename T1 = T, typename = typename std::enable_if_t<
std::is_default_constructible_v<T1>>>
#endif
Value();
/// Constructs a Value<T> by copying or cloning the given value @p v.
explicit Value(const T& v);
/// Constructs a Value<T> by forwarding the given @p args to T's constructor,
/// if available. This is only available for non-primitive T's that are
/// constructible from @p args.
#if defined(DRAKE_DOXYGEN_CXX)
template <typename... Args>
explicit Value(Args&&... args);
#else
// This overload is for copyable T.
template <typename Arg1, typename... Args,
typename = typename internal::ValueForwardingCtorEnabled<
true, T, Arg1, Args...>>
explicit Value(Arg1&& arg1, Args&&... args);
// This overload is for cloneable T.
template <typename Arg1, typename... Args, typename = void,
typename = typename internal::ValueForwardingCtorEnabled<
false, T, Arg1, Args...>>
explicit Value(Arg1&& arg1, Args&&... args);
#endif
/// Constructs a Value<T> by copying or moving the given value @p v.
/// @pre v is non-null.
explicit Value(std::unique_ptr<T> v);
~Value() override {}
/// Returns a const reference to the stored value.
/// The reference remains valid only until this object is set or destroyed.
const T& get_value() const;
/// Returns a mutable reference to the stored value.
/// The reference remains valid only until this object is set or destroyed.
T& get_mutable_value();
/// Replaces the stored value with a new one.
void set_value(const T& v);
// AbstractValue overrides.
std::unique_ptr<AbstractValue> Clone() const override;
void SetFrom(const AbstractValue& other) override;
const std::type_info& type_info() const final;
const std::type_info& static_type_info() const final;
// A using-declaration adds these methods into our class's Doxygen.
using AbstractValue::GetNiceTypeName;
using AbstractValue::static_type_info;
private:
using Traits = internal::ValueTraits<T>;
typename Traits::Storage value_;
};
#if !defined(DRAKE_DOXYGEN_CXX)
// Declare some private helper structs.
namespace internal {
// Extracts a hash of the type `T` in a __PRETTY_FUNCTION__ templated on T.
//
// For, e.g., TypeHash<int> the pretty_func string `pretty` looks like this:
// GCC 7.3: "... calc() [with T = int; size_t K = 16; ..."
// Clang 6.0: "... calc() [T = int]"
//
// We grab the characters for T's type (e.g., "int") and hash them using FNV1a.
// https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
//
// The value of @p which_argument chooses the which pretty template argument to
// hash. (Only one argument at a time is ever hashed.) In the GCC example
// above, which_argument of 0 hashes "int" and 1 hashes "16".
//
// If T is a template type like "std::vector<U>", we only hash "std::vector"
// here. We stop when we reach a '<' because each template argument is hashed
// separately below using parameter packs (see `TypeHasher<T<Args...>>`). This
// avoids compiler bugs where __PRETTY_FUNCTION__ is fickle about the spelling
// of "T = std::vector<U>" vs "T = std::vector<U, std::allocator<U>>", varying
// it from one method to the next. Because we visit each base type in turn, we
// hash "std::vector" then "U" then "std::allocator" then "U" and so it doesn't
// matter exactly how templates end up being spelled in __PRETTY_FUNCTION__.
//
// When @p discard_nested is true, then stopping at '<' means our success-return
// value will be true; if discard_nested is false then seeing any '<' is an
// error. Thus, we can detect and fail-fast when our specializations for
// template parameters fail to match.
//
// When @p discard_cast is true, we will omit a leading cast-expression after
// the equals sign, e.g., when pretty looks like "... [with K = (MyEnum)0]".
// If we see any other open-paren than this possibly-skipped cast, then our
// success-return value will be false. Thus, we can detect and fail-fast when
// our specializations for non-type template parameters fail to match, or when
// T's like function pointer signatures appear.
//
// Note that the compiler is required to inform us at compile-time if there are
// undefined operations in the below, such as running off the end of a string.
// Therefore, so as long as this function compiles, we know that `pretty` had
// at least something that looks like "T = ..." in it.
//
// Returns true on success / false on failure.
constexpr bool hash_template_argument_from_pretty_func(
const char* pretty, int which_argument,
bool discard_nested, bool discard_cast,
FNV1aHasher* result) {
// Advance to the desired template argument. For example, if which_argument
// is 0 and pretty == "... calc() [T = int]", then advance to the typename
// after the "T = " so that the cursor `p` is pointing at the 'i' in "int".
const char* p = pretty;
for (int n = 0; n <= which_argument; ++n) {
for (; (*p != '='); ++p) {} // Advance to the '=' that we want.
++p; // Advance to ' '.
++p; // Advance to the typename we want.
}
// For enums, GCC 7's pretty says "(MyEnum)0" not "MyEnum::kFoo". We'll strip
// off the useless parenthetical.
if (discard_cast && (*p == '(')) {
for (; (*p != ')'); ++p) {} // Advance to the ')'.
++p;
}
// Hash the characters in the typename, ending either when the typename ends
// (';' or ']') or maybe when the first template argument begins ('<').
while ((*p != ';') && (*p != ']')) {
// Map Clang's spelling for the anonymous namespace to match GCC. Start by
// searching for the clang spelling starting at `p` ...
const char* const clang_spelling = "(anonymous namespace)";
const char* clang_iter = clang_spelling;
const char* pretty_iter = p;
for (; *clang_iter != 0 && *pretty_iter != 0; ++clang_iter, ++pretty_iter) {
if (*clang_iter != *pretty_iter) {
break;
}
}
// ... and if we found the entire clang_spelling, emit gcc_spelling instead.
if (*clang_iter == 0) {
const char* const gcc_spelling = "{anonymous}";
for (const char* c = gcc_spelling; *c; ++c) {
result->add_byte(*c);
}
p = pretty_iter;
continue;
}
// GCC distinguishes between "<unnamed>" and "{anonymous}", while Clang does
// not. Map "<unnamed>" to "{anonymous}" for consistency and to avoid
// confusion with nested types ("<>") below.
const char* const unnamed_spelling = "<unnamed>";
const char* unnamed_iter = unnamed_spelling;
pretty_iter = p;
for (; *unnamed_iter != 0 && *pretty_iter != 0;
++unnamed_iter, ++pretty_iter) {
if (*unnamed_iter != *pretty_iter) {
break;
}
}
if (*unnamed_iter == 0) {
const char* const anonymous_spelling = "{anonymous}";
for (const char* c = anonymous_spelling; *c; ++c) {
result->add_byte(*c);
}
p = pretty_iter;
continue;
}
// If we find a nested type ("<>"), then either we expected it (in which
// case we're done) or we didn't expect it (and something is wrong).
if (*p == '<') {
if (discard_nested) {
break;
} else {
return false;
}
}
// If the type has parens (such as a function pointer or std::function),
// then we can't handle it. Adding support for function types involves not
// only unpacking the return and argument types, but also adding support
// for const / volatile / reference / etc.).
if (*p == '(') {
return false;
}
result->add_byte(*p);
++p;
}
return true;
}
// Traits type to ask whether T::NonTypeTemplateParameter exists.
template <typename T, typename U = void>
struct TypeHasherHasNonTypeTemplateParameter {
static constexpr bool value = false;
};
template <typename T>
struct TypeHasherHasNonTypeTemplateParameter<
T, std::void_t<typename T::NonTypeTemplateParameter>> {
static constexpr bool value = true;
};
// Provides a struct templated on T so that __PRETTY_FUNCTION__ will express T
// at compile time. The calc() function feeds the string representation of T
// to `result`. Returns true on success / false on failure. This base struct
// handles non-templated values (e.g., int); in a specialization down below, we
// handle template template T's.
template <typename T, bool = TypeHasherHasNonTypeTemplateParameter<T>::value>
struct TypeHasher {
// Returns true on success / false on failure.
static constexpr bool calc(FNV1aHasher* result) {
// With discard_nested disabled here, the hasher will fail if it sees a
// '<' in the typename. If that happens, it means that the parameter pack
// specialization(s) below did not match as expected.
const int which_argument = 0;
const bool discard_nested = false;
const bool discard_cast = false;
return hash_template_argument_from_pretty_func(
__PRETTY_FUNCTION__, which_argument, discard_nested, discard_cast,
result);
}
};
// Provides a struct templated on Ts... with a calc() that hashes a sequence of
// types (a template parameter pack).
template <typename... Args>
struct ParameterPackHasher {};
// Specializes for base case: an empty pack.
template <>
struct ParameterPackHasher<> {
static constexpr bool calc(FNV1aHasher*) { return true; }
};
// Specializes for inductive case: recurse using first + rest.
template <typename A, typename... B>
struct ParameterPackHasher<A, B...> {
static constexpr bool calc(FNV1aHasher* result) {
bool success = TypeHasher<A>::calc(result);
if (sizeof...(B)) {
// Add delimiter so that pair<cub,scone> and pair<cubs,cone> are distinct.
result->add_byte(',');
success = success && ParameterPackHasher<B...>::calc(result);
}
return success;
}
};
// Specializes TypeHasher for template types T so that we have the typename of
// each template argument separately from T's outer type (as explained in the
// overview above).
template <template <typename...> class T, class... Args>
struct TypeHasher<T<Args...>, false> {
static constexpr bool calc(FNV1aHasher* result) {
// First, hash just the "T" template template type, not the "<Args...>".
const int which_argument = 0;
const bool discard_nested = true;
const bool discard_cast = false;
bool success = hash_template_argument_from_pretty_func(
__PRETTY_FUNCTION__, which_argument, discard_nested, discard_cast,
result);
// Then, hash the "<Args...>". Add delimiters so that parameter pack
// nesting is correctly hashed.
result->add_byte('<');
success = success && ParameterPackHasher<Args...>::calc(result);
result->add_byte('>');
return success;
}
};
// Provides a struct templated on `Typename Konstant`, similar to TypeHasher<T>
// but here the "Konstant"'s string is hashed, not a typename.
template <typename T, T K>
struct ValueHasher {
static constexpr bool calc(FNV1aHasher* result) {
const int which_argument = 1;
const bool discard_nested = false;
const bool discard_cast = true;
return hash_template_argument_from_pretty_func(
__PRETTY_FUNCTION__, which_argument, discard_nested, discard_cast,
result);
}
};
// Specializes TypeHasher for a non-type template value so that we have the
// value of the template argument separately from T's outer type (as explained
// in the overview above).
template <typename T>
struct TypeHasher<T, true> {
static constexpr bool calc(FNV1aHasher* result) {
// First, hash just the "T" template template type, not the "<U u>".
const int which_argument = 0;
const bool discard_nested = true;
const bool discard_cast = false;
hash_template_argument_from_pretty_func(__PRETTY_FUNCTION__, which_argument,
discard_nested, discard_cast,
result);
// Then, hash the "<U=u>".
using U = typename T::NonTypeTemplateParameter::value_type;
result->add_byte('<');
bool success = TypeHasher<U>::calc(result);
result->add_byte('=');
success = success &&
ValueHasher<U, T::NonTypeTemplateParameter::value>::calc(result);
result->add_byte('>');
return success;
}
};
// Provides a struct templated on Ns... with a calc() that hashes a sequence of
// ints (an int parameter pack).
template <int... Ns>
struct IntPackHasher {};
// Specializes for base case: an empty pack.
template <>
struct IntPackHasher<> {
static constexpr bool calc(FNV1aHasher*) { return true; }
};
// Specializes for inductive case: recurse using first + rest.
template <int N, int... Ns>
struct IntPackHasher<N, Ns...> {
static constexpr bool calc(FNV1aHasher* result) {
result->add_byte('i');
result->add_byte('n');
result->add_byte('t');
result->add_byte('=');
bool success = ValueHasher<int, N>::calc(result);
if (sizeof...(Ns)) {
result->add_byte(',');
success = success && IntPackHasher<Ns...>::calc(result);
}
return success;
}
};
// Specializes TypeHasher for Eigen-like types.
template <template <typename, int, int...> class T, typename U, int N,
int... Ns>
struct TypeHasher<T<U, N, Ns...>, false> {
static constexpr bool calc(FNV1aHasher* result) {
// First, hash just the "T" template template type, not the "<U, N, Ns...>".
const int which_argument = 0;
const bool discard_nested = true;
const bool discard_cast = false;
bool success = hash_template_argument_from_pretty_func(
__PRETTY_FUNCTION__, which_argument, discard_nested, discard_cast,
result);
// Then, hash the "<U, N, Ns...>". Add delimiters so that parameter pack
// nesting is correctly hashed.
result->add_byte('<');
success = success && TypeHasher<U>::calc(result);
result->add_byte(',');
success = success && IntPackHasher<N, Ns...>::calc(result);
result->add_byte('>');
return success;
}
};
// Computes a typename hash as a compile-time constant. By putting it into a
// static constexpr, we force the compiler to compute the hash at compile time.
//
// We use these compile-time hashes to improve the performance of the downcast
// checks in AbstractValue. The hash constant ends up being inlined into the
// object code of AbstractValue's accessors. (We cannot use `typeid(T).name()`
// for this purpose at compile-time, because it's not constexpr.)
//
// This implementation is intended to work for the kinds of `T`s we would see
// in a `Value<T>`; notably, it does not support `T`s of type `std::function`,
// function pointers, and the like. It also does not support `T`'s with
// non-type template parameters. Unsupported types yield a hash value of zero
// so that using-code can decide how to handle the failure.
template <typename T>
struct TypeHash {
static constexpr size_t calc() {
FNV1aHasher hasher;
const bool success = TypeHasher<T>::calc(&hasher);
const size_t hash = size_t(hasher);
const size_t nonzero_hash = hash ? hash : 1;
return success ? nonzero_hash : 0;
}
// The hash of "T", or zero when the type is not supported by the hasher.
// (Such failures are expected to be rare.)
static constexpr size_t value = calc();
};
// This is called once per process per T whose type_hash is 0. It logs a
// TypeHash failure message to Drake's text log.
int ReportZeroHash(const std::type_info& detail);
// Any code in this file that uses TypeHash::value calls us for its T.
template <typename T, size_t hash>
struct ReportUseOfTypeHash {
static void used() {
// By default, do nothing.
}
};
template <typename T>
struct ReportUseOfTypeHash<T, 0> {
static void used() {
static int dummy = ReportZeroHash(typeid(T));
(void)(dummy);
}
};
// For copyable types, we can store a T directly within Value<T> and we don't
// need any special tricks to create or retrieve it.
template <typename T>
struct ValueTraitsImpl<T, true> {
using Storage = T;
static void reinitialize_if_necessary(Storage*) {}
static const T& to_storage(const T& other) { return other; }
static const Storage& to_storage(const std::unique_ptr<T>& other) {
DRAKE_DEMAND(other.get() != nullptr);
return *other;
}
static const T& access(const Storage& storage) { return storage; }
// NOLINTNEXTLINE(runtime/references)
static T& access(Storage& storage) { return storage; }
};
// For non-copyable types, we store a copyable_unique_ptr<T> so that Value<T>'s
// implementation's use of operator= and such work naturally. To store values,
// we must Clone them; to access values, we must de-reference the pointer.
template <typename T>
struct ValueTraitsImpl<T, false> {
static_assert(
drake::is_cloneable<T>::value,
"Types placed into a Value<T> must either be copyable or cloneable");
// We explicitly disallow Value<AbstractValue>. In cases where it occurs, it
// is likely that someone has created functions such as
// template DoBar(const AbstractValue& foo) { ... }
// template <class Foo> DoBar(const Foo& foo) { DoBar(Value<Foo>{foo}); }
// and accidentally called DoBar<AbstractValue>, or similar mistakes.
static_assert(!std::is_same_v<T, std::remove_cv_t<AbstractValue>>,
"T in Value<T> cannot be AbstractValue.");
using Storage = typename drake::copyable_unique_ptr<T>;
static void reinitialize_if_necessary(Storage* value) {
*value = std::make_unique<T>();
}
static Storage to_storage(const T& other) { return Storage{other.Clone()}; }
static Storage to_storage(std::unique_ptr<T> other) {
DRAKE_DEMAND(other.get() != nullptr);
return Storage{std::move(other)};
}
static const T& access(const Storage& storage) { return *storage; }
// NOLINTNEXTLINE(runtime/references)
static T& access(Storage& storage) { return *storage; }
};
} // namespace internal
template <typename T, typename>
std::unique_ptr<AbstractValue> AbstractValue::Make() {
return std::unique_ptr<AbstractValue>(new Value<T>());
}
template <typename T>
std::unique_ptr<AbstractValue> AbstractValue::Make(const T& value) {
return std::unique_ptr<AbstractValue>(new Value<T>(value));
}
template <typename T>
const T* AbstractValue::maybe_get_value() const {
if (!is_maybe_matched<T>()) {
return nullptr;
}
auto& self = static_cast<const Value<T>&>(*this);
return &self.get_value();
}
template <typename T>
T* AbstractValue::maybe_get_mutable_value() {
if (!is_maybe_matched<T>()) {
return nullptr;
}
auto& self = static_cast<Value<T>&>(*this);
return &self.get_mutable_value();
}
// In Debug mode, returns true iff `this` is-a `Value<T>`. In Release mode, a
// false return means `this` is definitely not a `Value<T>`; true means `this`
// is-probably-a `Value<T>`, but might rarely appear even for mismatched types.
template <typename T>
bool AbstractValue::is_maybe_matched() const {
constexpr auto hash = internal::TypeHash<T>::value;
internal::ReportUseOfTypeHash<T, hash>::used();
return (kDrakeAssertIsArmed || !hash) ? (typeid(T) == static_type_info())
: (hash == type_hash_);
}
// Casts this to a `const Value<T>&`, with error checking that throws.
template <typename T>
const Value<T>& AbstractValue::cast() const {
if (!is_maybe_matched<T>()) {
ThrowCastError<T>();
}
return static_cast<const Value<T>&>(*this);
}
// Casts this to a `Value<T>&`, with error checking that throws.
template <typename T>
Value<T>& AbstractValue::cast() {
if (!is_maybe_matched<T>()) {
ThrowCastError<T>();
}
return static_cast<Value<T>&>(*this);
}
// We use a separate method to report cast() errors so that cast() itself will
// be inlined in Release builds.
template <typename T>
void AbstractValue::ThrowCastError() const {
ThrowCastError(NiceTypeName::Get<T>());
}
template <typename T>
template <typename T1, typename T2>
Value<T>::Value()
: AbstractValue(Wrap{internal::TypeHash<T>::value}), value_{} {
internal::ReportUseOfTypeHash<T, internal::TypeHash<T>::value>::used();
Traits::reinitialize_if_necessary(&value_);
}
template <typename T>
Value<T>::Value(const T& v)
: AbstractValue(Wrap{internal::TypeHash<T>::value}),
value_(Traits::to_storage(v)) {
internal::ReportUseOfTypeHash<T, internal::TypeHash<T>::value>::used();
}
// We construct-in-place into our Storage value_.
template <typename T>
template <typename Arg1, typename... Args, typename>
Value<T>::Value(Arg1&& arg1, Args&&... args)
: AbstractValue(Wrap{internal::TypeHash<T>::value}),
value_{std::forward<Arg1>(arg1), std::forward<Args>(args)...} {
internal::ReportUseOfTypeHash<T, internal::TypeHash<T>::value>::used();
}
// We move a unique_ptr into our Storage value_.
template <typename T>
template <typename Arg1, typename... Args, typename, typename>
Value<T>::Value(Arg1&& arg1, Args&&... args)
: AbstractValue(Wrap{internal::TypeHash<T>::value}),
value_{std::make_unique<T>(std::forward<Arg1>(arg1),
std::forward<Args>(args)...)} {
internal::ReportUseOfTypeHash<T, internal::TypeHash<T>::value>::used();
}
// An explanation of the this constructor:
//
// We start with a unique_ptr<T> v. We std::move it to get an xvalue
// unique_ptr<T>&& that we pass to to_storage.
//
// In the copyable case, that matches to_storage(const unique_ptr<T>&), which
// does a nonnull check and then returns an alias to the owned const T& within
// v. Back in the Value constructor, the value_ member constructor is offered
// const T& so it does T::T(const T&) copy construction. As the constructor
// returns, the v argument goes out of scope and the T owned by v is deleted.
// The users's unique_ptr<T> was transferred to Value<T> with a single copy.
//
// In the cloneable case, that matches to_storage(unique_ptr<T>), which means v
// is moved into other. The to_storage does a nonnull check, then std::moves
// other into an xvalue unique_ptr<T>&& again, then constructs a
// copyable_unique_ptr<T> from the xvalue which moves the owned T resource into
// that temporary, then returns the temporary by-value. By RVO, the return
// value was already directly place into value_ and we are done. The user's
// unique_ptr<T> was transferred to Value<T> without any Clone.
template <typename T>
Value<T>::Value(std::unique_ptr<T> v)
: AbstractValue(Wrap{internal::TypeHash<T>::value}),
value_{Traits::to_storage(std::move(v))} {
internal::ReportUseOfTypeHash<T, internal::TypeHash<T>::value>::used();
}
template <typename T>
const T& Value<T>::get_value() const {
return Traits::access(value_);
}
template <typename T>
T& Value<T>::get_mutable_value() {
return Traits::access(value_);
}
template <typename T>
void Value<T>::set_value(const T& v) {
value_ = Traits::to_storage(v);
}
template <typename T>
std::unique_ptr<AbstractValue> Value<T>::Clone() const {
return std::make_unique<Value<T>>(get_value());
}
template <typename T>
void Value<T>::SetFrom(const AbstractValue& other) {
value_ = Traits::to_storage(other.get_value<T>());
}
template <typename T>
const std::type_info& Value<T>::type_info() const {
return typeid(get_value());
}
template <typename T>
const std::type_info& Value<T>::static_type_info() const {
return typeid(T);
}
#endif // DRAKE_DOXYGEN_CXX
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/README.md | drake/common - note to developers
=================================
Use this directory for general purpose C++ utilities that are used throughout Drake. Appropriate contents:
- general purpose macros
- utility classes that hide platform dependencies
- generally-useful containers and adapters
- preferred aliases for long type names
- predefined constants
- and similar code.
Do not include:
- Example programs
- Code that is specific to a Drake subarea that could be localized to that subarea.
Put unit tests for the above in the `test` subdirectory. Tests should have names that match the component being tested, with `_test` added at the end. Example: `common/some_useful_stuff.h` has test code `common/test/some_useful_stuff_test.cc` that generates an executable named `some_useful_stuff_test`.
Don't forget to add Doxygen documentation for every class and method explaining what they are for. Provide an `@code` example of how the utility should be used unless it is obvious.
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/eigen_types.h | #pragma once
/// @file
/// This file contains abbreviated definitions for certain specializations of
/// Eigen::Matrix that are commonly used in Drake.
/// These convenient definitions are templated on the scalar type of the Eigen
/// object. While Drake uses `<T>` for scalar types across the entire code base
/// we decided in this file to use `<Scalar>` to be more consistent with the
/// usage of `<Scalar>` in Eigen's code base.
/// @see also eigen_autodiff_types.h
#include <utility>
#include <Eigen/Dense>
static_assert(EIGEN_VERSION_AT_LEAST(3, 3, 5),
"Drake requires Eigen >= v3.3.5.");
#include "drake/common/constants.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
namespace drake {
/// The empty column vector (zero rows, one column), templated on scalar type.
template <typename Scalar>
using Vector0 = Eigen::Matrix<Scalar, 0, 1>;
/// A column vector of size 1 (that is, a scalar), templated on scalar type.
template <typename Scalar>
using Vector1 = Eigen::Matrix<Scalar, 1, 1>;
/// A column vector of size 1 of doubles.
using Vector1d = Eigen::Matrix<double, 1, 1>;
/// A column vector of size 2, templated on scalar type.
template <typename Scalar>
using Vector2 = Eigen::Matrix<Scalar, 2, 1>;
/// A column vector of size 3, templated on scalar type.
template <typename Scalar>
using Vector3 = Eigen::Matrix<Scalar, 3, 1>;
/// A column vector of size 4, templated on scalar type.
template <typename Scalar>
using Vector4 = Eigen::Matrix<Scalar, 4, 1>;
/// A column vector of size 6.
template <typename Scalar>
using Vector6 = Eigen::Matrix<Scalar, 6, 1>;
/// A column vector of size 6 of doubles.
using Vector6d = Eigen::Matrix<double, 6, 1>;
/// A column vector templated on the number of rows.
template <typename Scalar, int Rows>
using Vector = Eigen::Matrix<Scalar, Rows, 1>;
/// A column vector of any size, templated on scalar type.
template <typename Scalar>
using VectorX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
/// A vector of dynamic size templated on scalar type, up to a maximum of 6
/// elements.
template <typename Scalar>
using VectorUpTo6 = Eigen::Matrix<Scalar, Eigen::Dynamic, 1, 0, 6, 1>;
/// A row vector of size 2, templated on scalar type.
template <typename Scalar>
using RowVector2 = Eigen::Matrix<Scalar, 1, 2>;
/// A row vector of size 3, templated on scalar type.
template <typename Scalar>
using RowVector3 = Eigen::Matrix<Scalar, 1, 3>;
/// A row vector of size 4, templated on scalar type.
template <typename Scalar>
using RowVector4 = Eigen::Matrix<Scalar, 1, 4>;
/// A row vector of size 6.
template <typename Scalar>
using RowVector6 = Eigen::Matrix<Scalar, 1, 6>;
/// A row vector templated on the number of columns.
template <typename Scalar, int Cols>
using RowVector = Eigen::Matrix<Scalar, 1, Cols>;
/// A row vector of any size, templated on scalar type.
template <typename Scalar>
using RowVectorX = Eigen::Matrix<Scalar, 1, Eigen::Dynamic>;
/// A matrix of 2 rows and 2 columns, templated on scalar type.
template <typename Scalar>
using Matrix2 = Eigen::Matrix<Scalar, 2, 2>;
/// A matrix of 3 rows and 3 columns, templated on scalar type.
template <typename Scalar>
using Matrix3 = Eigen::Matrix<Scalar, 3, 3>;
/// A matrix of 4 rows and 4 columns, templated on scalar type.
template <typename Scalar>
using Matrix4 = Eigen::Matrix<Scalar, 4, 4>;
/// A matrix of 6 rows and 6 columns, templated on scalar type.
template <typename Scalar>
using Matrix6 = Eigen::Matrix<Scalar, 6, 6>;
/// A matrix of 2 rows, dynamic columns, templated on scalar type.
template <typename Scalar>
using Matrix2X = Eigen::Matrix<Scalar, 2, Eigen::Dynamic>;
/// A matrix of 3 rows, dynamic columns, templated on scalar type.
template <typename Scalar>
using Matrix3X = Eigen::Matrix<Scalar, 3, Eigen::Dynamic>;
/// A matrix of 4 rows, dynamic columns, templated on scalar type.
template <typename Scalar>
using Matrix4X = Eigen::Matrix<Scalar, 4, Eigen::Dynamic>;
/// A matrix of 6 rows, dynamic columns, templated on scalar type.
template <typename Scalar>
using Matrix6X = Eigen::Matrix<Scalar, 6, Eigen::Dynamic>;
/// A matrix of dynamic size, templated on scalar type.
template <typename Scalar>
using MatrixX = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
/// A matrix of dynamic size templated on scalar type, up to a maximum of 6 rows
/// and 6 columns. Rectangular matrices, with different number of rows and
/// columns, are allowed.
template <typename Scalar>
using MatrixUpTo6 =
Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, 0, 6, 6>;
/// A matrix of 6 rows and dynamic column size up to a maximum of 6, templated
/// on scalar type.
template <typename Scalar>
using Matrix6xUpTo6 = Eigen::Matrix<Scalar, 6, Eigen::Dynamic, 0, 6, 6>;
/// A matrix with the same compile-time sizes and storage order as Derived, but
/// with a different scalar type and its default alignment (Eigen::AutoAlign).
template <typename Scalar, typename Derived>
using MatrixLikewise = Eigen::Matrix<Scalar,
Derived::RowsAtCompileTime, Derived::ColsAtCompileTime,
Derived::IsRowMajor ? Eigen::RowMajor : Eigen::ColMajor,
Derived::MaxRowsAtCompileTime, Derived::MaxColsAtCompileTime>;
/// A fully dynamic Eigen stride.
using StrideX = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
/// A quaternion templated on scalar type.
template <typename Scalar>
using Quaternion = Eigen::Quaternion<Scalar>;
/// An AngleAxis templated on scalar type.
template <typename Scalar>
using AngleAxis = Eigen::AngleAxis<Scalar>;
/// An Isometry templated on scalar type.
template <typename Scalar>
using Isometry3 = Eigen::Transform<Scalar, 3, Eigen::Isometry>;
/*
* Determines if a type is derived from EigenBase<> (e.g. ArrayBase<>,
* MatrixBase<>).
*/
template <typename Derived>
struct is_eigen_type : std::is_base_of<Eigen::EigenBase<Derived>, Derived> {};
/*
* Determines if an EigenBase<> has a specific scalar type.
*/
template <typename Derived, typename Scalar>
struct is_eigen_scalar_same
: std::bool_constant<
is_eigen_type<Derived>::value &&
std::is_same_v<typename Derived::Scalar, Scalar>> {};
/*
* Determines if an EigenBase<> type is a compile-time (column) vector.
* This will not check for run-time size.
*/
template <typename Derived>
struct is_eigen_vector
: std::bool_constant<is_eigen_type<Derived>::value &&
Derived::ColsAtCompileTime == 1> {};
/*
* Determines if an EigenBase<> type is a compile-time (column) vector of a
* scalar type. This will not check for run-time size.
*/
template <typename Derived, typename Scalar>
struct is_eigen_vector_of
: std::bool_constant<
is_eigen_scalar_same<Derived, Scalar>::value &&
is_eigen_vector<Derived>::value> {};
// TODO(eric.cousineau): A 1x1 matrix will be disqualified in this case, and
// this logic will qualify it as a vector. Address the downstream logic if this
// becomes an issue.
/*
* Determines if a EigenBase<> type is a compile-time non-column-vector matrix
* of a scalar type. This will not check for run-time size.
* @note For an EigenBase<> of the correct Scalar type, this logic is
* exclusive to is_eigen_vector_of<> such that distinct specializations are not
* ambiguous.
*/
template <typename Derived, typename Scalar>
struct is_eigen_nonvector_of
: std::bool_constant<
is_eigen_scalar_same<Derived, Scalar>::value &&
!is_eigen_vector<Derived>::value> {};
// TODO(eric.cousineau): Add alias is_eigen_matrix_of = is_eigen_scalar_same if
// appropriate.
/// Given a random access container (like std::vector, std::array, or C array),
/// returns an Eigen::Map view into that container. Because this effectively
/// forms a reference to borrowed memory, you must be be careful using the
/// return value as anything other than a temporary. The Map return value
/// currently uses Eigen::Dynamic size at compile time even when the container
/// is fixed-size (e.g., std::array); if that ever turns into a performance
/// bottleneck in practice, it would be plausible to interrogate the size and
/// return a fixed-size Map, instead.
template <typename Container>
auto EigenMapView(Container&& c) {
using ElementRef = decltype(std::declval<Container&>()[size_t{}]);
using Element = std::remove_reference_t<ElementRef>;
if constexpr (std::is_const_v<Element>) {
using Scalar = std::remove_const_t<Element>;
return Eigen::Map<const VectorX<Scalar>>(std::data(c), std::size(c));
} else {
return Eigen::Map<VectorX<Element>>(std::data(c), std::size(c));
}
}
/// This wrapper class provides a way to write non-template functions taking raw
/// pointers to Eigen objects as parameters while limiting the number of copies,
/// similar to `Eigen::Ref`. Internally, it keeps an instance of `Eigen::Ref<T>`
/// and provides access to it via `operator*` and `operator->`. As with ordinary
/// pointers, these operators do not perform nullptr checks in Release builds.
/// User-facing APIs should check for nullptr explicitly.
///
/// The primary motivation of this class is to follow <a
/// href="https://google.github.io/styleguide/cppguide.html#Reference_Arguments">GSG's
/// "output arguments should be pointers" convention</a> while taking advantage
/// of using `Eigen::Ref`. It can also be used to pass optional Eigen objects
/// since %EigenPtr, unlike `Eigen::Ref`, can be null.
///
/// Some examples:
///
/// @code
/// // This function is taking an Eigen::Ref of a matrix and modifies it in
/// // the body. This violates GSG's pointer convention for output parameters.
/// void foo(Eigen::Ref<Eigen::MatrixXd> M) {
/// M(0, 0) = 0;
/// }
/// // At Call-site, we have:
/// foo(M);
/// foo(M.block(0, 0, 2, 2));
///
/// // We can rewrite the above function into the following using EigenPtr.
/// void foo(EigenPtr<Eigen::MatrixXd> M) {
/// DRAKE_THROW_UNLESS(M != nullptr); // If you want a Release-build check.
/// (*M)(0, 0) = 0;
/// }
/// // Note that, call sites should be changed to:
/// foo(&M);
///
/// // We need tmp to avoid taking the address of a temporary object such as the
/// // return value of .block().
/// auto tmp = M.block(0, 0, 2, 2);
/// foo(&tmp);
/// @endcode
///
/// Notice that methods taking an %EigenPtr can mutate the entries of a matrix
/// as in method `foo()` in the example code above, but cannot change its size.
/// This is because `operator*` and `operator->` return an `Eigen::Ref<T>`
/// object and only plain matrices/arrays can be resized and not expressions.
/// This **is** the desired behavior, since resizing the block of a matrix or
/// even a more general expression should not be allowed. If you do want to be
/// able to resize a mutable matrix argument, then you must pass it as a
/// `Matrix<T>*`, like so:
/// @code
/// void bar(Eigen::MatrixXd* M) {
/// DRAKE_THROW_UNLESS(M != nullptr);
/// // In this case this method only works with 4x3 matrices.
/// if (M->rows() != 4 && M->cols() != 3) {
/// M->resize(4, 3);
/// }
/// (*M)(0, 0) = 0;
/// }
/// @endcode
///
/// @note This class provides a way to avoid the `const_cast` hack introduced in
/// <a
/// href="https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html#TopicPlainFunctionsFailing">Eigen's
/// documentation</a>.
template <typename PlainObjectType>
class EigenPtr {
public:
typedef Eigen::Ref<PlainObjectType> RefType;
EigenPtr() : EigenPtr(nullptr) {}
/// Overload for `nullptr`.
// NOLINTNEXTLINE(runtime/explicit) This conversion is desirable.
EigenPtr(std::nullptr_t) {}
/// Copy constructor results in a _reference_ to the given matrix type.
EigenPtr(const EigenPtr& other) { assign(other); }
/// Constructs with a reference to another matrix type.
/// May be `nullptr`.
template <typename PlainObjectTypeIn>
// NOLINTNEXTLINE(runtime/explicit) This conversion is desirable.
EigenPtr(PlainObjectTypeIn* m) {
if (m) {
m_.set_value(m);
}
}
/// Constructs from another %EigenPtr.
template <typename PlainObjectTypeIn>
// NOLINTNEXTLINE(runtime/explicit) This conversion is desirable.
EigenPtr(const EigenPtr<PlainObjectTypeIn>& other) {
// Cannot directly construct `m_` from `other.m_`.
assign(other);
}
/// Copy assignment results in a _reference_ to the given matrix type.
EigenPtr& operator=(const EigenPtr& other) {
// We must explicitly override this version of operator=.
// The template below will not take precedence over this one.
return assign(other);
}
template <typename PlainObjectTypeIn>
EigenPtr& operator=(const EigenPtr<PlainObjectTypeIn>& other) {
return assign(other);
}
/// @pre The pointer is not null (enforced in Debug builds only).
RefType& operator*() const { return get_reference(); }
/// @pre The pointer is not null (enforced in Debug builds only).
RefType* operator->() const { return &get_reference(); }
/// Returns whether or not this contains a valid reference.
operator bool() const { return is_valid(); }
bool operator==(std::nullptr_t) const { return !is_valid(); }
bool operator!=(std::nullptr_t) const { return is_valid(); }
private:
// Simple reassignable container without requirement of heap allocation.
// This is used because `drake::optional<>` does not work with `Eigen::Ref<>`
// because `Ref` deletes the necessary `operator=` overload for
// `std::is_copy_assignable`.
class ReassignableRef {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ReassignableRef)
ReassignableRef() {}
~ReassignableRef() {
reset();
}
// Reset value to null.
void reset() {
if (has_value_) {
raw_value().~RefType();
has_value_ = false;
}
}
// Set value.
template <typename PlainObjectTypeIn>
void set_value(PlainObjectTypeIn* value_in) {
if (has_value_) {
raw_value().~RefType();
}
new (&raw_value()) RefType(*value_in);
has_value_ = true;
}
// Access to value.
RefType& value() {
DRAKE_ASSERT(has_value());
return raw_value();
}
// Indicates if it has a value.
bool has_value() const { return has_value_; }
private:
// Unsafe access to value.
RefType& raw_value() { return reinterpret_cast<RefType&>(storage_); }
bool has_value_{};
typename std::aligned_storage<sizeof(RefType), alignof(RefType)>::type
storage_;
};
// Use mutable, reassignable ref to permit pointer-like semantics (with
// ownership) on the stack.
mutable ReassignableRef m_;
// Consolidate assignment here, so that both the copy constructor and the
// construction from another type may be used.
template <typename PlainObjectTypeIn>
EigenPtr& assign(const EigenPtr<PlainObjectTypeIn>& other) {
if (other) {
m_.set_value(&(*other));
} else {
m_.reset();
}
return *this;
}
// Consolidate getting a reference here.
RefType& get_reference() const {
// Keep this tiny so it inlines.
DRAKE_ASSERT(m_.has_value());
return m_.value();
}
bool is_valid() const {
return m_.has_value();
}
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/parallelism.h | #pragma once
#include <optional>
#include <string_view>
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
namespace drake {
/** Specifies a desired degree of parallelism for a parallelized operation.
This class denotes a specific number of threads; either 1 (no parallelism), a
user-specified value (any number >= 1), or the maximum number. For convenience,
conversion from `bool` is provided so that `false` is no parallelism and `true`
is maximum parallelism.
Drake's API uses this class to allow users to control the degree of parallelism,
regardless of how the parallelization is implemented (e.g., `std::async`,
OpenMP, TBB, etc).
@section DRAKE_NUM_THREADS Configuring the process-wide maximum parallelism
The number of threads denoted by Parallelism::Max() is configurable with
environment variables, but will be invariant within a single process. The first
time it's accessed, the configured value will be latched into a global variable
indefinitely. To ensure your configuration is obeyed, any changes to the
environment variables that govern the max parallelism should be made prior to
importing or calling any Drake code.
The following recipe determines the value that Parallelism::Max().num_threads()
will report:
1. The default is the hardware limit from `std::thread::hardware_concurrency()`;
this will be used when none of the special cases below are in effect.
2. If the environment variable `DRAKE_NUM_THREADS` is set to a positive integer
less than `hardware_concurrency()`, the `num_threads` will be that value.
3. If the environment variable `DRAKE_NUM_THREADS` is not set but the
environment variable `OMP_NUM_THREADS` is set to a positive integer less than
`hardware_concurrency()`, the `num_threads` will be that value. (Note in
particular that a comma-separated `OMP_NUM_THREADS` value will be ignored, even
though that syntax might be valid for an OpenMP library).
The configuration recipe above does not require Drake to be built with OpenMP
enabled. The inspection of `OMP_NUM_THREADS` as a configuration value is
provided for convenience, regardless of whether OpenMP is enabled.
<b>A note for Drake developers</b>
In Drake's unit tests, `DRAKE_NUM_THREADS` is set to "1" by default. If your
unit test requires actual parallelism, use the `num_threads = N` attribute in
the `BUILD.bazel` file to declare a different value. */
class Parallelism {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Parallelism)
/** Constructs a %Parallelism with no parallelism (i.e., num_threads=1).
Python note: This function is not bound in pydrake (due to its name); instead,
use the default constructor (or pass either `1` or `False` to the 1-argument
constructor). */
static Parallelism None() { return Parallelism(); }
/** Constructs a %Parallelism with the maximum number of threads. Refer to the
class overview documentation for how to configure the maximum. */
static Parallelism Max();
/** Default constructs with no parallelism (i.e., num_threads=1). */
Parallelism() = default;
/** Constructs a %Parallelism with either no parallelism (i.e., num_threads=1)
or the maximum number of threads (Max()), as selected by `parallelize`. This
constructor allows for implicit conversion, for convenience. */
Parallelism(bool parallelize) { // NOLINT(runtime/explicit)
if (parallelize) {
*this = Max();
}
}
/** Constructs with the provided number of threads `num_threads`.
@pre num_threads >= 1.
@note Constructing and using a %Parallelism with num_threads greater than the
actual hardware concurrency may result in fewer than the specified number of
threads actually being launched or poor performance due to CPU contention. */
explicit Parallelism(int num_threads) : num_threads_(num_threads) {
DRAKE_THROW_UNLESS(num_threads >= 1);
}
/** Returns the degree of parallelism. The result will always be >= 1. */
int num_threads() const { return num_threads_; }
private:
int num_threads_ = 1;
};
namespace internal {
// Exposed for unit testing.
int ConfigureMaxNumThreads(const char* drake_num_threads,
const char* omp_num_threads);
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_cache.h | #pragma once
#include <filesystem>
#include <string>
#include <string_view>
namespace drake {
namespace internal {
/* The return type of FindOrCreateDrakeCache(). Exactly one of the two strings
is non-empty. */
struct PathOrError {
/** The absolute path to a writeable, Drake-specific cache directory. */
std::filesystem::path abspath;
/** The error message. */
std::string error;
};
/* Returns the platform-appropriate location for ~/.cache/drake/{subdir},
creating it if necessary. */
PathOrError FindOrCreateCache(std::string_view subdir);
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/cond.cc | #include "drake/common/cond.h"
// For now, this is an empty .cc file that only serves to confirm that cond.h
// is a stand-alone header.
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_runfiles_stub.cc | /* clang-format off to disable clang-format-includes */
#include "drake/common/find_runfiles.h"
/* clang-format on */
// This is a stubbed-out implementation of find_runfiles.h. Its purpose is for
// downstream users who choose not to run Drake's CMakeLists.txt nor BUILD
// files, but instead are writing their own build system for a subset of Drake.
//
// By providing this stub, those users can avoid the need to satisfy the
// include statement for "tools/cpp/runfiles/runfiles.h" when compiling
// find_runfiles.cc -- that header is provided internally by Bazel.
//
// This implementation is NOT used by the Bazel build (outside of the unit
// test); it's not even used in the Bazel-installed binary release build (e.g.,
// as called by Drake's CMakeLists.txt files). It is nominally dead code.
namespace drake {
bool HasRunfiles() {
return false;
}
RlocationOrError FindRunfile(const std::string& resource_path) {
RlocationOrError result;
result.error = "FindRunfile is stubbed out";
return result;
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/name_value.h | #pragma once
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
namespace drake {
/// (Advanced) A basic implementation of the Name-Value Pair concept as used in
/// the Serialize / Archive pattern.
///
/// %NameValue stores a pointer to a const `name` and a pointer to a mutable
/// `value`. Both pointers must remain valid throughout the lifetime of an
/// object. %NameValue objects are typically short-lived, existing only for a
/// transient moment while an Archive is visiting some Serializable field.
///
/// For more information, refer to Drake's
/// @ref yaml_serialization "YAML Serialization" and especially the
/// @ref implementing_serialize "Implementing Serialize" section, or also the
/// <a href="https://www.boost.org/doc/libs/release/libs/serialization/doc/wrappers.html#nvp">Boost
/// Name-Value Pairs</a> documentation for background.
template <typename T>
class NameValue {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(NameValue)
/// Type of the referenced value.
typedef T value_type;
/// (Advanced) Constructs a %NameValue. Prefer DRAKE_NVP instead of this
/// constructor. Both pointers are aliased and must remain valid for the
/// lifetime of this object. Neither pointer can be nullptr.
NameValue(const char* name_in, T* value_in)
: name_(name_in), value_(value_in) {
DRAKE_ASSERT(name_in != nullptr);
DRAKE_ASSERT(value_in != nullptr);
}
/// @name Accessors to the raw pointers
//@{
const char* name() const { return name_; }
T* value() const { return value_; }
//@}
private:
const char* const name_;
T* const value_;
};
/// (Advanced) Creates a NameValue. The conventional method for calling this
/// function is the DRAKE_NVP sugar macro below.
///
/// Both pointers are aliased for the lifetime of the return value.
template <typename T>
NameValue<T> MakeNameValue(const char* name, T* value) {
return NameValue<T>(name, value);
}
} // namespace drake
/// Creates a NameValue pair for an lvalue `x`.
#define DRAKE_NVP(x) ::drake::MakeNameValue(#x, &(x))
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_bool.h | #pragma once
#include <type_traits>
#include <Eigen/Core>
#include "drake/common/double_overloads.h"
#include "drake/common/drake_throw.h"
namespace drake {
/// A traits struct that describes the return type of predicates over a scalar
/// type (named `T`). For example, a predicate that evaluates `double`s will
/// return a `bool`, but a predicate that evaluates symbolic::Expression will
/// return a symbolic::Formula. By default, the return type is inferred from
/// the type's comparison operator, but scalar types are permitted to
/// specialize this template for their needs.
template <typename T>
struct scalar_predicate {
/// The return type of predicates over T.
using type = decltype(T() < T());
/// Whether `type` is `bool`.
static constexpr bool is_bool = std::is_same_v<type, bool>;
};
/// An alias for a boolean-like value, conditioned on the scalar type `T`.
/// In many cases this will be a synonym for `bool`, e.g., when `T = double`.
/// When `T = symbolic::Expression`, this is a synonym for `symbolic::Formula`.
/// This is a convenience abbreviation for scalar_predicate<T>::type.
template <typename T>
using boolean = typename scalar_predicate<T>::type;
/// Checks truth for all elements in matrix @p m. This is identical to
/// `Eigen::DenseBase::all()`, except this function allows for lazy evaluation,
/// so works even when scalar_predicate<>::is_bool does not hold. An empty
/// matrix returns true.
template <typename Derived>
typename Derived::Scalar all(const Eigen::DenseBase<Derived>& m) {
using Boolish = typename Derived::Scalar;
if (m.rows() == 0 || m.cols() == 0) {
// `all` holds vacuously when there is nothing to check.
return Boolish{true};
}
return m.redux([](const Boolish& v1, const Boolish& v2) {
return v1 && v2;
});
}
/// Checks if unary predicate @p pred holds for all elements in the matrix @p m.
/// An empty matrix returns true.
template <typename Derived>
boolean<typename Derived::Scalar> all_of(
const Eigen::MatrixBase<Derived>& m,
const std::function<boolean<typename Derived::Scalar>(
const typename Derived::Scalar&)>& pred) {
return drake::all(m.unaryExpr(pred));
}
/// Checks truth for at least one element in matrix @p m. This is identical to
/// `Eigen::DenseBase::any()`, except this function allows for lazy evaluation,
/// so works even when scalar_predicate<>::is_bool does not hold. An empty
/// matrix returns false.
template <typename Derived>
typename Derived::Scalar any(const Eigen::DenseBase<Derived>& m) {
using Boolish = typename Derived::Scalar;
if (m.rows() == 0 || m.cols() == 0) {
// `any` is vacuously false when there is nothing to check.
return Boolish{false};
}
return m.redux([](const Boolish& v1, const Boolish& v2) {
return v1 || v2;
});
}
/// Checks if unary predicate @p pred holds for at least one element in the
/// matrix @p m. An empty matrix returns false.
template <typename Derived>
boolean<typename Derived::Scalar> any_of(
const Eigen::MatrixBase<Derived>& m,
const std::function<boolean<typename Derived::Scalar>(
const typename Derived::Scalar&)>& pred) {
return any(m.unaryExpr(pred));
}
/// Checks that no elements of @p m are true. An empty matrix returns true.
template <typename Derived>
typename Derived::Scalar none(const Eigen::MatrixBase<Derived>& m) {
using Boolish = typename Derived::Scalar;
const auto negate = [](const Boolish& v) -> Boolish {
return !v;
};
return drake::all(m.unaryExpr(negate));
}
/// Checks if unary predicate @p pred holds for no elements in the matrix @p m.
/// An empty matrix returns true.
template <typename Derived>
boolean<typename Derived::Scalar> none_of(
const Eigen::MatrixBase<Derived>& m,
const std::function<boolean<typename Derived::Scalar>(
const typename Derived::Scalar&)>& pred) {
return none(m.unaryExpr(pred));
}
/// Overloads if_then_else for Eigen vectors of `m_then` and `m_else` values
/// with with a single `f_cond` condition to toggle them all at once.
template <typename T, int Rows>
auto if_then_else(const boolean<T>& f_cond,
const Eigen::Matrix<T, Rows, 1>& m_then,
const Eigen::Matrix<T, Rows, 1>& m_else) {
DRAKE_THROW_UNLESS(m_then.rows() == m_else.rows());
const int rows = m_then.rows();
Eigen::Matrix<T, Rows, 1> result(rows);
for (int i = 0; i < rows; ++i) {
result[i] = if_then_else(f_cond, m_then[i], m_else[i]);
}
return result;
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/sha256.h | #pragma once
#include <array>
#include <cstdint>
#include <cstring>
#include <iosfwd>
#include <optional>
#include <string>
#include "drake/common/drake_copyable.h"
namespace drake {
/** Represents a SHA-256 cryptographic checksum.
See also https://en.wikipedia.org/wiki/SHA-2.
This class is not bound in pydrake, because Python programmers should prefer
using https://docs.python.org/3/library/hashlib.html instead. */
class Sha256 final {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Sha256);
/** Constructs an all-zero checksum.
Note that this is NOT the same as the checksum of empty (zero-sized) data. */
Sha256() { bytes_.fill(0); }
/** Computes the checksum of the given `data` buffer. */
static Sha256 Checksum(std::string_view data);
/** Computes the checksum of the given `stream`.
Does not check for istream errors; that is the responsibility of the caller.
@pre stream != nullptr. */
static Sha256 Checksum(std::istream* stream);
/** Parses the 64-character ASCII hex representation of a SHA-256 checksum.
Returns std::nullopt if the argument is an invalid checksum. */
static std::optional<Sha256> Parse(std::string_view sha256);
/** Returns the 64-character ASCII hex representation of this checksum. */
std::string to_string() const;
// Offer typical comparison operations.
bool operator==(const Sha256& other) const { return bytes_ == other.bytes_; }
bool operator!=(const Sha256& other) const { return bytes_ != other.bytes_; }
bool operator<(const Sha256& other) const { return bytes_ < other.bytes_; }
private:
friend class std::hash<Sha256>;
std::array<uint8_t, 32> bytes_;
};
} // namespace drake
namespace std {
/** The STL container hash for Sha256 objects. This implementation avoids using
drake::hash_append for performance. The checksum should already be well-mixed,
so we can just squash it down into the required size. */
template <>
struct hash<drake::Sha256> {
size_t operator()(const drake::Sha256& x) const noexcept {
constexpr int kInputSize = sizeof(x.bytes_);
constexpr int kWordSize = sizeof(size_t);
static_assert(kInputSize % kWordSize == 0);
constexpr int kNumSteps = kInputSize / kWordSize;
size_t result = 0;
for (int i = 0; i < kNumSteps; ++i) {
// A memcpy is the canonical tool to convert raw memory between different
// compile-time types -- compilers will always optimize it away in release
// builds. The whole operator() implementation compiles down to just four
// instructions (the xor'ing of four 64-bit words).
size_t temp;
std::memcpy(&temp, x.bytes_.data() + i * kWordSize, kWordSize);
result = result ^ temp;
}
return result;
}
};
} // namespace std
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/type_safe_index.h | #pragma once
#include <limits>
#include <string>
#include <typeinfo>
#include "drake/common/drake_assert.h"
#include "drake/common/fmt_ostream.h"
#include "drake/common/hash.h"
namespace drake {
namespace internal {
[[noreturn]] void ThrowTypeSafeIndexAssertValidFailed(
const std::type_info& type, const char* source);
[[noreturn]] void ThrowTypeSafeIndexAssertNoOverflowFailed(
const std::type_info& type, const char* source);
} // namespace internal
/// A type-safe non-negative index class.
///
/// @note This is *purposely* a separate class from Identifier.
/// For more information, see @ref TypeSafeIndexVsIndentifier "this section".
///
/// This class serves as an upgrade to the standard practice of passing `int`s
/// around as indices. In the common practice, a method that takes indices into
/// multiple collections would have an interface like:
///
/// @code
/// void foo(int bar_index, int thing_index);
/// @endcode
///
/// It is possible for a programmer to accidentally switch the two index values
/// in an invocation. This mistake would still be _syntactically_ correct; it
/// will successfully compile but lead to inscrutable run-time errors. The
/// type-safe index provides the same speed and efficiency of passing `int`s,
/// but provides compile-time checking. The function would now look like:
///
/// @code
/// void foo(BarIndex bar_index, ThingIndex thing_index);
/// @endcode
///
/// and the compiler will catch instances where the order is reversed.
///
/// The type-safe index is a _stripped down_ `int`. Each uniquely declared
/// index type has the following properties:
///
/// - Valid index values are _explicitly_ constructed from `int` values.
/// - The index is implicitly convertible to an `int` (to serve as an index).
/// - The index supports increment, decrement, and in-place addition and
/// subtraction to support standard index-like operations.
/// - An index _cannot_ be constructed or compared to an index of another
/// type.
/// - In general, indices of different types are _not_ interconvertible.
/// - Binary integer operators (e.g., +, -, |, *, etc.) _always_ produce `int`
/// return values. One can even use operands of different index types in
/// such a binary expression. It is the _programmer's_ responsibility to
/// confirm that the resultant `int` value has meaning.
///
/// While there _is_ the concept of an "invalid" index, this only exists to
/// support default construction _where appropriate_ (e.g., using indices in
/// STL containers). Using an invalid index in _any_ operation is considered
/// an error. In Debug build, attempts to compare, increment, decrement, etc. an
/// invalid index will throw an exception.
///
/// A function that returns %TypeSafeIndex values which need to communicate
/// failure should _not_ use an invalid index. It should return an
/// `std::optional<Index>` instead.
///
/// It is the designed intent of this class, that indices derived from this
/// class can be passed and returned by value. (Drake's typical calling
/// convention requires passing input arguments by const reference, or by value
/// when moved from. That convention does not apply to this class.)
///
/// This is the recommended method to create a unique index type associated with
/// class `Foo`:
///
/// @code
/// using FooIndex = TypeSafeIndex<class FooTag>;
/// @endcode
///
/// This references a non-existent, and ultimately anonymous, class `FooTag`.
/// This is sufficient to create a unique index type. It is certainly possible
/// to use an existing class (e.g., `Foo`). But this provides no functional
/// benefit.
///
/// __Construction from integral types__
///
/// C++ will do
/// [implicit integer conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_conversions).
/// This allows construction of %TypeSafeIndex values with arbitrary integral
/// types. Index values must lie in the range of [0, 2³¹). The constructor will
/// validate the input value (in Debug mode). Ultimately, the caller is
/// responsible for confirming that the values provided lie in the valid range.
///
/// __Examples of valid and invalid operations__
///
/// The TypeSafeIndex guarantees that index instances of different types can't
/// be compared or combined. Efforts to do so will cause a compile-time
/// failure. However, comparisons or operations on _other_ types that are
/// convertible to an int will succeed. For example:
/// @code
/// using AIndex = TypeSafeIndex<class A>;
/// using BIndex = TypeSafeIndex<class B>;
/// AIndex a(1);
/// BIndex b(1);
/// if (a == 2) { ... } // Ok.
/// size_t sz = 7;
/// if (a == sz) { ... } // Ok.
/// if (a == b) { ... } // <-- Compiler error.
/// AIndex invalid; // Creates an invalid index.
/// ++invalid; // Runtime error in Debug build.
/// @endcode
///
/// As previously stated, the intent of this class is to seamlessly serve as an
/// index into indexed objects (e.g., vector, array, etc.). At the same time, we
/// want to avoid implicit conversions _from_ int to an index. These two design
/// constraints combined lead to a limitation in how TypeSafeIndex instances
/// can be used. Specifically, we've lost a common index pattern:
///
/// @code
/// for (MyIndex a = 0; a < N; ++a) { ... }
/// @endcode
///
/// This pattern no longer works because it requires implicit conversion of int
/// to TypeSafeIndex. Instead, the following pattern needs to be used:
///
/// @code
/// for (MyIndex a(0); a < N; ++a) { ... }
/// @endcode
///
/// __Use with Eigen__
///
/// At the time of this writing when using the latest Eigen 3.4 preview branch,
/// a TypeSafeIndex cannot be directly used to index into an Eigen::Matrix; the
/// developer must explicitly introduce the `int` conversion:
/// @code
/// VectorXd some_vector = ...;
/// FooIndex foo_index = ...;
/// some_vector(foo_index) = 0.0; // Fails to compile.
/// some_vector(int{foo_index}) = 0.0; // Compiles OK.
/// @endcode
/// TODO(#15354) We hope to fix this irregularity in the future.
///
/// @sa drake::geometry::Identifier
///
/// @tparam Tag The name of the tag associated with a class type. The class
/// need not be a defined class.
template <class Tag>
class TypeSafeIndex {
public:
/// @name Constructors
///@{
/// Default constructor; the result is an _invalid_ index. This only
/// exists to serve applications which require a default constructor.
TypeSafeIndex() {}
/// Construction from a non-negative `int` value. The value must lie in the
/// range of [0, 2³¹). Constructor only promises to test validity in
/// Debug build.
explicit TypeSafeIndex(int64_t index) : index_(static_cast<int>(index)) {
// NOTE: This tests the *input* value and not the result as an invalid
// input can lead to a truncation that appears valid.
DRAKE_ASSERT_VOID(
AssertValid(index, "Explicitly constructing an invalid index."));
}
/// Disallow construction from another index type.
template <typename U>
TypeSafeIndex(const TypeSafeIndex<U>& idx) = delete;
TypeSafeIndex(const TypeSafeIndex&) = default;
TypeSafeIndex(TypeSafeIndex&& other) noexcept : index_(other.index_) {
other.index_ = kDefaultInvalid;
}
///@}
/// @name Assignment
///@{
TypeSafeIndex& operator=(const TypeSafeIndex&) = default;
TypeSafeIndex& operator=(TypeSafeIndex&& other) noexcept {
index_ = other.index_;
other.index_ = kDefaultInvalid;
return *this;
}
///@}
/// @name Utility methods
///@{
/// Implicit conversion-to-int operator.
operator int() const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Converting to an int."));
return index_;
}
/// Reports if the index is valid--the only operation on an invalid index
/// that doesn't throw an exception in Debug builds.
bool is_valid() const {
// All other error testing, with assert armed, indirectly enforces the
// invariant that the only way to get an invalid index is via the default
// constructor. This assertion will catch any crack in that effort.
DRAKE_ASSERT((index_ >= 0) || (index_ == kDefaultInvalid));
return index_ >= 0;
}
///@}
/// @name Arithmetic operators
///@{
/// Prefix increment operator.
const TypeSafeIndex& operator++() {
DRAKE_ASSERT_VOID(
AssertValid(index_, "Pre-incrementing an invalid index."));
DRAKE_ASSERT_VOID(
AssertNoOverflow(1, "Pre-incrementing produced an invalid index."));
++index_;
return *this;
}
/// Postfix increment operator.
TypeSafeIndex operator++(int) {
DRAKE_ASSERT_VOID(
AssertValid(index_, "Post-incrementing an invalid index."));
DRAKE_ASSERT_VOID(
AssertNoOverflow(1, "Post-incrementing produced an invalid index."));
++index_;
return TypeSafeIndex(index_ - 1);
}
/// Prefix decrement operator.
/// In Debug builds, this method asserts that the resulting index is
/// non-negative.
const TypeSafeIndex& operator--() {
DRAKE_ASSERT_VOID(
AssertValid(index_, "Pre-decrementing an invalid index."));
--index_;
DRAKE_ASSERT_VOID(
AssertValid(index_, "Pre-decrementing produced an invalid index."));
return *this;
}
/// Postfix decrement operator.
/// In Debug builds, this method asserts that the resulting index is
/// non-negative.
TypeSafeIndex operator--(int) {
DRAKE_ASSERT_VOID(
AssertValid(index_, "Post-decrementing an invalid index."));
--index_;
DRAKE_ASSERT_VOID(
AssertValid(index_, "Post-decrementing produced an invalid index."));
return TypeSafeIndex(index_ + 1);
}
///@}
/// @name Compound assignment operators
///@{
/// Addition assignment operator.
/// In Debug builds, this method asserts that the resulting index is
/// non-negative.
TypeSafeIndex& operator+=(int i) {
DRAKE_ASSERT_VOID(AssertValid(
index_, "In-place addition with an int on an invalid index."));
DRAKE_ASSERT_VOID(AssertNoOverflow(
i, "In-place addition with an int produced an invalid index."));
index_ += i;
DRAKE_ASSERT_VOID(AssertValid(
index_, "In-place addition with an int produced an invalid index."));
return *this;
}
/// Allow addition for indices with the same tag.
TypeSafeIndex<Tag>& operator+=(const TypeSafeIndex<Tag>& other) {
DRAKE_ASSERT_VOID(AssertValid(
index_, "In-place addition with another index invalid LHS."));
DRAKE_ASSERT_VOID(AssertValid(
other.index_, "In-place addition with another index invalid RHS."));
DRAKE_ASSERT_VOID(AssertNoOverflow(
other.index_,
"In-place addition with another index produced an invalid index."));
index_ += other.index_;
DRAKE_ASSERT_VOID(AssertValid(
index_,
"In-place addition with another index produced an invalid index."));
return *this;
}
/// Prevent addition for indices of different tags.
template <typename U>
TypeSafeIndex<U>& operator+=(const TypeSafeIndex<U>& u) = delete;
/// Subtraction assignment operator.
/// In Debug builds, this method asserts that the resulting index is
/// non-negative.
TypeSafeIndex& operator-=(int i) {
DRAKE_ASSERT_VOID(AssertValid(
index_, "In-place subtraction with an int on an invalid index."));
DRAKE_ASSERT_VOID(AssertNoOverflow(
-i, "In-place subtraction with an int produced an invalid index."));
index_ -= i;
DRAKE_ASSERT_VOID(AssertValid(
index_, "In-place subtraction with an int produced an invalid index."));
return *this;
}
/// Allow subtraction for indices with the same tag.
TypeSafeIndex<Tag>& operator-=(const TypeSafeIndex<Tag>& other) {
DRAKE_ASSERT_VOID(AssertValid(
index_, "In-place subtraction with another index invalid LHS."));
DRAKE_ASSERT_VOID(AssertValid(
other.index_, "In-place subtraction with another index invalid RHS."));
// No test for overflow; it would only be necessary if other had a negative
// index value. In that case, it would be invalid and that would be caught
// by the previous assertion.
index_ -= other.index_;
DRAKE_ASSERT_VOID(AssertValid(
index_,
"In-place subtraction with another index produced an invalid index."));
return *this;
}
/// Prevent subtraction for indices of different tags.
template <typename U>
TypeSafeIndex<U>& operator-=(const TypeSafeIndex<U>& u) = delete;
///@}
/// @name Exclusive comparison operators
///
/// In order to prevent indices _of different type_ being added together or
/// compared against each other, we explicitly include indices of this type,
/// but exclude indices of all other types. This implicitly allows all
/// _other_ objects that can be converted to int types.
///@{
// Note for developers: Each comparison operator has a SFINAE-based version
// for handling comparison with unsigned values (created to allow comparison
// with size_t). The explicit methods are necessary to enable comparison
// without unsigned/signed comparison warnings (which Drake considers to be an
// error). Furthermore, the SFINAE is necessary to prevent ambiguity.
// Index == int can be resolved two ways:
//
// - convert Index to int
// - promote int to size_t
//
// SFINAE prevents the latter.
/// Allow equality test with indices of this tag.
bool operator==(const TypeSafeIndex<Tag>& other) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing == with invalid LHS."));
DRAKE_ASSERT_VOID(
AssertValid(other.index_, "Testing == with invalid RHS."));
return index_ == other.index_;
}
/// Allow equality test with unsigned integers.
template <typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>,
bool>
operator==(const U& value) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing == with invalid index."));
return value <= static_cast<U>(kMaxIndex) &&
index_ == static_cast<int>(value);
}
/// Prevent equality tests with indices of other tags.
template <typename U>
bool operator==(const TypeSafeIndex<U>& u) const = delete;
/// Allow inequality test with indices of this tag.
bool operator!=(const TypeSafeIndex<Tag>& other) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing != with invalid LHS."));
DRAKE_ASSERT_VOID(
AssertValid(other.index_, "Testing != with invalid RHS."));
return index_ != other.index_;
}
/// Allow inequality test with unsigned integers.
template <typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>,
bool>
operator!=(const U& value) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing != with invalid index."));
return value > static_cast<U>(kMaxIndex) ||
index_ != static_cast<int>(value);
}
/// Prevent inequality test with indices of other tags.
template <typename U>
bool operator!=(const TypeSafeIndex<U>& u) const = delete;
/// Allow less than test with indices of this tag.
bool operator<(const TypeSafeIndex<Tag>& other) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing < with invalid LHS."));
DRAKE_ASSERT_VOID(AssertValid(other.index_, "Testing < with invalid RHS."));
return index_ < other.index_;
}
/// Allow less than test with unsigned integers.
template <typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>,
bool>
operator<(const U& value) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing < with invalid index."));
return value > static_cast<U>(kMaxIndex) ||
index_ < static_cast<int>(value);
}
/// Prevent less than test with indices of other tags.
template <typename U>
bool operator<(const TypeSafeIndex<U>& u) const = delete;
/// Allow less than or equals test with indices of this tag.
bool operator<=(const TypeSafeIndex<Tag>& other) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing <= with invalid LHS."));
DRAKE_ASSERT_VOID(
AssertValid(other.index_, "Testing <= with invalid RHS."));
return index_ <= other.index_;
}
/// Allow less than or equals test with unsigned integers.
template <typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>,
bool>
operator<=(const U& value) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing <= with invalid index."));
return value > static_cast<U>(kMaxIndex) ||
index_ <= static_cast<int>(value);
}
/// Prevent less than or equals test with indices of other tags.
template <typename U>
bool operator<=(const TypeSafeIndex<U>& u) const = delete;
/// Allow greater than test with indices of this tag.
bool operator>(const TypeSafeIndex<Tag>& other) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing > with invalid LHS."));
DRAKE_ASSERT_VOID(AssertValid(other.index_, "Testing > with invalid RHS."));
return index_ > other.index_;
}
/// Allow greater than test with unsigned integers.
template <typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>,
bool>
operator>(const U& value) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing > with invalid index."));
return value <= static_cast<U>(kMaxIndex) &&
index_ > static_cast<int>(value);
}
/// Prevent greater than test with indices of other tags.
template <typename U>
bool operator>(const TypeSafeIndex<U>& u) const = delete;
/// Allow greater than or equals test with indices of this tag.
bool operator>=(const TypeSafeIndex<Tag>& other) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing >= with invalid LHS."));
DRAKE_ASSERT_VOID(
AssertValid(other.index_, "Testing >= with invalid RHS."));
return index_ >= other.index_;
}
/// Allow greater than or equals test with unsigned integers.
template <typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>,
bool>
operator>=(const U& value) const {
DRAKE_ASSERT_VOID(AssertValid(index_, "Testing >= with invalid index."));
return value <= static_cast<U>(kMaxIndex) &&
index_ >= static_cast<int>(value);
}
/// Prevent greater than or equals test with indices of other tags.
template <typename U>
bool operator>=(const TypeSafeIndex<U>& u) const = delete;
///@}
/// Implements the @ref hash_append concept. And invalid index will
/// successfully hash (in order to satisfy STL requirements), and it is up to
/// the user to confirm it is valid before using it as a key (or other hashing
/// application).
template <typename HashAlgorithm>
friend void hash_append(HashAlgorithm& hasher,
const TypeSafeIndex& i) noexcept {
using drake::hash_append;
hash_append(hasher, i.index_);
}
private:
// Checks if this index lies in the valid range; throws an exception if not.
// Invocations provide a string explaining the origin of the bad value.
static void AssertValid(int64_t index, const char* source) {
if (index < 0 || index > kMaxIndex) {
internal::ThrowTypeSafeIndexAssertValidFailed(typeid(TypeSafeIndex),
source);
}
}
// This tests for overflow conditions based on adding the given delta into
// the current index value.
void AssertNoOverflow(int delta, const char* source) const {
if (delta > 0 && index_ > kMaxIndex - delta) {
internal::ThrowTypeSafeIndexAssertNoOverflowFailed(typeid(TypeSafeIndex),
source);
}
}
// This value helps distinguish indices that are invalid through construction
// or moves versus user manipulation.
enum { kDefaultInvalid = -1234567 };
int index_{kDefaultInvalid};
// The largest representable index.
// Note: The handling of comparisons of TypeSafeIndex with unsigned integral
// types with *fewer* bits relies on truncations of *this* value consisting
// of all 1s. The maximum int satisfies that requirement. If, for whatever
// reason, some *alternative* maximum index is preferred (or the underlying
// integral type of TypeSafeIndex changes), keep this requirement in mind.
// Otherwise, comparisons against smaller unsigned integral types is likely
// to fail.
static constexpr int kMaxIndex = std::numeric_limits<int>::max();
};
template <typename Tag, typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>, bool>
operator==(const U& value, const TypeSafeIndex<Tag>& tag) {
return tag.operator==(value);
}
template <typename Tag, typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>, bool>
operator!=(const U& value, const TypeSafeIndex<Tag>& tag) {
return tag.operator!=(value);
}
template <typename Tag, typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>, bool>
operator<(const U& value, const TypeSafeIndex<Tag>& tag) {
return tag >= value;
}
template <typename Tag, typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>, bool>
operator<=(const U& value, const TypeSafeIndex<Tag>& tag) {
return tag > value;
}
template <typename Tag, typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>, bool>
operator>(const U& value, const TypeSafeIndex<Tag>& tag) {
return tag <= value;
}
template <typename Tag, typename U>
typename std::enable_if_t<std::is_integral_v<U> && std::is_unsigned_v<U>, bool>
operator>=(const U& value, const TypeSafeIndex<Tag>& tag) {
return tag < value;
}
} // namespace drake
namespace std {
/// Enables use of the type-safe index to serve as a key in STL containers.
/// @relates TypeSafeIndex
template <typename Tag>
struct hash<drake::TypeSafeIndex<Tag>> : public drake::DefaultHash {};
} // namespace std
// TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<.
namespace fmt {
template <typename Tag>
struct formatter<drake::TypeSafeIndex<Tag>> : drake::ostream_formatter {};
} // namespace fmt
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_throw.h | #pragma once
#include <type_traits>
#include "drake/common/drake_assert.h"
/// @file
/// Provides a convenient wrapper to throw an exception when a condition is
/// unmet. This is similar to an assertion, but uses exceptions instead of
/// ::abort(), and cannot be disabled.
namespace drake {
namespace internal {
// Throw an error message.
[[noreturn]] void Throw(const char* condition, const char* func,
const char* file, int line);
} // namespace internal
} // namespace drake
/// Evaluates @p condition and iff the value is false will throw an exception
/// with a message showing at least the condition text, function name, file,
/// and line.
///
/// The condition must not be a pointer, where we'd implicitly rely on its
/// nullness. Instead, always write out "!= nullptr" to be precise.
///
/// Correct: `DRAKE_THROW_UNLESS(foo != nullptr);`
/// Incorrect: `DRAKE_THROW_UNLESS(foo);`
///
/// Because this macro is intended to provide a useful exception message to
/// users, we should err on the side of extra detail about the failure. The
/// meaning of "foo" isolated within error message text does not make it
/// clear that a null pointer is the proximate cause of the problem.
#define DRAKE_THROW_UNLESS(condition) \
do { \
typedef ::drake::assert::ConditionTraits< \
typename std::remove_cv_t<decltype(condition)>> Trait; \
static_assert(Trait::is_valid, "Condition should be bool-convertible."); \
static_assert( \
!std::is_pointer_v<decltype(condition)>, \
"When using DRAKE_THROW_UNLESS on a raw pointer, always write out " \
"DRAKE_THROW_UNLESS(foo != nullptr), do not write DRAKE_THROW_UNLESS" \
"(foo) and rely on implicit pointer-to-bool conversion."); \
if (!Trait::Evaluate(condition)) { \
::drake::internal::Throw(#condition, __func__, __FILE__, __LINE__); \
} \
} while (0)
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_runfiles.h | #pragma once
#include <string>
/** @file
This file contains helpers to work with Bazel-declared runfiles -- declared
data dependencies used by C++ code. The functions in this file only succeed
when used within a Bazel build.
All source code within Drake should use FindResource() or FindResourceOrThrow()
instead of these Runfiles routines, because FindResource will operate correctly
in pre-compiled / installed builds of Drake whereas FindRunfile will not.
These runfiles-related helpers are intended for use by downstream Bazel
projects that use Drake as a library, so that those projects can reuse the
relatively complicated logic within these routines during source builds.
*/
namespace drake {
/** (Advanced.) Returns true iff this process has Bazel runfiles available.
For both C++ and Python programs, and no matter what workspace a program
resides in (`@drake` or otherwise), this will be true when running
`bazel-bin/pkg/program` or `bazel test //pkg:program` or `bazel run
//pkg:program`. */
bool HasRunfiles();
/** (Advanced.) The return type of FindRunfile(). Exactly one of the two
strings is non-empty. */
struct RlocationOrError {
/** The absolute path to the resource_path runfile. */
std::string abspath;
/** The error message. */
std::string error;
};
/** (Advanced.) Returns the absolute path to the given resource_path from Bazel
runfiles, or else an error message when not found. When HasRunfiles() is
false, returns an error. The `resource_path` looks like
`workspace/pkg/subpkg/file.ext`, e.g., "drake/common/foo.txt". */
RlocationOrError FindRunfile(const std::string& resource_path);
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_cache.cc | #include "drake/common/find_cache.h"
#include <cstdlib>
#include <filesystem>
#include <optional>
#include <utility>
#include <fmt/format.h>
#include "drake/common/drake_assert.h"
#include "drake/common/text_logging.h"
namespace drake {
namespace internal {
namespace {
namespace fs = std::filesystem;
#if defined(__APPLE__)
constexpr bool kApple = true;
#else
constexpr bool kApple = false;
#endif
/* If var_name is set, returns its value. Otherwise, returns nullopt. */
std::optional<std::string> GetStringEnv(const char* var_name) {
const char* const var_value = std::getenv(var_name);
if (var_value != nullptr) {
return var_value;
}
return std::nullopt;
}
/* If var_name is set to a directory that exists, returns that path.
Otherwise, returns nullopt. */
std::optional<fs::path> GetPathEnv(const char* var_name) {
const char* const var_value = std::getenv(var_name);
if (var_value != nullptr) {
auto path = fs::path{var_value};
std::error_code ec;
if (fs::is_directory(path, ec)) {
return path;
}
}
return std::nullopt;
}
/* If path exists, returns it. Otherwise, creates it and returns it. */
PathOrError CreateDirectory(fs::path path) {
std::error_code ec;
fs::create_directory(path, ec);
if (ec) {
return {.error = fmt::format("Could not create {}: {}", path.string(),
ec.message())};
}
return {.abspath = fs::canonical(path)};
}
} // namespace
PathOrError FindOrCreateCache(std::string_view subdir) {
// We'll try the following options to find the ~/.cache, in order:
// - ${TEST_TMPDIR}/.cache
// - ${XDG_CACHE_HOME}
// - /private/var/tmp/.cache_${USER} (on Apple only)
// - ${HOME}/.cache
const std::optional<fs::path> test_tmpdir = GetPathEnv("TEST_TMPDIR");
const std::optional<fs::path> xdg_cache_home = GetPathEnv("XDG_CACHE_HOME");
const std::optional<std::string> user = GetStringEnv("USER");
const std::optional<fs::path> home = GetPathEnv("HOME");
PathOrError cache_dir;
if (test_tmpdir.has_value()) {
cache_dir = CreateDirectory(*test_tmpdir / ".cache");
} else if (xdg_cache_home.has_value()) {
cache_dir.abspath = *xdg_cache_home;
} else if (kApple && user.has_value()) {
cache_dir = CreateDirectory(fs::path("/private/var/tmp") /
fmt::format(".cache_{}", *user));
} else if (home.has_value()) {
cache_dir = CreateDirectory(*home / ".cache");
} else {
return {.error =
"Could not determine an appropriate cache_dir to use. "
"Set $XDG_CACHE_HOME to a valid scratch directory."};
}
if (!cache_dir.error.empty()) {
return cache_dir;
}
// Create the Drake-specific subdirectory.
auto cache_dir_drake = CreateDirectory(cache_dir.abspath / "drake");
if (!cache_dir_drake.error.empty()) {
return cache_dir_drake;
}
log()->debug("FindCache found {}", cache_dir_drake.abspath.string());
// Create the requested subdirectory.
return CreateDirectory(cache_dir_drake.abspath / subdir);
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_loaded_library.cc | #include "drake/common/find_loaded_library.h"
#include <filesystem>
#include "drake/common/drake_throw.h"
// clang-format off
#ifdef __APPLE__
#include <dlfcn.h>
#include <mach-o/dyld.h>
#include <mach-o/dyld_images.h>
#else
#include <libgen.h> // dirname
#include <link.h>
#include <linux/limits.h> // PATH_MAX
#include <string.h>
#include <unistd.h>
#endif
// clang-format on
using std::string;
namespace drake {
#ifdef __APPLE__
// This code has been adapted from:
// https://stackoverflow.com/questions/4309117/determining-programmatically-what-modules-are-loaded-in-another-process-os-x/23229148#23229148
namespace {
// Reads memory from MacOS specific structures into an `unsigned char*`.
unsigned char* ReadProcessMemory(mach_vm_address_t addr,
mach_msg_type_number_t* size) {
vm_offset_t readMem;
kern_return_t kr = vm_read(mach_task_self(), addr, *size, &readMem, size);
if (kr != KERN_SUCCESS) {
return NULL;
}
return (reinterpret_cast<unsigned char*>(readMem));
}
} // namespace
// Gets the list of all the dynamic libraries that have been loaded. Finds
// `library_name` in the list, and returns its absolute directory path.
// This function is specific to MacOS
std::optional<string> LoadedLibraryPath(const string& library_name) {
task_dyld_info dyld_info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
// Getinformation from current process.
if (task_info(mach_task_self(), TASK_DYLD_INFO,
reinterpret_cast<task_info_t>(&dyld_info),
&count) == KERN_SUCCESS) {
// Recover list of dynamic libraries.
mach_msg_type_number_t size = sizeof(dyld_all_image_infos);
unsigned char* data =
ReadProcessMemory(dyld_info.all_image_info_addr, &size);
if (!data) {
return std::nullopt;
}
dyld_all_image_infos* infos = reinterpret_cast<dyld_all_image_infos*>(data);
// Recover number of dynamic libraries in list.
mach_msg_type_number_t size2 =
sizeof(dyld_image_info) * infos->infoArrayCount;
unsigned char* info_addr = ReadProcessMemory(
reinterpret_cast<mach_vm_address_t>(infos->infoArray), &size2);
if (!info_addr) {
return std::nullopt;
}
dyld_image_info* info = reinterpret_cast<dyld_image_info*>(info_addr);
// Loop over the dynamic libraries until `library_name` is found.
for (uint32_t i = 0; i < infos->infoArrayCount; i++) {
const char* pos_slash = strrchr(info[i].imageFilePath, '/');
if (!strcmp(pos_slash + 1, library_name.c_str())) {
// Path is always absolute on MacOS.
return string(info[i].imageFilePath, pos_slash - info[i].imageFilePath);
}
}
}
return std::nullopt;
}
#else // Not __APPLE__
// Gets the list of all the shared objects that have been loaded. Finds
// `library_name` in the list, and returns its absolute directory path.
// This function is specific to Linux.
std::optional<string> LoadedLibraryPath(const std::string& library_name) {
void* handle = dlopen(NULL, RTLD_NOW);
link_map* map;
dlinfo(handle, RTLD_DI_LINKMAP, &map);
// Loop over loaded shared objects until `library_name` is found.
while (map) {
// Avoid using `basename()` and `dirname()` implemented in `libgen.h`
// because as stated in `libgen.h` documentation [1], both functions
// may modify the content of the input c-string (which happened in the
// original implementation and resulted in a bug).
// [1] http://man7.org/linux/man-pages/man3/basename.3.html#DESCRIPTION
const char* pos_slash = strrchr(map->l_name, '/');
if (pos_slash && !strcmp(pos_slash + 1, library_name.c_str())) {
// Check if path is relative. If so, make it absolute.
if (map->l_name[0] != '/') {
std::string argv0 =
std::filesystem::read_symlink({"/proc/self/exe"}).string();
return string(dirname(&argv0[0])) + "/" +
string(map->l_name, pos_slash - map->l_name);
} else {
return string(map->l_name, pos_slash - map->l_name);
}
}
map = map->l_next;
}
return std::nullopt;
}
#endif
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/dummy_value.h | #pragma once
#include <limits>
namespace drake {
/// Provides a "dummy" value for a ScalarType -- a value that is unlikely to be
/// mistaken for a purposefully-computed value, useful for initializing a value
/// before the true result is available.
///
/// Defaults to using std::numeric_limits::quiet_NaN when available; it is a
/// compile-time error to call the unspecialized dummy_value::get() when
/// quiet_NaN is unavailable.
///
/// See autodiff_overloads.h to use this with Eigen's AutoDiffScalar.
template <typename T>
struct dummy_value {
static constexpr T get() {
static_assert(std::numeric_limits<T>::has_quiet_NaN,
"Custom scalar types should specialize this struct");
return std::numeric_limits<T>::quiet_NaN();
}
};
template <>
struct dummy_value<int> {
static constexpr int get() {
// D is for "Dummy". We assume as least 32 bits (per cppguide) -- if `int`
// is larger than 32 bits, this will leave some fraction of the bytes zero
// instead of 0xDD, but that's okay.
return 0xDDDDDDDD;
}
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_copyable.h | #pragma once
// ============================================================================
// N.B. The spelling of the macro names between doc/Doxyfile_CXX.in and this
// file must be kept in sync!
// ============================================================================
/** @file
Provides careful macros to selectively enable or disable the special member
functions for copy-construction, copy-assignment, move-construction, and
move-assignment.
http://en.cppreference.com/w/cpp/language/member_functions#Special_member_functions
When enabled via these macros, the `= default` implementation is provided.
Code that needs custom copy or move functions should not use these macros.
*/
/** DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN deletes the special member functions for
copy-construction, copy-assignment, move-construction, and move-assignment.
Drake's Doxygen is customized to render the deletions in detail, with
appropriate comments. Invoke this macro in the public section of the class
declaration, e.g.:
<pre>
class Foo {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Foo)
// ...
};
</pre>
*/
#define DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Classname) \
Classname(const Classname&) = delete; \
void operator=(const Classname&) = delete; \
Classname(Classname&&) = delete; \
void operator=(Classname&&) = delete;
/** DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN defaults the special member
functions for copy-construction, copy-assignment, move-construction, and
move-assignment. This macro should be used only when copy-construction and
copy-assignment defaults are well-formed. Note that the defaulted move
functions could conceivably still be ill-formed, in which case they will
effectively not be declared or used -- but because the copy constructor exists
the type will still be MoveConstructible. Drake's Doxygen is customized to
render the functions in detail, with appropriate comments. Typically, you
should invoke this macro in the public section of the class declaration, e.g.:
<pre>
class Foo {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Foo)
// ...
};
</pre>
However, if Foo has a virtual destructor (i.e., is subclassable), then
typically you should use either DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN in the
public section or else DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN in the
protected section, to prevent
<a href="https://en.wikipedia.org/wiki/Object_slicing">object slicing</a>.
The macro contains a built-in self-check that copy-assignment is well-formed.
This self-check proves that the Classname is CopyConstructible, CopyAssignable,
MoveConstructible, and MoveAssignable (in all but the most arcane cases where a
member of the Classname is somehow CopyAssignable but not CopyConstructible).
Therefore, classes that use this macro typically will not need to have any unit
tests that check for the presence nor correctness of these functions.
However, the self-check does not provide any checks of the runtime efficiency
of the functions. If it is important for performance that the move functions
actually move (instead of making a copy), then you should consider capturing
that in a unit test.
*/
#define DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Classname) \
Classname(const Classname&) = default; \
Classname& operator=(const Classname&) = default; \
Classname(Classname&&) = default; \
Classname& operator=(Classname&&) = default; \
/* Fails at compile-time if copy-assign doesn't compile. */ \
/* Note that we do not test the copy-ctor here, because */ \
/* it will not exist when Classname is abstract. */ \
static void DrakeDefaultCopyAndMoveAndAssign_DoAssign( \
Classname* a, const Classname& b) { *a = b; } \
static_assert( \
&DrakeDefaultCopyAndMoveAndAssign_DoAssign == \
&DrakeDefaultCopyAndMoveAndAssign_DoAssign, \
"This assertion is never false; its only purpose is to " \
"generate 'use of deleted function: operator=' errors " \
"when Classname is a template.");
/** DRAKE_DECLARE_COPY_AND_MOVE_AND_ASSIGN declares the special member functions
for copy-construction, copy-assignment, move-construction, and move-assignment.
Use this macro when these functions are available, but require non-default
implementations. (Use DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN instead if you can
use the compiler-generated default implementations.) Drake's Doxygen is
customized to render the declarations in detail, with appropriate comments
assuming _unsurprising_ behavior of your hand-written functions. Invoke this
macro in the public section of the class declaration, e.g.:
<pre>
class Foo {
public:
DRAKE_DECLARE_COPY_AND_MOVE_AND_ASSIGN(Foo)
// ...
};
</pre>
Then the matching definitions should be placed in the associated .cc file.
*/
#define DRAKE_DECLARE_COPY_AND_MOVE_AND_ASSIGN(Classname) \
Classname(const Classname&); \
Classname& operator=(const Classname&); \
Classname(Classname&&); \
Classname& operator=(Classname&&);
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/network_policy.cc | #include "drake/common/network_policy.h"
#include <algorithm>
#include <cstdlib>
#include "drake/common/drake_throw.h"
#include "drake/common/text_logging.h"
namespace drake {
namespace internal {
namespace {
bool IsAsciiLowercaseAlphaNumeric(std::string_view word) {
return std::all_of(word.begin(), word.end(), [](char ch) {
return ('a' <= ch && ch <= 'z') || ('0' <= ch && ch <= '9') || (ch == '_');
});
}
} // namespace
bool IsNetworkingAllowed(std::string_view component) {
DRAKE_THROW_UNLESS(component.length() > 0);
DRAKE_THROW_UNLESS(component != "none");
DRAKE_THROW_UNLESS(IsAsciiLowercaseAlphaNumeric(component));
// Unset or empty means allow-all.
const char* const env_cstr = std::getenv("DRAKE_ALLOW_NETWORK");
if (env_cstr == nullptr) {
return true;
}
if (*env_cstr == '\0') {
return true;
}
const std::string_view env_view{env_cstr};
// Set to "none" means deny-all.
if (env_view == "none") {
return false;
}
// Iterate over the colon-delimited tokens.
// N.B. We purposefully do not warn for unknown tokens because they may evolve
// over time and we don't want to force users to churn their policy variables
// to be congruent with their Drake version pin.
// TODO(jwnimmer-tri) As of C++20, use std::ranges::lazy_split_view.
bool match = false;
std::string_view worklist = env_view;
while (!worklist.empty()) {
std::string_view token;
auto delim = worklist.find(':');
if (delim == std::string_view::npos) {
token = worklist;
worklist = {};
} else {
token = worklist.substr(0, delim);
worklist.remove_prefix(delim + 1);
}
if (token == "none") {
static const logging::Warn log_once(
"Setting DRAKE_ALLOW_NETWORK={} combines 'none' with non-none "
"values; this is probably not what you wanted! The effect is "
"the same as just saying 'none' on its own; nothing is allowed!",
env_view);
return false;
}
if (token == component) {
match = true;
}
}
return match;
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/fmt_eigen.h | #pragma once
#include <string>
#include <string_view>
#include <Eigen/Core>
#include "drake/common/fmt.h"
namespace drake {
namespace internal {
/* A tag type to be used in fmt::format("{}", fmt_eigen(...)) calls.
Below we'll add a fmt::formatter<> specialization for this tag. */
template <typename Derived>
struct fmt_eigen_ref {
const Eigen::MatrixBase<Derived>& matrix;
};
/* Returns the string formatting of the given matrix.
@tparam T must be either double, float, or string */
template <typename T>
std::string FormatEigenMatrix(
const Eigen::Ref<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>&
matrix);
} // namespace internal
/** When passing an Eigen::Matrix to fmt, use this wrapper function to instruct
fmt to use Drake's custom formatter for Eigen types.
Within Drake, when formatting an Eigen matrix into a string you must wrap the
Eigen object as `fmt_eigen(M)`. This holds true whether it be for logging, error
messages, debugging, or etc.
For example:
@code
if (!CheckValid(M)) {
throw std::logic_error(fmt::format("Invalid M = {}", fmt_eigen(M)));
}
@endcode
@warning The return value of this function should only ever be used as a
temporary object, i.e., in a fmt argument list or a logging statement argument
list. Never store it as a local variable, member field, etc.
@note To ensure floating-point data is formatted without losing any digits,
Drake's code is compiled using -DEIGEN_NO_IO, which enforces that nothing within
Drake is allowed to use Eigen's `operator<<`. Downstream code that calls into
Drake is not required to use that option; it is only enforced by Drake's build
system, not by Drake's headers. */
template <typename Derived>
internal::fmt_eigen_ref<Derived> fmt_eigen(
const Eigen::MatrixBase<Derived>& matrix) {
return {matrix};
}
} // namespace drake
#ifndef DRAKE_DOXYGEN_CXX
// Formatter specialization for drake::fmt_eigen.
namespace fmt {
template <typename Derived>
struct formatter<drake::internal::fmt_eigen_ref<Derived>>
: formatter<std::string_view> {
template <typename FormatContext>
auto format(const drake::internal::fmt_eigen_ref<Derived>& ref,
// NOLINTNEXTLINE(runtime/references) To match fmt API.
FormatContext& ctx) DRAKE_FMT8_CONST -> decltype(ctx.out()) {
using Scalar = typename Derived::Scalar;
const auto& matrix = ref.matrix;
if constexpr (std::is_same_v<Scalar, double> ||
std::is_same_v<Scalar, float>) {
return formatter<std::string_view>{}.format(
drake::internal::FormatEigenMatrix<Scalar>(matrix), ctx);
} else {
return formatter<std::string_view>{}.format(
drake::internal::FormatEigenMatrix<std::string>(
matrix.unaryExpr([](const auto& element) -> std::string {
return fmt::to_string(element);
})),
ctx);
}
}
};
} // namespace fmt
#endif
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/sorted_pair.h | #pragma once
#include <algorithm>
#include <cstddef>
#include <type_traits>
#include <utility>
#include "drake/common/hash.h"
#include "drake/common/is_less_than_comparable.h"
/// @file
/// Provides drake::MakeSortedPair and drake::SortedPair for storing two
/// values of a certain type in sorted order.
namespace drake {
/// This class is similar to the std::pair class. However, this class uses a
/// pair of homogeneous types (std::pair can use heterogeneous types) and sorts
/// the first and second values such that the first value is less than or equal
/// to the second one). Note that the sort is a stable one. Thus the SortedPair
/// class is able to be used to generate keys (e.g., for std::map, etc.) from
/// pairs of objects.
///
/// The availability of construction and assignment operations (i.e., default
/// constructor, copy constructor, copy assignment, move constructor, move
/// assignment) is the same as whatever T provides . All comparison operations
/// (including equality, etc.) are always available.
///
/// To format this class for logging, include `<fmt/ranges.h>` (exactly the same
/// as for `std::pair`).
///
/// @tparam T A template type that provides `operator<`.
template <class T>
struct SortedPair {
static_assert(is_less_than_comparable<T>::value,
"SortedPair can only be used with types that can be compared "
"using the less-than operator (operator<).");
/// The default constructor creates `first()` and `second()` using T's default
/// constructor, iff T has a default constructor. Otherwise, this constructor
/// is not available.
#ifndef DRAKE_DOXYGEN_CXX
template <typename T1 = T,
typename std::enable_if_t<std::is_constructible_v<T1>, bool> = true>
#endif
SortedPair() {
}
/// Rvalue reference constructor, permits constructing with std::unique_ptr
/// types, for example.
SortedPair(T&& a, T&& b) {
if (b < a) {
first_ = std::move(b);
second_ = std::move(a);
} else {
first_ = std::move(a);
second_ = std::move(b);
}
}
/// Constructs a %SortedPair from two objects.
SortedPair(const T& a, const T& b) : first_(a), second_(b) {
if (second_ < first_) {
std::swap(first_, second_);
}
}
/// Type-converting copy constructor.
template <class U>
SortedPair(SortedPair<U>&& u)
: first_{std::forward<T>(u.first())},
second_{std::forward<T>(u.second())} {}
// N.B. We leave all of the copy/move/assign operations implicitly declared,
// so that iff T provides that operation, then we will also provide it. Do
// not declare any of those operations nor a destructor here, or else the
// implicitly declared functions might not longer be implicitly declared.
/// Resets the stored objects.
template <class U>
void set(U&& a, U&& b) {
first_ = std::forward<U>(a);
second_ = std::forward<U>(b);
if (second_ < first_) {
std::swap(first_, second_);
}
}
/// Gets the first (according to `operator<`) of the objects.
const T& first() const { return first_; }
/// Gets the second (according to `operator<`) of the objects.
const T& second() const { return second_; }
/// Swaps `this` and `t`.
void Swap(drake::SortedPair<T>& t) {
std::swap(t.first_, first_);
std::swap(t.second_, second_);
}
/// Implements the @ref hash_append concept.
template <class HashAlgorithm>
friend void hash_append(HashAlgorithm& hasher, const SortedPair& p) noexcept {
using drake::hash_append;
hash_append(hasher, p.first_);
hash_append(hasher, p.second_);
}
/// @name Support for using SortedPair in structured bindings.
//@{
template <size_t Index>
const T& get() const {
if constexpr (Index == 0) return first_;
if constexpr (Index == 1) return second_;
}
template <std::size_t Index>
friend const T& get(const SortedPair<T>& self) {
return self.get<Index>();
}
//@}
private:
T first_{}; // The first of the two objects, according to operator<.
T second_{}; // The second of the two objects, according to operator<.
};
/// Two pairs of the same type are equal iff their members are equal after
/// sorting.
template <class T>
inline bool operator==(const SortedPair<T>& x, const SortedPair<T>& y) {
return !(x < y) && !(y < x);
}
/// Compares two pairs using lexicographic ordering.
template <class T>
inline bool operator<(const SortedPair<T>& x, const SortedPair<T>& y) {
return std::tie(x.first(), x.second()) < std::tie(y.first(), y.second());
}
/// Determine whether two SortedPair objects are not equal using `operator==`.
template <class T>
inline bool operator!=(const SortedPair<T>& x, const SortedPair<T>& y) {
return !(x == y);
}
/// Determines whether `x > y` using `operator<`.
template <class T>
inline bool operator>(const SortedPair<T>& x, const SortedPair<T>& y) {
return y < x;
}
/// Determines whether `x <= y` using `operator<`.
template <class T>
inline bool operator<=(const SortedPair<T>& x, const SortedPair<T>& y) {
return !(y < x);
}
/// Determines whether `x >= y` using `operator<`.
template <class T>
inline bool operator>=(const SortedPair<T>& x, const SortedPair<T>& y) {
return !(x < y);
}
/// @brief A convenience wrapper for creating a sorted pair from two objects.
/// @param x The first_ object.
/// @param y The second_ object.
/// @return A newly-constructed SortedPair object.
template <class T>
inline constexpr SortedPair<typename std::decay<T>::type> MakeSortedPair(
T&& x, T&& y) {
return SortedPair<typename std::decay<T>::type>(std::forward<T>(x),
std::forward<T>(y));
}
} // namespace drake
namespace std {
/// Implements std::swap().
template <class T>
void swap(drake::SortedPair<T>& t, drake::SortedPair<T>& u) {
t.Swap(u);
}
/// Provides std::hash<SortedPair<T>>.
template <class T>
struct hash<drake::SortedPair<T>> : public drake::DefaultHash {};
#if defined(__GLIBCXX__)
// https://gcc.gnu.org/onlinedocs/libstdc++/manual/unordered_associative.html
template <class T>
struct __is_fast_hash<hash<drake::SortedPair<T>>> : std::false_type {};
#endif
/// Support using `SortedPair<T>` in structured bindings. E.g.,
///
/// SortedPair<Foo> pair(Foo(1), Foo(2));
/// const auto& [a, b] = pair;
template <typename T>
struct tuple_size<drake::SortedPair<T>> : std::integral_constant<size_t, 2> {};
template <size_t Index, typename T>
struct tuple_element<Index, drake::SortedPair<T>> {
using type = const T;
};
} // namespace std
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_export.h | #pragma once
/** DRAKE_NO_EXPORT sets C++ code to use hidden linker visibility.
Hidden visibility is appropriate for code that will be completely invisible to
users, e.g., for header files that are bazel-private, not installed, and only
used as implementation_deps.
This macro is most useful when Drake code includes externals that themselves
have hidden linker visibility and compilers complain about mismatched
visibility attributes.
For example, to un-export all classes and functions in a namespace:
<pre>
namespace internal DRAKE_NO_EXPORT {
class Foo {
// ...
};
} // namespace internal
</pre>
To un-export just one class:
<pre>
namespace internal {
class DRAKE_NO_EXPORT Foo {
// ...
};
} // namespace internal
</pre>
To un-export just one function:
<pre>
DRAKE_NO_EXPORT void CalcFoo(double arg) { ... }
</pre>
For the related CMake module, see:
https://cmake.org/cmake/help/latest/module/GenerateExportHeader.html
*/
#define DRAKE_NO_EXPORT __attribute__((visibility("hidden")))
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_resource.h | #pragma once
#include <filesystem>
#include <optional>
#include <string>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
namespace drake {
/// Models the outcome of drake::FindResource. After a call to FindResource,
/// typical calling code would use get_absolute_path_or_throw().
/// Alternatively, get_absolute_path() will return an `optional<string>`, which
/// can be manually checked to contain a value before using the path. If the
/// resource was not found, get_error_message() will contain an error message.
///
/// For a given FindResourceResult instance, exactly one of get_absolute_path()
/// or get_error_message() will contain a value. (Similarly, exactly one of
/// them will not contain a value.)
class FindResourceResult {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(FindResourceResult);
/// Returns the absolute path to the resource, iff the resource was found.
std::optional<std::string> get_absolute_path() const;
/// Either returns the get_absolute_path() iff the resource was found,
/// or else throws std::exception.
std::string get_absolute_path_or_throw() const;
/// Returns the error message, iff the resource was not found.
/// The string will never be empty; only the optional can be empty.
std::optional<std::string> get_error_message() const;
/// Returns the resource_path asked of FindResource.
/// (This may be empty only in the make_empty() case.)
std::string get_resource_path() const;
/// Returns a success result (the requested resource was found).
/// @pre neither string parameter is empty
/// @param resource_path the value passed to FindResource
/// @param base_path an absolute base path that precedes resource_path
static FindResourceResult make_success(std::string resource_path,
std::string absolute_path);
/// Returns an error result (the requested resource was NOT found).
/// @pre neither string parameter is empty
/// @param resource_path the value passed to FindResource
static FindResourceResult make_error(std::string resource_path,
std::string error_message);
/// Returns an empty error result (no requested resource).
static FindResourceResult make_empty();
private:
FindResourceResult() = default;
void CheckInvariants();
// The path as requested by the user.
std::string resource_path_;
// The absolute path where resource_path was found, if success.
std::optional<std::string> absolute_path_;
// An error message, permitted to be present only when base_path is empty.
//
// All three of resource_path, base_path, and error_message can be empty
// (e.g., a default-constructed and/or moved-from object), which represents
// resource-not-found along with an unspecified non-empty default error
// message from get_error_message().
std::optional<std::string> error_message_;
};
/// (Advanced) Attempts to locate a Drake resource named by the given
/// `resource_path`. The `resource_path` refers to the relative path within the
/// Drake source repository, prepended with `drake/`. For example, to find the
/// source file `examples/pendulum/Pendulum.urdf`, the `resource_path` would be
/// `drake/examples/pendulum/Pendulum.urdf`. Paths that do not start with
/// `drake/` will return an error result. The `resource_path` must refer
/// to a file (not a directory).
///
/// The search scans for the resource in the following resource roots and in
/// the following order:
///
/// 1. In the DRAKE_RESOURCE_ROOT environment variable.
/// 2. In the Bazel runfiles for a bazel-bin/pkg/program.
/// 3. In the Drake CMake install directory.
///
/// The first resource root from the list that exists is used to find any and
/// all Drake resources. If the resource root does not contain the resource,
/// the result is an error even (if a resource root lower on the list happens
/// to have the resource). If all three roots are unavailable, then returns an
/// error result.
FindResourceResult FindResource(const std::string& resource_path);
/// (Advanced) Convenient wrapper for querying FindResource(resource_path)
/// followed by FindResourceResult::get_absolute_path_or_throw().
///
/// The primary purpose of this function is for Drake's software internals to
/// locate Drake resources (e.g., config files) within Drake's build system.
/// In most cases, end users should not need to use it.
///
/// Do NOT use this function to feed into a drake::multibody::parsing::Parser.
/// Instead, use parser.AddModelsFromUrl() in coordination with the parser's
/// PackageMap.
std::string FindResourceOrThrow(const std::string& resource_path);
/// The name of the environment variable that provides the first place where
/// FindResource attempts to look. The environment variable is allowed to be
/// unset or empty; in that case, FindResource will attempt to use other
/// locations without complaint.
///
/// The value is guaranteed to be "DRAKE_RESOURCE_ROOT". (For some users, it
/// may be easier to hard-code a value than refer to this constant.)
///
/// When the environment variable is set, resources are sought in relation to
/// it by appending the FindResource() `resource_path` to the environment
/// variable (with an intermediate `/` as appropriate). For example, if the
/// `resource_path` is `drake/examples/pendulum/Pendulum.urdf` and the
/// `DRAKE_RESOURCE_ROOT` is set to `/home/someuser/foo` then the resource will
/// be sought at `/home/someuser/foo/drake/examples/pendulum/Pendulum.urdf`.
///
/// The intended use of this variable is to seek resources from an installed
/// copy of Drake, in case other methods have failed.
extern const char* const kDrakeResourceRootEnvironmentVariableName;
/// Returns the content of the file at the given path, or nullopt if it cannot
/// be read. Note that the path is a filesystem path, not a `resource_path`.
std::optional<std::string> ReadFile(const std::filesystem::path& path);
/// Returns the content of the file at the given path, or throws if it cannot
/// be read. Note that the path is a filesystem path, not a `resource_path`.
std::string ReadFileOrThrow(const std::filesystem::path& path);
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/polynomial.cc | #include "drake/common/polynomial.h"
#include <algorithm>
#include <cstring>
#include <limits>
#include <numeric>
#include <set>
#include <stdexcept>
#include <utility>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
using Eigen::Dynamic;
using Eigen::Matrix;
using std::accumulate;
using std::pair;
using std::runtime_error;
using std::string;
using std::vector;
namespace drake {
template <typename T>
bool Polynomial<T>::Monomial::HasSameExponents(const Monomial& other) const {
if (terms.size() != other.terms.size()) return false;
for (typename vector<Term>::const_iterator iter = terms.begin();
iter != terms.end(); iter++) {
typename vector<Term>::const_iterator match =
find(other.terms.begin(), other.terms.end(), *iter);
if (match == other.terms.end()) return false;
}
return true;
}
template <typename T>
bool Polynomial<T>::Monomial::HasVariable(const VarType& var) const {
for (const auto& t : terms) {
if (t.var == var) {
return true;
}
}
return false;
}
template <typename T>
Polynomial<T>::Polynomial(const T& scalar) {
Monomial m;
m.coefficient = scalar;
monomials_.push_back(m);
is_univariate_ = true;
}
template <typename T>
Polynomial<T>::Polynomial(const T coefficient, const vector<Term>& terms) {
Monomial m;
m.coefficient = coefficient;
m.terms = terms;
is_univariate_ = true;
for (int i = static_cast<int>(m.terms.size()) - 1; i >= 0; i--) {
if ((i > 0) && (m.terms[i].var != m.terms[0].var)) {
is_univariate_ = false;
}
for (int j = 0; j < (i - 1); j++) { // merge any duplicate vars
if (m.terms[i].var == m.terms[j].var) {
m.terms[j].power += m.terms[i].power;
m.terms.erase(m.terms.begin() + i);
break;
}
}
}
monomials_.push_back(m);
}
template <typename T>
Polynomial<T>::Polynomial(
typename vector<typename Polynomial<T>::Monomial>::const_iterator start,
typename vector<typename Polynomial<T>::Monomial>::const_iterator finish) {
is_univariate_ = true;
for (typename vector<typename Polynomial<T>::Monomial>::const_iterator iter =
start;
iter != finish; iter++)
monomials_.push_back(*iter);
MakeMonomialsUnique();
}
template <typename T>
Polynomial<T>::Polynomial(const string& varname, const unsigned int num) {
Monomial m;
m.coefficient = T{1};
Term t;
t.var = VariableNameToId(varname, num);
t.power = 1;
m.terms.push_back(t);
monomials_.push_back(m);
is_univariate_ = true;
}
template <typename T>
Polynomial<T>::Polynomial(const T& coeff, const VarType& v) {
Monomial m;
m.coefficient = coeff;
Term t;
t.var = v;
t.power = 1;
m.terms.push_back(t);
monomials_.push_back(m);
is_univariate_ = true;
}
template <typename T>
Polynomial<T>::Polynomial(const WithCoefficients& coefficients) {
const Eigen::Ref<const VectorX<T>>& coeffs = coefficients.value;
const VarType v = VariableNameToId("t");
monomials_.reserve(coeffs.size());
for (int i = 0; i < coeffs.size(); ++i) {
Monomial m;
m.coefficient = coeffs(i);
if (i > 0) {
m.terms.reserve(1);
m.terms.push_back(Term{v, i});
}
monomials_.push_back(std::move(m));
}
is_univariate_ = true;
}
template <typename T>
int Polynomial<T>::GetNumberOfCoefficients() const {
return static_cast<int>(monomials_.size());
}
template <typename T>
int Polynomial<T>::Monomial::GetDegree() const {
if (terms.empty()) return 0;
int degree = terms[0].power;
for (size_t i = 1; i < terms.size(); i++) degree *= terms[i].power;
return degree;
}
template <typename T>
int Polynomial<T>::Monomial::GetDegreeOf(VarType v) const {
for (const Term& term : terms) {
if (term.var == v) {
return term.power;
}
}
return 0;
}
template <typename T>
typename Polynomial<T>::Monomial Polynomial<T>::Monomial::Factor(
const Monomial& divisor) const {
Monomial error, result;
error.coefficient = 0;
result.coefficient = coefficient / divisor.coefficient;
for (const Term& term : terms) {
const PowerType divisor_power = divisor.GetDegreeOf(term.var);
if (term.power < divisor_power) {
return error;
}
Term new_term;
new_term.var = term.var;
new_term.power = term.power - divisor_power;
if (new_term.power > 0) {
result.terms.push_back(new_term);
}
}
for (const Term& divisor_term : divisor.terms) {
if (!GetDegreeOf(divisor_term.var)) {
return error;
}
}
return result;
}
template <typename T>
int Polynomial<T>::GetDegree() const {
int max_degree = 0;
for (typename vector<Monomial>::const_iterator iter = monomials_.begin();
iter != monomials_.end(); iter++) {
int monomial_degree = iter->GetDegree();
if (monomial_degree > max_degree) max_degree = monomial_degree;
}
return max_degree;
}
template <typename T>
bool Polynomial<T>::IsAffine() const {
for (const auto& monomial : monomials_) {
if ((monomial.terms.size() > 1) || (monomial.GetDegree() > 1)) {
return false;
}
}
return true;
}
template <typename T>
typename Polynomial<T>::VarType Polynomial<T>::GetSimpleVariable() const {
if (monomials_.size() != 1) return 0;
if (monomials_[0].terms.size() != 1) return 0;
if (monomials_[0].terms[0].power != 1) return 0;
return monomials_[0].terms[0].var;
}
template <typename T>
const std::vector<typename Polynomial<T>::Monomial>&
Polynomial<T>::GetMonomials() const {
return monomials_;
}
template <typename T>
VectorX<T> Polynomial<T>::GetCoefficients() const {
if (!is_univariate_) {
throw runtime_error(
"GetCoefficients is only defined for univariate polynomials");
}
VectorX<T> result = VectorX<T>::Zero(GetDegree() + 1);
for (const auto& monomial : monomials_) {
const int power = monomial.terms.empty() ? 0 : monomial.terms[0].power;
result[power] = monomial.coefficient;
}
return result;
}
template <typename T>
std::set<typename Polynomial<T>::VarType> Polynomial<T>::GetVariables() const {
std::set<Polynomial<T>::VarType> vars;
for (const Monomial& monomial : monomials_) {
for (const Term& term : monomial.terms) {
vars.insert(term.var);
}
}
return vars;
}
template <typename T>
Polynomial<T> Polynomial<T>::EvaluatePartial(
const std::map<VarType, T>& var_values) const {
using std::pow;
std::vector<Monomial> new_monomials;
for (const Monomial& monomial : monomials_) {
T new_coefficient = monomial.coefficient;
std::vector<Term> new_terms;
for (const Term& term : monomial.terms) {
if (var_values.contains(term.var)) {
new_coefficient *= pow(var_values.at(term.var), term.power);
} else {
new_terms.push_back(term);
}
}
Monomial new_monomial = {new_coefficient, new_terms};
new_monomials.push_back(new_monomial);
}
return Polynomial(new_monomials.begin(), new_monomials.end());
}
template <typename T>
void Polynomial<T>::Subs(const VarType& orig, const VarType& replacement) {
for (typename vector<Monomial>::iterator iter = monomials_.begin();
iter != monomials_.end(); iter++) {
for (typename vector<Term>::iterator t = iter->terms.begin();
t != iter->terms.end(); t++) {
if (t->var == orig) t->var = replacement;
}
}
}
template <typename T>
Polynomial<T> Polynomial<T>::Substitute(
const VarType& orig, const Polynomial<T>& replacement) const {
// TODO(russt): Consider making this more efficient by updating coefficients
// in place instead of relying on the more general polynomial operators.
Polynomial<T> p;
for (const auto& source_monomial : monomials_) {
if (source_monomial.HasVariable(orig)) {
Polynomial<T> m = source_monomial.coefficient;
for (const Term& t : source_monomial.terms) {
if (t.var == orig) {
m *= pow(replacement, t.power);
} else {
m *= Polynomial(1.0, {t});
}
p += m;
}
} else {
// Then this monomial is not changed; add it in directly.
p += Polynomial(source_monomial.coefficient, source_monomial.terms);
}
}
return p;
} // namespace drake
template <typename T>
Polynomial<T> Polynomial<T>::Derivative(int derivative_order) const {
DRAKE_DEMAND(derivative_order >= 0);
if (!is_univariate_)
throw runtime_error(
"Derivative is only defined for univariate polynomials");
if (derivative_order == 0) {
return *this;
}
Polynomial<T> ret;
for (typename vector<Monomial>::const_iterator iter = monomials_.begin();
iter != monomials_.end(); iter++) {
if (!iter->terms.empty() &&
(iter->terms[0].power >= static_cast<PowerType>(derivative_order))) {
Monomial m = *iter;
for (int k = 0; k < derivative_order;
k++) { // take the remaining derivatives
m.coefficient = m.coefficient * m.terms[0].power;
m.terms[0].power -= 1;
}
if (m.terms[0].power < 1) m.terms.erase(m.terms.begin());
ret.monomials_.push_back(m);
}
}
ret.is_univariate_ = true;
return ret;
}
template <typename T>
Polynomial<T> Polynomial<T>::Integral(const T& integration_constant) const {
if (!is_univariate_)
throw runtime_error("Integral is only defined for univariate polynomials");
Polynomial<T> ret = *this;
for (typename vector<Monomial>::iterator iter = ret.monomials_.begin();
iter != ret.monomials_.end(); iter++) {
if (iter->terms.empty()) {
Term t;
t.var = 0;
for (typename vector<Monomial>::iterator iterB = ret.monomials_.begin();
iterB != ret.monomials_.end(); iterB++) {
if (!iterB->terms.empty()) {
t.var = iterB->terms[0].var;
break;
}
}
if (t.var < 1) throw runtime_error("don't know the variable name");
t.power = 1;
iter->terms.push_back(t);
} else {
iter->coefficient /= static_cast<RealScalar>(iter->terms[0].power + 1);
iter->terms[0].power += PowerType{1};
}
}
Monomial m;
m.coefficient = integration_constant;
ret.is_univariate_ = true;
ret.monomials_.push_back(m);
return ret;
}
template <typename T>
bool Polynomial<T>::is_univariate() const {return is_univariate_;}
template <typename T>
bool Polynomial<T>::operator==(const Polynomial<T>& other) const {
// Comparison of unsorted vectors is faster copying them into std::set
// btrees rather than using std::is_permutation().
// TODO(#2216) switch from multiset to set for further performance gains.
const std::multiset<Monomial> this_monomials(monomials_.begin(),
monomials_.end());
const std::multiset<Monomial> other_monomials(other.monomials_.begin(),
other.monomials_.end());
return this_monomials == other_monomials;
}
template <typename T>
Polynomial<T>& Polynomial<T>::operator+=(const Polynomial<T>& other) {
for (const auto& iter : other.monomials_) {
monomials_.push_back(iter);
}
MakeMonomialsUnique(); // also sets is_univariate false if necessary
return *this;
}
template <typename T>
Polynomial<T>& Polynomial<T>::operator-=(const Polynomial<T>& other) {
for (const auto& iter : other.monomials_) {
monomials_.push_back(iter);
monomials_.back().coefficient *= T{-1};
}
MakeMonomialsUnique(); // also sets is_univariate false if necessary
return *this;
}
template <typename T>
Polynomial<T>& Polynomial<T>::operator*=(const Polynomial<T>& other) {
vector<Monomial> new_monomials;
for (const auto& iter : monomials_) {
for (const auto& other_iter : other.monomials_) {
Monomial m;
m.coefficient = iter.coefficient * other_iter.coefficient;
m.terms = iter.terms;
for (size_t i = 0; i < other_iter.terms.size(); i++) {
bool new_var = true;
for (size_t j = 0; j < m.terms.size(); j++) {
if (m.terms[j].var == other_iter.terms[i].var) {
m.terms[j].power += other_iter.terms[i].power;
new_var = false;
break;
}
}
if (new_var) {
m.terms.push_back(other_iter.terms[i]);
}
}
new_monomials.push_back(m);
}
}
monomials_ = new_monomials;
MakeMonomialsUnique(); // also sets is_univariate false if necessary
return *this;
}
template <typename T>
Polynomial<T>& Polynomial<T>::operator+=(const T& scalar) {
// add to the constant monomial if I have one
for (typename vector<Monomial>::iterator iter = monomials_.begin();
iter != monomials_.end(); iter++) {
if (iter->terms.empty()) {
iter->coefficient += scalar;
return *this;
}
}
// otherwise create the constant monomial
Monomial m;
m.coefficient = scalar;
monomials_.push_back(m);
return *this;
}
template <typename T>
Polynomial<T>& Polynomial<T>::operator-=(const T& scalar) {
// add to the constant monomial if I have one
for (typename vector<Monomial>::iterator iter = monomials_.begin();
iter != monomials_.end(); iter++) {
if (iter->terms.empty()) {
iter->coefficient -= scalar;
return *this;
}
}
// otherwise create the constant monomial
Monomial m;
m.coefficient = -scalar;
monomials_.push_back(m);
return *this;
}
template <typename T>
Polynomial<T>& Polynomial<T>::operator*=(const T& scalar) {
for (typename vector<Monomial>::iterator iter = monomials_.begin();
iter != monomials_.end(); iter++) {
iter->coefficient *= scalar;
}
return *this;
}
template <typename T>
Polynomial<T>& Polynomial<T>::operator/=(const T& scalar) {
for (typename vector<Monomial>::iterator iter = monomials_.begin();
iter != monomials_.end(); iter++) {
iter->coefficient /= scalar;
}
return *this;
}
template <typename T>
const Polynomial<T> Polynomial<T>::operator+(const Polynomial& other) const {
Polynomial<T> ret = *this;
ret += other;
return ret;
}
template <typename T>
const Polynomial<T> Polynomial<T>::operator-(const Polynomial& other) const {
Polynomial<T> ret = *this;
ret -= other;
return ret;
}
template <typename T>
const Polynomial<T> Polynomial<T>::operator-() const {
Polynomial<T> ret = *this;
for (typename vector<Monomial>::iterator iter = ret.monomials_.begin();
iter != ret.monomials_.end(); iter++) {
iter->coefficient = -iter->coefficient;
}
return ret;
}
template <typename T>
const Polynomial<T> Polynomial<T>::operator*(const Polynomial<T>& other) const {
Polynomial<T> ret = *this;
ret *= other;
return ret;
}
template <typename T>
const Polynomial<T> Polynomial<T>::operator/(const T& scalar) const {
Polynomial<T> ret = *this;
ret /= scalar;
return ret;
}
template <typename T>
typename Polynomial<T>::RootsType Polynomial<T>::Roots() const {
if (!is_univariate_)
throw runtime_error("Roots is only defined for univariate polynomials");
// RootsType (std::complex<T>) does not currently work for AutoDiffXd nor for
// Expression, which leaves only double. We could, in principle, try to
// support more types here.
if constexpr (std::is_same_v<T, double>) {
auto coefficients = GetCoefficients();
// need to handle degree 0 and 1 explicitly because Eigen's polynomial
// solver doesn't work for these
int degree = static_cast<int>(coefficients.size()) - 1;
switch (degree) {
case 0:
return Polynomial<T>::RootsType(degree);
case 1: {
Polynomial<T>::RootsType ret(degree);
ret[0] = -coefficients[0] / coefficients[1];
return ret;
}
default: {
Eigen::PolynomialSolver<RealScalar, Eigen::Dynamic> solver;
solver.compute(coefficients);
return solver.roots();
}
}
} else {
throw std::runtime_error(
"Polynomial<T>::Roots() is only supports T=double.");
}
}
template <typename T>
boolean<T> Polynomial<T>::CoefficientsAlmostEqual(
const Polynomial<T>& other, const Polynomial<T>::RealScalar& tol,
const ToleranceType& tol_type) const {
using std::abs;
using std::min;
std::vector<bool> monomial_has_match(monomials_.size(), false);
boolean<T> comparison{true};
for (const auto& m : other.GetMonomials()) {
bool found_matching_term = false;
for (size_t i = 0; i < monomials_.size(); i++) {
if (monomial_has_match[i]) continue;
if (m.terms == monomials_[i].terms) {
found_matching_term = true;
if (tol_type == ToleranceType::kAbsolute) {
comparison = comparison &&
abs(m.coefficient - monomials_[i].coefficient) <= tol;
} else {
comparison =
comparison &&
abs(m.coefficient - monomials_[i].coefficient) <=
tol * min(abs(m.coefficient), abs(monomials_[i].coefficient));
}
monomial_has_match[i] = true;
break;
}
}
if (!found_matching_term) {
if (tol_type == ToleranceType::kAbsolute) {
// then I can still succeed, if my coefficient is close to zero.
comparison = comparison && abs(m.coefficient) <= tol;
} else {
return boolean<T>{false};
}
}
}
// Finally, check any monomials in this that did not have a match in other.
for (size_t i = 0; i < monomials_.size(); i++) {
if (monomial_has_match[i]) continue;
if (tol_type == ToleranceType::kAbsolute) {
comparison = comparison && abs(monomials_[i].coefficient) <= tol;
} else {
return boolean<T>{false};
}
}
return comparison;
}
constexpr char kNameChars[] = "@#_.abcdefghijklmnopqrstuvwxyz";
const unsigned int kNumNameChars = sizeof(kNameChars) - 1;
const unsigned int kNameLength = 4;
const unsigned int kMaxNamePart = 923521; // (kNumNameChars+1)^kNameLength;
template <typename T>
bool Polynomial<T>::IsValidVariableName(const string name) {
size_t len = name.length();
if (len < 1) return false;
for (size_t i = 0; i < len; i++)
if (!strchr(kNameChars, name[i])) return false;
return true;
}
template <typename T>
typename Polynomial<T>::VarType Polynomial<T>::VariableNameToId(
const string name, const unsigned int m) {
DRAKE_THROW_UNLESS(IsValidVariableName(name));
unsigned int multiplier = 1;
VarType name_part = 0;
for (int i = static_cast<int>(name.size()) - 1; i >= 0; i--) {
const char* const character_match = strchr(kNameChars, name[i]);
DRAKE_ASSERT(character_match != nullptr);
VarType offset = static_cast<VarType>(character_match - kNameChars);
name_part += (offset + 1) * multiplier;
multiplier *= kNumNameChars + 1;
}
if (name_part > kMaxNamePart) {
throw runtime_error("name " + name + " (" + std::to_string(name_part) +
") exceeds max allowed");
}
const VarType maxId = std::numeric_limits<VarType>::max() / 2 / kMaxNamePart;
if (m > maxId) throw runtime_error("name exceeds max ID");
if (m < 1) throw runtime_error("m must be >0");
return static_cast<VarType>(2) * (name_part + kMaxNamePart * (m - 1));
}
template <typename T>
string Polynomial<T>::IdToVariableName(const VarType id) {
VarType name_part = (id / 2) % kMaxNamePart; // id/2 to be compatible w/
// msspoly, even though I'm not
// doing the trig support here
unsigned int m = id / 2 / kMaxNamePart;
unsigned int multiplier =
static_cast<unsigned int>(std::pow(static_cast<double>(kNumNameChars + 1),
static_cast<int>(kNameLength) - 1));
char name[kNameLength + 1];
int j = 0;
for (int i = 0; i < static_cast<int>(kNameLength); i++) {
unsigned int name_ind = (name_part / multiplier) % (kNumNameChars + 1);
if (name_ind > 0) name[j++] = kNameChars[name_ind - 1];
multiplier /= kNumNameChars + 1;
}
if (j == 0) name[j++] = kNameChars[0];
name[j] = '\0';
return string(name) + std::to_string((m + 1));
}
template <typename T>
void Polynomial<T>::MakeMonomialsUnique(void) {
VarType unique_var = 0; // also update the univariate flag
for (int i = static_cast<int>(monomials_.size()) - 1; i >= 0; --i) {
if (monomials_[i].coefficient == 0) {
monomials_.erase(monomials_.begin() + i);
continue;
}
Monomial& mi = monomials_[i];
if (!mi.terms.empty()) {
if (mi.terms.size() > 1) is_univariate_ = false;
if (mi.terms[0].var != unique_var) {
if (unique_var > 0) {
is_univariate_ = false;
} else {
unique_var = mi.terms[0].var;
}
}
}
for (int j = 0; j <= (i - 1); j++) {
Monomial& mj = monomials_[j];
if (mi.HasSameExponents(mj)) {
// it's a match, so delete monomial i
monomials_[j].coefficient += monomials_[i].coefficient;
monomials_.erase(monomials_.begin() + i);
break;
}
}
}
}
namespace {
using symbolic::Expression;
// Visitor class to implement FromExpression.
template <typename T>
class FromExpressionVisitor {
public:
Polynomial<T> Visit(const Expression& e) {
return drake::symbolic::VisitExpression<Polynomial<T>>(this, e);
}
private:
static Polynomial<T> VisitAddition(const Expression& e) {
const auto constant = get_constant_in_addition(e);
const auto& expr_to_coeff_map = get_expr_to_coeff_map_in_addition(e);
return accumulate(
expr_to_coeff_map.begin(), expr_to_coeff_map.end(),
Polynomial<T>{constant},
[](const Polynomial<T>& polynomial,
const pair<const Expression, double>& p) {
return polynomial + Polynomial<T>::FromExpression(p.first) * p.second;
});
}
static Polynomial<T> VisitMultiplication(const Expression& e) {
const auto constant = drake::symbolic::get_constant_in_multiplication(e);
const auto& base_to_exponent_map =
drake::symbolic::get_base_to_exponent_map_in_multiplication(e);
return accumulate(
base_to_exponent_map.begin(), base_to_exponent_map.end(),
Polynomial<T>{constant},
[](const Polynomial<T>& polynomial,
const pair<const Expression, Expression>& p) {
const Expression& base{p.first};
const Expression& exponent{p.second};
DRAKE_ASSERT(base.is_polynomial());
DRAKE_ASSERT(is_constant(exponent));
return polynomial *
pow(Polynomial<T>::FromExpression(base),
static_cast<int>(get_constant_value(exponent)));
});
}
static Polynomial<T> VisitDivision(const Expression& e) {
DRAKE_ASSERT(e.is_polynomial());
const auto& first_arg{get_first_argument(e)};
const auto& second_arg{get_second_argument(e)};
DRAKE_ASSERT(is_constant(second_arg));
return Polynomial<T>::FromExpression(first_arg) /
get_constant_value(second_arg);
}
static Polynomial<T> VisitVariable(const Expression& e) {
return Polynomial<T>{1.0, static_cast<Polynomial<double>::VarType>(
get_variable(e).get_id())};
}
static Polynomial<T> VisitConstant(const Expression& e) {
return Polynomial<T>{get_constant_value(e)};
}
static Polynomial<T> VisitLog(const Expression&) {
throw runtime_error("Log expression is not polynomial-convertible.");
}
static Polynomial<T> VisitPow(const Expression& e) {
DRAKE_ASSERT(e.is_polynomial());
const int exponent{
static_cast<int>(get_constant_value(get_second_argument(e)))};
return pow(Polynomial<T>::FromExpression(get_first_argument(e)), exponent);
}
static Polynomial<T> VisitAbs(const Expression&) {
throw runtime_error("Abs expression is not polynomial-convertible.");
}
static Polynomial<T> VisitExp(const Expression&) {
throw runtime_error("Exp expression is not polynomial-convertible.");
}
static Polynomial<T> VisitSqrt(const Expression&) {
throw runtime_error("Sqrt expression is not polynomial-convertible.");
}
static Polynomial<T> VisitSin(const Expression&) {
throw runtime_error("Sin expression is not polynomial-convertible.");
}
static Polynomial<T> VisitCos(const Expression&) {
throw runtime_error("Cos expression is not polynomial-convertible.");
}
static Polynomial<T> VisitTan(const Expression&) {
throw runtime_error("Tan expression is not polynomial-convertible.");
}
static Polynomial<T> VisitAsin(const Expression&) {
throw runtime_error("Asin expression is not polynomial-convertible.");
}
static Polynomial<T> VisitAcos(const Expression&) {
throw runtime_error("Acos expression is not polynomial-convertible.");
}
static Polynomial<T> VisitAtan(const Expression&) {
throw runtime_error("Atan expression is not polynomial-convertible.");
}
static Polynomial<T> VisitAtan2(const Expression&) {
throw runtime_error("Atan2 expression is not polynomial-convertible.");
}
static Polynomial<T> VisitSinh(const Expression&) {
throw runtime_error("Sinh expression is not polynomial-convertible.");
}
static Polynomial<T> VisitCosh(const Expression&) {
throw runtime_error("Cosh expression is not polynomial-convertible.");
}
static Polynomial<T> VisitTanh(const Expression&) {
throw runtime_error("Tanh expression is not polynomial-convertible.");
}
static Polynomial<T> VisitMin(const Expression&) {
throw runtime_error("Min expression is not polynomial-convertible.");
}
static Polynomial<T> VisitMax(const Expression&) {
throw runtime_error("Max expression is not polynomial-convertible.");
}
static Polynomial<T> VisitCeil(const Expression&) {
throw runtime_error("Ceil expression is not polynomial-convertible.");
}
static Polynomial<T> VisitFloor(const Expression&) {
throw runtime_error("Floor expression is not polynomial-convertible.");
}
static Polynomial<T> VisitIfThenElse(const Expression&) {
throw runtime_error("IfThenElse expression is not polynomial-convertible.");
}
static Polynomial<T> VisitUninterpretedFunction(const Expression&) {
throw runtime_error(
"Uninterpreted-function expression is not polynomial-convertible.");
}
// Makes VisitExpression a friend of this class so that VisitExpression can
// use its private methods.
friend Polynomial<T> drake::symbolic::VisitExpression<Polynomial<T>>(
FromExpressionVisitor*, const Expression&);
};
} // namespace
template <typename T>
Polynomial<T> Polynomial<T>::FromExpression(const Expression& e) {
return FromExpressionVisitor<T>{}.Visit(e);
}
// template class Polynomial<std::complex<double>>;
// doesn't work yet because the roots solver can't handle it
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::Polynomial)
| 0 |