PCCTMC3Common.h 31.4 KB
Newer Older
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
1
/* The copyright in this software is being made available under the BSD
David Flynn's avatar
David Flynn committed
2
3
4
 * Licence, included below.  This software may be subject to other third
 * party and contributor rights, including patent rights, and no such
 * rights are granted under this licence.
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
5
 *
David Flynn's avatar
David Flynn committed
6
 * Copyright (c) 2017-2018, ISO/IEC
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
7
8
9
10
11
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
David Flynn's avatar
David Flynn committed
12
13
14
15
16
17
18
19
20
21
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of the ISO/IEC nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
22
23
24
25
 *
 * 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
David Flynn's avatar
David Flynn committed
26
27
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
28
29
30
31
 * 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)
David Flynn's avatar
David Flynn committed
32
33
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
34
35
36
37
 */

#ifndef PCCTMC3Common_h
#define PCCTMC3Common_h
38

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
39
40
#include "PCCKdTree.h"
#include "PCCMath.h"
41
#include "constants.h"
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
42

43
44
#include "nanoflann.hpp"

45
#include <cstdint>
David Flynn's avatar
David Flynn committed
46
#include <cstddef>
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
47
48
49
50
#include <vector>

namespace pcc {

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Structure for sorting weights.
struct WeightWithIndex {
  float weight;
  int index;

  WeightWithIndex() = default;

  WeightWithIndex(const int index, const float weight)
    : weight(weight), index(index)
  {}

  // NB: this definition ranks larger weights before smaller values.
  bool operator<(const WeightWithIndex& rhs) const
  {
    // NB: index used to maintain stable sort
    if (weight == rhs.weight)
      return index < rhs.index;
    return weight > rhs.weight;
  }
};

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//---------------------------------------------------------------------------

struct MortonCodeWithIndex {
  uint64_t mortonCode;
  int32_t index;
  bool operator<(const MortonCodeWithIndex& rhs) const
  {
    // NB: index used to maintain stable sort
    if (mortonCode == rhs.mortonCode)
      return index < rhs.index;
    return mortonCode < rhs.mortonCode;
  }
};

//---------------------------------------------------------------------------

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
88
struct PCCNeighborInfo {
89
  uint64_t weight;
90
  uint32_t predictorIndex;
91
92
93
94
95
  bool operator<(const PCCNeighborInfo& rhs) const
  {
    return (weight == rhs.weight) ? predictorIndex < rhs.predictorIndex
                                  : weight < rhs.weight;
  }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
96
97
};

98
99
//---------------------------------------------------------------------------

Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
100
struct PCCPredictor {
101
  uint32_t neighborCount;
102
  PCCNeighborInfo neighbors[kAttributePredictionMaxNeighbourCount];
103
  int8_t predMode;
104
  int64_t maxDiff;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
105

106
  Vec3<uint8_t> predictColor(
107
    const PCCPointSet3& pointCloud, const std::vector<uint32_t>& indexes) const
108
  {
109
    Vec3<int64_t> predicted(0);
110
111
112
    if (predMode > neighborCount) {
      /* nop */
    } else if (predMode > 0) {
113
      const Vec3<uint8_t> color =
114
        pointCloud.getColor(indexes[neighbors[predMode - 1].predictorIndex]);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
115
      for (size_t k = 0; k < 3; ++k) {
116
117
118
119
        predicted[k] += color[k];
      }
    } else {
      for (size_t i = 0; i < neighborCount; ++i) {
120
        const Vec3<uint8_t> color =
121
          pointCloud.getColor(indexes[neighbors[i].predictorIndex]);
122
        const uint32_t w = neighbors[i].weight;
123
124
125
        for (size_t k = 0; k < 3; ++k) {
          predicted[k] += w * color[k];
        }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
126
      }
127
128
129
130
      for (uint32_t k = 0; k < 3; ++k) {
        predicted[k] =
          divExp2RoundHalfInf(predicted[k], kFixedPointWeightShift);
      }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
131
    }
132
    return Vec3<uint8_t>(predicted[0], predicted[1], predicted[2]);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
133
  }
134

135
  int64_t predictReflectance(
136
    const PCCPointSet3& pointCloud, const std::vector<uint32_t>& indexes) const
137
  {
138
    int64_t predicted(0);
139
140
141
    if (predMode > neighborCount) {
      /* nop */
    } else if (predMode > 0) {
142
143
      predicted = pointCloud.getReflectance(
        indexes[neighbors[predMode - 1].predictorIndex]);
144
145
    } else {
      for (size_t i = 0; i < neighborCount; ++i) {
146
147
        predicted += neighbors[i].weight
          * pointCloud.getReflectance(indexes[neighbors[i].predictorIndex]);
148
      }
149
      predicted = divExp2RoundHalfInf(predicted, kFixedPointWeightShift);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
150
    }
151
    return predicted;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
152
153
  }

154
  void computeWeights()
155
  {
156
157
158
159
160
161
162
163
164
    const uint32_t shift = (1 << kFixedPointWeightShift);
    int32_t n = 0;
    while ((neighbors[0].weight >> n) >= shift) {
      ++n;
    }
    if (n > 0) {
      for (size_t i = 0; i < neighborCount; ++i) {
        neighbors[i].weight = (neighbors[i].weight + (1 << (n - 1))) >> n;
      }
165
    }
166
167
168
169
170
171
172
173
    while (neighborCount > 1) {
      if (
        neighbors[neighborCount - 1].weight
        >= (neighbors[neighborCount - 2].weight << kFixedPointWeightShift)) {
        --neighborCount;
      } else {
        break;
      }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
174
    }
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    if (neighborCount <= 1) {
      neighbors[0].weight = shift;
    } else if (neighborCount == 2) {
      const uint64_t d0 = neighbors[0].weight;
      const uint64_t d1 = neighbors[1].weight;
      const uint64_t sum = d1 + d0;
      const uint64_t w1 = (d0 << kFixedPointWeightShift) / sum;
      const uint64_t w0 = shift - w1;
      neighbors[0].weight = uint32_t(w0);
      neighbors[1].weight = uint32_t(w1);
    } else {
      neighborCount = 3;
      const uint64_t d0 = neighbors[0].weight;
      const uint64_t d1 = neighbors[1].weight;
      const uint64_t d2 = neighbors[2].weight;
      const uint64_t sum = d1 * d2 + d0 * d2 + d0 * d1;
      const uint64_t w2 = ((d0 * d1) << kFixedPointWeightShift) / sum;
      const uint64_t w1 = ((d0 * d2) << kFixedPointWeightShift) / sum;
      const uint64_t w0 = shift - (w1 + w2);
      neighbors[0].weight = uint32_t(w0);
      neighbors[1].weight = uint32_t(w1);
      neighbors[2].weight = uint32_t(w2);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
197
198
199
    }
  }

200
  void init(const uint32_t predictorIndex)
201
  {
202
    neighborCount = (predictorIndex != PCC_UNDEFINED_INDEX) ? 1 : 0;
203
    neighbors[0].predictorIndex = predictorIndex;
204
    neighbors[0].weight = 1;
205
    predMode = 0;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
206
  }
207
208
209
210
211

  void init() { neighborCount = 0; }

  void insertNeighbor(
    const uint32_t reference,
212
    const uint64_t weight,
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
    const uint32_t maxNeighborCount)
  {
    bool sort = false;
    assert(
      maxNeighborCount > 0
      && maxNeighborCount <= kAttributePredictionMaxNeighbourCount);
    if (neighborCount < maxNeighborCount) {
      PCCNeighborInfo& neighborInfo = neighbors[neighborCount];
      neighborInfo.weight = weight;
      neighborInfo.predictorIndex = reference;
      ++neighborCount;
      sort = true;
    } else {
      PCCNeighborInfo& neighborInfo = neighbors[maxNeighborCount - 1];
      if (weight < neighborInfo.weight) {
        neighborInfo.weight = weight;
        neighborInfo.predictorIndex = reference;
        sort = true;
      }
    }
    for (int32_t k = neighborCount - 1; k > 0 && sort; --k) {
      if (neighbors[k] < neighbors[k - 1])
        std::swap(neighbors[k], neighbors[k - 1]);
      else
        return;
    }
  }
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
240
};
241
242
243

//---------------------------------------------------------------------------

244
inline int64_t
245
PCCQuantization(const int64_t value, const int64_t qs, bool isup = false)
246
{
247
  const int64_t shift = (qs / 3);
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
248
249
250
  if (!qs) {
    return value;
  }
251
252
253
254
255
256
  if (isup) {
    if (value >= 0) {
      return ((value << kFixedPointAttributeShift) + shift) / qs;
    }
    return -((shift - (value << kFixedPointAttributeShift)) / qs);
  } else if (value >= 0) {
257
    return (value + shift) / qs;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
258
  }
259
260
261
  return -((shift - value) / qs);
}

262
inline int64_t
263
264
PCCInverseQuantization(
  const int64_t value, const int64_t qs, bool isdown = false)
265
{
266
267
268
269
270
271
272
273
  if (!qs)
    return value;

  if (isdown) {
    const int offset = 1 << (kFixedPointAttributeShift - 1);
    return (value * qs + offset) >> kFixedPointAttributeShift;
  }
  return value * qs;
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
274
}
275

276
277
278
279
280
281
282
283
284
//---------------------------------------------------------------------------

inline void
PCCLiftPredict(
  const std::vector<PCCPredictor>& predictors,
  const size_t startIndex,
  const size_t endIndex,
  const bool direct,
  std::vector<Vec3<int64_t>>& attributes)
285
{
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
  const size_t predictorCount = endIndex - startIndex;
  for (size_t index = 0; index < predictorCount; ++index) {
    const size_t predictorIndex = predictorCount - index - 1 + startIndex;
    const auto& predictor = predictors[predictorIndex];
    auto& attribute = attributes[predictorIndex];
    Vec3<int64_t> predicted(int64_t(0));
    for (size_t i = 0; i < predictor.neighborCount; ++i) {
      const size_t neighborPredIndex = predictor.neighbors[i].predictorIndex;
      const uint32_t weight = predictor.neighbors[i].weight;
      assert(neighborPredIndex < startIndex);
      predicted += weight * attributes[neighborPredIndex];
    }
    predicted = divExp2RoundHalfInf(predicted, kFixedPointWeightShift);
    if (direct) {
      attribute -= predicted;
    } else {
      attribute += predicted;
    }
  }
305
306
}

307
inline void
308
309
310
311
312
PCCLiftPredict(
  const std::vector<PCCPredictor>& predictors,
  const size_t startIndex,
  const size_t endIndex,
  const bool direct,
313
  std::vector<int64_t>& attributes)
314
315
316
317
318
{
  const size_t predictorCount = endIndex - startIndex;
  for (size_t index = 0; index < predictorCount; ++index) {
    const size_t predictorIndex = predictorCount - index - 1 + startIndex;
    const auto& predictor = predictors[predictorIndex];
319
320
    auto& attribute = attributes[predictorIndex];
    int64_t predicted(int64_t(0));
321
322
    for (size_t i = 0; i < predictor.neighborCount; ++i) {
      const size_t neighborPredIndex = predictor.neighbors[i].predictorIndex;
323
      const uint32_t weight = predictor.neighbors[i].weight;
324
325
326
      assert(neighborPredIndex < startIndex);
      predicted += weight * attributes[neighborPredIndex];
    }
327
    predicted = divExp2RoundHalfInf(predicted, kFixedPointWeightShift);
328
    if (direct) {
329
      attribute -= predicted;
330
    } else {
331
      attribute += predicted;
332
333
334
335
336
337
    }
  }
}

//---------------------------------------------------------------------------

338
inline void
339
340
PCCLiftUpdate(
  const std::vector<PCCPredictor>& predictors,
341
  const std::vector<uint64_t>& quantizationWeights,
342
343
344
  const size_t startIndex,
  const size_t endIndex,
  const bool direct,
345
  std::vector<Vec3<int64_t>>& attributes)
346
{
347
348
349
  std::vector<uint64_t> updateWeights;
  updateWeights.resize(startIndex, uint64_t(0));
  std::vector<Vec3<int64_t>> updates;
350
351
  updates.resize(startIndex);
  for (size_t index = 0; index < startIndex; ++index) {
352
    updates[index] = int64_t(0);
353
354
355
356
357
  }
  const size_t predictorCount = endIndex - startIndex;
  for (size_t index = 0; index < predictorCount; ++index) {
    const size_t predictorIndex = predictorCount - index - 1 + startIndex;
    const auto& predictor = predictors[predictorIndex];
358
    const auto currentQuantWeight = quantizationWeights[predictorIndex];
359
360
    for (size_t i = 0; i < predictor.neighborCount; ++i) {
      const size_t neighborPredIndex = predictor.neighbors[i].predictorIndex;
361
362
      const uint64_t weight =
        predictor.neighbors[i].weight * currentQuantWeight;
363
364
365
366
367
368
369
      assert(neighborPredIndex < startIndex);
      updateWeights[neighborPredIndex] += weight;
      updates[neighborPredIndex] += weight * attributes[predictorIndex];
    }
  }
  for (size_t predictorIndex = 0; predictorIndex < startIndex;
       ++predictorIndex) {
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
    const uint32_t sumWeights = updateWeights[predictorIndex];
    if (sumWeights) {
      auto& update = updates[predictorIndex];
      update = (update + sumWeights / 2) / sumWeights;
      auto& attribute = attributes[predictorIndex];
      if (direct) {
        attribute += update;
      } else {
        attribute -= update;
      }
    }
  }
}

inline void
PCCLiftUpdate(
  const std::vector<PCCPredictor>& predictors,
  const std::vector<uint64_t>& quantizationWeights,
  const size_t startIndex,
  const size_t endIndex,
  const bool direct,
  std::vector<int64_t>& attributes)
{
  std::vector<uint64_t> updateWeights;
  updateWeights.resize(startIndex, uint64_t(0));
  std::vector<int64_t> updates;
  updates.resize(startIndex);
  for (size_t index = 0; index < startIndex; ++index) {
    updates[index] = int64_t(0);
  }
  const size_t predictorCount = endIndex - startIndex;
  for (size_t index = 0; index < predictorCount; ++index) {
    const size_t predictorIndex = predictorCount - index - 1 + startIndex;
    const auto& predictor = predictors[predictorIndex];
    const auto currentQuantWeight = quantizationWeights[predictorIndex];
    for (size_t i = 0; i < predictor.neighborCount; ++i) {
      const size_t neighborPredIndex = predictor.neighbors[i].predictorIndex;
      const uint64_t weight =
        predictor.neighbors[i].weight * currentQuantWeight;
      assert(neighborPredIndex < startIndex);
      updateWeights[neighborPredIndex] += weight;
      updates[neighborPredIndex] += weight * attributes[predictorIndex];
    }
  }
  for (size_t predictorIndex = 0; predictorIndex < startIndex;
       ++predictorIndex) {
    const uint32_t sumWeights = updateWeights[predictorIndex];
417
    if (sumWeights > 0.0) {
418
419
420
      auto& update = updates[predictorIndex];
      update = (update + sumWeights / 2) / sumWeights;
      auto& attribute = attributes[predictorIndex];
421
      if (direct) {
422
        attribute += update;
423
      } else {
424
        attribute -= update;
425
426
427
428
429
430
431
432
433
434
      }
    }
  }
}

//---------------------------------------------------------------------------

inline void
PCCComputeQuantizationWeights(
  const std::vector<PCCPredictor>& predictors,
435
  std::vector<uint64_t>& quantizationWeights)
436
437
438
439
{
  const size_t pointCount = predictors.size();
  quantizationWeights.resize(pointCount);
  for (size_t i = 0; i < pointCount; ++i) {
440
    quantizationWeights[i] = (1 << kFixedPointWeightShift);
441
442
443
444
  }
  for (size_t i = 0; i < pointCount; ++i) {
    const size_t predictorIndex = pointCount - i - 1;
    const auto& predictor = predictors[predictorIndex];
445
446
447
448
449
450
451
    const auto currentQuantWeight = quantizationWeights[predictorIndex];
    for (size_t j = 0; j < predictor.neighborCount; ++j) {
      const size_t neighborPredIndex = predictor.neighbors[j].predictorIndex;
      const auto weight = predictor.neighbors[j].weight;
      auto& neighborQuantWeight = quantizationWeights[neighborPredIndex];
      neighborQuantWeight += divExp2RoundHalfInf(
        weight * currentQuantWeight, kFixedPointWeightShift);
452
453
    }
  }
454
455
456
  for (auto& w : quantizationWeights) {
    w = isqrt(w);
  }
457
458
459
460
}

//---------------------------------------------------------------------------

461
462
inline uint32_t
FindNeighborWithinDistance(
463
  const PCCPointSet3& pointCloud,
464
  const std::vector<MortonCodeWithIndex>& packedVoxel,
465
466
  const int32_t index,
  const double radius2,
467
468
  const int32_t searchRange,
  std::vector<uint32_t>& retained)
469
{
470
471
472
473
474
475
476
477
478
479
480
481
482
  const auto& point = pointCloud[packedVoxel[index].index];
  const int32_t retainedSize = retained.size();
  int32_t j = retainedSize - 2;
  int32_t k = 0;
  while (j >= 0 && ++k < searchRange) {
    const int32_t index1 = retained[j];
    const int32_t pointIndex1 = packedVoxel[index1].index;
    const auto& point1 = pointCloud[pointIndex1];
    const auto d2 = (point1 - point).getNorm2();
    if (d2 <= radius2) {
      return index1;
    }
    --j;
483
  }
484
485
  return PCC_UNDEFINED_INDEX;
}
486

487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//---------------------------------------------------------------------------

inline void
computeNearestNeighbors(
  const PCCPointSet3& pointCloud,
  const std::vector<MortonCodeWithIndex>& packedVoxel,
  const std::vector<uint32_t>& retained,
  const int32_t startIndex,
  const int32_t endIndex,
  const int32_t searchRange,
  const int32_t numberOfNearestNeighborsInPrediction,
  std::vector<uint32_t>& indexes,
  std::vector<PCCPredictor>& predictors,
  std::vector<uint32_t>& pointIndexToPredictorIndex,
  int32_t& predIndex,
502
  std::vector<Box3<double>>& bBoxes)
503
504
505
506
507
508
509
510
511
512
513
514
515
{
  const int32_t retainedSize = retained.size();
  const int32_t bucketSize = 8;
  bBoxes.resize((retainedSize + bucketSize - 1) / bucketSize);
  for (int32_t i = 0, b = 0; i < retainedSize; ++b) {
    auto& bBox = bBoxes[b];
    bBox.min = bBox.max = pointCloud[packedVoxel[retained[i++]].index];
    for (int32_t k = 1; k < bucketSize && i < retainedSize; ++k, ++i) {
      const int32_t pointIndex = packedVoxel[retained[i]].index;
      const auto& point = pointCloud[pointIndex];
      for (int32_t p = 0; p < 3; ++p) {
        bBox.min[p] = std::min(bBox.min[p], point[p]);
        bBox.max[p] = std::max(bBox.max[p], point[p]);
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

  const int32_t index0 = numberOfNearestNeighborsInPrediction - 1;

  for (int32_t i = startIndex, j = 0; i < endIndex; ++i) {
    const int32_t index = indexes[i];
    const uint64_t mortonCode = packedVoxel[index].mortonCode;
    const int32_t pointIndex = packedVoxel[index].index;
    const auto& point = pointCloud[pointIndex];
    indexes[i] = pointIndex;
    while (j < retainedSize
           && mortonCode >= packedVoxel[retained[j]].mortonCode)
      ++j;
    j = std::min(retainedSize - 1, j);
    auto& predictor = predictors[--predIndex];
    pointIndexToPredictorIndex[pointIndex] = predIndex;

    predictor.init();

    const int32_t j0 = std::max(0, j - searchRange);
    const int32_t j1 = std::min(retainedSize, j + searchRange + 1);

    const int32_t bucketIndex0 = j / bucketSize;
    int32_t k0 = std::max(bucketIndex0 * bucketSize, j0);
    int32_t k1 = std::min((bucketIndex0 + 1) * bucketSize, j1);

    for (int32_t k = k0; k < k1; ++k) {
      const int32_t pointIndex1 = packedVoxel[retained[k]].index;
      const auto& point1 = pointCloud[pointIndex1];
      predictor.insertNeighbor(
        pointIndex1, (point - point1).getNorm2(),
        numberOfNearestNeighborsInPrediction);
    }

    for (int32_t s0 = 1, sr = (1 + searchRange / bucketSize); s0 < sr; ++s0) {
      for (int32_t s1 = 0; s1 < 2; ++s1) {
        const int32_t bucketIndex1 =
          s1 == 0 ? bucketIndex0 + s0 : bucketIndex0 - s0;
        if (bucketIndex1 < 0 || bucketIndex1 >= bBoxes.size()) {
          continue;
        }
        if (
          predictor.neighborCount < numberOfNearestNeighborsInPrediction
          || bBoxes[bucketIndex1].getDist2(point)
            < predictor.neighbors[index0].weight) {
          const int32_t k0 = std::max(bucketIndex1 * bucketSize, j0);
          const int32_t k1 = std::min((bucketIndex1 + 1) * bucketSize, j1);
          for (int32_t k = k0; k < k1; ++k) {
            const int32_t pointIndex1 = packedVoxel[retained[k]].index;
            const auto& point1 = pointCloud[pointIndex1];
            predictor.insertNeighbor(
              pointIndex1, (point - point1).getNorm2(),
              numberOfNearestNeighborsInPrediction);
          }
        }
      }
    }
    assert(predictor.neighborCount <= numberOfNearestNeighborsInPrediction);
576
577
578
579
580
581
  }
}

//---------------------------------------------------------------------------

inline void
582
subsampleByDistance(
583
  const PCCPointSet3& pointCloud,
584
585
586
587
588
  const std::vector<MortonCodeWithIndex>& packedVoxel,
  const std::vector<uint32_t>& input,
  const double radius2,
  const int32_t searchRange,
  std::vector<uint32_t>& retained,
589
590
  std::vector<uint32_t>& indexes)
{
591
592
593
594
595
596
597
  if (input.size() == 1) {
    indexes.push_back(input[0]);
  } else {
    for (const auto index : input) {
      if (retained.empty()) {
        retained.push_back(index);
        continue;
598
      }
599
600
601
602
603
604
605
606
607
608
      const auto& point = pointCloud[packedVoxel[index].index];
      if (
        (pointCloud[packedVoxel[retained.back()].index] - point).getNorm2()
          <= radius2
        || FindNeighborWithinDistance(
             pointCloud, packedVoxel, index, radius2, searchRange, retained)
          != PCC_UNDEFINED_INDEX) {
        indexes.push_back(index);
      } else {
        retained.push_back(index);
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
inline void
subsampleByDecimation(
  const std::vector<uint32_t>& input,
  std::vector<uint32_t>& retained,
  std::vector<uint32_t>& indexes)
{
  static const int kLodUniformQuant = 4;
  const int indexCount = int(input.size());
  for (int i = 0; i < indexCount; ++i) {
    if (i % kLodUniformQuant == 0)
      retained.push_back(input[i]);
    else
      indexes.push_back(input[i]);
  }
}

//---------------------------------------------------------------------------

inline void
subsample(
  bool useDecimation,
  const PCCPointSet3& pointCloud,
  const std::vector<MortonCodeWithIndex>& packedVoxel,
  const std::vector<uint32_t>& input,
  const double radius2,
  const int32_t searchRange,
  std::vector<uint32_t>& retained,
  std::vector<uint32_t>& indexes)
{
  if (useDecimation)
    subsampleByDecimation(input, retained, indexes);
  else
    subsampleByDistance(
      pointCloud, packedVoxel, input, radius2, searchRange, retained, indexes);
}

//---------------------------------------------------------------------------

654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
inline void
computeMortonCodes(
  const PCCPointSet3& pointCloud,
  std::vector<MortonCodeWithIndex>& packedVoxel)
{
  const int32_t pointCount = int32_t(pointCloud.getPointCount());
  packedVoxel.resize(pointCount);
  for (int n = 0; n < pointCount; n++) {
    const auto& position = pointCloud[n];
    packedVoxel[n].mortonCode = mortonAddr(
      int32_t(position[0]), int32_t(position[1]), int32_t(position[2]));
    packedVoxel[n].index = n;
  }
  sort(packedVoxel.begin(), packedVoxel.end());
}
669
670
671

//---------------------------------------------------------------------------

672
inline void
673
674
updatePredictors(
  const std::vector<uint32_t>& pointIndexToPredictorIndex,
675
676
  std::vector<PCCPredictor>& predictors)
{
677
678
  for (auto& predictor : predictors) {
    if (predictor.neighborCount < 2) {
679
680
      predictor.neighbors[0].weight = 1;
    } else if (predictor.neighbors[0].weight == 0) {
681
      predictor.neighborCount = 1;
682
      predictor.neighbors[0].weight = 1;
683
    }
684
685
686
687
688
    for (int32_t k = 0; k < predictor.neighborCount; ++k) {
      auto& neighbor = predictor.neighbors[k];
      neighbor.predictorIndex =
        pointIndexToPredictorIndex[neighbor.predictorIndex];
    }
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
// LoD generation using Binary-tree
inline void
buildLevelOfDetailBinaryTree(
  const PCCPointSet3& pointCloud,
  std::vector<uint32_t>& numberOfPointsPerLOD,
  std::vector<uint32_t>& indexes)
{
  const uint32_t pointCount = pointCloud.getPointCount();
  uint8_t const btDepth = std::log2(round(pointCount / 2)) - 1;
  PCCKdTree3 kdtree(pointCloud, btDepth);
  kdtree.build();

  bool skipLayer = true;  //if true, skips alternate layer of BT
  std::vector<bool> skipDepth(btDepth + 1, false);
  if (skipLayer) {
    for (int i = skipDepth.size() - 2; i >= 0; i--) {
      skipDepth[i] = !skipDepth[i + 1];  //if true, that layer is skipped
    }
  }

  indexes.resize(pointCount);
  std::vector<bool> visited(pointCount, false);
  uint32_t lod = 0;
  uint32_t start = 0;
  uint32_t end = 0;
  for (size_t i = 0; i < btDepth + 1; i++) {
    start = end;
    end = start + (1 << i);
    if (!skipDepth[i]) {
      for (int j = start; j < end; j++) {
        auto indx = kdtree.searchClosestAvailablePoint(kdtree.nodes[j].centd);
        if (indx != PCC_UNDEFINED_INDEX && !visited[indx]) {
          indexes[lod++] = indx;
          visited[indx] = true;
        }
      }
      numberOfPointsPerLOD.push_back(lod);
    }
  }
  for (size_t i = 0; i < pointCount; i++) {
    if (!visited[i]) {
      indexes[lod++] = i;
    }
  }
  numberOfPointsPerLOD.push_back(lod);
}

//---------------------------------------------------------------------------
struct PointCloudWrapper {
  PointCloudWrapper(
    const PCCPointSet3& pointCloud, const std::vector<uint32_t>& indexes)
    : _pointCloud(pointCloud), _indexes(indexes)
  {}
  inline size_t kdtree_get_point_count() const { return _pointCount; }
  inline void kdtree_set_point_count(const size_t pointCount)
  {
    assert(pointCount < _indexes.size());
    assert(pointCount < _pointCloud.getPointCount());
    _pointCount = pointCount;
  }
  inline double kdtree_get_pt(const size_t idx, int dim) const
  {
    assert(idx < _pointCount && dim < 3);
    return _pointCloud[_indexes[idx]][dim];
  }
  template<class BBOX>
  bool kdtree_get_bbox(BBOX& /* bb */) const
  {
    return false;
  }

  const PCCPointSet3& _pointCloud;
  const std::vector<uint32_t>& _indexes;
  size_t _pointCount = 0;
};
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
//---------------------------------------------------------------------------
inline void
computePredictors(
  const PCCPointSet3& pointCloud,
  const std::vector<uint32_t>& numberOfPointsPerLOD,
  const std::vector<uint32_t>& indexes,
  const size_t numberOfNearestNeighborsInPrediction,
  std::vector<PCCPredictor>& predictors)
{
  const uint32_t PCCTMC3MaxPredictionNearestNeighborCount = 3;
  const size_t pointCount = pointCloud.getPointCount();
  const size_t lodCount = numberOfPointsPerLOD.size();
  assert(lodCount);
  predictors.resize(pointCount);

  // delta prediction for LOD0
  uint32_t i0 = numberOfPointsPerLOD[0];
  for (uint32_t i = 0; i < i0; ++i) {
    auto& predictor = predictors[i];
    if (i == 0) {
      predictor.init(PCC_UNDEFINED_INDEX);
    } else {
      predictor.init(PCC_UNDEFINED_INDEX);
    }
  }
  PointCloudWrapper pointCloudWrapper(pointCloud, indexes);
  const nanoflann::SearchParams params(10, 0.0f, true);
  size_t indices[PCCTMC3MaxPredictionNearestNeighborCount];
  double sqrDist[PCCTMC3MaxPredictionNearestNeighborCount];
  nanoflann::KNNResultSet<double> resultSet(
    numberOfNearestNeighborsInPrediction);
  for (uint32_t lodIndex = 1; lodIndex < lodCount; ++lodIndex) {
    pointCloudWrapper.kdtree_set_point_count(i0);
    nanoflann::KDTreeSingleIndexAdaptor<
      nanoflann::L2_Simple_Adaptor<double, PointCloudWrapper>,
      PointCloudWrapper, 3>
      kdtree(
        3, pointCloudWrapper, nanoflann::KDTreeSingleIndexAdaptorParams(10));
    kdtree.buildIndex();
    const uint32_t i1 = numberOfPointsPerLOD[lodIndex];

    for (uint32_t i = i0; i < i1; ++i) {
      const uint32_t pointIndex = indexes[i];
      const auto& point = pointCloud[pointIndex];
      auto& predictor = predictors[i];
      resultSet.init(indices, sqrDist);
      kdtree.findNeighbors(resultSet, &point[0], params);
      const uint32_t resultCount = resultSet.size();
      if (sqrDist[0] == 0.0 || resultCount == 1) {
        const uint32_t predIndex = indices[0];
        predictor.init(predIndex);
      } else {
        predictor.neighborCount = resultCount;
        for (size_t n = 0; n < resultCount; ++n) {
          const uint32_t predIndex = indices[n];
          assert(predIndex < i);
          predictor.neighbors[n].predictorIndex = predIndex;
          const uint32_t pointIndex1 = indexes[predIndex];
          const auto& point1 = pointCloud[pointIndex1];
          predictor.neighbors[n].weight = 1.0 / (point - point1).getNorm2();
        }
      }
    }
    i0 = i1;
  }
}

//---------------------------------------------------------------------------
837
inline void
838
buildPredictorsFast(
839
  const PCCPointSet3& pointCloud,
840
  bool lod_decimation_enabled_flag,
841
842
843
844
845
846
847
848
  const std::vector<int64_t>& dist2,
  const int32_t levelOfDetailCount,
  const int32_t numberOfNearestNeighborsInPrediction,
  const int32_t searchRange1,
  const int32_t searchRange2,
  std::vector<PCCPredictor>& predictors,
  std::vector<uint32_t>& numberOfPointsPerLevelOfDetail,
  std::vector<uint32_t>& indexes)
849
{
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
  const int32_t pointCount = int32_t(pointCloud.getPointCount());
  assert(pointCount);

  std::vector<MortonCodeWithIndex> packedVoxel;
  computeMortonCodes(pointCloud, packedVoxel);

  std::vector<uint32_t> retained, input, pointIndexToPredictorIndex;
  pointIndexToPredictorIndex.resize(pointCount);
  retained.reserve(pointCount);
  input.resize(pointCount);
  for (uint32_t i = 0; i < pointCount; ++i) {
    input[i] = i;
  }

  // prepare output buffers
865
  predictors.resize(pointCount);
866
867
868
869
870
  numberOfPointsPerLevelOfDetail.resize(0);
  indexes.resize(0);
  indexes.reserve(pointCount);
  numberOfPointsPerLevelOfDetail.reserve(21);
  numberOfPointsPerLevelOfDetail.push_back(pointCount);
871

872
  std::vector<Box3<double>> bBoxes;
873
874
875
876
877
878
879
880
881
  int32_t predIndex = int32_t(pointCount);
  for (uint32_t lodIndex = 0; !input.empty() && lodIndex <= levelOfDetailCount;
       ++lodIndex) {
    const int32_t startIndex = indexes.size();
    if (lodIndex == levelOfDetailCount) {
      std::reverse(input.begin(), input.end());
      for (const auto index : input) {
        indexes.push_back(index);
      }
882
    } else {
883
884
      const double radius2 = dist2[lodIndex];
      subsample(
885
886
        lod_decimation_enabled_flag, pointCloud, packedVoxel, input, radius2,
        searchRange1, retained, indexes);
887
    }
888
889
890
891
892
893
894
895
896
897
898
    const int32_t endIndex = indexes.size();

    if (retained.empty()) {
      for (int32_t i = startIndex; i < endIndex; ++i) {
        const int32_t index = indexes[i];
        const int32_t pointIndex = packedVoxel[index].index;
        indexes[i] = pointIndex;
        auto& predictor = predictors[--predIndex];
        assert(predIndex >= 0);
        pointIndexToPredictorIndex[pointIndex] = predIndex;
        predictor.init(PCC_UNDEFINED_INDEX);
899
      }
900
901
902
903
904
905
      break;
    } else {
      computeNearestNeighbors(
        pointCloud, packedVoxel, retained, startIndex, endIndex, searchRange2,
        numberOfNearestNeighborsInPrediction, indexes, predictors,
        pointIndexToPredictorIndex, predIndex, bBoxes);
906
    }
907
908
909
910

    numberOfPointsPerLevelOfDetail.push_back(retained.size());
    input.resize(0);
    std::swap(retained, input);
911
  }
912
913
914
915
916
  std::reverse(indexes.begin(), indexes.end());
  updatePredictors(pointIndexToPredictorIndex, predictors);
  std::reverse(
    numberOfPointsPerLevelOfDetail.begin(),
    numberOfPointsPerLevelOfDetail.end());
917
918
}

919
920
//---------------------------------------------------------------------------

921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
inline void
buildPredictorsFastNoLod(
  const PCCPointSet3& pointCloud,
  const int32_t numberOfNearestNeighborsInPrediction,
  const int32_t searchRange,
  std::vector<PCCPredictor>& predictors,
  std::vector<uint32_t>& indexes)
{
  const int32_t pointCount = int32_t(pointCloud.getPointCount());
  assert(pointCount);

  indexes.resize(pointCount);
  // re-order points
  {
    std::vector<MortonCodeWithIndex> packedVoxel;
    computeMortonCodes(pointCloud, packedVoxel);
    for (int32_t i = 0; i < pointCount; ++i) {
      indexes[i] = packedVoxel[i].index;
    }
  }
  predictors.resize(pointCount);
  for (int32_t i = 0; i < pointCount; ++i) {
    const int32_t index = indexes[i];
    const auto& point = pointCloud[index];
    auto& predictor = predictors[i];
    predictor.init();
    const int32_t k0 = std::max(0, i - searchRange);
    const int32_t k1 = i - 1;
    for (int32_t k = k1; k >= k0; --k) {
      const int32_t index1 = indexes[k];
      const auto& point1 = pointCloud[index1];
      predictor.insertNeighbor(
        k, (point - point1).getNorm2(), numberOfNearestNeighborsInPrediction);
    }
    assert(predictor.neighborCount <= numberOfNearestNeighborsInPrediction);
    if (predictor.neighborCount < 2) {
957
958
      predictor.neighbors[0].weight = 1;
    } else if (predictor.neighbors[0].weight == 0) {
959
      predictor.neighborCount = 1;
960
      predictor.neighbors[0].weight = 1;
961
962
963
964
965
966
    }
  }
}

//---------------------------------------------------------------------------

967
}  // namespace pcc
Khaled Mammou's avatar
TMC3v0  
Khaled Mammou committed
968
969

#endif /* PCCTMC3Common_h */