forked from arcAstroVR/terrain4arcastrovr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terrain4aAVR.py
932 lines (820 loc) · 47 KB
/
terrain4aAVR.py
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Terrain4aAVR
A QGIS plugin
Outputs 300km square terrain data for arcAstroVR
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-11-17
git sha : $Format:%H$
copyright : (C) 2021 by Kuninori Iwashiro (scienceNODE)
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
GZ 2024-02-11: Google Translated comments Japanese->English
GZ 2024-02-17: Fixed numerous issues, esp. inner terrain size now works,
better documentation
filling (preliminary) center coordinates into text edit line
use QgsMessageLog.logMessage() to have GDAL log messages (print does nothing!)
"""
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .terrain4aAVR_dialog import Terrain4aAVRDialog
import os, sys, time, datetime
import processing
import numpy as np
from osgeo import gdal
class Terrain4aAVR:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'Terrain4aAVR_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Terrain for arcAstroVR')
# Check if plugin was started the first time in current QGIS session
# Must be set in initGui() to survive plugin reloads
self.first_start = None
# 定数定義 || #constant definition
eqEarth: float = 1.156 # 等価地球半径(倍) || #equivalent earth radius (times)
self.A: float = 6378137.0 * eqEarth # a(地球楕円体長半径(赤道面平均半径)) || # a(Earth ellipsoid semimajor axis (equatorial plane mean radius))
ONE_F: float = 298.257223563 # 1 / f(地球楕円体扁平率=(a - b) / a) || # 1 / f(Earth ellipsoid oblateness = (a - b) / a)
self.B: float = self.A * (1.0 - 1.0 / ONE_F) # b(地球楕円体短半径) || # b(Earth ellipsoid minor axis)
self.E2: float = (1.0 / ONE_F) * (2 - (1.0 / ONE_F)) # e^2 = 2 * f - f * f = (a^2 - b^2) / a^2
self.ED2: float = self.E2 * self.A * self.A / (self.B * self.B) # e'^2= (a^2 - b^2) / b^2
self.ecef_o: list[float] = []
# Output specifications:
# - output_size: output width (m),
# - dem_mesh: Terrain resolution (cell size, m)
# - tex_mesh: Texture resolution (pixel size, m)
# Note that the Terrain size (dem_px) for Unity must be one of 32, 64, 128, 256, 1024, 2048, 4096px.
# Be careful as blocks tend to appear if the input data mesh resolution (dem_px) is
# finer than the output data mesh resolution (output_size). Ideally, they should match.
self.L_output_size: float = 300000
self.L_dem_px: int = 4096 * 3 # About 256*3 is appropriate for lightweight confirmation processing.
self.L_dem_mesh: float = self.L_output_size / self.L_dem_px # px size, m. This comes to a fixed size of 24.414m.
self.L_tex_mesh: float = self.L_dem_mesh # px size, m.
self.S_dem_px: int = 4096 # About 256 is appropriate for lightweight confirmation processing. Normally 4096
# GZ: The S_dem_mesh finally works after
# (1) being declared in __init__ here and
# (2) set in the spinbox event handler.
# (3) Also resetting S_output_size and self.S_tex_mesh there.
self.S_dem_mesh: float = 1.0
self.S_output_size: float = self.S_dem_px * self.S_dem_mesh # total size of inner DEM, m.
# preliminary pixel size of inner DEM texture. The final texture will further be resampled from this.
# GZ: I don't understand why you don't set S_tex_size immediately to 16384 with according pixel size.
self.S_tex_mesh: float = self.S_dem_mesh / 5
#QgsMessageLog.logMessage(message=f'S_dem_mesh={self.S_dem_mesh:.2f} m pixel size, '
# f'narrow area S_output_size=({self.S_output_size:.2f} m)²',
# tag='terrain4aAVR', level=Qgis.Info)
# Adjustment values for UnityTerrain:
# - zoffset: elevation offset,
# - h_max: how many meters to set the maximum value,
# - down: how many meters to lower the base terrain of the mask area)
# When h_max = 10000 and zoffset=1000, the relationship is as follows
# Elevation-1000m: GeoTiff=0, Unity Box=0
# Elevation 0m: GeoTiff=6553.6, Unity Box=1000
# Elevation 9000m: GeoTiff=65536, Unity Box=10000
self.zoffset: float = 1000
self.h_max: float = 10000
self.down: float = 3
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('Terrain4aAVR', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
# Adds plugin icon to Plugins toolbar
self.iface.addToolBarIcon(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/terrain4aAVR/icon.png'
self.add_action(
icon_path,
text=self.tr(u'Terrain4aAVR'),
callback=self.run,
parent=self.iface.mainWindow())
# will be set False in run()
self.first_start = True
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
if not self.first_start:
self.marker.hide()
self.wideline.hide()
self.narrowline.hide()
self.canvas.scene().removeItem(self.marker)
self.canvas.scene().removeItem(self.wideline)
self.canvas.scene().removeItem(self.narrowline)
self.canvas.refreshAllLayers()
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&Terrain maker for arcAstroVR'),
action)
self.iface.removeToolBarIcon(action)
def run(self):
"""Run method that performs all the real work"""
# Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True:
self.first_start = False
self.dlg = Terrain4aAVRDialog()
# PREPARE lineEdit
self.dlg.lineEdit1_1.clear()
# PREPARE COMBO BOX
self.dlg.comboBox2_1.clear()
self.dlg.comboBox2_2.clear()
self.dlg.comboBox2_3.clear()
self.dlg.comboBox3_1.clear()
self.dlg.comboBox3_2.clear()
self.dlg.comboBox3_3.clear()
self.dlg.comboBox4.clear()
self.layers = [layer for layer in QgsProject.instance().mapLayers().values()]
self.single_list = [] # layers for DSM ("single-channel"?)
self.single_list.append("")
self.multi_list = [] # layers for texture
self.multi_list.append("")
self.vector_list = [] # layers for Mask (TODO: Document usage!)
self.vector_list.append("")
for layer in self.layers:
if layer.type() == QgsMapLayer.VectorLayer:
if layer.geometryType() == QgsWkbTypes.PolygonGeometry:
self.vector_list.append(layer.name())
elif (layer.type() == QgsMapLayer.RasterLayer) and (layer.name() != "narrowTerrain_DTM") and (
layer.name() != "narrowTerrain_TEX") and (layer.name() != "wideTerrain_DTM") and (
layer.name() != "wideTerrain_TEX"):
if layer.rasterType() < 2:
self.single_list.append(layer.name())
else:
self.multi_list.append(layer.name())
self.dlg.comboBox2_1.addItems(self.single_list)
self.dlg.comboBox2_2.addItems(self.single_list)
self.dlg.comboBox2_3.addItems(self.multi_list)
self.dlg.comboBox3_1.addItems(self.single_list)
self.dlg.comboBox3_2.addItems(self.single_list)
self.dlg.comboBox3_3.addItems(self.multi_list)
self.dlg.comboBox4.addItems(self.vector_list)
# メインCanvasを取得 || #Get main Canvas
self.canvas = iface.mapCanvas()
# マーカー描画設定 || #Marker drawing settings
self.marker = QgsVertexMarker(self.canvas)
self.marker.setColor(QColor(255, 0, 0))
self.marker.setIconSize(20)
self.marker.setIconType(QgsVertexMarker.ICON_X)
self.marker.setPenWidth(1)
# ライン描画設定 || #Line drawing settings
self.wideline = QgsRubberBand(self.canvas, QgsWkbTypes.GeometryType.LineGeometry)
self.wideline.setColor(QColor(255, 0, 0))
self.wideline.setWidth(2)
self.narrowline = QgsRubberBand(self.canvas, QgsWkbTypes.GeometryType.LineGeometry)
self.narrowline.setColor(QColor(0, 255, 0))
self.narrowline.setWidth(2)
# lineEdit(緯度経度)のチェンジイベント || # lineEdit (latitude and longitude) change event
# self.dlg.lineEdit1_1.editingFinished.connect(self.lineEdit1Activated)
self.dlg.lineEdit1_1.textEdited.connect(self.lineEdit1Activated)
# comboBoxのチェンジイベント || # comboBox change event
self.dlg.comboBox2_1.currentIndexChanged.connect(self.combobox2Activated)
self.dlg.comboBox3_1.currentIndexChanged.connect(self.combobox3Activated)
# PREPARE SAVE Dir
self.dlg.mQgsFileWidget_outputPath.setFilePath(os.path.expanduser('~/Desktop'))
self.dlg.mQgsFileWidget_outputPath.setStorageMode(QgsFileWidget.StorageMode.GetDirectory)
self.dlg.mQgsFileWidget_outputPath.setDialogTitle("Select a save directory")
# doubleSpinBoxのチェンジイベント || # qdoubleSpinBox change event
self.dlg.doubleSpinBox.valueChanged.connect(self.spinboxActivated)
# show the dialog
self.dlg.show()
# メインcanvasのCRSをlat,lon中心の正射投影に変更
# Change CRS of main canvas to orthographic projection centered on lat,lon
self.lineEdit1Activated()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
# Do something useful here - delete the line containing pass and
# substitute with your code.
self.main()
else:
self.wideline.hide()
self.narrowline.hide()
self.marker.hide()
# ダイアログチェンジイベント || #dialog change event
def lineEdit1Activated(self):
center_str = self.dlg.lineEdit1_1.text().split(",")
if len(center_str) == 2:
if self.isfloat(center_str[0]) and self.isfloat(center_str[1]):
self.lat = float(center_str[0]) # 緯度 || #latitude
self.lon = float(center_str[1]) # 経度 || #longitude
else:
# QMessageBox.information(None, 'Error', u'Invalid latitude/longitude values : Err code1')
return
else: # MapCanvas中心の緯度・経度取得 || #Get the latitude and longitude of the center of MapCanvas
if (center_str[0] != "") or len(center_str) > 2:
# QMessageBox.information(None, 'Error', u'Invalid latitude/longitude values : Err code2')
return
center = self.iface.mapCanvas().center()
canvas_crs = self.iface.mapCanvas().mapSettings().destinationCrs()
epsg4326_crs = QgsCoordinateReferenceSystem("EPSG:4326")
assert epsg4326_crs.isValid()
crs_trans = QgsCoordinateTransform(canvas_crs, epsg4326_crs, QgsProject.instance())
pt4326 = crs_trans.transform(center)
self.lat = float(pt4326.y()) # 緯度|| #latitude
self.lon = float(pt4326.x()) # 経度|| #longitude
if (self.lat < -90) or (self.lat > 90) or (self.lon < -180) or (self.lon > 180):
QMessageBox.information(None, 'Error', u'Invalid latitude/longitude values : Err code3')
else:
QgsMessageLog.logMessage(message=f'Center coordinates (lat={self.lat:10.8f}, lon={self.lon:10.8f})',
tag='terrain4aAVR', level=Qgis.Info)
# GZ: Also set the text input!
self.dlg.lineEdit1_1.setText(f'{self.lat: 8.10f}, {self.lon: 8.10f}')
# 指定座標を中心とした正斜投影のCRSをセット || #Set orthogonal projection CRS centered on specified coordinates
# Question (GZ): Why do you project on sphere, not on GRS80?
self.crs = QgsCoordinateReferenceSystem().fromProj(f'+proj=ortho +lat_0={self.lat:10.9} '
f'+lon_0={self.lon:10.9} +x_0=0 +y_0=0 '
'+ellps=sphere +units=m +no_defs')
QgsProject.instance().setCrs(self.crs)
# 指定座標にキャンバスを移動 || #Move the canvas to the specified coordinates
rect = QgsRectangle(QgsPointXY(-200000, -200000), QgsPointXY(+200000, +200000))
self.iface.mapCanvas().setExtent(rect)
self.iface.mapCanvas().refresh()
# 中心マーカー描画 || #center marker drawing
self.marker.setCenter(QgsPointXY(0, 0))
# 広域境界描画 || #Wide area boundary drawing
points = [QgsPoint(-150000, -150000), QgsPoint(-150000, 150000), QgsPoint(150000, 150000),
QgsPoint(150000, -150000), QgsPoint(-150000, -150000)]
self.wideline.setToGeometry(QgsGeometry.fromPolyline(points), None)
# キャンバス再描画 || #Canvas redraw
self.canvas.refreshAllLayers()
def combobox2Activated(self):
if self.dlg.comboBox2_1.currentIndex() != 0:
self.dlg.label2_2.setEnabled(True)
self.dlg.label2_3.setEnabled(True)
self.dlg.comboBox2_2.setEnabled(True)
self.dlg.comboBox2_3.setEnabled(True)
else:
self.dlg.label2_2.setEnabled(False)
self.dlg.label2_3.setEnabled(False)
self.dlg.comboBox2_2.setEnabled(False)
self.dlg.comboBox2_3.setEnabled(False)
def combobox3Activated(self):
if self.dlg.comboBox3_1.currentIndex() != 0:
self.dlg.label3_2.setEnabled(True)
self.dlg.label3_3.setEnabled(True)
self.dlg.label3_4.setEnabled(True)
self.dlg.label3_5.setEnabled(True)
self.dlg.comboBox3_2.setEnabled(True)
self.dlg.comboBox3_3.setEnabled(True)
self.dlg.doubleSpinBox.setEnabled(True)
self.narrowline.show()
self.spinboxActivated()
else:
self.dlg.label3_2.setEnabled(False)
self.dlg.label3_3.setEnabled(False)
self.dlg.label3_4.setEnabled(False)
self.dlg.label3_5.setEnabled(False)
self.dlg.comboBox3_2.setEnabled(False)
self.dlg.comboBox3_3.setEnabled(False)
self.dlg.doubleSpinBox.setEnabled(False)
self.narrowline.hide()
def spinboxActivated(self):
# GZ The round is important (GUI allows 1 decimal place), else some other grid becomes too large (L622)
self.S_dem_mesh = round(self.dlg.doubleSpinBox.value(), 1)
self.S_output_size = self.S_dem_px * self.S_dem_mesh # total size of inner DEM, m.
self.S_tex_mesh = self.S_dem_mesh / 5
area = self.S_dem_mesh * self.S_dem_px # inner square side length. (PixelSize * PixelCount)
self.dlg.label3_5.setText(f"(narrow area: {area:3.2f}m")
# 狭域境界描画 || #Narrow boundary drawing
points = [QgsPoint(-area / 2, -area / 2), QgsPoint(-area / 2, area / 2), QgsPoint(area / 2, area / 2),
QgsPoint(area / 2, -area / 2), QgsPoint(-area / 2, -area / 2)]
self.narrowline.setToGeometry(QgsGeometry.fromPolyline(points), None)
# noinspection PyMethodMayBeStatic
def isfloat(self, parameter):
"""Check that decimal point conversion is possible"""
if not parameter.isdecimal():
try:
float(parameter)
return True
except ValueError:
return False
else:
return True
# BLH (lat, lon, ht) -> ECEF 変換(x, y, z)
def blh2ecef(self, lat, lon, ht):
"""BLH (lat, lon, ht) -> ECEF conversion (x, y, z)
Geodetic lat/lon/ht to Earth-centered.
https://en.wikipedia.org/wiki/Geographic_coordinate_conversion
"""
lat_rad = np.deg2rad(lat)
lon_rad = np.deg2rad(lon)
# n = lambda x: self.A / np.sqrt(1.0 - self.E2 * np.sin(np.deg2rad(x))**2)
# x = (n(lat) + ht) * np.cos(lat_rad) * np.cos(lon_rad)
# y = (n(lat) + ht) * np.cos(lat_rad) * np.sin(lon_rad)
# z = (n(lat) * (1.0 - self.E2) + ht) * np.sin(lat_rad)
n_phi = self.A / np.sqrt(1.0 - self.E2 * np.sin(lat_rad) ** 2)
x = (n_phi + ht) * np.cos(lat_rad) * np.cos(lon_rad)
y = (n_phi + ht) * np.cos(lat_rad) * np.sin(lon_rad)
z = (n_phi * (1.0 - self.E2) + ht) * np.sin(lat_rad)
return [x, y, z]
# ECEF 変換(x, y, z) -> BLH (lat, lon, ht)
def ecef2blh(self, x, y, z):
"""ECEF conversion (x, y, z) -> BLH (lat, lon, ht)
Source: UNKNOWN. TODO: Please document!
"""
n = lambda x: self.A / np.sqrt(1.0 - self.E2 * np.sin(np.deg2rad(x)) ** 2)
p = np.sqrt(x * x + y * y)
theta = np.arctan2(z * self.A, p * self.B)
lat = np.rad2deg(
np.arctan2(z + self.ED2 * self.B * np.sin(theta) ** 3, p - self.E2 * self.A * np.cos(theta) ** 3))
lon = np.rad2deg(np.arctan2(y, x))
ht = (p / np.cos(np.deg2rad(lat))) - n(lat)
return [lat, lon, ht]
# noinspection PyMethodMayBeStatic
def mat_y(self, ang: float):
""" Rotation matrix around the y axis"""
a = np.deg2rad(ang)
c = np.cos(a)
s = np.sin(a)
return np.array([[c, 0.0, -s], [0.0, 1.0, 0.0], [s, 0.0, c]])
# noinspection PyMethodMayBeStatic
def mat_z(self, ang: float):
""" Rotation matrix around the z axis"""
a = np.deg2rad(ang)
c = np.cos(a)
s = np.sin(a)
return np.array([[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]])
# noinspection PyMethodMayBeStatic
def saveimg(self, options: QgsMapSettings, path: str):
"""jpg output
:type options: QgsMapSettings
"""
render = QgsMapRendererParallelJob(options)
render.start()
render.waitForFinished()
img = render.renderedImage()
img.save(path, "jpg")
# 出力領域(m):unity用Terrain対応の為に計算領域に+1pxの範囲を指定している
def terainCalc(self, width: float, dem_mesh: float, dem_layer: str, geo_layer: str, mask_layer: str, mask_array,
out_name: str):
"""Output area (m): +1px range is specified for calculation area to support Terrain for Unity
width: raster size (meters)
dem_mesh: target resolution (cell size, m)
dem_layer: name of DEM layer
geo_layer: name of geoid layer
mask_layer: name of mask layer (TODO: Document its use!)
mask_array
out_name: new name
"""
area_rect: str = '-' + str(width / 2) + ',' + str(width / 2 + dem_mesh) + ',-' + str(
width / 2 + dem_mesh) + ',' + str(width / 2)
layer : QgsMapLayer = QgsProject.instance().mapLayersByName(dem_layer)[0]
uri : str = layer.dataProvider().dataSourceUri()
# DTM:正斜投影で再投影し画像範囲でクリップ
# DTM: Reproject with orthographic projection and clip in image range
if (out_name == "narrowTerrain_DTM") and (mask_layer != ""):
# 詳細地形処理で且つマスク指定ありの場合 || #When using detailed terrain processing and with mask specified
# DTM:詳細地形をメモリ上にラスタ展開、 || #DTM: Raster development of detailed terrain in memory,
parameter = {'BANDS': [1], 'DATA_TYPE': 7, 'INPUT': uri, 'OPTIONS': '', 'OUTPUT': 'TEMPORARY_OUTPUT'}
memory_uri = processing.run('gdal:rearrange_bands', parameter)
# self.iface.addRasterLayer(memory_uri ['OUTPUT'], 'rearrangeDEM')
# Mask_Layerの領域下降処理 || #Mask_Layer area descending process
layer = QgsProject.instance().mapLayersByName(mask_layer)[0]
parameter = {'ADD': True, 'BURN': -self.down, 'EXTRA': '', 'INPUT': layer,
'INPUT_RASTER': memory_uri['OUTPUT'], 'OUTPUT': 'TEMPORARY_OUTPUT'}
memory_uri = processing.run('gdal:rasterize_over_fixed_value', parameter)
# self.iface.addRasterLayer(memory_uri ['OUTPUT'], 'over_fixedDEM')
parameter = { 'INPUT': memory_uri['OUTPUT'] }
#parameter = {'DATA_TYPE': 7, 'INPUT': memory_uri['OUTPUT'], 'OUTPUT': 'TEMPORARY_OUTPUT',
# 'TARGET_CRS': self.crs, 'TARGET_RESOLUTION': dem_mesh,
# 'TARGET_EXTENT': area_rect, 'TARGET_EXTENT_CRS': self.crs}
else: # ベース地形処理、またはマスク指定がない詳細地形処理
# Base terrain processing or detailed terrain processing without mask specification
parameter = {'INPUT': uri }
# Add common parameters
parameter |= {'DATA_TYPE': 7, 'OUTPUT': 'TEMPORARY_OUTPUT', 'TARGET_CRS': self.crs,
'TARGET_RESOLUTION': dem_mesh, 'TARGET_EXTENT': area_rect, 'TARGET_EXTENT_CRS': self.crs}
# TODO - DONE / GZ DEBUG: Why is TARGET RESOLUTION -tr always 5 if configured to be 0.5???
# GZ: If dem_mesh<layer_resolution, interpolate!!!! --> add RESAMPLING (bilinear)
if (dem_mesh < layer.rasterUnitsPerPixelX()):
parameter |= {'RESAMPLING': '1'}
QgsMessageLog.logMessage("DEM Processing " + str(parameter), tag='terrain4aAVR', level=Qgis.Info)
dem = processing.run('gdal:warpreproject', parameter)
# self.iface.addRasterLayer(dem['OUTPUT'], 'orthoDEM')
# DTM:numpy配列読み込み || #DTM: Read numpy array
src = gdal.Open(dem['OUTPUT'], gdal.GA_ReadOnly)
dem_array = src.GetRasterBand(1).ReadAsArray()
if (geo_layer != ""): # ジオイド指定がある場合 || #If there is a geoid specification
# GEOID:正斜投影で再投影し画像範囲でクリップ
# GEOID: Reproject with orthographic projection and clip by image range
layer = QgsProject.instance().mapLayersByName(geo_layer)[0]
uri = layer.dataProvider().dataSourceUri()
parameter = {'DATA_TYPE': 7, 'INPUT': uri, 'OUTPUT': 'TEMPORARY_OUTPUT', 'TARGET_CRS': self.crs,
'TARGET_RESOLUTION': dem_mesh, 'TARGET_EXTENT': area_rect, 'TARGET_EXTENT_CRS': self.crs}
geo = processing.run('gdal:warpreproject', parameter)
# self.iface.addRasterLayer(geo['OUTPUT'], 'orthoGEO')
# GEOID:numpy配列読み込み || #GEOID: read numpy array
src = gdal.Open(geo['OUTPUT'], gdal.GA_ReadOnly)
geo_array = src.GetRasterBand(1).ReadAsArray()
geo_array[geo_array < 0] = 0
# DTM/GEOID配列の統合 || #DTM/GEOID array integration
out_array = dem_array + geo_array
else: # ジオイド指定がない場合 || #If there is no geoid specification
QgsMessageLog.logMessage(out_name + " does not set GEOID", tag='terrain4aAVR', level=Qgis.Info)
out_array = dem_array
# プログレスバーの表示 || #Display progress bar
progressMessageBar = iface.messageBar().createMessage("Calculate DTM: " + dem_layer)
self.progress = QProgressBar()
self.progress.setMaximum(100)
self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
progressMessageBar.layout().addWidget(self.progress)
self.iface.messageBar().pushWidget(progressMessageBar, Qgis.Info)
# 球体補正値を加算 || #Add sphere correction value
half_width = width / 2
px_size = width / dem_mesh
plus_px_size = int(px_size + 1)
half_px_size = px_size / 2
co_prog = 100 / plus_px_size
co_level = 65536 / self.h_max
mask = False
if type(mask_array).__module__ == "numpy": # 詳細地形マスクの指定がある場合 || #If detailed terrain mask is specified
mask = True
mask_w = int(mask_array.shape[0] / 2)
for h in range(0, plus_px_size):
QApplication.processEvents()
self.progress.setValue(int(h * co_prog + 1))
for w in range(0, plus_px_size):
z = out_array[w, h] # 標高値 || #Elevation value
ecef_t = np.dot(self.mat, [w * dem_mesh - half_width, h * dem_mesh - half_width, 0])
ecef = np.add(self.ecef_o, ecef_t)
blh = self.ecef2blh(*ecef)
# blh[]=[lat, lon, ht]:blh[2]=球体降下値(+値)
# zoffset:標高オフセット、down:マスクエリアの降下量
# blh[]=[lat, lon, ht]: blh[2]=Sphere descent value (+ value)
# zoffset: Altitude offset, down: Amount of descent of mask area
level = (z - blh[2] + self.zoffset) * co_level # 0〜65536(-1000m=0, 0m=6553, 9000m=65536):球体補正後の高さ || Height after sphere correction
# 詳細マスク付き基本地形 || #Basic terrain with detailed mask
if out_name == "wideTerrain_DTM" and mask:
center_x = int(w - half_px_size)
center_y = int(h - half_px_size)
if abs(center_x) < mask_w and abs(center_y) < mask_w:
# マスク領域内の処理 || #Processing within the mask area
mask_z = mask_array[int(center_x + mask_w), int(center_y + mask_w)]
# 0〜65536(-1000m=0, 0m=6553, 9000m=65536):球体補正後の高さ || Height after sphere correction
if mask_z > (self.zoffset - blh[2]) * co_level:
# 詳細地形が地球楕円体より高い場合は、詳細地形-self.downを基本地形にセットする。
# #If the detailed terrain is higher than the earth ellipsoid, set detailed terrain-self.down to the basic terrain.
level = mask_z - self.down * co_level
# 詳細マスクなし基本地形 / 詳細地形:標高データが水面より下の場合、地球楕円体-1mを設定
# Basic terrain without detailed mask / Detailed terrain: If the elevation data is below the water surface, set earth ellipsoid -1m
elif dem_array[w, h] <= 0:
level = (self.zoffset - blh[2] - 1) * co_level
# 全ての地形 || #all terrain
if dem_array[w, h] == np.nan or level < 0:
# nodataまたは球体補正後の高さが負の場合は0を設定
# Set 0 if nodata or height after sphere correction is negative
level = 0
out_array[w, h] = level
# プログレスバーの非表示 || #Hide progress bar
self.iface.messageBar().clearWidgets()
# geotiff書き出し || #export geotiff
geotransform = src.GetGeoTransform()
originY = geotransform[3]
originX = geotransform[0]
dst = self.output_path + out_name + ".tif"
dtype = gdal.GDT_UInt16 # others: gdal.GDT_Byte, ...
band = 1 # バンド数 || # Number of bands
dst_raster = gdal.GetDriverByName('GTiff').Create(dst, int(px_size + 1), int(px_size + 1), band, dtype)
dst_raster.SetGeoTransform((originX, dem_mesh, 0, originY, 0, -dem_mesh))
dst_band = dst_raster.GetRasterBand(1)
# GZ These 2 numpy arrays only for diagnostics -- sometimes sizes don't match!
array_dst_band = np.array(dst_band)
array_out_array = np.array(out_array)
QgsMessageLog.logMessage('Raster sizes:'
f' dst_size {int(px_size + 1)}x{int(px_size + 1)} / {int(px_size + 1)**2}, '
f' dst_band {array_dst_band.shape} / {array_dst_band.size},'
f' out_array {array_out_array.shape} / {array_out_array.size}',
tag='terrain4aAVR', level=Qgis.Info)
dst_band.WriteArray(out_array)
dst_band.FlushCache()
dst_raster = None
# レイヤー追加 || #Add layer
layertree = QgsProject.instance().layerTreeRoot()
try:
layer = QgsProject.instance().mapLayersByName(out_name)[0]
except IndexError:
pass
else:
QgsProject.instance().removeMapLayer(layer)
layer = self.iface.addRasterLayer(dst, out_name)
layer.setCrs(self.crs)
return out_array, dst
# 出力領域(m) || #Output area (m)
def textureCalc(self, width: float, tex_mesh: float, tex_layer: str, out_name: str):
"""Create a square texture
width: new size, meters, but as float
tex_mesh: resolution (pixel size), m/px
tex_layer: name of texture layer
"""
QgsMessageLog.logMessage(message=f'textureCalc: width={width}, tex_mesh={tex_mesh}, tex_layer={tex_layer}, out_name={out_name}',
tag='terrain4aAVR', level=Qgis.Info)
area_rect: str = f'-{width / 2},{width / 2},-{width / 2},{width / 2}'
# TEXTURE:Canvasの投影形式でxyzタイルを画像範囲でクリップ
# TEXTURE: Clip xyz tiles by image range in Canvas projection format
layer = QgsProject.instance().mapLayersByName(tex_layer)[0]
uri = layer.dataProvider().dataSourceUri()
parameters = {'EXTENT': area_rect, 'LAYERS': [uri], 'MAP_UNITS_PER_PIXEL': tex_mesh,
'OUTPUT': 'TEMPORARY_OUTPUT', 'TILE_SIZE': width / tex_mesh}
# GZ DEBUG OUTPUT
QgsMessageLog.logMessage(message="Processing: call QGIS:rasterize with parameters:" + str(parameters),
tag='terrain4aAVR', level=Qgis.Info)
tex = processing.run('qgis:rasterize', parameters)
# layertree = QgsProject.instance().layerTreeRoot()
try:
layer = QgsProject.instance().mapLayersByName(out_name)[0]
except IndexError:
pass
else:
QgsProject.instance().removeMapLayer(layer)
layer = self.iface.addRasterLayer(tex['OUTPUT'], out_name)
layer.setCrs(self.crs)
def main(self):
# レイヤーの初期設定
# Layer initial settings.
# GZ: I think we can delete the empty pre-initializer.
# L_dem_layer = ""
# L_geo_layer = ""
# L_tex_layer = ""
# S_dem_layer = ""
# S_geo_layer = ""
# S_tex_layer = ""
# mask_layer = ""
# TODO: Decide upon one of these to avoid a deprecation warning. For now, we don't handle exceptions,
# so just not use them.
gdal.DontUseExceptions()
#gdal.UseExceptions()
self.output_path: str = self.dlg.mQgsFileWidget_outputPath.filePath() + "/"
if self.output_path == "/":
QMessageBox.information(None, 'Error', u'Destination not specified : Err code4')
return
else:
QgsMessageLog.logMessage("Save to =" + self.output_path, tag='terrain4aAVR', level=Qgis.Info)
# 入力レイヤー(L_はベース地形用、S_は詳細地形用)
# Input layer (L_ is for base terrain, S_ is for detailed terrain)
# TODO: It would be easier to read if the GUI elements were renamed in the .ui file.
L_dem_layer: str = self.single_list[self.dlg.comboBox2_1.currentIndex()]
L_geo_layer: str = self.single_list[self.dlg.comboBox2_2.currentIndex()]
L_tex_layer: str = self.multi_list[self.dlg.comboBox2_3.currentIndex()]
S_dem_layer: str = self.single_list[self.dlg.comboBox3_1.currentIndex()]
S_geo_layer: str = self.single_list[self.dlg.comboBox3_2.currentIndex()]
S_tex_layer: str = self.multi_list[self.dlg.comboBox3_3.currentIndex()]
mask_layer: str = self.vector_list[self.dlg.comboBox4.currentIndex()]
QgsMessageLog.logMessage("wideTerrain layer=" + L_dem_layer + ", " + L_geo_layer + ", " + L_tex_layer,
tag='terrain4aAVR', level=Qgis.Info)
QgsMessageLog.logMessage("narrowTerrain layer=" + S_dem_layer + ", " + S_geo_layer + ", " + S_tex_layer,
tag='terrain4aAVR', level=Qgis.Info)
QgsMessageLog.logMessage("Mask layer=" + mask_layer, tag='terrain4aAVR', level=Qgis.Info)
if (self.dlg.comboBox2_1.currentIndex() == 0) and (self.dlg.comboBox3_1.currentIndex() == 0):
QMessageBox.information(None, 'Error', u'DEM layer not specified : Err code5')
return
# 時間計測開始 || #Start time measurement
start = time.time()
QgsMessageLog.logMessage("Start time=" + str(datetime.datetime.now()), tag='terrain4aAVR', level=Qgis.Info)
# ERN->ECEF変換行列の作製 || #Create ERN->ECEF conversion matrix
mat_0 = self.mat_z(-90.0)
mat_1 = self.mat_y(self.lat - 90.0)
mat_2 = self.mat_z(-self.lon)
self.mat = np.dot(np.dot(mat_2, mat_1), mat_0)
# 原点のECEFを取得 || #Get the origin ECEF
self.ecef_o = self.blh2ecef(self.lat, self.lon, 0)
# 詳細地形の処理++++++++++++++++++
# Detailed terrain processing++++++++++++++++++
if (S_dem_layer != ""):
# Terrain作成 || #Create Terrain
S_out, S_uri = self.terainCalc(self.S_output_size, self.S_dem_mesh, S_dem_layer, S_geo_layer, mask_layer, 0,
"narrowTerrain_DTM")
# raw保存(リトルエンディアン形式"<" 符号なし16ビット"u2") https://note.nkmk.me/python-numpy-dtype-astype/
# Save raw (little endian format "<" unsigned 16 bit "u2")
S_out.astype('<u2').tofile(self.output_path + "terrain00.raw")
if (S_tex_layer != ""):
# Texture作成 || #Texture creation
self.textureCalc(self.S_output_size, self.S_tex_mesh, S_tex_layer, "narrowTerrain_TEX")
pxsize = self.S_output_size / self.S_tex_mesh
if pxsize > 16384:
pxsize = 16384
texlayer = QgsProject.instance().mapLayersByName("narrowTerrain_TEX")[0]
options = QgsMapSettings()
options.setLayers([texlayer])
options.setBackgroundColor(QColor(0, 0, 0))
options.setOutputSize(QSize(pxsize, pxsize))
options.setExtent(QgsRectangle(-self.S_output_size / 2, self.S_output_size / 2,
self.S_output_size / 2, -self.S_output_size / 2))
self.saveimg(options, self.output_path + "terrain00.jpg")
# Terrain Mask用Array作成 || #Creating an array for Terrain Mask
s_width = str(self.S_output_size / 2)
area_rect = '-' + s_width + ',' + s_width + ',-' + s_width + ',' + s_width
# 正斜投影・近傍の最小値データ( 'RESAMPLING' : 8)で再投影しベース地形解像度でクリップし直し
# Reproject with orthographic projection/neighboring minimum value data ('RESAMPLING': 8)
# and re-clip with base terrain resolution
uri = S_uri
parameter = {'DATA_TYPE': 7, 'INPUT': uri, 'OUTPUT': 'TEMPORARY_OUTPUT', 'RESAMPLING': 8,
'TARGET_CRS': self.crs, 'TARGET_RESOLUTION': self.L_dem_mesh,
'TARGET_EXTENT': area_rect, 'TARGET_EXTENT_CRS': self.crs}
mask = processing.run('gdal:warpreproject', parameter)
# iface.addRasterLayer(mask['OUTPUT'], 'areaTerrain_MASK')
# areaTerrain_MASK:numpy配列読み込み
# areaTerrain_MASK: read numpy array
src = gdal.Open(mask['OUTPUT'], gdal.GA_ReadOnly)
dem_mask = src.GetRasterBand(1).ReadAsArray()
else:
dem_mask = [[]]
# ベース地形の処理++++++++++++++++++ || #Base terrain processing++++++++++++++++++
if (L_dem_layer != ""):
# Terrain作成 || #Create Terrain
L_out, L_uri = self.terainCalc(self.L_output_size, self.L_dem_mesh, L_dem_layer, L_geo_layer,
mask_layer, dem_mask, "wideTerrain_DTM")
arr11 = L_out[:int(self.L_dem_px / 3 + 1), :int(self.L_dem_px / 3 + 1)]
arr12 = L_out[:int(self.L_dem_px / 3 + 1), int(self.L_dem_px / 3):int(self.L_dem_px * 2 / 3 + 1)]
arr13 = L_out[:int(self.L_dem_px / 3 + 1), int(self.L_dem_px * 2 / 3):]
arr21 = L_out[int(self.L_dem_px / 3):int(self.L_dem_px * 2 / 3 + 1), :int(self.L_dem_px / 3 + 1)]
arr22 = L_out[int(self.L_dem_px / 3):int(self.L_dem_px * 2 / 3 + 1),
int(self.L_dem_px / 3):int(self.L_dem_px * 2 / 3 + 1)]
arr23 = L_out[int(self.L_dem_px / 3):int(self.L_dem_px * 2 / 3 + 1), int(self.L_dem_px * 2 / 3):]
arr31 = L_out[int(self.L_dem_px * 2 / 3):, :int(self.L_dem_px / 3 + 1)]
arr32 = L_out[int(self.L_dem_px * 2 / 3):, int(self.L_dem_px / 3):int(self.L_dem_px * 2 / 3 + 1)]
arr33 = L_out[int(self.L_dem_px * 2 / 3):, int(self.L_dem_px * 2 / 3):]
# raw保存(リトルエンディアン形式"<" 符号なし16ビット"u2") https://note.nkmk.me/python-numpy-dtype-astype/
# Save raw (little endian format "<" unsigned 16 bit "u2") https://note.nkmk.me/python-numpy-dtype-astype/
arr11.astype('<u2').tofile(self.output_path + "terrain11.raw")
arr12.astype('<u2').tofile(self.output_path + "terrain12.raw")
arr13.astype('<u2').tofile(self.output_path + "terrain13.raw")
arr21.astype('<u2').tofile(self.output_path + "terrain21.raw")
arr22.astype('<u2').tofile(self.output_path + "terrain22.raw")
arr23.astype('<u2').tofile(self.output_path + "terrain23.raw")
arr31.astype('<u2').tofile(self.output_path + "terrain31.raw")
arr32.astype('<u2').tofile(self.output_path + "terrain32.raw")
arr33.astype('<u2').tofile(self.output_path + "terrain33.raw")
if (L_tex_layer != ""):
# Texture作成 || #Texture creation
self.textureCalc(self.L_output_size, self.L_tex_mesh, L_tex_layer, "wideTerrain_TEX")
texlayer = QgsProject.instance().mapLayersByName("wideTerrain_TEX")[0]
options = QgsMapSettings()
options.setLayers([texlayer])
options.setBackgroundColor(QColor(0, 0, 0))
options.setOutputSize(QSize(self.L_dem_px / 3, self.L_dem_px / 3))
options.setExtent(QgsRectangle(-self.L_output_size / 2, self.L_output_size / 2,
-self.L_output_size / 6, self.L_output_size / 6))
self.saveimg(options, self.output_path + "terrain11.jpg")
options.setExtent(QgsRectangle(-self.L_output_size / 6, self.L_output_size / 2,
self.L_output_size / 6, self.L_output_size / 6))
self.saveimg(options, self.output_path + "terrain12.jpg")
options.setExtent(QgsRectangle(self.L_output_size / 6, self.L_output_size / 2,
self.L_output_size / 2, self.L_output_size / 6))
self.saveimg(options, self.output_path + "terrain13.jpg")
options.setExtent(QgsRectangle(-self.L_output_size / 2, self.L_output_size / 6,
-self.L_output_size / 6, -self.L_output_size / 6))
self.saveimg(options, self.output_path + "terrain21.jpg")
options.setExtent(QgsRectangle(-self.L_output_size / 6, self.L_output_size / 6,
self.L_output_size / 6, -self.L_output_size / 6))
self.saveimg(options, self.output_path + "terrain22.jpg")
options.setExtent(QgsRectangle(self.L_output_size / 6, self.L_output_size / 6,
self.L_output_size / 2, -self.L_output_size / 6))
self.saveimg(options, self.output_path + "terrain23.jpg")
options.setExtent(QgsRectangle(-self.L_output_size / 2, -self.L_output_size / 6,
-self.L_output_size / 6, -self.L_output_size / 2))
self.saveimg(options, self.output_path + "terrain31.jpg")
options.setExtent(QgsRectangle(-self.L_output_size / 6, -self.L_output_size / 6,
self.L_output_size / 6, -self.L_output_size / 2))
self.saveimg(options, self.output_path + "terrain32.jpg")
options.setExtent(QgsRectangle(self.L_output_size / 6, -self.L_output_size / 6,
self.L_output_size / 2, -self.L_output_size / 2))
self.saveimg(options, self.output_path + "terrain33.jpg")
# レイヤの表示順(areTex>areaDTM>baseTEX>baseDTM)を変更++++++++++++++++++
# Change layer display order (areTex>areaDTM>baseTEX>baseDTM)++++++++++++++++++
layertree = QgsProject.instance().layerTreeRoot()
try:
layer = QgsProject.instance().mapLayersByName("wideTerrain_DTM")[0]
except IndexError:
pass
else:
lt = layertree.findLayer(layer.id())
lt_clone = lt.clone()
layertree.insertChildNode(0, lt_clone)
layertree.removeChildNode(lt)
layertree = QgsProject.instance().layerTreeRoot()
try:
layer = QgsProject.instance().mapLayersByName("narrowTerrain_TEX")[0]
except IndexError:
pass
else:
lt = layertree.findLayer(layer.id())
lt_clone = lt.clone()
layertree.insertChildNode(0, lt_clone)
layertree.removeChildNode(lt)
layertree = QgsProject.instance().layerTreeRoot()
try:
layer = QgsProject.instance().mapLayersByName("narrowTerrain_DTM")[0]
except IndexError:
pass
else:
lt = layertree.findLayer(layer.id())
lt_clone = lt.clone()
layertree.insertChildNode(0, lt_clone)
layertree.removeChildNode(lt)
# 出力時間============================ || #Output time ============================
elapsed_time = int(time.time() - start)
elapsed_hour = elapsed_time // 3600
elapsed_minute = (elapsed_time % 3600) // 60
elapsed_second = (elapsed_time % 3600 % 60)
QgsMessageLog.logMessage(message="output time={0}:{1}:{2}".format(str(elapsed_hour).zfill(2),
str(elapsed_minute).zfill(2),
str(elapsed_second).zfill(2)),
tag='terrain4aAVR', level=Qgis.Info)