feat(ShaderBake): 面片网格与选面、导出尺寸预设

- 面片改成"一格一张 UV 区域"的网格,向左/下扩展时新格 UV 编号递减(左邻为 [-1,0])
- 每格 UV 编号可单独改写,并在右侧实时显示
- 浏览图支持点选面片(与烘焙同一套投影做射线求交),选中格显示高亮框与 UV 编号
- 输出尺寸增加常用预设下拉与"匹配面片比例"
This commit is contained in:
2026-11-05 17:43:11 +08:00
parent 0db9bd5462
commit a0512ad450
7 changed files with 583 additions and 42 deletions
+60 -38
View File
@@ -23,11 +23,11 @@ namespace XericUI.ShaderBake
switch (surface.kind)
{
case ShaderBakeSurfaceKind.Plane:
return BuildGrid(surface, Mathf.Max(surface.segments.x, 1), Mathf.Max(surface.segments.y, 1));
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 BuildGrid(surface, 1, 1);
return BuildFaces(surface, 1, 1);
}
}
@@ -63,52 +63,74 @@ namespace XericUI.ShaderBake
return bounds;
}
/// <summary> 网格在自身变换之后、相机之前的最大分量跨度,用于决定要不要走 uint32 索引 </summary>
private static Mesh BuildGrid(ShaderBakeSurfaceSettings surface, int columns, int rows)
/// <summary>
/// 按面片网格造一张平面:每个格子是一张完整的面片,UV 从自己格子的编号起算。
/// <paramref name="segmentsX"/>/<paramref name="segmentsY"/> 是<b>单张面片内部</b>的细分,
/// 给顶点着色器留梯度用;格子本身恒为一张。
/// </summary>
private static Mesh BuildFaces(ShaderBakeSurfaceSettings surface, int segmentsX, int segmentsY)
{
float halfWidth = surface.size.x * 0.5f;
float halfHeight = surface.size.y * 0.5f;
int columns = Mathf.Max(surface.gridColumns, 1);
int rows = Mathf.Max(surface.gridRows, 1);
segmentsX = Mathf.Max(segmentsX, 1);
segmentsY = Mathf.Max(segmentsY, 1);
int vertexCount = (columns + 1) * (rows + 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 * 6);
var triangles = new List<int>(columns * rows * segmentsX * segmentsY * 6);
for (int y = 0; y <= rows; y++)
int stride = segmentsX + 1;
for (int row = 0; row < rows; row++)
for (int column = 0; column < columns; column++)
{
float ty = rows == 0 ? 0f : (float)y / rows;
for (int x = 0; x <= columns; x++)
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 tx = columns == 0 ? 0f : (float)x / columns;
vertices.Add(new Vector3(
Mathf.Lerp(-halfWidth, halfWidth, tx),
Mathf.Lerp(-halfHeight, halfHeight, ty),
0f));
normals.Add(Vector3.back); // 面朝 -Z,即默认相机(朝 +Z 看)看到的正面
uvs.Add(RemapUv(new Vector2(tx, ty), surface));
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 认定顺时针为正面(视线方向上的屏幕顺时针),所以是 左下→左上→右下;
// 顺序写反了整张面片会被背面剔除掉,画面全空还查不出原因
triangles.Add(bottomLeft);
triangles.Add(topLeft);
triangles.Add(bottomRight);
triangles.Add(topLeft);
triangles.Add(topRight);
triangles.Add(bottomRight);
}
}
int stride = columns + 1;
for (int y = 0; y < rows; y++)
for (int x = 0; x < columns; x++)
{
int bottomLeft = y * stride + x;
int bottomRight = bottomLeft + 1;
int topLeft = bottomLeft + stride;
int topRight = topLeft + 1;
// Unity 认定顺时针为正面(视线方向上的屏幕顺时针),所以是 左下→左上→右下;
// 顺序写反了整张面片会被背面剔除掉,画面全空还查不出原因
triangles.Add(bottomLeft);
triangles.Add(topLeft);
triangles.Add(bottomRight);
triangles.Add(topLeft);
triangles.Add(topRight);
triangles.Add(bottomRight);
}
var mesh = NewMesh("ShaderBakeQuad");
var mesh = NewMesh(vertexCount > 65000 ? "ShaderBakeFaces" : "ShaderBakeQuad");
if (vertexCount > 65000)
mesh.indexFormat = IndexFormat.UInt32;
mesh.SetVertices(vertices);
mesh.SetNormals(normals);
mesh.SetUVs(0, uvs);
@@ -130,7 +152,7 @@ namespace XericUI.ShaderBake
if (vertices.Count == 0)
{
Debug.LogWarning("[ShaderBake] 外部网格没有顶点数据(可能是只读网格),退回单片四边形");
return BuildGrid(surface, 1, 1);
return BuildFaces(surface, 1, 1);
}
var normals = new List<Vector3>();
+121
View File
@@ -156,6 +156,127 @@ namespace XericUI.ShaderBake
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
{
+115 -2
View File
@@ -1,8 +1,28 @@
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
{
@@ -32,12 +52,21 @@ namespace XericUI.ShaderBake
[Tooltip("面片种类:单片四边形 / 细分平面 / 外部网格")]
public ShaderBakeSurfaceKind kind = ShaderBakeSurfaceKind.Quad;
[Tooltip("面片尺寸(世界单位)。四边形与细分平面用它的 x/y;外部网格只在 normalizeSize 打开时用它缩放")]
[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;
@@ -71,6 +100,86 @@ namespace XericUI.ShaderBake
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>
@@ -89,6 +198,7 @@ namespace XericUI.ShaderBake
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)
@@ -100,9 +210,12 @@ namespace XericUI.ShaderBake
public string GetGeometrySignature()
{
var meshId = sourceMesh != null ? sourceMesh.GetInstanceID().ToString() : "none";
var builder = new System.Text.StringBuilder(64);
for (int i = 0; i < faces.Count; i++)
builder.Append(faces[i].uvX).Append(',').Append(faces[i].uvY).Append(';');
return kind + "_" + size + "_" + segments + "_" + uvOffset + "_" + uvTiling +
"_" + position + "_" + eulerAngles + "_" + scale + "_" + meshId + "_" + meshSubMesh +
"_" + normalizeMeshSize;
"_" + normalizeMeshSize + "_" + gridColumns + "x" + gridRows + "_" + builder;
}
}
}