thief-mission-viewer/project/code/Mission.cs

117 lines
2.5 KiB
C#

using Godot;
using KeepersCompound.LGS;
using KeepersCompound.LGS.Database;
using KeepersCompound.LGS.Database.Chunks;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
namespace KeepersCompound;
[Tool]
public partial class Mission : Node3D
{
[Export(PropertyHint.GlobalFile, "*.mis")]
public string FileName { get; set; }
[Export]
public bool Build = false;
DbFile _file;
public override void _Ready()
{
RebuildMap();
}
public override void _Process(double delta)
{
if (Build)
{
RebuildMap();
Build = false;
}
}
public override void _Input(InputEvent @event)
{
if (@event is InputEventKey keyEvent && keyEvent.Pressed)
{
if (keyEvent.Keycode == Key.R)
{
Build = true;
}
}
}
public void RebuildMap()
{
foreach (var node in GetChildren())
{
node.QueueFree();
}
_file = new(FileName);
var wr = (WorldRep)_file.Chunks["WREXT"];
foreach (var cell in wr.Cells)
{
BuildCellMesh(cell);
}
}
private void BuildCellMesh(WorldRep.Cell cell)
{
var numPolys = cell.PolyCount;
var numRenderPolys = cell.RenderPolyCount;
var numPortalPolys = cell.PortalPolyCount;
var vertices = new List<Vector3>();
var normals = new List<Vector3>();
var idxOffset = 0;
for (int i = 0; i < numPolys; i++)
{
var poly = cell.Polys[i];
// TODO: Make this break lol
if (i >= numRenderPolys || i >= numPolys - numPortalPolys)
{
idxOffset += poly.VertexCount;
continue;
}
var plane = cell.Planes[poly.PlaneId];
var normal = plane.Normal;
var numPolyVertices = poly.VertexCount;
for (int j = 1; j < numPolyVertices - 1; j++)
{
foreach (var offset in new int[] { 0, j, j + 1 })
// foreach (var offset in new int[] { j + 1, j, 0 })
{
var vertex = cell.Vertices[cell.Indices[idxOffset + offset]];
vertices.Add(vertex.ToGodotVec3(4.0f));
normals.Add(normal.ToGodotVec3(4.0f));
// vertices.Add(new Vector3(vertex.Y, vertex.Z, vertex.X));
// normals.Add(new Vector3(normal.Y, normal.Z, normal.X));
}
}
idxOffset += poly.VertexCount;
}
var arrMesh = new ArrayMesh();
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = vertices.ToArray();
arrays[(int)Mesh.ArrayType.Normal] = normals.ToArray();
arrMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
var meshInstance = new MeshInstance3D
{
Mesh = arrMesh,
CastShadow = GeometryInstance3D.ShadowCastingSetting.On
};
AddChild(meshInstance);
}
}