合并 dev2 的 ShaderBake 线(17 提交,2026-11-05/06)到 dev_chart
两条线从 a311c41 分叉:他那边是烘焙工具(编辑器窗口 + runtime 出图),
我这边是反射生成 UI 的字段配方。文件集只共用 Runtime/Core/XericRegistrationPaths.cs,
且他那侧只是新增 ToolBar 常量、两套根(工具栏 XericLibrary/Action Vessel、
右键 Xeric Library/Action Vessel)都保住了,所以合并无冲突。
This commit is contained in:
@@ -72,6 +72,8 @@ namespace XericUI.Core
|
||||
public const string TableBar = MenuBarRoot + "/Table";
|
||||
/// <summary> 通用 UI 族的工具栏入口(场景变形手柄开关) </summary>
|
||||
public const string UIBar = MenuBarRoot + "/UI";
|
||||
/// <summary> 工具族(离线渲染 / 烘焙之类的一次性工具) </summary>
|
||||
public const string ToolBar = MenuBarRoot + "/Tool";
|
||||
|
||||
// ── Hierarchy 创建菜单 ────────────────────────────────────
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 522b7a3600dfdd04b869d20446c48dab
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,125 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 一次性调用的门面:给"我就是要把这个 shader 烘成一张图/一个文件"的运行时代码用。
|
||||
/// 需要在帧之间反复改参数重画(比如编辑器预览)请直接用 <see cref="ShaderBakeRenderer"/>,
|
||||
/// 它会把目标纹理和网格留着复用。
|
||||
/// </summary>
|
||||
public static class ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 渲进一张新建的 RenderTexture。<b>返回的纹理由调用方销毁</b>(用
|
||||
/// <see cref="ShaderBakeRenderer.ReleaseTempObject"/> 就行)。失败返回 null,原因写在 lastError。
|
||||
/// </summary>
|
||||
public static RenderTexture BakeToRenderTexture(Material material, ShaderBakeSettings settings, out string lastError)
|
||||
{
|
||||
lastError = null;
|
||||
using (var renderer = CreateRenderer(material, settings, out lastError))
|
||||
{
|
||||
if (renderer == null)
|
||||
return null;
|
||||
RenderTexture rt = renderer.Render();
|
||||
lastError = renderer.lastError;
|
||||
if (rt == null)
|
||||
return null;
|
||||
|
||||
// renderer.Dispose 会把内部那张一起销毁,所以交出去的是按同一套参数另建的一张。
|
||||
// 这张要能被 Blit 写入,只能是单采样(采样已在 Render 里解析过了)。
|
||||
var effective = settings != null ? settings : ShaderBakeSettings.CreateDefault();
|
||||
var copy = effective.output.CreateRenderTexture("ShaderBakeResult", 1);
|
||||
Graphics.Blit(rt, copy);
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 渲成可读 Texture2D。调用方负责销毁。 </summary>
|
||||
public static Texture2D BakeToTexture2D(Material material, ShaderBakeSettings settings, bool generateMips = false)
|
||||
{
|
||||
string lastError;
|
||||
using (var renderer = CreateRenderer(material, settings, out lastError))
|
||||
{
|
||||
if (renderer == null)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] " + lastError);
|
||||
return null;
|
||||
}
|
||||
return renderer.RenderToTexture2D(generateMips);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 渲成 Sprite(连同它持有的纹理一起交给调用方)。 </summary>
|
||||
public static Sprite BakeToSprite(Material material, ShaderBakeSettings settings, float pixelsPerUnit = 100f)
|
||||
{
|
||||
string lastError;
|
||||
using (var renderer = CreateRenderer(material, settings, out lastError))
|
||||
{
|
||||
if (renderer == null)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] " + lastError);
|
||||
return null;
|
||||
}
|
||||
return renderer.RenderToSprite(pixelsPerUnit);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渲成图片文件字节(PNG / JPG / TGA / EXR)。
|
||||
/// <paramref name="settings"/> 为 null 时用默认 512×512 那套。
|
||||
/// </summary>
|
||||
public static byte[] BakeToBytes(Material material, ShaderBakeImageFormat format, ShaderBakeSettings settings = null)
|
||||
{
|
||||
string lastError;
|
||||
using (var renderer = CreateRenderer(material, settings, out lastError))
|
||||
{
|
||||
if (renderer == null)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] " + lastError);
|
||||
return null;
|
||||
}
|
||||
Texture2D keep;
|
||||
byte[] bytes = renderer.RenderToBytes(format, out keep);
|
||||
if (keep != null)
|
||||
ShaderBakeRenderer.ReleaseTempObject(keep);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 从 Shader 直接烘一份(内部建临时材质并在用完后销毁) </summary>
|
||||
public static byte[] BakeToBytes(Shader shader, ShaderBakeImageFormat format, ShaderBakeSettings settings = null)
|
||||
{
|
||||
if (shader == null)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] shader 为空");
|
||||
return null;
|
||||
}
|
||||
var temp = new Material(shader) { hideFlags = HideFlags.DontSave };
|
||||
try
|
||||
{
|
||||
return BakeToBytes(temp, format, settings);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ShaderBakeRenderer.ReleaseTempObject(temp);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 把参数与材质装进一个新渲染器;材质为空时返回 null 并写好 lastError </summary>
|
||||
public static ShaderBakeRenderer CreateRenderer(Material material, ShaderBakeSettings settings, out string lastError)
|
||||
{
|
||||
if (material == null)
|
||||
{
|
||||
lastError = "没有材质";
|
||||
return null;
|
||||
}
|
||||
lastError = string.Empty;
|
||||
return new ShaderBakeRenderer
|
||||
{
|
||||
material = material,
|
||||
settings = settings != null ? settings : ShaderBakeSettings.CreateDefault()
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 198f9d8821b7c7345b4f336fb8bea669
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 离屏"摄像机"参数。这里没有真的 Camera——投影与视口矩阵是自己算出来塞进 CommandBuffer 的,
|
||||
/// 好处是不往场景里塞任何临时物体,坏处是 API 相关的 Y 翻转要自己管(见 output.flipY)。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeCameraSettings
|
||||
{
|
||||
[Tooltip("正交(默认):面片不会因为透视而变形,适合贴图类 shader")]
|
||||
public bool orthographic = true;
|
||||
|
||||
[Tooltip("正交半高(世界单位):实际能看到的竖向范围是它的两倍")]
|
||||
public float orthographicSize = 0.6f;
|
||||
|
||||
[Tooltip("透视相机的竖向视野角(度),正交时忽略")]
|
||||
public float fieldOfView = 60f;
|
||||
|
||||
[Tooltip("近裁剪面")]
|
||||
public float nearClipPlane = 0.01f;
|
||||
|
||||
[Tooltip("远裁剪面")]
|
||||
public float farClipPlane = 100f;
|
||||
|
||||
[Tooltip("相机位置:正交时只有朝向影响画面,位置决定远近")]
|
||||
public Vector3 position = new Vector3(0f, 0f, -10f);
|
||||
|
||||
[Tooltip("相机旋转(欧拉角,度):默认朝 +Z 看,即看着放在原点、面朝 -Z 的面片")]
|
||||
public Vector3 eulerAngles;
|
||||
|
||||
/// <summary>
|
||||
/// 视口(世界 → 相机)矩阵。
|
||||
///
|
||||
/// <para><b>为什么要镜像 Z</b>:<see cref="Matrix4x4.Perspective"/> 与 <see cref="Matrix4x4.Ortho"/>
|
||||
/// 沿用 OpenGL 约定——相机朝 <b>-Z</b> 看;而 <c>TRS(...).inverse</c> 给出的是 Unity 自己的
|
||||
/// "朝 +Z 看"。两者直接拼起来,正前方的物体会得到负的裁剪 w(透视)或落在近远裁剪面之外(正交),
|
||||
/// 整块几何被裁光,表现就是"渲染成功但画面全透明"。</para>
|
||||
/// </summary>
|
||||
public Matrix4x4 viewMatrix
|
||||
{
|
||||
get
|
||||
{
|
||||
Matrix4x4 worldToLocal = Matrix4x4.TRS(position, Quaternion.Euler(eulerAngles), Vector3.one).inverse;
|
||||
return Matrix4x4.Scale(new Vector3(1f, 1f, -1f)) * worldToLocal;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 投影矩阵。正交时宽高按 aspect 分配(半宽 = 半高 × aspect),与 Unity 相机一致。
|
||||
/// </summary>
|
||||
public Matrix4x4 GetProjectionMatrix(float aspect)
|
||||
{
|
||||
if (aspect <= 0f) aspect = 1f;
|
||||
if (orthographic)
|
||||
{
|
||||
float halfHeight = Mathf.Max(orthographicSize, 0.0001f);
|
||||
float halfWidth = halfHeight * aspect;
|
||||
return Matrix4x4.Ortho(-halfWidth, halfWidth, -halfHeight, halfHeight,
|
||||
Mathf.Max(nearClipPlane, 0.0001f), Mathf.Max(farClipPlane, nearClipPlane + 0.0001f));
|
||||
}
|
||||
return Matrix4x4.Perspective(Mathf.Clamp(fieldOfView, 1f, 179f), aspect,
|
||||
Mathf.Max(nearClipPlane, 0.0001f), Mathf.Max(farClipPlane, nearClipPlane + 0.0001f));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把包围盒框进画面:正交改半高,透视改距离;同时把远近裁剪面推到包围盒外侧,
|
||||
/// 免得贴脸的大面片被近裁剪面削掉一块。
|
||||
/// </summary>
|
||||
public void FrameBounds(Bounds bounds, float aspect, float padding = 1.15f)
|
||||
{
|
||||
Vector3 extents = bounds.extents;
|
||||
float radius = extents.magnitude;
|
||||
if (radius < 0.0001f) radius = 0.0001f;
|
||||
if (aspect <= 0f) aspect = 1f;
|
||||
|
||||
if (orthographic)
|
||||
{
|
||||
// 横向不够宽时以横向为准:半高 = 半宽 / aspect
|
||||
float halfFromHeight = extents.y;
|
||||
float halfFromWidth = extents.x / aspect;
|
||||
orthographicSize = Mathf.Max(halfFromHeight, halfFromWidth) * Mathf.Max(padding, 1f);
|
||||
}
|
||||
else
|
||||
{
|
||||
float halfFov = Mathf.Clamp(fieldOfView, 1f, 179f) * 0.5f * Mathf.Deg2Rad;
|
||||
float verticalFit = extents.y;
|
||||
float horizontalFit = extents.x / aspect;
|
||||
float neededHalfHeight = Mathf.Max(verticalFit, horizontalFit) * Mathf.Max(padding, 1f);
|
||||
float distance = radius + neededHalfHeight / Mathf.Max(Mathf.Tan(halfFov), 0.0001f);
|
||||
|
||||
// 沿当前朝向平移,不改朝向——转着找角度是用户的事,这里只负责"离远一点"
|
||||
Vector3 dir = Quaternion.Euler(eulerAngles) * Vector3.forward;
|
||||
position = bounds.center - dir * Mathf.Max(distance, radius + 0.0001f);
|
||||
}
|
||||
|
||||
float distanceFromCamera = Vector3.Distance(position, bounds.center);
|
||||
nearClipPlane = Mathf.Max(0.0001f, distanceFromCamera - radius * 3f);
|
||||
farClipPlane = distanceFromCamera + radius * 3f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 收拢数值。负数在这组参数里没有任何含义,但数字框拦不住一个负号,而它造成的后果是
|
||||
/// "渲染成功、画面全空":半高为负时投影矩阵被钳成一条线,什么都框不住,还不报任何错。
|
||||
/// 取绝对值而不是就地归零,是因为负号多半是手滑,量级本身是用户想要的。
|
||||
/// </summary>
|
||||
public void Clamp()
|
||||
{
|
||||
orthographicSize = Mathf.Max(Mathf.Abs(orthographicSize), 0.0001f);
|
||||
fieldOfView = Mathf.Clamp(Mathf.Abs(fieldOfView), 1f, 179f);
|
||||
nearClipPlane = Mathf.Max(Mathf.Abs(nearClipPlane), 0.0001f);
|
||||
farClipPlane = Mathf.Max(Mathf.Abs(farClipPlane), nearClipPlane + 0.0001f);
|
||||
}
|
||||
|
||||
/// <summary> 摄像机指纹:变了不需要重建网格,只需要重画 </summary>
|
||||
public string GetCameraSignature()
|
||||
{
|
||||
return orthographic + "_" + orthographicSize + "_" + fieldOfView + "_" +
|
||||
nearClipPlane + "_" + farClipPlane + "_" + position + "_" + eulerAngles;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 65ae94c1813cc534f81fb2c5dc957a47
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,283 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 按 <see cref="ShaderBakeSurfaceSettings"/> 造出这次烘焙要画的那张网格。
|
||||
///
|
||||
/// <para><b>外部网格一定要复制</b>:UV 偏移/重复是写进顶点数据的,直接改
|
||||
/// <c>MeshFilter.sharedMesh</c> 等于改了项目里的资产。这里把顶点搬到一张新网格上,
|
||||
/// 蒙皮信息不带过来(烘焙用不到,带过来反而要把骨骼矩阵一起搬)。</para>
|
||||
/// </summary>
|
||||
public static class ShaderBakeGeometryBuilder
|
||||
{
|
||||
/// <summary> 造一张新网格(调用方负责销毁)。kind 为外部网格但没有指定网格时退回单片四边形。 </summary>
|
||||
public static Mesh Build(ShaderBakeSurfaceSettings surface)
|
||||
{
|
||||
if (surface == null)
|
||||
return null;
|
||||
surface.Clamp();
|
||||
|
||||
switch (surface.kind)
|
||||
{
|
||||
case ShaderBakeSurfaceKind.Plane:
|
||||
return BuildFaces(surface, Mathf.Max(surface.segments.x, 1), Mathf.Max(surface.segments.y, 1));
|
||||
case ShaderBakeSurfaceKind.Mesh when surface.sourceMesh != null:
|
||||
return BuildFromMesh(surface);
|
||||
default:
|
||||
return BuildFaces(surface, 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 世界空间的包围盒:网格局部包围盒乘面片变换。给"框住面片"用,所以要在外面算,
|
||||
/// 免得网格和变换的耦合漏进几何构建里。
|
||||
/// </summary>
|
||||
public static Bounds GetWorldBounds(Mesh mesh, Matrix4x4 matrix)
|
||||
{
|
||||
if (mesh == null)
|
||||
return new Bounds(Vector3.zero, Vector3.one);
|
||||
if (matrix.isIdentity)
|
||||
return mesh.bounds;
|
||||
|
||||
Bounds b = mesh.bounds;
|
||||
Vector3 min = b.min, max = b.max;
|
||||
Vector3 worldMin = matrix.MultiplyPoint(min);
|
||||
Vector3 worldMax = worldMin;
|
||||
|
||||
// 旋转过之后轴对齐盒子的八个角才是新盒子的候选极值,只转两个角会得到一个歪掉的框
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
Vector3 corner = matrix.MultiplyPoint(new Vector3(
|
||||
(i & 1) == 0 ? min.x : max.x,
|
||||
(i & 2) == 0 ? min.y : max.y,
|
||||
(i & 4) == 0 ? min.z : max.z));
|
||||
worldMin = Vector3.Min(worldMin, corner);
|
||||
worldMax = Vector3.Max(worldMax, corner);
|
||||
}
|
||||
|
||||
var bounds = new Bounds();
|
||||
bounds.SetMinMax(worldMin, worldMax);
|
||||
return bounds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按面片网格造一张平面:每个格子是一张完整的面片,UV 从自己格子的编号起算。
|
||||
/// <paramref name="segmentsX"/>/<paramref name="segmentsY"/> 是<b>单张面片内部</b>的细分,
|
||||
/// 给顶点着色器留梯度用;格子本身恒为一张。
|
||||
/// </summary>
|
||||
private static Mesh BuildFaces(ShaderBakeSurfaceSettings surface, int segmentsX, int segmentsY)
|
||||
{
|
||||
int columns = Mathf.Max(surface.gridColumns, 1);
|
||||
int rows = Mathf.Max(surface.gridRows, 1);
|
||||
segmentsX = Mathf.Max(segmentsX, 1);
|
||||
segmentsY = Mathf.Max(segmentsY, 1);
|
||||
|
||||
// size 是"每一格"的尺寸:加一格,整个平面就往那一侧长一格出去
|
||||
float faceWidth = surface.size.x;
|
||||
float faceHeight = surface.size.y;
|
||||
float halfWidth = faceWidth * columns * 0.5f;
|
||||
float halfHeight = faceHeight * rows * 0.5f;
|
||||
|
||||
int verticesPerFace = (segmentsX + 1) * (segmentsY + 1);
|
||||
int vertexCount = columns * rows * verticesPerFace;
|
||||
var vertices = new List<Vector3>(vertexCount);
|
||||
var normals = new List<Vector3>(vertexCount);
|
||||
var uvs = new List<Vector2>(vertexCount);
|
||||
var triangles = new List<int>(columns * rows * segmentsX * segmentsY * (surface.doubleSided ? 12 : 6));
|
||||
|
||||
int stride = segmentsX + 1;
|
||||
for (int row = 0; row < rows; row++)
|
||||
for (int column = 0; column < columns; column++)
|
||||
{
|
||||
ShaderBakeFaceCell face = surface.GetFace(row * columns + column);
|
||||
float originX = -halfWidth + column * faceWidth;
|
||||
float originY = -halfHeight + row * faceHeight;
|
||||
int baseIndex = vertices.Count;
|
||||
|
||||
for (int y = 0; y <= segmentsY; y++)
|
||||
{
|
||||
float ty = (float)y / segmentsY;
|
||||
for (int x = 0; x <= segmentsX; x++)
|
||||
{
|
||||
float tx = (float)x / segmentsX;
|
||||
vertices.Add(new Vector3(originX + tx * faceWidth, originY + ty * faceHeight, 0f));
|
||||
normals.Add(Vector3.back); // 面朝 -Z,即默认相机(朝 +Z 看)看到的正面
|
||||
// 格子编号 + 面内 0~1,再统一套上全局的偏移/重复
|
||||
uvs.Add(RemapUv(new Vector2(face.uvX + tx, face.uvY + ty), surface));
|
||||
}
|
||||
}
|
||||
|
||||
for (int y = 0; y < segmentsY; y++)
|
||||
for (int x = 0; x < segmentsX; x++)
|
||||
{
|
||||
int bottomLeft = baseIndex + y * stride + x;
|
||||
int bottomRight = bottomLeft + 1;
|
||||
int topLeft = bottomLeft + stride;
|
||||
int topRight = topLeft + 1;
|
||||
// 与 Unity 内置 Quad 同向:从法线指的那一侧看是 xy 平面的逆时针。
|
||||
// 究竟哪一侧算正面由图形 API 决定,而这条链路的投影矩阵是自己拼的、没有相机帮忙统一,
|
||||
// 所以单靠一个固定绕序永远会在某个 API 上被 Cull Back 剔光——见 doubleSided。
|
||||
AddQuad(triangles, bottomLeft, bottomRight, topRight, topLeft, false);
|
||||
if (surface.doubleSided)
|
||||
AddQuad(triangles, bottomLeft, bottomRight, topRight, topLeft, true);
|
||||
}
|
||||
}
|
||||
|
||||
var mesh = NewMesh(vertexCount > 65000 ? "ShaderBakeFaces" : "ShaderBakeQuad");
|
||||
if (vertexCount > 65000)
|
||||
mesh.indexFormat = IndexFormat.UInt32;
|
||||
mesh.SetVertices(vertices);
|
||||
mesh.SetNormals(normals);
|
||||
mesh.SetUVs(0, uvs);
|
||||
mesh.SetTriangles(triangles, 0);
|
||||
Upload(mesh);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一个格子的两个三角面。<paramref name="reverse"/> 为真时把绕序整个反过来:同一片几何
|
||||
/// 在"顺时针算正面"与"逆时针算正面"两种约定下各有一份是可见的,而另一份仍会被剔除,
|
||||
/// 所以不会画两遍、透明混合也不会被叠加两次。
|
||||
/// </summary>
|
||||
private static void AddQuad(List<int> triangles, int bottomLeft, int bottomRight, int topRight, int topLeft, bool reverse)
|
||||
{
|
||||
if (reverse)
|
||||
{
|
||||
triangles.Add(bottomLeft); triangles.Add(bottomRight); triangles.Add(topLeft);
|
||||
triangles.Add(bottomRight); triangles.Add(topRight); triangles.Add(topLeft);
|
||||
return;
|
||||
}
|
||||
triangles.Add(bottomLeft); triangles.Add(bottomRight); triangles.Add(topRight);
|
||||
triangles.Add(bottomLeft); triangles.Add(topRight); triangles.Add(topLeft);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 复制外部网格的第 0 套 UV(没有就按位置做平面投影),再套上偏移/重复。
|
||||
/// </summary>
|
||||
private static Mesh BuildFromMesh(ShaderBakeSurfaceSettings surface)
|
||||
{
|
||||
Mesh source = surface.sourceMesh;
|
||||
int subMesh = Mathf.Min(surface.meshSubMesh, Mathf.Max(source.subMeshCount - 1, 0));
|
||||
|
||||
var vertices = new List<Vector3>();
|
||||
source.GetVertices(vertices);
|
||||
if (vertices.Count == 0)
|
||||
{
|
||||
Debug.LogWarning("[ShaderBake] 外部网格没有顶点数据(可能是只读网格),退回单片四边形");
|
||||
return BuildFaces(surface, 1, 1);
|
||||
}
|
||||
|
||||
var normals = new List<Vector3>();
|
||||
if (source.HasVertexAttribute(VertexAttribute.Normal))
|
||||
source.GetNormals(normals);
|
||||
|
||||
var tangents = new List<Vector4>();
|
||||
if (source.HasVertexAttribute(VertexAttribute.Tangent))
|
||||
source.GetTangents(tangents);
|
||||
|
||||
var uvs = new List<Vector2>();
|
||||
if (source.HasVertexAttribute(VertexAttribute.TexCoord0))
|
||||
source.GetUVs(0, uvs);
|
||||
if (uvs.Count != vertices.Count)
|
||||
uvs = BuildPlanarUv(vertices);
|
||||
|
||||
// UV 是"面片的贴图坐标",不该被模型的尺寸归一化影响,所以先 remap 再缩放顶点
|
||||
for (int i = 0; i < uvs.Count; i++)
|
||||
uvs[i] = RemapUv(uvs[i], surface);
|
||||
|
||||
var mesh = NewMesh("ShaderBakeMesh");
|
||||
if (vertices.Count > 65000)
|
||||
mesh.indexFormat = IndexFormat.UInt32;
|
||||
|
||||
Bounds srcBounds = source.bounds;
|
||||
Vector3 normalizeScale = surface.normalizeMeshSize ? FitScale(srcBounds.size, surface.size) : Vector3.one;
|
||||
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
vertices[i] = Vector3.Scale(vertices[i] - srcBounds.center, normalizeScale);
|
||||
|
||||
mesh.SetVertices(vertices);
|
||||
if (normals.Count == vertices.Count) mesh.SetNormals(normals); else mesh.RecalculateNormals();
|
||||
if (tangents.Count == vertices.Count) mesh.SetTangents(tangents);
|
||||
mesh.SetUVs(0, uvs);
|
||||
|
||||
// 只搬到选中的那一层:后面的层不该跟着画出来,但 subMesh 之前的层要一起画(多层模型常有共用材质球的分层)
|
||||
int layerCount = subMesh + 1;
|
||||
mesh.subMeshCount = layerCount;
|
||||
for (int i = 0; i < layerCount; i++)
|
||||
{
|
||||
int[] tris = source.GetTriangles(i);
|
||||
if (surface.doubleSided)
|
||||
{
|
||||
// 反向补一份,理由同 AddQuad:正面对侧的约定由 API 决定,别让烘焙结果取决于显卡
|
||||
int complete = tris.Length / 3 * 3;
|
||||
var both = new int[tris.Length + complete];
|
||||
tris.CopyTo(both, 0);
|
||||
for (int t = 0; t < complete; t += 3)
|
||||
{
|
||||
both[tris.Length + t] = tris[t];
|
||||
both[tris.Length + t + 1] = tris[t + 2];
|
||||
both[tris.Length + t + 2] = tris[t + 1];
|
||||
}
|
||||
tris = both;
|
||||
}
|
||||
mesh.SetTriangles(tris, i);
|
||||
}
|
||||
|
||||
Upload(mesh);
|
||||
mesh.RecalculateBounds();
|
||||
return mesh;
|
||||
}
|
||||
|
||||
/// <summary> 把源尺寸装进目标尺寸:x/y 各自贴合,z 跟 x/y 的平均倍率走以免模型被压扁成纸片 </summary>
|
||||
private static Vector3 FitScale(Vector3 sourceSize, Vector2 targetSize)
|
||||
{
|
||||
float sx = sourceSize.x > 0.0001f ? targetSize.x / sourceSize.x : 1f;
|
||||
float sy = sourceSize.y > 0.0001f ? targetSize.y / sourceSize.y : 1f;
|
||||
float sz = sourceSize.z > 0.0001f ? (sx + sy) * 0.5f : 1f;
|
||||
return new Vector3(sx, sy, sz);
|
||||
}
|
||||
|
||||
/// <summary> 网格没带 UV 时的兜底:拿 x/y 位置做一次平面投影,至少贴图有坐标可用 </summary>
|
||||
private static List<Vector2> BuildPlanarUv(List<Vector3> vertices)
|
||||
{
|
||||
var min = new Vector3(float.MaxValue, float.MaxValue, 0f);
|
||||
var max = new Vector3(float.MinValue, float.MinValue, 0f);
|
||||
foreach (Vector3 v in vertices)
|
||||
{
|
||||
min = Vector3.Min(min, v);
|
||||
max = Vector3.Max(max, v);
|
||||
}
|
||||
|
||||
float rangeX = Mathf.Max(max.x - min.x, 0.0001f);
|
||||
float rangeY = Mathf.Max(max.y - min.y, 0.0001f);
|
||||
|
||||
var uvs = new List<Vector2>(vertices.Count);
|
||||
foreach (Vector3 v in vertices)
|
||||
uvs.Add(new Vector2((v.x - min.x) / rangeX, (v.y - min.y) / rangeY));
|
||||
return uvs;
|
||||
}
|
||||
|
||||
private static Vector2 RemapUv(Vector2 uv, ShaderBakeSurfaceSettings surface)
|
||||
{
|
||||
return Vector2.Scale(uv, surface.uvTiling) + surface.uvOffset;
|
||||
}
|
||||
|
||||
private static Mesh NewMesh(string name)
|
||||
{
|
||||
return new Mesh
|
||||
{
|
||||
name = name,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary> 上传为只读以外的可变网格(false):重建时还要读回顶点,别让 Unity 把它锁掉 </summary>
|
||||
private static void Upload(Mesh mesh)
|
||||
{
|
||||
mesh.UploadMeshData(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b86fe4466c4837f47bbe2e2bdc5454a1
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,158 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary> 能喂给 shader 的全局量类别,决定用哪个 SetGlobal 入口 </summary>
|
||||
public enum ShaderBakeGlobalKind
|
||||
{
|
||||
Float,
|
||||
Vector,
|
||||
Color,
|
||||
Texture
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一条全局参数。贴图引用标了 <see cref="NonSerializedAttribute"/>:JsonUtility 存不下来资产引用,
|
||||
/// 硬存一个实例 ID 反而会在换会话后变成半死的引用。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeGlobalEntry
|
||||
{
|
||||
public string name;
|
||||
|
||||
public ShaderBakeGlobalKind kind;
|
||||
|
||||
[Tooltip("关掉就完全不动这个全局量,包括不捕获、不还原")]
|
||||
public bool enabled;
|
||||
|
||||
public float x;
|
||||
public float y;
|
||||
public float z;
|
||||
public float w;
|
||||
|
||||
[NonSerialized] public Texture texture;
|
||||
|
||||
public ShaderBakeGlobalEntry() { }
|
||||
|
||||
public ShaderBakeGlobalEntry(string name, ShaderBakeGlobalKind kind, bool enabled = false)
|
||||
{
|
||||
this.name = name;
|
||||
this.kind = kind;
|
||||
this.enabled = enabled;
|
||||
w = 1f;
|
||||
}
|
||||
|
||||
public Vector4 ToVector() { return new Vector4(x, y, z, w); }
|
||||
|
||||
public Color ToColor() { return new Color(x, y, z, w); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一组全局参数。烘焙走的是离屏命令缓冲,没有相机在渲染,"灯在哪、环境光是什么"这类由引擎
|
||||
/// 在相机流程里塞进去的全局量天然缺失——这里就是补那一块的口子。
|
||||
///
|
||||
/// <para><b>只改自己认识的那几条,并且画完就还原</b>:不还原等于把一次烘焙的临时值泄漏给整个编辑器。
|
||||
/// 还原是尽力而为:引擎每帧会重设的内置量(例如相机相关的矩阵)可能被覆盖回去。</para>
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeGlobalSettings
|
||||
{
|
||||
[Tooltip("要参与烘焙的全局参数。没勾选的行完全不参与")]
|
||||
public List<ShaderBakeGlobalEntry> entries = new List<ShaderBakeGlobalEntry>();
|
||||
|
||||
/// <summary>
|
||||
/// 把启用的条目写进全局,并返回一组还原动作(按相反顺序执行)。
|
||||
/// </summary>
|
||||
public List<Action> Apply()
|
||||
{
|
||||
var restores = new List<Action>();
|
||||
if (entries == null)
|
||||
return restores;
|
||||
|
||||
for (int i = 0; i < entries.Count; i++)
|
||||
{
|
||||
ShaderBakeGlobalEntry entry = entries[i];
|
||||
if (entry == null || !entry.enabled || string.IsNullOrEmpty(entry.name))
|
||||
continue;
|
||||
|
||||
string name = entry.name;
|
||||
switch (entry.kind)
|
||||
{
|
||||
case ShaderBakeGlobalKind.Float:
|
||||
{
|
||||
float previous = Shader.GetGlobalFloat(name);
|
||||
Shader.SetGlobalFloat(name, entry.x);
|
||||
restores.Add(() => Shader.SetGlobalFloat(name, previous));
|
||||
break;
|
||||
}
|
||||
case ShaderBakeGlobalKind.Vector:
|
||||
{
|
||||
Vector4 previous = Shader.GetGlobalVector(name);
|
||||
Shader.SetGlobalVector(name, entry.ToVector());
|
||||
restores.Add(() => Shader.SetGlobalVector(name, previous));
|
||||
break;
|
||||
}
|
||||
case ShaderBakeGlobalKind.Color:
|
||||
{
|
||||
Color previous = Shader.GetGlobalColor(name);
|
||||
Shader.SetGlobalColor(name, entry.ToColor());
|
||||
restores.Add(() => Shader.SetGlobalColor(name, previous));
|
||||
break;
|
||||
}
|
||||
case ShaderBakeGlobalKind.Texture:
|
||||
{
|
||||
Texture previous = Shader.GetGlobalTexture(name);
|
||||
Shader.SetGlobalTexture(name, entry.texture);
|
||||
restores.Add(() => Shader.SetGlobalTexture(name, previous));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return restores;
|
||||
}
|
||||
|
||||
/// <summary> 按名字找已有条目,没有就追加一条(扫描与预设都走这里,避免重复) </summary>
|
||||
public ShaderBakeGlobalEntry Ensure(string name, ShaderBakeGlobalKind kind)
|
||||
{
|
||||
if (entries == null)
|
||||
entries = new List<ShaderBakeGlobalEntry>();
|
||||
for (int i = 0; i < entries.Count; i++)
|
||||
{
|
||||
if (entries[i] != null && entries[i].name == name)
|
||||
return entries[i];
|
||||
}
|
||||
var entry = new ShaderBakeGlobalEntry(name, kind);
|
||||
entries.Add(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 常用光照/环境量。全部默认关闭:不同渲染管线对这些名字的语义不完全一样,
|
||||
/// 该不该开由用户决定,工具不替他改画面。
|
||||
/// </summary>
|
||||
public void AddEnvironmentPresets()
|
||||
{
|
||||
AddVector("_WorldSpaceLightPos0", 0.3f, 0.7f, -0.6f, 0f);
|
||||
AddColor("_LightColor0", 1f, 1f, 1f, 1f);
|
||||
AddColor("unity_AmbientSky", 0.21f, 0.23f, 0.25f, 1f);
|
||||
AddColor("unity_AmbientEquator", 0.11f, 0.12f, 0.13f, 1f);
|
||||
AddColor("unity_AmbientGround", 0.04f, 0.04f, 0.04f, 1f);
|
||||
AddVector("_Time", 0f, 0f, 0f, 0f);
|
||||
Ensure("unity_SpecCube0", ShaderBakeGlobalKind.Texture);
|
||||
}
|
||||
|
||||
private void AddVector(string name, float x, float y, float z, float w)
|
||||
{
|
||||
ShaderBakeGlobalEntry entry = Ensure(name, ShaderBakeGlobalKind.Vector);
|
||||
entry.x = x; entry.y = y; entry.z = z; entry.w = w;
|
||||
}
|
||||
|
||||
private void AddColor(string name, float x, float y, float z, float w)
|
||||
{
|
||||
ShaderBakeGlobalEntry entry = Ensure(name, ShaderBakeGlobalKind.Color);
|
||||
entry.x = x; entry.y = y; entry.z = z; entry.w = w;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 77fd56ea769f4804d9953825a78f5ad0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 可导出的图片文件编码。全部走 Unity 自己的 <c>ImageConversion</c> 扩展方法,不引第三方编码器。
|
||||
/// </summary>
|
||||
public enum ShaderBakeImageFormat
|
||||
{
|
||||
/// <summary> PNG:带 alpha,无损 </summary>
|
||||
Png,
|
||||
|
||||
/// <summary> JPG:无 alpha,导出前会把透明压到背景色上 </summary>
|
||||
Jpg,
|
||||
|
||||
/// <summary> TGA:无压缩、带 alpha,Photoshop / 老管线常用 </summary>
|
||||
Tga,
|
||||
|
||||
/// <summary> EXR:浮点 HDR,配 output.hdr 用 </summary>
|
||||
Exr
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 编码分派。注意这几个函数都要求纹理是可读的、且是非压缩格式——
|
||||
/// 所以入口只接 <see cref="ShaderBakeReadback"/> 造出来的 RGBA32 / RGBAFloat,别把导入的资源塞进来。
|
||||
/// </summary>
|
||||
public static class ShaderBakeImageFormatExtensions
|
||||
{
|
||||
public static string GetExtension(this ShaderBakeImageFormat format)
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case ShaderBakeImageFormat.Jpg: return "jpg";
|
||||
case ShaderBakeImageFormat.Tga: return "tga";
|
||||
case ShaderBakeImageFormat.Exr: return "exr";
|
||||
default: return "png";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 这个格式能不能存 alpha </summary>
|
||||
public static bool SupportsAlpha(this ShaderBakeImageFormat format)
|
||||
{
|
||||
return format != ShaderBakeImageFormat.Jpg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 编码成文件字节。<paramref name="flattenBackground"/> 只给 JPG 用:它没有 alpha 通道,
|
||||
/// 直接把 RGBA 交上去会得到一圈发黑的边,所以先按这个颜色把透明压平(顺带把浮点截到 0~1)。
|
||||
/// </summary>
|
||||
public static byte[] Encode(this ShaderBakeImageFormat format, Texture2D texture, Color flattenBackground)
|
||||
{
|
||||
if (texture == null)
|
||||
throw new ArgumentNullException(nameof(texture));
|
||||
|
||||
if (format == ShaderBakeImageFormat.Jpg)
|
||||
{
|
||||
var flattened = ShaderBakeReadback.FlattenOntoBackground(texture, flattenBackground);
|
||||
try
|
||||
{
|
||||
return flattened.EncodeToJPG();
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 编辑器非播放状态下 Object.Destroy 会被拒绝并报错,统一走这条能分辨时机的回收
|
||||
ShaderBakeRenderer.ReleaseTempObject(flattened);
|
||||
}
|
||||
}
|
||||
|
||||
switch (format)
|
||||
{
|
||||
case ShaderBakeImageFormat.Tga:
|
||||
return texture.EncodeToTGA();
|
||||
case ShaderBakeImageFormat.Exr:
|
||||
return texture.EncodeToEXR(Texture2D.EXRFlags.None);
|
||||
default:
|
||||
return texture.EncodeToPNG();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EXR 要求浮点纹理才能存下超过 1 的分量;非 HDR 的源用 RGBA32 烘,导 EXR 时格式仍合法但值域被截断,
|
||||
/// 这里给个提示而不是报错。
|
||||
/// </summary>
|
||||
public static bool NeedsFloatSource(this ShaderBakeImageFormat format)
|
||||
{
|
||||
return format == ShaderBakeImageFormat.Exr;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bdcb0938705cfd640a80e6a3f798c494
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,144 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 把"用户给的 Shader 或 Material"归一成一张可渲染的材质,并管好这张材质的生死。
|
||||
///
|
||||
/// <para><b>为什么 Shader 入口要自己造材质</b>:渲染路径只认材质,而 Shader 资产本身不能被修改
|
||||
/// (属性默认值存在 Shader 里、不在任何实例上)。造一张临时材质是唯一能就地调参数的路子,
|
||||
/// 代价是它不属于任何资产——所以用完必须还,见 <see cref="Dispose"/>。</para>
|
||||
///
|
||||
/// <para><b>Material 入口不动原资产</b>:直接编辑传进来的材质资产等于改了项目里的文件,
|
||||
/// 用户点一下颜色滑块就写脏了一个 .mat。这里也造一份副本,改坏了指望不了别人替你记。</para>
|
||||
/// </summary>
|
||||
public sealed class ShaderBakeMaterialSource : IDisposable
|
||||
{
|
||||
/// <summary> 渲染实际用的材质(可能是临时造的副本) </summary>
|
||||
public Material material { get; private set; }
|
||||
|
||||
/// <summary> 这份材质是不是自己造的,决定 Dispose 时要不要销毁它 </summary>
|
||||
public bool ownsMaterial { get; private set; }
|
||||
|
||||
/// <summary> 用户给的 Shader 入口,用于界面显示与材质属性列表 </summary>
|
||||
public Shader sourceShader { get; private set; }
|
||||
|
||||
/// <summary> 用户给的 Material 入口,副本的参数就按它初始化 </summary>
|
||||
public Material sourceMaterial { get; private set; }
|
||||
|
||||
/// <summary> 当前生效的 shader(两个入口最终都落到它上面) </summary>
|
||||
public Shader shader
|
||||
{
|
||||
get
|
||||
{
|
||||
if (sourceShader != null) return sourceShader;
|
||||
return material != null ? material.shader : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 给界面看的来源说明:Shader 入口写"临时材质",Material 入口写"副本" </summary>
|
||||
public string description
|
||||
{
|
||||
get
|
||||
{
|
||||
if (sourceShader != null) return sourceShader.name + "(临时材质)";
|
||||
if (material != null) return material.name + "(副本)";
|
||||
return "未指定";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> Shader 入口:建一张临时材质。传 null 表示清空。 </summary>
|
||||
public void Assign(Shader shader)
|
||||
{
|
||||
ReleaseOwned();
|
||||
sourceShader = shader;
|
||||
sourceMaterial = null;
|
||||
if (shader == null)
|
||||
{
|
||||
material = null;
|
||||
return;
|
||||
}
|
||||
material = new Material(shader)
|
||||
{
|
||||
name = shader.name + " (Bake)",
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
ownsMaterial = true;
|
||||
}
|
||||
|
||||
/// <summary> Material 入口:复制一张临时材质,参数与来源一致。传 null 表示清空。 </summary>
|
||||
public void Assign(Material source)
|
||||
{
|
||||
ReleaseOwned();
|
||||
sourceShader = null;
|
||||
sourceMaterial = source;
|
||||
if (source == null)
|
||||
{
|
||||
material = null;
|
||||
return;
|
||||
}
|
||||
material = new Material(source)
|
||||
{
|
||||
name = source.name + " (Bake)",
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
ownsMaterial = true;
|
||||
}
|
||||
|
||||
/// <summary> 把副本当前的参数写回来源材质(用户显式按"应用"才走这里) </summary>
|
||||
public bool ApplyToSource()
|
||||
{
|
||||
if (material == null || sourceMaterial == null)
|
||||
return false;
|
||||
// CopyPropertiesFromMaterial 只搬它认得的属性,材质整体替换反而会把 hideFlags 带过来
|
||||
sourceMaterial.CopyPropertiesFromMaterial(material);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary> 丢弃副本上的改动,回到来源材质的参数 </summary>
|
||||
public bool RevertToSource()
|
||||
{
|
||||
if (sourceMaterial == null)
|
||||
return false;
|
||||
Assign(sourceMaterial);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary> 换 shader 名/属性列表之后要把副本丢干净 </summary>
|
||||
public void Clear()
|
||||
{
|
||||
ReleaseOwned();
|
||||
sourceShader = null;
|
||||
sourceMaterial = null;
|
||||
material = null;
|
||||
ownsMaterial = false;
|
||||
}
|
||||
|
||||
private void ReleaseOwned(bool immediate)
|
||||
{
|
||||
if (ownsMaterial && material != null)
|
||||
ShaderBakeRenderer.ReleaseTempObject(material, immediate);
|
||||
material = null;
|
||||
ownsMaterial = false;
|
||||
}
|
||||
|
||||
private void ReleaseOwned()
|
||||
{
|
||||
ReleaseOwned(false);
|
||||
}
|
||||
|
||||
/// <summary> 编辑器里退出窗口时按 immediate 释放,显存当场就还回去了 </summary>
|
||||
public void Dispose(bool immediate)
|
||||
{
|
||||
ReleaseOwned(immediate);
|
||||
sourceShader = null;
|
||||
sourceMaterial = null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3fe9d4e18fb587e49a4ba3ec6187f551
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,145 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 输出目标设置:决定"烘出来那张 RenderTexture 长什么样"。
|
||||
///
|
||||
/// <para><b>为什么 flipY 要摊开给用户</b>:这里走的是 CommandBuffer + 自建投影矩阵的离屏渲染,
|
||||
/// 没有相机帮你做 API 相关的 Y 翻转,于是同一段代码在 D3D 与 OpenGL/Metal 上读回来的像素是上下相反的。
|
||||
/// 与其替用户猜一个方向,不如把开关留在界面上(规范:一次调用不出结果时先怀疑方向,再怀疑内容)。</para>
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeOutputSettings
|
||||
{
|
||||
/// <summary> 边长下限 </summary>
|
||||
public const int kMinDimension = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 边长上限:4096² 的 RGBA32 读回是 64MB 内存,ARGBFloat 是 256MB。
|
||||
/// 再往上就不是"烘焙一张图"而是"烘一张图集"了,交给调用方自己决定要不要冒险。
|
||||
/// </summary>
|
||||
public const int kMaxDimension = 4096;
|
||||
|
||||
[Tooltip("导出图片的宽(像素)")]
|
||||
public int width = 512;
|
||||
|
||||
[Tooltip("导出图片的高(像素)")]
|
||||
public int height = 512;
|
||||
|
||||
[Tooltip("HDR:目标改用 ARGBFloat。开这项时请配 EXR 导出,PNG/JPG 存不下超过 1 的分量")]
|
||||
public bool hdr;
|
||||
|
||||
[Tooltip("多重采样,只能是 1 / 2 / 4 / 8;渲染完会自动解析回普通纹理再读回")]
|
||||
public int antiAliasing = 1;
|
||||
|
||||
[Tooltip("深度位数。只渲一张面片填 0 就够,渲模型(有多层遮挡)要留 24")]
|
||||
public int depthBuffer = 24;
|
||||
|
||||
[Tooltip("目标按 sRGB 存储。关掉=线性,通常配 HDR + EXR 自己走色彩管理")]
|
||||
public bool sRGB = true;
|
||||
|
||||
[Tooltip("背景色。alpha 留 0 才能导出带透明通道的图;导 JPG 时这个颜色会被压进图里")]
|
||||
public Color clearColor = new Color(0f, 0f, 0f, 0f);
|
||||
|
||||
[Tooltip("翻转投影 Y:画面上下颠倒时打开(不同图形 API 的读回方向不一样)")]
|
||||
public bool flipY;
|
||||
|
||||
[Tooltip("subShader 的 pass 下标,-1=所有 pass 叠加渲染")]
|
||||
public int shaderPass = -1;
|
||||
|
||||
[Tooltip("目标纹理的过滤方式")]
|
||||
public FilterMode filterMode = FilterMode.Bilinear;
|
||||
|
||||
[Tooltip("目标纹理的寻址方式")]
|
||||
public TextureWrapMode wrapMode = TextureWrapMode.Clamp;
|
||||
|
||||
/// <summary> 目标的 RenderTexture 格式 </summary>
|
||||
public RenderTextureFormat format
|
||||
{
|
||||
get { return hdr ? RenderTextureFormat.ARGBFloat : RenderTextureFormat.ARGB32; }
|
||||
}
|
||||
|
||||
/// <summary> 目标的色彩存储方式(HDR 只能线性) </summary>
|
||||
public RenderTextureReadWrite renderTextureColorSpace
|
||||
{
|
||||
get { return hdr || !sRGB ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB; }
|
||||
}
|
||||
|
||||
/// <summary> 读回成 Texture2D 时用的像素格式 </summary>
|
||||
public TextureFormat textureFormat
|
||||
{
|
||||
get { return hdr ? TextureFormat.RGBAFloat : TextureFormat.RGBA32; }
|
||||
}
|
||||
|
||||
/// <summary> 读回来的 Texture2D 是否按线性解释 </summary>
|
||||
public bool isLinearTexture
|
||||
{
|
||||
get { return hdr || !sRGB; }
|
||||
}
|
||||
|
||||
/// <summary> 目标纹理的有效宽高(读回、贴图、算尺寸都走这个,别各自再算一遍) </summary>
|
||||
public Vector2Int size
|
||||
{
|
||||
get { return new Vector2Int(width, height); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把用户敲进来的数值收进合法区间。非法值不报错、只归位——界面上每改一次都走这里,
|
||||
/// 报错会把输入框变成打字障碍。
|
||||
/// </summary>
|
||||
public void Clamp()
|
||||
{
|
||||
width = Mathf.Clamp(width, kMinDimension, kMaxDimension);
|
||||
height = Mathf.Clamp(height, kMinDimension, kMaxDimension);
|
||||
depthBuffer = Mathf.Clamp(depthBuffer, 0, 32);
|
||||
// HDR 浮点目标基本没有平台支持 MSAA,硬开着只会得到一张黑图
|
||||
if (hdr)
|
||||
antiAliasing = 1;
|
||||
else
|
||||
antiAliasing = SnapAntiAliasing(antiAliasing);
|
||||
}
|
||||
|
||||
/// <summary> 距离最近的一个合法采样倍数(1/2/4/8) </summary>
|
||||
public static int SnapAntiAliasing(int requested)
|
||||
{
|
||||
if (requested <= 1) return 1;
|
||||
if (requested <= 2) return 2;
|
||||
if (requested <= 4) return 4;
|
||||
return 8;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 目标设置指纹:变了就要重建 RenderTexture。尺寸、格式、采样、深度都会换掉显存布局。
|
||||
/// </summary>
|
||||
public string GetTargetSignature()
|
||||
{
|
||||
return width + "x" + height + "_" + (hdr ? "f" : "l") + "_" + antiAliasing + "_" + depthBuffer + "_" + (sRGB ? "s" : "l");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按当前设置造一张未被使用过的 RenderTexture(调用方负责销毁)。
|
||||
/// <paramref name="samples"/> 传负数表示按设置走;解析目标必须显式传 1——
|
||||
/// 往多采样目标上 Blit 是非法的,MSAA 那条路要靠"先画采样目标、再落地到单采样目标"。
|
||||
/// </summary>
|
||||
public RenderTexture CreateRenderTexture(string name = "ShaderBakeTarget", int samples = -1)
|
||||
{
|
||||
Clamp();
|
||||
int actualSamples = samples < 0 ? antiAliasing : SnapAntiAliasing(samples);
|
||||
if (hdr && actualSamples > 1)
|
||||
actualSamples = 1;
|
||||
var rt = new RenderTexture(width, height, depthBuffer, format, renderTextureColorSpace)
|
||||
{
|
||||
name = name,
|
||||
filterMode = filterMode,
|
||||
wrapMode = wrapMode,
|
||||
antiAliasing = actualSamples,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
// 显式 Create:antiAliasing 只有在初始化之前赋值才生效,靠第一次使用时自动建就丢了
|
||||
rt.Create();
|
||||
return rt;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 03abdcca544f3a346ba5202158b34274
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// RenderTexture → 可读 Texture2D,以及透明压平。
|
||||
///
|
||||
/// <para><b>为什么用 ReadPixels 而不是 AsyncGPUReadback</b>:后者要等帧,回调里的数据这一轮就拿不到,
|
||||
/// 而"点导出→拿到文件"这条链要的是同步返回。烘焙一张图本来就是离线动作, stall 一帧无所谓。</para>
|
||||
/// </summary>
|
||||
public static class ShaderBakeReadback
|
||||
{
|
||||
/// <summary>
|
||||
/// 把目标读回成可读纹理。<paramref name="linear"/> 决定纹理按线性还是 sRGB 解释,
|
||||
/// 必须和生成它的那张 RenderTexture 一致,否则同一张图在编辑器和文件里会差一层 gamma。
|
||||
/// </summary>
|
||||
public static Texture2D ToTexture2D(RenderTexture source, TextureFormat format, bool linear, bool mipChain = false)
|
||||
{
|
||||
if (source == null)
|
||||
throw new ArgumentNullException(nameof(source));
|
||||
|
||||
var texture = new Texture2D(source.width, source.height, format, mipChain, linear)
|
||||
{
|
||||
name = source.name,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
CopyInto(source, texture, mipChain);
|
||||
return texture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读进一张已存在的纹理(尺寸要和 source 一致;不一致 Unity 只会填左上角,剩下留黑)。
|
||||
/// 走 RenderTexture.active + ReadPixels,MSAA 目标已被调用方解析过,这里读到的是解析后的像素。
|
||||
/// </summary>
|
||||
public static void CopyInto(RenderTexture source, Texture2D destination, bool recalculateMipMaps = false)
|
||||
{
|
||||
RenderTexture previous = RenderTexture.active;
|
||||
try
|
||||
{
|
||||
RenderTexture.active = source;
|
||||
destination.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0, recalculateMipMaps);
|
||||
destination.Apply(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
RenderTexture.active = previous;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把浮点/带 alpha 的纹理压成 RGB24:透明部分按 <paramref name="background"/> 混合,
|
||||
/// 分量截到 0~1。JPG 没有 alpha 通道,直接用原图编码会得到一圈发黑的边。
|
||||
/// </summary>
|
||||
public static Texture2D FlattenOntoBackground(Texture2D source, Color background)
|
||||
{
|
||||
int width = source.width;
|
||||
int height = source.height;
|
||||
var flattened = new Texture2D(width, height, TextureFormat.RGB24, false, false)
|
||||
{
|
||||
name = source.name,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
|
||||
Color[] pixels = source.GetPixels();
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
{
|
||||
Color p = pixels[i];
|
||||
float a = Mathf.Clamp01(p.a);
|
||||
pixels[i] = new Color(
|
||||
Mathf.Lerp(background.r, p.r, a),
|
||||
Mathf.Lerp(background.g, p.g, a),
|
||||
Mathf.Lerp(background.b, p.b, a),
|
||||
1f);
|
||||
}
|
||||
flattened.SetPixels(pixels);
|
||||
flattened.Apply(false);
|
||||
return flattened;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 结果统计:把目标降采样到 64×64 再读回,算出"有不透明像素的比例"和它们的平均颜色。
|
||||
///
|
||||
/// <para><b>为什么值得花这一次读回</b>:离屏烘焙最常见的两种失败——"什么都没画出来"(剔除、
|
||||
/// pass、相机框不住)与"画出来了但 alpha 是 0"(贴图没指定、混合模式吃掉颜色)——在预览里
|
||||
/// 长得一模一样,都是棋盘格。有一个数字就能把它们分开。</para>
|
||||
/// </summary>
|
||||
public static bool MeasureCoverage(RenderTexture source, out float opaqueRatio, out Color averageColor)
|
||||
{
|
||||
opaqueRatio = 0f;
|
||||
averageColor = Color.clear;
|
||||
if (source == null || !source.IsCreated())
|
||||
return false;
|
||||
|
||||
const int side = 64;
|
||||
RenderTexture previous = RenderTexture.active;
|
||||
RenderTexture small = RenderTexture.GetTemporary(side, side, 0,
|
||||
RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
|
||||
var probe = new Texture2D(side, side, TextureFormat.RGBA32, false, true)
|
||||
{
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
try
|
||||
{
|
||||
// 用 GetTemporary 而不是自己建:省掉一次显存分配,也躲开"目标正在被显示"的占用冲突
|
||||
Graphics.Blit(source, small);
|
||||
RenderTexture.active = small;
|
||||
probe.ReadPixels(new Rect(0, 0, side, side), 0, 0, false);
|
||||
probe.Apply(false);
|
||||
|
||||
Color32[] pixels = probe.GetPixels32();
|
||||
int opaque = 0;
|
||||
float r = 0f, g = 0f, b = 0f;
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
{
|
||||
// 阈值 8/255:线性插值边缘那一圈极淡的像素不该算成"画出来了"
|
||||
if (pixels[i].a <= 8)
|
||||
continue;
|
||||
opaque++;
|
||||
r += pixels[i].r;
|
||||
g += pixels[i].g;
|
||||
b += pixels[i].b;
|
||||
}
|
||||
opaqueRatio = (float)opaque / pixels.Length;
|
||||
if (opaque > 0)
|
||||
averageColor = new Color(r / opaque / 255f, g / opaque / 255f, b / opaque / 255f, 1f);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
RenderTexture.active = previous;
|
||||
RenderTexture.ReleaseTemporary(small);
|
||||
ShaderBakeRenderer.ReleaseTempObject(probe);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把一张纹理/RT 画成 Sprite。注意 Sprite 不拥有纹理:纹理销毁了 Sprite 就空了,
|
||||
/// 所以调用方要么留着纹理,要么连纹理一起作为资产存下来。
|
||||
/// </summary>
|
||||
public static Sprite ToSprite(Texture2D texture, Vector2 pivot, float pixelsPerUnit, string name = null)
|
||||
{
|
||||
if (texture == null)
|
||||
throw new ArgumentNullException(nameof(texture));
|
||||
var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), pivot, pixelsPerUnit);
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
sprite.name = name;
|
||||
return sprite;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 91e2060e655b6264585f07d092ad4908
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,433 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 把材质渲染成图的执行者。<b>运行时与编辑器都能用</b>:全程不碰 UnityEditor,
|
||||
/// 不往场景里放相机或 GameObject——离屏渲染靠 CommandBuffer 自带视图/投影矩阵。
|
||||
///
|
||||
/// <para><b>用法</b>:<c>using (var r = new ShaderBakeRenderer(mat)) { var tex = r.RenderToTexture2D(); ... }</c>,
|
||||
/// 或者常驻一个实例反复改 <see cref="settings"/> 再 <see cref="Render"/>(预览就是这条路)。</para>
|
||||
///
|
||||
/// <para><b>已知的渲染环境限制</b>:没有真实相机,于是灯光、雾、环境光、阴影都不参与——
|
||||
/// Unlit 类 shader 效果一致,Surface/光照类 shader 会渲成"无灯"。要带光照请改用场景相机截帧,
|
||||
/// 那是另一条路,这里不假装支持。</para>
|
||||
/// </summary>
|
||||
public sealed class ShaderBakeRenderer : IDisposable
|
||||
{
|
||||
/// <summary> 怎么渲。外部可以直接改这个对象里的字段,改完调用 Render 就会跟着生效。 </summary>
|
||||
public ShaderBakeSettings settings = ShaderBakeSettings.CreateDefault();
|
||||
|
||||
/// <summary> 渲什么。允许为 null(此时 Render 返回 null 并留一条 lastError)。 </summary>
|
||||
public Material material;
|
||||
|
||||
/// <summary> 最近一次失败的原因;成功时清空。给界面状态栏用,不让用户去 Console 里找。 </summary>
|
||||
public string lastError = string.Empty;
|
||||
|
||||
private Mesh m_Geometry;
|
||||
private string m_GeometrySignature = string.Empty;
|
||||
private RenderTexture m_OwnedTarget;
|
||||
private string m_TargetSignature = string.Empty;
|
||||
private RenderTexture m_MultiSampleSource;
|
||||
private CommandBuffer m_Buffer;
|
||||
private MaterialPropertyBlock m_Block;
|
||||
|
||||
/// <summary> 当前这次烘焙用的网格(只读用途,外部别销毁) </summary>
|
||||
public Mesh geometry { get { return m_Geometry; } }
|
||||
|
||||
/// <summary> 上一次渲染留下的目标(可能为 null)。预览直接拿它显示,省一次重建。 </summary>
|
||||
public RenderTexture target { get { return m_OwnedTarget; } }
|
||||
|
||||
/// <summary> 面片在世界空间的包围盒(相机框位用) </summary>
|
||||
public Bounds geometryBounds
|
||||
{
|
||||
get { return ShaderBakeGeometryBuilder.GetWorldBounds(m_Geometry, settings.surface.localMatrix); }
|
||||
}
|
||||
|
||||
/// <summary> 参数变了但还没重画:界面用它决定状态栏写"待刷新"还是"已渲染" </summary>
|
||||
public bool isDirty
|
||||
{
|
||||
get { return m_TargetSignature != settings.output.GetTargetSignature() || m_GeometrySignature != settings.surface.GetGeometrySignature(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渲一次。<paramref name="target"/> 为空时用内部缓存的目标(尺寸变了自动重建),
|
||||
/// 非空时渲进调用方那张(要求宽高与 settings.output 一致,否则 Unity 只会画一部分)。
|
||||
/// 返回真正写入了结果的那张 RT,可能是传入的那张,也可能是内部那张。
|
||||
/// </summary>
|
||||
public RenderTexture Render(RenderTexture target = null)
|
||||
{
|
||||
lastError = string.Empty;
|
||||
|
||||
if (material == null)
|
||||
{
|
||||
lastError = "没有材质:先给一个 Shader 或 Material";
|
||||
return null;
|
||||
}
|
||||
if (material.shader == null)
|
||||
{
|
||||
lastError = "材质上的 shader 丢了";
|
||||
return null;
|
||||
}
|
||||
|
||||
settings.ClampAll();
|
||||
EnsureGeometry();
|
||||
if (m_Geometry == null)
|
||||
{
|
||||
lastError = "几何构建失败";
|
||||
return null;
|
||||
}
|
||||
|
||||
RenderTexture dest = target ?? EnsureOwnedTarget();
|
||||
if (dest == null)
|
||||
{
|
||||
lastError = "目标纹理创建失败(尺寸或格式超出显卡限制)";
|
||||
return null;
|
||||
}
|
||||
|
||||
// MSAA 目标不能直接被 ReadPixels 读到解析后的像素,所以先画进采样目标,再 Blit 回普通目标
|
||||
bool needResolve = settings.output.antiAliasing > 1 && target == null && m_MultiSampleSource != null;
|
||||
RenderTexture drawn = needResolve ? m_MultiSampleSource : dest;
|
||||
|
||||
DrawInto(drawn);
|
||||
|
||||
if (needResolve)
|
||||
Graphics.Blit(m_MultiSampleSource, dest);
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/// <summary> 渲成可读 Texture2D(调用方负责销毁)。导出文件与存资产都从这里出发。 </summary>
|
||||
public Texture2D RenderToTexture2D(bool generateMips = false)
|
||||
{
|
||||
RenderTexture rt = Render();
|
||||
if (rt == null)
|
||||
return null;
|
||||
var texture = ShaderBakeReadback.ToTexture2D(rt, settings.output.textureFormat, settings.output.isLinearTexture, generateMips);
|
||||
texture.name = material != null ? material.name : "ShaderBakeResult";
|
||||
return texture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渲成 Sprite。返回的 Sprite 持有那张纹理,<b>别去销毁 sprite.texture</b>;
|
||||
/// 默认轴心在正中、100 像素=1 单位,和 Unity 新建 Sprite 的默认值一致。
|
||||
/// </summary>
|
||||
public Sprite RenderToSprite(float pixelsPerUnit = 100f, float pivotX = 0.5f, float pivotY = 0.5f)
|
||||
{
|
||||
Texture2D texture = RenderToTexture2D(false);
|
||||
if (texture == null)
|
||||
return null;
|
||||
return ShaderBakeReadback.ToSprite(texture, new Vector2(pivotX, pivotY), Mathf.Max(pixelsPerUnit, 0.01f), texture.name);
|
||||
}
|
||||
|
||||
/// <summary> 渲成图片文件的字节。textureToKeep 非空时把中间纹理交出去由调用方销毁,否则就地销毁。 </summary>
|
||||
public byte[] RenderToBytes(ShaderBakeImageFormat format, out Texture2D textureToKeep)
|
||||
{
|
||||
textureToKeep = null;
|
||||
Texture2D texture = RenderToTexture2D(false);
|
||||
if (texture == null)
|
||||
return null;
|
||||
if (format.NeedsFloatSource() && !settings.output.hdr)
|
||||
Debug.LogWarning("[ShaderBake] EXR 建议配 HDR 输出,否则值域被截到 0~1");
|
||||
|
||||
byte[] bytes = format.Encode(texture, settings.output.clearColor);
|
||||
textureToKeep = texture;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary> 渲成图片文件的字节(中间纹理自动回收) </summary>
|
||||
public byte[] RenderToBytes(ShaderBakeImageFormat format, bool destroyTexture = true)
|
||||
{
|
||||
Texture2D texture;
|
||||
byte[] bytes = RenderToBytes(format, out texture);
|
||||
if (destroyTexture && texture != null)
|
||||
ReleaseTempObject(texture);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary> 把相机挪到刚好框住面片。改了尺寸/位置之后按一下就回到"看得见"的状态。 </summary>
|
||||
public void FitCameraToGeometry()
|
||||
{
|
||||
EnsureGeometry();
|
||||
if (m_Geometry == null)
|
||||
return;
|
||||
settings.camera.FrameBounds(geometryBounds, settings.aspect);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把浏览图上的一个点(0~1,左上为原点)打到面片网络上,返回命中的格子序号。
|
||||
/// 用的是与烘焙完全相同的投影,所以"看到的哪一格"和"点到的哪一格"是同一套坐标。
|
||||
/// </summary>
|
||||
public bool TryPickFace(Vector2 viewport01, out int faceIndex)
|
||||
{
|
||||
faceIndex = -1;
|
||||
Matrix4x4 viewProjection;
|
||||
if (!TryGetViewProjection(out viewProjection))
|
||||
return false;
|
||||
|
||||
ShaderBakeSurfaceSettings surface = settings.surface;
|
||||
float ndcX = viewport01.x * 2f - 1f;
|
||||
float ndcY = 1f - viewport01.y * 2f;
|
||||
Matrix4x4 inverse = viewProjection.inverse;
|
||||
Vector3 near = Unproject(inverse, new Vector3(ndcX, ndcY, -1f));
|
||||
Vector3 far = Unproject(inverse, new Vector3(ndcX, ndcY, 1f));
|
||||
Vector3 direction = far - near;
|
||||
|
||||
Matrix4x4 local = surface.localMatrix;
|
||||
Vector3 planePoint = local.MultiplyPoint3x4(Vector3.zero);
|
||||
Vector3 planeNormal = local.MultiplyVector(Vector3.forward).normalized;
|
||||
float denominator = Vector3.Dot(direction, planeNormal);
|
||||
if (Mathf.Abs(denominator) < 0.000001f)
|
||||
return false;
|
||||
float distance = Vector3.Dot(planePoint - near, planeNormal) / denominator;
|
||||
if (distance < 0f)
|
||||
return false;
|
||||
|
||||
int columns = Mathf.Max(surface.gridColumns, 1);
|
||||
int rows = Mathf.Max(surface.gridRows, 1);
|
||||
Vector3 localPoint = local.inverse.MultiplyPoint3x4(near + direction * distance);
|
||||
float totalWidth = surface.size.x * columns;
|
||||
float totalHeight = surface.size.y * rows;
|
||||
float u = (localPoint.x + totalWidth * 0.5f) / totalWidth;
|
||||
float v = (localPoint.y + totalHeight * 0.5f) / totalHeight;
|
||||
if (u < 0f || u > 1f || v < 0f || v > 1f)
|
||||
return false;
|
||||
int column = Mathf.Clamp(Mathf.FloorToInt(u * columns), 0, columns - 1);
|
||||
int row = Mathf.Clamp(Mathf.FloorToInt(v * rows), 0, rows - 1);
|
||||
faceIndex = row * columns + column;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 某一格在浏览图上的矩形范围(0~1,左上为原点),用来把选中高亮贴在图上。
|
||||
/// 透视或旋转时这是一个外接框,不是精确的四边形轮廓。
|
||||
/// </summary>
|
||||
public bool TryGetFaceViewportBounds(int faceIndex, out Vector2 min, out Vector2 max)
|
||||
{
|
||||
min = Vector2.zero;
|
||||
max = Vector2.zero;
|
||||
Matrix4x4 viewProjection;
|
||||
if (!TryGetViewProjection(out viewProjection))
|
||||
return false;
|
||||
|
||||
ShaderBakeSurfaceSettings surface = settings.surface;
|
||||
int columns = Mathf.Max(surface.gridColumns, 1);
|
||||
int rows = Mathf.Max(surface.gridRows, 1);
|
||||
if (faceIndex < 0 || faceIndex >= columns * rows)
|
||||
return false;
|
||||
|
||||
float faceWidth = surface.size.x;
|
||||
float faceHeight = surface.size.y;
|
||||
int column = faceIndex % columns;
|
||||
int row = faceIndex / columns;
|
||||
float x0 = -faceWidth * columns * 0.5f + column * faceWidth;
|
||||
float y0 = -faceHeight * rows * 0.5f + row * faceHeight;
|
||||
float x1 = x0 + faceWidth;
|
||||
float y1 = y0 + faceHeight;
|
||||
|
||||
Matrix4x4 local = surface.localMatrix;
|
||||
bool first = true;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
Vector3 corner = new Vector3((i & 1) == 0 ? x0 : x1, (i & 2) == 0 ? y0 : y1, 0f);
|
||||
Vector4 clip = viewProjection * local.MultiplyPoint3x4(corner);
|
||||
if (clip.w <= 0.0001f)
|
||||
return false;
|
||||
float u = (clip.x / clip.w + 1f) * 0.5f;
|
||||
float v = 1f - (clip.y / clip.w + 1f) * 0.5f;
|
||||
if (float.IsNaN(u) || float.IsNaN(v))
|
||||
return false;
|
||||
var point = new Vector2(Mathf.Clamp01(u), Mathf.Clamp01(v));
|
||||
if (first)
|
||||
{
|
||||
min = max = point;
|
||||
first = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
min = Vector2.Min(min, point);
|
||||
max = Vector2.Max(max, point);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryGetViewProjection(out Matrix4x4 viewProjection)
|
||||
{
|
||||
viewProjection = Matrix4x4.identity;
|
||||
if (settings == null || settings.surface == null)
|
||||
return false;
|
||||
// 外部网格不是平面,"点选格子"这件事对它没有意义
|
||||
if (settings.surface.kind == ShaderBakeSurfaceKind.Mesh && settings.surface.sourceMesh != null)
|
||||
return false;
|
||||
|
||||
Matrix4x4 projection = settings.camera.GetProjectionMatrix(settings.aspect);
|
||||
if (settings.output.flipY)
|
||||
projection = Matrix4x4.Scale(new Vector3(1f, -1f, 1f)) * projection;
|
||||
viewProjection = projection * settings.camera.viewMatrix;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Vector3 Unproject(Matrix4x4 inverse, Vector3 clip)
|
||||
{
|
||||
Vector4 point = inverse * new Vector4(clip.x, clip.y, clip.z, 1f);
|
||||
float w = Mathf.Abs(point.w) < 0.0000001f ? 0.0000001f : point.w;
|
||||
return new Vector3(point.x / w, point.y / w, point.z / w);
|
||||
}
|
||||
|
||||
/// <summary> 网格与相机指纹都记下来,界面据此判断要不要重建 </summary>
|
||||
public string stateSignature
|
||||
{
|
||||
get { return settings.output.GetTargetSignature() + "|" + settings.surface.GetGeometrySignature() + "|" + settings.camera.GetCameraSignature(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只重建网格(面片参数变了)。渲染路径本来就会在签名不符时重建,这里给界面留个显式入口。
|
||||
/// </summary>
|
||||
public void InvalidateGeometry()
|
||||
{
|
||||
m_GeometrySignature = string.Empty;
|
||||
}
|
||||
|
||||
private void EnsureGeometry()
|
||||
{
|
||||
string signature = settings.surface.GetGeometrySignature();
|
||||
if (m_Geometry != null && signature == m_GeometrySignature)
|
||||
return;
|
||||
|
||||
ReleaseTempObject(m_Geometry);
|
||||
m_Geometry = ShaderBakeGeometryBuilder.Build(settings.surface);
|
||||
m_GeometrySignature = signature;
|
||||
}
|
||||
|
||||
private RenderTexture EnsureOwnedTarget()
|
||||
{
|
||||
string signature = settings.output.GetTargetSignature();
|
||||
if (m_OwnedTarget != null && signature == m_TargetSignature)
|
||||
return m_OwnedTarget;
|
||||
|
||||
ReleaseTempObject(m_OwnedTarget);
|
||||
ReleaseTempObject(m_MultiSampleSource);
|
||||
// 落地目标永远单采样:它要能被 ReadPixels 读、能被 Blit 写入、也直接拿去显示
|
||||
m_OwnedTarget = settings.output.CreateRenderTexture("ShaderBakeTarget", 1);
|
||||
m_TargetSignature = m_OwnedTarget != null ? signature : string.Empty;
|
||||
|
||||
if (settings.output.antiAliasing > 1 && m_OwnedTarget != null)
|
||||
m_MultiSampleSource = settings.output.CreateRenderTexture("ShaderBakeMultiSample", settings.output.antiAliasing);
|
||||
|
||||
return m_OwnedTarget;
|
||||
}
|
||||
|
||||
private void DrawInto(RenderTexture rt)
|
||||
{
|
||||
if (m_Buffer == null)
|
||||
{
|
||||
m_Buffer = new CommandBuffer { name = "XericUI.ShaderBake" };
|
||||
}
|
||||
|
||||
Matrix4x4 projection = settings.camera.GetProjectionMatrix(settings.aspect);
|
||||
if (settings.output.flipY)
|
||||
projection = Matrix4x4.Scale(new Vector3(1f, -1f, 1f)) * projection;
|
||||
|
||||
m_Buffer.Clear();
|
||||
m_Buffer.SetRenderTarget(rt, 0, CubemapFace.Unknown, 0);
|
||||
m_Buffer.ClearRenderTarget(true, true, settings.output.clearColor, 1f);
|
||||
m_Buffer.SetViewProjectionMatrices(settings.camera.viewMatrix, projection);
|
||||
// UV 已经烘进顶点了;只有用户显式要求时再补一份 _MainTex_ST 给依赖 ST 的 shader。
|
||||
// 走属性块而不是改材质,是为了不让这一笔写进材质副本、进而被"写回原材质"带走。
|
||||
MaterialPropertyBlock block = null;
|
||||
if (settings.surface.applyUvToMainTexST)
|
||||
{
|
||||
if (m_Block == null)
|
||||
m_Block = new MaterialPropertyBlock();
|
||||
m_Block.Clear();
|
||||
m_Block.SetVector("_MainTex_ST", new Vector4(
|
||||
settings.surface.uvTiling.x, settings.surface.uvTiling.y,
|
||||
settings.surface.uvOffset.x, settings.surface.uvOffset.y));
|
||||
block = m_Block;
|
||||
}
|
||||
|
||||
m_Buffer.DrawMesh(m_Geometry, settings.surface.localMatrix, material,
|
||||
Mathf.Max(settings.surface.meshSubMesh, 0), settings.output.shaderPass, block);
|
||||
|
||||
// 翻 Y 的投影是一次镜像,会把绕序反过来,背面剔除于是剔掉本该看见的正面。
|
||||
// 不动网格(外部模型的绕序不该被我们改),只在这一刻把剔除方向反过来。
|
||||
bool previousInvert = GL.invertCulling;
|
||||
GL.invertCulling = previousInvert != settings.output.flipY;
|
||||
List<Action> restoreGlobals = settings.globals != null ? settings.globals.Apply() : null;
|
||||
try
|
||||
{
|
||||
Graphics.ExecuteCommandBuffer(m_Buffer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GL.invertCulling = previousInvert;
|
||||
// 画完立刻还原:这些是编辑器全局状态,留一次烘焙的值下来会污染别处的渲染
|
||||
if (restoreGlobals != null)
|
||||
{
|
||||
for (int i = restoreGlobals.Count - 1; i >= 0; i--)
|
||||
restoreGlobals[i]();
|
||||
}
|
||||
}
|
||||
m_Buffer.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 回收一次性对象。运行时要走 <c>Destroy</c>(当帧不能立即销毁),编辑器里请传
|
||||
/// <paramref name="immediate"/> 让 <c>DestroyImmediate</c> 立刻放掉显存——导一批图时差别很大。
|
||||
/// </summary>
|
||||
public static void ReleaseTempObject(UnityEngine.Object obj)
|
||||
{
|
||||
ReleaseTempObject(obj, false);
|
||||
}
|
||||
|
||||
public static void ReleaseTempObject(UnityEngine.Object obj, bool immediate)
|
||||
{
|
||||
if (obj == null)
|
||||
return;
|
||||
#if UNITY_EDITOR
|
||||
if (immediate || !Application.isPlaying)
|
||||
UnityEngine.Object.DestroyImmediate(obj);
|
||||
else
|
||||
UnityEngine.Object.Destroy(obj);
|
||||
#else
|
||||
UnityEngine.Object.Destroy(obj);
|
||||
#endif
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
/// <summary> 编辑器里关窗口时传 immediate,显存和网格内存当场还回去 </summary>
|
||||
public void Dispose(bool immediate)
|
||||
{
|
||||
if (m_Buffer != null)
|
||||
{
|
||||
// 只 Dispose:Dispose 内部已经 Release,再单独 Release 一次会二次释放,
|
||||
// 2021.3 上表现为关闭窗口时抛 _unity_self 为空的 ArgumentNullException
|
||||
try
|
||||
{
|
||||
m_Buffer.Dispose();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 退出编辑器/域重载期间原生对象可能已被回收,这时再报错没有意义
|
||||
}
|
||||
m_Buffer = null;
|
||||
}
|
||||
ReleaseTempObject(m_MultiSampleSource, immediate);
|
||||
ReleaseTempObject(m_OwnedTarget, immediate);
|
||||
ReleaseTempObject(m_Geometry, immediate);
|
||||
m_MultiSampleSource = null;
|
||||
m_OwnedTarget = null;
|
||||
m_Geometry = null;
|
||||
m_TargetSignature = string.Empty;
|
||||
m_GeometrySignature = string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b3ca0c634575cad4bb7704b10761be85
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 一次烘焙所需的全部参数:输出 / 面片 / 离屏相机三组。
|
||||
/// 材质不进这里——材质是"内容",会换、会被就地编辑,而这一份是"怎么渲",可以存下来复用。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeSettings
|
||||
{
|
||||
[Tooltip("输出目标")]
|
||||
public ShaderBakeOutputSettings output = new ShaderBakeOutputSettings();
|
||||
|
||||
[Tooltip("被渲染的面片")]
|
||||
public ShaderBakeSurfaceSettings surface = new ShaderBakeSurfaceSettings();
|
||||
|
||||
[Tooltip("离屏相机")]
|
||||
public ShaderBakeCameraSettings camera = new ShaderBakeCameraSettings();
|
||||
|
||||
[Tooltip("渲染前注入的全局参数(光照方向、环境光、反射贴图等)")]
|
||||
public ShaderBakeGlobalSettings globals = new ShaderBakeGlobalSettings();
|
||||
|
||||
/// <summary> 画面宽高比 </summary>
|
||||
public float aspect
|
||||
{
|
||||
get
|
||||
{
|
||||
if (output.height <= 0 || output.width <= 0) return 1f;
|
||||
return (float)output.width / output.height;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 三组参数各自归位 </summary>
|
||||
public void ClampAll()
|
||||
{
|
||||
output.Clamp();
|
||||
surface.Clamp();
|
||||
camera.Clamp();
|
||||
}
|
||||
|
||||
/// <summary> 复制一份(编辑器窗口拿它当工作副本,改坏了不至于污染存下来的那份) </summary>
|
||||
public ShaderBakeSettings Clone()
|
||||
{
|
||||
return FromJson(ToJson());
|
||||
}
|
||||
|
||||
/// <summary> JsonUtility 只吃 [Serializable] 的类,这里三组都满足;Mesh / 材质引用序列化成实例ID,读回来时由界面重新指派 </summary>
|
||||
public string ToJson()
|
||||
{
|
||||
return JsonUtility.ToJson(this);
|
||||
}
|
||||
|
||||
public static ShaderBakeSettings FromJson(string json)
|
||||
{
|
||||
if (string.IsNullOrEmpty(json)) return CreateDefault();
|
||||
var s = new ShaderBakeSettings();
|
||||
JsonUtility.FromJsonOverwrite(json, s);
|
||||
s.ClampAll();
|
||||
return s;
|
||||
}
|
||||
|
||||
public static ShaderBakeSettings CreateDefault()
|
||||
{
|
||||
return new ShaderBakeSettings();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6008bb008b33a724c949a88f401dcd58
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,234 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 一个面片的 UV 区域编号:面片 (0,0) 用 UV [0,1],左边一格是 [-1,0],右边一格是 [1,2],以此类推。
|
||||
/// 网格里按行优先存放(第 0 行是 y 最小的一行)。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeFaceCell
|
||||
{
|
||||
public int uvX;
|
||||
public int uvY;
|
||||
|
||||
public ShaderBakeFaceCell() { }
|
||||
|
||||
public ShaderBakeFaceCell(int x, int y)
|
||||
{
|
||||
uvX = x;
|
||||
uvY = y;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 被烘焙的几何面片是哪一种 </summary>
|
||||
public enum ShaderBakeSurfaceKind
|
||||
{
|
||||
/// <summary>单片四边形:两个三角面,UV 从 uvOffset 起、按 uvTiling 铺 </summary>
|
||||
Quad,
|
||||
|
||||
/// <summary>细分平面:顶点数量由 segments 决定,给"在顶点着色器里挪顶点"的 shader 留出梯度 </summary>
|
||||
Plane,
|
||||
|
||||
/// <summary>外部网格:模型(导入的或场景里挑的),UV 沿用网格自己的第 0 套再乘偏移缩放 </summary>
|
||||
Mesh
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 面片设置:形状、UV 变换与面片自身的变换("面片编辑"就是这一组数值)。
|
||||
///
|
||||
/// <para><b>UV 变换落在网格上而不是材质上</b>:这样 shader 里怎么写 <c>uv</c> 就怎么收到结果,
|
||||
/// 不会被 <c>_MainTex_ST</c> 之类的第二层缩放重复一遍。需要走 ST 的那类 shader 用
|
||||
/// <see cref="applyUvToMainTexST"/> 单独开。</para>
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeSurfaceSettings
|
||||
{
|
||||
/// <summary> 细分上限:单边 512 段=26 万顶点,再多就是把手抖拖进卡顿 </summary>
|
||||
public const int kMaxSegments = 512;
|
||||
|
||||
[Tooltip("面片种类:单片四边形 / 细分平面 / 外部网格")]
|
||||
public ShaderBakeSurfaceKind kind = ShaderBakeSurfaceKind.Quad;
|
||||
|
||||
[Tooltip("单张面片的尺寸(世界单位)。网格整体是它的 列数×行数 倍;外部网格只在 normalizeSize 打开时用它缩放")]
|
||||
public Vector2 size = Vector2.one;
|
||||
|
||||
[Tooltip("细分平面的行列段数。只有需要顶点插值的 shader 才要调大,四边形恒为 1x1")]
|
||||
public Vector2Int segments = Vector2Int.one;
|
||||
|
||||
[Tooltip("面片网格列数。每多一列就多一张 UV 区域,整体尺寸不变")]
|
||||
public int gridColumns = 1;
|
||||
|
||||
[Tooltip("面片网格行数")]
|
||||
public int gridRows = 1;
|
||||
|
||||
[Tooltip("每个面片对应的 UV 区域编号(行优先,第 0 行在下)。默认只有一格 (0,0)")]
|
||||
public List<ShaderBakeFaceCell> faces = new List<ShaderBakeFaceCell> { new ShaderBakeFaceCell(0, 0) };
|
||||
|
||||
[Tooltip("UV 起点偏移:把贴图的哪一块挪到面片左下角")]
|
||||
public Vector2 uvOffset;
|
||||
|
||||
[Tooltip("UV 重复次数(缩放):x/y 各铺几遍")]
|
||||
public Vector2 uvTiling = Vector2.one;
|
||||
|
||||
[Tooltip("外部网格(kind = 外部网格 时生效)")]
|
||||
public Mesh sourceMesh;
|
||||
|
||||
[Tooltip("外部网格用第几个 subMesh")]
|
||||
public int meshSubMesh;
|
||||
|
||||
[Tooltip("把外部网格归一化到 size 指定的尺寸(关掉就按模型原始米数渲,可能只占画面一角)")]
|
||||
public bool normalizeMeshSize = true;
|
||||
|
||||
[Tooltip("面片位置偏移")]
|
||||
public Vector3 position;
|
||||
|
||||
[Tooltip("面片旋转(欧拉角,度)")]
|
||||
public Vector3 eulerAngles;
|
||||
|
||||
[Tooltip("面片额外缩放(与 size 相乘,外部网格用它做整体缩放)")]
|
||||
public Vector3 scale = Vector3.one;
|
||||
|
||||
[Tooltip("把 UV 偏移/重复同时写进 _MainTex_ST:给 Standard / Unlit 那类靠 ST 做缩放的 shader 用")]
|
||||
public bool applyUvToMainTexST;
|
||||
|
||||
/// <summary>
|
||||
/// 双面绘制:正反两份绕序都写进网格。
|
||||
///
|
||||
/// <para><b>为什么要这么兜住</b>:这条链路没有相机,视图/投影矩阵是自己拼的(含一处 Z 镜像和
|
||||
/// 一个可选的 Y 镜像),"哪一侧算正面"于是成了我们自己的推导而不是引擎的保证;押错一次
|
||||
/// 就是整片被 Cull Back 剔掉,表现是"渲染成功、画面全透明"。两份绕序里同一时刻只有一份是
|
||||
/// 正面,所以透明混合不会被算两次。只有确定要复刻引擎的剔除行为时才关掉。</para>
|
||||
/// </summary>
|
||||
[Tooltip("双面绘制:正反两份绕序,避免押错正面约定导致整片被剔除")]
|
||||
public bool doubleSided = true;
|
||||
|
||||
/// <summary> 面片自己的局部变换矩阵(DrawMesh 用的那个 model 矩阵) </summary>
|
||||
public Matrix4x4 localMatrix
|
||||
{
|
||||
get { return Matrix4x4.TRS(position, Quaternion.Euler(eulerAngles), scale); }
|
||||
}
|
||||
|
||||
/// <summary> 面片网格单边上限:再多单张图已经容纳不下可辨认的细节了 </summary>
|
||||
public const int kMaxGrid = 16;
|
||||
|
||||
public int FaceCount { get { return gridColumns * gridRows; } }
|
||||
|
||||
public ShaderBakeFaceCell GetFace(int index)
|
||||
{
|
||||
EnsureFaces();
|
||||
return faces[Mathf.Clamp(index, 0, faces.Count - 1)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 让 faces 的数量与 gridColumns × gridRows 对齐。补出来的格子默认 (0,0),
|
||||
/// 真正的 UV 编号由 <see cref="AddColumn"/> / <see cref="AddRow"/> 按邻格推算。
|
||||
/// </summary>
|
||||
public void EnsureFaces()
|
||||
{
|
||||
gridColumns = Mathf.Clamp(gridColumns, 1, kMaxGrid);
|
||||
gridRows = Mathf.Clamp(gridRows, 1, kMaxGrid);
|
||||
if (faces == null)
|
||||
faces = new List<ShaderBakeFaceCell>();
|
||||
|
||||
int wanted = FaceCount;
|
||||
while (faces.Count < wanted)
|
||||
faces.Add(new ShaderBakeFaceCell(0, 0));
|
||||
if (faces.Count > wanted)
|
||||
faces.RemoveRange(wanted, faces.Count - wanted);
|
||||
for (int i = 0; i < faces.Count; i++)
|
||||
if (faces[i] == null)
|
||||
faces[i] = new ShaderBakeFaceCell(0, 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在左边/右边加一列。新列的 UV 编号取贴边那一列的编号往外挪一格——
|
||||
/// 这正是"左边加的面是 [-1,0]"这条规则的落点。
|
||||
/// </summary>
|
||||
public void AddColumn(bool right)
|
||||
{
|
||||
EnsureFaces();
|
||||
if (gridColumns >= kMaxGrid)
|
||||
return;
|
||||
|
||||
for (int row = gridRows - 1; row >= 0; row--)
|
||||
{
|
||||
int rowStart = row * gridColumns;
|
||||
int anchor = right ? rowStart + gridColumns - 1 : rowStart;
|
||||
ShaderBakeFaceCell source = faces[anchor];
|
||||
var cell = new ShaderBakeFaceCell(source.uvX + (right ? 1 : -1), source.uvY);
|
||||
faces.Insert(right ? anchor + 1 : rowStart, cell);
|
||||
}
|
||||
gridColumns++;
|
||||
}
|
||||
|
||||
/// <summary> 在上边/下边加一行,UV 编号同样从贴着的那一行往外推 </summary>
|
||||
public void AddRow(bool top)
|
||||
{
|
||||
EnsureFaces();
|
||||
if (gridRows >= kMaxGrid)
|
||||
return;
|
||||
|
||||
int offset = top ? faces.Count : 0;
|
||||
int anchorRow = top ? gridRows - 1 : 0;
|
||||
var added = new ShaderBakeFaceCell[gridColumns];
|
||||
for (int col = 0; col < gridColumns; col++)
|
||||
{
|
||||
ShaderBakeFaceCell source = faces[anchorRow * gridColumns + col];
|
||||
added[col] = new ShaderBakeFaceCell(source.uvX, source.uvY + (top ? 1 : -1));
|
||||
}
|
||||
faces.InsertRange(offset, added);
|
||||
gridRows++;
|
||||
}
|
||||
|
||||
/// <summary> 回到单片 (0,0) —— 网格加乱了时的退路 </summary>
|
||||
public void ResetGrid()
|
||||
{
|
||||
gridColumns = 1;
|
||||
gridRows = 1;
|
||||
faces = new List<ShaderBakeFaceCell> { new ShaderBakeFaceCell(0, 0) };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 收拢非法数值。段数与 subMesh 都可能被敲成负数或超出网格实际层数,这里一次归位。
|
||||
/// </summary>
|
||||
public void Clamp()
|
||||
{
|
||||
size = new Vector2(
|
||||
Mathf.Max(size.x, 0.0001f),
|
||||
Mathf.Max(size.y, 0.0001f));
|
||||
segments = new Vector2Int(
|
||||
Mathf.Clamp(segments.x, 1, kMaxSegments),
|
||||
Mathf.Clamp(segments.y, 1, kMaxSegments));
|
||||
scale = new Vector3(
|
||||
FixZero(scale.x),
|
||||
FixZero(scale.y),
|
||||
FixZero(scale.z));
|
||||
if (uvTiling.x == 0f) uvTiling.x = 1f;
|
||||
if (uvTiling.y == 0f) uvTiling.y = 1f;
|
||||
meshSubMesh = Mathf.Max(meshSubMesh, 0);
|
||||
EnsureFaces();
|
||||
}
|
||||
|
||||
private static float FixZero(float v)
|
||||
{
|
||||
return Mathf.Abs(v) < 0.0001f ? 1f : v;
|
||||
}
|
||||
|
||||
/// <summary> 几何指纹:变了就要重建网格 </summary>
|
||||
public string GetGeometrySignature()
|
||||
{
|
||||
var meshId = sourceMesh != null ? sourceMesh.GetInstanceID().ToString() : "none";
|
||||
var builder = new System.Text.StringBuilder(64);
|
||||
// 老存档里没有 faces 这一项,直接读会踩空;这里只算指纹,不做补全
|
||||
int faceCount = faces != null ? faces.Count : 0;
|
||||
for (int i = 0; i < faceCount; i++)
|
||||
builder.Append(faces[i].uvX).Append(',').Append(faces[i].uvY).Append(';');
|
||||
return kind + "_" + size + "_" + segments + "_" + uvOffset + "_" + uvTiling +
|
||||
"_" + position + "_" + eulerAngles + "_" + scale + "_" + meshId + "_" + meshSubMesh +
|
||||
"_" + normalizeMeshSize + "_" + doubleSided + "_" + gridColumns + "x" + gridRows + "_" + builder;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5b43d17582f4b254096aae006b3a0f3d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user