This repository has been archived by the owner on Mar 2, 2019. It is now read-only.
/
Game1.cs
executable file
·1516 lines (1282 loc) · 71.6 KB
/
Game1.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
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Kinect;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace HIVE_KinectGame
{
/// <summary>
/// The main type class for our videogame.
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
/// <summary>
/// This region will define all of our global variables used throughout the game.
/// </summary>
#region VariableDefinitions
/// <summary>
/// Set up the graphics controllers for the environment
/// </summary>
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
ContentManager content;
/// <summary>
/// Keyboard states for detecting keypressed
/// </summary>
private KeyboardState currentKeyboard;
private KeyboardState previousKeyboard;
/// <summary>
/// Draw the simple planar grid for avatar to stand on if true.
/// </summary>
private bool drawGrid;
/// <summary>
/// This is the coordinate cross we use to draw the world coordinate system axes.
/// </summary>
private CoordinateCross worldAxes;
/// <summary>
/// Simple planar grid for avatar to stand on.
/// </summary>
private GridXz planarXzGrid;
/// <summary>
/// Camera Arc Increment value.
/// </summary>
private const float CameraArcIncrement = 0.1f;
/// <summary>
/// Camera Arc angle limit value.
/// </summary>
private const float CameraArcAngleLimit = 90.0f;
/// <summary>
/// Camera Zoom Increment value.
/// </summary>
private const float CameraZoomIncrement = 0.25f;
/// <summary>
/// Camera Max Distance value.
/// </summary>
private const float CameraMaxDistance = 500.0f;
/// <summary>
/// Camera Min Distance value.
/// </summary>
private const float CameraMinDistance = 15.0f;
/// <summary>
/// Camera starting Distance value.
/// </summary>
private const float CameraHeight = 40.0f;
/// <summary>
/// Camera starting Distance value.
/// </summary>
private const float CameraStartingTranslation = 40.0f;
/// <summary>
/// Viewing Camera arc.
/// </summary>
private float cameraArc = 0;
/// <summary>
/// Viewing Camera current rotation.
/// The virtual camera starts where Kinect is looking i.e. looking along the Z axis, with +X left, +Y up, +Z forward
/// </summary>
private float cameraRotation = 0;
/// <summary>
/// Viewing Camera distance from origin.
/// The "Dude" model is defined in centimeters, hence all the units we use here are cm.
/// </summary>
private float cameraDistance = CameraStartingTranslation;
/// <summary>
/// The "Dude" model mesh is defined at an arbitrary size in centimeters.
/// Here we re-scale the Kinect translation so the model appears to walk more correctly on the ground.
/// </summary>
private static readonly Vector3 SkeletonTranslationScaleFactor = new Vector3(40.0f, 40.0f, 40.0f);
/// <summary>
/// The Kinect SDK can only actively track 2 skeletons at a time. This array holds the data
/// corresponding to the two active skeletons.
/// </summary>
private Skeleton[] activeSkeletons = new Skeleton[2];
/// <summary>
/// The main kinect sensor
/// </summary>
private KinectSensor kinect = null;
/// <summary>
/// Image frames from the kinect
/// </summary>
ColorImageFrame colorFrame = null;
DepthImageFrame depthFrame = null;
/// <summary>
/// Basic XNA effect for drawing on screen
/// </summary>
private BasicEffect effect;
/// <summary>
/// Flag for screen mode. Full screen the game if true
/// </summary>
private Boolean isFullScreen = false;
/// <summary>
/// Set up basic screen sizes. We want to keep the aspect ratio standard 720 / 1080 HD video
/// </summary>
private const int WindowedWidth = 1280;
private const int WindowedHeight = 720;
private const int FullScreenWidth = 1680; // Change to 1920 for final
private const int FullScreenHeight = 1050; // Change to 1080 for final
/// <summary>
/// This will be loaded with the 3D mesh of the avatars we will animate
/// </summary>
public Model[] avatars = new Model[2];
/// <summary>
/// Animators hold the data corresponding to how the mesh will be deformed for animation
/// </summary>
private AvatarAnimator[] animator = new AvatarAnimator[2];
/// <summary>
/// Map for the avatar mesh rigging to address bones in #AvatarRetargeting region
/// </summary>
private Dictionary<JointType, int> nuiJointToAvatarBoneIndex;
/// <summary>
/// Viewing Camera view matrix.
/// </summary>
private Microsoft.Xna.Framework.Matrix view;
/// <summary>
/// Viewing Camera projection matrix.
/// </summary>
private Microsoft.Xna.Framework.Matrix projection;
/// <summary>
/// Sets a seated posture when Seated Mode is on.
/// </summary>
private bool setSeatedPostureInSeatedMode;
/// <summary>
/// Fix the avatar hip center draw height.
/// </summary>
private bool fixAvatarHipCenterDrawHeight;
/// <summary>
/// Avatar hip center draw height.
/// </summary>
private float avatarHipCenterDrawHeight;
/// <summary>
/// Adjust Avatar lean when leaning back to reduce lean.
/// </summary>
private bool leanAdjust;
/// <summary>
/// Flag for controlling taking a photo of the players in the 3D environment. If true, we will take and save the image
/// to the content folder. This should really remain false at all times except during the ONE cycle we want to take
/// a snapshot-- else we will be continually taking photos.
/// </summary>
private Boolean takeScreencap = false;
/// <summary>
/// The screenshot/image number (a GUID) for writing the PNG file.
/// </summary>
private int snapNumber = 0;
/// <summary>
/// Random number generator
/// </summary>
private Random randomNum = new Random();
/// <summary>
/// Array of background images to display for the 3D environment.
/// We will set up the total number of images dynamically later.
/// Also, the splash screen image.
/// </summary>
private Texture2D[] envImages = null;
private Texture2D backgroundImage = null;
private Texture2D splashScreen = null;
/// <summary>
/// The array of slideshow images that we will look at during the show.
/// </summary>
private Texture2D[] slideshowImages = null;
/// <summary>
/// The final rendered image with the screenscreen processed onto it.
/// </summary>
private Texture2D finalImage = null;
/// <summary>
/// The index of which slide in the slideshow we look at.
/// </summary>
private int whichSlide = 0;
/// <summary>
/// A placeholder for which environment image we will use
/// </summary>
private int whichEnv = 0;
/// <summary>
/// We have to change a few things each time we change scene, so this will keep track of scene
/// changes. Mostly, we're concerned about being able to switch the background image in the 3D
/// environment.
/// </summary>
private Boolean sceneJustChanged = false;
/// <summary>
/// Define the game state to control on screen display.
/// 0 -> Intro graphic
/// 1 -> Fade into the 3D environment
/// 2 -> The 3D environment
/// 3 -> The snapshot/screencap
/// 4 -> Slideshow
/// </summary>
private int gameState = 0;
/// <summary>
/// A timer for controlling when events happen (i.e. when do we take snapshots and change the on
/// screen display)
/// </summary>
double gameTimer = 0;
/// <summary>
/// Fading controls for changing screens etc.
/// We only need to do the math if we want it, hence the flag.
/// </summary>
private int alphaValue = 255;
private Boolean updateAlpha = false;
private int fadeAmount = 10;
/// <summary>
/// Intermediate storage for the color data received from the camera
/// </summary>
private Byte[] colorPixels = null;
/// <summary>
/// Intermediate storage for the depth data received from the sensor
/// </summary>
private DepthImagePixel[] depthPixels = null;
/// <summary>
/// Intermediate storage for the green screen opacity mask
/// </summary>
private int[] greenScreenPixelData = null;
/// <summary>
/// Intermediate storage for the depth to color mapping
/// </summary>
private ColorImagePoint[] colorCoordinates = null;
/// <summary>
/// Inverse scaling factor between color and depth
/// </summary>
private int colorToDepthDivisor = 1;
private Boolean foundPlayer = false;
#endregion
/// <summary>
/// This section contains all information regarding initializing the game: loading content and starting up
/// the game.
/// </summary>
#region GameInitializationLogic
/// <summary>
/// Main game entry
/// </summary>
public Game1()
{
// Set up the graphics to display
graphics = new GraphicsDeviceManager(this);
// Content directory. Here is where we will expect to find the 3D model and data, as well
// as all imagery used in the project.
Content.RootDirectory = "Content";
/// Allows the game to run fullscreen
content = new ContentManager(Services);
// Set up resolution data for the final display.
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferredBackBufferHeight = 720;
graphics.PreferMultiSampling = false;
graphics.IsFullScreen = false;
// Create a ground plane for the model to stand on
this.planarXzGrid = new GridXz(this, new Vector3(0, 0, 0), new Vector2(500, 500), new Vector2(10, 10), Microsoft.Xna.Framework.Color.Black);
this.Components.Add(this.planarXzGrid);
this.drawGrid = false;
// Generate the coordinate system for the world the avatar is in.
this.worldAxes = new CoordinateCross(this, 500);
this.Components.Add(this.worldAxes);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// Set up the kinect sensor. Using the first Kinect sensor available on the system
// TODO: Add multi-kinect support in the future.
kinect = KinectSensor.KinectSensors.FirstOrDefault(s => s.Status == KinectStatus.Connected);
// Enable the video stream, skeleton stream, and depth stream from our Kinect.
kinect.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
kinect.SkeletonStream.Enable();
kinect.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
// Add a handler for when all frames are ready from the Kinect.
// Data processing of the image, depth and skeleton frames will happen in this function.
kinect.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(kinect_AllFramesReady);
// If all goes well, intialize the Kinect!
kinect.Start();
// Set mouse visibility in the game.
this.IsMouseVisible = true;
// Drawing options for the avatar. Most likely these will stay false except in
// certain circumstances. False for both enables free movement.
this.setSeatedPostureInSeatedMode = false;
this.leanAdjust = false;
// Here we can force the avatar to be drawn at fixed height in the XNA virtual world.
// The reason we may use this is because the sensor height above the physical floor
// and the feet locations are not always known. Hence the avatar cannot be correctly
// placed on the ground plane or will be very jumpy.
// Note: this will prevent the avatar from jumping and crouching.
this.fixAvatarHipCenterDrawHeight = true;
this.avatarHipCenterDrawHeight = 0.8f; // in meters
// Initialize our avatars and add them to the game.
this.animator[0] = new AvatarAnimator(this, this.RetargetMatrixHierarchyToAvatarMesh, Game1.SkeletonTranslationScaleFactor);
this.animator[1] = new AvatarAnimator(this, this.RetargetMatrixHierarchyToAvatarMesh, Game1.SkeletonTranslationScaleFactor);
this.Components.Add(this.animator[0]);
this.Components.Add(this.animator[1]);
// Start it all up!
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of the content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Create the XNA Basic Effect for line drawing
this.effect = new BasicEffect(GraphicsDevice);
if (null == this.effect)
{
throw new InvalidOperationException("Cannot load Basic Effect");
}
// Load in the avatar file into slots 0 and 1 of avatars. We are using the same
// basic model/rigging for both active avatars.
this.avatars[0] = Content.Load<Model>("dude");
this.avatars[1] = Content.Load<Model>("dude");
if (null == this.avatars[0])
{
throw new InvalidOperationException("Cannot load 3D avatar model");
}
// Load in the background images to place in the 3D environment.
// Discover all image files in the backgrounds folder (Content\backgrounds) and load them
string[] envFiles = Directory.GetFiles(Content.RootDirectory + "\\" + "backgrounds");
// Initialize our background image array to the number of images found.
this.envImages = new Texture2D[envFiles.Length];
// For each image we found in this directory, insert it into the array.
for (int ctr = 0; ctr < envFiles.Length; ctr++)
{
using (FileStream stream = File.OpenRead(envFiles[ctr]))
{
this.envImages[ctr] = Texture2D.FromStream(GraphicsDevice, stream);
}
}
// Load in the splash screen image.
FileStream splashStream = File.OpenRead(Content.RootDirectory + "\\splash.png");
this.splashScreen = Texture2D.FromStream(GraphicsDevice, splashStream);
// Load in the default background screen image.
FileStream backStream = File.OpenRead(Content.RootDirectory + "\\asframe.png");
this.backgroundImage = Texture2D.FromStream(GraphicsDevice, backStream);
// Magic function that maps the joints to the avatar for animation.
this.BuildJointHierarchy();
// Add the models to the avatar animators and set where the hip will be
// from earlier variables.
this.animator[0].Avatar = this.avatars[0];
this.animator[0].AvatarHipCenterHeight = this.avatarHipCenterDrawHeight;
this.animator[1].Avatar = this.avatars[1];
this.animator[1].AvatarHipCenterHeight = this.avatarHipCenterDrawHeight;
}
/// <summary>
/// This function configures the mapping between the Nui Skeleton bones/joints and the Avatar bones/joints.
/// Magic Microsoft-provided function.
/// </summary>
protected void BuildJointHierarchy()
{
// "Dude.fbx" bone index definitions
// These are described as the "bone" that the transformation affects.
// The rotation values are stored at the start joint before the bone (i.e. at the shared joint with the end of the parent bone).
// 0 = root node
// 1 = pelvis
// 2 = spine
// 3 = spine1
// 4 = spine2
// 5 = spine3
// 6 = neck
// 7 = head
// 8-11 = eyes
// 12 = Left clavicle (joint between spine and shoulder)
// 13 = Left upper arm (joint at left shoulder)
// 14 = Left forearm
// 15 = Left hand
// 16-30 = Left hand finger bones
// 31 = Right clavicle (joint between spine and shoulder)
// 32 = Right upper arm (joint at left shoulder)
// 33 = Right forearm
// 34 = Right hand
// 35-49 = Right hand finger bones
// 50 = Left Thigh
// 51 = Left Knee
// 52 = Left Ankle
// 53 = Left Ball
// 54 = Right Thigh
// 55 = Right Knee
// 56 = Right Ankle
// 57 = Right Ball
// For the Kinect NuiSkeleton, the joint at the end of the bone describes the rotation to get there,
// and the root orientation is in HipCenter. This is different to the Avatar skeleton described above.
if (null == this.nuiJointToAvatarBoneIndex)
{
this.nuiJointToAvatarBoneIndex = new Dictionary<JointType, int>();
}
// Note: the actual hip center joint in the Avatar mesh has a root node (index 0) as well, which we ignore here for rotation.
this.nuiJointToAvatarBoneIndex.Add(JointType.HipCenter, 1);
this.nuiJointToAvatarBoneIndex.Add(JointType.Spine, 4);
this.nuiJointToAvatarBoneIndex.Add(JointType.ShoulderCenter, 6);
this.nuiJointToAvatarBoneIndex.Add(JointType.Head, 7);
this.nuiJointToAvatarBoneIndex.Add(JointType.ElbowLeft, 13);
this.nuiJointToAvatarBoneIndex.Add(JointType.WristLeft, 14);
this.nuiJointToAvatarBoneIndex.Add(JointType.HandLeft, 15);
this.nuiJointToAvatarBoneIndex.Add(JointType.ElbowRight, 32);
this.nuiJointToAvatarBoneIndex.Add(JointType.WristRight, 33);
this.nuiJointToAvatarBoneIndex.Add(JointType.HandRight, 34);
this.nuiJointToAvatarBoneIndex.Add(JointType.KneeLeft, 50);
this.nuiJointToAvatarBoneIndex.Add(JointType.AnkleLeft, 51);
this.nuiJointToAvatarBoneIndex.Add(JointType.FootLeft, 52);
this.nuiJointToAvatarBoneIndex.Add(JointType.KneeRight, 54);
this.nuiJointToAvatarBoneIndex.Add(JointType.AnkleRight, 55);
this.nuiJointToAvatarBoneIndex.Add(JointType.FootRight, 56);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content
/// </summary>x
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
#endregion
/// <summary>
/// This section contains all the runtime logic that we're concerned about.
/// </summary>
#region RunTimeLogic
/// <summary>
/// Event Handler method for recieving data frames from the Kinect.
/// </summary>
///
protected void kinect_AllFramesReady(object sender, AllFramesReadyEventArgs imageFrames)
{
// RGB Image Frame
this.colorFrame = imageFrames.OpenColorImageFrame();
// Depth Image Frame
this.depthFrame = imageFrames.OpenDepthImageFrame();
// If we have depth and image data, and we want to take a screenshot of the users in a particular environment.
if (this.colorFrame != null && this.depthFrame != null && this.takeScreencap == true)
{
this.depthPixels = new DepthImagePixel[this.kinect.DepthStream.FramePixelDataLength];
this.greenScreenPixelData = new int[this.kinect.DepthStream.FramePixelDataLength];
this.colorCoordinates = new ColorImagePoint[this.kinect.DepthStream.FramePixelDataLength];
this.colorPixels = new Byte[colorFrame.PixelDataLength];
this.depthFrame.CopyDepthImagePixelDataTo(this.depthPixels);
this.colorFrame.CopyPixelDataTo(this.colorPixels);
this.kinect.CoordinateMapper.MapDepthFrameToColorFrame(
DepthImageFormat.Resolution640x480Fps30,
this.depthPixels,
ColorImageFormat.RgbResolution640x480Fps30,
this.colorCoordinates);
Array.Clear(greenScreenPixelData, 0, greenScreenPixelData.Length);
this.foundPlayer = false;
// loop over each row and column of the depth
for (int y = 0; y < 480; ++y)
{
for (int x = 0; x < 640; ++x)
{
// calculate index into depth array
int depthIndex = x + (y * 640);
DepthImagePixel depthPixel = depthPixels[depthIndex];
int player = depthPixel.PlayerIndex;
// if we're tracking a player for the current pixel, do green screen
if (player > 0)
{
this.foundPlayer = true;
// retrieve the depth to color mapping for the current depth pixel
ColorImagePoint colorImagePoint = this.colorCoordinates[depthIndex];
// scale color coordinates to depth resolution
int colorInDepthX = colorImagePoint.X / this.colorToDepthDivisor;
int colorInDepthY = colorImagePoint.Y / this.colorToDepthDivisor;
// make sure the depth pixel maps to a valid point in color space
// check y > 0 and y < depthHeight to make sure we don't write outside of the array
// check x > 0 instead of >= 0 since to fill gaps we set opaque current pixel plus the one to the left
// because of how the sensor works it is more correct to do it this way than to set to the right
if (colorInDepthX > 0 && colorInDepthX < 640 && colorInDepthY >= 0 && colorInDepthY < 480)
{
// calculate index into the green screen pixel array
int greenScreenIndex = colorInDepthX + (colorInDepthY * 640);
// set opaque
this.greenScreenPixelData[greenScreenIndex] = -1;
// compensate for depth/color not corresponding exactly by setting the pixel
// to the left to opaque as well
this.greenScreenPixelData[greenScreenIndex - 1] = -1;
}
}
}
}
// If we've found a player in the image, then run through the player mask
// and copy pixels from the RGB camera to a final image
// and save it as a screenshot.
if (true)//this.foundPlayer)
{
// get the RGB color frame image
// this.colorFrame.CopyPixelDataTo(this.colorPixels);
// Create a new Texture2D in which we will store out final image (masked player image)
this.finalImage = new Texture2D(graphics.GraphicsDevice, this.kinect.ColorStream.FrameWidth, this.kinect.ColorStream.FrameHeight);
// TODO: Process the image and merge the player onto our background scene.
// Once we've completed processing the image, save it into the screenshots directory.
this.finalImage.SetData(this.colorPixels);
//finalImage.SetData(this.greenScreenPixelData);
Stream stream = File.OpenWrite(this.Content.RootDirectory + "\\screenshots\\" + "snapshot-" + this.snapNumber + ".png");
this.finalImage.SaveAsPng(stream, 640, 480);
this.finalImage.SaveAsPng(stream, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight);
this.snapNumber++;
stream.Close();
}
this.takeScreencap = false;
this.sceneJustChanged = true;
}
// Process the skeleton stream
using (SkeletonFrame skeletonFrame = imageFrames.OpenSkeletonFrame())
{
if (skeletonFrame != null)
{
Skeleton[] allSkeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
skeletonFrame.CopySkeletonDataTo(allSkeletons);
// Clear out the activeSkeletons data. We don't want to keep it-- this allows dynamic on-the-fly user changes
// for groups of people.
activeSkeletons[0] = new Skeleton();
activeSkeletons[1] = new Skeleton();
activeSkeletons[0].TrackingId = -1;
activeSkeletons[1].TrackingId = -1;
// Add actively tracked skeletons to our list of activeSkeletons
foreach (Skeleton aSkeleton in allSkeletons)
{
if ((aSkeleton.TrackingState == SkeletonTrackingState.Tracked) && (activeSkeletons[0].TrackingId == -1))
{
activeSkeletons[0] = aSkeleton;
}
if ((aSkeleton.TrackingState == SkeletonTrackingState.Tracked) && (aSkeleton.TrackingId != activeSkeletons[0].TrackingId))
{
activeSkeletons[1] = aSkeleton;
}
}
// If we have a skeleton for the avatar, then set its visibility to true.
// Otherwise, make sure that we are hiding avatars that aren't attached to tracked people.
if (activeSkeletons[0].TrackingId != -1)
{
this.animator[0].CopySkeleton(activeSkeletons[0]);
this.animator[0].FloorClipPlane = skeletonFrame.FloorClipPlane;
this.animator[0].SkeletonVisible = true;
}
else { this.animator[0].SkeletonVisible = false; }
if (activeSkeletons[1].TrackingId != -1)
{
this.animator[1].CopySkeleton(activeSkeletons[1]);
this.animator[1].FloorClipPlane = skeletonFrame.FloorClipPlane;
this.animator[1].SkeletonVisible = true;
}
else { this.animator[1].SkeletonVisible = false; }
}
}
}
/// <summary>
/// Runs all updating information for our game.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Update the avatar renderer. If we don't have actively tracked skeletons, then make sure we flag it.
if (null != this.animator[0])
{
this.animator[0].SkeletonDrawn = false;
}
if (null != this.animator[1])
{
this.animator[1].SkeletonDrawn = false;
}
// Update saved keyboard state.
this.previousKeyboard = this.currentKeyboard;
this.currentKeyboard = Keyboard.GetState();
// Check to see if keyboard state has changed or if still holding a key/not pressed
if (this.previousKeyboard != this.currentKeyboard)
{
// Press Escape key to exit from game.
if (this.currentKeyboard.IsKeyDown(Keys.Escape))
{
this.Exit();
}
// Press F to fullscreen
if (this.currentKeyboard.IsKeyDown(Keys.F))
{
this.isFullScreen = !this.isFullScreen;
this.SetScreenMode();
}
// Manual override (mostly for testing)
// Press S to take a picture
if (this.currentKeyboard.IsKeyDown(Keys.S))
{
this.takeScreencap = true;
}
// Manually adjust the tilt of the kinect sensor
if (this.currentKeyboard.IsKeyDown(Keys.Up))
{
if (kinect.ElevationAngle < (kinect.MaxElevationAngle + 5))
{
kinect.ElevationAngle += 5;
}
}
if (this.currentKeyboard.IsKeyDown(Keys.Down))
{
if (kinect.ElevationAngle > (kinect.MinElevationAngle - 5))
{
kinect.ElevationAngle -= 5;
}
}
}
// Update the game timer
this.gameTimer += gameTime.ElapsedGameTime.TotalSeconds;
// Update alpha channel if we want to change it.
if (this.updateAlpha)
{
this.alphaValue -= this.fadeAmount;
}
base.Update(gameTime);
this.UpdateCamera(gameTime);
}
/// <summary>
/// Create the viewing camera.
/// </summary>
protected void UpdateViewingCamera()
{
GraphicsDevice device = this.graphics.GraphicsDevice;
// Compute camera matrices.
this.view = Microsoft.Xna.Framework.Matrix.CreateTranslation(0, -CameraHeight, 0) *
Microsoft.Xna.Framework.Matrix.CreateRotationY(MathHelper.ToRadians(this.cameraRotation)) *
Microsoft.Xna.Framework.Matrix.CreateRotationX(MathHelper.ToRadians(this.cameraArc)) *
Microsoft.Xna.Framework.Matrix.CreateLookAt(
new Vector3(0, 0, -this.cameraDistance),
new Vector3(0, 0, 0),
Vector3.Up);
// Kinect vertical FOV in degrees
float nominalVerticalFieldOfView = 45.6f;
nominalVerticalFieldOfView = this.kinect.DepthStream.NominalVerticalFieldOfView;
this.projection = Microsoft.Xna.Framework.Matrix.CreatePerspectiveFieldOfView(
nominalVerticalFieldOfView * (float)Math.PI / 180.0f,
device.Viewport.AspectRatio,
1,
10000);
}
/// <summary>
/// Handles camera input.
/// </summary>
/// <param name="gameTime">The gametime.</param>
private void UpdateCamera(GameTime gameTime)
{
float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;
// Check for input to rotate the camera up and down around the model.
if (this.currentKeyboard.IsKeyDown(Keys.Up) ||
this.currentKeyboard.IsKeyDown(Keys.W))
{
this.cameraArc += time * CameraArcIncrement;
}
if (this.currentKeyboard.IsKeyDown(Keys.Down) ||
this.currentKeyboard.IsKeyDown(Keys.S))
{
this.cameraArc -= time * CameraArcIncrement;
}
// Limit the arc movement.
if (this.cameraArc > CameraArcAngleLimit)
{
this.cameraArc = CameraArcAngleLimit;
}
else if (this.cameraArc < -CameraArcAngleLimit)
{
this.cameraArc = -CameraArcAngleLimit;
}
// Check for input to rotate the camera around the model.
if (this.currentKeyboard.IsKeyDown(Keys.Right) ||
this.currentKeyboard.IsKeyDown(Keys.D))
{
this.cameraRotation += time * CameraArcIncrement;
}
if (this.currentKeyboard.IsKeyDown(Keys.Left) ||
this.currentKeyboard.IsKeyDown(Keys.A))
{
this.cameraRotation -= time * CameraArcIncrement;
}
// Check for input to zoom camera in and out.
if (this.currentKeyboard.IsKeyDown(Keys.Z))
{
this.cameraDistance += time * CameraZoomIncrement;
}
if (this.currentKeyboard.IsKeyDown(Keys.X))
{
this.cameraDistance -= time * CameraZoomIncrement;
}
// Limit the camera distance from the origin.
if (this.cameraDistance > CameraMaxDistance)
{
this.cameraDistance = CameraMaxDistance;
}
else if (this.cameraDistance < CameraMinDistance)
{
this.cameraDistance = CameraMinDistance;
}
if (this.currentKeyboard.IsKeyDown(Keys.R))
{
this.cameraArc = 0;
this.cameraRotation = 0;
this.cameraDistance = CameraStartingTranslation;
}
}
/// <summary>
/// Set fullscreen or windowed mode
/// </summary>
private void SetScreenMode()
{
// This sets the display resolution or window size to the desired size
// If windowed, it also forces a 4:3 ratio for height and adds 110 for header/footer
if (this.isFullScreen)
{
foreach (DisplayMode mode in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
{
// Check our requested FullScreenWidth and Height against each supported display mode and set if valid
if ((mode.Width == FullScreenWidth) && (mode.Height == FullScreenHeight))
{
this.graphics.PreferredBackBufferWidth = FullScreenWidth;
this.graphics.PreferredBackBufferHeight = FullScreenHeight;
this.graphics.IsFullScreen = true;
this.graphics.ApplyChanges();
}
}
}
else
{
if (WindowedWidth <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width)
{
this.graphics.PreferredBackBufferWidth = WindowedWidth;
this.graphics.PreferredBackBufferHeight = 720;
this.graphics.IsFullScreen = false;
this.graphics.ApplyChanges();
}
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
// Clear the screen so we don't have artifacts from updating.
GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.White);
#region DisplaySplashScreenState
// If we are in the intro graphic screen. This will only happen at game startup.
if (this.gameState == 0)
{
if (this.updateAlpha == false && (this.gameTimer > 5))
{
this.updateAlpha = true;
}
// Display the opening graphic.
spriteBatch.Begin();
spriteBatch.Draw(this.splashScreen, new Rectangle(0, 0, (graphics.PreferredBackBufferWidth), graphics.PreferredBackBufferHeight), new Microsoft.Xna.Framework.Color((byte)MathHelper.Clamp(this.alphaValue, 0, 255), (byte)MathHelper.Clamp(this.alphaValue, 0, 255), (byte)MathHelper.Clamp(this.alphaValue, 0, 255), (byte)MathHelper.Clamp(this.alphaValue, 0, 255)));
spriteBatch.End();
// Change gamestate to move into the 3D environment.
if (this.alphaValue < 1)
{
this.updateAlpha = false;
this.gameState = 1;
this.gameTimer = 0;
}
}
#endregion
#region Display3DEnvironmentState
// If we are in the main 3D envrionment. This is the majority of the game.
if (this.gameState == 1)
{
if (this.finalImage != null)
{
// TEMPORARY FORCE DRAW RGB
spriteBatch.Begin();
spriteBatch.Draw(this.finalImage, new Rectangle(0, 0, 640, 480), Microsoft.Xna.Framework.Color.White);
spriteBatch.End();
}
// If we are changing the 3D environment, then ensure we load a different background image than we just had.
if (this.sceneJustChanged == true)
{
int tempInt = this.whichEnv;
while (this.whichEnv == tempInt)
{
this.whichEnv = randomNum.Next(this.envImages.Length);
}
this.sceneJustChanged = false;
}
// Draw the background template
if (this.backgroundImage != null)
{
spriteBatch.Begin();
spriteBatch.Draw(this.backgroundImage, new Rectangle(0, 0, (graphics.PreferredBackBufferWidth), graphics.PreferredBackBufferHeight), Microsoft.Xna.Framework.Color.White);
spriteBatch.End();
}
// Draw the environment images.
if (this.envImages != null)
{
if (this.isFullScreen)
{
spriteBatch.Begin();
// Hard-coded values are bad.
spriteBatch.Draw(this.envImages[this.whichEnv], new Rectangle(553, 44, 1326, 997), Microsoft.Xna.Framework.Color.White);
spriteBatch.End();
}
else
{
spriteBatch.Begin();
// Windowed mode is forcing 1280x720....
spriteBatch.Draw(this.envImages[this.whichEnv], new Rectangle(369, 29, 884, 664), Microsoft.Xna.Framework.Color.White);
spriteBatch.End();
}
}
// Update the viewing camera.
this.UpdateViewingCamera();
// Draw the world grid if we need it.
if (this.drawGrid && null != this.planarXzGrid && null != this.worldAxes)
{
this.planarXzGrid.Draw(gameTime, Microsoft.Xna.Framework.Matrix.Identity, this.view, this.projection);
this.worldAxes.Draw(gameTime, Microsoft.Xna.Framework.Matrix.Identity, this.view, this.projection);
}
// Draw the actual avatars in the 3D environment
if (activeSkeletons[0].TrackingId > -1)
{
this.animator[0].Draw(gameTime, Microsoft.Xna.Framework.Matrix.Identity, this.view, this.projection);
if (activeSkeletons[1].TrackingId > -1)