All files / Sources/Rendering/WebGPU/HardwareSelector index.js

8.43% Statements 14/166
0% Branches 0/64
16.66% Functions 2/12
8.58% Lines 14/163

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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              1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1x     1x                 1x                                                                                                                                                                                                                                                                                                     1x             1x     1x   1x   1x 1x     1x         1x                
import macro from 'vtk.js/Sources/macros';
import vtkHardwareSelector from 'vtk.js/Sources/Rendering/Core/HardwareSelector';
import vtkWebGPUBuffer from 'vtk.js/Sources/Rendering/WebGPU/Buffer';
import vtkWebGPUHardwareSelectionPass from 'vtk.js/Sources/Rendering/WebGPU/HardwareSelectionPass';
import vtkSelectionNode from 'vtk.js/Sources/Common/DataModel/SelectionNode';
import vtkDataSet from 'vtk.js/Sources/Common/DataModel/DataSet';
 
const { SelectionContent, SelectionField } = vtkSelectionNode;
const { FieldAssociations } = vtkDataSet;
const { vtkErrorMacro } = macro;
 
function getInfoHash(info) {
  return `${info.propID} ${info.compositeID}`;
}
 
function convert(xx, yy, buffdata, channel) {
  const offset =
    ((buffdata.height - yy - 1) * buffdata.colorBufferWidth + xx) * 4 + channel;
  return buffdata.colorValues[offset];
}
 
function getPixelInformationWithData(
  buffdata,
  inDisplayPosition,
  maxDistance,
  outSelectedPosition
) {
  // Base case
  const maxDist = maxDistance < 0 ? 0 : maxDistance;
  if (maxDist === 0) {
    outSelectedPosition[0] = inDisplayPosition[0];
    outSelectedPosition[1] = inDisplayPosition[1];
    if (
      inDisplayPosition[0] < 0 ||
      inDisplayPosition[0] >= buffdata.width ||
      inDisplayPosition[1] < 0 ||
      inDisplayPosition[1] >= buffdata.height
    ) {
      return null;
    }
 
    const actorid = convert(
      inDisplayPosition[0],
      inDisplayPosition[1],
      buffdata,
      0
    );
 
    if (actorid <= 0) {
      // the pixel did not hit any actor.
      return null;
    }
 
    const info = {};
 
    info.propID = actorid;
 
    let compositeID = convert(
      inDisplayPosition[0],
      inDisplayPosition[1],
      buffdata,
      1
    );
    if (compositeID < 0 || compositeID > 0xffffff) {
      compositeID = 0;
    }
    info.compositeID = compositeID;
 
    if (buffdata.captureZValues) {
      const offset =
        (buffdata.height - inDisplayPosition[1] - 1) *
          buffdata.zbufferBufferWidth +
        inDisplayPosition[0];
      info.zValue = buffdata.depthValues[offset];
      info.zValue = buffdata.webGPURenderer.convertToOpenGLDepth(info.zValue);
      info.displayPosition = inDisplayPosition;
    }
    return info;
  }
 
  // Iterate over successively growing boxes.
  // They recursively call the base case to handle single pixels.
  const dispPos = [inDisplayPosition[0], inDisplayPosition[1]];
  const curPos = [0, 0];
  let info = getPixelInformationWithData(
    buffdata,
    inDisplayPosition,
    0,
    outSelectedPosition
  );
  if (info) {
    return info;
  }
  for (let dist = 1; dist < maxDist; ++dist) {
    // Vertical sides of box.
    for (
      let y = dispPos[1] > dist ? dispPos[1] - dist : 0;
      y <= dispPos[1] + dist;
      ++y
    ) {
      curPos[1] = y;
      if (dispPos[0] >= dist) {
        curPos[0] = dispPos[0] - dist;
        info = getPixelInformationWithData(
          buffdata,
          curPos,
          0,
          outSelectedPosition
        );
        if (info) {
          return info;
        }
      }
      curPos[0] = dispPos[0] + dist;
      info = getPixelInformationWithData(
        buffdata,
        curPos,
        0,
        outSelectedPosition
      );
      if (info) {
        return info;
      }
    }
    // Horizontal sides of box.
    for (
      let x = dispPos[0] >= dist ? dispPos[0] - (dist - 1) : 0;
      x <= dispPos[0] + (dist - 1);
      ++x
    ) {
      curPos[0] = x;
      if (dispPos[1] >= dist) {
        curPos[1] = dispPos[1] - dist;
        info = getPixelInformationWithData(
          buffdata,
          curPos,
          0,
          outSelectedPosition
        );
        if (info) {
          return info;
        }
      }
      curPos[1] = dispPos[1] + dist;
      info = getPixelInformationWithData(
        buffdata,
        curPos,
        0,
        outSelectedPosition
      );
      if (info) {
        return info;
      }
    }
  }
 
  // nothing hit.
  outSelectedPosition[0] = inDisplayPosition[0];
  outSelectedPosition[1] = inDisplayPosition[1];
  return null;
}
 
//-----------------------------------------------------------------------------
function convertSelection(fieldassociation, dataMap, buffdata) {
  const sel = [];
 
  let count = 0;
  dataMap.forEach((value, key) => {
    const child = vtkSelectionNode.newInstance();
    child.setContentType(SelectionContent.INDICES);
    switch (fieldassociation) {
      case FieldAssociations.FIELD_ASSOCIATION_CELLS:
        child.setFieldType(SelectionField.CELL);
        break;
      case FieldAssociations.FIELD_ASSOCIATION_POINTS:
        child.setFieldType(SelectionField.POINT);
        break;
      default:
        vtkErrorMacro('Unknown field association');
    }
    child.getProperties().propID = value.info.propID;
    const wprop = buffdata.webGPURenderer.getPropFromID(value.info.propID);
    child.getProperties().prop = wprop.getRenderable();
    child.getProperties().compositeID = value.info.compositeID;
    child.getProperties().pixelCount = value.pixelCount;
    if (buffdata.captureZValues) {
      child.getProperties().displayPosition = [
        value.info.displayPosition[0],
        value.info.displayPosition[1],
        value.info.zValue,
      ];
      child.getProperties().worldPosition =
        buffdata.webGPURenderWindow.displayToWorld(
          value.info.displayPosition[0],
          value.info.displayPosition[1],
          value.info.zValue,
          buffdata.renderer
        );
    }
 
    child.setSelectionList(value.attributeIDs);
    sel[count] = child;
    count++;
  });
 
  return sel;
}
 
//----------------------------------------------------------------------------
function generateSelectionWithData(buffdata, fx1, fy1, fx2, fy2) {
  const x1 = Math.floor(fx1);
  const y1 = Math.floor(fy1);
  const x2 = Math.floor(fx2);
  const y2 = Math.floor(fy2);
 
  const dataMap = new Map();
 
  const outSelectedPosition = [0, 0];
 
  for (let yy = y1; yy <= y2; yy++) {
    for (let xx = x1; xx <= x2; xx++) {
      const pos = [xx, yy];
      const info = getPixelInformationWithData(
        buffdata,
        pos,
        0,
        outSelectedPosition
      );
      if (info) {
        const hash = getInfoHash(info);
        if (!dataMap.has(hash)) {
          dataMap.set(hash, {
            info,
            pixelCount: 1,
            attributeIDs: [info.attributeID],
          });
        } else {
          const dmv = dataMap.get(hash);
          dmv.pixelCount++;
          if (buffdata.captureZValues) {
            if (info.zValue < dmv.info.zValue) {
              dmv.info = info;
            }
          }
          if (dmv.attributeIDs.indexOf(info.attributeID) === -1) {
            dmv.attributeIDs.push(info.attributeID);
          }
        }
      }
    }
  }
  return convertSelection(buffdata.fieldAssociation, dataMap, buffdata);
}
 
// ----------------------------------------------------------------------------
// vtkWebGPUHardwareSelector methods
// ----------------------------------------------------------------------------
 
function vtkWebGPUHardwareSelector(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkWebGPUHardwareSelector');
 
  //----------------------------------------------------------------------------
  publicAPI.endSelection = () => {
    model.WebGPURenderer.setSelector(null);
  };
 
  //----------------------------------------------------------------------------
  // note we ignore the x,y arguments as WebGPU has to do buffer copies
  // of the entire depth bufer. We could realloc hardware selection textures
  // based on the passed in size etc but it gets messy so for now we always
  // render the full size window and copy it to the buffers.
  publicAPI.getSourceDataAsync = async (renderer) => {
    if (!renderer || !model._WebGPURenderWindow) {
      vtkErrorMacro('Renderer and view must be set before calling Select.');
      return false;
    }
 
    // todo revisit making selection part of core
    // then we can do this in core
    model._WebGPURenderWindow.getRenderable().preRender();
 
    if (!model._WebGPURenderWindow.getInitialized()) {
      model._WebGPURenderWindow.initialize();
      await new Promise((resolve) => {
        model._WebGPURenderWindow.onInitialized(resolve);
      });
    }
 
    const webGPURenderer = model._WebGPURenderWindow.getViewNodeFor(renderer);
 
    if (!webGPURenderer) {
      return false;
    }
 
    // Initialize renderer for selection.
    // change the renderer's background to black, which will indicate a miss
    const originalSuppress = webGPURenderer.getSuppressClear();
    webGPURenderer.setSuppressClear(true);
 
    model._selectionPass.traverse(model._WebGPURenderWindow, webGPURenderer);
 
    // restore original background
    webGPURenderer.setSuppressClear(originalSuppress);
 
    const device = model._WebGPURenderWindow.getDevice();
    const texture = model._selectionPass.getColorTexture();
    const depthTexture = model._selectionPass.getDepthTexture();
 
    // as this is async we really don't want to store things in
    // the class as multiple calls may start before resolving
    // so anything specific to this request gets put into the
    // result object (by value in most cases)
    const result = {
      area: [0, 0, texture.getWidth() - 1, texture.getHeight() - 1],
      captureZValues: model.captureZValues,
      fieldAssociation: model.fieldAssociation,
      renderer,
      webGPURenderer,
      webGPURenderWindow: model._WebGPURenderWindow,
      width: texture.getWidth(),
      height: texture.getHeight(),
    };
 
    // must be a multiple of 256 bytes, so 16 texels with rgba32uint
    result.colorBufferWidth = 16 * Math.floor((result.width + 15) / 16);
    result.colorBufferSizeInBytes =
      result.colorBufferWidth * result.height * 4 * 4;
    const colorBuffer = vtkWebGPUBuffer.newInstance({
      label: 'hardwareSelectColorBuffer',
    });
    colorBuffer.setDevice(device);
    /* eslint-disable no-bitwise */
    /* eslint-disable no-undef */
    colorBuffer.create(
      result.colorBufferSizeInBytes,
      GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
    );
    /* eslint-enable no-bitwise */
    /* eslint-enable no-undef */
 
    const cmdEnc = model._WebGPURenderWindow.getCommandEncoder();
    cmdEnc.copyTextureToBuffer(
      {
        texture: texture.getHandle(),
      },
      {
        buffer: colorBuffer.getHandle(),
        bytesPerRow: 16 * result.colorBufferWidth,
        rowsPerImage: result.height,
      },
      {
        width: result.width,
        height: result.height,
        depthOrArrayLayers: 1,
      }
    );
 
    let zbuffer;
    if (model.captureZValues) {
      result.zbufferBufferWidth = 64 * Math.floor((result.width + 63) / 64);
      zbuffer = vtkWebGPUBuffer.newInstance({
        label: 'hardwareSelectDepthBuffer',
      });
      zbuffer.setDevice(device);
      result.zbufferSizeInBytes = result.height * result.zbufferBufferWidth * 4;
      /* eslint-disable no-bitwise */
      /* eslint-disable no-undef */
      zbuffer.create(
        result.zbufferSizeInBytes,
        GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
      );
      /* eslint-enable no-bitwise */
      /* eslint-enable no-undef */
 
      cmdEnc.copyTextureToBuffer(
        {
          texture: depthTexture.getHandle(),
          aspect: 'depth-only',
        },
        {
          buffer: zbuffer.getHandle(),
          bytesPerRow: 4 * result.zbufferBufferWidth,
          rowsPerImage: result.height,
        },
        {
          width: result.width,
          height: result.height,
          depthOrArrayLayers: 1,
        }
      );
    }
    device.submitCommandEncoder(cmdEnc);
 
    /* eslint-disable no-undef */
    const cLoad = colorBuffer.mapAsync(GPUMapMode.READ);
    if (model.captureZValues) {
      const zLoad = zbuffer.mapAsync(GPUMapMode.READ);
      await Promise.all([cLoad, zLoad]);
      result.depthValues = new Float32Array(zbuffer.getMappedRange().slice());
      zbuffer.unmap();
    } else {
      await cLoad;
    }
    /* eslint-enable no-undef */
 
    result.colorValues = new Uint32Array(colorBuffer.getMappedRange().slice());
    colorBuffer.unmap();
 
    result.generateSelection = (fx1, fy1, fx2, fy2) =>
      generateSelectionWithData(result, fx1, fy1, fx2, fy2);
    return result;
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  // WebGPURenderWindow: null,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Build VTK API
  vtkHardwareSelector.extend(publicAPI, model, initialValues);
 
  model._selectionPass = vtkWebGPUHardwareSelectionPass.newInstance();
 
  macro.setGet(publicAPI, model, ['_WebGPURenderWindow']);
  macro.moveToProtected(publicAPI, model, ['WebGPURenderWindow']);
 
  // Object methods
  vtkWebGPUHardwareSelector(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(
  extend,
  'vtkWebGPUHardwareSelector'
);
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };