3
votes

I'm working with the Rendering Plugin sample for Unity.

Unity calls into the plugin and hands it a texture pointer, which is an OpenGL texture name (SetTextureFromUnity function for reference). I have another texture I'm creating and managing in my plugin. I would like to somehow get Unity's texture reference to use my texture instead of the one it hands to me.

Is it possible to make the Unity texture just point to my texture? I'm super rough with low level OpenGL.

Alternatively: is it possible to create a Texture2D from an openGL texture that already exists? Then I could just create my own texture and hand it back to unity to wrap with a Texture2D.

I know I could copy data from my texture to the Unity texture, but that's incredibly slow and inefficient when the data for both is already on the GPU. I am looking into FBO copies but all of this seems like overkill when I just want pointer A to point to the same thing that pointer B is pointing to (in theory any way)...

1
I'm looking into something similar, what i'm currently trying is: Using unity's Texture2D.GetNativeTexturePtr() to pass the pointer to the texture into the plugin during one of the render methods (OnPreRender() and such). The plugin then takes this pointer and uses GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, <texture pointer>) and GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); to load the bitmap into the texture. However its not working currently. - sh3rifme
have you ever found any working approach? Trying to implement similar thing. - vir us

1 Answers

0
votes
#define SIZE 1024
#define MASK (SIZE - 1)
struct texture
{
    my_image_object *image;
};

struct texture table[SIZE];

void
bind_my_image_object(my_image_object *image)
{
    uintmax_t hash;
    size_t    index;

    hash    = my_pointer_hash_function((uintptr_t)image);
    index   = hash & MASK;
    texture = table + index;

    glBindTexture(GL_TEXTURE_2D, index);

    if (texture->image != image)
    {
        your_texture_upload_routine(image);
        texture->image = image;
    }
}

Use a decent hash function. Shift down the pointer value to avoid considering the typical object alignment in your hash function. e.g.: (uintptr_t)image >> 3 on 64bit PC. And use a table large enough so you don't trash your texture every frame. Also use a table size that is a power of 2 so the hash & MASK will wrap properly.

General hash table advice apply. Your hashtable may vary.