-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmorph.py
executable file
·277 lines (216 loc) · 9.55 KB
/
morph.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
#!/usr/bin/env python
import os
import copy
import optparse
from cvf import *
from dictionary_spline import *
from math import atan2, sqrt, pi
def getCameraAngles(xSpline, ySpline, zSpline, frames, fixedX=None, fixedY=None, fixedZ=None):
yawVals = []
pitchVals = []
for frame in range(int(frames)):
currentXVal = xSpline[frame]
currentYVal = ySpline[frame]
currentZVal = zSpline[frame]
nextXVal = xSpline[(frame + 1) % frames] if fixedX is None else fixedX
nextYVal = ySpline[(frame + 1) % frames] if fixedY is None else fixedY
nextZVal = zSpline[(frame + 1) % frames] if fixedZ is None else fixedZ
dx = nextXVal - currentXVal
dy = nextYVal - currentYVal
dz = nextZVal - currentZVal
yaw = atan2(dx, dz) + pi / 2
pitch = atan2(sqrt(dz * dz + dx * dx), dy) + pi
yawVals.append(rad2deg(yaw))
pitchVals.append(rad2deg(pitch))
yawVals.append(yawVals[-1])
pitchVals.append(pitchVals[-1])
# duplicate last values
return yawVals, pitchVals
def findInflection(values):
if len(values) <= 2:
return
isUp = lambda x, y: x <= y
isDown = lambda x, y: x >= y
up = isUp(values[0], values[1])
normal = isUp if up else isDown
for i in range(len(values) -1):
if not normal(values[i], values[i+1]):
return i+1
def overrideSunMovement(scenes):
sunAltitudes = [scene.getSunAltitude() for scene in scenes]
if len(sunAltitudes) <= 2:
return
isIncreasing = all(
sunAltitudes[i] <= sunAltitudes[i+1] for i in range(len(sunAltitudes)-1))
isDecreasing = all(
sunAltitudes[i] >= sunAltitudes[i+1] for i in range(len(sunAltitudes)-1))
if not isIncreasing and not isDecreasing:
inflectionPoint = findInflection(sunAltitudes)
overrideSunMovement(scenes[:inflectionPoint])
overrideSunMovement(scenes[inflectionPoint-1:])
return
dawn = sunAltitudes[0] if isIncreasing else sunAltitudes[-1]
dusk = sunAltitudes[0] if isDecreasing else sunAltitudes[-1]
num = len(sunAltitudes)
step = float(dusk - dawn)/(num-1)
for i in range(1, num-1):
scenes[i].setSunAltitude(i*step)
def getTimes(cvfList, r, v, fixedLength=None):
times = [0.0]
totalLength = 0.0
xes = [cvf.getX() for cvf in cvfList]
yes = [cvf.getY() for cvf in cvfList]
zes = [cvf.getZ() for cvf in cvfList]
areAllSame = (
xes.count(xes[0]) == len(xes) and
yes.count(yes[0]) == len(yes) and
zes.count(zes[0]) == len(zes))
if areAllSame and len(cvfList) > 1:
times = [i * (fixedLength) / (len(cvfList) - 1)
for i in range(len(cvfList))]
totalLength = fixedLength
else:
for i in range(len(cvfList) - 1):
previousFrame = cvfList[i]
nextFrame = cvfList[i + 1]
dx = nextFrame.getX() - previousFrame.getX()
dy = nextFrame.getY() - previousFrame.getY()
dz = nextFrame.getZ() - previousFrame.getZ()
distance = (dx * dx + dy * dy + dz * dz) ** 0.5
times.append(distance * r / v)
times[-1] += times[-2]
totalLength += distance
if fixedLength is not None:
factor = fixedLength / times[-1]
times[:] = [time * factor for time in times]
return (times, totalLength)
def saveFiles(cvfs, outputDir, filenameOffset=0):
for i in range(len(cvfs)):
c = cvfs[i]
name = os.path.join(outputDir, "interpolated-" + str(i+filenameOffset) + ".json")
c.setName("interpolated-" + str(i))
print (str(i) + ": " +
("X: %(x).2f " +
"Y: %(y).2f " +
"Z: %(z).2f " +
"Pitch: %(pitch).2f " +
"Yaw: %(yaw).2f " +
"SunAltitude: %(alt).2f " +
"SunAzimuth: %(azim).2f ") %
{
'x': c.getX(),
'y': c.getY(),
'z': c.getZ(),
'pitch': c.getPitch(),
'yaw': c.getYaw(),
'alt': c.getSunAltitude(),
'azim': c.getSunAzimuth()
})
c.saveToFile(name)
def main():
parser = optparse.OptionParser(
usage="%prog [options] scene1 scene2 scene3 scene4 ...",
description="Chunkymator scene interpolator."
"Source available at https://github.com/matthiasvegh/Chunkymator")
parser.add_option("-o", "--outputdir", dest="outputdir",
help="Directory to place interpoalted scenes to.",
metavar="DIR")
parser.add_option("-f", "--frame-rate", dest="frameRate",
help="What frame rate you intend to play back the interpolated images (default: %default fps).",
metavar="NUM", default=25, type=float)
parser.add_option("-s", "--traveling-speed", dest="flyingSpeed",
help="What speed the camera should be traveling (default: %default m/s).",
metavar="NUM", default=5.4, type=float)
parser.add_option("-t", "--length", dest="length",
help="Usually the number of intermediate jsons to be generated are calcualated by taking "
"the distance between keyframes. This can be overridden by setting this option.",
metavar="NUM", type=int)
parser.add_option("-d", "--offset", dest="filenameOffset",
help="Filename numbering offset (default: %default).",
metavar="NUM", default=0, type=int)
parser.add_option("-c", "--use-chunky", dest="chunky",
help="If specified, pass input jsons on to Chunky for a sanity check.",
metavar="PATH", type=str)
parser.add_option("-S", "--override-sun", action="store_true", dest="sunoverride", default=False)
cameraPointOptionsGroup = optparse.OptionGroup(parser, "Camera settings",
"If you specify these, the camera will always point in the direction of "
"these coordinates, if you do not specify them, the camera shall always "
"point forward."
"Either specify them all, or specify none.")
cameraPointOptionsGroup.add_option("-x", "--focus-on-x",
help="X coordinate of where camera should look.",
dest="cameraX",
metavar="NUM", type=float)
cameraPointOptionsGroup.add_option("-y", "--focus-on-y",
help="Y coordinate of where camera should look.",
dest="cameraY",
metavar="NUM", type=float)
cameraPointOptionsGroup.add_option("-z", "--focus-on-z",
help="Z coordinate of where camera should look.",
dest="cameraZ",
metavar="NUM", type=float)
parser.add_option_group(cameraPointOptionsGroup)
(options, scenes) = parser.parse_args()
fixedCameraCoord = (options.cameraX, options.cameraY, options.cameraZ)
num = len(scenes)
cvfList = []
i = 0
if num < 4:
print "This script requires at least 4 input jsons to generate a route between them."
return
while i < num:
try:
filename = scenes[i]
print "loading ", filename
scene = cvf(filename)
cvfList.append(scene)
print ("X: " + str(scene.getX()) +
" Y: " + str(scene.getY()) +
" Z: " + str(scene.getZ()) +
" Pitch: " + str(scene.getPitch()) +
" Yaw: " + str(scene.getYaw()))
i += 1
except EnvironmentError:
print "could not get file #" + str(i + 1) + " please try again!"
return
print "done loading " + str(num) + " files."
cvfJsons = [_c.inputJson for _c in cvfList]
if not jsonSchemaCheck(cvfJsons):
print "Schema of input files do not match."
return
outputDir = options.outputdir
if outputDir is None:
outputDir = './outputs'
# input got, start actual work here.
#############################
v = options.flyingSpeed
r = options.frameRate
#############################
times, totalLength = getTimes(cvfList, r, v, options.length)
print "length of requested route: " + str(totalLength) + "m"
print "total number of frames to be generated: " + str(int(r * (totalLength / v)))
jsonList = [c.inputJson for c in cvfList]
jsonSpline = DictionarySpline(times, [jsonList])
localCVFs = []
for i in range(int(times[-1])):
json = jsonSpline(i)[0]
c = copy.deepcopy(cvfList[-1])
c.inputJson = json
c.inputJson['renderTime'] = cvfList[-1].inputJson['renderTime']
localCVFs.append(c)
xValues = []
yValues = []
zValues = []
print times
for cvf_ in localCVFs:
xValues.append(cvf_.getX())
yValues.append(cvf_.getY())
zValues.append(cvf_.getZ())
yawPath, pitchPath = getCameraAngles(
xValues, yValues, zValues, len(localCVFs), *fixedCameraCoord)
for cvfIndex in range(len(localCVFs)):
localCVFs[cvfIndex].setYaw(yawPath[cvfIndex])
localCVFs[cvfIndex].setPitch(pitchPath[cvfIndex])
saveFiles(localCVFs, outputDir, options.filenameOffset)
if __name__ == "__main__":
main()