#define _USE_MATH_DEFINES
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
#if defined(WIN32) || defined(WIN64)
#define NOMINMAX
#include "windows.h"
#endif
#ifdef MACOSX
#include "OpenGL/glu.h"
#else
#include "GL/glu.h"
#endif
#include <GLFW/glfw3.h>
#include "CMatrixGL.h"
#include "FontGL.h"
struct HapticDevice
{
int deviceId;
int numTools;
Eigen::Vector3d toolPosition[2];
Eigen::Matrix3d rotation;
bool useRotation;
bool useGripper;
HapticDevice()
: deviceId { -1 },
numTools {},
useRotation { false },
useGripper{ false }
{}
};
constexpr double Stiffness = 1000.0;
constexpr double Mass = 100.0;
constexpr double Kv = 1.0;
constexpr float TorusRadius0 = 0.05f;
constexpr float TorusRadius1 = 0.027f;
constexpr double ToolRadius = 0.005;
constexpr int SwapInterval = 1;
bool simulationRunning = true;
bool simulationFinished = false;
bool showRefreshRate = true;
GLFWwindow* window = nullptr;
int windowWidth = 0;
int windowHeight = 0;
std::vector<HapticDevice> devicesList;
Eigen::Vector3d torusPosition;
Eigen::Matrix3d torusRotation;
void DrawTorus(float a_outerRadius,
float a_innerRadius,
int a_majorNumSegments,
int a_minorNumSegments)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
double majorStep = 2.0 * M_PI / a_majorNumSegments;
for (int majorIndex = 0; majorIndex < a_majorNumSegments; ++majorIndex)
{
double a0 = majorIndex * majorStep;
double a1 = a0 + majorStep;
GLdouble x0 = cos(a0);
GLdouble y0 = sin(a0);
GLdouble x1 = cos(a1);
GLdouble y1 = sin(a1);
glBegin(GL_TRIANGLE_STRIP);
double minorStep = 2.0 * M_PI / a_minorNumSegments;
for (int minorIndex = 0; minorIndex <= a_minorNumSegments; ++minorIndex)
{
double b = minorIndex * minorStep;
GLdouble c = cos(b);
GLdouble r = a_innerRadius * c + a_outerRadius;
GLdouble z = a_innerRadius * sin(b);
glNormal3d(x0 * c, y0 * c, z / a_innerRadius);
glTexCoord2d(majorIndex / static_cast<GLdouble>(a_majorNumSegments), minorIndex / static_cast<GLdouble>(a_minorNumSegments));
glVertex3d(x0 * r, y0 * r, z);
glNormal3d(x1 * c, y1 * c, z / a_innerRadius);
glTexCoord2d((majorIndex + 1) / static_cast<GLdouble>(a_majorNumSegments), minorIndex / static_cast<GLdouble>(a_minorNumSegments));
glVertex3d(x1 * r, y1 * r, z);
}
glEnd();
}
}
int updateGraphics()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
static const GLfloat mat_ambient0[] = { 0.1f, 0.1f, 0.3f };
static const GLfloat mat_diffuse0[] = { 0.1f, 0.3f, 0.5f };
static const GLfloat mat_specular0[] = { 0.5f, 0.5f, 0.5f };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient0);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse0);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular0);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 1.0);
cMatrixGL matrix;
matrix.set(torusPosition, torusRotation);
matrix.glMatrixPushMultiply();
DrawTorus(TorusRadius0, TorusRadius1, 64, 64);
matrix.glMatrixPop();
static const GLfloat mat_ambient1[] = { 0.4f, 0.4f, 0.4f };
static const GLfloat mat_diffuse1[] = { 0.8f, 0.8f, 0.8f };
static const GLfloat mat_specular1[] = { 0.5f, 0.5f, 0.5f };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient1);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse1);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular1);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 1.0);
size_t devicesCount = devicesList.size();
for (size_t deviceIndex = 0; deviceIndex < devicesCount; deviceIndex++)
{
HapticDevice& currentDevice = devicesList[deviceIndex];
for (int toolIndex = 0; toolIndex < currentDevice.numTools; toolIndex++)
{
matrix.set(currentDevice.toolPosition[toolIndex], currentDevice.rotation);
matrix.glMatrixPushMultiply();
GLUquadricObj* sphere = gluNewQuadric();
gluSphere(sphere, ToolRadius, 32, 32);
if (currentDevice.useRotation)
{
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
glColor3f(0.45f, 0.45f, 0.45f);
glVertex3d(0.00, 0.000, 0.000);
glVertex3d(0.02, 0.000, 0.000);
glVertex3d(0.02, -0.004, 0.000);
glVertex3d(0.02, 0.004, 0.000);
glVertex3d(0.02, 0.000, -0.004);
glVertex3d(0.02, 0.000, 0.004);
glEnd();
glEnable(GL_LIGHTING);
}
matrix.glMatrixPop();
}
}
if (showRefreshRate)
{
static double lastFrequencyUpdateTime =
dhdGetTime();
static char frequencyString[16] = "0.000 kHz";
if (time - lastFrequencyUpdateTime > 0.1)
{
lastFrequencyUpdateTime = time;
snprintf(frequencyString, 10, "%0.03f kHz", frequency);
}
glDisable(GL_LIGHTING);
glColor3f(1.0, 1.0, 1.0);
glRasterPos3f(0.0f, -0.01f, -0.1f);
for (char* character = frequencyString; *character != '\0'; character++)
{
render_character(*character, HELVETICA12);
}
glEnable(GL_LIGHTING);
}
GLenum err = glGetError();
if (err != GL_NO_ERROR)
{
return -1;
}
return 0;
}
void* hapticsLoop(void* a_userData)
{
double px = 0.0;
double py = 0.0;
double pz = 0.0;
double rot[3][3] = {};
Eigen::Vector3d toolPosition[2];
Eigen::Vector3d toolLocalPosition;
Eigen::Vector3d forceLocal;
Eigen::Vector3d force;
Eigen::Vector3d forceTool[2];
forceTool[0].setZero();
forceTool[1].setZero();
Eigen::Vector3d torusAngularVelocity;
torusAngularVelocity.setZero();
size_t devicesCount = devicesList.size();
for (size_t deviceIndex = 0; deviceIndex < devicesCount; deviceIndex++)
{
}
while (simulationRunning)
{
double timeStep = time - timePrevious;
timePrevious = time;
for (size_t deviceIndex = 0; deviceIndex < devicesCount; deviceIndex++)
{
HapticDevice& currentDevice = devicesList[deviceIndex];
{
std::cout << std::endl <<
"error: failed to read rotation (" <<
dhdErrorGetLastStr() <<
")" << std::endl;
break;
}
currentDevice.rotation << rot[0][0], rot[0][1], rot[0][2],
rot[1][0], rot[1][1], rot[1][2],
rot[2][0], rot[2][1], rot[2][2];
if (currentDevice.useGripper)
{
{
std::cout << std::endl <<
"error: failed to read rotation (" <<
dhdErrorGetLastStr() <<
")" << std::endl;
break;
}
toolPosition[0] << px, py, pz;
{
std::cout << std::endl <<
"error: failed to read rotation (" <<
dhdErrorGetLastStr() <<
")" << std::endl;
break;
}
toolPosition[1] << px, py, pz;
}
else
{
{
std::cout << std::endl <<
"error: failed to read rotation (" <<
dhdErrorGetLastStr() <<
")" << std::endl;
break;
}
toolPosition[0] << px, py, pz;
}
for (int toolIndex = 0; toolIndex < currentDevice.numTools; toolIndex++)
{
toolLocalPosition = torusRotation.transpose() * (toolPosition[toolIndex] - torusPosition);
Eigen::Vector3d toolProjection = toolLocalPosition;
toolProjection(2) = 0.0;
forceLocal.setZero();
if (toolLocalPosition.squaredNorm() > 1e-10)
{
Eigen::Vector3d pointAxisTorus = TorusRadius0 * toolProjection.normalized();
Eigen::Vector3d torusToolDirection = toolLocalPosition - pointAxisTorus;
double distance = torusToolDirection.norm();
if ((distance < (TorusRadius1 + ToolRadius)) && (distance > 0.001))
{
forceLocal = ((TorusRadius1 + ToolRadius) - distance) * Stiffness * torusToolDirection.normalized();
toolLocalPosition = pointAxisTorus + (TorusRadius1 + ToolRadius) * torusToolDirection.normalized();
}
else
{
forceLocal.setZero();
}
}
forceTool[toolIndex] = torusRotation * forceLocal;
currentDevice.toolPosition[toolIndex] = torusRotation * toolLocalPosition;
torusAngularVelocity += -1.0 / Mass * timeStep * (currentDevice.toolPosition[toolIndex] - torusPosition).cross(forceTool[toolIndex]);
}
Eigen::Vector3d force;
double gripperForceMagnitude = 0.0;
if (!currentDevice.useGripper)
{
force = forceTool[0];
}
else
{
force = forceTool[0] + forceTool[1];
Eigen::Vector3d gripperDirection = toolPosition[1] - toolPosition[0];
if (gripperDirection.norm() > 0.00001)
{
gripperDirection.normalize ();
Eigen::Vector3d gripperForce = (forceTool[1].dot(gripperDirection) / (gripperDirection.squaredNorm())) * gripperDirection;
gripperForceMagnitude = gripperForce.norm();
if (force.norm() > 0.001)
{
double cosAngle = gripperDirection.dot(gripperForce) / (gripperDirection.norm() * gripperForce.norm());
cosAngle = std::min(1.0, cosAngle);
cosAngle = std::max(-1.0, cosAngle);
double angle = acos(cosAngle);
if ((angle > M_PI / 2.0) || (angle < -M_PI / 2.0))
{
gripperForceMagnitude = -gripperForceMagnitude;
}
}
}
{
gripperForceMagnitude = -gripperForceMagnitude;
}
}
static bool safeToRenderHaptics = false;
if (!safeToRenderHaptics)
{
if (force.norm() == 0.0 && gripperForceMagnitude == 0.0)
{
safeToRenderHaptics = true;
}
else
{
force.setZero();
gripperForceMagnitude = 0.0;
}
}
}
for (size_t deviceIndex = 0; deviceIndex < devicesCount; deviceIndex++)
{
{
torusAngularVelocity.setZero();
}
}
torusAngularVelocity *= (1.0 - Kv * timeStep);
if (torusAngularVelocity.norm() > 1e-10)
{
Eigen::Matrix3d torusRotationIncrement;
torusRotationIncrement = Eigen::AngleAxisd(torusAngularVelocity.norm(), torusAngularVelocity.normalized());
torusRotation = torusRotationIncrement * torusRotation;
}
}
simulationRunning = false;
simulationFinished = true;
return nullptr;
}
void onExit()
{
simulationRunning = false;
while (!simulationFinished)
{
}
size_t devicesCount = devicesList.size();
for (size_t deviceIndex = 0; deviceIndex < devicesCount; deviceIndex++)
{
{
std::cout <<
"error: failed to close the connection to device ID " << devicesList[deviceIndex].deviceId <<
" (" <<
dhdErrorGetLastStr() <<
")" << std::endl;
return;
}
}
std::cout << "connection closed" << std::endl;
return;
}
void onWindowResized(GLFWwindow* a_window,
int a_width,
int a_height)
{
windowWidth = a_width;
windowHeight = a_height;
double glAspect = (static_cast<double>(a_width) / static_cast<double>(a_height));
glViewport(0, 0, a_width, a_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, glAspect, 0.01, 10);
gluLookAt(0.2, 0.0, 0.0,
0.0, 0.0, 0.0,
0.0, 0.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void onKeyPressed(GLFWwindow* a_window,
int a_key,
int a_scanCode,
int a_action,
int a_modifiers)
{
if (a_action != GLFW_PRESS)
{
return;
}
if ((a_key == GLFW_KEY_ESCAPE) || (a_key == GLFW_KEY_Q))
{
exit(0);
}
if (a_key == GLFW_KEY_R)
{
showRefreshRate = !showRefreshRate;
}
}
void onError(int a_error,
const char* a_description)
{
std::cout << "error: " << a_description << std::endl;
}
int initializeGLFW()
{
if (!glfwInit())
{
return -1;
}
glfwSetErrorCallback(onError);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
windowWidth = static_cast<int>(0.8 * mode->height);
windowHeight = static_cast<int>(0.5 * mode->height);
int x = static_cast<int>(0.5 * (mode->width - windowWidth));
int y = static_cast<int>(0.5 * (mode->height - windowHeight));
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE);
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_STEREO, GL_FALSE);
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
#ifdef MACOSX
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GL_FALSE);
#endif
window = glfwCreateWindow(windowWidth, windowHeight, "Force Dimension - OpenGL Torus Example", nullptr, nullptr);
if (!window)
{
return -1;
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, onKeyPressed);
glfwSetWindowSizeCallback(window, onWindowResized);
glfwSetWindowPos(window, x, y);
glfwSwapInterval(SwapInterval);
glfwShowWindow(window);
onWindowResized(window, windowWidth, windowHeight);
GLfloat mat_ambient[] = { 0.5f, 0.5f, 0.5f };
GLfloat mat_diffuse[] = { 0.5f, 0.5f, 0.5f };
GLfloat mat_specular[] = { 0.5f, 0.5f, 0.5f };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 1.0);
GLfloat ambient[] = { 0.5f, 0.5f, 0.5f, 1.0f };
GLfloat diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.0);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.0);
GLfloat lightPos[] = { 2.0, 0.0, 0.0, 1.0f };
GLfloat lightDir[] = { -1.0, 0.0, 0.0, 1.0f };
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, lightDir);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 180);
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 1.0);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0, 0.0, 0.0, 1.0);
return 0;
}
int initializeHaptics()
{
if (devicesCount < 1)
{
std::cout << "error: no device found" << std::endl;
return -1;
}
for (int deviceIndex = 0; deviceIndex < devicesCount; deviceIndex++)
{
if (deviceId >= 0)
{
devicesList.push_back(HapticDevice {});
HapticDevice& currentDevice = devicesList.back();
currentDevice.deviceId = deviceId;
currentDevice.numTools = (currentDevice.useGripper) ? 2 : 1;
{
std::cout <<
"error: failed to enable button emulation (" <<
dhdErrorGetLastStr() <<
")" << std::endl;
return -1;
}
}
}
return 0;
}
int initializeSimulation()
{
size_t devicesCount = devicesList.size();
for (size_t deviceIndex = 0; deviceIndex < devicesCount; deviceIndex++)
{
for (int toolIndex = 0; toolIndex < devicesList[deviceIndex].numTools; toolIndex++)
{
devicesList[deviceIndex].toolPosition[toolIndex].setZero();
}
}
torusPosition.setZero();
torusRotation.Identity();
torusRotation = Eigen::AngleAxisd(M_PI * 45.0 / 180.0, Eigen::Vector3d(0.0, 1.0, -1.0));
return 0;
}
int main(int argc,
char* argv[])
{
std::cout << "Copyright (C) 2001-2023 Force Dimension" << std::endl;
std::cout << "All Rights Reserved." << std::endl << std::endl;
if (initializeHaptics() < 0)
{
std::cout << "error: failed to initialize haptics" << std::endl;
return -1;
}
if (initializeGLFW() < 0)
{
std::cout << "error: failed to initialize GLFW" << std::endl;
return -1;
}
if (initializeSimulation() < 0)
{
std::cout << "error: failed to initialize the simulation" << std::endl;
return -1;
}
#if defined(WIN32) || defined(WIN64)
DWORD threadHandle;
CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)(hapticsLoop), nullptr, 0x0000, &threadHandle);
SetThreadPriority(&threadHandle, THREAD_PRIORITY_ABOVE_NORMAL);
#else
pthread_t threadHandle;
pthread_create(&threadHandle, nullptr, hapticsLoop, nullptr);
struct sched_param schedulerParameters;
memset(&schedulerParameters, 0, sizeof(struct sched_param));
schedulerParameters.sched_priority = 10;
pthread_setschedparam(threadHandle, SCHED_RR, &schedulerParameters);
#endif
atexit(onExit);
std::cout << std::endl;
std::cout << "press 'r' to toggle display of the haptic rate" << std::endl;
std::cout << " 'q' to quit" << std::endl << std::endl;
while (simulationRunning && !glfwWindowShouldClose(window))
{
if (updateGraphics() < 0)
{
std::cout << "error: failed to update graphics" << std::endl;
break;
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
double __SDK dhdGetComFreq(char ID=-1)
Definition: dhdc.cpp:4654
int __SDK dhdSetDevice(char ID)
Definition: dhdc.cpp:504
int __SDK dhdOpenID(char ID)
Definition: dhdc.cpp:411
bool __SDK dhdHasGripper(char ID=-1)
Definition: dhdc.cpp:699
int __SDK dhdEnableForce(uchar val, char ID=-1)
Definition: dhdc.cpp:4378
bool __SDK dhdHasWrist(char ID=-1)
Definition: dhdc.cpp:641
int __SDK dhdClose(char ID=-1)
Definition: dhdc.cpp:443
int __SDK dhdGetGripperFingerPos(double *px, double *py, double *pz, char ID=-1)
Definition: dhdc.cpp:4621
void __SDK dhdSleep(double sec)
Definition: dhdc.cpp:4754
bool __SDK dhdHasActiveGripper(char ID=-1)
Definition: dhdc.cpp:726
const char *__SDK dhdGetSDKVersionStr()
Definition: dhdc.cpp:925
int __SDK dhdGetButton(int index, char ID=-1)
Definition: dhdc.cpp:1195
int __SDK dhdEmulateButton(uchar val, char ID=-1)
Definition: dhdc.cpp:2941
int __SDK dhdSetForceAndGripperForce(double fx, double fy, double fz, double fg, char ID=-1)
Definition: dhdc.cpp:4678
const char *__SDK dhdErrorGetLastStr()
Definition: dhdError.cpp:197
const char *__SDK dhdGetSystemName(char ID=-1)
Definition: dhdc.cpp:814
#define DHD_OFF
Definition: dhdc.h:129
bool __SDK dhdIsLeftHanded(char ID=-1)
Definition: dhdc.cpp:576
#define DHD_ON
Definition: dhdc.h:128
int __SDK dhdGetPosition(double *px, double *py, double *pz, char ID=-1)
Definition: dhdc.cpp:1614
int __SDK dhdGetAvailableCount()
Definition: dhdc.cpp:243
double __SDK dhdGetTime()
Definition: dhdc.cpp:190
int __SDK dhdGetOrientationFrame(double matrix[3][3], char ID=-1)
Definition: dhdc.cpp:4552
int __SDK dhdGetGripperThumbPos(double *px, double *py, double *pz, char ID=-1)
Definition: dhdc.cpp:4582