File: DisplayGraph.c++

package info (click to toggle)
inventor 2.1.5-10-21
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 36,312 kB
  • sloc: ansic: 33,864; lisp: 7,361; cpp: 3,874; yacc: 369; sh: 359; perl: 234; awk: 141; makefile: 81; csh: 35; sed: 11
file content (1084 lines) | stat: -rw-r--r-- 30,283 bytes parent folder | download | duplicates (9)
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
/*
 *
 *  Copyright (C) 2000 Silicon Graphics, Inc.  All Rights Reserved. 
 *
 *  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.
 *
 *  Further, this software is distributed without any warranty that it is
 *  free of the rightful claim of any third person regarding infringement
 *  or the like.  Any license provided herein, whether implied or
 *  otherwise, applies only to this software file.  Patent licenses, if
 *  any, provided herein do not apply to combinations of this program with
 *  other software, or any other product whatsoever.
 * 
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
 *  Mountain View, CA  94043, or:
 * 
 *  http://www.sgi.com 
 * 
 *  For further information regarding this notice, see: 
 * 
 *  http://oss.sgi.com/projects/GenInfo/NoticeExplan/
 *
 */

#include <stdlib.h>
#include <Inventor/SbBox.h>
#include <Inventor/SbDict.h>
#include <Inventor/SoDB.h>
#include <Inventor/SoInput.h>
#include <Inventor/SoPath.h>
#include <Inventor/SoType.h>
#include <Inventor/actions/SoSearchAction.h>
#include <Inventor/nodes/SoBaseColor.h>
#include <Inventor/nodes/SoCoordinate3.h>
#include <Inventor/nodes/SoCone.h>
#include <Inventor/nodes/SoCube.h>
#include <Inventor/nodes/SoDrawStyle.h>
#include <Inventor/nodes/SoGroup.h>
#include <Inventor/nodes/SoIndexedLineSet.h>
#include <Inventor/nodes/SoLabel.h>
#include <Inventor/nodes/SoLightModel.h>
#include <Inventor/nodes/SoLineSet.h>
#include <Inventor/nodes/SoPickStyle.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/nodes/SoSphere.h>
#include <Inventor/nodes/SoSwitch.h>

#include "GraphIcon.h"
#include "DisplayGraph.h"

SbBool	 DisplayGraph::initialized = FALSE;
SoNode	*DisplayGraph::instanceIcon;
SoNode	*DisplayGraph::closedIcon;
SoNode	*DisplayGraph::otherIcon;
SbDict	*DisplayGraph::iconDict;

#define ICON_FILE	"gviewIcons.iv"
#define ICON_INST_DIR	IVDEMODATADIR
#define ICON_ENV_VAR	"IV_GRAPH_DIR"

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Constructor - passed scene to view graph of, so it can count
//    nodes and set up correspondences. Also takes another
//    DisplayGraph (may be NULL) from which to copy info about icons.
//

DisplayGraph::DisplayGraph(SoNode *sceneGraph)
//
////////////////////////////////////////////////////////////////////////
{
    int	firstChildIndex;

    // Make sure icon stuff is initialized
    if (! initialized)
	init();

    // Count nodes in scene. nodeDict is used to detect instances
    numIcons = countNodes(sceneGraph);

    // Allocate array of GraphIcon instances to represent the nodes
    icons = new GraphIcon[numIcons];

    // Clear nodeDict, which will now be used to hold correspondences
    // to scene graph nodes to detect instances
    nodeDict.clear();

    // First node goes in index 0. First child of it goes in index 1.
    // The childIndex of the root is -1 to distinguish it from children.
    firstChildIndex = 1;
    setNode(sceneGraph, NULL, 0, firstChildIndex, -1);

    // Set up default spacing
    iconSpacing.setValue(1.0, 1.0);

    // Not showing any instance line
    instShown = FALSE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Destructor.
//

DisplayGraph::~DisplayGraph()
//
////////////////////////////////////////////////////////////////////////
{
    if (numIcons > 0)
	delete [] icons;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Initializes class.
//

void
DisplayGraph::init()
//
////////////////////////////////////////////////////////////////////////
{
    SoSeparator		*sep   = new SoSeparator;
    SoBaseColor		*color = new SoBaseColor;
    SoInput		in;
    SoNode		*inRoot, *parent;
    SoSearchAction	sa;
    const SoLabel	*label;
    SoType		type;
    int			i;

    // Build default closed icon graph
    sep   = new SoSeparator;
    color = new SoBaseColor;
    color->rgb.setValue(0.7, 0.2, 0.3);
    sep->addChild(color);
    sep->addChild(new SoCone);
    closedIcon = sep;

    // Build default instance icon graph
    sep   = new SoSeparator;
    color = new SoBaseColor;
    color->rgb.setValue(0.6, 0.6, 0.1);
    sep->addChild(color);
    sep->addChild(new SoSphere);
    instanceIcon = sep;

    // Build default unspecified node icon graph
    otherIcon = new SoCube;

    instanceIcon->ref();
    closedIcon->ref();
    otherIcon->ref();

    // Set up icon dictionary
    iconDict = new SbDict;

    // Insert icon for unspecific nodes. The casting is because C++
    // thinks the SoType is more than just an integer
    type = SoNode::getClassTypeId();
    iconDict->enter((unsigned long) * (int *) &type, (void *) otherIcon);

#if 0
    // Tell input to look for icon file based on environment variable
    // (before looking in current directory)
    in.addEnvDirectoriesFirst(ICON_ENV_VAR);

    // If it's not found in any of those, look in the standard
    // installed place
    in.addDirectoryLast(ICON_INST_DIR);

    // Open file containing icon graphs
    if (! in.openFile(ICON_FILE)) {
	fprintf(stderr, "Can't open %s\n", ICON_FILE);
	exit(1);
    }
#endif

#include "gviewIcons.iv.h"

    // Set to read from included char array
    in.setBuffer((void *) gviewIcons, sizeof(gviewIcons));

    // Read graph from file
    if (! SoDB::read(&in, inRoot)) {
	fprintf(stderr, "Error reading %s\n", ICON_FILE);
	exit(1);
    }
    inRoot->ref();

    // Search for all labels
    sa.setType(SoLabel::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.apply(inRoot);

    // For each label, store its parent node as the root of the icon
    // graph for the named node class
    for (i = 0; i < sa.getPaths().getLength(); i++) {
	label  = (const SoLabel *) sa.getPaths()[i]->getTail();
	parent = sa.getPaths()[i]->getNodeFromTail(1);

	// Find the type id for the named class
	type = SoType::fromName(label->label.getValue());

	// If such a type exists, add the parent to the dictionary
	if (! type.isBad()) {
	    iconDict->enter((unsigned long) * (int *) &type, (void *) parent);
	    parent->ref();
	}

	// Otherwise, it might be the icon for instances or closed groups
	else if (label->label.getValue() == "Instance") {
	    instanceIcon->unref();
	    instanceIcon = parent;
	    instanceIcon->ref();
	}
	else if (label->label.getValue() == "Closed") {
	    closedIcon->unref();
	    closedIcon = parent;
	    closedIcon->ref();
	}
    }

    inRoot->unref();

    GraphIcon::init();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Sets up correspondence between display graph icon and scene
//    graph node. Recurses to handle children. The second parameter is
//    the index of the graph icon to set. The third parameter is the
//    index into the "icons" array in which to put the first child of
//    the current icon. The fourth parameter is the index of this
//    child in its parent's list of children.
//

void
DisplayGraph::setNode(SoNode *node, GraphIcon *parentIcon,
		      int iconIndex, int &firstChildIndex, int childIndex)
//
////////////////////////////////////////////////////////////////////////
{
    GraphIcon	*icon = &icons[iconIndex];
    void	*oldIconPtr;

    icon->setNode(node);
    icon->setParent(parentIcon);
    icon->setChildIndex(childIndex);
    icon->setGraph(findIconGraph(node));

    // See if node was already counted - if so, it's an instance
    if (nodeDict.find((unsigned long) node, oldIconPtr))
	icon->setInstance((GraphIcon *) oldIconPtr);

    else {
	nodeDict.enter((unsigned long) node, (void *) icon);

	// If it's a group, recurse on children
	if (node->isOfType(SoGroup::getClassTypeId())) {
	    const SoGroup	*g = (const SoGroup *) node;
	    int			childIndex = firstChildIndex, i;

	    icon->setGroup(g->getNumChildren(), &icons[firstChildIndex]);

	    firstChildIndex += g->getNumChildren();

	    for (i = 0; i < g->getNumChildren(); i++)
		setNode(g->getChild(i), icon, childIndex + i,
			firstChildIndex, i);
	}
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Builds display graph. Returns root node. May be passed another
//    DisplayGraph from which to copy info about icons. (It is NULL
//    otherwise.)
//

SoNode *
DisplayGraph::build(DisplayGraph *oldDisplayGraph)
//
////////////////////////////////////////////////////////////////////////
{
    SoSeparator		*rootSep;	// Root for the display graph
    SoPickStyle		*pickStyle;	// Makes lines unpickable
    SoLightModel	*lightModel;	// To turn off lighting for lines
    SoDrawStyle		*drawStyle;	// To make lines wider
    SoLineSet		*instLine;	// Line to show instance connection
    SoBaseColor		*instColor;	// Color of instance connection line
    SoSeparator		*instSep;	// Sub-root for instance stuff
    SoNode		*iconGraph;
    int			i;

    rootSep = new SoSeparator(3 + numIcons);
    rootSep->ref();

    // Build subgraphs for all icons; add them to root. Also store
    // correspondence between GraphIcon and top node in icon graph in
    // dictionary. This lets us find the GraphIcon from a picked
    // geometry.
    for (i = 0; i < numIcons; i++) {
	iconGraph = icons[i].buildGraph();
	rootSep->addChild(iconGraph);
	shapeDict.enter((unsigned long) iconGraph, (void *) &icons[i]);
    }

    // Start out with just the first level of children visible
    if (icons[0].isGroup())
	icons[0].openGroup(FALSE);
    else
	icons[0].show();

    // If we are to copy visibility info from an old display graph, do so
    if (oldDisplayGraph != NULL) {
	int		i;
	GraphIcon	*newIcon, *oldIcon;
	void		*iconPtr;

	// Run through all icons in new display graph
	for (i = 0, newIcon = icons; i < numIcons; i++, newIcon++) {

	    // If there was an old icon for the node that this icon represents
	    if (oldDisplayGraph->nodeDict.find((unsigned long) newIcon->getNode(),
					       iconPtr)) {

		oldIcon = (GraphIcon *) iconPtr;

		// Change state of icon if necessary
		if (oldIcon->isGroup()) {
		    if (oldIcon->isOpen() && ! newIcon->isOpen())
			newIcon->openGroup(FALSE);
		    else if (oldIcon->isClosed() && ! newIcon->isClosed())
			newIcon->closeGroup();
		}
	    }
	}

	// If nodes had been deleted from the old display graph, the
	// state of the graph can be inconsistent. Clean it up.
	checkIconState(&icons[0], FALSE);
    }

    // Compute sizes and positions of icons
    icons[0].computeSize(iconSpacing);
    icons[0].computePosition(SbVec2f(0.0, 0.0), iconSpacing);

    // Lines are unpickable, unlit, and wide
    pickStyle = new SoPickStyle;
    pickStyle->style = SoPickStyle::UNPICKABLE;
    drawStyle = new SoDrawStyle;
    drawStyle->lineWidth = 2;
    lightModel = new SoLightModel;
    lightModel->model = SoLightModel::BASE_COLOR;
    rootSep->addChild(pickStyle);
    rootSep->addChild(drawStyle);
    rootSep->addChild(lightModel);

    // Build the stuff to represent the lines connecting icons
    coords  = new SoCoordinate3;
    lineSet = new SoIndexedLineSet;
    buildLines();
    rootSep->addChild(coords);
    rootSep->addChild(lineSet);

    // Build a line set to display instance connection
    instSwitch	= new SoSwitch;
    instSep	= new SoSeparator;
    instColor	= new SoBaseColor;
    instCoords	= new SoCoordinate3;
    instLine	= new SoLineSet;
    instColor->rgb.setValue(0.2, 0.2, 0.9);
    instSep->addChild(instColor);
    instSep->addChild(instCoords);
    instSep->addChild(instLine);
    instSwitch->addChild(instSep);
    rootSep->addChild(instSwitch);

    rootSep->unrefNoDelete();

    root = rootSep;

    return root;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Updates display graph when something changed in scene graph.
//

void
DisplayGraph::update()
//
////////////////////////////////////////////////////////////////////////
{
    // Compute sizes and positions of icons
    icons[0].computeSize(iconSpacing);
    icons[0].computePosition(SbVec2f(0.0, 0.0), iconSpacing);

    // Just rebuild the stuff to represent the connecting lines
    buildLines();

    // Make sure the instance line (if any) is ok
    if (instShown != NULL) {

	// Turn off line if either end is not visible
	if (! instShown->isVisible() ||
	    ! instShown->getInstance()->isVisible())
	    toggleInstance(instShown);

	// Otherwise, make sure coords are still correct
	else
	    setInstanceCoords();
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Returns icon corresponding to given selected path. We search up
//    the path from the bottom until we find a node that was entered
//    in the dictionary. If we find one, we return the corresponding
//    GraphIcon.
//

GraphIcon *
DisplayGraph::find(const SoPath *path)
//
////////////////////////////////////////////////////////////////////////
{
    void	*iconPtr;
    int		i;

    if (path == NULL)
	return NULL;

    // Check nodes from tail of path toward head
    for (i = path->getLength() - 1; i >= 0; --i)
	if (shapeDict.find((unsigned long) path->getNode(i), iconPtr))
	    return (GraphIcon *) iconPtr;

    // Not found
    return NULL;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Returns the icon that corresponds to the given path that starts
//    at the root of the scene graph this is an iconic version of.
//

GraphIcon *
DisplayGraph::findFromScenePath(const SoPath *path)
//
////////////////////////////////////////////////////////////////////////
{
    GraphIcon	*icon;
    int		i, index;
    SbBool	needUpdate = FALSE;

    // Trace the icons down to the correct one. On the way, make sure
    // the icon is visible: no closed groups or instances.

    icon = icons;

    if (icon->isClosed()) {
	icon->openGroup(FALSE);
	needUpdate = TRUE;
    }

    for (i = 1; i < path->getLength(); i++) {

	index = path->getIndex(i);

	if (! icon->isGroup() || index >= icon->getNumChildren()) {
	    fprintf(stderr, "Yipes! bad path in findFromScenePath()\n");
	    return icon;
	}

	icon = icon->getChild(index);

	// Last icon can be closed or an instance
	if (i < path->getLength() - 1) {
	    if (icon->isClosed()) {
		icon->openGroup(FALSE);
		needUpdate = TRUE;
	    }

	    else if (icon->isInstance()) {
		swapInstance(icon);
		needUpdate = TRUE;
	    }
	}
    }

    if (needUpdate)
	update();

    return icon;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Shows/hides what node an instance icon is an instance of.
//    Returns TRUE if graph needs to be rebuilt.
//

SbBool
DisplayGraph::toggleInstance(GraphIcon *icon)
//
////////////////////////////////////////////////////////////////////////
{
    // If there already is an instance showing and it is this icon,
    // just turn it off
    if (instShown == icon) {
	instSwitch->whichChild = SO_SWITCH_NONE;
	instShown = NULL;
	return TRUE;
    }

    // Find node this icon is an instance of
    GraphIcon	*instanceOf = icon->getInstance();

    // Make sure that node is visible
    if (! instanceOf->isVisible()) {
	makeIconVisible(instanceOf);
	// Recompute positions and all
	update();
    }

    // Save the pointer for later
    instShown = icon;

    // Set instance line to join the center of the two icons
    setInstanceCoords();

    // Turn the line on by setting the switch
    instSwitch->whichChild = 0;

    return TRUE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Swaps instance icon with icon it is an instance of. This allows
//    selection under an instance of a group.
//

void
DisplayGraph::swapInstance(GraphIcon *instanceIcon)
//
////////////////////////////////////////////////////////////////////////
{
    GraphIcon	*instanceOf, *icon;
    int		i;

    instanceOf = instanceIcon->getInstance();

    // Make sure the instance line is still valid, if present
    if (instShown == instanceIcon)
	instShown = instanceIcon->getInstance();

    // Swap the icon stuff
    instanceIcon->swapInstance();

    // If any other icons were instances of the other icon, make them
    // instances of the given icon
    for (i = 0, icon = icons; i < numIcons; i++, icon++)
	if (icon->getInstance() == instanceOf)
	    icon->setInstance(instanceIcon);

    // Recompute positions and all
    update();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Returns a path from the given root of the graph to the given
//    graph icon's root. The path is ref'ed.
//

SoPath *
DisplayGraph::findPathToIcon(SoNode *root, GraphIcon *icon)
//
////////////////////////////////////////////////////////////////////////
{
    SoSearchAction	sa;
    SoPath		*path;

    // This may be called with a NULL icon pointer.
    if (icon == NULL)
	return NULL;

    sa.setNode(icon->getIconRoot());
    sa.setInterest(SoSearchAction::FIRST);
    sa.apply(root);

    // Ref the path so it won't go away
    path = sa.getPath();

    if (path == NULL) {
	fprintf(stderr, "Yow! Can't find path to node!\n");
	return NULL;
    }

    path->ref();

    return path;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    This is used by selection pasting to determine where to draw the
//    feedback icon and where in the graph to insert the selection. It
//    returns TRUE if it was able to find a good place to paste. The
//    parentIcon parameter returns the parent under which to paste,
//    and the childIndex parameter returns the index of the child that
//    the pasted selection will become. The xFeedback and yFeedback
//    parameters indicate where the feedback should be centered.
//

SbBool
DisplayGraph::getPasteLocation(float x, float y,
			       GraphIcon *&parentIcon, int &childIndex, 
			       float &xFeedback, float &yFeedback)
//
////////////////////////////////////////////////////////////////////////
{
// X coordinate of feedback to right of given icon
#define NEXT_X_RIGHT(rightIcon)						      \
	(rightIcon->getPosition()[0] +					      \
	 .5 * (rightIcon->getSubgraphSize()[0] + iconSpacing[0]))

// X coordinate of feedback to left of given icon
#define NEXT_X_LEFT(leftIcon)						      \
	(leftIcon->getPosition()[0] -					      \
	 .5 * (leftIcon->getSubgraphSize()[0] + iconSpacing[0]))

// X coordinate of feedback between given icons
#define X_BETWEEN(leftIcon, rightIcon)					      \
	(.5 * (leftIcon->getPosition()[0] + rightIcon->getPosition()[0]))

// Y coordinate of feedback to left or right of given icon
#define NEXT_Y(icon)	(icon->getPosition()[1] - .5 * icon->getSize()[1])

    GraphIcon	*icon, *nextChild, *lastChild;
    SbVec2f	point(x, y);
    float	xPos, yPos, xSize, ySize;
    float	xl, xr, xFudge, yb, yt;
    SbBox2f	iconBox;
    int		index, i;

    for (i = 0, icon = icons; i < numIcons; i++, icon++) {

	if (! icon->isVisible())
	    continue;

	// Find the extent of the icon bounding box
	icon->getPosition(xPos, yPos);
	icon->getSize(xSize, ySize);
	xl = xPos - .5 * xSize;
	xr = xPos + .5 * xSize;
	yb = yPos - ySize;
	yt = yPos;
	iconBox.setBounds(xl, yb, xr, yt);

	//------------------------------------------------------------------
	// The point is on the icon
	//------------------------------------------------------------------

	if (iconBox.intersect(point)) {

	    // See if it's a group
	    if (icon->isGroup()) {

		parentIcon = icon;

		// If group has no children, draw feedback below icon
		if (icon->getNumChildren() == 0) {
		    childIndex = 0;
		    xFeedback = xPos;
		    yFeedback = yb - iconSpacing[1];
		    return TRUE;
		}

		// If open group, draw feedback to right of last child
		else if (icon->isOpen()) {
		    childIndex = icon->getNumChildren();
		    lastChild = icon->getChild(childIndex - 1);
		    xFeedback = NEXT_X_RIGHT(lastChild);
		    yFeedback = NEXT_Y(lastChild);
		}

		// If closed group, draw feedback below icon
		else {
		    childIndex = icon->getNumChildren();
		    xFeedback = xPos;
		    yFeedback = yb - iconSpacing[1];
		}

		return TRUE;
	    }

	    // If non-group, draw feedback halfway to next sibling (if
	    // any) to right or left, depending on whether the cursor
	    // is to the right or left of the center of the icon
	    else {
		parentIcon = icon->getParent();
		index = icon->getChildIndex();

		// Cursor is on left side
		if (x < xPos) {
		    childIndex = index;

		    if (index == 0)
			xFeedback = NEXT_X_LEFT(icon);
		    else {
			nextChild = parentIcon->getChild(index - 1);
			xFeedback = X_BETWEEN(nextChild, icon);
		    }
		}

		// Cursor is on right side
		else {
		    childIndex = index + 1;

		    if (index == parentIcon->getNumChildren() - 1)
			xFeedback = NEXT_X_RIGHT(icon);
		    else {
			nextChild = parentIcon->getChild(index + 1);
			xFeedback = X_BETWEEN(icon, nextChild);
		    }
		}

		yFeedback = yPos - .5 * ySize;

		return TRUE;
	    }
	}

	//------------------------------------------------------------------
	// The point is NOT on the icon, but it may be close enuf to one side
	//------------------------------------------------------------------

	if ((parentIcon = icon->getParent()) != NULL) {
	    index = icon->getChildIndex();

	    // If this is the first child of a group, see if the point
	    // is close enough to its left
	    if (index == 0)
		xFudge = 0.5 * icon->getSubgraphSize()[0] + iconSpacing[0];

	    // Otherwise, see if the point is between it and the next
	    // icon to the left
	    else {
		nextChild = parentIcon->getChild(index - 1);
		xFudge = xPos - nextChild->getPosition()[0];
	    }

	    iconBox.setBounds(xPos - xFudge, yb, xl, yt);

	    if (iconBox.intersect(point)) {
		childIndex = index;
		if (index == 0)
		    xFeedback = NEXT_X_LEFT(icon);
		else
		    xFeedback = X_BETWEEN(icon, nextChild);
		yFeedback = yPos - .5 * ySize;
		return TRUE;
	    }

	    // If this is the last child of a group, see if the point
	    // is close enough to its right
	    if (index == parentIcon->getNumChildren() - 1) {
		xFudge = 0.5 * (icon->getSubgraphSize()[0] + iconSpacing[0]);

		iconBox.setBounds(xr, yb, xPos + xFudge, yt);

		if (iconBox.intersect(point)) {
		    childIndex = index + 1;
		    xFeedback = xPos + xFudge;
		    yFeedback = yPos - .5 * ySize;
		    return TRUE;
		}
	    }
	}

	//------------------------------------------------------------------
	// Now see if it is below a closed or childless group icon
	//------------------------------------------------------------------

	// See if the point is close below a closed or childless group
	if (icon->isGroup() &&
	    (icon->isClosed() || icon->getNumChildren() == 0)) {

	    iconBox.setBounds(xl, yb - iconSpacing[1], xr, yb);

	    if (iconBox.intersect(point)) {
		parentIcon = icon;
		childIndex = icon->getNumChildren();
		xFeedback = xPos;
		yFeedback = yb - iconSpacing[1];

		return TRUE;
	    }
	}
    }

    //------------------------------------------------------------------
    // None of the above...
    //------------------------------------------------------------------

    return FALSE;
}

#undef NEXT_X_RIGHT
#undef NEXT_X_LEFT
#undef X_BETWEEN
#undef NEXT_Y

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Counts nodes in subgraph rooted by node
//

int
DisplayGraph::countNodes(const SoNode *root)
//
////////////////////////////////////////////////////////////////////////
{
    int	num = 1;

    // See if node was already counted - if so, it's an instance
    if (! nodeDict.enter((unsigned long) root, (void *) 1))
	;

    // Count children if this node is a group
    else if (root->isOfType(SoGroup::getClassTypeId())) {
	const SoGroup	*g = (const SoGroup *) root;
	int		i;

	for (i = 0; i < g->getNumChildren(); i++)
	    num += countNodes(g->getChild(i));
    }

    return num;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Makes sure state of icons rooted by given icon is consistent.
//

void
DisplayGraph::checkIconState(GraphIcon *root, SbBool shouldBeHidden)
//
////////////////////////////////////////////////////////////////////////
{
    if (shouldBeHidden && root->isVisible())
	root->hide();

    // Hide children if necessary
    if (root->isGroup()) {

	if (! shouldBeHidden && root->isClosed())
	    shouldBeHidden = TRUE;

	for (int i = 0; i < root->getNumChildren(); i++)
	    checkIconState(root->getChild(i), shouldBeHidden);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Sets up the coordinate3 and lineset nodes to display connecting
//    lines between icons.
//

void
DisplayGraph::buildLines()
//
////////////////////////////////////////////////////////////////////////
{
    int			numVisible, numLines, i, j, c;
    SbVec3f		*pts;
    int32_t		*inds;
    GraphIcon		*icon;
    float		hy, yBar, x, y, sx, sy, cx1, cy1, cx2, cy2;

    // Count non-hidden icons
    numVisible = 0;
    for (i = 0; i < numIcons; i++)
	if (icons[i].isVisible())
	    numVisible++;

    // All nodes except the root have 1 line above them
    numLines = numVisible - 1;

    // All open groups with > 1 children have 2 lines below them
    for (i = 0; i < numIcons; i++)
	if (icons[i].isGroup() &&
	    icons[i].getNumChildren() > 1 &&
	    icons[i].isOpen())
	    numLines += 2;

    // No groups? We're done!
    if (numLines <= 0) {
	lineSet->coordIndex.deleteValues(0);
	return;
    }

    hy   = iconSpacing[1] / 2.0;
    pts  = new SbVec3f[numLines * 2];
    inds = new int32_t[numLines * 3];

    // Fill in coordinates
    for (i = c = 0, icon = icons; i < numIcons; i++, icon++) {

	icon->getPosition(x, y);
	icon->getSize(sx, sy);

	if (icons[i].isGroup() &&
	    icons[i].getNumChildren() > 1 &&
	    icons[i].isOpen()) {

	    yBar = y - sy - hy;

	    // Line from top icon down
	    pts[c+0].setValue(x, yBar + hy, 0.0);
	    pts[c+1].setValue(x, yBar, 0.0);

	    // Horizontal bar
	    icon->getChild(0)->getPosition(cx1, cy1);
	    icon->getChild(icon->getNumChildren() - 1)->getPosition(cx2, cy2);
	    pts[c+2].setValue(cx1, yBar, 0.0);
	    pts[c+3].setValue(cx2, yBar, 0.0);
	    c += 4;

	    for (j = 0; j < icons[i].getNumChildren(); j++) {
		icon->getChild(j)->getPosition(cx1, cy1);
		pts[c+0].setValue(cx1, yBar, 0.0);
		pts[c+1].setValue(cx1, cy1, 0.0);
		c += 2;
	    }
	}
	else if (icons[i].isGroup() &&
		 icons[i].getNumChildren() == 1 &&
		 icons[i].isOpen()) {
	    // Line from top icon down to child
	    icon->getChild(0)->getPosition(cx1, cy1);
	    pts[c+0].setValue(x, y - sy, 0.0);
	    pts[c+1].setValue(cx1, cy1, 0.0);
	    c += 2;
	}
    }

    // Fill in indices
    c = 0;
    for (i = 0; i < numLines; i++) {
	inds[c+0] = i * 2;
	inds[c+1] = i * 2 + 1;
	inds[c+2] = SO_END_LINE_INDEX;
	c += 3;
    }

    coords->point.setValues(0, numLines * 2, pts);
    lineSet->coordIndex.setValues(0, numLines * 3, inds);

    // Delete old values if not needed any more
    if (lineSet->coordIndex.getNum() > numLines * 3)
	lineSet->coordIndex.deleteValues(numLines * 3);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Makes sure the given icon is visible.
//

void
DisplayGraph::makeIconVisible(GraphIcon *icon)
//
////////////////////////////////////////////////////////////////////////
{
    // Could this be called on the root? I think not! It's always visible!
    if (icon->getParent() == NULL)
	return;

    // Make sure parent is visible
    if (! icon->getParent()->isVisible())
	makeIconVisible(icon->getParent());

    // Make sure parent is open
    icon->getParent()->openGroup(FALSE);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Sets instCoords so that line between current instance and what
//    is an instance of will be drawn correctly.
//

void
DisplayGraph::setInstanceCoords()
//
////////////////////////////////////////////////////////////////////////
{
    // Find node the shown instance icon is an instance of
    GraphIcon	*instanceOf = instShown->getInstance();

    // Set instance line to join the center of the two icons
    float	x1, y1, x2, y2;
    float	sx1, sy1, sx2, sy2;
    instShown->getPosition(x1, y1);
    instShown->getSize(sx1, sy1);
    instanceOf->getPosition(x2, y2);
    instanceOf->getSize(sx2, sy2);
    // Line connects to center of icons
    y1 -= sy1 / 2.0;
    y2 -= sy2 / 2.0;
    instCoords->point.set1Value(0, x1, y1, 0.0);
    instCoords->point.set1Value(1, x1 + .2 * (x2-x1), y1 + .2 * (y2-y1), 3.0);
    instCoords->point.set1Value(2, x1 + .8 * (x2-x1), y1 + .8 * (y2-y1), 3.0);
    instCoords->point.set1Value(3, x2, y2, 0.0);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Finds the icon graph to use for the given node.
//

SoNode *
DisplayGraph::findIconGraph(SoNode *node)
//
////////////////////////////////////////////////////////////////////////
{
    // Look in dictionary for icon for this node class. If not found,
    // check parent class. Repeat until an icon is found. Since SoNode
    // always has a valid icon, this loop will always terminate
    // successfully.

    SoType	type;
    void	*graphPtr;

    type = node->getTypeId();

    while (TRUE) {
	if (iconDict->find((unsigned long) * (int *) &type, graphPtr))
	    return (SoNode *) graphPtr;

	type = type.getParent();
    }
}