using Newtonsoft.Json;
|
using OSGeo.GDAL;
|
using OSGeo.OGR;
|
using SimuTools.Domain;
|
using System;
|
using System.Collections.Generic;
|
using System.Configuration;
|
using System.Data;
|
using System.Diagnostics;
|
using System.Drawing;
|
using System.IO;
|
using System.Linq;
|
using System.Text;
|
|
namespace SimuTools.Tools
|
{
|
public class Handle
|
{
|
public static readonly int MAX = 256 * 256;
|
|
public static readonly string GdalPath = ConfigurationManager.AppSettings["gdalPath"];
|
|
public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory;
|
|
/// <summary>
|
/// 运行
|
/// </summary>
|
public static void Run(string terrainFile, string waterPath, string flowPath, string outPath)
|
{
|
Domain.Layer layer = new Domain.Layer();
|
layer.duration = new Duration();
|
layer.terrain = new Terrain();
|
layer.waters = new Water();
|
|
string temp = Path.Combine(outPath, "temp");
|
if (!Directory.Exists(temp)) Directory.CreateDirectory(temp);
|
|
//CopeTerrain(terrainFile, outPath, layer);
|
CopeWater(waterPath, outPath, layer);
|
CopeFlow(flowPath, outPath, layer);
|
CopeLayerJson(outPath, layer);
|
|
//if (Directory.Exists(temp)) Directory.Delete(temp, true);
|
}
|
|
/// <summary>
|
/// 处理地形
|
/// </summary>
|
private static void CopeTerrain(string terrainFile, string outPath, Domain.Layer layer)
|
{
|
Dataset ds = null;
|
try
|
{
|
ds = Gdal.Open(terrainFile, Access.GA_ReadOnly);
|
if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return;
|
|
SetTerrainInfo(ds, layer);
|
CreateTerrainPng(ds, layer, outPath);
|
}
|
finally
|
{
|
if (null != ds) ds.Dispose();
|
}
|
}
|
|
/// <summary>
|
/// 设置地形信息
|
/// </summary>
|
private static void SetTerrainInfo(Dataset ds, Domain.Layer layer)
|
{
|
Geometry minPoint = GdalHelper.GetMinPoint(ds);
|
Geometry maxPoint = GdalHelper.GetMaxPoint(ds);
|
layer.extension = new Extension(minPoint.GetX(0), minPoint.GetY(0), maxPoint.GetX(0), maxPoint.GetY(0));
|
|
OSGeo.GDAL.Band band = ds.GetRasterBand(1);
|
double[] mm = new double[2];
|
band.ComputeRasterMinMax(mm, 0);
|
layer.extension.SetHeight(mm[0], mm[1]);
|
}
|
|
/// <summary>
|
/// 创建地形图层
|
/// </summary>
|
private static void CreateTerrainPng(Dataset ds, Domain.Layer layer, string outPath)
|
{
|
string tempPath = Path.Combine(outPath, "temp");
|
if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
|
string terrainPath = Path.Combine(outPath, "terrain");
|
if (!Directory.Exists(terrainPath)) Directory.CreateDirectory(terrainPath);
|
|
foreach (int[] sizes in layer.terrain.size)
|
{
|
//string filePath = Path.Combine(outPath, sizes[0] + "_" + sizes[1] + ".png");
|
//// 填充内存图像
|
//byte[] buffer = new byte[sizes[0] * sizes[1] * 3];
|
//for (int i = 0; i < buffer.Length; i++)
|
//{
|
// buffer[i] = (byte)(i % 256);
|
//}
|
|
string tif = Path.Combine(tempPath, DateTime.Now.Ticks.ToString() + ".tif");
|
Resample(ds.GetDescription(), tif, sizes[0], sizes[1]);
|
if (!File.Exists(tif))
|
{
|
continue;
|
}
|
|
string png = Path.Combine(terrainPath, sizes[0] + "_" + sizes[1] + ".png");
|
Terrain2Png(layer, tif, png, sizes[0], sizes[1]);
|
}
|
}
|
|
/// <summary>
|
/// 重采样
|
/// </summary>
|
private static void Resample(string source, string dest, int width, int height)
|
{
|
// https://blog.51cto.com/u_16099346/6691820
|
string cmd = string.Format("{0}gdalwarp.exe -t_srs {1} -ts {2} {3} -r {4} -of GTiff \"{5}\" \"{6}\"", GdalPath, "EPSG:4326", width, height, "bilinear", source, dest);
|
string err = ExecExe(cmd);
|
}
|
|
/// <summary>
|
/// 执行命令
|
/// </summary>
|
public static string ExecExe(string cmd)
|
{
|
string str = null;
|
Process p = null;
|
try
|
{
|
p = new Process();
|
p.StartInfo.FileName = "cmd.exe";
|
p.StartInfo.UseShellExecute = false;
|
p.StartInfo.CreateNoWindow = true;
|
p.StartInfo.RedirectStandardInput = true;
|
p.StartInfo.RedirectStandardOutput = true;
|
p.StartInfo.RedirectStandardError = true;
|
p.Start();
|
|
StreamWriter si = p.StandardInput;
|
StreamReader se = p.StandardError;
|
|
si.AutoFlush = true;
|
si.WriteLine(cmd);
|
si.WriteLine("exit");
|
|
str = se.ReadToEnd();
|
se.Close();
|
si.Close();
|
}
|
catch (Exception ex)
|
{
|
LogOut.Error(ex.Message + "\r\n" + ex.StackTrace);
|
str = ex.Message;
|
}
|
finally
|
{
|
if (p != null) p.Close();
|
}
|
return str;
|
}
|
|
/// <summary>
|
/// Tif值转存至Png
|
/// </summary>
|
private static void Terrain2Png(Domain.Layer layer, string tif, string png, int width, int height)
|
{
|
Dataset ds = null;
|
try
|
{
|
ds = Gdal.Open(tif, Access.GA_ReadOnly);
|
if (null == ds || 0 == ds.RasterCount) return;
|
|
OSGeo.GDAL.Band band = ds.GetRasterBand(1);
|
float[] buffer = new float[width * height];
|
band.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0);
|
|
Bitmap image = new Bitmap(width, height);
|
//Graphics graphic = Graphics.FromImage(image);
|
//graphic.Clear(Color.Transparent); // 填充透明色
|
|
double perHeight = (layer.extension.maxHeight - layer.extension.minHeight) * 100 / 65536;
|
|
for (int x = 0; x < width; x++)
|
{
|
for (int y = 0; y < height; y++)
|
{
|
if (buffer[x * y] == double.NaN || buffer[x * y] == -9999)
|
{
|
image.SetPixel(x, y, Color.Transparent);
|
continue;
|
}
|
|
//int val = Convert.ToInt32(buffer[x * y]* 100); //Convert.ToInt32((buffer[x * y] - layer.extension.minHeight) * 100);
|
int val = Convert.ToInt32((buffer[x * y] - layer.extension.minHeight) * 100 / perHeight);
|
int r = val / 65536;
|
int g = (val - r * 65536) / 256;
|
int b = val % 256;
|
|
Color color = Color.FromArgb(0, r, g, b);
|
image.SetPixel(x, y, color);
|
}
|
}
|
|
image.Save(png, System.Drawing.Imaging.ImageFormat.Png);
|
}
|
finally
|
{
|
if (null != ds) ds.Dispose();
|
}
|
}
|
|
/// <summary>
|
/// 处理水面
|
/// </summary>
|
private static void CopeWater(string waterPath, string outPath, Domain.Layer layer)
|
{
|
string watersPath = Path.Combine(outPath, "waters");
|
if (!Directory.Exists(watersPath)) Directory.CreateDirectory(watersPath);
|
|
List<string> files = GetFiles(waterPath);
|
if (null == files || files.Count == 0) return;
|
|
SetWaterData(layer, files);
|
}
|
|
/// <summary>
|
/// 获取文件
|
/// </summary>
|
private static List<String> GetFiles(string path)
|
{
|
string[] files = Directory.GetFiles(path, "*.tif?", SearchOption.TopDirectoryOnly);
|
if (null == files || files.Length == 0) return null;
|
|
List<string> list = files.ToList();
|
list.Sort();
|
|
return list;
|
}
|
|
/// <summary>
|
/// 设置水面数据
|
/// </summary>
|
private static void SetWaterData(Domain.Layer layer, List<string> files)
|
{
|
DateTime now = DateTime.Now;
|
long startTicks = new DateTime(1970, 1, 1, 0, 0, 0).Ticks;
|
|
foreach (string file in files)
|
{
|
string fileName = Path.GetFileNameWithoutExtension(file);
|
int hour = Convert.ToInt32(fileName.Substring(0, 2));
|
int minute = Convert.ToInt32(fileName.Substring(2, 2));
|
int second = Convert.ToInt32(fileName.Substring(4, 2));
|
|
DateTime d = new DateTime(now.Year, now.Month, now.Day, hour, minute, second);
|
layer.waters.data.Add((d.Ticks - startTicks) / 10000);
|
}
|
}
|
|
/// <summary>
|
/// 处理流速流向
|
/// </summary>
|
private static void CopeFlow(string flowPath, string outPath, Domain.Layer layer)
|
{
|
|
}
|
|
/// <summary>
|
/// 处理元数据
|
/// </summary>
|
private static void CopeLayerJson(string outPath, Domain.Layer layer)
|
{
|
if (null == layer) return;
|
|
String json = JsonConvert.SerializeObject(layer);
|
|
string filePath = Path.Combine(outPath, "layer.json");
|
using (StreamWriter sw = new StreamWriter(filePath))
|
{
|
sw.Write(json);
|
}
|
}
|
|
#region 暂时不用
|
/// <summary>
|
/// 重采样 *
|
/// </summary>
|
private static void Resample(Dataset ds, string dest, int width, int height)
|
{
|
// 设置Warp的选项:https://blog.csdn.net/qq_43210879/article/details/121350561
|
string[] options = new string[] {
|
"format=GTiff",
|
"width=" + width,
|
"height=" + height,
|
"dstSRS=EPSG:4326"
|
};
|
|
OSGeo.GDAL.Driver driver = Gdal.GetDriverByName("GTiff");
|
Dataset destDs = driver.Create(dest, width, height, ds.RasterCount, ds.GetRasterBand(1).DataType, null);
|
|
GDALWarpAppOptions warpAppOptions = new GDALWarpAppOptions(options);
|
Gdal.Warp(destDs, new Dataset[] { ds }, warpAppOptions, null, null);
|
|
destDs.Dispose();
|
}
|
#endregion
|
}
|
}
|