diff --git a/404.html b/404.html index 3739e340050..38fcd289af9 100644 --- a/404.html +++ b/404.html @@ -4,13 +4,13 @@ deck.gl - - + +
- - + + \ No newline at end of file diff --git a/assets/js/0434f321.d65d6898.js b/assets/js/0434f321.06715786.js similarity index 99% rename from assets/js/0434f321.d65d6898.js rename to assets/js/0434f321.06715786.js index c23c3946f57..95f826d321a 100644 --- a/assets/js/0434f321.d65d6898.js +++ b/assets/js/0434f321.06715786.js @@ -1 +1 @@ -"use strict";(self.webpackChunkproject_website=self.webpackChunkproject_website||[]).push([[6612],{3905:(e,t,i)=>{i.d(t,{Zo:()=>d,kt:()=>g});var n=i(67294);function o(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function s(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function r(e){for(var t=1;t=0||(o[i]=e[i]);return o}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(o[i]=e[i])}return o}var l=n.createContext({}),c=function(e){var t=n.useContext(l),i=t;return e&&(i="function"==typeof e?e(t):r(r({},t),e)),i},d=function(e){var t=c(e.components);return n.createElement(l.Provider,{value:t},e.children)},u="mdxType",h={inlineCode:"code",wrapper:function(e){var t=e.children;return n.createElement(n.Fragment,{},t)}},p=n.forwardRef((function(e,t){var i=e.components,o=e.mdxType,s=e.originalType,l=e.parentName,d=a(e,["components","mdxType","originalType","parentName"]),u=c(i),p=o,g=u["".concat(l,".").concat(p)]||u[p]||h[p]||s;return i?n.createElement(g,r(r({ref:t},d),{},{components:i})):n.createElement(g,r({ref:t},d))}));function g(e,t){var i=arguments,o=t&&t.mdxType;if("string"==typeof e||o){var s=i.length,r=new Array(s);r[0]=p;var a={};for(var l in t)hasOwnProperty.call(t,l)&&(a[l]=t[l]);a.originalType=e,a[u]="string"==typeof e?e:o,r[1]=a;for(var c=2;c{i.d(t,{IM:()=>o,Sr:()=>n,fL:()=>s});const n={LIGHT:"https://deck.gl/mapstyle/deck-light.json",LIGHT_LABEL:"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",DARK:"https://deck.gl/mapstyle/deck-dark.json",BLANK:{version:8,sources:{},layers:[]}},o="https://raw.githubusercontent.com/visgl/deck.gl-data/master/website",s="https://github.com/visgl/deck.gl/tree/9.0-release"},44752:(e,t,i)=>{i.d(t,{C:()=>c});const n=["dataComparator","fetch"],o=["autoHighlight","coordinateOrigin","coordinateSystem","highlightColor","modelMatrix","opacity","pickable","visible","wrapLongitude"],s={loaders:[],coordinateSystem:"COORDINATE_SYSTEM.LNGLAT",renderSubLayers:"props => new GeoJsonLayer(props)",characterSet:'" !\\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~"'};function r(e,t){if(!e.includes("\n")||0===t)return e;const i=e.split("\n");if(t>0){const e="".padStart(t," ");return i.map(((t,i)=>i>0?e+t:t)).join("\n")}return i.map(((e,i)=>i>0?e.slice(-t):e)).join("\n")}function a(e){return null==e?"null":"string"==typeof e?"'"+e+"'":"function"==typeof e?e.toString():Array.isArray(e)?"["+e.map(a).join(", ")+"]":e===Number.MAX_SAFE_INTEGER?"Number.MAX_SAFE_INTEGER":r(JSON.stringify(e,null,2),2)}function l(e,t){const i=[],l={};t=function(e){const t=e.split("\n");t.pop();const i={};let n,o=1/0;for(const s of t){const e=s.match(/^(\s*)(\w+):\s*(.*)/);e&&e[1].length<=o?(o=e[1].length,n=e[2],i[n]=e[3]):n&&(i[n]+="\n"+s)}for(n in i)i[n]=r(i[n].replace(/,\s*$/,""),2-o);return i}(t);let c=e.constructor,d=!1;const u=e.props[Symbol.for("asyncPropOriginal")],h=e.props[Symbol.for("asyncPropResolved")];function p(e,t,o,s){if(!l[e]&&!n.includes(e)){const n=(o?"// ":"")+e+": "+t+",";void 0===s?i.push(n):i.splice(s,0,n),l[e]=!0}}let g=1;for(p("id",a(e.id)),t.data&&p("data",t.data,!1,g++);c.layerName;){if(c.hasOwnProperty("defaultProps")){i.push("","/* props "+(d?"inherited from":"from")+" "+c.layerName+" class */","");const n=Object.keys(c.defaultProps).sort();for(const i of n){const n=c.defaultProps[i],r=!(i in u)&&!(i in h)&&!Object.hasOwnProperty.call(e.props,i);let l,d=!1;i in t?l=t[i]:(d=n&&n.deprecatedFor,d=d||i.startsWith("_"),d=d||n&&"accessor"===n.type&&"function"==typeof n.value,d=d||"Layer"===c.layerName&&!o.includes(i),l=u[i]||e.props[i],l="function"==typeof l?null:i in s?s[i]:a(l)),d||p(i,l,r)}}c=Object.getPrototypeOf(c),d=!0}for(const n in t)n in l||p(n,t[n],!1,g++);return i.join("\n ")}function c(e,t){const{Layer:i,isExperimental:n,getTooltip:o,props:s,mapStyle:a=!0,dependencies:c=[],imports:d,initialViewState:u}=e,h=n?"_"+i.layerName:i.layerName,p=["DeckGL",h],g=[];if(d)for(const r in d)r[0]>="a"||(r.endsWith("Loader")?g.push(r):p.push(r));const f=r(JSON.stringify(u,null,2).replace(/"/g,""),2),m="const {"+p.join(", ")+"} = deck;\n"+(g.length?"const {"+g.join(", ")+"} = loaders;\n":"")+"\nconst layer = new "+h+"({\n "+l(t,s)+"\n});\n\nnew DeckGL({\n "+(a?"mapStyle: 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json',":"")+"\n initialViewState: "+f+",\n controller: true,\n "+(o?"getTooltip: "+o+",":"")+"\n layers: [layer]\n});\n ";!function(e){let{dependencies:t=[],title:i,source:n}=e;const o={js_external:t.concat(["https://unpkg.com/deck.gl@latest/dist.min.js"]).join(";"),title:i,parent:48721472,tags:["webgl","data visualization"],editors:"001",css:"\n body {\n margin: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n }\n \n .deck-tooltip {\n font-size: 0.8em;\n font-family: Helvetica, Arial, sans-serif;\n }\n ",js:"/*\n* "+window.location.href+"\n*/\n"+n},s=document.createElement("form");s.action="https://codepen.io/pen/define/",s.method="POST",s.style.display="none",document.body.appendChild(s);const r=document.createElement("input");r.type="text",r.name="data",r.value=JSON.stringify(o),s.appendChild(r),window.open("","deck-example-codepen"),s.target="deck-example-codepen",s.submit(),s.remove()}({dependencies:c.concat(["https://unpkg.com/maplibre-gl@3.6.0/dist/maplibre-gl.js"]),title:"deck.gl "+i.layerName,source:m})}},62757:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{v:()=>makeLayerDemo});var react__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(67294),_deck_gl_react__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(50920),react_map_gl_maplibre__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(24808),styled_components__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(19521),_docusaurus_theme_common__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(92949),_constants_defaults__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(27260),_codepen_automation__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(44752);const INITIAL_VIEW_STATE={longitude:-122.4,latitude:37.74,zoom:11,maxZoom:20,pitch:30,bearing:0},TOOLTIP_STYLE={padding:"4px",background:"rgba(0, 0, 0, 0.8)",color:"#fff",maxWidth:"300px",fontSize:"10px",zIndex:9},DemoPlaceholder=styled_components__WEBPACK_IMPORTED_MODULE_4__.ZP.div.withConfig({displayName:"demo-base__DemoPlaceholder",componentId:"sc-bhdrci-0"})(["height:50vh;min-height:200px;position:relative;margin-bottom:24px;@media screen and (max-width:768px){height:60vh;}"]),DemoContainer=styled_components__WEBPACK_IMPORTED_MODULE_4__.ZP.div.withConfig({displayName:"demo-base__DemoContainer",componentId:"sc-bhdrci-1"})(["height:50vh;min-height:200px;position:absolute;width:100%;left:0;top:0;overflow:hidden;@media screen and (max-width:768px){height:60vh;}"]),DemoSourceLink=styled_components__WEBPACK_IMPORTED_MODULE_4__.ZP.div.withConfig({displayName:"demo-base__DemoSourceLink",componentId:"sc-bhdrci-2"})(["position:absolute;top:0;right:0;padding:8px;background:var(--ifm-background-surface-color);margin:12px;box-shadow:0 2px 4px rgba(0,0,0,0.3);cursor:pointer;font-weight:bold;font-size:12px;&:hover{color:var(--ifm-color-primary);}svg{width:20px;vertical-align:middle;margin-right:4px;}"]);function evalObject(source,globals,output){return eval("(function evalObject(globals){\n Object.assign(globalThis, globals);\n "+(output?source+"\n return {"+output.join(",")+"};":"return "+source+";")+"\n })")(globals)}function makeLayerDemo(config){const{Layer:Layer,getTooltip:getTooltip,props:props,mapStyle:mapStyle=!0,initialViewState:initialViewState=INITIAL_VIEW_STATE,imports:imports}=config;config.initialViewState=initialViewState;const _getTooltip=getTooltip&&eval(getTooltip),styledGetTooltip=e=>{const t=_getTooltip&&_getTooltip(e);return t&&{text:t,style:TOOLTIP_STYLE}},layerProps=evalObject(props,imports);function Demo(){const{colorMode:e}=(0,_docusaurus_theme_common__WEBPACK_IMPORTED_MODULE_5__.I)(),t=new Layer(layerProps),i="dark"===e?_constants_defaults__WEBPACK_IMPORTED_MODULE_2__.Sr.DARK:_constants_defaults__WEBPACK_IMPORTED_MODULE_2__.Sr.LIGHT;return react__WEBPACK_IMPORTED_MODULE_0__.createElement(DemoPlaceholder,null,react__WEBPACK_IMPORTED_MODULE_0__.createElement(DemoContainer,null,react__WEBPACK_IMPORTED_MODULE_0__.createElement(_deck_gl_react__WEBPACK_IMPORTED_MODULE_6__.Z,{pickingRadius:5,initialViewState:initialViewState,getTooltip:styledGetTooltip,controller:!0,layers:[t]},mapStyle&&react__WEBPACK_IMPORTED_MODULE_0__.createElement(react_map_gl_maplibre__WEBPACK_IMPORTED_MODULE_1__.D5,{reuseMaps:!0,mapStyle:i}))),react__WEBPACK_IMPORTED_MODULE_0__.createElement(DemoSourceLink,{onClick:()=>(0,_codepen_automation__WEBPACK_IMPORTED_MODULE_3__.C)(config,t)},react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},react__WEBPACK_IMPORTED_MODULE_0__.createElement("path",{d:"M0 0h24v24H0V0z",fill:"none"}),react__WEBPACK_IMPORTED_MODULE_0__.createElement("path",{fill:"currentcolor",d:"M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"})),"Edit on Codepen"))}return react__WEBPACK_IMPORTED_MODULE_0__.memo(Demo)}},61413:(e,t,i)=>{i.d(t,{$6:()=>b,J6:()=>w,LN:()=>y,N0:()=>P,Pt:()=>L,R2:()=>C,b:()=>x,eg:()=>_,sD:()=>S,sX:()=>k,xY:()=>M,zC:()=>T});var n=i(19845),o=i(36148),s=i(39632),r=i(66918),a=i(15788),l=i(42688),c=i(87799),d=i(61112),u=i(36723),h=i(11092),p=i(75096),g=i(11041),f=i(48950),m=i(62757),v=i(27260);const y=(0,m.v)({Layer:o.Z,getTooltip:"({object}) => object && `${object.from.name} to ${object.to.name}`",props:"{\n data: '"+v.IM+"/bart-segments.json',\n pickable: true,\n getWidth: 12,\n getSourcePosition: d => d.from.coordinates,\n getTargetPosition: d => d.to.coordinates,\n getSourceColor: d => [Math.sqrt(d.inbound), 140, 0],\n getTargetColor: d => [Math.sqrt(d.outbound), 140, 0]\n }"}),_=(0,m.v)({Layer:s.Z,props:"{\n bounds: [-122.519, 37.7045, -122.355, 37.829],\n image: '"+v.IM+"/sf-districts.png'\n }"}),w=(0,m.v)({Layer:r.Z,getTooltip:"({object}) => object && `height: ${object.value * 5000}m`",props:"{\n data: '"+v.IM+"/hexagons.json',\n diskResolution: 12,\n radius: 250,\n extruded: true,\n pickable: true,\n elevationScale: 100,\n getPosition: d => d.centroid,\n getFillColor: d => [48, 128, d.value * 255, 255],\n getLineColor: [0, 0, 0],\n getLineWidth: 20,\n getElevation: d => d.value * 50\n }"}),P=(0,m.v)({Layer:a.Z,getTooltip:"({object}) => object && (object.properties.name || object.properties.station)",props:"{\n data: '"+v.IM+"/bart.geo.json',\n pickable: true,\n stroked: false,\n filled: true,\n extruded: true,\n lineWidthMinPixels: 2,\n pointType: 'circle+text',\n pointRadiusUnits: 'pixels',\n getText: f => f.properties.name,\n getTextSize: 12,\n getFillColor: [160, 160, 180, 200],\n getLineColor: f => {\n const hex = f.properties.color;\n // convert to RGB\n return hex ? hex.match(/[0-9a-f]{2}/g).map(x => parseInt(x, 16)) : [0, 0, 0];\n },\n getPointRadius: 4,\n getLineWidth: 20,\n getElevation: 30\n }"}),b=(0,m.v)({Layer:l.Z,getTooltip:"({object}) => object && `height: ${object.value * 5000}m`",props:"{\n data: '"+v.IM+"/hexagons.json',\n pickable: true,\n extruded: true,\n cellSize: 200,\n elevationScale: 5000,\n getPosition: d => d.centroid,\n getFillColor: d => [48, 128, d.value * 255, 255],\n getElevation: d => d.value\n }"}),x=(0,m.v)({Layer:c.Z,getTooltip:"({object}) => object && `${object.name}\n${object.address}`",props:"{\n data: '"+v.IM+"/bart-stations.json',\n pickable: true,\n iconAtlas: '"+v.IM+"/icon-atlas.png',\n iconMapping: {\n marker: {\n x: 0,\n y: 0,\n width: 128,\n height: 128,\n anchorY: 128,\n mask: true\n }\n },\n sizeScale: 8,\n getPosition: d => d.coordinates,\n getIcon: d => 'marker',\n getSize: d => 5,\n getColor: d => [Math.sqrt(d.exits), 140, 0]\n }"}),C=(0,m.v)({Layer:d.Z,getTooltip:"({object}) => object && `${object.from.name} to ${object.to.name}`",props:"{\n data: '"+v.IM+"/bart-segments.json',\n pickable: true,\n getWidth: 12,\n getSourcePosition: d => d.from.coordinates,\n getTargetPosition: d => d.to.coordinates,\n getColor: d => [Math.sqrt(d.inbound + d.outbound), 140, 0]\n }"}),S=(0,m.v)({Layer:u.Z,getTooltip:"({object}) => object && object.name",props:"{\n data: '"+v.IM+"/bart-lines.json',\n parameters: {\n depthMask: false\n },\n pickable: true,\n widthScale: 20,\n widthMinPixels: 2,\n getPath: d => d.path,\n getColor: d => {\n const hex = d.color;\n // convert to RGB\n return hex.match(/[0-9a-f]{2}/g).map(x => parseInt(x, 16));\n },\n getWidth: d => 5\n }"}),L=(0,m.v)({Layer:h.Z,getTooltip:"({object}) => object && object.position.join(', ')",imports:{COORDINATE_SYSTEM:n.Df},props:"{\n data: '"+v.IM+"/pointcloud.json',\n pickable: false,\n coordinateSystem: COORDINATE_SYSTEM.METER_OFFSETS,\n coordinateOrigin: [-122.4, 37.74],\n pointSize: 2,\n getPosition: d => d.position,\n getNormal: d => d.normal,\n getColor: d => d.color\n }"}),M=(0,m.v)({Layer:p.Z,getTooltip:"({object}) => object && `${object.zipcode}\nPopulation: ${object.population}`",props:"{\n data: '"+v.IM+"/sf-zipcodes.json',\n pickable: true,\n stroked: true,\n filled: true,\n extruded: true,\n wireframe: true,\n lineWidthMinPixels: 1,\n getPolygon: d => d.contour,\n getElevation: d => d.population / d.area / 10,\n getFillColor: d => [d.population / d.area / 60, 140, 0],\n getLineColor: [80, 80, 80],\n getLineWidth: d => 1\n }"}),k=(0,m.v)({Layer:g.Z,getTooltip:"({object}) => object && `${object.name}\n${object.address}`",props:"{\n data: '"+v.IM+"/bart-stations.json',\n pickable: true,\n opacity: 0.8,\n stroked: true,\n radiusScale: 6,\n radiusMinPixels: 1,\n radiusMaxPixels: 100,\n lineWidthMinPixels: 1,\n getPosition: d => d.coordinates,\n getRadius: d => Math.sqrt(d.exits),\n getFillColor: [255, 140, 0],\n getLineColor: [0, 0, 0]\n }"}),T=(0,m.v)({Layer:f.Z,getTooltip:"({object}) => object && `${object.name}\n${object.address}`",props:"{\n data: '"+v.IM+"/bart-stations.json',\n pickable: true,\n sizeScale: 1,\n getPosition: d => d.coordinates,\n getText: d => d.name,\n getColor: [255, 128, 0],\n getSize: 16,\n getAngle: 0,\n getTextAnchor: 'middle',\n getAlignmentBaseline: 'center'\n }"})},67551:(e,t,i)=>{i.r(t),i.d(t,{assets:()=>c,contentTitle:()=>a,default:()=>p,frontMatter:()=>r,metadata:()=>l,toc:()=>d});var n=i(83117),o=(i(67294),i(3905)),s=i(61413);const r={},a="ColumnLayer",l={unversionedId:"api-reference/layers/column-layer",id:"api-reference/layers/column-layer",title:"ColumnLayer",description:"This is the primitive layer rendered by HexagonLayer after aggregation. Unlike the HexagonLayer, it renders one column for each data object.",source:"@site/../docs/api-reference/layers/column-layer.md",sourceDirName:"api-reference/layers",slug:"/api-reference/layers/column-layer",permalink:"/docs/api-reference/layers/column-layer",draft:!1,editUrl:"https://github.com/visgl/deck.gl/tree/master/website/../docs/api-reference/layers/column-layer.md",tags:[],version:"current",frontMatter:{},sidebar:"tutorialSidebar",previous:{title:"BitmapLayer",permalink:"/docs/api-reference/layers/bitmap-layer"},next:{title:"CPUGridLayer",permalink:"/docs/api-reference/aggregation-layers/cpu-grid-layer"}},c={},d=[{value:"Installation",id:"installation",level:2},{value:"Properties",id:"properties",level:2},{value:"Render Options",id:"render-options",level:3},{value:"diskResolution (Number, optional)",id:"diskresolution",level:5},{value:"radius (Number, optional) transition-enabled",id:"radius",level:5},{value:"angle (Number, optional) transition-enabled",id:"angle",level:5},{value:"vertices (Array, optional)",id:"vertices",level:5},{value:"offset (Number, Number, optional) transition-enabled",id:"offset",level:5},{value:"coverage (Number, optional) transition-enabled",id:"coverage",level:5},{value:"elevationScale (Number, optional) transition-enabled",id:"elevationscale",level:5},{value:"filled (Boolean, optional)",id:"filled",level:5},{value:"stroked (Boolean, optional)",id:"stroked",level:5},{value:"extruded (Boolean, optional)",id:"extruded",level:5},{value:"wireframe (Boolean, optional)",id:"wireframe",level:5},{value:"flatShading (Boolean, optional)",id:"flatshading",level:5},{value:"radiusUnits (String, optional)",id:"radiusunits",level:5},{value:"lineWidthUnits (String, optional)",id:"linewidthunits",level:5},{value:"lineWidthScale (Boolean, optional) transition-enabled",id:"linewidthscale",level:5},{value:"lineWidthMinPixels (Number, optional) transition-enabled",id:"linewidthminpixels",level:5},{value:"lineWidthMaxPixels (Number, optional) transition-enabled",id:"linewidthmaxpixels",level:5},{value:"material (Object, optional)",id:"material",level:5},{value:"Data Accessors",id:"data-accessors",level:3},{value:"getPosition (Function, optional) transition-enabled",id:"getposition",level:5},{value:"getFillColor (Function|Array, optional) transition-enabled",id:"getfillcolor",level:5},{value:"getLineColor (Function|Array, optional) transition-enabled",id:"getlinecolor",level:5},{value:"getElevation (Function|Number, optional) transition-enabled",id:"getelevation",level:5},{value:"getLineWidth (Function|Number, optional) transition-enabled",id:"getlinewidth",level:5},{value:"Source",id:"source",level:2}],u={toc:d},h="wrapper";function p(e){let{components:t,...i}=e;return(0,o.kt)(h,(0,n.Z)({},u,i,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("h1",{id:"columnlayer"},"ColumnLayer"),(0,o.kt)(s.J6,{mdxType:"ColumnLayerDemo"}),(0,o.kt)("blockquote",null,(0,o.kt)("p",{parentName:"blockquote"},"This is the primitive layer rendered by ",(0,o.kt)("a",{parentName:"p",href:"/docs/api-reference/aggregation-layers/hexagon-layer"},"HexagonLayer")," after aggregation. Unlike the HexagonLayer, it renders one column for each data object.")),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"ColumnLayer")," renders extruded cylinders (tessellated regular polygons) at given coordinates."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},"import DeckGL from '@deck.gl/react';\nimport {ColumnLayer} from '@deck.gl/layers';\n\nfunction App({data, viewState}) {\n /**\n * Data format:\n * [\n * {centroid: [-122.4, 37.7], value: 0.2},\n * ...\n * ]\n */\n const layer = new ColumnLayer({\n id: 'column-layer',\n data,\n diskResolution: 12,\n radius: 250,\n extruded: true,\n pickable: true,\n elevationScale: 5000,\n getPosition: d => d.centroid,\n getFillColor: d => [48, 128, d.value * 255, 255],\n getLineColor: [0, 0, 0],\n getElevation: d => d.value\n });\n\n return object && `height: ${object.value * 5000}m`} />;\n}\n")),(0,o.kt)("h2",{id:"installation"},"Installation"),(0,o.kt)("p",null,"To install the dependencies from NPM:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-bash"},"npm install deck.gl\n# or\nnpm install @deck.gl/core @deck.gl/layers\n")),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},"import {ColumnLayer} from '@deck.gl/layers';\nnew ColumnLayer({});\n")),(0,o.kt)("p",null,"To use pre-bundled scripts:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-html"},'

Introduction

These docs are forLooking for an old version?

deck.gl is designed to simplify high-performance, WebGL2/WebGPU based visualization of large data sets. Users can quickly get impressive visual results with minimal effort by composing existing layers, or leverage deck.gl's extensible architecture to address custom needs.

deck.gl maps data (usually an array of JSON objects) into a stack of visual layers - e.g. icons, polygons, texts; and look at them with views: e.g. map, first-person, orthographic.

deck.gl handles a number of challenges out of the box:

  • Performant rendering and updating of large data sets
  • Interactive event handling such as picking, highlighting and filtering
  • Cartographic projections and integration with major basemap providers including Mapbox, Google Maps and ESRI
  • A catalog of proven, well-tested layers

Deck.gl is designed to be highly customizable. All layers come with flexible APIs to allow programmatic control of each aspect of the rendering. All core classes such are easily extendable by the users to address custom use cases.

Flavors

Script Tag

<script src="https://unpkg.com/deck.gl@latest/dist.min.js"></script>

NPM Module

npm install deck.gl

Pure JS

React

Python

pip install pydeck

Third-Party Bindings

Ecosystem

deck.gl is one of the main frameworks in the vis.gl framework suite.

deck.gl is developed in parallel with a number of companion modules, including:

  • luma.gl - A general purpose WebGL2/WebGPU library designed to be interoperable both with the raw browser APIs and (as far as possible) with other WebGL2/WebGPU libraries. In particular, luma.gl does not claim ownership of the WebGL2/WebGPU context, and can work with any supplied context, including contexts created by the application or other libraries.
  • loaders.gl - a suite of framework-independent loaders for file formats focused on visualization of big data, including point clouds, 3D geometries, images, geospatial formats as well as tabular data.
  • react-map-gl - A React wrapper around Mapbox GL which works seamlessly with deck.gl. There are two integration modes to choose from depending on which features you need, see Using With Mapbox for details.
  • nebula.gl - A high-performance feature editing framework for deck.gl.

Learning deck.gl

How you approach learning deck.gl will depend on your previous knowledge and how you want to use it.

Getting familiar with the various layers and their props, and reading the basic articles in the deck.gl developer guide should of course be one of the first steps.

Exploring the deck.gl examples is a good starting point.

In-depth tutorials for how to develop deck.gl applications are available on the Vis Academy website.

And our blog contains a lot of additional information that might be helpful.

But where to go after that?

Learning Reactive UI Programming

deck.gl is designed according to functional UI programming principles, popularized by frameworks like React. The key to writing good, performant deck.gl applications and layers lies in knowing how to minimize updates and redundant calculations, understanding concepts like "shallow equality" etc. This is critical when using deck.gl with React, but can still be helpful to understand when using deck.gl in non-React contexts.

There is an impressive amount of information (documentation, blog posts, educational videos, etc.) on the reactive programming paradigm in relation to modern web frameworks such as React, Flux and Redux. Where to start depends mostly on your application architecture choices. Exploring such information will take you beyond what we can cover in the basic deck.gl developer guide article on Updates.

Understanding WebGL2/WebGPU

Knowledge of WebGL2 or WebGPU is only needed if you want to create custom layers in deck.gl. Note that while trying out a new ambitious rendering approach for a new layer will likely require deeper knowledge, it is often possible to modify or extend existing deck.gl layers (including modifying the shader code) with a surprisingly limited amount of WebGL2/WebGPU knowledge.

There are many web resources for learning WebGL2/WebGPU. luma.gl can be a good start.

- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/aggregation-layer.html b/docs/api-reference/aggregation-layers/aggregation-layer.html index 44c88ce00b6..9fd7838184e 100644 --- a/docs/api-reference/aggregation-layers/aggregation-layer.html +++ b/docs/api-reference/aggregation-layers/aggregation-layer.html @@ -4,13 +4,13 @@ AggregationLayer | deck.gl - - + +

AggregationLayer

All of the layers in @deck.gl/aggregation-layers module perform some sort of data aggregation. All these layers perform aggregation with different parameters (CPU vs GPU, aggregation to rectangular bins vs hexagon bins, world space vs screen space, aggregation of single weight vs multiple weights etc).

AggregationLayer and GridAggregationLayer perform most of the common tasks for aggregation with flexibility of customizations. This document describes what AggregationLayer does and how to use it in other aggregation layers.

AggregationLayer is subclassed form CompositeLayer and all layers in @deck.gl/aggregation-layers are subclassed from this Layer.

Integration with AttributeManager

This layer creates AttributeManager and makes it available for its subclasses. Any aggregation layer can add attributes to the AttributeManager and retrieve them using getAttributes method. This enables using AttributeManager's features and optimization for using attributes. Also manual iteration of data prop can be removed and attributes can be directly set on GPU aggregation models or accessed directly for CPU aggregation.

Example: Adding attributes to an aggregation layer

const attributeManager = this.getAttributeManager();
attributeManager.add({
positions: {size: 3, accessor: 'getPosition'},
color: {size: 3, accessor: 'getColorWeight'},
elevation: {size: 3, accessor: 'getElevationWeight'}
});

updateState()

During update state, Subclasses of AggregationLayer must first call 'super.updateState()', which calls

  • updateShaders(shaders) : Subclasses can override this if they need to update shaders, for example, when performing GPU aggregation, aggregation shaders must be merged with argument of this function to correctly apply extensions.

  • _updateAttributes: This checks and updates attributes based on updated props.

Checking if aggregation is dirty

Dimensions

Typical aggregation, involves :

  1. Group the input data points into bins
  2. Compute the aggregated value for each bin

For example, when cellSize or data is changed, layer needs to perform both 1 and 2 steps, when a parameter affecting a bin's value is changed (like getWeight accessor), layer only need to perform step 2.

When doing CPU Aggregation, both above steps are performed individually. But for GPU aggregation, both are merged into single render call.

To support what state is dirty, constructor takes dimensions object, which contains, several keyed dimensions. It must contain data dimension that defines, when re-aggregation needs to be performed.

isAggregationDirty()

This helper can be used if a dimension is changed. Sublayers can defined custom dimensions and call this method to check if a dimension is changed.

isAttributeChanged()

AggregationLayer tracks what attributes are changed in each update cycle. Super classes can use isAttributeChanged() method to check if a specific attribute is changed or any attribute is changed.

- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/contour-layer.html b/docs/api-reference/aggregation-layers/contour-layer.html index d73122de423..d7391495955 100644 --- a/docs/api-reference/aggregation-layers/contour-layer.html +++ b/docs/api-reference/aggregation-layers/contour-layer.html @@ -4,13 +4,13 @@ ContourLayer | deck.gl - - + +

ContourLayer

The ContourLayer aggregates data into iso-lines or iso-bands for a given threshold and cell size. Isoline represents collection of line segments that separate the area above and below a given threshold. Isoband represents a collection of polygons (filled) that fill the area containing values in a given threshold range. To generate an Isoline single threshold value is needed, to generate an Isoband an Array with two values needed. Data is first aggregated using given cell size and resulting scalar field is used to run Marching Squares algorithm that generates a set of vertices to form Isolines or Isobands. In below documentation Isoline and Isoband is referred as contour.

import DeckGL from '@deck.gl/react';
import {ContourLayer} from '@deck.gl/aggregation-layers';

const CONTOURS = [
{threshold: 1, color: [255, 0, 0, 255], strokeWidth: 1}, // => Isoline for threshold 1
{threshold: 5, color: [0, 255, 0], strokeWidth: 2}, // => Isoline for threshold 5
{threshold: [6, 10], color: [0, 0, 255, 128]} // => Isoband for threshold range [6, 10)
];

function App({data, viewState}) {
/**
* Data format:
* [
* {COORDINATES: [-122.42177834, 37.78346622]},
* ...
* ]
*/
const layer = new ContourLayer({
id: 'contourLayer',
// Three contours are rendered.
contours: CONTOURS,
cellSize: 200,
getPosition: d => d.COORDINATES,
});

return <DeckGL viewState={viewState}
layers={[layer]}
getTooltip={({object}) => object && object.name} />;
}

Installation

To install the dependencies from NPM:

npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers @deck.gl/aggregation-layers
import {ContourLayer} from '@deck.gl/aggregation-layers';
new ContourLayer({});

To use pre-bundled scripts:

<script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
<!-- or -->
<script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/aggregation-layers@^8.0.0/dist.min.js"></script>
new deck.ContourLayer({});

Properties

Inherits from all Base Layer properties.

Render Options

cellSize (Number, optional) transition-enabled
  • Default: 1000

Size of each cell in meters

gpuAggregation (bool, optional)
  • Default: true

When set to true and browser supports GPU aggregation, aggregation is performed on GPU. GPU aggregation can be 2 to 3 times faster depending upon number of points and number of cells.

aggregation (String, optional)
  • Default: 'SUM'

Defines the type of aggregation operation, valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. When no value or an invalid value is set, 'SUM' is used as aggregation.

  • SUM : Grid cell contains sum of all weights that fall into it.
  • MEAN : Grid cell contains mean of all weights that fall into it.
  • MIN : Grid cell contains minimum of all weights that fall into it.
  • MAX : Grid cell contains maximum of all weights that fall into it.
contours (Array, optional)
  • Default: [{threshold: 1}]

Array of objects with following keys

  • threshold (Number or Array) :

    • Isolines: threshold value must be a single Number, Isolines are generated based on this threshold value.
    • Isobands: threshold value must be an Array of two Numbers. Isobands are generated using [threshold[0], threshold[1]) as threshold range, i.e area that has values >= threshold[0] and < threshold[1] are rendered with corresponding color. NOTE: threshold[0] is inclusive and threshold[1] is not inclusive.
  • color (Array, optional) : RGBA color array to be used to render the contour, if not specified a default value of [255, 255, 255, 255] is used. When a three component RGB array specified, a default value of 255 is used for Alpha.

  • strokeWidth (Number, optional) : Applicable for Isolines only, width of the Isoline in pixels, if not specified a default value of 1 is used.

  • zIndex (Number, optional) : Defines z order of the contour. Contour with higher zIndex value is rendered above contours with lower zIndex values. When visualizing overlapping contours, zIndex along with zOffset (defined below) can be used to precisely layout contours. This also avoids z-fighting rendering issues. If not specified a unique value from 0 to n (number of contours) is assigned.

NOTE: Like any other layer prop, a shallow comparison is performed on contours prop to determine if it is changed. This prop should be set to an array object, that changes only when contours need to be changed.

zOffset (Number, optional)
  • Default: 0.005

A very small z offset that is added for each vertex of a contour (Isoline or Isoband). This is needed to control the layout of contours, especially when rendering overlapping contours. Imagine a case where an Isoline is specified which is overlapped with an Isoband. To make sure the Isoline is visible we need to render this above the Isoband.

Data Accessors

getPosition (Function, optional)
  • Default: object => object.position

Method called to retrieve the position of each object.

getWeight (Function, optional)
  • Default: 1

The weight of each object.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.

Sub Layers

The ContourLayer renders the following sublayers:

Source

modules/aggregation-layers/src/contour-layer

- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/cpu-grid-layer.html b/docs/api-reference/aggregation-layers/cpu-grid-layer.html index 5fb33b24402..dd51a4afea4 100644 --- a/docs/api-reference/aggregation-layers/cpu-grid-layer.html +++ b/docs/api-reference/aggregation-layers/cpu-grid-layer.html @@ -4,8 +4,8 @@ CPUGridLayer | deck.gl - - + +
@@ -21,7 +21,7 @@ larger than the elevationUpperPercentile will be hidden.

elevationLowerPercentile (Number, optional) transition-enabled
  • Default: 0

Filter cells and re-calculate elevation by elevationLowerPercentile. Cells with elevation value smaller than the elevationLowerPercentile will be hidden.

colorScaleType (String, optional)
  • Default: 'quantize'

Scaling function used to determine the color of the grid cell, default value is 'quantize'. Supported Values are 'quantize', 'linear', 'quantile' and 'ordinal'.

material (Object, optional)
  • Default: true

This is an object that contains material props for lighting effect applied on extruded polygons. Check the lighting guide for configurable settings.

colorAggregation (String, optional)
  • Default: 'SUM'

Defines the operation used to aggregate all data object weights to calculate a cell's color value. Valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. 'SUM' is used when an invalid value is provided.

getColorWeight and colorAggregation together determine the elevation value of each cell. If the getColorValue prop is supplied, they will be ignored.

Example 1 : Using count of data elements that fall into a cell to encode the its color
  • Using getColorValue

...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getColorValue: points => points.length,
...
});
  • Using getColorWeight and colorAggregation

...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getColorWeight: point => 1,
colorAggregation: 'SUM'
...
});
Example 2 : Using mean value of 'SPACES' field of data elements to encode the color of the cell
  • Using getColorValue
function getMean(points) {
return points.reduce((sum, p) => sum += p.SPACES, 0) / points.length;
}
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getColorValue: getMean,
...
});
  • Using getColorWeight and colorAggregation
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getColorWeight: point => point.SPACES,
colorAggregation: 'SUM'
...
});

If your use case requires aggregating using an operation that is not one of 'SUM', 'MEAN', 'MAX' and 'MIN', getColorValue should be used to define such custom aggregation function.

elevationAggregation (String, optional)
  • Default: 'SUM'

Defines the operation used to aggregate all data object weights to calculate a cell's elevation value. Valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. 'SUM' is used when an invalid value is provided.

getElevationWeight and elevationAggregation together determine the elevation value of each cell. If the getElevationValue prop is supplied, they will be ignored.

Example 1 : Using count of data elements that fall into a cell to encode the its elevation
  • Using getElevationValue
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getElevationValue: points => points.length
...
});
  • Using getElevationWeight and elevationAggregation
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getElevationWeight: point => 1,
elevationAggregation: 'SUM'
...
});
Example 2 : Using maximum value of 'SPACES' field of data elements to encode the elevation of the cell
  • Using getElevationValue
function getMax(points) {
return points.reduce((max, p) => p.SPACES > max ? p.SPACES : max, -Infinity);
}
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getElevationValue: getMax,
...
});
  • Using getElevationWeight and elevationAggregation
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getElevationWeight: point => point.SPACES,
elevationAggregation: 'MAX'
...
});

If your use case requires aggregating using an operation that is not one of 'SUM', 'MEAN', 'MAX' and 'MIN', getElevationValue should be used to define such custom aggregation function.

Data Accessors

getPosition (Function, optional)
  • Default: object => object.position

Method called to retrieve the position of each object.

getColorWeight (Function, optional) transition-enabled
  • Default: 1

The weight of a data object used to calculate the color value for a cell.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.
getColorValue (Function, optional) transition-enabled
  • Default: null

After data objects are aggregated into cells, this accessor is called on each cell to get the value that its color is based on. If supplied, this will override the effect of getColorWeight and colorAggregation props.

Arguments:

  • objects (Array) - a list of objects whose positions fall inside this cell.
  • objectInfo (Object) - contains the following fields:
    • indices (Array) - the indices of objects in the original data
    • data - the value of the data prop.
getElevationWeight (Function, optional) transition-enabled
  • Default: 1

The weight of a data object used to calculate the elevation value for a cell.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.
getElevationValue (Function, optional) transition-enabled
  • Default: null

After data objects are aggregated into cells, this accessor is called on each cell to get the value that its elevation is based on. If supplied, this will override the effect of getElevationWeight and elevationAggregation props.

Arguments:

  • objects (Array) - a list of objects whose positions fall inside this cell.
  • objectInfo (Object) - contains the following fields:
    • indices (Array) - the indices of objects in the original data
    • data - the value of the data prop.

Callbacks

onSetColorDomain (Function, optional)
  • Default: ([min, max]) => {}

This callback will be called when cell color domain has been calculated.

onSetElevationDomain (Function, optional)
  • Default: ([min, max]) => {}

This callback will be called when cell elevation domain has been calculated.

Sub Layers

The CPUGridLayer renders the following sublayers:

Source

modules/aggregation-layers/src/cpu-grid-layer

- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/gpu-grid-layer.html b/docs/api-reference/aggregation-layers/gpu-grid-layer.html index 45ab2ece6e4..d411c612db5 100644 --- a/docs/api-reference/aggregation-layers/gpu-grid-layer.html +++ b/docs/api-reference/aggregation-layers/gpu-grid-layer.html @@ -4,8 +4,8 @@ GPUGridLayer | deck.gl - - + +
@@ -17,7 +17,7 @@ This is useful when you want to render different data input with the same elevation scale for comparison.

elevationRange (Array, optional)
  • Default: [0, 1000]

Elevation scale output range

elevationScale (Number, optional) transition-enabled
  • Default: 1

Cell elevation multiplier. This is a handy property to scale the height of all cells without updating the data.

extruded (Boolean, optional)
  • Default: true

Whether to enable cell elevation. If set to false, all cell will be flat.

material (Object, optional)
  • Default: true

This is an object that contains material props for lighting effect applied on extruded polygons. Check the lighting guide for configurable settings.

colorAggregation (String, optional)
  • Default: 'SUM'

Defines the operation used to aggregate all data object weights to calculate a cell's color value. Valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. 'SUM' is used when an invalid value is provided.

getColorWeight and colorAggregation together determine the elevation value of each cell.

elevationAggregation (String, optional)
  • Default: 'SUM'

Defines the operation used to aggregate all data object weights to calculate a cell's elevation value. Valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. 'SUM' is used when an invalid value is provided.

getElevationWeight and elevationAggregation together determine the elevation value of each cell.

Data Accessors

getPosition (Function, optional)
  • Default: object => object.position

Method called to retrieve the position of each object.

getColorWeight (Function, optional) transition-enabled
  • Default: 1

The weight of a data object used to calculate the color value for a cell.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.
getElevationWeight (Function, optional) transition-enabled
  • Default: 1

The weight of a data object used to calculate the elevation value for a cell.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.

Differences compared to CPUGridLayer

Unsupported props

Due to the nature of GPU Aggregation implementation following CPUGridLayer props are not supported by this layer.

upperPercentile lowerPercentile elevationUpperPercentile, elevationLowerPercentile, getColorValue, getElevationValue, onSetColorDomain and onSetElevationDomain

Instead of getColorValue, getColorWeight and colorAggregation should be used. Instead of getElevationValue, getElevationWeight and elevationAggregation should be used. There is no alternate for all other unsupported props, if they are needed CPUGridLayer should be used instead of this layer.

Picking

When picking mode is hover, only the elevation value, color value of selected cell are included in picking result. Array of all objects that aggregated into that cell is not provided. For all other modes, picking results match with CPUGridLayer, for these cases data is aggregated on CPU to provide array of all objects that aggregated to the cell.

Source

modules/aggregation-layers/src/gpu-grid-layer

- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/grid-aggregation-layer.html b/docs/api-reference/aggregation-layers/grid-aggregation-layer.html index 117dfd0a32a..95df2fe43ad 100644 --- a/docs/api-reference/aggregation-layers/grid-aggregation-layer.html +++ b/docs/api-reference/aggregation-layers/grid-aggregation-layer.html @@ -4,14 +4,14 @@ GridAggregationLayer | deck.gl - - + +

GridAggregationLayer

This layer performs some common tasks required to perform aggregation to grid cells, especially it takes care of deciding CPU vs GPU aggregation, allocating resources for GPU aggregation and uploading results.

This in an abstract layer, subclassed form AggregationLayer, GPUGridLayer, ScreenGridLayer and ContourLayer are subclassed from this layer.

updateState()

During updateState(), it calls updateAggregationState() which sub classes must implement. During this method, sub classes must set following aggregation flags and aggregation params.

Aggregation Flags

  • gpuAggregation: When true aggregation happens on GPU, otherwise on CPU.
  • aggregationDataDirty : When true data is re-aggregated.
  • aggregationWeightsDirty : This flag is applicable only for CPU aggregation. When true, bin's aggregated values are re computed.

Aggregation Parameters

  • gridOffset : Grid's cell size in the format {xOffset, yOffset}.
  • projectPoints : Should be true when doing screen space aggregation, when false it implies world space aggregation.
  • attributes : Layer's current set of attributes which provide position and weights to CPU/GPU aggregators.
  • viewport : current viewport object.
  • posOffset : Offset to be added to object's position before aggregating.
  • boundingBox : Bounding box of the input data. Following are applicable for GPU aggregation only:
  • translation : [xTranslation, yTranslation], position translation to be applied on positions.
  • scaling : [xScale, yScale, flag], scaling to be applied on positions. When scaling not needed flag should be set to 0.
  • vertexCount : Number of objects to be aggregated.
  • moduleSettings : Object with set of fields required for applying shader modules.

updateResults()

When aggregation performed on CPU, aggregation result is in JS Array objects. Subclasses can override this method to consume aggregation data. This method is called with an object with following fields:

  • aggregationData (Float32Array) - Array containing aggregation data per grid cell. Four elements per grid cell in the format [value, 0, 0, count], where value is the aggregated weight value, up to 3 different weights. count is the number of objects aggregated to the grid cell.

  • maxMinData (Float32Array) - Array with four values in format, [maxValue, 0, 0, minValue], where maxValue is max of all aggregated cells.

  • maxData (Float32Array) - Array with four values in format, [maxValue, 0, 0, count], where maxValue is max of all aggregated cells and count is total number aggregated objects.

  • minData (Float32Array) - Array with four values in format, [minValue, 0, 0, count], where minValue is min of all aggregated cells and count is total number aggregated objects.

    NOTE: The goal is to match format of CPU aggregation results to that of GPU aggregation, so consumers of this data (Sublayers) don't have to change.

allocateResources()

Called with following arguments to allocated resources required to hold aggregation results.

  • numRow (Number) - Number of rows in the grid.
  • numCol (Number) - Number of columns in the grid.
- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/grid-layer.html b/docs/api-reference/aggregation-layers/grid-layer.html index c573e151041..4dd38be4df0 100644 --- a/docs/api-reference/aggregation-layers/grid-layer.html +++ b/docs/api-reference/aggregation-layers/grid-layer.html @@ -4,8 +4,8 @@ GridLayer | deck.gl - - + +
@@ -21,7 +21,7 @@ larger than the elevationUpperPercentile will be hidden.

elevationLowerPercentile (Number, optional) transition-enabled
  • Default: 0

Filter cells and re-calculate elevation by elevationLowerPercentile. Cells with elevation value smaller than the elevationLowerPercentile will be hidden.

colorScaleType (String, optional)
  • Default: 'quantize'

Scaling function used to determine the color of the grid cell, default value is 'quantize'. Supported Values are 'quantize', 'linear', 'quantile' and 'ordinal'.

fp64 (Boolean, optional)
  • Default: false

Whether the aggregation should be performed in high-precision 64-bit mode. Note that since deck.gl v6.1, the default 32-bit projection uses a hybrid mode that matches 64-bit precision with significantly better performance.

gpuAggregation (bool, optional)
  • Default: false

When set to true, aggregation is performed on GPU, provided other conditions are met, for more details check the GPU Aggregation section below. GPU aggregation can be a lot faster than CPU depending upon the number of objects and number of cells.

Note: GPU Aggregation is faster only when using large data sets. For smaller data sets GPU Aggregation could be potentially slower than CPU Aggregation.

material (Object, optional)
  • Default: true

This is an object that contains material props for lighting effect applied on extruded polygons. Check the lighting guide for configurable settings.

colorAggregation (String, optional)
  • Default: 'SUM'

Defines the operation used to aggregate all data object weights to calculate a cell's color value. Valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. 'SUM' is used when an invalid value is provided.

getColorWeight and colorAggregation together determine the elevation value of each cell. If the getColorValue prop is supplied, they will be ignored. Note that supplying getColorValue disables GPU aggregation.

Example 1 : Using count of data elements that fall into a cell to encode the its color
  • Using getColorValue

...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getColorValue: points => points.length,
...
});
  • Using getColorWeight and colorAggregation

...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getColorWeight: point => 1,
colorAggregation: 'SUM'
...
});
Example 2 : Using mean value of 'SPACES' field of data elements to encode the color of the cell
  • Using getColorValue
function getMean(points) {
return points.reduce((sum, p) => sum += p.SPACES, 0) / points.length;
}
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getColorValue: getMean,
...
});
  • Using getColorWeight and colorAggregation
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getColorWeight: point => point.SPACES,
colorAggregation: 'SUM'
...
});

If your use case requires aggregating using an operation that is not one of 'SUM', 'MEAN', 'MAX' and 'MIN', getColorValue should be used to define such custom aggregation function. In those cases GPU aggregation is not supported.

elevationAggregation (String, optional)
  • Default: 'SUM'

Defines the operation used to aggregate all data object weights to calculate a cell's elevation value. Valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. 'SUM' is used when an invalid value is provided.

getElevationWeight and elevationAggregation together determine the elevation value of each cell. If the getElevationValue prop is supplied, they will be ignored. Note that supplying getElevationValue disables GPU aggregation.

Example 1 : Using count of data elements that fall into a cell to encode the its elevation
  • Using getElevationValue
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getElevationValue: points => points.length
...
});
  • Using getElevationWeight and elevationAggregation
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getElevationWeight: point => 1,
elevationAggregation: 'SUM'
...
});
Example 2 : Using maximum value of 'SPACES' field of data elements to encode the elevation of the cell
  • Using getElevationValue
function getMax(points) {
return points.reduce((max, p) => p.SPACES > max ? p.SPACES : max, -Infinity);
}
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getElevationValue: getMax,
...
});
  • Using getElevationWeight and elevationAggregation
...
const layer = new CPUGridLayer({
id: 'my-grid-layer',
...
getElevationWeight: point => point.SPACES,
elevationAggregation: 'MAX'
...
});

If your use case requires aggregating using an operation that is not one of 'SUM', 'MEAN', 'MAX' and 'MIN', getElevationValue should be used to define such custom aggregation function. In those cases GPU aggregation is not supported.

getElevationValue (Function, optional) transition-enabled
  • Default: null

After data objects are aggregated into cells, this accessor is called on each cell to get the value that its elevation is based on. If supplied, this will override the effect of getElevationWeight and elevationAggregation props. Note that supplying this prop disables GPU aggregation.

Arguments:

  • objects (Array) - a list of objects whose positions fall inside this cell.
  • objectInfo (Object) - contains the following fields:
    • indices (Array) - the indices of objects in the original data
    • data - the value of the data prop.

Data Accessors

getPosition (Function, optional)
  • Default: object => object.position

Method called to retrieve the position of each object.

getColorWeight (Function, optional) transition-enabled
  • Default: 1

The weight of a data object used to calculate the color value for a cell.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.
getColorValue (Function, optional) transition-enabled
  • Default: null

After data objects are aggregated into cells, this accessor is called on each cell to get the value that its color is based on. If supplied, this will override the effect of getColorWeight and colorAggregation props. Note that supplying this prop disables GPU aggregation.

Arguments:

  • objects (Array) - a list of objects whose positions fall inside this cell.
  • objectInfo (Object) - contains the following fields:
    • indices (Array) - the indices of objects in the original data
    • data - the value of the data prop.
getElevationWeight (Function, optional) transition-enabled
  • Default: 1

The weight of a data object used to calculate the elevation value for a cell.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.

Callbacks

onSetColorDomain (Function, optional)
  • Default: ([min, max]) => {}

This callback will be called when cell color domain has been calculated.

onSetElevationDomain (Function, optional)
  • Default: ([min, max]) => {}

This callback will be called when cell elevation domain has been calculated.

GPU Aggregation

Performance Metrics

The following table compares the performance between CPU and GPU aggregations using random data:

#objectsCPU #iterations/secGPU #iterations/secNotes
25K535359GPU is 33% slower
100K119437GPU is 267% faster
1M12.7158GPU is 1144% faster

Numbers are collected on a 2016 15-inch Macbook Pro (CPU: 2.8 GHz Intel Core i7 and GPU: AMD Radeon R9 M370X 2 GB)

Fallback Cases

This layer performs aggregation on GPU when the gpuAggregation prop is set to true, but will fallback to CPU in the following cases:

Percentile Props

When following percentile props are set, it requires sorting of aggregated values, which cannot be supported when aggregating on GPU.

  • lowerPercentile, upperPercentile, elevationLowerPercentile and elevationUpperPercentile.

Color and Elevation Props

When colorScaleType props is set to a 'quantile' or 'ordinal', aggregation will fallback to CPU. For GPU Aggregation, use 'quantize', 'linear'.

Color Scale Type Props

When following percentile props are set, it requires sorting of aggregated values, which cannot be supported when aggregating on GPU.

  • lowerPercentile, upperPercentile, elevationLowerPercentile and elevationUpperPercentile.

Domain setting callbacks

When using GPU Aggregation, onSetColorDomain and onSetElevationDomain are not fired.

Sub Layers

The GridLayer renders the following sublayers:

Source

modules/aggregation-layers/src/grid-layer

- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/heatmap-layer.html b/docs/api-reference/aggregation-layers/heatmap-layer.html index 99f1160c464..4bbc05934ba 100644 --- a/docs/api-reference/aggregation-layers/heatmap-layer.html +++ b/docs/api-reference/aggregation-layers/heatmap-layer.html @@ -4,13 +4,13 @@ HeatmapLayer | deck.gl - - + +

HeatmapLayer

HeatmapLayer can be used to visualize spatial distribution of data. It internally implements Gaussian Kernel Density Estimation to render heatmaps. Note that this layer does not support all platforms; see "limitations" section below.

import DeckGL from '@deck.gl/react';
import {HeatmapLayer} from '@deck.gl/aggregation-layers';

function App({data, viewState}) {
/**
* Data format:
* [
* {COORDINATES: [-122.42177834, 37.78346622], WEIGHT: 10},
* ...
* ]
*/
const layer = new HeatmapLayer({
id: 'heatmapLayer',
data,
getPosition: d => d.COORDINATES,
getWeight: d => d.WEIGHT,
aggregation: 'SUM'
});

return <DeckGL viewState={viewState} layers={[layer]} />;
}

Installation

To install the dependencies from NPM:

npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers @deck.gl/aggregation-layers
import {HeatmapLayer} from '@deck.gl/aggregation-layers';
new HeatmapLayer({});

To use pre-bundled scripts:

<script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
<!-- or -->
<script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/aggregation-layers@^8.0.0/dist.min.js"></script>
new deck.HeatmapLayer({});

Properties

Inherits from all Base Layer and CompositeLayer properties.

Render Options

radiusPixels (Number, optional) transition-enabled
  • Default: 30

Radius of the circle in pixels, to which the weight of an object is distributed.

colorRange (Array, optional)

The color palette used in the heatmap, as an array of colors [color1, color2, ...]. Each color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

See the colorDomain section below for how weight values are mapped to colors in colorRange.

intensity (Number, optional) transition-enabled
  • Default: 1

Value that is multiplied with the total weight at a pixel to obtain the final weight. A value larger than 1 biases the output color towards the higher end of the spectrum, and a value less than 1 biases the output color towards the lower end of the spectrum.

threshold (Number, optional) transition-enabled
  • Default: 0.05

The HeatmapLayer reduces the opacity of the pixels with relatively low weight to create a fading effect at the edge. A larger threshold smoothens the boundaries of color blobs, while making pixels with low relative weight harder to spot (due to low alpha value).

threshold is defined as the ratio of the fading weight to the max weight, between 0 and 1. For example, 0.1 affects all pixels with weight under 10% of the max.

threshold is ignored when colorDomain is specified.

colorDomain (Array, optional) transition-enabled
  • Default: null

Controls how weight values are mapped to the colorRange, as an array of two numbers [minValue, maxValue].

When colorDomain is specified, a pixel with minValue is assigned the first color in colorRange, a pixel with maxValue is assigned the last color in colorRange, and any value in between is linearly interpolated. Pixels with weight less than minValue gradually fade out by reducing alpha, until 100% transparency representing 0. Pixels with weight more than maxValue are capped to the last color in colorRange.

  • If using aggregation: 'SUM', values in colorDomain are interpreted as weight per square meter.
  • If using aggregation: 'MEAN', values in colorDomain are interpreted as weight.

When this prop is not specified, the maximum value is automatically determined from the current viewport, and the domain is set to [maxValue * threshold, maxValue]. This default behavior ensures that the colors are distributed somewhat reasonably regardless of the data in display. However, as a result, the color at a specific location is dependent on the current viewport and any other data points within view. To obtain a stable color mapping (e.g. for displaying a legend), you need to provide a custom colorDomain.

aggregation (String, optional)
  • Default: 'SUM'

Operation used to aggregate all data point weights to calculate a pixel's color value. One of 'SUM' or 'MEAN'. 'SUM' is used when an invalid value is provided.

The weight of each data object is distributed to all the pixels in a circle centered at the object position. The weight that a pixel receives is inversely proportional to its distance from the center. In 'SUM' mode, pixels that fall into multiple circles will have the sum of all weights. In 'MEAN' mode, pixels that fall into multiple circles will have their weight calculated as the weighted average from all the neighboring data points. And the weight of the pixel determines its color.

weightsTextureSize (Number, optional)
  • Default: 2048

weightsTextureSize specifies the size of weight texture. Smaller texture sizes can improve rendering performance. Heatmap aggregation calculates the maximum weight value in the texture and the process can take 50-100 ms for 2048x2048 texture, but only 5-7ms for 512x512 texture. Smaller texture sizes lead to visible pixelation.

debounceTimeout (Number, optional)
  • Default: 500

debounceTimeout is an interval in milliseconds during which changes to the viewport don't trigger aggregation. Large datasets combined with a large radiusPixels can cause freezes during user interactions due to aggregation updates. Setting positive debounceTimeout delays aggregation updates and prevents freezes during the interaction. As a side effect, the user has to wait to see updated results after the end of the interaction.

Data Accessors

getPosition (Function, optional)
  • Default: object => object.position

Method called to retrieve the position of each point.

getWeight (Function, optional)
  • Default: 1

Method called to retrieve weight of each point. By default each point will use a weight of 1.

Limitations

The HeatmapLayer performs aggregation on the GPU. This feature is fully supported in evergreen desktop browsers, but limited in the following platforms due to partial WebGL support:

  • iOS Safari: WebGL context does not support rendering to a float texture. The layer therefore falls back to an 8-bit low-precision mode, where weights must be integers and the accumulated weights in any pixel cannot exceed 255.

Source

modules/aggregation-layers/src/heatmap-layer

- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/hexagon-layer.html b/docs/api-reference/aggregation-layers/hexagon-layer.html index 53a0027f42e..0551ed4281e 100644 --- a/docs/api-reference/aggregation-layers/hexagon-layer.html +++ b/docs/api-reference/aggregation-layers/hexagon-layer.html @@ -4,8 +4,8 @@ HexagonLayer | deck.gl - - + +
@@ -34,7 +34,7 @@ larger than the elevationUpperPercentile will be hidden.

elevationLowerPercentile (Number, optional) transition-enabled
  • Default: 0

Filter bins and re-calculate elevation by elevationLowerPercentile. Hexagons with elevation value smaller than the elevationLowerPercentile will be hidden.

colorScaleType (String, optional)
  • Default: 'quantize'

Scaling function used to determine the color of the grid cell, default value is 'quantize'. Supported Values are 'quantize', 'quantile' and 'ordinal'.

material (Object, optional)
  • Default: true

This is an object that contains material props for lighting effect applied on extruded polygons. Check the lighting guide for configurable settings.

colorAggregation (String, optional)
  • Default: 'SUM'

Defines the operation used to aggregate all data object weights to calculate a bin's color value. Valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. 'SUM' is used when an invalid value is provided.

getColorWeight and colorAggregation together determine the elevation value of each bin. If the getColorValue prop is supplied, they will be ignored.

Example 1 : Using count of data elements that fall into a bin to encode the its color
  • Using getColorValue
...
const layer = new HexagonLayer({
id: 'my-hexagon-layer',
...
getColorValue: points => points.length,
...
});
  • Using getColorWeight and colorAggregation
...
const layer = new HexagonLayer({
id: 'my-hexagon-layer',
...
getColorWeight: point => 1,
colorAggregation: 'SUM'
...
});
Example 2 : Using mean value of 'SPACES' field of data elements to encode the color of the bin
  • Using getColorValue
function getMean(points) {
return points.reduce((sum, p) => sum += p.SPACES, 0) / points.length;
}
...
const layer = new HexagonLayer({
id: 'my-hexagon-layer',
...
getColorValue: getMean,
...
});
  • Using getColorWeight and colorAggregation
...
const layer = new HexagonLayer({
id: 'my-hexagon-layer',
...
getColorWeight: point => point.SPACES,
colorAggregation: 'SUM'
...
});

If your use case requires aggregating using an operation that is not one of 'SUM', 'MEAN', 'MAX' and 'MIN', getColorValue should be used to define such custom aggregation function.

elevationAggregation (String, optional)
  • Default: 'SUM'

Defines the operation used to aggregate all data object weights to calculate a bin's elevation value. Valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. 'SUM' is used when an invalid value is provided.

getElevationWeight and elevationAggregation together determine the elevation value of each bin. If the getElevationValue prop is supplied, they will be ignored.

Example 1 : Using count of data elements that fall into a bin to encode the its elevation
  • Using getElevationValue
...
const layer = new HexagonLayer({
id: 'my-hexagon-layer',
...
getElevationValue: points => points.length,
...
});
  • Using getElevationWeight and elevationAggregation
...
const layer = new HexagonLayer({
id: 'my-hexagon-layer',
...
getElevationWeight: point => 1,
elevationAggregation: 'SUM'
...
});
Example 2 : Using maximum value of 'SPACES' field of data elements to encode the elevation of the bin
  • Using getElevationValue
function getMax(points) {
return points.reduce((max, p) => p.SPACES > max ? p.SPACES : max, -Infinity);
}
...
const layer = new HexagonLayer({
id: 'my-hexagon-layer',
...
getElevationValue: getMax,
...
});
  • Using getElevationWeight and elevationAggregation
...
const layer = new HexagonLayer({
id: 'my-hexagon-layer',
...
getElevationWeight: point => point.SPACES,
elevationAggregation: 'MAX'
...
});

If your use case requires aggregating using an operation that is not one of 'SUM', 'MEAN', 'MAX' and 'MIN', getElevationValue should be used to define such custom aggregation function.

Data Accessors

getPosition (Function, optional)
  • Default: object => object.position

Method called to retrieve the position of each object.

getColorWeight (Function, optional) transition-enabled
  • Default: 1

The weight of a data object used to calculate the color value for a bin.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.
getColorValue (Function, optional) transition-enabled
  • Default: null

After data objects are aggregated into bins, this accessor is called on each bin to get the value that its color is based on. If supplied, this will override the effect of getColorWeight and colorAggregation props.

Arguments:

  • objects (Array) - a list of objects whose positions fall inside this cell.
  • objectInfo (Object) - contains the following fields:
    • indices (Array) - the indices of objects in the original data
    • data - the value of the data prop.
getElevationWeight (Function, optional) transition-enabled
  • Default: 1

The weight of a data object used to calculate the elevation value for a bin.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.
getElevationValue (Function, optional) transition-enabled
  • Default: null

After data objects are aggregated into bins, this accessor is called on each bin to get the value that its elevation is based on. If supplied, this will override the effect of getElevationWeight and elevationAggregation props.

Arguments:

  • objects (Array) - a list of objects whose positions fall inside this cell.
  • objectInfo (Object) - contains the following fields:
    • indices (Array) - the indices of objects in the original data
    • data - the value of the data prop.

Callbacks

onSetColorDomain (Function, optional)
  • Default: ([min, max]) => {}

This callback will be called when bin color domain has been calculated.

onSetElevationDomain (Function, optional)
  • Default: ([min, max]) => {}

This callback will be called when bin elevation domain has been calculated.

Sub Layers

The HexagonLayer renders the following sublayers:

  • hexagon-cell - a ColumnLayer rendering the aggregated columns.

Source

modules/aggregation-layers/src/hexagon-layer

- - + + \ No newline at end of file diff --git a/docs/api-reference/aggregation-layers/screen-grid-layer.html b/docs/api-reference/aggregation-layers/screen-grid-layer.html index b117c08a1da..aa400241c4e 100644 --- a/docs/api-reference/aggregation-layers/screen-grid-layer.html +++ b/docs/api-reference/aggregation-layers/screen-grid-layer.html @@ -4,8 +4,8 @@ ScreenGridLayer | deck.gl - - + +
@@ -16,7 +16,7 @@ discrete color range. If not provided, the layer will set colorDomain to [1, max-of-all-cell-weights], You can control how the color of cells mapped to value of its weight by passing in an arbitrary color domain. This property is extremely handy when you want to render different data input with the same color mapping for comparison.

colorRange (Array, optional)
  • Default:

Specified as an array of 6 colors [color1, color2, ... color6]. Each color is an array of 3 or 4 values [R, G, B] or [R, G, B, A], representing intensities of Red, Green, Blue and Alpha channels. Each intensity is a value between 0 and 255. When Alpha not provided a value of 255 is used. By default colorRange is set to colorbrewer 6-class YlOrRd.

NOTE: minColor and maxColor take precedence over colorDomain and colorRange, to use colorDomain and colorRange do not provide minColor and maxColor.

gpuAggregation (bool, optional)
  • Default: true

When set to true and browser supports GPU aggregation, aggregation is performed on GPU. GPU aggregation can be 10 to 20 times faster depending upon number of points and number of cells.

aggregation (String, optional)
  • Default: 'SUM'

Defines the type of aggregation operation, valid values are 'SUM', 'MEAN', 'MIN' and 'MAX'. When no value or an invalid value is set, 'SUM' is used as aggregation.

  • SUM : Grid cell contains sum of all weights that fall into it.
  • MEAN : Grid cell contains mean of all weights that fall into it.
  • MIN : Grid cell contains minimum of all weights that fall into it.
  • MAX : Grid cell contains maximum of all weights that fall into it.

Data Accessors

getPosition (Function, optional)
  • Default: object => object.position

Method called to retrieve the position of each object.

getWeight (Function, optional)
  • Default: 1

The weight of each object.

  • If a number is provided, it is used as the weight for all objects.
  • If a function is provided, it is called on each object to retrieve its weight.

Source

modules/aggregation-layers/src/screen-grid-layer

- - + + \ No newline at end of file diff --git a/docs/api-reference/arcgis/deck-layer.html b/docs/api-reference/arcgis/deck-layer.html index 470e09cef44..973a0bd19f7 100644 --- a/docs/api-reference/arcgis/deck-layer.html +++ b/docs/api-reference/arcgis/deck-layer.html @@ -4,13 +4,13 @@ DeckLayer | deck.gl - - + +

DeckLayer

This class inherits from the ArcGIS Layer class and can be added to maps created with the ArcGIS API for JavaScript.

At the moment, DeckLayer only supports 2D integration.

Usage

import {DeckLayer} from '@deck.gl/arcgis';
import {ScatterplotLayer} from '@deck.gl/layers';
import ArcGISMap from '@arcgis/core/Map';
import MapView from '@arcgis/core/views/MapView';

const layer = new DeckLayer({
'deck.layers': [
new ScatterplotLayer({
data: [
{position: [0.119, 52.205]}
],
getPosition: d => d.position,
getColor: [255, 0, 0],
radiusMinPixels: 20
})
]
});

const mapView = new MapView({
container: "viewDiv",
map: new ArcGISMap({
basemap: "dark-gray-vector",
layers: [layer]
}),
center: [0.119, 52.205],
zoom: 5
});

Constructor

new DeckLayer(props);

Inherits all properties from the base Layer class.

Property names that start with deck. are forwarded to a Deck instance. The following Deck props are supported:

  • deck.layers
  • deck.layerFilter
  • deck.parameters
  • deck.effects
  • deck.pickingRadius
  • deck.onBeforeRender
  • deck.onAfterRender
  • deck.onClick
  • deck.onHover
  • deck.onDragStart
  • deck.onDrag
  • deck.onDragEnd
  • deck.onError
  • deck.debug
  • deck.drawPickingColors
  • deck.getCursor
  • deck.getTooltip

Members

deck

An ArcGIS Accessor that stores Deck props. The props can be updated after the layer construction:

// Update deck layers
layer.deck.layers = [...]);

// Update multiple deck props
layer.deck.set({
layers: [...],
pickingRadius: 5,
...
});
- - + + \ No newline at end of file diff --git a/docs/api-reference/arcgis/deck-renderer.html b/docs/api-reference/arcgis/deck-renderer.html index 1c22f0dbf27..6b450b6f37a 100644 --- a/docs/api-reference/arcgis/deck-renderer.html +++ b/docs/api-reference/arcgis/deck-renderer.html @@ -4,14 +4,14 @@ DeckRenderer | deck.gl - - + +

DeckRenderer

This class is an experimental implementation of the ArcGIS ExternalRenderer interface and can be added to 3D views of maps created with the ArcGIS API for JavaScript.

Usage

import {DeckRenderer} from '@deck.gl/arcgis';
import {ScatterplotLayer} from '@deck.gl/layers';
import ArcGISMap from '@arcgis/core/Map';
import SceneView from '@arcgis/core/views/SceneView';
import * as externalRenderers from '@arcgis/core/views/3d/externalRenderers';

const sceneView = new SceneView({
container: 'viewDiv',
map: new ArcGISMap({
basemap: 'dark-gray-vector'
}),
camera: {
position: {x: -74, y: 40.65, z: 5000},
heading: 180,
tilt: 30
},
viewingMode: 'local'
});

const renderer = new DeckRenderer(sceneView, {
layers: [
new ScatterplotLayer({
data: [
{position: [0.119, 52.205]}
],
getPosition: d => d.position,
getColor: [255, 0, 0],
radiusMinPixels: 20
})
]
});

externalRenderers.add(sceneView, renderer);

Constructor

new DeckRenderer(sceneView, props)
  • sceneView (SceneView) - the view to use this renderer with. viewingMode must be set to 'local'.

  • props (Object) - forwarded to a Deck instance. The following Deck props are supported:

  • layers

  • layerFilter

  • parameters

  • effects

  • pickingRadius

  • onBeforeRender

  • onAfterRender

  • onClick

  • onHover

  • onDragStart

  • onDrag

  • onDragEnd

  • onError

  • debug

  • drawPickingColors

  • getCursor

  • getTooltip

Members

deck

An ArcGIS Accessor that stores Deck props. The props can be updated after the layer construction:

// Update deck layers
layer.deck.layers = [...]);

// Update multiple deck props
layer.deck.set({
layers: [...],
pickingRadius: 5,
...
});
- - + + \ No newline at end of file diff --git a/docs/api-reference/arcgis/load-arcgis-modules.html b/docs/api-reference/arcgis/load-arcgis-modules.html index 5ca2dc69f5b..b91c8267ef6 100644 --- a/docs/api-reference/arcgis/load-arcgis-modules.html +++ b/docs/api-reference/arcgis/load-arcgis-modules.html @@ -4,13 +4,13 @@ loadArcGISModules | deck.gl - - + +

loadArcGISModules

This utility function initializes the classes in this module by loading ArcGIS dependencies. Optionally, it can also load additional dependencies from the esri namespace.

Usage

import {loadArcGISModules} from '@deck.gl/arcgis';

loadArcGISModules(['esri/Map', 'esri/views/MapView'], {version: '4.21'})
.then(({DeckLayer, DeckRenderer, modules}) => {
const [ArcGISMap, MapView] = modules;

const layer = new DeckLayer({
'deck.layers': [
new ScatterplotLayer({
data: [
{position: [0.119, 52.205]}
],
getPosition: d => d.position,
getColor: [255, 0, 0],
radiusMinPixels: 20
})
]
});

const mapView = new MapView({
container: "viewDiv",
map: new ArcGISMap({
basemap: "dark-gray-vector",
layers: [layer]
}),
center: [0.119, 52.205],
zoom: 5
});
});

Arguments:

loadArcGISModules(modules, loadScriptOptions);
  • modules (Array, optional) - Array of esri modules to load, passed to esri-loader's loadModules
  • loadScriptOptions (Object, optional) - esri-loader options

Returns: a promise that resolves to an object with the following fields:

  • DeckLayer
  • DeckRenderer
  • modules (Array) - if the modules argument was specified, will represent an array of the resolved objects
- - + + \ No newline at end of file diff --git a/docs/api-reference/arcgis/overview.html b/docs/api-reference/arcgis/overview.html index d6049914524..f46fee28bf3 100644 --- a/docs/api-reference/arcgis/overview.html +++ b/docs/api-reference/arcgis/overview.html @@ -4,15 +4,15 @@ @deck.gl/arcgis | deck.gl - - + +

@deck.gl/arcgis

Use deck.gl layers with the ArcGIS API for JavaScript.

The functionality exported by this module must be loaded asynchronously using the loader function loadArcGISModules. This function can be used to load any module that ships with the ArcGIS API for JavaScript, plus an additional arcGIS module that acts as an interface between deck.gl and ArcGIS.

2D integration with MapView is supported by the DeckLayer class.

3D integration with SceneView is experimental: see the DeckRenderer class.

Installation

Include the Standalone Bundle

<script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
<!-- or -->
<script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/arcgis@^1.0.0/dist.min.js"></script>
<!-- usage -->
<script type="text/javascript">
deck.loadArcGISModules();
</script>

Note that only loadArcGISModules is expoted by the standalone bundle. DeckLayer and DeckRenderer are avalaible when loadArcGISModule() is resolved.

Install from NPM

npm install deck.gl @arcgis/core
# or
npm install @deck.gl/core @deck.gl/arcgis @arcgis/core
// if using with esri-loader
import {loadArcGISModules} from '@deck.gl/arcgis';
// if using with @arcgis/core
import {DeckLayer} from '@deck.gl/arcgis';

The integration classes (DeckLayer and DeckRenderer) extend ArcGIS core classes, therefore they are only available when ArcGIS is available. To load ArcGIS, applications have two options: from AMD modules on CDN or from locally installed ES modules. It is important that the Deck classes are imported in the same way as the ArcGIS dependency.

If the application is importing the ArcGIS Map via AMD modules (esri-loader), then the Deck classes should be accessed by calling loadArcGISModules. This is the case if you are using @esri/react-arcgis, which utilizes esri-loader under the hood.

If the application is importing the ArcGIS Map from locally installed ES modules (@arcgis/core), then the Deck classes should be imported directly from @deck.gl/arcgis.

Supported Features and Limitations

Supported deck.gl features:

  • Layers
  • Effects
  • Attribute transitions
  • Auto-highlighting
  • onHover and onClick callbacks

Not supported features:

  • Multiple views
  • Controller
  • React integration
- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/basemap.html b/docs/api-reference/carto/basemap.html index 8a393ce9c20..8127f76da15 100644 --- a/docs/api-reference/carto/basemap.html +++ b/docs/api-reference/carto/basemap.html @@ -4,13 +4,13 @@ BASEMAP | deck.gl - - + +

BASEMAP

CARTO basemaps are available and they can be used without a token.

Ensure you follow the Terms and Conditions when using them.

Usage

React

Important Note: Mapbox-GL-JS v2.0 changed to a license that requires an API key for loading the library, which will prevent you from using react-map-gl ( a higher level library). They have an in-depth guide about it here.

In short, if you want to use the library without a Mapbox token, then you have two options: use a react-map-gl version less than 6.0 (npm i react-map-gl@5), or substitute mapbox-gl with a fork.

To install the dependencies from NPM:

npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers @deck.gl/carto
import {DeckGL} from '@deck.gl/react';
import {StaticMap} from 'react-map-gl';
import {BASEMAP} from '@deck.gl/carto';
<DeckGL initialViewState={INITIAL_VIEW_STATE} controller={true} layers={layers}>
<StaticMap mapStyle={BASEMAP.POSITRON} />
</DeckGL>;

Standalone

To use pre-bundled scripts:

<script src="https://unpkg.com/deck.gl@^8.7.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^8.7.0/dist.min.js"></script>

<!-- or -->
<script src="https://unpkg.com/@deck.gl/core@^8.7.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/layers@^8.7.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/geo-layers@^8.7.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^8.7.0/dist.min.js"></script>
const deckgl = new deck.DeckGL({
container: 'map',
mapStyle: deck.carto.BASEMAP.POSITRON,
initialViewState: {
latitude: 0,
longitude: 0,
zoom: 1
},
controller: true
});

Supported basemaps

There are several basemaps available today:

  • POSITRON
  • DARK_MATTER
  • VOYAGER
  • POSITRON_NOLABELS
  • DARK_MATTER_NOLABELS
  • VOYAGER_NOLABELS
NAMEPREVIEWSTYLE URL
POSITRONhttps://basemaps.cartocdn.com/gl/positron-gl-style/style.json
DARK_MATTERhttps://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json
VOYAGERhttps://basemaps.cartocdn.com/gl/voyager-gl-style/style.json
POSITRON_NOLABELShttps://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json
DARK_MATTER_NOLABELShttps://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json
VOYAGER_NOLABELShttps://basemaps.cartocdn.com/gl/voyager-nolabels-gl-style/style.json
- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/data-sources.html b/docs/api-reference/carto/data-sources.html index d0590d6a75c..1a2cb41cdc4 100644 --- a/docs/api-reference/carto/data-sources.html +++ b/docs/api-reference/carto/data-sources.html @@ -4,13 +4,13 @@ Data Sources | deck.gl - - + +

Data Sources

To ease interacting with the CARTO platform, the CARTO deck.gl module includes a number of functions, which simplify the use of fetching your data from CARTO. At a high level these can be thought of as wrappers around the browsers fetch function, except that rather than passing a URL, options that specify the data in the CARTO are used.

Overview

The data source functions are a compact way to describe the data that you want to fetch. For example, to fetch a table from a data warehouse from the connection carto_dw:

import {vectorTableSource} from '@deck.gl/carto';
const data = vectorTableSource({
accessToken: 'XXX',
connectionName: 'carto_dw',
tableName: 'carto-demo-data.demo_tables.chicago_crime_sample',
})

Promise API

All data source functions return a Promise, which can be resolved to obtain the actual Tilejson. However, as the core deck.gl Layer prop supports Promises, it is often not necessary to resolve or await the Promise and the data source can be directly passed to the data prop:

import {H3TileLayer, h3TilesetSource} from '@deck.gl/carto';
new H3TileLayer({
data: h3TilesetSource({
accessToken: 'XXX',
connectionName: 'carto_dw',
tableName: 'carto-demo-data.demo_tables.h3_data'
}),

getFillColor: d => d.properties.color
});

Types

All the data source functions are fully typed, to aid in providing the correct parameters and working correctly with the return value.

Caching

The dataSource functions have an internal cache, which avoids fetching data from the server if the parameters have not changed. Thus they can be used, for example, in React render() functions without needing memoization.

Available Data Sources

All data source functions take the following global options:

type SourceOptions = {
accessToken: string;
connectionName: string;
apiBaseUrl?: string;
clientId?: string;
headers?: Record<string, string>;
mapsUrl?: string;
};

In addition, the following options are supported on each source:

vectorTableSource

type VectorTableSourceOptions = {
columns?: string[];
spatialDataColumn?: string;
tableName: string;
}

vectorQuerySource

type VectorQuerySourceOptions = {
spatialDataColumn?: string;
sqlQuery: string;
queryParameters: QueryParameters;
}

vectorTilesetSource

type VectorTilesetSourceOptions = {
tableName: string;
}

h3TableSource

type H3TableSourceOptions = {
aggregationExp: string;
aggregationResLevel?: number;
columns?: string[];
spatialDataColumn?: string;
tableName: string;
}

h3QuerySource

type H3QuerySourceOptions = {
aggregationExp: string;
aggregationResLevel?: number;
spatialDataColumn?: string;
sqlQuery: string;
queryParameters: QueryParameters;
}

h3TilesetSource

type H3TilesetSourceOptions = {
tableName: string;
}

quadbinTableSource

type QuadbinTableSourceOptions = {
aggregationExp: string;
aggregationResLevel?: number;
columns?: string[];
spatialDataColumn?: string;
tableName: string;
}

quadbinQuerySource

type QuadbinQuerySourceOptions = {
aggregationExp: string;
aggregationResLevel?: number;
spatialDataColumn?: string;
sqlQuery: string;
queryParameters: QueryParameters;
}

quadbinTilesetSource

type QuadbinTilesetSourceOptions = {
tableName: string;
}

rasterTilesetSource (Experimental)

type RasterTilesetSourceOptions = {
tableName: string;
}

boundaryTableSource (Experimental)

type BoundaryTableSourceOptions = {
tilesetTableName: string;
columns?: string[];
matchingColumn?: string;
propertiesTableName: string;
}

boundaryQuerySource (Experimental)

type BoundaryQuerySourceOptions = {
tilesetTableName: string;
matchingColumn?: string;
propertiesSqlQuery: string;
queryParameters?: QueryParameters;
}

QueryParameters

QueryParameters are used to parametrize SQL queries. The format depends on the source's provider, some examples:

PostgreSQL and Redshift:

vectorQuerySource({
...,
sqlQuery: `select * from users where username=$1`,
queryParameters: ['my-name']
})

BigQuery positional:

vectorQuerySource({
...,
sqlQuery: `select * from users where username=$1`,
queryParameters: ['my-name']
})

BigQuery named parameters:

vectorQuerySource({
...,
sqlQuery: `select * from users where username=@username`,
queryParameters: { username: 'my-name' }
})

Snowflake positional :

vectorQuerySource({
...,
sqlQuery: `select * from users where username=?`,
queryParameters: ['my-name']
});

or

vectorQuerySource({
data: `select * from users where username=:1`,
queryParameters: ['my-name']
});

Databricks ODBC

vectorQuerySource({
...
data: `select * from users where username=?`,
queryParameters: ['my-name']
});
- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/fetch-map.html b/docs/api-reference/carto/fetch-map.html index a09129f6309..770ff42f8ad 100644 --- a/docs/api-reference/carto/fetch-map.html +++ b/docs/api-reference/carto/fetch-map.html @@ -4,13 +4,13 @@ fetchMap | deck.gl - - + +

fetchMap

CARTO Builder is a powerful tool for designing map visualizations. With the fetchMap function, you can easily instantiate layers configured in Builder for use with deck.gl. It is available starting with CARTO Maps API version v3 and deck.gl 8.7.

Loading a Builder map with deck.gl

Usage

Static display of a CARTO map

import {Deck} from '@deck.gl/core';
import {fetchMap} from '@deck.gl/carto';

const cartoMapId = 'ff6ac53f-741a-49fb-b615-d040bc5a96b8';
fetchMap({cartoMapId}).then(map => new Deck(map));

Integration with CARTO basemaps

import mapboxgl from 'mapbox-gl';

fetchMap({cartoMapId}).then(({initialViewState, mapStyle, layers}) => {
// Add Mapbox GL for the basemap. It's not a requirement if you don't need a basemap.
const MAP_STYLE = `https://basemaps.cartocdn.com/gl/${mapStyle.styleType}-gl-style/style.json`;
const deckgl = new deck.DeckGL({
container: 'container',
controller: true,
mapStyle: MAP_STYLE,
initialViewState,
layers
});
});

Parameters

const map = await fetchMap({cartoMapId, credentials, autoRefresh, onNewData});
cartoMapId (String)

Required. Identifier of map created in CARTO Builder.

credentials (Object, optional)

CARTO Credentials to use in API requests.

headers (Object, optional)

Custom headers to include in the map instantiation requests.

autoRefresh (Number, optional)

Interval in seconds at which to autoRefresh the data. If provided, onNewData must also be provided.

onNewData (Function, Optional)

Callback function that will be invoked whenever data in layers is changed. If provided, autoRefresh must also be provided.

Return value

When invoked with a given cartoMapId, fetchMap will retrieve the information about the map from CARTO, generate appropriate layers and populate them with data. The properties of the map are as follows:

id (String)

The cartoMapId.

title (String)

The title given to the map in CARTO Builder.

description (String)

The description given to the map in CARTO Builder.

createdAt (String)

When the map was created.

updatedAt (String)

When the map was last updated.

initialViewState (String)

The view state.

mapStyle (String)

An identifier describing the basemap configured in CARTO Builder.

layers (Array)

A collection of deck.gl layers.

stopAutoRefresh (Function)

A function to invoke to stop auto-refreshing. Only present if autoRefresh option was provided to fetchMap.

Auto-refreshing

With dynamic data sources, the autoRefresh option to fetchMap makes it simple to create an live-updating map.

const deck = new Deck({canvas: 'deck-canvas'});
const mapConfiguration = {
autoRefresh: 5,
cartoMapId,
onNewData: ({layers}) => {
deck.setProps({layers});
}
};

const {initialViewState, layers, stopAutoRefresh} = await fetchMap(mapConfiguration);
deck.setProps({controller: true, initialViewState, layers});

buttonElement.addEventListener('click', () => {
stopAutoRefresh();
});
- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/h3-tile-layer.html b/docs/api-reference/carto/h3-tile-layer.html index 40347a3bd15..2b8fac6c749 100644 --- a/docs/api-reference/carto/h3-tile-layer.html +++ b/docs/api-reference/carto/h3-tile-layer.html @@ -4,13 +4,13 @@ H3TileLayer | deck.gl - - + +

H3TileLayer

H3TileLayer is a layer for visualizing tiled data described using the H3 Spatial Index.

Usage

import DeckGL from '@deck.gl/react';
import {H3TileLayer, h3QuerySource} from '@deck.gl/carto';

function App({viewState}) {
const data = h3QuerySource({
accessToken: 'XXX',
connectionName: 'carto_dw',
sqlQuery: 'select * from carto-demo-data.demo_tables.chicago_crime_sample',
});

const layer = new H3TileLayer({
data,
getFillColor: d => d.properties.color
})

return <DeckGL viewState={viewState} layers={[layer]} />;
}

Installation

To install the dependencies from NPM:

npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers @deck.gl/carto
import {H3TileLayer} from '@deck.gl/carto';
new H3TileLayer({});

To use pre-bundled scripts:

<script src="https://unpkg.com/deck.gl@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^9.0.0/dist.min.js"></script>

<!-- or -->
<script src="https://unpkg.com/@deck.gl/core@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/layers@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/geo-layers@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^9.0.0/dist.min.js"></script>
new deck.carto.H3TileLayer({});

Properties

Inherits all properties from H3HexagonLayer and TileLayer, with exceptions indicated below.

data (TilejsonResult)

Required. A valid TilejsonResult object.

Use one of the following Data Sources to fetch this from the CARTO API:

Source

modules/carto/src/layers/h3-tile-layer.ts

- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/overview.html b/docs/api-reference/carto/overview.html index 15b8bf70dc3..eaac28cb72a 100644 --- a/docs/api-reference/carto/overview.html +++ b/docs/api-reference/carto/overview.html @@ -4,13 +4,13 @@ @deck.gl/carto | deck.gl - - + +

@deck.gl/carto

Deck.gl is the preferred and official solution for creating modern geospatial web applications using CARTO Location Intelligence platform.

With deck.gl and the CARTO platform you can directly access spatial datasets and tilesets that are hosted in your current cloud data warehouse. CARTO provides seamless integrations with Google BigQuery, Amazon Redshift, Snowflake, Databricks and PostgreSQL-compatible databases, eliminating the need to move your data into CARTO.

The platform integrates with the CARTO Maps API to:

  • Provide a geospatial backend storage for your geospatial data.
  • Visualize large datasets overcoming browser memory limitations.
  • Provide an SQL spatial interface to work directly with your data.

Install package

npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers @deck.gl/carto

Usage

Automatically create layers configured in CARTO Builder

import {Deck} from '@deck.gl/core';
import {fetchMap} from '@deck.gl/carto';

const cartoMapId = 'ff6ac53f-741a-49fb-b615-d040bc5a96b8';
fetchMap({cartoMapId}).then(map => new Deck(map));

Custom layers connected to CARTO datasource

import DeckGL from '@deck.gl/react';
import {VectorTileLayer, vectorQuerySource} from '@deck.gl/carto';

function App() {
const data = vectorQuerySource({
accessToken: 'XXX',
connectionName: 'carto_dw',
sqlQuery: 'SELECT * FROM cartobq.testtables.points_10k',
});

const layer = new VectorTileLayer({
data,
pointRadiusMinPixels: 2,
getLineColor: [0, 0, 0, 200],
getFillColor: [238, 77, 90],
lineWidthMinPixels: 1
});

return <DeckGL layers={[layer]} />;
}

Examples

You can view a collection of working examples on the CARTO documentation website.

CARTO Layers

The CARTO module contains a number of custom layers which can be used to visualize the data, which work in conjunction with the data source functions:

CARTO Data sources

There are a number of data source functions for accessing data from the CARTO platform. These provide a simple way to fetch data from the CARTO platform, which can then be used with deck.gl layers.

Authentication

When defining a data source it is necessary to provide a:

Support for other deck.gl layers

The CARTO module includes a collection of layers for easy visualization of data from the CARTO platfrom. For performace and scalability, this data is served as tiles.

It is also straightforward to request data directly using the CARTO SQL API. It can then be integrated with other deck.gl layers, for example:

import DeckGL from '@deck.gl/react';
import {GeoJsonLayer} from '@deck.gl/layers';
import {query} from '@deck.gl/carto';

function App() {
const data = query({
accessToken: 'XXX',
connectionName: 'carto_dw',
sqlQuery: 'SELECT * FROM cartobq.testtables.points_10k',
});

const layer = new ScatterplotLayer({
data,
dataTransform: data => data.rows,
getPosition: d => d.geom.coordinates,
getRadius: d => d.size
});

return <DeckGL layers={[layer]} />;
}
- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/quadbin-tile-layer.html b/docs/api-reference/carto/quadbin-tile-layer.html index d99426e559d..486851497f5 100644 --- a/docs/api-reference/carto/quadbin-tile-layer.html +++ b/docs/api-reference/carto/quadbin-tile-layer.html @@ -4,13 +4,13 @@ QuadbinTileLayer | deck.gl - - + +

QuadbinTileLayer

QuadbinTileLayer is a layer for visualizing tiled data described using the Quadbin Spatial Index.

Usage

import DeckGL from '@deck.gl/react';
import {QuadbinTileLayer, quadbinTilesetSource} from '@deck.gl/carto';

function App({viewState}) {
const data = quadbinTilesetSource({
accessToken: 'XXX',
connectionName: 'carto_dw',
tableName: 'carto-demo-data.demo_tilesets.quadbin'
});

const layer = new QuadbinTileLayer({
data,
getFillColor: d => d.properties.color
})

return <DeckGL viewState={viewState} layers={[layer]} />;
}

Installation

To install the dependencies from NPM:

npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers @deck.gl/carto
import {QuadbinTileLayer} from '@deck.gl/carto';
new QuadbinTileLayer({});

To use pre-bundled scripts:

<script src="https://unpkg.com/deck.gl@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^9.0.0/dist.min.js"></script>

<!-- or -->
<script src="https://unpkg.com/@deck.gl/core@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/layers@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/geo-layers@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^9.0.0/dist.min.js"></script>
new deck.carto.QuadbinTileLayer({});

Properties

Inherits all properties from QuadkeyLayer and TileLayer, with exceptions indicated below.

data (TilejsonResult)

Required. A valid TilejsonResult object.

Use one of the following Data Sources to fetch this from the CARTO API:

Data Accessors

getQuadbin (Function, optional)

Note that the getQuadkey accessor is replaced with getQuadbin.

Called for each data object to retrieve the quadbin bigint identifier.

  • default: object => object.quadbin

Source

modules/carto/src/layers/quadbin-tile-layer.ts

- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/raster-tile-layer.html b/docs/api-reference/carto/raster-tile-layer.html index d95527343a5..1474ae93787 100644 --- a/docs/api-reference/carto/raster-tile-layer.html +++ b/docs/api-reference/carto/raster-tile-layer.html @@ -4,13 +4,13 @@ RasterTileLayer (Experimental) | deck.gl - - + +

RasterTileLayer (Experimental)

RasterTileLayer is a layer for visualizing tiled raster data.

Usage

import DeckGL from '@deck.gl/react';
import {RasterTileLayer, rasterTilesetSource} from '@deck.gl/carto';

function App({viewState}) {
const data = rasterTilesetSource({
accessToken: 'XXX',
connectionName: 'carto_dw',
tableName: 'cartobq.public_account.temperature_raster'
});

const layer = new RasterTileLayer({
data,
getFillColor: d => {
const {band_1} = d.properties;
return [10 * (band_1 - 20), 0, 300 - 5 * band_1];
}
})

return <DeckGL viewState={viewState} layers={[layer]} />;
}

Installation

To install the dependencies from NPM:

npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers @deck.gl/carto
import {RasterTileLayer} from '@deck.gl/carto';
new RasterTileLayer({});

To use pre-bundled scripts:

<script src="https://unpkg.com/deck.gl@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^9.0.0/dist.min.js"></script>

<!-- or -->
<script src="https://unpkg.com/@deck.gl/core@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/layers@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/geo-layers@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^9.0.0/dist.min.js"></script>
new deck.carto.RasterTileLayer({});

Properties

Inherits all properties from ColumnLayer and TileLayer, with exceptions indicated below.

data (TilejsonResult)

Required. A valid TilejsonResult object.

Use the rasterTilesetSource to fetch this from the CARTO API.

Source

modules/carto/src/layers/raster-tile-layer.ts

- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/styles.html b/docs/api-reference/carto/styles.html index b04174e17fa..a7071562967 100644 --- a/docs/api-reference/carto/styles.html +++ b/docs/api-reference/carto/styles.html @@ -4,13 +4,13 @@ Styles | deck.gl - - + +

Styles

Helper functions to create data-driven map visualizations.

These helpers take advantage of CARTOColors, custom color schemes built on top of well-known standards for color use on maps, with next generation enhancements for the web and CARTO basemaps.

colorBins

Helper function for quickly creating a color bins style based on d3 scaleThreshold.

Data values of each attribute are rounded down to the nearest value in the domain and are then styled with the corresponding color.

new CartoLayer({
type: MAP_TYPES.QUERY,
data: 'SELECT the_geom_webmercator, gn_pop FROM populated_places',
getFillColor: colorBins({
attr: 'gn_pop',
domain: [1e5, 2e5, 3e5],
colors: 'Teal'
})
});

In this example, using Teal of length domain.length + 1, the range/color equivalence is:

[, 1e5)     -> Teal[0]
[1e5, 2e5) -> Teal[1]
[2e5, 3e5) -> Teal[2]
[3e5,] -> Teal[3]

Arguments

attr (String)

Attribute or column to symbolize by.

domain (Array)

Assign manual class break values.

colors (String | Array, optional)

Color assigned to each domain value.

  • String: A valid named CARTOColors palette.
  • Array: Array of colors in RGBA [ [r, g, b, [a]] ].

Default: PurpOr

nullColor (Array, optional)

Color for null values.

Default: [204, 204, 204]

colorCategories

Helper function for quickly creating a color category style.

Data values of each attribute listed in the domain are mapped one to one with corresponding colors in the range.

new CartoLayer({
type: MAP_TYPES.QUERY,
data: 'SELECT the_geom_webmercator, type FROM ne_10m_airports',
getFillColor: colorCategories({
attr: 'type',
domain: ['mid', 'major', 'military mid', 'mid and military', 'major and military'],
colors: 'Bold'
})
});

Arguments

attr (String)

Attribute or column to symbolize by.

domain (Array)

Category list. Must be a valid list of categories.

colors (String | Array, optional)

Color assigned to each domain value.

  • String: A valid named CARTOColors palette.
  • Array: Array of colors in RGBA [ [r, g, b, [a]] ].

Default: PurpOr

nullColor (Array, optional)

Color for null values.

Default: [204, 204, 204]

othersColor (Array, optional)

Fallback color for a category not correctly assigned.

Default: [119, 119, 119]

Color Continuous

Helper function for quickly creating a color continuous style.

Data values of each field are interpolated linearly across values in the domain and are then styled with a blend of the corresponding color in the range.

new CartoLayer({
type: MAP_TYPES.QUERY,
data: 'SELECT the_geom_webmercator, gn_pop FROM populated_places',
getFillColor: colorContinuous({
attr: 'gn_pop',
domain: [0, 1e5],
colors: 'BluYl'
})
});

Arguments

attr (String)

Attribute or column to symbolize by.

domain (Array)

Attribute domain to define the data range.

colors (String | Array, optional)

Color assigned to each domain value.

  • String: A valid named CARTOColors palette.
  • Array: Array of colors in RGBA [ [r, g, b, [a]] ].

Default: PurpOr

nullColor (Array, optional)

Color for null values.

Default: [204, 204, 204]

- - + + \ No newline at end of file diff --git a/docs/api-reference/carto/vector-tile-layer.html b/docs/api-reference/carto/vector-tile-layer.html index 2caffec2882..1f944f9f592 100644 --- a/docs/api-reference/carto/vector-tile-layer.html +++ b/docs/api-reference/carto/vector-tile-layer.html @@ -4,13 +4,13 @@ VectorTileLayer | deck.gl - - + +

VectorTileLayer

VectorTileLayer is a layer for visualizing tiled vector data. It inherits all the properties from the MVTLayer.

Usage

import DeckGL from '@deck.gl/react';
import {VectorTileLayer, vectorTableSource} from '@deck.gl/carto';

function App({viewState}) {
const data = vectorTableSource({
accessToken: 'XXX',
connectionName: 'carto_dw',
tableName: 'carto-demo-data.demo_tables.chicago_crime_sample',
});

const layer = new VectorTileLayer({
data,
pointRadiusMinPixels: 2,
getLineColor: [0, 0, 0, 200],
getFillColor: [238, 77, 90],
lineWidthMinPixels: 1
})

return <DeckGL viewState={viewState} layers={[layer]} />;
}

To install the dependencies from NPM:

npm install deck.gl
# or
npm install @deck.gl/core @deck.gl/layers @deck.gl/carto
import {VectorTileLayer} from '@deck.gl/carto';
new VectorTileLayer({});

To use pre-bundled scripts:

<script src="https://unpkg.com/deck.gl@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^9.0.0/dist.min.js"></script>

<!-- or -->
<script src="https://unpkg.com/@deck.gl/core@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/layers@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/geo-layers@^9.0.0/dist.min.js"></script>
<script src="https://unpkg.com/@deck.gl/carto@^9.0.0/dist.min.js"></script>
new deck.carto.VectorTileLayer({});

Properties

The properties of MVTLayer will be inherited.

data (TilejsonResult)

Required. A valid TilejsonResult object.

Use one of the following Data Sources to fetch this from the CARTO API:

Source

modules/carto/src/layers/vector-tile-layer.ts

- - + + \ No newline at end of file diff --git a/docs/api-reference/core/ambient-light.html b/docs/api-reference/core/ambient-light.html index 2bdebb6a9f8..518f5a31aa5 100644 --- a/docs/api-reference/core/ambient-light.html +++ b/docs/api-reference/core/ambient-light.html @@ -4,13 +4,13 @@ AmbientLight | deck.gl - - + +

AmbientLight

Create an ambient light source which illuminates all the objects equally. Ambient light comes from all directions, adding ambient light ensures that object colors are rendered but does not show structure in 3D objects like directional and point lights do. Only one ambient light is supported.

Two spheres with ambient light

Usage

Create an ambient light source with color and intensity.

const ambientLight= new AmbientLight({
color: [128, 128, 0],
intensity: 2.0
});

Methods

constructor

The constructor for the AmbientLight class. Use this to create a new AmbientLight.

const ambientLight = new AmbientLight({color, intensity});
  • color - (array,) RGB color of ambient light source, default value is [255, 255, 255].
  • intensity - (number) Strength of ambient light source, default value is 1.0.
- - + + \ No newline at end of file diff --git a/docs/api-reference/core/attribute-manager.html b/docs/api-reference/core/attribute-manager.html index e43e4f114d0..bd29e188a2a 100644 --- a/docs/api-reference/core/attribute-manager.html +++ b/docs/api-reference/core/attribute-manager.html @@ -4,8 +4,8 @@ AttributeManager | deck.gl - - + +
@@ -22,7 +22,7 @@ shaderAttributes will share a single buffer created based on the size parameter. This can be used to interleave attributes. Each shader attribute object may contain any of the following:
  • size (Number) - number of elements per vertex
  • vertexOffset (Number) - offset of the attribute by vertex (stride). Default 0.
  • elementOffset (Number) - offset of the attribute by element. default 0.
  • divisor (Boolean, optional) - 1 if this is an instanced attribute (a.k.a. divisor). Default to 0.
addInstanced

Shorthand for add() in which all attributes instanced field are set to true.

remove

Removes defined attributes.

Parameters:

  • attributeNames (Array) - Array of attribute names to be removed
invalidate

Mark an attribute as need update.

Parameters:

  • name (String) - Either the name of the attribute, or the name of an accessor. If an name of accessor is provided, all attributes with that accessor are invalidated.
  • dataRange (Object, optional) - A partial range of the attribute to invalidate, in the shape of {startRow, endRow}. Start (included) and end (excluded) are indices into the data array. If not provided, recalculate the attribute for all data.
invalidateAll

Mark all attributes as need update.

Parameters:

  • dataRange (Object, optional) - A partial range of the attributes to invalidate, in the shape of {startRow, endRow}. Start (included) and end (excluded) are indices into the data array. If not provided, recalculate the attributes for all data.
update

Ensure all attribute buffers are updated from props or data.

attributeManager.update({
data,
numInstances,
transitions,
startIndex,
endIndex,
props = {},
buffers = {},
context = {},
ignoreUnknownAttributes = false
});

Parameters:

  • data (Object) - data (iterable object)
  • numInstances (Number) - count of data
  • buffers (Object) - pre-allocated buffers
  • props (Object) - passed to updaters
  • context (Object) - Used as "this" context for updaters

Notes:

  • Any preallocated buffers in "buffers" matching registered attribute names will be used. No update will happen in this case.
  • Calls onUpdateStart and onUpdateEnd log callbacks before and after.

Remarks

Attribute Type

The following type values are supported for attribute definitions:

typevalue array typenotes
GL.FLOATFloat32Array
GL.DOUBLEFloat64ArrayBecause 64-bit floats are not supported by WebGL, the value is converted to an interleaved Float32Array before uploading to the GPU. It is exposed to the vertex shader as two attributes, <attribute_name> and <attribute_name>64Low, the sum of which is the 64-bit value.
GL.BYTEInt8Array
GL.SHORTInt16Array
GL.INTInt32Array
GL.UNSIGNED_BYTEUint8ClampedArray
GL.UNSIGNED_SHORTUint16Array
GL.UNSIGNED_INTUint32Array

Source

modules/core/src/lib/attribute-manager.ts

- - + + \ No newline at end of file diff --git a/docs/api-reference/core/attribute.html b/docs/api-reference/core/attribute.html index 184f8dbc196..cd1b1af9e31 100644 --- a/docs/api-reference/core/attribute.html +++ b/docs/api-reference/core/attribute.html @@ -4,13 +4,13 @@ Attribute (Internal) | deck.gl - - + +

Attribute (Internal)

This class is a target for refactor.

This class helps deck.gl manage attributes. It integrates into the luma.gl Model.setAttributes() method by implementing the Attribute.getValue() method. luma.gl checks for the presence of this method on any attribute passed in.

Usage

Create model object by passing shaders, uniforms, geometry and render it by passing updated uniforms.

import {_Attribute as Attribute} from './attribute';
// construct the model.
const positions = new Attribute({
id: 'vertexPositions',
size: 3,
value: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0])
});

// and on each frame update any uniforms (typically matrices) and call render.
model.setAttributes({positions});
model.draw();

Methods

constructor

The constructor for the Attribute class. Use this to create a new Attribute.

new Attribute(gl, options);

  • gl - WebGL context.
  • size (number) - The number of components in each element the buffer (1-4).
  • id (string, optional) - Identifier of the attribute. Cannot be updated.
  • type (GLenum, optional) - Type of the attribute. If not supplied will be inferred from value. Cannot be updated.
  • isIndexed (bool, optional) - If the attribute is element index. Default false. Cannot be updated.
  • constant (bool, optional) - If the attribute is a constant. Default false.
  • isInstanced (bool, optional) - Whether buffer contains instance data. Default false.
  • normalized (boolean, optional) - Default false
  • integer (boolean, optional) - Default false
  • offset (number, optional) - where the data starts in the buffer. Default 0.
  • stride (number, optional) - an additional offset between each element in the buffer. Default 0.
  • value (TypedArray) - value of the attribute.
    • If constant is true, the length of value should match size
    • If constant is false, the length of value should be size multiplies the number of vertices.
  • buffer (Buffer) - an external buffer for the attribute.

delete

Free GPU resources associated with this attribute.

update

attribute.update({value: newValue});

Update attribute options. See constructor for possible options.

getBuffer

Returns a Buffer object associated with this attribute, if any.

- - + + \ No newline at end of file diff --git a/docs/api-reference/core/camera-light.html b/docs/api-reference/core/camera-light.html index c26c71dfde8..f8bfce0c811 100644 --- a/docs/api-reference/core/camera-light.html +++ b/docs/api-reference/core/camera-light.html @@ -4,13 +4,13 @@ CameraLight (Experimental) | deck.gl - - + +

CameraLight (Experimental)

CameraLight is a special point light source which always emits from the camera position.

Two spheres with camera light

Usage

Create an camera light source.

import {_CameraLight as CameraLight} from '@deck.gl/core';

new CameraLight({
color: [255, 255, 255],
intensity: 1
});

constructor

The constructor for the CameraLight class. Use this to create a new CameraLight.

const cameraLight = new CameraLight({color, intensity});
  • color - (array) RGB color of camera light source, default value is [255, 255, 255].
  • intensity - (number) Strength of camera light source, default value is 1.0.

Source

/modules/core/src/effects/lighting/camera-light.ts

- - + + \ No newline at end of file diff --git a/docs/api-reference/core/composite-layer.html b/docs/api-reference/core/composite-layer.html index 1d7dd3874ce..1720d8656c2 100644 --- a/docs/api-reference/core/composite-layer.html +++ b/docs/api-reference/core/composite-layer.html @@ -4,8 +4,8 @@ CompositeLayer Class | deck.gl - - + +
@@ -23,7 +23,7 @@ layer.decodePickingColor().
  • picked (Boolean) - true if index is not -1.
  • pickParams.mode (String) - One of hover and click

  • pickParams.sourceLayer (Layer) - the sublayer instance where this event originates from.

  • Returns:

    • An info object with optional fields about what was picked. This object will be passed to the layer's onHover or onClick callbacks.
    • null, if the corresponding event should be cancelled with no callback functions called.

    The default implementation returns pickParams.info without any change.

    getSubLayerProps

    This utility method helps create sublayers that properly inherit a composite layer's basic props. For example, it creates a unique id for the sublayer, and makes sure the sublayer's coordinateSystem is set to be the same as the parent.

    Parameters:

    • subLayerProps (Object)
      • id (String, required) - an id that is unique among all the sublayers generated by this composite layer.
      • updateTriggers (Object) - the sublayer's update triggers.
      • Any additional props are optional.

    Returns a properties object used to generate a sublayer, with the following keys:

    • id - a unique id for the sublayer, by prepending the parent layer id to the sublayer id.
    • updateTriggers - merged object of the parent layer update triggers and the sublayer update triggers.
    • Base layer props that are directly forwarded from the base layer:
      • opacity
      • pickable
      • visible
      • parameters
      • getPolygonOffset
      • highlightedObjectIndex
      • autoHighlight
      • highlightColor
      • coordinateSystem
      • coordinateOrigin
      • wrapLongitude
      • positionFormat
      • modelMatrix
    • Any other additional props from the input parameter are directly forwarded.
    • Any overriding props specified in _subLayerProps.
    shouldRenderSubLayer

    Called to determine if a sublayer should be rendered. A composite layer can override this method to change the default behavior.

    Parameters:

    • id (String) - the sublayer id
    • data (Array) - the sublayer data

    Returns true if the sublayer should be rendered. The base class implementation returns true if data is not empty.

    getSubLayerClass

    Called to retrieve the constructor of a sublayer. A composite layer can override this method to change the default behavior.

    Parameters:

    • id (String) - the sublayer id
    • DefaultLayerClass - the default constructor used for this sublayer.

    Returns:

    Constructor for this sublayer. The base class implementation checks if type is specified for the sublayer in _subLayerProps, otherwise returns the default.

    getSubLayerRow

    Used by adapter layers) to decorate transformed data with a reference to the original object.

    Parameters:

    • row (Object) - a custom data object to pass to a sublayer.
    • sourceObject (Object) - the original data object provided by the user
    • sourceObjectIndex (Object) - the index of the original data object provided by the user

    Returns:

    The row object, decorated with a reference.

    getSubLayerAccessor

    Used by adapter layers) to allow user-provided accessors to read the original objects from transformed data.

    Parameters:

    • accessor (Function|Any) - the accessor provided to the current layer.

    Returns:

    • If accessor is a function, returns a new accessor function.
    • If accessor is a constant value, returns it as is.

    Source

    modules/core/src/lib/composite-layer.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/controller.html b/docs/api-reference/core/controller.html index 6ce02e52b64..b098ca98818 100644 --- a/docs/api-reference/core/controller.html +++ b/docs/api-reference/core/controller.html @@ -4,13 +4,13 @@ Controller | deck.gl - - + +

    Controller

    The base class for all viewport controllers.

    A controller class can be passed to either the Deck class's controller prop or a View class's controller prop to specify viewport interactivity.

    Options

    The base Controller class supports the following options:

    • scrollZoom (Boolean|Object) - enable zooming with mouse wheel. Default true. If an object is supplied, it may contain the following fields to customize the zooming behavior:
      • speed (Number) - scaler that translates wheel delta to the change of viewport scale. Default 0.01.
      • smooth (Boolean) - smoothly transition to the new zoom. If enabled, will provide a slightly lagged but smoother experience. Default false.
    • dragPan (Boolean) - enable panning with pointer drag. Default true
    • dragRotate (Boolean) - enable rotating with pointer drag. Default true
    • doubleClickZoom (Boolean) - enable zooming with double click. Default true
    • touchZoom (Boolean) - enable zooming with multi-touch. Default true
    • touchRotate (Boolean) - enable rotating with multi-touch. Use two-finger rotating gesture for horizontal and three-finger swiping gesture for vertical rotation. Default false
    • keyboard (Boolean|Object) - enable interaction with keyboard. Default true. If an object is supplied, it may contain the following fields to customize the keyboard behavior:
      • zoomSpeed (Number) - speed of zoom using +/- keys. Default 2.
      • moveSpeed (Number) - speed of movement using arrow keys, in pixels.
      • rotateSpeedX (Number) - speed of rotation using shift + left/right arrow keys, in degrees. Default 15.
      • rotateSpeedY (Number) - speed of rotation using shift + up/down arrow keys, in degrees. Default 10.
    • dragMode (String) - drag behavior without pressing function keys, one of pan and rotate.
    • inertia (Boolean|Number) - Enable inertia after panning/pinching. If a number is provided, indicates the duration of time over which the velocity reduces to zero, in milliseconds. Default false.

    Methods

    A controller is not meant to be instantiated by the application. The following methods are documented for creating custom controllers that extend the base Controller class.

    constructor
    import {Controller} from 'deck.gl';

    class MyController extends Controller {
    constructor(props) {
    super(props);
    }
    }

    The constructor takes one argument:

    • props (Object) - contains the following options:
      • eventManager- handles events subscriptions
      • makeViewPort (viewState) - creates new Viewport based on provided ViewState, and current view's width and height
      • onStateChange callback function
      • onViewStateChange callback function
      • timeline - an instance of luma.gl animation timeline class
    handleEvent(event)

    Called by the event manager to handle pointer events. This method delegate to the following methods to handle the default events:

    • _onPanStart(event)
    • _onPan(event)
    • _onPanEnd(event)
    • _onPinchStart(event)
    • _onPinch(event)
    • _onPinchEnd(event)
    • _onTriplePanStart(event)
    • _onTriplePan(event)
    • _onTriplePanEnd(event)
    • _onDoubleTap(event)
    • _onWheel(event)
    • _onKeyDown(event)

    See Event object documentation.

    setProps(props)

    Called by the view when the view state updates. This method handles adding/removing event listeners based on user options.

    updateViewport(newMapState, extraProps, interactionState)

    Called by the event handlers, this method updates internal state, and invokes onViewStateChange callback with a new map state.

    getCenter(event)

    Utility used by the event handlers, returns pointer position [x, y] from any event.

    isFunctionKeyPressed(event)

    Utility used by the event handlers, returns true if ctrl/alt/meta key is pressed during any event.

    isPointInBounds(pos, [event])

    Utility used by the event handlers, returns true if a pointer position [x, y] is inside the current view.

    If event is provided, returns false if the event is already handled, and mark the event as handled if the point is in bounds. This can be used to make sure that certain events are only handled by one controller, when there are overlapping viewports.

    isDragging()

    Returns true if the user is dragging the view.

    Example: Implementing A Custom Controller

    import {Controller} from 'deck.gl';

    class MyController extends Controller{
    constructor(props) {
    super(props);
    this.events = ['pointermove'];
    }

    handleEvent(event) {
    if (event.type === 'pointermove') {
    // do something
    } else {
    super.handleEvent(event);
    }
    }
    }

    In its constructor, a controller class can optionally specify a list of event names that it subscribes to with the events field. A full list of supported events can be found here.

    Note that the following events are always toggled on/off by user options:

    • scrollZoom - ['wheel']
    • dragPan and dragRotate - ['pan']
    • touchZoom - ['pinch']
    • touchRotate - ['pinch', 'tripan']
    • doubleClickZoom - ['doubletap']
    • keyboard - ['keydown']

    Source

    modules/core/src/controllers/controller.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/deck.html b/docs/api-reference/core/deck.html index 8bacc004912..1bbc169e116 100644 --- a/docs/api-reference/core/deck.html +++ b/docs/api-reference/core/deck.html @@ -4,13 +4,13 @@ Deck | deck.gl - - + +

    Deck

    Deck is a class that takes deck.gl layer instances and viewport parameters, renders those layers as a transparent overlay, and handles events.

    If you are using React, you should not use this class directly. Instead you should be rendering the DeckGL React component.

    Usage

    // Basic standalone use
    import {Deck} from '@deck.gl/core';
    import {ScatterplotLayer} from '@deck.gl/layers';

    const deck = new Deck({
    initialViewState: {
    longitude: -122.45,
    latitude: 37.78,
    zoom: 12
    },
    controller: true,
    layers: [
    new ScatterplotLayer({data})
    ]
    });

    Constructor

    Creates a new Deck instance.

    const deck = new Deck(props);

    Parameters:

    See the Properties section.

    Properties

    Initialization Settings

    The following properties are used to initialize a Deck instance. Any custom value should always be provided to the Deck constructor. Changing them with setProps afterwards will have no effect.

    canvas (HTMLCanvasElement | String, optional)

    The canvas to render into. Can be either a HTMLCanvasElement or the element id. Will be auto-created if not supplied.

    gl (WebGLContext)

    WebGL context. Will be auto-created if not supplied.

    glOptions (Object)

    Additional options used when creating the WebGLContext. See WebGL context attributes.

    id (String)
    • Default: 'deckgl-overlay'

    ID assigned to the canvas that is created by this Deck instance, to allow style customization in CSS.

    parent (HTMLElement)
    • Default: document.body

    The container to append the auto-created canvas to.

    debug (Boolean)
    • Default: false

    Flag to enable GPU debug mode. Also requires an extra luma.gl import:

    import '@luma.gl/debug';
    import {Deck} from '@deck.gl/core';

    new Deck({
    // ...
    debug: true
    })

    Notes:

    • Debug mode is slower as it will use synchronous operations to keep track of GPU state.
    _typedArrayManagerProps (Object)
    • Default: {}

    (Experimental) May contain the following fields:

    • overAlloc (Number) - Default 2. By default, attributes are allocated twice the memory than they actually need (on both CPU and GPU). Must be larger than 1.
    • poolSize (Number) - Default 100. When memory reallocation is needed, old chunks are held on to and recycled. Smaller number uses less CPU memory. Can be any number >=0.

    The above default settings make data updates faster, at the price of using more memory. If the app does not anticipate frequent data changes, they may be aggressively reduced:

    new Deck({
    // ...
    _typedArrayManagerProps: isMobile ? {overAlloc: 1, poolSize: 0} : null
    })

    Rendering Configuration

    width (Number|String)
    • Default: '100%'

    Width of the canvas, a number in pixels or a valid CSS string.

    height (Number|String)
    • Default: '100%'

    Height of the canvas, a number in pixels or a valid CSS string.

    style (Object)

    Additional CSS styles for the canvas.

    useDevicePixels (Boolean|Number)
    • Default: true

    Controls the resolution of drawing buffer used for rendering.

    • true: Device (physical) pixels resolution is used for rendering, this resolution is defined by window.devicePixelRatio. On Retina/HD systems this resolution is usually twice as big as CSS pixels resolution.
    • false: CSS pixels resolution (equal to the canvas size) is used for rendering.
    • Number (Experimental): Specified Number is used as a custom ratio (drawing buffer resolution to CSS pixel resolution) to determine drawing buffer size, a value less than one uses resolution smaller than CSS pixels, gives better performance but produces blurry images, a value greater than one uses resolution bigger than CSS pixels resolution (canvas size), produces sharp images but at a lower performance.

    Note:

    • Consider setting to false or to a number <=1 if better rendering performance is needed.
    • When it is set to a high Number (like, 4 or more), it is possible to hit the system limit for allocating drawing buffer, such cases will log a warning and fallback to system allowed resolution.
    parameters (Object)

    Expects an object with GPU parameters. Before each frame is rendered, this object will be passed to luma.gl's setParameters function to reset the GPU context parameters, e.g. to disable depth testing, change blending modes etc. The default parameters set by Deck on initialization are the following:

    {
    blend: true,
    blendFunc: [GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA, GL.ONE, GL.ONE_MINUS_SRC_ALPHA],
    polygonOffsetFill: true,
    depthTest: true,
    depthFunc: GL.LEQUAL
    }

    Refer to the luma.gl setParameters API for documentation on supported parameters and values.

    import GL from '@luma.gl/constants';
    new Deck({
    // ...
    parameters: {
    blendFunc: [GL.ONE, GL.ONE, GL.ONE, GL.ONE],
    depthTest: false
    }
    });

    Notes:

    • Any GPU parameters prop supplied to individual layers will still override the global parameters when that layer is rendered.
    • An alternative way to set parameters is to instead define the onWebGLInitialized callback (it receives the gl context as parameter) and call the luma.gl setParameters method inside it.
    layers (Array)
    • Default: []

    The array of Layer instances to be rendered.

    Nested arrays are accepted, as well as falsy values (null, false, undefined). This allows applications to do something like:

    new Deck({
    // ...
    layers: dataSource.map((item, index) => item && [
    new ScatterplotLayer({id: `scatterplot-${index}`, ...}),
    new PolygonLayer({id: `polygon-${index}`, ...})
    ])
    });
    // layers is in the shape of [[<layer>, <layer>], null, [<layer>, <layer>], ...]
    layerFilter (Function)
    • Default: null

    If supplied, will be called before a layer is drawn to determine whether it should be rendered. This gives the application an opportunity to filter out layers from the layer list during either rendering or picking. Filtering can be done per viewport or per layer or both. This enables techniques like adding helper layers that work as masks during picking but do not show up during rendering.

    new Deck({
    // ...
    layerFilter: ({layer, viewport}) => {
    if (viewport.id !== 'minimap' && layer.id === 'geofence') {
    // only display geofence in the minimap
    return false;
    }
    return true;
    }
    }

    Receives arguments:

    • layer (Layer) - the layer to be drawn
    • viewport (Viewport) - the current viewport
    • isPicking (Boolean) - whether this is a picking pass
    • cullRect (Object) - if defined, indicates that only the content rendered to the given rectangle is needed.
    • renderPass (String) - the name of the current render pass. Some standard passes are:
      • 'screen' - drawing to screen
      • 'picking:hover' - drawing to offscreen picking buffer due to pointer move
      • 'picking:query' - drawing to offscreen picking buffer due to user-initiated query, e.g. calling deck.pickObject.
      • 'shadow' - drawing to shadow map

    Returns:

    true if the layer should be drawn.

    Notes:

    • layerFilter does not override the visibility if the layer is disabled via visible: false or pickable: false props.
    • All the lifecycle methods other than draw are still triggered even a if a layer is filtered out using this method.
    views (Object|Array)
    • Default: new MapView()

    A single View instance, or an array of View instances.

    Views represent the "camera(s)" (essentially viewport dimensions and projection matrices) that you look at your data with. deck.gl offers multiple view types for both geospatial and non-geospatial use cases. Read the Views and Projections guide for the concept and examples.

    viewState (Object)

    An object that describes the view state for each view in the views prop. For example, the default view's view state is described here:

    new Deck({
    // ...
    viewState: {
    longitude: -122.45,
    latitude: 37.78,
    zoom: 12,
    pitch: 30,
    bearing: 0
    }
    })

    When using multiple views, the viewState is a map from each view id to its respective view state object. See example.

    Transitions between two viewState objects can also be achieved by providing set of fields to viewState prop, for more details check ViewState Transitions).

    Notes:

    • If you supply this prop, you are responsible of managing the changes to the view state upon user interaction. This prop is therefore usually used together with the onViewStateChange callback (example). For Deck to update view states automatically, use the initialViewState prop instead.
    initialViewState (Object)

    If initialViewState is provided, the Deck component will track view state changes from any attached controller using internal state, with initialViewState as its initial view state. This is the easiest way to control the camera.

    If the initialViewState prop changes, the internally tracked view state will be updated to match the new "initial" view state.

    Notes:

    • The onViewStateChange callback will still be called, if provided.
    • If the viewState prop is supplied by the application, the supplied viewState will always be used, overriding the Deck component's internal view state.
    • In simple applications, use of the initialViewState prop can avoid the need to track the view state in the application.
    • One drawback of using initialViewState for reactive/functional applications is that the Deck component becomes more stateful.
    effects (Array)

    The array of effects to be rendered. A lighting effect will be added if an empty array is supplied. Refer to effect's documentation to see details:

    _framebuffer (Object)

    (Experimental) Render to a custom frame buffer other than to screen.

    _animate (Boolean)
    • Default: false

    (Experimental) Forces deck.gl to redraw layers every animation frame. Normally deck.gl layers are only redrawn if any change is detected.

    Interaction Settings

    controller (Function | Boolean | Object)
    • Default: null

    Options for viewport interactivity, e.g. pan, rotate and zoom with mouse, touch and keyboard. This is a shorthand for defining interaction with the views prop if you are using the default view (i.e. a single MapView).

    new Deck({
    // ...
    views: [
    new MapView({
    controller: {touchRotate: true, doubleClickZoom: false}
    })
    ]
    })

    is equivalent to:

    new Deck({
    // ...
    // views: undefined
    controller: {touchRotate: true, doubleClickZoom: false}
    })

    controller can be one of the following types:

    • null or false: the viewport is not interactive.
    • true: initiates the default controller of the default view - e.g. a MapController if MapView is used.
    • Controller class (not instance): initiates the provided controller with default options. Must be a subclass of Controller.
    • Object: controller options. This will be merged with the default controller options.
      • controller.type: the controller class, must be a subclass of Controller.
      • Other options supported by the controller type. Consult the documentation of Controller.
    getCursor (Function)
    • Default: ({isDragging}) => isDragging ? 'grabbing' : 'grab'

    A custom callback to retrieve the cursor type.

    Receives arguments:

    • interactiveState (Object)
      • isDragging (Boolean) - whether the pointer is down and moving
      • isHovering (Boolean) - whether the pointer is over a pickable object

    Returns:

    A valid CSS cursor string.

    Remarks:

    • It is worth noting that when supplying a custom image for the cursor icon, Chrome requires a fallback option to be supplied, otherwise the custom image will not be loaded; e.g. getCursor={() => 'url(images/custom.png), auto'}
    getTooltip (Function)

    Callback that takes a hovered-over point and renders a tooltip. If the prop is not specified, the tooltip is always hidden.

    Receives arguments:

    • info - the picking info describing the object being hovered.

    Returns one of the following:

    • null - the tooltip is hidden, with the CSS display property set to none.
    • A string - the string is rendered in a tooltip with the default CSS styling described below.
    • An object with the following fields:
      • text (String, optional) - Specifies the innerText attribute of the tooltip.
      • html (String, optional) - Specifies the innerHTML attribute of the tooltip. Note that this will override the specified innerText.
      • className (String, optional) - Class name to attach to the tooltip element. The element has the default class name of deck-tooltip.
      • style (Object, optional) - An object of CSS styles to apply to the tooltip element, which can override the default styling.

    By default, the tooltip has the following CSS style:

    z-index: 1;
    position: absolute;
    color: #a0a7b4;
    background-color: #29323c;
    padding: 10px;
    pickingRadius (Number)

    Extra pixels around the pointer to include while picking. This is helpful when rendered objects are difficult to target, for example irregularly shaped icons, small moving circles or interaction by touch. Default 0.

    touchAction (String)
    • Default: none.

    Allow browser default touch actions. See hammer.js documentation.

    By default, the deck canvas captures all touch interactions. This prop is useful for mobile applications to unblock default scrolling behavior. For example, use the combination controller: {dragPan: false} and touchAction: 'pan-y' to allow vertical page scroll when dragging over the canvas.

    eventRecognizerOptions (Object)
    • default: {}

    Set options for gesture recognition. May contain the following fields:

    • pan - an object that is Hammer.Pan options. This gesture is used for drag events.
    • pinch - an object that is Hammer.Pinch options This gesture is used for two-finger touch events.
    • tripan - an object that is Hammer.Pan options. This gesture is used for three-finger touch events.
    • tap - an object that is Hammer.Tap options. This gesture is used for the onClick callback.
    • doubletap - an object that is Hammer.Tap options. This gesture is used for double click events.

    For example, the following setting makes panning less sensitive and clicking easier on mobile:

    new Deck({
    // ...
    eventRecognizerOptions: isMobile ? {
    pan: {threshold: 10},
    tap: {threshold: 5}
    } : {}
    })
    _pickable (Boolean)
    • Default: true

    (Experimental) If set to false, force disables all picking features, disregarding the pickable prop set in any layer.

    Event Callbacks

    onWebGLInitialized (Function)

    Called once the WebGL context has been initiated.

    Receives arguments:

    • gl - the WebGL context.
    onViewStateChange (Function)

    Called when the user has interacted with the deck.gl canvas, e.g. using mouse, touch or keyboard.

    onViewStateChange({viewState, interactionState, oldViewState})

    Receives arguments:

    • viewState - An updated view state object.
    • interactionState - Describes the interaction that invoked the view state change. May include the following fields:
      • inTransition (Boolean)
      • isDragging (Boolean)
      • isPanning (Boolean)
      • isRotating (Boolean)
      • isZooming (Boolean)
    • oldViewState - The previous view state object.

    Returns:

    A view state object that is used to update Deck's internally tracked view state (see initialViewState). This can be used to intercept and modify the view state before the camera updates, see add constraints to view state example.

    If no value is returned, it's equivalent to (viewState) => viewState.

    onInteractionStateChange (Function)

    Called when the user has interacted with the deck.gl canvas, e.g. using mouse, touch or keyboard.

    onInteractionStateChange(interactionState)

    Receives arguments:

    • interactionState - Describes the current interaction. May include the following fields:
      • inTransition (Boolean)
      • isDragging (Boolean)
      • isPanning (Boolean)
      • isRotating (Boolean)
      • isZooming (Boolean)

    Note:

    • onInteractionStateChange may be fired without onViewStateChange. For example, when the pointer is released at the end of a drag-pan, isDragging is reset to false, without the viewport's longitude and latitude changing.
    onHover (Function)

    Called when the pointer moves over the canvas.

    Receives arguments:

    • info - the picking info describing the object being hovered.
    • event - the original gesture event
    onClick (Function)

    Called when clicking on the canvas.

    Receives arguments:

    • info - the picking info describing the object being clicked.
    • event - the original gesture event
    onDragStart (Function)

    Called when the user starts dragging on the canvas.

    Receives arguments:

    • info - the picking info describing the object being dragged.
    • event - the original gesture event
    onDrag (Function)

    Called when dragging the canvas.

    Receives arguments:

    • info - the picking info describing the object being dragged.
    • event - the original gesture event
    onDragEnd (Function)

    Called when the user releases from dragging the canvas.

    Receives arguments:

    • info - the picking info describing the object being dragged.
    • event - the original gesture event
    onLoad (Function)

    Called once after gl context and Deck components (ViewManager, LayerManager, etc) are created. It is safe to trigger viewport transitions after this event.

    onResize (Function)

    Called when the canvas resizes.

    Receives arguments:

    • size
      • width (Number) - the new width of the deck canvas, in client pixels
      • height (Number) - the new height of the deck canvas, in client pixels
    onBeforeRender (Function)

    Called just before the canvas rerenders.

    Receives arguments:

    • gl - the WebGL context.
    onAfterRender (Function)

    Called right after the canvas rerenders.

    Receives arguments:

    • gl - the WebGL context.
    onError (Function)
    • Default: console.error

    Called if deck.gl encounters an error. By default, deck logs the error to console and attempt to continue rendering the rest of the scene. If this callback is set to null, errors are silently ignored.

    Receives arguments:

    • error (Error)
    • layer (Layer?) - the layer where the error is originated, if applicable
    _onMetrics (Function)

    (Experimental) Called once every second with performance metrics.

    Receives arguments:

    • metrics - an object with fields specified here.

    Methods

    finalize

    Frees all resources associated with this Deck instance.

    deck.finalize()

    getCanvas

    Get the canvas element attached to this Deck instance.

    deck.getCanvas()

    Returns:

    • Either an HTMLCanvasElement or null if one isn't assigned.

    Notes:

    • See the canvas prop for more information.
    setProps

    Updates (partial) properties.

    deck.setProps({...});

    Parameters:

    • One or more properties to update, as described in the "Properties" section on this page.
    redraw

    Attempt to draw immediately, rather than waiting for the next draw cycle. By default, deck flushes all changes to the canvas on each animation frame. This behavior might cause the deck canvas to fall out of sync with other components if synchronous updates are required.

    Redrawing frequently outside of rAF may cause performance problems. Only use this method if the render cycle must be managed manually.

    deck.redraw(true);

    Parameters:

    • force (Boolean) - if false, only redraw if necessary (e.g. changes have been made to views or layers). If true, skip the check. Default false.
    pickObject

    Get the closest pickable and visible object at the given screen coordinate.

    deck.pickObject({x, y, radius, layerIds, unproject3D})

    Parameters:

    • x (Number) - x position in pixels
    • y (Number) - y position in pixels
    • radius (Number, optional) - radius of tolerance in pixels. Default 0.
    • layerIds (Array, optional) - a list of layer ids to query from. If not specified, then all pickable and visible layers are queried.
    • unproject3D (Boolean, optional) - if true, info.coordinate will be a 3D point by unprojecting the x, y screen coordinates onto the picked geometry. Default false.

    Returns:

    • a single info object, or null if nothing is found.
    pickMultipleObjects

    Performs deep picking. Finds all close pickable and visible object at the given screen coordinate, even if those objects are occluded by other objects.

    deck.pickMultipleObjects({x, y, radius, layerIds, depth, unproject3D})

    Parameters:

    • x (Number) - x position in pixels
    • y (Number) - y position in pixels
    • radius (Number, optional) - radius of tolerance in pixels. Default 0.
    • layerIds (Array, optional) - a list of layer ids to query from. If not specified, then all pickable and visible layers are queried.
    • depth - Specifies the max number of objects to return. Default 10.
    • unproject3D (Boolean, optional) - if true, info.coordinate will be a 3D point by unprojecting the x, y screen coordinates onto the picked geometry. Default false.

    Returns:

    • An array of info objects. The array will be empty if no object was picked.

    Notes:

    • Deep picking is implemented as a sequence of simpler picking operations and can have a performance impact. Should this become a concern, you can use the depth parameter to limit the number of matches that can be returned, and thus the maximum number of picking operations.
    pickObjects

    Get all pickable and visible objects within a bounding box.

    deck.pickObjects({x, y, width, height, layerIds, maxObjects})

    Parameters:

    • x (Number) - left of the bounding box in pixels
    • y (Number) - top of the bouding box in pixels
    • width (Number, optional) - width of the bouding box in pixels. Default 1.
    • height (Number, optional) - height of the bouding box in pixels. Default 1.
    • layerIds (Array, optional) - a list of layer ids to query from. If not specified, then all pickable and visible layers are queried.
    • maxObjects (Number, optional) - if specified, limits the number of objects that can be returned.

    Returns:

    • an array of unique info objects

    Notes:

    • The query methods are designed to quickly find objects by utilizing the picking buffer.
    • The query methods offer more flexibility for developers to handle events compared to the built-in hover and click callbacks.

    Member Variables

    isInitialized

    Flag indicating that the Deck instance has initialized its resources. It is safe to call public methods when isInitialized is true.

    metrics

    A map of various performance statistics for the last 60 frames of rendering. Metrics gathered in deck.gl are the following:

    • fps - average number of frames rendered per second
    • updateAttributesTime - time spent updating layer attributes
    • setPropsTime - time spent setting deck properties
    • framesRedrawn - number of times the scene was rendered
    • pickTime - total time spent on picking operations
    • pickCount - number of times a pick operation was performed
    • gpuTime - total time spent on GPU processing
    • gpuTimePerFrame - average time spent on GPU processing per frame
    • cpuTime - total time spent on CPU processing
    • cpuTimePerFrame - average time spent on CPU processing per frame
    • bufferMemory - total GPU memory allocated for buffers
    • textureMemory - total GPU memory allocated for textures
    • renderbufferMemory - total GPU memory allocated for renderbuffers
    • gpuMemory - total allocated GPU memory

    Source

    modules/core/src/lib/deck.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/deckgl.html b/docs/api-reference/core/deckgl.html index a554bffc7c7..6d3938a3c1f 100644 --- a/docs/api-reference/core/deckgl.html +++ b/docs/api-reference/core/deckgl.html @@ -4,13 +4,13 @@ DeckGL (Scripting Interface) | deck.gl - - + +

    DeckGL (Scripting Interface)

    DeckGL extends the core Deck class with some additional features such as Mapbox integration. It offers a convenient way to use deck.gl in prototype environments such as Codepen, JSFiddle and Observable.

    Make sure to read the Using deck.gl Scripting API article.

    Usage

    new deck.DeckGL({
    mapStyle: 'https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json',
    initialViewState: {
    longitude: -122.45,
    latitude: 37.8,
    zoom: 12
    },
    controller: true,
    layers: [
    new deck.ScatterplotLayer({
    data: [
    {position: [-122.45, 37.8], color: [255, 0, 0], radius: 100}
    ],
    getColor: d => d.color,
    getRadius: d => d.radius
    })
    ]
    });

    Properties

    All Deck class properties, with these additional props that can be passed to the constructor:

    container (DOMElement | String, optional)

    Default: document.body

    The container in which deck.gl should append its canvas. Can be either a HTMLDivElement or the element id. The deck.gl canvas is resized to fill the container.

    map (Object, optional)

    Default: window.mapboxgl || window.maplibregl

    The scripting API offers out-of-the-box integration with Mapbox GL JS or MapLibre GL JS. To add a base map to your visualization, you need to include the base map library and stylesheet:

    <script src="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.js"></script>
    <link href="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.css" rel="stylesheet" />
    <!-- or -->
    <script src="https://unpkg.com/maplibre-gl@3.0.0/dist/maplibre-gl.js"></script>
    <link href="https://unpkg.com/maplibre-gl@3.0.0/dist/maplibre-gl.css" rel="stylesheet" />

    The above script adds mapboxgl or maplibregl to the global scope, which will be picked up by default.

    To disable the base map, simply exclude the mapbox script or set map to false.

    In some environments such as Observable, libraries cannot be imported into the global scope, in which case you need to manually pass the mapboxgl object to map:

    mapboxgl = require('mapbox-gl@^3.0.0/dist/mapbox-gl.js');
    // or
    maplibregl = require('maplibre-gl@^3.0.0/dist/maplibre-gl.js');

    And

    new deck.DeckGL({
    ...
    map: mapboxgl // or maplibregl
    });
    mapStyle (Object | String)

    The style JSON or URL for the Mapbox map.

    mapboxApiAccessToken (String)

    The API access token to use Mapbox tiles. See Mapbox GL JS documentation for how to use Mapbox.

    Methods

    All Deck class methods, with these additional methods:

    getMapboxMap

    Returns the mapbox-gl or maplibre-gl Map instance if a base map is present.

    Source

    modules/main/bundle.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/directional-light.html b/docs/api-reference/core/directional-light.html index b10a2a2e4c6..95ae0d87e4c 100644 --- a/docs/api-reference/core/directional-light.html +++ b/docs/api-reference/core/directional-light.html @@ -4,13 +4,13 @@ DirectionalLight | deck.gl - - + +

    DirectionalLight

    Create a directional light source which emits from a specific direction.A directional light can be considered "infinitely" far away (like the Sun) and does not attenuate with distance. At most 5 directional lights can be supported.

    Two spheres with directional light

    Usage

    Create a directional light source with color, intensity and direction.

    const directionalLight= new DirectionalLight({
    color: [128, 128, 0],
    intensity: 2.0,
    direction: [0, -100, -100]
    });

    Methods

    constructor

    The constructor for the DirectionalLight class. Use this to create a new DirectionalLight.

    const directionalLight = new DirectionalLight({color, intensity, direction});
    • color - (array,) RGB color of directional light source, default value is [255, 255, 255].
    • intensity - (number) Strength of directional light source, default value is 1.0.
    • direction - (array,) 3D vector specifies the direction the light comes from, default value is [0, 0, -1].
    • _shadow - (boolean, optional) Enable experimental shadow effect, default value is false.

    Source

    /modules/core/src/effects/lighting/directional-light.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/first-person-controller.html b/docs/api-reference/core/first-person-controller.html index 0ddf4f2edd1..ee14e7f888b 100644 --- a/docs/api-reference/core/first-person-controller.html +++ b/docs/api-reference/core/first-person-controller.html @@ -4,13 +4,13 @@ FirstPersonController | deck.gl - - + +

    FirstPersonController

    Inherits from Base Controller.

    The FirstPersonController class can be passed to either the Deck class's controller prop or a View class's controller prop to specify that viewport interaction should be enabled.

    FirstPersonController is the default controller for FirstPersonView. It simulates the movement of a human being, with the scroll motion moving forward/backwards and dragging rotating the head.

    Usage

    Use with the default view:

    import {Deck, FirstPersonView} from '@deck.gl/core';

    new Deck({
    views: new FirstPersonView(),
    controller: {keyboard: false, inertia: true},
    initialViewState: viewState
    });

    is equivalent to:

    import {Deck, FirstPersonView} from '@deck.gl/core';

    new Deck({
    views: new FirstPersonView({
    controller: {keyboard: false, inertia: true}
    }),
    initialViewState: viewState
    })

    Options

    Supports all Controller options with the following default behavior:

    • dragMode: default 'rotate' (drag to rotate, shift-drag to pan)
    • dragPan: default true (supported only from v9.0)
    • keyboard: arrow keys to move camera, arrow keys with shift/ctrl down to rotate, +/- to move vertically
    • scrollZoom: scroll to move in direction of mouse pointer, in horizontal 2D plane

    Custom FirstPersonController

    You can further customize the FirstPersonController's behavior by extending the class:

    import {Deck, FirstPersonView, FirstPersonController} from '@deck.gl/core';

    class MyFirstPersonController extends FirstPersonController {

    handleEvent(event) {
    if (event.type === 'pan') {
    // do something
    } else {
    super.handleEvent(event);
    }
    }
    }

    new Deck({
    views: new FirstPersonView(),
    controller: {type: MyFirstPersonController},
    initialViewState: viewState
    })

    See the Controller class documentation for the methods that you can use and/or override.

    Source

    modules/core/src/controllers/first-person-controller.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/first-person-view.html b/docs/api-reference/core/first-person-view.html index 684fea364b9..52cce3b55df 100644 --- a/docs/api-reference/core/first-person-view.html +++ b/docs/api-reference/core/first-person-view.html @@ -4,13 +4,13 @@ FirstPersonView | deck.gl - - + +

    FirstPersonView

    The FirstPersonView class is a subclass of View that describes a camera placed at a provided location, looking towards the direction and orientation specified by viewState. The behavior is similar to that of a first-person game.

    It's recommended that you read the Views and Projections guide before using this class.

    Constructor

    import {FirstPersonView} from '@deck.gl/core';
    new FirstPersonView({id, ...});

    FirstPersonView takes the same parameters as the View superclass constructor, plus the following:

    projectionMatrix (Array[16], optional)

    Projection matrix.

    If projectionMatrix is not supplied, the View class will build a projection matrix from the following parameters:

    fovy (Number, optional)

    Field of view covered by camera, in the perspective case. In degrees. Default 75.

    near (Number, optional)

    Distance of near clipping plane. Default 0.1.

    far (Number, optional)

    Distance of far clipping plane. Default 1000.

    focalDistance (Number, optional)

    Modifier of viewport scale. Corresponds to the number of pixels per meter. Default 1.

    View State

    To render, a FirstPersonView needs to be combined with a viewState object with the following parameters:

    • longitude (Number, optional) - longitude of the camera
    • latitude (Number, optional) - latitude of the camera
    • position (Number[3], optional) - meter offsets of the camera from the lng-lat anchor point. Default [0, 0, 0].
    • bearing (Number, optional) - bearing angle in degrees. Default 0 (north).
    • pitch (Number, optional) - pitch angle in degrees. Default 0 (horizontal).
    • maxPitch (Number, optional) - max pitch angle. Default 90 (down).
    • minPitch (Number, optional) - min pitch angle. Default -90 (up).

    Controller

    By default, FirstPersonView uses the FirstPersonController to handle interactivity. To enable the controller, use:

    const view = new FirstPersonView({id: 'pov', controller: true});

    Visit the FirstPersonController documentation for a full list of supported options.

    Source

    modules/core/src/views/first-person-view.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/fly-to-interpolator.html b/docs/api-reference/core/fly-to-interpolator.html index 6e902f6455d..8f910af895b 100644 --- a/docs/api-reference/core/fly-to-interpolator.html +++ b/docs/api-reference/core/fly-to-interpolator.html @@ -4,13 +4,13 @@ FlyToInterpolator | deck.gl - - + +

    FlyToInterpolator

    Performs "fly to" style interpolation between two geospatial view states. Implements TransitionInterpolator.

    See View State Transitions for usage examples.

    Constructor

    import {FlyToInterpolator} from '@deck.gl/core';

    new FlyToInterpolator({speed: 2});

    Parameters:

    • options (Object)
      • curve (Number, optional) - The zooming "curve" that will occur along the flight path. Default 1.414.
      • speed (Number, optional) - The average speed of the animation defined in relation to options.curve, it linearly affects the duration, higher speed returns smaller durations and vice versa. Default 1.2.
      • screenSpeed (Number, optional) - The average speed of the animation measured in screenfuls per second. Similar to speed it linearly affects the duration, when specified speed is ignored.
      • maxDuration (Number, optional) - Maximum duration in milliseconds, if calculated duration exceeds this value, 0 is returned.

    Source

    modules/core/src/transitions/fly-to-interpolator.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/globe-controller.html b/docs/api-reference/core/globe-controller.html index 5e0130035be..92b777f3cde 100644 --- a/docs/api-reference/core/globe-controller.html +++ b/docs/api-reference/core/globe-controller.html @@ -4,13 +4,13 @@ GlobeController (Experimental) | deck.gl - - + +

    GlobeController (Experimental)

    Inherits from Base Controller.

    The GlobeController class can be passed to either the Deck class's controller prop or a View class's controller prop to specify that viewport interaction should be enabled.

    GlobeController is the default controller for GlobeView.

    Usage

    Use with the default view:

    import {Deck, _GlobeView as GlobeView} from '@deck.gl/core';

    new Deck({
    views: new GlobeView(),
    controller: {keyboard: false, inertia: true},
    initialViewState: viewState
    });

    is equivalent to:

    import {Deck, _GlobeView as GlobeView} from '@deck.gl/core';

    new Deck({
    views: new GlobeView({
    controller: {keyboard: false, inertia: true}
    }),
    initialViewState: viewState
    })

    Options

    Supports all Controller options with the following default behavior:

    • dragPan: default 'pan' (drag to pan)
    • dragRotate: not effective, this view does not currently support rotation
    • touchRotate: not effective, this view does not currently support rotation
    • keyboard: arrow keys to pan, +/- to zoom

    Custom GlobeController

    You can further customize the GlobeController's behavior by extending the class:

    import {Deck, _GlobeView as GlobeView, _GlobeController as GlobeController} from '@deck.gl/core';

    class MyGlobeController extends GlobeController {

    handleEvent(event) {
    if (event.type === 'pan') {
    // do something
    } else {
    super.handleEvent(event);
    }
    }
    }

    new Deck({
    views: new GlobeView(),
    controller: {type: MyGlobeController},
    initialViewState: viewState
    })

    See the Controller class documentation for the methods that you can use and/or override.

    Source

    modules/core/src/controllers/globe-controller.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/globe-view.html b/docs/api-reference/core/globe-view.html index 96c59abb4f3..33ea5dc2272 100644 --- a/docs/api-reference/core/globe-view.html +++ b/docs/api-reference/core/globe-view.html @@ -4,14 +4,14 @@ GlobeView (Experimental) | deck.gl - - + +

    GlobeView (Experimental)

    This class is experimental, which means it does not provide the compatibility and stability that one would typically expect from other View classes. Use with caution and report any issues that you find on GitHub.

    The GlobeView class is a subclass of View. This view projects the earth into a 3D globe.

    It's recommended that you read the Views and Projections guide before using this class.

    Limitations

    The goal of GlobeView is to provide a generic solution to rendering and navigating data in the 3D space. In the initial release, this class mainly addresses the need to render an overview of the entire globe. The following limitations apply, as features are still under development:

    • No support for rotation (pitch or bearing). The camera always points towards the center of the earth, with north up.
    • No high-precision rendering at high zoom levels (> 12). Features at the city-block scale may not be rendered accurately.
    • Only supports COORDINATE_SYSTEM.LNGLAT (default of the coordinateSystem prop).
    • Known rendering issues when using multiple views mixing GlobeView and MapView, or switching between the two.
    • Support for TileLayer and MVTLayer is experimental.
    • These layers currently do not work in this view:
      • Aggregation layers: HeatmapLayer, ContourLayer
      • TerrainLayer
    • MaskExtension is not supported in this view.

    When GeoJson paths and polygons are rendered with this view, the straight lines and flat surfaces are warped to the surface of the globe. Note that the warped edges still correspond to straight lines in the Mercator projection. To draw lines along the shortest distance on the globe, use the GreatCircleLayer.

    Constructor

    import {_GlobeView as GlobeView} from '@deck.gl/core';
    const view = new GlobeView({id, ...});

    GlobeView takes the same parameters as the View superclass constructor, plus the following:

    resolution (Number, optional)

    The resolution at which to turn flat features into 3D meshes, in degrees. Smaller numbers will generate more detailed mesh. Default 10.

    nearZMultiplier (Number, optional)

    Scaler for the near plane, 1 unit equals to the height of the viewport. Default to 0.1. Overwrites the near parameter.

    farZMultiplier (Number, optional)

    Scaler for the far plane, 1 unit equals to the distance from the camera to the edge of the screen. Default to 2. Overwrites the far parameter.

    View State

    To render, GlobeView needs to be used together with a viewState with the following parameters:

    • longitude (Number) - longitude at the viewport center
    • latitude (Number) - latitude at the viewport center
    • zoom (Number) - zoom level
    • maxZoom (Number, optional) - max zoom level. Default 20.
    • minZoom (Number, optional) - min zoom level. Default 0.

    Controller

    By default, GlobeView uses the GlobeController to handle interactivity. To enable the controller, use:

    const view = new GlobeView({id: 'globe', controller: true});

    Visit the GlobeController documentation for a full list of supported options.

    Remarks

    Occlusion

    In the MapView, it is often sufficient to provide a solid background color where there is no geometry. In the GlobeView, the user can "see through" to the other side of the earth. There are two ways to fix this:

    • Render a polygon that represents the surface of the earth:
    new SolidPolygonLayer({
    id: 'background',
    data: [
    [[-180, 90], [0, 90], [180, 90], [180, -90], [0, -90], [-180, -90]]
    ],
    getPolygon: d => d,
    stroked: false,
    filled: true,
    getFillColor: [40, 40, 40]
    })
    • Discard all surfaces that face away from the camera by passing the following prop to Deck:
    parameters: {
    cull: true
    }

    Source

    modules/core/src/views/globe-view.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/globe-viewport.html b/docs/api-reference/core/globe-viewport.html index 876c46a3988..838aea591aa 100644 --- a/docs/api-reference/core/globe-viewport.html +++ b/docs/api-reference/core/globe-viewport.html @@ -4,13 +4,13 @@ GlobeViewport (Experimental) | deck.gl - - + +

    GlobeViewport (Experimental)

    The GlobeViewport class takes globe view states (latitude, longitude, and zoom), and performs projections between world and screen coordinates. It is a helper class for visualizing the earth as a 3D globe.

    Usage

    A GlobeViewport instance is created under the hood by a GlobeView.

    import {_GlobeViewport as GlobeViewport} from '@deck.gl/core';

    const viewport = new GlobeViewport({
    width: 600,
    height: 400,
    longitude: -122.45,
    latitude: 37.78,
    zoom: 12
    });

    viewport.project([-122.45, 37.78]);
    // [300,200]

    Constructor

    new GlobeViewport({width, height, longitude, latitude, zoom});

    Parameters:

    • opts (Object) - Globe viewport options

      • width (Number) - Width of the viewport.
      • height (Number) - Height of the viewport.

      geospatial arguments:

      • latitude (Number, optional) - Latitude of the viewport center on map. Default to 0.
      • longitude (Number, optional) - Longitude of the viewport center on map. Default to 0.
      • zoom (Number, optional) - Map zoom (scale is calculated as 2^zoom). Default to 11.
      • altitude (Number, optional) - Altitude of camera, 1 unit equals to the height of the viewport. Default to 1.5.

      projection matrix arguments:

      • nearZMultiplier (Number, optional) - Scaler for the near plane, 1 unit equals to the height of the viewport. Default to 0.1.
      • farZMultiplier (Number, optional) - Scaler for the far plane, 1 unit equals to the distance from the camera to the top edge of the screen. Default to 1.

    Remarks:

    • width and height are forced to 1 if supplied as 0, to avoid division by zero. This is intended to reduce the burden of apps to check values before instantiating a Viewport.
    • Per cartographic tradition, longitudes and latitudes are specified as degrees.

    Inherits all Viewport methods.

    Methods

    Inherits all methods from Viewport.

    project

    Projects world coordinates to pixel coordinates on screen.

    Parameters:

    • coordinates (Array) - [longitude, latitude, altitude]. altitude is in meters and default to 0 if not supplied.
    • opts (Object)
      • topLeft (Boolean, optional) - Whether projected coords are top left. Default to true.

    Returns:

    • [x, y] or [x, y, z] in pixels coordinates. z is pixel depth.
      • If input is [longitude, latitude]: returns [x, y].
      • If input is [longitude, latitude: altitude]: returns [x, y, z].
    unproject

    Unproject pixel coordinates on screen into world coordinates.

    Parameters:

    • pixels (Array) - [x, y, z] in pixel coordinates. Passing a z is optional.
    • opts (Object)
      • topLeft (Boolean, optional) - Whether projected coords are top left. Default to true.
      • targetZ (Number, optional) - If pixel depth z is not specified in pixels, this is used as the elevation plane to unproject onto. Default 0.

    Returns:

    • [longitude, latitude] or [longitude, latitude, altitude] in world coordinates. altitude is in meters.
      • If input is [x, y] without specifying opts.targetZ: returns [longitude, latitude].
      • If input is [x, y] with opts.targetZ: returns [longitude, latitude, targetZ].
      • If input is [x, y, z]: returns [longitude, latitude, altitude].

    Source

    modules/core/src/viewports/globe-viewport.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/layer-manager.html b/docs/api-reference/core/layer-manager.html index 0c77297292b..285796c5577 100644 --- a/docs/api-reference/core/layer-manager.html +++ b/docs/api-reference/core/layer-manager.html @@ -4,13 +4,13 @@ LayerManager Class (Internal) | deck.gl - - + +

    LayerManager Class (Internal)

    The LayerManager class is gradually being refactor into a ComponentManager class and will be made part of the lifecycle directory. It is now an internal class, use the Deck class (or the DeckGL React Component) which creates a LayerManager under the hood.

    The LayerManager class manages a set of layers' lifecycle.

    For more information consult the Using Standalone article.

    Constructor

    Creates a new LayerManager instance.

    new LayerManager(gl, {eventManager: ...}})`

    Parameters:

    Methods

    needsRedraw

    Checks if layers need to be redrawn.

    layerManager.needsRedraw({clearRedrawFlags = false});

    Parameters:

    • clearRedrawFlags (Bool) - Reset the needs redraw status

    Returns:

    • true if redraw is needed.
    getLayers

    Returns an list of layers, optionally be filtered by a list of layer ids.

    const layers = layerManager.getLayers({layerIds = []});

    Parameters:

    • layerIds (String[], optional) - A list of layer id strings. If supplied, the returned list will only contain layers whose id property matches (see note) one of the strings in the list.

    Returns:

    • Layer[] - array of layer instances.

    Notes:

    • The returned list of layers is "expanded" in the sense that composite layers will have been recursively rendered and the list will thus only contain primitive layers.
    • When supplying the layer id of a composite layer, all the sub layers rendered by that layer will be included.
    • layer id matching checks that a layer id starts with one of the supplied strings. This ensures that sublayers rendered by a composite layer with the given id will also be included in the matched list.
    setLayers

    Provide a new list of layers. Layers will be matched against old layers, and any composite layers will be recursively expanded into primitive layers.

    layerManager.updateLayers({newLayers});
    • newLayers (Layer[]) - Array of layers
    updateLayers

    Updates the current list of layers.

    Source

    modules/core/src/lib/layer-manager.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/layer.html b/docs/api-reference/core/layer.html index cdaf259eb6a..724d3ed0568 100644 --- a/docs/api-reference/core/layer.html +++ b/docs/api-reference/core/layer.html @@ -4,8 +4,8 @@ Layer Class | deck.gl - - + +
    @@ -16,7 +16,7 @@ The variables may be numbers, strings, objects or functions. During each rendering cycle, deck.gl shallow-compares them with the previous values.

    Note:

    • change of the data prop has higher priority than the updateTriggers. If the app supplies a new data object, then all attributes will be automatically updated, even if the updateTriggers have not changed. To block excessive attribute updates, set the dataComparator prop.
    loaders (Array, optional)
    • Default: []

    An array of loaders.gl loaders.

    Out of the box, deck.gl supports loading JSON and image files (with ImageLoader), and specific layer implementation such as MVTLayer, TerrainLayer and ScenegraphLayer also include loaders for their targeted formats.

    Support for addtional formats can be added by adding loaders to the loaders prop. For example, to load data from CSV files:

    import {CSVLoader} from '@loaders.gl/csv';

    const layer = new HexagonLayer({
    data: './data.csv',
    loaders: [CSVLoader]
    ...
    });
    loadOptions (Object, optional)
    • Default: null

    Layers use loaders.gl to load data and other resources. loadOptions is an object to customize the behavior of any loader used during fetching and parsing. The object may contain any of the top-level options, as well as loader-specific options targeting a particular format.

    Layers may also include specialized loaders for their own use case, such as images, 3d-tiles, etc. See the documentation of each layer for additional load options that are available.

    Find usage examples in the data loading guide.

    fetch (Function, optional)

    Called to fetch and parse content from URLs.

    The function receives the following arguments:

    • url (String) - the URL to fetch
    • context (Object)
      • layer (Layer) - the current layer
      • propName (String) - the name of the prop that is making the request
      • loaders (Array?) - an array of loaders.gl loaders to parse this request with, default to props.loaders.
      • loadOptions (Object?) - loader options for this request, default to props.loadOptions.
      • signal (AbortSignal?) - the signal to abort the request

    The function is expected to return a Promise that resolves to loaded data.

    • Default: load(url, loaders, loadOptions)
    onDataLoad (Function, optional)

    Called when remote data is fully loaded. This callback applies when data is assigned a value that is either string (URL), Promise or an async iterable.

    The function receives two arguments:

    • value - the loaded data
    • context (Object)
      • layer - the current layer

    Render Properties

    parameters (Object, optional)

    The parameters allows applications to specify values for WebGL parameters such as blending mode, depth testing etc. Any parameters will be applied temporarily while rendering this layer only.

    To get access to static parameter values, applications can import GL from '@luma.gl/constants'. Please refer to the luma.gl setParameters API for documentation on supported parameters and values.

    getPolygonOffset (Function, optional)
    • Default: ({layerIndex}) => [0, -layerIndex * 100]

    When multiple layers are rendered on the same plane, z-fighting may create undesirable artifacts. To improve the visual quality of composition, deck.gl allows layers to use gl.polygonOffset to apply an offset to its depth. By default, each layer is offset a small amount by its index so that layers are cleanly stacked from bottom to top.

    This accessor takes a single parameter uniform - an object that contains the current render uniforms, and returns an array of two numbers factor and units. Negative values pull layer towards the camera, and positive values push layer away from the camera. For more information, refer to the documentation and FAQ.

    If the accessor is assigned a falsy value, polygon offset will be set to [0, 0].

    Remarks:

    • While this feature helps mitigate z-fighting, at close up zoom levels the issue might return because of the precision error of 32-bit projection matrices. Try set the fp64 prop to true in this case.
    transitions (Object, optional)
    • Default: {}

    When creating layers, animation can be enabled by supplying an transitions prop. Animation parameters are defined per attribute by using attribute names or accessor names as keys:

    new Layer({
    transitions: {
    getPositions: 600,
    getColors: {
    duration: 300,
    easing: d3.easeCubicInOut,
    enter: value => [value[0], value[1], value[2], 0] // fade in
    },
    getRadius: {
    type: 'spring',
    stiffness: 0.01,
    damping: 0.15,
    enter: value => [0] // grow from size 0
    }
    }
    });

    Each accessor name is mapped to an object that is the transition setting. The object may contain the following fields:

    KeyTypeDefaultDescription
    typeString'interpolation'Type of the transition (either 'interpolation' or 'spring')
    enterFunctionAPPEARANCE (value => value)Callback to get the value that the entering vertices are transitioning from. See notes below
    onStartFunctionnullCallback when the transition is started
    onEndFunctionnullCallback when the transition is done
    onInterruptFunctionnullCallback when the transition is interrupted

    Additional fields for type: 'interpolation':

    KeyTypeDefaultDescription
    durationNumber0Duration of the transition animation, in milliseconds
    easingFunctionLINEAR (t => t)Easing function that maps a value from [0, 1] to [0, 1], see http://easings.net/

    Additional fields for type: 'spring':

    KeyTypeDefaultDescription
    stiffnessNumber0.05"Tension" factor for the spring
    dampingNumber0.5"Friction" factor that counteracts the spring's acceleration

    Notes:

    • As a shorthand, if an accessor key maps to a number rather than an object, then the number is assigned to the duration parameter, and an interpolation transition is used.
    • Attribute transition is performed between the values at the same index. If the new data is larger, enter callback is called for each new vertex to backfill the values to transition from.
    • enter should return the value to transition from. for the current vertex. It receives two arguments:
      • toValue (TypedArray) - the new value to transition to, for the current vertex
      • fromChunk (Array | TypedArray) - the existing value to transition from, for the chunk that the current vertex belongs to. A "chunk" is a group of vertices that help the callback determine the context of this transition. For most layers, all objects are in one chunk. For PathLayer and PolygonLayer, each path/polygon is a chunk.

    Members

    Layer members are designed to support the creation of new layers or layer sub-classing and are NOT intended to be used by applications.

    context (Object)

    The context object stores information that are shared by all layers.

    state (Object)

    The state object allows a layer to store persistent information cross rendering cycles.

    props (Object)

    Properties of this layer.

    isLoaded

    true if all asynchronous assets are loaded.

    parent

    A Layer instance if this layer is rendered by a CompositeLayer

    Methods

    Layer methods are designed to support the creation of new layers or layer sub-classing and are NOT intended to be called by applications.

    General Methods

    clone
    const updatedLayer = layer.clone(overrideProps);

    Create a copy of this layer, optionally change some prop values.

    Arguments:

    • overrideProps (Object, optional) - layer props to update.
    setState

    Used to update the layers state object. Calling this method will also cause the layer to rerender.

    setModuleParameters

    Used to update the settings of shader modules.

    raiseError

    Used to propagate errors thrown in layers to the deck.gl error handling system. This prevents rendering from being interrupted by exceptions in layers.

    raiseError(error, message)

    • error (Error) - a JavaScript Error object
    • message (String, optional) - additional contextual description to amend the error message with

    Layer Lifecycle Methods

    For more information about when these methods are called, see layer lifecycle.

    initializeState

    This method is called only once for each layer to set up the initial state.

    initializeState(context)

    • context - The layer context is supplied as a parameter
      • context.gl (WebGL2RenderingContext) - gl context
      • ...

    deck.gl will already have created the state object at this time, and added the gl context and the attributeManager state.

    shouldUpdateState

    Called during each rendering cycle when layer properties or context has been updated and before layers are drawn.

    shouldUpdateState({props, oldProps, context, changeFlags})

    Parameters:

    • props (Object) - Layer properties from the current rendering cycle.
    • oldProps (Object) - Layer properties from the previous rendering cycle.
    • context (Object) - Layer context from the current rendering cycle.
    • changeFlags:
      • an object that contains the following boolean flags:
      • dataChanged, propsChanged, viewportChanged, somethingChanged, propsOrDataChanged, stateChanged, updateTriggersChanged, viewportChanged

    Returns:

    • true this layer needs to be updated.

    Remarks:

    • Prop change is determined by shallow comparison.
    • Data change is determined by shallow comparison of props.data unless dataComparator is supplied.
    • The default implementation returns true if any change has been detected in data or props, but ignores viewport changes.
    updateState

    Called when a layer needs to be updated.

    updateState({props, oldProps, context, changeFlags})

    Parameters:

    • props (Object) - Layer properties from the current rendering cycle.
    • oldProps (Object) - Layer properties from the previous rendering cycle.
    • context (Object) - Layer context from the current rendering cycle.
    • changeFlags:
      • an object that contains the following boolean flags:
      • dataChanged, propsChanged, viewportChanged, somethingChanged, propsOrDataChanged, stateChanged, updateTriggersChanged, viewportChanged

    The default implementation will invalidate all attributeManager attributes if the data prop has changed.

    draw

    Called on a layer to render to the WebGL canvas.

    draw({moduleParameters, uniforms, ..., context})

    Parameters:

    • uniforms:

    • an object that contains all the default unforms to be passed to the shaders.

    • context - The layer context is supplied as a parameter

      • context.gl (WebGL2RenderingContext) - gl context
      • ...

    The default implementation looks for a variable model in the layer's state (which is expected to be an instance of the luma.gl Model class) and calls draw on that model with the parameters.

    getPickingInfo

    Called when a layer is being hovered or clicked, before any user callbacks are called. The layer can override or add additional fields to the info object that will be passed to the callbacks.

    Parameters:

    • pickParams (Object)

      • pickParams.info (Object) - The current info object. By default it contains the following fields:

        • x (Number) - Mouse position x relative to the viewport.
        • y (Number) - Mouse position y relative to the viewport.
        • coordinate ([Number, Number]) - Mouse position in world coordinates. Only applies if coordinateSystem is COORDINATE_SYSTEM.LNGLAT.
        • color (Number[4]) - The color of the pixel that is being picked. It represents a "picking color" that is encoded by layer.encodePickingColor().
        • index (Number) - The index of the object that is being picked. It is the returned value of layer.decodePickingColor().
        • picked (Boolean) - true if index is not -1.
      • pickParams.mode (String) - One of hover and click

    Returns:

    • An info object with optional fields about what was picked. This object will be passed to the layer's onHover or onClick callbacks.
    • null, if the corresponding event should cancelled with no callback functions called.

    The default implementation populates the info.object field with the info.index element from the layer's data prop.

    finalizeState

    This method is called before the layer is being removed. A layer should release all resources created during its life span.

    Layer Projection Methods

    While most projection is handled "automatically" in the layers vertex shader, it is occasionally useful to be able to work in the projected coordinates in JavaScript while calculating uniforms etc.

    project

    Projects a map coordinate to screen coordinate, using the current viewport settings and the current coordinate system.

    Parameters:

    • coordinates (Array) - [x, y, z] in this layer's coordinate system.

    Returns:

    • A screen coordinates array [x, y] or [x, y, z] if an altitude was given.
    unproject

    Unprojects a screen coordinate using the current viewport settings.

    Parameters:

    • pixels (Array) - [x, y, z] Passing a z is optional.

    Returns:

    • A map coordinates array [lng, lat] or [lng, lat, altitude] if a z was given.
    projectPosition

    Projects a map coordinate to world coordinate using the current viewport settings and the current coordinate system. Can be useful to calculate world space angle and distances.

    Parameters:

    • coordinates (Array) - [x, y, z] in this layer's coordinate system.
    • params (Object, optional) - Projection parameters override. It accepts the following fields:
      • viewport (Viewport) - defaults to this.context.viewport.
      • modelMatrix (Matrix4) - defaults to this.props.modelMatrix.
      • coordinateOrigin ([Number, Number, Number]) - defaults to this.props.coordinateOrigin.
      • coordinateSystem (Number) - defaults to this.props.coordinateSystem.
      • fromCoordinateOrigin ([Number, Number, Number]) - defaults to passed coordinateOrigin.
      • fromCoordinateSystem (Number) - defaults to passed coordinateSystem.

    Returns:

    • World coordinates in [x, y].

    Layer Picking Methods

    For the usage of these methods, see how picking works.

    decodePickingColor

    Converts a color to a "sub-feature index" number. This color is encoded by the layer.encodePickingColor() method.

    Parameters:

    • color (Array) - The color to be decoded in [r, g, b].

    Returns:

    • A number representing the index of the feature. The null picking color (See Layer.nullPickingColor) will be decoded as -1.

    Note:

    • The null picking color is returned when a pixel is picked that is not covered by the layer, or when the layer has selected to render a pixel using the null picking color to make it unpickable.
    encodePickingColor

    Converts a "sub-feature index" number to a color. This color can later be decoded by the layer.decodePickingColor() method.

    Parameters:

    • index (Integer) - The index to be encoded.

    Returns:

    • An array of [r, g, b].

    To get a color that does not correspond to any sub-feature, use layer.nullPickingColor().

    Notes:

    • indices to be encoded must be integers larger than or equal to 0.
    • Picking colors are 24 bit values and can thus encode up to 16 million indices.
    nullPickingColor

    Returns:

    • a "null" picking color which is equal the color of pixels not covered by the layer. This color is guaranteed not to match any index value greater than or equal to zero.

    Source

    modules/core/src/lib/layer.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/lighting-effect.html b/docs/api-reference/core/lighting-effect.html index fdcf68aacc2..771de7963ab 100644 --- a/docs/api-reference/core/lighting-effect.html +++ b/docs/api-reference/core/lighting-effect.html @@ -4,13 +4,13 @@ LightingEffect | deck.gl - - + +

    LightingEffect

    The LightingEffect applies ambient, point and directional lighting to layers which support material property.

    Constructor

    new LightingEffect({light0, light1, light2, ...});

    Parameters:

    • lights(Object) - a collection of light sources. Keys can be any arbitrary name and values.

    Members

    Light Sources

    ambientLight (Object, optional)

    An AmbientLight source which illuminates all the objects equally.

    • Default: ambient light source with color = [255, 255, 255] and intensity = 1.0
    directionalLights (Array, optional)

    Array of DirectionalLight source which emits from a specific directions.

    • Default: two directional light sources
    Light SourceColorIntensityDirection_shadow
    1[255, 255, 255]1.0[-1, -3, -1]false
    2[255, 255, 255]0.9[1, 8, -2.5]false
    • For rendering experimental shadow effect, _shadow prop of DirectionalLight must be set to true. The effect can be toggled on and off for a layer by setting layer's shadowEnabled prop.
    pointLights (Array, optional)

    Array of PointLight source which emits from a point in all directions.

    • Default: []

    Remarks

    • Only one ambient light is supported.
    • Point light position uses the same coordinate system as view state.

    Source

    /modules/core/src/effects/lighting/lighting-effect.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/linear-interpolator.html b/docs/api-reference/core/linear-interpolator.html index ca900193a0b..8245f92f7ea 100644 --- a/docs/api-reference/core/linear-interpolator.html +++ b/docs/api-reference/core/linear-interpolator.html @@ -4,13 +4,13 @@ LinearInterpolator | deck.gl - - + +

    LinearInterpolator

    Performs simple linear interpolation between two view states. Implements TransitionInterpolator.

    See View State Transitions for usage examples.

    Constructor

    import {LinearInterpolator} from '@deck.gl/core';

    new LinearInterpolator({transitionProps: ['target', 'zoom']});

    Parameters:

    • options (Object)
      • transitionProps (Array, optional) - Array of prop names that should be linearly interpolated. Default ['longitude', 'latitude', 'zoom', 'bearing', 'pitch'].
      • around (Array, optional) - A point to zoom/rotate around, [x, y] in screen pixels. If provided, the location at this point will not move during the transition.
      • makeViewport (Function, optional) - Called to construct a viewport, e.g. props => new WebMercatorViewport(props). Must be provided if around is used.

    Source

    modules/core/src/transitions/linear-interpolator.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/map-controller.html b/docs/api-reference/core/map-controller.html index 1960f056268..7da26f5d93d 100644 --- a/docs/api-reference/core/map-controller.html +++ b/docs/api-reference/core/map-controller.html @@ -4,13 +4,13 @@ MapController | deck.gl - - + +

    MapController

    Inherits from Base Controller.

    The MapController class can be passed to either the Deck class's controller prop or a View class's controller prop to specify that map interaction should be enabled.

    MapController is the default controller for MapView..

    Usage

    Use with the default view:

    import {Deck} from '@deck.gl/core';

    new Deck({
    controller: {doubleClickZoom: false, inertia: true},
    initialViewState: viewState
    });

    is equivalent to:

    import {Deck} from '@deck.gl/core';

    new Deck({
    views: new MapView({
    controller: {doubleClickZoom: false, inertia: true}
    }),
    initialViewState: viewState
    })

    Options

    Supports all Controller options with the following default behavior:

    • dragMode - default 'pan' (drag to pan, shift/ctrl + drag to rotate)
    • keyboard - arrow keys to pan, arrow keys with shift/ctrl down to rotate, +/- to zoom
    • normalize - normalize viewport props to fit map height into viewport. Default true

    Custom MapController

    You can further customize the MapController's behavior by extending the class:

    import {Deck, MapController} from '@deck.gl/core';

    class MyMapController extends MapController {

    handleEvent(event) {
    if (event.type === 'pan') {
    // do something
    } else {
    super.handleEvent(event);
    }
    }
    }

    new Deck({
    controller: {type: MyMapController},
    initialViewState: viewState
    })

    See the Controller class documentation for the methods that you can use and/or override.

    Source

    modules/core/src/controllers/map-controller.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/map-view.html b/docs/api-reference/core/map-view.html index 88b1be4838d..016ec7355a6 100644 --- a/docs/api-reference/core/map-view.html +++ b/docs/api-reference/core/map-view.html @@ -4,13 +4,13 @@ MapView | deck.gl - - + +

    MapView

    The MapView class is a subclass of View. This viewport creates a camera that looks at a geospatial location on a map from a certain direction. The behavior of MapView is generally modeled after that of Mapbox GL JS.

    It's recommended that you read the Views and Projections guide before using this class.

    Constructor

    import {MapView} from '@deck.gl/core';
    const view = new MapView({id, ...});

    MapView takes the same parameters as the View superclass constructor, plus the following:

    repeat (Boolean, optional)

    Whether to render multiple copies of the map at low zoom levels. Default false.

    nearZMultiplier (Number, optional)

    Scaler for the near plane, 1 unit equals to the height of the viewport. Default to 0.1. Overwrites the near parameter.

    farZMultiplier (Number, optional)

    Scaler for the far plane, 1 unit equals to the distance from the camera to the top edge of the screen. Default to 1.01. Overwrites the far parameter.

    projectionMatrix (Array[16], optional)

    Projection matrix.

    If projectionMatrix is not supplied, the View class will build a projection matrix from the following parameters:

    fovy (Number, optional)

    Field of view covered by the camera, in the perspective case. In degrees. If not supplied, will be calculated from altitude.

    altitude (Number, optional)

    Distance of the camera relative to viewport height. Default 1.5.

    orthographic (Boolean)

    Whether to create an orthographic or perspective projection matrix. Default is false (perspective projection).

    View State

    To render, MapView needs to be used together with a viewState with the following parameters:

    • longitude (Number) - longitude at the map center
    • latitude (Number) - latitude at the map center
    • zoom (Number) - zoom level
    • pitch (Number, optional) - pitch angle in degrees. Default 0 (top-down).
    • bearing (Number, optional) - bearing angle in degrees. Default 0 (north).
    • maxZoom (Number, optional) - max zoom level. Default 20.
    • minZoom (Number, optional) - min zoom level. Default 0.
    • maxPitch (Number, optional) - max pitch angle. Default 60.
    • minPitch (Number, optional) - min pitch angle. Default 0.
    • position (Array, optional) - Viewport center offsets from lng, lat in meters. Default: [0,0,0].

    Controller

    By default, MapView uses the MapController to handle interactivity. To enable the controller, use:

    const view = new MapView({id: 'base-map', controller: true});

    Visit the MapController documentation for a full list of supported options.

    Source

    modules/core/src/views/map-view.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/orbit-controller.html b/docs/api-reference/core/orbit-controller.html index 1093067220b..30eee134873 100644 --- a/docs/api-reference/core/orbit-controller.html +++ b/docs/api-reference/core/orbit-controller.html @@ -4,13 +4,13 @@ OrbitController | deck.gl - - + +

    OrbitController

    Inherits from Base Controller.

    The OrbitController class can be passed to either the Deck class's controller prop or a View class's controller prop to specify that viewport interaction should be enabled.

    OrbitController is the default controller for OrbitView.

    Usage

    Use with the default view:

    import {Deck, OrbitView} from '@deck.gl/core';

    new Deck({
    views: new OrbitView(),
    controller: {dragPan: false, inertia: true},
    initialViewState: viewState
    });

    is equivalent to:

    import {Deck, OrbitView} from '@deck.gl/core';

    new Deck({
    views: new OrbitView({
    controller: {dragPan: false, inertia: true}
    }),
    initialViewState: viewState
    })

    Options

    Supports all Controller options with the following default behavior:

    • dragMode: default 'rotate' (drag to rotate, shift/ctrl + drag to pan)
    • keyboard: arrow keys to pan, arrow keys with shift/ctrl down to rotate, +/- to zoom

    Custom OrbitController

    You can further customize the OrbitController's behavior by extending the class:

    import {Deck, OrbitView, OrbitController} from '@deck.gl/core';

    class MyOrbitController extends OrbitController {

    handleEvent(event) {
    if (event.type === 'pan') {
    // do something
    } else {
    super.handleEvent(event);
    }
    }
    }

    new Deck({
    views: new OrbitView(),
    controller: {type: MyOrbitController},
    initialViewState: viewState
    })

    See the Controller class documentation for the methods that you can use and/or override.

    Source

    modules/core/src/controllers/orbit-controller.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/orbit-view.html b/docs/api-reference/core/orbit-view.html index f9906792c95..e9c52b86b48 100644 --- a/docs/api-reference/core/orbit-view.html +++ b/docs/api-reference/core/orbit-view.html @@ -4,13 +4,13 @@ OrbitView | deck.gl - - + +

    OrbitView

    The OrbitView class is a subclass of View that creates a 3D camera that rotates around a target position. It is usually used for the examination of a 3D scene in non-geospatial use cases.

    It's recommended that you read the Views and Projections guide before using this class.

    Constructor

    import {OrbitView} from '@deck.gl/core';
    const view = new OrbitView({id, ...});

    OrbitView takes the same parameters as the View superclass constructor, plus the following:

    orbitAxis (String, optional)

    Axis with 360 degrees rotating freedom, either 'Y' or 'Z', default to 'Z'.

    projectionMatrix (Array[16], optional)

    Projection matrix.

    If projectionMatrix is not supplied, the View class will build a projection matrix from the following parameters:

    fovy (Number, optional)

    Field of view covered by camera, in the perspective case. In degrees. Default 50.

    near (Number, optional)

    Distance of near clipping plane. Default 0.1.

    far (Number, optional)

    Distance of far clipping plane. Default 1000.

    orthographic (Boolean)

    Whether to create an orthographic or perspective projection matrix. Default is false (perspective projection).

    View State

    To render, OrbitView needs to be used together with a viewState with the following parameters:

    • target (Number[3], optional) - The world position at the center of the viewport. Default [0, 0, 0].
    • rotationOrbit (Number, optional) - Rotating angle around orbit axis. Default 0.
    • rotationX (Number, optional) - Rotating angle around X axis. Default 0.
    • zoom (Number, optional) - The zoom level of the viewport. zoom: 0 maps one unit distance to one pixel on screen, and increasing zoom by 1 scales the same object to twice as large. Default 0.
    • minZoom (Number, optional) - The min zoom level of the viewport. Default -Infinity.
    • maxZoom (Number, optional) - The max zoom level of the viewport. Default Infinity.
    • minRotationX (Number, optional) - The min rotating angle around X axis. Default -90.
    • maxRotationX (Number, optional) - The max rotating angle around X axis. Default 90.

    Controller

    By default, OrbitView uses the OrbitController to handle interactivity. To enable the controller, use:

    const view = new OrbitView({id: '3d-scene', controller: true});

    Visit the OrbitController documentation for a full list of supported options.

    Source

    modules/core/src/views/orbit-view.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/orthographic-controller.html b/docs/api-reference/core/orthographic-controller.html index a41edbc6bd3..08279717259 100644 --- a/docs/api-reference/core/orthographic-controller.html +++ b/docs/api-reference/core/orthographic-controller.html @@ -4,13 +4,13 @@ OrthographicController | deck.gl - - + +

    OrthographicController

    Inherits from Base Controller.

    The OrthographicController class can be passed to either the Deck class's controller prop or a View class's controller prop to specify that viewport interaction should be enabled.

    OrthographicController is the default controller for OrthographicView.

    Usage

    Use with the default view:

    import {Deck, OrthographicView} from '@deck.gl/core';

    new Deck({
    views: new OrthographicView(),
    controller: {scrollZoom: false, inertia: true},
    initialViewState: viewState
    });

    is equivalent to:

    import {Deck, OrthographicView} from '@deck.gl/core';

    new Deck({
    views: new OrthographicView({
    controller: {scrollZoom: false, inertia: true}
    }),
    initialViewState: viewState
    })

    Options

    Supports all Controller options with the following default behavior:

    • dragPan: default 'pan' (drag to pan)
    • dragRotate: not effective, this view cannot be rotated
    • touchRotate: not effective, this view cannot be rotated
    • keyboard: arrow keys to pan, +/- to zoom

    Also accepts additional options:

    • zoomAxis (String) - which axes to apply zoom to. Affects scroll, keyboard +/- and double tap. One of X (zoom along the X axis only), Y (zoom along the Y axis only), all. Default all. If this option is set to X or Y, viewState.zoom must be an array to enable independent zoom for each axis.

    Custom OrthographicController

    You can further customize the OrthographicController's behavior by extending the class:

    import {Deck, OrthographicView, OrthographicController} from '@deck.gl/core';

    class MyOrthographicController extends OrthographicController {

    handleEvent(event) {
    if (event.type === 'pan') {
    // do something
    } else {
    super.handleEvent(event);
    }
    }
    }

    new Deck({
    views: new OrthographicView(),
    controller: {type: MyOrthographicController},
    initialViewState: viewState
    })

    See the Controller class documentation for the methods that you can use and/or override.

    Source

    modules/core/src/controllers/orthographic-controller.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/orthographic-view.html b/docs/api-reference/core/orthographic-view.html index 151759b8bcb..e4cc9234cd0 100644 --- a/docs/api-reference/core/orthographic-view.html +++ b/docs/api-reference/core/orthographic-view.html @@ -4,13 +4,13 @@ OrthographicView | deck.gl - - + +

    OrthographicView

    The OrthographicView class is a subclass of View that creates a top-down view of the XY plane. It is usually used for rendering 2D charts in non-geospatial use cases.

    It's recommended that you read the Views and Projections guide before using this class.

    Constructor

    import {OrthographicView} from '@deck.gl/core';
    const view = new OrthographicView({id, ...});

    OrthographicView takes the same parameters as the View superclass constructor, plus the following:

    flipY (Boolean)

    Whether to use top-left coordinates (true) or bottom-left coordinates (false). Default true.

    near (Number, optional)

    Distance of near clipping plane. Default 0.1.

    far (Number, optional)

    Distance of far clipping plane. Default 1000.

    View State

    To render, OrthographicView needs to be used together with a viewState with the following parameters:

    • target (Number[3], optional) - The world position at the center of the viewport. Default [0, 0, 0].
    • zoom (Number|Number[2], optional) - The zoom level of the viewport. zoom: 0 maps one unit distance to one pixel on screen, and increasing zoom by 1 scales the same object to twice as large. For example zoom: 1 is 2x the original size, zoom: 2 is 4x, zoom: 3 is 8x etc.. To apply independent zoom levels to the X and Y axes, supply an array [zoomX, zoomY]. Default 0.
    • minZoom (Number, optional) - The min zoom level of the viewport. Default -Infinity.
    • maxZoom (Number, optional) - The max zoom level of the viewport. Default Infinity.

    Controller

    By default, OrthographicView uses the OrthographicController to handle interactivity. To enable the controller, use:

    const view = new OrthographicView({id: '2d-scene', controller: true});

    Visit the OrthographicController documentation for a full list of supported options.

    Source

    modules/core/src/views/orthographic-view.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/point-light.html b/docs/api-reference/core/point-light.html index 97395370723..ee358a952fc 100644 --- a/docs/api-reference/core/point-light.html +++ b/docs/api-reference/core/point-light.html @@ -4,13 +4,13 @@ PointLight | deck.gl - - + +

    PointLight

    Create a point light source which emits from a point in all directions.Point lights attenuation is not available. At most 5 directional lights can be supported.

    Two spheres with point light

    Usage

    Create a point light source with color, intensity and position.

    const pointLight= new PointLight({
    color: [128, 128, 0],
    intensity: 2.0,
    position: [0, 0, 200]
    });

    Methods

    constructor

    The constructor for the PointLight class. Use this to create a new PointLight.

    const pointLight = new PointLight({color, intensity, position});

    Parameters

    • color - (array,) RGB color of point light source, default value is [255, 255, 255].
    • intensity - (number) Strength of point light source, default value is 1.0.
    • position - (array,) Location of point light source, default value is [0, 0, 1].The coordinate system of the position depends on the current view: [longitude, latitude, altitude] in geospatial views and world position in non-geospatial views.

    Source

    /modules/core/src/effects/lighting/point-light.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/post-process-effect.html b/docs/api-reference/core/post-process-effect.html index 36e08f9c8e6..5b7d86a211b 100644 --- a/docs/api-reference/core/post-process-effect.html +++ b/docs/api-reference/core/post-process-effect.html @@ -4,13 +4,13 @@ PostProcessEffect | deck.gl - - + +

    PostProcessEffect

    The PostProcessEffect applies screen space pixel manipulation effects to deck.gl layers.

    Constructor

    new PostProcessEffect(shaderModule, props);

    Parameters:

    • shaderModule(Object) - a shader module wraps a screen space effect. For supported effects see luma.gl shader modules.
    • props(Object) - parameters to replace the default values in shader module.

    Example

    import {brightnessContrast} from '@luma.gl/shadertools';
    import {PostProcessEffect} from '@deck.gl/core';

    const postProcessEffect = new PostProcessEffect(brightnessContrast, {
    brightness: 1.0,
    contrast: 1.0
    });

    const deckgl = new Deck({
    canvas: 'my-deck-canvas',
    initialViewState,
    controller: true,
    // add effect to deck
    effects: [postProcessEffect],
    layers: [new GeoJsonLayer({
    ...
    })]
    });

    Source

    /modules/core/src/effects/post-process-effect.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/project.html b/docs/api-reference/core/project.html index b9be2190719..ec592d86c9d 100644 --- a/docs/api-reference/core/project.html +++ b/docs/api-reference/core/project.html @@ -4,13 +4,13 @@ project (Shader Module) | deck.gl - - + +

    project (Shader Module)

    The project shader module is part of the core of deck.gl. It makes it easy to write shaders that support all of deck.gl's projection modes and it supports some advanced rendering techniques such as pixel space rendering etc.

    The project module has two extensions:

    • project32 shorthand functions for projecting directly from worldspace to clipspace.
    • project64 counterpart of project32 that enables 64 bit projections, providing an increase in precision, at the cost of performance.

    Usage

    Projects worldspace coordinates to clipspace coordinates.

    // instanced geometry
    in vec3 positions;
    // instance attributes
    in vec3 instanceCenter;
    in float instanceSize;

    void main(void) {
    vec3 center = project_position(instanceCenter);
    vec3 vertex = positions * project_size(instanceSize);
    gl_Position = project_common_position_to_clipspace(center + vertex);
    }

    getUniforms

    The JavaScript uniforms are extracted from both contextual and per-layer props. The following information are used:

    • viewport
    • devicePixelRatio
    • coordinateSystem
    • coordinateOrigin
    • modelMatrix

    GLSL Uniforms

    Uniforms are considered private to each shader module. They may change in between patch releases. Always use documented functions instead of accessing module uniforms directly.

    The uniforms of the project shader module are prefixed with project_ in their names.

    GLSL Functions

    The projection module enables you to write vertex shaders that support deck.gl's coordinate systems and projection methods. Using the projection module ensures that you layer will be able accept position coordinates in the various formats supported by deck.gl, such as [longitude, latitude, altitude] or [metersX, metersY, metersZ]. To support the basic features expected of a deck.gl layer, such as various viewport types and coordinate systems, your own shaders should always use the built-in projection functions.

    The functions converts positions/vectors between 4 coordinate spaces:

    NameShort NameDescription
    World spaceworldThe coordinate system defined by the layer, not necessarily linear or uniform.
    Common spacecommonA normalized intermediate 3D space that deck.gl uses for consistent processing of geometries, guaranteed to be linear and uniform. Therefore, it is safe to add/rotate/scale positions and vectors in this space.
    Screen spacepixelTop-left coordinate system runs from [0, 0] to [viewportWidth, viewportHeight] (see remarks below).
    Clip spaceclipspaceOutput of the vertex shader.

    More detailed explanation of each coordinate space can be found in the coordinate systems guide.

    The GLSL functions of the project shader module uses the following naming convention:

    project_[<source_space>]_<object_type>_[to_<target_space>]
    • source_space: the short name of the coordinate space of the input. If not specified, the input is always in the world space.
    • object_type: one of the following
      • position: absolute position of a point
      • offset: the delta between two positions
      • normal: the normal vector of a surface
      • size: the measurement of a geometry. This is different from offset in that size is uniform on all axes (e.g. [x, y, z] in meters in LNGLAT world space) and offset may not be (e.g. [dLon, dLat, dAlt] in degrees, degrees, and meters respectively in LNGLAT world space).
    • target_space: the short name of the coordinate space of the output. If not specified, the output is always in the common space.

    project_position

    vec2 project_position(vec2 position)
    vec3 project_position(vec3 position)
    vec3 project_position(vec3 position, vec3 position64Low)
    vec4 project_position(vec4 position)
    vec4 project_position(vec4 position, vec3 position64Low)

    Converts the coordinates of a point from the world space to the common space. The coordinates are interpreted according to coordinateSystem and modelMatrix is applied.

    project_size

    float project_size(float meters)
    vec2 project_size(vec2 meters)
    vec3 project_size(vec3 meters)
    vec4 project_size(vec4 meters)

    Converts the size of a geometry from the world space (meters if geospatial, and absolute units otherwise) to the common space.

    project_size_to_pixel

    float project_size_to_pixel(float size)
    float project_size_to_pixel(float size, int units)

    Converts the size of a geometry from the given units in the world space to the common space. If unspecified, units is meters. The result corresponds to the number of screen pixels when the given size is viewed with a top-down camera.

    project_pixel_size

    float project_pixel_size(float pixels)
    float project_pixel_size(vec2 pixels)

    Converts the size of a geometry from the screen space to the common space.

    project_pixel_size_to_clipspace

    vec2 project_pixel_size_to_clipspace(vec2 pixels)

    Converts the size of a geometry from the screen space to the clip space.

    project_normal

    vec3 project_normal(vec3 vector)

    Converts position deltas from the world space to normalized vector in the common space.

    project_common_position_to_clipspace

    vec4 project_common_position_to_clipspace(vec4 position)

    Converts the coordinates of a point from the common space to the clip space, which can be assigned to gl_Position as the "return value" from the vertex shader.

    project_get_orientation_matrix

    mat3 project_get_orientation_matrix(vec3 up)

    Returns a matrix that rotates any vector defined in the default common space to a new orientation, such that vec3(0, 0, 1) is aligned with up. up is a normal in common space.

    Remarks

    • For consistent results, the screen space pixels are logical pixels, not device pixels, i.e. functions in the project module multiply pixels with project_uDevicePixelRatio.
    • The pixels offsets will be divided by the w coordinate of gl_Position. This is simply the GPUs standard treatment of any coordinate. This means that there will be more pixels closer to the camera and less pixels further away from the camer. Setting the focalDistance uniform controls this.
    • To avoid pixel sizes scaling with distance from camera, simply set focalDistance to 1 and multiply clipspace offset with gl_Position.w
    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/project32.html b/docs/api-reference/core/project32.html index 6af47f15f11..a7ffed523c0 100644 --- a/docs/api-reference/core/project32.html +++ b/docs/api-reference/core/project32.html @@ -4,14 +4,14 @@ project32 (Shader Module) | deck.gl - - + +

    project32 (Shader Module)

    The project32 shader module is an extension of the project shader module that adds some projection utilities.

    GLSL Functions

    project_position_to_clipspace

    32 bit implementation of the project_position_to_clipspace interface.

    vec4 project_position_to_clipspace(vec3 position, vec3 position64Low, vec3 offset)
    vec4 project_position_to_clipspace(vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition)

    Parameters:

    • position - vertex position in the layer's coordinate system.
    • position64Low - lower part of the vertex position, calculated as aLow = a - Math.fround(a).
    • offset - offset from the coordinate, in common space
    • commonPosition - projected position in the common space

    Returns: Projected position in the clipspace.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/project64.html b/docs/api-reference/core/project64.html index 838eabab5c6..6cfb5a03896 100644 --- a/docs/api-reference/core/project64.html +++ b/docs/api-reference/core/project64.html @@ -4,14 +4,14 @@ project64 (Shader Module) | deck.gl - - + +

    project64 (Shader Module)

    The project64 shader module is an extension of the project shader module that does projection using 64 bit floating point. It provides an increase in precision, at the cost of performance. Note that starting with deck.gl v6.1, the improved default 32 bit projection mode provides sufficient precision for most use cases.

    getUniforms

    The uniforms needed by project64 are extracted from the project module uniforms project_uViewProjectionMatrix and project_uScale.

    GLSL Uniforms

    Uniforms are considered private to each shader module. They may change in between patch releases. Always use documented functions instead of accessing module uniforms directly.

    The uniforms of the project64 shader module are prefixed with project64_ in their names.

    GLSL Functions

    project_position_to_clipspace

    64 bit implementation of the project_position_to_clipspace interface.

    vec4 project_position_to_clipspace(vec3 position, vec3 position64Low, vec3 offset)
    vec4 project_position_to_clipspace(vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition)

    Parameters:

    • position - vertex position in the layer's coordinate system.
    • position64Low - low part of the vertex position, calculated as aLow = a - Math.fround(a).
    • offset - offset from the coordinate, in common space
    • commonPosition - projected position in the common space

    Returns: Projected position in the clipspace.

    project_position_fp64

    64 bit counterpart of the project modules project_position

    void project_position_fp64(vec4 position_fp64, out vec2 out_val[2])
    void project_position_fp64(vec2 position, vec2 position64Low, out vec2 out_val[2])

    project_common_position_to_clipspace_fp64

    64 bit counterpart of the project modules project_common_position_to_clipspace

    vec4 project_to_clipspace_fp64(vec2 vertex_pos_modelspace[4])

    Remarks

    • project64 depends on luma.gl's fp64 module which is a big and complex shader module, which means that project64 is a big dependency for your shader.
    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/sun-light.html b/docs/api-reference/core/sun-light.html index e889eee8753..9d492892bfd 100644 --- a/docs/api-reference/core/sun-light.html +++ b/docs/api-reference/core/sun-light.html @@ -4,13 +4,13 @@ SunLight (Experimental) | deck.gl - - + +

    SunLight (Experimental)

    SunLight is a directional light source simulating the sun. Sun position calculations are based on article and inspired by SunCalc.

    Usage

    Create a sun light source.

    import {_SunLight as SunLight} from '@deck.gl/core';

    new SunLight({
    timestamp: 1554927200000,
    color: [255, 0, 0],
    intensity: 1
    });

    constructor

    The constructor for the SunLight class. Use this to create a new SunLight.

    const sunLight = new SunLight({timestamp, color, intensity});
    • timestamp - (number) - Unix timestamp in milliseconds.
    • color - (array) RGB color of sun light source, default value is [255, 255, 255].
    • intensity - (number) Strength of sun light source, default value is 1.0.

    Source

    /modules/core/src/effects/lighting/sun-light.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/transition-interpolator.html b/docs/api-reference/core/transition-interpolator.html index 68f4a4a9b6a..c8183e471af 100644 --- a/docs/api-reference/core/transition-interpolator.html +++ b/docs/api-reference/core/transition-interpolator.html @@ -4,13 +4,13 @@ TransitionInterpolator | deck.gl - - + +

    TransitionInterpolator

    Base interpolator class that provides common functionality required to interpolate between two View States. This class is not intended to be used directly. See View State Transitions for backgrounds.

    Example

    import {TransitionInterpolator} from '@deck.gl/core';

    // Interpolate between two values
    function lerp(from, to, t) {
    return from + (to - from) * t;
    }

    /*
    * This interpolator moves the camera along a straight path on the Web Mercator map
    * Horizontally it moves in the direction that is shorter
    */
    class SphericalLinearInterpolator extends TransitionInterpolator {
    constructor({speed = 100} = {}) {
    super(['longitude', 'latitude']);

    // degrees per second
    this.speed = speed;
    }

    getDuration(startViewState, endViewState) {
    const deltaLat = Math.abs(startViewState.latitude - endViewState.latitude);
    let deltaLng = Math.abs(startViewState.longitude - endViewState.longitude);
    // Transition to the destination longitude along the smaller half of the circle
    if (deltaLng > 180) deltaLng = 360 - deltaLng;
    return Math.max(deltaLng, deltaLat) / this.speed * 1000;
    }

    initializeProps(startViewState, endViewState) {
    const fromLng = startViewState.longitude;
    let toLng = endViewState.longitude;
    // Transition to the destination longitude along the smaller half of the latitude circle
    if (toLng > fromLng + 180) toLng -= 360;
    if (toLng < fromLng - 180) toLng += 360;

    return {
    start: {longitude: fromLng, latitude: startViewState.latitude},
    end: {longitude: toLng, latitude: endViewState.latitude}
    };
    }

    interpolateProps(start, end, t) {
    const latitude = lerp(start.latitude, end.latitude, t);
    let longitude = lerp(start.longitude, end.longitude, t);
    // Put longitude back into the [-180, 180] range
    if (longitude > 180) longitude -= 360;
    if (longitude < -180) longitude += 360;

    return {longitude, latitude};
    }
    }

    Constructor

    Parameters:

    • opts (Object | Array)
      • If an object is provided, it should contain the following fields:
        • compare (Array) - prop names used in equality check. Transition is triggered if some of the compare props are not deeply equal.
        • extract (Array) - prop names needed for interpolation. See initializeProps below.
        • required (Array) - prop names that must be supplied. See initializeProps below.
      • If an array is provided, the same list of prop names is used for all three above.

    Interface

    getDuration

    This method can be optionally implemented by a subclass. If implemented, the user can specify transitionDuration: 'auto' when using this interpolator, and the duration will be dynamically computed using this method.

    Receives the following arguments:

    • startViewState (Object) - the view state that is transitioning from.
    • endViewState (Object) - the view state that is transitioning to.

    Returns:

    • A number in milliseconds representing the target duration of the transition. If 0, transition is disabled.
    initializeProps

    Called when a transition is about to be triggered. This can be used to preprocess values for use in every transition frame by interpolateProps.

    Receives the following arguments:

    • startViewState (Object) - the view state that is transitioning from.
    • endViewState (Object) - the view state that is transitioning to.

    Returns:

    • An object in the shape of {start, end} that will be passed to interpolateProps.

    The default implementation takes all values of the extract prop names from the start and end view states.

    If some required prop names are missing from the view state, an error will be thrown.

    interpolateProps

    This method must be implemented by a subclasses.

    Receives the following arguments:

    • start (Object) - descriptor of the state that is transitioning from, generated by initializeProps.
    • end (Object) - descriptor of the state that is transitioning to, generated by initializeProps.
    • t (Number) - current time into the transition, between 0 and 1.

    Returns:

    • An object that contains the interpolated view state fields.

    Source

    modules/core/src/transitions/transition-interpolator.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/view.html b/docs/api-reference/core/view.html index 302a4dac47e..5435fbd6b8e 100644 --- a/docs/api-reference/core/view.html +++ b/docs/api-reference/core/view.html @@ -4,13 +4,13 @@ View Class | deck.gl - - + +

    View Class

    For detailed explanations and code examples about deck.gl's views system, visit the Views and Projections article.

    The View class and its subclasses are used to specify where and how your deck.gl layers should be rendered. Applications typically instantiate at least one View subclass.

    Views allow you to specify:

    • A unique id.
    • The position and extent of the view on the canvas: x, y, width, and height.
    • Certain camera parameters specifying how your data should be projected into this view, e.g. field of view, near/far planes, perspective vs. orthographic, etc.
    • The controller to be used for this view. A controller listens to pointer events and touch gestures, and translates user input into changes in the view state. If enabled, the camera becomes interactive.

    deck.gl offers a set of View classes that package the camera and controller logic that you need to visualize and interact with your data. You may choose one or multiple View classes based on the type of data (e.g. geospatial, 2D chart) and the desired perspective (top down, first-person, etc).

    Constructor

    const view = new View({id, x, y, width, height, ...});

    Parameters:

    id (String, optional)

    A unique id of the view. In a multi-view use case, this is important for matching view states and place contents into this view.

    x (String|Number, optional)

    A relative (e.g. '50%') or absolute position. Default 0.

    y (String|Number, optional)

    A relative (e.g. '50%') or absolute position. Default 0.

    width (String|Number, optional)

    A relative (e.g. '50%') or absolute extent. Default '100%'.

    height (String|Number, optional)

    A relative (e.g. '50%') or absolute extent. Default '100%'.

    padding (Object, optional)

    Padding around the viewport, in the shape of {left, right, top, bottom} where each value is either a relative (e.g. '50%') or absolute pixels. This can be used to move the "look at"/target/vanishing point away from the center of the viewport rectangle.

    controller (Function|Boolean|Object, optional)

    Options for viewport interactivity.

    • null or false: this view is not interactive.
    • true: initiates the default controller with default options.
    • Controller class (not instance): initiates the provided controller with default options.
    • Object: controller options. This will be merged with the default controller options.
      • controller.type: the controller class
      • For other options, consult the documentation of Controller.

    Default null.

    viewState (String|Object, optional)

    The optional viewState property enables a View to specify, select or select-and-modify its view state.

    viewState is an overloaded property that can take either just a view state id string, or an object specifying view state parameters and optionally a view state id string:

    • null (default): Will select a view state based on view.id, falling back to using the first view state.
    • String: Will attempt to match the indicated view state.
    • Object (with id field): if the object contains an id field which matches a dynamic view state, the remaining fields in View.viewState will extend (be merged into a copy of) the selected dynamic view state.
    • Object (with no id field): If no id is provided, the View.viewState object will be used directly as the view state, essentially representing a fixed or constant view state.

    Note that specifying viewState as an object with an id field effectively allows the View to modify a dynamic view state by overriding some of its fields. This is useful in multiview situations where it enables having one view that fixes some parameters (eg. zoom, pitch and bearing to show an overview map).

    The viewState property is intended to support a number of use cases:

    • Sharing view states between multiple views - If a View id is different from the designed view state's id.
    • specify a complete, constant (fixed) view state directly in the view
    • Overriding a partial set of view state properties from a selected view state.
    clear (Boolean|Object, optional)

    Clears the contents (pixels) of the viewport. The value of the clear prop is passed as an argument to luma.gl's clear function. If true clears color and depth buffers. If an object, behaviour is controlled by the following fields:

    • color (Boolean or Array) - if not false, clears all active color buffers with either the provided color or the currently set clear color.
    • depth (Boolean) - if true, clears the depth buffer.
    • stencil (Boolean) - if true clears the stencil buffer.

    Note that deck.gl always clears the screen before each render, and clearing, while cheap, is not totally free. This means that viewports should only specify the clear property if they need additional clearing, e.g. because they are rendering on top of another viewport, or want to have a different background color etc.

    Default false.

    Methods

    Note: most applications just create Views with the appropriate props and do not need to call the following View methods directly.

    equals

    Returns true if deck.gl can determine that the supplied View instance is identical (equivalent) with this view.

    view.equals(otherView)

    • otherView (View) - Another view instance to compare with.

    Returns:

    • true - the given view is identical to the current one.

    Note: For speed, deck.gl uses shallow equality. This means that a value of false does not guarantee that the views are not equivalent.

    makeViewport
    view.makeViewport({width, height, viewState})

    Parameters:

    • width (Number) - Dimension in pixels of the target viewport.
    • height (Number) - Dimension in pixels of the target viewport.
    • viewState (Object) - view state compatible with the current View subclass in use. Note that any prop provided to the View constructor will override that inside the viewState.

    Returns a Viewport using the viewport type, props in the View and provided dimensions and view state.

    getDimensions

    Returns the actual pixel position and size that this View will occupy in a given "canvas" size.

    const {x, y, width, height} = view.getDimensions({width, height});

    Parameters:

    • width (Number) - Dimension in CSS pixels of the deck.gl "canvas".
    • height (Number) - Dimension in CSS pixels of the deck.gl "canvas".

    Returns an object containing the following fields:

    • x (Number) - x position in CSS pixels
    • y (Number) - y position in CSS pixels
    • width (Number) - width in CSS pixels
    • height (Number) - height in CSS pixels

    Remarks

    • The View class and its subclasses are perhaps best thought of as geospatially enabled counterparts of the typical Camera classes found in most 3D libraries.

    Source

    modules/core/src/views/view.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/viewport.html b/docs/api-reference/core/viewport.html index 3482a467d56..dd1f5cdd9d9 100644 --- a/docs/api-reference/core/viewport.html +++ b/docs/api-reference/core/viewport.html @@ -4,14 +4,14 @@ Viewport | deck.gl - - + +

    Viewport

    Read the article detailing deck.gl's Views and Projections system.

    A deck.gl Viewport is essentially a geospatially enabled camera, and combines a number of responsibilities, which can project and unproject 3D coordinates to the screen.

    Viewport classes are focused on mathematical operations such as coordinate projection/unprojection, and calculation of view and projection matrices and other uniforms needed by the WebGL2/WebGPU vertex shaders. The basic Viewport class is a generic geospatially enabled version of the typical 3D "camera" class you would find in most 3D/WebGL2/OpenGL libraries.

    While the Viewport class can certainly be used directly if you need and are able to calculate your own projection matrices, you typically do not directly create Viewport instances. Instead, Viewport classes are created using the View class descriptors and the current viewState.

    Overview of Viewport Classes

    Viewport ClassDescription
    ViewportThe base viewport has to be supplied view and projection matrices. It is typically only instantiated directly if the application needs to work with viewports that have been supplied from external sources, such as the WebVR API.
    WebMercatorViewportWhile all Viewport subclasses are geospatially enabled, this class renders from a perspective that matches a typical top-down map and is designed to synchronize perfectly with a mapbox-gl base map (even in 3D enabled perspective mode).

    Usage

    The Viewport class is normally not instantiated directly. The View class is more commonly used by applications. deck.gl automatically creates Viewports from Views and viewState when needed, using the View.makeViewport method.

    Constructor

    new Viewport({width: 500, height: 500, viewMatrix, projectionMatrix, ...});

    General Parameters

    • x (Number, optional) - x position of viewport top-left corner. Default 0.
    • y (Number, optional) - y position of viewport top-left corner. Default 0.
    • width (Number) - Width of viewport. Default 1.
    • height (Number) - Height of viewport. Default 1.

    View Matrix Parameters

    • viewMatrix (Array[16], optional) - 4x4 view matrix. Defaults to the identity matrix.

    Position and Geospatial Anchor Options (Optional)

    • latitude (Number, optional) - Center of viewport on map (alternative to center). Must be provided if constructing a geospatial viewport.

    • longitude (Number, optional) - Center of viewport on map (alternative to center). Must be provided if constructing a geospatial viewport.

    • zoom (Number, optional) - zoom level .

    • focalDistance (Number, optional) - modifier of viewport scale if zoom is not supplied. Corresponds to the number of pixels per meter. Default to 1.

    • position (Array[3], optional) - Position of viewport camera. Default [0, 0, 0].

    • modelMatrix (Array[16], optional) - Optional 4x4 model matrix applied to position.

    Projection Matrix Parameters.

    • projectionMatrix (Array[16], optional) - 4x4 projection matrix.

    If projectionMatrix is not supplied, an attempt is made to build from the remaining parameters. Otherwise the remaining parameters will be ignored.

    • fovy (Number, optional) - Field of view covered by camera, in the perspective case. In degrees. Default 75.
    • near (Number, optional) - Distance of near clipping plane. Default 0.1. (Note that in geospatial viewports, this actual distance used is scaled by the height of the screen).
    • far (Number, optional) - Distance of far clipping plane. Default 1000. (Note that in geospatial viewports, this actual distance used is scaled by the height of the screen).
    • orthographic (Boolean, optional) - whether to create an orthographic or perspective projection matrix. Default false (perspective projection).

    Methods

    equals

    Parameters:

    • viewport (Viewport) - The viewport to compare with.

    Returns:

    • true if the given viewport is identical to the current one.
    project

    Projects world coordinates to pixel coordinates on screen.

    Parameters:

    • coordinates (Array) - [X, Y, Z] in world units. Z is default to 0 if not supplied.
    • opts (Object)
      • topLeft (Boolean, optional) - Whether projected coords are top left. Default to true.

    Returns:

    • [x, y] or [x, y, z] in pixels coordinates. z is pixel depth.
      • If input is [X, Y]: returns [x, y].
      • If input is [X, Y, Z]: returns [x, y, z].
    unproject

    Unproject pixel coordinates on screen into world coordinates.

    Parameters:

    • pixels (Array) - [x, y, z] in pixel coordinates. Passing a z is optional.
    • opts (Object)
      • topLeft (Boolean, optional) - Whether projected coords are top left. Default to true.
      • targetZ (Number, optional) - If pixel depth z is not specified in pixels, this is used as the elevation plane to unproject onto. Default 0.

    Returns:

    • [X, Y] or [X, Y, Z] in world coordinates.
      • If input is [x, y] without specifying opts.targetZ: returns [X, Y].
      • If input is [x, y] with opts.targetZ: returns [X, Y, targetZ].
      • If input is [x, y, z]: returns [X, Y, Z].
    projectPosition

    Projects latitude, longitude (and altitude) to coordinates in the common space.

    Parameters:

    • coordinates (Array) - [lng, lat, altitude] Passing an altitude is optional.

    Returns:

    • [x, y, z] in WebMercator coordinates.
    unprojectPosition

    Projects a coordinate from the common space to latitude, longitude and altitude.

    Parameters:

    • coordinates (Array) - [x, y, z] in the WebMercator world. z is optional.

    Returns:

    • [longitude, latitude, altitude]
    getBounds

    Extracts the axis-aligned bounding box of the current visible area.

    • options (Object, optional)
      • options.z (Number, optional) - To calculate a bounding volume for fetching 3D data, this option can be used to get the bounding box at a specific elevation. Default 0.

    Returns:

    • [minX, minY, maxX, maxY] that defines the smallest orthogonal bounds that encompasses the visible region.
    getFrustumPlanes

    Extract view frustum planes of the current camera. Each plane is defined by its normal normal and distance from the origin distance (such that point x is on the plane if dot(normal, x) === distance) in the common space.

    Returns:

    • {near: {normal, distance}, far: {normal, distance}, left: {normal, distance}, right: {normal, distance}, top: {normal, distance}, bottom: {normal, distance}}
    import {Vector3} from '@math.gl/core';

    // Culling tests must be done in common space
    const commonPosition = new Vector3(viewport.projectPosition(point));

    // Extract frustum planes based on current view.
    const frustumPlanes = viewport.getFrustumPlanes();
    let outDir = null;

    // Check position against each plane
    for (const dir in frustumPlanes) {
    const plane = frustumPlanes[dir];
    if (commonPosition.dot(plane.normal) > plane.distance) {
    outDir = dir;
    break;
    }
    }
    if (outDir) {
    console.log(`Point is outside of the ${outDir} plane`);
    } else {
    console.log('Point is visible');
    }

    Remarks

    • The Viewport class and its subclasses are perhaps best thought of as geospatially enabled counterparts of the typical Camera classes found in most 3D libraries.
    • The Viewport class works together with the project shader module and generates the uniforms that module needs to project correctly in GLSL code.
    • Accordingly, a main function of viewports is to generate WebGL2/WebGPU compatible view and projection matrices (column-major format).
    • Functions (including projection and unprojection of coordinates) are available both in JavaScript and in GLSL, so that layers can do consistent projection calculations in both GLSL and JavaScript.
    • To support pixel project/unproject functions (in addition to the clipspace projection that Camera classes typically manage), the Viewport is also aware of the viewport extents.
    • In geospatial setups, Viewports can contain geospatial anchors.

    Source

    modules/core/src/viewports/viewport.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/web-mercator-viewport.html b/docs/api-reference/core/web-mercator-viewport.html index bffcb789e15..b734dd27189 100644 --- a/docs/api-reference/core/web-mercator-viewport.html +++ b/docs/api-reference/core/web-mercator-viewport.html @@ -4,13 +4,13 @@ WebMercatorViewport | deck.gl - - + +

    WebMercatorViewport

    The WebMercatorViewport class takes map view states (latitude, longitude, zoom, pitch, bearing etc.), and performs projections between world and screen coordinates. It is tuned to work in synchronization with mapbox-gl's projection matrix.

    Usage

    The WebMercatorViewport is the default viewport for deck.gl, created under the hood by a MapView.

    import {WebMercatorViewport} from '@deck.gl/core';

    const viewport = new WebMercatorViewport({
    width: 600,
    height: 400,
    longitude: -122.45,
    latitude: 37.78,
    zoom: 12,
    pitch: 30,
    bearing: 15
    });

    viewport.project([-122.45, 37.78]);
    // [300,200]

    Constructor

    new WebMercatorViewport({width, height, longitude, latitude, zoom, pitch, bearing});

    Parameters:

    • opts (Object) - Web Mercator viewport options

      • width (Number) - Width of the viewport.
      • height (Number) - Height of the viewport.

      web mercator style arguments:

      • latitude (Number, optional) - Latitude of the viewport center on map. Default to 0.
      • longitude (Number, optional) - Longitude of the viewport center on map. Default to 0.
      • zoom (Number, optional) - Map zoom (scale is calculated as 2^zoom). Default to 11.
      • pitch (Number, optional) - The pitch (tilt) of the map from the screen, in degrees (0 is straight down). Default to 0.
      • bearing (Number, optional) - The bearing (rotation) of the map from north, in degrees counter-clockwise (0 means north is up). Default to 0.
      • altitude (Number, optional) - Altitude of camera in screen units. Default to 1.5.

      projection matrix arguments:

      • nearZMultiplier (Number, optional) - Scaler for the near plane, 1 unit equals to the height of the viewport. Default to 0.1.
      • farZMultiplier (Number, optional) - Scaler for the far plane, 1 unit equals to the distance from the camera to the top edge of the screen. Default to 1.01.
      • orthographic (Boolean, optional) - Default false.
      • projectionMatrix (Array, optional) - Optional 16-element 4x4 projection matrix, that overrides the matrix created from the parameters above.

    Remarks:

    • altitude has a default value that matches assumptions in mapbox-gl
    • width and height are forced to 1 if supplied as 0, to avoid division by zero. This is intended to reduce the burden of apps to check values before instantiating a Viewport.
    • When using Mercator projection, per cartographic tradition, longitudes and latitudes are specified as degrees.
    • latitude of 90 or -90 are projected to infinity in Web Mercator projection. Using pole locations with this viewport may result in NaNs. Many base map providers cut off at 85.051129 at which the full world becomes a square.
    • When constructing the viewport, a field of view is not specified, but rather is calculated from the altitude or (if present) the projectionMatrix. The value can be obtained from this.fovy (in degrees).

    Inherits all Viewport methods.

    Methods

    Inherits all methods from Viewport.

    project

    Projects world coordinates to pixel coordinates on screen.

    Parameters:

    • coordinates (Array) - [longitude, latitude, altitude]. altitude is in meters and default to 0 if not supplied.
    • opts (Object)
      • topLeft (Boolean, optional) - Whether projected coords are top left. Default to true.

    Returns:

    • [x, y] or [x, y, z] in pixels coordinates. z is pixel depth.
      • If input is [longitude, latitude]: returns [x, y].
      • If input is [longitude, latitude: altitude]: returns [x, y, z].
    unproject

    Unproject pixel coordinates on screen into world coordinates.

    Parameters:

    • pixels (Array) - [x, y, z] in pixel coordinates. Passing a z is optional.
    • opts (Object)
      • topLeft (Boolean, optional) - Whether projected coords are top left. Default to true.
      • targetZ (Number, optional) - If pixel depth z is not specified in pixels, this is used as the elevation plane to unproject onto. Default 0.

    Returns:

    • [longitude, latitude] or [longitude, latitude, altitude] in world coordinates. altitude is in meters.
      • If input is [x, y] without specifying opts.targetZ: returns [longitude, latitude].
      • If input is [x, y] with opts.targetZ: returns [longitude, latitude, targetZ].
      • If input is [x, y, z]: returns [longitude, latitude, altitude].
    getDistanceScales

    Returns an object with scale values supporting first order (linear) and second order (quadratic) approximations of the local Web Mercator projection scale around the viewport center. Error increases with distance from viewport center (very roughly 1% per 100km in linear mode, quadratic approximation does significantly better).

    Returns:

    • An object with precalculated distance scales allowing conversion between lnglat deltas, meters and pixels.
    addMetersToLngLat

    Add a meter delta to a base lnglat coordinate using linear approximation. For information on numerical precision, see remarks on getDistanceScales.

    Parameters:

    • lngLatZ (Array) - Base coordinate in [longitude, latitude, altitude]. Passing a altitude is optional.
    • xyz (Array) - Array of [x, y, z] in meter deltas. Passing a z is optional.

    Returns:

    • New coordinate array in [longitude, latitude] or [longitude, latitude, altitude] if z is provided.
    fitBounds

    Returns a new viewport that fit around the given bounding box. Viewport width and height must be either set or provided as options. Only supports non-perspective mode.

    Parameters:

    • bounds (Array) - Bounding box in [[longitude, latitude], [longitude, latitude]].
    • opts (Object) - See additional options in @math.gl/web-mercator
      • width (Number) - If not supplied, will use the current width of the viewport (default 1)
      • height (Number) - If not supplied, will use the current height of the viewport (default 1)
      • minExtent (Number) - In degrees, 0.01 would be about 1000 meters
      • maxZoom (Number) - Max zoom level
      • padding (Number) - The amount of padding in pixels to add to the given bounds.
      • offset (Array) - The center in [x, y] of the given bounds relative to the map's center measured in pixels.

    Returns:

    • New WebMercatorViewport fit around the given bounding box.

    Remarks

    • Because WebMercatorViewport a subclass of Viewport, an application can implement support for generic 3D Viewports and automatically get the ability to accept web mercator style map coordinates.
    • A limitation at the moment is that there is no way to extract web mercator parameters from a "generic" viewport, so for map synchronization applications (rendering on top of a typical map component that only accepts web mercator parameters) the WebMercatorViewport is necessary.
    • Facilitates the necessary mercator projections by breaking them into a minimal non-linear piece followed by a standard projection chain.
    • Making deck.gl work with non-mapbox map systems in perspective mode might require subclassing WebMercatorViewport and adjust the projection so it matches the map's projection.

    Source

    modules/core/src/viewports/web-mercator-viewport.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/core/widget.html b/docs/api-reference/core/widget.html index 90dec9a4f31..10c53a49f41 100644 --- a/docs/api-reference/core/widget.html +++ b/docs/api-reference/core/widget.html @@ -4,13 +4,13 @@ Widget Class | deck.gl - - + +

    Widget Class

    A widget is a UI component that can interact with deck.gl's cameras and layers. Some examples are:

    • A tooltip that follows the pointer and provide information for the hovered object
    • A marker pinned to a geo-location containing HTML content
    • Buttons to manipulate the camera, such as +/- zoom buttons, a compass rose for the MapView, a gimble widget for the OrbitView, etc.
    • A legend that offers visual comparison of sizes, colors etc. corresponding to the rendered layers and viewport. For example a distance ruler, a color scale for the HeatmapLayer, etc.

    You may find many ready-to-use widgets in the @deck.gl/widgets module.

    A widget is expected to implement the Widget interface. Here is a custom widget that shows a spinner while layers are loading:

    import {Widget} from '@deck.gl/core';

    class LoadingIndicator implements Widget {
    element?: HTMLDivElement;
    size: number;

    constructor(options: {
    size: number;
    }) {
    this.size = options.size;
    }

    onAdd() {
    const el = document.createElement('div');
    el.className = 'spinner';
    el.style.width = `${this.size}px`;
    // TODO - create animation for .spinner in the CSS stylesheet
    this.element = el;
    return el;
    }

    onRemove() {
    this.element = undefined;
    }

    onRedraw({layers}) {
    const isVisible = layers.some(layer => !layer.isLoaded);
    this.element.style.display = isVisible ? 'block' : 'none';
    }
    }

    deckgl.addWidget(new LoadingIndicator({size: 48}));

    Widget Interface

    When a widget instance is added to Deck, the user can optionally specify a viewId that it is attached to (default null). If assigned, this widget will only respond to events occured inside the specific view that matches this id.

    Members

    A Widget implements the following members.

    id

    Unique identifier of the widget.

    props (Object)

    Any options for the widget, as passed into the constructor and can be updated with setProps.

    viewId (String | null)
    • Default: null

    The id of the view that the widget is attached to. If null, the widget receives events from all views. Otherwise, it only receives events from the view that matches this id.

    placement (String, optional)
    • Default: 'top-left'

    Widget positioning within the view. One of:

    • 'top-left'
    • 'top-right'
    • 'bottom-left'
    • 'bottom-right'
    • 'fill'

    Methods

    onAdd

    Required. Called when the widget is added to a Deck instance.

    Receives the following arguments:

    • context (Object)
      • deck (Deck) - the Deck instance that this widget is being attached to.
      • viewId (String | null) - the view id that this widget is being attached to.

    Returns an optional UI element that should be appended to the Deck container.

    onRemove

    Required. Called when the widget is removed.

    setProps

    Optional. Called to update widget options.

    onViewportChange

    Op†ional. Called when the containing view is changed. If viewId: null, will be called if any viewport changes.

    Receives the following arguments:

    • viewport (Viewport) - the viewport that has changed
    onRedraw

    Optional. Called when the containing view is redrawn. If viewId: null, will be called if anything redraws.

    Receives the following arguments:

    • params
      • viewports (Viewport[]) - the viewports that are being redrawn
      • layers (Layer[]) - the layers that are being redrawn
    onHover

    Optional. Called when a hover event occurs in the containing view. If viewId: null, will be called if hover occurs in any view.

    Receives arguments:

    • info - the picking info describing the object being hovered.
    • event - the original gesture event
    onClick

    Optional. Called when a click event occurs in the containing view. If viewId: null, will be called if click occurs in any view.

    Receives arguments:

    • info - the picking info describing the object being clicked.
    • event - the original gesture event
    onDragStart

    Optional. Called when a dragstart event occurs in the containing view. If viewId: null, will be called if drag occurs in any view.

    Receives arguments:

    • info - the picking info describing the object being dragged.
    • event - the original gesture event
    onDrag

    Optional. Called when a drag event occurs in the containing view. If viewId: null, will be called if drag occurs in any view.

    Receives arguments:

    • info - the picking info describing the object being dragged.
    • event - the original gesture event
    onDragEnd

    Optional. Called when a dragend event occurs in the containing view. If viewId: null, will be called if drag occurs in any view.

    Receives arguments:

    • info - the picking info describing the object being dragged.
    • event - the original gesture event
    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/brushing-extension.html b/docs/api-reference/extensions/brushing-extension.html index 2de5dbf55d3..3c7bc6adc44 100644 --- a/docs/api-reference/extensions/brushing-extension.html +++ b/docs/api-reference/extensions/brushing-extension.html @@ -4,13 +4,13 @@ BrushingExtension | deck.gl - - + +

    BrushingExtension

    The BrushingExtension adds GPU-based data brushing functionalities to layers. It allows the layer to show/hide objects based on the current pointer position.

    import {ScatterplotLayer} from '@deck.gl/layers';
    import {BrushingExtension} from '@deck.gl/extensions';

    const layer = new ScatterplotLayer({
    id: 'points',
    data: POINTS,

    // props from ScatterplotLayer
    getPosition: d => d.position,
    getRadius: d => d.radius,

    // props added by BrushingExtension
    brushingEnabled: true,
    brushingRadius: 100000,

    // Define extensions
    extensions: [new BrushingExtension()]
    });

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/extensions
    import {BrushingExtension} from '@deck.gl/extensions';
    new BrushingExtension();

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^7.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^7.0.0/dist.min.js"></script>
    new deck.BrushingExtension();

    Constructor

    new BrushingExtension();

    Layer Properties

    When added to a layer via the extensions prop, the BrushingExtension adds the following properties to the layer:

    brushingRadius (Number)

    The brushing radius centered at the pointer, in meters. If a data object is within this circle, it is rendered; otherwise it is hidden.

    brushingEnabled (Boolean, optional)
    • Default: true

    Enable/disable brushing. If brushing is disabled, all objects are rendered.

    Brushing is always disabled when the pointer leaves the current viewport.

    brushingTarget (Enum, optional)
    • Default: source

    The position used to filter each object by. One of the following:

    • 'source': Use the primary position for each object. This can mean different things depending on the layer. It usually refers to the coordinates returned by getPosition or getSourcePosition accessors.
    • 'target': Use the secondary position for each object. This may not be available in some layers. It usually refers to the coordinates returned by getTargetPosition accessors.
    • 'source_target': Use both the primary position and secondary position for each object. Show objet if either is in brushing range.
    • 'custom': Some layers may not describe their data objects with one or two coordinates, for example PathLayer and PolygonLayer. Use this option with the getBrushingTarget prop to provide a custom position that each object should be filtered by.
    getBrushingTarget (Function, optional)
    • Default: null

    Called to retrieve an arbitrary position for each object that it will be filtered by. Returns an array [x, y]. Only effective if brushingTarget is set to custom.

    Source

    modules/extensions/src/brushing

    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/clip-extension.html b/docs/api-reference/extensions/clip-extension.html index c0ea2923a6d..f412b396310 100644 --- a/docs/api-reference/extensions/clip-extension.html +++ b/docs/api-reference/extensions/clip-extension.html @@ -4,13 +4,13 @@ ClipExtension | deck.gl - - + +

    ClipExtension

    The ClipExtension adds support for clipping rendered layers by rectangular bounds.

    import {GeoJsonLayer} from '@deck.gl/layers';
    import {ClipExtension} from '@deck.gl/extensions';

    const layer = new GeoJsonLayer({
    // Natural Earth countries dataset includes Antarctica, which renders stretched further to south in MapView with viewState normalization disabled
    data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson',
    // clip rendered layer by Mercator bounds
    extensions: [new ClipExtension()],
    clipBounds: [-180, -85.051129, 180, 85.051129],
    });

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/extensions
    import {ClipExtension} from '@deck.gl/extensions';
    new ClipExtension();

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^8.0.0/dist.min.js"></script>
    new deck.ClipExtension();

    Constructor

    new ClipExtension();

    Layer Properties

    When added to a layer via the extensions prop, the ClipExtension adds the following properties to the layer:

    clipBounds (Array)

    Rectangular bounds to be used for clipping the rendered region.

    Supported format: [left, bottom, right, top]

    clipByInstance (Boolean, optional)

    clipByInstance controls whether an object is clipped by its anchor (e.g. icon, point) or by its geometry (e.g. path, polygon). If not specified, it is deduced from whether there is an attribute called instancePositions. This behavior can be overridden if:

    • the anchor attribute goes by some other name
    • to clip an anchored layer by geometry, like the text layer

    Source

    modules/extensions/src/clip

    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/collision-filter-extension.html b/docs/api-reference/extensions/collision-filter-extension.html index 6f1bd2981e1..0c63e5963aa 100644 --- a/docs/api-reference/extensions/collision-filter-extension.html +++ b/docs/api-reference/extensions/collision-filter-extension.html @@ -4,14 +4,14 @@ CollisionFilterExtension | deck.gl - - + +

    CollisionFilterExtension

    The CollisionFilterExtension allows layers to hide features which overlap with other features. An example is a dense ScatterplotLayer with many points which overlap: by using this extension points that collide with others are hidden such that only one of the colliding points is shown. The collisions are computed on the GPU in realtime, allowing the collisions to be updated smoothly on every frame.

    To use this extension on a layer, add the CollisionFilterExtension to the layer's extensions prop.

    import {ScatterplotLayer} from '@deck.gl/layers';
    import {CollisionFilterExtension} from '@deck.gl/extensions';

    const layer = new ScatterplotLayer({
    id: 'points',
    data: points,
    extensions: [new CollisionFilterExtension()],
    getPosition: d => d.COORDINATES,
    getRadius: 10,
    radiusUnits: 'pixels'
    })

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/extensions
    import {CollisionFilterExtension} from '@deck.gl/extensions';
    new CollisionFilterExtension();

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.9.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.9.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^8.9.0/dist.min.js"></script>
    new deck.CollisionFilterExtension();

    Constructor

    new CollisionFilterExtension();

    Layer Properties

    When added to a layer via the extensions prop, the CollisionFilterExtension adds the following properties to the layer:

    collisionEnabled (Boolean, optional)

    Enable/disable collisions. If collisions are disabled, all objects are rendered. Defaults to true.

    collisionGroup (string, optional)

    Collision group this layer belongs to. If it is not set, the 'default' collision group is used. Two (or more) layers that share the same collisionGroup will be considered together when calculating collisions.

    For example, here the icon and text features will avoid colliding with each other, but permits collisions with the scatterplot features.

    const layers = [
    new ScatterplotLayer({
    ...,
    extensions: [new CollisionFilterExtension()],
    collisionGroup: 'visualization'
    }),
    new IconLayer({
    ...,
    extensions: [new CollisionFilterExtension()],
    collisionGroup: 'legend'
    }),
    new TextLayer({
    ...,
    extensions: [new CollisionFilterExtension()],
    collisionGroup: 'legend'
    })
    ];
    collisionTestProps (Object, optional)

    Props to override when computing collisions. A common use case is to increase the size of the features when computing collisions to provide greater spacing between visible features. For the ScatterplotLayer this would be done by:

    collisionTestProps: {radiusScale: 2}
    getCollisionPriority (Function, optional)

    The collision priority of each object. Features with higher values are shown preferentially. The priority is a number in the range -1000 -> 1000, values outside will be clamped.

    • If a number is provided, it is used for all objects in the layer.
    • If a function is provided, it is called on each object to retrieve its priority.

    Using with transparent layers

    The CollisionFilterExtension samples at the anchor point of a feature when calculating collisions. Layers must ensure that a pixel is rendered at this location when the picking pass is drawn.

    A common issue is with the IconLayer, which discards transparent pixels. To avoid this, use alphaCutoff: -1. A similar issue occurs when the anchor point of the IconLayer is too close to the edge of the image, to be safe include a few pixels of padding, e.g.

    iconMapping: {
    marker: {x: 0, y: 0, width: 128, height: 128, anchorY: 124}
    }

    Limitations

    • Accessors are not supported in collisionTestProps
    • Given that collisions is performed on the GPU, the layers of @deck.gl/aggregation-layers module that does aggregation on the CPU, for example CPUGridLayer and HexagonLayer, are not supported.
    • The collision is point-in-polygon, specifically is computed by comparing the anchor point of a feature with the rasterized screen-space areas of other features. While good for realtime applications, generally this will not give the same results as a full collision test would.

    Source

    modules/extensions/src/collision-filter

    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/data-filter-extension.html b/docs/api-reference/extensions/data-filter-extension.html index eb175b33f4c..2cb5a847581 100644 --- a/docs/api-reference/extensions/data-filter-extension.html +++ b/docs/api-reference/extensions/data-filter-extension.html @@ -4,13 +4,13 @@ DataFilterExtension | deck.gl - - + +

    DataFilterExtension

    The DataFilterExtension adds GPU-based data filtering functionalities to layers. It allows the layer to show/hide objects based on user-defined properties. This extension provides a significantly more performant alternative to filtering the data array on the CPU.

    Note: This extension does not work with all deck.gl layers. See "limitations" below.

    import {GeoJsonLayer} from '@deck.gl/layers';
    import {DataFilterExtension} from '@deck.gl/extensions';

    const layer = new GeoJsonLayer({
    id: 'geojson-layer',
    data: GEOJSON,

    // props from GeoJsonLayer
    getFillColor: [160, 160, 180],
    getLineColor: [0, 0, 0],
    getLineWidth: 10,

    // props added by DataFilterExtension
    getFilterValue: f => f.properties.timeOfDay, // in seconds
    filterRange: [43200, 46800], // 12:00 - 13:00

    // Define extensions
    extensions: [new DataFilterExtension({filterSize: 1})]
    });

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/extensions
    import {DataFilterExtension} from '@deck.gl/extensions';
    new DataFilterExtension({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^7.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^7.0.0/dist.min.js"></script>
    new deck.DataFilterExtension({});

    Constructor

    new DataFilterExtension({filterSize, fp64});
    • filterSize (Number) - the size of the filter (number of columns to filter by). The data filter can show/hide data based on 1-4 numeric properties of each object. Default 1.
    • categorySize (Number) - the size of the category filter (number of columns to filter by). The category filter can show/hide data based on 1-4 properties of each object. Default 1.
    • fp64 (Boolean) - if true, use 64-bit precision instead of 32-bit. Default false. See the "remarks" section below for use cases and limitations.
    • countItems (Boolean) - if true, reports the number of filtered objects with the onFilteredItemsChange callback. Default false.

    Layer Properties

    When added to a layer via the extensions prop, the DataFilterExtension adds the following properties to the layer:

    getFilterValue (Function)

    Called to retrieve the value for each object that it will be filtered by. Returns either a number (if filterSize: 1) or an array.

    For example, consider data in the following format:

    [
    {"timestamp": 0.1, "coordinates": [-122.45, 37.78], "speed": 13.3},
    ...
    ]

    To filter by timestamp:

    new ScatterplotLayer({
    data,
    getPosition: d => d.coordinates,
    getFilterValue: d => d.timestamp,
    filterRange: [0, 1],
    extensions: [new DataFilterExtension({filterSize: 1})]
    })

    To filter by both timestamp and speed:

    new ScatterplotLayer({
    data,
    getPosition: d => d.coordinates,
    getFilterValue: d => [d.timestamp, d.speed],
    filterRange: [[0, 1], [10, 20]],
    extensions: [new DataFilterExtension({filterSize: 2})]
    })

    Note that all filtered values are uploaded as 32-bit floating numbers, so certain values e.g. raw unix epoch time may not be accurately represented. You may test the validity of a timestamp by calling Math.fround(t) to check if there would be any loss of precision.

    filterRange (Array)

    The bounds which defines whether an object should be rendered. If an object's filtered value is within the bounds, the object will be rendered; otherwise it will be hidden. This prop can be updated on user input or animation with very little cost.

    Format:

    • If filterSize is 1: [min, max]
    • If filterSize is 2 to 4: [[min0, max0], [min1, max1], ...] for each filtered property, respectively.
    filterSoftRange (Array, optional)
    • Default: null

    If specified, objects will be faded in/out instead of abruptly shown/hidden. When the filtered value is outside of the bounds defined by filterSoftRange but still within the bounds defined by filterRange, the object will be rendered as "faded." See filterTransformSize and filterTransformColor for additional control over this behavior.

    new ScatterplotLayer({
    data,
    getPosition: d => d.coordinates,
    getFilterValue: d => d.timestamp,
    filterRange: [0, 1],
    filterSoftRange: [0.2, 0.8],
    filterTransformSize: true,
    filterTransformColor: true,
    extensions: [new DataFilterExtension({filterSize: 1})]
    })

    Format:

    • If filterSize is 1: [softMin, softMax]
    • If filterSize is 2 to 4: [[softMin0, softMax0], [softMin1, softMax1], ...] for each filtered property, respectively.
    getFilterCategory (Function, optional)
    • Default: 0

    Called to retrieve the category for each object that it will be filtered by. Returns either a category as a number or string (if categorySize: 1) or an array.

    For example, consider data in the following format:

    [
    {"industry": "retail", "coordinates": [-122.45, 37.78], "size": 10},
    ...
    ]

    To filter by industry:

    new ScatterplotLayer({
    data,
    getPosition: d => d.coordinates,
    getFilterCategory: d => d.industry,
    filterCategories: ['retail', 'health'],
    extensions: [new DataFilterExtension({categorySize: 1})]
    })

    To filter by both industry and size:

    new ScatterplotLayer({
    data,
    getPosition: d => d.coordinates,
    getFilterCategory: d => [d.industry, d.size],
    filterCategories: [['retail', 'health'], [10, 20, 50]],
    extensions: [new DataFilterExtension({categorySize: 2})]
    })
    filterCategories (Array, optional)
    • Default: [0]

    The list of categories that should be rendered. If an object's filtered category is in the list, the object will be rendered; otherwise it will be hidden. This prop can be updated on user input or animation with very little cost.

    Format:

    • If categorySize is 1: ['category1', 'category2']
    • If categorySize is 2 to 4: [['category1', 'category2', ...], ['category3', ...], ...] for each filtered property, respectively.

    The maximum number of supported is determined by the categorySize:

    • If categorySize is 1: 128 categories
    • If categorySize is 2: 64 categories per dimension
    • If categorySize is 3 or 4: 32 categories per dimension

    If this value is exceeded any categories beyond the limit will be ignored.

    filterTransformSize (Boolean, optional)
    • Default: true

    When an object is "faded", manipulate its size so that it appears smaller or thinner. Only works if filterSoftRange is specified.

    filterTransformColor (Boolean, optional)
    • Default: true

    When an object is "faded", manipulate its opacity so that it appears more translucent. Only works if filterSoftRange is specified.

    filterEnabled (Boolean, optional)
    • Default: true

    Enable/disable the data filter. If the data filter is disabled, all objects are rendered.

    onFilteredItemsChange (Function, optional)

    Only used if the countItems option is enabled. Called with the following arguments when the filter changes:

    • event (Object)
      • id (String) - the id of the source layer. Note when this prop is specified on a CompositeLayer, such as GeoJsonLayer, the callback is called once by each sub layer.
      • count (Number) - the number of data objects that pass the filter.

    Remarks

    Filter precision

    By default, both the filter values and the filter range are uploaded to the GPU as 32-bit floats. When using very large filter values, most commonly Epoch timestamps, 32-bit float representation could lead to an error margin of >1 minute. Enabling 64-bit precision by setting fp64: true would allow the filter range to be evaluated more accurately. However, 64-bit support requires one extra attribute slot, which increases the risk of exceeding the hardware limit on vertex attributes. Depending on the layer that the DataFilterExtension is used with, it may interfere with the layer's ability to use other extensions.

    If this becomes an issue, an alternative technique is to transform each filter value by subtracting a fixed "origin" value, thus making the numbers smaller:

    getFilterValue: d => d.timestamp - ORIGIN_TS,
    filterRange: [rangeStart - ORIGIN_TS, rangeEnd - ORIGIN_TS]

    32-bit floats can accurately represent each second within ~190 days (2^24). Unless the filter values require both a large span and fine granularity, 32-bit floats should be sufficient.

    Limitations

    Given data filtering happens on GPU, not all layers of @deck.gl/aggregation-layers module, support this feature.

    Always supported:

    • HeatMapLayer
    • GPUGridLayer

    Supported only when aggregation is performed on GPU:

    • ScreenGridlayer
    • ContourLayer
    • GridLayer

    Not supported:

    • CPUGridLayer
    • HexagonLayer

    Source

    modules/extensions/src/data-filter

    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/fill-style-extension.html b/docs/api-reference/extensions/fill-style-extension.html index b37ed6e74da..c1d0269a864 100644 --- a/docs/api-reference/extensions/fill-style-extension.html +++ b/docs/api-reference/extensions/fill-style-extension.html @@ -4,14 +4,14 @@ FillStyleExtension | deck.gl - - + +

    FillStyleExtension

    The FillStyleExtension adds selected features to layers that render a "fill", such as the PolygonLayer and ScatterplotLayer.

    import {GeoJsonLayer} from '@deck.gl/layers';
    import {FillStyleExtension} from '@deck.gl/extensions';

    const layer = new GeoJsonLayer({
    id: 'geojson-layer',
    data: GEOJSON,

    // props from GeoJsonLayer
    getFillColor: [255, 0, 0],
    getLineColor: [0, 0, 0],
    getLineWidth: 10,

    // props added by FillStyleExtension
    fillPatternAtlas: './pattern.png',
    fillPatternMapping: './pattern.json',
    getFillPattern: f => 'hatch',
    getFillPatternScale: 1,
    getFillPatternOffset: [0, 0],

    // Define extensions
    extensions: [new FillStyleExtension({pattern: true})]
    });

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/extensions
    import {FillStyleExtension} from '@deck.gl/extensions';
    new FillStyleExtension({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^7.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^7.0.0/dist.min.js"></script>
    new deck.FillStyleExtension({});

    Constructor

    new FillStyleExtension({pattern});
    • pattern (Boolean) - if true, adds the ability to tile the filled area with a pattern.

    Layer Properties

    When added to a layer via the extensions prop, the FillStyleExtension adds the following properties to the layer:

    Fill Pattern

    The following properties are available if the pattern option is enabled.

    fillPatternAtlas (Texture2D | String)

    Sprite image url or texture that packs all your patterns into one layout. You can create sprite images with tools such as TexturePacker.

    fillPatternEnabled (Boolean)
    • Default: true

    Whether to use pattern fill. If false, then the extension has no effect.

    fillPatternMapping (Object | String)

    Pattern names mapped to pattern definitions. Each pattern is defined with the following values:

    • x (Number, required): x position of pattern on the atlas image
    • y (Number, required): y position of pattern on the atlas image
    • width (Number, required): width of pattern on the atlas image
    • height (Number, required): height of pattern on the atlas image
    fillPatternMask (Boolean)
    • Default: true

    Whether to treat the patterns as transparency masks.

    • If true, user defined color (e.g. from getFillColor) is applied.
    • If false, pixel color from the image is applied.
    getFillPattern (Function)

    Called to retrieve the name of the pattern. Returns a string key from the fillPatternMapping object.

    getFillPatternScale (Function|Number)
    • Default: 1

    The scale of the pattern, relative to the original size. If the pattern is 24 x 24 pixels, scale 1 roughly yields 24 meters.

    • If a number is provided, it is used as the pattern scale for all objects.
    • If a function is provided, it is called on each object to retrieve its pattern scale.
    getFillPatternOffset (Function|Array)
    • Default: [0, 0]

    The offset of the pattern, relative to the original size. Offset [0.5, 0.5] shifts the pattern alignment by half.

    • If an array is provided, it is used as the pattern offset for all objects.
    • If a function is provided, it is called on each object to retrieve its pattern offset.

    Source

    modules/extensions/src/fill-style

    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/fp64-extension.html b/docs/api-reference/extensions/fp64-extension.html index bff75403ae1..650d35c9ff0 100644 --- a/docs/api-reference/extensions/fp64-extension.html +++ b/docs/api-reference/extensions/fp64-extension.html @@ -4,13 +4,13 @@ Fp64Extension | deck.gl - - + +

    Fp64Extension

    The Fp64Extension adds 64-bit precision to geospatial layers.

    Note: This extension is the equivalent of the fp64 prop from older deck.gl versions. As of v6.3, the fp64 mode was deprecated in favor of the new default 32-bit projection mode that is comparable in precision but considerably more performant.

    import {GeoJsonLayer} from '@deck.gl/layers';
    import {Fp64Extension} from '@deck.gl/extensions';

    const layer = new GeoJsonLayer({
    id: 'geojson-layer',
    data: GEOJSON,
    ...
    extensions: [new Fp64Extension()]
    });

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/extensions
    import {Fp64Extension} from '@deck.gl/extensions';
    new Fp64Extension({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^7.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^7.0.0/dist.min.js"></script>
    new deck.Fp64Extension({});

    Constructor

    new Fp64Extension();

    Layer Properties

    When added to a layer via the extensions prop, the Fp64Extension requires the coordinateSystem prop of the layer to be COORDINATE_SYSTEM.LNGLAT_DEPRECATED.

    Source

    modules/extensions/src/fp64

    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/mask-extension.html b/docs/api-reference/extensions/mask-extension.html index 283b738c659..18250eb45ed 100644 --- a/docs/api-reference/extensions/mask-extension.html +++ b/docs/api-reference/extensions/mask-extension.html @@ -4,13 +4,13 @@ MaskExtension | deck.gl - - + +

    MaskExtension

    The MaskExtension allows layers to show/hide objects by a geofence. For example, a map may filter a list of user locations by the boundaries of a given country, or highlight part of a base map that is inside a user-drawn circle or lasso area. This extension provides a significantly more performant alternative to testing the data array against a bounding geometry on the CPU.

    To use this extension, first define a mask layer with the prop operation: 'mask'. A mask layer is not rendered to screen; it defines the geometry of the mask. If the layer renders 3D objects, its footprint on the XY plane is used.

    For each layer that should be masked, add the MaskExtension to its extensions prop, and set the maskId prop to the id of the mask layer. A masked layer only renders data objects that fall inside the mask.

    Note: This extension does not work with all deck.gl layers. See "limitations" below.

    import {GeoJsonLayer, ScatterplotLayer} from '@deck.gl/layers';
    import {MaskExtension} from '@deck.gl/extensions';

    const layers = [
    new GeoJsonLayer({
    id: 'geofence',
    data: POLYGON_FEATURE,
    operation: 'mask'
    }),
    new ScatterplotLayer({
    id: 'pickups',
    data: PICKUP_LOCATIONS,
    getPosition: d => [d.lng, d.lat],
    getRadius: 50,
    // only render points that are inside the geofence
    extensions: [new MaskExtension()],
    maskId: 'geofence'
    })
    ];

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/extensions
    import {MaskExtension} from '@deck.gl/extensions';
    new MaskExtension();

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.7.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.7.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^8.7.0/dist.min.js"></script>
    new deck.MaskExtension();

    Constructor

    new MaskExtension();

    Layer Properties

    When added to a layer via the extensions prop, the MaskExtension adds the following properties to the layer:

    maskId (String)

    Id of the layer that defines the mask. The mask layer must use the prop operation: 'mask'. Masking is disabled if maskId is empty or no valid mask layer with the specified id is found.

    maskByInstance (Boolean, optional)

    maskByInstance controls whether an object is clipped by its anchor (usually defined by an accessor called getPosition, e.g. icon, scatterplot) or by its geometry (e.g. path, polygon). If not specified, it is automatically deduced from the layer type.

    maskByInstance

    maskInverted (Boolean, optional)

    When maskInverted is true the result of the masking operation is inverted. Inversion is applied when reading the mask, thus it is possible to use the same mask normally on some layers and inverted on other layers. Defaults to false.

    Limitations

    • The current implementation supports up to 4 masks at the same time.
    • Given that masking is performed on the GPU, the layers of @deck.gl/aggregation-layers module that does aggregation on the CPU, for example CPUGridLayer and HexagonLayer, are not supported.
    • Masking is not supported in GlobeView

    Source

    modules/extensions/src/mask

    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/overview.html b/docs/api-reference/extensions/overview.html index 3ee1aea09b0..f8101db16e9 100644 --- a/docs/api-reference/extensions/overview.html +++ b/docs/api-reference/extensions/overview.html @@ -4,13 +4,13 @@ @deck.gl/extensions | deck.gl - - + +

    @deck.gl/extensions

    Layer extensions are bonus features that you can optionally add to the core deck.gl layers. These features are not included in the layers by default because one or more of the following reasons:

    • They do not work consistently for all layers, but still valuable for some;
    • While they optimize for specific use cases, there is an unnecessary performance overhead for users who don't need them;
    • Once separated from the core layer code, they can be tree shaken. Applications can have smaller bundle sizes by only including the features they need.

    This module contains the following extensions:

    For instructions on authoring your own layer extensions, visit developer guide.

    Installation

    Install from NPM

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/extensions
    import {DataFilterExtension} from '@deck.gl/extensions';
    new DataFilterExtension({});

    Include the Standalone Bundle

    <script src="https://unpkg.com/deck.gl@^7.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^7.0.0/dist.min.js"></script>
    new deck.DataFilterExtension({});
    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/path-style-extension.html b/docs/api-reference/extensions/path-style-extension.html index 017e7c731c7..85a48e11ad3 100644 --- a/docs/api-reference/extensions/path-style-extension.html +++ b/docs/api-reference/extensions/path-style-extension.html @@ -4,13 +4,13 @@ PathStyleExtension | deck.gl - - + +

    PathStyleExtension

    The PathStyleExtension adds selected features to the PathLayer and composite layers that render the PathLayer, e.g. PolygonLayer and GeoJsonLayer.

    Note: In v8.0, the getDashArray and dashJustified props are removed from the PathLayer and moved into this extension.

    import {PolygonLayer} from '@deck.gl/layers';
    import {PathStyleExtension} from '@deck.gl/extensions';

    const layer = new PolygonLayer({
    id: 'polygon-layer',
    data,
    ...
    getDashArray: [3, 2],
    dashJustified: true,
    dashGapPickable: true,
    extensions: [new PathStyleExtension({dash: true})]
    });

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/extensions
    import {PathStyleExtension} from '@deck.gl/extensions';
    new PathStyleExtension({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^8.0.0/dist.min.js"></script>
    new deck.PathStyleExtension({});

    Constructor

    new PathStyleExtension({dash});
    • dash (Boolean) - add capability to render dashed lines. Default false.
    • highPrecisionDash (Boolean) - improve dash rendering quality in certain circumstances. Note that this option introduces additional performance overhead, see "Remarks" below. Default false.
    • offset (Boolean) - add capability to offset lines. Default false.

    Layer Properties

    When added to a layer via the extensions prop, the PathStyleExtension adds the following properties to the layer:

    getDashArray (Function|Array)

    Must be specified if the dash option is enabled.

    The dash array to draw each path with: [dashSize, gapSize] relative to the width of the path.

    • If an array is provided, it is used as the dash array for all paths.
    • If a function is provided, it is called on each path to retrieve its dash array. Return [0, 0] to draw the path in solid line.
    • If this accessor is not specified, all paths are drawn as solid lines.
    dashJustified (Boolean, optional)
    • Default: false

    Only effective if getDashArray is specified. If true, adjust gaps for the dashes to align at both ends. Overrides the effect of highPrecisionDash.

    getOffset (Function|Number)

    Must be specified if the offset option is enabled.

    The offset to draw each path with, relative to the width of the path. Negative offset is to the left hand side, and positive offset is to the right hand side. 0 extrudes the path so that it is centered at the specified coordinates.

    • If a number is provided, it is used as the offset for all paths.
    • If a function is provided, it is called on each path to retrieve its offset.
    dashGapPickable (Boolean, optional)
    • Default false

    Only effective if getDashArray is specified. If true, gaps between solid strokes are pickable. If false, only the solid strokes are pickable.

    Remarks

    Limitations

    WebGL2 has guaranteed support for up to 16 attributes per shader. The current implementation of PathLayer uses 13 attributes. Each one of the options of this extension adds one more attribute. In other words, if all options are enabled, the layer will not be able to use other extensions.

    Tips on Rendering Dash Lines

    There are three modes to render dash lines with this extension:

    1. Default: dash starts from the beginning of each line segment
    2. Justified: dash is stretched to center on each line segment
    3. High precision: dash is evaluated continuously from the beginning of a path

    Comparison between dash modes

    The above table illustrates the visual behavior of the three modes.

    The default mode works best if the data consists of long, disjoint paths. It renders dashes at exactly the defined lengths.

    The justified mode is guaranteed to render sharp, well-defined corners. This is great for rendering polyline shapes. However, the gap size may look inconsistent across line segments due to stretching.

    The high precision mode pre-calculates path length on the CPU, so it may be slower and use more resources for large datasets. When a path contains a lot of short segments, this mode yields the best result.

    Source

    modules/extensions/src/path-style

    - - + + \ No newline at end of file diff --git a/docs/api-reference/extensions/terrain-extension.html b/docs/api-reference/extensions/terrain-extension.html index c6012fc2e8c..a471eaff6a6 100644 --- a/docs/api-reference/extensions/terrain-extension.html +++ b/docs/api-reference/extensions/terrain-extension.html @@ -4,13 +4,13 @@ TerrainExtension (Experimental) | deck.gl - - + +

    TerrainExtension (Experimental)

    This extension is experimental, which means it does not provide the compatibility and stability that one would typically expect from other features. Use with caution and report any issues that you find on GitHub.

    The TerrainExtension renders otherwise 2D data along a 3D surface. For example, a GeoJSON of city streets and building footprints can be overlaid on top of a elevation model. It is useful when viewing a mixture of 2D and 3D data sources. The re-positioning of geometries is performed on the GPU.

    To use this extension, first define a terrain source with the prop operation: 'terrain' or operation: 'terrain+draw'. A terrain source provides the 3D surface to fit other data on to.

    For each layer that should be fitted to the terrain surface, add the TerrainExtension to its extensions prop.

    import {GeoJsonLayer} from '@deck.gl/layers';
    import {TerrainLayer} from '@deck.gl/geo-layers';
    import {_TerrainExtension as TerrainExtension} from '@deck.gl/extensions';

    const layers = [
    new TerrainLayer({
    id: 'terrain',
    minZoom: 0,
    maxZoom: 23,
    strategy: 'no-overlap',
    elevationDecoder: {
    rScaler: 6553.6,
    gScaler: 25.6,
    bScaler: 0.1,
    offset: -10000
    },
    elevationData: `https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.png?access_token=${MAPBOX_TOKEN}`,
    texture: `https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}@2x.png?access_token=${MAPBOX_TOKEN}`,
    operation: 'terrain+draw'
    }),
    new GeoJsonLayer({
    data,
    getFillColor: [0, 160, 180, 200],
    getLineColor: [220, 80, 0],
    getLineWidth: 50,
    getPointRadius: 150,
    extensions: [new TerrainExtension()]
    })
    ];

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/extensions
    import {_TerrainExtension as TerrainExtension} from '@deck.gl/extensions';
    new TerrainExtension();

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.7.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.7.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/extensions@^8.7.0/dist.min.js"></script>
    new deck._TerrainExtension();

    Constructor

    new TerrainExtension();

    Layer Properties

    When added to a layer via the extensions prop, the TerrainExtension adds the following properties to the layer:

    terrainDrawMode ('offset' | 'drape')

    How data should be fitted to the terrain surface. If not specified, will be automatically determined from the layer type.

    • offset: each object is translated vertically by the elevation at its anchor (usually defined by an accessor called getPosition, e.g. icon, scatterplot). This is the desired behavior for layers that render 3D objects.
    • drape: each object is overlaid as a texture over the terrain surface. All altitude and extrusion in the layer will be ignored.

    terrainDrawMode: offset

    terrainDrawMode: drape

    Source

    modules/extensions/src/terrain

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/geohash-layer.html b/docs/api-reference/geo-layers/geohash-layer.html index 509bdc3b8fe..6c780749c3b 100644 --- a/docs/api-reference/geo-layers/geohash-layer.html +++ b/docs/api-reference/geo-layers/geohash-layer.html @@ -4,13 +4,13 @@ GeohashLayer | deck.gl - - + +

    GeohashLayer

    The GeohashLayer renders filled and/or stroked polygons based on the Geohash geospatial indexing system.

    GeohashLayer is a CompositeLayer.

    import DeckGL from '@deck.gl/react';
    import {GeohashLayer} from '@deck.gl/geo-layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * // Geohash in SF Bay Area
    * geohash: "9q8yv",
    * value: 0.7668453218020029
    * },
    * {
    * geohash: "9q8yyp",
    * value: 0.8789404786833306
    * },
    * ...
    * ]
    */
    const layer = new GeohashLayer({
    id: 'geohash-layer',
    data,
    pickable: true,
    wireframe: false,
    filled: true,
    extruded: true,
    elevationScale: 1000,
    getGeohash: d => d.geohash,
    getFillColor: d => [d.value * 255, (1 - d.value) * 128, (1 - d.value) * 255],
    getElevation: d => d.value
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.geohash} value: ${object.value}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {GeohashLayer} from '@deck.gl/geo-layers';
    new GeohashLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.7.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.7.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.7.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.7.0/dist.min.js"></script>
    new deck.GeohashLayer({});

    Properties

    Inherits from all Base Layer, CompositeLayer, and PolygonLayer properties, plus the following:

    Data Accessors

    getGeohash (Function, optional)

    Called for each data object to retrieve the geohash string identifier.

    • default: object => object.geohash

    Sub Layers

    The GeohashLayer renders the following sublayers:

    Source

    modules/geo-layers/src/geohash-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/great-circle-layer.html b/docs/api-reference/geo-layers/great-circle-layer.html index 2d5241c8f41..409086ebba9 100644 --- a/docs/api-reference/geo-layers/great-circle-layer.html +++ b/docs/api-reference/geo-layers/great-circle-layer.html @@ -4,14 +4,14 @@ GreatCircleLayer | deck.gl - - + +

    GreatCircleLayer

    The GreatCircleLayer is a variation of the ArcLayer. It renders flat arcs along the great circle joining pairs of source and target points, specified as latitude/longitude coordinates.

    Starting v8.2, using this layer is identical to using the ArcLayer with props greatCircle: true and getHeight: 0.

    import DeckGL, {GreatCircleLayer} from 'deck.gl';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * "from": {
    * "type": "major",
    * "name": "San Francisco Int'l",
    * "abbrev": "SFO",
    * "coordinates": [
    * -122.38347034444931,
    * 37.61702508680534
    * ]
    * },
    * "to": {
    * "type": "major",
    * "name": "Liverpool John Lennon",
    * "abbrev": "LPL",
    * "coordinates": [
    * -2.858620657849378,
    * 53.3363751054422
    * ]
    * }
    * ...
    * ]
    */
    const layer = new GreatCircleLayer({
    id: 'great-circle-layer',
    data,
    pickable: true,
    getStrokeWidth: 12,
    getSourcePosition: d => d.from.coordinates,
    getTargetPosition: d => d.to.coordinates,
    getSourceColor: [64, 255, 0],
    getTargetColor: [0, 128, 200]
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.from.name} to ${object.to.name}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {GreatCircleLayer} from '@deck.gl/geo-layers';
    new GreatCircleLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.0.0/dist.min.js"></script>
    new deck.GreatCircleLayer({});

    Properties

    Inherits from all Base Layer and ArcLayer properties.

    Source

    great-circle-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/h3-cluster-layer.html b/docs/api-reference/geo-layers/h3-cluster-layer.html index 15b119f1af1..72fc53fa4f7 100644 --- a/docs/api-reference/geo-layers/h3-cluster-layer.html +++ b/docs/api-reference/geo-layers/h3-cluster-layer.html @@ -4,13 +4,13 @@ H3ClusterLayer | deck.gl - - + +

    H3ClusterLayer

    The H3ClusterLayer renders regions represented by hexagon sets from the H3 geospatial indexing system.

    H3ClusterLayer is a CompositeLayer.

    import DeckGL from '@deck.gl/react';
    import {H3ClusterLayer} from '@deck.gl/geo-layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * mean: 73.333,
    * count: 440,
    * hexIds: [
    * '88283082b9fffff',
    * '88283082b1fffff',
    * '88283082b5fffff',
    * '88283082b7fffff',
    * '88283082bbfffff',
    * '882830876dfffff'
    * ]
    * },
    * ...
    * ]
    */
    const layer = new H3ClusterLayer({
    id: 'h3-cluster-layer',
    data,
    pickable: true,
    stroked: true,
    filled: true,
    extruded: false,
    getHexagons: d => d.hexIds,
    getFillColor: d => [255, (1 - d.mean / 500) * 255, 0],
    getLineColor: [255, 255, 255],
    lineWidthMinPixels: 2
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `density: ${object.mean}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {H3ClusterLayer} from '@deck.gl/geo-layers';
    new H3ClusterLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/h3-js@^4.0.0"></script>
    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.0.0/dist.min.js"></script>
    new deck.H3ClusterLayer({});

    Note that h3-js must be included before deck.gl.

    Properties

    Inherits from all Base Layer, CompositeLayer, and PolygonLayer properties, plus the following:

    Data Accessors

    getHexagons (Function, optional)

    Method called to retrieve the hexagon cluster from each object, as an array of H3 hexagon indices. These hexagons are joined into polygons that represent the geospatial outline of the cluster.

    Sub Layers

    The H3ClusterLayer renders the following sublayers:

    Source

    modules/geo-layers/src/h3-layers/h3-cluster-layer.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/h3-hexagon-layer.html b/docs/api-reference/geo-layers/h3-hexagon-layer.html index 005390cae4e..452fe8283db 100644 --- a/docs/api-reference/geo-layers/h3-hexagon-layer.html +++ b/docs/api-reference/geo-layers/h3-hexagon-layer.html @@ -4,13 +4,13 @@ H3HexagonLayer | deck.gl - - + +

    H3HexagonLayer

    The H3HexagonLayer renders hexagons from the H3 geospatial indexing system.

    H3HexagonLayer is a CompositeLayer.

    import DeckGL from '@deck.gl/react';
    import {H3HexagonLayer} from '@deck.gl/geo-layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * hex: '88283082b9fffff',
    * count: 96
    * },
    * ...
    * ]
    */
    const layer = new H3HexagonLayer({
    id: 'h3-hexagon-layer',
    data,
    pickable: true,
    wireframe: false,
    filled: true,
    extruded: true,
    elevationScale: 20,
    getHexagon: d => d.hex,
    getFillColor: d => [255, (1 - d.count / 500) * 255, 0],
    getElevation: d => d.count
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.hex} count: ${object.count}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {H3HexagonLayer} from '@deck.gl/geo-layers';
    new H3HexagonLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/h3-js@^4.0.0"></script>
    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.0.0/dist.min.js"></script>
    new deck.H3HexagonLayer({});

    Note that h3-js must be included before deck.gl.

    Properties

    Inherits from all Base Layer, CompositeLayer, and PolygonLayer properties, plus the following:

    Render Options

    highPrecision (Boolean, optional)
    • Default: 'auto'

    Each hexagon in the H3 indexing system is slightly different in shape. To draw a large number of hexagons efficiently, the H3HexagonLayer may choose to use instanced drawing by assuming that all hexagons within the current viewport have the same shape as the one at the center of the current viewport. The discrepancy is usually too small to be visible.

    There are several cases in which high-precision mode is required. In these cases, H3HexagonLayer may choose to switch to high-precision mode, where it trades performance for accuracy:

    • The input set contains a pentagon. There are 12 pentagons world wide at each resolution, and these cells and their immediate neighbors have significant differences in shape.
    • The input set is at a coarse resolution (res 0 through res 5). These cells have larger differences in shape, particularly when using a Mercator projection.
    • The input set contains hexagons with different resolutions.

    Possible values:

    • 'auto': The layer chooses the mode automatically. High-precision rendering is only used if an edge case is encountered in the data.
    • true: Always use high-precision rendering.
    • false: Always use instanced rendering, regardless of the characteristics of the data.
    coverage (Number, optional) transition-enabled
    • Default: 1

    Hexagon radius multiplier, between 0 - 1. When coverage = 1, hexagon is rendered with actual size, by specifying a different value (between 0 and 1) hexagon can be scaled down.

    Data Accessors

    getHexagon (Function, optional)
    • Default: object => object.hexagon

    Method called to retrieve the H3 hexagon index of each object. Note that all hexagons within one H3HexagonLayer must use the same resolution.

    Sub Layers

    The H3HexagonLayer renders the following sublayers:

    Source

    modules/geo-layers/src/h3-layers/h3-hexagon-layer.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/mvt-layer.html b/docs/api-reference/geo-layers/mvt-layer.html index 30fb1da8342..92811db518b 100644 --- a/docs/api-reference/geo-layers/mvt-layer.html +++ b/docs/api-reference/geo-layers/mvt-layer.html @@ -4,13 +4,13 @@ MVTLayer | deck.gl - - + +

    MVTLayer

    The MVTLayer is a derived TileLayer that makes it possible to visualize very large datasets through MVTs (Mapbox Vector Tiles). Behaving like TileLayer, it will only load, decode and render MVTs containing features that are visible within the current viewport.

    Data is loaded from URL templates in the data property.

    This layer also handles feature clipping so that there are no features divided by tile divisions.

    import DeckGL from '@deck.gl/react';
    import {MVTLayer} from '@deck.gl/geo-layers';

    function App({viewState}) {
    const layer = new MVTLayer({
    data: `https://a.tiles.mapbox.com/v4/mapbox.mapbox-streets-v7/{z}/{x}/{y}.vector.pbf?access_token=${MAPBOX_TOKEN}`,

    minZoom: 0,
    maxZoom: 23,
    getLineColor: [192, 192, 192],
    getFillColor: [140, 170, 180],

    getLineWidth: f => {
    switch (f.properties.class) {
    case 'street':
    return 6;
    case 'motorway':
    return 10;
    default:
    return 1;
    }
    },
    lineWidthMinPixels: 1
    });

    return <DeckGL viewState={viewState} layers={[layer]} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/extensions @deck.gl/geo-layers
    import {MVTLayer} from '@deck.gl/geo-layers';
    new MVTLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.0.0/dist.min.js"></script>
    new deck.MVTLayer({});

    Properties

    Inherits all properties from TileLayer and base Layer, with exceptions indicated below.

    If using the default renderSubLayers, supports all GeoJSONLayer properties to style features.

    data (String | Array | JSON)

    Required. It defines the remote data for the MVT layer.

    • String: Either a URL template or a TileJSON URL.

    • Array: an array of URL templates. It allows to balance the requests across different tile endpoints. For example, if you define an array with 4 urls and 16 tiles need to be loaded, each endpoint is responsible to server 16/4 tiles.

    • JSON: A valid TileJSON object.

    See TileLayer's data prop documentation for the URL template syntax.

    The getTileData prop from the TileLayer class will not be called.

    uniqueIdProperty (String)

    Optional. Needed for highlighting a feature split across two or more tiles if no feature id is provided.

    An string pointing to a tile attribute containing a unique identifier for features across tiles.

    highlightedFeatureId (Number | String)
    • Default: null

    Optional. When provided, a feature with ID corresponding to the supplied value will be highlighted with highlightColor.

    If uniqueIdProperty is provided, value within that feature property will be used for ID comparison. If not, feature id will be used.

    loadOptions (Object, optional)

    On top of the default options, also accepts options for the following loaders:

    Note that by default, the MVTLoader parses data using web workers, with code loaded from a CDN. To change this behavior, see loaders and workers.

    binary (Boolean, optional)
    • Default: true

    Use tile data in binary format to improve performance (2-3x faster on large datasets). It removes the need for serialization and deserialization of data transferred by the worker back to the main process. See here for details on this format.

    Remarks:

    • It requires using GeoJsonLayer in the renderSubLayers callback.

    Callbacks

    onDataLoad (Function, optional)

    Called if data is a TileJSON URL when it is successfully fetched

    Receives arguments:

    • tileJSON (Object) - the loaded TileJSON

    Methods

    getRenderedFeatures (Function)

    Get the rendered features in the current viewport.

    If a uniqueIdProperty is provided only unique properties are returned.

    Requires pickable prop to be true.

    Parameters:

    • maxFeatures (Number, optional): Max number of features to retrieve when getRenderedFeatures is called. Default to null.

    Returns:

    • An array with geometries in GeoJSON format.

    Remarks:

    • As it's an expensive operation, it's not recommended to call getRenderedFeatures every time onViewStateChange is executed, use a debounce function instead.
    • In most of the cases you probably want to use it attached to onViewStateChange and onViewportLoad.

    Tile

    Aside from all members of the Tile class, tile instances from the MVTLayer also include the following fields:

    dataInWGS84 (Array)

    A list of features in world coordinates (WGS84).

    Usage example:

    const onViewportLoad = tiles => {
    tiles.forEach(tile => {
    // data in world coordinates (WGS84)
    const dataInWGS84 = tile.dataInWGS84;
    });
    };
    new MVTLayer({
    id: "..."
    data: "..."
    onViewportLoad
    })

    Source

    modules/geo-layers/src/mvt-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/quadkey-layer.html b/docs/api-reference/geo-layers/quadkey-layer.html index ab90e41bb89..37bd54ccf06 100644 --- a/docs/api-reference/geo-layers/quadkey-layer.html +++ b/docs/api-reference/geo-layers/quadkey-layer.html @@ -4,13 +4,13 @@ QuadkeyLayer | deck.gl - - + +

    QuadkeyLayer

    The QuadkeyLayer renders filled and/or stroked polygons based on the Quadkey geospatial indexing system.

    QuadkeyLayer is a CompositeLayer.

    import DeckGL from '@deck.gl/react';
    import {QuadkeyLayer} from '@deck.gl/geo-layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * // Quadkey in SF Bay Area
    * quadkey: "023012010333",
    * value: 0.5979242952642347
    * },
    * {
    * quadkey: "023012010332",
    * value: 0.5446256069712141
    * },
    * ...
    * ]
    */
    const layer = new QuadkeyLayer({
    id: 'quadkey-layer',
    data,
    pickable: true,
    wireframe: false,
    filled: true,
    extruded: true,
    elevationScale: 1000,
    getQuadkey: d => d.quadkey,
    getFillColor: d => [d.value * 255, (1 - d.value) * 255, (1 - d.value) * 128],
    getElevation: d => d.value
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.quadkey} value: ${object.value}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {QuadkeyLayer} from '@deck.gl/geo-layers';
    new QuadkeyLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.7.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.7.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.7.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.7.0/dist.min.js"></script>
    new deck.QuadkeyLayer({});

    Properties

    Inherits from all Base Layer, CompositeLayer, and PolygonLayer properties, plus the following:

    Data Accessors

    getQuadkey (Function, optional)

    Called for each data object to retrieve the quadkey string identifier.

    • default: object => object.quadkey

    Sub Layers

    The QuadkeyLayer renders the following sublayers:

    Source

    modules/geo-layers/src/quadkey-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/s2-layer.html b/docs/api-reference/geo-layers/s2-layer.html index bdeae4169a1..eaf21e2f138 100644 --- a/docs/api-reference/geo-layers/s2-layer.html +++ b/docs/api-reference/geo-layers/s2-layer.html @@ -4,13 +4,13 @@ S2Layer | deck.gl - - + +

    S2Layer

    The S2Layer renders filled and/or stroked polygons based on the S2 geospatial indexing system.

    S2Layer is a CompositeLayer.

    import DeckGL from '@deck.gl/react';
    import {S2Layer} from '@deck.gl/geo-layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * // S2 Cell in SF Bay Area
    * token: "80858004",
    * value: 0.5979242952642347
    * },
    * {
    * token: "8085800c",
    * value: 0.5446256069712141
    * },
    * ...
    * ]
    */
    const layer = new S2Layer({
    id: 's2-layer',
    data,
    pickable: true,
    wireframe: false,
    filled: true,
    extruded: true,
    elevationScale: 1000,
    getS2Token: d => d.token,
    getFillColor: d => [d.value * 255, (1 - d.value) * 255, (1 - d.value) * 128],
    getElevation: d => d.value
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.token} value: ${object.value}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {S2Layer} from '@deck.gl/geo-layers';
    new S2Layer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.1.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.1.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.1.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.1.0/dist.min.js"></script>
    new deck.S2Layer({});

    Properties

    Inherits from all Base Layer, CompositeLayer, and PolygonLayer properties, plus the following:

    Data Accessors

    getS2Token (Function, optional) transition-enabled

    Called for each data object to retrieve the identifier of the S2 cell. May return one of the following:

    • A string that is the cell's hex token
    • A string that is the Hilbert quad key (containing /)
    • A Long object that is the cell's id

    Check S2 Cell for more details.

    • default: object => object.token

    Sub Layers

    The S2Layer renders the following sublayers:

    Source

    modules/geo-layers/src/s2-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/terrain-layer.html b/docs/api-reference/geo-layers/terrain-layer.html index 006e0ebc5a3..ee988498bae 100644 --- a/docs/api-reference/geo-layers/terrain-layer.html +++ b/docs/api-reference/geo-layers/terrain-layer.html @@ -4,8 +4,8 @@ TerrainLayer | deck.gl - - + +
    @@ -13,7 +13,7 @@ An object containing the following fields:

    • rScaler: Multiplier of the red channel.
    • gScaler: Multiplier of the green channel.
    • bScaler: Multiplier of the blue channel.
    • offset: Translation of the sum.

    Each color channel (r, g, and b) is a number between [0, 255].

    For example, the Mapbox terrain service's elevation is encoded as follows:

    height = -10000 + ((R * 256 * 256 + G * 256 + B) * 0.1)

    The corresponding elevationDecoder is:

    {
    "rScaler": 6553.6,
    "gScaler": 25.6,
    "bScaler": 0.1,
    "offset": -10000
    }

    The default value of elevationDecoder decodes a grayscale image:

    {
    "rScaler": 1,
    "gScaler": 0,
    "bScaler": 0,
    "offset": 0
    }
    bounds (Array, optional)

    Bounds of the image to fit x,y coordinates into. In [left, bottom, right, top]. left and right refers to the world longitude/x at the corresponding side of the image. top and bottom refers to the world latitude/y at the corresponding side of the image.

    Must be supplied when using non-tiled elevation data.

    • Default: null
    loadOptions (Object, optional)

    On top of the default options, also accepts options for the following loaders:

    Note that by default, the TerrainLoader parses data using web workers, with code loaded from a CDN. To change this behavior, see loaders and workers.

    Render Options

    color (Color, optional)

    Color to use if texture is unavailable. Forwarded to SimpleMeshLayer's getColor prop.

    • Default: [255, 255, 255]
    wireframe (Boolean, optional)

    Forwarded to SimpleMeshLayer's wireframe prop.

    • Default: false
    material (Object, optional)

    Forwarded to SimpleMeshLayer's material prop.

    • Default: true

    Sub Layers

    The TerrainLayer renders the following sublayers:

    • tiles - a TileLayer. Only rendered if elevationData is a URL template.
    • mesh - a SimpleMeshLayer rendering the terrain mesh.

    Source

    modules/geo-layers/src/terrain-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/tile-3d-layer.html b/docs/api-reference/geo-layers/tile-3d-layer.html index 4f6d5660c1a..8aaf3c2def1 100644 --- a/docs/api-reference/geo-layers/tile-3d-layer.html +++ b/docs/api-reference/geo-layers/tile-3d-layer.html @@ -4,8 +4,8 @@ Tile3DLayer | deck.gl - - + +
    @@ -16,7 +16,7 @@ It recieves tileHeader object as argument and return type is array of [r, g, b] values in the 0-255 range. This value is only applied when tile format is mesh. Can be used only for I3S debugging purposes.

    • Default: _getMeshColor: (tileHeader) => [255, 255, 255]

    Sub Layers

    The Tile3DLayer renders the following sublayers based on tile format:

    • scenegraph - a ScenegraphLayer rendering all the tiles with Batched 3D Model format (b3dm) or Instanced 3D Model format (i3dm).
      • _lighting is default to pbr.
    • pointcloud - a PointCloudLayer rendering all the tiles with Point Cloud format (pnts).
    • mesh - a SimpleMeshLayer rendering all the tiles ESRI MeshPyramids data.

    Follow CompositeLayer and example in this layer doc to see how to override sub layer props.

    Remarks

    • The Tile3DLayer can be rendered in multiple views. A tile is loaded if it is required by any of the viewports, and shared across all views via a single cache system.

    Source

    modules/geo-layers/src/tile-3d-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/tile-layer.html b/docs/api-reference/geo-layers/tile-layer.html index e464d5d628f..71b7870e7ce 100644 --- a/docs/api-reference/geo-layers/tile-layer.html +++ b/docs/api-reference/geo-layers/tile-layer.html @@ -4,8 +4,8 @@ TileLayer | deck.gl - - + +
    @@ -13,7 +13,7 @@ Users have the option to load each tile from a unique URL, defined by a template in the data property. The layer can also supply a callback getTileData that does custom fetching when a tile is requested. The loaded tile data is then rendered with the layer(s) returned by renderSubLayers.

    import DeckGL from '@deck.gl/react';
    import {BitmapLayer} from '@deck.gl/layers';
    import {TileLayer} from '@deck.gl/geo-layers';

    function App({viewState}) {
    const layer = new TileLayer({
    // https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
    data: 'https://c.tile.openstreetmap.org/{z}/{x}/{y}.png',

    minZoom: 0,
    maxZoom: 19,
    tileSize: 256,

    renderSubLayers: props => {
    const {
    bbox: {west, south, east, north}
    } = props.tile;

    return new BitmapLayer(props, {
    data: null,
    image: props.data,
    bounds: [west, south, east, north]
    });
    }
    });

    return <DeckGL viewState={viewState} layers={[layer]} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {TileLayer} from '@deck.gl/geo-layers';
    new TileLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.0.0/dist.min.js"></script>
    new deck.TileLayer({});

    Indexing System

    At each integer zoom level (z), the XY plane in the view space is divided into square tiles of the same size, each uniquely identified by their x and y index. When z increases by 1, the view space is scaled by 2, meaning that one tile at z covers the same area as four tiles at z+1.

    When the TileLayer is used with a geospatial view such as the MapView, x, y, and z are determined from the OSM tile index.

    When the TileLayer is used with a non-geospatial view such as the OrthographicView or the OrbitView, x and y increment from the world origin, and each tile's width and height match that defined by the tileSize prop. For example, the tile x: 0, y: 0 occupies the square between [0, 0] and [tileSize, tileSize].

    If you need to offset the z level at which the tiles are fetched in order to fetch tiles at a higher resolution in order to produce a "crisper" picture, there is a zoomOffset prop.

    Properties

    Inherits all properties from base Layer.

    If using the default renderSubLayers, supports all GeoJSONLayer properties to style features.

    Data Options

    data (String|Array, optional)
    • Default: []

    Either a URL template or an array of URL templates from which the tile data should be loaded.

    If the value is a string: a URL template. Substrings {x} {y} and {z}, if present, will be replaced with a tile's actual index when it is requested.

    If the value is an array: multiple URL templates. Each endpoint must return the same content for the same tile index. This can be used to work around domain sharding, allowing browsers to download more resources simultaneously. Requests made are balanced among the endpoints, based on the tile index.

    getTileData (Function, optional)
    • Default: tile => load(tile.url)

    If supplied, getTileData is called to retrieve the data of each tile. It receives one argument tile which contains the following fields:

    • index (Object) - index of the tile. index is in the shape of {x, y, z}, corresponding to the integer values specifying the tile.
    • id (String) - unique string representation of index.
    • url (String) - resolved url of the tile if the data prop is provided, otherwise null
    • bbox (Object) - bounding box of the tile. When used with a geospatial view, bbox is in the shape of {west: <longitude>, north: <latitude>, east: <longitude>, south: <latitude>}. When used with a non-geospatial view, bbox is in the shape of {left, top, right, bottom}.
    • signal (Object) - an AbortSignal that may be signalled if there are too many queued requests. Note: only tiles that aren't visible will be aborted.

    It should return either the tile data or a Promise that resolves to the tile data.

    This prop is not required if data points to a supported format (JSON or image by default). Additional formats may be added by registering loaders.gl modules.

    It is recommended to pass signal to any fetch calls and check its aborted property before doing any expensive computation. If signal is aborted, then throw or return falsy from getTileData so the data is not cached; do not return incomplete data. If signal is aborted, but getTileData still returns a truthy response, then its data will be cached.

    const {signal} = tile;
    const data = fetch(url, {signal});

    if (signal.aborted) {
    return null;
    }
    // Expensive computation on returned data
    TilesetClass (class, optional)
    • Default: Tileset2D

    Tileset class that TileLayer uses for tile indexing. Extend Tileset2D to implement a custom indexing scheme.

    tileSize (Number, optional)

    The pixel dimension of the tiles, usually a power of 2.

    For geospatial viewports, tile size represents the target pixel width and height of each tile when rendered. Smaller tile sizes display the content at higher resolution, while the layer needs to load more tiles to fill the same viewport.

    For non-geospatial viewports, the tile size should correspond to the true pixel size of the tiles.

    • Default: 512
    zoomOffset (Number, optional)

    This offset changes the zoom level at which the tiles are fetched. Needs to be an integer.

    • Default: 0
    maxZoom (Number|Null, optional)

    The max zoom level of the layer's data. When overzoomed (i.e. zoom > maxZoom), tiles from this level will be displayed.

    • Default: null
    minZoom (Number, optional)

    The min zoom level of the layer's data. When underzoomed (i.e. zoom < minZoom), the layer will not display any tiles unless extent is defined, to avoid issuing too many tile requests.

    • Default: 0
    extent (Array, optional)

    The bounding box of the layer's data, in the form of [minX, minY, maxX, maxY]. If provided, the layer will only load and render the tiles that are needed to fill this box.

    • Default: null
    maxCacheSize (Number, optional)

    The maximum number of tiles that can be cached. The tile cache keeps loaded tiles in memory even if they are no longer visible. It reduces the need to re-download the same data over and over again when the user pan/zooms around the map, providing a smoother experience.

    If not supplied, the maxCacheSize is calculated as 5 times the number of tiles in the current viewport.

    • Default: null
    maxCacheByteSize (Number, optional)

    The maximum memory used for caching tiles. If this limit is supplied, getTileData must return an object that contains a byteLength field.

    • Default: null
    refinementStrategy (String|Function, optional)

    How the tile layer refines the visibility of tiles. When zooming in and out, if the layer only shows tiles from the current zoom level, then the user may observe undesirable flashing while new data is loading. By setting refinementStrategy the layer can attempt to maintain visual continuity by displaying cached data from a different zoom level before data is available.

    This prop accepts one of the following:

    • 'best-available': If a tile in the current viewport is waiting for its data to load, use cached content from the closest zoom level to fill the empty space. This approach minimizes the visual flashing due to missing content.
    • 'no-overlap': Avoid showing overlapping tiles when backfilling with cached content. This is usually favorable when tiles do not have opaque backgrounds.
    • 'never': Do not display any tile that is not selected.
    • A custom function. See "custom strategy" below.
    • Default: 'best-available'
    custom strategy

    Apps may define a custom refinementStrategy by supplying its own callback function. The function will be called frequently on every viewport update and every tile loaded event.

    When called, the function receives an array of Tile instances representing every tile that is currently in the cache. It is an opportunity to manipulate tile.isVisible before sub layers are rendered. isVisible is initially set to the value of isSelected (equivalent to refinementStrategy: 'never').

    maxRequests (Number, optional)

    The maximum number of concurrent getTileData calls.

    If <= 0, no throttling will occur, and getTileData may be called an unlimited number of times concurrently regardless of how long that tile is or was visible.

    If > 0, a maximum of maxRequests instances of getTileData will be called concurrently. Requests may never be called if the tile wasn't visible long enough to be scheduled and started. Requests may also be aborted (through the signal passed to getTileData) if there are more than maxRequests ongoing requests and some of those are for tiles that are no longer visible.

    If getTileData makes fetch requests against an HTTP 1 web server, then maxRequests should correlate to the browser's maximum number of concurrent fetch requests. For Chrome, the max is 6 per domain. If you use the data prop and specify multiple domains, you can increase this limit. For example, with Chrome and 3 domains specified, you can set maxRequests=18.

    If the web server supports HTTP/2 (Open Chrome dev tools and look for "h2" in the Protocol column), then you can make an unlimited number of concurrent requests (and can set maxRequests=-1). Note that this will request data for every tile, no matter how long the tile was visible, and may increase server load.

    • Default: 6
    debounceTime (Number, optional)

    Queue tile requests until no new tiles have been added for at least debounceTime milliseconds.

    If debounceTime == 0, tile requests are issued as quickly as the maxRequests concurrent request limit allows.

    If debounceTime > 0, tile requests are queued until a period of at least debounceTime milliseconds has passed without any new tiles being added to the queue. May reduce bandwidth usage and total loading time during interactive view transitions.

    • Default: 0

    Render Options

    renderSubLayers (Function, optional)

    Renders one or an array of Layer instances with all the TileLayer props and the following props:

    • id: An unique id for this sublayer
    • data: Resolved from getTileData. As of deck.gl 8.2, this prop is always the data resolved from the Promise and is never a Promise itself.
    • tile: An object containing index, bbox, and id of the tile.
    • Default: props => new GeoJsonLayer(props)

    Note that the following sub layer props are overridden by TileLayer internally:

    • visible (toggled based on tile visibility)
    • highlightedObjectIndex (set based on the parent layer's highlight state)
    zRange (Array, optional)

    An array representing the height range of the content in the tiles, as [minZ, maxZ]. This is designed to support tiles with 2.5D content, such as buildings or terrains. At high pitch angles, such a tile may "extrude into" the viewport even if its 2D bounding box is out of view. Therefore, it is necessary to provide additional information for the layer to behave correctly. The value of this prop is used for two purposes: 1) to determine the necessary tiles to load and/or render; 2) to determine the possible intersecting tiles during picking.

    This prop currently only has effect when used with a geospatial view.

    • Default: null (interpreted as [0, 0])
    modelMatrix (Matrix4, optional)

    Affects both rendering and tile fetching to produce a transformed tile layer. Note that this can result in tiles being fetched outside the extent prop, for example if the modelMatrix defines a rotation.

    • Default: null

    Callbacks

    onViewportLoad (Function, optional)

    onViewportLoad is a function that is called when all tiles in the current viewport are loaded. An array of loaded Tile instances are passed as argument to this function

    • Default: data => null
    onTileLoad (Function, optional)

    onTileLoad called when a tile successfully loads.

    • Default: () => {}

    Receives arguments:

    • tile (Object) - the tile that has been loaded.
    onTileError (Function, optional)

    onTileError called when a tile failed to load.

    • Default: console.error

    Receives arguments:

    • error (Error)
    onTileUnload (Function, optional)

    onTileUnload called when a tile is cleared from cache.

    • Default: () => {}

    Receives arguments:

    • tile (Object) - the tile that has been cleared from cache.

    Tile

    Class to hold the reading of a single tile

    Properties:

    • index (Object) - index of the tile. index is in the shape of {x, y, z}, corresponding to the integer values specifying the tile.
    • id (String) - unique string representation of index, as 'x-y-z', e.g. '0-2-3'.
    • bbox (Object) - bounding box of the tile. When used with a geospatial view, bbox is in the shape of {west: <longitude>, north: <latitude>, east: <longitude>, south: <latitude>}. When used with a non-geospatial view, bbox is in the shape of {left, top, right, bottom}.
    • content (Object) - the tile's cached content. null if the tile's initial load is pending, cancelled, or encountered an error.
    • data (Object|Promise) - the tile's requested content. If the tile is loading, returns a Promise that resolves to the loaded content when loading is completed.
    • parent (Tile) - the nearest ancestor tile (a tile on a lower z that contains this tile), if present in the cache
    • children (Tile[]) - the nearest sub tiles (tiles on higher z that are contained by this tile), if present in the cache
    • isSelected (Boolean) - if the tile is expected to show up in the current viewport
    • isVisible (Boolean) - if the tile should be rendered
    • isLoaded (Boolean) - if the content of the tile has been loaded

    Tileset2D

    Class that manages loading and purging of tile data. This class caches recently visited tiles and only creates new tiles if they are present.

    To implement a custom indexing scheme, extend Tileset2D and implement the following interface:

    • getTileIndices({viewport, maxZoom, minZoom, zRange, modelMatrix, modelMatrixInverse}) - returns an array of indices in the given viewport. The indices should have the shape of Objects, like {q: '0123'}, to allow referencing in the URL template supplied to the data prop.
    • getTileId(index) - returns unique string key for a tile index.
    • getParentIndex(index) - returns the index of the parent tile.
    • getTileZoom(index) - returns a zoom level for a tile index.
    • getTileMetadata(index) - returns additional metadata to add to tile. This must be an object that contains a bounding box as bbox in the format {west: number, south: number, east: number, north: number}.

    For example, to index using quadkeys:

    import {_Tileset2D as Tileset2D} from '@deck.gl/geo-layers';
    class QuadkeyTileset2D extends Tileset2D {
    getTileIndices(opts) {
    // Quadkeys and OSM tiles share the layout, leverage existing algorithm
    // Data format: [{quadkey: '0120'}, {quadkey: '0121'}, {quadkey: '0120'},...]
    return super.getTileIndices(opts).map(tileToQuadkey);
    }

    getTileId({quadkey}) {
    return quadkey;
    }

    getTileZoom({quadkey}) {
    return quadkey.length;
    }

    getParentIndex({quadkey}) {
    const quadkey = quadkey.slice(0, -1);
    return {quadkey};
    }
    }

    const quadkeyTileLayer = new TileLayer({
    TilesetClass: QuadkeyTileset2D,
    data: 'quadkey/{quadkey}.json',
    ...
    });

    Source

    modules/geo-layers/src/tile-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/trips-layer.html b/docs/api-reference/geo-layers/trips-layer.html index b2d293b2fb4..c4b4f2d7a18 100644 --- a/docs/api-reference/geo-layers/trips-layer.html +++ b/docs/api-reference/geo-layers/trips-layer.html @@ -4,14 +4,14 @@ TripsLayer | deck.gl - - + +

    TripsLayer

    The TripsLayer renders animated paths that represent vehicle trips.

    import {TripsLayer} from '@deck.gl/geo-layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * waypoints: [
    * {coordinates: [-122.3907988, 37.7664413], timestamp: 1554772579000}
    * {coordinates: [-122.3908298,37.7667706], timestamp: 1554772579010}
    * ...,
    * {coordinates: [-122.4485672, 37.8040182], timestamp: 1554772580200}
    * ]
    * }
    * ]
    */
    const layer = new TripsLayer({
    id: 'trips-layer',
    data,
    getPath: d => d.waypoints.map(p => p.coordinates),
    // deduct start timestamp from each data point to avoid overflow
    getTimestamps: d => d.waypoints.map(p => p.timestamp - 1554772579000),
    getColor: [253, 128, 93],
    opacity: 0.8,
    widthMinPixels: 5,
    rounded: true,
    fadeTrail: true,
    trailLength: 200,
    currentTime: 100
    });

    return <DeckGL viewState={viewState} layers={[layer]} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {TripsLayer} from '@deck.gl/geo-layers';
    new TripsLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.0.0/dist.min.js"></script>
    new deck.TripsLayer({});

    Properties

    Inherits from all Base Layer and PathLayer properties, plus the following:

    Render Options

    currentTime (Number, optional) transition-enabled
    • Default: 0

    The current time of the frame, i.e. the playhead of the animation.

    This value should be in the same units as the timestamps from getPath.

    fadeTrail (Boolean, optional)
    • Default: true

    Whether or not the path fades out.

    If false, trailLength has no effect.

    trailLength (Number, optional) transition-enabled
    • Default: 120

    How long it takes for a path to completely fade out.

    This value should be in the same units as the timestamps from getPath.

    Data Accessors

    getPath (Function, optional)
    • Default: d => d.path

    Called for each data object to retrieve paths. Returns an array of navigation points on a single path.

    See PathLayer documentation for supported path formats.

    getTimestamps (Function, optional)
    • Default: d => d.timestamps

    Returns an array of timestamps, one for each navigation point in the geometry returned by getPath, representing the time that the point is visited.

    Because timestamps are stored as 32-bit floating numbers, raw unix epoch time can not be used. You may test the validity of a timestamp by calling Math.fround(t) to check if there would be any loss of precision.

    Legacy API, removing in a future major release:

    If getTimestamps is not supplied, each navigation point in the path is interpreted as [longitude, latitude, timestamp], and the paths will always be rendered flat against the ground.

    Source

    modules/geo-layers/src/trips-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/geo-layers/wms-layer.html b/docs/api-reference/geo-layers/wms-layer.html index cc52851ce8a..04c41a3f454 100644 --- a/docs/api-reference/geo-layers/wms-layer.html +++ b/docs/api-reference/geo-layers/wms-layer.html @@ -4,13 +4,13 @@ WMSLayer (Experimental) | deck.gl - - + +

    WMSLayer (Experimental)

    from v8.9

    This class is experimental, which means it does not provide the compatibility and stability that one would typically expect from other layers, detailed in the limitations section. Use with caution and report any issues that you find on GitHub.

    The WMSLayer is a composite layer that connects with an image service that can render map images optimized for the current view. Instead of loading a detailed map image covering the entire globe, an image is rendered.

    In contrast to the TileLayer which loads many small image tiles, the WMSLayer loads a single image that covers the entire viewport in one single request, and updates the image by performing additional requests when the viewport changes.

    To use this layer, an image source must be specified. Image sources are specified by supplying a URL to the WMSLayer data property. See the section on image sources below for mor information.

    import DeckGL from '@deck.gl/react';
    import {BitmapLayer} from '@deck.gl/layers';
    import {_WMSLayer as WMSLayer} from '@deck.gl/geo-layers';

    function App({viewState}) {
    const layer = new WMSLayer({
    data: 'https://ows.terrestris.de/osm/service',
    serviceType: 'wms',
    layers: ['OSM-WMS']
    });

    return <DeckGL viewState={viewState} layers={[layer]} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/geo-layers
    import {_WMSLayer as WMSLayer} from '@deck.gl/geo-layers';
    new WMSLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/geo-layers@^8.0.0/dist.min.js"></script>
    new deck._WMSLayer({});

    Image Sources

    The WMSLayer needs a URL to an image source from which it can start loading map images. The WMSLayer knows how to build URLs for geospatial image services such as WMS.

    However, it is also possible to connect the WMSLayer to any other REST based service that can render map images from a set of web mercator bounds and a given pixel resolution (perhaps an ArcGIS image server) by specify a custom URL template.

    Note that additional features, such as metadata loading, is only supported for known image services, which currently only includes WMS.

    Layers

    Image servers such as WMS can render different layers. Typically as list of layers must be specified, otherwise requests for map images will fail. For WMS services, this is controlled by props.layers. For other services, layers (if required by that service) can be specified in the template URL, either as a parameter or as a hard-coded part of the template string.

    Image Service Metadata

    Image services like WMS can often provide metadata (aka capabilities) about the service, listing;

    • attribution information,
    • available layers
    • additional capabilities (pixel/neighborhood queries, legend generation etc).

    The WMSLayer will automatically attempt to query metadata for known service types (currently WMS).

    Template URLs only cover image requests and there is no support for providing a custom URL for the metadata queries. This needs to be handled by the application for non-WMS services.

    Interactivity

    WMS services sometimes provide a mechanism to query a specific pixel. This is supported through the getFeatureInfoText() method on the WMSLayer

    Methods

    getFeatureInfoText()

    This is a method on the layer that can be called to retrieve additional information from the image service about the map near the specified pixel.

    Arguments:

    • x (number) - The x component of the pixel in the image
    • y (number) - The y component of the pixel in the image

    Returns

    • Promise<string> - Resolves to a string containing additional information about the map around the provided pixel

    Properties

    Inherits all properties from base Layer.

    Data Options

    data (string)

    A base URL to a well-known service type, or a full URL template from which the map images should be loaded.

    If props.serviceType is set to 'template', data is expected to be a URL template. The template may contain the following substrings, which will be replaced with a viewport's actual bounds and size at request time:

    • {east}
    • {north}
    • {west}
    • {south}
    • {width}
    • {height}
    • {layers} - replaced with a string built from the content of props.layers. The array of layer name strings in props.layers will be joined by commas (,) into a single string.
    serviceType (string, optional)
    • Default: 'auto'

    Specifies the type of service at the URL supplied in props.data. Currently accepts either 'wms' or 'template'. The default 'auto' setting will try to autodetect service from the URL.

    layers (string[], optional)
    • Default: []

    Specifies names of layers that should be visualized from the image service.

    Note that WMS services will typically not display anything unless at least one valid layer name is provided.

    srs (string, optional)
    • Default: 'auto'

    Spatial Reference System for map output, used to query image from the server. Can be one of EPSG:4326', 'EPSG:3857' or 'auto'.

    If 'auto', the layer will request EPSG:3857 in MapView, and EPSG:4326 otherwise. Note that a particular SRS may not be supported by your image server.

    Callbacks

    onMetadataLoad (Function, optional)

    onMetadataLoad called when the metadata of the image source successfully loads.

    • Default: metadata => {}

    Receives arguments:

    • metadata (Object) - The metadata for the image services has been loaded.

    Note that metadata will not be loaded when props.serviceType is set to 'template.

    onMetadataLoadError (Function, optional)

    onMetadataLoadError called when metadata failed to load.

    • Default: console.error

    Receives arguments:

    • error (Error)
    onImageLoadStart (Function, optional)

    onImageLoadStart is a function that is called when the WMSLayer starts loading metadata after a new image source has been specified.

    • Default: data => null

    Receives arguments:

    • requestId (number) - Allows tracking of specific requests
    onImageLoad (Function, optional)

    onImageLoad called when an image successfully loads.

    • Default: () => {}

    Receives arguments:

    • requestId (number) - Allows tracking of specific requests
    onImageLoadError (Function, optional)

    onImageLoadError called when an image failed to load.

    • Default: console.error

    Receives arguments:

    • requestId (number) - Allows tracking of specific requests
    • error (Error)

    Limitations

    • Each instance of the WMSLayer only supports being rendered in one view. See rendering layers in multiple views for a workaround.
    • This layer currently does not work well with perspective views (i.e. pitch>0).
    • This layer does not work with non-geospatial views such as the OrthographicView or the OrbitView.

    Source

    modules/geo-layers/src/wms-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/google-maps/google-maps-overlay.html b/docs/api-reference/google-maps/google-maps-overlay.html index a0f9b3052ff..1ca83c69da5 100644 --- a/docs/api-reference/google-maps/google-maps-overlay.html +++ b/docs/api-reference/google-maps/google-maps-overlay.html @@ -4,13 +4,13 @@ GoogleMapsOverlay | deck.gl - - + +

    GoogleMapsOverlay

    This class implements the OverlayView/WebGLOverlayView (depending on map rendering type) interface and can be used as any other Google Maps overlay.

    Vector/Raster maps

    As detailed in the overview, the overlay supports both Vector and Raster Google map rendering. Depending on the Google Map configuration, the correct deck.gl overlay rendering method will be chosen at runtime.

    Usage

      import {GoogleMapsOverlay as DeckOverlay} from '@deck.gl/google-maps';
    import {GeoJsonLayer} from '@deck.gl/layers';

    // Create map
    const map = new google.maps.Map(document.getElementById('map'), {
    center: { lat: 40, lng: -100 },
    zoom: 5,
    mapId: GOOGLE_MAP_ID // Only required for Vector maps
    });

    // Create overlay instance
    const overlay = new DeckOverlay({
    layers: [
    new GeoJsonLayer({
    ...
    })
    ]
    });
    // Add overlay to map
    overlay.setMap(map);

    Constructor

    const overlay = new GoogleMapsOverlay(props)

    props are forwarded to a Deck instance. The following Deck props are supported:

    • style
    • layers
    • effects
    • parameters
    • pickingRadius
    • useDevicePixels
    • onWebGLInitialized
    • onBeforeRender
    • onAfterRender
    • onLoad

    The constructor additionally accepts the following option:

    • interleaved (Boolean) - When set to false, a dedicated deck.gl canvas is layered on top of the base map. If set to true and the Google Map is configured for Vector rendering, deck.gl layers are inserted into the Google Maps layer stack, sharing the same WebGL2RenderingContext. Default is true.

    Methods

    setMap
    overlay.setMap(map);

    Add/remove the overlay from a map. An overlay can be temporarily hidden from a map by calling setMap(null). Removing an overlay does not destroy the WebGL2 context; use finalize() if the overlay should be permanently removed.

    setProps
    overlay.setProps(props);

    Update (partial) props.

    pickObject

    Equivalent of deck.pickObject.

    pickObjects

    Equivalent of deck.pickObjects.

    pickMultipleObjects

    Equivalent of deck.pickMultipleObjects.

    finalize
    overlay.finalize();

    Remove the overlay and release all underlying resources.

    getCanvas

    See Deck.getCanvas. When using interleaved: true, returns the base map's canvas.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/google-maps/overview.html b/docs/api-reference/google-maps/overview.html index 68f2c68d870..ef92cbbacc9 100644 --- a/docs/api-reference/google-maps/overview.html +++ b/docs/api-reference/google-maps/overview.html @@ -4,13 +4,13 @@ @deck.gl/google-maps | deck.gl - - + +

    @deck.gl/google-maps

    Use deck.gl layers as a custom Google Maps overlay.

    Installation

    Include the Standalone Bundle

    <script src="https://unpkg.com/deck.gl@^7.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/google-maps@^7.0.0/dist.min.js"></script>
    <!-- usage -->
    <script type="text/javascript">
    const {GoogleMapsOverlay} = deck;
    </script>

    Install from NPM

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/google-maps
    import {GoogleMapsOverlay} from '@deck.gl/google-maps';

    Vector/Raster maps

    Starting with Google Maps v3.45 there are two modes of rendering Vector and Raster. To control which rendering mode is used, you need to configure the Google Map using the Google Cloud Platform.

    From v8.6, the GoogleMapsOverlay class automatically detects at runtime which rendering type is used. The Vector rendering mode is in general more performant, and the GoogleMapsOverlay class offers several features not available when using Raster rendering:

    • Shared 3D space: objects drawn by the GoogleMapsOverlay class appear inside the Google Maps scene, correctly intersecting with 3D buildings and behind the contextual labels drawn by Google Maps
    • Tilting and rotating the view is supported
    • Rendering uses the same WebGL2 context as Google Maps, improving performance

    Supported Features and Limitations

    Supported deck.gl features:

    • Layers
    • Effects
    • Auto-highlighting
    • Attribute transitions
    • onHover and onClick callbacks
    • Tooltip
    • Tilting & Rotation (Vector maps only)

    Not supported features:

    • Views
    • Controller
    • React integration
    • Gesture event callbacks (e.g. onDrag*)
    - - + + \ No newline at end of file diff --git a/docs/api-reference/json/conversion-reference.html b/docs/api-reference/json/conversion-reference.html index dc30c7f8757..67bae5fa0bd 100644 --- a/docs/api-reference/json/conversion-reference.html +++ b/docs/api-reference/json/conversion-reference.html @@ -4,8 +4,8 @@ Conversion Reference | deck.gl - - + +
    @@ -22,7 +22,7 @@ an array of coordinates (e.g., [[0, 1], [0, 5]]), passing @@=- would return those values.

    Additionally, @@= provides access to a small Javascript expression parser. You can apply basic Boolean, inline conditionals, and arithmetic operations via this parser. For example, the following are all valid functions–

    "getPosition": "@@=[lng, lat, altitudeMeters]",
    "getFillColor": "@@=[color / 255, 200, 20]",
    "getLineColor": "@@=value > 10 ? [255, 0, 0] : [0, 255, 200]",

    Each would be evaluated to an expression equivalent to–

    datum => [datum.lng, datum.lat, altitudeMeters / 1000]
    datum => [datum.color / 255, 200, 20]
    datum => datum.value > 10 ? [255, 0, 0] : [0, 255, 200]
    - - + + \ No newline at end of file diff --git a/docs/api-reference/json/json-configuration.html b/docs/api-reference/json/json-configuration.html index 690589303ff..d95a43fe15c 100644 --- a/docs/api-reference/json/json-configuration.html +++ b/docs/api-reference/json/json-configuration.html @@ -4,13 +4,13 @@ JSONConfiguration | deck.gl - - + +

    JSONConfiguration

    Object with the following fields.

    • classes - a map of general classes that should be made available to the JSON class resolver. (In the case of deck.gl, this would typically be Layer and View classes).
    • functions - a map of functions that should be made available to the JSON function resolver.
    • enumerations - a map of enumerations that should be made available to the JSON string resolver.
    • constants - A map of constants that should be made available to the JSON string resolver.
    • reactComponents - a map of general react components that should be made available to the JSON class resolver.
    • React - React support is experimental. The React dependency has to be injected via the configuration

    See more details in the Configuration Reference section.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/json/json-converter.html b/docs/api-reference/json/json-converter.html index a94083f12ba..09d7645361c 100644 --- a/docs/api-reference/json/json-converter.html +++ b/docs/api-reference/json/json-converter.html @@ -4,14 +4,14 @@ JSONConverter | deck.gl - - + +

    JSONConverter

    NOTE: This component is only intended to support official deck.gl API props via JSON. In particular, it is not intended to evolve an implementation of alternate JSON schemas. Support for such schemas should be developed independently, perhaps using the source code of this component as a base. See the JSON Layers RFC for more on this.

    Converts a JSON description of a deck.gl visualization into properties that can be passed to the Deck component.

    Requirements on the JSON description:

    • Expected to contain at minimum "layers" and "initialViewState" fields.
    • The JSON for each layer should be formatted as in described in JSONLayer.

    Usage

    import {JSONConverter} from '@deck.gl/json';

    import json from './us-map.json';

    const configuration = {
    layers: require('@deck.gl/layers')
    };

    const new jsonConverter = new JSONConverter({configuration});

    const deck = new Deck({
    canvas: 'deck-canvas',
    json
    });

    deck.setProps(jsonConverter.convert(json));

    Properties

    json (Object|String)

    A JSON string or a parsed JSON structure. All properties in this object, after processing, are passed to a Deck instance as props.

    Configuration

    See more details in the Configuration Reference section.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/json/overview.html b/docs/api-reference/json/overview.html index 938c966ce9f..e5bc1274841 100644 --- a/docs/api-reference/json/overview.html +++ b/docs/api-reference/json/overview.html @@ -4,13 +4,13 @@ @deck.gl/json | deck.gl - - + +

    @deck.gl/json

    The deck.gl JSON module provides a JSONConverter class that converts textual JSON specifications into JavaScript objects, and functions.

    Through a set of conventions, the JSON module allows the specification of JavaScript class instances, React elements, enumerations and functions (in addition to the basic types created during the JSON parsing process (i.e. arrays, objects, strings, numbers and booleans).

    The set of classes, React components, functions, constants and enumerations that should be available to the JSONConverter must be provided via an application-provided configuration object.

    Use Cases

    Especially in the infovis space, there is a growing need to be able to generate powerful visualizations directly from the backend. Being able to describe a visualization in abstract terms and send it to the front-end for display without modifying JavaScript code can be valuable.

    deck.gl Integration

    deck.gl supports a declarative system for describing layers and their props, and this declarative API can be trivially exposed via the JSON API.

    A JSON layer editor built on the @deck.gl/json module

    See our live demo.

    The module was created to enable specifying deck.gl visualizations using JSON formatted text files and strings, but is completely generic and

    Installation

    Include the Standalone Bundle

    <script src="https://unpkg.com/deck.gl@^7.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^7.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/json@^7.0.0/dist.min.js"></script>
    <!-- usage -->
    <script type="text/javascript">
    const {JSONConverter} = deck;
    </script>

    Install from NPM

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers @deck.gl/json
    import {JSONConverter} from '@deck.gl/json';

    Schema

    The valid combinations are defined by the documented API.

    Error Handling

    Error detection is currently limited and error messages may not be very helpful.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers.html b/docs/api-reference/layers.html index 5ba31b24690..25142bb84a2 100644 --- a/docs/api-reference/layers.html +++ b/docs/api-reference/layers.html @@ -4,13 +4,13 @@ Layer Catalog Overview | deck.gl - - + +

    Layer Catalog Overview

    For first-time deck.gl developers, it is helpful to read the following pages before jumping into the layer catalog:

    • Guide to using deck.gl layers: general concepts and frequently asked questions
    • All deck.gl layers inherit from either the Layer or the CompositeLayer base classes, and the props of those layers are available to all layers unless otherwise documented. The base class props are not repeated in individual layer documentation.

    Core Layers

    The Core Layers are a group of generic-purpose layers, intended to represent the building blocks for all data visualizations.

    The core layers are the most stable and supported deck.gl layers.

    Aggregation Layers

    The Aggregation Layers are layers that aggregate the input data and visualize them in alternative representations, such as grid and hexagon binning, contour, and heatmap.

    Geo Layers

    The Geo Layers collects layers that specifically target geospatial visualization use cases, including support for map tiles, popular geospatial indexing systems, GIS formats, etc.

    Mesh Layers

    The Mesh Layers visualize 3D models, with experimental support for scenegraph in the glTF format.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/arc-layer.html b/docs/api-reference/layers/arc-layer.html index 5366adf2603..4275595ebd9 100644 --- a/docs/api-reference/layers/arc-layer.html +++ b/docs/api-reference/layers/arc-layer.html @@ -4,14 +4,14 @@ ArcLayer | deck.gl - - + +

    ArcLayer

    The ArcLayer renders raised arcs joining pairs of source and target coordinates.

    import DeckGL from '@deck.gl/react';
    import {ArcLayer} from '@deck.gl/layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * inbound: 72633,
    * outbound: 74735,
    * from: {
    * name: '19th St. Oakland (19TH)',
    * coordinates: [-122.269029, 37.80787]
    * },
    * to: {
    * name: '12th St. Oakland City Center (12TH)',
    * coordinates: [-122.271604, 37.803664]
    * },
    * ...
    * ]
    */
    const layer = new ArcLayer({
    id: 'arc-layer',
    data,
    pickable: true,
    getWidth: 12,
    getSourcePosition: d => d.from.coordinates,
    getTargetPosition: d => d.to.coordinates,
    getSourceColor: d => [Math.sqrt(d.inbound), 140, 0],
    getTargetColor: d => [Math.sqrt(d.outbound), 140, 0],
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.from.name} to ${object.to.name}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers
    import {ArcLayer} from '@deck.gl/layers';
    new ArcLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    new deck.ArcLayer({});

    Properties

    Inherits from all Base Layer properties.

    Render Options

    greatCircle (Boolean, optional)
    • Default: false

    If true, create the arc along the shortest path on the earth surface. This option is only effective with data in the LNGLAT coordinate system.

    numSegments (Number, optional)
    • Default: 50

    The number of segments used to draw each arc. This prop can be used to make arcs smooth when using greatCircle with long paths.

    widthUnits (String, optional)
    • Default: 'pixels'

    The units of the line width, one of 'meters', 'common', and 'pixels'. See unit system.

    widthScale (Number, optional) transition-enabled
    • Default: 1

    The scaling multiplier for the width of each line. This prop is a very efficient way to change the width of all objects, comparing to recalculating the width for each object with getWidth.

    widthMinPixels (Number, optional) transition-enabled
    • Default: 0

    The minimum line width in pixels. This prop can be used to prevent the line from getting too thin when zoomed out.

    widthMaxPixels (Number, optional) transition-enabled
    • Default: Number.MAX_SAFE_INTEGER

    The maximum line width in pixels. This prop can be used to prevent the line from getting too thick when zoomed in.

    Data Accessors

    getSourcePosition (Function, optional) transition-enabled
    • Default: object => object.sourcePosition

    Method called to retrieve the source position of each object.

    getTargetPosition (Function, optional) transition-enabled
    • Default: object => object.targetPosition

    Method called to retrieve the target position of each object.

    getSourceColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the source color for all objects.
    • If a function is provided, it is called on each object to retrieve its source color.
    getTargetColor (Function|Array, optional) transition-enabled
    • Default [0, 0, 0, 255]

    The rgba color at the target, in r, g, b, [a]. Each component is in the 0-255 range.

    • If an array is provided, it is used as the target color for all objects.
    • If a function is provided, it is called on each object to retrieve its target color.
    getWidth (Function|Number, optional) transition-enabled
    • Default: 1

    The line width of each object, in units specified by widthUnits (default pixels).

    • If a number is provided, it is used as the line width for all objects.
    • If a function is provided, it is called on each object to retrieve its line width.
    getHeight (Function|Number, optional) transition-enabled
    • Default: 1

    Multiplier of layer height. 0 will make the layer flat.

    getTilt (Function|Number, optional) transition-enabled
    • Default: 0

    Use to tilt the arc to the side if you have multiple arcs with the same source and target positions. In degrees, can be positive or negative (-90 to +90).

    Source

    modules/layers/src/arc-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/bitmap-layer.html b/docs/api-reference/layers/bitmap-layer.html index 26f080ba4e4..e54e4605f6d 100644 --- a/docs/api-reference/layers/bitmap-layer.html +++ b/docs/api-reference/layers/bitmap-layer.html @@ -4,14 +4,14 @@ BitmapLayer | deck.gl - - + +

    BitmapLayer

    The BitmapLayer renders a bitmap at specified boundaries.

    import DeckGL from '@deck.gl/react';
    import {BitmapLayer} from '@deck.gl/layers';

    function App({data, viewState}) {
    const layer = new BitmapLayer({
    id: 'bitmap-layer',
    bounds: [-122.5190, 37.7045, -122.355, 37.829],
    image: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-districts.png'
    });

    return <DeckGL viewState={viewState} layers={[layer]} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers
    import {BitmapLayer} from '@deck.gl/layers';
    new BitmapLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    new deck.BitmapLayer({});

    Properties

    Data

    image (String|Texture|Image|ImageData|HTMLCanvasElement|HTMLVideoElement|ImageBitmap|Promise|Object)
    • Default null.

    The image to display.

    • If a string is supplied, it is interpreted as a URL or a Data URL.
    • One of the following, or a Promise that resolves to one of the following:
      • One of the valid pixel sources for WebGL2 texture
      • A luma.gl Texture instance
      • A plain object that can be passed to the Texture constructor, e.g. {width: <number>, height: <number>, data: <Uint8Array>}. Note that whenever this object shallowly changes, a new texture will be created.

    The image data will be converted to a Texture object. See textureParameters prop for advanced customization.

    bounds (Array)

    Supported formats:

    • Coordinates of the bounding box of the bitmap [left, bottom, right, top]
    • Coordinates of four corners of the bitmap, should follow the sequence of [[left, bottom], [left, top], [right, top], [right, bottom]]. Each position could optionally contain a third component z.

    left and right refers to the world longitude/x at the corresponding side of the image. top and bottom refers to the world latitude/y at the corresponding side of the image.

    loadOptions (Object, optional)

    On top of the default options, also accepts options for the following loaders:

    textureParameters (Object)

    Customize the texture parameters.

    If not specified, the layer uses the following defaults to create a linearly smoothed texture from image:

    {
    minFilter: 'linear',
    magFilter: 'linear',
    mipmapFilter: 'linear',
    addressModeU: 'clamp-to-edge',
    addressModeV: 'clamp-to-edge'
    }

    For example, to remove smoothing and achieve a pixelated appearance:

    import GL from '@luma.gl/constants';

    new BitmapLayer({
    ...
    textureParameters: {
    minFilter: 'nearest',
    magFilter: 'nearest'
    }
    })

    This prop is only used when image initially loads or changes.

    _imageCoordinateSystem (Number, optional)

    Note: this prop is experimental.

    Specifies how image coordinates should be geographically interpreted.

    By default, the image is uniformly stretched to fill the geometry defined by bounds. This might not be desirable if the image is encoded in a different coordinate system from the projection that the layer is using. For example, a satellite image encoded in longitude/latitude should not be interpreted linearly when placed in a Web Mercator visualization.

    This prop allows you to explicitly inform the layer of the coordinate system of the image:

    • COORDINATE_SYSTEM.LNGLAT if x-axis maps to longitude and y-axis maps to latitude
    • COORDINATE_SYSTEM.CARTESIAN if the image is pre-projected into the Web Mercator plane.

    This option only works with geospatial views and bounds that is orthogonal ([left, bottom, right, top]).

    See the article on Coordinate Systems for more information.

    Render Options

    desaturate (Number) transition-enabled
    • Default 0

    The desaturation of the bitmap. Between [0, 1]. 0 being the original color and 1 being grayscale.

    transparentColor (Array) transition-enabled
    • Default [0, 0, 0, 0]

    The color to use for transparent pixels, in [r, g, b, a]. Each component is in the [0, 255] range. Equivalent to overlaying the image over a background in this color.

    tintColor (Array) transition-enabled
    • Default [255, 255, 255]

    The color to tint the bitmap by, in [r, g, b]. Each component is in the [0, 255] range.

    Pixel Picking

    (From v8.4) The picking info passed to callbacks (onHover, onClick, etc.) provides information on which pixel was picked. It contains an additional bitmap field if applicable:

    • bitmap
      • pixel ([number, number]) Integer coordinates into the bitmap
      • size ({width: number; height: number}) Size of bitmap in pixels
      • uv ([number, number]) Normalized (0-1) floating point coordinates

    Note that the bitmap field can be null if on mouse leave or if the bitmap has not yet loaded.

    The following code reads the picked pixel color from the bitmap when the layer is clicked:

    import {readPixelsToArray} from '@luma.gl/core';

    new BitmapLayer({
    image: './my-image.png',
    bounds: [-122.45, 37.75, -122.43, 37.78],
    pickable: true,
    onClick: ({bitmap, layer}) => {
    if (bitmap) {
    const pixelColor = readPixelsToArray(layer.props.image, {
    sourceX: bitmap.pixel[0],
    sourceY: bitmap.pixel[1],
    sourceWidth: 1,
    sourceHeight: 1
    })
    console.log('Color at picked pixel:', pixelColor)
    }
    }
    })

    Source

    modules/layers/src/bitmap-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/column-layer.html b/docs/api-reference/layers/column-layer.html index 91f9636d589..092c060c736 100644 --- a/docs/api-reference/layers/column-layer.html +++ b/docs/api-reference/layers/column-layer.html @@ -4,8 +4,8 @@ ColumnLayer | deck.gl - - + +
    @@ -16,7 +16,7 @@ "horizontal" lines closing the top and bottom polygons and a vertical line (a "strut") for each vertex around the disk. Only applies if extruded: true.

    flatShading (Boolean, optional)
    • Default: false

    If true, the vertical surfaces of the columns use flat shading. If false, use smooth shading. Only effective if extruded is true.

    radiusUnits (String, optional)
    • Default: 'meters'

    The units of the radius, one of 'meters', 'common', and 'pixels'. See unit system.

    lineWidthUnits (String, optional)
    • Default: 'meters'

    The units of the line width, one of 'meters', 'common', and 'pixels'. See unit system.

    lineWidthScale (Boolean, optional) transition-enabled
    • Default: 1

    The line width multiplier that multiplied to all outlines if the stroked attribute is true.

    lineWidthMinPixels (Number, optional) transition-enabled
    • Default: 0

    The minimum outline width in pixels.

    lineWidthMaxPixels (Number, optional) transition-enabled
    • Default: Number.MAX_SAFE_INTEGER

    The maximum outline width in pixels.

    material (Object, optional)
    • Default: true

    This is an object that contains material props for lighting effect applied on extruded polygons. Check the lighting guide for configurable settings.

    Data Accessors

    getPosition (Function, optional) transition-enabled
    • Default: object => object.position

    Method called to retrieve the position of each column, in [x, y]. An optional third component can be used to set the elevation of the bottom.

    getFillColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    • If not provided, it falls back to getColor.
    getLineColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the outline color for all columns.
    • If a function is provided, it is called on each object to retrieve its outline color.
    • If not provided, it falls back to getColor.
    getElevation (Function|Number, optional) transition-enabled
    • Default: 1000

    The elevation of each cell in meters.

    • If a number is provided, it is used as the elevation for all objects.
    • If a function is provided, it is called on each object to retrieve its elevation.
    getLineWidth (Function|Number, optional) transition-enabled
    • Default: 1

    The width of the outline of the column, in units specified by lineWidthUnits (default meters). Only applies if extruded: false and stroked: true.

    • If a number is provided, it is used as the outline width for all columns.
    • If a function is provided, it is called on each object to retrieve its outline width.

    Source

    modules/layers/src/column-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/geojson-layer.html b/docs/api-reference/layers/geojson-layer.html index ca6d5f85c38..28e2971ecee 100644 --- a/docs/api-reference/layers/geojson-layer.html +++ b/docs/api-reference/layers/geojson-layer.html @@ -4,8 +4,8 @@ GeoJsonLayer | deck.gl - - + +
    @@ -30,7 +30,7 @@ positions: {value: Float32Array([x0, y0, x1, y1, x2, y2]), size: 2}, featureIds: {value: Uint16Array([0, 1, 1, ...]), size: 1} }

    Array lengths

    Due to MultiPoints, the length of properties and fields arrays will not always be the same length (multiplied by positions.size) as the positions array. The length will match the count of individual features. This is in contrast to the featureId and numericProp arrays, which will contain the same number of elements as the positions array (divided by positions.size).

    Example comparison

    geojson = {
    type: 'FeatureCollection',
    features: [{
    id: 123,
    type: 'Feature',
    properties: {name: 'London', population: 10000000},
    geometry: {coordinates: [1.23, 4.56], type: 'Point'}
    },
    ...
    ]
    }

    binary = {
    points: {
    positions: {value: Float32Array([1,23, 4.56, ...]), size: 2},
    properties: [{name: 'London'}, ...],
    numericProps: {
    population: {value: Float32Array([10000000, ...], size: 1}
    }
    featureIds: {value: Uint16Array([0, ...]), size: 1}
    fields: [{id: 123}]
    }
    }

    Lines

    Lines are represented in a similar manner, with the addition of a pathIndices array, which contains a series of offsets into the positions array, specifying where each line begins. All the other parameters are as above, namely that featureIds and numericProps are stored per-vertex, while properties and fields are per-feature.

    Here is how lines are represented, the first four vertices belong to the first line, thus the value of the second path index is 4.

    lines: {
    positions: {value: Float32Array([x0, y0, ..., x4, y4, ...]), size: 2},
    properties: [{name: 'name0'}, {name: 'name1}, ...],
    numericProps: {
    population: {value: Float32Array([100, 100, 100, 100, 789, 789, ...], size: 1}
    }
    pathIndices: {value: Uint16Array([0, 4, ...]), size: 1}
    featureIds: {value: Uint16Array([0, 0, 0, 0, 1, 1, ...]), size: 1}
    fields: [{id: 123}, {id: 456}]
    }

    Polygons

    Polygons are an extension of the idea introduced with lines, but instead of pathIndices the polygonIndicies array specifies where each polygon starts inside the positions array. Because polygons can have holes, the offsets for the outer and inner rings are stored separately in the primitivePolygonIndices array. A polygon that has an outer ring consisting of 60 vertices and a hole with 40 vertices is represented as:

    polygons: {
    positions: {value: Float32Array([x0, y0, ...]), size: 2},
    polygonIndices: {value: Uint16Array([0, 100, ...]), size: 1}
    primitivePolygonIndices: {value: Uint16Array([0, 60, 100, ...]), size: 1}
    }

    Note the subtle difference here to other columnar formats (like GeoArrow) where the indices are nested, i.e. polygonIndices point into the primitivePolygonIndices array rather than directly into positions.

    Global feature ids

    Because the features array in the GeoJSON can contain a mix of different geometry types, in order to represent this ordering each of the points, lines and polygons objects contains a globalFeatureIds array, which contains the per-vertex indices into the original GeoJSON `features' array.

    Overriding attibutes

    In order to pass pass attributes directly directly to the sublayers, an optional attributes member can be added to the points, lines or polygons. For example to pass the getWidth attribute to the PathLayer:

    lines: {
    ...,
    attributes: {
    getWidth: {value: new Float32Array([1, 2, 3, ....]), size: 1}
    }
    }

    Remarks

    • Geometry transition can be enabled with props.transitions: {geometry: <transition_settings>}.
    • Input data must adhere to the GeoJSON specification. Most GIS software support exporting to GeoJSON format. You may validate your data with free tools such as this.
    • The GeoJsonLayer renders 3D geometries if each feature's coordinates contain 3D points.

    Source

    modules/layers/src/geojson-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/grid-cell-layer.html b/docs/api-reference/layers/grid-cell-layer.html index 90b8cc3f48d..242ce5e8d8c 100644 --- a/docs/api-reference/layers/grid-cell-layer.html +++ b/docs/api-reference/layers/grid-cell-layer.html @@ -4,8 +4,8 @@ GridCellLayer | deck.gl - - + +
    @@ -17,7 +17,7 @@ elevationScale * getElevation(d). elevationScale is a handy property to scale all cell elevations without updating the data.

    extruded (Boolean, optional)
    • Default: true

    Whether to enable grid elevation. If set to false, all grid will be flat.

    material (Object, optional)
    • Default: true

    This is an object that contains material props for lighting effect applied on extruded polygons. Check the lighting guide for configurable settings.

    Data Accessors

    getPosition (Function, optional) transition-enabled
    • Default: x => x.position

    Method called to retrieve the bottom-left corner ([minX, minY]) of each cell.

    getColor (Function|Array, optional) transition-enabled
    • Default: [255, 0, 255, 255]

    The rgba color of each object, in r, g, b, [a]. Each component is in the 0-255 range.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    getElevation (Function|Number, optional) transition-enabled
    • Default: 1000

    The elevation of each cell in meters.

    • If a number is provided, it is used as the elevation for all objects.
    • If a function is provided, it is called on each object to retrieve its elevation.

    Source

    modules/layers/src/column-layer/grid-cell-layer.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/icon-layer.html b/docs/api-reference/layers/icon-layer.html index 6f2fe33b619..fe620330dd6 100644 --- a/docs/api-reference/layers/icon-layer.html +++ b/docs/api-reference/layers/icon-layer.html @@ -4,8 +4,8 @@ IconLayer | deck.gl - - + +
    @@ -22,7 +22,7 @@ Default: false

    If you go with pre-packed strategy, this prop is required.

    If you choose to use auto packing, this prop should be left empty.

    sizeScale (Number, optional) transition-enabled
    • Default: 1

    Icon size multiplier.

    sizeUnits (String, optional)
    • Default: pixels

    The units of the size, one of 'meters', 'common', and 'pixels'. See unit system.

    sizeMinPixels (Number, optional) transition-enabled
    • Default: 0

    The minimum size in pixels. When using non-pixel sizeUnits, this prop can be used to prevent the icon from getting too small when zoomed out.

    sizeMaxPixels (Number, optional) transition-enabled
    • Default: Number.MAX_SAFE_INTEGER

    The maximum size in pixels. When using non-pixel sizeUnits, this prop can be used to prevent the icon from getting too big when zoomed in.

    billboard (Boolean, optional)
    • Default: true

    If true, the icon always faces camera. Otherwise the icon faces up (z).

    alphaCutoff (Number, optional)
    • Default: 0.05

    Discard pixels whose opacity is below this threshold. A discarded pixel would create a "hole" in the icon that is not considered part of the object. This is useful for customizing picking behavior, e.g. setting alphaCutoff: 0, autoHighlight will highlight an object whenever the cursor moves into its bounding box, instead of over the visible pixels.

    loadOptions (Object, optional)

    On top of the default options, also accepts options for the following loaders:

    • ImageLoader if the iconAtlas prop is an URL, or if getIcon returns URLs for auto-packing
    textureParameters (Object)

    Customize the texture parameters.

    If not specified, the layer uses the following defaults to create a linearly smoothed texture from iconAtlas:

    {
    minFilter: 'linear',
    magFilter: 'linear',
    mipmapFilter: 'linear',
    addressModeU: 'clamp-to-edge',
    addressModeV: 'clamp-to-edge'
    }

    Data Accessors

    getIcon (Function, optional)
    • Default: d => d.icon

    Method called to retrieve the icon name of each object, returns string or object.

    If you go with pre-packed strategy, then getIcon should return a string representing name of the icon, used to retrieve icon definition from given iconMapping.

    If you choose to use auto packing, then getIcon should return an object which contains the following properties.

    • url (String, required): url to fetch the icon
    • height (Number, required): max height of icon
    • width (Number, required): max width of icon
    • id: (String, optional): unique identifier of the icon, fall back to url if not specified
    • anchorX, anchorY, mask are the same as mentioned in iconMapping

    IconLayer uses id (fallback to url) to dedupe icons. For icons with the same id, even if their sizes differ, IconLayer will only define one icon according to the first occurrence and ignore the rest of them. Vice versa, for icons with different ids, even if urls are the same, the image will be fetched again to create a new definition with different size, anchor, etc.

    The image loaded from url is always resized to fit the box defined by [width, height] while preserving its aspect ratio.

    getPosition (Function, optional) transition-enabled
    • Default: d => d.position

    Method called to retrieve the position of each object, returns [lng, lat, z].

    getSize (Function|Number, optional) transition-enabled
    • Default: 1

    The height of each object, in units specified by sizeUnits (default pixels).

    • If a number is provided, it is used as the size for all objects.
    • If a function is provided, it is called on each object to retrieve its size.
    getColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    • If mask = false, only the alpha component will be used to control the opacity of the icon.
    getAngle (Function|Number, optional) transition-enabled
    • Default: 0

    The rotating angle of each object, in degrees.

    • If a number is provided, it is used as the angle for all objects.
    • If a function is provided, it is called on each object to retrieve its angle.
    getPixelOffset (Function|Array, optional) transition-enabled
    • Default: [0, 0]

    Screen space offset relative to the coordinates in pixel unit.

    • If an array is provided, it is used as the offset for all objects.
    • If a function is provided, it is called on each object to retrieve its offset.

    Callbacks

    onIconError (Function)
    • Default: null

    Only used when using auto-packing. If the attempt to fetch an icon returned by getIcon fails, this callback is called with the following arguments:

    • event (Object)
      • url (String) - the URL that was trying to fetch
      • loadOptions (Object) - the load options used for the fetch
      • source (Object) - the original data object that requested this icon
      • sourceIndex (Object) - the index of the original data object that requested this icon
      • error (Error)

    Use binary attributes

    This section is about the special requirements when supplying attributes directly to an IconLayer.

    If data.attributes.getIcon is supplied, since its value can only be a typed array, iconMapping can only use integers as keys.

    Source

    modules/layers/src/icon-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/line-layer.html b/docs/api-reference/layers/line-layer.html index 711615d00cb..2422bd1be42 100644 --- a/docs/api-reference/layers/line-layer.html +++ b/docs/api-reference/layers/line-layer.html @@ -4,13 +4,13 @@ LineLayer | deck.gl - - + +

    LineLayer

    The LineLayer renders straight lines joining pairs of source and target coordinates.

    import DeckGL from '@deck.gl/react';
    import {LineLayer} from '@deck.gl/layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * inbound: 72633,
    * outbound: 74735,
    * from: {
    * name: '19th St. Oakland (19TH)',
    * coordinates: [-122.269029, 37.80787]
    * },
    * to: {
    * name: '12th St. Oakland City Center (12TH)',
    * coordinates: [-122.271604, 37.803664]
    * },
    * ...
    * ]
    */
    const layer = new LineLayer({
    id: 'line-layer',
    data,
    pickable: true,
    getWidth: 50,
    getSourcePosition: d => d.from.coordinates,
    getTargetPosition: d => d.to.coordinates,
    getColor: d => [Math.sqrt(d.inbound + d.outbound), 140, 0]
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.from.name} to ${object.to.name}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers
    import {LineLayer} from '@deck.gl/layers';
    new LineLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    new deck.LineLayer({});

    Properties

    Inherits from all Base Layer properties.

    Render Options

    The width used to draw each line. Unit is pixels.

    widthUnits (String, optional)
    • Default: 'pixels'

    The units of the line width, one of 'meters', 'common', and 'pixels'. See unit system.

    widthScale (Number, optional) transition-enabled
    • Default: 1

    The scaling multiplier for the width of each line. This prop is a very efficient way to change the width of all objects, comparing to recalculating the width for each object with getWidth.

    widthMinPixels (Number, optional) transition-enabled
    • Default: 0

    The minimum line width in pixels. This prop can be used to prevent the line from getting to thin when zoomed out.

    widthMaxPixels (Number, optional) transition-enabled
    • Default: Number.MAX_SAFE_INTEGER

    The maximum line width in pixels. This prop can be used to prevent the line from getting to thick when zoomed in.

    Data Accessors

    getSourcePosition (Function, optional) transition-enabled
    • Default: object => object.sourcePosition

    Method called to retrieve the source position of each object.

    getTargetPosition (Function, optional) transition-enabled
    • Default: object => object.targetPosition

    Method called to retrieve the target position of each object.

    getColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    getWidth (Function|Number, optional) transition-enabled
    • Default: 1

    The line width of each object, in units specified by widthUnits (default pixels).

    • If a number is provided, it is used as the line width for all objects.
    • If a function is provided, it is called on each object to retrieve its line width.

    Source

    modules/layers/src/line-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/path-layer.html b/docs/api-reference/layers/path-layer.html index 4ea4f133a78..00e62142a05 100644 --- a/docs/api-reference/layers/path-layer.html +++ b/docs/api-reference/layers/path-layer.html @@ -4,15 +4,15 @@ PathLayer | deck.gl - - + +

    PathLayer

    The PathLayer renders lists of coordinate points as extruded polylines with mitering.

    import DeckGL from '@deck.gl/react';
    import {PathLayer} from '@deck.gl/layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * path: [[-122.4, 37.7], [-122.5, 37.8], [-122.6, 37.85]],
    * name: 'Richmond - Millbrae',
    * color: [255, 0, 0]
    * },
    * ...
    * ]
    */
    const layer = new PathLayer({
    id: 'path-layer',
    data,
    pickable: true,
    widthScale: 20,
    widthMinPixels: 2,
    getPath: d => d.path,
    getColor: d => colorToRGBArray(d.color),
    getWidth: d => 5
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && object.name} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers
    import {PathLayer} from '@deck.gl/layers';
    new PathLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    new deck.PathLayer({});

    Properties

    Inherits from all Base Layer properties.

    Render Options

    widthUnits (String, optional)
    • Default: 'meters'

    The units of the line width, one of 'meters', 'common', and 'pixels'. See unit system.

    widthScale (Number, optional) transition-enabled
    • Default: 1

    The path width multiplier that multiplied to all paths.

    widthMinPixels (Number, optional) transition-enabled
    • Default: 0

    The minimum path width in pixels. This prop can be used to prevent the path from getting too thin when zoomed out.

    widthMaxPixels (Number, optional) transition-enabled
    • Default: Number.MAX_SAFE_INTEGER

    The maximum path width in pixels. This prop can be used to prevent the path from getting too thick when zoomed in.

    capRounded (Boolean, optional)
    • Default: false

    Type of caps. If true, draw round caps. Otherwise draw square caps.

    jointRounded (Boolean, optional)
    • Default: false

    Type of joint. If true, draw round joints. Otherwise draw miter joints.

    billboard (Boolean, optional)
    • Default: false

    If true, extrude the path in screen space (width always faces the camera). If false, the width always faces up.

    miterLimit (Number, optional) transition-enabled
    • Default: 4

    The maximum extent of a joint in ratio to the stroke width. Only works if jointRounded is false.

    _pathType (Object, optional)
    • Default: null

    Note: This prop is experimental

    One of null, 'loop' or 'open'.

    If 'loop' or 'open', will skip normalizing the coordinates returned by getPath and instead assume all paths are to be loops or open paths. Disabling normalization improves performance during data update, but makes the layer prone to error in case the data is malformed. It is only recommended when you use this layer with preprocessed static data or validation on the backend.

    When normalization is disabled, paths must be specified in the format of flat array. Open paths must contain at least 2 vertices and closed paths must contain at least 3 vertices. See getPath below for details.

    Data Accessors

    getPath (Function, optional) transition-enabled
    • Default: object => object.path

    Called on each object in the data stream to retrieve its corresponding path.

    A path can be one of the following formats:

    • An array of points ([x, y, z]). Compatible with the GeoJSON LineString specification.
    • A flat array or TypedArray of numbers, in the shape of [x0, y0, z0, x1, y1, z1, ...]. By default, each coordinate is assumed to contain 3 consecutive numbers. If each coordinate contains only two numbers (x, y), set the positionFormat prop of the layer to XY:
    new PathLayer({
    ...
    getPath: object => object.vertices, // [x0, y0, x1, y1, x2, y2, ...]
    positionFormat: `XY`
    })
    getColor (Function|Array, optional) transition-enabled
    • Default [0, 0, 0, 255]

    The rgba color of each object, in r, g, b, [a]. Each component is in the 0-255 range.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    getWidth (Function|Number, optional) transition-enabled
    • Default: 1

    The width of each path, in units specified by widthUnits (default meters).

    • If a number is provided, it is used as the width for all paths.
    • If a function is provided, it is called on each path to retrieve its width.

    Use binary attributes

    This section is about the special requirements when supplying attributes directly to a PathLayer.

    Because each path has a different number of vertices, when data.attributes.getPath is supplied, the layer also requires an array data.startIndices that describes the vertex index at the start of each path. For example, if there are 3 paths of 2, 3, and 4 vertices each, startIndices should be [0, 2, 5, 9].

    Additionally, all other attributes (getColor, getWidth, etc.), if supplied, must contain the same layout (number of vertices) as the getPath buffer.

    To truly realize the performance gain from using binary data, the app likely wants to skip all data processing in this layer. Specify the _pathType prop to skip normalization.

    Example use case:

    // USE PLAIN JSON OBJECTS
    const PATH_DATA = [
    {
    path: [[-122.4, 37.7], [-122.5, 37.8], [-122.6, 37.85]],
    name: 'Richmond - Millbrae',
    color: [255, 0, 0]
    },
    ...
    ];

    new PathLayer({
    data: PATH_DATA,
    getPath: d => d.path,
    getColor: d => d.color
    })

    Convert to using binary attributes:

    // USE BINARY
    // Flatten the path vertices
    // [-122.4, 37.7, -122.5, 37.8, -122.6, 37.85, ...]
    const positions = new Float64Array(PATH_DATA.map(d => d.path).flat(2));
    // The color attribute must supply one color for each vertex
    // [255, 0, 0, 255, 0, 0, 255, 0, 0, ...]
    const colors = new Uint8Array(PATH_DATA.map(d => d.path.map(_ => d.color)).flat(2));
    // The "layout" that tells PathLayer where each path starts
    const startIndices = new Uint16Array(PATH_DATA.reduce((acc, d) => {
    const lastIndex = acc[acc.length - 1];
    acc.push(lastIndex + d.path.length);
    return acc;
    }, [0]));

    new PathLayer({
    data: {
    length: PATH_DATA.length,
    startIndices: startIndices, // this is required to render the paths correctly!
    attributes: {
    getPath: {value: positions, size: 2},
    getColor: {value: colors, size: 3}
    }
    },
    _pathType: 'open' // this instructs the layer to skip normalization and use the binary as-is
    })

    Source

    modules/layers/src/path-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/point-cloud-layer.html b/docs/api-reference/layers/point-cloud-layer.html index 3da67436f30..33561985fdf 100644 --- a/docs/api-reference/layers/point-cloud-layer.html +++ b/docs/api-reference/layers/point-cloud-layer.html @@ -4,14 +4,14 @@ PointCloudLayer | deck.gl - - + +

    PointCloudLayer

    The PointCloudLayer renders a point cloud with 3D positions, normals and colors.

    import DeckGL from '@deck.gl/react';
    import {PointCloudLayer} from '@deck.gl/layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {position: [-122.4, 37.7, 12], normal: [-1, 0, 0], color: [255, 255, 0]},
    * ...
    * ]
    */
    const layer = new PointCloudLayer({
    id: 'point-cloud-layer',
    data,
    pickable: false,
    coordinateSystem: COORDINATE_SYSTEM.METER_OFFSETS,
    coordinateOrigin: [-122.4, 37.74],
    radiusPixels: 4,
    getPosition: d => d.position,
    getNormal: d => d.normal,
    getColor: d => d.color
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && object.position.join(', ')} />;
    }

    loaders.gl offers a category of loaders for loading point clouds from standard formats. For example, the following code adds support for LAS/LAZ files:

    import {PointCloudLayer} from '@deck.gl/layers';
    import {LASLoader} from '@loaders.gl/las';

    new PointCloudLayer({
    ...
    mesh: 'path/to/pointcloud.laz',
    loaders: [LASLoader]
    });

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers
    import {PointCloudLayer} from '@deck.gl/layers';
    new PointCloudLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    new deck.PointCloudLayer({});

    Properties

    Inherits from all Base Layer properties.

    Render Options

    sizeUnits (String, optional)
    • Default: 'pixels'

    The units of the point size, one of 'meters', 'common', and 'pixels'. See unit system.

    pointSize (Number, optional) transition-enabled
    • Default: 10

    Global radius of all points, in units specified by sizeUnits (default pixels).

    material (Object, optional)
    • Default: true

    This is an object that contains material props for lighting effect applied on extruded polygons. Check the lighting guide for configurable settings.

    Data Accessors

    getPosition (Function, optional) transition-enabled
    • Default: object => object.position

    Method called to retrieve the position of each object.

    getNormal (Function|Array, optional) transition-enabled
    • Default: [0, 0, 1]

    The normal of each object, in [nx, ny, nz].

    • If an array is provided, it is used as the normal for all objects.
    • If a function is provided, it is called on each object to retrieve its normal.
    getColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.

    Source

    modules/layers/src/point-cloud-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/polygon-layer.html b/docs/api-reference/layers/polygon-layer.html index ca350c272ef..22d0028e29a 100644 --- a/docs/api-reference/layers/polygon-layer.html +++ b/docs/api-reference/layers/polygon-layer.html @@ -4,8 +4,8 @@ PolygonLayer | deck.gl - - + +
    @@ -27,7 +27,7 @@ the first and last vertices, when those vertices are not equal.
  • The specification of complex polygons intentionally follows the GeoJson conventions for representing polygons with holes.
  • Wireframe lines are rendered with GL.LINE and thus will always be 1 pixel wide.
  • Wireframe and solid extrusions are exclusive, you'll need to create two layers with the same data if you want a combined rendering effect.
  • Source

    modules/layers/src/polygon-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/scatterplot-layer.html b/docs/api-reference/layers/scatterplot-layer.html index ebfea7467e3..a5394ade93a 100644 --- a/docs/api-reference/layers/scatterplot-layer.html +++ b/docs/api-reference/layers/scatterplot-layer.html @@ -4,13 +4,13 @@ ScatterplotLayer | deck.gl - - + +

    ScatterplotLayer

    The ScatterplotLayer renders circles at given coordinates.

    import DeckGL from '@deck.gl/react';
    import {ScatterplotLayer} from '@deck.gl/layers';

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {name: 'Colma (COLM)', code:'CM', address: '365 D Street, Colma CA 94014', exits: 4214, coordinates: [-122.466233, 37.684638]},
    * ...
    * ]
    */
    const layer = new ScatterplotLayer({
    id: 'scatterplot-layer',
    data,
    pickable: true,
    opacity: 0.8,
    stroked: true,
    filled: true,
    radiusScale: 6,
    radiusMinPixels: 1,
    radiusMaxPixels: 100,
    lineWidthMinPixels: 1,
    getPosition: d => d.coordinates,
    getRadius: d => Math.sqrt(d.exits),
    getFillColor: d => [255, 140, 0],
    getLineColor: d => [0, 0, 0]
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.name}\n${object.address}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers
    import {ScatterplotLayer} from '@deck.gl/layers';
    new ScatterplotLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    new deck.ScatterplotLayer({});

    Properties

    Inherits from all Base Layer properties.

    Render Options

    radiusUnits (String, optional) transition-enabled
    • Default: 'meters'

    The units of the radius, one of 'meters', 'common', and 'pixels'. See unit system.

    radiusScale (Number, optional) transition-enabled
    • Default: 1

    A global radius multiplier for all points.

    lineWidthUnits (String, optional) transition-enabled
    • Default: 'meters'

    The units of the line width, one of 'meters', 'common', and 'pixels'. See unit system.

    lineWidthScale (Number, optional) transition-enabled
    • Default: 1

    A global line width multiplier for all points.

    stroked (Boolean, optional)
    • Default: false

    Draw the outline of points.

    filled (Boolean, optional)
    • Default: true

    Draw the filled area of points.

    radiusMinPixels (Number, optional) transition-enabled
    • Default: 0

    The minimum radius in pixels. This prop can be used to prevent the circle from getting too small when zoomed out.

    radiusMaxPixels (Number, optional) transition-enabled
    • Default: Number.MAX_SAFE_INTEGER

    The maximum radius in pixels. This prop can be used to prevent the circle from getting too big when zoomed in.

    lineWidthMinPixels (Number, optional) transition-enabled
    • Default: 0

    The minimum line width in pixels. This prop can be used to prevent the stroke from getting too thin when zoomed out.

    lineWidthMaxPixels (Number, optional) transition-enabled
    • Default: Number.MAX_SAFE_INTEGER

    The maximum line width in pixels. This prop can be used to prevent the path from getting too thick when zoomed in.

    billboard (Boolean, optional)
    • Default: false

    If true, rendered circles always face the camera. If false circles face up (i.e. are parallel with the ground plane).

    antialiasing (Boolean, optional)
    • Default: true

    If true, circles are rendered with smoothed edges. If false, circles are rendered with rough edges. Antialiasing can cause artifacts on edges of overlapping circles. Also, antialiasing isn't supported in FirstPersonView.

    Data Accessors

    getPosition (Function, optional) transition-enabled
    • Default: object => object.position

    Method called to retrieve the position of each object.

    getRadius (Function|Number, optional) transition-enabled
    • Default: 1

    The radius of each object, in units specified by radiusUnits (default meters).

    • If a number is provided, it is used as the radius for all objects.
    • If a function is provided, it is called on each object to retrieve its radius.
    getColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.

    It will be overridden by getLineColor and getFillColor if these new accessors are specified.

    getFillColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the filled color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    • If not provided, it falls back to getColor.
    getLineColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the outline color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    • If not provided, it falls back to getColor.
    getLineWidth (Function|Number, optional) transition-enabled
    • Default: 1

    The width of the outline of each object, in units specified by lineWidthUnits (default meters).

    • If a number is provided, it is used as the outline width for all objects.
    • If a function is provided, it is called on each object to retrieve its outline width.
    • If not provided, it falls back to strokeWidth.

    Source

    modules/layers/src/scatterplot-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/solid-polygon-layer.html b/docs/api-reference/layers/solid-polygon-layer.html index 043c36b12f3..f53ce1d63d5 100644 --- a/docs/api-reference/layers/solid-polygon-layer.html +++ b/docs/api-reference/layers/solid-polygon-layer.html @@ -4,8 +4,8 @@ SolidPolygonLayer | deck.gl - - + +
    @@ -26,7 +26,7 @@ outlines, use the PathLayer
  • Polygons are always closed, i.e. there is an implicit line segment between the first and last vertices, when those vertices are not equal.
  • The specification of complex polygons intentionally follows the GeoJson conventions for representing polygons with holes.
  • Source

    modules/layers/src/solid-polygon-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/layers/text-layer.html b/docs/api-reference/layers/text-layer.html index 2d754c480d2..cd511f66e2f 100644 --- a/docs/api-reference/layers/text-layer.html +++ b/docs/api-reference/layers/text-layer.html @@ -4,14 +4,14 @@ TextLayer | deck.gl - - + +

    TextLayer

    The TextLayer renders text labels at given coordinates.

    TextLayer is a CompositeLayer that wraps around the IconLayer. It automatically creates an atlas texture from the specified font settings and characterSet.

    import DeckGL from '@deck.gl/react';
    import {TextLayer} from '@deck.gl/layers';

    function App({data, viewState}) { /**
    * Data format:
    * [
    * {name: 'Colma (COLM)', address: '365 D Street, Colma CA 94014', coordinates: [-122.466233, 37.684638]},
    * ...
    * ]
    */

    const layer = new TextLayer({
    id: 'text-layer',
    data,
    pickable: true,
    getPosition: d => d.coordinates,
    getText: d => d.name,
    getSize: 32,
    getAngle: 0,
    getTextAnchor: 'middle',
    getAlignmentBaseline: 'center'
    });

    return <DeckGL viewState={viewState}
    layers={[layer]}
    getTooltip={({object}) => object && `${object.name}\n${object.address}`} />;
    }

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/layers
    import {TextLayer} from '@deck.gl/layers';
    new TextLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/layers@^8.0.0/dist.min.js"></script>
    new deck.TextLayer({});

    Properties

    Inherits from all Base Layer and CompositeLayer properties.

    Rendering Options

    sizeScale (Number, optional) transition-enabled
    • Default: 1

    Text size multiplier.

    sizeUnits (String, optional)
    • Default: pixels

    The units of the size, one of 'meters', 'common', and 'pixels'. See unit system.

    sizeMinPixels (Number, optional) transition-enabled
    • Default: 0

    The minimum size in pixels. When using non-pixel sizeUnits, this prop can be used to prevent the icon from getting too small when zoomed out.

    sizeMaxPixels (Number, optional) transition-enabled
    • Default: Number.MAX_SAFE_INTEGER

    The maximum size in pixels. When using non-pixel sizeUnits, this prop can be used to prevent the icon from getting too big when zoomed in.

    billboard (Boolean, optional)
    • Default: true

    If true, the text always faces camera. Otherwise the text faces up (z).

    background (Boolean, optional)
    • Default false

    Whether to render background for the text blocks.

    backgroundPadding (Array, optional)
    • Default [0, 0, 0, 0]

    The padding of the background, an array of either 2 or 4 numbers.

    • If an array of 2 is supplied, it is interpreted as [padding_x, padding_y] in pixels.
    • If an array of 4 is supplied, it is interpreted as [padding_left, padding_top, padding_right, padding_bottom] in pixels.
    fontFamily (String, optional)
    • Default: 'Monaco, monospace'

    Specifies a prioritized list of one or more font family names and/or generic family names. Follow the specs for CSS font-family.

    See the remarks section below for tips on using web fonts.

    characterSet (Array | Set | String, optional)
    • Default: ASCII characters 32-128

    Specifies a list of characters to include in the font.

    • If set to 'auto', automatically detects the characters used in the data. This option has a performance overhead and may cause the layer to take longer to load if the data is very large.
    • If set to an array or set of characters, the generated font will be limited to these characters. If you already know all the characters that are needed (e.g. numbers, latin alphabet), using this option provides better performance. If a character outside of the specified range is referenced by getText, a warning will be logged to the JavaScript console.

    Note that there is a limit to the number of unique characters supported by a single layer. The maximum number subjects to fontSettings.fontSize and the MAX_TEXTURE_SIZE of the device/browser.

    fontWeight (Number | String, optional)
    • Default: normal.

    css font-weight.

    lineHeight (Number, optional)
    • Default: 1.0.

    A unitless number that will be multiplied with the current font size to set the line height.

    fontSettings (Object, optional)

    Advance options for fine tuning the appearance and performance of the generated shared fontAtlas.

    Options:

    • fontSize (Number): Font size in pixels. Default is 64. This option is only applied for generating fontAtlas, it does not impact the size of displayed text labels. Larger fontSize will give you a sharper look when rendering text labels with very large font sizes. But larger fontSize requires more time and space to generate the fontAtlas.
    • buffer (Number): Whitespace buffer around each side of the character. Default is 4. In general, bigger fontSize requires bigger buffer. Increase buffer will add more space between each character when layout characterSet in fontAtlas. This option could be tuned to provide sufficient space for drawing each character and avoiding overlapping of neighboring characters.
    • sdf (Boolean): Flag to enable / disable sdf. Default is false. sdf (Signed Distance Fields) will provide a sharper look when rendering with very large or small font sizes. TextLayer integrates with TinySDF which implements the sdf algorithm.
    • radius (Number): How many pixels around the glyph shape to use for encoding distance. Default is 12. Bigger radius yields higher quality outcome. Only applies when sdf: true.
    • cutoff (Number): How much of the radius (relative) is used for the inside part the glyph. Default is 0.25. Bigger cutoff makes character thinner. Smaller cutoff makes character look thicker. Only applies when sdf: true.
    • smoothing (Number): How much smoothing to apply to the text edges. Default 0.1. Only applies when sdf: true.
    wordBreak (String, optional)
    • Default: break-word

    Available options are break-all and break-word. A valid maxWidth has to be provided to use wordBreak.

    maxWidth (Number, optional)
    • Default: -1

    A unitless number that will be multiplied with the current text size to set the width limit of a string. If specified, when the text is longer than the width limit, it will be wrapped into multiple lines using the strategy of wordBreak.

    For example, maxWidth: 10.0 used with getSize: 12 is roughly the equivalent of max-width: 120px in CSS.

    outlineWidth (Number, optional)
    • Default: 0

    Width of outline around the text, relative to the font size. Only effective if fontSettings.sdf is true.

    outlineColor (Array, optional)
    • Default: [0, 0, 0, 255]

    Color of outline around the text, in [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    Data Accessors

    getText (Function, optional)
    • Default: x => x.text

    Method called to retrieve the content of each text label.

    getPosition (Function, optional) transition-enabled
    • Default: x => x.position

    Method called to retrieve the location of each text label.

    getSize (Function|Number, optional) transition-enabled
    • Default: 32

    The font size of each text label, in units specified by sizeUnits (default pixels).

    • If a number is provided, it is used as the size for all objects.
    • If a function is provided, it is called on each object to retrieve its size.
    getColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    getAngle (Function|Number, optional) transition-enabled
    • Default: 0

    The rotating angle of each text label, in degrees.

    • If a number is provided, it is used as the angle for all objects.
    • If a function is provided, it is called on each object to retrieve its angle.
    getTextAnchor (Function|String, optional)
    • Default: 'middle'

    The text anchor. Available options include 'start', 'middle' and 'end'.

    • If a string is provided, it is used as the text anchor for all objects.
    • If a function is provided, it is called on each object to retrieve its text anchor.
    getAlignmentBaseline (Function|String, optional)
    • Default: 'center'

    The alignment baseline. Available options include 'top', 'center' and 'bottom'.

    • If a string is provided, it is used as the alignment baseline for all objects.
    • If a function is provided, it is called on each object to retrieve its alignment baseline.
    getPixelOffset (Function|Array, optional) transition-enabled
    • Default: [0, 0]

    Screen space offset relative to the coordinates in pixel unit.

    • If an array is provided, it is used as the offset for all objects.
    • If a function is provided, it is called on each object to retrieve its offset.
    getBackgroundColor (Function|Array, optional) transition-enabled
    • Default: [255, 255, 255, 255]

    The background color. Only effective if background: true.

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the background color for all objects.
    • If a function is provided, it is called on each object to retrieve its background color.
    getBorderColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The border color of the background. Only effective if background: true.

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the border color for all objects.
    • If a function is provided, it is called on each object to retrieve its border color.
    getBorderWidth (Function|Number, optional) transition-enabled
    • Default: 0

    The border thickness of each text label, in pixels. Only effective if background: true.

    • If a number is provided, it is used as the border thickness for all objects.
    • If a function is provided, it is called on each object to retrieve its border thickness.

    Sub Layers

    The TextLayer renders the following sublayers:

    • characters - an IconLayer rendering all the characters.
    • background - the background for each text block, if background: true.

    Use binary attributes

    This section is about the special requirements when supplying attributes directly to a TextLayer.

    Because each text string has a different number of characters, when data.attributes.getText is supplied, the layer also requires an array data.startIndices that describes the character index at the start of each text object. For example, if there are 3 text objects of 2, 3, and 4 characters each, startIndices should be [0, 2, 5, 9].

    Additionally, all other attributes (getColor, getWidth, etc.), if supplied, must contain the same layout (number of characters) as the getText buffer.

    Example use case:

    // USE PLAIN JSON OBJECTS
    const TEXT_DATA = [
    {
    text: 'Hello',
    position: [-122.4, 37.7],
    color: [255, 0, 0]
    },
    {
    text: 'World',
    position: [-122.5, 37.8],
    color: [0, 0, 255]
    }
    ...
    ];

    new TextLayer({
    data: TEXT_DATA,
    getText: d => d.text,
    getPosition: d => d.position,
    getColor: d => d.color
    })

    Convert to using binary attributes:

    // USE BINARY
    // Flatten the text by converting to unicode value
    // Non-Latin characters may require Uint16Array
    // [72, 101, 108, 108, 111, ...]
    const texts = new Uint8Array(TEXT_DATA.map(d => Array.from(d.text).map(char => char.charCodeAt(0))).flat());
    // The position attribute must supply one position for each character
    // [-122.4, 37.7, -122.4, 37.7, -122.4, 37.7, ...]
    const positions = new Float64Array(TEXT_DATA.map(d => Array.from(d.text).map(_ => d.position)).flat(2));
    // The color attribute must supply one color for each character
    // [255, 0, 0, 255, 0, 0, 255, 0, 0, ...]
    const colors = new Uint8Array(TEXT_DATA.map(d => Array.from(d.text).map(_ => d.color)).flat(2));

    // The "layout" that tells TextLayer where each string starts
    const startIndices = new Uint16Array(TEXT_DATA.reduce((acc, d) => {
    const lastIndex = acc[acc.length - 1];
    acc.push(lastIndex + d.text.length);
    return acc;
    }, [0]));

    new TextLayer({
    data: {
    length: TEXT_DATA.length,
    startIndices: startIndices, // this is required to render the texts correctly!
    attributes: {
    getText: {value: texts},
    getPosition: {value: positions, size: 2},
    getColor: {value: colors, size: 3}
    }
    }
    })

    Use binary attributes with background

    To use background: true with binary data, the background attributes must be supplied separately via data.attributes.background. Each attribute is packed with one vertex per object.

    data.attributes.background may contain the following keys:

    • getPosition: corresponds to the getPosition accessor
    • getAngle: corresponds to the getAngle accessor
    • getSize: corresponds to the getSize accessor
    • getPixelOffset: corresponds to the getPixelOffset accessor
    • getFillColor: corresponds to the getBackgroundColor accessor
    • getLineColor: corresponds to the getBorderColor accessor
    • getLineWidth: corresponds to the getBorderWidth accessor

    Following the above example, additional attributes are required to render the background:

    // The background position attribute supplies one position for each text block
    const backgroundPositions = new Float64Array(TEXT_DATA.map(d => d.position).flat());
    // The background color attribute supplies one color for each text block
    const backgroundColors = new Uint8Array(TEXT_DATA.map(d => d.bgColor).flat());

    new TextLayer({
    data: {
    length: TEXT_DATA.length,
    startIndices: startIndices, // this is required to render the texts correctly!
    attributes: {
    getText: {value: texts},
    getPosition: {value: positions, size: 2},
    getColor: {value: colors, size: 3},
    background: {
    getPosition: {value: backgroundPosition, size: 2},
    getFillColor: {value: backgroundColors, size: 3}
    }
    }
    },
    background: true
    })

    Remarks

    Use web fonts

    The TextLayer creates a font texture when it is first added with the fillText API. If the font specified by fontFamily is not loaded at this point, it will fall back to using the default font just like regular CSS behavior. The loading sequence may become an issue when a web font is used, due to lazy loading.

    One way to force a web font to load before the script execution is to preload the font resource:

    <link rel="preload" href="https://fonts.gstatic.com/s/materialicons/v90/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2" as="font" crossorigin="anonymous" type="font/woff2" />
    @font-face {
    font-family: 'Material Icons';
    font-style: normal;
    font-weight: 400;
    src: url(https://fonts.gstatic.com/s/materialicons/v90/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2) format('woff2');
    }

    Another way is to use the FontFace API to load a web font before adding the TextLayer:

    async function renderLayers() {
    const font = new FontFace('Material Icons', 'url(https://fonts.gstatic.com/s/materialicons/v90/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2)');
    // wait for font to be loaded
    await font.load();
    // add font to document
    document.fonts.add(font);
    // add TextLayer
    const textLayer = new TextLayer({
    fontFamily: 'Material Icons',
    // ...
    });
    deck.setProps({
    layers: [textLayer]
    });
    }

    Unicode support

    The TextLayer has full support for Unicode characters. To reference a Unicode character in JavaScript you can either use a string literal ('日本語', '©') or escaped code point ('\u{1F436}').

    At the moment this layer doesn't render multi-color emojis.

    Font Atlas Cache Limit

    To conserve memory, DeckGL caches the most 3 used fontAtlas by default. Creating a fontAtlas is a CPU intesive operation specially if fontSettings.sdf is set to true. If you are using much more than 3 fonts, you might experience perforamnce hits because DeckGL constantly tries to evict the least most used fontAtlas from cache and recreate them when needed.

    To mitigate the potential performance degradation, you can override the fontAtlas default cache limit by setting TextLayer.fontAtlasCacheLimit value:

    import {TextLayer} from '@deck.gl/layers';

    TextLayer.fontAtlasCacheLimit = 10;

    // ... rest of the application

    It is recommended to set fontAtlasCacheLimit once in your application since it recreates the cache which removes existing cached fontAtlas.

    Source

    modules/layers/src/text-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/mapbox/mapbox-layer.html b/docs/api-reference/mapbox/mapbox-layer.html index aa49380b795..28f3de4ec65 100644 --- a/docs/api-reference/mapbox/mapbox-layer.html +++ b/docs/api-reference/mapbox/mapbox-layer.html @@ -4,13 +4,13 @@ MapboxLayer | deck.gl - - + +

    MapboxLayer

    MapboxLayer is an implementation of Mapbox GL JS's CustomLayerInterface API. By adding a MapboxLayer instance to an mapbox map, one can render any deck.gl layer inside the mapbox canvas / WebGL2 context. This is in contrast to the traditional deck.gl/mapbox integration where the deck.gl layers are rendered into a separate canvas over the base map.

    See the Mapbox map.addLayer(layer, before?) API for how to add a layer to an existing layer stack.

    Example

    import {MapboxLayer} from '@deck.gl/mapbox';
    import {ScatterplotLayer} from '@deck.gl/layers';

    const map = new mapboxgl.Map({...});

    const myScatterplotLayer = new MapboxLayer({
    id: 'my-scatterplot',
    type: ScatterplotLayer,
    data: [
    {position: [-74.5, 40], size: 100}
    ],
    getPosition: d => d.position,
    getRadius: d => d.size,
    getColor: [255, 0, 0]
    });

    // wait for map to be ready
    map.on('load', () => {
    // insert before the mapbox layer "waterway_label"
    map.addLayer(myScatterplotLayer, 'waterway_label');

    // update the layer
    myScatterplotLayer.setProps({
    getColor: [0, 0, 255]
    });
    });

    Constructor

    import {MapboxLayer} from '@deck.gl/mapbox';
    new MapboxLayer(props);

    Parameters:

    • props (Object)
      • props.id (String) - an unique id is required for each layer.
      • props.type (Layer, optional) - a class that extends deck.gl's base Layer class. Required if deck is not provided.
      • props.deck (Deck, optional) - a Deck instance that controls the rendering of this layer. If provided, the layer will be looked up from its layer stack by id at render time, and all other props are ignored. It's recommended that you use the MapboxOverlay class where a Deck instance is automatically managed.
      • Optional: any other prop needed by this type of layer. See deck.gl's layer catalog for documentation and examples on how to create layers.

    Methods

    setProps(props)
    const layer = new MapboxLayer({
    id: 'my-scatterplot',
    type: ScatterplotLayer,
    ...
    });

    map.addLayer(layer);

    layer.setProps({
    radiusScale: 2
    });

    Update a layer after it's added. Has no effect if props.deck is provided.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/mapbox/mapbox-overlay.html b/docs/api-reference/mapbox/mapbox-overlay.html index 67ec7a1bbb2..a1569501d88 100644 --- a/docs/api-reference/mapbox/mapbox-overlay.html +++ b/docs/api-reference/mapbox/mapbox-overlay.html @@ -4,14 +4,14 @@ MapboxOverlay | deck.gl - - + +

    MapboxOverlay

    MapboxOverlay is an implementation of Mapbox GL JS's IControl API. When adding a MapboxOverlay control to an mapbox map, deck.gl layers are rendered in synchronization with the base map layers. This control supports both overlaid and interleaved rendering modes.

    Example

    Overlaid

    import {MapboxOverlay} from '@deck.gl/mapbox';
    import {ScatterplotLayer} from '@deck.gl/layers';

    const map = new mapboxgl.Map({
    center: [-74.5, 40],
    zoom: 14,
    antialias: true // Improves the rendering quality
    });

    const overlay = new MapboxOverlay({
    interleaved: false,
    layers: [
    new ScatterplotLayer({
    id: 'my-scatterplot',
    data: [
    {position: [-74.5, 40], size: 100}
    ],
    getPosition: d => d.position,
    getRadius: d => d.size,
    getFillColor: [255, 0, 0]
    })
    ]
    });

    map.addControl(overlay);

    Interleaved

    import {MapboxOverlay} from '@deck.gl/mapbox';
    import {ScatterplotLayer} from '@deck.gl/layers';

    const map = new mapboxgl.Map({
    center: [-74.5, 40],
    zoom: 14,
    antialias: true // Improves the rendering quality
    });

    const overlay = new MapboxOverlay({
    interleaved: true,
    layers: [
    new ScatterplotLayer({
    id: 'my-scatterplot',
    data: [
    {position: [-74.5, 40], size: 100}
    ],
    getPosition: d => d.position,
    getRadius: d => d.size,
    getFillColor: [255, 0, 0],

    beforeId: 'admin_labels' // Insert before this Mapbox layer
    })
    ]
    });

    map.addControl(overlay);

    Using with react-map-gl

    The following code demonstrates how to create a React component from MapboxOverlay with react-map-gl@7.x and Typescript:

    import {ScatterplotLayer} from '@deck.gl/layers';
    import {MapboxOverlay, MapboxOverlayProps} from '@deck.gl/mapbox';
    import {useControl} from 'react-map-gl';

    import Map, {NavigationControl} from 'react-map-gl';

    function DeckGLOverlay(props: MapboxOverlayProps & {
    interleaved?: boolean;
    }) {
    const overlay = useControl<MapboxOverlay>(() => new MapboxOverlay(props));
    overlay.setProps(props);
    return null;
    }

    export default function App() {
    const scatterplotLayer = new ScatterplotLayer({
    id: 'my-scatterplot',
    data: [
    {position: [-74.5, 40], size: 100}
    ],
    getPosition: d => d.position,
    getRadius: d => d.size,
    getFillColor: [255, 0, 0]
    });

    return (
    <Map
    initialViewState={{
    latitude: 40,
    longitude: -74.5,
    zoom: 12
    }}
    mapStyle="mapbox://styles/mapbox/light-v9"
    mapboxAccessToken=""
    >
    <DeckGLOverlay layers={[scatterplotLayer]} />
    <NavigationControl />
    </Map>
    );
    }

    See react-map-gl's useControl hook. See using deck.gl with Typescript.

    Constructor

    import {MapboxOverlay} from '@deck.gl/mapbox';
    new MapboxOverlay(props);

    MapboxOverlay accepts the same props as the Deck class, with the following exceptions:

    • views - multi-view support is limited. There is only one MapView that can synchronize with the base map. See the using with multi-views section for details.
    • parent / canvas / gl - context creation is managed internally.
    • viewState / initialViewState - camera state is managed internally.
    • controller - always disabled (to use Mapbox's interaction handlers).

    The constructor additionally accepts the following option:

    • interleaved (Boolean) - If false, a dedicated deck.gl canvas is added on top of the base map. If true, deck.gl layers are inserted into mapbox-gl's layer stack, and share the same WebGL2RenderingContext as the base map. Default is false. Note that interleaving with basemaps such as mapbox-gl-js v1 that only support WebGL 1 is not supported, see compatibility.

    When using interleaved: true, you may optionally add a beforeId prop to a layer to specify its position in the Mapbox layer stack. If multiple deck.gl layers have the same beforeId, they are rendered in the order that is passed into the layers array.

    Methods

    setProps
    const overlay = new MapboxOverlay({
    interleaved: true,
    layers: []
    });

    map.addControl(overlay);

    // Update layers
    overlay.setProps({
    layers: [new ScatterplotLayer({...})]
    })

    Updates (partial) props of the underlying Deck instance. See Deck.setProps.

    pickObject

    See Deck.pickObject.

    pickObjects

    See Deck.pickObjects.

    pickMultipleObjects

    See Deck.pickMultipleObjects.

    finalize

    Removes the control and deletes all resources.

    getCanvas

    See Deck.getCanvas. When using interleaved: true, returns the base map's canvas.

    Remarks

    Multi-view usage

    When using MapboxOverlay with multiple views passed to the views prop, only one of the views can match the base map and receive interaction.

    With that said, it is still possible to take advantage of deck's multi-view system and render a mapbox base map onto any one MapView of your choice by setting the views array and a layerFilter callback.

    • To use multiple views, define a MapView with the id “mapbox”. This view will receive the state that matches the base map at each render.
    • If views are provided but the array does not contain this id, then a MapView({id: 'mapbox'}) will be inserted at the bottom of the stack.
    import {MapboxOverlay} from '@deck.gl/mapbox';
    import {Deck, MapView, OrthographicView} from '@deck.gl/core';
    import {ScatterplotLayer} from '@deck.gl/layers';

    const map = new mapboxgl.Map({...});

    const overlay = new MapboxOverlay({
    views: [
    // This view will be synchronized with the base map
    new MapView({id: 'mapbox'}),
    // This view will not be interactive
    new OrthographicView({id: 'widget'})
    ],
    layerFilter: ({layer, viewport}) => {
    const shouldDrawInWidget = layer.id.startsWith('widget');
    if (viewport.id === 'widget') return shouldDrawInWidget;
    return !shouldDrawInWidget;
    },
    layers: [
    new ScatterplotLayer({
    id: 'my-scatterplot',
    data: [
    {position: [-74.5, 40], size: 100}
    ],
    getPosition: d => d.position,
    getRadius: d => d.size,
    getFillColor: [255, 0, 0]
    }),
    new ScatterplotLayer({
    id: 'widget-scatterplot',
    data: [
    {position: [0, 0], size: 100}
    ],
    getPosition: d => d.position,
    getRadius: d => d.size,
    getFillColor: [255, 0, 0]
    })
    ]
    });

    map.addControl(overlay);
    - - + + \ No newline at end of file diff --git a/docs/api-reference/mapbox/overview.html b/docs/api-reference/mapbox/overview.html index e0eacfcd865..c4f0c387775 100644 --- a/docs/api-reference/mapbox/overview.html +++ b/docs/api-reference/mapbox/overview.html @@ -4,13 +4,13 @@ @deck.gl/mapbox | deck.gl - - + +

    @deck.gl/mapbox

    This module integrates deck.gl into the Mapbox GL JS API-compatible ecosystem.

    • It synchronizes a deck.gl MapView with the mapbox-gl camera.
    • It allows deck.gl to be used with mapbox-gl controls and plugins such as NavigationControl, GeolocateControl and mapbox-gl-geocoder.
    • It adds the option to interleave deck.gl layers with the base map layers, such as drawing behind map labels, z-occlusion between deck.gl 3D objects and Mapbox buildings, etc.

    This module may be used in the React, Pure JS, and Scripting Environments. Visit the mapbox base map developer guide for examples of each option.

    When you use this module, Mapbox is the root HTML element and deck.gl is the child, with Mapbox handling all user inputs. Some of deck.gl's features are therefore unavailable due to limitations of mapbox-gl's API, see limitations.

    It may be easier to understand the concepts of the module if you are already a mapbox-gl developer.

    This module is compatible with Mapbox GL JS forks. Known exceptions will be clearly marked. For more, see Compatibility with Mapbox GL JS forks

    Installation

    Include the Standalone Bundle

    <script src="https://unpkg.com/deck.gl@^9.0.0/dist.min.js"></script>
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.js'></script>
    <script type="text/javascript">
    const {MapboxOverlay} = deck;
    </script>

    Install from NPM

    npm install @deck.gl/mapbox
    import {MapboxOverlay} from '@deck.gl/mapbox';

    Camera Syncronization between deck.gl and Mapbox

    This module keeps a deck.gl MapView in sync with the mapbox-gl camera so that the base map and deck layers are always geospactially aligned. Some Deck props, such as viewState, are ignored or have different behavior. See MapboxOverlay constructor notes. Also, some camera features are unable to be fully synchronized due to mapbox-gl API limitations, see limitations.

    Using mapbox-gl controls and plugins with deck.gl

    The Mapbox ecosystem offers many well-designed controls, from the basic functionalities of NavigationControl, Popup and GeolocateControl, to vendor-service-bound UI implementations such as mapbox-gl-geocoder and mapbox-gl-directions. These libraries require that the Mapbox Map holds the source of truth of the camera state, instead of the normal state management by Deck. When you use the MapboxOverlay classes from this module, deck.gl plays nice with all the mapbox-gl peripherals.

    Mixing deck.gl layers and Mapbox layers

    Some important information in the Mapbox map could be hidden by a deck.gl visualization layer, and controlling opacity is not enough. A typical example of this is labels and roads, where it is desirable to have a deck.gl visualization layer render on top of the Mapbox geography, but where one might still want to see e.g. labels and/or roads. Alternatively, the deck.gl visualization should cover the ground, but not the roads and labels.

    To inject a deck layer into the Mapbox stack add an interleaved: true props to the MapboxOverlay control and add a beforeId prop to any layer passed to the MapboxOverlay control.

    Mapbox provides an example of finding the first label layer. For more sophisticated injection point lookups, refer to Mapbox' documentation on the format of Mapbox style layers, see Mapbox Style Spec.

    In some cases, the application wants to add a deck.gl 3D layer (e.g. ArcLayer, HexagonLayer, GeoJsonLayer) on top of a Mapbox basemap, while seamlessly blend into the z-buffer. This will interleave the useful visualization layers from both the deck.gl and Mapbox layer catalogs. In this case, a beforeId is not needed.

    Interleaved Renderer Compatibility

    The following table details renderer support across different versions of mapbox-gl and maplibre-gl. See base map renderers to learn about the differences between overlaid and interleaved renderers.

    LibraryOverlaid (default)Interleaved
    mapbox-gl-js (before v2.13)
    mapbox-gl-js v2.13+✓ with useWebGl2: true
    mapbox-gl-js v3+
    maplibre-gl-js (before v3)
    maplibre-gl-js v3+✓*

    *will fallback to WebGL1 if WebGL2 is not available

    Alternative Mapbox Integrations

    If you're using deck.gl in a React or Scripting environment, you just want the base map as a back drop, and do not need mapbox-gl's UI controls or need to mix deck.gl and Mapbox layers, it is recommended that you do not use this module and instead use deck.gl as the root HTML element. Visit Using Deck.gl as the root HTML element for an example.

    Limitations

    • When using deck.gl's multi-view system, only one of the views can match the base map and receive interaction. See using MapboxOverlay with multi-views for details.
    • When using deck.gl as Mapbox layers or controls, Deck only receives a subset of user inputs delegated by Map. Therefore, certain interactive callbacks like onDrag, onInteractionStateChange are not available.
    • Mapbox/Maplibre's terrain features are partially supported. When a terrain is used, the camera of deck.gl and the base map should synchronize, however the deck.gl data with z=0 are rendered at the sea level and not aligned with the terrain surface.
    • Only Mercator projection is supported. Mapbox adaptive projection is not supported as their API doesn't expose the projection used.
    • The position property in viewState has no equivalent in mapbox-gl.
    - - + + \ No newline at end of file diff --git a/docs/api-reference/mesh-layers/scenegraph-layer.html b/docs/api-reference/mesh-layers/scenegraph-layer.html index d4a07556cd2..4bb64bd62a1 100644 --- a/docs/api-reference/mesh-layers/scenegraph-layer.html +++ b/docs/api-reference/mesh-layers/scenegraph-layer.html @@ -4,8 +4,8 @@ ScenegraphLayer | deck.gl - - + +
    @@ -19,7 +19,7 @@ Only triggers when scenegraph property changes.

    _lighting (String, optional)
    • Default: flat

    Experimental lighting support, can be:

    • flat: No light calculation. Works well with any textured object.
    • pbr Uses glTF PBR model. Works well with glTF models.

    Only read when scenegraph property changes. Uses global light configuration from deck.

    _imageBasedLightingEnvironment (Function or GLTFEnvironment, optional)
    • Default: null

    Experimental Can be:

    • A GLTFEnvironment object.
    • A function that takes {gl, layer} as first argument and returns a GLTFEnvironment.

    Only read when scenegraph property changes.

    Data Accessors

    getPosition (Function, optional) transition-enabled
    • Default: object => object.position

    Method called to retrieve the center position for each object in the data stream.

    getColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    The rgba color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied. Only used if texture is empty.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    getOrientation (Function|Array, optional)
    • Default: [0, 0, 0]

    Object orientation defined as a vec3 of Euler angles, [pitch, yaw, roll] in degrees. This will be composed with layer's modelMatrix.

    • If an array is provided, it is used as the orientation for all objects.
    • If a function is provided, it is called on each object to retrieve its orientation.
    getScale (Function|Array, optional)
    • Default: [1, 1, 1]

    Scaling factor on the mesh along each axis.

    • If an array is provided, it is used as the scale for all objects.
    • If a function is provided, it is called on each object to retrieve its scale.
    getTranslation (Function|Array, optional)
    • Default: [0, 0, 0]

    Translation of the mesh along each axis. Offset from the center position given by getPosition. [x, y, z] in meters.

    • If an array is provided, it is used as the offset for all objects.
    • If a function is provided, it is called on each object to retrieve its offset.
    getTransformMatrix (Function|Array, optional)
    • Default: null

    Explicitly define a 4x4 column-major model matrix for the mesh. If provided, will override getOrientation, getScale, getTranslation. This will be composed with layer's modelMatrix.

    • If an array is provided, it is used as the transform matrix for all objects.
    • If a function is provided, it is called on each object to retrieve its transform matrix.
    sizeMinPixels (Number, optional)
    • Default: 0

    The minimum size in pixels for one unit of the scene.

    sizeMaxPixels (Number, optional)
    • Default: Number.MAX_SAFE_INTEGER

    The maximum size in pixels for one unit of the scene.

    Source

    modules/mesh-layers/src/scenegraph-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/mesh-layers/simple-mesh-layer.html b/docs/api-reference/mesh-layers/simple-mesh-layer.html index c7f639583fe..5308c29911c 100644 --- a/docs/api-reference/mesh-layers/simple-mesh-layer.html +++ b/docs/api-reference/mesh-layers/simple-mesh-layer.html @@ -4,15 +4,15 @@ SimpleMeshLayer | deck.gl - - + +

    SimpleMeshLayer

    The SimpleMeshLayer renders a number of instances of an arbitrary 3D geometry. For example, it can be used to visualize a fleet of 3d cars each with a position and an orientation over the map.

    import DeckGL from '@deck.gl/react';
    import {SimpleMeshLayer} from '@deck.gl/mesh-layers';
    import {CubeGeometry} from '@luma.gl/core'

    function App({data, viewState}) {
    /**
    * Data format:
    * [
    * {
    * position: [-122.45, 37.7],
    * angle: 0,
    * color: [255, 0, 0]
    * },
    * {
    * position: [-122.46, 37.73],
    * angle: 90,
    * color: [0, 255, 0]
    * },
    * ...
    * ]
    */
    const layer = new SimpleMeshLayer({
    id: 'mesh-layer',
    data,
    texture: 'texture.png',
    mesh: new CubeGeometry(),
    getPosition: d => d.position,
    getColor: d => d.color,
    getOrientation: d => [0, d.angle, 0]
    });

    return <DeckGL viewState={viewState} layers={[layer]} />;
    }

    loaders.gl offers a category of loaders for loading meshes from standard formats. For example, the following code adds support for OBJ files:

    import {SimpleMeshLayer} from '@deck.gl/mesh-layers';
    import {OBJLoader} from '@loaders.gl/obj';

    new SimpleMeshLayer({
    ...
    mesh: 'path/to/model.obj',
    loaders: [OBJLoader]
    });

    Installation

    To install the dependencies from NPM:

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/mesh-layers
    import {SimpleMeshLayer} from '@deck.gl/mesh-layers';
    new SimpleMeshLayer({});

    To use pre-bundled scripts:

    <script src="https://unpkg.com/deck.gl@^8.0.0/dist.min.js"></script>
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/mesh-layers@^8.0.0/dist.min.js"></script>
    new deck.SimpleMeshLayer({});

    Properties

    Inherits from all Base Layer properties.

    Mesh

    mesh (String|Geometry|Object)

    The geometry to render for each data object. One of:

    • An URL to a mesh description file in a format supported by loaders.gl. The appropriate loader will have to be registered via the loaders.gl registerLoaders function for this usage.
    • A luma.gl Geometry instance
    • An object containing the following fields:
      • positions (Float32Array) - 3d vertex offset from the object center, in meters
      • normals (Float32Array) - 3d normals
      • texCoords (Float32Array) - 2d texture coordinates
    texture (String|Texture|Image|ImageData|HTMLCanvasElement|HTMLVideoElement|ImageBitmap|Promise|Object, optional)
    • Default null.

    The texture of the geometries.

    • If a string is supplied, it is interpreted as a URL or a Data URL.
    • One of the following, or a Promise that resolves to one of the following:
      • One of the valid pixel sources for WebGL2 texture
      • A luma.gl Texture instance
      • A plain object that can be passed to the Texture constructor, e.g. {width: <number>, height: <number>, data: <Uint8Array>}. Note that whenever this object shallowly changes, a new texture will be created.

    The image data will be converted to a Texture object. See textureParameters prop for advanced customization.

    If texture is supplied, texture is used to render the geometries. Otherwise, object color obtained via the getColor accessor is used.

    textureParameters (Object)

    Customize the texture parameters.

    If not specified, the layer uses the following defaults to create a linearly smoothed texture from texture:

    {
    minFilter: 'linear',
    magFilter: 'linear',
    mipmapFilter: 'linear',
    addressModeU: 'clamp-to-edge',
    addressModeV: 'clamp-to-edge'
    }

    Render Options

    sizeScale (Number, optional) transition-enabled
    • Default 1.

    Multiplier to scale each geometry by.

    wireframe (Boolean, optional)
    • Default: false

    Whether to render the mesh in wireframe mode.

    material (Object, optional)
    • Default: true

    This is an object that contains material props for lighting effect applied on extruded polygons. Check the lighting guide for configurable settings.

    Data Accessors

    getPosition (Function, optional) transition-enabled
    • Default: object => object.position

    Method called to retrieve the center position for each object in the data stream.

    getColor (Function|Array, optional) transition-enabled
    • Default: [0, 0, 0, 255]

    If mesh does not contain vertex colors, use this color to render each object. If mesh contains vertex colors, then the two colors are mixed together. Use [255, 255, 255] to use the original mesh colors. If texture is assigned, then both colors will be ignored.

    The color is in the format of [r, g, b, [a]]. Each channel is a number between 0-255 and a is 255 if not supplied.

    • If an array is provided, it is used as the color for all objects.
    • If a function is provided, it is called on each object to retrieve its color.
    getOrientation (Function|Array, optional)
    • Default: [0, 0, 0]

    Object orientation defined as a vec3 of Euler angles, [pitch, yaw, roll] in degrees. This will be composed with layer's modelMatrix.

    • If an array is provided, it is used as the orientation for all objects.
    • If a function is provided, it is called on each object to retrieve its orientation.
    getScale (Function|Array, optional)
    • Default: [1, 1, 1]

    Scaling factor on the mesh along each axis.

    • If an array is provided, it is used as the scale for all objects.
    • If a function is provided, it is called on each object to retrieve its scale.
    getTranslation (Function|Array, optional)
    • Default: [0, 0, 0]

    Translation of the mesh along each axis. Offset from the center position given by getPosition. [x, y, z] in meters. This will be composed with layer's modelMatrix.

    • If an array is provided, it is used as the offset for all objects.
    • If a function is provided, it is called on each object to retrieve its offset.
    getTransformMatrix (Function|Array, optional)
    • Default: null

    Explicitly define a 4x4 column-major model matrix for the mesh. If provided, will override getOrientation, getScale, getTranslation.

    • If an array is provided, it is used as the transform matrix for all objects.
    • If a function is provided, it is called on each object to retrieve its transform matrix.

    Source

    modules/mesh-layers/src/simple-mesh-layer

    - - + + \ No newline at end of file diff --git a/docs/api-reference/react/deckgl.html b/docs/api-reference/react/deckgl.html index 1a6618b2dc6..d8078085b2f 100644 --- a/docs/api-reference/react/deckgl.html +++ b/docs/api-reference/react/deckgl.html @@ -4,13 +4,13 @@ DeckGL (React Component) | deck.gl - - + +

    DeckGL (React Component)

    DeckGL is the main interface to deck.gl for React applications. DeckGL is a React component that takes a list of deck.gl layer instances and a view state, and renders those layers on a transparent canvas that can be used as an overlay over other components like maps.

    Make sure to read the Using deck.gl with React article.

    The DeckGL class is a React wrapper of the Deck JavaScript class which exposes essentially the same props. The Deck class should not be used directly in React applications.

    Usage

    // Basic usage
    import DeckGL from '@deck.gl/react';
    import {ScatterplotLayer} from '@deck.gl/layers';

    const App = (data) => (
    <DeckGL
    longitude={-122.45}
    latitude={37.78}
    zoom={12}
    layers={[new ScatterplotLayer({data})]} />
    );

    Like any React component, DeckGL can accept child components. Child components are often maps (e.g. the StaticMap component from react-map-gl), but can be any React components.

    import DeckGL from '@deck.gl/react';
    import {StaticMap} from 'react-map-gl';

    const App = (data) => (
    <DeckGL
    initialViewState={{longitude: -122.45, latitude: 37.78, zoom: 12}}
    controller={true}
    layers={[new ScatterplotLayer({data})]}
    >
    <StaticMap
    mapStyle="mapbox://styles/mapbox/dark-v9"
    mapboxApiAccessToken={MAPBOX_ACCESS_TOKEN} />
    </DeckGL>
    );

    Properties

    DeckGL accepts all Deck properties, with these additional semantics:

    React Context

    ContextProvider (React.Component, optional)

    A Context.Provider component. If supplied, will be rendered as the ancestor to all children. The passed through context contains the following values:

    • viewport (Viewport) - the current viewport
    • container (DOMElement) - the DOM element containing the deck canvas
    • eventManager (EventManager)
    /// Example using react-map-gl v6 controls with deck.gl
    /// To use react-map-gl v7, see https://deck.gl/docs/api-reference/mapbox/mapbox-overlay
    import DeckGL from '@deck.gl/react';
    import {_MapContext as MapContext, NavigationControl} from 'react-map-gl';

    <DeckGL ... ContextProvider={MapContext.Provider}>
    <div style={NAVIGATION_CONTROL_STYLES}>
    <NavigationControl />
    </div>
    </DeckGL>

    Children

    The following semantics of the standard React children property are considered experimental.

    JSX layers

    It is possible to use JSX syntax to create deck.gl layers as React children of the DeckGL React components, instead of providing them as ES6 class instances to the layers prop.

      <DeckGL {...viewState}>
    <LineLayer id="line-layer" data={data} />
    <DeckGL />

    Caveat: The JSX layer syntax is limited in that it only works when the layers are direct children of the DeckGL component. deck.gl layers are not true React components and cannot be rendered independently by React, and the JSX support depends on deck.gl intercepting the JSX generated child elements before React tries to render them.

    JSX views

    It is possible to use JSX syntax to create deck.gl views as React children of the DeckGL React components, instead of providing them as ES6 class instances to the views prop.

      <DeckGL initialViewState={...viewState} layers={layers} >
    <MapView id="map" width="50%" controller={true} >
    <StaticMap mapboxApiAccessToken={MAPBOX_ACCESS_TOKEN} />
    </MapView>
    <FirstPersonView width="50%" x="50%" fovy={50} />
    <DeckGL />

    If a certain view id is used in both JSX views and the views prop, the view instance in the views prop has priority.

      const views = [
    new MapView({id: 'map', width: '50%', controller: true}),
    new FirstPersonView({width: '50%', x: '50%', fovy: 50})
    ];

    <DeckGL initialViewState={...viewState} layers={layers} views={views} >
    <View id="map">
    <StaticMap mapboxApiAccessToken={MAPBOX_ACCESS_TOKEN} />
    </View>
    <DeckGL />

    Position Children in Views

    To make it easy to use React components in combination with deck.gl views (e.g. to place a base map under a view, or add a label on top of a view), deck.gl can make such components automatically adjust as that view is added, removed or resized.

    Each child element of DeckGL is positioned inside a view. All children of a view is wrapped in a DOM container that:

    • is offset to be relative to the deck.gl view that it corresponds to.
    • is resized to match the extent of the deck.gl view with the corresponding view id.
    • is hidden if the view id is missing from DeckGL's views prop.

    The containing view of each element is determined as follows:

    • If the element is a direct child of DeckGL, it is positioned inside the default (first) view.
    • If the element is nested under a <View id={id}> tag, it is positioned inside the view corresponding to the id prop.

    Render callbacks

    You may supply a function as a child to the DeckGL or View node (see JSX views). The function will be called to retrieve the React children when the viewport updates.

    The following arguments are passed:

    • x - the left offset of the current view, in pixels
    • y - the top offset of the current view, in pixels
    • width - the width of the current view, in pixels
    • height - the height of the current view, in pixels
    • viewState - the view state of the current view
    • viewport - the Viewport instance of the current view

    This is useful when you need to specify custom rendering logic for a child:

      <DeckGL {...viewState}>
    {({x, y, width, height, viewState, viewport}) => (
    <Marker
    project={viewport.project}
    longitude={-122.45}
    latitude={37.8}
    width={24}
    height={24} />
    )}
    <DeckGL />

    Additional Notes:

    • The DeckGL components own canvas element is added last to the child list, to sit on top of all the base components, however Z index can be used to override this.
    • Child repositioning is done with CSS styling on a wrapper div.
    • Children that do not belong to any <View> tag and are functions are called with the properties of the default view.
    • Children that do not belong to any <View> tag and are valid React elements are rendered as is.

    Methods

    All Deck methods are available on the DeckGL component, but not all of them can be explicitly called. For example, to rerender your component, you can pass updated props to DeckGL component directly, while you should call setProps with new props in Deck.

    The public methods you can call explicitly list below:

    • pickObject
    • pickMultipleObjects
    • pickObjects

    We do recommend you to use the pure JavaScript version of deck.gl if you are more comfortable with an imperative programming style (e.g. deck.setProps()).

    Source

    modules/react/src/deckgl.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/test-utils/generate-layer-tests.html b/docs/api-reference/test-utils/generate-layer-tests.html index 158735745db..911c9e7d5e9 100644 --- a/docs/api-reference/test-utils/generate-layer-tests.html +++ b/docs/api-reference/test-utils/generate-layer-tests.html @@ -4,13 +4,13 @@ generateLayerTests | deck.gl - - + +

    generateLayerTests

    This utility generates a series of test cases to be used with testLayer that checks the conformance of a layer class.

    Example

    Example of layer unit tests using tape. The test utility itself is test framework agnostic.

    import test from 'tape-promise/tape';
    import {testLayer, generateLayerTests} from '@deck.gl/test-utils';
    import {GeoJsonLayer} from '@deck.gl/layers';

    test('GeoJsonLayer#tests', t => {

    const testCases = generateLayerTests({
    Layer: GeoJsonLayer,
    sampleProps: {
    data: SAMPLE_GEOJSON
    },
    assert: ({layer, subLayers}) => {
    t.ok(layer.state.features, 'should update features');
    t.is(subLayers.length, layer.props.stroked ? 2 : 1, 'correct number of sublayers');
    }
    });

    testLayer({Layer: GeoJsonLayer, testCases});

    t.end();
    });

    Usage

    generateLayerTests({Layer, sampleProps, assert, onError});
    • Layer (Object) - the layer component class to test
    • sampleProps (Object, Optional) - a list of props to use as the basis for all generated tests. Can be used to supply a meaningful set of data.
    • assert (Function, optional) - callback when checking a condition. Receives two arguments:
      • condition - a value that is expected to be truthy
      • comment (String) - information about the check
    • onBeforeUpdate - custom callback to be added to each test case.
    • onAfterUpdate - custom callback to be added to each test case.
    - - + + \ No newline at end of file diff --git a/docs/api-reference/test-utils/interaction-test-runner.html b/docs/api-reference/test-utils/interaction-test-runner.html index 029e77c84f2..ce280a9b135 100644 --- a/docs/api-reference/test-utils/interaction-test-runner.html +++ b/docs/api-reference/test-utils/interaction-test-runner.html @@ -4,13 +4,13 @@ InteractionTestRunner | deck.gl - - + +

    InteractionTestRunner

    Client-side utility for browser-based deck.gl interaction tests.

    This class is intended to be used with BrowserTestDriver from @probe.gl/test-utils. Together they support the following workflow:

    • Launch a Puppeteer instance (headless or non-headless) to run a test application
    • In the test application, create a deck.gl canvas.
    • For each test case, dispatch a sequence of keyboard/mouse events, and check the updated state.
    • Proceed to the next test case until done.

    Example

    See SnapshotTestRunner for Node side set up instructions.

    In your script that is run on the browser:

    const {InteractionTestRunner} = require('@deck.gl/test-utils');

    const TEST_CASES = [
    {
    name: 'MapController',
    events: [
    {type: 'drag', startX: 400, startY: 200, endX: 300, endY: 200, steps: 3}
    ],
    onBeforeEvents: ({deck}) => ({viewport: deck.getViewports[0]}),
    onAfterEvents: ({deck, context}) => {
    const oldViewport = context.viewport;
    const newViewport = deck.getViewports[0];
    t.ok(newViewport.longitude > oldViewport.longitude, 'map moved');
    }
    }
    ];

    new TestRender({
    width: 800,
    height: 600,
    initialViewState: {
    longitude: -122.4,
    latitude: 37.8,
    zoom: 12
    },
    controller: true
    })
    .add(TEST_CASES)
    .run()
    .then(window.browserTestDriver_finish);

    Methods

    constructor(props: Object)

    new InteractionTestRunner(deckProps)

    Create a InteractionTestRunner instance. The deckProps argument is passed to the Deck constructor.

    add(testCase: Array|Object)

    Add one or a list of test cases. Each test case may contain the following fields:

    • name (String) - name of the test case.
    • events (Array) - a sequence of inputs to dispatch. See Event section below.
    • onBeforeEvents (Function, optional) - called before the events are dispatched. Receives the following arguments:
      • deck - the Deck instance.
    • onAfterEvents (Function, optional) - called after the events are dispatched. Receives the following arguments:
      • deck - the Deck instance.
      • layers - the rendered layers.
      • context - the return value of onBeforeEvents.

    run(options: Object)

    Run all test cases.

    Options:

    • timeout (Number) - time to wait for each test case to resolve (by calling the done callback) before aborting, in milliseconds. Default 2000.

    Returns: a Promise that resolves when all test cases are done.

    Members

    isHeadless

    Whether the test is being run in headless mode. In headless mode, Chromium uses software render which behaves slightly differently from non-headless. Image diffing tolerance may need to be adjusted accordingly.

    Event

    An event is a javascript descriptor of emulated user input. The following event types are supported:

    keypress

    Press a key on the keyboard.

    • type: 'keypress'
    • key (String) - see https://github.com/GoogleChrome/puppeteer/blob/master/lib/USKeyboardLayout.js
    • delay (Number) - the time between keydown and keyup. Default 0.
    • shiftKey (Boolean) - whether to press the key with the shift key down. Default false.
    • ctrlKey (Boolean) - whether to press the key with the control key down. Default false.
    • metaKey (Boolean) - whether to press the key with the meta key down. Default false.

    click

    Click the mouse at a given screen coordinate.

    • type: 'click'
    • x (Number) - the screen x of the click.
    • y (Number) - the screen y of the click.
    • button (String) - 'left', 'right' or 'middle'.
    • delay (Number) - the time between mousedown and mouse up. Default 0.
    • shiftKey (Boolean) - whether to click with the shift key pressed. Default false.
    • ctrlKey (Boolean) - whether to click with the control key pressed. Default false.
    • metaKey (Boolean) - whether to click with the meta key pressed. Default false.

    mousemove

    Move the mouse to a given screen coordinate.

    • type: 'mousemove'
    • x (Number) - the screen x to move the pointer to.
    • y (Number) - the screen y to move the pointer to.
    • steps (Number) - how many intermediate mousemove events to generate, default 1.

    drag

    Drag the mouse from a given screen coordinate to another.

    • type: 'drag'
    • startX (Number) - the screen x to drag from.
    • startY (Number) - the screen y to drag from.
    • endX (Number) - the screen x to drag to.
    • endY (Number) - the screen y to drag to.
    • button (String) - 'left', 'right' or 'middle'.
    • steps (Number) - how many intermediate mousemove events to generate, default 1.
    • shiftKey (Boolean) - whether to click with the shift key pressed. Default false.
    • ctrlKey (Boolean) - whether to click with the control key pressed. Default false.
    • metaKey (Boolean) - whether to click with the meta key pressed. Default false.

    wait

    Idle for a given period of time before the next event.

    • wait (Number) - the timeout in milliseconds.
    - - + + \ No newline at end of file diff --git a/docs/api-reference/test-utils/overview.html b/docs/api-reference/test-utils/overview.html index 368f1cbc598..c5b060bb000 100644 --- a/docs/api-reference/test-utils/overview.html +++ b/docs/api-reference/test-utils/overview.html @@ -4,13 +4,13 @@ @deck.gl/test-utils | deck.gl - - + +

    @deck.gl/test-utils

    A set of utilities to facilitate testing deck.gl layers. Tests can be run:

    • Completely in Node.js (lifecycle tests only).
    • Completely in the Browser (lifecycle and rendering tests).
    • From Node in a controlled Browser instance (with probe.gl's BrowserTestDriver).

    Installation

    The deck.gl test utilities are published as a separate npm module that is only intended to be used during development. Install it as as a "dev dependency" as follows:

    npm install --save-dev @deck.gl/test-utils

    or

    yarn add -D @deck.gl/test-utils

    You typically want the major and minor version of @deck.gl/test-utils to match the version of @deck.gl/core that you are using. i.e. you want to use 5.2.x and 5.2.y together. Check and if necessary edit your package.json to make sure things align.

    Layer Conformance Tests

    Layer conformance tests are designed to verify deck.gl that layers update their internal state correctly in response to various props and prop changes. The layer update test support includes test drivers to initialize a layer and then run a sequence of successive updates, with facilities for validating the layer after each change, and also provides functions to initialize, update and render layers in a test environment.

    Note that internally in deck.gl, updates are handled by the deck.gl layer "lifecycle" and these tests are therefore also called "lifecycle tests". Lifecycle tests are less demanding of the WebGL2/WebGPU environment than rendering tests described below and are thus easily integrated in traditional Node.js unit test suites (e.g. based on tape, jest or similar unit test frameworks).

    Layer Rendering Tests

    Rendering tests are a key feature of deck.gl's test utils. Rendering tests involve rendering layers with known inputs and performing pixel-comparison between the results against "golden images".

    Currently, rendering tests requires running layers with predefined props and views in a controlled Chrome instance, reporting values back to Node.js.

    Testing Applications instead of Layers

    The current test utilities are focused on testing of layers. This might seem to make them less suited for testing deck.gl code in applications. Still, there are techniques that can be used to get parts of the application's rendering stack tested.

    Applications that render multiple layers can e.g. render them with mock application data, and compare the result against a golden image.

    More direct support for application testing is under consideration. Future support might include rendering layers directly in Node.js under headless gl, enabling apps to be tested in CI environments, as well as support for "snapshotting" deck.gl output inside live applications and comparing against golden images.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/test-utils/snapshot-test-runner.html b/docs/api-reference/test-utils/snapshot-test-runner.html index 48521cd3932..2ef295097f7 100644 --- a/docs/api-reference/test-utils/snapshot-test-runner.html +++ b/docs/api-reference/test-utils/snapshot-test-runner.html @@ -4,13 +4,13 @@ SnapshotTestRunner | deck.gl - - + +

    SnapshotTestRunner

    Client-side utility for browser-based deck.gl render tests.

    This class is intended to be used with BrowserTestDriver from @probe.gl/test-utils. Together they support the following workflow:

    • Launch a Puppeteer instance (headless or non-headless) to run a test application
    • In the test application, create a deck.gl canvas.
    • For each test case, render a set of deck props including views and layers, take a screenshot, and perform pixel-diffing with a pre-defined "golden image". Report the matching result.
    • Proceed to the next test case until done.

    Example

    In your node.js start script:

    // This is the script that runs in Node.js and starts the browser
    const {BrowserTestDriver} = require('@probe.gl/test-utils');
    new BrowserTestDriver().run({
    server: {
    // Bundles and serves the browser script
    command: 'webpack-dev-server',
    arguments: ['--env.render-test']
    },
    headless: true
    });

    In your script that is run on the browser:

    const {SnapshotTestRunner} = require('@deck.gl/test-utils');
    const {ScatterplotLayer} = require('@deck.gl/layers');

    const TEST_CASES = [
    {
    name: 'ScatterplotLayer',
    // `Deck` props
    viewState: {
    longitude: -122.4,
    latitude: 37.8,
    zoom: 12,
    pitch: 20
    },
    layers: [
    new ScatterplotLayer({
    id: 'circles',
    data: './data/scatterplot.json',
    getPosition: d => d.position,
    getRadius: d => d.size,
    getFillColor: [255, 0, 0]
    })
    ],
    // `done` must be called when ready for screenshot and compare
    onAfterRender: ({layers, done}) => {
    if (layers[0].props.data.length) {
    // data is loaded
    done();
    }
    },
    // Target rendering result
    goldenImage: './test/render/golden-images/scatterplot.png'
    }
    ];

    new TestRender({width: 800, height: 600})
    .add(TEST_CASES)
    .run({
    onTestFail: window.browserTestDriver_fail
    })
    .then(window.browserTestDriver_finish);

    Methods

    constructor(props: Object)

    new SnapshotTestRunner(deckProps)

    Create a SnapshotTestRunner instance. The deckProps argument is passed to the Deck constructor.

    add(testCase: Array|Object)

    Add one or a list of test cases. Each test case may contain the following fields:

    • name (String) - name of the test case.

    • goldenImage (String) - path to the golden image, relative to the root where the node script is executed.

    • timeout (Number) - time to wait for this test case to resolve (by calling the done callback) before aborting, in milliseconds. If not provided, fallback to the shared option that is passed to SnapshotTestRunner.run.

    • imageDiffOptions (Object, optional) - image diffing options for this test case. See "Image Diff Options" section below.

    • onBeforeRender (Function, optional) - callback before each time deck rerenders. Receives the following arguments:

      • deck (Deck) - the Deck instance.
      • layers (Array) - the list of layers that were rendered.
    • onAfterRender (Function, optional) - callback after each time deck rerenders. Receives the following arguments:

      • deck (Deck) - the Deck instance.
      • layers (Array) - the list of layers that were rendered.
      • done (Function) - must be called when the test case is done rendering and ready for screen capture and comparison.

      The default onAfterRender calls done immediately, i.e. takes screenshot as soon as the canvas is rendered for the first time. If some resources are loaded asynchronously, you may need to provide an implementation of this callback to check whether all layers are fully loaded.

    • Any other props that Deck.setProps accepts.

    run(options: Object)

    Run all test cases.

    Options:

    • timeout (Number) - time to wait for each test case to resolve (by calling the done callback) before aborting, in milliseconds. Default 2000.
    • imageDiffOptions (Object) - image diffing options for all test cases. This will be overridden if a test case defines its own imageDiffOptions. See "Image Diff Options" section below.
    • onTestStart (Function) - callback when a test starts. Receives the current test case. Default logs the test name to console.
    • onTestPass (Function) - callback when a test passes. Receives the current test case and the diffing result. Default logs the pixel matching percentage to console.
    • onTestFail (Function) - callback when a test fails, either because the matching rate is below threshold or a critical error. Receives the current test case. Default logs the error message or the pixel matching percentage to console.

    Returns: a Promise that resolves when all test cases are done.

    Members

    isHeadless

    Whether the test is being run in headless mode. In headless mode, Chromium uses software render which behaves slightly differently from non-headless. Image diffing tolerance may need to be adjusted accordingly.

    Image Diff Options

    The test renderer and each test case may choose to override the default image diffing options. The following options from captureAndDiffScreen are supported:

    • tolerance
    • threshold
    • includeAA
    • includeEmpty
    • createDiffImage
    • saveOnFail
    • saveAs
    - - + + \ No newline at end of file diff --git a/docs/api-reference/test-utils/test-layer.html b/docs/api-reference/test-utils/test-layer.html index d1fe7fab818..f05123b058e 100644 --- a/docs/api-reference/test-utils/test-layer.html +++ b/docs/api-reference/test-utils/test-layer.html @@ -4,14 +4,14 @@ testLayer | deck.gl - - + +

    testLayer

    The testLayer utility initializes a layer, test layer updates and draw calls on a series of new props, and allow test suites to inspect the result.

    The testLayerAsync utility is like testLayer, but designed for layers that need to resolve resources asynchronously.

    Example

    Example of layer unit tests using tape. The test utility itself is test framework agnostic.

    import test from 'tape-promise/tape';
    import {testLayer, testLayerAsync} from '@deck.gl/test-utils';
    import {GeoJsonLayer} from '@deck.gl/layers';

    test('GeoJsonLayer#tests', t => {
    testLayer({Layer: GeoJsonLayer, testCases: [
    // Test case 1
    {
    props: {data: []}
    },
    // Test case 2
    {
    props: {
    data: SAMPLE_GEOJSON
    },
    onAfterUpdate({layer, oldState}) {
    t.ok(layer.state.features !== oldState.features, 'should update features');
    t.is(subLayers.length, 2, 'should render 2 subLayers');
    }
    },
    // Test case 3
    {
    updateProps: {
    // will be merged with the previous props
    lineWidthScale: 3
    },
    onAfterUpdate({subLayers}) {
    const pathLayer = subLayers.find(layer => layer.id.endsWith('linestrings'));
    t.is(pathLayer.props.widthScale, 3, 'widthScale is passed to sub layer');
    }
    }
    ]});

    t.end();
    });

    Usage

    testLayer({Layer, spies, testCases, onError});
    await testLayerAsync({Layer, spies, testCases, onError});
    • Layer (Object) - the layer component class to test
    • testCases (Array) - a list of test cases, as described below.
    • viewport (Viewport, Optional) - a viewport instance to use for the tests.
    • spies (Array, Optional) - names of layer class methods to spy on.
    • onError (Function, Optional) - callback after each operation with potential errors. Called with two arguments:
      • error (Error|null)
      • title (String) - name of the operation.

    Test Cases

    Test cases specified as objects and are run sequentially. Each test case provided to testLayer specifies what properties are going to be updated.

    A test case is an object with the following fields:

    • title (String) - title of the test case
    • props (Object) - specifies a complete new set of props
    • updateProps (Object) - specifies an incremental prop change (overrides props from previous test case)
    • spies (Array, Optional) - names of layer class methods to spy on. Overrides the list that was sent to testLayer.
    • onBeforeUpdate (Function, Optional) - callback invoked before the layer props are updated. Receives a single argument info:
      • info.testCase (Object) - the current test case
      • info.layer (Layer) - the old layer
    • onAfterUpdate (Function, Optional) - callback invoked after the layer props have been updated. This allows the test case to verify that the layer's state has been correctly updated, or that certain functions (spies) have been called etc. Receives a single argument info: {layer, oldState, subLayers, subLayer, spies: spyMap}.
      • info.testCase (Object) - the current test case
      • info.layer (Layer) - the updated layer
      • info.oldState (Object) - layer state before the update
      • info.subLayers (Array) - sub layers rendered, if the layer is composite
      • info.subLayer (Layer) - the first sub layer rendered, if the layer is composite
      • info.spies (Object) - key are layer method names and values are spies.

    Note that onAfterUpdate is called immediately after the props are updated. If the layer contains asynchronous props, they may not have been loaded at this point.

    When using TestLayerAsync, onAfterUpdate is called multiple times until all resources are loaded.

    Source

    modules/test-utils/src/lifecycle-test.ts

    - - + + \ No newline at end of file diff --git a/docs/api-reference/widgets/compass-widget.html b/docs/api-reference/widgets/compass-widget.html index 3d0093740f1..225dbef1439 100644 --- a/docs/api-reference/widgets/compass-widget.html +++ b/docs/api-reference/widgets/compass-widget.html @@ -4,13 +4,13 @@ CompassWidget | deck.gl - - + +

    CompassWidget

    This widget visualizes bearing and pitch. Click it once to reset bearing to 0, click it a second time to reset pitch to 0. Supports Map and Globe view.

    Props

    id (String)

    Default: 'fullscreen'

    Unique identifier of the widget.

    viewId (String, optional)

    Default: null

    The widget is attached to the view identified by this viewId. When assigned, the widget is placed within the specified view, and exclusively interacts with it. Required when using multiple views.

    placement (String, optional)

    Default: 'top-left'

    Widget position within the view relative to the map container. Valid options are top-left, top-right, bottom-left, bottom-right, or fill.

    label (String, optional)

    Tooltip message displayed while hovering a mouse over the widget.

    Default: 'Compass'

    transitionDuration (Number, optional)

    Default: 200

    Bearing and pitch reset transition duration in milliseconds.

    style (Object, optional)

    Default: {}

    Additional CSS styles for the canvas.

    className (String, optional)

    Default: undefined

    Class name to attach to the widget element. The element has the default class name of deck-widget deck-compass-widget.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/widgets/fullscreen-widget.html b/docs/api-reference/widgets/fullscreen-widget.html index 01e9e0d39ae..b46f3b88d3a 100644 --- a/docs/api-reference/widgets/fullscreen-widget.html +++ b/docs/api-reference/widgets/fullscreen-widget.html @@ -4,13 +4,13 @@ FullscreenWidget | deck.gl - - + +

    FullscreenWidget

    This widget enlarges deck.gl to fill the full screen. Click the widget to enter or exit full screen.

    Props

    id (String)

    Default: 'fullscreen'

    Unique identifier of the widget.

    placement (String, optional)

    Default: 'top-left'

    Widget position within the view relative to the map container. Valid options are top-left, top-right, bottom-left, bottom-right, or fill.

    container (HTMLElement, optional)

    Default: undefined

    A compatible DOM element which should be made full screen. By default, the map container element will be made full screen.

    enterLabel (String, optional)

    Tooltip message displayed while hovering a mouse over the widget when out of fullscreen.

    Default: 'Enter Fullscreen'

    exitLabel (String, optional)

    Tooltip message displayed while hovering a mouse over the widget when fullscreen.

    Default: 'Exit Fullscreen'

    style (Object, optional)

    Default: {}

    Additional CSS styles for the canvas.

    className (String, optional)

    Default: undefined

    Class name to attach to the widget element. The element has the default class name of deck-widget deck-fullscreen-widget.

    - - + + \ No newline at end of file diff --git a/docs/api-reference/widgets/overview.html b/docs/api-reference/widgets/overview.html index d846697e76a..f39f1de7d59 100644 --- a/docs/api-reference/widgets/overview.html +++ b/docs/api-reference/widgets/overview.html @@ -4,13 +4,13 @@ @deck.gl/widgets | deck.gl - - + +

    @deck.gl/widgets

    Widgets are UI components around the WebGL2/WebGPU canvas to offer controls and information for a better user experience.

    This module contains the following widgets:

    Installation

    Install from NPM

    npm install deck.gl
    # or
    npm install @deck.gl/core @deck.gl/widgets
    import {FullscreenWidget} from '@deck.gl/widgets';
    import '@deck.gl/widgets/stylesheet.css';

    new FullscreenWidget({});

    Include the Standalone Bundle

    <script src="https://unpkg.com/deck.gl@^8.10.0/dist.min.js"></script>
    <link src="https://unpkg.com/deck.gl@^8.10.0/widgets/stylesheet.css" rel='stylesheet' />
    <!-- or -->
    <script src="https://unpkg.com/@deck.gl/core@^8.10.0/dist.min.js"></script>
    <script src="https://unpkg.com/@deck.gl/widgets@^8.10.0/dist.min.js"></script>
    <link src="https://unpkg.com/deck.gl@^8.10.0/widgets/stylesheet.css" rel='stylesheet' />
    new deck.FullscreenWidget({});

    CSS Theming

    Customizing the appearance of widgets can be achieved using CSS variables. This section provides guidance on how to theme widgets at different levels of specificity.

    Global Theming

    Apply to all widgets with the .deck-widget selector.

    .deck-widget {
    --button-size: 48px;
    }

    Note: While variables can be globally applied using the :root selector, ensuring their availability throughout the entire document, this method is not recommended. Applying variables globally can lead to naming conflicts, especially in larger projects or when integrating with other libraries.

    Type-specific Theming

    Theme a specific type of widget using the .deck-widget-[type] selector.

    .deck-widget-fullscreen {
    --button-size: 48px;
    }

    Instance-specific Theming

    Apply styles to a single instance of a widget using inline styles.

    new FullscreenWidget({ style: {'--button-size': '48px'}})

    Custom Class Theming

    Define a custom class with your desired styles and apply it to a widget.

    .my-class {
    --button-size: 48px;
    }
    new FullscreenWidget({ className: 'my-class'})

    Customizable CSS Variables

    We've provided a set of CSS variables to make styling UI Widgets more convenient. These variables allow for customization of widget sizes, colors, and other properties. Below is a comprehensive list of these variables, their expected types, and default values:

    Size

    NameTypeDefault
    --button-sizeDimension28px
    --button-border-radiusDimension8px
    --widget-marginDimension12px

    Color

    NameTypeDefault
    --button-backgroundColor#fff
    --button-strokeColorrgba(255, 255, 255, 0.3)
    --button-inner-strokeBorderunset
    --button-shadowBox Shadow0px 0px 8px 0px rgba(0, 0, 0, 0.25)
    --button-backdrop-filterBackdrop Filterunset
    --button-icon-idleColorrgba(97, 97, 102, 1)
    --button-icon-hoverColorrgba(24, 24, 26, 1)
    --icon-compass-north-colorColor#F05C44
    --icon-compass-south-colorColor#C2C2CC

    Icon

    NameTypeDefault
    --icon-fullscreen-enterSVG Data UrlMaterial Symbol Fullscreen
    --icon-fullscreen-enterSVG Data UrlMaterial Symbol Fullscreen Exit
    --icon-zoom-inSVG Data UrlMaterial Symbol Add
    --icon-zoom-outSVG Data UrlMaterial Symbol Remove

    Replacing Icons

    Users can to customize icons to better align with their design preferences or branding. This section provides a step-by-step guide on how to replace and customize these icons.

    1. Prepare Your Icons:
    1. Icon Replacement:
    • Use CSS variables, such as --icon-fullscreen-enter, to replace the default icons with your customized ones.
    1. Color Customization:
    • The original color embedded in your SVG will be disregarded. However, it's crucial that the SVG isn't transparent.
    • Customize the color of your icon using the appropriate CSS variable, such as --button-icon-idle.

    Example:

    .deck-widget {
    --icon-fullscreen-enter: url('path_to_your_svg_icon.svg');
    --button-icon-idle: blue;
    }
    - - + + \ No newline at end of file diff --git a/docs/api-reference/widgets/zoom-widget.html b/docs/api-reference/widgets/zoom-widget.html index 5167b67758b..d8d5b1f7242 100644 --- a/docs/api-reference/widgets/zoom-widget.html +++ b/docs/api-reference/widgets/zoom-widget.html @@ -4,13 +4,13 @@ ZoomWidget | deck.gl - - + +

    ZoomWidget

    This widget controls the zoom level of a deck.gl view. Click '+' to zoom in by 1, click '-' to zoom out by 1. Supports controlling Map and Globe views.

    Props

    id (String)

    Default: 'zoom'

    Unique identifier of the widget.

    viewId (String, optional)

    Default: null

    The widget is attached to the view identified by this viewId. When assigned, the widget is placed within the specified view, and exclusively interacts with it. Required when using multiple views.

    placement (String, optional)

    Default: 'top-left'

    Widget position within the view relative to the map container. Valid options are top-left, top-right, bottom-left, bottom-right, or fill.

    orientation (String, optional)

    Default: 'vertical'

    Widget button orientation. Valid options are vertical or horizontal.

    container (HTMLElement, optional)

    Default: undefined

    A compatible DOM element which should be made full screen. By default, the map container element will be made full screen.

    zoomInLabel (String, optional)

    Tooltip message displayed while hovering a mouse over the zoom in button.

    Default: 'Zoom In'

    zoomOutLabel (String, optional)

    Tooltip message displayed while hovering a mouse over the zoom out button.

    Default: 'Zoom Out'

    transitionDuration (Number, optional)

    Default: 200

    Zoom transition duration in milliseconds.

    style (Object, optional)

    Default: {}

    Additional CSS styles for the canvas.

    className (String, optional)

    Default: undefined

    Class name to attach to the widget element. The element has the default class name of deck-widget deck-zoom-widget.

    - - + + \ No newline at end of file diff --git a/docs/contributing.html b/docs/contributing.html index 9bd6df326d9..3af385a84c6 100644 --- a/docs/contributing.html +++ b/docs/contributing.html @@ -4,8 +4,8 @@ Contributing to deck.gl | deck.gl - - + +
    @@ -13,7 +13,7 @@ We use yarn to manage the dependencies of deck.gl.

    git checkout master
    yarn bootstrap
    yarn test

    See additional instructions for Windows, Linux and Apple M1.

    Run the layer browser application:

    cd examples/layer-browser
    yarn
    yarn start-local

    If you consider opening a PR, here is some documentation to get you started:

    Testing examples with modified deck.gl source

    Each example can be run so that it is built against the deck.gl source code in this repo instead of building against the installed version of deck.gl. This enables using the examples to debug the main deck.gl library source.

    To do so use the yarn start-local command present in each example's directory. See webpack.config.local.js for details.

    Working with other vis.gl dependencies

    Deck.gl has a number of dependencies that fall under vis.gl, and there may be times when it is necessary to make a change in one of these. Thus for development it is necessary to checkout a copy of such a dependency and make local changes.

    When running an example using yarn start-local you can use local version of luma.gl or math.gl by appending the --env.local-luma or --env.local-math option.

    It is possible to test against the local source of other dependency libraries by modifying examples/vite.config.local.mjs.

    Community Governance

    vis.gl is part of the OpenJS Foundation. See the organization's Technical Charter.

    Technical Steering Committee

    deck.gl development is governed by the vis.gl Technical Steering Committee (TSC). Current members:

    Maintainers

    Maintainers of deck.gl have commit access to this GitHub repository, and take part in the decision making process.

    If you are interested in becoming a maintainer, read the governance guidelines.

    The vis.gl TSC meets monthly and publishes meeting notes via a mailing list. This mailing list can also be utilized to reach out to the TSC.

    Code of Conduct

    Please be mindful of and adhere to the Linux Foundation's Code of Conduct when contributing to deck.gl.

    Troubleshooting

    Develop on Linux

    To run the test suite, you may need to install additional dependencies (verified on Ubuntu LTS):

    Verify that everything works by running yarn test.

    Develop on Windows

    It's possible to set up the dev environment in Windows Subsystem for Linux.

    To run the Node tests, you need to set up OpenGL support via X11 forwarding:

    • Install VcXsrv.

    • Run xlaunch.exe, choose multiple windows, display 0, start no client, disable native opengl, disable access control. reference

    • If working with WSL2, allow WSL to access your X server with firewall rules.

    • Set the DISPLAY environment variable:

      # WSL 1
      export DISPLAY=localhost:0
      # WSL 2
      export DISPLAY=$(grep -m 1 nameserver /etc/resolv.conf | awk '{print $2}'):0.0

    You can test that it is set up successfully with:

    sudo apt-get install mesa-utils
    glxgears

    You should see a window open with gears turning at this point.

    Follow instructions for developing on linux.

    Develop on MacOs on Apple Silicon (M1 chip)

    To install dependencies specify that you explicitly need the arm64 version

    arch -arm64 brew install pkg-config cairo pango libpng jpeg giflib librsvg

    You also need a system-wide Python available (python). For example, it can be installed using Homebrew and then symlinked:

    brew install python
    sudo ln -s /opt/homebrew/bin/python3 /opt/homebrew/bin/python

    After this yarn bootstrap can be run with

    CPLUS_INCLUDE_PATH=/opt/homebrew/include yarn bootstrap
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/animations-and-transitions.html b/docs/developer-guide/animations-and-transitions.html index f9fcb49e3c4..937d6c2d1c7 100644 --- a/docs/developer-guide/animations-and-transitions.html +++ b/docs/developer-guide/animations-and-transitions.html @@ -4,13 +4,13 @@ Animations and Transitions | deck.gl - - + +

    Animations and Transitions

    This document was recently added and is still being finalized

    deck.gl provides several ways to implement animation and transitions.

    • Camera Transitions - (aka View State Transitions) when changing the view state, deck.gl can move the camera smoothly between the initial and final view state.
    • Layer Transitions - (aka Attribute Transitions)
    • Property Animation -

    Animation

    Drawing Constantly vs. When Needed

    While some 3D applications such as games often keep drawing to screen at a high frame rate, deck.gl avoids this by default. When not animating, deck.gl is optimized to only render to the screen when something changes (a layer's data or props, the viewState etc). This keeps the GPU and CPU load low and minimizes power consumption.

    However when animating properties, deck.gl needs to update the screen frequently. This does consume more power and can cause fans to spin up etc. However, even when animating deck.gl does not draw to the screen when the application's browser tab is not active.

    Property Animation

    Layer properties are divided into two categories. Accessors (that control "attributes" and only update when data changes or update triggers fire) and non-accessors that update every time the layer is rendered.

    Property animation refers to assigning functions as values to non-accessor layer props. The functions will be called every render frame, potentially generating new values every frame at 60 FPS.

    Advantages of Property Animation

    While it is certainly possible to implement deck.gl animation by supplying a "freshly minted" list of layers to the deck.gl component every frame, e.g. using Deck.setProps({layers: [new ...Layer(...), ...]}), this approach has a performance penalty as both your application logic and deck.gl's layer matching system must kick into gear each render frame.

    By setting property animation functions, properties will be evaluated by the underlying render loop system with considerably less overhead, both deck.gl and your application will essentially remain undisturbed as the layer properties are updated inside a tight inner animation loop.

    Transitions

    Transitions in deck.gl are short animations that are triggered when deck.gl detects a change of some property. Instead of immediately redrawing based on the new view value, deck.gl draws a number of frames, automatically interpolating the value over time.

    View State Transitions

    View state transitions provide smooth and visually appealing camera transitions when view states change. View state transitions are initiated by updating the Deck.viewState prop.

    Following fields of viewState can be used to achieve viewport transitions.

    • transitionDuration (Number, optional, default: 0) - Transition duration in milliseconds, default value 0, implies no transition.
    • transitionEasing (Function, optional, default: t => t) - Easing function that can be used to achieve effects like "Ease-In-Cubic", "Ease-Out-Cubic", etc. Default value performs Linear easing. (list of sample easing functions: http://easings.net/)
    • transitionInterpolator (Object, optional, default: LinearInterpolator) - An interpolator object that defines the transition behavior between two viewports, deck.gl provides LinearInterpolator and FlyToInterpolator. Default value, LinearInterpolator, performs linear interpolation on ViewState fields. FlyToInterpolator animates ViewStates similar to MapBox flyTo API and applicable for MapState, this is pretty useful when camera center changes by long distance. But a user can provide any custom implementation for this object using TransitionInterpolator base class.
    • transitionInterruption (TRANSITION_EVENTS (Number), optional, default: BREAK) - This field controls how to process a new ViewState change that occurs while performing an existing transition. This field has no impact once transition is complete. Here is the list of all possible values with resulting behavior.
    TRANSITION_EVENTSResult
    BREAKCurrent transition will stop at the current state and next ViewState update is processed.
    SNAP_TO_ENDCurrent transition will skip remaining transition steps and ViewState is updated to final value, transition is stopped and next ViewState update is processed.
    IGNOREAny ViewState update is ignored until current transition is complete, this also includes ViewState changes due to user interaction.
    • onTransitionStart (Functional, optional) - Callback fires when requested transition starts.
    • onTransitionInterrupt (Functional, optional) - Callback fires when transition is interrupted.
    • onTransitionEnd (Functional, optional) - Callback fires when transition ends.

    TransitionInterpolators

    • LinearInterpolator - Performs linear interpolation between two ViewStates.
    • FlyToInterpolator - This class is designed to perform flyTo style interpolation between two MapState objects.
    • TransitionInterpolator - Base interpolator class that provides common functionality required to interpolate between two ViewState props. This class can be subclassed to implement any custom interpolation:

    Examples

    Sample code that provides flyTo style transition to move camera from current location to NewYork city.

    class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
    viewState: {
    latitude: 37.7751,
    longitude: -122.4193,
    zoom: 11,
    bearing: 0,
    pitch: 0,
    width: 500,
    height: 500
    }
    };
    this._onViewStateChange = this._onViewStateChange.bind(this);
    }

    _goToNYC() {
    this.setState({
    viewState: {
    ...this.state.viewState,
    longitude: -74.1,
    latitude: 40.7,
    zoom: 14,
    pitch: 0,
    bearing: 0,
    transitionDuration: 8000,
    transitionInterpolator: new FlyToInterpolator()
    }
    });
    }

    _onViewStateChange({viewState}) {
    this.setState({viewState});
    }

    render() {
    const {viewState} = this.state;

    return (
    <div>
    <DeckGL
    viewState={viewState}
    controller={MapController}
    onViewStateChange={this._onViewStateChange}
    >
    <StaticMap
    // props
    ...
    />
    </DeckGL>

    <button onClick={this._goToNYC}>New York City</button>
    </div>
    );
    }
    }

    Sample code to get continuous rotations along vertical axis until user interrupts by rotating the map by mouse interaction. It uses LinearInterpolator and restricts transitions for bearing prop. Continuous transitions are achieved by triggering new transitions using onTransitionEnd callback.

    const transitionInterpolator = new LinearInterpolator(['bearing']);

    const INITIAL_VIEW_STATE = {
    // set to required initial view state
    ...
    };

    class App extends Component {
    constructor(props) {
    super(props);
    this.rotationStep = 0;
    this.state = {
    viewState: INITIAL_VIEW_STATE
    };

    this._onLoad = this._onLoad.bind(this);
    this._onViewStateChange = this._onViewStateChange.bind(this);
    this._rotateCamera = this._rotateCamera.bind(this);
    }

    _onLoad() {
    this._rotateCamera();
    }

    _onViewStateChange({viewState}) {
    this.setState({viewState});
    }

    _rotateCamera() {
    // change bearing by 120 degrees.
    const bearing = this.state.viewState.bearing + 120;
    this.setState({
    viewState: {
    ...this.state.viewState,
    bearing,
    transitionDuration: 1000,
    transitionInterpolator,
    onTransitionEnd: this._rotateCamera
    }
    });
    }

    _renderLayers() {
    // render any deck.gl layers
    ...
    }

    render() {
    const {viewState} = this.state;
    return (
    <DeckGL
    layers={this._renderLayers()}
    viewState={viewState}
    onLoad={this._onLoad}
    onViewStateChange={this._onViewStateChange}
    controller={true}
    >
    <StaticMap
    // props
    ...
    />
    </DeckGL>
    );
    }
    }
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/base-maps/using-with-arcgis.html b/docs/developer-guide/base-maps/using-with-arcgis.html index ed31e815072..72c44cecc96 100644 --- a/docs/developer-guide/base-maps/using-with-arcgis.html +++ b/docs/developer-guide/base-maps/using-with-arcgis.html @@ -4,13 +4,13 @@ Using with ArcGIS | deck.gl - - + +

    Using with ArcGIS

    Pure JSReactOverlaidInterleaved
    example

    Starting with v8.1, deck.gl has support for ArcGIS with the @deck.gl/arcgis module.

    deck.gl as a ArcGIS map layer

    2D integration with MapView is supported by the DeckLayer class, see pure JS example.

    3D integration with SceneView is experimental: see the DeckRenderer class.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/base-maps/using-with-google-maps.html b/docs/developer-guide/base-maps/using-with-google-maps.html index a12947c5056..632f84b6811 100644 --- a/docs/developer-guide/base-maps/using-with-google-maps.html +++ b/docs/developer-guide/base-maps/using-with-google-maps.html @@ -4,13 +4,13 @@ Using with Google Maps Platform | deck.gl - - + +

    Using with Google Maps Platform

    Pure JSReactOverlaidInterleaved
    exampleexample

    deck.gl as a Google Maps overlay

    Deck.gl has interleaved and overlaid support for Google Maps with the @deck.gl/google-maps module. It allows you to construct a Deck instance and apply it to a map using the Maps JavaScript API.

    See Google Maps documentation](/docs/api-reference/google-maps/overview) page for a full list of features.

    Google Maps Platform API key

    Note that to use deck.gl with the Google's basemap, you must load the Maps JavaScript API using a valid API key. For more information on getting an API key, see the Google Maps Platform API key documentation for the Maps JavaScript API.

    Using interleaved

    Starting with v8.6, deck.gl added interleaving support on Google's vector map, using the Maps JavaScript API WebGLOverlayView class.

    When a Deck instance is applied to the map, deck.gl detects whether it is an instance of the vector map, then automatically enables interleaving. For information on how to enable the Google's vector map for the web, see the Maps JavaScript API documentation.

    By default, when a Deck instance is added to the map, deck.gl will detect if the map is an instance of the vector map and enable interleaved mode. If the vector map is not detected or the user's device does not support WebGL2, deck.gl will automatically fallback to overlaid mode.

    Using overlaid

    Starting with v7.0, deck.gl added support to overlay visualizations on Google's raster map using the Maps JavaScript API OverlayView class.

    In this mode, the Deck canvas can only be used as a overlay on top of Google Maps, see pure JS example, and 3D features like tilt, rotation, and interleaving are not supported.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/base-maps/using-with-mapbox.html b/docs/developer-guide/base-maps/using-with-mapbox.html index 28b29bcb529..3b33c71e4f8 100644 --- a/docs/developer-guide/base-maps/using-with-mapbox.html +++ b/docs/developer-guide/base-maps/using-with-mapbox.html @@ -4,13 +4,13 @@ Using with Mapbox | deck.gl - - + +

    Using with Mapbox

    Pure JSReactOverlaidInterleaved
    exampleexample

    deck.gl interleaved with Mapbox layers

    Mapbox GL JS is a powerful open-source map renderer from Mapbox. deck.gl's MapView is designed to sync perfectly with the camera of Mapbox, at every zoom level and rotation angle.

    When using deck.gl and Mapbox, there are three options you can choose from:

    1. All deck.gl environments support deep integration with Mapbox features using the @deck.gl/mapbox module. This is recommended approach as it supports interleaved and overlaid rendering, as well as Mapbox controls and plugins. See Inserting deck.gl into the Mapbox container.
    2. The deck.gl React API supports an additional configuration when you just need a map backdrop and prefer to use the Deck API for interactivity. See Inserting Mapbox into the deck.gl container.
    3. Finally, deck.gl offers out-of-the-box integration with Mapbox when using the Scripting API.

    Inserting deck.gl into the Mapbox container

    import Map, {useControl} from 'react-map-gl';
    import { MapboxOverlay } from '@deck.gl/mapbox';

    function DeckGLOverlay(props) {
    const overlay = useControl(() => new MapboxOverlay(props));
    overlay.setProps(props);
    return null;
    }

    <Map
    initialViewState={{
    latitude: 40,
    longitude: -74.5,
    zoom: 12
    }}
    >
    <DeckGLOverlay interleaved={true}/>
    </Map>

    If you want to use features of mapbox-gl, such as controls like NavigationControl or plugins, then need to insert Deck into the Mapbox map container using MapboxOverlay from the @deck.gl/mapbox module, which allows you to construct a Deck instance and apply it to a map using the IControl API. In this configuration mapbox-gl handles all user input, holds the source of truth of the camera state, and is the root HTML element of your map.

    There are two renderers to pick from, overlaid or interleaved.

    Overlaid

    If want to use the base map as a backdrop, the recommended approach is to use the Deck canvas as a overlay on top of the Mapbox map using MapboxOverlay in its default mode (overlaid, which corresponds to interleaved: false). The react get-started example and pure js get-started example illustrates this pattern.

    Interleaved

    If you also need to mix deck.gl layers with base map layers, e.g. having deck.gl surfaces below text labels or objects occluding each other correctly in 3D, then you have to use deck.gl layers interleaved with Mapbox layers in the same WebGL2 context. In addition to using MapboxOverlay to insert Deck into the map container, you have to use interleaved mode (interleaved: true). Be cautious that this feature subjects to bugs and limitations of mapbox-gl's custom layer interface, and is only compatible with WebGL2 (See interleaved renderer compatibility). The pure js gallery example illustrates this pattern.

    Inserting Mapbox into the deck.gl container

    import DeckGL from '@deck.gl/react';
    import Map from 'react-map-gl';

    <DeckGL
    initialViewState={{
    latitude: 40,
    longitude: -74.5,
    zoom: 12
    }}
    >
    <Map/>
    </DeckGL>

    If you're using deck.gl in a React environment and just need a map backdrop, then you may use Deck as the root HTML element with its canvas as an overlay on top of the child Mapbox map. The Minimap example illustrates the basic pattern. This is a well tested and robust use case with respect to Deck's functionality, as you can find it in most of the layer examples on this website. You can't use all the features of mapbox-gl like controls (e.g. NavigationControl) and plugins, but you can instead use @deck.gl/widgets.

    Note: This usage is not supported in the Pure JS environment.

    react-map-gl

    react-map-gl is a React wrapper around mapbox-gl. If you'd like to use deck.gl with React, this component is the recommended companion.

    All the examples on this website are implemented using the React integration.

    When you choose the react-map-gl Map React component as the root component, using MapboxOverlay with react-map-gl useControl works especially well to insert perfectly synchronized deck.gl layers in the map container.

    When you choose the DeckGL React component as the root component, react-map-gl Map as a child automatically interprets the deck.gl view state (i.e. latitude, longitude, zoom etc). In this configuration your deck.gl layers will still render as a synchronized geospatial overlay over the underlying map.

    Using DeckGL as the root component is not compatible with react-map-gl controls (NavigationControl, GeolocateControl etc.) because of react-map-gl decisions to prioritize its own maintainability, performance, and compatibility when used standalone.

    Using Mapbox basemap service (with Mapbox token)

    The mapbox-gl library is a popular commercial basemap with a free tier. To use Mapbox, you will need to register on their website in order to retrieve an access token required by the map component, which will be used to identify you and start serving up map tiles. The service will be free until a certain level of traffic is exceeded.

    If you are using mapbox-gl without React, check out Mapbox GL JS API for how to apply the token.

    If you are using react-map-gl, there are several ways to provide a token to your app:

    • Set the MapboxAccessToken environment variable. You may need to add additional set up to the bundler (example) so that process.env.MapboxAccessToken is accessible at runtime.
    • Provide it in the URL, e.g ?access_token=TOKEN
    • Pass it as a prop to the react-map-gl Map instance <Map mapboxAccessToken={TOKEN} />

    Compatibility with Mapbox GL JS forks

    As of v2.0, Mapbox GL JS went proprietary and requires a Mapbox account to use even if you don't load tiles from the Mapbox data service. Community forks of the v1 code base such as MapLibre GL JS can generally be used as a drop-in replacement of mapbox-gl. If you are using react-map-gl, see their Get Started guide for more details.

    We provide get-started examples with Maplibre GL JS for pure js and react, and an interleaved rendering example in our gallery.

    If the forked libraries and Mapbox API diverge in the future, compatibility issues may arise. deck.gl intends to support open source efforts wherever reasonable. Please report any issue on GitHub.

    Using with other basemap services

    It is possible to use the map component without the Mapbox service, you need a URL that conforms to the Mapbox Style Specification and pass it to the mapStyle prop in mapbox-gl Map constructor or react-map-gl Map component.

    You can use existing free vector tile services:

    Hosting your own basemap service

    If you host your own map tiles, you will need a custom Mapbox GL style that points to your own vector tile source, this custom style must match the schema of your tile source.

    Open source tile schemas include:

    Some useful resources for creating your own map service:

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/binary-data.html b/docs/developer-guide/binary-data.html index 510b95556c0..89953b7898b 100644 --- a/docs/developer-guide/binary-data.html +++ b/docs/developer-guide/binary-data.html @@ -4,13 +4,13 @@ Using Binary Data | deck.gl - - + +

    Using Binary Data

    Binary data support in deck.gl is actively being developed. This article provides information on current state and some hints about what may come.

    Binary Data

    If you plan to work with binary data, you will want to make sure you are up to speed on JavaScript typed arrays as well as GPU buffers, both in terms of general concepts as well as a basic grasp of the API.

    JavaScript has a number of different ways to represent binary data (Browser Blob, Node.js Buffers, base64 etc), however deck.gl primarily accepts typed arrays. deck.gl should accept GPU buffers (luma.gl Buffer instances).

    CPU vs GPU memory

    Ultimately all deck.gl rendering is done on the GPU, and all memory must be available to the GPU by being "uploaded" into GPU memory Buffers. By pre-creating GPU buffers and passing these to deck.gl layers you exercise the maximum amount of control of memory management.

    import {Buffer} from 'luma.gl';
    const buffer = new Buffer(gl, {data: });

    Note that GPU buffers have many advanced features. They can be interleaved etc. The luma.gl Accessor class lets you describe how GPU Buffers should be accessed.

    Endianness

    In most cases, when working with binary data, care must be taken to properly define and respect "endianness" which essentially describes the order of bytes when larger numbers are stored in memory. However, essentially all of the current web is little endian, so potential big-endian issues are ignored for now.

    Flattened vs. Nested Data

    Binary data is flat, whereas JavaScript Arrays can have structure

    Interleaved Data

    Binary data can be interleaved. Working directly with interleaved data requires working with luma.gl Buffer instances and attribute accessor objects and is considered an advanced topic.

    // lon1, lat1, radius1, red1, green1, blue1, lon2, lat2, ...
    const binaryData = new Float32Array([-122.4, 37.78, 1000, 255, 200, 0, -122.41, 37.775, 500, 200, 0, 0, -122.39, 37.8, 500, 0, 40, 200]);

    Binary Table Formats

    deck.gl layers are designed to accept "tables" of data as input (the data prop). Tables can be organized in several different ways. For binary data you will be working with columnar tables.

    Row-Based Tables (non-Binary)

    Row-based tables are the most common and generally the easiest to work with (each row is typically a JavaScript object with fields representing the values of various columns at that row).

    new Layer({
    data: [
    {value: 1, time: 1.00},
    {value: 2, time: 1.10},
    ]
    })

    Columnar Tables

    Organizing values by column instead of row creates a columnar table. Columnar tables can be significantly more efficient. In particular, because each value is of the same type, columnar tables can be stored as binary data.

    To use a columnar table as layer data, provide a bundle of typed arrays (a "vector bundle"?) as your data prop:

    new Layer({
    data: {
    value: new Int32Array([1, 2]),
    time: new Float32Array([1.00, 1.10])
    }
    });

    Chunked Columnar Tables

    A disadvantage of columnar tables is that columns can get very long, blocking incremental reads/writes of tables and even exceeding platform's allocation limits.

    More advanced binary columnar table formats like Apache Arrow solves this by breaking logical arrays into chunks. An additional benefit of chunked arrays can support remarkably efficient data-frame operations (slicing/dicing and filtering multi-gigabyte data set with "zero cost").

    Another complication when using binary columnar tables is that it may not be possible to represent e.g. the lack of a value. In some libraries (e.g. Apache Arrow) this is solved through an additional null map.

    Thus, a downside of chunked arrays is that they are complex to work with that they typically require an API (such as Apache Arrow).

    Chunked Arrow Arrays follows a more complicated relationship with Vector instances representing chunks:

    Table ---* Column (Chunked) ---* Vector

    Note: These cannot currently be used in deck.gl without pre-concatenating the chunks.

    There is an RFC (chunked-data-rfc) that would enable chunked data tables (data frames) to be directly consumed by deck.gl (and then sliced and diced at zero cost).

    Using Binary Data

    It is sometimes desirable for applications to work directly with binary data and to be able to pass such binary data directly to layers. The motivation is often performance-related but it could just be that the application is able to load data directly in a binary format.

    • Using typed arrays as layer input data - Using The input data is in binary form, perhaps it is delivered this way from the back-end, and it would be preferable to not have to unpack it.
    • Using typed arrays or GPU buffers directly as layer attributes - The input data is already formatted in the memory format expected by the GPU and deck.gl's shaders.

    Using Binary Data directly in GPU

    The simplest way to supply binary data to deck.gl layers is to override normal attribute calculation and feed in a binary typed array to be used directly as the attribute.

    This requires that the binary data columns are formatted in exactly the way that the layer expects. This is often fairly straight forward for fixed primitive layers but not often practical for variable primitive layers, as the number of vertices per primitive depends on the details of the tesselation algorithm which can be hard for the data provided to anticipate.

    Using Binary Data to Calculate Attributes in GPU/GLSL

    This would mean passing binary data into the vertex shader and there use it to calculate the values the layer needs (colors, elevations etc). This use case would involve writing custom accessor functions. It is currently not directly supported in deck.gl, but could be achieved by creating a custom layer.

    There are RFCs (glsl accessors, texture attributes) that if implemented, would dramatically improve deck.gl's ability to use provided binary data attributes without pre-processing them in JavaScript.

    Use Binary Data to Generate Attributes in CPU/JavaScript

    JavaScript iteration approaches for binary data bundles are under development for v7

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/building-apps.html b/docs/developer-guide/building-apps.html index 77aaec6d908..2249eb4e8f6 100644 --- a/docs/developer-guide/building-apps.html +++ b/docs/developer-guide/building-apps.html @@ -4,13 +4,13 @@ Building Apps | deck.gl - - + +

    Building Apps

    This article contains additional information on options for how to build deck.gl.

    Optimizing for Bundle Size

    deck.gl and luma.gl provide a lot of functionality and the amount of code these libraries contain will of course impact the size of your application bundle and your startup load time.

    There are multiple techniques used in JavaScript.

    Choosing an entry point

    When installed from npm, deck.gl and related libraries come with two separate distributions.

    DirectorymainFieldDescription
    dist/es5mainAll code is transpiled to be compatible with the most commonly adopted evergreen browsers (see below). Exports/imports are transpiled into commonjs requires. The main reason to use this distribution is under Node.js (e.g. unit tests), or if your bundler does not support tree-shaking using import/export.
    dist/esmmoduleSame as dist/es5, except export and import statements are left untranspiled to enable tree shaking.

    You will have to check the documentation of your particular bundler to see what configuration options are available. Webpack picks module main field over main if it is available. You can also explicitly choose one distribution by specifying a resolve.mainFields array.

    The transpilation target is set to >0.2%, maintained node versions, not ie 11, not dead, not chrome 49 resolved by browserslist. To support older or less common browsers, you may use @babel/preset-ev in your babel settings and include node_modules.

    About Tree-Shaking

    deck.gl was designed from the start to leverage tree-shaking. This technique has been talked about for quite some time but has been slow in actually providing the expected benefits. With the combination of webpack 4 and babel 7 we are finally starting to see significant results, so you may want to experiment with upgrading your bundler if you are not getting results.

    Note that tree-shaking still has limitations:

    • At least in webpack, tree shaking is done by the uglifier, which is typically only run on production builds, so it is typically not possible to assess the benefits of tree shaking during development. In addition, this makes it even harder to make statements about bundle size impact from looking at bundle sizes in development builds. The recommendation is to always measure impact on your final production builds.
    • Static dependency analyzers err on the side of safety and will still include any symbol it is not sure will never be used.
    • This is compounded by the fact that there are side effects in various language feature that complicate or defeat current static dependency analysis techniques, causing "dead code" to still be bundled. The good news is that the analyzers are getting better.
    • Naturally, an application that uses all the functionality offered by the library will benefit little from tree shaking, whereas a small app that only uses a few layers should expect bigger savings.

    Bundle Size Numbers

    So, what bundle size impact should you expect? When do you know if you have set up your bundler optimally. To help answer these questions, we provide some numbers you can compare against. deck.gl has scripts that measure the size of a minified bundle after each build, which allows us to provide comparison numbers between releases.

    Entry point8.5 Bundle (Compressed)8.4 Bundle (Compressed)Comments
    esm398 KB (115 KB)485 KB (128 KB)Transpiled, tree-shaking enabled
    es5686 KB (178 KB)812 KB (197 KB)Transpiled, no tree-shaking

    Notes:

    • Numbers represent the bundle size of a minimal application, bundled with Webpack 4, which means that the untranspiled and the ESM distribution results benefit from some tree shaking.
    • The number in parenthesis is the compressed bundle size. This is how much bigger you might expect your gzipped bundle to get by adding deck.gl as a dependency to your application.

    Future Work

    This is not the final word on deck.gl bundle size. More work is being done to reduce the size of deck.gl and we are confident that even as future releases will have more functionality, we will be able to keep the library code from growing and, more importantly, make deck.gl even more "tree shakeable", with the intention that apps should only "pay for what they use".

    Remarks

    • Optimizing for minified code - Due to inclusion of sourcemaps etc, the bundle size impact of deck.gl tends to look more significant in development builds than in the final production builds. While reducing the size of the development libraries is also desirable, the current goal is to ensure the impact of adding deck.gl on the final, minified/uglified application bundle is as small as possible.
    • Compressed bundle sizes are calculated using gzip -9. Consider using slower brotli compression for static assets, it typically provides an additional 20% reduction.
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/controllers.html b/docs/developer-guide/controllers.html index c8bc7484e33..a65e1859341 100644 --- a/docs/developer-guide/controllers.html +++ b/docs/developer-guide/controllers.html @@ -4,13 +4,13 @@ Controllers | deck.gl - - + +

    Controllers

    This page is a placeholder

    deck.gl supports several models of event handling and viewport controls

    Viewport Controls

    States

    ...

    Customizing Controls

    About Event Handling

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/coordinate-systems.html b/docs/developer-guide/coordinate-systems.html index 97c12173aab..751cd822b51 100644 --- a/docs/developer-guide/coordinate-systems.html +++ b/docs/developer-guide/coordinate-systems.html @@ -4,13 +4,13 @@ Coordinate Systems | deck.gl - - + +

    Coordinate Systems

    In most deck.gl layers, every data object is expected to contain one or more positions (e.g. the center of a point, or the start and end of an arc, the vertices of a polygon, etc). Positions are expected to be supplied as two or three element arrays ([x, y] or [x, y, z]). Objects can also have dimensions (e.g. the radius of a circle, the width of a path, etc), most of which are specified as a single number. Positions and dimensions are used to construct a 3D world with your data.

    deck.gl supports a selection of coordinate systems, addressing diverse geospatial and non-geospatial use cases. Each layer can set its own coordinateSystem prop to specify how its positions should be interpreted. Layers using different coordinate systems can be composed together, which is very useful when dealing with datasets from different sources.

    Many layers also provide props for defining the units that dimensions are measured in, usually named as *Units. A layer can leverage such props to control its appearance in a way that makes the most sense for the data and the desired user experience.

    import {COORDINATE_SYSTEM} from '@deck.gl/core';
    import {PointCloudLayer} from '@deck.gl/layers';

    new PointCloudLayer({
    coordinateSystem: COORDINATE_SYSTEM.METER_OFFSETS,
    coordinateOrigin: [-122.4004935, 37.7900486, 0], // anchor point in longitude/latitude/altitude
    data: [
    {position: [33.22, 109.87, 1.455]}, // meter offsets from the coordinate origin
    ...
    ],
    radiusPixels: 2,
    sizeUnits: 'pixels'
    })

    Concepts

    Throughout this document you will find reference to the following coordinate spaces in deck.gl's projection system:

    World space

    The natural coordinate system of a dataset. It is usually determined by the source of the data, like the device it is generated on, and the format that it is stored as on disk or a cloud data warehouse.

    Some examples of different world space definitions include a Shapefile with any standard geospatial reference; WGS84 as used by GeoJSON or KML; GPS traces; LIDAR scans; info-vis values that do not map to real-world dimensions; Slippy Map tiles from services like OpenStreetMaps and Mapbox; 3D tiling standards such as Cesium 3D Tiles and Esri I3S.

    Positions in different world spaces come with different scales and orientations, may be measured relative to static or dynamic reference points, and in many cases their scales are not linear. It is common for an application to overlay multiple datasets from different world spaces into the same 3D view.

    Common space

    To correctly compose data from various world spaces together, deck.gl transforms them into common space - a unified, intermediate 3D space that is a right-handed Cartesian coordinate system. Once positions are in the common space, it is safe to add, substract, rotate, scale and extrude them as 3D vectors using standard linear algebra. This is the basis of all geometry processing in deck.gl layers.

    The transformation between the world space and the common space is referred to in deck.gl documentation as "project" (world space to common space) and "unproject" (common space to world space), a process controlled by both the specification of the world space, such as WGS84, and the projection mode, such as Web Mercator. Projections are implemented as part of deck.gl's core.

    Screen space

    A top-left coordinate system that runs from [0, 0] to [viewportWidth, viewportHeight], measured in pixels.

    For a given dataset, positions in the common space normally do not change with user interaction, while their appearance in screen space can be frequently changing as the user pans, zooms and rotates the camera.

    Positions

    Each layer is expected to specify its coordinateSystem prop to match the world space of its data. Within the data supplied to a single layer, all positions will be interpreted in the same coordinate system.

    By default, a layer's coordinateSystem is assumed to be COORDINATE_SYSTEM.LNGLAT if rendered in a geospatial view (e.g. MapView, GlobeView) and COORDINATE_SYSTEM.CARTESIAN if rendered in a non-geospatial view (e.g. OrbitView, OrthographicView).

    Some coordinate systems need to be used with the coordinateOrigin prop, which specifies where the positions are measured from.

    Supported coordinate systems

    Coordinate systemPositionsCoordinate originNotes
    COORDINATE_SYSTEM.LNGLAT[longitude, latitude, altitude]ignoredLongitude and latitude are specified as WGS84 coordinates in degrees from Greenwich meridian / equator respectively, and altitude is specified in meters above sea level.
    COORDINATE_SYSTEM.METER_OFFSETS[Δx, Δy, Δz][longitude, latitude, altitude]Positions are given in meter offsets from a reference geo-location that is specified by coordinateOrigin. The x axis points map east, the y axis points map north, and z points up. Only works with geospatial views.
    COORDINATE_SYSTEM.LNGLAT_OFFSETS[Δlongitude, Δlatitude, Δaltitude][longitude, latitude, altitude]Positions are given in degree offsets from a reference geo-location that is specified by coordinateOrigin. Only works with geospatial views.
    COORDINATE_SYSTEM.CARTESIAN[x, y, z][x, y, z] (optional, default [0, 0, 0])A linear system that measures equally on all 3 axes.

    Remarks:

    • Although Universal Transverse Mercator uses similar notions as the METER_OFFSETS mode, be aware that the deck.gl offset system does not have the sophistication of the UTM spec and should not be used interchangeably. See the limitations section for details.
    • The CARTESIAN mode describes positions that are identical in the world space and the common space. It is the default coordinate system when rendering into non-geospatial views. When combined with geospatial views, the positions are treated as common space coordinates for that particular projection mode. The latter can be seen used by the MVTLayer, where the data decoded from the tiles are already pre-projected onto the Web Mercator plane.

    Limitations of the offset systems

    Most cartographic projections, including the Web Mercator projection, are non-linear. The METER_OFFSETS and LNGLAT_OFFSETS coordinate systems trade accuracy for performance by approximating the projection with a linearized local projection system. When working on local scales, such as small cities, using meter offsets gives a very high degree of precision. When visualizing data on large scales, such as countries and continents, projection will only be correct if you use the LNGLAT mode.

    Transforming positions

    Generally speaking, converting data from one coordinate system to another on the CPU is costly and should be avoided, especially when dealing with spherical coordinates. Whether your data comes in longitude/latitude or meter offsets, the best choice is to just configure any deck.gl layers displaying that data to use the corresponding coordinateSystem. When dealing with data that come from different coordinate systems, the recommended approach is to render them on separate layers, for each you may specify a coordinate system respectively.

    Raw data do not always align cleanly with one of the provided coordinate systems. Here are some examples:

    • Instead of meters, offsets and dimensions may come in millimeters, feet or miles.
    • Instead of x aligning with map east and y aligning with map north, the offsets may be measured by a device with dynamic orientation. This is common in use cases such as a LIDAR scanner mounted on a moving vehicle.

    Again, converting raw data to match the coordinate system expectations can be very expensive if done on the CPU. This should be avoided whenever possible.

    Instead, in addition to specifying coordinateSystem: COORDINATE_SYSTEM.METER_OFFSETS and coordinateOrigin, a layer could also specify the modelMatrix prop as a 4x4 transformation matrix. The math.gl library (a light wrapper of gl-matrix) can be used for this purpose, which is already a dependency of deck.gl.

    The modelMatrix prop is most useful with the METER_OFFSETS and CARTESIAN coordinate systems. It is usually the right solution for pre-processing (flipping, rotating, scaling etc) your data, since these operations will be done very performantly in the GPU. Note that these two coordinate systems are the only ones that are linear and uniform in all directions. Longitude and latitude based positions cannot be scaled/rotated/translated correctly with a 4x4 matrix.

    Dimensions

    Most deck.gl layers that deal with dimensions allow specifying the dimensions in one of the coordinate spaces, with props such as radiusUnits in ScatterplotLayer, sizeUnits in IconLayer, and widthUnits in PathLayer.

    Supported units

    meters

    The universal metric unit.

    Typically used when sizes should correspond with measurements in the physical world. For example, a PathLayer may draw the street network in a city from GeoJSON LineString features, and each path with width that are calculated from the number of lanes. Or an IconLayer may draw traffic signs that match their physical dimensions.

    Exactly how big one meter will appear after projection subjects to the projection mode used. One should be aware that all cartographic projections come with some sort of distortion, for example one meter is projected to different pixel sizes at different latitudes in a Mercator map.

    When used with non-geospatial views, this value does not have any tangible meaning and is treated as identical to common.

    common

    One unit in the common space. When zooming in and out, common sizes scale with the base map.

    When visualizing numeric values that do not have any cartographic meaning (e.g. population or income), layers often map them to the size of geometries (e.g. radius of circles). In this case, using common units may be preferrable as one common unit projects to the same size regardless of where it is on the map. It offers the visual consistency and comparability that meters lacks, especially when viewing data on a global scale.

    pixels

    One unit in the screen space. When zooming in and out, pixel sizes remain the same on screen.

    For example, PathLayer evaluates getWidth: 12, widthUnits: 'pixels' to the same size as a DOM block with the CSS rule width: 12px, regardless of the zoom level.

    This mode is typically used when legibility is important at all zoom levels, such as text labels.

    When pixel sizes are viewed from a perspective (e.g. MapView with pitch, FirstPersonView or OrbitView), the same size may appear bigger if the geometry is positioned closer to the camera, in order to preserve the sense of depth. In this case, one pixel at the focal point of the camera (usually the center of the viewport) is always rendered as one true CSS pixel.

    Transforming dimensions

    The most performant way to transform the dimensions for each object is to use an uniform multiplier. Most layers that deal with dimensions provide props such as radiusScale, widthScale, sizeScale etc. Check each layer's documentation for what's available.

    The conversion between meter sizes and common sizes depend on the projection mode:

    The conversion between common sizes and pixel sizes: 1 common unit equals 2 ** z pixel where z is the zoom of the current viewport.

    Comparison to Standard 3D Graphics Concepts

    If you are familiar with the traditional 3D graphics/game engine terminologies, here is how they map to deck.gl's coordinate spaces:

    • deck.gl's world space maps to the standard "model space", i.e. the data that comes in before any transforms have been applied.
    • deck.gl's common space plays the role of standard "world space", but there are a few important differences. To compensate for the lack of 64-bit floats in WebGL2/WebGPU, deck.gl may apply a dynamic translation to common-space positions, determined by the viewport, to improve the precision of projection.
    • Zoom levels are applied by scaling the view matrix with Math.pow(2, zoom).
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers.html b/docs/developer-guide/custom-layers.html index d88b8075fb0..0d07ee58bc5 100644 --- a/docs/developer-guide/custom-layers.html +++ b/docs/developer-guide/custom-layers.html @@ -4,8 +4,8 @@ Writing Your Own Layer | deck.gl - - + +
    @@ -15,7 +15,7 @@ your layer should offer.

    You also need to define the default values of the layer's properties.

    The most efficient method of doing this is to define a static defaultProps member on your layer class.

    AwesomeLayer.defaultProps = {
    color: [255, 0, 0],
    opacity: 0.5
    };

    Also consider the properties of the base Layer class, as well as any other inherited properties if you are deriving.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/attribute-management.html b/docs/developer-guide/custom-layers/attribute-management.html index 6fbb341908c..a46410e0e00 100644 --- a/docs/developer-guide/custom-layers/attribute-management.html +++ b/docs/developer-guide/custom-layers/attribute-management.html @@ -4,14 +4,14 @@ Attribute Management | deck.gl - - + +

    Attribute Management

    Overview

    deck.gl layers' public API were designed to follow a Reactive programming paradigm.

    The challenge is that in the "reactive" model, every change to application state causes everything to be re-rendered. This is not an issue for UI rendering for general purpose apps, but for high performance, graphics intensive and sometime 3D contents to be rendered by the GPU, huge memory buffers (so called "vertex attributes", or just "attributes" for short) must be prepared and transferred to the GPUs before any draw calls got executed on the GPUs.

    GPU Performance Challenges

    Creating and transferring new GPU buffers before every draw call would result in unacceptable performance even for moderately complex models. Just like in React (which "renders" to the browser's slow-updating DOM), the challenge becomes to detect which part of the visualization is changed to limit both attributes recalculation and re-rendering to the minimum.

    Since the length of attributes are usually proportional of to the number of data elements being visualized (hundreds of thousands or even multiple millions of elements are not uncommon in big data visualizations), efficient attribute updates is critical.

    deck.gl alleviates the burden of layer developers by providing an AttributeManager class to manage the lifecycle of those GPU attributes. Note that it is completely possible for a layer to use custom code to manage attribute updates, however most layers rely on the AttributeManager class to handle GPU buffer management for them.

    Automatic Attribute Generation

    Automated attribute generation and management is suitable when a set of vertex shader attributes are generated by iteration over a data array, and updates to these attributes are needed either when the data itself changes, or when other data relevant to the calculations change.

    • First the application registers descriptions of its dynamic vertex attributes using AttributeManager.add().
    • Then, when any change that affects attributes is detected by the application, the app will call AttributeManager.invalidate().
    • Finally before it renders, it calls AttributeManager.update() to ensure that attributes are automatically rebuilt if anything has been invalidated.

    The application provided update functions describe how attributes should be updated from a data array and are expected to traverse that data array (or iterable) and fill in the attribute's typed array.

    Note that the attribute manager intentionally does not do advanced change detection, but instead makes it easy to build such detection by offering the ability to "invalidate" each attribute separately.

    Accessors, Shallow Comparisons and updateTriggers

    The layer will expect each object to provide a number of "attributes" that it can use to set the GL buffers. By default, the layer will look for these attributes to be available as fields directly on the objects during iteration over the supplied data set. To gain more control of attribute access and/or to do on-the-fly calculation of attributes.

    Note: A layer only renders when a property change is detected. For performance reasons, property change detection uses shallow compare, which means that mutating an element inside a buffer or a mutable data array does not register as a property change, and thus does not trigger a re-render.

    To force trigger a render after mutating buffers, simply increment the renderCount property. To force trigger a buffer update after mutating data, increment the updateCount property.

    Advanced Topics

    Manual Buffer Management

    While most apps rely on their layers to automatically generate appropriate GPU buffers from their props, it is possible for applications to take control of buffer generation and supply the buffers as properties.

    While this allows for ultimate performance and control of updates, as well as potential sharing of buffers between layers, the application will need to generate attributes in exactly the format that the layer shaders expect, creating a strong coupling between the application and the layer.

    Note: The application can provide some buffers and let others be managed by the layer. As an example management of the instancePickingColors buffer is normally left to the layer.

    More information

    Introduction to Vertex Attributes

    deck.gl layers use WebGL2/WebGPU to render visualization elements. In this programming model, all geometry elements are made of a set of vertices, and each vertex has multiple attributes to determine how it will be rendered to the screen. These attributes are called vertex attributes and are provided by users using JavaScript typed arrays (e.g. Float32Array or Uint8Array).

    During rendering, these vertex attributes will become available in vertex shaders executing on the GPU.

    Part of designing a new layer is creating an elegant mapping from a set of data properties in JavaScript to a set of GPU vertex attributes, and then implementing the code that generates the typed arrays that represent the geometry so that GPU calls can be performed efficiently later when drawing the layer.

    Introduction to Instanced Vertex Attributes

    Even for GPU-accelerated rendering, setting up draw calls and dispatching them to the GPU can quickly become a performance bottleneck for visualizing big data. Therefore, each deck.gl layer aspires to use as few GPU draw calls as possible to draw everything contained in the data.

    Here the Instanced Rendering comes into play. While some vertex attributes will still describe the geometry of each object (or instance), other vertex attributes will describe what is different between each object or instance. The latter kind of attributes are called instanced attributes.

    Learning More

    While you can certainly start consulting detailed WebGL2/WebGPU resources to learn more about vertex attributes, be aware that many available resources can get quite technical, involving more concepts than you may need at this point.

    If you are new to these concepts, we have found that a great way to learn more is simply to copy an existing deck.gl layer and start extending/modifying its functionality.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/composite-layers.html b/docs/developer-guide/custom-layers/composite-layers.html index c610c297e61..a1aac696ffe 100644 --- a/docs/developer-guide/custom-layers/composite-layers.html +++ b/docs/developer-guide/custom-layers/composite-layers.html @@ -4,14 +4,14 @@ Composite Layers | deck.gl - - + +

    Composite Layers

    A composite layer is a special kind of layer that creates other layers. It enables the creation of new layers by careful composition of existing layers (a primary example being the GeoJsonLayer). In addition, it is often convenient to change the interface and behavior of an existing layer using a composite "adaptor" layer instead of modifying the layer itself (the sample S2Layer is a simple adaptor on top of the PolygonLayer).

    Use Cases

    Adaptor Layers

    Sometimes an existing layer renders the right thing, but it would be desirable that it accepts another data format, had another interface (different accessors), or performed aggregation on its data.

    Examples could be:

    • A LASPointCloudLayer that accepts data as an URL pointing to a LAS file, and convert it to the format that PointCloudLayer consumes.
    • A TopoJSONLayer that is like the GeoJsonLayer, but accepts TopoJSON provided to the data prop.
    • Adding aggregation to an existing layer. By default, deck.gl layers render one graphical element for each element in the data prop. But in some cases, e.g. heatmaps, the data needs to be aggregated (or "binned") into cells before rendering. An adaptor in the form of a composite layer is one way to add this functionality.

    The deck.gl layers TextLayer, HexagonLayer, CPUGridLayer and few others are written as composite "adapter" layers.

    Collection Layers

    Often a more complex visualization is composited from a number of layers that use a common set of props. For example:

    • A NodeLayer that renders a text string inside a circle at each anchor position, by combining the ScatterplotLayer and the TextLayer.
    • A MapLayer that takes a custom map data format, breaks it down to sets of geometries by type, and render them with the PathLayer, SolidPolygonLayer, and TextLayer respectively.

    Creating a collection layer have the following advantages:

    • Collect the complex code that handles a specific data format or visual configuration into one class. This helps to create a cleaner, more abstract interface for the users of this layer, and control the complexity of the component that renders the Deck instance.
    • Improve memory usage by sharing the same objects/buffers cross layers. Instead of each sublayer loading and storing their own copy of the raw data, the composite layer will manage the data source and pass it down to several layers.

    The deck.gl layers GeoJsonLayer and PolygonLayer are written as composite "collection" layers.

    Implementing A Composite Layer

    Consider the following example: we need a layer that is like the IconLayer, but renders a text label alongside each icon.

    A composite layer can be created by extending the CompositeLayer class:

    import {CompositeLayer, IconLayer, TextLayer} from 'deck.gl';

    class LabeledIconLayer extends CompositeLayer {
    // TODO
    }
    LabeledIconLayer.layerName = 'LabeledIconLayer';

    Defining Composite Layer Properties

    We will need to define the layer-specific properties of the new layer. In this example, the new layer's interface is a combination of that of the IconLayer and the TextLayer:

    LabeledIconLayer.defaultProps = {
    // Shared accessors
    getPosition: {type: 'accessor', value: x => x.position},
    // Icon properties
    iconAtlas: null,
    iconMapping: {type: 'object', value: {}, async: true},
    // Icon accessors
    getIcon: {type: 'accessor', value: x => x.icon},
    getIconSize: {type: 'accessor', value: 20},
    getIconColor: {type: 'accessor', value: [0, 0, 0, 255]},
    // Text properties
    fontFamily: DEFAULT_FONT_FAMILY,
    fontWeight: DEFAULT_FONT_WEIGHT,
    // Text accessors
    getText: {type: 'accessor', value: x => x.text},
    getTextSize: {type: 'accessor', value: 12}
    getTextColor: {type: 'accessor', value: [0, 0, 0, 255]}
    }

    Rendering Sublayers

    A composite layer should implement the renderLayers() method and return an array of layers ("sublayers").

    In this example, the idea is to draw an IconLayer and a TextLayer, which share the same source data:

    class LabeledIconLayer extends CompositeLayer {
    renderLayers() {
    return [
    // the icons
    new IconLayer({
    data: this.props.data,
    // TODO
    }),
    // the labels
    new TextLayer({
    data: this.props.data,
    // TODO
    })
    ];
    }
    }

    Mapping Properties

    Because the composite layer doesn't draw directly to the canvas, it controls the rendering result by setting props of its sublayers.

    Since the sublayers do not understand our custom layer's prop names, we will need to map the props of the LabeledIconLayer to the appropriate props of each sublayer:

    class LabeledIconLayer extends CompositeLayer {
    renderLayers() {
    return [
    // the icons
    new IconLayer({
    id: `${this.props.id}-icon`,
    data: this.props.data,

    iconAtlas: this.props.iconAtlas,
    iconMapping: this.props.iconMapping,

    getPosition: this.props.getPosition,
    getIcon: this.props.getIcon,
    getSize: this.props.getIconSize,
    getColor: this.props.getIconColor
    }),
    // the labels
    new TextLayer({
    id: `${this.props.id}-label`,
    data: this.props.data,

    fontFamily: this.props.fontFamily,
    fontWeight: this.props.fontWeight,

    getPosition: this.props.getPosition,
    getText: this.props.getText,
    getSize: this.props.getTextSize
    getColor: this.props.getTextColor
    })
    ];
    }
    }

    Something that needs special attention is that all layer ids must be unique, no matter whether they are nested inside other layers. This means the sublayer ids must be generated dynamically based on the id of their parent, otherwise when there are multiple instances of LabeledIconLayers their sublayer ids will collide.

    Finally, to make updateTriggers work when accessors need to be recalculated, we need to remap the user's updateTriggers from the parent layer's prop names to the sublayers' prop names.

    class LabeledIconLayer extends CompositeLayer {
    renderLayers() {
    return [
    // the icons
    new IconLayer({
    ...
    updateTriggers: {
    getPosition: this.props.updateTriggers.getPosition,
    getIcon: this.props.updateTriggers.getIcon,
    getSize: this.props.updateTriggers.getIconSize,
    getColor: this.props.updateTriggers.getIconColor
    }
    }),
    // the labels
    new TextLayer({
    ...
    updateTriggers: {
    getPosition: this.props.updateTriggers.getPosition,
    getText: this.props.updateTriggers.getText,
    getSize: this.props.updateTriggers.getTextSize,
    getColor: this.props.updateTriggers.getTextColor
    }
    })
    ];
    }
    }

    Forwarding Properties

    There are a number of base Layer class props that are usually expected to propagate down to all sublayers, such as pickable, visible, coordinateSystem and opacity. It is desirable to just forward many of these props directly to the sublayers.

    There is a method compositeLayer.getSubLayerProps that handles a lot of these common compliance chore that were mentioned above. When calling it with a list of prop values that we care about, the list gets wrapped/populated with additional props that will help the sublayers align with deck.gl norms.

    The complete code looks like follows:

    class LabeledIconLayer extends CompositeLayer {
    renderLayers() {
    return [
    // the icons
    new IconLayer(this.getSubLayerProps({
    // `getSubLayerProps` will concat the parent layer id with this id
    id: 'icon',
    data: this.props.data,

    iconAtlas: this.props.iconAtlas,
    iconMapping: this.props.iconMapping,

    getPosition: this.props.getPosition,
    getIcon: this.props.getIcon,
    getSize: this.props.getIconSize,
    getColor: this.props.getIconColor,

    updateTriggers: {
    getPosition: this.props.updateTriggers.getPosition,
    getIcon: this.props.updateTriggers.getIcon,
    getSize: this.props.updateTriggers.getIconSize,
    getColor: this.props.updateTriggers.getIconColor
    }
    })),
    // the labels
    new TextLayer(this.getSubLayerProps({
    // `getSubLayerProps` will concat the parent layer id with this id
    id: 'id',
    data: this.props.data,

    fontFamily: this.props.fontFamily,
    fontWeight: this.props.fontWeight,

    getPosition: this.props.getPosition,
    getText: this.props.getText,
    getSize: this.props.getTextSize
    getColor: this.props.getTextColor,

    updateTriggers: {
    getPosition: this.props.updateTriggers.getPosition,
    getText: this.props.updateTriggers.getText,
    getSize: this.props.updateTriggers.getTextSize,
    getColor: this.props.updateTriggers.getTextColor
    }
    }))
    ];
    }
    }

    Picking

    By default, the composite layer passes the picking info from its sublayers as-is to the callbacks. However, when we implement an adaptor layer that performs data conversion or aggregation, the data that the sublayer sees may not be the same data that the user passed in.

    In this case, The composite layer may intercept the event info and modify it by implementing the getPickingInfo() method:

    class AwesomeCompositeLayer extends CompositeLayer {

    ...

    getPickingInfo({info, sourceLayer}) {
    // override info.object
    return info;
    }

    }

    For more details, read about how picking works.

    Transforming Data

    Because deck.gl's primitive layers expect input to be a flat iteratorable data structure, some composite layers need to transform user data into a different format before passing to sublayers. This transformation may consist converting a tree to an array, filtering, sorting, etc. For example, the GeoJsonLayer splits features by type and passes each to ScatterplotLayer, PathLayer or SolidPolygonLayer respectively. The TextLayer breaks each text string down to multiple characters and render them with a variation of IconLayer.

    From the user's perspective, when they specify accessors such as getColor, or callbacks such as onHover, the functions should always interface with the original data that they give the top-level layer, instead of its internal implementations. For the sublayer to reference back to the original data, we can add a reference onto every transformed datum by calling getSubLayerRow:

    class MyCompositeLayer extends CompositeLayer {
    updateState({props, changeFlags}) {
    if (changeFlags.dataChanged) {
    // data to pass to the sublayer
    const subLayerData = [];
    /*
    * input data format:
    [
    {position: [-122.45, 37.78], timestamps: [0, 1, 4, 7, 8]},
    {position: [-122.43, 38.01], timestamps: [2, 4]},
    ...
    ]
    * data format to pass to sublayer:
    [
    {timestamp: 0},
    {timestamp: 1},
    {timestamp: 4},
    {timestamp: 7},
    ...
    ]
    */
    props.data.forEach((object, index) => {
    for (const timestamp of object.timestamps) {
    // `getSubLayerRow` decorates each data row for the sub layer with a reference to the original object and index
    subLayerData.push(this.getSubLayerRow({
    timestamp
    }, object, index));
    }
    });

    this.setState({subLayerData});
    }
    }
    }

    When the sublayer receives data decorated by getSubLayerRow, its accessors need to know how to read the data to access the original objects. In the above example, getPosition: d => d.position would fail if called with {timestamp: 0}, while the user expects it to be called with {position: [-122.45, 37.78], timestamps: [0, 1, 4, 7, 8]}. This can be solved by wrapping the user-provided accessor with getSubLayerAccessor:

      renderLayers() {
    const {subLayerData} = this.state;
    const {getPosition, getRadius, getFillColor, getLineColor, getLineWidth, updateTriggers} = this.props;

    return new ScatterplotLayer(props, this.getSubLayerProps({
    id: 'scatterplot',
    updateTriggers,

    data: this.state.subLayerData,
    getPosition: this.getSubLayerAccessor(getPosition),
    getRadius: this.getSubLayerAccessor(getRadius),
    getFillColor: this.getSubLayerAccessor(getFillColor),
    getLineColor: this.getSubLayerAccessor(getLineColor),
    getLineWidth: this.getSubLayerAccessor(getLineWidth)
    }));
    }

    The default implementations of lifecycle methods such as getPickingInfo also understand how to retrieve the original objects from the sublayer data if they are created using getSubLayerRow.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/layer-attributes.html b/docs/developer-guide/custom-layers/layer-attributes.html index 4e25df88a46..e072cfa6494 100644 --- a/docs/developer-guide/custom-layers/layer-attributes.html +++ b/docs/developer-guide/custom-layers/layer-attributes.html @@ -4,13 +4,13 @@ Layer Attributes | deck.gl - - + +

    Layer Attributes

    This section explains how the data in deck.gl layers are mapped to and accessed by the GPU during rendering.

    Overview

    A central concept of deck.gl is that every Layer accepts a "table of data" (through the data prop) and maps into visual elements that are then rendered efficiently on the GPU.

    For purposes of GPU computation, there are two separate types of layers and two types of attributes. We'll use the following terminology:

    Geometric Attribute per rowDescriptive Attribute per row
    Shared-Primitive LayerN/A (Use shared primitive)1 value (instance) per row
    Variable-Primitive LayerVariable # of vertices (Ni)Ni duplicate values per row

    Fixed vs Variable Primitive Layers

    • Fixed Primitive Layer - (Sometimes called instanced layers). These layers map each data row to a fixed primitive (set of vertices). Because of this simple mapping, these layers can naturally use instanced rendering, in the sense that the unique attributes for each row (instance) can be described by a single value in an instanced attribute array.

    • Variable Primitive Layer - (Sometimes called tesselated layers). These layers require custom primitive for each row in the data table. The process of generating a custom primitive is referred to as tesselation, and requires extra work during generation. In this case it is not possible to use instancing to represent the unique attributes

    Examples of fixed primitive layers are CircleLayer, PointCloudLayer, LineLayer etc.

    Examples of variable primitive layers are PathLayer, PolygonLayer etc.

    Remarks:

    • The primitive in a fixed primitive layer can be arbitrarily complex (from a single triangle, through more complex primitives like an extruded hexagon, to an entire mesh or scenegraph loaded from e.g. a glTF file). As the glTF example hints at, there can even be multiple primitives per table row (in multi-model layers). The defining characteristic is just that the primitive(s) are identical for each row.
    • As mentioned, Fixed primitive layers are sometimes called instanced layers, however the term is not precise as it is possible for a tesselated/variable primitive layer to use instanced rendering (e.g. the PathLayer currently does this as a performance micro-optimization to reduce the amount of custom geometry generated during tesselation). This use of instancing is not related to efficiently storing the unique values for each table row.

    Geometric vs Descriptive Attributes

    Geometric Attributes

    Positions, Normals, Tangents, Co-Tangents etc.

    For fixed primitive layers, these attributes are all pre-defined as part of the Layer's reference primitive.

    For variable primitive layers, these attributes are normally all generated as a result of the tesselation process, and it is normal to have a unique value for each of these attributes in each vertex.

    Descriptive Attributes

    Descriptive Attributes are used to share (non-geometrical) attributes (colors, ...) related to the data in each table row.

    The big difference between the two layer types is how descriptive attributes are handled.

    For fixed primitive layers the standard setup is very simple: each descriptive attribute is an instanced attribute, with one value for each table row.

    For variable primitive layers there are two options:

    2) Copy each descriptive attribute N times (N being the number of vertices generated for that row during tesselation). This is the method that is used in deck.gl today.

    3) Add a single rowIndex attribute and copy the same index N times as above. In this approach, descriptive values could then be read from textures where they are stored a single time. This provides flexibility at the price of performance (texture access latency) and complexity (working with data in textures).

    Remarks:

    • In tesselated layers it is of course possible to use the fact that each vertex has a unique value for each descriptive attribute value to achieve certain effects. One could for instance make a custom PathLayer that defines a gradient of colors along the path. This technique tends to get harder to use for layers that tesselate triangles in 2D or 3D as the order of vertices is less predictable. Also, if indices are generated in this phase, in which case extra care must be taken since some vertices can be repeated in the geometry. Because of these complications, this is not a promoted customization technique for layers.
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/layer-extensions.html b/docs/developer-guide/custom-layers/layer-extensions.html index 3623f8776e9..0e347fecfb3 100644 --- a/docs/developer-guide/custom-layers/layer-extensions.html +++ b/docs/developer-guide/custom-layers/layer-extensions.html @@ -4,13 +4,13 @@ Creating Layer Extensions | deck.gl - - + +

    Creating Layer Extensions

    It's recommended that you read subclassing layers before proceeding

    Sometimes we need to modify several deck.gl layers to add similar functionalities. If we create custom layer classes for each one of them, it will require multiple files that contain more or less the same code. Layer extension is a way to generalize, reuse, and share subclassed layer code.

    Example: Subclassing Is Not Enough

    Consider a hypothetical use case: in a ScatterplotLayer, we inject a piece of custom code into the fragment shader to highlight every object that is red.

    import {ScatterplotLayer} from '@deck.gl/layers';

    class FilteredScatterplotLayer extends ScatterplotLayer {
    getShaders() {
    return {
    ...super.getShaders(),
    inject: {
    // Declare custom uniform
    'fs:#decl': 'uniform bool highlightRed;',
    // Standard injection hook - see "Writing Shaders"
    'fs:DECKGL_FILTER_COLOR': `
    if (highlightRed) {
    if (color.r / max(color.g, 0.001) > 2. && color.r / max(color.b, 0.001) > 2.) {
    // is red
    color = vec4(1.0, 0.0, 0.0, 1.0);
    } else {
    discard;
    }
    }
    `
    }
    };
    }

    updateState({props, oldProps, changeFlags}) {
    super.updateState({props, oldProps, changeFlags});

    if (props.highlightRed !== oldProps.highlightRed) {
    // Set the custom uniform
    this.state.model.setUniforms({
    highlightRed: props.highlightRed
    });
    }
    }
    }

    new FilteredScatterplotLayer({...});

    If we want to do the same for GeoJsonLayer, it becomes more complicated. We will need to subclass all of ScatterplotLayer, PathLayer and SolidPolygonLayer, then tell the GeoJsonLayer to use our custom classes:

    import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers';

    class FilteredScatterplotLayer extends ScatterplotLayer {
    // same code
    }
    class FilteredPathLayer extends PathLayer {
    // same code
    }
    class FilteredSolidPolygonLayer extends SolidPolygonLayer {
    // same code
    }

    new GeoJsonLayer({
    ...
    _subLayerProps: {
    points: {type: FilteredScatterplotLayer},
    linestrings: {type: FilteredPathLayer},
    'polygons-stroke': {type: FilteredPathLayer},
    'polygons-fill': {type: FilteredSolidPolygonLayer}
    }
    });

    We end up with copying and pasting a lot of code.

    The same functionality can be achieved by creating a layer extension. When we give an extension to a composite layer such as GeoJsonLayer, it's automatically passed down to all its sublayers, including ScatterplotLayer, PathLayer and SolidPolygonLayer.

    import {LayerExtension} from '@deck.gl/core';

    class RedFilter extends LayerExtension {
    // TODO - This is our reusable code
    }

    new GeoJsonLayer({
    ...
    extensions: [new RedFilter()]
    });

    Now we can implement the red filter once and only once in the custom extension, and use it everywhere!

    LayerExtension Interface

    Constructor

    class RedFilter extends LayerExtension {}

    const extension = new RedFilter({color: [1, 1, 0]});
    console.log(extension.opts);

    The base layer extension constructor optionally takes one argument opts and stores it in this.opts. This object will be accessible to lifecycle methods via extension.opts. Additional properties can also be attached to the extension instance in the constructor for future use.

    Note that if two extension instances are of the same class and have the same opts object, they are considered equal during layer updates. Creating a new extension instance with different options can potentially lead to the layers that use this extension to recompile their shaders, which may be an expensive operation. opts is generally only used for options that require shader updates.

    Methods

    When a layer extension is used, it injects itself into a layer. This means that you can implement most of the layer lifecycle methods as part of the extension, and they will be executed in addition to the layer's own.

    getShaders

    Called to retrieve the additional shader parameters. Returns an object that will be merged with the layer's own getShaders result before sending to luma.gl's shader assembly. See writing shaders for deck.gl-specific modules and hooks.

    When this method is executed, this points to the layer.

    Receives one argument:

    • extension - the source extension instance.
    initializeState

    Called after the layer's own initializeState.

    When this method is executed, this points to the layer.

    Arguments:

    • context - same context object passed to layer.initializeState.
    • extension - the source extension instance.
    updateState

    Called after the layer's own updateState.

    When this method is executed, this points to the layer.

    Arguments:

    • params - same object passed to layer.updateState.
    • extension - the source extension instance.
    draw

    Called before the layer's own draw.

    When this method is executed, this points to the layer.

    Arguments:

    • params - same object passed to layer.draw.
    • extension - the source extension instance.
    finalizeState

    Called after the layer's own finalizeState.

    When this method is executed, this points to the layer.

    Arguments:

    • extension - the source extension instance.
    getSubLayerProps

    Called by composite layers to retrieve the additional props that should be passed to its sublayers. Normally, a composite layer only passes through props that it recognizes. If an extension adds new props to a layer, then it is responsible of collecting these props by implementing this method.

    Arguments:

    • extension - the source extension instance.

    Example: Layer Extension

    Back to our example use case. We can implement the red filter with the following code that works with all deck.gl layers:

    import {LayerExtension} from '@deck.gl/core';

    class RedFilter extends LayerExtension {
    getShaders() {
    return {
    inject: {
    // Declare custom uniform
    'fs:#decl': 'uniform bool highlightRed;',
    // Standard injection hook - see "Writing Shaders"
    'fs:DECKGL_FILTER_COLOR': `
    if (highlightRed) {
    if (color.r / max(color.g, 0.001) > 2. && color.r / max(color.b, 0.001) > 2.) {
    // is red
    color = vec4(1.0, 0.0, 0.0, 1.0);
    } else {
    discard;
    }
    }
    `
    }
    };
    }

    updateState(params) {
    const {highlightRed = true} = params.props;
    for (const model of this.getModels()) {
    model.setUniforms({highlightRed});
    }
    }

    getSubLayerProps() {
    const {highlightRed = true} = params.props;
    return {
    highlightRed
    };
    }
    }

    new GeoJsonLayer({
    ...
    extensions: [new RedFilter()]
    });

    This example is on codepen.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/layer-lifecycle.html b/docs/developer-guide/custom-layers/layer-lifecycle.html index 100cb7dfa26..c9d62fdef56 100644 --- a/docs/developer-guide/custom-layers/layer-lifecycle.html +++ b/docs/developer-guide/custom-layers/layer-lifecycle.html @@ -4,8 +4,8 @@ Layer Lifecycle | deck.gl - - + +
    @@ -75,7 +75,7 @@ the old layers' state objects to any new matched layers.

    Note: the data prop, attribute props and the viewport context are central to deck.gl layers and get special handling. React is more generic and leaves the interpretation of most props to the component.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/picking.html b/docs/developer-guide/custom-layers/picking.html index 133218bba3f..0291074ad30 100644 --- a/docs/developer-guide/custom-layers/picking.html +++ b/docs/developer-guide/custom-layers/picking.html @@ -4,15 +4,15 @@ Picking | deck.gl - - + +

    Picking

    Make sure you have read Interactivity before reading this section.

    How It Works

    The Color Picking Technique

    Rather than doing traditional ray-casting or building octrees etc in JavaScript, deck.gl implements picking on the GPU using a technique we refer to as "color picking". When deck.gl needs to determine what is under the mouse (e.g. when the user moves or clicks the pointer over the deck.gl canvas), all pickable layers are rendered into an off-screen buffer, but in a special mode activated by a GLSL uniform. In this mode, the shaders of the core layers render picking colors instead of their normal visual colors.

    Each object in each layer gets its own picking color assigned. The picking color is determined using layer.encodePickingColor() that converts the index of a object of a given layer into a 3-byte color array (the color buffer allows us to distinguish between 16M unique colors per layer, and between 256 different layers).

    After the picking buffer is rendered, deck.gl looks at the color of the pixel under the pointer, and decodes it back to the index number using layer.decodePickingColor().

    Event Propagation

    Once an object is picked, deck.gl creates a picking info object that describes what is under the pointer.

    The layer.getPickingInfo() method is called first on the layer that directly rendered the picked object, to modify or add additional fields to the info.

    The info object is then passed to the getPickingInfo() of its parent layer, and then its grandparent, and so on. This is so that composite layers can further augment the info object after it is processed by the picked sublayer. This allows the composite layer to hide implementation details and expose only user-friendly information.

    When the processing chain is over, the event is invoked on the top-level layer. This means that only the top-level layer's on<Event> callbacks are invoked, and the final picking info's layer field will point to the top-level layer. The idea is that the user should only interface with the layer that they created, and not having to know the underlying implementation.

    When an event fires, the callback functions are executed in the following order:

    • layer.on<Event> (default implementation invokes this.props.on<Event>)
    • layer.props.on<Event> (only if the layer method is not defined)
    • deck.props.on<Event>

    If any of the callback functions return true, the event is marked handled and the rest of the callbacks will be skipped.

    Default Handling of Pointer Events

    Whenever the pointer moves over the canvas, deck.gl performs a new picking pass, yielding a picking info object describing the result. This object is used for multiple purposes:

    • The onHover callbacks are called with it
    • To update the picked layer if autoHighlight is enabled
    • Saved for later use

    When other gestures (click, drag, etc.) are detected, deck.gl does not repeat picking. Instead, their callbacks are called with the last picked info from hover.

    Implementing Custom Picking

    While deck.gl allows applications to implement picking however they want, special support is provided for the built-in "picking color" based picking system, which most layers use.

    To take full control of picking, a layer need to take the following steps:

    Creating A Picking Color Attribute

    Add an attribute for each vertex using the layer's AttributeManager:

    import GL from '@luma.gl/constants';

    class MyLayer extends Layer {
    initializeState() {
    this.state.attributeManager.add({
    customPickingColors: {
    size: 3,
    type: GL.UNSIGNED_BYTE,
    update: this.calculatePickingColors
    }
    });
    }
    }

    Populate the attribute by providing a different picking color for every object that you need to differentiate. The default implementation of layer.encodePickingColor() and layer.decodePickingColor() is likely sufficient, but you may need to implement your own pair.

    class MyLayer extends Layer {

    ...

    calculatePickingColors(attribute) {
    const {data} = this.props;
    const {value} = attribute;

    let i = 0;
    for (const object of data) {
    const pickingColor = this.encodePickingColor(i);
    value[i * 3] = pickingColor[0];
    value[i * 3 + 1] = pickingColor[1];
    value[i * 3 + 2] = pickingColor[2];
    i++;
    }
    }
    }

    By default, the object field of the picking info object is indexed from the layer's data prop. Custom layers often need to define on their own terms what constitutes meaningful information to the user's callbacks. A layer can achieve this by overriding layer.getPickingInfo() to add or modify fields to the info object.

    Model object creation

    If your layer creates its own Model object, add picking module to modules array.

    import {Model} from '@luma.gl/core';
    import {picking} from '@deck.gl/core';

    new Model(gl, {
    ...
    vs: CUSTOM_VS,
    fs: CUSTOM_FS,
    modules: [picking]
    });

    Implementing Picking in Custom Shaders

    All core layers (including composite layers) support picking using luma.gl's picking module. If you are using custom shaders with any of the core layers or building custom layers with your own shaders, the following steps are needed to enable picking:

    Vertex Shader

    Vertex shader should set current picking color using picking_setPickingColor method provided by picking shader module.

    attribute vec3 customPickingColors;

    void main(void) {
    ...

    picking_setPickingColor(customPickingColors);
    }

    Fragment Shader

    Fragment shader should use picking_filterPickingColor to update gl_FragColor, which outputs picking color if it is the picking pass.

    void main(void) {
    ...

    // Should be the last Fragment shader instruction that updates gl_FragColor
    gl_FragColor = picking_filterPickingColor(gl_FragColor);
    }

    For more details refer to luma.gl's Picking Module.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/primitive-layers.html b/docs/developer-guide/custom-layers/primitive-layers.html index e40e9a4d6ac..1c641caa1ea 100644 --- a/docs/developer-guide/custom-layers/primitive-layers.html +++ b/docs/developer-guide/custom-layers/primitive-layers.html @@ -4,13 +4,13 @@ Primitive Layers | deck.gl - - + +

    Primitive Layers

    If you want to draw something completely different and you are comfortable around WebGL2/WebGPU shaders, you may consider implementing a new layer by directly extending the Layer class.

    Implementing the Layer Lifecycle Functions

    To describe how a layer's properties relate to shader attributes and uniforms you need to implement the layer's lifecycle functions.

    Initializing Layer

    initializeState() - This is the one method that you must implement to create any GPU resources you need for rendering your layer.

    Creating The Model

    A layer should create its model during this phase. A model is a luma.gl Model instance that defines what will be drawn to the WebGL2/WebGPU context.

    Most layers are Single-model layers - this is the predominant form among all core layers that deck.gl currently provides. In these layers, a single geometry model is created for each layer and saved to state.model during initialization. The default implementation of the rest of the lifecycle methods will then look for this model for rendering and picking etc., meaning that you don't have to do anything more to get a working layer.

    import {Layer} from '@deck.gl/core';

    export default class CubeLayer extends Layer {

    initializeState() {
    const {gl} = this.context;
    this.setState({
    model: this._getModel(gl)
    });
    }

    _getModel(gl) {
    // TODO: create Model here
    }

    }

    A choice to make is whether your GPU primitives (draw calls) should be instanced, or use dynamic geometry:

    • Instanced layer - This type of layer renders the same geometry many times. Usually the simplest way to go when creating a layer that renders a lot of similar objects (think ScatterplotLayer, ArcLayers etc).
    import {Model, CubeGeometry} from '@luma.gl/core';

    export default class CubeLayer extends Layer {
    ...
    _getModel(gl) {
    return new Model(gl, Object.assign({}, this.getShaders(), {
    id: this.props.id,
    geometry: new CubeGeometry(),
    isInstanced: true
    }));
    }
    }
    • Dynamic geometry layer - This is needed when dealing with data that needs to be rendered using multiple similar but unique geometries, such as polygons (i.e. the geometries are not copies of each other that that only differ in terms of parameters).
    import {Model, Geometry} from '@luma.gl/core';

    export default class MyLayer extends Layer {
    ...
    _getModel(gl) {
    return new Model(gl, Object.assign({}, this.getShaders(), {
    id: this.props.id,
    geometry: new Geometry({
    id: this.props.id,
    topology: 'line-list',
    }),
    vertexCount: 0,
    isIndexed: true
    });
    }
    }

    It is sometimes desirable to have a single layer render using multiple geometry primitives (e.g both circles and lines, or triangles and textured meshes etc), rather than creating separate layers. The custom AxesLayer example uses this technique to share attributes between grids and labels.

    Defining Attributes

    A layer should also define its attributes during initialization. This allows the attribute manager to do the heavy lifting for Attribute Management.

    Define attributes by calling attributeManager.add:

    initializeState() {
    const {gl} = this.context;
    this.setState({
    model: this._getModel(gl)
    });

    this.state.attributeManager.add({
    /* this attribute is automatically filled by the return value of `props.getPosition` */
    instancePositions: {size: 3, accessor: 'getPosition'},
    /* this attribute is populated by calling `layer.calculateInstanceColors` */
    instanceColors: {size: 4, type: GL.UNSIGNED_BYTE, accessor: 'getColor', update: this.calculateInstanceColors}
    });
    }

    Handling property updates

    updateState() - This is the method that you may want to implement to handle property changes.

    The key to writing good, performant deck.gl layers lies in understanding how to minimize updates of any calculated data, such as GPU buffers.

    The ideas used here are very similar to (and directly inspired by) those used in the React/Redux/Flux/Immutable.js communities, and learning more about those frameworks can be helpful as a way to get a better understanding of how to use these concepts in the best way.

    • data - Typically if a layer is re-rendered with a changed data prop, all GPU attributes must be regenerated and the layer needs to be redrawn. The default is to do exactly that, but sometimes a layer can be smarter and limit updates, or more work needs to be done.

    • If the viewport has changed, the layer will automatically be re-rendered. Many layers can thus ignore viewport changes, however, if the layer has any dependencies on the viewport (such as a layer that calculates extents or positions in screen space rather than world space) it would need to update state or uniforms whenever the viewport changes.

    • If other props change, it would typically mean that the layer needs to update some uniform or state so that rendering is affected appropriately.

    Rendering Layer

    draw() - If you want to use custom uniforms or settings when drawing, you would typically implement the draw method and pass those to your render call. Note that draw is called with viewport uniforms that you need to pass to your shader, but you can of course add any layer specific uniforms to that.

    Note: the reason that the supplied uniforms need to be passed on to your shaders is to enable your shader to use deck.gl's GLSL shaderlibs (such as project or project64 etc.). If you don't use these shaderlibs, you would obviously not need to supply these uniforms, but you would have to implement features like cartographic projection etc. on your own.

    Destroying Layer

    finalizeState() - If implemented, this method is called when your layer state is discarded. This is a good time to destroy non-shared GPU resources directly, rather than waiting for the garbage collector to do it.

    Handling Coordinate Systems

    While you have the freedom to create any type of layer you want, with any type of coordinate system that suits your application, a common characteristic of the layers provided by deck.gl is that they work seamlessly as map overlays, both with positions specified as longitude and latitude coordinates, as well as with positions specified in meters.

    Making Shaders Work with deck.gl's Coordinate Systems

    By supplying the modules: ['project'] parameter when you create your layer's luma.gl Model you get access to deck.gl's family of GLSL projection methods that support all three deck.gl projection modes: latlon (default), meters and neutral.

    By always using the following shader functions for handling projections and scaling, a single layer class can support all projection modes for free:

    • All positions must be passed through the project_position function (available both in JavaScript and GLSL) to convert non-linear web-mercator coordinates to linear mercator "world" or "pixel" coordinates, that can be passed to the projection matrix.

    • All offsets must be passed through the project_scale function (available both in JavaScript and GLSL) to convert distances to world coordinates. Note that that distance scales are latitude dependent under web mercator projection (see http://wiki.openstreetmap.org/wiki/Zoom_levels for more details), so scaling will depend on the viewport center and should only be expected to be locally correct.

    Implement Picking

    If your layer is instanced (data prop is an array and each element is rendered as one primitive), then you may take advantage of the default implementation of the layer picking methods.

    By default, each layer creates an instancePickingColors attribute and automatically calculates it using the length of the data array.

    For custom picking, read about Implementing Custom Picking.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/prop-types.html b/docs/developer-guide/custom-layers/prop-types.html index 6c0677703a7..7b24b5c8781 100644 --- a/docs/developer-guide/custom-layers/prop-types.html +++ b/docs/developer-guide/custom-layers/prop-types.html @@ -4,13 +4,13 @@ Property Types | deck.gl - - + +

    Property Types

    This article documents the system that deck.gl offers to provide extra type annotations for layer properties.

    A number of deck.gl features are enabled by rich descriptions of the types of the properties in a layer:

    • Asynchronous props (e.g. loading layer data from an URL)
    • Type checking (during development)
    • Improve render performance, see "Prop Types and Performance" section below
    • Transitions and Animation
    • Reflection (e.g. dynamically creating UI controls for layer props)

    Declaring Layer Properties

    A layer class may supply a static member defaultProps that defines its default property types and values:

    import {Layer} from 'deck.gl';

    class MyLayer extends Layer {
    // implementation
    }

    MyLayer.defaultProps = {
    texture: {type: 'object', value: null, async: true},
    strokeOpacity: {type: 'number', value: 1, min: 0, max: 1},
    strokeColor: {type: 'color', value: [255, 0, 0]},
    getRadius: {type: 'accessor', value: d => d.radius}
    };

    When the user construct this layer, the props are resolved as such:

    const layer = new MyLayer({id: 'my-layer', strokeOpacity: 0.5})
    /**
    layer.props:
    {
    texture: null,
    strokeOpacity: 0.5,
    strokeColor: [255, 0, 0],
    getRadius: d => d.radius,
    // other default base Layer props
    }
    */

    Property Types

    The property types system enables layers to opt-in to specifying types, and also allows a certain amount of type auto-deduction to happen based on existing default values for layers that do not opt in.

    Each prop in defaultProps may be an object in the following shape:

    • type (string, required)
    • value (any, required) - the default value if this prop is not supplied
    • async (boolean, optional) - if true, the prop can either be a Promise that resolves to its actual value, or an url string (loaded using the base Layer's fetch prop).
    • transform (function, optional) - transforms an asynchronously loaded value and returns a new form. Receives the following arguments:
      • value - the new value of this prop
      • propType - this prop type definition
      • layer - the owner of this prop
    • release (function, optional) - release a transformed value when it's no longer in use. Receives the following arguments:
      • value - the old value of this prop
      • propType - this prop type definition
      • layer - the owner of this prop
    • validate (function, optional) - returns true if the value is valid. Validation of layer props is only invoked in debug mode. This function is automatically populated if the prop has a built-in type. Receives the following arguments:
      • value - the value to be validated
      • propType - this prop type definition
    • equal (function, optional) - returns true if the two prop values should be considered equal. Comparison of layer props is invoked during layer update and the result is passed to changeFlags.propsChanged. This function is automatically populated if the prop has a built-in type. Receives the following arguments:
      • value - the new value of this prop
      • oldValue - the previous value of this prop
      • propType - this prop type definition
    • deprecatedFor (string|array, optional) - mark this prop as deprecated. The value is the new prop name(s) that this prop has been deprecated for. If the old prop is supplied instead of the new one, its value will be transferred to the new prop. The user will get a warning about the deprecation.
    • Any additional options, see individual types below.

    Built-in Types

    boolean

    Any value.

    • Default validate: always pass
    • Default equal: compared by truthiness
    MyLayerClass.defaultProps = {
    // explicit
    fill: {type: 'boolean', value: false}
    // inferred
    fill: false
    }
    number

    A numeric value.

    • Options:
      • min (number, optional) - the minimum allowed value
      • max (number, optional) - the maximum allowed value
    • Default validate: value is finite and within bounds (if specified)
    • Default equal: strict equal
    MyLayerClass.defaultProps = {
    // explicit, with bounds
    radiusScale: {type: 'number', value: 1, min: 0}
    // inferred, no bounds
    radiusScale: 1
    }
    color

    A RGBA color.

    • Default validate: value is an array of 3 or 4 numbers
    • Default equal: deep equal
    MyLayerClass.defaultProps = {
    // must be explicit
    fillColor: {type: 'color', value: [255, 204, 0]}
    }
    image

    One of: URL string, luma.gl Texture object, Image, HTMLCanvasElement, HTMLVideoElement, ImageBitmap or ImageData.

    • Options:

      • parameters (object, optional) - custom texture parameters of the texture. If not specified, the following defaults are used:
      {
      minFilter: 'linear',
      magFilter: 'linear',
      mipmapFilter: 'linear',
      addressModeU: 'clamp-to-edge',
      addressModeV: 'clamp-to-edge'
      }
    • Default transform: converts to a Texture2D object

    array

    An array of objects.

    • Options:
      • optional (boolean, optional) - accept null or undefined. Default false.
      • ignore (boolean, optional) - if true, prop comparison is disabled. Default false.
      • compare (boolean|number, optional) - compare deeply during prop comparison. Default false. If a number is supplied, indicates the maximum depth to deep-compare, where 0 is shallow comparison and -1 is infinite depth. true is equivalent to 1.
    • Default validate: value is an array
    • Default equal: shallow equal if compare: false, otherwise deep equal
    MyLayerClass.defaultProps = {
    // explicit
    coordinateOrigin: {type: 'array', value: [0, 0, 0], compare: true}
    // inferred
    coordinateOrigin: [0, 0, 0]
    }
    object

    An arbitrary object.

    • Options:
      • optional (boolean, optional) - accept null or undefined. Default false.
      • ignore (boolean, optional) - if true, prop comparison is disabled. Default false.
      • compare (boolean|number, optional) - compare deeply during prop comparison. Default false. If a number is supplied, indicates the maximum depth to deep-compare, where 0 is shallow comparison and -1 is infinite depth. true is equivalent to 1.
    • Default equal: shallow equal if compare: false, otherwise deep equal
    MyLayerClass.defaultProps = {
    // explicit
    parameters: {type: 'object', value: {}, compare: 2}
    // inferred
    loadOptions: {}
    }
    accessor

    An accessor used to update shader attributes.

    • Default validate: value is either a function or the same type as the default value
    • Default equal: true if function, otherwise deep equal
    MyLayerClass.defaultProps = {
    // must be explicit
    getColor: {type: 'accessor', value: [255, 255, 255]}
    }
    function

    A function.

    • Options:
      • optional (boolean, optional) - accept null or undefined. Default false.
      • ignore (boolean, optional) - if true, prop comparison is disabled. Default true.
    • Default validate: value is a function
    • Default equal: true if ignore: true, otherwise strict equal
    MyLayerClass.defaultProps = {
    // explicit
    sizeScale: {type: 'function', value: x => Math.sqrt(x), ignore: false}
    // inferred
    sizeScale: x => Math.sqrt(x)
    }

    Prop Types and Performance

    The performance of a deck.gl application can be greatly improved by limiting the frequency of layer updates. Consider the following app:

    import React from 'react';

    function App() {
    const layers = [
    new GeoJsonLayer({
    id: 'geojson',
    data: DATA_URL,
    extruded: true,
    wireframe: true,
    getElevation: f => ELEVATION_SCALE(f.properties.population),
    getFillColor: f => COLOR_SCALE(f.properties.income),
    getLineColor: [255, 255, 255]
    })
    ];

    return (
    <DeckGL
    layers={layers}
    initialViewState={{
    latitude: 49.254,
    longitude: -123.13,
    zoom: 11
    }}
    controller={true}
    />
    );
    }

    Each time the user interacts with the viewport, the app state is updated, and render() is called. Because getElevation, getFillColor and getLineColor are functions and arrays defined inline, they have changed from the previous render.

    Usually, any prop change results in updating a layer, that is, recomputing its internal states. Updating a layer could be expensive. In GeoJsonLayer's case, it creates ScatterplotLayer, PolygonLayer and PathLayer, and those layers also need to be updated recursively.

    In reality, we do not want to update GeoJsonLayer, because no layer props changed from the user's perspective. In GeoJsonLayer, these props are declared as such:

    const defaultProps = {
    ...
    getElevation: {type: 'accessor', value: 1000},
    getFillColor: {type: 'accessor', value: [0, 0, 0, 255]},
    getLineColor: {type: 'accessor', value: [0, 0, 0, 255]}
    }

    The default comparator of the access prop type ignores shallow changes in functions. As a result, deck.gl decides that no props have changed between the two renders, and the GeoJsonLayer does not need to be updated.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/subclassed-layers.html b/docs/developer-guide/custom-layers/subclassed-layers.html index 2e8b894b661..1f1bb57b851 100644 --- a/docs/developer-guide/custom-layers/subclassed-layers.html +++ b/docs/developer-guide/custom-layers/subclassed-layers.html @@ -4,8 +4,8 @@ Subclassed Layers | deck.gl - - + +
    @@ -23,7 +23,7 @@ the draw() method:

    /// rounded-rectangle-layer.js
    // Example to draw rounded rectangles instead of circles in ScatterplotLayer
    import {ScatterplotLayer} from '@deck.gl/layers';
    import customFragmentShader from './rounded-rectangle-layer-fragment';

    export default RoundedRectangleLayer extends ScatterplotLayer {

    draw({uniforms}) {
    super.draw({
    uniforms:
    {
    ...uniforms,
    cornerRadius: this.props.cornerRadius
    }
    })
    }

    getShaders() {
    // use object.assign to make sure we don't overwrite existing fields like `vs`, `modules`...
    return Object.assign({}, super.getShaders(), {
    fs: customFragmentShader
    });
    }
    }

    RoundedRectangleLayer.defaultProps = {
    // cornerRadius: the amount of rounding at the rectangle corners
    // 0 - rectangle. 1 - circle.
    cornerRadius: 0.1
    }

    Modified fragment shader that uses this uniform (learn more in writing your own shaders):

    /// rounded-rectangle-layer-fragment.js
    // This is copied and adapted from scatterplot-layer-fragment.glsl.js
    // Modifications are annotated
    export default `\
    #define SHADER_NAME rounded-rectangle-layer-fragment-shader

    precision highp float;

    uniform float cornerRadius;

    varying vec4 vFillColor;
    varying vec2 unitPosition;

    void main(void) {

    float distToCenter = length(unitPosition);

    /* Calculate the cutoff radius for the rounded corners */
    float threshold = sqrt(2.0) * (1.0 - cornerRadius) + 1.0 * cornerRadius;
    if (distToCenter <= threshold) {
    gl_FragColor = vFillColor;
    } else {
    discard;
    }

    gl_FragColor = picking_filterHighlightColor(gl_FragColor);

    gl_FragColor = picking_filterPickingColor(gl_FragColor);
    }
    `;

    Defining Additional Attributes

    During initialization, you may define additional attributes by accessing the layer's attribute manager:

    // my-point-cloud-layer.js
    // Example to add per-point size to point cloud layer
    import {PointCloudLayer} from 'deck.gl';
    import vertexShader from 'my-point-cloud-layer-vertex';

    export default MyPointCloudLayer extends PointCloudLayer {

    initializeState() {
    super.initializeState();

    this.state.attributeManager.addInstanced({
    instanceRadiusPixels: {size: 1, accessor: 'getRadius'}
    });
    }

    getShaders() {
    return Object.assign({}, super.getShaders(), {
    vs: vertexShader,
    });
    }
    }

    MyPointCloudLayer.defaultProps = {
    // returns point radius in pixels
    getRadius: {type: 'accessor', value: 1}
    };

    Modified vertex shader that uses this attribute (learn more in writing your own shaders):

    // my-point-cloud-layer-vertex.js
    // This is copied and adapted from point-cloud-layer-vertext.glsl.js
    // Modifications are annotated
    export default `\
    #define SHADER_NAME point-cloud-layer-vertex-shader

    attribute vec3 positions;
    attribute vec3 instanceNormals;
    attribute vec4 instanceColors;
    attribute vec3 instancePositions;
    attribute vec3 instancePositions64Low;
    attribute vec3 instancePickingColors;

    /* New attribute */
    attribute flat instanceRadiusPixels;

    uniform float opacity;

    varying vec4 vColor;
    varying vec2 unitPosition;

    void main(void) {
    unitPosition = positions.xy;

    vec4 position_commonspace;
    gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.), position_commonspace);
    /* replaced uniform 'radiusPixels' with 'instanceRadiusPixels' */
    gl_Position.xy += project_pixel_size_to_clipspace(positions.xy * instanceRadiusPixels);

    vec3 lightColor = lighting_getLightColor(instanceColors.rgb, project_uCameraPosition, position_commonspace.xyz, project_normal(instanceNormals));

    vColor = vec4(lightColor, instanceColors.a * opacity) / 255.0;

    picking_setPickingColor(instancePickingColors);
    }
    `;

    Layer Extensions

    Sometimes we need to subclass multiple layers to add similar functionalities. Layer extension is a way to generalize, reuse, and share subclassed layer code. Read on about how to package up a subclassed layer code into a layer extension.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/custom-layers/writing-shaders.html b/docs/developer-guide/custom-layers/writing-shaders.html index 5815ed64d4b..daaba7a5e01 100644 --- a/docs/developer-guide/custom-layers/writing-shaders.html +++ b/docs/developer-guide/custom-layers/writing-shaders.html @@ -4,13 +4,13 @@ Writing Shaders | deck.gl - - + +

    Writing Shaders

    A shader library facilitates creating shaders that work seamlessly with deck.gl. The modules parameter passed to the Model class can dynamically include parts from this library into your own GLSL code:

    import {picking, project32, gouraudLighting} from '@deck.gl/core';

    const model = new Model(gl, {
    vs: '// vertex shader GLSL source'
    fs: '// fragment shader GLSL source',
    modules: [picking, project32, gouraudLighting] // list of optional module names
    });

    Shader Assembly

    Your shaders will be run through the luma.gl shader assembler, which injects code from various module dependencies, The generated shader always contains a prologue of platform defines, and then the modules (see below), and finally your shader code is added.

    Platform defines

    This "virtual" module is a dynamically generated prologue containing #defines describing your graphics card and platform. It is designed to work around certain platform-specific issues to allow the same rendering results are different GPUs and platforms. It is automatically injected by assembleShaders before any modules are included.

    Shader Modules

    projection

    The project shader module is part of the core of deck.gl. It makes it easy to write shaders that support all of deck.gl's projection modes and it supports some advanced rendering techniques such as pixel space rendering etc.

    The project module also has two extensions, project32 and project64.

    lighting

    A simple lighting package is provided in deck.gl, supporting a single directional light in addition to ambient light. Turning on lighting requires normals to be provided for each vertex. There are two flavors:

    • [gouraudLighting] - for lighting calculated in the vertex shader
    • [phongLighting] - for lighting calculated in the fragment shader

    fp64

    The fp64 shader math library can be used leveraged by developers to conduct numerical computations that requires high numerical accuracy. This shader math library uses "multiple precision" algorithms to emulate 64-bit double precision floating point numbers, with some limitations, using two 32-bit single precision floating point numbers. To use it, just set the "fp64" key to "true" when calling assembleShaders. Please refer to the "64-bit layers" section in the document for more information.

    Note that for geospatial projection, deck.gl v6.1 introduced a "hybrid" 32-bit projection mode that provides the precision of 64-bit projection with the performance of 32-bit calculations, so it is recommended that any use of fp64 be used for non-position-projection related use cases.

    picking

    Picking is supported using luma.gl picking shader module.

    Standard Shader Hooks

    When subclassing an official deck.gl layer with minor feature additions, it is possible to inject custom code into predefined locations into the original shaders. These hooks are considered the public API of layers that will work consistently cross minor releases.

    const shaders = this.getShaders();

    const model = new Model(gl, {
    ...this.getShaders(),
    inject: {
    'fs:decl': `
    uniform float coverage;
    `
    'fs:DECKGL_FILTER_COLOR': `
    if (abs(geometry.uv.x) > coverage) discard;
    `
    }
    });
    vs:#decl

    Inject into the top of the vertex shader (declarations).

    vs:#main-start

    Inject into the the very beginning of the main function in the vertex shader.

    vs:#main-end

    Inject into the the very end of the main function in the vertex shader.

    vs:DECKGL_FILTER_SIZE

    Inject into a function in the vertex shader to manipulate the size of a geometry. Called before projection.

    Arguments:

    • inout vec3 size - offset of the current vertex from geometry.worldPosition in common space.
    • VertexGeometry geometry - descriptor of the current geometry
    vs:DECKGL_FILTER_GL_POSITION

    Inject into a function in the vertex shader to manipulate the projected position of the current vertex. Called after projection.

    Arguments:

    • inout vec4 position - position of the current vertex in clipspace
    • VertexGeometry geometry - descriptor of the current geometry
    vs:DECKGL_FILTER_COLOR

    Inject into a function in the vertex shader to manipulate the color of the current geometry. Called after projection.

    Arguments:

    • inout vec4 color - color of the current geometry, RGBA in the [0, 1] range
    • VertexGeometry geometry - descriptor of the current geometry
    fs:#decl

    Inject into the top of the fragment shader (declarations).

    fs:#main-start

    Inject into the the very beginning of the main function in the fragment shader.

    fs:#main-end

    Inject into the the very end of the main function in the fragment shader.

    fs:DECKGL_FILTER_COLOR

    Inject into a function in the vertex shader to manipulate the color of the current geometry. Called after projection.

    Arguments:

    • inout vec4 color - color of the current geometry, RGBA in the [0, 1] range
    • FragmentGeometry geometry - descriptor of the current geometry

    VertexGeometry struct

    • vec3 worldPosition - The world position of the current geometry, usually populated from a getPosition accessor.
    • vec3 worldPositionAlt - The secondary world position of the current geometry. This property is populated if the geometry is instanced between a source position and a target position, for example ArcLayer.
    • vec3 normal - The normal at the current vertex in common space. Only populated for 3D layers.
    • vec2 uv - The uv position at the current vertex.
    • vec4 position - The position of the current vertex in common space. Populated during projection.
    • vec3 pickingColor - The picking color of the current vertex.

    FragmentGeometry struct

    • vec2 uv - The uv position at the current vertex.

    Shader Techniques and Ideas

    Filtering and Brushing (Vertex and Fragment Shaders)

    When rendering large data sets (especially a lot of intersecting lines or arcs) it can be hard to see the structure in the data in the resulting visualization. A useful technique in these cases is to use "brushing".

    Sometimes, being able to filter out a specific color, or range of colors, from the data without modifying the data container itself can be helpful for performance or just code simplification reasons. This is also a feature that can easily be added to a deck.gl shader.

    Tip: Use discard in the fragment shader instead of 0 alpha. Faster and leaves the depth buffer unaffected.

    Animation (Vertex Shader)

    A powerful capability of deck.gl is to render layers with thousands of animated and/or interactive objects with the computing power of GPUs.

    Creating an animated layer can be as easy as having the application supply start and end positions for every object, and a time interval over which to animate, and have the vertex shader interpolate the positions for every frame using a simple mix GLSL instruction.

    Uniforms

    Layer prop uniforms

    float layerIndex

    The layerIndex is a small integer that starts at zero and is incremented for each layer that is rendered. It can be used to add small offsets to the z coordinate of layers to resolve z-fighting between overlapping layers.

    float opacity

    In the fragment shader, multiply the fragment color with the opacity uniform.

    Shader Module Uniforms

    The luma.gl/deck.gl shader modules provide javascript functions to set their uniforms but the actual GLSL uniforms are typically considered implementation dependent. The intention is that you should use the public functions exposed by each shader module. That said, some uniforms from the project module are considered special and are documented.

    Remarks

    • Use With Other GLSL Code Assemblers - Your shader code can be run through another GLSL code assembler like glslify before you pass it to assembleShaders. This means that you are not forced to work with only luma.gl shader modules, you can use multiple techniques to organize your shader code to fit your project needs.
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/debugging.html b/docs/developer-guide/debugging.html index 148e5c6e163..a40a8baf3ab 100644 --- a/docs/developer-guide/debugging.html +++ b/docs/developer-guide/debugging.html @@ -4,13 +4,13 @@ Debugging | deck.gl - - + +

    Debugging

    deck.gl provides support for debugging applications and layers, which includes:

    • deck.gl logging
    • luma.gl debugging support

    deck.gl logging

    deck.gl (and luma.gl) are based on the probe.gl debugging library, providing user configurable console logging with advanced functions like the ability to log images and tables etc to the console.

    In your browser console, select the log level you would like:

    deck.log.enable()
    deck.log.level = 2
    Log levelDescription
    0Critical logs only
    1Logs the reason for redraws and picking operations
    2Logs layer updates
    3+Additional logging around layer lifecycle, prop diffing etc

    Starting v8.0, deck.gl no longer bundles the debugging module in production mode. This includes the pre-bundled dist.min.js, and any bundle built with the environment variable NODE_ENV=production. To enable debugging in a production build, you may include the pre-bundled debug module AFTER the deck.gl bundle:

    <!-- the bundle that contains deck.gl -->
    <script src="app.js"></script>
    <!-- the debug module -->
    <script src="https://unpkg.com/@deck.gl/core@^8.0.0/debug.min.js"></script>

    WebGL2/WebGPU debugging using luma.gl

    For lower level debugging, including debugging of layer rendering and picking, deck.gl is built on luma.gl which has extensive debugging and instrumentation support for WebGL2/WebGPU level code and GPU input values (shader uniforms and attributes). To enable debug logging simply issue the following commands in your browser console:

    luma.log.enable()
    luma.log.level = 2

    The following features are available:

    • Automatic sanity checks are performed on uniforms and attributes. Passing an undefined value to a uniform is a common JavaScript mistake that will immediately generate a descriptive exception in deck.gl. This can be tracked from the console output.

    • The Deck class and DeckGL react component have a debug flag which instructs luma.gl to instruments the WebGL2/WebGPU context (with a performance cost) which allows tracing all GPU call errors, see below on luma debug log levels. It also generates exceptions immediately when a GPU operation fails, allowing you to pinpoint exactly where in the code the issue happened. Due to the asynchronous nature of the GPU, some GPU execution errors are surfaced and caught later than the calls that generate them.

    In the browser console, setting luma.log.level to various values will enable increasing levels of debugging.

    Log levelDescription
    0Critical logs only
    1Minimal logging
    2 and 3Will display all uniforms and attributes before each draw call, allowing you to be confident in what values your shaders are actually working on.
    4Will trace every single gl call.
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/fp64.html b/docs/developer-guide/fp64.html index 6c986e3177a..b272e63f3df 100644 --- a/docs/developer-guide/fp64.html +++ b/docs/developer-guide/fp64.html @@ -4,14 +4,14 @@ About 64-bit Layers | deck.gl - - + +

    About 64-bit Layers

    deck.gl can leverage high precision GPU floating point using emulated 64-bit floating point. For supported layers (look for the 64-bit icon in the docs), 64-bit shaders are used when the fp64 prop is set to true.

    With the improved precision 32 bit projection mode in deck.gl 6.1, the use of fp64 is no longer required to achieve sub-centimeter precision. The new 32 bit projection mode has much better performance. This makes the fp64 mode more of a niche technology that demonstrates how to use 64 bit calculations should you need to use them in your own applications.

    32-bit vs 64-bit Mandelbrot Set Zoom

    Mandelbrot set rendered on GPU using native 32-bit (left) floating point shaders and emulated 64-bit (right) floating point shaders provided by deck.gl.

    Precision

    With 64-bit floating point support in shader, deck.gl layers is able to visualize data with very high dynamic range. Points covering a whole city and accurate down to sub-centimeter level can be processed and rendered to canvas on-the-fly.

    Since WebGL does not support 64-bit floating point, deck.gl uses two 32-bit native floating point number to extend and preserve significant digits and uses algorithms similar to those used in many multiple precision math libraries to achieve the precision close to what IEEE-754 double precision floating point numbers provide.

    Generally speaking, this mechanism provide 46 significant digits in mantissa (48 overall) within the normal range of 32-bit single precision float point numbers. This transfers to ~ 1x10^-15 relative error within ~ 1.2x10^-38 and 1.7x10^+38.

    The error bound as tested on 2015 MacBook Pro with AMD Radeon R9 M370X GPU:

    OperationError
    Addition< 1 ulp
    Subtraction< 1 ulp
    Multiplication~1.5 ulps
    Division~2 ulps
    Square root~2.6 ulps
    Exponential~2.6 ulps
    Logarithm~11.6 ulps
    Trigonometry~5 ulps

    Note: ulp = unit of least precision

    Performance Implications

    Since the 64-bit floating point maths are emulated using the multiple precision arithmetics, it costs more GPU cycles than native 32-bit math (the shader execution time alone is about 10x slower). However, since 64-bit floating point maths are usually only required in vertex shader, the overall performance impact is usually less than 10x.

    There will be a memory impact too, in that all vertex attributes and uniform that uses 64-bit maths require double storage space in JavaScript. Same as mentioned above, since a layer usually has some attributes that do not require 64-bit maths, the total memory impact is normally significantly less than 2x.

    Shaders are more complex and can take time to compile on some systems, notably Windows.

    For more information regarding the performance of 64-bit layers, please check the performance benchmark layers in the layer-browser example in deck.gl repo.

    Other Considerations

    64-bit shaders push the GPU drivers quite a bit, and workarounds are needed to prevent GPU drivers from optimizing away critical parts of the code. The fp64 shader module has been tested on a range of GPUs and drivers however every now and then we encounter a new driver that needs special treatment.

    If you mainly deploy into a know set of clients that you can test in advance, this is not a big issue, however if you expect your applications to work across a large set of devices you may want to stay with 32-bit calculations.

    References

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/interactivity.html b/docs/developer-guide/interactivity.html index 62341c6683d..3c889eb71d3 100644 --- a/docs/developer-guide/interactivity.html +++ b/docs/developer-guide/interactivity.html @@ -4,14 +4,14 @@ Adding Interactivity | deck.gl - - + +

    Adding Interactivity

    Controlling the Camera

    Out of the box, deck.gl offers viewport controllers that map keyboard, mouse or touch input to camera state change. The easiest way to enable pan/zoom/rotate of the visualization is to set the controller prop on Deck or <DeckGL> to true along with an initialViewState object that defines the initial camera settings:

    import {Deck} from '@deck.gl/core';

    new Deck({
    initialViewState: {
    longitude: -122.4,
    latitude: 37.8,
    zoom: 12,
    pitch: 0,
    bearing: 0
    },
    controller: true,
    layers: []
    });

    You can also selectively enable/disable certain controller features:

      controller: {doubleClickZoom: false, touchRotate: true}

    See Controller for all options.

    Reset Camera Position

    An application can reset the camera state by supplying a new initialViewState object at any time:

    import {Deck} from '@deck.gl/core';

    const deckgl = new Deck({
    initialViewState: {
    longitude: -122.4,
    latitude: 37.8,
    zoom: 12
    },
    controller: true,
    layers: []
    });

    button.onclick = gotoNYC;

    // Jump to New York City
    function goToNYC() {
    deckgl.setProps({
    initialViewState: {
    longitude: -70.4,
    latitude: 40.7,
    zoom: 12
    }
    })
    }

    To add a transition animation, see view state transitions.

    Add Constraints to View State

    An application can optionally supply the onViewStateChange callback and manipulate the view state before it is used. The following example constrains the map in a bounding box:

    import {Deck} from '@deck.gl/core';

    const LONGITUDE_RANGE = [-123, -122];
    const LATITUDE_RANGE = [37, 38];

    new Deck({
    initialViewState: {
    longitude: -122.4,
    latitude: 37.8,
    zoom: 12
    },
    controller: true,
    onViewStateChange: ({viewState}) => {
    viewState.longitude = Math.min(LONGITUDE_RANGE[1], Math.max(LONGITUDE_RANGE[0], viewState.longitude));
    viewState.latitude = Math.min(LATITUDE_RANGE[1], Math.max(LATITUDE_RANGE[0], viewState.latitude));
    return viewState;
    }
    });

    Externally Manage View State

    For more flexibility you can maintain the view state yourself and pass it in to deck.gl via the viewState parameter. This essentially makes Deck/<DeckGL> a stateless component, and allows you to share the view state between multiple components, e.g. via a Redux store.

    Note: Do not combine initialViewState and viewState props. viewState will always overwrite any internal state.

    The following example demonstrates how to do this with React:

    import React, {useState} from 'react';
    import DeckGL from '@deck.gl/react';

    function App() {
    const [viewState, setViewState] = useState({
    longitude: -122.4,
    latitude: 37.8,
    zoom: 12
    });

    const layers = [
    //...
    ];
    return (
    <DeckGL
    viewState={viewState}
    onViewStateChange={e => setViewState(e.viewState)}
    controller={true}
    layers={layers}>
    </DeckGL>
    );
    }

    Advanced View Controls

    • Alternative views such as OrbitView, FirstPersonView, and using multiple views such as VR, minimap: Views and Projections
    • Implement a custom controller: Controller

    Picking

    deck.gl includes a powerful picking engine that enables the application to precisely determine what object and layer is rendered on a certain pixel on the screen. This picking engine can either be called directly by an application (which is then typically implementing its own event handling), or it can be called automatically by the basic built-in event handling in deck.gl

    What can be Picked?

    The "picking engine" identifies which object in which layer is at the given coordinates. While usually intuitive, what constitutes a pickable "object" is defined by each layer. Typically, it corresponds to one of the data entries that is passed in via prop.data. For example, in Scatterplot Layer, an object is an element in the props.data array that is used to render one circle. In GeoJson Layer, an object is a GeoJSON feature in the props.data feature collection that is used to render one point, path or polygon.

    Enabling Picking

    Picking can be enabled or disabled on a layer-by-layer basis. To enable picking on a layer, set its pickable prop to true. This value is false by default.

    The Picking Info Object

    The picking engine returns "picking info" objects which contains a variety of fields describing what layer and object was picked.

    KeyValue
    layerThe layer that the picked object belongs to. Only layers with the pickable prop set to true can be picked.
    indexThe index of the object in the layer that was picked.
    objectThe object that was picked. This is typically an entry in the layer's props.data array, but can vary from layer to layer.
    xMouse position x relative to the viewport.
    yMouse position y relative to the viewport.
    coordinateMouse position in geospatial coordinates. Only applies if layer.props.coordinateSystem is a geospatial mode such as COORDINATE_SYSTEM.LNGLAT.
    viewportThe viewport that the picked object belongs to.

    Remarks:

    • Specific deck.gl Layers may add additional fields to the picking info object. Check the documentation of each layer.
    • Limitation when using multiple views: viewport could potentially be misidentified if two views that contain the picked layer also overlap with each other and do not clear the background.

    Example: Display a Tooltip for Hovered Object

    Using the Built-In Tooltip

    Deck automatically renders a tooltip if the getTooltip callback is supplied:

    import {Deck} from '@deck.gl/core';
    import {ScatterplotLayer} from '@deck.gl/layers';

    const deck = new Deck({
    canvas: 'deck-canvas',
    initialViewState: {longitude: -122.45, latitude: 37.78, zoom: 12},
    controller: true,
    layers: [
    new ScatterplotLayer({
    data: [
    {position: [-122.45, 37.78], message: 'Hover over me'}
    ],
    getPosition: d => d.position,
    getRadius: 1000,
    getFillColor: [255, 255, 0],
    // Enable picking
    pickable: true
    })
    ],
    getTooltip: ({object}) => object && object.message
    });

    It receives a picking info object and returns the content of the tooltip. To custom the tooltip further, return an object instead:

      getTooltip: ({object}) => object && {
    html: `<h2>${object.name}</h2><div>${object.message}</div>`,
    style: {
    backgroundColor: '#f00',
    fontSize: '0.8em'
    }
    }

    For a range of options, see getTooltip documentation.

    Using React

    import React, {useState} from 'react';
    import {DeckGL, ScatterplotLayer} from 'deck.gl';

    const data = [
    {position: [-122.45, 37.78], message: 'Hover over me'}
    ];

    function App() {
    const [hoverInfo, setHoverInfo] = useState;

    const layers = [
    new ScatterplotLayer({
    data,
    getPosition: d => d.position,
    getRadius: 1000,
    getFillColor: [255, 255, 0],
    // Enable picking
    pickable: true,
    // Update app state
    onHover: info => setHoverInfo(info)
    })
    ];

    return (
    <DeckGL initialViewState={{longitude: -122.45, latitude: 27.78, zoom: 12}}
    controller={true}
    layers={layers} >
    {hoverInfo.object && (
    <div style={{position: 'absolute', zIndex: 1, pointerEvents: 'none', left: hoverInfo.x, top: hoverInfo.y}}>
    { hoverInfo.object.message }
    </div>
    )}
    </DeckGL>
    );
    }

    Calling the Picking Engine Directly

    The picking engine is exposed through the Deck.pickObject and Deck.pickObjects methods. These methods allow you to query what layers and objects within those layers are under a specific point or within a specified rectangle. They return Picking Info objects as described below.

    pickObject allows an application to define its own event handling. When it comes to how to actually do event handling in a browser, there are many options. In a React application, perhaps the simplest is to just use React's "synthetic" event handling together with pickObject:

    import React, {useRef, useCallback} from 'react';

    function App() {
    const deckRef = useRef(null);

    const onClick = useCallback(event => {
    const pickInfo = deckRef.current.pickObject({
    x: event.clientX,
    y: event.clientY,
    radius: 1
    });
    console.log(pickInfo.coordinate);
    }, [])

    return (
    <div onClick={onClick}>
    <DeckGL ref={deckRef} ... />
    </div>
    );
    }

    Also note that by directly calling queryObject, integrating deck.gl into an existing application often becomes easier since you don't have to change the application's existing approach to event handling.

    Under The Hood

    If you are using the core layers, all has been taken care of.

    If you are implementing a custom layer, read more about how picking is implemented.

    Built-in Events

    For applications that have basic event handling needs, deck.gl has built-in support for handling selected pointer events. When the application registers callbacks, deck.gl automatically tracks these events, runs the picking engine and calls application callbacks with a single parameter info which contains the resulting picking info object.

    The following event handlers are supported:

    • onHover
    • onClick
    • onDragStart
    • onDrag
    • onDragEnd

    A event handler function is called with two parameters: info that contains the object being interacted with, and event that contains the pointer event.

    There are two ways to subscribe to the built-in picking event handling:

    const layer = new ScatterplotLayer({
    ...
    pickable: true,
    onHover: (info, event) => console.log('Hovered:', info, event),
    onClick: (info, event) => console.log('Clicked:', info, event)
    });
    <DeckGL
    ...
    onHover={this._onHover}
    onClick={this._onClick}
    />

    Behavior of Built-in Event Handling

    Picking events are triggered based on pickable objects:

    • A click event is triggered every time the pointer clicked on an object in a pickable layer.
    • A hover event is triggered every time the hovered object of a pickable layer changes.

    When an event is fired, the onHover or onClick callback of the affected layer is called first. If the callback returns a truthy value, the event is marked as handled. Otherwise, the event will bubble up to the DeckGL canvas and be visible to its onHover and onClick callbacks.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/loading-data.html b/docs/developer-guide/loading-data.html index b2c4f3a70b9..9c615e569fe 100644 --- a/docs/developer-guide/loading-data.html +++ b/docs/developer-guide/loading-data.html @@ -4,14 +4,14 @@ Loading Data | deck.gl - - + +

    Loading Data

    deck.gl uses loaders.gl, a framework-agnostic library to read data and resources.

    deck.gl core always includes loaders for JSON and standard image formats (e.g, png, jpeg, svg). Certain layers include additional loaders supporting their own use cases. It is easy for applications to provide options to configure the behavior of the default loaders or to add loaders to support for additional formats.

    Some examples of when loaders are used:

    • JSON array or object from an URL passed to the data prop of a layer
    • Texture from an image, such as image in BitmapLayer, iconAtlas in IconLayer, and texture in SimpleMeshLayer
    • Geometries from a binary tile, e.g. MVTLayer, TerrainLayer, and Tile3DLayer
    • Geometries from a standard 3D format, e.g. scenegraph in ScenegraphLayer, and mesh in SimpleMeshLayer

    Customize Data Loading Behavior

    All layers support a loadOptions prop that can be used to customize loading and parsing.

    Example: Fetch data with credentials

    In a production environment, deck.gl applications may need to load data from secure APIs that require special HTTP headers (such as Authorization) to be set.

    In order to access a secure API, the loadOptions.fetch option passes through additional parameters to fetch, which deck.gl calls under the hood to load resources.

    new ScatterplotLayer({
    data: 'https://secure-server.com/userActivity',
    loadOptions: {
    fetch: {
    method: 'POST',
    body: JSON.stringify(requestBody),
    headers: {
    'Authorization': `Bearer ${accessToken}`,
    }
    }
    }
    ...
    });

    Example: Override the default image loading options

    deck.gl uses ImageLoader to read common image formats. The default loader options are:

    {
    image: {type: 'auto'},
    imagebitmap: {premultiplyAlpha: 'none'}
    }

    The image is decoded into an ImageBitmap if the browser supports it (Firefox, Chrome, Edge) for better performance. You can override the default options for the createImageBitmap API as follows:

    new IconLayer({
    iconAtlas: '/path/to/image.png',
    loadOptions: {
    imagebitmap: {
    // Flip the image vertically
    imageOrientation: 'flipY'
    }
    }
    })

    If the image is a SVG that does not include width and height information, createImageBitmap will throw a DOMException: The image element contains an SVG image without intrinsic dimensions, and no resize options or crop region are specified. This can be fixed by explicitly setting its dimensions:

    new IconLayer({
    ...
    iconAtlas: '/path/to/image.svg',
    loadOptions: {
    imagebitmap: {
    resizeWidth: 256,
    resizeHeight: 256,
    resizeQuality: 'high'
    }
    }
    })

    Support Additional Formats

    All layers support a loaders prop that can be used to add loaders.gl loaders for parsing a specific input format.

    For example, the following code adds the CSVLoader to support CSV/TSV files:

    import {CSVLoader} from '@loaders.gl/csv';

    new HexagonLayer({
    data: 'path/to/data.tsv',
    loaders: [CSVLoader],
    loadOptions: {
    csv: {
    delimiter: '\t',
    dynamicTyping: true,
    skipEmptyLines: true
    }
    }
    });

    The following code adds the LASLoader to support LAS/LAZ files:

    import {LASLoader} from '@loaders.gl/las';

    new PointCloudLayer({
    mesh: 'path/to/pointcloud.laz',
    loaders: [LASLoader]
    });

    Force Reload From an URL

    Usually, a layer refreshes its data when and only when the data prop changes. The following code refreshes data from the same URL every 5 minutes by changing a query parameter:

    const deck = new Deck({...});

    let dataVersion = 0;
    function update() {
    const layer = new ScatterplotLayer({
    data: `path/to/data.json?v=${dataVersion}`
    });

    deck.setProps({layers: [layer]});
    };

    setInterval(() => {
    dataVersion++;
    update();
    }, 5 * 60 * 1000);

    Loaders and Web Workers

    For the best performance, some specialized loaders parse data using web workers, for example TerrainLoader in the TerrainLayer and MVTLoader in the MVTLayer. By default, the worker code is loaded from from the latest published NPM module on unpkg.com.

    It might be desirable for some applications to serve the worker code itself without relying on the CDN. To do this, locate the worker bundle locally in node_modules/@loaders.gl/<module>/dist/<name>-loader.worker.js and serve it as a static asset with your server. Point the loader to use this alternative URL using loadOptions.<name>.workerUrl:

    new MVTLayer({
    loadOptions: {
    mvt: {
    workerUrl: <my_worker_url>
    }
    }
    }

    If the layer is used in an environment that does not support web workers, or you need to debug the loader code on the main thread, you may import the full loader like this:

    import {MVTLoader} from '@loaders.gl/mvt';
    new MVTLayer({
    loaders: [MVTLoader],
    loadOptions: {worker: false}
    });

    Refer to each specific layer's documentation to see which loaders are used.

    Load Resource Without an URL

    In some use cases, resources do not exist at a static URL. For example, some applications construct images dynamically based on user input. Some applications receive arbitrary binary blobs from a server via a WebSocket connection.

    Before reading on, remember that you don't have to use a loader if your app already knows how to interpret the content. For example, if you have the RGBA values of all pixels of an image. you can simply construct an ImageData object:

    new BitmapLayer({
    image: new ImageData(pixels, 128, 128)
    })

    If you have a custom-formatted binary, consider the techniques in using binary data.

    The following examples only address the use cases where you need a loader/parser to interpret the incoming data.

    Example: Use image from a programmatically generated SVG string

    The following code dynamically generates SVG icons and convert them to data URLs.

    function createSVGIcon(number) {
    const label = number < 10 ? number.toString : '10+';
    return `\
    <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
    <circle cx="12" cy="12" r="10" fill="#c00" stroke="#fa1" stroke-width="2"/>
    <text x="12" y="12" fill="#fff" text-anchor="middle" alignment-baseline="middle" font-size="8">${label}</text>
    </svg>`;
    }

    // Note that a xml string cannot be directly embedded in a data URL
    // it has to be either escaped or converted to base64.
    function svgToDataURL(svg) {
    return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
    // or
    return `data:image/svg+xml;base64,${btoa(svg)}`;
    }

    new IconLayer({
    getIcon: d => {
    url: svgToDataURL(createSVGIcon(d.value)),
    width: 24,
    height: 24
    }
    })

    Example: Parse glTF from a binary blob

    The following code shows how to parse a glTF model that is already loaded into an ArrayBuffer object.

    There are two ways for deck.gl to load it. One is to create a blob URL:

    const blob = new Blob([arraybuffer]);
    const objectURL = URL.createObjectURL(blob);

    new ScenegraphLayer({
    scenegraph: objectURL
    });

    Or more directly, import the parse utility from loaders.gl (already a dependency of deck.gl), which returns a promise:

    import {parse} from '@loaders.gl/core';
    import {GLTFLoader} from '@loaders.gl/gltf';

    new ScenegraphLayer({
    scenegraph: parse(arraybuffer, GLTFLoader)
    })
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/performance.html b/docs/developer-guide/performance.html index 5c266962a36..f5bfcc8320f 100644 --- a/docs/developer-guide/performance.html +++ b/docs/developer-guide/performance.html @@ -4,8 +4,8 @@ Performance Optimization | deck.gl - - + +
    @@ -22,7 +22,7 @@ number of pixels drawn.

    Thus it is possible to render a scatterplot layer with 10M items with reasonable frame rates on recent GPUs, provided that the radius (number of pixels) of each point is small.

    It is good to be aware that excessive overdraw (drawing many objects/pixels on top of each other) can generate very high fragment counts and thus hurt performance. As an example, a Scatterplot radius of 5 pixels generates ~ 100 pixels per point. If you have a Scatterplot layer with 10 million points, this can result in up to 1 billion fragment shader invocations per frame. While dependent on zoom levels (clipping will improve performance to some extent) this many fragments will certainly strain even a recent MacBook Pro GPU.

    Layer Picking Performance

    deck.gl performs picking by drawing the layer into an off screen picking buffer. This essentially means that every layer that supports picking will be drawn off screen when panning and hovering. The picking is performed using the same GPU code that does the visual rendering, so the performance should be easy to predict.

    Picking limitations:

    • The picking system can only distinguish between 16M items per layer.
    • The picking system can only handle 256 layers with the pickable flag set to true.

    Number of Layers

    The layer count of an advanced deck.gl application tends to gradually increase, especially when using composite layers. We have built and optimized a highly complex application using close to 100 deck.gl layers (this includes hierarchies of sublayers rendered by custom composite layers rendering other composite layers) without seeing any performance issues related to the number of layers. If you really need to, it is probably possible to go a little higher (a few hundred layers). Just keep in mind that deck.gl was not designed to be used with thousands of layers.

    Common Issues

    A couple of particular things to watch out for that tend to have a big impact on performance:

    • If not needed disable Retina/High DPI rendering. It generates 4x the number of pixels (fragments) and can have a big performance impact that depends on which computer or monitor is being used. This feature can be controlled using useDevicePixels prop of DeckGL component and it is on by default.
    • Avoid using luma.gl debug mode in production. It queries the GPU error status after each operation which has a big impact on performance.

    Smaller considerations:

    • Enabling picking can have a small performance penalty so make sure the pickable property is false in layers that do not need picking (this is the default value).
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/testing.html b/docs/developer-guide/testing.html index 9f3d0d59ec2..509c9e99827 100644 --- a/docs/developer-guide/testing.html +++ b/docs/developer-guide/testing.html @@ -4,13 +4,13 @@ Testing Layers and Applications | deck.gl - - + +

    Testing Layers and Applications

    Testing WebGL2/WebGPU code is much harder than testing regular JavaScript. GPU and browser dependent commands may not run under Node. Rendering behavior differs cross platforms and hardware. Since it draws into a canvas, there is also no precisely verifiable output.

    The @deck.gl/test-utils module is used to ensure the quality and stability of the deck.gl framework. It is also available for those who need to test their own custom layers and/or deck.gl applications.

    Unit Tests for deck.gl Layers

    Lifecycle test functions are designed to allow for integration with different unit test frameworks. Some of the details depend on the test framework you are using. deck.gl itself uses tape so the tests in the deck.gl repository contain extensive examples of tape integration, but it should also be straightforward to integrate with other unit testing frameworks.

    Example

    Using testLayer util to instantiate a layer and test a series of prop updates:

    import test from 'tape-promise/tape';
    import {testLayer} from '@deck.gl/test-utils';
    import {GeoJsonLayer} from '@deck.gl/layers';

    test('GeoJsonLayer#tests', t => {
    testLayer({Layer: GeoJsonLayer, testCases: [
    // Test case 1
    {
    props: {data: []}
    },
    // Test case 2
    {
    props: {
    data: SAMPLE_GEOJSON
    },
    assert({layer, oldState}) {
    t.ok(layer.state.features !== oldState.features, 'should update features');
    t.is(subLayers.length, 2, 'should render 2 subLayers');
    }
    },
    // Test case 3
    {
    updateProps: {
    // will be merged with the previous props
    lineWidthScale: 3
    },
    assert({subLayers}) {
    const pathLayer = subLayers.find(layer => layer.id.endsWith('linestrings'));
    t.is(pathLayer.props.widthScale, 3, 'widthScale is passed to sub layer');
    }
    }
    ]});

    t.end();
    });

    The generateLayerTests utility automatically generates a series of test cases for testLayers based on the layer class' default props. It is useful for checking the conformance of a layer class:

    import test from 'tape-promise/tape';
    import {testLayer, generateLayerTests} from '@deck.gl/test-utils';
    import {GeoJsonLayer} from '@deck.gl/layers';

    test('GeoJsonLayer#tests', t => {

    const testCases = generateLayerTests({
    Layer: GeoJsonLayer,
    sampleProps: {
    data: SAMPLE_GEOJSON
    },
    assert: ({layer, subLayers}) => {
    t.ok(layer.state.features, 'should update features');
    t.is(subLayers.length, layer.props.stroked ? 2 : 1, 'correct number of sublayers');
    }
    });

    testLayer({Layer: GeoJsonLayer, testCases});

    t.end();
    });

    Integration Tests

    While unit tests are good at capturing issues in layer initialization and prop updates, they do not guarantee that the layer will be correctly rendered to screen. Some issues in e.g. the GPU shaders can only be spotted in an integration test.

    The @deck.gl/test-utils module offers a SnapshotTestRunner that works with the probe.gl library's BrowserTestDriver class to perform this task. Together, they enable the following scenario:

    • start a controlled Chromium browser instance
    • start a server (we use a webpack-dev-server) that bundles a test script.
    • the test script renders a set of tests (described below), compares the output against golden images and report the result back to the Node process
    • closes down all processes and browser tabs.
    • the node process exists with a 0 (success) or 1 if any test failed.

    Example

    In your node.js start script:

    // This is the script that runs in Node.js and starts the browser
    const {BrowserTestDriver} = require('@probe.gl/test-utils');
    new BrowserTestDriver().run({
    server: {
    // Bundles and serves the browser script
    command: 'webpack-dev-server',
    arguments: ['--env.render-test']
    },
    headless: true
    });

    In your script that is run on the browser:

    const {SnapshotTestRunner} = require('@deck.gl/test-utils');
    const {ScatterplotLayer} = require('@deck.gl/layers');

    const TEST_CASES = [
    {
    name: 'ScatterplotLayer',
    // `Deck` props
    viewState: {
    longitude: -122.4,
    latitude: 37.8,
    zoom: 12,
    pitch: 20
    },
    layers: [
    new ScatterplotLayer({
    id: 'circles',
    data: './data/scatterplot.json',
    getPosition: d => d.position,
    getRadius: d => d.size,
    getFillColor: [255, 0, 0]
    })
    ],
    // `done` must be called when ready for screenshot and compare
    onAfterRender: ({layers, done}) => {
    if (layers[0].props.data.length) {
    // data is loaded
    done();
    }
    },
    // Target rendering result
    goldenImage: './test/render/golden-images/scatterplot.png'
    }
    ];

    new TestRender({width: 800, height: 600})
    .add(TEST_CASES)
    .run({
    onTestFail: window.browserTestDriver_fail
    })
    .then(window.browserTestDriver_finish);
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/tips-and-tricks.html b/docs/developer-guide/tips-and-tricks.html index 04e47c0636a..7fd2ad630bb 100644 --- a/docs/developer-guide/tips-and-tricks.html +++ b/docs/developer-guide/tips-and-tricks.html @@ -4,14 +4,14 @@ Tips and Tricks | deck.gl - - + +

    Tips and Tricks

    Rendering Tips

    Per Layer Control of GPU parameters

    The base Layer class (which is inherited by all layers) supports a parameters property that allows applications to specify the state of GPU parameters such as blending mode, depth testing etc. This can provide significant extra control over rendering.

    const layer = new ScatterplotLayer({
    ...,
    parameters: {depthTest: false}
    });

    z-fighting and Depth Testing

    A common problem faced by 3D application developers is known as "z fighting". It relates to multiple objects being drawn at the same depth in the 3D scene, and due to rounding artifacts in the so called z buffer the GPU cannot accurately determine whether a pixel has already been drawn in a specific place.

    If you are not using 3D extrusions, the easiest way to get rid of z fighting is typically just to turn off depth testing. It can be done globally or per-layer.

    new ...Layer({
    ...,
    parameters: {
    depthTest: false
    }
    });

    Also, if the z-fighting occurs between layers (rather than between elements within a single layers), deck.gl offers a slightly more sophisticated polygonOffset property.

    Browser Blending Modes

    Occasionally, the default blending in the browser does not give ideal results. In that case you may want to test the tips in this section.

    To understand why browser blending modes can matter, consider that deck.gl renders in a separate transparent div on top of the map div, so the final composition of the image a user see on the monitor is controlled by the browser according to CSS settings instead of the WebGL settings.

    One way to control this blending effect is by specifying the CSS property mix-blend-mode in modern browsers to be multiply:

    .overlays canvas {
    mix-blend-mode: multiply;
    }

    multiply blend mode usually gives the expected results, as it only darkens. This blend mode keeps the overlay colors, but lets map legends underneath remain black and legible.

    Note: that there is a caveat with setting mix-blend-mode, as it can affect other peer HTML elements, especially other map children (perhaps controls or legends that are being rendered on top of the map). If this is an issue, set the isolation CSS prop on the DeckGL parent element.

    .deckgl-parent-class {
    isolation: 'isolate';
    }

    Optimization for Mobile

    Experimental Memory Usage Controls

    The Deck class supports the following experimental props to aggressively reduce memory usage on memory-restricted devices:

    The app can sacrifice certain features and/or runtime performance in exchange for a smaller memory footprint:

    new Deck({
    // ...
    _pickable: false,
    _typedArrayManagerProps: isMobile ? {overAlloc: 1, poolSize: 0} : null
    })
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/using-layers.html b/docs/developer-guide/using-layers.html index d9357aebb32..148b204fdf6 100644 --- a/docs/developer-guide/using-layers.html +++ b/docs/developer-guide/using-layers.html @@ -4,13 +4,13 @@ Using Layers | deck.gl - - + +

    Using Layers

    The "Layer" is a core concept of deck.gl. A deck.gl layer is a packaged visualization type that takes a collection of datums, associate each with positions, colors, extrusions, etc., and renders them on a map.

    deck.gl provides an extensive layer catalog and is designed to compose many layers together to form complex visuals.

    Constructing a Layer Instance

    A layer is instantiated with a properties object:

    import {ScatterplotLayer} from 'deck.gl';

    const layer = new ScatterplotLayer({
    id: 'bart-stations',
    data: [
    {name: 'Colma', passengers: 4214, coordinates: [-122.466233, 37.684638]},
    {name: 'Civic Center', passengers: 24798, coordinates: [-122.413756,37.779528]},
    ...
    ],
    stroked: false,
    filled: true,
    getPosition: d => d.coordinates,
    getRadius: d => Math.sqrt(d.passengers),
    getFillColor: [255, 200, 0]
    });

    The properties are settings that the layer uses to build the visualization. Users of a layer typically specify the following types of props:

    Layer ID

    The id prop is the unique identifier of this layer among all layers. Constructing a new layer instance in its own does not have any performance impact, as deck.gl only does the expensive calculations when a layer is created (an id appearing for the first time) or updated (different props are passed in for the same id). Read more about this in layer lifecycle.

    It is recommend that this prop is set explicitly to avoid collision.

    Data

    The data prop specifies data source of this layer's visualization. The value is expected to be a collection (typically a JavaScript array) of data objects with similar structure, such as rows in a table. deck.gl layers are able to handle millions of data objects very efficiently.

    The value of this prop can be Array, Map, Set, any object that contains a length field, a Promise that resolves to any of the above, or an URL to a JSON array. See data prop documentation for details.

    Accessors

    An accessor is a prop that maps an object in data to its visual configuration, e.g. the radius of a circle, the color of a line, etc. All accessor prop names start with get.

    If an accessor prop is set to a function, when the layer is about to be drawn on screen for the first time, the layer will traverse the data stream and call the accessor function with each element.

    The accessor function receives two arguments:

    • object - the current element in the data stream. If data is an array or an iterable, the element of the current iteration is used. If data is a non-iterable object, this argument is always null.
    • objectInfo (Object) - contextual information of the current element. Contains the following fields:
      • index (Number) - the index of the current iteration
      • data - the value of the data prop
      • target (Array) - a pre-allocated array. The accessor function can optionally fill data into this array and return it, instead of creating a new array for every object. In some browsers this improves performance significantly by reducing garbage collection.

    The accessor function is typically expected to return either a number or an array.

    Some accessors also support constant values instead of functions. When a constant value is provided, it is applied to all objects in the data stream.

    Other Layer Props

    The rest of the props are typically numeric or boolean values that apply to the whole layer. These include props that define the render options (opacity, extrusion of the PolygonLayer, font family of the TextLayer, etc.), coordinate system, and interactivity.

    Rendering Layers

    deck.gl allows you to render multiple layers using the same or different data sets. You simply provide an array of layer instances and deck.gl will render them in order (and handle interactivity when hovering clicking etc).

    This allows you to compose visualizations using several primitive layers.

    import {PathLayer, ScatterplotLayer, ArcLayer} from '@deck.gl/layers';

    // A layers array contains deck.gl layer instances. It can also be nested, or contain empty objects
    const layers = [
    new PathLayer({id: 'paths', data: ...}),
    shouldRenderPoints ? [
    new ScatterplotLayer({id: 'big-points', data: ...}),
    new ScatterplotLayer({id: 'small-points', data: ...})
    ] : null,
    new ArcLayer({id: 'arcs', data: ...})
    ];
    // Use with pure JS
    import {Deck} from '@deck.gl/core';
    const deck = new Deck({...});
    deck.setProps({layers});

    // Use with React
    import DeckGL from '@deck.gl/react';
    <DeckGL ... layers={layers} />

    FAQ

    Should I be Creating New Layers on Every Render?

    The Reactive Programming Paradigm

    deck.gl's architecture is based on the reactive programming paradigm:

    • In a reactive application, a complete UI description is "re-rendered" every time something in the application state changes (in the case of a deck.gl application, a new list of layers is created whenever something changes).
    • The UI framework (in this case, deck.gl) makes the choices about what to update, by comparing (or "diffing") the newly rendered UI description with the last rendered UI description.
    • The framework then makes the minimal necessary changes to account for the differences, and then redraws.
    • The required changes are made to "GPU state" in case of deck.gl, and to the Browser's DOM (HTML element tree) in case of React.

    Creating Layer Instances Is Cheap

    The deck.gl model means that applications are expected to create a new set of layers every time application state changes, which can seem surprisingly inefficient to someone who hasn't done reactive programming before. The trick is that layers are just descriptor objects that are very cheap to instantiate, and internally, the new layers are efficiently matched against existing layers so that no updates are performed unless actually needed.

    So, even though the application creates new "layers", those layers are only "descriptors" containing props that specify what needs to be rendered and how. All calculated state (WebGL2/WebGPU "programs", "vertex attributes" etc) are stored in a state object and this state object is moved forward to the newly matched layer on every render cycle. The new layer ends up with the state of the old layer (and the props of the new layer), while the old layer is simply discarded for garbage collection.

    The application does not have to be aware about this, as long as it keeps rendering new layers with the same id they will be matched and the existing state of that layer will be updated accordingly.

    The constant creation and disposal of layer instances may seem wasteful, however the creation and recycling of JavaScript objects is quite efficient in modern JavaScript environments, and this is very similar to how React works where every render cycle generates a new tree of ReactElement instances, so the model is proven.

    For more details on layer creation, update and destruction, read about Layer Lifecycle.

    Why Doesn't My Layer Update with New Props?

    Since the reactive programming frameworks conceptually render the entire UI every render cycle, and achieves efficiency by comparing and "diffing" changes between render cycles, it is important that comparisons are fast. Because of this, deck.gl uses shallow equality as the default comparison method for most props.

    An exception is the accessors. Changing the value of an accessor (i.e. supplying a different function to the accessor prop) will not in itself trigger an attribute update. This is because the function identity is a poor indicator of whether an update is needed, and the convenience of using local functions as prop values.

    Consider the code below, getRadius is shallowly changed every time render() is called, even if its execution result would not change:

    function render() {
    const layer = new ScatterplotLayer({
    ...
    getColor: x => x.color, // this creates a new function every render
    getRadius: this._getRadius.bind(this) // bind generates a new function every render
    });
    deck.setProps([layer]);
    }

    In another example, getColor is shallowly changed, so would its execution result:

    const DATA = [...];

    function setPillColor(index, color) {
    DATA[index].pill = color;
    render();
    }

    function render() {
    const layer = new ScatterplotLayer({
    data: DATA,
    ...
    getColor: object => object.pill === 'red' ? [255, 0, 0] : [0, 0, 255], // Does not trigger an attribute update!
    });
    deck.setProps([layer]);
    }

    There is no way for deck.gl to know what the programmer intended just by looking at or comparing the functions that are supplied to a Layers accessor props. Because recalculating attributes can be potentially expensive, deck.gl by default ignores shallow changes in accessor props. This is designed to provide the best performance to the most common use cases without compromising convenience.

    Instead, the updateTriggers property gives you fine grained control, enabling you to tell deck.gl exactly which attributes need to change, and when.

    Read more about this behavior in Performance Optimization.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/using-lighting.html b/docs/developer-guide/using-lighting.html index c334f1369c3..8a86892dabc 100644 --- a/docs/developer-guide/using-lighting.html +++ b/docs/developer-guide/using-lighting.html @@ -4,13 +4,13 @@ Using Lighting | deck.gl - - + +

    Using Lighting

    A deck.gl lighting effect is a visual approximation of environment illumination based on simplified models to make rendering appear more realistic.

    To enable lighting in deck.gl, it is required that both the lighting effect and material instances are properly instantiated.

    Interactive demo of LightingEffect

    Constructing A Lighting Effect Instance

    A LightingEffect can be instantiated with a lights object:

    import {AmbientLight, PointLight, DirectionalLight, LightingEffect} from '@deck.gl/core';

    // create ambient light source
    const ambientLight = new AmbientLight({
    color: [255, 255, 255],
    intensity: 1.0
    });
    // create point light source
    const pointLight = new PointLight({
    color: [255, 255, 255],
    intensity: 2.0,
    // use coordinate system as the same as view state
    position: [-125, 50.5, 5000]
    });
    // create directional light source
    const directionalLight = new DirectionalLight({
    color: [255, 255, 255],
    intensity: 1.0,
    direction: [-3, -9, -1]
    });
    // create lighting effect with light sources
    const lightingEffect = new LightingEffect({ambientLight, pointLight, directionalLight});

    The lights has all the light sources that the lighting effect uses to build the visualization. Users typically specify the following types of light sources:

    Constructing A Material Instance

    A material is a plain JavaScript object representing a lighting model specified per layer. Properties are ambient (number 0-1), diffuse (number 0-1), shininess (number > 0), specularColor (array [0-255, 0-255, 0-255]). Setting a material property to the value true will set all properties to their defaults, which are:

    {
    ambient: 0.35,
    diffuse: 0.6,
    shininess: 32,
    specularColor: [30, 30, 30]
    }

    Using Materials

    new GeoJsonLayer({
    id: 'geojson-layer',
    // layer props
    ...
    // lighting only applies to extruded polygons
    extruded: true,
    // specify material properties per layer
    material
    });

    Refer to each layer's documentation to see if the material prop is supported.

    Using Effects

    Pure JS

    import {Deck, LightingEffect} from '@deck.gl/core';
    import {GeoJsonLayer} from '@deck.gl/layers';

    const lightingEffect = new LightingEffect({
    ...
    });

    const INITIAL_VIEW_STATE = {
    latitude: 49.254,
    longitude: -123.13,
    zoom: 11,
    pitch: 45
    };
    const deckgl = new Deck({
    canvas: 'my-deck-canvas',
    initialViewState: INITIAL_VIEW_STATE,
    controller: true,
    // add lighting effect to deck
    effects: [lightingEffect],
    layers: [new GeoJsonLayer({
    ...
    })]
    });

    React

    import DeckGL from '@deck.gl/react';
    import {LightingEffect} from '@deck.gl/core';
    import {GeoJsonLayer} from '@deck.gl/layers';

    const lightingEffect = new LightingEffect({
    ...
    });

    const INITIAL_VIEW_STATE = {
    latitude: 49.254,
    longitude: -123.13,
    zoom: 11,
    pitch: 45
    };

    <DeckGL
    initialViewState={INITIAL_VIEW_STATE}
    controller={true}
    effects={[lightingEffect]}
    layers={[new GeoJsonLayer({
    ...
    })]}
    />

    Remarks

    • A default lighting effect is created in deck when user doesn't provide one.
    • A default material is created in layers which support material prop.
    • Lighting is only applied to extruded polygons or point clouds.
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/view-state-transitions.html b/docs/developer-guide/view-state-transitions.html index 0f1aa173fb1..e24376ef774 100644 --- a/docs/developer-guide/view-state-transitions.html +++ b/docs/developer-guide/view-state-transitions.html @@ -4,14 +4,14 @@ View State Transitions | deck.gl - - + +

    View State Transitions

    View state transitions provide smooth and visually appealing transitions when ViewState change from one state to the other.

    Transitions are supported by adding the following fields when setting Deck's viewState or initialViewState prop:

    • transitionDuration (Number|String, optional, default: 0) - Transition duration in milliseconds, default value 0, implies no transition. When using FlyToInterpolator, it can also be set to 'auto' where actual duration is auto calculated based on start and end viewports and is linear to the distance between them. This duration can be further customized using speed parameter to FlyToInterpolator constructor.
    • transitionEasing (Function, optional, default: t => t) - Easing function that can be used to achieve effects like "Ease-In-Cubic", "Ease-Out-Cubic", etc. Default value performs Linear easing. (list of sample easing functions: http://easings.net/)
    • transitionInterpolator (Object, optional, default: LinearInterpolator) - An interpolator object that defines the transition behavior between two viewports, deck.gl provides LinearInterpolator and FlyToInterpolator. Default value, LinearInterpolator, performs linear interpolation on view state fields. FlyToInterpolator animates ViewStates similar to MapBox flyTo API and applicable for MapState, this is pretty useful when camera center changes by long distance. But a user can provide any custom implementation for this object using TransitionInterpolator base class.
    • transitionInterruption (Enum, optional, default: TRANSITION_EVENTS.BREAK) - This field controls how to process a new view state change that occurs while performing an existing transition. This field has no impact once transition is complete. Here is the list of all possible values with resulting behavior.
    TRANSITION_EVENTSResult
    BREAKCurrent transition will stop at the current state and next view state update is processed.
    SNAP_TO_ENDCurrent transition will skip remaining transition steps and view state is updated to final value, transition is stopped and next view state update is processed.
    IGNOREAny view state update is ignored until current transition is complete, this also includes view state changes due to user interaction.
    • onTransitionStart (Functional, optional) - Callback fires when requested transition starts.
    • onTransitionInterrupt (Functional, optional) - Callback fires when transition is interrupted.
    • onTransitionEnd (Functional, optional) - Callback fires when transition ends.

    Usage

    Sample code that provides flyTo style transition to move camera from current location to NewYork city.

    import React, {useState, useCallback} from 'react';
    import DeckGL, {FlyToInterpolator} from 'deck.gl';
    import {StaticMap} from 'react-map-gl';

    function App() {
    const [initialViewState, setInitialViewState] = useState({
    latitude: 37.7751,
    longitude: -122.4193,
    zoom: 11,
    bearing: 0,
    pitch: 0,
    });

    const goToNYC = useCallback(() => {
    setInitialViewState({
    longitude: -74.1,
    latitude: 40.7,
    zoom: 14,
    pitch: 0,
    bearing: 0,
    transitionDuration: 8000,
    transitionInterpolator: new FlyToInterpolator()
    })
    }, []);

    return (
    <div>
    <DeckGL
    initialViewState={initialViewState}
    controller={true}
    >
    <StaticMap />
    </DeckGL>

    <button onClick={goToNYC}>New York City</button>
    </div>
    );
    }

    Sample code to get continuous rotations along vertical axis until user interrupts by rotating the map by mouse interaction. It uses LinearInterpolator and restricts transitions for bearing prop. Continuous transitions are achieved by triggering new transitions using onTransitionEnd callback.

    import React, {useState, useCallback} from 'react';
    import DeckGL from 'deck.gl';
    import {StaticMap} from 'react-map-gl';

    const transitionInterpolator = new LinearInterpolator(['bearing']);

    function App() {
    const [initialViewState, setInitialViewState] = useState({
    longitude: -122.45,
    latitude: 37.78,
    zoom: 12
    });

    const rotateCamera = useCallback(() => {
    setInitialViewState(viewState => ({
    ...viewState,
    bearing: viewState.bearing + 120,
    transitionDuration: 1000,
    transitionInterpolator,
    onTransitionEnd: rotateCamera
    }))
    }, []);

    return (
    <DeckGL
    initialViewState={initialViewState}
    controller={true}
    onLoad={rotateCamera}
    >
    <StaticMap />
    </DeckGL>
    );
    }

    Interpolators

    The following interpolator classes are available out-of-the-box:

    You can also implement a custom interpolator. See TransitionInterpolator.

    Remarks

    Deck's transition model is "set and forget": the values of the following props at the start of a transition carry through the entire duration of the transition:

    • transitionDuration
    • transitionInterpolator
    • transitionEasing
    • transitionInterruption

    The default transition behavior can always be intercepted and overwritten in the handler for onViewStateChange. However, if a transition is in progress, the properties that are being transitioned (e.g. longitude and latitude) should not be manipulated, otherwise the change will be interpreted as an interruption of the transition.

    - - + + \ No newline at end of file diff --git a/docs/developer-guide/viewports.html b/docs/developer-guide/viewports.html index 44e5179a39f..1e66df6b80f 100644 --- a/docs/developer-guide/viewports.html +++ b/docs/developer-guide/viewports.html @@ -4,13 +4,13 @@ Viewports | deck.gl - - + +

    Viewports

    If you are new to deck.gl's View and Viewport classes it is suggested that you start by reading up on Views before learning about Viewports. Most applications start by using View classes.

    Viewports

    deck.gl provides a hierarchy of Viewport classes. Unless an application needs to project or unproject coordinates in JavaScript, they typically do not directly create Viewport classes. Instead, Viewport classes are created under the hood based on the View class descriptors.

    Viewport classes are focused on mathematical operations such as coordinate projection/unprojection and calculation of projection matrices and GLSL uniforms.

    As mentioned, the basic Viewport class is a generic geospatially enabled version of the typical 3D "camera" class you would find in most 3D/WebGL2/OpenGL libraries, holding view and projection matrices and other uniforms needed by the vertex shaders.

    While the Viewport class can certainly be used directly if you need and are able to calculate your own projection matrices. it is often preferable to use a Viewport subclass that takes higher level parameters, such as camera position and viewing direction, or map coordinates, rather than working directly with matrices.

    In addition to generating WebGL2/WebGPU uniforms, the Viewport class also offers JavaScript functions to project and unproject as well as getting local distance scales.

    Overview of Viewports

    Viewport ClassDescription
    ViewportThe base viewport has to be supplied view and projection matrices. It is typically only instantiated directly if the application needs to work with viewports that have been supplied from external sources, such as the WebVR API.
    WebMercatorViewportWhile all Viewport subclasses are geospatially enabled, this class renders from a perspective that matches a typical top-down map and is designed to synchronize perfectly with a mapbox-gl base map (even in 3D enabled perspective mode).

    About Geospatial Positioning

    A special property of the Viewport classes that set them apart from a typical OpenGL Camera class is that it has the necessary plumbing to support non-linear Web Mercator projection.

    Like many things in deck.gl, Viewports can be positioned using a lng/lat "anchor" and a meter offset. See the article about coordinate systems for more information about this setup.

    Viewport Positioning

    Viewports allow the application to specify the position and extent of the viewport (i.e. the target rendering area on the screen). Viewport positions are specified in CSS coordinates (top left, non-retina, these coordinates are different from GPU coordinates, see remarks below). It is expected that CSS coordinates are most natural to work with, as the rest of the UI layout with other HTML components is done in the CSS coordinate system.

    • x,y coordinates - Viewports allow specification of x,y coordinates in the viewport in addition to width and height. These are only used for positioning (and not for calculation of intrinsic viewport parameters).

    Remarks

    • About viewport position and size coordinates: Internally, gl.viewport uses bottom-left, retina coordinates and normal CSS layout uses top left, non-retina coordinates. Translating between the two is surprisingly fiddly since both y coordinates and heights need to be stacked, and devicePixelRatio has to be matched to application settings, so having this translation taken care of by deck.gl was an explicit design goal.
    • For the project/unproject JavaScript functions, the default pixel coordinate system of the viewport is defined with the origin in the top left, where the positive x-axis goes right, and the positive y-axis goes down. That is, the top left corner is [0, 0] and the bottom right corner is [width - 1, height - 1]. The functions have a flag that can reverse this convention.
    • Non-pixel projection matrices are bottom-left.
    • Mercator coordinates are specified in "lng-lat" format [lng, lat, z] format (which naturally corresponds to [x, y, z]).
    • It is possible to query the WebMercatorViewport for a meters per pixel scale. Note that that distance scales are latitude dependent under web mercator projection (see http://wiki.openstreetmap.org/wiki/Zoom_levels for more details), so scaling will depend on the viewport center and any linear scale factor should only be expected to be locally correct.
    - - + + \ No newline at end of file diff --git a/docs/developer-guide/views.html b/docs/developer-guide/views.html index d3f70103954..9596c56138c 100644 --- a/docs/developer-guide/views.html +++ b/docs/developer-guide/views.html @@ -4,14 +4,14 @@ Views and Projections | deck.gl - - + +

    Views and Projections

    The same data can be drawn differently to screen based on what projection method is used. deck.gl's view system defines how one or more cameras should be set up to look at your data objects. The default view used in deck.gl is the MapView, which implements the Web Mercator projection. The view system is designed to be flexible and composable and can handle many different configurations such as side-by-side views, overlapping views etc. If you plan to work with non-geospatial data, or show more than a single standard viewport, it may be worth spending some time to get familiar with the View API.

    View classes enable applications to specify one or more rectangular viewports and control what should be rendered inside each view.

    A "minimap" app, implemented as two overlapping, partially synchronized MapViews

    A vehicle log rendered from the driver's perspective, implemented with FirstPersonView

    A graph, implemented with OrthographicView

    View, View State and Viewport

    View

    A View instance defines the following information:

    • A unique id.
    • The position and extent of the view on the canvas: x, y, width, and height.
    • Certain camera parameters specifying how your data should be projected into this view, e.g. field of view, near/far planes, perspective vs. orthographic, etc.
    • The controller to be used for this view. A controller listens to pointer events and touch gestures, and translates user input into changes in the view state. If enabled, the camera becomes interactive.

    To summarize, a View instance wraps the "hard configuration" of a camera. Once defined, it does not need to change frequently.

    deck.gl allows multiple views to be specified, allowing the application to divide the screen into multiple similar or different views. These views can be synchronized or separately controlled by the user or the application.

    View State

    A View instance must be used in combination with a viewState object. As the name suggests, the object describes the state of a View instance. The view state object defines the temporary properties of a view at runtime, like the camera position, orientation, zoom, etc. If the view is interactive, every time the user pans/rotates/zooms, the view state will be updated to reflect the change.

    To summarize, a viewState object describes the "real-time properties" of a camera. It may be updated continuously during interaction and/or transition.

    Viewport

    A Viewport instance is the camera itself. It is "resolved" from a View instance and its viewState. It handles the mathematical operations such as coordinate projection/unprojection, the calculation of projection matrices, and other GLSL uniforms needed by the shaders.

    Whenever viewState updates, the view creates a new viewport under the hood. Typically, the deck.gl user does not need to work with viewports directly. In certain use cases, the JavaScript functions offered by a Viewport instance can be handy for projecting and unprojecting coordinates.

    If you are using the Deck canvas as an overlay on a base map rendered by another library, you may need to update the viewport using the API provided by that library rather than by deck.gl.

    import {Deck, MapView} from '@deck.gl/core';

    const deck = new Deck({
    ...
    views: [new MapView()],
    onClick: ({layer, object}) => {
    if (layer) {
    // The viewport is a WebMercatorViewport instance
    const {viewport} = layer.context;
    const {longitude, latitude, zoom} = viewport.fitBounds([
    [object.minLng, object.minLat],
    [object.maxLng, object.maxLat]
    ]);
    // Zoom to the object
    deck.setProps({
    viewState: {longitude, latitude, zoom}
    });
    }
    }
    });

    Types of Views

    deck.gl offers a set of View classes that package the camera and controller logic that you need to visualize and interact with your data. You may choose one or multiple View classes based on the type of data (e.g. geospatial, 2D chart) and the desired perspective (top down, first-person, etc).

    Note that the set of view state parameters that will be used varies between Views. Consult each view class' documentation for a full list of parameters supported.

    View ClassUse CaseStatusDescription
    ViewThe base view has to be supplied with raw view and projection matrices. It is typically only instantiated directly if the application needs to work with views that have been supplied from external sources, such as the WebVR API.
    MapView (default)geospatialfull supportThis view renders data using the Web Mercator projection and is designed to match an external base map library such as Mapbox or Google Maps.
    GlobeViewgeospatialexperimentalThis view renders data as a 3D globe.
    FirstPersonViewgeospatialfull supportThe camera is positioned in a provided geolocation and looks in a provided direction, similar to that of a first-person game.
    OrthographicViewinfo-vis (2D)full supportThe camera looks at a target point from top-down. Does not rotate.
    OrbitViewinfo-vis (3D)full supportThe camera looks at a target point from a provided direction. Rotates around the target.

    Examples

    Using a View Class

    If the views prop of Deck is not specified, deck.gl will automatically create a MapView that fills the whole canvas, so basic geospatial applications often do not have to specify any Views.

    If using non-geospatial data, you will need to manually create a view that is appropriate for info-vis, e.g.:

    import {Deck, OrthographicView} from '@deck.gl/core';

    const deck = new Deck({
    ...
    views: new OrthographicView()
    });

    Using a View Class with View State

    If initialViewState is provided, deck.gl automatically tracks the view states of interactive views (used as a "stateful" component):

    import {Deck, MapView} from '@deck.gl/core';

    const deck = new Deck({
    ...
    views: new MapView(),
    controller: true, // applies to the first view
    initialViewState: {
    longitude: -122.4,
    latitude: 37.8,
    zoom: 10,
    pitch: 0,
    bearing: 0
    }
    });

    If you need to manage and manipulate the view state outside of deck.gl, you may do so by providing an external viewState prop (used as a "stateless" component). In this case, you also need to listen to the onViewStateChange callback and update the viewState object yourself:

    import React, {useState, useCallback} from 'react';
    import DeckGL from '@deck.gl/react';
    import {OrthographicView} from '@deck.gl/core';

    function App() {
    const [viewState, setViewState] = useState({
    target: [0, 0, 0],
    rotationX: 0,
    rotationOrbit: 0,
    zoom: 1
    })

    const onViewStateChange = useCallback(({viewState}) => {
    // Manipulate view state
    viewState.target[0] = Math.min(viewState.target[0], 10);
    // Save the view state and trigger rerender
    setViewState(viewState);
    }, []);

    return <DeckGL
    views={new OrthographicView()}
    controller={true}
    viewState={viewState}
    onViewStateChange={onViewStateChange}
    />;
    }

    Using Multiple Views

    deck.gl also supports multiple views by taking a views prop that is a list of View instances.

    Views allow the application to specify the position and extent of the viewport (i.e. the target rendering area on the screen) with x (left), y (top), width and height. These can be specified in either numbers or CSS-like percentage strings (e.g. width: '50%'), which is evaluated at runtime when the canvas resizes.

    Common examples in 3D applications that render a 3D scene multiple times with different "cameras":

    • To show views from multiple viewpoints (cameras), e.g. in a split screen setup.
    • To show a detail view (e.g, first person), and an overlaid, smaller "map" view (e.g. third person or top down, zoomed out to show where the primary viewpoint is).
    • To support stereoscopic rendering (e.g. VR), where left and right views are needed, providing the necessary parallax between left and right eye.
    • For rendering into offscreen framebuffers, which can then be used for e.g. advanced visual effects, screen shot solutions, overlays onto DOM elements outside of the primary deck.gl canvas (e.g. a video).

    Example of using with the WebVR API:

    import {Deck, View} from '@deck.gl/core';

    const deck = new Deck({
    ...
    views: [
    new View({
    id: 'left-eye',
    width: '50%',
    viewMatrix: leftViewMatrix,
    projectionMatrix: leftProjectionMatrix
    }),
    new View({
    id: 'right-eye',
    x: '50%',
    width: '50%',
    viewMatrix: rightViewMatrix,
    projectionMatrix: rightProjectionMatrix
    })
    ]
    });

    Views can also overlap, (e.g. having a small "mini" map in the bottom middle of the screen overlaid over the main view)

    import {Deck, FirstPersonView, MapView} from '@deck.gl/core';

    const deck = new Deck({
    ...
    views: [
    new FirstPersonView({
    id: 'first-person',
    controller: true
    }),
    new MapView({
    id: 'mini-map',
    x: '80%',
    y: '80%',
    height: '15%',
    width: '15%',
    clear: true,
    controller: true
    })
    ]
    });

    Using Multiple Views with View States

    When using multiple views, each View can either have its own independent view state, or share the same view state as other views. To define the view state of a specific view, add a key to the viewState object that matches its view id:

    import React, {useState, useCallback} from 'react';
    import DeckGL from '@deck.gl/react';
    import {FirstPersonView, MapView} from '@deck.gl/core';

    function App() {
    const [viewStates, setViewStates] = useState({
    longitude: -122.4,
    latitude: 37.8,
    pitch: 0,
    bearing: 0,
    zoom: 10
    });

    const onViewStateChange = useCallback(({viewId, viewState}) => {
    if (viewId === 'main') {
    setViewStates(currentViewStates => ({
    main: viewState,
    minimap: {
    ...currentViewStates.minimap,
    longitude: viewState.longitude,
    latitude: viewState.latitude
    }
    }));
    } else {
    setViewStates(currentViewStates => ({
    main: {
    ...currentViewStates.main,
    longitude: viewState.longitude,
    latitude: viewState.latitude
    },
    minimap: viewState
    }));
    }
    }, []);

    render() {
    return <DeckGL
    views={views: [
    new MapView({id: 'main', controller: true}),
    new MapView({id: 'minimap', x: 10, y: 10, width: '20%', height: '20%', controller: true})
    ]}
    viewState={viewStates}
    onViewStateChange={onViewStateChange}
    />;
    }
    }

    Rendering Layers in Multiple Views

    By default, all visible layers are rendered into all the views. This may not be the case if certain layers are designed to go into one particular view.

    The Deck class' layerFilter prop has access to information of the view via the viewport argument. It can be used to determine which layers to draw in which view:

    import {Deck, FirstPersonView, MapView} from '@deck.gl/core';
    import {MeshLayer, GeoJsonLayer} from '@deck.gl/layers';

    function layerFilter({layer, viewport}) {
    if (viewport.id === 'first-person' && layer.id === 'car') {
    // Do not draw the car layer in the first person view
    return false;
    }
    return true;
    }

    const deck = new Deck({
    ...
    layerFilter,
    layers: [
    new MeshLayer({id: 'car', ...}),
    new GeoJsonLayer({id: 'streets', ...})
    ],
    views: [
    new FirstPersonView({id: 'first-person', ...}),
    new MapView({id: 'mini-map', ...})
    ]
    });

    Some layers, including TileLayer, HeatmapLayer and ScreenGridLayer, perform expensive operations (data fetching/aggregation) on viewport change. Therefore, it is generally NOT recommended to render them into multiple views. If you do need to show e.g. tiled base map in multiple views, create one layer instance for each view and limit their rendering with layerFilter:

    const deck = new Deck({
    ...
    views: [
    new MapView({id: 'main', ...}),
    new MapView({id: 'mini-map', ...})
    ],
    layers: [
    new TileLayer({id: 'tiles-for-main', ...}),
    new TileLayer({id: 'tiles-for-mini-map', ...})
    ],
    layerFilter: ({layer, viewport} => {
    return layer.id === `tiles-for-${viewport.id}`;
    });
    });

    Starting with v8.5, Tile3DLayer supports rendering in multiple views with a single tile cache.

    Picking in Multiple Views

    deck.gl's built-in picking support extends naturally to multiple viewports. The picking process renders all viewports.

    Note that the pickInfo object does not contain a viewport reference, so you will not be able to tell which viewport was used to pick an object.

    Similar to the above example, you may control which layer is pickable in which view by supplying a layerFilter:

    function layerFilter({layer, viewport, isPicking}) {
    if (isPicking && viewport.id === 'first-person' && layer.id === 'car') {
    // Do not pick the car layer in the first person view
    return false;
    }
    return true;
    }

    Auto-Positioning React/HTML Components Behind Views

    This feature is currently only implemented in the React version of deck.gl.

    One of the core features of deck.gl is enabling perfectly synchronized visualization overlays on top other React components and DOM elements.

    When using a single View, the child components of DeckGL are positioned to fill the entire canvas. In this example the StaticMap component gets automatically positioned under the default MapView:

    import {StaticMap} from 'react-map-gl';
    import DeckGL from '@deck.gl/react';

    function App() {
    return (
    <DeckGL initialViewState={...} layers={...} controller={true}>
    <StaticMap />
    </DeckGL>
    );
    }

    When using multiple views, you can wrap component(s) in a View tag to align its position and size with a specific view. In the following example, the mapbox component is positioned and stretched to fit the "minimap" view:

    import {StaticMap} from 'react-map-gl';
    import {View, FirstPersonView, MapView} from '@deck.gl/core';
    import DeckGL from '@deck.gl/react';

    const views = [
    new FirstPersonView({id: 'first-person', ...}),
    new MapView({id: 'minimap', ...})
    ];

    function App() {
    return (
    <DeckGL views={views} initialViewState={...} layers={...} >
    <View id="minimap">
    <StaticMap />
    </View>
    </DeckGL>
    );
    }

    Performance Notes

    views and viewState props are deep compared to determine if anything changed, so there is little performance cost if new view instances are constructed each render.

    When views/viewState do change, new viewports are constructed. At this point, layers can get a chance to update their state, with the changeFlags argument containing viewportChanged: true. During interaction and transition, this may happen many times a second, raising performance concern if many layers need to recompute their states. By default, most layers ignore viewport changes, so the updateState lifecycle method do not get called if nothing else change.

    However, some layers do need to update state when viewport changes (e.g. the TileLayer). To make sure updateState is called, the layer needs to override shouldUpdateState.

    Read more in Layer Lifecycles.

    - - + + \ No newline at end of file diff --git a/docs/faq.html b/docs/faq.html index 69c6a1e1682..397da541b14 100644 --- a/docs/faq.html +++ b/docs/faq.html @@ -4,13 +4,13 @@ Frequently Asked Questions | deck.gl - - + +

    Frequently Asked Questions

    deck.gl is designed to be easy to use, however it is built on top of a complex technology (WebGL2/WebGPU) and supports a functional/reactive programming paradigm which many users are initially unfamiliar with.

    Installing npm modules, learning React, it is just too much!

    Not to worry, there are easier ways to use deck.gl:

    • Scripting - deck.gl has a scripting API that allows you get started just by adding a <script> statement to your HTML to use standard JavaScript. For an easy introduction to deck.gl scripting, see our blog post.

    • JSON Layers - It is even possible to use deck.gl without programming, by specifying deck.gl layers using a simple JSON format. See declarative playground.

    • kepler.gl - If scripting JSON is also too much, and you just want to play around with deck.gl visualizations in a polished application user interface, please check out kepler.gl.

    Layer pixels render randomly on top of each other

    You are likely experiencing a well-known issue in 3D graphics known as Z-fighting. The good news is that there are many ways to mitigate Z-fighting and deck.gl provides several mechanisms to help you. To get started, see the tips and tricks article.

    Should I really regenerate all layers every time something changes?

    Q: If I wanted to, say, change the opacity of a layer, Is my only option to create a new layer with the same Id and different properties?

    Yes. deck.gl is a "reactive" application architecture and is optimized to be used like this. The layer and its props are essentially only a "descriptor", deck.gl matches and "diffs" the layers under the hood and only does the necessary changes based on actual differences compared to last layer.

    This is a "functional" take on programming, and it parallels key ideas in the widely used React library. The reactive architecture has big benefits when writing larger programs, but these are not as evident when writing smaller scripts.

    If you are coming from a more "imperative" programming experience, it can initially seem a little counter-intuitive (especially from a performance perspective). But in spite of how the API looks, performance should be very good, if this is not the case you are likely doing something else wrong.

    For more information, see the article about updates.

    I can't "extend" my Custom Layer

    Q: Why does deck.gl call Object.seal on the Layer base class? I can't add members to my subclass.

    An important thing to understand about layer instances is that they are essentially just "disposable descriptors". All permanent state is stored in the layer.state object, which "moves" between layers.

    Every time you change your layer, you create a new layer and pass it to Deck or DeckGL. Internally DeckGL matches new layers with old layers, and the old layers are released for garbage collection. So storing data on the layer itself typically does not make sense.

    How do I debug deck.gl applications?

    Both deck.gl and luma.gl have powerful logging capabilities.

    See the article about debugging.

    How do I test deck.gl applications?

    Q: It is hard to test WebGL2/WebGPU based applications, assuming deck.gl is no different?

    Check out @deck.gl/test-utils, which (among other things) supports visual regression testing.

    - - + + \ No newline at end of file diff --git a/docs/get-started/getting-started.html b/docs/get-started/getting-started.html index 6c03db8bcbf..8d93a98b38e 100644 --- a/docs/get-started/getting-started.html +++ b/docs/get-started/getting-started.html @@ -4,13 +4,13 @@ Installing and Running Examples | deck.gl - - + +

    Installing and Running Examples

    Installation

    To install the deck.gl framework:

    npm install deck.gl --save

    or

    yarn add deck.gl

    The deck.gl module includes all deck.gl features and their dependencies. If you want to selectively install a subset of the features, see the Dependencies section below.

    Running the Examples

    The deck.gl repository contains an examples folder with a selection of small, standalone examples that could be good starting points for your application.

    You should be able to copy these folders to your preferred locations, and get them running simply as follows:

    Clone the deck.gl repo, if you haven't already

    git clone git@github.com:visgl/deck.gl.git

    For most consistent results, it is recommended that you check out the latest release branch (e.g. 8.0-release) instead of master when running examples.

    git checkout 8.0-release

    Change directory to the example you are interested in, e.g.

    cd deck.gl/examples/get-started/pure-js/basic

    Then install dependencies using the installer of your choice:

    npm install
    # or
    yarn

    and then running using:

    npm start

    If the example uses a mapbox base map you need a Mapbox access token

    export MapboxAccessToken={Your Token Here} && npm start

    If you want to build the example against the latest deck.gl source code in the cloned repo (rather than the published version of deck.gl listed in the examples package.json)

    npm run start-local

    The examples on the master branch are updated to use features from the latest, unreleased version of deck.gl. If some example doesn't work using npm start it can be worth trying npm run start-local.

    While all examples support npm run start-local, there are some caveats when running against local source. Most importantly, you must make sure to run npm install or yarn in the deck.gl root folder before running npm run start-local in an example folder.

    Selectively Install Dependencies

    A family of NPM modules are published as part of the deck.gl framework. The following tree shows their scope and dependencies:

    • @deck.gl/core - Core module that handles the GPU rendering pipeline, data management, and user interaction
      • @deck.gl/layers - Primitive layers that are the building blocks of all visualizations
        • @deck.gl/aggregation-layers - Advanced layers that aggregate data into alternative representations, e.g. heatmap, contour, hex bins, etc.
        • @deck.gl/geo-layers - Additional layers that handle geospatial use cases and GIS formats.
        • @deck.gl/mesh-layers - Additional layers that render 3D meshes and scene graphs.
      • @deck.gl/json - Declarative interface that supports specifying deck.gl layers and views using a JSON format.
      • @deck.gl/mapbox - An integration with the Mapbox custom layer API.
      • @deck.gl/react - React wrapper of deck.gl.
      • @deck.gl/test-utils - Testing utilities.

    For example, to render a PointCloudLayer, you may install:

    yarn add @deck.gl/core @deck.gl/layers

    To use the HexagonLayer with React, you need to install:

    yarn add @deck.gl/core @deck.gl/layers @deck.gl/aggregation-layers @deck.gl/react

    While installing submodules separately affords applications the maximum control over the dependencies that it pulls in, the submodule versions are expected to be synchronized manually in order to produce consistent results.

    The deck.gl master module includes all submodules except for @deck.gl/test-utils. Most bundling solutions (Webpack, Rollup etc.) offer tree-shaking capabilities that exclude unused exports from a production build.

    - - + + \ No newline at end of file diff --git a/docs/get-started/learning-resources.html b/docs/get-started/learning-resources.html index 20e8d1c1c3a..54353acacd7 100644 --- a/docs/get-started/learning-resources.html +++ b/docs/get-started/learning-resources.html @@ -4,13 +4,13 @@ Learning Resources | deck.gl - - + +

    Learning Resources

    API Documentation

    The documentation for the latest release can be found on deck.gl website.

    The documentation for previous releases are in the docs directory on the <version-release> branch in this repo.

    Technical Deep Dive

    An in-depth view into the technical details and architectural decisions behind deck.gl. Google Slides

    Live Demos

    The sources of deck.gl website demos can be found in the repo's examples directory. Most of the applications use React, although non-React templates are provided for developers from other ecosystems.

    Prototyping & Sharing

    PureJS examples in prototyping environments. These are great templates for feature testing and bug reporting:

    Community

    vis.gl's Medium blog

    Join our Slack workspace for learning and discussions.

    - - + + \ No newline at end of file diff --git a/docs/get-started/using-standalone.html b/docs/get-started/using-standalone.html index 34284e062a0..208a901bcfb 100644 --- a/docs/get-started/using-standalone.html +++ b/docs/get-started/using-standalone.html @@ -4,13 +4,13 @@ Using deck.gl without React | deck.gl - - + +

    Using deck.gl without React

    The deck.gl core library and layers have no dependencies on React, Mapbox GL, or Maplibre GL and can be used by any JavaScript application.

    Our get-started examples contains vanilla JavaScript templates that serve as a starting point for your application.

    Using @deck.gl/core

    @deck.gl/core is a submodule of deck.gl that contains no React dependency.

    The Deck class takes deck.gl layer instances and viewport parameters, and renders those layers as a transparent overlay.

    npm install @deck.gl/core @deck.gl/layers
    import {Deck} from '@deck.gl/core';
    import {ScatterplotLayer} from '@deck.gl/layers';

    const INITIAL_VIEW_STATE = {
    latitude: 37.8,
    longitude: -122.45,
    zoom: 15
    };

    const deckgl = new Deck({
    initialViewState: INITIAL_VIEW_STATE,
    controller: true,
    layers: [
    new ScatterplotLayer({
    data: [
    {position: [-122.45, 37.8], color: [255, 0, 0], radius: 100}
    ],
    getFillColor: d => d.color,
    getRadius: d => d.radius
    })
    ]
    });

    Using the Scripting API

    deck.gl also offers a standalone bundled version of the library - a native JavaScript scripting interface like that of d3.js. You can now use deck.gl in prototype environments such as Codepen, JSFiddle and Observable. This effort aims to make it easier for designers, creative coders and data scientists everywhere to leverage the GPU for interactive visualizations. The scripting API offers out-of-the-box integration with Mapbox GL JS or MapLibre GL JS. To add a base map to your visualization, you need to include the base map library and stylesheet:

    To use deck.gl in a scripting environment, include the standalone version in a script tag:

    <script src="https://unpkg.com/deck.gl@latest/dist.min.js"></script>
    <!-- optional if mapbox base map is needed -->
    <script src="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.js"></script>
    <link href="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.css" rel="stylesheet" />
    <!-- Allow the map to render in full screen -->
    <style>
    body {
    width: 100vw;
    height: 100vh;
    margin: 0;
    }
    </style>

    It exposes two global objects deck and luma. Any exports from the deck.gl core can be accessed by deck.<Class>.

    The scripting API's DeckGL class extends the core Deck class with some additional features such as Mapbox or Maplibre integration.

    //This example renders a scatterplot with DeckGL, on top of a basemap rendered with mapbox-gl, using a map style JSON from Carto.
    new deck.DeckGL({
    mapboxApiAccessToken: '<mapbox-access-token>',
    mapStyle: 'mapbox://styles/mapbox/light-v9',
    initialViewState: {
    longitude: -122.45,
    latitude: 37.8,
    zoom: 15
    },
    controller: true,
    layers: [
    new deck.ScatterplotLayer({
    data: [
    {position: [-122.45, 37.8], color: [255, 0, 0], radius: 100}
    ],
    getFillColor: d => d.color,
    getRadius: d => d.radius
    })
    ]
    });

    Check our codepen showcase and observable profile for examples.

    - - + + \ No newline at end of file diff --git a/docs/get-started/using-with-map.html b/docs/get-started/using-with-map.html index 2caf492462e..142b4a2cdd8 100644 --- a/docs/get-started/using-with-map.html +++ b/docs/get-started/using-with-map.html @@ -4,13 +4,13 @@ Base Maps | deck.gl - - + +

    Base Maps

    While deck.gl works independently without any map component, when visualizing geospatial datasets, a base map can offer invaluable context for understanding the overlay layers.

    Base Maps Renderers

    deck.gl has been designed to work in tandem with popular JavaScript base map providers. Depending on your tech stack, deck.gl's support for a particular base map solution may come with different level of compatibility and limitations.

    There are two types of integration between deck.gl and a base map renderer:

    • Overlaid: the Deck canvas is rendered over the base map as a separate DOM element. Deck's camera and the camera of the base map are synchronized so they pan/zoom together. This is the more robust option since the two libraries manage their renderings independently from each other. It is usually sufficient if the base map is 2D.

    Deck as overlay on top of the base map

    • Interleaved: Deck renders into the WebGL2 context of the base map. This allows for occlusion between deck.gl layers and the base map's labels and/or 3D features. The availability of this option depends on whether the base map solution exposes certain developer APIs, and may subject the user to bugs/limitations associated with such APIs.

    Note: Deck cannot render into a WebGL1 context. Check your base map solution for WebGL2 compatibility.

    Deck interleaved with base map layers

    LibraryPure JSReactOverlaidInterleavedDocs
    ArcGIS API for JavaScriptexamplelink
    Google Maps JavaScript APIexampleexamplelink
    harp.glexample
    Leafletexample
    Mapbox GL JSexampleexamplelink
    MapLibre GL JSexampleexamplelink
    OpenLayersexample

    It is also important to understand the difference between the JS library that renders the map and the map data provider. For example, you can use Mapbox GL JS with the Mapbox service, but also with any other service that hosts Mapbox Vector Tiles. When using a base map, be sure to follow the terms and conditions, as well as the attribution requirements of both the JS library and the data provider.

    - - + + \ No newline at end of file diff --git a/docs/get-started/using-with-react.html b/docs/get-started/using-with-react.html index 750178029ac..faa1d9f65a7 100644 --- a/docs/get-started/using-with-react.html +++ b/docs/get-started/using-with-react.html @@ -4,8 +4,8 @@ Using deck.gl with React | deck.gl - - + +
    @@ -24,7 +24,7 @@ callbacks on initial load and for each rendered frame. The DeckGL component also handles events propagation across layers, and prevents unnecessary calculations using React and deck.gl lifecycle functions.

    See full API doc for the DeckGL component.

    - - + + \ No newline at end of file diff --git a/docs/get-started/using-with-typescript.html b/docs/get-started/using-with-typescript.html index e2dbf269545..b736383584b 100644 --- a/docs/get-started/using-with-typescript.html +++ b/docs/get-started/using-with-typescript.html @@ -4,13 +4,13 @@ Using deck.gl with TypeScript | deck.gl - - + +

    Using deck.gl with TypeScript

    deck.gl v9+

    Starting from v9.0, deck.gl publishes official TypeScript types for all modules. If TypeScript is enabled in your project, imports from deck.gl packages will include types. Examples:

    // Values and types.
    import DeckGL from '@deck.gl/react';
    import {GeoJsonLayer} from '@deck.gl/layers';

    // Types only.
    import type {DeckGLRef} from '@deck.gl/react';
    import type {GeoJsonLayerProps} from '@deck.gl/layers';

    Help us improve the types by reporting issues or sending suggestions on GitHub!

    deck.gl v8

    Starting from v8.8, deck.gl publishes "public preview" TypeScript types via an opt-in only entry point. To use the official types in your application, find the following statements:

    import DeckGL from '@deck.gl/react';
    import {GeoJsonLayer} from '@deck.gl/layers';

    and replace the package name with @deck.gl/<module_name>/typed:

    import DeckGL from '@deck.gl/react/typed';
    import {GeoJsonLayer} from '@deck.gl/layers/typed';

    You can also import additional type definitions:

    import type {DeckGLRef} from '@deck.gl/react/typed';
    import type {GeoJsonLayerProps} from '@deck.gl/layers/typed';

    Note that the typed exports are a work in progress. They are not exposed by default to prevent any typing errors from breaking existing TypeScript applications. Help us improve them by reporting any issues or suggestions on GitHub!

    The typed exports will remain at the typed entry points throughout the rest of the 8.x releases. They will be exposed directly at the package roots starting in v9.0.

    Legacy Versions

    If you are using a version before v8.8, a third-party typings library is available.

    Find the compatible version of @danmarshall/deckgl-typings based on your deck.gl version:

    deck.gl versiondeckgl-typings version
    5.x.x1.x.x
    6.x.x2.x.x
    7.x.x3.x.x
    8.x.x4.x.x

    For example, for deck.gl 7.x, install the following package:

    npm install @danmarshall/deckgl-typings@^3.0.0

    Create a new file like deckgl.d.ts in your source directory with the following code:

    import * as DeckTypings from "@danmarshall/deckgl-typings"
    declare module "deck.gl" {
    export namespace DeckTypings {}
    }
    - - + + \ No newline at end of file diff --git a/docs/roadmap.html b/docs/roadmap.html index 78f6ae8ef07..680c9bd0b9c 100644 --- a/docs/roadmap.html +++ b/docs/roadmap.html @@ -4,13 +4,13 @@ Roadmap | deck.gl - - + +

    Roadmap

    Interested in what is coming down the road? We are trying to make the deck.gl roadmap as public as possible.

    We are currently using the following ways to share information about the direction of deck.gl.

    • Roadmap Document - (this document) A high-level summary of our current direction for future releases.
    • Blog - We use the vis.gl blog blog to share information about what we are doing.
    • RFCs - A wealth of technical detail around planned features is available in our RFCs (Requests For Comments). RFCs are technical writeups that describe a proposed feature. RFCs are available here.
    • Experimental exports - We are making unfinished features available as experimental exports. This gives users a clear indication about what is coming and even allow early adopters a chance to play with and provide comments on these features.
    • Experimental Layers - We are publishing a number of work-in-progress layers to make it easy to experiment with them in applications, see below.
    • Github issues - As always, github issues are a good way to see what is being discussed and join the discussions.

    Experimental Layers

    The @deck.gl/experimental-layers is available as of deck.gl v5.2 and contains early versions of future layers.

    There are a number of interesting layers in this module, however there are caveats:

    • We do not provide website documentation for these layers, so if you want to use these layers you may need to refer directly to the deck.gl source code.
    • While we make reasonable attempts to not break things, we do not guarantee that they will be stable between releases.
    • To prevent surprises, you may want to pin the version of the @deck.gl/experimental-layers module in your package.json.
    • Worst case, if you have to upgrade and some unexpected change happens, you can copy the source code of the affected layer(s) to your app.

    deck.gl v6.0

    These are some of the big priorities for our next release:

    • Aggregation - Improve and generalize automatic data aggregation (the current HexagonLayer and GridLayer are examples of what to expect).
    • Better Infovis Support - Better support for non-geospatial visualizations. (Don't worry if you are a geospatial user, deck.gl will remain a "geospatial-first" library since that is the more difficult use case.)
    • Better GPGPU/WebGL2 Support - Many stones are still left unturned here. Expect better performance, and new features for WebGL2 capable browsers (such as animations of entire attributes).
    • Visual Effects - Shadows, blur, postprocessing etc. This continues to be strong goal that we intend to make progress on.
    • Transitions and Animations - 5.0 introduces viewport transitions. Expect to see similar support for layer properties and attributes. Viewport transitions feature is available in the experimental namespace, and for additional details check the RFC.

    deck.gl v5.2

    These are some of things we tackled in our most recent release

    • Pure JavaScript Support - the deck.gl npm module currently has a hard dependency on React, however in v5.0 the internal code is effectively 100% independent of React. We intend to split the library into a core module exposing a "pure" JavaScript API and an (optional) module containing the React integration. (Don't worry if you are a React user, deck.gl will continue to be "React-first", designed from the ground up with the "reactive programming paradigm" in mind. We just want non-React users to also be able use deck.gl).
    • Multi-viewport Support - Extensive work has been done in v5.0, and we expect to finalize and make much of this functionality official in next release. For now, multiviewport features are available in the experimental namespace. For additional details check the RFCs.
    • Multiple Modules - In addition, in the future we plan to publish separate modules with deck.gl layers.
    • Code Size - deck.gl has gone through rapid development and we need to overhaul the code and build processes to reduce the size.

    Details on Planned Features

    Controller Support for Multiple Viewports

    TBA - This is a planned feature for a future release

    Restrict Event Handling to match Viewport Size - Controllers need to be able to be restricted to a certain area (in terms of event handling). Some controllers are completely general (just general drag up/down):

    • When working with a map controller, especially panning and zooming, the point under the mouse represents a grab point or a reference for the operation and mapping event coordinates correctly is imporant for the experience.
    • Controllers might not be designed to receive coordinates from outside their viewports.
    • Basically, if the map backing one WebMercator viewport doesn't fill the entire canvas, and the application wants to use a MapControls

    Controllers will also benefit from be able to feed multiple viewports of different types. There are limits to this of course, in particular it would be nice if for instance a geospatially neabled FirstPerson controller can feed both a FirstPersonViewport and a WebMercatorViewport. Various different viewports must be created from one set of parameters.

    Contrast this to deck.gl v4.1, where the idea was that each the of Viewport was associated with a specific controller (WebMercatorViewport has a MapController, etc).

    • Using Multiple Controllers An application having multiple viewports might want to use different interaction in each viewport - this has multiple complications...
    • Switching Controllers - An application that wants to switch between Viewports might want to switch between controllers, ideally this should not require too much coding effort.

    Experimental Features in Current Release

    Multi-Viewport Support

    Multi-viewport support was added during deck.gl 5.0 development. The APIs are still not considered stable so the related classes are exported as part of the "experimental" namespace, and in most cases.

    deck.gl now allows you to divide your screen into multiple viewports and render your layers from different perspectives, using the experimental _viewports property. It is e.g. possible to render a top-down map view next to a first person view for dramatic new perspectives on your data. E.g. an app can allow your users to "walk around" in the city onto which its data is overlaid.

    WebVR Support and Example

    Multi viewport support can be used to integrate with the WebVR API and create dual WebVR compatible viewports that render a first person view of your data for left and right eye respectively which will display as stereoscopic 3D in supporting hardware.

    Automatic Positioning of React Children under Viewports

    In addition, a new viewId React property can be added to DeckGL's children. This will synchronize the position of the react component with the corresponding deck.gl viewport, which makes it trivial to precisely position e.g. multiple "base maps" and other background or foreground HTML components in multi-viewport layouts. The viewportId prop also automatically hides the react children when a viewport with the corresponding id is not present or when viewport parameters can not be supported by the underlying map component.

    Orbit Controller and Orbit Viewport Support

    TBA

    All Viewports Now Geospatially Enabled

    All Viewport classes are now geospatially enabled: they now take an optional longitude/latitude reference point. In this mode, positions will be treated as meter offsets from that reference point per COORDINATE_SYSTEM.METER_OFFSET conventions.

    This means that you can now use a FirstPersonViewport (the successor to the PerspectiveViewport with layers encoded in COORDINATE_SYSTEM.LNG_LAT and COORDINATE_SYSTEM.METER_OFFSETS) and place a camera anywhere in the scene (in contrast to the WebMercatorViewport which only allows you to look "down" on a position on the map).

    Viewports even accept a modelMatrix to allow viewport/camera positions to be specified in exactly the same coordinates as METER_OFFSET layers, making it possible to place a camera at the exact location any of your existing data points without having to think or do any math.

    - - + + \ No newline at end of file diff --git a/docs/upgrade-guide.html b/docs/upgrade-guide.html index cb18d14faa9..c92db1a99e9 100644 --- a/docs/upgrade-guide.html +++ b/docs/upgrade-guide.html @@ -4,8 +4,8 @@ Upgrade Guide | deck.gl - - + +
    @@ -13,7 +13,7 @@ Check Using Lighting in developer guide for more details.

    Views

    v7.0 includes major bug fixes for OrbitView and OrthographicView. Their APIs are also changed for better clarity and consistency.

    Breaking Changes:

    • View state: zoom is now logarithmic in all View classes. zoom: 0 maps one unit in world space to one pixel in screen space.
    • View state: minZoom and maxZoom now default to no limit.
    • View state: offset (pixel-shift of the viewport center) is removed, use target (world position [x, y, z] of the viewport center) instead.
    • Constructor prop: added target to specify the viewport center in world position.
    • OrthographicView's constructor props left, right, top and bottom are removed. Use target to specify viewport center.
    • OrbitView's constructor prop distance and static method getDistance are removed. Use fovy and zoom instead.

    project Shader Module

    Deprecations:

    • project_scale -> project_size
    • project_to_clipspace -> project_common_position_to_clipspace
    • project_to_clipspace_fp64 -> project_common_position_to_clipspace_fp64
    • project_pixel_to_clipspace -> project_pixel_size_to_clipspace

    React

    If you are using DeckGL with react-map-gl, @deck.gl/react@^7.0.0 no longer works with react-map-gl v3.x.

    Upgrading from deck.gl v6.3 to v6.4

    OrthographicView

    The experimental OrthographicView class has the following breaking changes:

    • zoom is reversed (larger value means zooming in) and switched to logarithmic scale.
    • Changed view state defaults:
      • zoom - 1 -> 0
      • offset - [0, 1] -> [0, 0]
      • minZoom - 0.1 -> -10
    • eye, lookAt and up are now set in the OrthographicView constructor instead of viewState.

    ScatterplotLayer

    Deprecations:

    • outline is deprecated: use stroked instead.
    • strokeWidth is deprecated: use getLineWidth instead. Note that while strokeWidth is in pixels, line width is now specified in meters. The old appearance can be achieved by using lineWidthMinPixels and/or lineWidthMaxPixels.
    • getColor is deprecated: use getFillColor and getLineColor instead.

    Breaking changes:

    • outline / stroked no longer turns off fill. Use filled: false instead.

    GeoJsonLayer

    Breaking changes:

    • stroked, getLineWidth and getLineColor props now apply to point features (rendered with a ScatterplotLayer) in addition to polygon features. To revert to the old appearance, supply a _subLayerProps override:
    new GeoJsonLayer({
    // ...other props
    stroked: true,
    _subLayerProps: {
    points: {stroked: false}
    }
    });

    Upgrading from deck.gl v6.2 to v6.3

    GridLayer and HexagonLayer

    Shallow changes in getColorValue and getElevationValue props are now ignored by default. To trigger an update, use the updateTriggers prop. This new behavior is aligned with other core layers and improves runtime performance.

    Prop Types in Custom Layers

    Although the prop types system is largely backward-compatible, it is possible that some custom layers may stop updating when a certain prop changes. This is because the automatically deduced prop type from defaultProps does not match its desired usage. Switch to explicit descriptors will fix the issue, e.g. from:

    MyLayer.defaultProps = {
    prop: 0
    };

    To:

    MyLayer.defaultProps = {
    prop: {type: 'number', value: 0, min: 0}
    };

    Upgrading from deck.gl v6.1 to v6.2

    fp64

    The default coordinate system COORDINATE_SYSTEM.LNGLAT is upgraded to offer high-precision results in a way that is much faster and more cross-platform compatible. The fp64 layer prop is ignored when using this new coordinate system. You can get the old fp64 mode back by using coordinateSystem: COORDINATE_SYSTEM.LNGLAT_DEPRECATED with fp64: true.

    Upgrading from deck.gl v5.3 to v6.0

    luma.gl v6.0

    deck.gl v6.0 brings in luma.gl v6.0 which is a major release with a few breaking changes. The change that is most likely to affect deck.gl applications is probably that the way the GL constant is imported has changed. For details, see to the luma.gl Upgrade Guide.

    Pixel sizes

    Pixel sizes in line, icon and text layers now match their HTML/SVG counterparts. To achieve the same rendering output as v5, you should use half the previous value in the following props:

    • ArcLayer.getStrokeWidth
    • LineLayer.getStrokeWidth
    • IconLayer.getSize or IconLayer.sizeScale
    • TextLayer.getSize or TextLayer.sizeScale
    • PointCloudLayer.radiusPixels

    Accessors

    All layer accessors that support constant values have had their default values changed to constants. For example, ScatterplotLayer's default getRadius prop is changed from d => d.radius || 1 to 1. All dynamic attributes now must be explicitly specified. This change makes sure that using default values results in best performance.

    Views and Controllers

    • (React only) Viewport constraint props: maxZoom, minZoom, maxPitch, minPitch are no longer supported by the DeckGL component. They must be specified as part of the viewState object.
    • (React only) ViewportController React component has been removed. The functionality is now built in to the Deck and DeckGL classes.
    • Deck.onViewportChange(viewport) etc callbacks are no longer supported. Use Deck.onViewStateChange({viewState})
    • DeckGL.viewport and DeckGL.viewports props are no longer supported. Use DeckGL.views.

    ScreenGridLayer

    minColor and maxColor props are deprecated. Use colorRange and colorDomain props.

    Shader Modules

    Some previously deprecated project_ module GLSL functions have now been removed.

    Attribute

    isGeneric field of attribute object returned by AttributeManager's update callbacks is replaced by constant. For more details check attribute manager.

    Upgrading from deck.gl v5.2 to v5.3

    Viewport classes

    Continuing the changes that started in 5.2: while the base Viewport class will remain supported, the various Viewport subclasses are now deprecated. For now, if for projection purposes you need to create a Viewport instance matching one of your View instances you can use View.makeViewport:

    new MapView().makeViewport({width, height, viewState: {longitude, latitude, zoom}});

    Layer properties

    LayerRemoved PropNew PropComment
    ArcLayerstrokeWidthgetStrokeWidthCan be set to constant value
    LineLayerstrokeWidthgetStrokeWidthCan be set to constant value

    Pure JS applications

    Core layers are broken out from @deck.gl/core to a new submodule @deck.gl/layers. Non-React users of deck.gl should now install both submodules:

    npm install @deck.gl/core @deck.gl/layers

    And import layers from the new submodule instead of core:

    import {ScatterplotLayer} from '@deck.gl/layers';

    Users of deck.gl are not affected by this change.

    Upgrading from deck.gl v5.1 to v5.2

    DeckGL component

    • DeckGL.viewports and DeckGL.viewport are deprecated and should be replaced with DeckGL.views.

    Viewport classes

    • A number of Viewport subclasses have been deprecated. They should be replaced with their View counterparts.

    Experimental Features

    Some experimental exports have been removed:

    • The experimental React controller components (MapController and OrbitController) have been removed. These are now replaced with JavaScript classes that can be used with the Deck.controller / DeckGL.controller property.

    Upgrading from deck.gl v5 to v5.1

    N/A

    Upgrading from deck.gl v4.1 to v5

    Dependencies

    deck.gl 4.1 requires luma.gl as peer dependency, but 5.0 specifies it as a normal "dependency". This means that many applications no longer need to list luma.gl in their package.json. Applications that do might get multiple copies of luma.gl installed, which will not work. luma.gl will detect this situation during run-time throwing an exception, but npm and yarn will not detect it during install time. Thus your build can look successful during upgrade but fail during runtime.

    Layer Props

    Coordinate system related props have been renamed for clarity. The old props are no longer supported and will generate errors when used.

    LayerRemoved PropNew PropComment
    LayerprojectionModecoordinateSystemAny constant from COORDINATE_SYSTEM
    LayerprojectionOrigincoordinateOrigin[lng, lat]

    Note; There is also an important semantical change in that using coordinateSystem instead of projectionMode causes the superimposed METER_OFFSET system's y-axis to point north instead of south. This was always the intention so in some sense this was regarded as a bug fix.

    DeckGL component

    Following methods and props have been renamed for clarity. The semantics are unchanged. The old props are still available but will generate a deprecation warning.

    Old MethodNew MethodComment
    queryObjectpickObjectThese names were previously aligned with react-map-gl, but ended up confusing users. Since rest of the deck.gl documentation talks extensively about "picking" it made sense to stay with that terminology.
    queryVisibleObjectspickObjectsThe word "visible" was intended to remind the user that this function only selects the objects that are actually visible in at least one pixel, but again it confused more than it helped.

    Removed picking Uniforms

    Removed uniformComment
    renderPickingBufferpicking shader module
    pickingEnabledpicking shader module
    selectedPickingColorpicking shader module

    The shader uniforms are used for implementing picking in custom shaders, these uniforms are no longer set by the deck.gl. Custom shaders can now use luma.gl picking shader module.

    Initial WebGL State

    Following WebGL parameters are set during DeckGL component initialization.

    WebGL StateValue
    depthTesttrue
    depthFuncgl.LEQUAL
    blendFuncSeparate[gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]

    All our layers enable depth test so we are going set this state during initialization. We are also changing blend function for more appropriate rendering when multiple elements are blended.

    For any custom needs, these parameters can be overwritten by updating them in onWebGLInitialized callback or by passing them in parameters object to drawLayer method of Layer class.

    assembleShaders

    The assembleShaders function was moved to luma.gl in v4.1 and is no longer re-exported from deck.gl. As described in v4.1 upgrade guide please use Model class instead or import it from luma.gl.

    Removed Immutable support

    ScatterplotLayer and PolygonLayer supported immutable/ES6 containers using get method, due to performance reasons this support has been dropped.

    Upgrading from deck.gl v4 to v4.1

    deck.gl v4.1 is a backward-compatible release. Most of the functionality and APIs remain unchanged but there are smaller changes that might requires developers' attention if they develop custom layers. Note that applications that are only using the provided layers should not need to make any changes issues.

    Dependencies

    Be aware that deck.gl 4.1 bumps the luma.gl peer dependency from 3.0 to 4.0. There have been instances where this was not detected by the installer during update.

    Layer Life Cycle Optimization

    • shouldUpdateState - deck.gl v4.1 contains additional optimizations of the layer lifecycle and layer diffing algorithms. Most of these changes are completely under the hood but one visible change is that the default implementation of Layer.shouldUpdate no longer returns true if only the viewport has changed. This means that layers that need to update state in response to changes in screen space (viewport) will need to redefine shouldUpdate:
      shouldUpdateState({changeFlags}) {
    return changeFlags.somethingChanged; // default is now changeFlags.propsOrDataChanged;
    }

    Note that this change has already been done in all the provided deck.gl layers that are screen space based, including the ScreenGridLayer and the HexagonLayer.

    luma.gl Model class API change

    • deck.gl v4.1 bumps luma.gl to from v3 to v4. This is major release that brings full WebGL2 enablement to deck.gl. This should not affect you if you are mainly using the provided deck.gl layers but if you are writing your own layers using luma.gl classes you may want to look at the upgrade guide of luma.gl.

    The gl parameter is provided as a separate argument in luma.gl v4, instead of part of the options object.

    // luma.gl v4
    new Model(gl, {opts});
    // luma.gl v3
    new Model({gl, ...opts});

    Shader Assembly

    Custom layers are no longer expected to call assembleShaders directly. Instead, the new Model class from luma.gl v4 will take shaders and the modules they are using as parameters and assemble shaders automatically.

    // luma.gl v4
    const model = new Model(gl, {
    vs: VERTEX_SHADER,
    fs: FRAGMENT_SHADER,
    modules: ['fp64', ...],
    shaderCache: this.context.shaderCache
    ...
    }));

    // luma.gl v3
    const shaders = assembleShaders(gl, {
    vs: VERTEX_SHADER,
    fs: FRAGMENT_SHADER,
    modules: ['fp64', 'project64'],
    shaderCache: this.context.shaderCache
    });
    const model = new Model({
    gl,
    vs: shaders.vs,
    fs: shaders.fs,
    ...
    });

    Removed Layers

    LayerStatusReplacement
    ChoroplethLayerRemovedGeoJsonLayer, PolygonLayer and PathLayer
    ChoroplethLayer64RemovedGeoJsonLayer, PolygonLayer and PathLayer
    ExtrudedChoroplethLayerRemovedGeoJsonLayer, PolygonLayer and PathLayer
    • ChoroplethLayer, ChoroplethLayer64, ExtrudedChoroplethLayer

    These set of layers were deprecated in deck.gl v4, and are now removed in v5. You can still get same functionality using more unified, flexible and performant layers: GeoJsonLayer, PolygonLayer and PathLayer.

    Upgrading from deck.gl v3 to v4

    Changed Import: The DeckGL React component

    A small but breaking change that will affect all applications is that the 'deck.gl/react' import is no longer available. As of v4.0, the app is required to import deck.gl as follows:

    // V4
    import DeckGL from 'deck.gl';
    // V3
    import DeckGL from 'deck.gl/react';

    While it would have been preferable to avoid this change, a significant modernization of the deck.gl build process and preparations for "tree-shaking" support combined to make it impractical to keep supporting the old import style.

    Deprecated/Removed Layers

    LayerStatusReplacement
    ChoroplethLayerDeprecatedGeoJsonLayer, PolygonLayer and PathLayer
    ChoroplethLayer64DeprecatedGeoJsonLayer, PolygonLayer and PathLayer
    ExtrudedChoroplethLayerDeprecatedGeoJsonLayer, PolygonLayer and PathLayer
    EnhancedChoroplethLayerMoved to examplesPathLayer
    • ChoroplethLayer, ChoroplethLayer64, ExtrudedChoroplethLayer

    These set of layers are deprecated in deck.gl v4, with their functionality completely substituted by more unified, flexible and performant new layers: GeoJsonLayer, PolygonLayer and PathLayer.

    Developers should be able to just supply the same geojson data that are used with ChoroplethLayers to the new GeoJsonLayer. The props of the GeoJsonLayer are a bit different from the old ChoroplethLayer, so proper testing is recommended to achieve satisfactory result.

    • EnhancedChoroplethLayer

    This was a a sample layer in deck.gl v3 and has now been moved to a stand-alone example and is no longer exported from the deck.gl npm module.

    Developers can either copy this layer from the example folder into their application's source tree, or consider using the new PathLayer which also handles wide lines albeit in a slightly different way.

    Removed, Changed and Deprecated Layer Properties

    LayerOld PropNew PropComment
    LayerdataIteratorN/AProp was not functional in v3
    ScatterplotLayerradiusradiusScaleDefault has changed from 30 to 1
    ScatterplotLayerdrawOutlineoutline
    ScreenGridLayerunitWidthcellSizePixels
    ScreenGridLayerunitHeightcellSizePixels

    Note about strokeWidth props

    All line based layers (LineLayer and ArcLayerand theScatterplotLayerin outline mode) now use use shaders to render an exact pixel thickness on lines, instead of using theGL.LINE` drawing mode.

    This particular change was caused by browsers dropping support for this feature (Chrome and Firefox).

    Also GL.LINE mode rendering always had significant limitations in terms of lack of support for mitering, unreliable support for anti-aliasing and platform dependent line width limits so this should represent an improvement in visual quality and consistency for these layers.

    Removed prop: Layer.dataIterator

    This prop has been removed in deck.gl v4. Note that it was not functioning as documented in deck.gl v3.

    Renamed Props: The ...Scale suffix

    Props that have their name end of Scale is a set of props that multiply some existing value for all objects in the layers. These props usually correspond to WebGL shader uniforms that "scaling" all values of specific attributes simultaneously.

    For API consistency reasons these have all been renamed with the suffix ..Scale. See the property table above.

    Removed lifecycle method: Layer.willReceiveProps

    This lifecycle was deprecated in v3 and is now removed in v4. Use Layer.updateState instead.

    Changes to updateTriggers

    Update triggers can now be specified by referring to the name of the accessor, instead of the name of the actual WebGL attribute.

    Note that this is supported on all layers supplied by deck.gl v4, but if you are using older layers, they need a small addition to their attribute definitions to specify the name of the accessor.

    AttributeManager changes

    Removed method: AttributeManager.setLogFunctions

    Use the new static function AttributeManager.setDefaultLogFunctions to set loggers for all AttributeManagers (i.e. for all layers).

    Removed method: AttributeManager.addDynamic

    This method has been deprecated since version 2.5 and is now removed in v4. Use AttributeManager.add() instead.

    - - + + \ No newline at end of file diff --git a/docs/whats-new.html b/docs/whats-new.html index 6166e650910..b188c574deb 100644 --- a/docs/whats-new.html +++ b/docs/whats-new.html @@ -4,8 +4,8 @@ What's New | deck.gl - - + +
    @@ -16,7 +16,7 @@ The GeoJsonLayer is an example of a composite layer that instantiates other layers (in this case PathLayer, PolygonLayer and ScatterplotLayer) to do the actual rendering. This layer replaces the now deprecated family of ChoroplethLayers.

    PathLayer

    Takes a sequence of coordinates and renders them as a thick line with mitered or rounded end caps.

    PolygonLayer

    Each object in data is expected to provide a "closed" sequence of coordinates and renders them as a polygon, optionally extruded or in wireframe mode. Supports polygons with holes.

    IconLayer

    Allows the user to provide a texture atlas and a JSON configuration specifying where icons are located in the atlas.

    GridLayer

    A layer that draws rectangular, optionally elevated cells. A typical grid based heatmap layer. Differs from the ScreenGridLayer in that the cells are in world coordinates and pre aggregated.

    HexagonLayer

    A layer that draws hexagonal, optionally elevated cells.

    Point Cloud Layer

    Draws a LiDAR point cloud. Supports point position/normal/color.

    Improvements to all Layers

    Support for Per-Layer Model Matrix

    Each layer now supports a modelMatrix property that can be used to specify a local coordinate system for the data in that layer:

    • Model matrices can dramatically simplify working with data in different coordinate systems, as the data does not need to be pre-transformed into a common coordinate system.

    • Model matrices also enable interesting layer animation and composition possibilities as individual layers can be scaled, rotated, translated etc with very low computational cost (i.e. without modifying the data).

    UpdateTriggers now accept Accessor Names

    updateTriggers now accept Accessor Names.

    The updateTriggers mechanism in deck.gl v3 required the user to know the name of the vertex attribute controlled by an accessor. It is now possible to supply names of accessors.

    More intuitive mouse events

    • onHover is now only fired on entering/exiting an object instead of on mouse move.
    • onClick is now only fired on the picked layer instead of all pickable layers.

    New Features for Layer Subclassing

    Overridable Shaders

    All layers now have a getShaders method that can be overridden by subclasses, enables reuse of all layer code while just replacing one or both shaders, often dramatically reducing the amount of code needed to add a small feature or change to en existing layers.

    New Features for Layer Writers

    defaultProps

    Layers are now encouraged to define a defaultProps static member listing their props and default values, rather than programmatically declaring the props in constructor parameters etc. Using defaultProps means that many layer classes no longer need a constructor.

    AttributeManager now accepts new accessor field

    Can be a string or a an array of strings. Will be used to match updateTriggers accessor names with instance attributes.

    getPickingInfo()

    This method replaces the old pick() method and is expected to return an info object. Layers can block the execution of callback functions by returning null.

    Performance

    A number of performance improvements and fixes have been gradually introduced since deck.gl v3.0 was launched. While many are not new in v4.0, cumulatively they enable noticeably better framerates and a lighter footprint when big data sets are loaded, compared to the initial v3.0.0 version.

    The AttributeManager class now supports default logging of timings for attribute updates. This logging can be activated by simply setting deck.log.priority=2 in the console (levels 1 and 2 provide different amounts of detail). This can be very helpful in verifying that your application is not triggering unnecessary attribute updates.

    In addition, the new function AttributeManager.setDefaultLogFunctions allows the app to install its own custom logging functions to take even more control over logging of attribute updates.

    Library Improvements

    JavaScript build tooling continues to evolve and efforts have been made to ensure deck.gl supports several popular new tooling setups:

    • Dependency Reduction The number of npm dependencies (both in deck.gl, luma.gl and react-map-gl) have been reduced considerably, meaning that installing deck.gl and related modules will bring in less additional JavaScript code into your app, and your app will build and run faster.
    • Tree-shaking support: deck.gl and related libraries now publish a "module" entry point in package.json which points to a parallel distribution (deck.gl/dist-es6) that preserves the import and export statements. This should allow tree shaking bundlers such as webpack 2 and rollup to further reduce bundle size.
    • Pure ES6 source code: With few exceptions (e.g some JSX usage in examples), the source code of deck.gl and related modules are now all restricted to conformant ES6 (i.e. no ES2016 or ES2017, flow or similar syntax is used). This means that the source code can run directly (ie. without transpilation) in Node.js and modern browsers. You could potentially import code directly from deck.gl/src to experiment with this.
    • Buble support in examples. Buble is a nice alternative to babel if you have a simple app and don't need all the power of babel. Many of the examples now use buble for faster and smaller builds.

    Examples

    Code examples have been improved in several ways:

    • Multiple Examples deck.gl now provides multiple different examples in an examples folder, showing various interesting uses of deck.gl.
    • Stand Alone Examples Examples are now stand alone, each with its own minimal package.json and configuration files, enabling them to be easily copied and modified.
    • Hello World Examples Minimal examples for building with webpack 2 and browserify (previously called "exhibits") are still provided, and have been further simplified.
    • Layer Browser The main layer-browser example has been expanded into a full "layer and property browser" allowing for easy testing of layers.

    Deprecations

    The various Choropleth layers have been deprecated since deck.gl has new and better layers (GeoJsonLayer, PathLayer, PolygonLayer) that fill the same roles. The choropleth layers are still available but will not be maintained beyond critical bug fixes and will likely be removed in the next major version of deck.gl.

    A careful API audit has also been done to align property names between old and new layers. While this will makes the layers more consistent and the combined API easier to learn and work with, it does mean that some properties have been renamed, with the old name being deprecated, and in some very few cases, default values have changed.

    For more information on deprecations and how to update your code in response to these changes, please consult the deck.gl Upgrade Guide.

    deck.gl v3.0

    Release date: November, 2016

    Highlights

    • New website
    • Comprehensive documentation
    • All Core Layers updated (API, features, performance)
    • 64-bit Layers (High Precision)
    • METERS projection mode (High Precision)
    • Multi-Primitive Layer Support
    • Composite Layer Support

    React Integration

    • DeckGL (DeckGLOverlay in v2) component now requires a separate import (import DeckGL from 'deck.gl/react'). This allows the core deck.gl library to be imported by non-React applications without pulling in React.
    • Adds onLayerClick and onLayerHover props to the DeckGL React component.
    • The DeckGL component now cancels animation loop on unmount, important when repeatedly creating/destroying deck.gl components.
    • The DeckGL component no longer manages WebGL blending modes, as this is better done directly by layers.

    Layers

    • All layers now support accessors, removing the need for applications to transform data before passing it to deck.gl.
    • Layer props and accessors now always expect arrays (e.g. colors are expected as [r,g,b,a] instead of {r,g,b,a} etc).
    • line widths now takes device pixel ratio into account for more consistent look between displays
    • METERS projection mode allows specifying positions in meter offsets in addition to longitude/latitude.
    • Layers now receive viewport information from the DeckGL component. This implies that apps no longer need to pass the width, height, longitude, latitude, zoom, pitch, bearing and bearing props to each layer. These properties only need to be passed to the DeckGL react component.

    Base Layer

    • deepCompare prop replaced with more flexible dataComparator

    ArcLayer

    • Specify separate start and end color for each arc.
    • Renders smoother arcs, especially for bottom arc segments close to map
    • Fixes flickering last segments

    ScatterplotLayer

    • Adds drawOutline option.
    ScreenGridLayer
    • New name for deck.gl v2 GridLayer
    • Now have accessors (getPosition, getWeight)
    • Custom color ramps (minColor, maxColor)
    ChoroplethLayer
    • Now renders MultiPolygons and Polygons with holes
    HexagonLayer (REMOVED)
    • The v2 HexagonLayer has not yet been ported to v3.

    64bit layers

    A set of new high precision layers that support extreme zoom levels

    ArcLayer64 (NEW)
    ChoroplethLayer64 (NEW)
    ScatterplotLayer64 (NEW)
    64 bit ExtrudedChoroplethLayer (NEW)
    • Great for rendering 3D buildings on top of maps
    • Includes a basic shading model
    GeoJsonLayer (NEW, EXPERIMENTAL)
    • Initial composite layer, only Polygons for now.

    Sample Layers

    Sample layers now available through import 'deck.gl/samples';

    Changes affecting Custom Layers

    Streamlined life cycle methods

    • The Layer life cycle methods are now optimized for deck.gl's needs and no longer try to mimic React.
    • Limited compatibility with deck.gl v2 is provided but it is strongly recommended to update layers to the new methods

    Optimizations

    • Uint8Array encoding is now supported for color and picking color attributes, which provides significant GPU memory savings.

    GLSL package manager and modules

    • All layers now use assembleShaders to inject GLSL packages and platform fixes
    • GLSL project package
      • GLSL fp64 emulated double precision floating point package
      • GLSL fp32 package - 32bit improved precision library
        • Adds high precision version of trigonometry functions and tan
        • Especially for Intel GPUs

    deck.gl v2

    Release date: May 2016

    Highlights

    • 3D Perspective Mode
    • Performance: Huge under the hood refactor of layer update logic
    • Automatic attribute management (AttributeManager class)
    • Linux fixes - deck.gl and luma.gl now work on Linux.
    • Adopts luma.gl as default WebGL framework.
    • Retina display support
    • Support for disabling mercator project (experimental)

    React Integration

    • Ability to specify canvas ID and customize styles

    Layers

    • Added data deep comparison support

    ScatterplotLayer

    • Add per point radius support for the scatterplot-layer
    • Added per point color support for the scatterplot-layer
    • Fixed primitive distortion bug

    LineLayer (NEW)

    deck.gl v1

    Original release date: December 2015

    Initial open-source version of deck.gl, with five sample layers.

    - - + + \ No newline at end of file diff --git a/examples.html b/examples.html index 4210ab817dd..0855e72a4a9 100644 --- a/examples.html +++ b/examples.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/arc-layer.html b/examples/arc-layer.html index d8c76500a4a..a09efc15914 100644 --- a/examples/arc-layer.html +++ b/examples/arc-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/arcgis.html b/examples/arcgis.html index 15a83cdbf18..6e06d24f61c 100644 --- a/examples/arcgis.html +++ b/examples/arcgis.html @@ -4,13 +4,13 @@ deck.gl - - + +

    ArcGIS

    San Francisco 3D Buildings
    i

    Highly detailed LoD2 textured 3D buildings for downtown San Francisco in I3S format, visualized with deck.gl's Tile3DLayer. This data is provided by Precision Light Works (PLW).

    View Code ↗
    - - + + \ No newline at end of file diff --git a/examples/brushing-extension.html b/examples/brushing-extension.html index b61655a70c6..1950b4c3921 100644 --- a/examples/brushing-extension.html +++ b/examples/brushing-extension.html @@ -4,13 +4,13 @@ deck.gl - - + +

    BrushingExtension

    United States County-to-county Migration
    i

    People moving in and out of between 2009-2013

    Net gainNet loss

    Data source: US Census Bureau

    No. of Counties0
    No. of Arcs0

    Brush Radius: 200000
    Enable Brushing: true
    Width: 1
    Arc Opacity: 0.4
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/carto.html b/examples/carto.html index 21eb022a348..cd9d40e5f58 100644 --- a/examples/carto.html +++ b/examples/carto.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/collision-filter-extension.html b/examples/collision-filter-extension.html index 75c8c053b11..0ac34895080 100644 --- a/examples/collision-filter-extension.html +++ b/examples/collision-filter-extension.html @@ -4,13 +4,13 @@ deck.gl - - + +

    CollisionFilterExtension

    Mexico principals roads
    i

    Principal roads from Mexico

    Data sources:


    Avoid overlap: true
    Label spacing: 5
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/contour-layer.html b/examples/contour-layer.html index 4f97620312a..481b38aad2e 100644 --- a/examples/contour-layer.html +++ b/examples/contour-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/data-filter-extension.html b/examples/data-filter-extension.html index d661dd6c23a..27548b09624 100644 --- a/examples/data-filter-extension.html +++ b/examples/data-filter-extension.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/first-person-view.html b/examples/first-person-view.html index d572ae5da28..fc022933efd 100644 --- a/examples/first-person-view.html +++ b/examples/first-person-view.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/geojson-layer-paths.html b/examples/geojson-layer-paths.html index 9c7b0596278..ec12603e021 100644 --- a/examples/geojson-layer-paths.html +++ b/examples/geojson-layer-paths.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/geojson-layer-polygons.html b/examples/geojson-layer-polygons.html index da50dadad00..cc5fec5a228 100644 --- a/examples/geojson-layer-polygons.html +++ b/examples/geojson-layer-polygons.html @@ -4,13 +4,13 @@ deck.gl - - + +

    GeoJsonLayer (Polygons)

    Vancouver Property Value
    i

    The property value of Vancouver, BC

    Height of polygons - average property value per square meter of lot
    Color - value growth from last assessment

    -60%
    -30%
    0%
    30%
    60%
    90%
    120%

    Data source: City of Vancouver

    No. of Polygons0
    No. of Vertices0
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/globe-view.html b/examples/globe-view.html index 3d0437d98fa..f6d849a4f4c 100644 --- a/examples/globe-view.html +++ b/examples/globe-view.html @@ -4,13 +4,13 @@ deck.gl - - + +

    GlobeView

    Air Traffic During the Global Pandemic
    i

    The development of air traffic on selected dates between Feburary and October, 2020.

    Data source: Crowdsourced air traffic data from The OpenSky Network

    No. of Flights0
    View Code ↗
    - - + + \ No newline at end of file diff --git a/examples/google-3d-tiles.html b/examples/google-3d-tiles.html index bcd9acd9171..b411639a7fc 100644 --- a/examples/google-3d-tiles.html +++ b/examples/google-3d-tiles.html @@ -4,13 +4,13 @@ deck.gl - - + +

    Google 3D Tiles

    Photorealistic 3D Tiles
    i

    Colored building outlines draped over Google Photorealistic 3D Tiles.

    See full interactive Story Map

    CloseFar

    Buildings are colored according to the distance to the nearest tree

    Data sources:


    Distance to tree: 0
    Opacity: 0.2
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/google-maps.html b/examples/google-maps.html index 1a51fcdc21e..1271eac56fc 100644 --- a/examples/google-maps.html +++ b/examples/google-maps.html @@ -4,13 +4,13 @@ deck.gl - - + +

    Google Maps

    Animated Truck Routes
    i

    Interleaving 3D layers with Google Maps

    Low Poly Truck model by Arifido._ licensed under CC-BY-4.0


    Show paths: false
    Camera tracking: true
    View Code ↗
    - - + + \ No newline at end of file diff --git a/examples/heatmap-layer.html b/examples/heatmap-layer.html index 47dd3b801ee..16d74a3efed 100644 --- a/examples/heatmap-layer.html +++ b/examples/heatmap-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/hexagon-layer.html b/examples/hexagon-layer.html index 04f16e602f1..5667745d052 100644 --- a/examples/hexagon-layer.html +++ b/examples/hexagon-layer.html @@ -4,13 +4,13 @@ deck.gl - - + +

    HexagonLayer

    United Kingdom Road Safety
    i

    Personal injury road accidents in GB from 1979

    The layer aggregates data within the boundary of each hexagon cell

    Fewer AccidentsMore Accidents

    Data source: DATA.GOV.UK

    Accidents0

    Coverage: 0.7
    Radius: 2000
    Upper Percentile: 100
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/icon-layer.html b/examples/icon-layer.html index 63386e7b059..d71ea0fd4f0 100644 --- a/examples/icon-layer.html +++ b/examples/icon-layer.html @@ -4,13 +4,13 @@ deck.gl - - + +

    IconLayer

    Meteorites Landings
    i

    Data set from The Meteoritical Society showing information on all of the known meteorite landings.

    Hover on a pin to see the list of names

    Click on a pin to see the details

    Data source: NASA

    No. of Meteorites0

    Cluster: true
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/line-layer.html b/examples/line-layer.html index caf10e938ef..ebf5fb066af 100644 --- a/examples/line-layer.html +++ b/examples/line-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/mapbox.html b/examples/mapbox.html index 50308e3f1e8..71278b85ccc 100644 --- a/examples/mapbox.html +++ b/examples/mapbox.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/mask-extension.html b/examples/mask-extension.html index dddd6237a80..f863d4b9e99 100644 --- a/examples/mask-extension.html +++ b/examples/mask-extension.html @@ -4,13 +4,13 @@ deck.gl - - + +

    MaskExtension

    Flights over cities
    i

    Global flights, highlighting cities where a plane passed overhead in the last N mins

    Data source: Crowdsourced air traffic data from The OpenSky Network


    Animation speed: 3
    Show flights: true
    Minutes since flight: 30
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/multi-view.html b/examples/multi-view.html index a81535128eb..aa978066e7b 100644 --- a/examples/multi-view.html +++ b/examples/multi-view.html @@ -4,13 +4,13 @@ deck.gl - - + +

    Minimap

    Radio Stations in the United States
    i

    Radio stations and their service contour in the United States.

    Data source: Federal communications Commission


    Minimap: true
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/orthographic-view.html b/examples/orthographic-view.html index 5a57a4ee860..3ec1bf64e92 100644 --- a/examples/orthographic-view.html +++ b/examples/orthographic-view.html @@ -4,13 +4,13 @@ deck.gl - - + +

    OrthographicView

    World Weather Station Temperatures, 1880-2020
    i

    Annual average temperature recorded by the Global Historical Climatology Network, homogenized.

    -60
    -45
    -30
    -15
    0
    15
    30

    Data source: NOAA GHCNm v4

    Stations0
    Data points0

    View Code ↗
    - - + + \ No newline at end of file diff --git a/examples/plot.html b/examples/plot.html index 7013eed8bff..77f6d056573 100644 --- a/examples/plot.html +++ b/examples/plot.html @@ -4,13 +4,13 @@ deck.gl - - + +

    OrbitView

    3D Surface Explorer
    i

    Surface plot from a mathematical equation

    Hover on the plot to see the values


    Z = f(x, y): sin(x ^ 2 + y ^ 2) * x / 3.14
    Resolution: 200
    Grid: true
    View Code ↗
    - - + + \ No newline at end of file diff --git a/examples/point-cloud-layer.html b/examples/point-cloud-layer.html index 8eee6550163..79c39a003b3 100644 --- a/examples/point-cloud-layer.html +++ b/examples/point-cloud-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/scatterplot-layer.html b/examples/scatterplot-layer.html index 38230af4f88..ad6ab44df14 100644 --- a/examples/scatterplot-layer.html +++ b/examples/scatterplot-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/scenegraph-layer.html b/examples/scenegraph-layer.html index 0eedbef38a5..b6e3d82b921 100644 --- a/examples/scenegraph-layer.html +++ b/examples/scenegraph-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/screen-grid-layer.html b/examples/screen-grid-layer.html index cedf39bbee9..8fb79933ee0 100644 --- a/examples/screen-grid-layer.html +++ b/examples/screen-grid-layer.html @@ -4,13 +4,13 @@ deck.gl - - + +

    ScreenGridLayer

    Uber Pickup Locations In NewYork City
    i

    Pickup locations form April to September 2014.

    The layer aggregates data within the boundary of screen grid cells and maps the aggregated values to a dynamic color scale

    Data source: Uber TLC FOIL Response

    No. of Samples0

    Cell Size: 5
    GPU Acceleration: false
    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/terrain-extension.html b/examples/terrain-extension.html index b6230c9c89f..2d45e949b95 100644 --- a/examples/terrain-extension.html +++ b/examples/terrain-extension.html @@ -4,13 +4,13 @@ deck.gl - - + +

    TerrainExtension

    Tour de France routes
    i

    Reconstructed 3D terrain with official routes from Tour de France 2023.

    Data sources:

    Cycling Stage Tour de France 2023


    View Code ↗
    Hold down shift to rotate
    - - + + \ No newline at end of file diff --git a/examples/terrain-layer.html b/examples/terrain-layer.html index 54534388b5a..826934303c1 100644 --- a/examples/terrain-layer.html +++ b/examples/terrain-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/text-layer.html b/examples/text-layer.html index ad1894350ce..7ac4f8e98b5 100644 --- a/examples/text-layer.html +++ b/examples/text-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/tile-3d-layer.html b/examples/tile-3d-layer.html index 3145e63b16f..cba2399d3f7 100644 --- a/examples/tile-3d-layer.html +++ b/examples/tile-3d-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/tile-layer-non-geospatial.html b/examples/tile-layer-non-geospatial.html index b927845a7d5..032d1dfcf25 100644 --- a/examples/tile-layer-non-geospatial.html +++ b/examples/tile-layer-non-geospatial.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/tile-layer.html b/examples/tile-layer.html index 2f69420ca33..3cfdf4aca0a 100644 --- a/examples/tile-layer.html +++ b/examples/tile-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/trips-layer.html b/examples/trips-layer.html index b97055a24b3..fc7e76b50e9 100644 --- a/examples/trips-layer.html +++ b/examples/trips-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/examples/wms-layer.html b/examples/wms-layer.html index 2fc702830e8..4ef848bae1c 100644 --- a/examples/wms-layer.html +++ b/examples/wms-layer.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/index.html b/index.html index 93fa4032977..23ea13c00b3 100644 --- a/index.html +++ b/index.html @@ -4,13 +4,13 @@ Home | deck.gl - - + +

    deck.gl

    GPU-powered, highly performant large-scale data visualization

    GET STARTED

    deck.gl is a GPU-powered framework for visual exploratory data analysis of large datasets.


    A Layered Approach to Data Visualization

    deck.gl allows complex visualizations to be constructed by composing existing layers, and makes it easy to package and share new visualizations as reusable layers. We already offer a catalog of proven layers and we have many more in the works.

    High-Precision Computations in the GPU

    By emulating 64 bit floating point computations in the GPU, deck.gl renders datasets with unparalleled accuracy and performance.

    React Friendly

    deck.gl APIs are designed to reflect the reactive programming paradigm. Whether using Vanilla JS or the React interface, it can handle efficient WebGL2/WebGPU rendering under heavy data load.

    Integration with Base Map Providers

    While deck.gl works standalone without a base map, it plays nicely with your favorite base map providers such as Google Maps, Mapbox, ArcGIS and more. Where the base map library permits, deck.gl may interleave with 3D map layers to create seamless visualizations.

    - - + + \ No newline at end of file diff --git a/playground.html b/playground.html index 1a1fe0c28c1..b4214fed90c 100644 --- a/playground.html +++ b/playground.html @@ -4,13 +4,13 @@ deck.gl - - + + - - + + \ No newline at end of file diff --git a/search.html b/search.html index fca9badf986..d526c2f4189 100644 --- a/search.html +++ b/search.html @@ -4,13 +4,13 @@ Search the documentation | deck.gl - - + + - - + + \ No newline at end of file diff --git a/showcase.html b/showcase.html index 89574df0355..8952ad6cd50 100644 --- a/showcase.html +++ b/showcase.html @@ -4,13 +4,13 @@ Showcase | deck.gl - - + +

    Would you like us to feature your project? Let us know!

    Taxo&Map Biodiversity Map

    by Geomatico

    Biodiversity world map to browse the collections of the Natural Science Museum of Barcelona and other institutions. It loads of a dataset of 200,000 points with GPU filtering, providing high interactivity and refresh rates.

    Internet Speed Tests Map

    by Fair Internet Report

    An interactive map displaying 3.6 million speed tests from a single day in June 2023, animated seamlessly over a responsive MapBox layer. Deck.gl's performance and custom shaders ensure the animations run smoothly and vividly. Data is efficiently loaded from a binary format and accessed with array offsets in JavaScript for optimal performance.

    Radiance: solar panel positioning optimization

    by Radiance

    An interactive tool for panel density layout optimization and financial modeling for solar projects. Uses Google 3D tiles rendered in deck.gl to show realistic immersive environment. Visualize solar flux and hourly shade images on top of the 3D tiles.

    I3S Explorer

    Visualization and Debug Tool for I3S 3D geographic data

    Vizgen Single-Cell MERFISH Spatial Visualizer

    by Vizgen

    Vizgen's Interactive Single-Cell Spatial Visualizer enables users to explore single-cell gene expression data from our MERFISH Mouse Brain Receptor Map. Cells can be visualized using a UMAP embedding or the spatial coordinates within the brain - providing a detailed spatial map of the tissue.

    ISB Covid19

    by Data Visualization Center at Fred Hutch

    The Institute for Systems Biology Covid19 Atlas provides insights into how the immune system responds with disease progression. The website features single-cell multi-omics time-series data as well as clinical annotations on more than 400 patients.

    Descartes

    by Data Visualization Center at Fred Hutch

    Understanding the trajectory of a developing human requires understanding of how genes are regulated and expressed. The Descartes Human Cell Atlases features the largest single cell dataset generated to date. It contains data on ~5 million individual cells that when analyzed provides a comprehensive atlas of early human development.

    Viv

    Source code | by Gehlenborg Lab/Harvard Medical School

    Viv is a library for multiscale visualization of high-resolution, highly multiplexed bioimaging data on the web. It directly renders data in Bio-Formats-compatible Zarr and OME-TIFF formats. Avivator is a lightweight image viewer that showcases the capabilities of Viv. The development of Viv and Avivator was supported with funding from the National Institutes of Health and Harvard University.

    Flowmap.blue

    Source code | by Ilya Boyandin

    Flowmap.blue is a free tool for representing aggregated numbers of movements between geographic locations as flow maps. It is used to visualize urban mobility, commuting behavior, bus, subway and air travels, bicycle sharing, human and bird migration, refugee flows, freight transportation, trade, supply chains, scientific collaboration, epidemiological and historical data and many other topics.

    Isochronic Map

    Source code | Blog post | Blog post 2

    Remapping road network in major cities by travel times.

    Simulating the 2016 Primary

    by Andrew Pulcipher

    An interactive visualization of the 2016 Presidential primary election in Maricopa County that uses polling place operations research to simulate election day lines and voter walkoffs in real time.

    The Bad Bet

    ProPublica

    Data journalists use deck.gl to visualize how the revenue generated by video gambling machines in Illinois grow over time and how those revenues failed to meet the projections of legislators.

    SandDance

    by Microsoft | GitHub | Demo

    SandDance helps you find insights about your data with unit visualizations and smooth animated transitions. It uses deck.gl to render chart layouts described with Vega.

    Autonomous Visualization System

    GitHub | Demo

    A visualization protocol and toolkit for robotics data in the browser.

    Escape

    MIT Senseable City Laboratory, Singapore | About

    Escape is an inspirational flight search engine that helps you choose a destination and find the cheapest flight for your next vacation.

    BusRouter SG

    by cheeaun | data © Land Transport Authority | GitHub

    Explore bus stops and routes on the map for all bus services in Singapore, with realtime bus arrival times and per-bus-stop passing routes overview.

    FlightMapper

    by Dylan Babbs | Example map

    Map and explore your flight history with interactive visualizations and analytics.

    Kepler.gl

    GitHub | Example map

    Kepler.gl is a powerful web-based geospatial data analysis tool. Built on a high performance rendering engine and designed for large-scale data sets.

    Ascii Video Player

    Source code

    Uses the TextLayer API to convert pixels into characters on the fly. WebGL2 compatible browser is required.

    Wind Map

    Source code | Blog post

    GPU-based data interpolation and partical effects.

    Minecraft Chunk Viewer

    Source code | Blog post

    Rendering A Minecraft World With deck.gl.

    - - + + \ No newline at end of file