I’ve been trying to manipulate textures in an OpenGL-based C plugin, as others have done in the past, but I can’t get it working. I have the plugin compiling, and I know the method’s being called as it returns the number of bytes written and that appears right, but the texture remains unchanged. I can also change the texture using the SetPixel() method, but that’s not fast enough for what I’m planning.
I am running the editor (and standalones) with the ‘-force-opengl’ command line option and the menubar’s indicating that I’m running in the correct mode.
The C code for the plugin I’m using is as follows:
#define EXPORT __declspec(dllexport)
#include <GL\gl.h>
#include <stdlib.h>
#include <vector>
extern "C" {
EXPORT int RebuildTexture(int texture_id, int width, int height, int time)
{
// Set up the memory block storing the RGB info.
int size = width * height * 3;
char* bytes = (char*) malloc(size);
int updated = 0;
for( int i = 0 ; i < size; i++ )
{
bytes[i] = time;
updated++;
}
// Use the memory block to replace the texture.
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexSubImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)bytes);
free(bytes);
return updated;
}
}
…and I’m building it with the MinGW GCC install using the command…
gcc.exe UnityVideoPlugin.cpp -lopengl32 -static -shared -o UnityVideoPlugin.dll
Finally my C# plugin is
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
public class UnityVideoPlugin : MonoBehaviour {
private int frame;
private Texture2D texture;
private int width = 512;
private int height = 512;
//Lets make our calls from the Plugin
[DllImport ("UnityVideoPlugin")]
private static extern int RebuildTexture(
int texture_id, int width, int height, int time);
void Start() {
texture = new Texture2D(width, height, TextureFormat.RGB24, false);
renderer.material.mainTexture = texture;
// Test we're able to set colors with SetPixel
for (int x=0; x< texture.width; x++) {
for (int y=0; y<texture.height; y++) {
var color = new Color(x/(float) texture.width, y/(float)texture.height,0);
texture.SetPixel(x, y, color);
}
}
texture.Apply();
}
void Update () {
var texture = renderer.material.mainTexture as Texture2D;
var textureID = texture.GetNativeTextureID();
frame++;
var result = RebuildTexture(textureID, width, height, frame % 200);
print(textureID + "- " + width + " x " + height +", " + frame + " = " + result);
}
}
Does anyone have any ideas what I’m doing wrong here and how to fix it? Thanks.