GLCanvas.m 13.6 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 29

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;
}

30 31 32 33
// For reference, see implementation of gl-shader's GLCanvas

@implementation GLCanvas
{
34
  RCTBridge *_bridge;
35
  
36
  GLRenderData *_renderData;
37 38
    
  NSMutableArray *_captureListeners;
39
  
40
  NSArray *_contentTextures;
41 42 43 44
  NSDictionary *_images; // This caches the currently used images (imageSrc -> GLReactImage)
  
  BOOL _opaque; // opaque prop (if false, the GLCanvas will become transparent)
  
45
  BOOL _deferredRendering; // This flag indicates a render has been deferred to the next frame (when using contents)
46 47
  
  GLint defaultFBO;
48 49 50
  
  NSMutableArray *_preloaded;
  BOOL _preloadingDone;
51 52
  
  NSTimer *animationTimer;
53
      
54
    BOOL _needSync;
55 56 57 58 59 60 61
}

- (instancetype)initWithBridge:(RCTBridge *)bridge
{
  if ((self = [super init])) {
    _bridge = bridge;
    _images = @{};
62
    _preloaded = [[NSMutableArray alloc] init];
63
    _captureListeners = [[NSMutableArray alloc] init];
64
    _preloadingDone = false;
65
    self.context = [bridge.rnglContext getContext];
66
    self.contentScaleFactor = RCTScreenScale();
67 68 69 70 71 72
  }
  return self;
}

RCT_NOT_IMPLEMENTED(-init)

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
73 74
//// Props Setters

75 76 77 78 79 80
- (void) capture:(RCTResponseSenderBlock)callback
{
  [_captureListeners addObject:callback];
  [self setNeedsDisplay];
}

81 82 83 84
-(void)setImagesToPreload:(NSArray *)imagesToPreload
{
  if (_preloadingDone) return;
  if ([imagesToPreload count] == 0) {
85
    [self dispatchOnLoad];
86 87
    _preloadingDone = true;
  }
88 89 90
  else {
    _preloadingDone = false;
  }
91 92
  _imagesToPreload = imagesToPreload;
}
93 94 95 96 97 98 99

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

100 101
- (void)setRenderId:(NSNumber *)renderId
{
102
  if (_nbContentTextures > 0) {
103 104 105 106
    [self setNeedsDisplay];
  }
}

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
- (void)setAutoRedraw:(BOOL)autoRedraw
{
  if (autoRedraw) {
    if (!animationTimer)
      animationTimer = // FIXME: can we do better than this?
      [NSTimer scheduledTimerWithTimeInterval:1.0/60.0
                                       target:self
                                     selector:@selector(setNeedsDisplay)
                                     userInfo:nil
                                      repeats:YES];
  }
  else {
    if (animationTimer) {
      [animationTimer invalidate];
    }
  }
}

- (void)setEventsThrough:(BOOL)eventsThrough
{
127
  _eventsThrough = eventsThrough;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
128
  [self syncEventsThrough];
129 130 131 132 133
}

-(void)setVisibleContent:(BOOL)visibleContent
{
  _visibleContent = visibleContent;
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
134
  [self syncEventsThrough];
135 136
}

137 138 139 140 141 142
- (void)setData:(GLData *)data
{
  _data = data;
  [self requestSyncData];
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156
- (void)setNbContentTextures:(NSNumber *)nbContentTextures
{
  [self resizeUniformContentTextures:[nbContentTextures intValue]];
  _nbContentTextures = nbContentTextures;
}

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

- (void) syncEventsThrough
{
  self.userInteractionEnabled = !(_eventsThrough);
  self.superview.userInteractionEnabled = !(_eventsThrough && !_visibleContent);
}

157 158
- (void)requestSyncData
{
159 160
    _needSync = true;
    [self setNeedsDisplay];
161 162 163 164 165 166
}

- (void)syncData
{
  [EAGLContext setCurrentContext:self.context];
  @autoreleasepool {
167
    
168 169 170
    NSDictionary *prevImages = _images;
    NSMutableDictionary *images = [[NSMutableDictionary alloc] init];
    
171 172 173
    GLRenderData * (^traverseTree) (GLData *data);
    __block __weak GLRenderData * (^weak_traverseTree)(GLData *data);
    weak_traverseTree = traverseTree = ^GLRenderData *(GLData *data) {
174 175
      NSNumber *width = data.width;
      NSNumber *height = data.height;
176 177 178 179 180 181
      int fboId = [data.fboId intValue];
      
      NSMutableArray *contextChildren = [[NSMutableArray alloc] init];
      for (GLData *child in data.contextChildren) {
        [contextChildren addObject:weak_traverseTree(child)];
      }
182 183 184
      
      NSMutableArray *children = [[NSMutableArray alloc] init];
      for (GLData *child in data.children) {
185
        [children addObject:weak_traverseTree(child)];
186 187
      }
      
188
      GLShader *shader = [_bridge.rnglContext getShader:data.shader];
189 190 191 192 193 194 195 196 197
      
      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];
        
198
          
199
        if (type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE) {
200
          uniforms[uniformName] = [NSNumber numberWithInt:units++];
201
          if ([value isEqual:[NSNull null]]) {
202 203 204
            GLTexture *emptyTexture = [[GLTexture alloc] init];
            [emptyTexture setPixelsEmpty];
            textures[uniformName] = emptyTexture;
205
          }
206 207 208 209 210 211 212 213
          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];
214
            }
215 216
            else if ([type isEqualToString:@"fbo"]) {
              NSNumber *id = [RCTConvert NSNumber:value[@"id"]];
217
              GLFBO *fbo = [_bridge.rnglContext getFBO:id];
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
              textures[uniformName] = fbo.color[0];
            }
            else if ([type isEqualToString:@"uri"]) {
              NSString *src = srcResource(value);
              if (!src) {
                RCTLogError(@"texture uniform '%@': Invalid uri format '%@'", uniformName, value);
              }
              
              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
233
                __weak GLCanvas *weakSelf = self;
234
                image = [[GLImage alloc] initWithBridge:_bridge withOnLoad:^{
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
235
                  if (weakSelf) [weakSelf onImageLoad:src];
236 237
                }];
                image.src = src;
238
                images[src] = image;
239 240
              }
              textures[uniformName] = [image getTexture];
241
            }
242 243
            else {
              RCTLogError(@"texture uniform '%@': Unexpected type '%@'", uniformName, type);
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
            }
          }
        }
        else {
          uniforms[uniformName] = value;
        }
      }
      
      int maxTextureUnits;
      glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
      if (units > maxTextureUnits) {
        RCTLogError(@"Maximum number of texture reach. got %i >= max %i", units, maxTextureUnits);
      }
      
      for (NSString *uniformName in shader.uniformTypes) {
        if (uniforms[uniformName] == nil) {
          RCTLogError(@"All defined uniforms must be provided. Missing '%@'", uniformName);
        }
      }
263
      
264 265 266 267 268 269 270 271
      return [[GLRenderData alloc]
              initWithShader:shader
              withUniforms:uniforms
              withTextures:textures
              withWidth:width
              withHeight:height
              withFboId:fboId
              withContextChildren:contextChildren
272
              withChildren:children];
273 274
    };
    
275
    _renderData = traverseTree(_data);
276 277 278 279
    _images = images;
  }
}

280
- (void)syncContentTextures
281 282
{
  int i = 0;
283
  for (GLTexture *texture in _contentTextures) {
284 285
    UIView* view = self.superview.subviews[i]; // We take siblings by index (closely related to the JS code)
    if (view) {
286 287 288 289
      if ([view.subviews count] == 1)
        [texture setPixelsWithView:view.subviews[0]];
      else
        [texture setPixelsWithView:view];
290 291 292 293 294 295 296
    } else {
      [texture setPixelsEmpty];
    }
    i ++;
  }
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
297 298 299

//// Draw

300 301
- (void)drawRect:(CGRect)rect
{
302 303 304 305
    if (_needSync) {
        _needSync = false;
        [self syncData];
    }
306 307
  self.layer.opaque = _opaque;
  [self syncEventsThrough];
308
  __weak GLCanvas *weakSelf = self;
309
  
310 311 312 313 314
  if (!_preloadingDone) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT);
    return;
  }
315
  BOOL needsDeferredRendering = _nbContentTextures > 0 && !_autoRedraw;
316 317
  if (needsDeferredRendering && !_deferredRendering) {
    dispatch_async(dispatch_get_main_queue(), ^{
318
      if (!weakSelf) return;
319
      _deferredRendering = true;
320
      [weakSelf setNeedsDisplay];
321 322 323
    });
  }
  else {
Dima's avatar
Dima committed
324
    RCTProfileBeginEvent(0, @"GLCanvas render", nil);
325
    [self render];
Dima's avatar
Dima committed
326
    RCTProfileEndEvent(0, @"gl", nil);
327
    _deferredRendering = false;
328 329 330 331 332 333
    
    unsigned long nbCaptureListeners = [_captureListeners count];
    if (nbCaptureListeners > 0) {
      NSArray *listeners = _captureListeners;
      _captureListeners = [[NSMutableArray alloc] init];
      
334 335 336 337 338 339 340
      dispatch_async(dispatch_get_main_queue(), ^{ // snapshot not allowed in render tick. defer it.
        if (!weakSelf) return;
        UIImage *frameImage = [weakSelf snapshot];
        NSData *frameData = UIImagePNGRepresentation(frameImage);
        NSString *frame =
        [NSString stringWithFormat:@"data:image/png;base64,%@",
         [frameData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
341 342 343 344
        for (int i = 0; i < nbCaptureListeners; i++) {
          RCTResponseSenderBlock listener = listeners[i];
          listener(@[[NSNull null], frame]);
        }
345 346
      });
    }
347 348 349
  }
}

350
- (void)render
351 352 353 354 355 356 357 358 359 360 361 362
{
  if (!_renderData) return;
  
  CGFloat scale = RCTScreenScale();
  
  @autoreleasepool {
    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;
      
363 364 365
      for (GLRenderData *child in renderData.contextChildren)
        weak_recDraw(child);
      
366
      for (GLRenderData *child in renderData.children)
367
        weak_recDraw(child);
368
      
369
      if (renderData.fboId == -1) {
370 371 372 373
        glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
        glViewport(0, 0, w, h);
      }
      else {
374
        GLFBO *fbo = [_bridge.rnglContext getFBO:[NSNumber numberWithInt:renderData.fboId]];
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        [fbo setShapeWithWidth:w withHeight:h];
        [fbo bind];
      }
      
      [renderData.shader bind];
      
      for (NSString *uniformName in renderData.textures) {
        GLTexture *texture = renderData.textures[uniformName];
        int unit = [((NSNumber *)renderData.uniforms[uniformName]) intValue];
        [texture bind:unit];
      }
      
      for (NSString *uniformName in renderData.uniforms) {
        [renderData.shader setUniform:uniformName withValue:renderData.uniforms[uniformName]];
      }
      
391
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
392 393
      glClearColor(0.0, 0.0, 0.0, 0.0);
      glClear(GL_COLOR_BUFFER_BIT);
394 395 396
      glDrawArrays(GL_TRIANGLES, 0, 6);
    };
    
397 398
    // DRAWING THE SCENE
    
399
    [self syncContentTextures];
400
    
401
    glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO);
402
    glEnable(GL_BLEND);
403 404
    recDraw(_renderData);
    glDisable(GL_BLEND);
405 406 407 408
    glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO);
  }
}

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
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
//// utility methods

- (void)onImageLoad:(NSString *)loaded
{
  if (!_preloadingDone) {
    [_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];
    if (count == total) {
      [self dispatchOnLoad];
      _preloadingDone = true;
      [self requestSyncData];
    }
  }
  else {
    // Any texture image load will trigger a future re-sync of data (if no preloaded)
    [self requestSyncData];
  }
}

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

Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
- (void)resizeUniformContentTextures:(int)n
{
  [EAGLContext setCurrentContext:self.context];
  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
{
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
460
  [_bridge.eventDispatcher sendInputEventWithName:@"load" body:@{ @"target": self.reactTag }];
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
461 462 463 464
}

- (void)dispatchOnProgress: (double)progress withLoaded:(int)loaded withTotal:(int)total
{
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
465 466 467 468 469 470 471
  NSDictionary *event =
  @{
    @"target": self.reactTag,
    @"progress": @(progress),
    @"loaded": @(loaded),
    @"total": @(total) };
  [_bridge.eventDispatcher sendInputEventWithName:@"progress" body:event];
Gaëtan Renaudeau's avatar
Gaëtan Renaudeau committed
472
}
473

474 475 476 477 478 479 480
- (void)dispatchOnCapture: (NSString *)frame withId:(int)id
{
  NSDictionary *event = @{ @"target": self.reactTag, @"frame": frame, @"id":@(id) };
  // FIXME: using onChange is a hack before we use the new system to directly call callbacks. we will replace with: self.onCaptureNextFrame(...)
  [_bridge.eventDispatcher sendInputEventWithName:@"change" body:event];
}

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