findAccessorMinMax.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import getAccessorByteStride from "./getAccessorByteStride.js";
  2. import getComponentReader from "./getComponentReader.js";
  3. import numberOfComponentsForType from "./numberOfComponentsForType.js";
  4. import ComponentDatatype from "../../Core/ComponentDatatype.js";
  5. import defined from "../../Core/defined.js";
  6. /**
  7. * Finds the min and max values of the accessor.
  8. *
  9. * @param {object} gltf A javascript object containing a glTF asset.
  10. * @param {object} accessor The accessor object from the glTF asset to read.
  11. * @returns {{min: Array, max: Array}} min holding the array of minimum values and max holding the array of maximum values.
  12. *
  13. * @private
  14. */
  15. function findAccessorMinMax(gltf, accessor) {
  16. const bufferViews = gltf.bufferViews;
  17. const buffers = gltf.buffers;
  18. const bufferViewId = accessor.bufferView;
  19. const numberOfComponents = numberOfComponentsForType(accessor.type);
  20. // According to the spec, when bufferView is not defined, accessor must be initialized with zeros
  21. if (!defined(accessor.bufferView)) {
  22. return {
  23. min: new Array(numberOfComponents).fill(0.0),
  24. max: new Array(numberOfComponents).fill(0.0),
  25. };
  26. }
  27. const min = new Array(numberOfComponents).fill(Number.POSITIVE_INFINITY);
  28. const max = new Array(numberOfComponents).fill(Number.NEGATIVE_INFINITY);
  29. const bufferView = bufferViews[bufferViewId];
  30. const bufferId = bufferView.buffer;
  31. const buffer = buffers[bufferId];
  32. const source = buffer.extras._pipeline.source;
  33. const count = accessor.count;
  34. const byteStride = getAccessorByteStride(gltf, accessor);
  35. let byteOffset =
  36. accessor.byteOffset + bufferView.byteOffset + source.byteOffset;
  37. const componentType = accessor.componentType;
  38. const componentTypeByteLength =
  39. ComponentDatatype.getSizeInBytes(componentType);
  40. const dataView = new DataView(source.buffer);
  41. const components = new Array(numberOfComponents);
  42. const componentReader = getComponentReader(componentType);
  43. for (let i = 0; i < count; i++) {
  44. componentReader(
  45. dataView,
  46. byteOffset,
  47. numberOfComponents,
  48. componentTypeByteLength,
  49. components
  50. );
  51. for (let j = 0; j < numberOfComponents; j++) {
  52. const value = components[j];
  53. min[j] = Math.min(min[j], value);
  54. max[j] = Math.max(max[j], value);
  55. }
  56. byteOffset += byteStride;
  57. }
  58. return {
  59. min: min,
  60. max: max,
  61. };
  62. }
  63. export default findAccessorMinMax;