1
13693261870
2024-11-06 568696691efa96f44f1e88304459f612acc7e6e7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package com.se.simu.service;
 
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.se.simu.config.PropertiesConfig;
import com.se.simu.domain.po.DataPo;
import com.se.simu.domain.po.SimuPo;
import com.se.simu.domain.vo.*;
import com.se.simu.domain.vo.Layer;
import com.se.simu.helper.GdalHelper;
import com.se.simu.helper.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconst;
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * 内涝服务类
 *
 * @author WWW
 * @date   2024-07-16
 */
@Slf4j
@Service
@SuppressWarnings("ALL")
public class WaterService {
    @Resource
    PropertiesConfig config;
 
    /**
     * 获取元数据信息
     */
    public byte[] getson(String serviceName, String json) {
        try {
            String filePath = config.getOutPath() + File.separator + serviceName + File.separator + json;
 
            File dat = new File(filePath);
            if (!dat.exists()) {
                return null;
            }
 
            byte[] bytes = new byte[(int) dat.length()];
 
            FileInputStream fs = new FileInputStream(filePath);
            fs.read(bytes);
            fs.close();
 
            return bytes;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return null;
        }
    }
 
    /**
     * 获取地形高度图
     */
    public String getTerraMap(String serviceName, Integer width, Integer height) {
        return config.getOutPath() + File.separator + serviceName + File.separator + "terrain" + File.separator + width + "_" + height + ".png";
    }
 
    /**
     * 获取水面高度图
     */
    public String getWaterMap(String serviceName, Integer width, Integer height, Long timestamp) {
        return config.getOutPath() + File.separator + serviceName + File.separator + "waters" + File.separator + timestamp + File.separator + width + "_" + height + ".png";
    }
 
    /**
     * 获取水流向流速图
     */
    public String getFlowMap(String serviceName, Integer width, Integer height, Long timestamp) {
        return config.getOutPath() + File.separator + serviceName + File.separator + "flows" + File.separator + timestamp + File.separator + width + "_" + height + ".png";
    }
 
    /**
     * 获取图层 *
     */
    public Layer getLayer(String serviceName) {
        Layer layer = new Layer();
        layer.setVersion(config.getVer());
        layer.setDuration(new Duration(1719812810225L, 1719812810225L));
        layer.setExtension(new Extension(2.11062743358, 0.53812160220, 2.11070827834, 0.53819799453, 1.151, 38.83));
 
        List<Integer[]> sizes = new ArrayList<>();
        sizes.add(new Integer[]{64, 64});
        sizes.add(new Integer[]{128, 128});
        sizes.add(new Integer[]{256, 256});
        sizes.add(new Integer[]{512, 512});
        sizes.add(new Integer[]{1024, 1024});
        sizes.add(new Integer[]{2048, 2048});
        layer.setTerrain(new Terrain(sizes));
 
        List<Long> data = new ArrayList<>(Arrays.asList(1719812812225L, 1719812812225L, 1719812812225L, 1719812812225L, 1719812812225L, 1719812812225L));
        layer.setWaters(new Water(data));
 
        return layer;
    }
 
    /**
     * 根据坐标查询积水深度:gdalconst.GA_Update
     */
    public Double getWaterHeight(SimuPo simu, double x, double y, Long timestamp) {
        String filePath = config.getOutPath() + File.separator + simu.getServiceName() + File.separator + "waters"
                + File.separator + timestamp + File.separator + "water.tif";
        if (!FileUtil.exist(filePath)) return null;
 
        Dataset ds = null;
        try {
            ds = gdal.Open(filePath, gdalconst.GA_ReadOnly);
            if (null == ds || ds.getRasterCount() < 1) {
                return null;
            }
            if (null == ds.GetSpatialRef()) {
                ds.SetSpatialRef(getSpatialRef(simu));
            }
 
            double[] gt = ds.GetGeoTransform();
            double[] xy = GdalHelper.fromWgs84(ds.GetSpatialRef(), x, y);
            int[] XY = coordinates2ColRow(gt, xy[0], xy[1]);
 
            if (XY[0] < 0 || XY[1] < 0 || XY[0] > ds.getRasterXSize() || XY[1] > ds.getRasterYSize()) {
                return null;
            }
 
            double[] vals = new double[1];
            ds.GetRasterBand(1).ReadRaster(XY[0], XY[1], 1, 1, vals);
 
            return isValid(vals[0]) ? vals[0] : null;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return null;
        } finally {
            if (null != ds) ds.delete();
        }
    }
 
    private SpatialReference getSpatialRef(SimuPo simu) {
        DataPo data = JSONUtil.toBean(simu.getData(), DataPo.class);
 
        return data.getSpatialReference();
    }
 
    /**
     * 将地图坐标转换为栅格像素坐标
     *
     * @param gt 仿射变换参数
     * @param x  横坐标
     * @param y  纵坐标
     * @return 像素坐标
     */
    public int[] coordinates2ColRow(double[] gt, double x, double y) {
        // 向下取整,如果向上取整会导致计算结果偏大,从而在后面读取到邻近像元的数据
        //Double col = Math.floor(((y - gt[3]) * gt[1] - (x - gt[0]) * gt[4]) / (gt[5] * gt[1] - gt[2] * gt[4]));
        Double col = Math.floor((y * gt[1] - x * gt[4] + gt[0] * gt[4] - gt[3] * gt[1]) / (gt[5] * gt[1] - gt[2] * gt[4]));
        Double row = Math.floor((x - gt[0] - col * gt[2]) / gt[1]);
 
        return new int[]{row.intValue(), col.intValue()};
    }
 
    public static boolean isValid(double val) {
        return !Double.isNaN(val) && val > Integer.MIN_VALUE;
    }
 
    public Double getWaterArea(SimuPo simu, double x, double y, Long timestamp) {
        String filePath = config.getOutPath() + File.separator + simu.getServiceName() + File.separator + "waters"
                + File.separator + timestamp + File.separator + "water.geojson";
        if (!FileUtil.exist(filePath)) return null;
 
        Driver driver = null;
        DataSource dataSource = null;
        org.gdal.ogr.Layer layer = null;
        try {
            driver = ogr.GetDriverByName("GeoJSON");
            if (null == driver) return null;
 
            DataSource ds = driver.Open(filePath);
            if (null == ds) return null;
 
            layer = ds.GetLayer(0);
            double[] xy = GdalHelper.fromWgs84(layer.GetSpatialRef(), x, y);
 
            Geometry p = new Geometry(ogr.wkbPoint);
            p.AddPoint_2D(xy[0], xy[1]);
            p.AssignSpatialReference(layer.GetSpatialRef());
 
            for (long i = 0, d = layer.GetFeatureCount(); i < d; i++) {
                Feature f = layer.GetFeature(i);
                if (f.GetGeometryRef().Intersects(p)) {
                    /*f.GetFieldAsDouble("val");
                    Geometry g = f.GetGeometryRef();
                    GdalHelper.fromWgs84(layer.GetSpatialRef(), g);
                    Double area= g.GetArea();*/
 
                    return f.GetGeometryRef().Area();
                }
            }
 
            return null;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return null;
        } finally {
            GdalHelper.delete(layer, dataSource, driver);
        }
    }
 
    /**
     * 根据seid查询建筑物涉水深度
     */
    public List<BuildingDepthVo> getBuildingDepthBySeid(String serviceName, String seid) {
        List<BuildingDepthVo> list = readBuildingJson(serviceName);
        if (CollectionUtils.isEmpty(list)) return null;
 
        return list.parallelStream()
                .filter(b -> seid.equals(b.getId()))
                .sorted((a, b) -> a.getTimestamp().compareTo(b.getTimestamp()))
                .collect(Collectors.toList());
    }
 
    public List<BuildingDepthVo> getBuildingDepthByTime(String serviceName, Long timestamp) {
        List<BuildingDepthVo> list = readBuildingJson(serviceName);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
 
        return list.parallelStream().filter(b -> timestamp.equals(b.getTimestamp())).collect(Collectors.toList());
    }
 
    private List<BuildingDepthVo> readBuildingJson(String serviceName) {
        String filePath = config.getOutPath() + File.separator + serviceName + File.separator + "building.json";
        String json = getText(filePath);
        if (StringHelper.isEmpty(json)) {
            return null;
        }
 
        return JSONUtil.toList(json, BuildingDepthVo.class);
    }
 
    private String getText(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }
 
        return FileUtil.readUtf8String(file);
    }
}