<commit_before>/*
 * # Copyright (c) 2016-2017 The Khronos Group Inc.
 * # Copyright (c) 2016 <NAME>
 * #
 * # 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
 * #
 * #     http://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.
 */

/*
  TODO
  points - warn on duplicates
  lines - degenerate (v(2n)=v(2n+1)), duplicates (incl. reversed)
  line_loop, line_stripe - degenerate (v(n)=v(n+1)),
  triangles - degenerate (v1=v2 | v2=v3 | v1=v3), duplicates (order-aware)
  triangle_strip - degenerate (v1=v2=v3), duplicates (order-aware)
  triangle_fan - ???
 */

/*
  TODO
  warn when there're more than two equal consequential animation frames
  (across all outputs)
 */

/*
  TODO
  warn when interpolation may produce zero-length quaternions
 */

library gltf.data_access.validate_accessors_data;

import 'dart:math';
import 'package:gltf/gltf.dart';
import 'package:gltf/src/base/gltf_property.dart';
import 'package:gltf/src/gl.dart' as gl;
import 'package:vector_math/vector_math.dart';

void validateAccessorsData(Gltf gltf, Context context) {
  context.path
    ..clear()
    ..add(ACCESSORS);

  final matrix = new Matrix4.zero();

  final doubleMins = new List<double>(16);
  final doubleMaxs = new List<double>(16);

  final intMins = new List<int>(16);
  final intMaxs = new List<int>(16);

  final triangle = new List<int>(3);

  gltf.accessors.forEachWithIndices((i, accessor) {
    // Skip broken accessors
    if (accessor.type == null ||
        accessor.componentType == -1 ||
        accessor.count == -1) {
      return;
    }

    if (accessor.isXyzSign && accessor.components != 4) {
      return;
    }

    if (accessor.isUnit && accessor.components > 4) {
      return;
    }

    // Skip empty accessors
    if (accessor.bufferView == null && accessor.sparse == null) {
      return;
    }

    context.path.add(i.toString());

    if (accessor.sparse != null) {
      // Check sparse indices
      final view = accessor.sparse.getIndicesTypedView();
      if (view != null) {
        var index = 0;
        var lastValue = -1;
        for (var value in view) {
          if (lastValue != -1 && value <= lastValue) {
            context.addIssue(DataError.accessorSparseIndicesNonIncreasing,
                args: [index, value, lastValue]);
          }
          if (value >= accessor.count) {
            context.addIssue(DataError.accessorSparseIndexOob,
                args: [index, value, accessor.count]);
          }
          lastValue = value;
          ++index;
        }
      }
    }

    final components = accessor.components;

    var sum = 0.0;
    var index = 0;
    var componentIndex = 0;

    final iterator = gltf.accessors[i].getElements().iterator;

    var hasNext = iterator.moveNext();
    if (!hasNext) {
      return;
    }

    // Validation of float and integer data is partly
    // duplicated to avoid extra polymorphism
    if (accessor.componentType == gl.FLOAT) {
      var lastValue = -1.0;

      // Clean min/max arrays to not re-use values from previous accessors
      if (accessor.min != null) {
        doubleMins.fillRange(0, 16, double.NAN);
      }

      if (accessor.max != null) {
        doubleMaxs.fillRange(0, 16, double.NAN);
      }

      while (hasNext) {
        final double value = iterator.current;

        // Min and max checks are performed on each component value,
        // other checks wait until all components are provided

        if (value.isNaN || value.isInfinite) {
          context.addIssue(DataError.accessorInvalidFloat, args: [index]);
        } else {
          // Check that there're no out-of-bounds values

          if (accessor.min != null) {
            if (value < accessor.min[componentIndex]) {
              context.addIssue(DataError.accessorElementOutOfMinBound,
                  name: MIN,
                  args: [value, index, accessor.min[componentIndex]]);
            }

            if (doubleMins[componentIndex].isNaN ||
                doubleMins[componentIndex] > value) {
              doubleMins[componentIndex] = value;
            }
          }

          if (accessor.max != null) {
            if (value > accessor.max[componentIndex]) {
              context.addIssue(DataError.accessorElementOutOfMaxBound,
                  name: MAX,
                  args: [value, index, accessor.max[componentIndex]]);
            }

            if (doubleMaxs[componentIndex].isNaN ||
                doubleMaxs[componentIndex] < value) {
              doubleMaxs[componentIndex] = value;
            }
          }

          if (accessor.usage == AccessorUsage.AnimationInput) {
            if (value < 0.0) {
              context.addIssue(DataError.accessorAnimationInputNegative,
                  args: [index, value]);
            } else {
              if (lastValue != -1.0 && value <= lastValue) {
                context.addIssue(DataError.accessorAnimationInputNonIncreasing,
                    args: [index, value, lastValue]);
              }
              lastValue = value;
            }
          } else if (accessor.usage == AccessorUsage.IBM) {
            matrix.storage[componentIndex] = value;
          } else if (accessor.isUnit) {
            sum += value * value;
          }
        }

        if (++componentIndex == components) {
          if (accessor.usage == AccessorUsage.IBM) {
            if (!isTrsDecomposable(matrix)) {
              context.addIssue(DataError.indecomposableMatrix, args: [index]);
            }
          } else if (accessor.isUnit) {
            if (accessor.isXyzSign) {
              sum -= value * value;
            }

            if ((sum - 1.0).abs() > 0.0005) {
              context.addIssue(DataError.accessorNonUnit,<commit_msg>Tweak tangent vector length calculation<commit_after>/*
 * # Copyright (c) 2016-2017 The Khronos Group Inc.
 * # Copyright (c) 2016 <NAME>
 * #
 * # 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
 * #
 * #     http://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.
 */

/*
  TODO
  points - warn on duplicates
  lines - degenerate (v(2n)=v(2n+1)), duplicates (incl. reversed)
  line_loop, line_stripe - degenerate (v(n)=v(n+1)),
  triangles - degenerate (v1=v2 | v2=v3 | v1=v3), duplicates (order-aware)
  triangle_strip - degenerate (v1=v2=v3), duplicates (order-aware)
  triangle_fan - ???
 */

/*
  TODO
  warn when there're more than two equal consequential animation frames
  (across all outputs)
 */

/*
  TODO
  warn when interpolation may produce zero-length quaternions
 */

library gltf.data_access.validate_accessors_data;

import 'dart:math';
import 'package:gltf/gltf.dart';
import 'package:gltf/src/base/gltf_property.dart';
import 'package:gltf/src/gl.dart' as gl;
import 'package:vector_math/vector_math.dart';

void validateAccessorsData(Gltf gltf, Context context) {
  context.path
    ..clear()
    ..add(ACCESSORS);

  final matrix = new Matrix4.zero();

  final doubleMins = new List<double>(16);
  final doubleMaxs = new List<double>(16);

  final intMins = new List<int>(16);
  final intMaxs = new List<int>(16);

  final triangle = new List<int>(3);

  gltf.accessors.forEachWithIndices((i, accessor) {
    // Skip broken accessors
    if (accessor.type == null ||
        accessor.componentType == -1 ||
        accessor.count == -1) {
      return;
    }

    if (accessor.isXyzSign && accessor.components != 4) {
      return;
    }

    if (accessor.isUnit && accessor.components > 4) {
      return;
    }

    // Skip empty accessors
    if (accessor.bufferView == null && accessor.sparse == null) {
      return;
    }

    context.path.add(i.toString());

    if (accessor.sparse != null) {
      // Check sparse indices
      final view = accessor.sparse.getIndicesTypedView();
      if (view != null) {
        var index = 0;
        var lastValue = -1;
        for (var value in view) {
          if (lastValue != -1 && value <= lastValue) {
            context.addIssue(DataError.accessorSparseIndicesNonIncreasing,
                args: [index, value, lastValue]);
          }
          if (value >= accessor.count) {
            context.addIssue(DataError.accessorSparseIndexOob,
                args: [index, value, accessor.count]);
          }
          lastValue = value;
          ++index;
        }
      }
    }

    final components = accessor.components;

    var sum = 0.0;
    var index = 0;
    var componentIndex = 0;

    final iterator = gltf.accessors[i].getElements().iterator;

    var hasNext = iterator.moveNext();
    if (!hasNext) {
      return;
    }

    // Validation of float and integer data is partly
    // duplicated to avoid extra polymorphism
    if (accessor.componentType == gl.FLOAT) {
      var lastValue = -1.0;

      // Clean min/max arrays to not re-use values from previous accessors
      if (accessor.min != null) {
        doubleMins.fillRange(0, 16, double.NAN);
      }

      if (accessor.max != null) {
        doubleMaxs.fillRange(0, 16, double.NAN);
      }

      while (hasNext) {
        final double value = iterator.current;

        // Min and max checks are performed on each component value,
        // other checks wait until all components are provided

        if (value.isNaN || value.isInfinite) {
          context.addIssue(DataError.accessorInvalidFloat, args: [index]);
        } else {
          // Check that there're no out-of-bounds values

          if (accessor.min != null) {
            if (value < accessor.min[componentIndex]) {
              context.addIssue(DataError.accessorElementOutOfMinBound,
                  name: MIN,
                  args: [value, index, accessor.min[componentIndex]]);
            }

            if (doubleMins[componentIndex].isNaN ||
                doubleMins[componentIndex] > value) {
              doubleMins[componentIndex] = value;
            }
          }

          if (accessor.max != null) {
            if (value > accessor.max[componentIndex]) {
              context.addIssue(DataError.accessorElementOutOfMaxBound,
                  name: MAX,
                  args: [value, index, accessor.max[componentIndex]]);
            }

            if (doubleMaxs[componentIndex].isNaN ||
                doubleMaxs[componentIndex] < value) {
              doubleMaxs[componentIndex] = value;
            }
          }

          if (accessor.usage == AccessorUsage.AnimationInput) {
            if (value < 0.0) {
              context.addIssue(DataError.accessorAnimationInputNegative,
                  args: [index, value]);
            } else {
              if (lastValue != -1.0 && value <= lastValue) {
                context.addIssue(DataError.accessorAnimationInputNonIncreasing,
                    args: [index, value, lastValue]);
              }
              lastValue = value;
            }
          } else if (accessor.usage == AccessorUsage.IBM) {
            matrix.storage[componentIndex] = value;
          } else if (accessor.isUnit &&
              !(accessor.isXyzSign && componentIndex == 3)) {
            sum += value * value;
          }
        }

        if (++componentIndex == components) {
          if (accessor.usage == AccessorUsage.IBM) {
            if (!isTrsDecomposable(matrix)) {
              context.addIssue(DataError.indecomposableMatrix, args: [index]);
            }
          } else if (accessor.isUnit) {
            if ((sum - 1.0).abs() > 0.0005) {
              context.addIssue(DataError.accessorNonUnit,
{'fraction_non_alphanumeric': 0.11413527744025921, 'fraction_numerical': 0.011259619279060348, 'mean_word_length': 2.1366869918699187, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '242015', 'n_tokens_mistral': 3753, 'n_tokens_neox': 3545, 'n_words': 919}