Created
May 27, 2025 08:58
-
-
Save yosun/86bcc77287e3c13e65694dcb6bd485ec to your computer and use it in GitHub Desktop.
places image quad at position of MoGe glb in Unity https://github.com/microsoft/MoGe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class MoGe2UnityMatching : MonoBehaviour | |
{ | |
public GameObject goTestMesh; | |
public Texture2D goTestImage; | |
public Material matImageQuadMaterial; | |
void Start() | |
{ | |
// test | |
RunIt(goTestMesh, goTestImage); | |
} | |
public void RunIt(GameObject g, Texture2D tex) | |
{ | |
MeshFilter meshFilter = g.GetComponentInChildren<MeshFilter>(); | |
if (meshFilter == null) | |
{ | |
Debug.LogError("No MeshFilter found on the GameObject."); | |
return; | |
} | |
Mesh mesh = meshFilter.mesh; | |
if (mesh == null) | |
{ | |
Debug.LogError("MeshFilter has no mesh assigned."); | |
return; | |
} | |
// determine where to place plane so that it matches MoGe median projection depth | |
float medianZ = EstimateMedianZ(mesh); | |
GameObject imageQuad = GameObject.CreatePrimitive(PrimitiveType.Quad); | |
imageQuad.transform.localPosition = new Vector3(0f, 0f, medianZ); | |
// size plane | |
float imageAspect = (float)tex.width / tex.height; | |
float planeHeight = 2f * medianZ * Mathf.Tan(Camera.main.fieldOfView * 0.5f * Mathf.Deg2Rad); | |
float planeWidth = planeHeight * imageAspect; | |
imageQuad.transform.localScale = new Vector3(planeWidth, planeHeight,1); | |
// Assign the texture to the plane's material | |
Renderer planeRenderer = imageQuad.GetComponent<Renderer>(); | |
planeRenderer.material.mainTexture = tex; | |
// rotate plane to face camera | |
imageQuad.transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward, Vector3.up); //* Quaternion.Euler(90f, 180f, 0f); | |
} | |
float EstimateMedianZ(Mesh mesh) | |
{ | |
Vector3[] vertices = mesh.vertices; | |
if (vertices == null || vertices.Length == 0) | |
{ | |
Debug.LogWarning("Mesh has no vertices."); | |
return 1.0f; // fallback depth | |
} | |
float[] zValues = new float[vertices.Length]; | |
for (int i = 0; i < vertices.Length; i++) | |
{ | |
zValues[i] = vertices[i].z; | |
} | |
System.Array.Sort(zValues); | |
int mid = zValues.Length / 2; | |
return (zValues.Length % 2 == 0) | |
? (zValues[mid - 1] + zValues[mid]) * 0.5f | |
: zValues[mid]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment