GLCanvas.java 21 KB
Newer Older
Gaëtan Renaudeau's avatar
WIP  
Gaëtan Renaudeau committed
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
package com.projectseptember.RNGL;

import static android.opengl.GLES20.*;

import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Logger;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class GLCanvas extends GLSurfaceView implements GLSurfaceView.Renderer {

    private static final Logger logger = Logger.getLogger(GLCanvas.class.getName());

    private ReactContext reactContext;
    private RNGLContext rnglContext;
    private boolean preloadingDone = false;
    private boolean deferredRendering = false;
    private GLRenderData renderData;
    private int[] defaultFBO;

    private int nbContentTextures;
    private int renderId;
    private boolean opaque;
    private boolean autoRedraw;
    private boolean eventsThrough;
    private boolean visibleContent;
    private int captureNextFrameId;
    private GLData data;
    private ReadableArray imagesToPreload; // TODO we need to make a List<Uri> I guess? probably Uri should be resolved in advance. not in GLImage

    List<String> preloaded; // TODO List<Uri>

    private Map<String, GLImage> images = new HashMap<>();
    private List<GLTexture> contentTextures = new ArrayList<>();

    public GLCanvas(ThemedReactContext context) {
        super(context);
        reactContext = context;
        this.rnglContext = context.getNativeModule(RNGLContext.class);
        this.setEGLContextClientVersion(2);
        this.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
        this.getHolder().setFormat(PixelFormat.RGBA_8888);
        this.setRenderer(this);
        this.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        this.requestRender();

        preloadingDone = true; // TODO
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        // FIXME anything to do here?
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        // FIXME anything to do here?
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        runAll(mRunOnDraw);

        syncEventsThrough(); // FIXME, really need to do this ?

        if (!preloadingDone) {
            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            glClear(GL_COLOR_BUFFER_BIT);
            return;
        }

        boolean needsDeferredRendering = nbContentTextures > 0 && !autoRedraw;
        if (needsDeferredRendering && !deferredRendering) {
            deferredRendering = true;
            this.requestRender(); // FIXME is this working correctly?
            /*
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!weakSelf) return;
                deferredRendering = true;
                [weakSelf setNeedsDisplay];
            });
            */
        }
        else {
            this.render();
            deferredRendering = false;
        }
    }

    public void setNbContentTextures(int nbContentTextures) {
        this.nbContentTextures = nbContentTextures;
        // TODO: resize uniform content textures
    }

    public void setRenderId(int renderId) {
        this.renderId = renderId;
        if (nbContentTextures > 0)
            this.requestRender();
    }

    public void setOpaque(boolean opaque) {
        this.opaque = opaque;
        /* // FIXME: how to do ?
        if (opaque) {
            this.getHolder().setFormat(PixelFormat.RGB_565);
        }
        else {
            this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        }
        */
        this.requestRender(); // FIXME is this required?
    }

    public void setAutoRedraw(boolean autoRedraw) {
        this.autoRedraw = autoRedraw;
        this.setRenderMode(autoRedraw ? GLSurfaceView.RENDERMODE_CONTINUOUSLY : GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    public void setEventsThrough(boolean eventsThrough) {
        this.eventsThrough = eventsThrough;
        syncEventsThrough();
    }

    public void setVisibleContent(boolean visibleContent) {
        this.visibleContent = visibleContent;
        syncEventsThrough();
    }

    public void setCaptureNextFrameId(int captureNextFrameId) {
        // FIXME move away from this pattern. just use a method, same to ObjC impl
        this.captureNextFrameId = captureNextFrameId;
        this.requestRender();
    }

    private boolean ensureCompiledShader (List<GLData> data) {
        for (GLData d: data) {
            if (!ensureCompiledShader(d));
                return false;
        }
        return true;
    }

    private boolean ensureCompiledShader (GLData data) {
        GLShader shader = rnglContext.getShader(data.shader);
        if (shader == null) return false;
        shader.ensureCompile();
        return ensureCompiledShader(data.children) && ensureCompiledShader(data.contextChildren);
    }

    public void setData (GLData data) {
        this.data = data;
        this.requestSyncData();
    }


    public void setImagesToPreload(ReadableArray imagesToPreload) {
        logger.info("setImageToPreload, working correctly?"); // TODO
        if (preloadingDone) return;
        if (imagesToPreload.size() == 0) {
            dispatchOnLoad();
            preloadingDone = true;
        }
        else {
            preloadingDone = false;
        }

        this.imagesToPreload = imagesToPreload;
    }

    // Sync methods

    private final Queue<Runnable> mRunOnDraw = new LinkedList<>();
    protected void runOnDraw (final Runnable runnable) {
        synchronized (mRunOnDraw) {
            mRunOnDraw.add(runnable);
            requestRender();
        }
    }
    private void runAll(Queue<Runnable> queue) {
        synchronized (queue) {
            while (!queue.isEmpty()) {
                queue.poll().run();
            }
        }
    }

    public void requestSyncData () {
        runOnDraw(new Runnable() {
            public void run() {
                if (ensureCompiledShader(data))
                    syncData();
                else
                    requestSyncData();
            }
        });
    }

    public void syncContextTextures () {
        int i = 0;
        for (GLTexture texture: contentTextures) {
            View view = ((ViewGroup) this.getParent()).getChildAt(i);
            texture.setPixelsWithView(view);
            i ++;
        }
    }

    public void resizeUniformContentTextures (int n) {
        int length = contentTextures.size();
        if (length == n) return;
        if (n < length) {
            contentTextures = contentTextures.subList(0, n);
        }
        else {
            for (int i = contentTextures.size(); i < n; i++) {
                contentTextures.add(new GLTexture());
            }
        }
    }


    private int countPreloaded () {
        int nb = 0;
        for (int i=0; i<imagesToPreload.size(); i++) {/*
            if ([_preloaded containsObject:srcResource(toload)]) // TODO
            nb++;
            */
        }
        return nb;
    }

    private void onImageLoad (String loaded) {
        if (!preloadingDone) {
            preloaded.add(loaded);
            int count = countPreloaded();
            int total = imagesToPreload.size();
            double progress = ((double) count) / ((double) total);
            dispatchOnProgress(progress, count, total);
            if (count == total) {
                dispatchOnLoad();
                preloadingDone = true;
                requestSyncData();
            }
        }
        else {
            // Any texture image load will trigger a future re-sync of data (if no preloaded)
            requestSyncData();
        }
    }


    public String srcResource (ReadableMap res) {
        String src = null;
        boolean isStatic = res.hasKey("isStatic") && res.getBoolean("isStatic");
        if (res.hasKey("path")) src = res.getString("path");
        if (src==null || isStatic) src = res.getString("uri");
        return src;
    }

    public GLRenderData recSyncData (GLData data, HashMap<String, GLImage> images) {
        Map<String, GLImage> prevImages = this.images;

        GLShader shader = rnglContext.getShader(data.shader);
        Map<String, Integer> uniformsInteger = new HashMap<>();
        Map<String, Float> uniformsFloat = new HashMap<>();
        Map<String, IntBuffer> uniformsIntBuffer = new HashMap<>();
        Map<String, FloatBuffer> uniformsFloatBuffer = new HashMap<>();
        Map<String,GLTexture> textures = new HashMap<>();
        List<GLRenderData> contextChildren = new ArrayList<>();
        List<GLRenderData> children = new ArrayList<>();

        shader.bind();

        for (GLData child: data.contextChildren) {
            contextChildren.add(recSyncData(child, images));
        }

        for (GLData child: data.children) {
            children.add(recSyncData(child, images));
        }

        Map<String, Integer> uniformTypes = shader.getUniformTypes();

        int units = 0;
        ReadableMapKeySetIterator iterator = data.uniforms.keySetIterator();
        while (iterator.hasNextKey()) {
            String uniformName = iterator.nextKey();
            int type = uniformTypes.get(uniformName);

            ReadableMap dataUniforms = data.uniforms;

            if (type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE) {
                uniformsInteger.put(uniformName, units++);

                if (dataUniforms.isNull(uniformName)) {
                    GLTexture emptyTexture = new GLTexture();
                    emptyTexture.setPixelsEmpty();
                    textures.put(uniformName, emptyTexture);
                }
                else {
                    ReadableMap value = dataUniforms.getMap(uniformName);
                    String t = value.getString("type");
                    if (t.equals("content")) {
                        int id = value.getInt("id");
                        if (id >= contentTextures.size()) {
                            this.resizeUniformContentTextures(id + 1);
                        }
                        textures.put(uniformName, contentTextures.get(id));
                    }
                    else if (t.equals("fbo")) {
                        int id = value.getInt("id");
                        GLFBO fbo = rnglContext.getFBO(id);
                        textures.put(uniformName, fbo.color.get(0));
                    }
                    else if (t.equals("uri")) {
                        final String src = srcResource(value);
                        if (src==null || src.equals("")) {
                            logger.severe("Shader '"+shader.getName()+": texture uniform '"+uniformName+"': Invalid uri format '"+value+"'");
                        }

                        GLImage image = images.get(src);
                        if (image == null) {
                            image = prevImages.get(src);
                            if (image != null)
                                images.put(src, image);
                        }
                        if (image == null) {
                            image = new GLImage(reactContext.getApplicationContext(), new Runnable() {
                                public void run() {
                                    onImageLoad(src);
                                }
                            }); // TODO bind on load
                            /*
                            [[GLImage alloc] initWithBridge:_bridge withOnLoad:^{
                                if (weakSelf) [weakSelf onImageLoad:src];
                            }];
                            */
                            image.setSrc(src);
                            images.put(src, image);
                        }
                        textures.put(uniformName, image.getTexture());
                    }
                    else {
                        logger.severe("Shader '"+shader.getName()+": texture uniform '"+uniformName+"': Unexpected type '"+type+"'");
                    }
                }
            }
            else {
                switch (type) {
                    case GL_INT:
                        uniformsInteger.put(uniformName, dataUniforms.getInt(uniformName));
                        break;

                    case GL_BOOL:
                        uniformsInteger.put(uniformName, dataUniforms.getBoolean(uniformName) ? 1 : 0);
                        break;

                    case GL_FLOAT:
                        uniformsFloat.put(uniformName, (float) dataUniforms.getDouble(uniformName));
                        break;

                    case GL_FLOAT_VEC2:
                    case GL_FLOAT_VEC3:
                    case GL_FLOAT_VEC4:
                    case GL_FLOAT_MAT2:
                    case GL_FLOAT_MAT3:
                    case GL_FLOAT_MAT4:
                        ReadableArray arr = dataUniforms.getArray(uniformName);
                        if (arraySizeForType(type) != arr.size()) {
                            throw new Error("Shader '"+shader.getName()+
                                    "' uniform '"+uniformName+
                                    "': Invalid array size: "+arr.size()+
                                    ". Expected: "+arraySizeForType(type));
                        }
                        uniformsFloatBuffer.put(uniformName, parseAsFloatArray(arr));
                        break;

                    case GL_INT_VEC2:
                    case GL_INT_VEC3:
                    case GL_INT_VEC4:
                    case GL_BOOL_VEC2:
                    case GL_BOOL_VEC3:
                    case GL_BOOL_VEC4:
                        ReadableArray arr2 = dataUniforms.getArray(uniformName);
                        if (arraySizeForType(type) != arr2.size()) {
                            throw new Error("Shader '"+shader.getName()+
                                    "' uniform '"+uniformName+
                                    "': Invalid array size: "+arr2.size()+
                                    ". Expected: "+arraySizeForType(type));
                        }
                        uniformsIntBuffer.put(uniformName, parseAsIntArray(arr2));
                        break;

                    default:
                        throw new Error("Shader '"+shader.getName()+
                                "' uniform '"+uniformName+
                                "': type not supported: "+type);
                }

            }
        }

        int[] maxTextureUnits = new int[1];
        glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, maxTextureUnits, 0);
        if (units > maxTextureUnits[0]) {
            logger.severe("Shader '"+shader.getName()+": Maximum number of texture reach. got "+units+" >= max "+maxTextureUnits);
        }

        for (String uniformName: uniformTypes.keySet()) {
            if (!uniformsFloat.containsKey(uniformName) &&
                !uniformsInteger.containsKey(uniformName) &&
                !uniformsFloatBuffer.containsKey(uniformName) &&
                !uniformsIntBuffer.containsKey(uniformName)) {
                logger.severe("Shader '"+shader.getName()+": All defined uniforms must be provided. Missing '"+uniformName+"'");
            }
        }

        return new GLRenderData(
                shader,
                uniformsInteger,
                uniformsFloat,
                uniformsIntBuffer,
                uniformsFloatBuffer,
                textures,
                data.width,
                data.height,
                data.fboId,
                contextChildren,
                children);
    }

    private FloatBuffer parseAsFloatArray(ReadableArray array) {
        int size = array.size();
        FloatBuffer buf = ByteBuffer.allocateDirect(size * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        for (int i=0; i<size; i++)
          buf.put((float) array.getDouble(i));
        buf.position(0);
        return buf;
    }

    private IntBuffer parseAsIntArray(ReadableArray array) {
        int size = array.size();
        IntBuffer buf = ByteBuffer.allocateDirect(size * 4)
                .order(ByteOrder.nativeOrder())
                .asIntBuffer();
        for (int i=0; i<size; i++)
            buf.put(array.getInt(i));
        buf.position(0);
        return buf;
    }

    private int arraySizeForType(int type) {
        switch (type) {
            case GL_FLOAT_VEC2:
            case GL_INT_VEC2:
            case GL_BOOL_VEC2:
                return 2;

            case GL_FLOAT_VEC3:
            case GL_INT_VEC3:
            case GL_BOOL_VEC3:
                return 3;

            case GL_FLOAT_VEC4:
            case GL_INT_VEC4:
            case GL_BOOL_VEC4:
            case GL_FLOAT_MAT2:
                return 4;

            case GL_FLOAT_MAT3:
                return 9;

            case GL_FLOAT_MAT4:
                return 16;

            default:
                throw new Error("Invalid array type: "+type);
        }
    }

    public void syncData () {
        if (data == null) return;
        HashMap<String, GLImage> images = new HashMap<>();
        renderData = recSyncData(data, images);
        this.images = images;
        this.requestRender(); // FIXME don't do it here since syncData is called in render phase
    }

    public void recRender (GLRenderData renderData) {
        DisplayMetrics dm = reactContext.getResources().getDisplayMetrics();

        int w = new Float(renderData.width.floatValue() * dm.density).intValue();
        int h = new Float(renderData.height.floatValue() * dm.density).intValue();

        for (GLRenderData child: renderData.contextChildren)
            recRender(child);

        for (GLRenderData child: renderData.children)
            recRender(child);

        if (renderData.fboId == -1) {
            glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO[0]);
            glViewport(0, 0, w, h);
        }
        else {
            GLFBO fbo = rnglContext.getFBO(renderData.fboId);
            fbo.setShape(w, h);
            fbo.bind();
        }

        renderData.shader.bind();

        for (String uniformName: renderData.textures.keySet()) {
            GLTexture texture = renderData.textures.get(uniformName);
            int unit = renderData.uniformsInteger.get(uniformName);
            texture.bind(unit);
        }

        Map<String, Integer> uniformTypes = renderData.shader.getUniformTypes();
        for (String uniformName: renderData.uniformsInteger.keySet()) {
            renderData.shader.setUniform(uniformName, renderData.uniformsInteger.get(uniformName));
        }
        for (String uniformName: renderData.uniformsFloat.keySet()) {
            renderData.shader.setUniform(uniformName, renderData.uniformsFloat.get(uniformName));
        }
        for (String uniformName: renderData.uniformsFloatBuffer.keySet()) {
            renderData.shader.setUniform(uniformName, renderData.uniformsFloatBuffer.get(uniformName), uniformTypes.get(uniformName));
        }
        for (String uniformName: renderData.uniformsIntBuffer.keySet()) {
            renderData.shader.setUniform(uniformName, renderData.uniformsIntBuffer.get(uniformName), uniformTypes.get(uniformName));
        }

        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDrawArrays(GL_TRIANGLES, 0, 6);
    }

    public void render () {
        if (renderData == null) return;
        syncContextTextures();

        defaultFBO = new int[1];
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, defaultFBO, 0);
        glEnable(GL_BLEND);
        recRender(renderData);
        glDisable(GL_BLEND);
        glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO[0]);
    }

    public void syncEventsThrough () {
        // TODO: figure out how to do this (Obj C code below)
        //self.userInteractionEnabled = !(_eventsThrough);
        //self.superview.userInteractionEnabled = !(_eventsThrough && !_visibleContent);
    }


    private void dispatchOnProgress(double progress, int count, int total) {
        WritableMap event = Arguments.createMap();
        event.putDouble("progress", progress);
        event.putInt("count", count);
        event.putInt("total", total);
        ReactContext reactContext = (ReactContext)getContext();
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                getId(),
                "progress",
                event);
    }

    public void dispatchOnLoad () {
        WritableMap event = Arguments.createMap();
        ReactContext reactContext = (ReactContext)getContext();
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                getId(),
                "load",
                event);
    }

}