Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Transform.cc « math « openvdb « internal « openvdb « extern - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c0b45710476c1001d3b0bcb4dc11e0e39cb85f98 (plain)
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
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2013 DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// *     Neither the name of DreamWorks Animation nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////

#include "Transform.h"
#include "LegacyFrustum.h"

#include <openvdb/version.h>
#include <sstream>
#include <string>
#include <vector>

namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace math {


////////////////////////////////////////


Transform::Transform(const MapBase::Ptr& map):
    mMap(boost::const_pointer_cast</*to=*/MapBase, /*from=*/const MapBase>(map))
{
    // auto-convert to simplest type
    if (!mMap->isType<UniformScaleMap>() && mMap->isLinear()) {
        AffineMap::Ptr affine = mMap->getAffineMap();
        mMap = simplify(affine);
    }
}

Transform::Transform(const Transform& other):
    mMap(boost::const_pointer_cast</*to=*/MapBase, /*from=*/const MapBase>(other.baseMap()))
{
}


////////////////////////////////////////


// Factory methods

Transform::Ptr
Transform::createLinearTransform(double voxelDim)
{
    return Transform::Ptr(new Transform(
        MapBase::Ptr(new UniformScaleMap(voxelDim))));
}

Transform::Ptr
Transform::createLinearTransform(const Mat4R& m)
{
    return Transform::Ptr(new Transform(MapBase::Ptr(new AffineMap(m))));
}

Transform::Ptr
Transform::createFrustumTransform(const BBoxd& bbox, double taper,
    double depth, double voxelDim)
{
    return Transform::Ptr(new  Transform(
        NonlinearFrustumMap(bbox, taper, depth).preScale(Vec3d(voxelDim, voxelDim, voxelDim))));
}


////////////////////////////////////////


void
Transform::read(std::istream& is)
{
    // Read the type name.
    Name type = readString(is);

    if (io::getFormatVersion(is) < OPENVDB_FILE_VERSION_NEW_TRANSFORM) {
        // Handle old-style transforms.

        if(type == "LinearTransform") {
            // First read in the old transform's base class.
            Coord tmpMin, tmpMax;
            is.read(reinterpret_cast<char*>(&tmpMin), sizeof(Coord::ValueType) * 3);
            is.read(reinterpret_cast<char*>(&tmpMax), sizeof(Coord::ValueType) * 3);

            // Second read in the old linear transform
            Mat4d tmpLocalToWorld, tmpWorldToLocal, tmpVoxelToLocal, tmpLocalToVoxel;

            tmpLocalToWorld.read(is);
            tmpWorldToLocal.read(is);
            tmpVoxelToLocal.read(is);
            tmpLocalToVoxel.read(is);

            // Convert and simplify
            AffineMap::Ptr affineMap(new AffineMap(tmpVoxelToLocal*tmpLocalToWorld));
            mMap = simplify(affineMap);

        } else if (type == "FrustumTransform") {

            internal::LegacyFrustum legacyFrustum(is);

            CoordBBox bb      = legacyFrustum.getBBox();
            BBoxd   bbox(bb.min().asVec3d(), bb.max().asVec3d());
            double  taper     = legacyFrustum.getTaper();
            double  depth     = legacyFrustum.getDepth();

            double nearPlaneWidth = legacyFrustum.getNearPlaneWidth();
            double nearPlaneDist  = legacyFrustum.getNearPlaneDist();
            Mat4d camxform        = legacyFrustum.getCamXForm();

            // create the new frustum with these parameters
            Mat4d xform(Mat4d::identity());
            xform.setToTranslation(Vec3d(0,0, -nearPlaneDist));
            xform.preScale(Vec3d(nearPlaneWidth, nearPlaneWidth, -nearPlaneWidth));

            MapBase::Ptr linearMap(simplify(AffineMap(xform * camxform).getAffineMap()));

            // note that the depth is scaled on the nearPlaneSize.
            // the linearMap will uniformly scale the frustum to the correct size
            // and rotate to align with the camera
            mMap = MapBase::Ptr(new NonlinearFrustumMap(
                bbox, taper, depth/nearPlaneWidth, linearMap));


        } else {
            OPENVDB_THROW(IoError, "Transforms of type " + type + " are no longer supported");
        }
    } else {
        // Check if the map has been registered.
        if (!MapRegistry::instance()->isRegistered(type)) {
            OPENVDB_THROW(KeyError, "Map " << type << " is not registered");
        }

        // Create the map of the type and then read it in.
        mMap = math::MapRegistry::instance()->createMap(type);
        mMap->read(is);
    }
}


void
Transform::write(std::ostream& os) const
{
    if (!mMap) OPENVDB_THROW(IoError, "Transform does not have a map");

    // Write the type-name of the map.
    writeString(os, mMap->type());

    mMap->write(os);
}


////////////////////////////////////////

bool
Transform::isIdentity() const 
{
    if (mMap->isLinear()) {
        return mMap->getAffineMap()->isIdentity();
    } else if ( mMap->isType<NonlinearFrustumMap>() ) {
        NonlinearFrustumMap::Ptr frustum 
            = boost::static_pointer_cast<NonlinearFrustumMap, MapBase>(mMap);
        return frustum->isIdentity();
    }
    // unknown nonlinear map type
    return false;
}

void
Transform::preRotate(double radians, const Axis axis)
{
   mMap = mMap->preRotate(radians, axis);
}

void
Transform::preTranslate(const Vec3d& t)
{
    mMap = mMap->preTranslate(t);
}

void
Transform::preScale(const Vec3d& s)
{
    mMap = mMap->preScale(s);
}

void
Transform::preScale(double s)
{
    const Vec3d vec(s,s,s);
    mMap = mMap->preScale(vec);
}

void
Transform::preShear(double shear, Axis axis0, Axis axis1)
{
    mMap = mMap->preShear(shear, axis0, axis1);
}

void
Transform::preMult(const Mat4d& m)
{   
    if (mMap->isLinear()) {

        const Mat4d currentMat4 = mMap->getAffineMap()->getMat4();
        const Mat4d newMat4 = m * currentMat4;
                
        AffineMap::Ptr affineMap( new AffineMap( newMat4) );
        mMap = simplify(affineMap);

    } else if (mMap->isType<NonlinearFrustumMap>() ) {
        
        NonlinearFrustumMap::Ptr currentFrustum =  
            boost::static_pointer_cast<NonlinearFrustumMap, MapBase>(mMap);
        
        const Mat4d currentMat4 = currentFrustum->secondMap().getMat4();
        const Mat4d newMat4 = m * currentMat4;

        AffineMap affine(newMat4);
        
        NonlinearFrustumMap::Ptr frustum( new NonlinearFrustumMap( currentFrustum->getBBox(),
                                                                   currentFrustum->getTaper(),
                                                                   currentFrustum->getDepth(),
                                                                   affine.copy() ) );
        mMap = boost::static_pointer_cast<MapBase, NonlinearFrustumMap>( frustum );
    }
        
}    

void
Transform::preMult(const Mat3d& m)
{
    Mat4d mat4 = Mat4d::identity();
    mat4.setMat3(m);
    preMult(mat4);
}

void
Transform::postRotate(double radians, const Axis axis)
{
   mMap = mMap->postRotate(radians, axis);
}

void
Transform::postTranslate(const Vec3d& t)
{
    mMap = mMap->postTranslate(t);
}

void
Transform::postScale(const Vec3d& s)
{
    mMap = mMap->postScale(s);
}

void
Transform::postScale(double s)
{
    const Vec3d vec(s,s,s);
    mMap = mMap->postScale(vec);
}

void
Transform::postShear(double shear, Axis axis0, Axis axis1)
{
    mMap = mMap->postShear(shear, axis0, axis1);
}


void
Transform::postMult(const Mat4d& m)
{   
    if (mMap->isLinear()) {

        const Mat4d currentMat4 = mMap->getAffineMap()->getMat4();
        const Mat4d newMat4 = currentMat4 * m;
                
        AffineMap::Ptr affineMap( new AffineMap( newMat4) );
        mMap = simplify(affineMap);

    } else if (mMap->isType<NonlinearFrustumMap>() ) {
        
        NonlinearFrustumMap::Ptr currentFrustum =  
            boost::static_pointer_cast<NonlinearFrustumMap, MapBase>(mMap);
        
        const Mat4d currentMat4 = currentFrustum->secondMap().getMat4();
        const Mat4d newMat4 =  currentMat4 * m;

        AffineMap affine(newMat4);
        
        NonlinearFrustumMap::Ptr frustum( new NonlinearFrustumMap( currentFrustum->getBBox(),
                                                                   currentFrustum->getTaper(),
                                                                   currentFrustum->getDepth(),
                                                                   affine.copy() ) );
        mMap = boost::static_pointer_cast<MapBase, NonlinearFrustumMap>( frustum );
    }
        
}    

void
Transform::postMult(const Mat3d& m)
{
    Mat4d mat4 = Mat4d::identity();
    mat4.setMat3(m);
    postMult(mat4);
}


////////////////////////////////////////

// Utility methods

void
calculateBounds(const Transform& t,
                const Vec3d& minWS,
                const Vec3d& maxWS,
                Vec3d& minIS,
                Vec3d& maxIS)
{
    /// the pre-image of the 8 corners of the box
    Vec3d corners[8];
    corners[0] = minWS;
    corners[1] = Vec3d(maxWS(0), minWS(1), minWS(2));
    corners[2] = Vec3d(maxWS(0), maxWS(1), minWS(2));
    corners[3] = Vec3d(minWS(0), maxWS(1), minWS(2));
    corners[4] = Vec3d(minWS(0), minWS(1), maxWS(2));
    corners[5] = Vec3d(maxWS(0), minWS(1), maxWS(2));
    corners[6] = maxWS;
    corners[7] = Vec3d(minWS(0), maxWS(1), maxWS(2));

    Vec3d pre_image;
    minIS = t.worldToIndex(corners[0]);
    maxIS = minIS;
    for (int i = 1; i < 8; ++i) {
        pre_image = t.worldToIndex(corners[i]);
        for (int j = 0; j < 3; ++j) {
            minIS(j) = std::min(minIS(j), pre_image(j));
            maxIS(j) = std::max(maxIS(j), pre_image(j));
        }
    }
}


////////////////////////////////////////


bool
Transform::operator==(const Transform& other) const
{
    if (!this->voxelSize().eq(other.voxelSize())) return false;

    if (this->mapType() == other.mapType()) {
        return this->baseMap()->isEqual(*other.baseMap());
    }

    if (this->isLinear() && other.isLinear()) {
        // promote both maps to mat4 form and compare
        return  ( *(this->baseMap()->getAffineMap()) ==
                  *(other.baseMap()->getAffineMap()) );
    }

    return this->baseMap()->isEqual(*other.baseMap());
}


////////////////////////////////////////


void
Transform::print(std::ostream& os, const std::string& indent) const
{
    struct Local {
        // Print a Vec4d more compactly than Vec4d::str() does.
        static std::string rowAsString(const Vec4d& row)
        {
            std::ostringstream ostr;
            ostr << "[" << std::setprecision(3) << row[0] << ", "
                << row[1] << ", " << row[2] << ", " << row[3] << "] ";
            return ostr.str();
        }
    };

    // Write to a string stream so that I/O manipulators don't affect the output stream.
    std::ostringstream ostr;

    {
        Vec3d dim = this->voxelSize();
        if (dim.eq(Vec3d(dim[0]))) {
            ostr << indent << std::left << "voxel size: " << std::setprecision(3) << dim[0];
        } else {
            ostr << indent << std::left << "voxel dimensions: [" << std::setprecision(3)
                << dim[0] << ", " << dim[1] << ", " << dim[2] << "]";
        }
        ostr << "\n";
    }

    if (this->isLinear()) {
        openvdb::Mat4R v2w = this->baseMap()->getAffineMap()->getMat4();

        ostr << indent << std::left << "index to world:\n";
        for (int row = 0; row < 4; ++row) {
            ostr << indent << "   " << std::left << Local::rowAsString(v2w[row]) << "\n";
        }

    } else if (this->mapType() == NonlinearFrustumMap::mapType()) {
        const NonlinearFrustumMap& frustum =
            static_cast<const NonlinearFrustumMap&>(*this->baseMap());
        const openvdb::Mat4R linear = this->baseMap()->getAffineMap()->getMat4();

        std::vector<std::string> linearRow;
        size_t w = 0;
        for (int row = 0; row < 4; ++row) {
            std::string str = Local::rowAsString(linear[row]);
            w = std::max(w, str.size());
            linearRow.push_back(str);
        }
        w = std::max<size_t>(w, 30);

        // Print rows of the linear component matrix side-by-side with frustum parameters.
        ostr << indent << std::left << std::setw(w) << "linear:"
            << "  frustum:\n";
        ostr << indent << "   " << std::left << std::setw(w) << linearRow[0]
            << "  taper:  " << frustum.getTaper() << "\n";
        ostr << indent << "   " << std::left << std::setw(w) << linearRow[1]
            << "  depth:  " << frustum.getDepth() << "\n";

        std::ostringstream ostmp;
        ostmp << indent << "   " << std::left << std::setw(w) << linearRow[2]
            << "  bounds: " << frustum.getBBox();
        if (ostmp.str().size() < 79) {
            ostr << ostmp.str() << "\n";
            ostr << indent << "   " << std::left << std::setw(w) << linearRow[3] << "\n";
        } else {
            // If the frustum bounding box doesn't fit on one line, split it into two lines.
            ostr << indent << "   " << std::left << std::setw(w) << linearRow[2]
                << "  bounds: " << frustum.getBBox().min() << " ->\n";
            ostr << indent << "   " << std::left << std::setw(w) << linearRow[3]
                << "             " << frustum.getBBox().max() << "\n";
        }

    } else {
        /// @todo Handle other map types.
    }

    os << ostr.str();
}


////////////////////////////////////////


std::ostream&
operator<<(std::ostream& os, const Transform& t)
{
    os << "Transform type: " << t.baseMap()->type() << std::endl;
    os << t.baseMap()->str() << std::endl;
    return os;
}


} // namespace math
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb

// Copyright (c) 2012-2013 DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )