/
motion.cpp
563 lines (467 loc) · 21.5 KB
/
motion.cpp
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
/*
This file is part of Mitsuba, a physically based rendering system.
Copyright (c) 2007-2012 by Wenzel Jakob and others.
Mitsuba is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License Version 3
as published by the Free Software Foundation.
Mitsuba is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mitsuba/render/scene.h>
#include <mitsuba/render/renderproc.h>
#include <mitsuba/core/autodiff.h>
#include <mitsuba/core/statistics.h>
#include <boost/algorithm/string.hpp>
DECLARE_DIFFSCALAR_BASE();
MTS_NAMESPACE_BEGIN
static StatsCounter statsConverged(
" manifold", "Converged manifold walks", EPercentage);
/*!\plugin{motion}{Motion and specular motion vector integrator}
* \parameters{
* \parameter{time}{\Float}{
* Denotes the time stamp of the target frame of the motion vectors.
* The current frame is specified via the sensor's \code{shutterOpen}
* and \code{shutterClose} parameters, which should both be set to
* the same value. \default{0}
* }
* \parameter{time}{\String}{
* Path configuration of the desired motion vectors:
* \begin{enumerate}[(i)]
* \item \textbf{d}: Primary (non-specular) hit points\vspace{-1mm}
* \item \textbf{rd}: A non-specular surface seen through a specular reflection\vspace{-1mm}
* \item \textbf{ttd}: A non-specular surface seen through a pair of specular refractions\vspace{-1mm}
* \item \textbf{trtd}: A non-specular surface seen through a sequence of refraction, reflection, and refraction events.\vspace{-1mm}
* \end{enumerate}
* etc.
* }
* \parameter{derivativesOnly}{\Boolean}{
* By default, the Manifold Exploration technique is used to accurately
* solve the underlying specular flow problem. When this parameter is set to \code{true},
* the nonlinear solver is deactivated, and only first-order extrapolations are provided.
* \default{\code{false}}
* }
* \parameter{glossyThreshold}{\Float}{
* Threshold on the roughness parameter of reflectance models
* to be classified as specular.
* \default{\texttt{0}, i.e.~only perfectly specular materials are classified as specular}
* }
* \parameter{maxTimeSteps}{\Integer}{
* Maximum number of temporal sub-steps \default{5}
* }
* \parameter{maxSpaceSteps}{\Integer}{
* Maximum number of spatial sub-steps \default{10}
* }
* }
* This integrator extracts motion vectors for animated input scenes, alternatively
* at primary hit points or at hit points observed through sequences of reflective
* and refractive objects. The first two color components (R and G) of the resulting
* rendering specify the screen-space motion in 2D pixel coordinates, and the last
* component (B) denotes the change in distance of the observed 3D point to the
* camera position. Sometimes a specular path cannot be tracked from one frame to the other,
* e.g. because it does not exist, or because the solver did not converge. In this case,
* the pixel color is set to infinity. The images on the following page show
* motion vectors obtained for a sphere that is moving from the left to the right.
*
* \renderings{
* \rendering{Input scene at time $t=0$}{integrator_motion_sphere_1}
* \rendering{Input scene at time $t=1$}{integrator_motion_sphere_2}
* }
* \renderings{
* \medrendering{\code{config="d"}}{integrator_motion_path_d}
* \medrendering{\code{config="rd"}}{integrator_motion_path_rd}
* \medrendering{\code{config="ttd"}}{integrator_motion_path_ttd}
* }
* \renderings{
* \rendering{\code{config="trtd"}}{integrator_motion_path_trtd}
* \rendering{\code{config="trrtd"}}{integrator_motion_path_trrtd}
* }
* \clearpage
*
* \begin{xml}[caption={Exemplary scene configuration for computing specular motion vectors}]
* <scene>
* <integrator type="motion">
* <string name="config" value="ttd"/>
* <float name="time" value="1"/>
* </integrator>
*
* <shape type="serialized">
* <string name="filename" value="..."/>
* <animation name="toWorld">
* <transform time="0">
* <!-- Transformation at time zero -->
* </transform>
* <transform time="1">
* <!-- Transformation at time one -->
* </transform>
* </animation>
* <bsdf type="dielectric"/>
* </shape>
*
* <sensor type="perspective">
* <float name="shutterOpen" value="0"/>
* <float name="shutterClose" value="0"/>
*
* <sampler type="ldsampler">
* <integer name="sampleCount" value="1"/>
* <boolean name="pixelCenters" value="true"/>
* </sampler>
*
* <film type="hdrfilm" id="film">
* <string name="pixelFormat" value="rgb"/>
* <boolean name="banner" value="false"/>
* <rfilter type="box"/>
* </film>
* </sensor>
* </scene>
* \end{xml}
*/
class MotionIntegrator : public SamplingIntegrator {
public:
typedef Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic> EMatrix;
typedef Eigen::Matrix<Float, Eigen::Dynamic, 1> EVector;
typedef Eigen::Matrix<Float, 1, 7> Gradient;
typedef DScalar1<Float, Gradient> DScalar;
typedef DScalar::DVector3 DVector;
MotionIntegrator(const Properties &props) : SamplingIntegrator(props) {
m_time = props.getFloat("time");
m_config = boost::to_lower_copy(props.getString("config", "d"));
if (m_config.length() == 0)
Log(EError, "Path configuration string must have at least one entry!");
if (m_config[m_config.length()-1] != 'd')
Log(EError, "Configuration string must end with 'd'!");
m_derivativesOnly = props.getBoolean("derivativesOnly", false);
m_maxTimeSteps = props.getInteger("maxTimeSteps", 5);
m_maxSpaceSteps = props.getInteger("maxSpaceSteps", 10);
m_glossyThreshold = props.getFloat("glossyThreshold", 0);
m_subSteps = props.getInteger("subSteps", 1);
}
MotionIntegrator(Stream *stream, InstanceManager *manager)
: SamplingIntegrator(stream, manager) {
m_time = stream->readFloat();
m_config = stream->readString();
m_derivativesOnly = stream->readBool();
m_maxTimeSteps = stream->readInt();
m_maxSpaceSteps = stream->readInt();
m_glossyThreshold = stream->readFloat();
m_subSteps = stream->readInt();
}
void serialize(Stream *stream, InstanceManager *manager) const {
SamplingIntegrator::serialize(stream, manager);
stream->writeFloat(m_time);
stream->writeString(m_config);
stream->writeBool(m_derivativesOnly);
stream->writeInt(m_maxTimeSteps);
stream->writeInt(m_maxSpaceSteps);
stream->writeFloat(m_glossyThreshold);
stream->writeInt(m_subSteps);
}
Spectrum Li(const RayDifferential &r, RadianceQueryRecord &rRec) const {
const Point2 apertureSample(0.5f);
Point p0, p1;
if (m_config.length() == 1) {
Intersection &its = rRec.its;
// compute motion of environment
if (!rRec.rayIntersect(r)) {
BSphere sphere = rRec.scene->getBSphere();
Float nearT, farT;
sphere.radius = 1e6;
sphere.rayIntersect(r, nearT, farT);
p0 = r(nearT);
} else {
p0 = its.p;
}
p1 = p0;
// reproject point according to the motion of the intersected shape
if (its.isValid() && its.instance != NULL) {
Intersection its2(its);
its2.adjustTime(m_time);
p1 = its2.p;
}
} else {
std::vector<Intersection> source, target, temp, temp2;
Ray ray(r);
/* Trace an initial light path with the given configuration*/
if (!tracePath(rRec, ray, source))
return Spectrum(0.0f);
m_scene = rRec.scene;
p0 = source[1].p;
int timeIteration = 0;
Float stepSizeReduction = 1.0f;
while (true) {
if (++timeIteration > m_maxTimeSteps)
return Spectrum(std::numeric_limits<Float>::infinity());
Float maxStepSize = (m_time-r.time) / m_subSteps;
Float timeStepSize = std::min((Float) 1.0f, maxStepSize / (m_time-source[0].time));
timeStepSize *= stepSizeReduction;
/* Compute updated intersection records for time 'm_time' */
adjustTime(rRec, apertureSample, source, target, timeStepSize);
if (timeIteration == 1) {
bool moved = false;
for (size_t i=0; i<source.size(); ++i)
if ((source[i].p-target[i].p).length() > 1e-4f)
moved = true;
if (!moved)
return Spectrum(0.0f);
if (m_derivativesOnly) {
p1 = extrapolateTimePoint(source, target);
break;
} else {
statsConverged.incrementBase();
}
}
if (!timeStep(rRec, source, target, temp, temp2)) {
stepSizeReduction *= 0.5f;
} else {
p1 = source[1].p;
stepSizeReduction = std::min((Float) 1.0f, stepSizeReduction * 2);
if (std::abs(source[0].time-m_time) < 1e-5f) {
++statsConverged;
break;
}
}
}
}
const Sensor *sensor = rRec.scene->getSensor();
DirectSamplingRecord dRec0(p0, r.time), dRec1(p1, m_time);
sensor->sampleDirect(dRec0, apertureSample);
sensor->sampleDirect(dRec1, apertureSample);
/* Step 4: Compute depth difference */
Float dDelta = dRec1.dist - dRec0.dist;
Spectrum result(0.0f);
result.fromLinearRGB(dRec1.uv.x-dRec0.uv.x,
dRec1.uv.y-dRec0.uv.y,
std::isfinite(dDelta) ? dDelta : (Float) 0);
return result;
}
bool timeStep(RadianceQueryRecord &rRec, std::vector<Intersection> &source, const std::vector<Intersection> &target, std::vector<Intersection> &temp, std::vector<Intersection> &temp2) const {
Ray ray = extrapolateTimeRay(source, target);
if (!tracePath(rRec, ray, temp))
return false;
Float error = computeError(temp, target);
Float spaceStepSize = 1.0f;
int spaceIteration = 0;
while (error > 1e-5f) {
++spaceIteration;
if (spaceIteration > m_maxSpaceSteps) {
return false;
}
Ray candidateRay = extrapolateSpaceRay(temp, target, spaceStepSize);
Float candidateError = 0;
if (!tracePath(rRec, candidateRay, temp2))
candidateError = std::numeric_limits<Float>::infinity();
else
candidateError = computeError(temp2, target);
if (candidateError < error) {
temp = temp2;
error = candidateError;
spaceStepSize = std::min((Float) 1.0f, spaceStepSize * 2);
} else {
spaceStepSize *= 0.5f;
}
}
source = temp;
return true;
}
bool tracePath(RadianceQueryRecord &rRec, Ray ray, std::vector<Intersection> &intersections) const {
int depth = 0;
Intersection its;
memset(&its, 0, sizeof(Intersection));
its.p = ray.o;
its.time = ray.time;
intersections.clear();
intersections.push_back(its);
while (depth < (int) m_config.size()) {
rRec.scene->rayIntersect(ray, its);
char interactionType = m_config[depth++];
if (interactionType == 'd') {
if (!its.isValid()) {
BSphere sphere = rRec.scene->getBSphere();
Float nearT, farT;
sphere.radius *= 1000;
bool success = sphere.rayIntersect(ray, nearT, farT);
Assert(success && nearT < 0 && farT > 0);
its.p = ray(farT);
its.geoFrame = its.shFrame = Frame(-ray.d);
its.dpdu = its.geoFrame.s;
its.dpdv = its.geoFrame.t;
its.time = ray.time;
its.uv = Point2(0.0f);
its.shape = its.instance = NULL;
}
if (its.isValid() && !(its.shape->getBSDF()->getType() & BSDF::EDiffuseReflection) && !its.isEmitter())
return false;
intersections.push_back(its);
break;
}
if (!its.isValid())
return false;
intersections.push_back(its);
/* Sample BSDF * cos(theta) */
const BSDF *bsdf = its.shape->getBSDF();
BSDFSamplingRecord bRec(its, rRec.sampler, ERadiance);
if (interactionType == 'r') {
if (bsdf->getType() & BSDF::EDeltaReflection) {
bRec.typeMask = BSDF::EDeltaReflection;
} else if (bsdf->getType() & BSDF::EGlossyReflection) {
for (int i=0; i<bsdf->getComponentCount(); ++i)
if ((bsdf->getType(i) & BSDF::EGlossyReflection) && bsdf->getRoughness(its, i) < m_glossyThreshold)
bRec.typeMask = BSDF::EGlossyReflection;
}
} else if (interactionType == 't') {
if (bsdf->getType() & BSDF::EDeltaTransmission) {
bRec.typeMask = BSDF::EDeltaTransmission;
} else if (bsdf->getType() & BSDF::EGlossyTransmission) {
for (int i=0; i<bsdf->getComponentCount(); ++i)
if ((bsdf->getType(i) & BSDF::EGlossyTransmission) && bsdf->getRoughness(its, i) < m_glossyThreshold)
bRec.typeMask = BSDF::EGlossyTransmission;
}
}
if (bRec.typeMask == BSDF::EAll)
return false;
Spectrum bsdfWeight = bsdf->sample(bRec, Point2(0.0f));
if (bsdfWeight.isZero())
return false;
const Vector wo = its.toWorld(bRec.wo);
ray = Ray(its.p, wo, ray.time);
}
return true;
}
void adjustTime(const RadianceQueryRecord &rRec, const Point2 &apertureSample, const std::vector<Intersection> &source, std::vector<Intersection> &target, Float timeStepSize) const {
target = source;
Float targetTime = (1-timeStepSize) * source[0].time + timeStepSize * m_time;
const Sensor *sensor = rRec.scene->getSensor();
DirectSamplingRecord dRec0(Point(0.0f), source[0].time),
dRec1(Point(0.0f), targetTime);
sensor->sampleDirect(dRec0, apertureSample);
sensor->sampleDirect(dRec1, apertureSample);
Assert((source[0].p-dRec0.p).lengthSquared() < 1e-6);
target[0].p = dRec1.p;
target[0].time = targetTime;
for (size_t i=1; i<target.size(); ++i)
target[i].adjustTime(targetTime);
}
DVector getVertexPosition(const std::vector<Intersection> &source, const std::vector<Intersection> &target, int i, int rel) const {
DScalar u(rel*2, 0), v(rel*2+1, 0), time(6, 0);
return DScalar::vector(source[i].p)
+ DScalar::vector(source[i].dpdu) * u
+ DScalar::vector(source[i].dpdv) * v
+ DScalar::vector(target[i].p-source[i].p) * time;
}
void getVertexFrame(const std::vector<Intersection> &source, const std::vector<Intersection> &target, int i, DVector &s, DVector &t, DVector &n) const {
DScalar u(2, 0), v(3, 0), time(6, 0);
const BSDF *bsdf = source[i].shape->getBSDF();
Frame frame, du, dv;
frame = bsdf->getFrame(source[i]);
bsdf->getFrameDerivative(source[i], du, dv);
DVector n0 = DScalar::vector(frame.n)
+ DScalar::vector(du.n) * u
+ DScalar::vector(dv.n) * v;
DVector s0 = DScalar::vector(frame.s)
+ DScalar::vector(du.s) * u
+ DScalar::vector(dv.s) * v;
DVector t0 = DScalar::vector(frame.t)
+ DScalar::vector(du.t) * u
+ DScalar::vector(dv.t) * v;
frame = bsdf->getFrame(target[i]);
bsdf->getFrameDerivative(target[i], du, dv);
DVector n1 = DScalar::vector(frame.n)
+ DScalar::vector(du.n) * u
+ DScalar::vector(dv.n) * v;
DVector s1 = DScalar::vector(frame.s)
+ DScalar::vector(du.s) * u
+ DScalar::vector(dv.s) * v;
DVector t1 = DScalar::vector(frame.t)
+ DScalar::vector(du.t) * u
+ DScalar::vector(dv.t) * v;
n = (1-time)*n0 + time*n1;
s = (1-time)*s0 + time*s1;
t = (1-time)*t0 + time*t1;
}
void assembleMatrix(const std::vector<Intersection> &source, const std::vector<Intersection> &target, EMatrix &M) const {
DScalar::setVariableCount(7);
M.resize(2*(source.size()-2), 2*source.size()+1);
M.setZero();
for (int i=1; i < (int) source.size()-1; ++i) {
DVector p_pred = getVertexPosition(source, target, i-1, 0);
DVector p_cur = getVertexPosition(source, target, i, 1);
DVector p_succ = getVertexPosition(source, target, i+1, 2);
DVector s, t, n;
getVertexFrame(source, target, i, s, t, n);
DVector wi = p_pred - p_cur, wo = p_succ - p_cur;
wi *= inverse(sqrt(wi.dot(wi)));
wo *= inverse(sqrt(wo.dot(wo)));
Float eta = source[i].shape->getBSDF()->getEta();
if (m_config[i-1] == 'r')
eta = 1;
else if (wi.dot(n).getValue() < 0)
eta = 1/eta;
DVector H = wi + wo * DScalar(eta);
H *= inverse(sqrt(H.dot(H)));
Gradient H_s = H.dot(s).getGradient(),
H_t = H.dot(t).getGradient();
M.block<1, 6>((i-1)*2+0, (i-1)*2) = H_s.segment<6>(0);
M.block<1, 6>((i-1)*2+1, (i-1)*2) = H_t.segment<6>(0);
M((i-1)*2+0, M.cols()-1) = H_s(6);
M((i-1)*2+1, M.cols()-1) = H_t(6);
}
}
Point extrapolateTimePoint(const std::vector<Intersection> &source, const std::vector<Intersection> &target) const {
EMatrix M;
assembleMatrix(source, target, M);
EVector b = -M.block(0, 2, (source.size()-2)*2, (source.size()-2)*2).lu().solve(M.col(M.cols()-1));
return target[1].p + target[1].dpdu * b[0] + target[1].dpdv * b[1];
}
Ray extrapolateTimeRay(const std::vector<Intersection> &source, const std::vector<Intersection> &target) const {
EMatrix M;
assembleMatrix(source, target, M);
EVector b = -M.block(0, 2, (source.size()-2)*2, (source.size()-2)*2).lu().solve(M.col(M.cols()-1));
Point rayOrigin = target[0].p;
Point rayTarget = target[1].p + target[1].dpdu * b[0] + target[1].dpdv * b[1];
return Ray(rayOrigin, normalize(rayTarget-rayOrigin), target[1].time);
}
Float computeError(const std::vector<Intersection> &source, const std::vector<Intersection> &target) const {
int last = source.size()-1;
Float scale = std::max(Epsilon,std::max(std::abs(target[last].p.x), std::max(std::abs(target[last].p.y), std::abs(target[last].p.z))));
return (target[last].p-source[last].p).length() / scale;
}
Ray extrapolateSpaceRay(const std::vector<Intersection> &source, const std::vector<Intersection> &target, Float stepSize) const {
EMatrix M;
assembleMatrix(source, target, M);
Eigen::PartialPivLU<EMatrix> lu = M.block(0, 2, (source.size()-2)*2, (source.size()-2)*2).lu();
int last = source.size()-1;
Vector rel = target[last].p-source[last].p,
dpdu = source[last].dpdu,
dpdv = source[last].dpdv;
Float b1 = dot(rel, dpdu),
b2 = dot(rel, dpdv),
a11 = dot(dpdu, dpdu), a12 = dot(dpdu, dpdv),
a22 = dot(dpdv, dpdv),
det = a11 * a22 - a12 * a12;
Float invDet = 1.0f / det,
du = ( a22 * b1 - a12 * b2) * invDet,
dv = (-a12 * b1 + a11 * b2) * invDet;
EVector b = -(du*lu.solve(M.col(M.cols()-3)) + dv*lu.solve(M.col(M.cols()-2)));
Point rayTarget = source[1].p + stepSize * (source[1].dpdu * b[0] + source[1].dpdv * b[1]);
return Ray(source[0].p, normalize(rayTarget-source[0].p), source[1].time);
}
std::string toString() const {
return "MotionIntegrator[]";
}
MTS_DECLARE_CLASS()
private:
Float m_time;
std::string m_config;
bool m_derivativesOnly;
int m_maxSpaceSteps;
int m_maxTimeSteps;
int m_subSteps;
Float m_glossyThreshold;
mutable const Scene *m_scene;
};
MTS_IMPLEMENT_CLASS_S(MotionIntegrator, false, SamplingIntegrator)
MTS_EXPORT_PLUGIN(MotionIntegrator, " motion vector integrator");
MTS_NAMESPACE_END