File: OmniDriver.cpp

package info (click to toggle)
sofa-framework 1.0~beta4-9
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 88,688 kB
  • ctags: 27,205
  • sloc: cpp: 151,126; ansic: 2,387; xml: 581; sh: 417; makefile: 67
file content (361 lines) | stat: -rw-r--r-- 11,502 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <sofa/component/controller/OmniDriver.h>

#include <sofa/core/ObjectFactory.h>
#include <sofa/core/objectmodel/OmniEvent.h>
//
////force feedback
#include <sofa/component/controller/ForceFeedback.h>
#include <sofa/component/controller/NullForceFeedback.h>
//
#include <sofa/simulation/common/AnimateBeginEvent.h>
#include <sofa/simulation/common/AnimateEndEvent.h>
//
#include <sofa/simulation/common/Node.h>


//sensable namespace
using namespace sofa::defaulttype;

double prevTime;

namespace sofa
{

namespace component
{

namespace controller
{

using namespace sofa::defaulttype;
using namespace core::componentmodel::behavior;

//static DeviceData gServoDeviceData;
//static DeviceData deviceData;
//static DeviceData previousData;
static HHD hHD = HD_INVALID_HANDLE ;
static bool isInitialized = false;
static HDSchedulerHandle hStateHandle = HD_INVALID_HANDLE;

void printError(FILE *stream, const HDErrorInfo *error,
                   const char *message)
{
    fprintf(stream, "%s\n", hdGetErrorString(error->errorCode));
    fprintf(stream, "HHD: %X\n", error->hHD);
    fprintf(stream, "Error Code: %X\n", error->errorCode);
    fprintf(stream, "Internal Error Code: %d\n", error->internalErrorCode);
    fprintf(stream, "Message: %s\n", message);
}

bool isSchedulerError(const HDErrorInfo *error)
{
    switch (error->errorCode)
    {
        case HD_COMM_ERROR:
        case HD_COMM_CONFIG_ERROR:
        case HD_TIMER_ERROR:
        case HD_INVALID_PRIORITY:
        case HD_SCHEDULER_FULL:
            return HD_TRUE;

        default:
            return HD_FALSE;
    }
}

HDCallbackCode HDCALLBACK stateCallback(void *userData)
{
	OmniData* data = static_cast<OmniData*>(userData);
	//FIXME : Apparenlty, this callback is run before the mechanical state initialisation. I've found no way to know whether the mechcanical state is initialized or not, so i wait ...
	//static int wait = 0;

	if (data->servoDeviceData.stop)
	{
		return HD_CALLBACK_DONE;
	}

	if (!data->servoDeviceData.ready)
	{
		return HD_CALLBACK_CONTINUE;
	}

	HHD hapticHD = hdGetCurrentDevice();
	hdBeginFrame(hapticHD);

	data->servoDeviceData.id = hapticHD;

	//static int renderForce = true;

	// Retrieve the current button(s).
	hdGetIntegerv(HD_CURRENT_BUTTONS, &data->servoDeviceData.m_buttonState);

	//hdGetDoublev(HD_CURRENT_POSITION, data->servoDeviceData.m_devicePosition);
	// Get the column major transform
	HDdouble transform[16];
	hdGetDoublev(HD_CURRENT_TRANSFORM, transform);

	// Swap the X and Z axis

	Mat3x3d mrot;

	Quat rot;
	for (int i=0; i<3; i++)
		for (int j=0; j<3; j++)
			mrot[i][j] = transform[j*4+i];

	mrot = data->rotation * mrot;
	data->servoDeviceData.pos = data->translation + data->rotation * (Vec3d(transform[12+0], transform[12+1], transform[12+2]) * data->scale);

	rot.fromMatrix(mrot);
	rot.normalize();

	if ((rot[0]*data->servoDeviceData.quat[0]+rot[1]*data->servoDeviceData.quat[1]+rot[2]*data->servoDeviceData.quat[2]+rot[3]*data->servoDeviceData.quat[3]) < 0)
		for (int i=0;i<4;i++)
			rot[i] *= -1;

	data->servoDeviceData.quat[0] = rot[0];
	data->servoDeviceData.quat[1] = rot[1];
	data->servoDeviceData.quat[2] = rot[2];
	data->servoDeviceData.quat[3] = rot[3];

	//if(data->servoDeviceData.m_buttonState1)
	//	renderForce = !renderForce;

	double fx=0.0, fy=0.0, fz=0.0;
	if (data->forceFeedback != NULL)
		(data->forceFeedback)->computeForce(data->servoDeviceData.pos[0], data->servoDeviceData.pos[1], data->servoDeviceData.pos[2], data->servoDeviceData.quat[0], data->servoDeviceData.quat[1], data->servoDeviceData.quat[2], data->servoDeviceData.quat[3], fx, fy, fz);


	double currentForce[3];
	currentForce[0] = ( data->rotation[0][0] * fx + data->rotation[1][0] * fy + data->rotation[2][0] * fz) * data->forceScale;
	currentForce[1] = ( data->rotation[0][1] * fx + data->rotation[1][1] * fy + data->rotation[2][1] * fz) * data->forceScale;
	currentForce[2] = ( data->rotation[0][2] * fx + data->rotation[1][2] * fy + data->rotation[2][2] * fz) * data->forceScale;

 	if((data->servoDeviceData.m_buttonState & HD_DEVICE_BUTTON_1) || data->permanent_feedback)
		hdSetDoublev(HD_CURRENT_FORCE, currentForce);

	++data->servoDeviceData.nupdates;
	hdEndFrame(hapticHD);


	 HDErrorInfo error;
	if (HD_DEVICE_ERROR(error = hdGetError()))
	{
		printError(stderr, &error, "Error during scheduler callback");
		if (isSchedulerError(&error))
		{
			return HD_CALLBACK_DONE;
		}
	}
/*
 	OmniX = data->servoDeviceData.transform[12+0]*0.1;
	OmniY =	data->servoDeviceData.transform[12+1]*0.1;
	OmniZ =	data->servoDeviceData.transform[12+2]*0.1;
*/

	return HD_CALLBACK_CONTINUE;
}

void exitHandler()
{
    hdStopScheduler();
    hdUnschedule(hStateHandle);
/*
    if (hHD != HD_INVALID_HANDLE)
    {
        hdDisableDevice(hHD);
        hHD = HD_INVALID_HANDLE;
    }
*/
}


HDCallbackCode HDCALLBACK copyDeviceDataCallback(void *pUserData)
{
	OmniData *data = static_cast<OmniData*>(pUserData);
	memcpy(&data->deviceData, &data->servoDeviceData, sizeof(DeviceData));
	//data->servoDeviceData.quat[0] = data->servoDeviceData.quat[1] = data->servoDeviceData.quat[2] = data->servoDeviceData.quat[3] = 0.0;
	data->servoDeviceData.nupdates = 0;
	data->servoDeviceData.ready = true;
    return HD_CALLBACK_DONE;
}

HDCallbackCode HDCALLBACK stopCallback(void *pUserData)
{
	OmniData *data = static_cast<OmniData*>(pUserData);
	data->servoDeviceData.stop = true;
    return HD_CALLBACK_DONE;
}

/**
 * Sets up the device,
 */
int initDevice(OmniData& data)
{
	if (isInitialized) return 0;
	isInitialized = true;

	data.deviceData.quat[0] = 0;
	data.deviceData.quat[1] = 0;
	data.deviceData.quat[2] = 0;
	data.deviceData.quat[3] = 1;

	data.servoDeviceData.quat[0] = 0;
	data.servoDeviceData.quat[1] = 0;
	data.servoDeviceData.quat[2] = 0;
	data.servoDeviceData.quat[3] = 1;

    HDErrorInfo error;
    // Initialize the device, must be done before attempting to call any hd functions.
	if (hHD == HD_INVALID_HANDLE)
	{
		hHD = hdInitDevice(HD_DEFAULT_DEVICE);
		if (HD_DEVICE_ERROR(error = hdGetError())) 
		{
			printError(stderr, &error, "Failed to initialize the device");
			return -1;
		}
		printf("Found device %s\n",hdGetString(HD_DEVICE_MODEL_TYPE));

		hdEnable(HD_FORCE_OUTPUT);
		hdEnable(HD_MAX_FORCE_CLAMPING);

		// Start the servo loop scheduler.
		hdStartScheduler();
		if (HD_DEVICE_ERROR(error = hdGetError())) 
		{
			printError(stderr, &error, "Failed to start the scheduler");
			return -1;
		}
	}

	data.servoDeviceData.ready = false;
	data.servoDeviceData.stop = false;
    hStateHandle = hdScheduleAsynchronous( stateCallback, (void*) &data, HD_MAX_SCHEDULER_PRIORITY);

    if (HD_DEVICE_ERROR(error = hdGetError()))
    {
        printError(stderr, &error, "Failed to initialize haptic device");
        fprintf(stderr, "\nPress any key to quit.\n");
        getchar();
        exit(-1);
    }

	return 0;
}

OmniDriver::OmniDriver()
: scale(initData(&scale, 0.1, "scale","Default scale applied to the Phantom Coordinates. "))
, forceScale(initData(&forceScale, 1.0, "forceScale","Default forceScale applied to the force feedback. "))
, position(initData(&position, Vec3d(0,0,0), "position","Default position applied to the Phantom Coordinates"))
, orientation(initData(&orientation, Vec3d(0,0,0), "orientation","Default orientation applied to the Phantom Coordinates"))
, permanent(initData(&permanent, false, "permanent" , "Apply the force feedback permanently"))
{
	serr<<"toto"<<sendl;
	this->f_listening.setValue(true);
	data.forceFeedback = new NullForceFeedback();
}

OmniDriver::~OmniDriver()
{
}

void OmniDriver::cleanup()
{
	sout << "OmniDriver::cleanup()" << sendl;
	hdScheduleSynchronous(stopCallback, (void*) &data, HD_MIN_SCHEDULER_PRIORITY);
    //exitHandler();
    isInitialized = false;
//    delete forceFeedback;
}

void OmniDriver::setForceFeedback(ForceFeedback* ff)
{
	sout << "change ff" << endl;
	if(data.forceFeedback)
		delete data.forceFeedback;
	data.forceFeedback = ff;
};

void OmniDriver::init()
{
	sout << "OmniDriver::init()" << sendl;
	this->reinit();
}

void OmniDriver::reinit()
{
	simulation::Node *context = dynamic_cast<simulation::Node *>(this->getContext()); // access to current node
	ForceFeedback *ff = context->getTreeObject<ForceFeedback>();
	
	if(ff)
	{
		this->setForceFeedback(ff);
	}

	data.scale = scale.getValue();
	data.forceScale = forceScale.getValue();
	data.translation = position.getValue();
	Vector3 radV = orientation.getValue() * M_PI/180;
	Quaternion q = helper::Quater<double>::createFromRotationVector(radV);
	q.toMatrix(data.rotation);
	initDevice(data);
	sout << "OmniDriver::init() done" << sendl;

	data.permanent_feedback = permanent.getValue();
}

void OmniDriver::handleEvent(core::objectmodel::Event *event)
{
	if (dynamic_cast<sofa::simulation::AnimateBeginEvent *>(event))
	{
		//getData(); // copy data->servoDeviceData to gDeviceData
		hdScheduleSynchronous(copyDeviceDataCallback, (void *) &data, HD_MIN_SCHEDULER_PRIORITY);
		if (data.deviceData.ready)
		{
			data.deviceData.quat.normalize();
			//sout << "driver is working ! " << data->servoDeviceData.transform[12+0] << endl;

			sofa::core::objectmodel::OmniEvent omniEvent(data.deviceData.id, data.deviceData.pos, data.deviceData.quat, data.deviceData.m_buttonState);

			this->getContext()->propagateEvent(&omniEvent);
		}
	}
}

int OmniDriverClass = core::RegisterObject("Solver to test compliance computation for new articulated system objects")
    .add< OmniDriver >();

SOFA_DECL_CLASS(OmniDriver)


} // namespace controller

} // namespace component

} // namespace sofa