78 lines
3.2 KiB
C#
78 lines
3.2 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Globalization;
|
||
using System.IO;
|
||
using System.Text;
|
||
|
||
namespace XNet.Business.Parser
|
||
{
|
||
public class SimpleObjParser
|
||
{
|
||
public class ObjData
|
||
{
|
||
public required float[] Vertices { get; set; }
|
||
public required int[] Indices { get; set; }
|
||
}
|
||
|
||
public static ObjData Parse(string filePath)
|
||
{
|
||
var verts = new List<float>();
|
||
var indices = new List<int>();
|
||
|
||
if (!File.Exists(filePath)) throw new FileNotFoundException("Obj file not found", filePath);
|
||
var lines = File.ReadAllLines(filePath);
|
||
|
||
foreach (var line in lines)
|
||
{
|
||
var trimmed = line.Trim();
|
||
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith("#")) continue;
|
||
var parts = trimmed.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||
if (parts.Length == 0) continue;
|
||
|
||
if (parts[0] == "v")
|
||
{
|
||
float x = float.Parse(parts[1], CultureInfo.InvariantCulture);
|
||
float y = float.Parse(parts[2], CultureInfo.InvariantCulture);
|
||
float z = float.Parse(parts[3], CultureInfo.InvariantCulture);
|
||
|
||
//verts.Add(x);
|
||
//verts.Add(y);
|
||
//verts.Add(z);
|
||
// ========================================
|
||
// ✅ 修改点 1【核心】:右手坐标系OBJ → 左手坐标系 顶点修正
|
||
// Unity导出的右手OBJ Z轴是反向的,这里取反Z轴,适配DotRecast左手坐标系
|
||
// 唯一改动:z → -z ,X/Y完全不变!
|
||
// ========================================
|
||
verts.Add(-x); // ✅ 新增:X轴取负,解决Cocos左右颠倒
|
||
verts.Add(y);
|
||
verts.Add(-z);
|
||
}
|
||
else if (parts[0] == "f")
|
||
{
|
||
if (parts.Length >= 4)
|
||
{
|
||
int v1 = int.Parse(parts[1].Split('/')[0]) - 1;
|
||
int v2 = int.Parse(parts[2].Split('/')[0]) - 1;
|
||
int v3 = int.Parse(parts[3].Split('/')[0]) - 1;
|
||
|
||
indices.Add(v1);
|
||
indices.Add(v2);
|
||
indices.Add(v3);
|
||
|
||
// ========================================
|
||
// ✅ 修改点 2【核心必改】:反转三角面绕序,修正法线/面朝向
|
||
// 右手OBJ的面是顺时针,DotRecast左手要求逆时针,交换v2和v3即可
|
||
// 这行代码是解决「导航网格加载为0、寻路失效」的关键!
|
||
// ========================================
|
||
//indices.Add(v1);
|
||
//indices.Add(v3); // 交换:原v2 → 现v3
|
||
//indices.Add(v2); // 交换:原v3 → 现v2
|
||
|
||
}
|
||
}
|
||
}
|
||
|
||
return new ObjData { Vertices = verts.ToArray(), Indices = indices.ToArray() };
|
||
}
|
||
}
|
||
} |