GLCanvas.m 14.1 KB
Newer Older
1 2 3 4

#import "RCTBridge.h"
#import "RCTUtils.h"
#import "RCTConvert.h"
5
#import "RCTEventDispatcher.h"
6
#import "RCTLog.h"
Dima's avatar
Dima committed
7
#import "RCTProfile.h"
8
#import "RNGLContext.h"
9 10 11 12 13
#import "GLCanvas.h"
#import "GLShader.h"
#import "GLTexture.h"
#import "GLImage.h"
#import "GLRenderData.h"
14
#import "UIView+React.h"
15

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
16 17 18 19 20 21 22 23 24 25 26 27 28
NSString* srcResource (id res)
{
  NSString *src;
  if ([res isKindOfClass:[NSString class]]) {
    src = [RCTConvert NSString:res];
  } else {
    BOOL isStatic = [RCTConvert BOOL:res[@"isStatic"]];
    src = [RCTConvert NSString:res[@"path"]];
    if (!src || isStatic) src = [RCTConvert NSString:res[@"uri"]];
  }
  return src;
}

29 30 31 32 33 34 35 36 37 38
NSArray* diff (NSArray* a, NSArray* b) {
  NSMutableArray *arr = [[NSMutableArray alloc] init];
  for (NSString* k in a) {
    if (![b containsObject:k]) {
      [arr addObject:k];
    }
  }
  return arr;
}

39 40 41 42
// For reference, see implementation of gl-shader's GLCanvas

@implementation GLCanvas
{
43
  RCTBridge *_bridge;
44

45
  GLRenderData *_renderData;
46

47
  BOOL _captureFrameRequested;
48

49
  NSArray *_contentData;
50
  NSArray *_contentTextures;
51
  NSDictionary *_images; // This caches the currently used images (imageSrc -> GLReactImage)
52

53
  BOOL _opaque; // opaque prop (if false, the GLCanvas will become transparent)
54

55
  BOOL _deferredRendering; // This flag indicates a render has been deferred to the next frame (when using contents)
56

57
  GLint defaultFBO;
58

59
  NSMutableArray *_preloaded;
60 61
  BOOL _dirtyOnLoad;
  BOOL _neverRendered;
62

63
  NSTimer *animationTimer;
64

65
  BOOL _needSync;
66 67 68 69 70 71 72
}

- (instancetype)initWithBridge:(RCTBridge *)bridge
{
  if ((self = [super init])) {
    _bridge = bridge;
    _images = @{};
73
    _preloaded = [[NSMutableArray alloc] init];
74
    _captureFrameRequested = false;
75 76
    _dirtyOnLoad = true;
    _neverRendered = true;
77
    self.context = [bridge.rnglContext getContext];
78 79 80 81 82 83
  }
  return self;
}

RCT_NOT_IMPLEMENTED(-init)

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
84 85
//// Props Setters

86
- (void) requestCaptureFrame
87
{
88
  _captureFrameRequested = true;
89 90 91
  [self setNeedsDisplay];
}

92 93 94
-(void)setImagesToPreload:(NSArray *)imagesToPreload
{
  _imagesToPreload = imagesToPreload;
95
  [self requestSyncData];
96
}
97 98 99 100 101 102 103

- (void)setOpaque:(BOOL)opaque
{
  _opaque = opaque;
  [self setNeedsDisplay];
}

104 105
- (void)setRenderId:(NSNumber *)renderId
{
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
106
  if ([_nbContentTextures intValue] > 0) {
107 108 109 110
    [self setNeedsDisplay];
  }
}

111 112
- (void)setAutoRedraw:(BOOL)autoRedraw
{
113
  _autoRedraw = autoRedraw;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
114 115 116 117 118 119
  [self performSelectorOnMainThread:@selector(syncAutoRedraw) withObject:nil waitUntilDone:false];
}

- (void)syncAutoRedraw
{
  if (_autoRedraw) {
120
    if (!animationTimer)
121
      animationTimer =
122 123
      [NSTimer scheduledTimerWithTimeInterval:1.0/60.0
                                       target:self
124
                                     selector:@selector(autoRedrawUpdate)
125 126 127 128 129 130 131 132 133 134
                                     userInfo:nil
                                      repeats:YES];
  }
  else {
    if (animationTimer) {
      [animationTimer invalidate];
    }
  }
}

135
- (void)setPointerEvents:(RCTPointerEvents)pointerEvents
136
{
137 138 139 140
  self.userInteractionEnabled = (pointerEvents != RCTPointerEventsNone);
  if (pointerEvents == RCTPointerEventsBoxNone) {
    self.accessibilityViewIsModal = NO;
  }
141 142
}

143 144 145 146 147 148
- (void)setPixelRatio:(NSNumber *)pixelRatio
{
  self.contentScaleFactor = [pixelRatio floatValue];
  [self setNeedsDisplay];
}

149 150 151
- (void)setData:(GLData *)data
{
  _data = data;
152
  _renderData = nil;
153 154 155
  [self requestSyncData];
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
156 157 158 159 160 161 162
- (void)setNbContentTextures:(NSNumber *)nbContentTextures
{
  _nbContentTextures = nbContentTextures;
}

//// Sync methods (called from props setters)

163 164
- (void)requestSyncData
{
165 166
  _needSync = true;
  [self setNeedsDisplay];
167 168 169 170 171
}

- (void)syncData
{
  @autoreleasepool {
172

173 174
    NSDictionary *prevImages = _images;
    NSMutableDictionary *images = [[NSMutableDictionary alloc] init];
175

176 177 178
    GLRenderData * (^traverseTree) (GLData *data);
    __block __weak GLRenderData * (^weak_traverseTree)(GLData *data);
    weak_traverseTree = traverseTree = ^GLRenderData *(GLData *data) {
179 180
      NSNumber *width = data.width;
      NSNumber *height = data.height;
181
      int fboId = [data.fboId intValue];
182

183 184
      NSMutableArray *contextChildren = [[NSMutableArray alloc] init];
      for (GLData *child in data.contextChildren) {
185 186 187
        GLRenderData *node = weak_traverseTree(child);
        if (node == nil) return nil;
        [contextChildren addObject:node];
188
      }
189

190 191
      NSMutableArray *children = [[NSMutableArray alloc] init];
      for (GLData *child in data.children) {
192 193 194
        GLRenderData *node = weak_traverseTree(child);
        if (node == nil) return nil;
        [children addObject:node];
195
      }
196

197
      GLShader *shader = [_bridge.rnglContext getShader:data.shader];
198
      if (shader == nil) return nil;
199

200 201 202 203 204 205 206
      NSDictionary *uniformTypes = [shader uniformTypes];
      NSMutableDictionary *uniforms = [[NSMutableDictionary alloc] init];
      NSMutableDictionary *textures = [[NSMutableDictionary alloc] init];
      int units = 0;
      for (NSString *uniformName in data.uniforms) {
        id value = [data.uniforms objectForKey:uniformName];
        GLenum type = [uniformTypes[uniformName] intValue];
207 208


209
        if (type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE) {
210
          uniforms[uniformName] = [NSNumber numberWithInt:units++];
211
          if ([value isEqual:[NSNull null]]) {
212
            GLTexture *emptyTexture = [[GLTexture alloc] init];
213
            [emptyTexture setPixels:nil];
214
            textures[uniformName] = emptyTexture;
215
          }
216 217 218 219 220 221 222 223
          else {
            NSString *type = [RCTConvert NSString:value[@"type"]];
            if ([type isEqualToString:@"content"]) {
              int id = [[RCTConvert NSNumber:value[@"id"]] intValue];
              if (id >= [_contentTextures count]) {
                [self resizeUniformContentTextures:id+1];
              }
              textures[uniformName] = _contentTextures[id];
224
            }
225 226
            else if ([type isEqualToString:@"fbo"]) {
              NSNumber *id = [RCTConvert NSNumber:value[@"id"]];
227
              GLFBO *fbo = [_bridge.rnglContext getFBO:id];
228 229 230 231 232 233 234
              textures[uniformName] = fbo.color[0];
            }
            else if ([type isEqualToString:@"uri"]) {
              NSString *src = srcResource(value);
              if (!src) {
                RCTLogError(@"texture uniform '%@': Invalid uri format '%@'", uniformName, value);
              }
235

236 237 238 239 240 241 242
              GLImage *image = images[src];
              if (image == nil) {
                image = prevImages[src];
                if (image != nil)
                  images[src] = image;
              }
              if (image == nil) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
243
                __weak GLCanvas *weakSelf = self;
244
                image = [[GLImage alloc] initWithBridge:_bridge withOnLoad:^{
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
245
                  if (weakSelf) [weakSelf onImageLoad:src];
246 247
                }];
                image.src = src;
248
                images[src] = image;
249 250
              }
              textures[uniformName] = [image getTexture];
251
            }
252 253
            else {
              RCTLogError(@"texture uniform '%@': Unexpected type '%@'", uniformName, type);
254 255 256 257 258 259 260
            }
          }
        }
        else {
          uniforms[uniformName] = value;
        }
      }
261

262 263 264 265 266
      int maxTextureUnits;
      glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
      if (units > maxTextureUnits) {
        RCTLogError(@"Maximum number of texture reach. got %i >= max %i", units, maxTextureUnits);
      }
267

268 269 270 271 272
      for (NSString *uniformName in shader.uniformTypes) {
        if (uniforms[uniformName] == nil) {
          RCTLogError(@"All defined uniforms must be provided. Missing '%@'", uniformName);
        }
      }
273

274 275 276 277 278 279 280 281
      return [[GLRenderData alloc]
              initWithShader:shader
              withUniforms:uniforms
              withTextures:textures
              withWidth:width
              withHeight:height
              withFboId:fboId
              withContextChildren:contextChildren
282
              withChildren:children];
283
    };
284

285 286
    GLRenderData *res = traverseTree(_data);
    if (res != nil) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
287
      _needSync = false;
288 289
      _renderData = traverseTree(_data);
      _images = images;
290 291 292
      for (NSString *src in diff([prevImages allKeys], [images allKeys])) {
        [_preloaded removeObject:src];
      }
293
    }
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
294 295 296
    else {
      // the data is not ready, retry in one tick
      [self setNeedsDisplay];
297
    }
298 299 300
  }
}

301
- (void)syncContentData
302
{
303
  RCT_PROFILE_BEGIN_EVENT(0, @"GLCanvas syncContentData", nil);
304 305 306 307 308
  NSMutableArray *contentData = [[NSMutableArray alloc] init];
  int nb = [_nbContentTextures intValue];
  for (int i = 0; i < nb; i++) {
    UIView *view = self.superview.subviews[i]; // We take siblings by index (closely related to the JS code)
    GLImageData *imgData = nil;
309
    if (view) {
310 311 312
      UIView *v = [view.subviews count] == 1 ?
      view.subviews[0] :
      view;
313
      imgData = [GLImageData genPixelsWithView:v withPixelRatio:self.contentScaleFactor];
314
    } else {
315
      imgData = nil;
316
    }
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
317
    if (imgData) contentData[i] = imgData;
318 319
  }
  _contentData = contentData;
320
  _deferredRendering = false;
321 322
  [self setNeedsDisplay];
  RCT_PROFILE_END_EVENT(0, @"gl", nil);
323 324 325 326 327 328 329 330
}


- (void)syncContentTextures
{
  unsigned long max = MIN([_contentData count], [_contentTextures count]);
  for (int i=0; i<max; i++) {
    [_contentTextures[i] setPixels:_contentData[i]];
331 332 333
  }
}

334 335 336 337 338 339 340 341 342 343
- (BOOL)haveRemainingToPreload
{
  for (id res in _imagesToPreload) {
    if (![_preloaded containsObject:srcResource(res)]) {
      return true;
    }
  }
  return false;
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
344 345 346

//// Draw

347
- (void) autoRedrawUpdate
348
{
349 350 351 352 353
  if ([self haveRemainingToPreload]) {
    return;
  }
  if ([_nbContentTextures intValue] > 0) {
    [self syncContentData];
354
  }
355 356 357
  [self setNeedsDisplay];
}

358 359
- (void)drawRect:(CGRect)rect
{
360
  self.layer.opaque = _opaque;
361

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
362 363
  if (_neverRendered) {
    _neverRendered = false;
364 365
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT);
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
366
  }
367

368 369 370
  if (_needSync) {
    [self syncData];
  }
371

372
  if ([self haveRemainingToPreload]) {
373 374
    return;
  }
375

376
  bool willRender = !_deferredRendering;
377

378
  if ([_nbContentTextures intValue] > 0 && !_autoRedraw) {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
379
    _deferredRendering = true;
380
    [self performSelectorOnMainThread:@selector(syncContentData) withObject:nil waitUntilDone:NO];
381
  }
382

383
  if (willRender) {
384
    [self render];
385 386
    if (_captureFrameRequested) {
      _captureFrameRequested = false;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
387
      [self performSelectorOnMainThread:@selector(capture) withObject:nil waitUntilDone:NO];
388
    }
389 390 391
  }
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
392 393 394 395 396 397 398 399 400 401
-(void)capture
{
  UIImage *frameImage = [self snapshot];
  NSData *frameData = UIImagePNGRepresentation(frameImage);
  NSString *frame =
  [NSString stringWithFormat:@"data:image/png;base64,%@",
   [frameData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
  if (self.onGLCaptureFrame) self.onGLCaptureFrame(@{ @"frame": frame });
}

402
- (void)render
403
{
404 405
  GLRenderData *rd = _renderData;
  if (!rd) return;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
406
  RCT_PROFILE_BEGIN_EVENT(0, @"GLCanvas render", nil);
407
  CGFloat scale = self.contentScaleFactor;
408

409
  @autoreleasepool {
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
410
    CGFloat scale = RCTScreenScale();
411

412 413 414 415 416
    void (^recDraw) (GLRenderData *renderData);
    __block __weak void (^weak_recDraw) (GLRenderData *renderData);
    weak_recDraw = recDraw = ^void(GLRenderData *renderData) {
      float w = [renderData.width floatValue] * scale;
      float h = [renderData.height floatValue] * scale;
417

418 419
      for (GLRenderData *child in renderData.contextChildren)
        weak_recDraw(child);
420

421
      for (GLRenderData *child in renderData.children)
422
        weak_recDraw(child);
423

424
      if (renderData.fboId == -1) {
425 426 427 428
        glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
        glViewport(0, 0, w, h);
      }
      else {
429
        GLFBO *fbo = [_bridge.rnglContext getFBO:[NSNumber numberWithInt:renderData.fboId]];
430 431 432
        [fbo setShapeWithWidth:w withHeight:h];
        [fbo bind];
      }
433

434
      [renderData.shader bind];
435

436 437 438 439 440
      for (NSString *uniformName in renderData.textures) {
        GLTexture *texture = renderData.textures[uniformName];
        int unit = [((NSNumber *)renderData.uniforms[uniformName]) intValue];
        [texture bind:unit];
      }
441

442 443 444
      for (NSString *uniformName in renderData.uniforms) {
        [renderData.shader setUniform:uniformName withValue:renderData.uniforms[uniformName]];
      }
445

446
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
447 448
      glClearColor(0.0, 0.0, 0.0, 0.0);
      glClear(GL_COLOR_BUFFER_BIT);
449 450
      glDrawArrays(GL_TRIANGLES, 0, 6);
    };
451

452
    // DRAWING THE SCENE
453

454
    [self syncContentTextures];
455

456
    glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
457
    glEnable(GL_BLEND);
458
    recDraw(rd);
459
    glDisable(GL_BLEND);
460
    glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
461
    glBindBuffer(GL_ARRAY_BUFFER, 0);
462

463 464 465 466
    if (_dirtyOnLoad && ![self haveRemainingToPreload]) {
      _dirtyOnLoad = false;
      [self dispatchOnLoad];
    }
467
  }
468

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
469
  RCT_PROFILE_END_EVENT(0, @"gl", nil);
470 471
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
472 473 474 475
//// utility methods

- (void)onImageLoad:(NSString *)loaded
{
476 477 478 479 480 481 482
  [_preloaded addObject:loaded];
  int count = [self countPreloaded];
  int total = (int) [_imagesToPreload count];
  double progress = ((double) count) / ((double) total);
  [self dispatchOnProgress:progress withLoaded:count withTotal:total];
  _dirtyOnLoad = true;
  [self requestSyncData];
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
483 484 485 486 487 488 489 490 491 492 493
}

- (int)countPreloaded
{
  int nb = 0;
  for (id toload in _imagesToPreload) {
    if ([_preloaded containsObject:srcResource(toload)])
      nb++;
  }
  return nb;
}
494

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
- (void)resizeUniformContentTextures:(int)n
{
  int length = (int) [_contentTextures count];
  if (length == n) return;
  if (n < length) {
    _contentTextures = [_contentTextures subarrayWithRange:NSMakeRange(0, n)];
  }
  else {
    NSMutableArray *contentTextures = [[NSMutableArray alloc] initWithArray:_contentTextures];
    for (int i = (int) [_contentTextures count]; i < n; i++) {
      [contentTextures addObject:[[GLTexture alloc] init]];
    }
    _contentTextures = contentTextures;
  }
}

- (void)dispatchOnLoad
{
513
  if (self.onGLLoad) self.onGLLoad(@{});
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
514 515 516 517
}

- (void)dispatchOnProgress: (double)progress withLoaded:(int)loaded withTotal:(int)total
{
518
  if (self.onGLProgress) self.onGLProgress(
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
519 520 521 522 523
                                           @{
                                             @"progress": @(RCTZeroIfNaN(progress)),
                                             @"loaded": @(RCTZeroIfNaN(loaded)),
                                             @"total": @(RCTZeroIfNaN(total))
                                             });
524 525
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
526
@end