Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pickingRadius prop #641

Merged
merged 3 commits into from
May 17, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Remove elementInScope feature
  • Loading branch information
Xiaoji Chen committed May 15, 2017
commit abd9261b651a894761f27401ea6be413e925c48f
17 changes: 4 additions & 13 deletions examples/layer-browser/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ class App extends PureComponent {
// immutable: false,
// Effects are experimental for now. Will be enabled in the future
// effects: false,
separation: 0
separation: 0,
pickingRadius: 0
// the rotation controls works only for layers in
// meter offset projection mode. They are commented out
// here since layer browser currently only have one layer
Expand Down Expand Up @@ -102,12 +103,6 @@ class App extends PureComponent {
setImmutableDataSamples(settings.immutable);
}

_onQueryFeatures() {
const {deckgl} = this.refs;
const {width, height} = this.state;
console.log(deckgl.elementsInScope([0, 0], [width, height])); // eslint-disable-line
}

_onHover(info) {
this.setState({hoveredItem: info});
}
Expand Down Expand Up @@ -181,7 +176,7 @@ class App extends PureComponent {
}

_renderMap() {
const {width, height, mapViewState, settings: {effects}} = this.state;
const {width, height, mapViewState, settings: {effects, pickingRadius}} = this.state;
return (
<MapboxGLMap
mapboxApiAccessToken={MAPBOX_ACCESS_TOKEN || 'no_token'}
Expand All @@ -192,10 +187,10 @@ class App extends PureComponent {

<DeckGL
debug
ref="deckgl"
id="default-deckgl-overlay"
width={width} height={height}
{...mapViewState}
pickingRadius={pickingRadius}
onWebGLInitialized={ this._onWebGLInitialized }
onLayerHover={ this._onHover }
onLayerClick={ this._onClick }
Expand Down Expand Up @@ -227,10 +222,6 @@ class App extends PureComponent {
{ this._renderMap() }
{ !MAPBOX_ACCESS_TOKEN && this._renderNoTokenWarning() }
<div id="control-panel">
<div>
<h4 />
<button onClick={this._onQueryFeatures} >Query Rendered Features</button>
</div>
<LayerControls
title="Composite Settings"
settings={settings}
Expand Down
2 changes: 1 addition & 1 deletion examples/layer-browser/src/components/layer-controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default class LayerControls extends PureComponent {
if (propType && Number.isFinite(propType.max)) {
max = propType.max;

} else if (/radiusScale|elevationScale|width|height|pixel|size|miter/i.test(settingName) &&
} else if (/radius|scale|width|height|pixel|size|miter/i.test(settingName) &&

(/^((?!scale).)*$/).test(settingName)) {
max = 100;
Expand Down
165 changes: 40 additions & 125 deletions src/lib/draw-and-pick.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,17 @@ export function pickLayers(gl, {

} else {
// For all other events, run picking process normally.
const pickResult = pickFromBuffer(gl, {
const pickInfo = pickFromBuffer(gl, {
layers,
pickingFBO,
deviceX,
deviceY,
deviceRadius
});

pickedColor = pickResult.color;
pickedLayer = pickResult.layer;
pickedObjectIndex = pickResult.objectIndex;
pickedColor = pickInfo.pickedColor;
pickedLayer = pickInfo.pickedLayer;
pickedObjectIndex = pickInfo.pickedObjectIndex;
affectedLayers = pickedLayer ? [pickedLayer] : [];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason we move this logical out of pickFromBuffer() function now?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only logic that has been moved out is affectedLayers. pickFromBuffer() and pickFromBufferByBoundingBox() now return similarly shaped objects.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, I already moved this out in the drag events PR because we don't always pick -- drag events that indicate the continuation of a drag event that started on a specific element don't need to re-pick. In that case, the user is assumed to be dragging an element around and so the element picked on dragstart is returned without picking.


if (mode === 'hover') {
Expand Down Expand Up @@ -193,65 +193,10 @@ export function pickLayers(gl, {

return unhandledPickInfos;
}
/* eslint-enable max-depth, max-statements */

export function pickLayersByBoundingBox(gl, {
layers,
pickingFBO,
boundingBox: {x, y, width, height},
viewport
}) {

// Convert from canvas top-left to WebGL bottom-left coordinates
// And compensate for pixelRatio
const pixelRatio = typeof window !== 'undefined' ?
window.devicePixelRatio : 1;
const deviceBox = {
x: Math.round(x * pixelRatio),
y: Math.round(gl.canvas.height - (y + height) * pixelRatio),
width: Math.round(width * pixelRatio),
height: Math.round(height * pixelRatio)
};

// For all other events, run picking process normally.
const pickResults = pickFromBufferByBoundingBox(gl, {
layers,
pickingFBO,
deviceBox
});

const baseInfo = createInfo([x, y], viewport);
baseInfo.pixelRatio = pixelRatio;

// Convert each result to pickingInfo object
const infos = {};

pickResults.filter(Boolean)
.forEach(({color, layer, objectIndex}) => {
// Get unique objects
const objectId = `${layer.id}:${objectIndex}`;

if (!infos[objectId]) {
const info = Object.assign({}, baseInfo, {
color,
index: objectIndex,
picked: true
});

infos[objectId] = getLayerPickingInfo({
layer,
info,
mode: 'query'
});
}
});

return Object.values(infos);
}

/**
* Pick at a specified pixel with a tolerance radius
* Returns the closest object to the pixel in shape `{color, layer, objectIndex}`
* Returns the closest object to the pixel in shape `{pickedColor, pickedLayer, pickedObjectIndex}`
*/
function pickFromBuffer(gl, {
layers,
Expand All @@ -264,54 +209,9 @@ function pickFromBuffer(gl, {
// Create a box of size `radius * 2 + 1` centered at [deviceX, deviceY]
const x = Math.max(0, deviceX - deviceRadius);
const y = Math.max(0, deviceY - deviceRadius);
const deviceBox = {
x,
y,
width: Math.min(pickingFBO.width, deviceX + deviceRadius) - x + 1,
height: Math.min(pickingFBO.height, deviceY + deviceRadius) - y + 1
};

const pickResults = pickFromBufferByBoundingBox(gl, {layers, pickingFBO, deviceBox});

// Traverse all pixels in picking results and find the one closest to the supplied
// [deviceX, deviceY]
let minDistanceToCenter = deviceRadius;
let closestResultToCenter = null;
/* eslint-disable max-depth */
for (let col = 0; col < deviceBox.width; col++) {
for (let row = 0; row < deviceBox.height; row++) {
const pickResult = pickResults[row * deviceBox.width + col];
if (pickResult) {
const dx = deviceBox.x + col - deviceX;
const dy = deviceBox.y + row - deviceY;
const d = Math.sqrt(dx * dx + dy * dy);
if (d <= minDistanceToCenter) {
minDistanceToCenter = d;
closestResultToCenter = pickResult;
pickResult.x = deviceBox.x + col;
pickResult.y = deviceBox.y + row;
}
}
}
}
/* eslint-enable max-depth */

return closestResultToCenter || {
color: EMPTY_PIXEL,
layer: null,
objectIndex: -1
};
}
const width = Math.min(pickingFBO.width, deviceX + deviceRadius) - x + 1;
const height = Math.min(pickingFBO.height, deviceY + deviceRadius) - y + 1;

/**
* Returns an array of picked object for each pixel in bounding box
* In the shape of `{color, layer, objectIndex}`
*/
function pickFromBufferByBoundingBox(gl, {
layers,
pickingFBO,
deviceBox: {x, y, width, height}
}) {
// TODO - just return glContextWithState once luma updates
// Make sure we clear scissor test and fbo bindings in case of exceptions
// We are only interested in one pixel, no need to render anything else
Expand Down Expand Up @@ -357,29 +257,44 @@ function pickFromBufferByBoundingBox(gl, {
// restore blend mode
setBlendMode(gl, oldBlendMode);

const pickResults = [];

for (let i = 0; i < pickedColors.length; i += 4) {
// Decode picked color
const pickedLayerIndex = pickedColors[i + 3] - 1;
if (pickedLayerIndex >= 0) {
const pickedLayer = layers[pickedLayerIndex];
const pickedColor = pickedColors.slice(i, i + 4);
const pickedObjectIndex = pickedLayer.decodePickingColor(pickedColor);

pickResults.push({
color: pickedColor,
layer: pickedLayer,
objectIndex: pickedObjectIndex
});
} else {
pickResults.push(null);
// Traverse all pixels in picking results and find the one closest to the supplied
// [deviceX, deviceY]
let minSquareDistanceToCenter = deviceRadius * deviceRadius;
let closestResultToCenter = null;
let i = 0;

for (let row = 0; row < height; row++) {
for (let col = 0; col < width; col++) {
// Decode picked layer from color
const pickedLayerIndex = pickedColors[i + 3] - 1;

if (pickedLayerIndex >= 0) {
const dx = col + x - deviceX;
const dy = row + y - deviceY;
const d2 = dx * dx + dy * dy;

if (d2 <= minSquareDistanceToCenter) {
minSquareDistanceToCenter = d2;

// Decode picked object index from color
const pickedColor = pickedColors.slice(i, i + 4);
const pickedLayer = layers[pickedLayerIndex];
const pickedObjectIndex = pickedLayer.decodePickingColor(pickedColor);
closestResultToCenter = {pickedColor, pickedLayer, pickedObjectIndex};
}
}
i += 4;
}
}

return pickResults;
return closestResultToCenter || {
pickedColor: EMPTY_PIXEL,
pickedLayer: null,
pickedObjectIndex: -1
};
});
}
/* eslint-enable max-depth, max-statements */

function createInfo(pixel, viewport) {
// Assign a number of potentially useful props to the "info" object
Expand Down
22 changes: 1 addition & 21 deletions src/lib/layer-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
import Layer from './layer';
import {log} from './utils';
import assert from 'assert';
import {drawLayers, pickLayers, pickLayersByBoundingBox} from './draw-and-pick';
import {drawLayers, pickLayers} from './draw-and-pick';
import {LIFECYCLE} from './constants';
import {Viewport} from './viewports';
import {setOverride, layerEditListener, logLayer} from '../debug/seer-integration';
Expand Down Expand Up @@ -170,26 +170,6 @@ export default class LayerManager {
});
}

pickLayerByBoundingBox({x, y, width, height}) {
const {gl, uniforms} = this.context;

// Set up a frame buffer if needed
if (this.context.pickingFBO === null ||
gl.canvas.width !== this.context.pickingFBO.width ||
gl.canvas.height !== this.context.pickingFBO.height) {
this.context.pickingFBO = new FramebufferObject(gl, {
width: gl.canvas.width,
height: gl.canvas.height
});
}
return pickLayersByBoundingBox(gl, {
layers: this.layers,
viewport: this.context.viewport,
pickingFBO: this.context.pickingFBO,
boundingBox: {x, y, width, height}
});
}

needsRedraw({clearRedrawFlags = false} = {}) {
if (!this.context.viewport) {
return false;
Expand Down
35 changes: 6 additions & 29 deletions src/react/deckgl.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,17 +80,6 @@ export default class DeckGL extends React.Component {
this._updateLayers(nextProps);
}

/* Public API */
elementsInScope(topLeft, bottomRight) {
return this.layerManager.pickLayerByBoundingBox({
x: topLeft[0],
y: topLeft[1],
width: bottomRight[0] - topLeft[0],
height: bottomRight[1] - topLeft[1]
});
}
/* End Public API */

_updateLayers(nextProps) {
const {width, height, latitude, longitude, zoom, pitch, bearing, altitude} = nextProps;
let {viewport} = nextProps;
Expand Down Expand Up @@ -159,12 +148,8 @@ export default class DeckGL extends React.Component {
return;
}
const {event: {offsetX: x, offsetY: y}} = event;
const selectedInfos = this.layerManager.pickLayer({
x,
y,
mode: 'click',
radius: this.props.pickingRadius
});
const radius = this.props.pickingRadius;
const selectedInfos = this.layerManager.pickLayer({x, y, radius, mode: 'click'});
if (selectedInfos.length) {
const firstInfo = selectedInfos.find(info => info.index >= 0);
// Event.event holds the original MouseEvent object
Expand All @@ -179,12 +164,8 @@ export default class DeckGL extends React.Component {
return;
}
const {event: {offsetX: x, offsetY: y}} = event;
const selectedInfos = this.layerManager.pickLayer({
x,
y,
mode: 'hover',
radius: this.props.pickingRadius
});
const radius = this.props.pickingRadius;
const selectedInfos = this.layerManager.pickLayer({x, y, radius, mode: 'hover'});
if (selectedInfos.length) {
const firstInfo = selectedInfos.find(info => info.index >= 0);
// Event.event holds the original MouseEvent object
Expand Down Expand Up @@ -224,12 +205,8 @@ export default class DeckGL extends React.Component {
}

if (mode) {
const selectedInfos = this.layerManager.pickLayer({
x,
y,
mode,
radius: this.props.pickingRadius
});
const radius = this.props.pickingRadius;
const selectedInfos = this.layerManager.pickLayer({x, y, radius, mode});
if (selectedInfos.length) {
const firstInfo = selectedInfos.find(info => info.index >= 0);
// Event.event holds the original MouseEvent object
Expand Down