rabidus-test/Assets/Dreamteck/Splines/Core/IO/CSV.cs

1 line
9.4 KiB
C#
Raw Permalink Normal View History

2023-07-24 16:38:13 +03:00
using System.Collections;using System.Collections.Generic;using UnityEngine;using System.IO;using System.Text.RegularExpressions;namespace Dreamteck.Splines.IO{ public class CSV : SplineParser { public enum ColumnType { Position, Tangent, Tangent2, Normal, Size, Color } public List<ColumnType> columns = new List<ColumnType>(); private System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US"); private System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Any; public CSV(SplineComputer computer) { Spline spline = new Spline(computer.type, computer.sampleRate); spline.points = computer.GetPoints(); if (spline.type != Spline.Type.Bezier && spline.type != Spline.Type.Linear) spline.CatToBezierTangents(); if (computer.isClosed) spline.Close(); buffer = new SplineDefinition(computer.name, spline); fileName = computer.name; columns.Add(ColumnType.Position); columns.Add(ColumnType.Tangent); columns.Add(ColumnType.Tangent2); } public CSV(string filePath, List<ColumnType> customColumns = null) { if (File.Exists(filePath)) { string ext = Path.GetExtension(filePath).ToLower(); fileName = Path.GetFileNameWithoutExtension(filePath); if (ext != ".csv") { Debug.LogError("CSV Parsing ERROR: Wrong format. Please use SVG or XML"); return; } string[] lines = File.ReadAllLines(filePath); if (customColumns == null) { columns.Add(ColumnType.Position); columns.Add(ColumnType.Tangent); columns.Add(ColumnType.Tangent2); columns.Add(ColumnType.Normal); columns.Add(ColumnType.Size); columns.Add(ColumnType.Color); } else columns = new List<ColumnType>(customColumns); buffer = new SplineDefinition(fileName, Spline.Type.CatmullRom); Read(lines); } } void Read(string[] lines) { int expectedElementCount = 0; foreach (ColumnType col in columns) { switch (col) { case ColumnType.Position: expectedElementCount +=3; break; case ColumnType.Tangent: expectedElementCount += 3; break; case ColumnType.Tangent2: expectedElementCount += 3; break; case ColumnType.Normal: expectedElementCount += 3; break; case ColumnType.Size: expectedElementCount ++; break; case ColumnType.Color: expectedElementCount += 4; break; } } for (int i = 1; i < lines.Length; i++) { lines[i] = Regex.Replace(lines[i], @"\s+", ""); string[] elements = lines[i].Split(','); if(elements.Length != expectedElementCount) { Debug.LogError("Unexpected element count on row " + i + ". Expected " + expectedElementCount + " found " + elements.Length + " Please make sure that all values exist and the column order is correct."); continue; } float[] values = new float[elements.Length]; for (int j = 0; j < elements.Length; j++) { float.TryParse(elements[j], style, culture, out values[j]); } int currentValue = 0; foreach (ColumnType col in columns) { switch (col) {