-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNGonDisplayControl.xaml.cs
1253 lines (1055 loc) · 51.6 KB
/
NGonDisplayControl.xaml.cs
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
namespace Demo
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
//BUGBUG: Doesn't handle a large number of UIElements very efficeintly ;) Tried placing 500 buttons in it, real slow to do
//layout caclculations and the rotations make it hard to tell it is 3d since the exterior angle between faces is very
//close to 180 degrees
//
//BUGBUG: Doesn't allow users to style the items in the controls in any special manner, could imagine displaying some border
//around the item or header above/below it.
//
//BUGBUG: Doesn't handle variable sized content at all, since things are always in a Viewport3D (right now) they will
//always fill the Viewport area, so smaller items will be streched and larger items will be shrunk.
[ContentPropertyAttribute("Items")]
public partial class NGonDisplayControl : ContentControl, INotifyPropertyChanged
{
#region Private Fields
private bool viewportNeedsReset;
private static readonly Vector3D xAxisVector = new Vector3D(1.0, 0.0, 0.0);
private static readonly Vector3D yAxisVector = new Vector3D(0.0, 1.0, 0.0);
private Point3D[] vertexPoints;
private bool[] calculatedFaces;
private bool canRotateForward;
private bool canRotateBack;
private bool lightsAdded;
//stores the information to ensure our camera looks right when positioned looking at an arbitrary face, recalculated
//when the numbers of faces changes
private Point3D cameraPosition;
private Vector3D cameraUpDirection;
private Vector3D faceNormal;
private QuaternionRotation3D cameraAngleRotation;
private ScaleTransform3D cameraScaleTransform;
private Transform3DGroup cameraTransformGroup;
//Debugging aid, allows a rendering of all the items in our control since we can only see one at a time in the
//actual control
private ObservableCollection<VisualBrush> brushes = new ObservableCollection<VisualBrush>();
private ObservableCollection<string> debuggingInfo = new ObservableCollection<string>();
private Viewport3D viewport3D;
private PerspectiveCamera viewportCamera;
private int currentFaceIndex = 0;
#endregion
#region Dependency Properties
/// <summary>
/// Property that controls the amount of margin applied to each face of the N-Gon, this allows for gaps between each side to allow the user to see through to items along
/// the edge farthest from the camera.
/// </summary>
public static readonly DependencyProperty FaceMarginProperty = DependencyProperty.Register("FaceMargin",
typeof(double),
typeof(NGonDisplayControl),
new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.None, HandleFaceMarginChanged));
/// <summary>
/// Property for the item currently being displayed in the 2d content controls Content area.
/// </summary>
public static readonly DependencyProperty CurrentItemProperty = DependencyProperty.Register("CurrentItem",
typeof(UIElement),
typeof(NGonDisplayControl),
new FrameworkPropertyMetadata(HandleCurrentItemPropertyChanged));
/// <summary>
/// Property that controls how long the zoom in/out effect takes when doing the face transition animations.
/// </summary>
public static readonly DependencyProperty ZoomAnimationTimeProperty = DependencyProperty.Register("ZoomAnimationTime",
typeof(TimeSpan),
typeof(NGonDisplayControl),
new FrameworkPropertyMetadata(TimeSpan.FromMilliseconds(250)));
/// <summary>
/// Property that controls how long the rotation between current and target face on the N-Gon takes.
/// </summary>
public static readonly DependencyProperty RotationAnimationTimeProperty = DependencyProperty.Register("RotationAnimationTime",
typeof(TimeSpan),
typeof(NGonDisplayControl),
new FrameworkPropertyMetadata(TimeSpan.FromMilliseconds(350)));
/// <summary>
/// Property that contains the lights for the 3d viewport to affect the display of items during the 3d transitions.
/// </summary>
public static readonly DependencyProperty ViewPortLightsProperty = DependencyProperty.Register("ViewPortLights",
typeof(IEnumerable<Light>),
typeof(NGonDisplayControl),
new FrameworkPropertyMetadata(CreateDefaultLights(), FrameworkPropertyMetadataOptions.None, HandleLightCollectionChanged));
/// <summary>
/// Property which holds the items to display on each of face of the N-Gon.
/// </summary>
public static readonly DependencyProperty ItemsProperty = DependencyProperty.RegisterAttached("Items",
typeof(ICollection<UIElement>),
typeof(NGonDisplayControl),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, HandleItemsPropertyChanged));
/// <summary>
/// Property that controls whether the N-Gon is vertically or horizontally aligned (affects whether it rotates left <-> right (horizontally aligned) or top <-> Bottom (vertically aligned).
/// </summary>
public static readonly DependencyProperty OrientationProperty = StackPanel.OrientationProperty.AddOwner(typeof(NGonDisplayControl),
new FrameworkPropertyMetadata(Orientation.Horizontal, HandleOrientationChanged));
#endregion
#region Constructor
public NGonDisplayControl()
{
this.cameraTransformGroup = new Transform3DGroup();
//used for zoom effects
this.cameraScaleTransform = new ScaleTransform3D(1.0, 1.0, 1.0);
this.cameraTransformGroup.Children.Add(this.cameraScaleTransform);
//used for rotation effects
this.cameraAngleRotation = new QuaternionRotation3D();
this.cameraTransformGroup.Children.Add(new RotateTransform3D(this.cameraAngleRotation));
InitializeComponent();
PerspectiveCamera camera = new PerspectiveCamera();
//Initially positioned at +3 the Z-axis looking towards the 'front' face of the N-Gon.
camera.Position = new Point3D(0.0, 0.0, 3.0);
//Looking down the Z-axis.
camera.LookDirection = new Vector3D(0.0, 0.0, -1.0);
camera.FieldOfView = 60.0;
//Which way is up :)
camera.UpDirection = yAxisVector;
ViewportCamera = camera;
//Register our camera so that animations can locate it by name.
NameScope.GetNameScope(this).RegisterName("viewportCamera", ViewportCamera);
//Assign our transform group to our camera and mark our viewport as needing a reset so the first time we try to animate the N-Gon (and thus
//need our 3d view, we will set it up).
this.viewportCamera.Transform = this.cameraTransformGroup;
this.viewportNeedsReset = true;
}
#endregion
#region Public Properties
/// <summary>
/// Allows for adding some empty space where the n-gon faces meet, default value is 0.0. Since the n-gon
/// is laid out inside a unit circle values for this property likely lie in the range [0.0,1.0].
/// </summary>
public double FaceMargin
{
get
{
return (double)GetValue(NGonDisplayControl.FaceMarginProperty);
}
set
{
SetValue(NGonDisplayControl.FaceMarginProperty, value);
}
}
/// <summary>
/// Exposes the <see cref="UIElement"/> which is currently being displayed to the user.
/// </summary>
public UIElement CurrentItem
{
get
{
return (UIElement)GetValue(NGonDisplayControl.CurrentItemProperty);
}
set
{
SetValue(NGonDisplayControl.CurrentItemProperty, value);
}
}
/// <summary>
/// The collection of <see cref="Light"/> objects used to illuminate the viewport the NGonDisplayControl
/// resides in.
/// </summary>
public IEnumerable<Light> ViewPortLights
{
get
{
return (IEnumerable<Light>)GetValue(NGonDisplayControl.ViewPortLightsProperty);
}
set
{
SetValue(NGonDisplayControl.ViewPortLightsProperty, value);
}
}
/// <summary>
/// The orientation of the NGonDisplayControl. <see cref="Orientation.Horizontal"/> means that <see cref="UIElement">s</see> will be
/// arranged circling the y-axis and displayed horizontally. <see cref="Orientation.Vertical"/> means that <see cref="UIElement">s</see>
/// will be arrange circling the x-axis and displayed vertically.
/// </summary>
public Orientation Orientation
{
get
{
return (Orientation)GetValue(NGonDisplayControl.OrientationProperty);
}
set
{
SetValue(NGonDisplayControl.OrientationProperty, value);
}
}
/// <summary>
/// Exposes the <see cref="TimeSpan"/> which represents the time the Zoom in and Zoom out animations should take to complete.
/// </summary>
public TimeSpan ZoomAnimationTime
{
get
{
return (TimeSpan)GetValue(NGonDisplayControl.ZoomAnimationTimeProperty);
}
set
{
SetValue(NGonDisplayControl.ZoomAnimationTimeProperty, value);
}
}
/// <summary>
/// Exposes the <see cref="TimeSpan"/> which represents the time the rotation animation should take to compelte.
/// </summary>
public TimeSpan RotationAnimationTime
{
get
{
return (TimeSpan)GetValue(NGonDisplayControl.RotationAnimationTimeProperty);
}
set
{
SetValue(NGonDisplayControl.RotationAnimationTimeProperty, value);
}
}
/// <summary>
/// Exposes the <see cref="ICollection{T}"/> of <see cref="UIElement">s</see> that the control is currently hosting.
/// </summary>
public ICollection<UIElement> Items
{
get
{
return (ICollection<UIElement>)GetValue(NGonDisplayControl.ItemsProperty);
}
set
{
SetValue(NGonDisplayControl.ItemsProperty, value);
}
}
/// <summary>
/// Determines whether the control can rotate forward or not. Currently this is only false while animations are occuring, when we have
/// no items (silly scenario), or when we have a single item (also a silly scenario).
/// </summary>
public bool CanRotateForward
{
get
{
return this.canRotateForward && (Items != null && Items.Count > 1);
}
internal set
{
this.canRotateForward = value;
RaisePropertyChanged("CanRotateForward");
}
}
/// <summary>
/// Determines whether the control can rotate backwards or not. Currently this is only false while animations are occuring, when we have
/// no items (silly scenario) or when we only have a single item (also a silly scenario).
/// </summary>
public bool CanRotateBack
{
get
{
return this.canRotateBack && (Items != null && Items.Count > 1);
}
internal set
{
this.canRotateBack = value;
RaisePropertyChanged("CanRotateBack");
}
}
#endregion
#region Public Methods
/// <summary>
/// Animates from the currently displayed item to the next item in the items collection. If <see cref="CanRotateForward"/> is returning
/// <c>false</c> when this is called this method will do nothing.
/// </summary>
public void MoveNext()
{
if (CanRotateForward)
{
if (this.viewportNeedsReset)
{
//Our viewport is dirty/uninitialized, so lets set it up now since we are about to use it.
ResetViewport();
InitializeViewport();
this.viewportNeedsReset = false;
}
//if face margin is > 0.0 then we will be able to see faces on the opposite side of the n-gon through the cracks.
//in this case to maintain a correct look we need to ensure all faces have been created, otherwise we only need to
//ensure the items along the path of rotation have been created.
if (FaceMargin > 0.0)
{
EnsurePathCalculated(Items.Count /*rotationCount*/ , RotationDirection.Forward /*rotationDirection*/ );
}
else
{
EnsurePathCalculated(1/*rotationCount*/, RotationDirection.Forward /*rotationDirection*/);
}
this.currentFaceIndex = AdjustIndex(this.currentFaceIndex, RotationDirection.Forward);
ApplyCameraAnimations(1 /*rotation multiplier*/, 1 /*rotation count*/);
}
}
/// <summary>
/// Animates from the currently displayed item to the next item in the items collection. If <see cref="CanRotateBackwards"/> is returning
/// <c>false</c> when this is called this method will do nothing.
/// </summary>
public void MovePrevious()
{
if (CanRotateBack)
{
if (this.viewportNeedsReset)
{
//Our viewport is dirty/uninitialized, so lets set it up now since we are about to use it.
ResetViewport();
InitializeViewport();
this.viewportNeedsReset = false;
}
//if face margin is > 0.0 then we will be able to see faces on the opposite side of the n-gon through the cracks.
//in this case to maintain a correct look we need to ensure all faces have been created, otherwise we only need to
//ensure the items along the path of rotation have been created.
if (FaceMargin > 0.0)
{
EnsurePathCalculated(Items.Count /*rotationCount*/, RotationDirection.Backwards /*rotationDirection*/);
}
else
{
EnsurePathCalculated(1 /*rotationCount*/, RotationDirection.Backwards /*rotationDirection*/);
}
this.currentFaceIndex = AdjustIndex(this.currentFaceIndex, RotationDirection.Backwards);
ApplyCameraAnimations(-1 /*rotation multiplier*/, 1 /*rotation count*/);
}
}
/// <summary>
/// Animates from the currently displayed item to the item with the given identifier. If no items with the given identifier exist or
/// the shortest rotation path (forward/back) has its associated CanRotateX property return <c>false</c> this method will do nothing.
/// </summary>
public void MoveTo(string itemIdentifier)
{
if (itemIdentifier == null)
{
throw new ArgumentNullException("itemIdentifier");
}
if (Items != null)
{
UIElement item = Items.FirstOrDefault((i) => (string)i.GetValue(FrameworkElement.NameProperty) == itemIdentifier);
if (item != null)
{
MoveTo(item);
return;
}
Debug.WriteLine(String.Format("Request to rotate to face with id '{0}' failed. No face with id '{0}' was found.", itemIdentifier));
}
}
/// <summary>
/// Animates from the currently displayed item to the given <see cref="UIElement"/> in the Items collection. If the given <see cref="UIElement"/>
/// is not found or the shortest rotation path (forward/back) our CanRotate(Forward/Back) property returns <c>false</c> this method will do nothing.
/// </summary>
private void MoveTo(UIElement item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (Items != null)
{
int currentPosition = this.currentFaceIndex;
//BUGBUG: A few places I need a List so I can index the collection, should either make the DP of type IList
//or maintain a synchronized local copy of the DP provided ICollection
List<UIElement> collection = new List<UIElement>(Items);
//guard against doing any work in the degenerative do nothing case
if (collection[currentPosition] != item)
{
int newFaceIndex = -1;
int angleMultiplier;
int rotationCount;
//step 1 from our current position check the length of rotating forward through the items collection
//and backwards
int forwardRotationCount = 0;
int backwardsRotationCount = 0;
for (int i = ((currentPosition != collection.Count - 1) ? (currentPosition + 1) : 0); i != currentPosition; )
{
forwardRotationCount++;
if (collection[i] == item)
{
newFaceIndex = i;
if ((forwardRotationCount + this.currentFaceIndex) >= Items.Count)
{
backwardsRotationCount = this.currentFaceIndex - newFaceIndex;
}
else
{
backwardsRotationCount = (Items.Count - newFaceIndex) + this.currentFaceIndex;
}
break;
}
i = AdjustIndex(i, RotationDirection.Forward);
}
if (newFaceIndex != -1)
{
if (this.viewportNeedsReset)
{
ResetViewport();
InitializeViewport();
this.viewportNeedsReset = false;
}
//step 2: pick the shorter of the two paths and set the proper angle multiplier and number of rotations
//we need to do to get to our target and ensure we are in a rotateable state
if (forwardRotationCount <= backwardsRotationCount)
{
if (!CanRotateForward)
{
return;
}
angleMultiplier = 1;
rotationCount = forwardRotationCount;
}
else
{
if (!CanRotateBack)
{
return;
}
angleMultiplier = -1;
rotationCount = backwardsRotationCount;
}
if (FaceMargin > 0.0)
{
EnsurePathCalculated(Items.Count /*rotationCount*/, (RotationDirection)angleMultiplier /*rotationDirection*/);
}
else
{
EnsurePathCalculated(rotationCount /*rotationCount*/, (RotationDirection)angleMultiplier /*rotationDirection*/);
}
//step 3: change our face index to our destination and apply the animations to get us there
this.currentFaceIndex = newFaceIndex;
ApplyCameraAnimations(angleMultiplier, rotationCount);
}
else
{
string propertyIdentifier = "name";
string itemIdentifier = (string)item.GetValue(FrameworkElement.NameProperty);
if (itemIdentifier == null)
{
propertyIdentifier = "hashcode";
itemIdentifier = item.GetHashCode().ToString();
}
Debug.WriteLine(String.Format("Request to rotate to face with {0} '{1}' failed. No face with {0} '{1}' was found.", propertyIdentifier, itemIdentifier));
}
}
}
}
#endregion
#region Overridden Methods
//since our mesh size/camera placement is dependent on the render size of our viewport we need to recalculate when that changes
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
this.viewportNeedsReset = true;
}
#endregion
#region Private Helpers
#region DependencyPropertyChanged Handlers
/// <summary>
/// DependencyPropertyChanged callback. This alerts me when my <see cref="IEnumerable{T}"/> of <see cref="Light">s</see>
/// that I am using has been replaced.
/// </summary>
private static void HandleLightCollectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((NGonDisplayControl)sender).HandleLightCollectionChanged(args);
}
/// <summary>
/// Instance version that the static DependencyPropertyChanged callback thunks into.
/// </summary>
private void HandleLightCollectionChanged(DependencyPropertyChangedEventArgs args)
{
if (args.OldValue != null)
{
INotifyCollectionChanged oldCollection = args.OldValue as INotifyCollectionChanged;
if (oldCollection != null)
{
oldCollection.CollectionChanged -= HandleLightCollectionChanged;
}
}
RemoveLights();
if (args.NewValue != null)
{
INotifyCollectionChanged newCollection = args.NewValue as INotifyCollectionChanged;
if (newCollection != null)
{
newCollection.CollectionChanged += HandleLightCollectionChanged;
}
AddLights();
}
}
/// <summary>
/// DependencyPropertyChanged callback. This alerts me when the control's <see cref="CurrentItem"/> property has changed.
/// </summary>
private static void HandleCurrentItemPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((NGonDisplayControl)sender).HandleCurrentItemPropertyChanged(args);
}
/// <summary>
/// Instance version that the static DependencyPropertyChanged callback thunks into.
/// </summary>
private void HandleCurrentItemPropertyChanged(DependencyPropertyChangedEventArgs args)
{
UIElement item = (UIElement)args.NewValue;
if (item != null)
{
MoveTo(item);
}
}
/// <summary>
/// DependencyPropertyChanged callback. This alerts me when my <see cref="ICollection{T}"/> of <see cref="UIElement">s</see>
/// that I am hosting has been replaced.
/// </summary>
private static void HandleItemsPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((NGonDisplayControl)sender).HandleItemsPropertyChanged(args);
}
/// <summary>
/// Instance version that the static DependencyPropertyChanged callback thunks into.
/// </summary>
private void HandleItemsPropertyChanged(DependencyPropertyChangedEventArgs args)
{
if (args.OldValue != null)
{
INotifyCollectionChanged oldCollection = args.OldValue as INotifyCollectionChanged;
if (oldCollection != null)
{
oldCollection.CollectionChanged -= HandleItemsCollectionChanged;
}
}
this.viewportNeedsReset = true;
if (args.NewValue != null)
{
INotifyCollectionChanged newCollection = args.NewValue as INotifyCollectionChanged;
if (newCollection != null)
{
newCollection.CollectionChanged += HandleItemsCollectionChanged;
}
if (this.currentFaceIndex >= Items.Count)
{
this.currentFaceIndex = Items.Count - 1;
}
if (args.NewValue != null)
{
if (Items.Count != 0)
{
List<UIElement> indexableList = new List<UIElement>(Items);
Content = CurrentItem = indexableList[this.currentFaceIndex];
CanRotateForward = CanRotateBack = (Items.Count > 1);
}
}
else
{
Content = null;
}
}
else
{
CanRotateForward = CanRotateBack = false;
}
}
/// <summary>
/// DependencyPropertyChanged callback. This alerts me when the <see cref="Orientation"/> in which I am
/// laying out my hosted <see cref="UIElement">s</see> has changed.
/// </summary>
private static void HandleOrientationChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((NGonDisplayControl)sender).HandleOrientationChanged(args);
}
/// <summary>
/// Instance version that the static DependencyPropertyChanged callback thunks into.
/// </summary>
private void HandleOrientationChanged(DependencyPropertyChangedEventArgs args)
{
ResetBrushOpacity();
this.debuggingInfo.Add(String.Format("Orientation changed to '{0}', throwing away cached face models.", Orientation.ToString()));
this.viewportNeedsReset = true;
}
/// <summary>
/// DependencyPropertyChanged callback. This alerts me when the face margin value has changed.
/// </summary>
private static void HandleFaceMarginChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((NGonDisplayControl)sender).HandleFaceMarginChanged(args);
}
/// <summary>
/// Instance version that the static DependencyPropertyChanged callback thunks into.
/// </summary>
private void HandleFaceMarginChanged(DependencyPropertyChangedEventArgs args)
{
ResetBrushOpacity();
this.viewportNeedsReset = true;
}
#endregion
#region Private Properties
#region Debugging Aids
/// <summary>
/// The collection of <see cref="VisualBrush"/> objects representing the elements the control is hosting. This mainly used to be able to
/// display all the elements the control is hosting for debugging purposes.
/// </summary>
public ObservableCollection<VisualBrush> Brushes
{
get
{
return this.brushes;
}
}
/// <summary>
/// Holds strings which are output at various points if debugging is enabled.
/// </summary>
public ObservableCollection<string> DebuggingInfo
{
get
{
return this.debuggingInfo;
}
}
#endregion
/// <summary>
/// The camera used in the <see cref="ViewPort3D"/> that the <see cref="NGonDisplayControl"/> resides in.
/// </summary>
private PerspectiveCamera ViewportCamera
{
get
{
return this.viewportCamera;
}
set
{
this.viewportCamera = value;
}
}
private bool[] CalculatedFaces
{
get
{
if (this.calculatedFaces == null)
{
this.calculatedFaces = new bool[((Items != null) ? Items.Count : 4)];
}
return this.calculatedFaces;
}
set
{
this.calculatedFaces = value;
}
}
#endregion
/// <summary>
/// Populates the <see cref="ObservableCollection{T}"/> of <see cref="VisualBrush"/> objects with a brush for each item
/// we are hosting. Assumes the visual brush collection is empty and adds all brushes with an opacity of 0.5.
/// </summary>
private void PopulateBrushCollection(IEnumerable<UIElement> items)
{
foreach (UIElement item in items)
{
VisualBrush brush = new VisualBrush();
brush.AutoLayoutContent = false;
brush.Opacity = 0.5;
brush.Visual = item;
this.brushes.Add(brush);
}
}
/// <summary>
/// Updates the brushes if <see cref="Items"/> is of type <see cref="INotifyCollectionChanged"/> and we receive a collection
/// changed event.
/// </summary>
private void UpdateBrushCollection(NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
{
VisualBrush brush = new VisualBrush((UIElement)e.NewItems[0]);
brush.Opacity = 0.5;
this.brushes.Insert(e.NewStartingIndex, brush);
break;
}
case NotifyCollectionChangedAction.Remove:
{
this.brushes.RemoveAt(e.OldStartingIndex);
break;
}
case NotifyCollectionChangedAction.Replace:
{
VisualBrush brush = new VisualBrush((UIElement)e.NewItems[0]);
brush.Opacity = 0.5;
this.brushes.RemoveAt(e.OldStartingIndex);
this.brushes.Insert(e.OldStartingIndex, brush);
break;
}
case NotifyCollectionChangedAction.Reset:
{
this.brushes.Clear();
break;
}
}
}
/// <summary>
/// Resets the Opacity of all <see cref="VisualBrush"/> objects to 0.5. The opacity is used for debugging to indicate
/// while items we are hosting have had 3d meshes calculated and placed in the view port. If the opacity is 0.5 it means
/// we haven't actually constructed the 3d representation, otherwise we have.
/// </summary>
private void ResetBrushOpacity()
{
foreach (VisualBrush brush in this.brushes)
{
brush.Opacity = 0.5;
}
}
/// <summary>
/// Creates the default lights that shine up our viewport.
/// </summary>
private static IEnumerable<Light> CreateDefaultLights()
{
List<Light> defaultLights = new List<Light>(6);
//light shining down negative x-axis
defaultLights.Add(new DirectionalLight(Colors.White, new Vector3D(-1.0, 0.0, 0.0)));
//light shining up positive x-axis
defaultLights.Add(new DirectionalLight(Colors.White, new Vector3D(1.0, 0.0, 0.0)));
//light shining down negative y-axis
defaultLights.Add(new DirectionalLight(Colors.White, new Vector3D(0.0, -1.0, 0.0)));
//light shining up positive y-axis
defaultLights.Add(new DirectionalLight(Colors.White, new Vector3D(0.0, 1.0, 0.0)));
//light shining down negative z-axis
defaultLights.Add(new DirectionalLight(Colors.White, new Vector3D(0.0, 0.0, -1.0)));
//light shining up positive z-axis
defaultLights.Add(new DirectionalLight(Colors.White, new Vector3D(0.0, 0.0, 1.0)));
return defaultLights;
}
/// <summary>
/// Clears old mesh data as well as clearing the list of faces we have calculated.
/// </summary>
private void ResetViewport()
{
for (int i = 0; i < ViewPort.Children.Count; i++)
{
ModelVisual3D model = ViewPort.Children[i] as ModelVisual3D;
//we only want to remove the 3d models that are hosting UIElements, not the lights
if (!(model.Content is Light))
{
//readjust our index so we don't skip any visuals
ViewPort.Children.RemoveAt(i--);
}
}
//since all the meshes are gone we need to recalculate all faces on request
Array.Clear(CalculatedFaces, 0, CalculatedFaces.Length);
this.brushes.Clear();
}
/// <summary>
/// Goes about constructing the n-gon which hosts the UIElements. Calculates the vertex points for the n-gon
/// and makes sure the face that is facing the camera is constructed and visible.
/// </summary>
private void InitializeViewport()
{
if (Items == null || Items.Count == 0 || ActualWidth == 0.0 || ActualHeight == 0.0)
{
return;
}
//first time laying out our visuals, we have no lights yet so lets put them in first
if (!this.lightsAdded)
{
AddLights();
this.lightsAdded = true;
}
if (this.currentFaceIndex >= Items.Count)
{
this.currentFaceIndex = Items.Count - 1;
}
if (CalculatedFaces.Length < Items.Count)
{
CalculatedFaces = new bool[Items.Count];
}
else
{
Array.Clear(CalculatedFaces, 0, CalculatedFaces.Length);
}
PopulateBrushCollection(Items);
//calculate our n-gons vertex points, these will be used to place the meshes initially before they are rotated
//into final viewing position
double sideLength = (Orientation == Orientation.Horizontal) ? ActualWidth / ActualHeight : 1.0;
this.vertexPoints = NGon3DHelper.CalculateVertexPoints(Items.Count, sideLength, FaceMargin, Orientation);
EnsureFaceCalculated(this.currentFaceIndex);
this.brushes[this.currentFaceIndex].Opacity = 1.0;
ResetCameraPosition();
}
/// <summary>
/// Remove all <see cref="Light"/> objects from the <see cref="ViewPort3D"/> the <see cref="NGonDisplayControl"/>
/// is hosted in.
/// </summary>
private void RemoveLights()
{
for (int i = 0; i < ViewPort.Children.Count; i++)
{
ModelVisual3D model = ViewPort.Children[i] as ModelVisual3D;
if (model.Content is Light)
{
ViewPort.Children.RemoveAt(i--);
}
}
}
/// <summary>
/// Adds directional lights to the view port so we can see stuff
/// </summary>
private void AddLights()
{
foreach (Light light in ViewPortLights)
{
ModelVisual3D lightSource = new ModelVisual3D();
lightSource.Content = light;
ViewPort.Children.Add(lightSource);
}
}
/// <summary>
/// Takes off any rotations that are currently applied to the camera and resets to be looking at the current face.
/// </summary>
private void ResetCameraPosition()
{
Vector3D rotationVector = (Orientation == Orientation.Horizontal) ? yAxisVector : xAxisVector;
//this allows us to reset the animation state of the quaternion, otherwise our set on the next
//line has no effect
this.cameraAngleRotation.BeginAnimation(QuaternionRotation3D.QuaternionProperty, null);
this.cameraAngleRotation.Quaternion = new Quaternion(rotationVector, 0.0);
if (ViewportCamera.IsFrozen)
{
ViewportCamera = ViewportCamera.Clone();
}
ViewportCamera.UpDirection = this.cameraUpDirection;
ViewportCamera.Position = this.cameraPosition;
ViewportCamera.LookDirection = this.faceNormal;
}
/// <summary>
/// Applies the zoom / rotation animations.
/// </summary>
/// <param name="angleMultiplier">Determines if the rotation should be forwards or backwards through the item collection. -1 means backwards, 1 means forwards.</param>
/// <param name="rotationCount"></param>
private void ApplyCameraAnimations(int angleMultiplier, int rotationCount)
{
Content = ViewPort;
if (angleMultiplier != -1 && angleMultiplier != 1)
{
throw new ArgumentException("Value must be either -1 or 1.", "angleMultiplier");
}
Storyboard cameraAnimationStoryBoard = new Storyboard();
double rotationAngle = ((360.0 / Items.Count) * rotationCount) * angleMultiplier;
Vector3D axisOfRotation = (Orientation == Orientation.Horizontal) ? yAxisVector : xAxisVector;
AnimationHelper.AddZoomAnimations(cameraAnimationStoryBoard, ZoomAnimationTime, TimeSpan.Zero, 1.5);