-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathex9_model_vis_web.py
214 lines (167 loc) · 7.06 KB
/
ex9_model_vis_web.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
# Copyright (c) 2012-2024 Esri R&D Center Zurich
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# A copy of the license is available in the repository's LICENSE file.
import os
import random
import string
import json
import argparse
import getpass
import math
from pathlib import Path
import tornado.ioloop
import tornado.web
import webbrowser
from threading import Timer
import pyprt
from arcgis.gis import GIS
DBG = True
CS_FOLDER = Path().absolute()
ROOT = os.path.join(CS_FOLDER, 'ex9_html')
OUTPUT_PATH = os.path.join(CS_FOLDER, 'ex9_output')
RPK = os.path.join(CS_FOLDER, 'data', 'translateModel.rpk')
PORT = 9999
AGO_DATA_DIR = 'modelVisServerData'
allowed = set(string.ascii_letters + string.digits + '-' + '_')
def check(file_basename):
return set(file_basename) <= allowed
def georef_shift_vertices(model_vertices, x_coord_goal, y_coord_goal, z_coord_goal):
shifted_vertices = model_vertices.copy()
# Bounding box
min_y_value = min(model_vertices[1::3])
mod_x_values = model_vertices[0::3]
center_x_value = (max(mod_x_values)+min(mod_x_values))/2.0
mod_z_values = model_vertices[2::3]
center_z_value = (max(mod_z_values)+min(mod_z_values))/2.0
# Offset the initial shape at the right location
shifted_vertices[0::3] = [a-center_x_value +
x_coord_goal for a in shifted_vertices[0::3]]
shifted_vertices[1::3] = [
a-min_y_value+z_coord_goal for a in shifted_vertices[1::3]]
shifted_vertices[2::3] = [a-center_z_value -
y_coord_goal for a in shifted_vertices[2::3]]
return shifted_vertices
class MainHandler(tornado.web.RequestHandler):
def initialize(self, gis):
self.basename = ''
self.file_path = ''
self.filename_slpk = ''
self.gis = gis
def save_file(self):
uploaded_file = self.request.files['file'][0]
original_filename = uploaded_file['filename']
extension = os.path.splitext(original_filename)[1]
self.basename = os.path.splitext(original_filename)[0] + '_' + ''.join(random.choice(string.ascii_lowercase +
string.digits) for x in range(5))
if not check(self.basename):
self.basename = ''.join(random.choice(
string.ascii_lowercase + string.digits) for x in range(10))
print(
f'Warning: Invalid basename. Filename renamed to: {self.basename}')
extension_filename = self.basename + extension
self.file_path = os.path.join(OUTPUT_PATH, extension_filename)
with open(self.file_path, 'wb') as output_file:
output_file.write(uploaded_file['body'])
def convert_to_slpk(self):
x_coord = self.get_argument("x_coordinate")
y_coord = self.get_argument("y_coordinate")
elev = self.get_argument("elevation")
if DBG:
print(
f'Setting georef to ({round(float(x_coord),2)}, {round(float(y_coord),2)}) (Web Mercator) with elevation {int(float(elev))} meters')
# Model Generator Instance
mod_generator1 = pyprt.ModelGenerator(
[pyprt.InitialShape(self.file_path)])
shape_attributes = {}
model = mod_generator1.generate_model([shape_attributes], RPK,
'com.esri.pyprt.PyEncoder', {'emitReport': False})
# Shift to right location
mod_vertices = model[0].get_vertices()
mod_vertices_shift = georef_shift_vertices(
mod_vertices, float(x_coord), float(y_coord), float(elev))
shifted_shape = pyprt.InitialShape(
mod_vertices_shift, model[0].get_indices(), model[0].get_faces())
mod_generator2 = pyprt.ModelGenerator([shifted_shape])
slpk_encoder = 'com.esri.prt.codecs.I3SEncoder'
slpk_encoder_options = {
'sceneType': "Local",
'baseName': self.basename,
'sceneWkid': "3857",
'layerTextureEncoding': ["2"],
'layerEnabled': [True],
'layerUID': ["1"],
'layerName': ["1"],
'layerTextureQuality': [1.0],
'layerTextureCompression': [9],
'layerTextureScaling': [1.0],
'layerTextureMaxDimension': [2048],
'layerFeatureGranularity': ["0"],
'layerBackfaceCulling': [False],
'outputPath': OUTPUT_PATH
}
mod_generator2.generate_model([shape_attributes], RPK,
slpk_encoder, slpk_encoder_options)
self.filename_slpk = os.path.join(
OUTPUT_PATH, self.basename + '.slpk')
def publish(self):
slpk_item = self.gis.content.add(
{
"title": f"PyPRT_webApp_{self.basename}",
"tags": "slpk",
},
data=self.filename_slpk,
folder=AGO_DATA_DIR
)
slpk_item_published = slpk_item.publish()
slpk_item_published.share(everyone=True)
slpk_item.delete()
return slpk_item_published.id
def post(self):
self.save_file()
self.convert_to_slpk()
if DBG:
print('Publishing file on ArcGIS Online:')
print(self.filename_slpk)
id = self.publish()
self.write(json.dumps({'portalId': id}))
self.finish()
def on_finish(self):
if DBG:
print('Cleaning up files:')
print(self.file_path)
print(self.filename_slpk)
os.remove(self.file_path)
os.remove(self.filename_slpk)
if not os.path.exists(OUTPUT_PATH):
os.makedirs(OUTPUT_PATH)
def open_browser():
webbrowser.open_new(f'http://localhost:{PORT}/')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='ArcGIS Online credentials')
parser.add_argument(
'--username', help='Your username for AGO', type=str, required=True)
args = parser.parse_args()
user_pwd = getpass.getpass(prompt='Enter your AGOL password: ')
gis = GIS(url='https://www.arcgis.com',
username=args.username, password=user_pwd)
# Create folder for scene layers
gis.content.create_folder(AGO_DATA_DIR)
application = tornado.web.Application([
(r"/file-upload", MainHandler, dict(gis=gis)),
(r"/(.*)", tornado.web.StaticFileHandler,
{"path": ROOT, "default_filename": "index.html"})
])
# PRT Initialization
pyprt.initialize_prt()
application.listen(PORT)
print(f'Listening on Port={PORT}')
Timer(1, open_browser).start()
tornado.ioloop.IOLoop.instance().start()