Source

kinect-viewer / KVDepthView.m

Full commit
  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
/*
 * Copyright 2010 Cliff L. Biffle.  All Rights Reserved.
 * Use of this source code is governed by the Apache License 2.0,
 * which can be found in the LICENSE file.
 */

#import "KVDepthView.h"
#import "KVSpaceModel.h"
#import "KVRayFieldSpaceModel.h"
#import "trackball.h"
#import "utility.h"

@interface KVDepthView ()
- (void) resetCamera;
- (void) resizeGL;
- (void) updateProjection;
- (void) updateModelView;
- (void) updateColorTransform;

@property(assign, nonatomic) BOOL updateQueued;
- (void) requestUpdateFromBackgroundThread;
- (void) markAsDirty;

@end

@implementation KVDepthView
#pragma mark --- Properties ---

@synthesize updateQueued;

@synthesize lightsOn;

- (void) setLightsOn: (BOOL)flag {
  lightsOn = flag;
  
  [[self openGLContext] makeCurrentContext];
  if (flag) {
    glEnable(GL_LIGHTING);
  } else {
    glDisable(GL_LIGHTING);
  }
  [self setNeedsDisplay: YES];  
}

@synthesize textured;
@synthesize spaceModel;

@synthesize colorTransform;
- (void) setColorTransform: (projective_transform_t)newTransform {
  colorTransform = newTransform;
  [self setNeedsDisplay: YES];
}

- (void) updateColorTransform {
  // A bit of a hack, but it triggers automatic KVO and the setter above.
  self.colorTransform = colorTransform;
}

@synthesize frozen;
@synthesize anaglyph;
@synthesize recording;
@synthesize polygonMode;

#pragma mark --- Trivial NSView Overrides ---

- (BOOL) acceptsFirstResponder {
  return YES;
}

- (BOOL) becomeFirstResponder {
  return YES;
}

- (BOOL) resignFirstResponder {
  return YES;
}

#pragma mark --- Initialization ---

- (void) awakeFromNib {
  deviceWhite = [[NSColor colorWithDeviceRed: 1.F green: 1.F blue: 1.F alpha: 1.F] retain];
  
  self.colorTransform = (projective_transform_t) {
    .offset = { 14, 40, 0 },
    .scale = { 0.92F, 0.92F },
  };
  
  self.spaceModel = [[[KVRayFieldSpaceModel alloc] init] autorelease];
  self.polygonMode = KVFilledPolygonMode;
}

#pragma mark --- GL Stuff ---

- (void) prepareOpenGL {
  // Sync to vertical blank.
  GLint swapInterval = 1;
  [[self openGLContext] setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  
  // GL state initialization
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);
  glFrontFace(GL_CCW);
  glShadeModel(GL_SMOOTH);
  
  glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.05F);
  
  GLfloat ambientColor[4] = { 0, 0, 0, 1 };
  glLightfv(GL_LIGHT0, GL_AMBIENT, ambientColor);
  
  GLfloat diffuseColor[4] = { 1.f, 1.0f, 1.0f, 1.0f };
  glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseColor);
  
  GLfloat globalAmbient[4] = { 0.1f, 0.1f, 0.1f, 1.0f };
  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbient);
  
  glEnable(GL_NORMALIZE);
  glEnable(GL_LIGHT0);
  
  glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
  glEnable(GL_COLOR_MATERIAL);
  
  glClearColor(0, 0, 0, 0);
  
  [self resetCamera];
}

- (void) resetCamera {
  camera = (camera_t) {
    .fov = 57,
    .pivot = { 0, 0, 0 },
    .pos = { 0, 0, -3 },
    .target = { 0, 0, 0 },
    .up = { 0, 1, 0 },
  };
}

- (void) resizeGL {
  NSRect bounds = [self bounds];
  
  // Note: this always happens on the first drawing call.
  if (camera.viewHeight != bounds.size.height
      || camera.viewWidth != bounds.size.width) {
    camera.viewHeight = (float) bounds.size.height;
    camera.viewWidth = (float) bounds.size.width;
    
    glViewport(0, 0, camera.viewWidth, camera.viewHeight);
    [self updateProjection];
  }
}

#define MAXIMUM_DEPTH (16.0F)

- (void) updateProjection {
  [[self openGLContext] makeCurrentContext];
  
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  
  GLdouble near = -camera.pos.z - MAXIMUM_DEPTH;  
  GLdouble far = -camera.pos.z + MAXIMUM_DEPTH * 16;
  
  // I do not fully understand this.
  if (near < 0.0001) near = 0.0001;
  if (far < 1.0) far = 1.0;
  
  GLdouble aspectRatio = camera.viewWidth / (GLdouble) camera.viewHeight;
  
  gluPerspective(camera.fov / aspectRatio, aspectRatio, near, far);
}

- (void) updateModelView {
  [[self openGLContext] makeCurrentContext];
  
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  
  gluLookAt(camera.pos.x, camera.pos.y, camera.pos.z,
            camera.target.x, camera.target.y, camera.target.z,
            camera.up.x, camera.up.y, camera.up.z);
  
  glRotatef(trackballRotation[0], trackballRotation[1], trackballRotation[2], trackballRotation[3]);
  glRotatef(worldRotation[0], worldRotation[1], worldRotation[2], worldRotation[3]);
  glRotatef(spinY, 0, 1, 0);
  glRotatef(spinX, 1, 0, 0);
  
  GLfloat lightPos[4] = { 0, 0, -1, 1 };
  glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
}

#define INTEROCULAR_DISTANCE (0.0635F/1)
- (void) drawRect: (NSRect)dirtyRect {
  [self resizeGL];
    
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  
  NSDictionary *options = [NSDictionary dictionaryWithObject: self.polygonMode forKey: KVPolygonMode];
  
  if (self.anaglyph) {
    camera.pos.x -= INTEROCULAR_DISTANCE / 2;

    glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
  }
  
  // Draw right eye or center.
  [self updateModelView];
  [spaceModel drawInCurrentOpenGLContextWithOptions: options];
  
  if (self.anaglyph) {
    // Draw left eye.
    glClear(GL_DEPTH_BUFFER_BIT);
    
    camera.pos.x += INTEROCULAR_DISTANCE;
    
    glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE);
    [self updateModelView];
    [spaceModel drawInCurrentOpenGLContextWithOptions: options];
    
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    
    camera.pos.x -= INTEROCULAR_DISTANCE / 2;
  }
  
  [[self openGLContext] flushBuffer];
  self.updateQueued = NO;
}

- (void) requestUpdateFromBackgroundThread {
  @synchronized (self) {
    if (!self.updateQueued) {
      self.updateQueued = YES;
      [self performSelectorOnMainThread: @selector(markAsDirty) withObject: nil waitUntilDone: NO];
    }
  }
}

- (void) markAsDirty {
  [self setNeedsDisplay: YES];
}

#pragma mark --- User Interaction ---

- (void) mouseDown: (NSEvent *)theEvent {
  NSPoint location = [self convertPoint: [theEvent locationInWindow] fromView: nil];
  location.y = camera.viewHeight - location.y;  // Flip Y axis
  usingTrackball = YES;
  startTrackball(location.x, location.y, 0, 0, camera.viewWidth, camera.viewHeight);
}

- (void) mouseUp: (NSEvent *)theEvent {
  if (usingTrackball) {
    usingTrackball = NO;
    addToRotationTrackball(trackballRotation, worldRotation);
    for (int i = 0; i < 4; i++) trackballRotation[i] = 0;
  }
}

- (void) mouseDragged: (NSEvent *)theEvent {
  NSPoint location = [self convertPoint: [theEvent locationInWindow] fromView: nil];
  location.y = camera.viewHeight - location.y;  // Flip Y axis

  if (usingTrackball) {
    rollToTrackball(location.x, location.y, trackballRotation);
    [self setNeedsDisplay: YES];
  }
}

#define SCROLL_SPEED (50.F)

- (void) scrollWheel: (NSEvent *)theEvent {
  float deltaV = (float) [theEvent deltaY];
  BOOL changes = NO;
  if (deltaV) {
    if ([theEvent modifierFlags] & NSCommandKeyMask) {
      camera.pos.z -= deltaV / SCROLL_SPEED;
      camera.target.z -= deltaV / SCROLL_SPEED;
    } else {
      camera.pos.y -= deltaV / SCROLL_SPEED;
      camera.target.y -= deltaV / SCROLL_SPEED;
    }
    changes = YES;
  }
  
  float deltaH = (float) [theEvent deltaX];
  if (deltaH) {
    camera.pos.x -= deltaH / SCROLL_SPEED;
    camera.target.x -= deltaH / SCROLL_SPEED;
    changes = YES;
  }
  
  if (changes) {
    [self updateProjection];
    [self setNeedsDisplay: YES];
  }
}

- (void) magnifyWithEvent: (NSEvent *)theEvent {
  float mag = (float) [theEvent magnification];
  camera.pos.z += mag;
  camera.target.z += mag;
  [self updateProjection];
  [self setNeedsDisplay: YES];
}

-(void)keyDown: (NSEvent *)theEvent
{
  NSString *characters = [theEvent characters];
  if ([characters length]) {
    unichar character = [characters characterAtIndex:0];
		switch (character) {
			case 'a':
				spinY += 10;
				[self setNeedsDisplay: YES];
				break;
			case 'd':
				spinY -= 10;
				[self setNeedsDisplay: YES];
				break;
			case 'w':
				spinX += 10;
				[self setNeedsDisplay: YES];
				break;
			case 's':
				spinX -= 10;
				[self setNeedsDisplay: YES];
				break;
        
      // Camera origin control
      case 'i':
        colorTransform.offset.y -= 1;
        [self updateColorTransform];
        break;
        
      case 'k':
        colorTransform.offset.y += 1;
        [self updateColorTransform];
        break;

      case 'j':
        colorTransform.offset.x -= 1;
        [self updateColorTransform];
        break;
        
      case 'l':
        colorTransform.offset.x += 1;
        [self updateColorTransform];
        break;
        
      case 'h':
        colorTransform.offset.z -= 1.F/100.F;
        [self updateColorTransform];
        break;

      case 'y':
        colorTransform.offset.z += 1.F/100.F;
        [self updateColorTransform];
        break;
        
      // Scale control
      case 'n':
        colorTransform.scale.x -= 0.01F;
        [self updateColorTransform];
        break;
        
      case 'm':
        colorTransform.scale.x += 0.01F;
        [self updateColorTransform];
        break;
        
      case ',':
        colorTransform.scale.y -= 0.01F;
        [self updateColorTransform];
        break;
        
      case '.':
        colorTransform.scale.y += 0.01F;
        [self updateColorTransform];
        break;
		}
	}
}

#pragma mark --- Actions ---

- (IBAction) selectPointCloudRenderer: sender {
  self.polygonMode = KVDottedPolygonMode;
  [self setNeedsDisplay: YES];
}

- (IBAction) selectMeshRenderer: sender {
  self.polygonMode = KVWireframePolygonMode;
  [self setNeedsDisplay: YES];
}

- (IBAction) selectSolidRenderer: sender {
  self.polygonMode = KVFilledPolygonMode;
  [self setNeedsDisplay: YES];
}

- (IBAction) toggleDepthFieldUpdates: sender {
  self.frozen = !self.frozen;
  [sender setState: self.frozen? NSOnState : NSOffState];
}

- (IBAction) toggleLighting: sender {
  self.lightsOn = !lightsOn;
  [sender setState: lightsOn? NSOnState : NSOffState];
}

- (IBAction) toggleRecording: sender {
  if (recording) {
    @synchronized(self) {
      fclose(depthOutput);
      depthOutput = NULL;
      recording = NO;
    }
    [sender setState: NSOffState];
  } else {
    @synchronized(self) {
      depthOutput = fopen("/tmp/depth-recording.bin", "wb");
      recording = YES;
    }
    [sender setState: NSOnState];
  }
}

- (IBAction) toggleAnaglyph: sender {
  self.anaglyph = !self.anaglyph;
  [self setNeedsDisplay: YES];
}

- (IBAction) toggleTextures: sender {
  self.textured = !textured;
  [self setNeedsDisplay: YES];
  [sender setState: textured? NSOnState : NSOffState];
}

#pragma mark --- KFKinect Delegate Implementation ---

- (void) depthFieldUpdated: (const depth_t *)buffer from: (KFKinect *)kinect {
  @synchronized (self) {
    if (recording) {
      fwrite(buffer, sizeof(uint16_t), 640*480, depthOutput);
    }
  }
      
  if (!self.frozen) {
    [spaceModel setDepthSamples: [NSData dataWithBytesNoCopy: (void *) buffer length: sizeof *buffer freeWhenDone: NO]];
    [self setNeedsDisplay: YES];
  }
}

- (void) colorFieldUpdated: (const colors_t *)buffer from: (KFKinect *)kinect {
  if (!self.frozen) {
    [spaceModel setColorSamples: [NSData dataWithBytesNoCopy: (void *) buffer length: sizeof *buffer freeWhenDone: NO]];
    [self setNeedsDisplay: YES];
  }
}

@end