using Newtonsoft.Json;
using OSGeo.GDAL;
using OSGeo.OGR;
using SimuTools.Domain;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace SimuTools.Tools
{
public class Handle
{
#region 成员变量
public static readonly int MAX = 256 * 256;
public static readonly double MAX_X_OFFSET = 0.002;
public static readonly double MIN_X_OFFSET = -0.00005;
public static readonly double WaterHeightOffset = 1.0;
public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory;
public static readonly string GdalPath = ConfigurationManager.AppSettings["gdalPath"];
#endregion
///
/// 运行
///
public static void Run(Args args)
{
Domain.Layer layer = new Domain.Layer();
layer.duration = new Duration();
layer.terrain = new Terrain();
layer.waters = new Water();
CopeTerrain(args, layer);
CopeBuilding(args, layer);
CopeWater(args, layer);
CopeFlow(args, layer);
CopeLayerJson(args, layer);
if (Directory.Exists(args.temp)) Directory.Delete(args.temp, true);
}
#region 地形
///
/// 处理地形
///
private static void CopeTerrain(Args args, Domain.Layer layer)
{
Dataset ds = null;
try
{
ds = Gdal.Open(args.terrainFile, Access.GA_ReadOnly);
if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return;
SetTerrainInfo(ds, layer);
SetWaterInfo(args, layer);
CreateTerrainPng(args, ds, layer);
}
finally
{
if (null != ds) ds.Dispose();
}
}
///
/// 设置地形信息
///
private static void SetTerrainInfo(Dataset ds, Domain.Layer layer)
{
//String srsName = ds.GetSpatialRef().GetName();
//layer.terrain.epsg = !string.IsNullOrEmpty(srsName) && srsName.Contains(GdalHelper.CGCS2000) ? "EPSG:4490" : "EPSG:4326";
Geometry minPoint = GdalHelper.GetMinPoint(ds);
Geometry maxPoint = GdalHelper.GetMaxPoint(ds);
double minx = GetMinVal(minPoint.GetX(0), 10000000);
double miny = GetMinVal(minPoint.GetY(0), 10000000);
double maxx = GetMaxVal(maxPoint.GetX(0) + MAX_X_OFFSET, 10000000);
double maxy = GetMaxVal(maxPoint.GetY(0), 10000000);
layer.extension = new Extension(minx, miny, maxx, maxy, double.MaxValue, double.MinValue);
Band band = ds.GetRasterBand(1);
double[] mm = new double[2];
band.ComputeRasterMinMax(mm, 0);
layer.terrain.SetHeight(GetMinVal(mm[0]), GetMaxVal(mm[1]));
}
///
/// 获取最小值
///
private static double GetMinVal(double val, double radix = 1000)
{
return Convert.ToInt32(Math.Floor(val * radix)) / radix;
}
///
/// 获取最大值
///
private static double GetMaxVal(double val, double radix = 1000)
{
return Convert.ToInt32(Math.Ceiling(val * radix)) / radix;
}
///
/// 创建地形PNG
///
private static void CreateTerrainPng(Args args, Dataset ds, Domain.Layer layer)
{
string terrainPath = Path.Combine(args.outPath, "terrain");
if (!Directory.Exists(terrainPath)) Directory.CreateDirectory(terrainPath);
foreach (int[] sizes in layer.terrain.size)
{
string tif = Path.Combine(args.temp, "terrain_" + sizes[0] + "_" + sizes[1] + ".tif");
//Resample(ds.GetDescription(), tif, sizes[0], sizes[1]);
Resample(ds, tif, sizes[0], sizes[1], layer);
if (!File.Exists(tif)) continue;
string png = Path.Combine(terrainPath, sizes[0] + "_" + sizes[1] + ".png");
Terrain2Png(layer, tif, png, sizes[0], sizes[1]);
}
}
///
/// 重采样
///
private static void Resample(Dataset ds, string dest, int width, int height, Domain.Layer layer)
{
// https://blog.51cto.com/u_16099346/6691820
//string args = string.Format("-t_srs {0} -ts {1} {2} -r {3} -of {4}", "EPSG:4326", width, height, "bilinear", "GTiff");
//string[] options = Gdal.ParseCommandLine(args);
string[] options = new string[]
{
"-t_srs", "EPSG:4326", // layer.terrain.epsg,
"-ts", width.ToString(), height.ToString(),
"-te", layer.extension.minx.ToString(), layer.extension.miny.ToString(), layer.extension.maxx.ToString(), layer.extension.maxy.ToString(),
"-te_srs", "EPSG:4326", // layer.terrain.epsg,
"-r", "bilinear",
"-of", "GTiff"
};
GDALWarpAppOptions warpAppOptions = new GDALWarpAppOptions(options);
Dataset destDs = Gdal.Warp(dest, new Dataset[] { ds }, warpAppOptions, null, null);
destDs.Dispose();
}
///
/// 地形转PNG
///
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;
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.terrain.maxHeight - layer.terrain.minHeight) * 100 / 65536;
double differ = layer.extension.maxHeight - layer.extension.minHeight, minHeight = layer.extension.minHeight;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int offset = x + y * width;
if (float.IsNaN(buffer[offset]) || buffer[offset] < -999 || buffer[offset] < minHeight) continue;
//int val = Convert.ToInt32((buffer[offset] - layer.terrain.minHeight) * 100 / perHeight);
//int val = Convert.ToInt32((buffer[offset] - layer.terrain.minHeight) / differ * 255); // 65535
int r = 0, g, b;
if (buffer[offset] - layer.extension.maxHeight > 0)
{
g = b = 255;
}
else
{
int val = Convert.ToInt32((buffer[offset] - minHeight) / differ * 65535);
g = val / 256;
b = val % 256;
}
Color color = Color.FromArgb(127, r, g, b);
image.SetPixel(x, y, color);
}
}
image.Save(png, System.Drawing.Imaging.ImageFormat.Png);
}
finally
{
if (null != ds) ds.Dispose();
//if (File.Exists(tif)) File.Delete(tif);
}
}
#endregion
#region 建筑
///
/// 处理建筑
///
private static void CopeBuilding(Args args, Domain.Layer layer)
{
Dataset ds = null;
try
{
ds = Gdal.Open(args.buildingFile, Access.GA_ReadOnly);
if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return;
foreach (int[] sizes in layer.terrain.size)
{
string tif = Path.Combine(args.temp, "building_" + sizes[0] + "_" + sizes[1] + ".tif");
Resample(ds, tif, sizes[0], sizes[1], layer);
if (!File.Exists(tif)) continue;
Dataset dataset = Gdal.Open(tif, Access.GA_ReadOnly);
if (null == dataset || 0 == dataset.RasterCount) return;
float[] buffer = new float[sizes[0] * sizes[1]];
dataset.GetRasterBand(1).ReadRaster(0, 0, sizes[0], sizes[1], buffer, sizes[0], sizes[1], 0, 0);
args.buildings[sizes[0] + "_" + sizes[1]] = buffer;
dataset.Dispose();
}
}
finally
{
if (null != ds) ds.Dispose();
}
}
#endregion
#region 水面
///
/// 设置水面信息
///
private static void SetWaterInfo(Args args, Domain.Layer layer)
{
List files = layer.waters.files = GetFiles(args.waterPath);
if (null == files || files.Count == 0) return;
SetWaterData(layer, files);
SetWaterHeight(layer, files);
}
///
/// 处理水面
///
private static void CopeWater(Args args, Domain.Layer layer)
{
List files = layer.waters.files;
if (files.Count == 0 || files.Count != layer.waters.data.Count) return;
ProcessWaters(args, files, layer);
}
///
/// 获取文件
///
private static List GetFiles(string path, string prefix = "")
{
string[] files = Directory.GetFiles(path, prefix + "*.tif?", SearchOption.TopDirectoryOnly);
if (null == files || files.Length == 0) return new List();
List list = files.ToList();
list.Sort();
return list;
}
///
/// 设置水面数据
///
private static void SetWaterData(Domain.Layer layer, List files)
{
DateTime now = DateTime.Now;
long startTicks = new DateTime(1970, 1, 1, 8, 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);
}
layer.duration.start = layer.waters.data[0];
layer.duration.end = layer.waters.data[layer.waters.data.Count - 1];
}
///
/// 设置水面高度
///
private static void SetWaterHeight(Domain.Layer layer, List files)
{
Parallel.For(0, files.Count, i =>
{
Dataset ds = null;
try
{
ds = Gdal.Open(files[i], Access.GA_ReadOnly);
if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return;
double[] mm = new double[2];
ds.GetRasterBand(1).ComputeRasterMinMax(mm, 0);
layer.extension.SetHeight(mm[0], mm[1]);
}
finally
{
if (null != ds) ds.Dispose();
}
});
layer.extension.minHeight = GetMinVal(layer.extension.minHeight - 1);
layer.extension.maxHeight = GetMaxVal(layer.extension.maxHeight + 1);
}
///
/// 处理水面数据
///
private static void ProcessWaters(Args args, List files, Domain.Layer layer)
{
Parallel.For(0, files.Count, i =>
//for (int i = 0; i < files.Count; i++)
{
Dataset ds = null;
try
{
ds = Gdal.Open(files[i], Access.GA_ReadOnly);
if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return;
CreateWaterPng(args, ds, layer, layer.waters.data[i]);
}
finally
{
if (null != ds) ds.Dispose();
}
});
}
///
/// 创建水面PNG
///
private static void CreateWaterPng(Args args, Dataset ds, Domain.Layer layer, long ticks)
{
string waterPath = Path.Combine(args.outPath, "waters", ticks.ToString());
if (!Directory.Exists(waterPath)) Directory.CreateDirectory(waterPath);
foreach (int[] sizes in layer.terrain.size)
{
string fileName = Path.GetFileNameWithoutExtension(ds.GetDescription()) + "_" + sizes[0] + "_" + sizes[1];
string tif = Path.Combine(args.temp, fileName + ".tif");
Resample(ds, tif, sizes[0], sizes[1], layer);
if (!File.Exists(tif)) continue;
string png = Path.Combine(waterPath, sizes[0] + "_" + sizes[1] + ".png");
Water2Png(args, layer, tif, png, sizes[0], sizes[1]);
}
}
///
/// 水面转PNG
///
private static void Water2Png(Args args, 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;
Band band = ds.GetRasterBand(1);
float[] buffer = new float[width * height];
band.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0);
float[] building = args.buildings[width + "_" + height];
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;
double differ = layer.extension.maxHeight - layer.extension.minHeight, minHeight = layer.extension.minHeight;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int offset = x + y * width;
if (float.IsNaN(buffer[offset]) || buffer[offset] < -999 || buffer[offset] < minHeight) continue;
if (!float.IsNaN(building[offset]) && building[offset] > -999) continue;
//int val = Convert.ToInt32((buffer[offset] - layer.extension.minHeight + WaterHeightOffset) * 100 / perHeight);
int r = 0, g, b;
if (buffer[offset] - layer.extension.maxHeight > 0)
{
g = b = 255;
}
else
{
int val = Convert.ToInt32((buffer[offset] - minHeight) / differ * 65535);
g = val / 256;
b = val % 256;
}
Color color = Color.FromArgb(127, r, g, b);
image.SetPixel(x, y, color);
}
}
image.Save(png, System.Drawing.Imaging.ImageFormat.Png);
}
finally
{
if (null != ds) ds.Dispose();
//if (File.Exists(tif)) File.Delete(tif);
}
}
#endregion
#region 流速流向
///
/// 处理流速流向
///
private static void CopeFlow(Args args, Domain.Layer layer)
{
List vxFiles = GetFiles(args.flowPath, "vx");
List vyFiles = GetFiles(args.flowPath, "vy");
if (null == vxFiles || null == vyFiles || vxFiles.Count != vyFiles.Count || vxFiles.Count != layer.waters.data.Count) return;
Parallel.For(0, vxFiles.Count, i =>
//for (int i = 0; i < vxFiles.Count; i++)
{
Dataset vxDs = null, vyDs = null;
try
{
vxDs = Gdal.Open(vxFiles[i], Access.GA_ReadOnly);
vyDs = Gdal.Open(vyFiles[i], Access.GA_ReadOnly);
if (null == vxDs || 0 == vxDs.RasterCount || null == vxDs.GetSpatialRef() ||
null == vyDs || 0 == vyDs.RasterCount || null == vyDs.GetSpatialRef()) return;
CreateFlowPng(args, vxDs, vyDs, layer, layer.waters.data[i]);
}
finally
{
if (null != vxDs) vxDs.Dispose();
if (null != vyDs) vyDs.Dispose();
}
});
}
///
/// 创建流速流向PNG
///
private static void CreateFlowPng(Args args, Dataset vxDs, Dataset vyDs, Domain.Layer layer, long ticks)
{
string flowPath = Path.Combine(args.outPath, "flows", ticks.ToString());
if (!Directory.Exists(flowPath)) Directory.CreateDirectory(flowPath);
foreach (int[] sizes in layer.terrain.size)
{
string vxName = Path.GetFileNameWithoutExtension(vxDs.GetDescription()) + "_" + sizes[0] + "_" + sizes[1];
string vxTif = Path.Combine(args.temp, vxName + ".tif");
Resample(vxDs, vxTif, sizes[0], sizes[1], layer);
string vyName = Path.GetFileNameWithoutExtension(vyDs.GetDescription()) + "_" + sizes[0] + "_" + sizes[1];
string vyTif = Path.Combine(args.temp, vyName + ".tif");
Resample(vyDs, vyTif, sizes[0], sizes[1], layer);
if (!File.Exists(vxTif) || !File.Exists(vyTif)) continue;
string png = Path.Combine(flowPath, sizes[0] + "_" + sizes[1] + ".png");
VxyTif2Png(layer, vxTif, vyTif, png, sizes[0], sizes[1]);
}
}
///
/// 流速流向Tif值转存至Png
///
private static void VxyTif2Png(Domain.Layer layer, string vxTif, string vyTif, string png, int width, int height)
{
Dataset vxDs = null, vyDs = null;
try
{
vxDs = Gdal.Open(vxTif, Access.GA_ReadOnly);
vyDs = Gdal.Open(vyTif, Access.GA_ReadOnly);
if (null == vxDs || 0 == vxDs.RasterCount || null == vyDs || 0 == vyDs.RasterCount) return;
float[] vxBuffer = new float[width * height], vyBuffer = new float[width * height];
vxDs.GetRasterBand(1).ReadRaster(0, 0, width, height, vxBuffer, width, height, 0, 0);
vyDs.GetRasterBand(1).ReadRaster(0, 0, width, height, vyBuffer, width, height, 0, 0);
CreateFlowPng(vxBuffer, vyBuffer, png, width, height);
}
finally
{
if (null != vxDs) vxDs.Dispose();
if (null != vyDs) vyDs.Dispose();
//if (File.Exists(vxTif)) File.Delete(vxTif);
//if (File.Exists(vyTif)) File.Delete(vyTif);
}
}
///
/// 创建流速流向PNG
///
private static void CreateFlowPng(float[] vxBuffer, float[] vyBuffer, string png, int width, int height)
{
Bitmap image = new Bitmap(width, height);
Graphics graphic = Graphics.FromImage(image);
graphic.Clear(Color.Transparent); // 填充透明色
// 用 R通道表示,流向为归一化的二维向量(x,y),G通道表示为 x *255 , B通道表示为 y * 255
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int offset = x + y * width;
float fx = GetFloatValue(vxBuffer[offset]);
float fy = GetFloatValue(vyBuffer[offset]);
if (float.IsNaN(fx) && float.IsNaN(fy) || (fx == 0 && fy == 0)) continue;
fx = float.IsNaN(fx) ? 0 : fx;
fy = float.IsNaN(fy) ? 0 : fy;
double dr = Math.Sqrt(Math.Pow(fx, 2) + Math.Pow(fy, 2));
int r = Convert.ToInt32(dr / 4 * 255);
int g = Convert.ToInt32((fx / dr * 0.5 + 0.5) * 255);
int b = Convert.ToInt32((fy / dr * 0.5 + 0.5) * 255);
Color color = Color.FromArgb(127, GetSafeValue(r), GetSafeValue(g), GetSafeValue(b));
image.SetPixel(x, y, color);
}
}
image.Save(png, System.Drawing.Imaging.ImageFormat.Png);
}
///
/// 获取Float值
///
private static float GetFloatValue(float val)
{
return (float.IsNaN(val) || val < -999) ? float.NaN : val;
}
///
/// 获取安全值
///
private static int GetSafeValue(int val)
{
if (val < 0) return 0;
if (val > 255) return 255;
return val;
}
#endregion
#region 元数据
///
/// 处理元数据
///
private static void CopeLayerJson(Args args, Domain.Layer layer)
{
if (null == layer) return;
String json = JsonConvert.SerializeObject(layer);
string filePath = Path.Combine(args.outPath, "layer.json");
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write(json);
}
}
#endregion
#region 暂时不用
///
/// 设置地形信息
///
private static void SetTerrainInfo(Args args, Dataset ds, Domain.Layer layer)
{
string tif = Path.Combine(args.temp, Path.GetFileNameWithoutExtension(ds.GetDescription()) + ".tif");
Resample(ds, tif);
if (!File.Exists(tif)) throw new Exception("高程文件重投影失败!");
Dataset tifDS = null;
try
{
tifDS = Gdal.Open(tif, Access.GA_ReadOnly);
if (null == tifDS || 0 == tifDS.RasterCount || null == tifDS.GetSpatialRef()) return;
double[] transform = new double[6];
tifDS.GetGeoTransform(transform);
double minx = transform[0];
double miny = transform[3] - tifDS.RasterYSize * transform[1];
double maxx = transform[0] + (tifDS.RasterYSize * transform[1]);
double maxy = transform[3];
layer.extension = new Extension(minx, miny, maxx, maxy, double.MaxValue, double.MinValue);
Band band = tifDS.GetRasterBand(1);
double[] mm = new double[2];
band.ComputeRasterMinMax(mm, 0);
layer.terrain.SetHeight(GetMinVal(mm[0]), GetMaxVal(mm[1]));
}
finally
{
if (null != tifDS) tifDS.Dispose();
}
}
///
/// 重采样
///
private static void Resample(Dataset ds, string dest)
{
string[] options = new string[] { "-t_srs", "EPSG:4326", "-r", "bilinear", "-of", "GTiff" };
GDALWarpAppOptions warpAppOptions = new GDALWarpAppOptions(options);
Dataset destDs = Gdal.Warp(dest, new Dataset[] { ds }, warpAppOptions, null, null);
destDs.Dispose();
}
///
/// 重采样
///
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);
}
///
/// 执行命令
///
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;
}
#endregion
}
}