Skip to content

Instantly share code, notes, and snippets.

@negipoyoc
Last active June 10, 2018 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save negipoyoc/24f539e01755458e03ea3d93ea90e067 to your computer and use it in GitHub Desktop.
Save negipoyoc/24f539e01755458e03ea3d93ea90e067 to your computer and use it in GitHub Desktop.
Unity と NativePluginの連携について
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
public class FastImageLoader : MonoBehaviour
{
[DllImport("plugin1")]
private static extern IntPtr setTexturePtr(IntPtr texturePointer);
[DllImport("plugin1")]
private static extern IntPtr setTextureData(byte[] textureData);
[DllImport("plugin1")]
private static extern IntPtr getRenderEventFunc();
Texture2D tex = null;
IntPtr ptr;
byte[] data;
void Start()
{
tex = new Texture2D(120, 120, TextureFormat.RGBA32, false);
ptr = tex.GetNativeTexturePtr();
Debug.Log(ptr);
setTexturePtr(ptr);
GetComponent<Renderer>().material.mainTexture = tex;
var fileURL = Application.streamingAssetsPath + "/test1.jpg";
StartCoroutine(DownloadTexture(fileURL));
}
IEnumerator DownloadTexture(string url) {
using(var www = new WWW(url)) {
while (!www.isDone) {
yield return null;
}
Debug.Log("Error is " + www.error);
Create(www.bytes);
data = www.bytes;
}
}
private void OnGUI()
{
//画像がロードできたら押す
var str = data.Length != 0 ? "DataLoaded": "No";
if (GUILayout.Button(str, GUILayout.Width(300), GUILayout.Height(100)))
{
StartCoroutine(Create(data));
}
}
IEnumerator Create(byte[] data)
{
yield return new WaitForEndOfFrame();
setTextureData(data);
GL.IssuePluginEvent(getRenderEventFunc(), 0);
tex.UpdateExternalTexture(ptr);
}
}
#include <GLES2/gl2.h>
#include <GLES/gl.h>
#include <malloc.h>
#include <android/log.h>
extern "C" {
using UnityRenderEvent = void(*)(int);
namespace
{
GLuint texture_;
GLubyte* textureData;
}
void setTexturePtr(void* ptr)
{
texture_ = (GLuint)(size_t)ptr;
}
void setTextureData(void* textureByte){
textureData = (GLubyte *)textureByte;
}
void SetTexture(){
glGenTextures(1, &texture_);
glBindTexture(GL_TEXTURE_2D, texture_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 120, 120, 0, GL_RGBA,GL_UNSIGNED_BYTE, textureData);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
}
void onRenderEvent(int eventId)
{
SetTexture();
}
UnityRenderEvent getRenderEventFunc()
{
return onRenderEvent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment