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
|
using UnityEngine;
using UnityEditor;
using System.IO;
[ExecuteInEditMode]
public class Impostors : MonoBehaviour
{
[Header("Bounding Sphere")]
public float sphere_radius_ = 1f;
[Header("Grid Settings")]
[Range(2, 20)] public int gridResolution = 5;
[Header("Camera Settings")]
[Range(1, 4096)] public int cameraResolution = 256;
public float nearClippingDistance = 0.01f;
public LayerMask cullingMask = -1;
public bool renderSkybox = false;
[Header("Original Mesh")]
public GameObject originalMesh;
[HideInInspector] public Camera[] cameras;
private GameObject impostorObject;
private Material impostorMaterial;
public bool HasImpostor => impostorObject != null;
private float Radius => sphere_radius_ * transform.lossyScale.x;
private const string OutputFolder = "Assets/yum_food/3ner/Impostor_Generated";
void OnEnable() => Camera.onPreRender += UpdateMainCameraPos;
void OnDisable() => Camera.onPreRender -= UpdateMainCameraPos;
static void UpdateMainCameraPos(Camera cam)
{
if (cam.cameraType == CameraType.Game || cam.cameraType == CameraType.SceneView)
Shader.SetGlobalVector("_ImpostorMainCameraPos", cam.transform.position);
}
void OnDrawGizmos()
{
Gizmos.color = Color.cyan;
Gizmos.DrawWireSphere(transform.position, Radius);
if (Application.isEditor && gridResolution > 0)
{
Gizmos.color = Color.yellow;
for (int y = 0; y < gridResolution; y++)
{
for (int x = 0; x < gridResolution; x++)
{
Vector3 worldPos = transform.position + PlaneToHemiOctahedron(x, y) * (Radius + nearClippingDistance);
Gizmos.DrawSphere(worldPos, Radius * 0.05f);
Gizmos.DrawLine(worldPos, transform.position);
}
}
}
}
Vector3 PlaneToHemiOctahedron(int gridX, int gridY)
{
float x = (gridX / (float)(gridResolution - 1)) * 2f - 1f;
float z = (gridY / (float)(gridResolution - 1)) * 2f - 1f;
// Rotate 45° to fit square into diamond
float x_rot = (x + z) * 0.5f;
float z_rot = (z - x) * 0.5f;
// Octahedral decode
float y = Mathf.Max(0f, 1f - Mathf.Abs(x_rot) - Mathf.Abs(z_rot));
// Normalize
Vector3 oct_pos = new Vector3(x_rot, y, z_rot).normalized;
// Rotate back by -45° around y
float rcp_sqrt2 = 0.70710678f;
float x_unrot = (oct_pos.x - oct_pos.z) * rcp_sqrt2;
float z_unrot = (oct_pos.x + oct_pos.z) * rcp_sqrt2;
return new Vector3(x_unrot, oct_pos.y, z_unrot);
}
public void CreateCameras()
{
DestroyExistingCameras();
GameObject parent = new GameObject("Cameras");
parent.transform.SetParent(transform, false);
cameras = new Camera[gridResolution * gridResolution];
int idx = 0;
for (int y = 0; y < gridResolution; y++)
{
for (int x = 0; x < gridResolution; x++)
{
Vector3 localDir = PlaneToHemiOctahedron(x, y);
Vector3 worldPos = transform.position + (transform.rotation * localDir) * (Radius + nearClippingDistance);
GameObject camObj = new GameObject($"Camera_{x}_{y}");
camObj.transform.SetParent(parent.transform, false);
camObj.transform.position = worldPos;
camObj.transform.LookAt(transform.position, transform.up);
Camera cam = camObj.AddComponent<Camera>();
cam.orthographic = true;
cam.orthographicSize = sphere_radius_;
cam.nearClipPlane = nearClippingDistance;
cam.farClipPlane = sphere_radius_ * 2f + nearClippingDistance;
cam.cullingMask = cullingMask;
cam.clearFlags = renderSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
cam.backgroundColor = Color.clear;
cam.enabled = false;
cameras[idx++] = cam;
}
}
}
public void DestroyExistingCameras()
{
Transform camsTransform = transform.Find("Cameras");
if (camsTransform != null) DestroyImmediate(camsTransform.gameObject);
cameras = null;
}
public void BakeTexture()
{
SetRenderersEnabled(true);
if (cameras == null || cameras.Length != gridResolution * gridResolution || cameras[0] == null) CreateCameras();
// Render atlas
int size = cameraResolution * gridResolution;
Texture2D atlas = new Texture2D(size, size, TextureFormat.RGBA32, false);
RenderTexture rt = RenderTexture.GetTemporary(cameraResolution, cameraResolution, 24);
int idx = 0;
for (int y = 0; y < gridResolution; y++)
{
for (int x = 0; x < gridResolution; x++)
{
cameras[idx++].targetTexture = rt;
cameras[idx - 1].Render();
RenderTexture.active = rt;
Texture2D temp = new Texture2D(cameraResolution, cameraResolution);
temp.ReadPixels(new Rect(0, 0, cameraResolution, cameraResolution), 0, 0);
temp.Apply();
atlas.SetPixels(x * cameraResolution, y * cameraResolution, cameraResolution, cameraResolution, temp.GetPixels());
DestroyImmediate(temp);
}
}
atlas.Apply();
RenderTexture.active = null;
RenderTexture.ReleaseTemporary(rt);
// Save
if (!AssetDatabase.IsValidFolder(OutputFolder))
{
if (!AssetDatabase.IsValidFolder("Assets/yum_food/3ner"))
AssetDatabase.CreateFolder("Assets/yum_food", "3ner");
AssetDatabase.CreateFolder("Assets/yum_food/3ner", "Impostor_Generated");
}
string name = gameObject.name.Replace(" ", "_");
string path = Path.Combine(OutputFolder, $"{name}_atlas.png");
File.WriteAllBytes(Path.Combine(Application.dataPath, "..", path), atlas.EncodeToPNG());
DestroyImmediate(atlas);
AssetDatabase.Refresh();
TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;
if (importer != null)
{
importer.mipmapEnabled = true;
importer.alphaIsTransparency = true;
importer.wrapMode = TextureWrapMode.Clamp;
importer.filterMode = FilterMode.Trilinear;
importer.SaveAndReimport();
}
// Create impostor
Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
if (tex != null)
{
DestroyExistingImpostor();
Shader shader = Shader.Find("yum_food/Gimmicks/Impostors");
if (shader == null) { Debug.LogError("Shader not found"); return; }
impostorMaterial = new Material(shader);
impostorMaterial.SetTexture("_ImpostorAtlas", tex);
impostorMaterial.SetInt("_GridResolution", gridResolution);
AssetDatabase.CreateAsset(impostorMaterial, Path.Combine(OutputFolder, $"{name}_mat.mat"));
impostorObject = GameObject.CreatePrimitive(PrimitiveType.Quad);
impostorObject.name = "Impostor";
impostorObject.transform.SetParent(transform, false);
impostorObject.transform.localScale = Vector3.one * sphere_radius_ * 2f;
DestroyImmediate(impostorObject.GetComponent<Collider>());
impostorObject.GetComponent<MeshRenderer>().sharedMaterial = impostorMaterial;
SetRenderersEnabled(false);
}
}
public void DestroyExistingImpostor()
{
if (impostorObject != null) DestroyImmediate(impostorObject);
impostorObject = null;
impostorMaterial = null;
}
public void ToggleRenderers()
{
if (originalMesh == null) return;
bool showing = originalMesh.GetComponentInChildren<Renderer>()?.enabled ?? false;
SetRenderersEnabled(!showing);
}
void SetRenderersEnabled(bool enabled)
{
if (originalMesh == null) return;
foreach (Renderer r in originalMesh.GetComponentsInChildren<Renderer>(true))
r.enabled = enabled;
if (impostorObject != null) impostorObject.SetActive(!enabled);
}
}
[CustomEditor(typeof(Impostors))]
public class ImpostorsEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
Impostors s = (Impostors)target;
GUILayout.Space(10);
GUILayout.Label("Impostor Management", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Create Impostor", GUILayout.Height(40))) s.BakeTexture();
GUI.enabled = s.HasImpostor;
if (GUILayout.Button("Destroy Impostor", GUILayout.Height(40)))
{
s.DestroyExistingImpostor();
s.DestroyExistingCameras();
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
if (s.originalMesh != null && GUILayout.Button("Toggle Visibility", GUILayout.Height(30)))
s.ToggleRenderers();
}
}
|