-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMainWindow.xaml.cs
382 lines (330 loc) · 15 KB
/
MainWindow.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
//------------------------------------------------------------------------------
// <copyright file="MainWindow.xaml.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Samples.Kinect.InfraredBasics
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Linq;
using Microsoft.Kinect;
using System.Windows.Threading;
using System.Windows.Controls;
/// <summary>
/// Interaction logic for the MainWindow
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
/// <summary>
/// Maximum value (as a float) that can be returned by the InfraredFrame
/// </summary>
private const float InfraredSourceValueMaximum = (float)ushort.MaxValue;
/// <summary>
/// The value by which the infrared source data will be scaled
/// </summary>
private const float InfraredSourceScale = 0.75f;
/// <summary>
/// Smallest value to display when the infrared data is normalized
/// </summary>
private const float InfraredOutputValueMinimum = 0.01f;
/// <summary>
/// Largest value to display when the infrared data is normalized
/// </summary>
private const float InfraredOutputValueMaximum = 1.0f;
/// <summary>
/// Active Kinect sensor
/// </summary>
private KinectSensor kinectSensor = null;
/// <summary>
/// Reader for infrared frames
/// </summary>
private InfraredFrameReader infraredFrameReader = null;
/// <summary>
/// Description (width, height, etc) of the infrared frame data
/// </summary>
private FrameDescription infraredFrameDescription = null;
/// <summary>
/// Bitmap to display
/// </summary>
private WriteableBitmap infraredBitmap = null;
/// <summary>
/// Current status text to display
/// </summary>
private string statusText = null;
private Magic magic;
/// <summary>
/// Initializes a new instance of the MainWindow class.
/// </summary>
public MainWindow()
{
// get the kinectSensor object
this.kinectSensor = KinectSensor.GetDefault();
// open the reader for the depth frames
this.infraredFrameReader = this.kinectSensor.InfraredFrameSource.OpenReader();
// wire handler for frame arrival
this.infraredFrameReader.FrameArrived += this.Reader_InfraredFrameArrived;
// get FrameDescription from InfraredFrameSource
this.infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription;
// create the bitmap to display
this.infraredBitmap = new WriteableBitmap(this.infraredFrameDescription.Width, this.infraredFrameDescription.Height, 96.0, 96.0, PixelFormats.Gray32Float, null);
// set IsAvailableChanged event notifier
this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged;
// open the sensor
this.kinectSensor.Open();
// set the status text
this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
: Properties.Resources.NoSensorStatusText;
// use the window object as the view model in this simple example
this.DataContext = this;
magic = new Magic(infraredFrameDescription);
magic.gameController.bluetoothController.OnSpellListChanged += (spells) =>
{
spellsText.Dispatcher.Invoke(() =>
{
spellsText.Text = string.Join(", ", spells);
});
};
// initialize the components (controls) of the window
this.InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Start();
Task.Run(() => magic.Initialize());
//this.detection_counter.Text = "";
Action castSpellUpdate = () =>
{
castSpell.Text = string.Join(
" or ", magic.gameController.machine.PermittedTriggers
.Where(t => t != Trigger.Dud && t != Trigger.Times_Up)
.Select(t => t.ToString().Replace("_", " ")));
};
magic.gameController.machine.OnTransitionCompleted((transition) =>
{
robotStatus.Dispatcher.Invoke(() =>
{
robotStatus.Text = transition.Destination.ToString();
});
castSpell.Dispatcher.Invoke(castSpellUpdate);
});
timer.Tick += (sender, e) =>
{
magic.gameController.dispatcherTimer_Tick(sender, e);
timeRemaining.Dispatcher.Invoke(() =>
{
var current_time = magic.gameController.current_time;
if (magic.gameController.machine.State == State.Waiting)
{
timeRemaining.Text = "Not Playing";
}
else if (current_time == 0)
{
timeRemaining.Text = "Clock is Off";
}
else
{
timeRemaining.Text = $"{current_time} second{(current_time == 1 ? "" : "s")}";
}
});
};
castSpellUpdate();
robotStatus.Text = magic.gameController.machine.State.ToString();
timeRemaining.Text = "Not Playing";
}
/// <summary>
/// INotifyPropertyChangedPropertyChanged event to allow window controls to bind to changeable data
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the bitmap to display
/// </summary>
public ImageSource ImageSource
{
get
{
return this.infraredBitmap;
}
}
/// <summary>
/// Gets or sets the current status text to display
/// </summary>
public string StatusText
{
get
{
return this.statusText;
}
set
{
if (this.statusText != value)
{
this.statusText = value;
// notify any bound elements that the text has changed
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("StatusText"));
}
}
}
}
/// <summary>
/// Execute shutdown tasks
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
if (this.infraredFrameReader != null)
{
// InfraredFrameReader is IDisposable
this.infraredFrameReader.Dispose();
this.infraredFrameReader = null;
}
if (this.kinectSensor != null)
{
this.kinectSensor.Close();
this.kinectSensor = null;
}
}
/// <summary>
/// Handles the user clicking on the screenshot button
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void ScreenshotButton_Click(object sender, RoutedEventArgs e)
{
if (this.infraredBitmap != null)
{
// create a png bitmap encoder which knows how to save a .png file
BitmapEncoder encoder = new PngBitmapEncoder();
// create frame from the writable bitmap and add to encoder
encoder.Frames.Add(BitmapFrame.Create(this.infraredBitmap));
string time = System.DateTime.Now.ToString("hh'-'mm'-'ss", CultureInfo.CurrentUICulture.DateTimeFormat);
string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
string path = Path.Combine(myPhotos, "KinectScreenshot-Infrared-" + time + ".png");
// write the new file to disk
try
{
// FileStream is IDisposable
using (FileStream fs = new FileStream(path, FileMode.Create))
{
encoder.Save(fs);
}
this.StatusText = string.Format(CultureInfo.CurrentCulture, Properties.Resources.SavedScreenshotStatusTextFormat, path);
}
catch (IOException)
{
this.StatusText = string.Format(CultureInfo.CurrentCulture, Properties.Resources.FailedScreenshotStatusTextFormat, path);
}
}
}
/// <summary>
/// Handles the infrared frame data arriving from the sensor
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void Reader_InfraredFrameArrived(object sender, InfraredFrameArrivedEventArgs e)
{
// InfraredFrame is IDisposable
using (InfraredFrame infraredFrame = e.FrameReference.AcquireFrame())
{
if (infraredFrame != null)
{
// the fastest way to process the infrared frame data is to directly access
// the underlying buffer
using (Microsoft.Kinect.KinectBuffer infraredBuffer = infraredFrame.LockImageBuffer())
{
// verify data and write the new infrared frame data to the display bitmap
if (((this.infraredFrameDescription.Width * this.infraredFrameDescription.Height) == (infraredBuffer.Size / this.infraredFrameDescription.BytesPerPixel)) &&
(this.infraredFrameDescription.Width == this.infraredBitmap.PixelWidth) && (this.infraredFrameDescription.Height == this.infraredBitmap.PixelHeight))
{
this.ProcessInfraredFrameData(infraredBuffer.UnderlyingBuffer, infraredBuffer.Size);
}
}
}
}
}
/// <summary>
/// Directly accesses the underlying image buffer of the InfraredFrame to
/// create a displayable bitmap.
/// This function requires the /unsafe compiler option as we make use of direct
/// access to the native memory pointed to by the infraredFrameData pointer.
/// </summary>
/// <param name="infraredFrameData">Pointer to the InfraredFrame image data</param>
/// <param name="infraredFrameDataSize">Size of the InfraredFrame image data</param>
private unsafe void ProcessInfraredFrameData(IntPtr infraredFrameData, uint infraredFrameDataSize)
{
// infrared frame data is a 16 bit value
ushort* frameData = (ushort*)infraredFrameData;
// lock the target bitmap
this.infraredBitmap.Lock();
// get the pointer to the bitmap's back buffer
float* backBuffer = (float*)this.infraredBitmap.BackBuffer;
if (checkBox.IsChecked.HasValue && checkBox.IsChecked.Value)
{
int detection_count = magic.ProcessFrame(frameData, infraredFrameDataSize, infraredFrameDescription, captureSpellOption.IsChecked.Value, spellNameBox.Text);
var data = (float*)magic.traceCanvas.Data;
for (int i = 0; i < (int)(infraredFrameDataSize / this.infraredFrameDescription.BytesPerPixel); ++i)
{
backBuffer[i] = (float)data[i];
}
//this.detection_counter.Text = detection_count.ToString();
}
else
{
// process the infrared data
for (int i = 0; i < (int)(infraredFrameDataSize / this.infraredFrameDescription.BytesPerPixel); ++i)
{
// since we are displaying the image as a normalized grey scale image, we need to convert from
// the ushort data (as provided by the InfraredFrame) to a value from [InfraredOutputValueMinimum, InfraredOutputValueMaximum]
backBuffer[i] = Math.Min(InfraredOutputValueMaximum, (((float)frameData[i] / InfraredSourceValueMaximum * InfraredSourceScale) * (1.0f - InfraredOutputValueMinimum)) + InfraredOutputValueMinimum);
}
}
// mark the entire bitmap as needing to be drawn
this.infraredBitmap.AddDirtyRect(new Int32Rect(0, 0, this.infraredBitmap.PixelWidth, this.infraredBitmap.PixelHeight));
// unlock the bitmap
this.infraredBitmap.Unlock();
}
/// <summary>
/// Handles the event which the sensor becomes unavailable (E.g. paused, closed, unplugged).
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void Sensor_IsAvailableChanged(object sender, IsAvailableChangedEventArgs e)
{
// set the status text
this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
: Properties.Resources.SensorNotAvailableStatusText;
}
private async void OnTextClick(object sender, RoutedEventArgs e)
{
await magic.gameController.TriggerSpell(Spell.Lumos);
}
private bool is_grabbing = false;
private async void GrabControlButton_Click(object sender, RoutedEventArgs e)
{
if (magic.gameController.machine.State != State.Waiting)
{
return;
}
if (!is_grabbing)
{
is_grabbing = true;
State target_state = (State)Enum.Parse(typeof(State), ((ComboBoxItem)GrabControlOption.SelectedItem).Tag.ToString());
await magic.gameController.ManualStartGrab(target_state);
}
else
{
is_grabbing = false;
await magic.gameController.ManualFinishGrab();
}
}
}
}