repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/luma/index.js
#!/usr/bin/env node // Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const Path = require('path'); const wrtc = require('wrtc'); const Fastify = require('fastify'); const Peer = require('simple-peer'); const {renderLesson, renderEvent} = require('./render'); const fastify = Fastify() .register(require('fastify-socket.io')) .register(require('fastify-static'), {root: Path.join(__dirname, 'public')}) .get('/', (req, reply) => reply.sendFile('video.html')); fastify.listen(8080) .then(() => fastify.io.on('connect', onConnect)) .then(() => console.log('server ready')); function onConnect(sock) { let cancelLesson = () => {}; const peer = new Peer({ wrtc, sdpTransform: (sdp) => { // Remove bandwidth restrictions // https://github.com/webrtc/samples/blob/89f17a83ed299ef28d45b933419d809b93d41759/src/content/peerconnection/bandwidth/js/main.js#L240 sdp = sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, ''); return sdp; } }); peer.on('close', closeConnection); peer.on('error', closeConnection); peer.on('data', onDataChannelMessage); sock.on('disconnect', () => peer.destroy()); sock.on('signal', (data) => { peer.signal(data); }); peer.on('signal', (data) => { sock.emit('signal', data); }); peer.on('connect', () => { const stream = new wrtc.MediaStream({id: `${sock.id}:video`}); const source = new wrtc.nonstandard.RTCVideoSource({}); stream.addTrack(source.createTrack()); peer.addStream(stream); cancelLesson = renderLesson( { id: sock.id, width: 800, height: 600, lesson: '14', animationProps: { startTime: Date.now(), engineTime: 0, tick: 0, tock: 0, time: 0, } }, source, ); }); function closeConnection(err) { console.log('connection closed' + (err ? ` (${err})` : '')); cancelLesson && cancelLesson({id: sock.id}); cancelLesson = null; sock.disconnect(true); err ? peer.destroy(err) : peer.destroy(); } function onDataChannelMessage(msg) { const {type, data} = (() => { try { return JSON.parse('' + msg); } catch (e) { return {}; } })(); switch (data && type) { case 'event': { return renderEvent(sock.id, data); } } } }
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/luma/README.md
# Luma.gl Server Side Rendering (SSR) and Streaming Server The back end to the [Viz-App](https://github.com/rapidsai/node/tree/main/modules/demo/viz-app) demo, using luma.gl for rendering. Streamed using webRTC utilizing [nvENC](https://docs.nvidia.com/video-technologies/video-codec-sdk/nvenc-video-encoder-api-prog-guide/). ## Featured Dependencies - @rapidsai/jsdom - @rapidsai/deckgl ## Data Requirements The demo will default to internal data, a pretty little teapot. ## Start To start the server: ```bash yarn start #NOTE: For the demo to work, run this in one terminal instance AND run the Viz-App in another terminal (use point cloud option) ```
0
rapidsai_public_repos/node/modules/demo/ssr/luma
rapidsai_public_repos/node/modules/demo/ssr/luma/render/index.js
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const Path = require('path'); const {nanoid} = require('nanoid'); const shm = require('shm-typed-array'); let numClients = 0; const clients = Object.create(null); const pendingEvents = Object.create(null); const pendingRenders = Object.create(null); const pendingResolves = Object.create(null); function renderEvent(id, event) { const queue = pendingEvents[id] || (pendingEvents[id] = []); queue.push(event); let removed = false; return () => { if (!removed) { removed = true; const i = queue.findIndex((x) => x === event); if (i !== -1) { queue.splice(i, 1); } } }; } function renderLesson(data, output) { const {id} = data; if (!clients[id]) { ++numClients; clients[id] = {data, output}; } Object.assign(clients[id].data, data); start(); return () => { if (clients[id]) { --numClients; delete clients[id]; sharedMemoryMap.delete(id); if (numClients === 0) { pause(); } } } } module.exports.renderEvent = renderEvent; module.exports.renderLesson = renderLesson; let intervalId = null; function start() { if (intervalId !== null) { return; } let workerId = -1; intervalId = setInterval(() => { for (const clientId in clients) { if (pendingRenders[clientId]) { continue; } const msgId = nanoid(); const {data} = clients[clientId] || {}; const events = pendingEvents[clientId] || []; const buffer = sharedMemoryMap.get(clientId, data); delete pendingEvents[clientId]; pendingRenders[clientId] = new Promise((r) => { pendingResolves[msgId] = r; }); pendingRenders[clientId].then(({frame, ...data}) => { delete pendingRenders[clientId]; if (clients[clientId]) { Object.assign(clients[clientId].data, data); clients[clientId].output.onFrame({...frame, data: buffer}); } }); workerId = (workerId + 1) % workers.length; workers[workerId].send({ id: msgId, type: 'render.request', data: {data, events, sharedMemoryKey: buffer.key}, }); } }, 1000 / 60); } function pause() { if (intervalId !== null) { clearInterval(intervalId); intervalId = null; } } const onWorkerExit = (wId, ...xs) => { console.log(`worker ${wId} exit:`, ...xs); }; const onWorkerError = (wId, ...xs) => { console.log(`worker ${wId} error:`, ...xs); }; const onWorkerClose = (wId, ...xs) => { console.log(`worker ${wId} close:`, ...xs); }; const onWorkerDisconnect = (wId, ...xs) => { console.log(`worker ${wId} disconnect:`, ...xs); }; function onWorkerMessage(wId, {id, type, data}) { switch (type) { case 'render.result': { const f = pendingResolves[id]; delete pendingResolves[id]; return f && f(data); } } } const sharedMemoryMap = { buffersByClientId: new Map(), get(id, {width, height}) { const map = this.buffersByClientId; const size = width * height * 3 / 2; if (!map.has(id)) { // map.set(id, shm.create(size, 'Uint8ClampedArray')); } else { const mem = map.get(id); if (mem.byteLength !== size) { shm.detach(mem.key); map.set(id, shm.create(size, 'Uint8ClampedArray')); } } return map.get(id); }, delete (id) { this.buffersByClientId.delete(id); } }; const workers = Array .from({length: 4}, () => require('child_process').fork(Path.join(__dirname, 'worker.js'), { cwd: __dirname, execArgv: ['--trace-uncaught'], serialization: 'advanced', stdio: ['pipe', 'inherit', 'inherit', 'ipc'], env: { ...process.env, DISPLAY: undefined, WAYLAND_DISPLAY: undefined, }, })) .map( (proc, i) => proc.on('exit', onWorkerExit.bind(proc, i)) .on('error', onWorkerError.bind(proc, i)) .on('close', onWorkerClose.bind(proc, i)) .on('message', onWorkerMessage.bind(proc, i)) .on('disconnect', onWorkerDisconnect.bind(proc, i)) // ); process.on('beforeExit', (code = 'SIGKILL') => { workers.forEach((worker) => { if (!worker.killed) { worker.send({type: 'exit'}); worker.kill(code); } }); }); console.log('num workers:', workers.length);
0
rapidsai_public_repos/node/modules/demo/ssr/luma
rapidsai_public_repos/node/modules/demo/ssr/luma/render/worker.js
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const Path = require('path'); const copyFramebuffer = require('./copy')(); const {RapidsJSDOM} = require('@rapidsai/jsdom'); const lessons = Path.dirname(require.resolve('@rapidsai/demo-luma.gl-lessons')); let loop = null; let jsdom = null; function render({data, events = [], sharedMemoryKey}) { const {lesson, width = 800, height = 600, animationProps} = data; if (loop) { loop = loop.restore(animationProps); } else { ({jsdom, loop} = createLoop(width, height, lesson)); } Object.assign(jsdom.window, {width, height}); events.filter(Boolean).forEach((event) => { try { jsdom.window.dispatchEvent(event); } catch (e) { console.error(e && e.stack || e); } }); const rendered = loop.waitForRender(); loop.start(); return rendered.then((loop) => ({ ...data, animationProps: loop.serialize(), frame: copyFramebuffer(loop, sharedMemoryKey), })); } function createLoop(width, height, lesson) { const state = {}; state.jsdom = new RapidsJSDOM({ glfwOptions: {width, height}, module: { path: Path.join(lessons, 'lessons', lesson), }, babel: { presets: [ // transpile all ESM to CJS ['@babel/preset-env', {targets: {node: 'current'}}], ...RapidsJSDOM.defaultOptions.babel.presets, ] }, onAnimationFrameRequested: immediateAnimationFrame(state), }); state.loop = state.jsdom.window.evalFn(() => { window.website = true; const AppAnimationLoop = require('./app').default; const {AnimationLoopSSR} = require('@rapidsai/deck.gl'); ((src, dst) => { dst.start = src.start; dst.pause = src.pause; dst.restore = src.restore; dst.serialize = src.serialize; dst._renderFrame = src._renderFrame; dst.onAfterRender = src.onAfterRender; dst.onBeforeRender = src.onBeforeRender; dst._initializeCallbackData = src._initializeCallbackData; dst._requestAnimationFrame = src._requestAnimationFrame; })(AnimationLoopSSR.prototype, AppAnimationLoop.prototype); const loop = new AppAnimationLoop({ width: window.width, height: window.height, createFramebuffer: true, }); loop.props._onAfterRender = ({_loop}) => { _loop.pause(); }; return loop; }); return state; } function immediateAnimationFrame(state) { let request = null; let flushing = false; const flush = () => { flushing = true; while (request && request.active) { const f = request.flush; request = null; f(); } flushing = false; }; return function onAnimationFrameRequested(r) { if (flushing) { return request = r; } if (state.loop._initialized) { return flush(request = r); } if (!request && (request = r)) { setImmediate(flush); } }; } module.exports.render = render; if (require.main === module) { const {fromEvent, EMPTY} = require('rxjs'); const {tap, groupBy, mergeMap, concatMap} = require('rxjs/operators'); fromEvent(process, 'message', (x) => x) .pipe(groupBy(({type}) => type)) .pipe(mergeMap((group) => { switch (group.key) { case 'exit': return group.pipe(tap(() => process.exit(0))); case 'render.request': return group // .pipe(concatMap(({data}) => render(data), ({id}, data) => ({id, data}))) // .pipe(tap((result) => process.send({...result, type: 'render.result'}))); } return EMPTY; })) .subscribe(); }
0
rapidsai_public_repos/node/modules/demo/ssr/luma
rapidsai_public_repos/node/modules/demo/ssr/luma/render/copy.js
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. const {CUDA, Uint8Buffer} = require('@rapidsai/cuda'); const {Buffer: DeckBuffer} = require('@rapidsai/deck.gl'); const {Framebuffer, readPixelsToBuffer} = require('@luma.gl/webgl'); const shm = require('shm-typed-array'); Object.defineProperty(Framebuffer, Symbol.hasInstance, { value: (x) => x?.constructor?.name === 'Framebuffer', }); module.exports = copyAndConvertFramebuffer; function copyAndConvertFramebuffer() { let i420DeviceBuffer = null; let rgbaDeviceBuffer = null; return ({gl, framebuffer}, sharedMemoryKey) => { const {width, height} = framebuffer; const rgbaByteLength = width * height * 4; const i420ByteLength = width * height * 3 / 2; if (rgbaDeviceBuffer?.byteLength !== rgbaByteLength) { rgbaDeviceBuffer?.delete({deleteChildren: true}); rgbaDeviceBuffer = new DeckBuffer(gl, { byteLength: rgbaByteLength, accessor: {type: gl.UNSIGNED_BYTE, size: 4}, }); } if (i420DeviceBuffer?.byteLength !== i420ByteLength) { i420DeviceBuffer = new Uint8Buffer(i420ByteLength); } // DtoD copy from framebuffer into our pixelbuffer readPixelsToBuffer( framebuffer, {sourceType: gl.UNSIGNED_BYTE, sourceFormat: gl.BGRA, target: rgbaDeviceBuffer}); // Map and unmap the GL buffer as a CUDA buffer rgbaDeviceBuffer.asMappedResource((glBuffer) => { const cuBuffer = glBuffer.asCUDABuffer(0, rgbaByteLength); // flip horizontally to account for WebGL's coordinate system (e.g. ffmpeg -vf vflip) CUDA.rgbaMirror(width, height, 0, cuBuffer); // convert colorspace from OpenGL's BGRA to WebRTC's IYUV420 CUDA.bgraToYCrCb420(i420DeviceBuffer, cuBuffer, width, height); }); // DtoH copy for output const out = shm.get(sharedMemoryKey, 'Uint8ClampedArray'); i420DeviceBuffer.copyInto(out); shm.detach(sharedMemoryKey); return {width, height, data: sharedMemoryKey}; }; }
0
rapidsai_public_repos/node/modules/demo/ssr/luma
rapidsai_public_repos/node/modules/demo/ssr/luma/public/video.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>WebRTC NVENC Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#2e2e2e" /> </head> <body style="background:#2e2e2e; margin:0;"> <video autoplay muted width="800" height="600"></video> <script src="https://cdn.jsdelivr.net/npm/[email protected]/simplepeer.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script> <script> const sock = io({ transports: ['websocket'], reconnection: false }); const video = document.querySelector('video'); const peer = new SimplePeer({ trickle: true, initiator: true, sdpTransform: (sdp) => { // Remove bandwidth restrictions // https://github.com/webrtc/samples/blob/89f17a83ed299ef28d45b933419d809b93d41759/src/content/peerconnection/bandwidth/js/main.js#L240 sdp = sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, ''); // Force h264 encoding by removing all VP8/9 codecs from the sdp sdp = onlyH264(sdp); return sdp; } }); // Negotiate handshake sock.on('signal', (data) => peer.signal(data)); peer.on('signal', (data) => sock.emit('signal', data)); // Server video stream peer.on('stream', (stream) => { ('srcObject' in video) ? (video.srcObject = stream) : (video.src = window.URL.createObjectURL(stream)); // for older browsers video.play(); }); dispatchRemoteEvent(video, 'blur'); dispatchRemoteEvent(video, 'focus'); dispatchRemoteEvent(video, 'wheel'); dispatchRemoteEvent(window, 'beforeunload'); dispatchRemoteEvent(document, 'keyup'); dispatchRemoteEvent(document, 'keydown'); dispatchRemoteEvent(document, 'keypress'); dispatchRemoteEvent(video, 'mouseup'); dispatchRemoteEvent(video, 'mousemove'); dispatchRemoteEvent(video, 'mousedown'); dispatchRemoteEvent(video, 'mouseenter'); dispatchRemoteEvent(video, 'mouseleave'); function dispatchRemoteEvent(target, type) { target.addEventListener(type, (e) => peer.send(JSON.stringify({ type: 'event', data: serializeEvent(e) }))); } function serializeEvent(original) { return Object .getOwnPropertyNames(Object.getPrototypeOf(original)) .reduce((serialized, field) => { switch (typeof original[field]) { case 'object': case 'symbol': case 'function': break; default: serialized[field] = original[field]; } return serialized; }, { type: original.type }); } function onlyH264(sdp) { // remove non-h264 codecs from the supported codecs list const videos = sdp.match(/^m=video.*$/gm); if (videos) { return videos.map((video) => [video, [ ...getCodecIds(sdp, 'VP9'), ...getCodecIds(sdp, 'VP8'), ...getCodecIds(sdp, 'HEVC'), ...getCodecIds(sdp, 'H265') ]]).reduce((sdp, [video, ids]) => ids.reduce((sdp, id) => [ new RegExp(`^a=fmtp:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtpmap:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtcp-fb:${id}(.*?)$`, 'gm'), ].reduce((sdp, expr) => sdp.replace(expr, ''), sdp), sdp) .replace(video, ids.reduce((video, id) => video.replace(` ${id}`, ''), video)), sdp) .replace('\r\n', '\n').split('\n').map((x) => x.trim()).filter(Boolean).join('\r\n') + '\r\n'; } return sdp; function getCodecIds(sdp, codec) { return getIdsForMatcher(sdp, new RegExp( `^a=rtpmap:(?<id>\\d+)\\s+${codec}\\/\\d+$`, 'm' )).reduce((ids, id) => [ ...ids, id, ...getIdsForMatcher(sdp, new RegExp( `^a=fmtp:(?<id>\\d+)\\s+apt=${id}$`, 'm' )) ], []); } function getIdsForMatcher(sdp, matcher) { const ids = []; /** @type RegExpMatchArray */ let res, str = '' + sdp, pos = 0; for (; res = str.match(matcher); str = str.slice(pos)) { pos = res.index + res[0].length; if (res.groups) { ids.push(res.groups.id); } } return ids; } } </script> </body> </html>
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/umap/package.json
{ "private": true, "name": "@rapidsai/demo-umap", "main": "index.js", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/react": "8.8.10", "@luma.gl/core": "8.5.16", "@rapidsai/cuda": "~22.12.2", "@rapidsai/cudf": "~22.12.2", "@rapidsai/cugraph": "~22.12.2", "@rapidsai/deck.gl": "~22.12.2", "@rapidsai/glfw": "~22.12.2", "@rapidsai/jsdom": "~22.12.2", "ix": "4.4.1", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "src", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/umap/index.js
#!/usr/bin/env node // Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: '', visible: true, transparent: false, }) => { let args = process.argv.slice(2); if (args.length === 1 && args[0].includes(' ')) { args = args[0].split(' '); } const parseArg = (prefix, fallback = '') => (args.find((arg) => arg.includes(prefix)) || `${prefix}${fallback}`).slice(prefix.length); const delay = Math.max(0, parseInt(parseArg('--delay=', 0)) | 0); async function* inputs(delay, paths) { const sleep = (t) => new Promise((r) => setTimeout(r, t)); for (const path of paths.split(',')) { if (path) { yield path; } await sleep(delay); } } return require('@rapidsai/jsdom') .RapidsJSDOM.fromReactComponent( './src/app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }, { nodes: inputs(delay, parseArg('--nodes=')), edges: inputs(delay, parseArg('--edges=')), width: parseInt(parseArg('--width=', 800)) | 0, height: parseInt(parseArg('--height=', 600)) | 0, layoutParams: JSON.parse(`{${parseArg('--params=')}}`), }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/umap/README.md
# UMAP Demo A UMAP visualization using cuML and deck.gl. ## Featured Dependencies - @rapidsai/cudf - @rapidsai/cuml - @rapidsai/deck.gl - @rapidsai/glfw ## Data requirements Make sure the `data.tar.xz` file has been pulled from git lfs. Extract it using the following command: ```bash tar -xf ./data/data.tar.xz -C ./data ``` ## Start Example of starting demo ``` yarn start ```
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/umap/UMAP Demo.ipynb
var graphDemoWindow = require('@rapidsai/demo-umap'); graphDemoWindow.open({ _title: 'UMAP Demo', width: 1024, height: 768, layoutParams: { autoCenter: false, } })
0
rapidsai_public_repos/node/modules/demo/umap
rapidsai_public_repos/node/modules/demo/umap/src/loader.js
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {clampRange as clamp} from '@rapidsai/cuda'; import {DataFrame, Float32, Series, Uint32, Uint64, Uint8, Utf8String} from '@rapidsai/cudf'; import {UMAP} from '@rapidsai/cuml'; import {concat as concatAsync, zip as zipAsync} from 'ix/asynciterable'; import {flatMap as flatMapAsync} from 'ix/asynciterable/operators'; const defaultLayoutParams = { simulating: {name: 'simulating', val: true}, autoCenter: {name: 'auto-center', val: false}, train: { name: 'start iterative training', val: false, }, supervised: {name: 'supervised', val: false}, controlsVisible: {name: 'controls visible', val: true}, }; const df = DataFrame.readCSV({header: 0, sourceType: 'files', sources: [`${__dirname}/../data/data.csv`]}) .castAll(new Float32); const layoutParamNames = Object.keys(defaultLayoutParams); export default async function* loadGraphData(props = {}) { const layoutParams = {...defaultLayoutParams}; if (props.layoutParams) { layoutParamNames.forEach((name) => { if (props.layoutParams.hasOwnProperty(name)) { const {val, min, max} = layoutParams[name]; switch (typeof val) { case 'boolean': layoutParams[name].val = !!props.layoutParams[name]; break; case 'number': layoutParams[name].val = Math.max(min, Math.min(max, props.layoutParams[name])); break; } } }); } let selectedParameter = 0; window.addEventListener('keydown', (e) => { if ('1234567890'.includes(e.key)) { selectedParameter = +e.key; } else if (e.code === 'ArrowUp') { selectedParameter = clamp(layoutParamNames.length, selectedParameter - 1)[0] % layoutParamNames.length; } else if (e.code === 'ArrowDown') { selectedParameter = clamp(layoutParamNames.length, selectedParameter + 1)[0] % layoutParamNames.length; } else if (['PageUp', 'PageDown', 'ArrowLeft', 'ArrowRight'].indexOf(e.code) !== -1) { const key = layoutParamNames[selectedParameter]; const {val, min, max, step} = layoutParams[key]; if (typeof val === 'boolean') { layoutParams[key].val = !val; } else if (e.code === 'PageUp') { layoutParams[key].val = Math.min(max, parseFloat(Number(val + step * 10).toPrecision(3))); } else if (e.code === 'PageDown') { layoutParams[key].val = Math.max(min, parseFloat(Number(val - step * 10).toPrecision(3))); } else if (e.code === 'ArrowLeft') { layoutParams[key].val = Math.max(min, parseFloat(Number(val - step).toPrecision(3))); } else if (e.code === 'ArrowRight') { layoutParams[key].val = Math.min(max, parseFloat(Number(val + step).toPrecision(3))); } } }); async function* getDataFrames(source, getDefault, dataTypes) { if (!source) { if (typeof getDefault === 'function') { yield getDefault(); } return; } if (source instanceof DataFrame) { return yield source; } if (typeof source === 'string' && dataTypes) { return yield DataFrame.readCSV( {header: 0, sourceType: 'files', sources: [source], dataTypes}); } if (typeof source[Symbol.iterator] === 'function' || typeof source[Symbol.asyncIterator] === 'function') { let count = 0; for await (const x of flatMapAsync((x) => getDataFrames(x, undefined, dataTypes))(source)) { count++; yield x; } if (count == 0) { yield* getDataFrames(null, getDefault, dataTypes); } } } let nodeDFs = getDataFrames(props.nodes, getDefaultNodes, { name: 'str', id: 'uint32', color: 'uint32', size: 'uint8', data: 'str', }); let edgeDFs = getDataFrames(props.edges, getDefaultEdges, { name: 'str', src: 'uint32', dst: 'uint32', edge: 'uint64', color: 'uint64', bundle: 'uint64', data: 'str', }); function getDefaultEdges() { return null; } /** * @type DataFrame<{name: Utf8String, id: Uint32, color: Uint32, size: Uint8, x: Float32, y: * Float32}> */ let nodes = null; let embeddings = null; let graphDesc = {}; let bbox = [0, 0, 0, 0]; let onAfterRender = () => {}; let rendered = new Promise(() => {}); console.log(nodeDFs); let dataframes = concatAsync(zipAsync(nodeDFs, edgeDFs), (async function*() { datasourceCompleted = true; nextFrames = new Promise(() => {}); })())[Symbol.asyncIterator](); let nextFrames = dataframes.next(); let datasourceCompleted = false; let graphUpdated = false; let supervisedUpdated = false; while (true) { graphUpdated = false; // Wait for a new set of source dataframes or for the // most recent frame to finish rendering before advancing const newDFs = await (datasourceCompleted ? rendered : Promise.race([rendered, nextFrames.then(({value} = {}) => value)])); if (newDFs) { if (newDFs[0] !== nodes) { graphUpdated = true; [nodes, embeddings] = generateUMAP(newDFs[0], embeddings, layoutParams.supervised.val); nextFrames = dataframes.next(); } } if (layoutParams.train.val) { [nodes, embeddings] = generateUMAP(nodes, embeddings, layoutParams.supervised.val); } if (supervisedUpdated != layoutParams.supervised.val) { embeddings = null; supervisedUpdated = layoutParams.supervised.val; } if (!layoutParams.simulating.val && !graphUpdated) { // If user paused rendering, wait a bit and continue rendered = new Promise((r) => (onAfterRender = () => setTimeout(r, 0))); } else { // Compute the positions minimum bounding box [xMin, xMax, yMin, yMax] bbox = [...nodes.get('x').minmax(), ...nodes.get('y').minmax()]; graphDesc = createGraphRenderProps(nodes); ({promise: rendered, resolve: onAfterRender} = promiseSubject()); } // Yield the results to the caller for rendering yield { graph: graphDesc, params: layoutParams, selectedParameter: layoutParams.controlsVisible.val ? selectedParameter : undefined, bbox, autoCenter: layoutParams.autoCenter.val, onAfterRender }; // Wait for the frame to finish rendering before advancing rendered = rendered.catch(() => {}).then(() => {}); } } function promiseSubject() { let resolve, reject; let promise = new Promise((r1, r2) => { resolve = r1; reject = r2; }); return {promise, resolve, reject}; } /** * * @param {DataFrame<{ * name: Utf8String, id: Uint32, color: Uint32, size: Uint8, x: Float32, y: Float32, * }>} nodes * @param {DataFrame<{ * name: Utf8String, src: Uint32, dst: Uint32, edge: Uint64, color: Uint64, bundle: Uint64, * }>} edges * @param {*} graph */ function createGraphRenderProps(nodes) { const numNodes = nodes.numRows; const numEdges = 0; return { numNodes, numEdges, nodeRadiusScale: 1 / 75, // nodeRadiusScale: 1/255, nodeRadiusMinPixels: 5, nodeRadiusMaxPixels: 150, data: { nodes: { offset: 0, length: numNodes, attributes: { nodeName: nodes.get('name'), nodeRadius: nodes.get('size').data, nodeXPositions: nodes.get('x').data, nodeYPositions: nodes.get('y').data, nodeFillColors: nodes.get('color').data, nodeElementIndices: nodes.get('id').data, nodeData: nodes.has('data') ? nodes.get('data') : null } }, edges: { offset: 0, length: numEdges, attributes: {edgeName: null, edgeList: null, edgeColors: null, edgeBundles: null, edgeData: null} }, }, } } function generateUMAP(nodesDF, fittedUMAP = null, supervised = false) { const options = {nNeighbors: 5, init: 1, randomState: 42}; if (fittedUMAP == null) { fittedUMAP = (new UMAP({nEpochs: 300, ...options})) .fitDataFrame(df.drop(['target']), supervised ? df.get('target') : null); } else { fittedUMAP.refineDataFrame(df.drop(['target']), supervised ? df.get('target') : null); } const lowDimensionEmbeddingDF = fittedUMAP.embeddings.asDataFrame(); return [ nodesDF.assign({ x: lowDimensionEmbeddingDF.get(0), y: lowDimensionEmbeddingDF.get(1), size: Series.sequence({type: new Uint8, init: 0.1, step: 0, size: nodesDF.numRows}) }), fittedUMAP ]; } function getDefaultNodes() { console.log('called getDefaultNodes'); const colorData = [ '-12451426', '-11583787', '-12358156', '-10375427', '-7610114', '-4194305', '-6752794', '-5972565', '-5914010', '-4356046' ]; const labelsData = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; const nodesDF = new DataFrame({ id: Series.sequence({type: new Uint32, init: 0, step: 1, size: df.numRows}), name: df.get('target') }); const labelsUnique = [...nodesDF.get('name').unique()]; let color = Series.sequence({type: new Uint32, init: 0, step: 1, size: df.numRows}); let data = Series.new({type: new Utf8String, data: [...color]}); labelsUnique.forEach(e => { color = color.scatter(colorData[e], nodesDF.filter(nodesDF.get('name').eq(e)).get('id')); data = data.scatter(labelsData[e], nodesDF.filter(nodesDF.get('name').eq(e)).get('id')); }); return nodesDF.assign({color, data}); }
0
rapidsai_public_repos/node/modules/demo/umap
rapidsai_public_repos/node/modules/demo/umap/src/app.jsx
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { log as deckLog, OrthographicView } from '@deck.gl/core'; import { TextLayer } from '@deck.gl/layers'; import { default as DeckGL } from '@deck.gl/react'; import { GraphLayer } from '@rapidsai/deck.gl'; import { as as asAsyncIterable } from 'ix/asynciterable/as'; import { takeWhile } from 'ix/asynciterable/operators/takewhile'; import * as React from 'react'; import { default as loadGraphData } from './loader'; deckLog.level = 0; deckLog.enable(false); const composeFns = (fns) => function (...args) { fns.forEach((fn) => fn && fn.apply(this, args)); } export class App extends React.Component { constructor(props, context) { super(props, context); this._isMounted = false; this._deck = React.createRef(); this.state = { graph: {}, autoCenter: true }; } componentWillUnmount() { this._isMounted = false; } componentDidMount() { this._isMounted = true; asAsyncIterable(loadGraphData(this.props)) .pipe(takeWhile(() => this._isMounted)) .forEach((state) => this.setState(state)) .catch((e) => console.error(e)); } render() { const { onAfterRender, ...props } = this.props; const { params = {}, selectedParameter } = this.state; const [viewport] = (this._deck?.current?.deck?.viewManager?.getViewports() || []); if (this.state.autoCenter && this.state.bbox) { const viewState = centerOnBbox(this.state.bbox); viewState && (props.initialViewState = viewState); } const [minX = Number.NEGATIVE_INFINITY, minY = Number.NEGATIVE_INFINITY] = (viewport?.getBounds() || []); return ( <DeckGL {...props} ref={this._deck} onViewStateChange={() => this.setState({ autoCenter: params.autoCenter ? (params.autoCenter.val = false) : false })} _framebuffer={props.getRenderTarget ? props.getRenderTarget() : null} onAfterRender={composeFns([onAfterRender, this.state.onAfterRender])}> <GraphLayer edgeStrokeWidth={2} edgeOpacity={.5} nodesStroked={true} nodeFillOpacity={.5} nodeStrokeOpacity={.9} {...this.state.graph} getNodeLabels={getNodeLabels} getEdgeLabels={getEdgeLabels} /> {viewport && selectedParameter !== undefined ? <TextLayer sizeScale={1} opacity={0.9} maxWidth={2000} pickable={false} background={true} getBackgroundColor={() => [46, 46, 46]} getTextAnchor='start' getAlignmentBaseline='top' getSize={(d) => d.size} getColor={(d) => d.color} getPixelOffset={(d) => [0, d.index * 15]} getPosition={(d) => d.position} data={Object.keys(params).map((key, i) => ({ size: 15, index: i, text: i === selectedParameter ? `(${i}) ${params[key].name}: ${params[key].val}` : ` ${i} ${params[key].name}: ${params[key].val}`, color: [255, 255, 255], position: [minX, minY], }))} /> : null } </DeckGL> ); } } export default App; App.defaultProps = { controller: { keyboard: false }, onHover: onDragEnd, onDrag: onDragStart, onDragEnd: onDragEnd, onDragStart: onDragStart, initialViewState: { zoom: 1, target: [0, 0, 0], minZoom: Number.NEGATIVE_INFINITY, maxZoom: Number.POSITIVE_INFINITY, }, views: [ new OrthographicView({ clear: { color: [...[46, 46, 46].map((x) => x / 255), 1] } }) ] } ; function onDragStart({ index }, { target }) { if (target) { [window, target].forEach((element) => (element.style || {}).cursor = 'grabbing'); } } function onDragEnd({ index }, { target }) { if (target) { [window, target].forEach((element) => (element.style || {}).cursor = ~index ? 'pointer' : 'default'); } } function centerOnBbox([minX, maxX, minY, maxY]) { const width = maxX - minX, height = maxY - minY; if ((width === width) && (height === height)) { const { outerWidth, outerHeight } = window; const world = (width > height ? width : height); const screen = (width > height ? outerWidth : outerHeight) * .9; const zoom = (world > screen ? -(world / screen) : (screen / world)); return { minZoom: Number.NEGATIVE_INFINITY, maxZoom: Number.POSITIVE_INFINITY, zoom: Math.log(Math.abs(zoom)) * Math.sign(zoom), target: [minX + (width * .5), minY + (height * .5), 0], }; } } function getNodeLabels({ x, y, coordinate, nodeId, props, layer }) { let size = 14; const color = [255, 255, 255]; const labels = [{ size, color, offset: [14, 0], position: () => { const x = window.mouseInWindow ? window.mouseX : -1; const y = window.mouseInWindow ? window.mouseY : -1; return layer.context.viewport.unproject([x, y]); }, text: props.data.nodes.attributes.nodeName ? props.data.nodes.attributes.nodeName.getValue(nodeId) : `${nodeId}`, }]; if (props.data.nodes.attributes.nodeData) { size *= 1.5; const text = `${props.data.nodes.attributes.nodeData.getValue(nodeId) || ''}`.trimEnd(); const lineSpacing = 3, padding = 20; const nBreaks = ((text.match(/\n/ig) || []).length + 1); const offsetX = 0, offsetY = (size + lineSpacing) * nBreaks; labels.push({ text, color, size, position: () => { const [minX, , , maxY] = layer.context.viewport.getBounds(); return [minX, maxY]; }, offset: [offsetX + padding, -padding - offsetY], }); } return labels; } function getEdgeLabels({ x, y, coordinate, edgeId, props, layer }) { let size = 14; const color = [255, 255, 255]; const labels = [{ size, color, offset: [14, 0], position: () => { const x = window.mouseInWindow ? window.mouseX : -1; const y = window.mouseInWindow ? window.mouseY : -1; return layer.context.viewport.unproject([x, y]); }, text: props.data.edges.attributes.edgeName ? props.data.edges.attributes.edgeName.getValue(edgeId) : `${sourceNodeId} - ${targetNodeId}`, }]; if (props.data.edges.attributes.edgeData) { size *= 1.5; const text = `${props.data.edges.attributes.edgeData.getValue(edgeId) || ''}`.trimEnd(); const lineSpacing = 3, padding = 20; const nBreaks = ((text.match(/\n/ig) || []).length + 1); const offsetX = 0, offsetY = (size + lineSpacing) * nBreaks; labels.push({ text, color, size, offset: [offsetX + padding, -padding - offsetY], position: () => { const [minX, , , maxY] = layer.context.viewport.getBounds(); return [minX, maxY]; }, }); } return labels; }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/point-cloud/package.json
{ "private": true, "name": "@rapidsai/demo-deck-point-cloud-laz", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@loaders.gl/core": "3.2.9", "@loaders.gl/las": "3.2.9", "@loaders.gl/ply": "3.2.9", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "app.js", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/point-cloud/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Point Cloud Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); } /* * Introduces new error: * * (node:2608695) V8: /opt/rapids/node/node_modules/@loaders.gl/las/dist/es5/libs/laz-perf.js:2321 * Linking failure in asm.js: Unexpected stdlib member (Use `node --trace-warnings ...` to show * where the warning was created) * * still works tho */
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/point-cloud/README.md
This is a minimal standalone version of the Graph Explorer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data Source The sample data is from [kaarta.com](https://kaarta.com)
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/point-cloud/app.jsx
/* eslint-disable no-unused-vars */ const { OrbitView, COORDINATE_SYSTEM, LinearInterpolator } = require('@deck.gl/core'); import DeckGL from '@deck.gl/react'; import { PointCloudLayer } from '@rapidsai/deck.gl'; import * as React from 'react' import { PureComponent } from 'react'; import { render } from 'react-dom'; import { DataFrame, Float32, Series, Uint32 } from '@rapidsai/cudf'; const transitionInterpolator = new LinearInterpolator(['rotationOrbit']); const df = new DataFrame({ 'x': Series.new({ type: new Float32, data: [ 0, 0, 31.41076, 19.58429, -6.98955, -28.30012, -28.30012, -6.98955, 19.58429, 31.41076, 62.79052, 55.59824, 35.66908, 7.56856, -22.26583, -46.99938, -60.96594, -60.96594, -46.99938, -22.26583, 7.56856, 35.66908, 55.59824, 62.79052, 94.10831, 89.00927, 74.26468, 51.47237, 23.10223, -7.7714, -37.80288, -63.73783, -82.76579 ] }), 'y': Series.new({ type: new Float32, data: [ 0, 0, 0, 24.55792, 30.62323, 13.62862, -13.62862, -30.62323, -24.55792, 0, 0, 29.18021, 51.67558, 62.33271, 58.71016, 41.63782, 15.02675, -15.02675, -41.63782, -58.71016, -62.33271, -51.67558, -29.18021, 0, 0, 30.55692, 57.80252, 78.78433, 91.22862, 93.78689, 86.18188, 69.23774, 44.79061 ] }), 'z': Series.new({ type: new Float32, data: [ 0, 0, 10, 0.49344, 0.49344, 0.49344, 0.49344, 0.49344, 0.49344, 0.49344, 1.97327, 5, 1.97327, 1.97327, 1.97327, 1.97327, 1.97327, 1.97327, 1.97327, 1.97327, 11, 1.97327, 1.97327, 1.97327, 4.43804, 4.43804, 4.43804, 4.43804, 4.43804, 19, 4.43804, 4.43804, 4.43804 ] }), 'color': Series.new({ type: new Uint32, data: [ 4293326232, 4294815329, 4294208835, 4294967231, 4293326232, 4293326232, 4294815329, 4294208835, 4294967231, 4293326232, 4293326232, 4294815329, 4294208835, 4294967231, 4293326232, 4293326232, 4294815329, 4294208835, 4294967231, 4293326232, 4293326232, 4294815329, 4294208835, 4294967231, 4293326232, 4293326232, 4294815329, 4294208835, 4294967231, 4293326232, 4293326232, 4294815329, 4294208835 ] }) }) console.log('Number of rendered points', df.numRows); const INITIAL_VIEW_STATE = { target: [df.get('x').mean(), df.get('y').mean(), df.get('z').mean()], rotationX: 0, rotationOrbit: 0, maxZoom: 10, zoom: 1 }; export default class App extends PureComponent { constructor(props) { super(props); this.state = { viewState: INITIAL_VIEW_STATE }; this._onViewStateChange = this._onViewStateChange.bind(this); } _onViewStateChange({ viewState }) { this.setState({ viewState }); } render() { const { viewState } = this.state; const layers = [new PointCloudLayer({ id: 'laz-point-cloud-layer', numPoints: df.numRows, data: { points: { offset: 0, length: df.numRows, attributes: { pointPositionX: df.get('x').data, pointPositionY: df.get('y').data, pointPositionZ: df.get('z').data, pointColor: df.get('color').data, } } }, coordinateSystem: COORDINATE_SYSTEM.CARTESIAN, getNormal: [0, 1, 0], // getColor: [138, 245, 66, 255], opacity: 0.5, pointSize: 3, sizeUnits: 'pixels' })]; return ( <DeckGL views={new OrbitView({ orbitAxis: 'Y', fov: 50, transitionInterpolator })} viewState={viewState} controller={true} onViewStateChange={this._onViewStateChange} layers={layers} // parameters={{ clearColor: [0.93, 0.86, 0.81, 1] }} /> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/icon/package.json
{ "private": true, "name": "@rapidsai/demo-deck-icon", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19", "supercluster": "6.0.2" }, "files": [ "data", "icon-cluster-layer.js", "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/icon/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Icon Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/icon/README.md
This is a minimal standalone version of the IconLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/icon). To use your own data, checkout the [documentation of IconLayer](../../../docs/layers/icon-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/icon/icon-cluster-layer.js
import { CompositeLayer } from '@deck.gl/core'; import { IconLayer } from '@deck.gl/layers'; import Supercluster from 'supercluster'; function getIconName(size) { if (size === 0) { return ''; } if (size < 10) { return `marker-${size}`; } if (size < 100) { return `marker-${Math.floor(size / 10)}0`; } return 'marker-100'; } function getIconSize(size) { return Math.min(100, size) / 100 + 1; } export default class IconClusterLayer extends CompositeLayer { shouldUpdateState({ changeFlags }) { return changeFlags.somethingChanged; } updateState({ props, oldProps, changeFlags }) { const rebuildIndex = changeFlags.dataChanged || props.sizeScale !== oldProps.sizeScale; if (rebuildIndex) { const index = new Supercluster({ maxZoom: 16, radius: props.sizeScale }); index.load( props.data.map(d => ({ geometry: { coordinates: props.getPosition(d) }, properties: d })) ); this.setState({ index }); } const z = Math.floor(this.context.viewport.zoom); if (rebuildIndex || z !== this.state.z) { this.setState({ data: this.state.index.getClusters([-180, -85, 180, 85], z), z }); } } getPickingInfo({ info, mode }) { const pickedObject = info.object && info.object.properties; if (pickedObject) { if (pickedObject.cluster && mode !== 'hover') { info.objects = this.state.index .getLeaves(pickedObject.cluster_id, 25) .map(f => f.properties); } info.object = pickedObject; } return info; } renderLayers() { const { data } = this.state; const { iconAtlas, iconMapping, sizeScale } = this.props; return new IconLayer( this.getSubLayerProps({ id: 'icon', data, iconAtlas, iconMapping, sizeScale, getPosition: d => d.geometry.coordinates, getIcon: d => getIconName(d.properties.cluster ? d.properties.point_count : 1), getSize: d => getIconSize(d.properties.cluster ? d.properties.point_count : 1) }) ); } } IconClusterLayer.componentName = 'IconClusterLayer';
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/icon/app.jsx
import { MapView } from '@deck.gl/core'; import { IconLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; import IconClusterLayer from './icon-cluster-layer'; // Set your mapbox token here const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line // Source data CSV const DATA_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/icon/meteorites.json'; // eslint-disable-line const MAP_VIEW = new MapView({ repeat: true }); const INITIAL_VIEW_STATE = { longitude: -35, latitude: 36.7, zoom: 1.8, maxZoom: 20, pitch: 0, bearing: 0 }; /* eslint-disable react/no-deprecated */ export default class App extends Component { constructor(props) { super(props); this.state = { x: 0, y: 0, hoveredObject: null, expandedObjects: null }; this._onHover = this._onHover.bind(this); this._onClick = this._onClick.bind(this); this._closePopup = this._closePopup.bind(this); this._renderhoveredItems = this._renderhoveredItems.bind(this); } _onHover(info) { if (this.state.expandedObjects) { return; } const { x, y, object } = info; this.setState({ x, y, hoveredObject: object }); } _onClick(info) { const { showCluster = true } = this.props; const { x, y, objects, object } = info; if (object && showCluster) { this.setState({ x, y, expandedObjects: objects || [object] }); } else { this._closePopup(); } } _closePopup() { if (this.state.expandedObjects) { this.setState({ expandedObjects: null, hoveredObject: null }); } } _renderhoveredItems() { const { x, y, hoveredObject, expandedObjects } = this.state; if (expandedObjects) { return ( <div className='tooltip interactive' style={{ left: x, top: y }}> {expandedObjects.map(({ name, year, mass, class: meteorClass }) => { return (<div key={name}> <h5>{name}</h5> <div>Year: {year || 'unknown'}</div> <div>Class: {meteorClass}</div> <div>Mass: {mass}g</div> </div> ); })} </div>); } if (!hoveredObject) { return null; } return hoveredObject.cluster ? ( <div className='tooltip' style={{ left: x, top: y }}> <h5>{hoveredObject.point_count} records</h5> </div> ) : ( <div className='tooltip' style={{ left: x, top: y }}> <h5> {hoveredObject.name} {hoveredObject.year ? `(${hoveredObject.year})` : ''} </h5> </div> ); } _renderLayers() { const { data = DATA_URL, iconMapping = 'data/location-icon-mapping.json', iconAtlas = 'data/location-icon-atlas.png', showCluster = true } = this.props; const layerProps = { data, pickable: true, getPosition: d => d.coordinates, iconAtlas, iconMapping, onHover: this._onHover }; const layer = showCluster ? new IconClusterLayer({ ...layerProps, id: 'icon-cluster', sizeScale: 60 }) : new IconLayer({ ...layerProps, id: 'icon', getIcon: d => 'marker', sizeUnits: 'meters', sizeScale: 2000, sizeMinPixels: 6 }); return [layer]; } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL layers={this._renderLayers()} views={MAP_VIEW} initialViewState={INITIAL_VIEW_STATE} controller={{ dragRotate: false }} onViewStateChange={this._closePopup} onClick={this._onClick} > <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> {this._renderhoveredItems} </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck/icon
rapidsai_public_repos/node/modules/demo/deck/icon/data/location-icon-mapping.json
{ "marker-1": { "x": 0, "y": 0, "width": 128, "height": 128, "anchorY": 128 }, "marker-2": { "x": 128, "y": 0, "width": 128, "height": 128, "anchorY": 128 }, "marker-3": { "x": 256, "y": 0, "width": 128, "height": 128, "anchorY": 128 }, "marker-4": { "x": 384, "y": 0, "width": 128, "height": 128, "anchorY": 128 }, "marker-5": { "x": 0, "y": 128, "width": 128, "height": 128, "anchorY": 128 }, "marker-6": { "x": 128, "y": 128, "width": 128, "height": 128, "anchorY": 128 }, "marker-7": { "x": 256, "y": 128, "width": 128, "height": 128, "anchorY": 128 }, "marker-8": { "x": 384, "y": 128, "width": 128, "height": 128, "anchorY": 128 }, "marker-9": { "x": 0, "y": 256, "width": 128, "height": 128, "anchorY": 128 }, "marker-10": { "x": 128, "y": 256, "width": 128, "height": 128, "anchorY": 128 }, "marker-20": { "x": 256, "y": 256, "width": 128, "height": 128, "anchorY": 128 }, "marker-30": { "x": 384, "y": 256, "width": 128, "height": 128, "anchorY": 128 }, "marker-40": { "x": 0, "y": 384, "width": 128, "height": 128, "anchorY": 128 }, "marker-50": { "x": 128, "y": 384, "width": 128, "height": 128, "anchorY": 128 }, "marker-60": { "x": 256, "y": 384, "width": 128, "height": 128, "anchorY": 128 }, "marker-70": { "x": 384, "y": 384, "width": 128, "height": 128, "anchorY": 128 }, "marker-80": { "x": 0, "y": 512, "width": 128, "height": 128, "anchorY": 128 }, "marker-90": { "x": 128, "y": 512, "width": 128, "height": 128, "anchorY": 128 }, "marker-100": { "x": 256, "y": 512, "width": 128, "height": 128, "anchorY": 128 }, "marker": { "x": 384, "y": 512, "width": 128, "height": 128, "anchorY": 128 } }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/tagmap/package.json
{ "private": true, "name": "@rapidsai/demo-deck-tagmap", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "d3-scale": "2.2.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19", "tagmap.js": "1.1.2" }, "files": [ "app.jsx", "index.js", "tagmap-layer", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/tagmap/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Tag Map Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/tagmap/README.md
This is a standalone version of the TagMap example built upon [deck.gl](http://deck.gl). ![tagmap](https://raw.githubusercontent.com/rivulet-zhang/rivulet-zhang.github.io/master/dataRepo/static/tagmap.png) ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data can be found [here](https://rivulet-zhang.github.io/dataRepo/tagmap/hashtags10k.json).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/tagmap/app.jsx
/* eslint-disable max-len */ import { TextLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; import TagmapLayer from './tagmap-layer'; // Set your mapbox token here const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line // sample data const DATA_URL = 'https://rivulet-zhang.github.io/dataRepo/tagmap/hashtags10k.json'; // mapbox style file path const MAPBOX_STYLE = 'https://rivulet-zhang.github.io/dataRepo/mapbox/style/map-style-dark-v9-no-labels.json'; const DEFAULT_COLOR = [29, 145, 192]; const INITIAL_VIEW_STATE = { latitude: 39.1, longitude: -94.57, zoom: 3.8, maxZoom: 16, pitch: 0, bearing: 0 }; export default class App extends Component { _renderLayers() { const { data = DATA_URL, cluster = true, fontSize = 32 } = this.props; return [cluster ? new TagmapLayer({ id: 'twitter-topics-tagmap', data, getLabel: x => x.label, getPosition: x => x.coordinates, minFontSize: 14, maxFontSize: fontSize * 2 - 14 }) : new TextLayer({ id: 'twitter-topics-raw', data, getText: d => d.label, getPosition: x => x.coordinates, getColor: d => DEFAULT_COLOR, getSize: d => 20, sizeScale: fontSize / 20 })]; } render() { const { mapStyle = MAPBOX_STYLE } = this.props; return ( <DeckGL layers={this._renderLayers()} initialViewState={INITIAL_VIEW_STATE} controller={{ dragRotate: false }}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck/tagmap
rapidsai_public_repos/node/modules/demo/deck/tagmap/tagmap-layer/index.js
export {default} from './tagmap-layer';
0
rapidsai_public_repos/node/modules/demo/deck/tagmap
rapidsai_public_repos/node/modules/demo/deck/tagmap/tagmap-layer/README.md
# Tagmap Layer The tagmap layer generates and visualizes [an occlusion-free label layout on map](https://github.com/rivulet-zhang/tagmap.js). ```js import DeckGL from '@deck.gl/react'; import TagmapLayer from './tagmap-layer'; const App = ({data, viewport}) => { /** * Data format: * [ * {label: '#San Francisco', coordinates: [-122.425586, 37.775049], weight: 1}, * ... * ] */ const layers = [ new TagmapLayer({ id: 'tagmap-layer', data }) ]; return (<DeckGL {...viewport} layers={[layer]} />); }; ``` ## Properties Tagmap Layer is extended based on [Composite Layer](/docs/api-reference/composite-layer.md). ### Render Options ##### `maxFontSize` (Number, optional) - Default: `32` The font size for the label of the maximal (aggregated) weight. Unit is pixel. ##### `minFontSize` (Number, optional) - Default: `14` The font size for the label of the minimal (aggregated) weight. Unit is pixel. ##### `weightThreshold` (Number, optional) - Default: `1` The minimal (aggregated) weight for labels to be visible on map. ##### `colorScheme` (Array, optional) - Default: `['#1d91c0', '#41b6c4', '#7fcdbb', '#c7e9b4', '#edf8b1']` (A sequential scheme from [ColorBrewer](http://colorbrewer2.org/) that looks OKAY with a dark map background) A color scheme in hex format that is used to color-encode the (aggregated) weight of labels. ### Data Accessors ##### `getLabel` (Function, optional) - Default: `x => x.label` Method called to retrieve the label of each label. ##### `getWeight` (Function, optional) - Default: `x => x.weight` Method called to retrieve the weight of each label. ##### `getPosition` (Function, optional) - Default: `x => x.coordinates` Method called to retrieve the location of each label.
0
rapidsai_public_repos/node/modules/demo/deck/tagmap
rapidsai_public_repos/node/modules/demo/deck/tagmap/tagmap-layer/tagmap-wrapper.js
/* create a tagmap instance, set colorscheme, sizeMeasurer */ /* eslint-disable max-len */ /* global document */ import TagMap from 'tagmap.js'; import RBush from 'rbush'; import {lngLatToWorld, worldToLngLat} from '@math.gl/web-mercator'; function getDrawingContext() { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '10px "Lucida Console", Monaco, monospace'; ctx.fillStyle = '#000'; ctx.textBaseline = 'hanging'; ctx.textAlign = 'left'; return ctx; } export default class TagMapWrapper { constructor() { this.tagMap = null; this.ctx = getDrawingContext(); this.measureText = this.measureText.bind(this); this.textSizes = {}; this.weightThreshold = 1; // cache of layout results this.clusterCache = {}; } setData(data, {getLabel, getPosition, getWeight}) { this.textSizes = {}; data.forEach(d => { const label = getLabel(d); this.textSizes[label] = this.ctx.measureText(label).width; }); this.tagMap = new TagMap(); this.tagMap.buildHierarchy(data, {getLabel, getPosition, getWeight}); this.clusterCache = {}; } extractCluster({scale, weightThreshold}) { const project = lngLat => { const p = lngLatToWorld(lngLat); p[0] *= scale; p[1] *= scale; return p; }; const tagList = this.tagMap.extractCluster({project, weightThreshold}); tagList.forEach(tag => { tag.minX = tag.center[0]; tag.minY = tag.center[1]; tag.maxX = tag.center[0]; tag.maxY = tag.center[1]; }); const cluster = new RBush(); cluster.load(tagList); return cluster; } layout({tagList, scale, minFontSize, maxFontSize}) { const tags = this.tagMap.layout({ tagList, minFontSize, maxFontSize, maxNumOfTags: 150, sizeMeasurer: this.measureText }); // transform tags to the format that are used to be visualized as icons in the deckgl layer tags.forEach(tag => { tag.position = worldToLngLat([tag.center[0] / scale, tag.center[1] / scale]); }); return tags; } getTags({zoom, bbox, minFontSize, maxFontSize, weightThreshold}) { if (weightThreshold !== this.weightThreshold) { this.weightThreshold = weightThreshold; this.clusterCache = {}; } const scale = Math.pow(2, zoom); const cluster = this.clusterCache[zoom] || this.extractCluster({scale, weightThreshold}); this.clusterCache[zoom] = cluster; let tagList; if (bbox) { const sw = lngLatToWorld([bbox.minX, bbox.minY]); const ne = lngLatToWorld([bbox.maxX, bbox.maxY]); tagList = cluster.search({ minX: sw[0] * scale, minY: sw[1] * scale, maxX: ne[0] * scale, maxY: ne[1] * scale }); } else { tagList = cluster.all(); } return this.layout({ tagList, scale, minFontSize, maxFontSize }); } measureText(label, fontSize) { const width = this.textSizes[label]; return {width: (width / 10) * fontSize, height: fontSize}; } }
0
rapidsai_public_repos/node/modules/demo/deck/tagmap
rapidsai_public_repos/node/modules/demo/deck/tagmap/tagmap-layer/tagmap-layer.js
/* eslint-disable max-len */ import {CompositeLayer} from '@deck.gl/core'; import {TextLayer} from '@deck.gl/layers'; import {scaleQuantile} from 'd3-scale'; import TagMapWrapper from './tagmap-wrapper'; const DEFAULT_COLOR_SCHEME = [ [29, 145, 192], [65, 182, 196], [127, 205, 187], [199, 233, 180], [237, 248, 177] ]; const defaultProps = { getLabel: x => x.label, getWeight: x => x.weight || 1, getPosition: x => x.position, colorScheme: DEFAULT_COLOR_SCHEME, minFontSize: 14, maxFontSize: 32, weightThreshold: 1 }; const MAX_CACHED_ZOOM_LEVEL = 5; export default class TagmapLayer extends CompositeLayer { initializeState() { this.state = { // Cached tags per zoom level tagsCache: {}, tags: [] }; } shouldUpdateState({changeFlags}) { return changeFlags.somethingChanged; } updateState({props, oldProps, changeFlags}) { super.updateState({props, oldProps, changeFlags}); let needsUpdate = changeFlags.viewportChanged; if (changeFlags.dataChanged) { this.updateTagMapData(); needsUpdate = true; } else if ( props.minFontSize !== oldProps.minFontSize || props.maxFontSize !== oldProps.maxFontSize || props.weightThreshold !== oldProps.weightThreshold ) { this.setState({tagsCache: {}}); needsUpdate = true; } if (needsUpdate) { this.updateTagMapVis(); } if (props.colorScheme !== oldProps.colorScheme) { // set color scheme const colorScale = scaleQuantile() .domain([props.minFontSize, props.maxFontSize]) .range(props.colorScheme); this.setState({colorScale}); } } updateTagMapData() { const {data, getLabel, getPosition, getWeight} = this.props; const tagMap = new TagMapWrapper(); tagMap.setData(data, {getLabel, getPosition, getWeight}); this.setState({tagMap, tagsCache: {}}); } updateTagMapVis() { const {tagMap, tagsCache} = this.state; if (!tagMap) { return; } const {viewport} = this.context; const discreteZoomLevel = Math.floor(viewport.zoom); let tags = tagsCache[discreteZoomLevel]; if (tags) { this.setState({tags}); return; } const {minFontSize, maxFontSize, weightThreshold} = this.props; let bbox = null; if (discreteZoomLevel > MAX_CACHED_ZOOM_LEVEL) { const {unproject, width, height} = viewport; const corners = [ unproject([0, 0]), unproject([width, 0]), unproject([0, height]), unproject([width, height]) ]; bbox = { minX: Math.min.apply(null, corners.map(p => p[0])), minY: Math.min.apply(null, corners.map(p => p[1])), maxX: Math.max.apply(null, corners.map(p => p[0])), maxY: Math.max.apply(null, corners.map(p => p[1])) }; } tags = tagMap.getTags({ bbox, minFontSize, maxFontSize, weightThreshold, zoom: discreteZoomLevel }); if (discreteZoomLevel <= MAX_CACHED_ZOOM_LEVEL) { tagsCache[discreteZoomLevel] = tags; } this.setState({tags}); } renderLayers() { const {tags, colorScale} = this.state; return [ new TextLayer({ id: 'tagmap-layer', data: tags, getText: d => d.label, getPosition: d => d.position, getColor: d => colorScale(d.height), getSize: d => d.height }) ]; } } TagmapLayer.layerName = 'TagmapLayer'; TagmapLayer.defaultProps = defaultProps;
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/playground/package.json
{ "private": true, "name": "@rapidsai/demo-deck-playground", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/aggregation-layers": "8.8.10", "@deck.gl/core": "8.8.10", "@deck.gl/geo-layers": "8.8.10", "@deck.gl/google-maps": "8.8.10", "@deck.gl/json": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@loaders.gl/3d-tiles": "3.2.9", "@loaders.gl/core": "3.2.9", "@loaders.gl/csv": "3.2.9", "@loaders.gl/draco": "3.2.9", "@loaders.gl/gltf": "3.2.9", "@luma.gl/constants": "8.5.16", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "src", "index.js", "json-examples", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/playground/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Playground Demo', transparent: false }) => { return require('@rapidsai/jsdom') .RapidsJSDOM.fromReactComponent(require('path').join(__dirname, 'src', 'app.jsx'), { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/scatterplot.json
{ "description": "The deck.gl website ScatterplotLayer example in JSON format", "websiteUrl": "https://deck.gl/#/examples/core-layers/scattterplot-layer", "initialViewState": { "longitude": -74, "latitude": 40.7, "zoom": 11, "maxZoom": 16, "pitch": 0, "bearing": 0 }, "views": [ { "@@type": "MapView", "controller": true, "mapStyle": "https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json" } ], "layers": [ { "@@type": "ScatterplotLayer", "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/scatterplot/manhattan.json", "radiusScale": 30, "radiusMinPixels": 0.25, "getPosition": "@@=-", "getFillColor": [ 0, 128, 255 ], "getRadius": 1 } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/index.js
export default { // WEBSITE EXAMPLES AS JSON PAYLOADS 'website/3D Heatmap (HexagonLayer)':/* */ require('./3d-heatmap.json'), 'website/3D Heatmap (wth Minimap)':/* */ require('./3d-heatmap-minimap.json'), 'website/GeoJSON (GeoJsonLayer)':/* */ require('./geojson.json'), 'website/Line (LineLayer)':/* */ require('./line.json'), 'website/Scatterplot (ScatterplotLayer)':/* */ require('./scatterplot.json'), 'website/Screen Grid (ScreenGridLayer)':/* */ require('./screen-grid.json'), 'website/TagMap (TextLayer)':/* */ require('./tagmap.json'), 'website/3D Tiles (Tile3DLayer, Royal)':/* */ require('./3d-tiles-royal.json'), 'website/3D Tiles (Tile3DLayer, St Helens)':/* */ require('./3d-tiles-st-helens.json'), 'website/3D Tiles (Tile3DLayer, Cairo/vricon)':/* */ require('./3d-tiles-cairo-vricon.json'), 'website/3D Tiles (Tile3DLayer, New York)':/* */ require('./3d-tiles-new-york.json'), 'website/CartoLayer':/* */ require('./carto.json'), // GET STARTED EXAMPLES AS JSON PAYLOADS 'get-started/US map (GeoJsonLayer)':/* */ require('./us-map.json'), 'get-started/Dot Text (Scatterplot/TextLayer)':/* */ require('./dot-text.json') };
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/tagmap.json
{ "description": "A deck.gl TextLayer example in JSON format", "initialViewState": { "latitude": 39.1, "longitude": -94.57, "zoom": 3.8, "maxZoom": 16, "pitch": 0, "bearing": 0 }, "views": [ { "@@type": "MapView", "controller": true, "mapStyle": "https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json" } ], "layers": [ { "@@type": "TextLayer", "id": "twitter-topics-raw", "data": "https://rivulet-zhang.github.io/dataRepo/tagmap/hashtags10k.json", "characterSet": "auto", "getText": "@@=label", "getPosition": "@@=coordinates", "getColor": [ 29, 145, 192 ], "getSize": 12 } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/3d-tiles-royal.json
{ "description": "The deck.gl website tile-3d-layer example", "websiteUrl": "https://deck.gl/#/examples/geo-layers/tile-3d-layer", "initialViewState": { "latitude": -37.8058, "longitude": 144.9713, "pitch": 45, "maxPitch": 60, "bearing": 0, "minZoom": 2, "maxZoom": 20, "zoom": 17.36 }, "views": [ { "@@type": "MapView", "mapStyle": "https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json", "controller": true } ], "layers": [ { "@@type": "Tile3DLayer", "id": "tiles-royal", "loader": "@@#Tiles3DLoader", "getPointColor": [0, 125, 200, 255], "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/3d-tiles/RoyalExhibitionBuilding/tileset.json" } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/screen-grid.json
{ "description": "The deck.gl website ScreenGridLayer example in JSON format", "websiteUrl": "https://deck.gl/#/examples/core-layers/screen-grid-layer", "initialViewState": { "longitude": -119.3, "latitude": 35.6, "zoom": 6, "maxZoom": 20, "pitch": 0, "bearing": 0 }, "map": true, "views": [ { "@@type": "MapView", "controller": true, "mapStyle": "https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json" } ], "layers": [ { "@@type": "ScreenGridLayer", "id": "grid", "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/screen-grid/ca-transit-stops.json", "opacity": 0.8, "cellSizePixels": 20, "colorRange": [ [ 255, 255, 178, 25 ], [ 254, 217, 118, 85 ], [ 254, 178, 76, 127 ], [ 253, 141, 60, 170 ], [ 240, 59, 32, 212 ], [ 189, 0, 38, 255 ] ], "getPosition": "@@=-", "gpuAggregation": true } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/README.md
# JSON examples JSON versions of deck.gl examples go into this folder. - New examples need to be listed in `../'src/templates.js` - Any new layers or classes used by the examples need to be added to `../'src/configuration.js`
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/3d-heatmap.json
{ "description": "The deck.gl website hexagonlayer example in JSON format", "websiteUrl": "https://deck.gl/#/examples/core-layers/hexagon-layer", "initialViewState": { "longitude": -1.4157267858730052, "latitude": 52.232395363869415, "zoom": 6.6, "minZoom": 5, "maxZoom": 15, "pitch": 40.5, "bearing": -27.396674584323023 }, "views": [ { "@@type": "MapView", "controller": true, "mapStyle": "https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json" } ], "layers": [ { "@@type": "HexagonLayer", "id": "heatmap", "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/3d-heatmap/heatmap-data.csv", "coverage": 1, "pickable": true, "autoHighlight": true, "elevationRange": [ 0, 3000 ], "elevationScale": 50, "extruded": true, "getPosition": "@@=[lng,lat]", "radius": 1000, "upperPercentile": 100, "colorRange": [ [1, 152, 189], [73, 227, 206], [216, 254, 181], [254, 237, 177], [254, 173, 84], [209, 55, 78] ] } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/3d-tiles-cairo-vricon.json
{ "description": "The deck.gl website tile-3d-layer example", "websiteUrl": "https://deck.gl/#/examples/geo-layers/tile-3d-layer", "initialViewState": { "latitude": 29.99, "longitude": 31.13, "pitch": 45, "maxPitch": 60, "bearing": 0, "minZoom": 2, "maxZoom": 30, "zoom": 12.8 }, "views": [ { "@@type": "MapView", "mapStyle": "https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json", "controller": true } ], "layers": [ { "@@type": "Tile3DLayer", "id": "tiles-cairo-vricon", "DracoWorkerLoader": "@!DracoWorkerLoader", "loader": "@@#CesiumIonLoader", "data": "https://assets.cesium.com/29328/tileset.json", "loadOptions": { "cesium-ion": { "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlYWMxMzcyYy0zZjJkLTQwODctODNlNi01MDRkZmMzMjIxOWIiLCJpZCI6OTYyMCwic2NvcGVzIjpbImFzbCIsImFzciIsImdjIl0sImlhdCI6MTU2Mjg2NjI3M30.1FNiClUyk00YH_nWfSGpiQAjR5V2OvREDq1PJ5QMjWQ" } } } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/line.json
{ "description": "The deck.gl website LineLayer example in JSON format", "websiteUrl": "https://deck.gl/#/examples/line-layers/line-layer", "initialViewState": { "latitude": 47.65, "longitude": 7, "zoom": 4.5, "maxZoom": 16, "pitch": 50, "bearing": 0 }, "map": true, "pickingRadius": 5, "views": [ { "@@type": "MapView", "controller": true, "mapStyle": "https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json" } ], "layers": [ { "@@type": "ScatterplotLayer", "id": "airports", "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/line/airports.json", "radiusScale": 20, "getPosition": "@@=coordinates", "getFillColor": [ 255, 140, 0 ], "getRadius": 60 }, { "@@type": "LineLayer", "id": "flight-paths", "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/line/heathrow-flights.json", "opacity": 0.8, "strokeWidth": 3, "getSourcePosition": "@@=start", "getTargetPosition": "@@=end", "getColor": [ 200, 32, 64, 192 ] } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/dot-text.json
{ "description": "A minimal deck.gl example rendering a circle with text", "initialViewState": { "longitude": -122.45, "latitude": 37.8, "zoom": 12 }, "layers": [ { "@@type": "ScatterplotLayer", "data": [ { "position": [ -122.45, 37.8 ] } ], "getFillColor": [ 255, 0, 0, 255 ], "getRadius": 1000 }, { "@@type": "TextLayer", "data": [ { "position": [ -122.45, 37.8 ], "text": "Hello World" } ] } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/3d-tiles-new-york.json
{ "description": "The deck.gl website tile-3d-layer example", "websiteUrl": "https://deck.gl/#/examples/geo-layers/tile-3d-layer", "initialViewState": { "latitude": 40.73, "longitude": -73.99, "pitch": 45, "maxPitch": 60, "bearing": 0, "minZoom": 2, "maxZoom": 30, "zoom": 10.77 }, "views": [ { "@@type": "MapView", "mapStyle": "https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json", "controller": true } ], "layers": [ { "@@type": "Tile3DLayer", "id": "tiles-new-york", "DracoWorkerLoader": "@!DracoWorkerLoader", "loader": "@@#CesiumIonLoader", "data": "https://assets.cesium.com/7162/tileset.json", "loadOptions": { "cesium-ion": { "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzMGY4ODczYy1mNTk4LTRiMDUtYmIxYy0xZWYwOWZmMGY4NjQiLCJpZCI6NDQsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJhc3NldHMiOlsxLDIsMyw0LDYxOTMsNjI3Myw3MTYyLDczNTMsNzE0Ml0sImlhdCI6MTU0MTYxODM0NX0.lWnGs9ySXO4QK3HagcMsDpZ8L01DpmUDQm38-2QAQuE" } } } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/us-map.json
{ "description": "A deck.gl get-started GeoJsonLayer example in JSON format", "initialViewState": { "latitude": 40, "longitude": -100, "zoom": 3, "bearing": 30, "pitch": 30 }, "map": true, "views": [ { "@@type": "MapView", "controller": true } ], "layers": [ { "@@type": "GeoJsonLayer", "data": "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_110m_admin_1_states_provinces_shp.geojson", "stroked": true, "filled": true, "lineWidthMinPixels": 2, "opacity": 0.4, "getLineColor": [ 255, 100, 100 ], "getFillColor": [ 200, 160, 0, 180 ] } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/geojson.json
{ "description": "The deck.gl website GeoJsonLayer (polygons) example in JSON format", "websiteUrl": "https://deck.gl/#/examples/core-layers/geojson-layer-polygons", "initialViewState": { "latitude": 49.254, "longitude": -123.13, "zoom": 11, "maxZoom": 16, "pitch": 45, "bearing": 0 }, "views": [ { "@@type": "MapView", "controller": true, "mapStyle": "https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json" } ], "layers": [ { "@@type": "GeoJsonLayer", "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/geojson/vancouver-blocks.json", "opacity": 0.8, "stroked": false, "filled": true, "extruded": true, "wireframe": true, "elevationScale": 0.10, "getElevation": "@@=properties.valuePerSqm", "getFillColor": [ 199, 233, 180 ], "getLineColor": [ 255, 255, 255 ] } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/3d-tiles-st-helens.json
{ "description": "The deck.gl website tile-3d-layer example", "websiteUrl": "https://deck.gl/#/examples/geo-layers/tile-3d-layer", "initialViewState": { "latitude": 46.26, "longitude": -122.12, "pitch": 45, "maxPitch": 60, "bearing": 0, "minZoom": 2, "maxZoom": 30, "zoom": 10 }, "views": [ { "@@type": "MapView", "mapStyle": "https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json", "controller": true } ], "layers": [ { "@@type": "Tile3DLayer", "id": "tiles-st-helens", "loader": "@@#CesiumIonLoader", "data": "https://assets.cesium.com/33301/tileset.json", "loadOptions": { "cesium-ion": { "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2NhMzkwYi0zNWM4LTRjNTYtYWE3Mi1jMDAxYzhlOGVmNTAiLCJpZCI6OTYxOSwic2NvcGVzIjpbImFzbCIsImFzciIsImFzdyIsImdjIl0sImlhdCI6MTU2MjE4MTMxM30.OkgVr6NaKYxabUMIGqPOYFe0V5JifXLVLfpae63x-tA" } } } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/carto.json
{ "description": "CartoLayer declarative example", "initialViewState": { "latitude": 40.7368521, "longitude": -73.8536065, "zoom": 3, "pitch": 0, "bearing": 0 }, "views": [ { "@@type": "MapView", "controller": true, "mapStyle": "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json" } ], "layers": [ { "@@type": "CartoLayer", "type": "@@#CARTO_MAP_TYPES.TILESET", "data": "cartobq.maps.osm_buildings", "getFillColor": { "@@function": "colorBins", "attr": "aggregated_total", "domain": [10, 100, 1000, 10000, 100000, 1000000], "colors": "BluYl" }, "pointRadiusMinPixels": 2, "stroked": false } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/json-examples/3d-heatmap-minimap.json
{ "description": "The deck.gl website hexagonlayer example (with added minimap)", "websiteUrl": "https://deck.gl/#/examples/core-layers/hexagon-layer", "initialViewState": { "id": "view-state", "longitude": -1.4157267858730052, "latitude": 52.232395363869415, "zoom": 6.6, "minZoom": 5, "maxZoom": 15, "pitch": 40.5, "bearing": -27.396674584323023 }, "views": [ { "@@type": "MapView", "id": "main", "mapStyle": "https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json", "controller": true }, { "@@type": "MapView", "id": "minimap", "mapStyle": "https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json", "width": "40%", "height": "40%", "x": "55%", "y": "5%", "clear": true, "viewState": { "id": "main", "pitch": 0, "bearing": 0, "zoom": 4 } } ], "layers": [ { "@@type": "HexagonLayer", "id": "heatmap", "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/3d-heatmap/heatmap-data.csv", "coverage": 1, "elevationRange": [0, 3000], "elevationScale": 50, "extruded": true, "getPosition": "@@=[lng,lat]", "radius": 1000, "upperPercentile": 100, "colorRange": [ [1, 152, 189], [73, 227, 206], [216, 254, 181], [254, 237, 177], [254, 173, 84], [209, 55, 78] ] } ] }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/src/deck-with-google-maps.jsx
/* global console, document, window */ import { GoogleMapsOverlay } from '@deck.gl/google-maps'; import * as React from 'react'; import { Component } from 'react'; const HOST = 'https://maps.googleapis.com/maps/api/js'; const LOADING_GIF = 'https://upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif'; const style = { height: 1000, width: 1000 }; function injectScript(src) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = src; script.addEventListener('load', resolve); script.addEventListener('error', e => reject(e.error)); document.head.appendChild(script); }); } function loadGoogleMapApi(apiKey, onComplete) { const url = `${HOST}?key=${apiKey}&libraries=places`; injectScript(url) .then(() => onComplete()) // eslint-disable-next-line no-console .catch(e => console.error(e)); } export default class DeckWithGoogleMaps extends Component { constructor(props) { super(props); this.state = { googleMapsLoaded: window.google && window.google.maps }; } componentDidMount() { const { googleMapsToken } = this.props; if (!window.google || (window.google && !window.google.maps)) { loadGoogleMapApi(googleMapsToken, () => { this.setState({ googleMapsLoaded: true }); }); } } render() { const { googleMapsLoaded } = this.state; if (!googleMapsLoaded) { return <img src={LOADING_GIF} alt='Loading Google Maps overlay...' />; } return < DeckOverlayWrapper {...this.props} />; } } class DeckOverlayWrapper extends Component { constructor(props) { super(props); this.state = { isOverlayConfigured: false }; this.DeckOverlay = new GoogleMapsOverlay({ layers: [] }); this.containerRef = React.createRef(); } componentDidMount() { const { initialViewState } = this.props; const view = { center: { lat: initialViewState.latitude, lng: initialViewState.longitude }, mapTypeId: this.props.mapTypeId || 'satellite', zoom: initialViewState.zoom }; const map = new window.google.maps.Map(this.containerRef.current, view); this.DeckOverlay.setMap(map); this.DeckOverlay.setProps({ layers: this.props.layers }); //eslint-disable-next-line react/no-did-mount-set-state this.setState({ isOverlayConfigured: true }); } componentDidUpdate(prevProps, prevState, snapshot) { this.DeckOverlay.setProps({ layers: this.props.layers }); } componentWillUnmount() { delete this.DeckOverlay; } render() { return <div ref={this.containerRef} style={style} />; } }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/src/configuration.js
// This configuration object determines which deck.gl classes are accessible in Playground import { MapView, FirstPersonView, OrbitView, OrthographicView } from '@deck.gl/core'; import * as Layers from '@deck.gl/layers'; import * as AggregationLayers from '@deck.gl/aggregation-layers'; import * as GeoLayers from '@deck.gl/geo-layers'; import * as MeshLayers from '@deck.gl/mesh-layers'; import { CartoLayer, CartoSQLLayer, CartoBQTilerLayer, MAP_TYPES as CARTO_MAP_TYPES, colorBins, colorCategories, colorContinuous } from '@deck.gl/carto'; import { COORDINATE_SYSTEM } from '@deck.gl/core'; import GL from '@luma.gl/constants'; import { registerLoaders } from '@loaders.gl/core'; import { CSVLoader } from '@loaders.gl/csv'; import { DracoWorkerLoader } from '@loaders.gl/draco'; import { Tiles3DLoader, CesiumIonLoader } from '@loaders.gl/3d-tiles'; // Note: deck already registers JSONLoader... registerLoaders([CSVLoader, DracoWorkerLoader]); export default { // Classes that should be instantiatable by JSON converter classes: Object.assign( // Support `@deck.gl/core` Views { MapView, FirstPersonView, OrbitView, OrthographicView }, // a map of all layers that should be exposes as JSONLayers Layers, AggregationLayers, GeoLayers, MeshLayers, { CartoLayer, CartoBQTilerLayer, CartoSQLLayer }, // Any non-standard views {} ), // Functions that should be executed by JSON converter functions: { colorBins, colorCategories, colorContinuous }, // Enumerations that should be available to JSON parser // Will be resolved as `<enum-name>.<enum-value>` enumerations: { COORDINATE_SYSTEM, GL, CARTO_MAP_TYPES }, // Constants that should be resolved with the provided values by JSON converter constants: { Tiles3DLoader, CesiumIonLoader } };
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/src/deck-with-mapbox-maps.jsx
import { View } from '@deck.gl/core'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { Component } from 'react'; export default class DeckWithMapboxMaps extends Component { render() { const { views = [] } = this.props; const maps = []; for (const view of views) { if (view.props.map || view.props.mapStyle) { maps.push( <View id={view.props.id} key={view.props.id}> <this.props.Map reuseMap mapStyle={view.props.mapStyle} mapboxApiAccessToken={view.props.mapToken || this.props.mapboxApiAccessToken} /> </View> ); } } return ( <DeckGL id='json-deck' {...this.props}> {maps} </DeckGL> ); } }
0
rapidsai_public_repos/node/modules/demo/deck/playground
rapidsai_public_repos/node/modules/demo/deck/playground/src/app.jsx
import * as React from 'react' import { Component, Fragment } from 'react'; import { StaticMap } from 'react-map-gl'; import DeckWithMapboxMaps from './deck-with-mapbox-maps.jsx'; import DeckWithGoogleMaps from './deck-with-google-maps.jsx'; import { FlyToInterpolator } from '@deck.gl/core'; import { JSONConverter, JSONConfiguration, _shallowEqualObjects } from '@deck.gl/json'; import JSON_CONVERTER_CONFIGURATION from './configuration'; import JSON_TEMPLATES from '../json-examples'; const INITIAL_TEMPLATE = Object.keys(JSON_TEMPLATES)[0]; // Set your mapbox token here const GOOGLE_MAPS_TOKEN = process.env.GoogleMapsAPIKey; // eslint-disable-line function isFunctionObject(value) { return typeof value === 'object' && '@@function' in value; } function addUpdateTriggersForAccessors(json) { if (!json || !json.layers) return; for (const layer of json.layers) { const updateTriggers = {}; for (const [key, value] of Object.entries(layer)) { if ((key.startsWith('get') && typeof value === 'string') || isFunctionObject(value)) { // it's an accessor and it's a string // we add the value of the accesor to update trigger to refresh when it changes updateTriggers[key] = value; } } if (Object.keys(updateTriggers).length) { layer.updateTriggers = updateTriggers; } } } export default class App extends Component { constructor(props) { super(props); this.state = { // react-ace text: '', // deck.gl JSON Props jsonProps: {}, initialViewState: null }; // TODO/ib - could use arrow functions // keeping like this for now to allow this code to be copied back to deck.gl this._onTemplateChange = this._onTemplateChange.bind(this); this._onEditorChange = this._onEditorChange.bind(this); // Configure and create the JSON converter instance const configuration = new JSONConfiguration(JSON_CONVERTER_CONFIGURATION); this.jsonConverter = new JSONConverter({ configuration }); } componentDidMount() { let found = INITIAL_TEMPLATE; try { const { template } = this.props; if (template) { const json = require(require('path').join('..', 'json-examples', template)); found = Object.keys(JSON_TEMPLATES).find((key) => JSON_TEMPLATES[key] === json); } } catch (e) { }; this._setTemplate(found || INITIAL_TEMPLATE); } // Updates deck.gl JSON props // Called on init, when template is changed, or user types _setTemplate(value) { const json = JSON_TEMPLATES[value]; if (json) { // Triggers an editor change, which updates the JSON this._setEditorText(json); this._setJSON(json); } } _setJSON(json) { addUpdateTriggersForAccessors(json); const jsonProps = this.jsonConverter.convert(json); this._updateViewState(jsonProps); this.setState({ jsonProps }); } // Handle `json.initialViewState` // If we receive new JSON we need to decide if we should update current view state // Current heuristic is to compare with last `initialViewState` and only update if changed _updateViewState(json) { const initialViewState = json.initialViewState || json.viewState; if (initialViewState) { const updateViewState = !this.state.initialViewState || !_shallowEqualObjects(initialViewState, this.state.initialViewState); if (updateViewState) { this.setState({ initialViewState: { ...initialViewState, // Tells deck.gl to animate the camera move to the new tileset transitionDuration: 4000, transitionInterpolator: new FlyToInterpolator() } }); } } return json; } // Updates pretty printed text in editor. // Called on init, when template is changed, or user types _setEditorText(json) { // Pretty print JSON with tab size 2 const text = typeof json !== 'string' ? JSON.stringify(json, null, 2) : json; // console.log('setting text', text) this.setState({ text }); } _onTemplateChange(event) { const value = event && event.target && event.target.value; this._setTemplate(value); } _onEditorChange(text, event) { let json = null; // Parse JSON, while capturing and ignoring exceptions try { json = text && JSON.parse(text); } catch (error) { // ignore error, user is editing and not yet correct JSON } this._setEditorText(text); this._setJSON(json); } _renderJsonSelector() { return ( <select name="JSON templates" onChange={this._onTemplateChange}> {Object.entries(JSON_TEMPLATES).map(([key]) => ( <option key={key} value={key}> {key} </option> ))} </select> ); } render() { const { jsonProps, initialViewState } = this.state; let deckMap; if (jsonProps.google === true) { deckMap = ( <DeckWithGoogleMaps initialViewState={initialViewState} id="json-deck" {...jsonProps} googleMapsToken={GOOGLE_MAPS_TOKEN} ref={(e) => window._inputEventTarget = e && e.current} /> ); } else { deckMap = ( <DeckWithMapboxMaps id="json-deck" {...jsonProps} Map={StaticMap} initialViewState={initialViewState} ref={(e) => window._inputEventTarget = e && e.current} /> ); } return ( <Fragment> {/* Left Pane: Ace Editor and Template Selector */} {/* <div id="left-pane"> {this._renderJsonSelector()} <div id="editor"> <AutoSizer> {({ width, height }) => ( <AceEditor width={`${width}px`} height={`${height}px`} mode="json" theme="github" onChange={this._onEditorChange} name="AceEditorDiv" editorProps={{ $blockScrolling: true }} ref={instance => { this.ace = instance; }} value={this.state.text} /> )} </AutoSizer> </div> </div> */} {/* Right Pane: DeckGL */} <div id="right-pane">{deckMap}</div> </Fragment> ); } }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/highway/package.json
{ "private": true, "name": "@rapidsai/demo-deck-highway", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "d3-request": "1.0.6", "d3-scale": "2.2.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/highway/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Highway Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/highway/README.md
This is a minimal standalone version of the GeoJsonLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/geojson). To use your own data, checkout the [documentation of GeoJsonLayer](../../../docs/layers/geojson-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/highway/app.jsx
import { GeoJsonLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import { scaleLinear, scaleThreshold } from 'd3-scale'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here const MAPBOX_TOKEN = 'pk.eyJ1Ijoid21qcGlsbG93IiwiYSI6ImNrN2JldzdpbDA2Ym0zZXFzZ3oydXN2ajIifQ.qPOZDsyYgMMUhxEKrvHzRA'; // eslint-disable-line // Source data GeoJSON const DATA_URL = { ACCIDENTS: 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/highway/accidents.csv', ROADS: 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/highway/roads.json' }; function getKey({ state, type, id }) { return `${state}-${type}-${id}`; } export const COLOR_SCALE = scaleThreshold().domain([0, 4, 8, 12, 20, 32, 52, 84, 136, 220]).range([ [26, 152, 80], [102, 189, 99], [166, 217, 106], [217, 239, 139], [255, 255, 191], [254, 224, 139], [253, 174, 97], [244, 109, 67], [215, 48, 39], [168, 0, 0] ]); const WIDTH_SCALE = scaleLinear().clamp(true).domain([0, 200]).range([10, 2000]); const INITIAL_VIEW_STATE = { latitude: 38, longitude: -100, zoom: 4, minZoom: 2, maxZoom: 8 }; export default class App extends Component { constructor(props) { super(props); this.state = { hoveredObject: null, ...this._aggregateAccidents(props.accidents) }; this._onHover = this._onHover.bind(this); this._renderTooltip = this._renderTooltip.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.accidents !== this.props.accidents) { this.setState({ ...this._aggregateAccidents(nextProps.accidents) }); } } _aggregateAccidents(accidents) { const incidents = {}; const fatalities = {}; if (accidents) { accidents.forEach(a => { const r = (incidents[a.year] = incidents[a.year] || {}); const f = (fatalities[a.year] = fatalities[a.year] || {}); const key = getKey(a); r[key] = a.incidents; f[key] = a.fatalities; }); } return { incidents, fatalities }; } _getLineColor(f, fatalities) { if (!fatalities) { return [200, 200, 200]; } const key = getKey(f.properties); const fatalitiesPer1KMile = ((fatalities[key] || 0) / f.properties.length) * 1000; return COLOR_SCALE(fatalitiesPer1KMile); } _getLineWidth(f, incidents) { if (!incidents) { return 10; } const key = getKey(f.properties); const incidentsPer1KMile = ((incidents[key] || 0) / f.properties.length) * 1000; return WIDTH_SCALE(incidentsPer1KMile); } _onHover({ x, y, object }) { this.setState({ x, y, hoveredObject: object }); } _renderLayers() { const { roads = DATA_URL.ROADS, year } = this.props; const { incidents, fatalities } = this.state; return [new GeoJsonLayer({ id: 'geojson', data: roads, stroked: false, filled: false, lineWidthMinPixels: 0.5, parameters: { depthTest: false }, getLineColor: f => this._getLineColor(f, fatalities[year]), getLineWidth: f => this._getLineWidth(f, incidents[year]), pickable: true, onHover: this._onHover, updateTriggers: { getLineColor: { year }, getLineWidth: { year } }, transitions: { getLineColor: 1000, getLineWidth: 1000 } })]; } _renderTooltip() { const { hoveredObject, x, y, fatalities, incidents } = this.state; const { year } = this.props; if (!hoveredObject) { return null; } const props = hoveredObject.properties; const key = getKey(props); const f = ((fatalities || {})[year] || {})[key] || ''; const r = ((incidents || {})[year] || {})[key] || ''; const content = r ? ( <div><b>{f}</b> people died in <b>{r}</b>crashes on{' '} { props.type === 'SR' ? props.state : props.type} - {props.id} in <b>{year}</b> </div> ) : ( <div> no accidents recorded in <b>{year}</b> </div> ); return ( <div className='tooltip' style={{ left: x, top: y }}> <big> {props.name}({props.state}) </big> {content} </div> ); } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL layers={this._renderLayers()} pickingRadius={5} initialViewState={INITIAL_VIEW_STATE} controller={true}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> {this._renderTooltip} </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); const formatRow = d => ({ ...d, incidents: Number(d.incidents), fatalities: Number(d.fatalities) }); require('d3-request').csv(DATA_URL.ACCIDENTS, formatRow, (error, response) => { if (!error) { render(<App accidents={response} year={response[0].year} />, container); } }); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/map-tile/package.json
{ "private": true, "name": "@rapidsai/demo-deck-map-tile", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/geo-layers": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "app.js", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/map-tile/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Map Tile Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/map-tile/README.md
This is a standalone version of the [OpenStreetMap](https://www.openstreetmap.org/) example using TileLayer and BitmapLayer on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data Source The sample tiles are loaded from [OpenStreetMap](https://www.openstreetmap.org).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/map-tile/app.jsx
import { MapView } from '@deck.gl/core'; import { TileLayer } from '@deck.gl/geo-layers'; import { BitmapLayer, PathLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; const INITIAL_VIEW_STATE = { latitude: 47.65, longitude: 7, zoom: 4.5, maxZoom: 20, maxPitch: 89, bearing: 0 }; /* global window */ const devicePixelRatio = (typeof window !== 'undefined' && window.devicePixelRatio) || 1; function getTooltip({ tile }) { return tile && `tile: x: ${tile.x}, y: ${tile.y}, z: ${tile.z}`; } export default function App({ showBorder = false, onTilesLoad = null }) { const tileLayer = new TileLayer({ // https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers data: [ 'https://a.tile.openstreetmap.org/{z}/{x}/{y}.png', 'https://b.tile.openstreetmap.org/{z}/{x}/{y}.png', 'https://c.tile.openstreetmap.org/{z}/{x}/{y}.png' ], // Since these OSM tiles support HTTP/2, we can make many concurrent requests // and we aren't limited by the browser to a certain number per domain. maxRequests: 20, pickable: true, onViewportLoad: onTilesLoad, autoHighlight: showBorder, highlightColor: [60, 60, 60, 40], // https://wiki.openstreetmap.org/wiki/Zoom_levels minZoom: 0, maxZoom: 19, tileSize: 256, zoomOffset: devicePixelRatio === 1 ? -1 : 0, renderSubLayers: props => { const { bbox: { west, south, east, north } } = props.tile; return [ new BitmapLayer(props, { data: null, image: props.data, bounds: [west, south, east, north] }), showBorder && new PathLayer({ id: `${props.id}-border`, visible: props.visible, data: [[[west, north], [west, south], [east, south], [east, north], [west, north]]], getPath: d => d, getColor: [255, 0, 0], widthMinPixels: 4 }) ]; } }); return ( <DeckGL layers={[tileLayer]} views={new MapView({ repeat: true })} initialViewState={INITIAL_VIEW_STATE} controller={true} getTooltip={getTooltip} > </DeckGL> ); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/image-tile/package.json
{ "private": true, "name": "@rapidsai/demo-deck-image-tile", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/geo-layers": "8.8.10", "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@loaders.gl/core": "3.2.9", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "app.js", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/image-tile/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Image Tile Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/image-tile/README.md
This is a standalone high resolution image example using TileLayer and BitmapLayer, with non-geospatial coordinates on the [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data Source A DeepZoom pyramid was created from a [source image](http://lroc.sese.asu.edu/posts/293). If you have [libvips](https://github.com/libvips/libvips) installed, you can run something from the command line like: `vips dzsave wac_nearside.tif moon.image --tile-size 512 --overlap 0`
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/image-tile/app.jsx
import * as React from 'react' import { PureComponent } from 'react'; import { render } from 'react-dom'; import { OrthographicView, COORDINATE_SYSTEM } from '@deck.gl/core'; import DeckGL from '@deck.gl/react'; import { TileLayer } from '@deck.gl/geo-layers'; import { BitmapLayer } from '@deck.gl/layers'; import { load } from '@loaders.gl/core'; const INITIAL_VIEW_STATE = { target: [13000, 13000, 0], zoom: -5 }; const ROOT_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/website/image-tiles/moon.image'; export default class App extends PureComponent { constructor(props) { super(props); this.state = { height: null, width: null, tileSize: null }; this._onHover = this._onHover.bind(this); this._renderTooltip = this._renderTooltip.bind(this); this.inTileBounds = this.inTileBounds.bind(this); this.cutOffImageBounds = this.cutOffImageBounds.bind(this); this.fetchDataFromDZI(`${ROOT_URL}/moon.image.dzi`); } _onHover({ x, y, sourceLayer, tile }) { this.setState({ x, y, hoveredObject: { sourceLayer, tile } }); } _renderTooltip() { const { x, y, hoveredObject } = this.state; const { sourceLayer, tile } = hoveredObject || {}; return ( sourceLayer && tile && ( <div className="tooltip" style={{ left: x, top: y }}> tile: x: {tile.x}, y: {tile.y}, z: {tile.z} </div> ) ); } inTileBounds({ x, y, z }) { const xInBounds = x < Math.ceil(this.state.width / (this.state.tileSize * 2 ** z)) && x >= 0; const yInBounds = y < Math.ceil(this.state.height / (this.state.tileSize * 2 ** z)) && y >= 0; return xInBounds && yInBounds; } cutOffImageBounds({ left, bottom, right, top }) { return { left: Math.max(0, left), bottom: Math.max(0, Math.min(this.state.height, bottom)), right: Math.max(0, Math.min(this.state.width, right)), top: Math.max(0, top) }; } fetchDataFromDZI(dziSource) { return ( fetch(dziSource) // eslint-disable-line no-undef .then(response => response.text()) // eslint-disable-next-line no-undef .then(str => new window.DOMParser().parseFromString(str, 'text/xml')) .then(dziXML => { if (Number(dziXML.getElementsByTagName('Image')[0].attributes.Overlap.value) !== 0) { // eslint-disable-next-line no-undef, no-console console.warn('Overlap paramter is nonzero and should be 0'); } this.setState({ height: Number(dziXML.getElementsByTagName('Size')[0].attributes.Height.value), width: Number(dziXML.getElementsByTagName('Size')[0].attributes.Width.value), tileSize: Number(dziXML.getElementsByTagName('Image')[0].attributes.TileSize.value) }); }) ); } _renderLayers() { const { autoHighlight = true, highlightColor = [60, 60, 60, 40] } = this.props; const { tileSize } = this.state; return [ new TileLayer({ pickable: true, onHover: this._onHover, tileSize, autoHighlight, highlightColor, minZoom: -16, maxZoom: 0, coordinateSystem: COORDINATE_SYSTEM.CARTESIAN, getTileData: ({ x, y, z }) => { if (this.inTileBounds({ x, y, z: -z })) { return load(`${ROOT_URL}/moon.image_files/${15 + z}/${x}_${y}.jpeg`); } return null; }, renderSubLayers: props => { const { bbox: { left, bottom, right, top } } = props.tile; const newBounds = this.cutOffImageBounds({ left, bottom, right, top }); return new BitmapLayer(props, { data: null, image: props.data, bounds: [newBounds.left, newBounds.bottom, newBounds.right, newBounds.top] }); } }) ]; } render() { return ( <DeckGL views={[new OrthographicView({ id: 'ortho' })]} layers={this.state.tileSize ? this._renderLayers() : []} initialViewState={INITIAL_VIEW_STATE} controller={true} > {this._renderTooltip} </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/3d-tiles/package.json
{ "private": true, "name": "@rapidsai/demo-deck-3d-tiles", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/geo-layers": "8.8.10", "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@loaders.gl/3d-tiles": "3.2.9", "@loaders.gl/core": "3.2.9", "@loaders.gl/draco": "3.2.9", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/3d-tiles/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: '3D Titles Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/3d-tiles/README.md
This is a minimal standalone version of the 3D Tile example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). To download the Cesium 3D tileset, you need a Cesium ion access token, and set it to `ION_TOKEN` in `app.js`. ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in Cesium ion server. To use your own data, checkout the [documentation of Tile3DLayer](../../../docs/layers/tile-3d-layer.md)
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/3d-tiles/app.jsx
import { Tile3DLayer } from '@deck.gl/geo-layers'; import DeckGL from '@deck.gl/react'; import { CesiumIonLoader } from '@loaders.gl/3d-tiles'; import { registerLoaders } from '@loaders.gl/core'; // To manage dependencies and bundle size, the app must decide which supporting loaders to bring in import { DracoWorkerLoader } from '@loaders.gl/draco'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; registerLoaders([DracoWorkerLoader]); // Set your mapbox token here const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line const ION_ASSET_ID = 43978; const ION_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlYWMxMzcyYy0zZjJkLTQwODctODNlNi01MDRkZmMzMjIxOWIiLCJpZCI6OTYyMCwic2NvcGVzIjpbImFzbCIsImFzciIsImdjIl0sImlhdCI6MTU2Mjg2NjI3M30.1FNiClUyk00YH_nWfSGpiQAjR5V2OvREDq1PJ5QMjWQ'; const TILESET_URL = `https://assets.cesium.com/${ION_ASSET_ID}/tileset.json`; const INITIAL_VIEW_STATE = { latitude: 40, longitude: -75, pitch: 45, maxPitch: 60, bearing: 0, minZoom: 2, maxZoom: 30, zoom: 17 }; export default class App extends Component { constructor(props) { super(props); this.state = { initialViewState: INITIAL_VIEW_STATE, attributions: [] }; } _onTilesetLoad(tileset) { this._centerViewOnTileset(tileset); if (this.props.updateAttributions) { this.props.updateAttributions(tileset.credits && tileset.credits.attributions); } } // Recenter view to cover the new tileset, with a fly-to transition _centerViewOnTileset(tileset) { const { cartographicCenter, zoom } = tileset; this.setState({ initialViewState: { ...INITIAL_VIEW_STATE, // Update deck.gl viewState, moving the camera to the new tileset longitude: cartographicCenter[0], latitude: cartographicCenter[1], zoom, bearing: INITIAL_VIEW_STATE.bearing, pitch: INITIAL_VIEW_STATE.pitch } }); } _renderTile3DLayer() { return new Tile3DLayer({ id: 'tile-3d-layer', pointSize: 2, data: TILESET_URL, loader: CesiumIonLoader, loadOptions: { 'cesium-ion': { accessToken: ION_TOKEN } }, onTilesetLoad: this._onTilesetLoad.bind(this) }); } render() { const { initialViewState } = this.state; const tile3DLayer = this._renderTile3DLayer(); const { mapStyle = 'mapbox://styles/uberdata/cive485h000192imn6c6cc8fc' } = this.props; return ( <div> <DeckGL layers={[tile3DLayer]} initialViewState={initialViewState} controller={true}> <StaticMap mapStyle={mapStyle} mapboxApiAccessToken={MAPBOX_TOKEN} preventStyleDiffing /> </DeckGL> </div>); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/worldmap/package.json
{ "private": true, "name": "@rapidsai/demo-deck-worldmap", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/worldmap/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'World Map Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/worldmap/README.md
This is a minimal standalone version of the Worldmap example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ```
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/worldmap/app.jsx
import { _SunLight as SunLight, AmbientLight, LightingEffect } from '@deck.gl/core'; import { GeoJsonLayer, PolygonLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here const MAPBOX_TOKEN = 'pk.eyJ1Ijoid21qcGlsbG93IiwiYSI6ImNrN2JldzdpbDA2Ym0zZXFzZ3oydXN2ajIifQ.qPOZDsyYgMMUhxEKrvHzRA'; // eslint-disable-line // Source data GeoJSON const DATA_URL = 'https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json'; export const INITIAL_VIEW_STATE = { latitude: 49.254, longitude: -123.13, zoom: 1, maxZoom: 16, pitch: 45, bearing: 0 }; const ambientLight = new AmbientLight({ color: [255, 255, 255], intensity: 1.0 }); const dirLight = new SunLight( { timestamp: Date.UTC(2019, 7, 1, 22), color: [255, 255, 255], intensity: 1.0, _shadow: true }); const landCover = [[[-123.0, 49.196], [-123.0, 49.324], [-123.306, 49.324], [-123.306, 49.196]]]; export default class App extends Component { constructor(props) { super(props); this.state = { hoveredObject: null }; this._onHover = this._onHover.bind(this); this._renderTooltip = this._renderTooltip.bind(this); const lightingEffect = new LightingEffect({ ambientLight, dirLight }); lightingEffect.shadowColor = [0, 0, 0, 1]; this._effects = [lightingEffect]; } _onHover({ x, y, object }) { this.setState({ x, y, hoveredObject: object }); } _renderLayers() { const { data = DATA_URL } = this.props; return [ // console.log(data), // only needed when using shadows - a plane for shadows to drop on new PolygonLayer({ id: 'ground', data: landCover, stroked: false, getPolygon: f => f, getFillColor: [0, 0, 0, 0] }), new GeoJsonLayer({ id: 'geojson', data, opacity: 0.9, stroked: false, filled: true, extruded: true, wireframe: true, getElevation: 8000, getFillColor: [65, 182, 196], getLineColor: [65, 182, 196], pickable: true, onHover: this._onHover }), ]; } _renderTooltip() { const { x, y, hoveredObject } = this.state; return ( hoveredObject && (<div className='tooltip' style={{ top: y, left: x }}><div><b>Country</b> </div> <div> <div>{hoveredObject.properties .name}</div> <div> id:{hoveredObject.id} </div> </div> </div>)); } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL layers={this._renderLayers()} effects={this._effects} initialViewState={INITIAL_VIEW_STATE} controller={true}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> {this._renderTooltip} </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/trips/package.json
{ "private": true, "name": "@rapidsai/demo-deck-trips", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/geo-layers": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/trips/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Trips Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/trips/README.md
This is a minimal standalone version of the [TripsLayer example](https://deck.gl/#/examples/custom-layers/trip-routes) on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/trips). To use your own data, checkout the [documentation of TripsLayer](https://github.com/uber/deck.gl/tree/master/modules/experimental-layers/src/trips-layer).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/trips/app.jsx
/* global window */ import { AmbientLight, LightingEffect, PointLight } from '@deck.gl/core'; import { TripsLayer } from '@deck.gl/geo-layers'; import { PolygonLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here const MAPBOX_TOKEN = 'pk.eyJ1Ijoid21qcGlsbG93IiwiYSI6ImNrN2JldzdpbDA2Ym0zZXFzZ3oydXN2ajIifQ.qPOZDsyYgMMUhxEKrvHzRA'; // eslint-disable-line // Source data CSV const DATA_URL = { BUILDINGS: 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/trips/buildings.json', // eslint-disable-line TRIPS: 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/trips/trips-v7.json' // eslint-disable-line }; const ambientLight = new AmbientLight({ color: [255, 255, 255], intensity: 1.0 }); const pointLight = new PointLight({ color: [255, 255, 255], intensity: 2.0, position: [-74.05, 40.7, 8000] }); const lightingEffect = new LightingEffect({ ambientLight, pointLight }); const material = { ambient: 0.1, diffuse: 0.6, shininess: 32, specularColor: [60, 64, 70] }; const DEFAULT_THEME = { buildingColor: [74, 80, 87], trailColor0: [253, 128, 93], trailColor1: [23, 184, 190], material, effects: [lightingEffect] }; const INITIAL_VIEW_STATE = { longitude: -74, latitude: 40.72, zoom: 13, pitch: 45, bearing: 0 }; const landCover = [[[-74.0, 40.7], [-74.02, 40.7], [-74.02, 40.72], [-74.0, 40.72]]]; export default class App extends Component { constructor(props) { super(props); this.state = { time: 0 }; } componentDidMount() { this._animate(); } componentWillUnmount() { if (this._animationFrame) { window.cancelAnimationFrame(this._animationFrame); } } _animate() { const { loopLength = 1800, // unit corresponds to the timestamp in source data animationSpeed = 30 // unit time per second } = this.props; const timestamp = Date.now() / 1000; const loopTime = loopLength / animationSpeed; this.setState({ time: ((timestamp % loopTime) / loopTime) * loopLength }); this._animationFrame = window.requestAnimationFrame(this._animate.bind(this)); } _renderLayers() { const { buildings = DATA_URL.BUILDINGS, trips = DATA_URL.TRIPS, trailLength = 180, theme = DEFAULT_THEME } = this.props; return [ // This is only needed when using shadow effects new PolygonLayer({ id: 'ground', data: landCover, getPolygon: f => f, stroked: false, getFillColor: [0, 0, 0, 0] }), new TripsLayer({ id: 'trips', data: trips, getPath: d => d.path, getTimestamps: d => d.timestamps, getColor: d => (d.vendor === 0 ? theme.trailColor0 : theme.trailColor1), opacity: 0.3, widthMinPixels: 2, rounded: true, trailLength, currentTime: this.state.time, shadowEnabled: false }), new PolygonLayer({ id: 'buildings', data: buildings, extruded: true, wireframe: false, opacity: 0.5, getPolygon: f => f.polygon, getElevation: f => f.height, getFillColor: theme.buildingColor, material: theme.material }), ]; } render() { const { viewState, mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json', theme = DEFAULT_THEME } = this.props; return ( <DeckGL layers={this._renderLayers()} effects={theme.effects} initialViewState={INITIAL_VIEW_STATE} viewState={viewState} controller={true}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/scatterplot/package.json
{ "private": true, "name": "@rapidsai/demo-deck-scatterplot", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/scatterplot/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Scatter Plot Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/scatterplot/README.md
This is a minimal standalone version of the ScatterplotLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/scatterplot). To use your own data, checkout the [documentation of ScatterplotLayer](../../../docs/layers/scatterplot-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/scatterplot/app.jsx
import { ScatterplotLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line const MALE_COLOR = [0, 128, 255]; const FEMALE_COLOR = [255, 0, 128]; // Source data CSV const DATA_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/scatterplot/manhattan.json'; // eslint-disable-line const INITIAL_VIEW_STATE = { longitude: -74, latitude: 40.7, zoom: 11, maxZoom: 16, pitch: 0, bearing: 0 }; export default class App extends Component { _renderLayers() { const { data = DATA_URL, radius = 30, maleColor = MALE_COLOR, femaleColor = FEMALE_COLOR } = this.props; return [new ScatterplotLayer({ id: 'scatter-plot', data, radiusScale: radius, radiusMinPixels: 0.25, getPosition: d => [d[0], d[1], 0], getFillColor: d => (d[2] === 1 ? maleColor : femaleColor), getRadius: 1, updateTriggers: { getFillColor: [maleColor, femaleColor] } })]; } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL layers={this._renderLayers()} initialViewState={INITIAL_VIEW_STATE} controller={true}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/text-layer/package.json
{ "private": true, "name": "@rapidsai/demo-deck-text-layer", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@luma.gl/constants": "8.5.16", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/text-layer/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Text Layer Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/text-layer/README.md
This is a standalone demo of the [text layer](./text-layer) built upon [deck.gl](http://deck.gl). This example illustrates the text layer features by animating a small sample of Twitter hashtags posted in the U.S. during one day. You can tweak `app.js` to generate a static text layer instead. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data can be found [here](https://rivulet-zhang.github.io/dataRepo/text-layer/hashtagsOneDay.json).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/text-layer/app.jsx
/* eslint-disable max-len */ /* global fetch, window */ import { TextLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import GL from '@luma.gl/constants'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here const MAPBOX_TOKEN = process.env.MapboxAccessToken || 'pk.eyJ1Ijoid21qcGlsbG93IiwiYSI6ImNrN2JldzdpbDA2Ym0zZXFzZ3oydXN2ajIifQ.qPOZDsyYgMMUhxEKrvHzRA'; // eslint-disable-line // mapbox style file path const MAPBOX_STYLE = ( 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' || 'https://rivulet-zhang.github.io/dataRepo/mapbox/style/map-style-dark-v9-no-labels.json' ); // sample data const DATA_URL = 'https://rivulet-zhang.github.io/dataRepo/text-layer/hashtagsOneDayWithTime.json'; const SECONDS_PER_DAY = 24 * 60 * 60; // visualize data within in the time window of [current - TIME_WINDOW, current + TIME_WINDOW] const TIME_WINDOW = 2; const TEXT_COLOR = [255, 200, 0]; const INITIAL_VIEW_STATE = { latitude: 39.1, longitude: -94.57, zoom: 3.8, maxZoom: 16, pitch: 0, bearing: 0 }; export default class App extends Component { constructor(props) { super(props); this.state = {}; if (!window.demoLauncherActive) { this._loadData(); } } componentWillUnmount() { if (this._animationFrame) { window.cancelAnimationFrame(this._animationFrame); } } _loadData() { fetch(DATA_URL).then(resp => resp.json()).then(resp => { // each entry in the data object contains all tweets posted at that second const data = Array.from({ length: SECONDS_PER_DAY }, () => []); resp.forEach(val => { const second = parseInt(val.time, 10) % SECONDS_PER_DAY; data[second].push(val); }); this.setState({ data }); window.requestAnimationFrame(this._animateData.bind(this)); }); } _animateData() { const { data } = this.state; const now = Date.now(); const getSecCeil = ms => Math.ceil(ms / 1000, 10) % SECONDS_PER_DAY; const getSecFloor = ms => Math.floor(ms / 1000, 10) % SECONDS_PER_DAY; const timeWindow = [getSecCeil(now - TIME_WINDOW * 1000), getSecFloor(now + TIME_WINDOW * 1000)]; if (data) { let dataSlice = []; for (let i = timeWindow[0]; i <= timeWindow[1]; i++) { if (i >= 0 && i < data.length) { const slice = data[i].map(val => { const offset = Math.abs(getSecFloor(now) + (now % 1000) / 1000 - i) / TIME_WINDOW; // use non-linear function to achieve smooth animation const opac = Math.cos((offset * Math.PI) / 2); const color = [...TEXT_COLOR, opac * 255]; return Object.assign({}, val, { color }, { size: 12 * (opac + 1) }); }); dataSlice = [...dataSlice, ...slice]; } } this.setState({ dataSlice }); } this._animationFrame = window.requestAnimationFrame(this._animateData.bind(this)); } _renderLayers() { return [new TextLayer({ id: 'hashtag-layer', data: this.state.dataSlice, sizeScale: 4, getPosition: d => d.coordinates, getColor: d => d.color, getSize: d => d.size })]; } render() { const { mapStyle = MAPBOX_STYLE } = this.props; return ( <DeckGL layers={this._renderLayers()} initialViewState={INITIAL_VIEW_STATE} controller={true} parameters={{ blendFunc: [GL.SRC_ALPHA, GL.ONE, GL.ONE_MINUS_DST_ALPHA, GL.ONE], blendEquation: GL.FUNC_ADD }}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/screen-grid/package.json
{ "private": true, "name": "@rapidsai/demo-deck-screengrid", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/aggregation-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@luma.gl/core": "8.5.16", "@rapidsai/jsdom": "~22.12.2", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/screen-grid/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Screen Grid Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/screen-grid/README.md
This is a minimal standalone version of the ScreenGridLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/screen-grid). To use your own data, checkout the [documentation of ScreenGridLayer](../../../docs/layers/screen-grid-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/screen-grid/app.jsx
import { ScreenGridLayer } from '@deck.gl/aggregation-layers'; import DeckGL from '@deck.gl/react'; import { isWebGL2 } from '@luma.gl/core'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line // Source data CSV const DATA_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/screen-grid/uber-pickup-locations.json'; // eslint-disable-line const INITIAL_VIEW_STATE = { longitude: -73.75, latitude: 40.73, zoom: 9.6, maxZoom: 16, pitch: 0, bearing: 0 }; const colorRange = [ [255, 255, 178, 25], [254, 217, 118, 85], [254, 178, 76, 127], [253, 141, 60, 170], [240, 59, 32, 212], [189, 0, 38, 255] ]; export default class App extends Component { _renderLayers() { const { data = DATA_URL, cellSize = 20, gpuAggregation = true, aggregation = 'SUM' } = this.props; return [new ScreenGridLayer({ id: 'grid', data, opacity: 0.8, getPosition: d => [d[0], d[1]], getWeight: d => d[2], cellSizePixels: cellSize, colorRange, gpuAggregation, aggregation })]; } _onInitialized(gl) { if (!isWebGL2(gl)) { console.warn('GPU aggregation is not supported'); // eslint-disable-line if (this.props.disableGPUAggregation) { this.props.disableGPUAggregation(); } } } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL layers={this._renderLayers()} initialViewState={INITIAL_VIEW_STATE} onWebGLInitialized={this._onInitialized.bind(this)} controller={true}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/bezier/package.json
{ "private": true, "name": "@rapidsai/demo-deck-bezier", "version": "22.12.2", "main": "index.js", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "src", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/bezier/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Bezier Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./src/app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/bezier/README.md
This is a minimal standalone version of the BezierCurveLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. Run ``` npm install npm start ``` ### Data format To use your own data, checkout the [documentation of BezierCurveLayer](../../docs/layers/bezier-curve-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck/bezier
rapidsai_public_repos/node/modules/demo/deck/bezier/src/sample-graph.json
{ "nodes": [ {"id": "a", "position": [0, -100]}, {"id": "b", "position": [-95.1, -30.9]}, {"id": "c", "position": [-58.7, 80.9]}, {"id": "d", "position": [58.7, 80.9]}, {"id": "e", "position": [95.1, -30.9]}, {"id": "f", "position": [0, 0]} ], "edges": [ { "id": "1", "sourceId": "a", "targetId": "b" }, { "id": "2", "sourceId": "b", "targetId": "a" }, { "id": "3", "sourceId": "a", "targetId": "f" }, { "id": "4", "sourceId": "f", "targetId": "a" }, { "id": "5", "sourceId": "a", "targetId": "e" }, { "id": "6", "sourceId": "e", "targetId": "a" }, { "id": "7", "sourceId": "b", "targetId": "c" }, { "id": "8", "sourceId": "c", "targetId": "b" }, { "id": "9", "sourceId": "b", "targetId": "f" }, { "id": "9", "sourceId": "f", "targetId": "b" }, { "id": "10", "sourceId": "c", "targetId": "f" }, { "id": "11", "sourceId": "f", "targetId": "c" }, { "id": "12", "sourceId": "c", "targetId": "d" }, { "id": "13", "sourceId": "d", "targetId": "c" }, { "id": "14", "sourceId": "d", "targetId": "f" }, { "id": "14", "sourceId": "f", "targetId": "d" }, { "id": "15", "sourceId": "d", "targetId": "e" }, { "id": "15", "sourceId": "e", "targetId": "d" }, { "id": "16", "sourceId": "e", "targetId": "f" }, { "id": "16", "sourceId": "f", "targetId": "e" } ] }
0
rapidsai_public_repos/node/modules/demo/deck/bezier
rapidsai_public_repos/node/modules/demo/deck/bezier/src/bezier-graph-layer.js
import {COORDINATE_SYSTEM, CompositeLayer} from '@deck.gl/core'; import {ScatterplotLayer} from '@deck.gl/layers'; import BezierCurveLayer from './bezier-curve-layer/bezier-curve-layer'; export default class BezierGraphLayer extends CompositeLayer { updateState({props, changeFlags}) { if (changeFlags.dataChanged) { this.setState(layoutGraph(props.data)); } } renderLayers() { const {nodes, edges} = this.state; return [ new BezierCurveLayer({ id: 'edges', data: edges, coordinateSystem: COORDINATE_SYSTEM.CARTESIAN, getSourcePosition: e => e.source, getTargetPosition: e => e.target, getControlPoint: e => e.controlPoint, getColor: e => [150, 150, 150, 255], strokeWidth: 5, // interaction: pickable: true, autoHighlight: true, highlightColor: [255, 0, 0, 255] }), new ScatterplotLayer({ id: 'nodes', data: nodes, coordinateSystem: COORDINATE_SYSTEM.CARTESIAN, getPosition: d => d.position, getRadius: 10, getFillColor: [0, 0, 150, 255], // interaction: pickable: true, autoHighlight: true, highlightColor: [255, 0, 0, 255] }) ]; } } /** * A helper function to compute the control point of a quadratic bezier curve * @param {number[]} source - the coordinates of source point, ex: [x, y, z] * @param {number[]} target - the coordinates of target point, ex: [x, y, z] * @param {number} direction - the direction of the curve, 1 or -1 * @param {number} offset - offset from the midpoint * @return {number[]} - the coordinates of the control point */ function computeControlPoint(source, target, direction, offset) { const midPoint = [(source[0] + target[0]) / 2, (source[1] + target[1]) / 2]; const dx = target[0] - source[0]; const dy = target[1] - source[1]; const normal = [dy, -dx]; const length = Math.sqrt(Math.pow(normal[0], 2.0) + Math.pow(normal[1], 2.0)); const normalized = [normal[0] / length, normal[1] / length]; return [ midPoint[0] + normalized[0] * offset * direction, midPoint[1] + normalized[1] * offset * direction ]; } /** * A helper function to generate a graph with curved edges. * @param {Object} graph - {nodes: [], edges: []} * expected input format: { * nodes: [{id: 'a', position: [0, -100]}, {id: 'b', position: [0, 100]}, ...], * edges: [{id: '1', sourceId: 'a',, targetId: 'b',}, ...] * } * @return {Object} Return new graph with curved edges. * expected output format: { * nodes: [{id: 'a', position: [0, -100]}, {id: 'b', position: [0, 100]}, ...], * edges: [{id: '1', sourceId: 'a', source: [0, -100], targetId: 'b', target: [0, 100], controlPoint: [50, 0]}, ...] } */ function layoutGraph(graph) { // create a map for referencing node position by node id. const nodePositionMap = graph.nodes.reduce((res, node) => { res[node.id] = node.position; return res; }, {}); // bucket edges between the same source/target node pairs. const nodePairs = graph.edges.reduce((res, edge) => { const nodes = [edge.sourceId, edge.targetId]; // sort the node ids to count the edges with the same pair // but different direction (a -> b or b -> a) const pairId = nodes.sort().toString(); // push this edge into the bucket if (!res[pairId]) { res[pairId] = [edge]; } else { res[pairId].push(edge); } return res; }, {}); // start to create curved edges const unitOffset = 30; const layoutEdges = Object.keys(nodePairs).reduce((res, pairId) => { const edges = nodePairs[pairId]; const curved = edges.length > 1; // curve line is directional, pairId is a list of sorted node ids. const nodeIds = pairId.split(','); const curveSourceId = nodeIds[0]; const curveTargetId = nodeIds[1]; // generate new edges with layout information const newEdges = edges.map((e, idx) => { // curve direction (1 or -1) const direction = idx % 2 ? 1 : -1; // straight line if there's only one edge between this two nodes. const offset = curved ? (1 + Math.floor(idx / 2)) * unitOffset : 0; return { ...e, source: nodePositionMap[e.sourceId], target: nodePositionMap[e.targetId], controlPoint: computeControlPoint( nodePositionMap[curveSourceId], nodePositionMap[curveTargetId], direction, offset ) }; }); return res.concat(newEdges); }, []); return { nodes: graph.nodes, edges: layoutEdges }; }
0
rapidsai_public_repos/node/modules/demo/deck/bezier
rapidsai_public_repos/node/modules/demo/deck/bezier/src/app.jsx
import { OrthographicView } from '@deck.gl/core'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { Component } from 'react'; import * as ReactDOM from 'react-dom'; import BezierGraphLayer from './bezier-graph-layer'; import SAMPLE_GRAPH from './sample-graph.json'; const INITIAL_VIEW_STATE = { target: [0, 0, 0], zoom: 1 }; export default class App extends Component { render() { const { data = SAMPLE_GRAPH, ...props } = this.props; return ( <DeckGL width='100%' height='100%' initialViewState={INITIAL_VIEW_STATE} controller={true} views={new OrthographicView()} layers={[new BezierGraphLayer({ data })]} {...props} /> ); } } if (require.main === module) { ReactDOM.render(<App />, document.body.appendChild(document.createElement('div'))); }
0
rapidsai_public_repos/node/modules/demo/deck/bezier/src
rapidsai_public_repos/node/modules/demo/deck/bezier/src/bezier-curve-layer/bezier-curve-layer.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import {Layer, fp64LowPart, picking} from '@deck.gl/core'; import GL from '@luma.gl/constants'; import {Model, Geometry} from '@luma.gl/core'; import vs from './bezier-curve-layer-vertex.glsl'; import fs from './bezier-curve-layer-fragment.glsl'; const NUM_SEGMENTS = 40; const DEFAULT_COLOR = [0, 0, 0, 255]; const defaultProps = { strokeWidth: {type: 'number', min: 0, value: 1}, getSourcePosition: {type: 'accessor', value: x => x.sourcePosition}, getTargetPosition: {type: 'accessor', value: x => x.targetPosition}, getControlPoint: {type: 'accessor', value: x => x.controlPoint}, getColor: {type: 'accessor', value: DEFAULT_COLOR} }; export default class BezierCurveLayer extends Layer { getShaders() { return {vs, fs, modules: [picking]}; } initializeState() { const attributeManager = this.getAttributeManager(); /* eslint-disable max-len */ attributeManager.addInstanced({ instanceSourcePositions: { size: 3, transition: true, accessor: 'getSourcePosition' }, instanceTargetPositions: { size: 3, transition: true, accessor: 'getTargetPosition' }, instanceControlPoints: { size: 3, transition: false, accessor: 'getControlPoint' }, instanceColors: { size: 4, type: GL.UNSIGNED_BYTE, transition: true, accessor: 'getColor', defaultValue: [0, 0, 0, 255] } }); /* eslint-enable max-len */ } updateState({props, oldProps, changeFlags}) { super.updateState({props, oldProps, changeFlags}); if (changeFlags.extensionsChanged) { const {gl} = this.context; if (this.state.model) { this.state.model.delete(); } this.setState({model: this._getModel(gl)}); } } draw({uniforms}) { const {strokeWidth} = this.props; this.state.model.render( Object.assign({}, uniforms, { strokeWidth }) ); } _getModel(gl) { /* * (0, -1)-------------_(1, -1) * | _,-" | * o _,-" o * | _,-" | * (0, 1)"-------------(1, 1) */ let positions = []; for (let i = 0; i <= NUM_SEGMENTS; i++) { positions = positions.concat([i, -1, 0, i, 1, 0]); } const model = new Model( gl, Object.assign({}, this.getShaders(), { id: this.props.id, geometry: new Geometry({ drawMode: GL.TRIANGLE_STRIP, attributes: { positions: new Float32Array(positions) } }), isInstanced: true, shaderCache: this.context.shaderCache }) ); model.setUniforms({numSegments: NUM_SEGMENTS}); return model; } calculateInstanceSourceTargetPositions64xyLow(attribute) { const {data, getSourcePosition, getTargetPosition} = this.props; const {value, size} = attribute; let i = 0; data.forEach(object => { const sourcePosition = getSourcePosition(object); const targetPosition = getTargetPosition(object); value[i + 0] = fp64LowPart(sourcePosition[0]); value[i + 1] = fp64LowPart(sourcePosition[1]); value[i + 2] = fp64LowPart(targetPosition[0]); value[i + 3] = fp64LowPart(targetPosition[1]); i += size; }); } } BezierCurveLayer.layerName = 'BezierCurveLayer'; BezierCurveLayer.defaultProps = defaultProps;
0
rapidsai_public_repos/node/modules/demo/deck/bezier/src
rapidsai_public_repos/node/modules/demo/deck/bezier/src/bezier-curve-layer/bezier-curve-layer-vertex.glsl.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. export default `\ #version 410 #define SHADER_NAME bezier-curve-layer-vertex-shader attribute vec3 positions; attribute vec3 instanceSourcePositions; attribute vec3 instanceTargetPositions; attribute vec3 instanceControlPoints; attribute vec4 instanceColors; attribute vec3 instancePickingColors; uniform float numSegments; uniform float strokeWidth; uniform float opacity; varying vec4 vColor; // offset vector by strokeWidth pixels // offset_direction is -1 (left) or 1 (right) vec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction) { // normalized direction of the line vec2 dir_screenspace = normalize(line_clipspace * project_uViewportSize); // rotate by 90 degrees dir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x); vec2 offset_screenspace = dir_screenspace * offset_direction * strokeWidth / 2.0; vec2 offset_clipspace = project_pixel_size_to_clipspace(offset_screenspace).xy; return offset_clipspace; } float getSegmentRatio(float index) { return smoothstep(0.0, 1.0, index / numSegments); } vec4 computeBezierCurve(vec4 source, vec4 target, vec4 controlPoint, float segmentRatio) { float mt = 1.0 - segmentRatio; float mt2 = pow(mt, 2.0); float t2 = pow(segmentRatio, 2.0); // quadratic curve float a = mt2; float b = mt * segmentRatio * 2.0; float c = t2; // TODO: if depth is not needed remove z computaitons. vec4 ret = vec4( a * source.x + b * controlPoint.x + c * target.x, a * source.y + b * controlPoint.y + c * target.y, a * source.z + b * controlPoint.z + c * target.z, 1.0 ); return ret; } void main(void) { // Position vec3 sourcePos = project_position(instanceSourcePositions); vec3 targetPos = project_position(instanceTargetPositions); vec3 controlPointPos = project_position(instanceControlPoints); vec4 source = project_common_position_to_clipspace(vec4(sourcePos, 1.0)); vec4 target = project_common_position_to_clipspace(vec4(targetPos, 1.0)); vec4 controlPoint = project_common_position_to_clipspace(vec4(controlPointPos, 1.0)); // linear interpolation of source & target to pick right coord float segmentIndex = positions.x; float segmentRatio = getSegmentRatio(segmentIndex); vec4 p = computeBezierCurve(source, target, controlPoint, segmentRatio); // next point float indexDir = mix(-1.0, 1.0, step(segmentIndex, 0.0)); float nextSegmentRatio = getSegmentRatio(segmentIndex + indexDir); vec4 nextP = computeBezierCurve(source, target, controlPoint, nextSegmentRatio); // extrude float direction = float(positions.y); direction = mix(-1.0, 1.0, step(segmentIndex, 0.0)) * direction; vec2 offset = getExtrusionOffset(nextP.xy - p.xy, direction); gl_Position = p + vec4(offset, 0.0, 0.0); // Color vColor = vec4(instanceColors.rgb, instanceColors.a * opacity) / 255.; // Set color to be rendered to picking fbo (also used to check for selection highlight). picking_setPickingColor(instancePickingColors); } `;
0
rapidsai_public_repos/node/modules/demo/deck/bezier/src
rapidsai_public_repos/node/modules/demo/deck/bezier/src/bezier-curve-layer/README.md
# Bezier Curve Layer This layer renders qudratic bezier curves. Right now it accepts only one control point. import BezierCurveLayer from './bezier-curve-layer'; Inherits from all [Base Layer](/docs/layers/base-layer.md) properties. ##### `getSourcePosition` (Function, optional) - Default: `d => d.sourcePosition` Each point is defined as an array of three numbers: `[x, y, z]`. ##### `getTargetPosition` (Function, optional) - Default: `d => d.targetPosition` Each point is defined as an array of three numbers: `[x, y, z]`. ##### `getControlPoint` (Function, optional) - Default: `d => d.controlPoint` Each point is defined as an array of three numbers: `[x, y, z]`. ##### `getColor` (Function|Array, optional) - 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.
0
rapidsai_public_repos/node/modules/demo/deck/bezier/src
rapidsai_public_repos/node/modules/demo/deck/bezier/src/bezier-curve-layer/bezier-curve-layer-fragment.glsl.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. export default `\ #version 410 #define SHADER_NAME bezier-curve-layer-fragment-shader precision highp float; varying vec4 vColor; void main(void) { gl_FragColor = vColor; // use highlight color if this fragment belongs to the selected object. gl_FragColor = picking_filterHighlightColor(gl_FragColor); // use picking color if rendering to picking FBO. gl_FragColor = picking_filterPickingColor(gl_FragColor); } `;
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/interleaved-buffer/package.json
{ "private": true, "name": "@rapidsai/demo-deck-interleaved-buffer", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@luma.gl/constants": "8.5.16", "@luma.gl/core": "8.5.16", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1" }, "files": [ "src", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/interleaved-buffer/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Interleaved Buffer Demo', transparent: false }) => { const jsdom = new (require('@rapidsai/jsdom').RapidsJSDOM)({ glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); jsdom.window.evalFn(() => require(`./src/app.js`)); return jsdom; }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0