Debian Codegraph @

lib/interaction/src/draggers/SoTrackballDragger.c++

raw
1 /*
2 *
3 * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * Further, this software is distributed without any warranty that it is
16 * free of the rightful claim of any third person regarding infringement
17 * or the like. Any license provided herein, whether implied or
18 * otherwise, applies only to this software file. Patent licenses, if
19 * any, provided herein do not apply to combinations of this program with
20 * other software, or any other product whatsoever.
21 *
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 *
26 * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
27 * Mountain View, CA 94043, or:
28 *
29 * http://www.sgi.com
30 *
31 * For further information regarding this notice, see:
32 *
33 * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
34 *
35 */
36
37 /*
38 * Copyright (C) 1990,91 Silicon Graphics, Inc.
39 *
40 _______________________________________________________________________
41 ______________ S I L I C O N G R A P H I C S I N C . ____________
42 |
43 | $Revision: 1.1.1.1 $
44 |
45 | Classes:
46 | SoTrackballDragger
47 |
48 | Author(s): Paul Isaacs, David Mott
49 |
50 ______________ S I L I C O N G R A P H I C S I N C . ____________
51 _______________________________________________________________________
52 */
53
54
55 #include <cstdio>
56
57 #include <Inventor/errors/SoDebugError.h>
58 #include <Inventor/events/SoEvent.h>
59 #include <Inventor/events/SoKeyboardEvent.h>
60 #include <Inventor/SoDB.h>
61 #include <Inventor/sensors/SoTimerSensor.h>
62 #include <Inventor/sensors/SoFieldSensor.h>
63 #include <Inventor/actions/SoHandleEventAction.h>
64 #include <Inventor/draggers/SoTrackballDragger.h>
65 #include <Inventor/nodes/SoRotation.h>
66 #include <Inventor/nodes/SoSwitch.h>
67 #include <Inventor/nodes/SoSeparator.h>
68 #include <Inventor/nodes/SoSurroundScale.h>
69 #include <Inventor/nodes/SoAntiSquish.h>
70 #include <Inventor/projectors/SbCylinderPlaneProjector.h>
71 #include <Inventor/projectors/SbSphereSectionProjector.h>
72 #include <Inventor/projectors/SbLineProjector.h>
73
74 #include "geom/SoTrackballDraggerGeom.h"
75
76
77 // Defines
78
79 #define FAST_ANIM_RATE (1/60.0) // animation frame rate
80 #define ANIM_ADJUSTMENT 0.05 // used to schedule timerSensor to take
81 // a little more or a little less time.
82
83 // size of the rotation buffer, which is used to animate the spinning ball.
84 #define ROT_BUFFER_SIZE 5
85
86 SO_KIT_SOURCE(SoTrackballDragger);
87
88 ////////////////////////////////////////////////////////////////////////
89 //
90 // Description:
91 // Constructor
92 //
93 SoTrackballDragger::SoTrackballDragger()
94 //
95 ////////////////////////////////////////////////////////////////////////
96 {
97 SO_KIT_CONSTRUCTOR(SoTrackballDragger);
98
99 isBuiltIn = TRUE;
100
101 // Don't create this by default. It's only really put into use
102 // if this dragger is put inside a manipulator.
103 SO_KIT_ADD_CATALOG_ENTRY(surroundScale, SoSurroundScale,
104 TRUE, topSeparator, geomSeparator,TRUE);
105 // Create an anti-squish node by default.
106 SO_KIT_ADD_CATALOG_ENTRY(antiSquish, SoAntiSquish,
107 FALSE, topSeparator, geomSeparator,TRUE);
108
109 // Put this stuff under the geomSeparator so it will draw more
110 // efficiently.
111 SO_KIT_ADD_CATALOG_ENTRY(rotatorSwitch, SoSwitch, TRUE,
112 geomSeparator, ,FALSE);
113 SO_KIT_ADD_CATALOG_ENTRY(rotator, SoSeparator, TRUE,
114 rotatorSwitch, ,TRUE);
115 SO_KIT_ADD_CATALOG_ENTRY(rotatorActive, SoSeparator, TRUE,
116 rotatorSwitch, ,TRUE);
117
118 SO_KIT_ADD_CATALOG_ENTRY(XRotatorSwitch, SoSwitch, TRUE,
119 geomSeparator, ,FALSE);
120 SO_KIT_ADD_CATALOG_ENTRY(XRotator, SoSeparator, TRUE,
121 XRotatorSwitch, ,TRUE);
122 SO_KIT_ADD_CATALOG_ENTRY(XRotatorActive, SoSeparator, TRUE,
123 XRotatorSwitch, ,TRUE);
124
125 SO_KIT_ADD_CATALOG_ENTRY(YRotatorSwitch, SoSwitch, TRUE,
126 geomSeparator, ,FALSE);
127 SO_KIT_ADD_CATALOG_ENTRY(YRotator, SoSeparator, TRUE,
128 YRotatorSwitch, ,TRUE);
129 SO_KIT_ADD_CATALOG_ENTRY(YRotatorActive, SoSeparator, TRUE,
130 YRotatorSwitch, ,TRUE);
131
132 SO_KIT_ADD_CATALOG_ENTRY(ZRotatorSwitch, SoSwitch, TRUE,
133 geomSeparator, ,FALSE);
134 SO_KIT_ADD_CATALOG_ENTRY(ZRotator, SoSeparator, TRUE,
135 ZRotatorSwitch, ,TRUE);
136 SO_KIT_ADD_CATALOG_ENTRY(ZRotatorActive, SoSeparator, TRUE,
137 ZRotatorSwitch, ,TRUE);
138
139 SO_KIT_ADD_CATALOG_ENTRY(userAxisRotation, SoRotation, TRUE,
140 geomSeparator, ,FALSE);
141
142 SO_KIT_ADD_CATALOG_ENTRY(userAxisSwitch, SoSwitch, TRUE,
143 geomSeparator, ,FALSE);
144 SO_KIT_ADD_CATALOG_ENTRY(userAxis, SoSeparator, TRUE,
145 userAxisSwitch, ,TRUE);
146 SO_KIT_ADD_CATALOG_ENTRY(userAxisActive, SoSeparator, TRUE,
147 userAxisSwitch, ,TRUE);
148
149 SO_KIT_ADD_CATALOG_ENTRY(userRotatorSwitch, SoSwitch, TRUE,
150 geomSeparator, ,FALSE);
151 SO_KIT_ADD_CATALOG_ENTRY(userRotator, SoSeparator, TRUE,
152 userRotatorSwitch, ,TRUE);
153 SO_KIT_ADD_CATALOG_ENTRY(userRotatorActive, SoSeparator, TRUE,
154 userRotatorSwitch, ,TRUE);
155
156 // read geometry for shared parts
157 if (SO_KIT_IS_FIRST_INSTANCE())
158 readDefaultParts("trackballDragger.iv", geomBuffer, sizeof(geomBuffer) );
159
160 SO_KIT_ADD_FIELD(rotation, (0.0, 0.0, 0.0, 1.0));
161 SO_KIT_ADD_FIELD(scaleFactor, (1.0, 1.0, 1.0));
162
163 SO_KIT_INIT_INSTANCE();
164
165 // Make the anti-squish node surround the biggest dimension
166 SoAntiSquish *as = SO_GET_ANY_PART( this,"antiSquish", SoAntiSquish );
167 as->sizing = SoAntiSquish::LONGEST_DIAGONAL;
168
169 // create the parts...
170 setPartAsDefault("rotator", "trackballRotator");
171 setPartAsDefault("rotatorActive", "trackballRotatorActive");
172 setPartAsDefault("XRotator", "trackballXRotator");
173 setPartAsDefault("XRotatorActive", "trackballXRotatorActive");
174 setPartAsDefault("YRotator", "trackballYRotator");
175 setPartAsDefault("YRotatorActive", "trackballYRotatorActive");
176 setPartAsDefault("ZRotator", "trackballZRotator");
177 setPartAsDefault("ZRotatorActive", "trackballZRotatorActive");
178 setPartAsDefault("userAxis", "trackballUserAxis");
179 setPartAsDefault("userAxisActive", "trackballUserAxisActive");
180 setPartAsDefault("userRotator", "trackballUserRotator");
181 setPartAsDefault("userRotatorActive","trackballUserRotatorActive");
182
183 // Set the switches of the ball and stripes to 0...
184 setSwitchValue( rotatorSwitch.getValue(), 0 );
185 setSwitchValue( XRotatorSwitch.getValue(), 0 );
186 setSwitchValue( YRotatorSwitch.getValue(), 0 );
187 setSwitchValue( ZRotatorSwitch.getValue(), 0 );
188
189 //Turn off userAxis Completely (SO_SWITCH_NONE)
190 setSwitchValue( userAxisSwitch.getValue(), SO_SWITCH_NONE );
191 setSwitchValue( userRotatorSwitch.getValue(), SO_SWITCH_NONE );
192
193 // Set the rotation of the userStuffRotation to an initial value.
194 SoRotation *rN = SO_GET_ANY_PART(this,"userAxisRotation", SoRotation);
195 rN->rotation.setValue( SbRotation( SbVec3f(0,1,0), 0.0 ) );
196
197 currentState = INACTIVE;
198
199 setHighlights();
200
201 // init the user axis to align with 'y'
202 userAxisVec.setValue( 0, 1, 0);
203
204 // queues used for animation
205 rotBuffer = new SbRotation[ROT_BUFFER_SIZE];
206 timeBuffer = new SbTime[ROT_BUFFER_SIZE];
207
208 // allocate animation sensor
209 spinSensor = new SoTimerSensor(&SoTrackballDragger::spinSensorCB, this);
210
211 animationEnabled = TRUE;
212 wasSpinningAtDragStart = FALSE;
213
214 sphereProj = new SbSphereSectionProjector( 0.85 );
215 stripeProj = new SbCylinderPlaneProjector( 0.85 );
216
217 // add the callbacks to perform the dragging
218 addStartCallback( &SoTrackballDragger::startCB );
219 addMotionCallback( &SoTrackballDragger::motionCB );
220 addFinishCallback( &SoTrackballDragger::finishCB );
221
222 // add the callback to update things each time a meta key changes.
223 addOtherEventCallback( &SoTrackballDragger::metaKeyChangeCB );
224
225 // Update the rotation and scale fields when the motionMatrix is set.
226 addValueChangedCallback( &SoTrackballDragger::valueChangedCB );
227
228 // Updates the motionMatrix when the scaleFactor field is set.
229 rotFieldSensor = new SoFieldSensor(&SoTrackballDragger::fieldSensorCB,this);
230 rotFieldSensor->setPriority( 0 );
231
232 // Updates the motionMatrix when the scaleFactor field is set.
233 scaleFieldSensor
234 = new SoFieldSensor( &SoTrackballDragger::fieldSensorCB, this);
235 scaleFieldSensor->setPriority( 0 );
236
237 setUpConnections( TRUE, TRUE );
238 }
239
240 ////////////////////////////////////////////////////////////////////////
241 //
242 // Description:
243 // Destructor.
244 //
245 // Use: public
246
247 SoTrackballDragger::~SoTrackballDragger()
248 //
249 ////////////////////////////////////////////////////////////////////////
250 {
251 // deallocate queues
252 delete [ /*ROT_BUFFER_SIZE*/ ] rotBuffer;
253 delete [ /*ROT_BUFFER_SIZE*/ ] timeBuffer;
254
255 delete sphereProj;
256 delete stripeProj;
257
258 // delete sensors
259 if (spinSensor != NULL)
260 delete spinSensor;
261 if (rotFieldSensor != NULL)
262 delete rotFieldSensor;
263 if (scaleFieldSensor != NULL)
264 delete scaleFieldSensor;
265 }
266
267 // detach/attach any sensors, callbacks, and/or field connections.
268 // Called by: start/end of SoBaseKit::readInstance
269 // and on new copy by: start/end of SoBaseKit::copy.
270 // Classes that redefine must call setUpConnections(TRUE,TRUE)
271 // at end of constructor.
272 // Returns the state of the node when this was called.
273 SbBool
274 SoTrackballDragger::setUpConnections( SbBool onOff, SbBool doItAlways )
275 {
276 if ( !doItAlways && connectionsSetUp == onOff)
277 return onOff;
278
279 if ( onOff ) {
280
281 // We connect AFTER base class.
282 SoDragger::setUpConnections( onOff, FALSE );
283
284 // Call the sensor CBs to make things are up-to-date.
285 fieldSensorCB( this, NULL );
286
287 // Figure out the userAxisVec (a protected variable) from the
288 // 'userAxisRotation' part.
289 SoRotation *rN = (SoRotation *) userAxisRotation.getValue();
290 if (rN != NULL) {
291 SbRotation uRot = rN->rotation.getValue();
292 uRot.multVec( SbVec3f(0,1,0), userAxisVec );
293
294 // decide whether or not to display the spinning wheel.
295 // only show it if does not line up with a major axis.
296 if ( ( fabs(userAxisVec[0]) > 0.99 )
297 || ( fabs(userAxisVec[1]) > 0.99 )
298 || ( fabs(userAxisVec[2]) > 0.99 ) ) {
299 setSwitchValue( userAxisSwitch.getValue(), SO_SWITCH_NONE );
300 setSwitchValue( userRotatorSwitch.getValue(), SO_SWITCH_NONE );
301 }
302 else {
303 setSwitchValue( userAxisSwitch.getValue(), 1 );
304 setSwitchValue( userRotatorSwitch.getValue(), 1 );
305 }
306 }
307
308 // Connect the field sensors
309 if (rotFieldSensor->getAttachedField() != &rotation)
310 rotFieldSensor->attach( &rotation );
311 if (scaleFieldSensor->getAttachedField() != &scaleFactor)
312 scaleFieldSensor->attach( &scaleFactor );
313 }
314 else {
315
316 // We disconnect BEFORE base class.
317
318 // Disconnect the field sensors.
319 if (rotFieldSensor->getAttachedField())
320 rotFieldSensor->detach();
321 if (scaleFieldSensor->getAttachedField())
322 scaleFieldSensor->detach();
323
324 SoDragger::setUpConnections( onOff, FALSE );
325 }
326
327 return !(connectionsSetUp = onOff);
328 }
329
330 ////////////////////////////////////////////////////////////////////////
331 //
332 // Description:
333 // Destructor.
334 //
335 // Use: public
336 void
337 SoTrackballDragger::setAnimationEnabled( SbBool newVal )
338 //
339 ////////////////////////////////////////////////////////////////////////
340 {
341 animationEnabled = newVal;
342 if (animationEnabled == FALSE )
343 resetSpinStuff();
344 }
345
346 ////////////////////////////////////////////////////////////////////////
347 //
348 // Description:
349 // Sets the various switch nodes to highlight the correct parts
350 // of the trackball, depending on the state.
351 //
352 // Use: private
353 //
354 void
355 SoTrackballDragger::setHighlights()
356 //
357 ////////////////////////////////////////////////////////////////////////
358 {
359 switch ( currentState ) {
360 case INACTIVE:
361 case SPINNING:
362 setAllPartsActive( FALSE );
363 break;
364 case FREE_ROTATE:
365 case SCALE:
366 setAllPartsActive( TRUE );
367 break;
368 case X_ROTATE:
369 setAllPartsActive( FALSE );
370 setSwitchValue( XRotatorSwitch.getValue(), 1 );
371 break;
372 case Y_ROTATE:
373 setAllPartsActive( FALSE );
374 setSwitchValue( YRotatorSwitch.getValue(), 1 );
375 break;
376 case Z_ROTATE:
377 setAllPartsActive( FALSE );
378 setSwitchValue( ZRotatorSwitch.getValue(), 1 );
379 break;
380 case USER_AXIS_ROTATE:
381 case USER_AXIS_ADJUST:
382 {
383 setAllPartsActive( FALSE );
384
385 SoSwitch *sw = (SoSwitch *) userAxisSwitch.getValue();
386 if ( sw && sw->whichChild.getValue() != SO_SWITCH_NONE )
387 setSwitchValue( userAxisSwitch.getValue(), 1 );
388
389 sw = (SoSwitch *) userRotatorSwitch.getValue();
390 if ( sw && sw->whichChild.getValue() != SO_SWITCH_NONE )
391 setSwitchValue( userRotatorSwitch.getValue(), 1 );
392 }
393 break;
394 }
395 }
396
397 ////////////////////////////////////////////////////////////////////////
398 //
399 // Description:
400 // Rotate the trackball and object based on mouse motion.
401 //
402 // Use: private
403 //
404 void
405 SoTrackballDragger::dragStart()
406 //
407 ////////////////////////////////////////////////////////////////////////
408 {
409 // register time for animation of continuous spinning
410 prevTime = getEvent()->getTime();
411
412 // We want to remember if we were spinning at drag start.
413 // If so, we will always call ha->setHandled() in dragFinish().
414 // This way, it won't be considered an item selection, which is usually
415 // the case when you click on an object without moving the mouse.
416 wasSpinningAtDragStart = (currentState == SPINNING);
417 resetSpinStuff(); // check if spinning should be stopped
418
419 const SoPath *pickPath = getPickPath();
420
421 // Invalidate surroundScale if it exists.
422 SoSurroundScale *ss = SO_CHECK_PART(this, "surroundScale", SoSurroundScale);
423 if (ss != NULL)
424 ss->invalidate();
425
426 // Make a note of which modifier keys are down
427 ctlDown = getEvent()->wasCtrlDown();
428 shftDown = getEvent()->wasShiftDown();
429
430 // Determine the current state
431 if (ctlDown)
432 currentState = SCALE;
433 else if (shftDown)
434 currentState = USER_AXIS_ADJUST;
435 else if (pickPath && pickPath->containsNode( XRotatorSwitch.getValue() ) ||
436 getSurrogatePartPickedName() == "XRotator" )
437 currentState = X_ROTATE;
438 else if (pickPath && pickPath->containsNode( YRotatorSwitch.getValue() ) ||
439 getSurrogatePartPickedName() == "YRotator" )
440 currentState = Y_ROTATE;
441 else if (pickPath && pickPath->containsNode( ZRotatorSwitch.getValue() ) ||
442 getSurrogatePartPickedName() == "ZRotator" )
443 currentState = Z_ROTATE;
444 else if (pickPath && pickPath->containsNode(userRotatorSwitch.getValue()) ||
445 getSurrogatePartPickedName() == "userRotator" )
446 currentState = USER_AXIS_ROTATE;
447 else
448 currentState = FREE_ROTATE;
449
450 // set the constrained axis, if appropriate
451 switch( currentState ) {
452 case X_ROTATE:
453 constrainedAxis.setValue( 1, 0, 0);
454 break;
455 case Y_ROTATE:
456 constrainedAxis.setValue( 0, 1, 0);
457 break;
458 case Z_ROTATE:
459 constrainedAxis.setValue( 0, 0, 1);
460 break;
461 case USER_AXIS_ROTATE:
462 constrainedAxis = userAxisVec;
463 break;
464 default:
465 break;
466 }
467
468 // Working space is space after "antiSquish"
469 SbMatrix workSpaceToLocal, localToWorkSpace;
470 getPartToLocalMatrix( "antiSquish", workSpaceToLocal, localToWorkSpace);
471 SbMatrix worldSpaceToWork = getWorldToLocalMatrix();
472 worldSpaceToWork.multRight( localToWorkSpace );
473 SbMatrix workSpaceToWorld = getLocalToWorldMatrix();
474 workSpaceToWorld.multLeft( workSpaceToLocal );
475
476 // Find the starting point in workspace.
477 SbVec3f startWorkSpaceHitPt;
478 worldSpaceToWork.multVecMatrix(getWorldStartingPoint(),startWorkSpaceHitPt);
479
480
481 float rad;
482 SbVec3f zero( 0,0,0 );
483 SbLine theAxis;
484 rad = startWorkSpaceHitPt.length();
485
486
487 // Setup projector and get a starting value
488 switch( currentState ) {
489 case SCALE:
490 case USER_AXIS_ADJUST:
491 case FREE_ROTATE:
492 {
493 SbVec3f sphCenter(0,0,0);
494 sphereProj->setSphere( SbSphere( sphCenter, rad ));
495
496 SbViewVolume viewVol = getViewVolume();
497
498 sphereProj->setViewVolume(viewVol );
499 sphereProj->setWorkingSpace( workSpaceToWorld );
500
501 // If the hit point is on the near side of the center from where
502 // the eye is, then tell the projector to intersect front.
503 // Else, tell it to intersect back.
504 if (getFrontOnProjector() == USE_PICK )
505 sphereProj->setFront( sphereProj->isPointInFront( startWorkSpaceHitPt ));
506 else if (getFrontOnProjector() == FRONT )
507 sphereProj->setFront( TRUE );
508 else
509 sphereProj->setFront( FALSE );
510 // We need to project and save the starting world point,
511 // Since our rotate projectors might intersect to find a
512 // different point than we hit on the geometry itself.
513 SbVec3f ptOnProjector, worldSpacePt;
514 ptOnProjector = sphereProj->project(getNormalizedLocaterPosition());
515 workSpaceToWorld.multVecMatrix(ptOnProjector,worldSpacePt);
516 setStartingPoint(worldSpacePt);
517 }
518 break;
519 case X_ROTATE:
520 case Y_ROTATE:
521 case Z_ROTATE:
522 case USER_AXIS_ROTATE:
523 {
524 theAxis.setValue( zero, zero + constrainedAxis );
525 stripeProj->setCylinder( SbCylinder(theAxis, rad) );
526 stripeProj->setViewVolume(getViewVolume());
527 stripeProj->setWorkingSpace( workSpaceToWorld );
528
529 // If the hit point is on the near side of the center from where
530 // the eye is, then tell the projector to intersect front.
531 // Else, tell it to intersect back.
532 if (getFrontOnProjector() == USE_PICK )
533 stripeProj->setFront( stripeProj->isPointInFront( startWorkSpaceHitPt));
534 else if (getFrontOnProjector() == FRONT )
535 stripeProj->setFront( TRUE );
536 else
537 stripeProj->setFront( FALSE );
538
539 // We need to project and save the starting world point,
540 // Since our rotate projectors might intersect to find a
541 // different point than we hit on the geometry itself.
542 SbVec3f ptOnProjector, worldSpacePt;
543 ptOnProjector = stripeProj->project(getNormalizedLocaterPosition());
544 workSpaceToWorld.multVecMatrix(ptOnProjector,worldSpacePt);
545 setStartingPoint(worldSpacePt);
546 }
547 break;
548 case INACTIVE:
549 case SPINNING:
550 break;
551 }
552
553 // Save for incremental rotations, needed by spherical projector.
554 prevWorldHitPt = getWorldStartingPoint();
555 prevMotionMatrix = getStartMotionMatrix();
556
557 if ( currentState == USER_AXIS_ADJUST )
558 userStripeDrag();
559
560 setHighlights();
561 }
562
563
564 ////////////////////////////////////////////////////////////////////////
565 //
566 // Description:
567 // Drag the trackball based on mouse motion.
568 // This routine just ships the work to rotateDrag or
569 // scaleDrag.
570 //
571 // Use: private
572 //
573 void
574 SoTrackballDragger::drag()
575 //
576 ////////////////////////////////////////////////////////////////////////
577 {
578 switch( currentState ) {
579 case SCALE:
580 scaleDrag();
581 break;
582 case USER_AXIS_ADJUST:
583 userStripeDrag();
584 break;
585 case FREE_ROTATE:
586 case X_ROTATE:
587 case Y_ROTATE:
588 case Z_ROTATE:
589 case USER_AXIS_ROTATE:
590 rotateDrag();
591 break;
592 case INACTIVE:
593 case SPINNING:
594 break;
595 }
596 }
597
598 ////////////////////////////////////////////////////////////////////////
599 //
600 // Description:
601 // Rotate the trackball and object based on mouse motion.
602 //
603 // Use: private
604 //
605 SbBool
606 SoTrackballDragger::rotateDrag()
607 //
608 ////////////////////////////////////////////////////////////////////////
609 {
610 SbMatrix workSpaceToLocal, localToWorkSpace;
611 getPartToLocalMatrix( "antiSquish", workSpaceToLocal, localToWorkSpace);
612 SbMatrix workSpaceToWorld = getLocalToWorldMatrix();
613 workSpaceToWorld.multLeft( workSpaceToLocal );
614 SbMatrix worldSpaceToWork = getWorldToLocalMatrix();
615 worldSpaceToWork.multRight( localToWorkSpace );
616
617 // update the viewvolume and workspace on the projectors
618 sphereProj->setViewVolume(getViewVolume());
619 stripeProj->setViewVolume(getViewVolume());
620 sphereProj->setWorkingSpace( workSpaceToWorld );
621 stripeProj->setWorkingSpace( workSpaceToWorld );
622
623 // Get newHitPt and prevHitPt in workspace.
624 SbVec3f prevHitPt;
625 worldSpaceToWork.multVecMatrix(prevWorldHitPt, prevHitPt );
626 SbVec3f newHitPt;
627 SbRotation deltaRot;
628 if ( currentState == FREE_ROTATE ) {
629 newHitPt = sphereProj->project(getNormalizedLocaterPosition());
630 deltaRot = sphereProj->getRotation(prevHitPt,newHitPt);
631 }
632 else {
633 newHitPt = stripeProj->project(getNormalizedLocaterPosition());
634 deltaRot = stripeProj->getRotation(prevHitPt,newHitPt);
635 }
636
637 // Append deltaRot to prevMotionMatrix, which we saved last time.
638 SbMatrix newMotionMatrix =
639 appendRotation( prevMotionMatrix, deltaRot, SbVec3f(0,0,0),
640 &workSpaceToLocal );
641
642 // Save our incremental results.
643 workSpaceToWorld.multVecMatrix(newHitPt, prevWorldHitPt);
644 prevMotionMatrix = newMotionMatrix;
645
646 setMotionMatrix( newMotionMatrix );
647
648 // save information for animation of continuous spining
649 prevTime = getEvent()->getTime();
650
651 // save increment of rotation for animation
652 lastIndex = ((lastIndex+1) % ROT_BUFFER_SIZE);
653 rotBuffer[lastIndex] = deltaRot;
654 timeBuffer[lastIndex] = prevTime;
655
656 // check if queue is full
657 // if so, through away oldest events from queue
658 if (((lastIndex+1) % ROT_BUFFER_SIZE) == firstIndex)
659 firstIndex = ((firstIndex+1) % ROT_BUFFER_SIZE);
660
661 return TRUE;
662 }
663
664 ////////////////////////////////////////////////////////////////////////
665 //
666 // Description:
667 // Apply a uniform scale to the trackball, by finding the closest point
668 // on the line and seeing how much further (orcloser) from the
669 // center we are than last time.
670 //
671 // Use: private
672 //
673 SbBool
674 SoTrackballDragger::scaleDrag()
675 //
676 ////////////////////////////////////////////////////////////////////////
677 {
678 SbMatrix workSpaceToLocal, localToWorkSpace;
679 getPartToLocalMatrix( "antiSquish", workSpaceToLocal, localToWorkSpace);
680 SbMatrix workSpaceToWorld = getLocalToWorldMatrix();
681 workSpaceToWorld.multLeft( workSpaceToLocal );
682 SbMatrix worldSpaceToWork = getWorldToLocalMatrix();
683 worldSpaceToWork.multRight( localToWorkSpace );
684
685 SbVec3f startHitPt, cntr( 0,0,0 );
686 SbLineProjector lineProj;
687 worldSpaceToWork.multVecMatrix( getWorldStartingPoint(), startHitPt );
688
689 // make a projection line between the center and the initial hit point.
690 lineProj.setLine( SbLine( cntr, startHitPt ));
691 lineProj.setViewVolume(getViewVolume());
692 lineProj.setWorkingSpace( workSpaceToWorld );
693
694 SbVec3f newHitPt;
695 // lineProj has the line we are locked to in expanding and contracting
696 // the trackball. Find the point from lineProj closest to the mouseLine
697 newHitPt = lineProj.project(getNormalizedLocaterPosition());
698
699 SbVec3f oldRadVec = startHitPt - cntr;
700 SbVec3f newRadVec = newHitPt - cntr;
701
702 // [1] Find the distance from the old and new projected points to origin
703 float oldRad = oldRadVec.length();
704 float newRad = newRadVec.length();
705
706 // [2] Check if we've flipped to the other side of the origin.
707 if (startHitPt.dot(newHitPt) < 0.0)
708 newRad *= -1.0;
709
710 // [3] Change in scale is ratio of newRad to oldRad
711 #define TINY .0001
712 float delta = (fabs(oldRad) < TINY || fabs(newRad) < TINY)
713 ? 1.0 : newRad / oldRad;
714 #undef TINY
715
716 // constrain the scaling to be greater than getMinScale()
717 if (delta < getMinScale())
718 delta = getMinScale();
719
720 // Set the scaling (to be done relative to scale in startMotionMatrix).
721 SbVec3f scl( delta, delta, delta );
722
723 // Save our incremental results.
724 workSpaceToWorld.multVecMatrix(newHitPt, prevWorldHitPt);
725
726 // Append this to the startMotionMatrix, which we saved at the beginning
727 // of the drag, to find the current motion matrix.
728 setMotionMatrix( appendScale( getStartMotionMatrix(), scl,SbVec3f(0,0,0),
729 &workSpaceToLocal));
730
731 return TRUE;
732 }
733
734 ////////////////////////////////////////////////////////////////////////
735 //
736 // Description:
737 // Select a new user-selected axis for constrained rotation.
738 // When the user selects this special axis, an axis and a wheel
739 // are displayed. Once selected and displayed, the user can
740 // pick the wheel and use it to spin the trackball about this
741 // axis.
742 //
743 // Use: private
744 //
745 SbBool
746 SoTrackballDragger::userStripeDrag()
747 //
748 ////////////////////////////////////////////////////////////////////////
749 {
750 SbMatrix workSpaceToLocal, localToWorkSpace;
751 getPartToLocalMatrix( "antiSquish", workSpaceToLocal, localToWorkSpace);
752 SbMatrix workSpaceToWorld = getLocalToWorldMatrix();
753 workSpaceToWorld.multLeft( workSpaceToLocal );
754 SbMatrix worldSpaceToWork = getWorldToLocalMatrix();
755 worldSpaceToWork.multRight( localToWorkSpace );
756
757 SbVec3f newHitPt;
758
759 // get the newHitPt
760 // temporarily make the tolerance = 1.0, since we want all possible sphere
761 // intersections. This makes for a nicer interface of axis picking
762 ((SbSphereSectionProjector *)sphereProj)->setTolerance( 1.0 );
763 newHitPt = sphereProj->project(getNormalizedLocaterPosition());
764 ((SbSphereSectionProjector *)sphereProj)->setTolerance( 0.85 );
765
766 // find the new axis
767 userAxisVec = newHitPt;
768 userAxisVec.normalize();
769
770 SbRotation plcmntRot(SbVec3f(0,1,0), userAxisVec);
771 ((SoRotation *)userAxisRotation.getValue())->rotation.setValue( plcmntRot );
772
773 // decide whether or not to display the spinning wheel.
774 // only show it if does not line up with a major axis.
775 if ( ( fabs(userAxisVec[0]) > 0.99 )
776 || ( fabs(userAxisVec[1]) > 0.99 )
777 || ( fabs(userAxisVec[2]) > 0.99 ) ) {
778 setSwitchValue( userAxisSwitch.getValue(), SO_SWITCH_NONE );
779 setSwitchValue( userRotatorSwitch.getValue(), SO_SWITCH_NONE );
780 }
781 else {
782 setSwitchValue( userAxisSwitch.getValue(), 1 );
783 setSwitchValue( userRotatorSwitch.getValue(), 1 );
784 }
785
786 // save intersection for later
787 workSpaceToWorld.multVecMatrix( newHitPt, prevWorldHitPt );
788
789 return TRUE;
790 }
791
792 ////////////////////////////////////////////////////////////////////////
793 //
794 // Description:
795 // Called when the mouse-button is released.
796 // Prepares the spinSensor to continue spinning...
797 //
798 // Use: private
799 //
800 void
801 SoTrackballDragger::dragFinish()
802 //
803 ////////////////////////////////////////////////////////////////////////
804 {
805 // Invalidate surroundScale if it exists.
806 SoSurroundScale *ss = SO_CHECK_PART(this, "surroundScale", SoSurroundScale);
807 if (ss != NULL)
808 ss->invalidate();
809
810 switch ( currentState ) {
811 case FREE_ROTATE:
812 case X_ROTATE:
813 case Y_ROTATE:
814 case Z_ROTATE:
815 case USER_AXIS_ROTATE:
816 // check if we need to continue spinning
817 if ( isAnimationEnabled()
818 && (getEvent()->getTime() - prevTime) == SbTime::zero()) {
819 // button came up during motion
820
821 spinTime.setToTimeOfDay();
822 scheduleRate = FAST_ANIM_RATE;
823 currentState = SPINNING;
824 computeAverage = TRUE;
825 spinSensor->setInterval(scheduleRate);
826 spinSensor->schedule();
827 }
828 else
829 currentState = INACTIVE;
830 break;
831 default:
832 currentState = INACTIVE;
833 break;
834 }
835
836 setHighlights();
837
838 if (wasSpinningAtDragStart)
839 getHandleEventAction()->setHandled();
840 }
841
842 ////////////////////////////////////////////////////////////////////////
843 //
844 // Description:
845 // Resets all variables for turning off the spinSensor
846 //
847 // Use: private
848
849 void
850 SoTrackballDragger::resetSpinStuff()
851 //
852 ////////////////////////////////////////////////////////////////////////
853 {
854 if ( currentState == SPINNING ) {
855 currentState = INACTIVE;
856 spinSensor->unschedule();
857 renderCaching = AUTO;
858 }
859
860 // reset animation queue for spinning
861 firstIndex = 0;
862 lastIndex = -1;
863 }
864
865 ////////////////////////////////////////////////////////////////////////
866 //
867 // Description:
868 // Routine which animates the ball spinning (called by sensor).
869 //
870 // Use: private
871
872 void
873 SoTrackballDragger::spinAnimate()
874 //
875 ////////////////////////////////////////////////////////////////////////
876 {
877 // get the time difference
878 SbTime time = SbTime::getTimeOfDay();
879 SbTime timeDiff = time - spinTime;
880 spinTime = time; // save current time
881 double sec = timeDiff.getValue();
882 float angle;
883
884 // check if average rotation needs to be computed
885 if (computeAverage) {
886
887 // get number of samples
888 int num = (((lastIndex - firstIndex) + 1 +
889 ROT_BUFFER_SIZE) % ROT_BUFFER_SIZE);
890
891 // check for not enough samples
892 if (num < 2) {
893 resetSpinStuff();
894 return;
895 }
896
897 // get average axis of rotation
898 // ??? right now only take one sample for axis
899 rotBuffer[firstIndex].getValue(averageAxis, angle);
900
901 // get angular velocity
902 SbVec3f axis;
903 angleVelocity = 0;
904 for (int i=0; i<num; i++) {
905 int n = (firstIndex + i) % ROT_BUFFER_SIZE;
906 rotBuffer[n].getValue(axis, angle);
907 angleVelocity += angle;
908 }
909 SbTime deltaTime = timeBuffer[lastIndex] - timeBuffer[firstIndex];
910
911 #ifdef DEBUG
912 // check for negative number
913 if (deltaTime.getValue() <= 0.0)
914 SoDebugError::post("SoTrackballDragger::spinAnimate",
915 "Zero or negative Dt %f", deltaTime.getValue());
916 #endif
917
918 angleVelocity /= deltaTime.getValue();
919
920 computeAverage = FALSE;
921 }
922
923 // calculate the change in rotation
924 angle = angleVelocity * sec;
925
926 // append the incremental rotation after the current rotation
927 SbRotation rotIncrement(averageAxis, angle);
928
929 // recalculate trackball placement
930 // 1 -- convert local motion into matrix
931 SbMatrix tm;
932 tm.setRotate( rotIncrement );
933 // 2 -- transform matrix across antisquish node.
934 transformMatrixToLocalSpace( tm, tm, "antiSquish");
935 // 3 -- append matrix to motion
936 SbMatrix newMotion = getMotionMatrix();
937 setMotionMatrix( newMotion.multLeft( tm ) );
938
939 if ( timeDiff > ( scheduleRate * ( 1 + ANIM_ADJUSTMENT) ))
940 // If things are taking significantly longer than expected,
941 // increase the amount of time between calls.
942 scheduleRate *= ( 1 + ANIM_ADJUSTMENT );
943 else if ( timeDiff < ( scheduleRate * ( 1 + (ANIM_ADJUSTMENT/2.0)) )) {
944 // otherwise, if things are going quickly, reduce the time.
945 // See which is smaller, scaling down the rate (newRate1)
946 // or a binary-search hop down to the FAST_ANIM_RATE
947 SbTime newRate1 = scheduleRate * ( 1 - ANIM_ADJUSTMENT );
948 SbTime newRate2 = scheduleRate - 0.5 * (scheduleRate - FAST_ANIM_RATE);
949 scheduleRate = ( newRate1 < newRate2 ) ? newRate1 : newRate2;
950 }
951
952 // Make sure we don't go below the fastest rate
953 if ( scheduleRate < FAST_ANIM_RATE )
954 scheduleRate = FAST_ANIM_RATE;
955
956 // reschedule at the new rate, starting at THIS time + one increment
957 // We don't need to unschedule first -- it's done automatically!
958 spinSensor->setInterval(scheduleRate);
959 spinSensor->setBaseTime(spinTime + scheduleRate);
960 spinSensor->schedule();
961 }
962
963 //
964 ////////////////////////////////////////////////////////////////////////
965 // static callbacks stubs
966 ////////////////////////////////////////////////////////////////////////
967 //
968
969 void
970 SoTrackballDragger::spinSensorCB(void *v, SoSensor *)
971 {
972 SoTrackballDragger *m = (SoTrackballDragger *) v;
973
974 m->renderCaching = OFF;
975 m->spinAnimate();
976 }
977
978 ////////////////////////////////////////////////////////////////////////
979 //
980 // Use: protected
981 //
982 void
983 SoTrackballDragger::setAllPartsActive( SbBool onOrOff )
984 //
985 ////////////////////////////////////////////////////////////////////////
986 {
987 int sVal = (onOrOff == TRUE) ? 1 : 0;
988
989 setSwitchValue( rotatorSwitch.getValue(), sVal );
990 setSwitchValue( XRotatorSwitch.getValue(), sVal );
991 setSwitchValue( YRotatorSwitch.getValue(), sVal );
992 setSwitchValue( ZRotatorSwitch.getValue(), sVal );
993
994 SoSwitch *sw = (SoSwitch *) userAxisSwitch.getValue();
995 if ( sw && sw->whichChild.getValue() != SO_SWITCH_NONE )
996 setSwitchValue( userAxisSwitch.getValue(), sVal );
997
998 sw = (SoSwitch *) userRotatorSwitch.getValue();
999 if ( sw && sw->whichChild.getValue() != SO_SWITCH_NONE )
1000 setSwitchValue( userRotatorSwitch.getValue(), sVal );
1001 }
1002
1003 //
1004 ////////////////////////////////////////////////////////////////////////
1005 // keypress/release callback function
1006 //
1007 // This assures that the proper changes to the highlights,
1008 // currentState, and projectors are made
1009 //
1010 // It is called every time a meta key is pressed or released
1011 //
1012 ////////////////////////////////////////////////////////////////////////
1013 //
1014
1015 void
1016 SoTrackballDragger::metaKeyChangeCB( void *, SoDragger *inDragger)
1017 {
1018 SoTrackballDragger *tb = (SoTrackballDragger *) inDragger;
1019
1020 SoHandleEventAction *ha = tb->getHandleEventAction();
1021
1022 //[1] Only do this if we are grabbing
1023 if ( ha->getGrabber() != tb )
1024 return;
1025
1026 //[2] We only want key press or release events.
1027 const SoEvent *event = tb->getEvent();
1028 if ( !SO_KEY_PRESS_EVENT(event, ANY) && !SO_KEY_RELEASE_EVENT(event, ANY))
1029 return;
1030
1031 //[3] Is the key constrain or modify?
1032 const SoKeyboardEvent *ke = (const SoKeyboardEvent *) event;
1033 SoKeyboardEvent::Key key = ke->getKey();
1034 if ( key == SoKeyboardEvent::LEFT_SHIFT ||
1035 key == SoKeyboardEvent::RIGHT_SHIFT ||
1036 key == SoKeyboardEvent::LEFT_CONTROL ||
1037 key == SoKeyboardEvent::RIGHT_CONTROL ) {
1038
1039 // We want to end the old gesture and start a new one.
1040
1041 // [A] Release the grabber. This ends the gesture and calls all
1042 // finishCallbacks (on parent dragger, too, if we're registered)
1043 ha->releaseGrabber();
1044
1045 // [B] Set the starting point to be our saved prevWorldHitPt
1046 tb->setStartingPoint( tb->prevWorldHitPt );
1047
1048 // [C] Become the grabber again. This begins a new gesture and calls all
1049 // startCallbacks (parent dragger, too). Info like viewVolume,
1050 // viewportRegion, handleEventAction, and tempPathToThis
1051 // is still valid.
1052 ha->setGrabber(tb);
1053
1054 // [D] set handled
1055 ha->setHandled();
1056 }
1057 }
1058
1059 ////////////////////////////////////////////////////////////////////
1060 // Stubs for callbacks
1061 ////////////////////////////////////////////////////////////////////
1062 void
1063 SoTrackballDragger::startCB( void *, SoDragger *inDragger )
1064 {
1065 SoTrackballDragger *tb = (SoTrackballDragger *) inDragger;
1066 tb->dragStart();
1067 }
1068
1069 void
1070 SoTrackballDragger::motionCB( void *, SoDragger *inDragger )
1071 {
1072 SoTrackballDragger *tb = (SoTrackballDragger *) inDragger;
1073 tb->drag();
1074 }
1075
1076 void
1077 SoTrackballDragger::finishCB( void *, SoDragger *inDragger )
1078 {
1079 SoTrackballDragger *tb = (SoTrackballDragger *) inDragger;
1080 tb->dragFinish();
1081 }
1082
1083 void
1084 SoTrackballDragger::valueChangedCB( void *, SoDragger *inDragger )
1085 {
1086 SoTrackballDragger *m = (SoTrackballDragger *) inDragger;
1087 SbMatrix motMat = m->getMotionMatrix();
1088
1089 SbVec3f trans, scale;
1090 SbRotation rot, scaleOrient;
1091 getTransformFast( motMat, trans, rot, scale, scaleOrient);
1092
1093 // Disconnect the field sensors
1094 m->rotFieldSensor->detach();
1095 m->scaleFieldSensor->detach();
1096
1097 if ( m->rotation.getValue() != rot )
1098 m->rotation = rot;
1099 if ( m->scaleFactor.getValue() != scale )
1100 m->scaleFactor = scale;
1101
1102 // Reconnect the field sensors
1103 m->rotFieldSensor->attach( &(m->rotation) );
1104 m->scaleFieldSensor->attach( &(m->scaleFactor) );
1105 }
1106
1107 void
1108 SoTrackballDragger::fieldSensorCB( void *inDragger, SoSensor * )
1109 {
1110 SoTrackballDragger *dragger = (SoTrackballDragger *) inDragger;
1111
1112 SbMatrix motMat = dragger->getMotionMatrix();
1113 dragger->workFieldsIntoTransform( motMat );
1114
1115 dragger->setMotionMatrix( motMat );
1116 }
1117
1118 void
1119 SoTrackballDragger::setDefaultOnNonWritingFields()
1120 {
1121 // These nodes may change after construction, but we still
1122 // don't want to write them out.
1123 surroundScale.setDefault(TRUE);
1124 antiSquish.setDefault(TRUE);
1125
1126 // If the userAxis is not being displayed, then do not write
1127 // out the userAxisRotation node.
1128 SoSwitch *sw = (SoSwitch *) userAxisSwitch.getValue();
1129 if ( sw == NULL || sw->whichChild.getValue() == SO_SWITCH_NONE ) {
1130 userAxisRotation.setDefault(TRUE);
1131 }
1132
1133 // Call the base class...
1134 SoDragger::setDefaultOnNonWritingFields();
1135 }