JD2022-TU1/main/tools/apps/PleoLab/CurveSet.cs

131 lines
3.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Xml.Linq;
namespace PleoLab
{
public struct Vector2
{
public Vector2(double _x, double _y)
{
x = _x;
y = _y;
}
public double x;
public double y;
}
public class CurveSet
{
private string m_fileName;
public string FileName
{
get
{
return m_fileName;
}
}
private Dictionary<string, List<Vector2>> m_curves;
public Dictionary<string, List<Vector2>> Curves
{
get
{
return m_curves;
}
}
public CurveSet()
{
m_fileName = "";
m_curves = new Dictionary<string, List<Vector2>>();
}
public void WriteToFile()
{
if (m_fileName != "")
{
XDocument doc = XDocument.Load(m_fileName);
foreach (KeyValuePair<string, List<Vector2>> curve in m_curves)
{
string curveName = curve.Key;
List<Vector2> curvePoints = curve.Value;
doc.Descendants("BandwidthCurve")
.Where(x => (x.Attribute("name")).Value == curveName)
.Remove();
XElement curveElement = new XElement("BandwidthCurve", new XAttribute("name", curveName));
doc.Element("BandwidthCurves").Add(curveElement);
foreach (Vector2 normalizedPoint in curvePoints)
{
curveElement.Add(new XElement("Point", new XElement("x", normalizedPoint.x), new XElement("y", normalizedPoint.y)));
}
}
doc.Descendants("BandwidthCurves")
.Elements("BandwidthCurve")
.Where(x => (!m_curves.ContainsKey((string)x.Attribute("name"))))
.Remove();
doc.Save(m_fileName);
}
}
public void CreateFile(string _fileName)
{
XDocument doc =new XDocument(new XElement("BandwidthCurves"));
doc.Save(_fileName);
m_fileName = _fileName;
}
public void ReadFile(string _fileName)
{
XDocument doc = XDocument.Load(_fileName);
LoadFromXML(doc.Element("BandwidthCurves"), _fileName);
}
public void LoadFromXML(XElement _bandwidthCurveElem, string _fileName)
{
m_curves.Clear();
m_fileName = "";
foreach (XElement curveElement in _bandwidthCurveElem.Elements())
{
string name = curveElement.Attribute("name").Value;
if (name == null)
continue;
List<Vector2> normalizedPoints = new List<Vector2>();
foreach (XElement pointElement in curveElement.Elements())
{
Vector2 p = new Vector2(
Convert.ToDouble(pointElement.Element("x").Value),
Convert.ToDouble(pointElement.Element("y").Value));
normalizedPoints.Add(p);
}
m_curves[name] = normalizedPoints;
}
m_fileName = _fileName;
}
}
public class EditorUtils
{
public static double GetDistance(Point p1, Point p2)
{
return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
}
public static double Lerp(double value1, double value2, double alpha)
{
double retval = value2 * alpha + value1 * (1.0 - alpha);
return retval;
}
}
}