feat(ShaderBake): 面片网格与选面、导出尺寸预设
- 面片改成"一格一张 UV 区域"的网格,向左/下扩展时新格 UV 编号递减(左邻为 [-1,0]) - 每格 UV 编号可单独改写,并在右侧实时显示 - 浏览图支持点选面片(与烘焙同一套投影做射线求交),选中格显示高亮框与 UV 编号 - 输出尺寸增加常用预设下拉与"匹配面片比例"
This commit is contained in:
@@ -35,6 +35,14 @@ namespace XericUI.ShaderBake.Editor
|
||||
|
||||
private const float kDefaultDetailWidth = 340f;
|
||||
private static readonly string[] kAntiAliasingChoices = { "1", "2", "4", "8" };
|
||||
private const string kCustomSize = "自定义";
|
||||
|
||||
/// <summary> 常用导出尺寸。最后一项只是让当前值不在表里时下拉框有个落点 </summary>
|
||||
private static readonly string[] kSizePresets =
|
||||
{
|
||||
"256 × 256", "512 × 512", "1024 × 1024", "2048 × 2048", "4096 × 4096",
|
||||
"512 × 256", "1024 × 512", "2048 × 1024", kCustomSize
|
||||
};
|
||||
|
||||
private ShaderBakeMaterialSource m_Source;
|
||||
private ShaderBakeRenderer m_Renderer;
|
||||
@@ -59,6 +67,7 @@ namespace XericUI.ShaderBake.Editor
|
||||
|
||||
private bool m_RenderPending;
|
||||
private double m_LastRenderMs = -1;
|
||||
private int m_SelectedFace;
|
||||
|
||||
[MenuItem(XericRegistrationPaths.ToolBar + "/Bake Shader As Image", false, 20)]
|
||||
private static void OpenFromMenu()
|
||||
@@ -99,8 +108,11 @@ namespace XericUI.ShaderBake.Editor
|
||||
return;
|
||||
}
|
||||
|
||||
m_Preview.faceClicked += OnFaceClicked;
|
||||
|
||||
CollectReferences();
|
||||
BuildPropertyTable();
|
||||
BindFaceGrid();
|
||||
BindToolbar();
|
||||
BindSections();
|
||||
BindSettings();
|
||||
@@ -404,6 +416,15 @@ namespace XericUI.ShaderBake.Editor
|
||||
|
||||
private void BindOutput()
|
||||
{
|
||||
DropdownField preset = rootVisualElement.Q<DropdownField>("out-preset");
|
||||
if (preset != null)
|
||||
{
|
||||
preset.choices = new List<string>(kSizePresets);
|
||||
m_Syncers.Add(() => preset.SetValueWithoutNotify(CurrentSizePreset()));
|
||||
preset.RegisterValueChangedCallback(evt => ApplySizePreset(evt.newValue));
|
||||
}
|
||||
Click("out-fit-aspect", FitOutputAspect);
|
||||
|
||||
BindInt("out-width", () => m_Renderer.settings.output.width, v => m_Renderer.settings.output.width = v);
|
||||
BindInt("out-height", () => m_Renderer.settings.output.height, v => m_Renderer.settings.output.height = v);
|
||||
BindInt("out-depth", () => m_Renderer.settings.output.depthBuffer, v => m_Renderer.settings.output.depthBuffer = v);
|
||||
@@ -427,6 +448,167 @@ namespace XericUI.ShaderBake.Editor
|
||||
}
|
||||
}
|
||||
|
||||
private string CurrentSizePreset()
|
||||
{
|
||||
Vector2Int size = m_Renderer.settings.output.size;
|
||||
string label = size.x + " × " + size.y;
|
||||
for (int i = 0; i < kSizePresets.Length - 1; i++)
|
||||
if (kSizePresets[i] == label)
|
||||
return label;
|
||||
return kCustomSize;
|
||||
}
|
||||
|
||||
private void ApplySizePreset(string label)
|
||||
{
|
||||
if (label == kCustomSize)
|
||||
return;
|
||||
string[] parts = label.Split('×');
|
||||
if (parts.Length != 2)
|
||||
return;
|
||||
if (!int.TryParse(parts[0].Trim(), out int width) || !int.TryParse(parts[1].Trim(), out int height))
|
||||
return;
|
||||
m_Renderer.settings.output.width = width;
|
||||
m_Renderer.settings.output.height = height;
|
||||
Commit();
|
||||
}
|
||||
|
||||
/// <summary> 按面片网格的整体宽高比把高度对上,省得手算 </summary>
|
||||
private void FitOutputAspect()
|
||||
{
|
||||
ShaderBakeSettings settings = m_Renderer.settings;
|
||||
float totalWidth = settings.surface.size.x * settings.surface.gridColumns;
|
||||
float totalHeight = settings.surface.size.y * settings.surface.gridRows;
|
||||
if (totalWidth <= 0.0001f || totalHeight <= 0.0001f)
|
||||
return;
|
||||
settings.output.height = Mathf.Clamp(
|
||||
Mathf.RoundToInt(settings.output.width * totalHeight / totalWidth),
|
||||
ShaderBakeOutputSettings.kMinDimension, ShaderBakeOutputSettings.kMaxDimension);
|
||||
Commit();
|
||||
SetStatus("高度已按面片比例对齐");
|
||||
}
|
||||
|
||||
// ── 面片网格与选面 ──────────────────────────────────────
|
||||
|
||||
private void BindFaceGrid()
|
||||
{
|
||||
Click("grid-left", () => ResizeGrid(true, true));
|
||||
Click("grid-right", () => ResizeGrid(false, true));
|
||||
Click("grid-down", () => ResizeGrid(true, false));
|
||||
Click("grid-up", () => ResizeGrid(false, false));
|
||||
Click("grid-reset", () =>
|
||||
{
|
||||
m_Renderer.settings.surface.ResetGrid();
|
||||
m_SelectedFace = 0;
|
||||
Commit();
|
||||
});
|
||||
Click("face-zero", () =>
|
||||
{
|
||||
ShaderBakeFaceCell cell = SelectedFaceCell();
|
||||
if (cell == null)
|
||||
return;
|
||||
cell.uvX = 0;
|
||||
cell.uvY = 0;
|
||||
Commit();
|
||||
});
|
||||
|
||||
BindInt("face-uv-x",
|
||||
() => SelectedFaceCell() != null ? SelectedFaceCell().uvX : 0,
|
||||
v => { ShaderBakeFaceCell cell = SelectedFaceCell(); if (cell != null) cell.uvX = v; });
|
||||
BindInt("face-uv-y",
|
||||
() => SelectedFaceCell() != null ? SelectedFaceCell().uvY : 0,
|
||||
v => { ShaderBakeFaceCell cell = SelectedFaceCell(); if (cell != null) cell.uvY = v; });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在左/右加一列,或上/下加一行。新格的 UV 编号由 <see cref="ShaderBakeSurfaceSettings"/>
|
||||
/// 按贴边那一格往外推,所以向左加出来的一定是 [-1,0] 这种负号区间。
|
||||
/// </summary>
|
||||
private void ResizeGrid(bool negativeSide, bool column)
|
||||
{
|
||||
ShaderBakeSurfaceSettings surface = m_Renderer.settings.surface;
|
||||
if (column)
|
||||
surface.AddColumn(!negativeSide);
|
||||
else
|
||||
surface.AddRow(!negativeSide);
|
||||
Commit();
|
||||
SetStatus(surface.gridColumns + " × " + surface.gridRows + " 格");
|
||||
}
|
||||
|
||||
private ShaderBakeFaceCell SelectedFaceCell()
|
||||
{
|
||||
if (m_Renderer == null)
|
||||
return null;
|
||||
ShaderBakeSurfaceSettings surface = m_Renderer.settings.surface;
|
||||
if (surface.kind == ShaderBakeSurfaceKind.Mesh && surface.sourceMesh != null)
|
||||
return null;
|
||||
return surface.GetFace(m_SelectedFace);
|
||||
}
|
||||
|
||||
private void OnFaceClicked(Vector2 viewport01)
|
||||
{
|
||||
int face;
|
||||
if (!m_Renderer.TryPickFace(viewport01, out face))
|
||||
return;
|
||||
m_SelectedFace = face;
|
||||
RefreshFaceUi();
|
||||
SetStatus("选中第 " + (face + 1) + " 格");
|
||||
}
|
||||
|
||||
private void RefreshFaceUi()
|
||||
{
|
||||
if (m_Renderer == null)
|
||||
return;
|
||||
ShaderBakeSurfaceSettings surface = m_Renderer.settings.surface;
|
||||
int count = surface.FaceCount;
|
||||
m_SelectedFace = Mathf.Clamp(m_SelectedFace, 0, Mathf.Max(count - 1, 0));
|
||||
|
||||
Label gridInfo = rootVisualElement.Q<Label>("grid-info");
|
||||
if (gridInfo != null)
|
||||
gridInfo.text = surface.gridColumns + " × " + surface.gridRows + " 格";
|
||||
|
||||
bool meshMode = surface.kind == ShaderBakeSurfaceKind.Mesh && surface.sourceMesh != null;
|
||||
ShaderBakeFaceCell cell = meshMode ? null : surface.GetFace(m_SelectedFace);
|
||||
Label faceInfo = rootVisualElement.Q<Label>("face-info");
|
||||
if (faceInfo != null)
|
||||
{
|
||||
faceInfo.text = meshMode
|
||||
? "外部网格不参与面片点选"
|
||||
: "选中第 " + (m_SelectedFace + 1) + " 格:UV (" + cell.uvX + ", " + cell.uvY + ")";
|
||||
}
|
||||
SetFaceFieldsEnabled(!meshMode);
|
||||
UpdateFaceOverlay();
|
||||
}
|
||||
|
||||
private void SetFaceFieldsEnabled(bool enabled)
|
||||
{
|
||||
IntegerField x = rootVisualElement.Q<IntegerField>("face-uv-x");
|
||||
IntegerField y = rootVisualElement.Q<IntegerField>("face-uv-y");
|
||||
if (x != null) x.SetEnabled(enabled);
|
||||
if (y != null) y.SetEnabled(enabled);
|
||||
}
|
||||
|
||||
/// <summary> 把选中格的屏幕框和 UV 编号贴到浏览图上 </summary>
|
||||
private void UpdateFaceOverlay()
|
||||
{
|
||||
if (m_Preview == null || m_Renderer == null)
|
||||
return;
|
||||
ShaderBakeSurfaceSettings surface = m_Renderer.settings.surface;
|
||||
if (surface.kind == ShaderBakeSurfaceKind.Mesh && surface.sourceMesh != null)
|
||||
{
|
||||
m_Preview.SetFaceSelection(false, Vector2.zero, Vector2.zero, string.Empty);
|
||||
return;
|
||||
}
|
||||
|
||||
Vector2 min, max;
|
||||
if (!m_Renderer.TryGetFaceViewportBounds(m_SelectedFace, out min, out max))
|
||||
{
|
||||
m_Preview.SetFaceSelection(false, Vector2.zero, Vector2.zero, string.Empty);
|
||||
return;
|
||||
}
|
||||
ShaderBakeFaceCell cell = surface.GetFace(m_SelectedFace);
|
||||
m_Preview.SetFaceSelection(true, min, max, "UV (" + cell.uvX + ", " + cell.uvY + ")");
|
||||
}
|
||||
|
||||
// ── 面片 ────────────────────────────────────────────────
|
||||
|
||||
private void BindSurface()
|
||||
@@ -698,6 +880,7 @@ namespace XericUI.ShaderBake.Editor
|
||||
m_Renderer.settings.ClampAll();
|
||||
m_Renderer.InvalidateGeometry();
|
||||
SyncUiFromSettings();
|
||||
RefreshFaceUi();
|
||||
RequestRender();
|
||||
}
|
||||
|
||||
@@ -758,6 +941,7 @@ namespace XericUI.ShaderBake.Editor
|
||||
}
|
||||
|
||||
m_Preview.SetResult(rt, m_Renderer.settings.output.size);
|
||||
UpdateFaceOverlay();
|
||||
UpdateSizeReadout();
|
||||
if (string.IsNullOrEmpty(m_StatusMessage.text) || m_StatusMessage.text.StartsWith("导出"))
|
||||
SetStatus("已渲染");
|
||||
|
||||
@@ -181,6 +181,34 @@
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.field-quarter {
|
||||
flex-grow: 1;
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
margin-right: 3px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* ── 浏览图里的选中面片高亮 ── */
|
||||
.face-overlay {
|
||||
position: absolute;
|
||||
display: none;
|
||||
border-width: 1px;
|
||||
border-color: rgb(255, 196, 64);
|
||||
background-color: rgba(255, 196, 64, 0.14);
|
||||
}
|
||||
|
||||
.face-overlay-label {
|
||||
position: absolute;
|
||||
left: 2px;
|
||||
top: 2px;
|
||||
font-size: 10px;
|
||||
color: rgb(255, 224, 160);
|
||||
background-color: rgba(0, 0, 0, 0.55);
|
||||
padding: 0 4px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.field-toggle {
|
||||
font-size: 11px;
|
||||
margin-top: 2px;
|
||||
|
||||
@@ -38,6 +38,10 @@
|
||||
<ui:VisualElement name="preview-frame" class="preview-frame">
|
||||
<ui:Image name="preview-checker" class="preview-checker" />
|
||||
<ui:Image name="preview-image" class="preview-image" />
|
||||
<!-- 选中面片的高亮:位置按百分比算,缩放时不用重排 -->
|
||||
<ui:VisualElement name="face-overlay" class="face-overlay">
|
||||
<ui:Label name="face-overlay-label" class="face-overlay-label" text="UV (0,0)" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:ScrollView>
|
||||
@@ -68,6 +72,10 @@
|
||||
<ui:VisualElement name="sec-output" class="section">
|
||||
<ui:Toggle name="sec-output-head" label="输出" value="true" class="section-head" />
|
||||
<ui:VisualElement name="sec-output-body" class="section-body">
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:DropdownField name="out-preset" label="预设" class="field-half" />
|
||||
<ui:Button name="out-fit-aspect" text="匹配面片比例" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:IntegerField name="out-width" label="宽" class="field-half" />
|
||||
<xer:IntegerField name="out-height" label="高" class="field-half" />
|
||||
@@ -94,9 +102,28 @@
|
||||
<xer:FloatField name="surf-size-y" label="高" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:IntegerField name="surf-seg-x" label="列" class="field-half" />
|
||||
<xer:IntegerField name="surf-seg-y" label="行" class="field-half" />
|
||||
<xer:IntegerField name="surf-seg-x" label="面内细分列" class="field-half" />
|
||||
<xer:IntegerField name="surf-seg-y" label="面内细分行" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
|
||||
<ui:Label class="field-note" text="面片网格(一格一张 UV 区域,向左/下扩展编号递减)" />
|
||||
<ui:Label name="grid-info" class="field-note" text="1 × 1" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="grid-left" text="←加列" class="field-quarter" />
|
||||
<ui:Button name="grid-right" text="加列→" class="field-quarter" />
|
||||
<ui:Button name="grid-down" text="↓加行" class="field-quarter" />
|
||||
<ui:Button name="grid-up" text="↑加行" class="field-quarter" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="grid-reset" text="恢复 1×1" class="field-half" />
|
||||
<ui:Button name="face-zero" text="选中面归零" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:Label name="face-info" class="field-note" text="在左侧浏览图里点选面片" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:IntegerField name="face-uv-x" label="UV X" class="field-half" />
|
||||
<xer:IntegerField name="face-uv-y" label="UV Y" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
|
||||
<ui:Label class="field-note" text="UV" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="surf-uv-off-x" label="偏移X" class="field-half" />
|
||||
|
||||
@@ -20,6 +20,11 @@ namespace XericUI.ShaderBake.Editor
|
||||
private readonly Image m_Checker;
|
||||
private readonly Image m_Image;
|
||||
private readonly Label m_Readout;
|
||||
private readonly VisualElement m_FaceOverlay;
|
||||
private readonly Label m_FaceOverlayLabel;
|
||||
|
||||
/// <summary> 在图上点了一下(不是拖拽)。参数是 0~1、左上为原点的坐标 </summary>
|
||||
public event Action<Vector2> faceClicked;
|
||||
|
||||
private Texture2D m_CheckerTexture;
|
||||
private int m_CheckerWidth;
|
||||
@@ -29,6 +34,7 @@ namespace XericUI.ShaderBake.Editor
|
||||
private float m_Zoom = 1f;
|
||||
private bool m_AutoFit = true;
|
||||
private bool m_Dragging;
|
||||
private bool m_PointerMoved;
|
||||
private Vector2 m_DragStart;
|
||||
private Vector2 m_ScrollStart;
|
||||
|
||||
@@ -46,6 +52,10 @@ namespace XericUI.ShaderBake.Editor
|
||||
m_Checker = root.Q<Image>("preview-checker");
|
||||
m_Image = root.Q<Image>("preview-image");
|
||||
m_Readout = root.Q<Label>("preview-readout");
|
||||
m_FaceOverlay = root.Q<VisualElement>("face-overlay");
|
||||
m_FaceOverlayLabel = root.Q<Label>("face-overlay-label");
|
||||
if (m_FaceOverlay != null)
|
||||
m_FaceOverlay.pickingMode = PickingMode.Ignore;
|
||||
|
||||
if (m_Viewport == null || m_Frame == null || m_Image == null)
|
||||
throw new InvalidOperationException("BakeShaderWindow.uxml 缺少预览区节点");
|
||||
@@ -106,6 +116,27 @@ namespace XericUI.ShaderBake.Editor
|
||||
SetZoom(fit);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把选中面片的框贴到图上。范围是 0~1(左上为原点),用百分比定位,缩放/滚动都不用重算。
|
||||
/// </summary>
|
||||
public void SetFaceSelection(bool visible, Vector2 min, Vector2 max, string label)
|
||||
{
|
||||
if (m_FaceOverlay == null)
|
||||
return;
|
||||
if (!visible)
|
||||
{
|
||||
m_FaceOverlay.style.display = DisplayStyle.None;
|
||||
return;
|
||||
}
|
||||
m_FaceOverlay.style.display = DisplayStyle.Flex;
|
||||
m_FaceOverlay.style.left = Length.Percent(Mathf.Clamp01(min.x) * 100f);
|
||||
m_FaceOverlay.style.top = Length.Percent(Mathf.Clamp01(min.y) * 100f);
|
||||
m_FaceOverlay.style.width = Length.Percent(Mathf.Max(max.x - min.x, 0.002f) * 100f);
|
||||
m_FaceOverlay.style.height = Length.Percent(Mathf.Max(max.y - min.y, 0.002f) * 100f);
|
||||
if (m_FaceOverlayLabel != null)
|
||||
m_FaceOverlayLabel.text = label;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
m_PixelSize = Vector2Int.zero;
|
||||
@@ -188,6 +219,7 @@ namespace XericUI.ShaderBake.Editor
|
||||
if (m_PixelSize.x <= 0)
|
||||
return;
|
||||
m_Dragging = true;
|
||||
m_PointerMoved = false;
|
||||
m_DragStart = evt.position;
|
||||
m_ScrollStart = m_Viewport.scrollOffset;
|
||||
m_Viewport.CapturePointer(evt.pointerId);
|
||||
@@ -200,6 +232,8 @@ namespace XericUI.ShaderBake.Editor
|
||||
return;
|
||||
// 2022.1 的 position 是 Vector3,直接和 Vector2 相减会二义
|
||||
Vector2 delta = (Vector2)evt.position - m_DragStart;
|
||||
if (delta.sqrMagnitude > 16f)
|
||||
m_PointerMoved = true;
|
||||
m_Viewport.scrollOffset = m_ScrollStart - delta;
|
||||
}
|
||||
|
||||
@@ -207,6 +241,18 @@ namespace XericUI.ShaderBake.Editor
|
||||
{
|
||||
m_Dragging = false;
|
||||
m_Viewport.ReleasePointer(evt.pointerId);
|
||||
if (m_PointerMoved || m_PixelSize.x <= 0 || faceClicked == null)
|
||||
return;
|
||||
|
||||
// 没拖动才算点选:拖动是平移视图,抬手时不该顺手换掉选中的面
|
||||
Rect bounds = m_Frame.worldBound;
|
||||
var position = new Vector2(evt.position.x, evt.position.y);
|
||||
if (bounds.width < 1f || bounds.height < 1f || !bounds.Contains(position))
|
||||
return;
|
||||
// 统一用"左上为原点"的 0~1 坐标,和 Renderer.TryPickFace 的约定一致
|
||||
faceClicked.Invoke(new Vector2(
|
||||
(position.x - bounds.x) / bounds.width,
|
||||
(position.y - bounds.y) / bounds.height));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -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>();
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user