Debian Codegraph @

bqplot/js/src/ScatterGL.ts

raw
1 /* Copyright 2015 Bloomberg Finance L.P.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 import { Mark } from './Mark';
16 import * as d3 from 'd3';
17 import * as markers from './Markers';
18 import * as _ from 'underscore';
19 import { deepCopy } from './utils';
20 import { ScatterGLModel } from './ScatterGLModel';
21 import { Scale } from './Scale';
22 import * as THREE from 'three';
23
24 type TypedArray =
25 | Int8Array
26 | Uint8Array
27 | Int16Array
28 | Uint16Array
29 | Int32Array
30 | Uint32Array
31 | Uint8ClampedArray
32 | Float32Array
33 | Float64Array;
34
35 const bqSymbol = markers.symbol;
36
37 const to_float_array = function (value: any) {
38 if (value instanceof Float32Array) {
39 return value;
40 }
41 if (typeof value[Symbol.iterator] === 'function') {
42 const N = value.length;
43 const array32 = new Float32Array(N);
44 for (let i = 0; i < N; i++) {
45 array32[i] = value[i];
46 }
47 return array32;
48 }
49 return new Float32Array(value);
50 };
51
52 const color_to_array_rgba = function (color, default_color?) {
53 const color_name = color || default_color || [0, 0, 0, 0];
54 if (color_name == 'none') {
55 return [0, 0, 0, 0];
56 } else {
57 const color = new THREE.Color(color_name);
58 return [color.r, color.g, color.b, 1.0];
59 }
60 };
61
62 const create_colormap = function (scale) {
63 // convert the d3 color scale to a texture
64 const colors = scale ? scale.model.color_range : ['#ff0000', '#ff0000'];
65 const color_scale = d3
66 .scaleLinear()
67 .range(colors)
68 .domain(_.range(colors.length).map((i) => i / (colors.length - 1)));
69 const colormap_array = [];
70 const N = 256;
71 _.map(_.range(N), (i) => {
72 const index = i / (N - 1);
73 const rgb = d3.color(String(color_scale(index))).hex();
74 const rgb_str = String(rgb);
75 const rgb_arr = [
76 parseInt('0x' + rgb_str.substring(1, 3)),
77 parseInt('0x' + rgb_str.substring(3, 5)),
78 parseInt('0x' + rgb_str.substring(5, 7)),
79 ];
80 colormap_array.push(rgb_arr[0], rgb_arr[1], rgb_arr[2]);
81 });
82 const colormap_arr = new Uint8Array(colormap_array);
83 const colormap_texture = new THREE.DataTexture(
84 colormap_arr,
85 N,
86 1,
87 THREE.RGBFormat,
88 THREE.UnsignedByteType
89 );
90 colormap_texture.needsUpdate = true;
91
92 return colormap_texture;
93 };
94
95 class AttributeParameters {
96 constructor(
97 array: TypedArray,
98 item_size = 1,
99 mesh_per_attribute = 1,
100 normalized = false
101 ) {
102 this.array = array;
103 this.item_size = item_size;
104 this.mesh_per_attribute = mesh_per_attribute;
105 this.normalized = normalized;
106 }
107
108 array: TypedArray;
109 item_size: number;
110 mesh_per_attribute: number;
111 normalized: boolean;
112 }
113
114 class ColorAttributeParameters extends AttributeParameters {
115 constructor(
116 array: TypedArray,
117 item_size: number = 1,
118 mesh_per_attribute: number = 1,
119 normalized: boolean = false,
120 use_colormap: boolean = true
121 ) {
122 super(array, item_size, mesh_per_attribute, normalized);
123 this.use_colormap = use_colormap;
124 }
125
126 use_colormap: boolean;
127 }
128
129 class SelectionAttributeParameters extends AttributeParameters {
130 constructor(
131 array: TypedArray,
132 item_size: number = 1,
133 mesh_per_attribute: number = 1,
134 normalized: boolean = false,
135 use_selection: boolean = true
136 ) {
137 super(array, item_size, mesh_per_attribute, normalized);
138 this.use_selection = use_selection;
139 }
140
141 use_selection: boolean;
142 }
143
144 export class ScatterGL extends Mark {
145 async render() {
146 const base_render_promise = super.render();
147
148 this.transitions = [];
149 this.invalidated_pixel_position = true;
150
151 // only used for the legend
152 this.dot = bqSymbol().type(this.model.get('marker'));
153
154 // Create square geometry (two triangles) for markers
155 this.instanced_geometry = new THREE.InstancedBufferGeometry();
156
157 const vertices = new Float32Array([
158 -0.5, 0.5, 0, 0.5, 0.5, 0, -0.5, -0.5, 0, 0.5, -0.5, 0,
159 ]);
160 this.instanced_geometry.addAttribute(
161 'position',
162 new THREE.Float32BufferAttribute(vertices, 3)
163 );
164
165 const uv = new Float32Array([0, 1, 1, 1, 0, 0, 1, 0]);
166 this.instanced_geometry.addAttribute(
167 'uv',
168 new THREE.Float32BufferAttribute(uv, 2)
169 );
170
171 const indices = new Uint16Array([0, 2, 1, 2, 3, 1]);
172 this.instanced_geometry.index = new THREE.Uint16BufferAttribute(indices, 1);
173
174 // Create material for markers
175 this.scatter_material = new THREE.RawShaderMaterial({
176 uniforms: {
177 domain_x: { type: '2f', value: [0, 10] },
178 domain_y: { type: '2f', value: [-12, 12] },
179 domain_z: { type: '2f', value: [0, 1] },
180 domain_size: { type: '2f', value: [0, 1] },
181 domain_color: { type: '2f', value: [0, 1] },
182 domain_rotation: { type: '2f', value: [0, 180] },
183 domain_opacity: { type: '2f', value: [0, 1] },
184 range_x: { type: '2f', value: [0, 1] },
185 range_y: { type: '2f', value: [0, 1] },
186 range_z: { type: '2f', value: [0, 1] },
187 range_size: { type: '2f', value: [0, 1] },
188 range_rotation: { type: '2f', value: [0, Math.PI] },
189 range_opacity: { type: '2f', value: [0, 1] },
190 animation_time_x: { type: 'f', value: 1 },
191 animation_time_y: { type: 'f', value: 1 },
192 animation_time_z: { type: 'f', value: 1 },
193 animation_time_size: { type: 'f', value: 1 },
194 animation_time_color: { type: 'f', value: 1 },
195 animation_time_rotation: { type: 'f', value: 1 },
196 animation_time_opacity: { type: 'f', value: 1 },
197
198 has_selection: { type: 'b', value: false },
199 has_hover: { type: 'b', value: false },
200
201 has_selected_fill: { type: 'b', value: false },
202 has_selected_stroke: { type: 'b', value: false },
203 has_selected_opacity: { type: 'b', value: false },
204 has_unselected_fill: { type: 'b', value: false },
205 has_unselected_stroke: { type: 'b', value: false },
206 has_unselected_opacity: { type: 'b', value: false },
207
208 has_hovered_fill: { type: 'b', value: false },
209 has_hovered_stroke: { type: 'b', value: false },
210 has_hovered_opacity: { type: 'b', value: false },
211 has_unhovered_fill: { type: 'b', value: false },
212 has_unhovered_stroke: { type: 'b', value: false },
213 has_unhovered_opacity: { type: 'b', value: false },
214
215 selected_fill: { type: '4f', value: [1, 0, 0, 1.0] },
216 selected_stroke: { type: '4f', value: [1, 0, 0, 1.0] },
217 selected_opacity: { value: 1.0 },
218 unselected_fill: { type: '4f', value: [1, 0, 0, 1.0] },
219 unselected_stroke: { type: '4f', value: [1, 0, 0, 1.0] },
220 unselected_opacity: { value: 1.0 },
221 hovered_fill: { type: '4f', value: [0, 1, 0, 1.0] },
222 hovered_opacity: { value: 1.0 },
223 hovered_stroke: { type: '4f', value: [0, 1, 0, 1.0] },
224 unhovered_fill: { type: '4f', value: [0, 1, 0, 1.0] },
225 unhovered_stroke: { type: '4f', value: [0, 1, 0, 1.0] },
226 unhovered_opacity: { value: 1.0 },
227
228 default_stroke_color: { type: '4f', value: [0, 0, 0, 0] },
229
230 colormap: { type: 't', value: null },
231 fill: { type: 'b', value: true },
232 stroke_width: { type: 'f', value: 1.5 },
233 marker_scale: { type: 'f', value: 1.0 },
234 },
235 vertexShader: require('raw-loader!../shaders/scatter-vertex.glsl')
236 .default,
237 fragmentShader: require('raw-loader!../shaders/scatter-fragment.glsl')
238 .default,
239 transparent: true,
240 depthTest: false,
241 depthWrite: false,
242 // background reading for blending:
243 // https://limnu.com/webgl-blending-youre-probably-wrong/
244 blending: THREE.CustomBlending,
245
246 blendEquation: THREE.AddEquation,
247 blendSrc: THREE.OneFactor,
248 blendDst: THREE.OneMinusSrcAlphaFactor,
249
250 blendEquationAlpha: THREE.AddEquation,
251 blendSrcAlpha: THREE.OneFactor,
252 blendDstAlpha: THREE.OneMinusSrcAlphaFactor,
253 });
254
255 // Create mesh
256 this.mesh = new THREE.Mesh(this.instanced_geometry, this.scatter_material);
257
258 await base_render_promise;
259
260 this.camera = new THREE.OrthographicCamera(
261 -1 / 2,
262 1 / 2,
263 1 / 2,
264 -1 / 2,
265 -10000,
266 10000
267 );
268 this.camera.position.z = 10;
269 this.scene = new THREE.Scene();
270
271 const x_parameters = new AttributeParameters(
272 to_float_array(this.model.get('x'))
273 );
274 this.x = this.initialize_attribute('x', x_parameters);
275 this.x_previous = this.initialize_attribute('x_previous', x_parameters);
276
277 const y_parameters = new AttributeParameters(
278 to_float_array(this.model.get('y'))
279 );
280 this.y = this.initialize_attribute('y', y_parameters);
281 this.y_previous = this.initialize_attribute('y_previous', y_parameters);
282
283 this.markers_number = Math.min(this.x.array.length, this.y.array.length);
284 this.instanced_geometry.maxInstancedCount = this.markers_number;
285
286 const color_parameters = this.get_color_attribute_parameters();
287 this.color = this.initialize_attribute('color', color_parameters);
288 this.scatter_material.defines['USE_COLORMAP'] =
289 color_parameters.use_colormap;
290
291 const opacity_parameters = this.get_opacity_attribute_parameters();
292 this.opacity = this.initialize_attribute('opacity', opacity_parameters);
293 this.opacity_previous = this.initialize_attribute(
294 'opacity_previous',
295 opacity_parameters
296 );
297
298 const size_parameters = this.get_size_attribute_parameters();
299 this.size = this.initialize_attribute('size', size_parameters);
300 this.size_previous = this.initialize_attribute(
301 'size_previous',
302 size_parameters
303 );
304
305 const rotation_parameters = this.get_rotation_attribute_parameters();
306 this.rotation = this.initialize_attribute('rotation', rotation_parameters);
307 this.rotation_previous = this.initialize_attribute(
308 'rotation_previous',
309 rotation_parameters
310 );
311
312 const selected_parameters = this.get_selected_attribute_parameters();
313 this.selected = this.initialize_attribute('selected', selected_parameters);
314 this.scatter_material.uniforms['has_selection'].value =
315 selected_parameters.use_selection;
316
317 this.scatter_material.needsUpdate = true;
318
319 this.scene.add(this.mesh);
320
321 this.create_listeners();
322 this.compute_view_padding();
323 this.update_scene();
324 this.listenTo(this.parent, 'margin_updated', () => {
325 this.update_scene();
326 });
327 }
328
329 initialize_attribute(name: string, parameters: AttributeParameters) {
330 const attribute = new THREE.InstancedBufferAttribute(
331 parameters.array,
332 parameters.item_size,
333 parameters.mesh_per_attribute
334 );
335 attribute.normalized = parameters.normalized;
336 attribute.dynamic = true;
337 this.instanced_geometry.addAttribute(name, attribute);
338
339 return attribute;
340 }
341
342 get_color_attribute_parameters() {
343 if (this.model.get('color')) {
344 const color = this.model.get('color');
345
346 // TODO Use `default_color`?
347 let array: Float32Array;
348 if (color.length < this.markers_number) {
349 array = to_float_array(this.markers_number);
350 array.set(color);
351 } else {
352 array = to_float_array(color);
353 }
354
355 return new ColorAttributeParameters(array, 1, 1, true, true);
356 } else {
357 let colors = this.model.get('colors');
358
359 if (!colors) {
360 const color =
361 (this.model.get('unselected_style') || {})['fill'] || 'orange';
362 colors = [color];
363 }
364
365 let array: Float32Array;
366 let mesh_per_attribute: number;
367 if (colors.length == 1) {
368 const color = new THREE.Color(colors[0]);
369
370 array = to_float_array([color.r, color.g, color.b]);
371 mesh_per_attribute = this.markers_number;
372 } else {
373 array = to_float_array(this.markers_number * 3);
374 _.each(_.range(this.markers_number), (i) => {
375 const color = new THREE.Color(colors[i % colors.length]);
376 array[i * 3 + 0] = color.r;
377 array[i * 3 + 1] = color.g;
378 array[i * 3 + 2] = color.b;
379 });
380 mesh_per_attribute = 1;
381 }
382
383 return new ColorAttributeParameters(
384 array,
385 3,
386 mesh_per_attribute,
387 false,
388 false
389 );
390 }
391 }
392
393 get_opacity_attribute_parameters() {
394 let opacities = this.model.get('opacities') || [1];
395
396 if (opacities.length == 0) {
397 opacities = [1];
398 }
399
400 if (this.model.get('opacity')) {
401 const opacity = this.model.get('opacity');
402
403 let array: Float32Array;
404 if (opacity.length < this.markers_number) {
405 array = to_float_array(this.markers_number);
406 array.set(opacity);
407
408 _.each(_.range(this.markers_number - opacity.length), (i) => {
409 i = i + opacity.length;
410 array[i] = opacities[i % opacities.length];
411 });
412 } else {
413 array = to_float_array(opacity);
414 }
415
416 return new AttributeParameters(array, 1, 1);
417 } else {
418 let array: Float32Array;
419 let mesh_per_attribute: number;
420 if (opacities.length == 1) {
421 array = to_float_array(opacities);
422 mesh_per_attribute = this.markers_number;
423 } else {
424 array = to_float_array(this.markers_number);
425 mesh_per_attribute = 1;
426 _.each(_.range(this.markers_number), (i) => {
427 array[i] = opacities[i % opacities.length];
428 });
429 }
430
431 return new AttributeParameters(array, 1, mesh_per_attribute);
432 }
433 }
434
435 get_size_attribute_parameters() {
436 if (this.model.get('size')) {
437 // One size per marker
438 const size = this.model.get('size');
439
440 let array: Float32Array;
441 if (size.length < this.markers_number) {
442 array = to_float_array(this.markers_number);
443 array.fill(this.model.get('default_size'));
444 array.set(size);
445 } else {
446 array = to_float_array(size);
447 }
448
449 return new AttributeParameters(array, 1, 1);
450 } else {
451 // Same size for all the markers
452 return new AttributeParameters(
453 to_float_array([this.model.get('default_size')]),
454 1,
455 this.markers_number
456 );
457 }
458 }
459
460 get_rotation_attribute_parameters() {
461 if (this.model.get('rotation')) {
462 const rotation = this.model.get('rotation');
463
464 let array: Float32Array;
465 if (rotation.length < this.markers_number) {
466 array = to_float_array(this.markers_number);
467 array.set(rotation);
468 } else {
469 array = to_float_array(rotation);
470 }
471
472 return new AttributeParameters(array, 1, 1);
473 } else {
474 return new AttributeParameters(to_float_array(1), 1, this.markers_number);
475 }
476 }
477
478 get_selected_attribute_parameters() {
479 if (this.model.get('selected')) {
480 const selected = this.model.get('selected');
481 const array = to_float_array(this.markers_number);
482
483 for (let i = 0; i < selected.length; i++) {
484 if (selected[i] < array.length) {
485 array[selected[i]] = 1;
486 }
487 }
488
489 return new SelectionAttributeParameters(array, 1, 1, false, true);
490 } else {
491 return new SelectionAttributeParameters(
492 to_float_array(1),
493 1,
494 this.markers_number,
495 false,
496 false
497 );
498 }
499 }
500
501 update_scene() {
502 this.parent.update_gl();
503 }
504
505 render_gl() {
506 this.set_ranges();
507 const fig = this.parent;
508 const x_scale = this.scales.x ? this.scales.x : this.parent.scale_x;
509 const y_scale = this.scales.y ? this.scales.y : this.parent.scale_y;
510
511 const range_x = this.parent.padded_range('x', x_scale.model);
512 const range_y = this.parent.padded_range('y', y_scale.model);
513
514 _.each(['selected', 'hovered'], (style_type) => {
515 _.each(['stroke', 'fill', 'opacity'], (style_property) => {
516 this.scatter_material.uniforms[
517 `has_${style_type}_${style_property}`
518 ].value = Boolean(
519 this.model.get(`${style_type}_style`)[style_property]
520 );
521 this.scatter_material.uniforms[
522 `has_un${style_type}_${style_property}`
523 ].value = Boolean(
524 this.model.get(`un${style_type}_style`)[style_property]
525 );
526 if (_.contains(['opacity'], style_property)) {
527 this.scatter_material.uniforms[
528 `${style_type}_${style_property}`
529 ].value = this.model.get(`${style_type}_style`)[style_property];
530 this.scatter_material.uniforms[
531 `un${style_type}_${style_property}`
532 ].value = this.model.get(`un${style_type}_style`)[style_property];
533 } else {
534 this.scatter_material.uniforms[
535 `${style_type}_${style_property}`
536 ].value = color_to_array_rgba(
537 this.model.get(`${style_type}_style`)[style_property],
538 'green'
539 );
540 this.scatter_material.uniforms[
541 `un${style_type}_${style_property}`
542 ].value = color_to_array_rgba(
543 this.model.get(`un${style_type}_style`)[style_property],
544 'green'
545 );
546 }
547 });
548 });
549
550 this.camera.left = 0;
551 this.camera.right = fig.plotarea_width;
552 this.camera.bottom = 0;
553 this.camera.top = fig.plotarea_height;
554 this.camera.updateProjectionMatrix();
555
556 this.scatter_material.uniforms['range_x'].value = range_x;
557 this.scatter_material.uniforms['range_y'].value = [range_y[1], range_y[0]]; // flipped coordinates in WebGL
558 this.scatter_material.uniforms['domain_x'].value = x_scale.scale.domain();
559 this.scatter_material.uniforms['domain_y'].value = y_scale.scale.domain();
560
561 if (this.scales.size) {
562 this.scatter_material.uniforms['range_size'].value =
563 this.scales.size.scale.range();
564 this.scatter_material.uniforms['domain_size'].value =
565 this.scales.size.scale.domain();
566 } else {
567 const size = this.model.get('default_size');
568 this.scatter_material.uniforms['range_size'].value = [0, size];
569 this.scatter_material.uniforms['domain_size'].value = [0, size];
570 }
571
572 if (this.scales.rotation) {
573 this.scatter_material.uniforms['range_rotation'].value =
574 this.scales.rotation.scale.range();
575 this.scatter_material.uniforms['domain_rotation'].value =
576 this.scales.rotation.scale.domain();
577 }
578
579 if (this.scales.opacity) {
580 this.scatter_material.uniforms['range_opacity'].value =
581 this.scales.opacity.scale.range();
582 this.scatter_material.uniforms['domain_opacity'].value =
583 this.scales.opacity.scale.domain();
584 }
585
586 const renderer = fig.renderer;
587 renderer.render(this.scene, this.camera);
588
589 const transitions_todo = [];
590 for (let i = 0; i < this.transitions.length; i++) {
591 const t = this.transitions[i];
592 if (!t.is_done()) {
593 transitions_todo.push(t);
594 }
595 t.update();
596 }
597 this.transitions = transitions_todo;
598 if (this.transitions.length > 0) {
599 this.update_scene();
600 }
601 }
602
603 create_listeners() {
604 super.create_listeners();
605
606 this.listenTo(this.model, 'change:x', this.update_x);
607 this.listenTo(this.model, 'change:y', this.update_y);
608
609 this.listenTo(
610 this.model,
611 'change:color change:colors change:unselected_style',
612 this.update_color
613 );
614 this.listenTo(
615 this.model,
616 'change:opacity change:opacities',
617 this.update_opacity
618 );
619 this.listenTo(
620 this.model,
621 'change:size change:default_size',
622 this.update_size
623 );
624 this.listenTo(this.model, 'change:rotation', this.update_rotation);
625 this.listenTo(this.model, 'change:selected', this.update_selected);
626
627 this.listenTo(this.model, 'change:marker', this.update_marker);
628 this.update_marker();
629
630 this.listenTo(this.model, 'change:stroke', this.update_stroke);
631 this.update_stroke();
632
633 this.listenTo(this.model, 'change:stroke_width', this.update_stroke_width);
634 this.update_stroke_width();
635
636 const sync_visible = () => {
637 this.mesh.visible = this.model.get('visible');
638 this.update_scene();
639 };
640 this.listenTo(this.model, 'change:visible', sync_visible);
641 sync_visible();
642
643 const sync_fill = () => {
644 this.scatter_material.defines['FILL'] = this.model.get('fill') ? 1 : 0;
645 this.scatter_material.needsUpdate = true;
646 this.update_scene();
647 };
648 this.listenTo(this.model, 'change:fill', sync_fill);
649 sync_fill();
650
651 this.listenTo(this.model, 'change', this.update_legend);
652 }
653
654 update_attribute(
655 name: string,
656 value: THREE.InstancedBufferAttribute,
657 new_parameters: AttributeParameters
658 ) {
659 // Workaround, updating `meshPerAttribute` does not work in ThreeJS and can result in a buffer overflow
660 // so we need to re-initialize the attribute. Same for an array size increase.
661 if (value.meshPerAttribute != new_parameters.mesh_per_attribute) {
662 value = this.initialize_attribute(name, new_parameters);
663 } else if (value.array.length < new_parameters.array.length) {
664 value = this.initialize_attribute(name, new_parameters);
665 } else {
666 value.itemSize = new_parameters.item_size;
667 value.setArray(new_parameters.array);
668 }
669
670 value.needsUpdate = true;
671
672 return value;
673 }
674
675 update_attributes(
676 name: string,
677 value: THREE.InstancedBufferAttribute,
678 value_previous: THREE.InstancedBufferAttribute,
679 new_parameters: AttributeParameters,
680 animate: boolean = true,
681 after_animation: Function = () => {}
682 ) {
683 if (animate) {
684 // `value_previous.array` must have at least the same length as `value.array` in order for animation to work
685 if (
686 value.array.length < new_parameters.array.length &&
687 value.meshPerAttribute == new_parameters.mesh_per_attribute
688 ) {
689 const array = deepCopy(new_parameters.array);
690 // array.fill(default_value);
691 array.set(value.array);
692 value_previous = this.update_attribute(
693 name + '_previous',
694 value_previous,
695 new AttributeParameters(
696 array,
697 value.itemSize,
698 value.meshPerAttribute,
699 value.normalized
700 )
701 );
702 }
703 // meshPerAttribute changed but not the array size, it is very likely that the number of markers has changed, value_previous must
704 // have the right meshPerAttribute
705 else if (
706 value.array.length == new_parameters.array.length &&
707 value.meshPerAttribute != new_parameters.mesh_per_attribute
708 ) {
709 value_previous = this.update_attribute(
710 name + '_previous',
711 value_previous,
712 new AttributeParameters(
713 value.array,
714 value.itemSize,
715 new_parameters.mesh_per_attribute,
716 value.normalized
717 )
718 );
719 } else {
720 value_previous = this.update_attribute(
721 name + '_previous',
722 value_previous,
723 new AttributeParameters(
724 value.array,
725 value.itemSize,
726 value.meshPerAttribute,
727 value.normalized
728 )
729 );
730 }
731
732 value = this.update_attribute(name, value, new_parameters);
733
734 this.animate_attribute(name, after_animation);
735 } else {
736 value_previous = this.update_attribute(
737 name + '_previous',
738 value_previous,
739 new_parameters
740 );
741 value = this.update_attribute(name, value, new_parameters);
742 }
743
744 return [value, value_previous];
745 }
746
747 animate_attribute(name: string, after_animation: Function = () => {}) {
748 this.scatter_material.uniforms['animation_time_' + name]['value'] = 0;
749 const set = (value) => {
750 this.scatter_material.uniforms['animation_time_' + name]['value'] = value;
751 };
752 this.transition(set, after_animation, this);
753 }
754
755 update_x(rerender: boolean = true) {
756 const x_array = to_float_array(this.model.get('x'));
757
758 const new_markers_number = Math.min(x_array.length, this.y.array.length);
759
760 // If the `markers_number` changes
761 if (this.markers_number != new_markers_number) {
762 this.update_markers_number(new_markers_number);
763 }
764
765 [this.x, this.x_previous] = this.update_attributes(
766 'x',
767 this.x,
768 this.x_previous,
769 new AttributeParameters(x_array, 1, 1)
770 );
771
772 if (rerender) {
773 this.update_scene();
774 }
775 }
776
777 update_y(rerender: boolean = true) {
778 const y_array = to_float_array(this.model.get('y'));
779
780 const new_markers_number = Math.min(this.x.array.length, y_array.length);
781
782 // If the `markers_number` changes
783 if (this.markers_number != new_markers_number) {
784 this.update_markers_number(new_markers_number);
785 }
786
787 [this.y, this.y_previous] = this.update_attributes(
788 'y',
789 this.y,
790 this.y_previous,
791 new AttributeParameters(y_array, 1, 1)
792 );
793
794 if (rerender) {
795 this.update_scene();
796 }
797 }
798
799 update_markers_number(n: number) {
800 const old_markers_number = this.markers_number;
801
802 this.markers_number = n;
803 this.instanced_geometry.maxInstancedCount = n;
804
805 // Increasing the number of markers, we need to update buffer sizes in
806 // order to prevent buffer overflows. We assume here that
807 // `update_markers_number` is called from `update_x` or `update_y` hence they
808 // are already correctly sized
809 // If the number of markers has decreased, no need to change the buffer sizes
810 if (this.markers_number > old_markers_number) {
811 this.update_color(false);
812 this.update_opacity(false);
813 this.update_size(false);
814 this.update_rotation(false);
815 this.update_selected(false);
816 }
817 }
818
819 update_color(rerender: boolean = true) {
820 const color_parameters = this.get_color_attribute_parameters();
821 this.color = this.update_attribute('color', this.color, color_parameters);
822 this.color.normalized = color_parameters.normalized;
823 this.scatter_material.defines['USE_COLORMAP'] =
824 color_parameters.use_colormap;
825
826 this.scatter_material.needsUpdate = true;
827
828 if (rerender) {
829 this.update_scene();
830 }
831 }
832
833 update_opacity(rerender: boolean = true) {
834 const opacity_parameters = this.get_opacity_attribute_parameters();
835 [this.opacity, this.opacity_previous] = this.update_attributes(
836 'opacity',
837 this.opacity,
838 this.opacity_previous,
839 opacity_parameters
840 );
841
842 if (rerender) {
843 this.update_scene();
844 }
845 }
846
847 update_size(rerender: boolean = true) {
848 const size_parameters = this.get_size_attribute_parameters();
849 [this.size, this.size_previous] = this.update_attributes(
850 'size',
851 this.size,
852 this.size_previous,
853 size_parameters
854 );
855
856 if (rerender) {
857 this.update_scene();
858 }
859 }
860
861 update_rotation(rerender: boolean = true) {
862 const rotation_parameters = this.get_rotation_attribute_parameters();
863 [this.rotation, this.rotation_previous] = this.update_attributes(
864 'rotation',
865 this.rotation,
866 this.rotation_previous,
867 rotation_parameters
868 );
869
870 if (rerender) {
871 this.update_scene();
872 }
873 }
874
875 update_selected(rerender: boolean = true) {
876 const selected_parameters = this.get_selected_attribute_parameters();
877 this.selected = this.update_attribute(
878 'selected',
879 this.selected,
880 selected_parameters
881 );
882 this.scatter_material.uniforms['has_selection'].value =
883 selected_parameters.use_selection;
884
885 if (rerender) {
886 this.update_scene();
887 }
888 }
889
890 update_marker() {
891 const FAST_CIRCLE = 1;
892 const FAST_SQUARE = 2;
893 const FAST_ARROW = 3;
894 const FAST_CROSS = 4;
895 const FAST_TRIANGLE_UP = 5;
896 const FAST_TRIANGLE_DOWN = 6;
897
898 const marker = this.model.get('marker');
899 this.dot.type(marker);
900
901 if (marker === 'circle') {
902 // same as in ./Markers.js
903 this.scatter_material.uniforms.marker_scale.value =
904 1 / Math.sqrt(Math.PI);
905 this.scatter_material.defines['FAST_DRAW'] = FAST_CIRCLE;
906 }
907 if (marker === 'square') {
908 this.scatter_material.uniforms.marker_scale.value = 1 / 2;
909 this.scatter_material.defines['FAST_DRAW'] = FAST_SQUARE;
910 }
911 if (marker === 'arrow') {
912 this.scatter_material.uniforms.marker_scale.value = 2;
913 this.scatter_material.defines['FAST_DRAW'] = FAST_ARROW;
914 }
915 if (marker === 'cross') {
916 this.scatter_material.uniforms.marker_scale.value =
917 3 / (2 * Math.sqrt(5));
918 this.scatter_material.defines['FAST_DRAW'] = FAST_CROSS;
919 }
920 if (marker === 'triangle-up') {
921 this.scatter_material.uniforms.marker_scale.value = 2;
922 this.scatter_material.defines['FAST_DRAW'] = FAST_TRIANGLE_UP;
923 }
924 if (marker === 'triangle-down') {
925 this.scatter_material.uniforms.marker_scale.value = 2;
926 this.scatter_material.defines['FAST_DRAW'] = FAST_TRIANGLE_DOWN;
927 }
928
929 this.scatter_material.needsUpdate = true;
930 this.update_scene();
931 }
932
933 update_stroke() {
934 const stroke = this.model.get('stroke');
935
936 if (stroke) {
937 this.scatter_material.uniforms.default_stroke_color.value =
938 color_to_array_rgba(stroke);
939 this.scatter_material.defines['HAS_DEFAULT_STROKE_COLOR'] = true;
940 } else {
941 this.scatter_material.defines['HAS_DEFAULT_STROKE_COLOR'] = false;
942 }
943
944 this.scatter_material.needsUpdate = true;
945 this.update_scene();
946 }
947
948 update_stroke_width() {
949 this.scatter_material.uniforms.stroke_width.value =
950 this.model.get('stroke_width');
951 this.update_scene();
952 }
953
954 update_color_map() {
955 this.scatter_material.uniforms['colormap'].value = create_colormap(
956 this.scales.color
957 );
958
959 if (this.scales.color) {
960 const color = this.model.get('color');
961 if (color) {
962 let min;
963 let max;
964 if (this.scales.color.model.min !== null) {
965 min = this.scales.color.model.min;
966 } else {
967 min = Math.min(...color);
968 }
969 if (this.scales.color.model.max !== null) {
970 max = this.scales.color.model.max;
971 } else {
972 max = Math.max(...color);
973 }
974 this.scatter_material.uniforms['domain_color'].value = [min, max];
975 } else {
976 if (
977 this.scales.color.model.min !== null &&
978 this.scales.color.model.max !== null
979 ) {
980 this.scatter_material.uniforms['domain_color'].value = [
981 this.scales.color.model.min,
982 this.scales.color.model.max,
983 ];
984 } else {
985 console.warn(
986 'no color set, and color scale does not have a min or max'
987 );
988 }
989 }
990 }
991
992 this.update_scene();
993 }
994
995 update_position(animate?) {
996 this.update_scene();
997 this.invalidate_pixel_position();
998 }
999
1000 // we want to compute the pixels coordinates 'lazily', since it's quite expensive for 10^6 points
1001 invalidate_pixel_position() {
1002 this.invalidated_pixel_position = true;
1003 }
1004
1005 ensure_pixel_position() {
1006 if (this.invalidated_pixel_position) {
1007 this.update_pixel_position();
1008 }
1009 }
1010
1011 update_pixel_position(animate?) {
1012 const x_scale = this.scales.x,
1013 y_scale = this.scales.y;
1014
1015 const x_data = this.model.get('x');
1016 const y_data = this.model.get('y');
1017 const N = Math.min(x_data.length, y_data.length);
1018 // this.pixel_coords = _.map(_.range(N), (i) => {
1019 // return [x_scale.scale(x_data[i]) + x_scale.offset,
1020 // y_scale.scale(y_data[i]) + y_scale.offset];
1021 // });
1022 this.pixel_x = new Float64Array(N);
1023 this.pixel_y = new Float64Array(N);
1024 for (let i = 0; i < N; i++) {
1025 this.pixel_x[i] = x_scale.scale(x_data[i]) + x_scale.offset;
1026 this.pixel_y[i] = y_scale.scale(y_data[i]) + y_scale.offset;
1027 }
1028 this.invalidated_pixel_position = false;
1029 }
1030
1031 selector_changed(point_selector, rect_selector) {
1032 if (!this.trottled_selector_changed) {
1033 this.trottled_selector_changed = _.throttle(
1034 this._real_selector_changed,
1035 50,
1036 { leading: false }
1037 );
1038 }
1039 this.trottled_selector_changed(point_selector, rect_selector);
1040 }
1041
1042 _real_selector_changed(point_selector, rect_selector) {
1043 // not sure why selection isn't working yet
1044 this.ensure_pixel_position();
1045 if (point_selector === undefined) {
1046 this.model.set('selected', null);
1047 this.touch();
1048 return [];
1049 }
1050 const selection_mask = point_selector(this.pixel_x, this.pixel_y);
1051 let selected = new Uint32Array(selection_mask.length);
1052 let count = 0;
1053 const N = selection_mask.length;
1054 for (let i = 0; i < N; i++) {
1055 if (selection_mask[i]) {
1056 selected[count++] = i;
1057 }
1058 }
1059 selected = selected.slice(0, count);
1060 this.model.set('selected', selected);
1061 this.touch();
1062 }
1063
1064 set_positional_scales() {
1065 this.x_scale = this.scales.x;
1066 this.y_scale = this.scales.y;
1067 // If no scale for "x" or "y" is specified, figure scales are used.
1068 if (!this.x_scale) {
1069 this.x_scale = this.parent.scale_x;
1070 }
1071 if (!this.y_scale) {
1072 this.y_scale = this.parent.scale_y;
1073 }
1074
1075 // TODO Support ordinal scales?
1076 const scaleTypeMap = {
1077 // Linear scales
1078 date: 1,
1079 linear: 1,
1080 // Log scales
1081 log: 2,
1082 };
1083 this.scatter_material.defines[`SCALE_TYPE_x`] =
1084 scaleTypeMap[this.x_scale.model.type];
1085 this.scatter_material.defines[`SCALE_TYPE_y`] =
1086 scaleTypeMap[this.y_scale.model.type];
1087 this.scatter_material.needsUpdate = true;
1088
1089 this.listenTo(this.x_scale, 'domain_changed', function () {
1090 if (!this.model.dirty) {
1091 const animate = true;
1092 this.update_position(animate);
1093 }
1094 });
1095 this.listenTo(this.y_scale, 'domain_changed', function () {
1096 if (!this.model.dirty) {
1097 const animate = true;
1098 this.update_position(animate);
1099 }
1100 });
1101 this.update_scene();
1102 }
1103
1104 initialize_additional_scales() {
1105 const color_scale = this.scales.color;
1106 const size_scale = this.scales.size;
1107 const opacity_scale = this.scales.opacity;
1108 const rotation_scale = this.scales.rotation;
1109 // the following handlers are for changes in data that does not
1110 // impact the position of the elements
1111 if (color_scale) {
1112 this.listenTo(color_scale, 'all', this.update_color_map);
1113 this.listenTo(this.model, 'change:color', this.update_color_map);
1114 this.update_color_map();
1115 }
1116 if (size_scale) {
1117 this.listenTo(size_scale, 'domain_changed', () => {
1118 this.update_scene();
1119 });
1120 }
1121 if (opacity_scale) {
1122 this.listenTo(opacity_scale, 'domain_changed', () => {
1123 this.update_scene();
1124 });
1125 }
1126 if (rotation_scale) {
1127 this.listenTo(rotation_scale, 'domain_changed', () => {
1128 this.update_scene();
1129 });
1130 }
1131 }
1132
1133 set_ranges() {
1134 const x_scale = this.scales.x,
1135 y_scale = this.scales.y,
1136 size_scale = this.scales.size,
1137 opacity_scale = this.scales.opacity,
1138 skew_scale = this.scales.skew,
1139 rotation_scale = this.scales.rotation;
1140 if (x_scale) {
1141 x_scale.set_range(this.parent.padded_range('x', x_scale.model));
1142 }
1143 if (y_scale) {
1144 y_scale.set_range(this.parent.padded_range('y', y_scale.model));
1145 }
1146 if (size_scale) {
1147 size_scale.set_range([0, this.model.get('default_size')]);
1148 }
1149 if (opacity_scale) {
1150 opacity_scale.set_range([0.2, 1]);
1151 }
1152 if (skew_scale) {
1153 skew_scale.set_range([0, 1]);
1154 }
1155 if (rotation_scale) {
1156 rotation_scale.set_range([0, Math.PI]); // TODO: this mirrors the 180 from the normal scatter, but why not 360?
1157 }
1158 }
1159
1160 transition(f, on_done, context) {
1161 // this is a copy from ipyvolume, maybe better to use tween, and do the rerendering
1162 // at the figure level (say if multiple scatter's want to rerender)
1163 const that = this;
1164 const Transition = function () {
1165 //this.objects = []
1166 this.time_start = new Date().getTime();
1167 this.duration = that.parent.model.get('animation_duration');
1168 this.cancelled = false;
1169 this.called_on_done = false;
1170 this.set = function (obj) {
1171 this.objects.push(obj);
1172 };
1173 this.is_done = function () {
1174 const dt = new Date().getTime() - this.time_start;
1175 return dt >= this.duration || this.cancelled;
1176 };
1177 (this.cancel = function () {
1178 this.cancelled = true;
1179 }),
1180 (this.update = function () {
1181 if (this.cancelled) {
1182 return;
1183 }
1184 const dt = (new Date().getTime() - this.time_start) / this.duration;
1185
1186 const u = Math.min(1, dt);
1187 f.apply(context, [u]);
1188 if (dt >= 1 && !this.called_on_done) {
1189 this.called_on_done = true;
1190 on_done.apply(context);
1191 }
1192 that.update_scene();
1193 });
1194 if (!this.duration) {
1195 f.apply(context, [1]);
1196 on_done.apply(context);
1197 that.update_scene();
1198 } else {
1199 that.transitions.push(this);
1200 }
1201 };
1202 return new Transition();
1203 }
1204
1205 draw_legend(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) {
1206 this.legend_el = elem.selectAll('.legend' + this.uuid).data([{}]);
1207 const colors = this.model.get('colors'),
1208 len = colors.length;
1209
1210 const that = this;
1211 const rect_dim = inter_y_disp * 0.8;
1212 const el_added = this.legend_el
1213 .enter()
1214 .append('g')
1215 .attr('class', 'legend' + this.uuid)
1216 .attr('transform', (d, i) => {
1217 return 'translate(0, ' + (i * inter_y_disp + y_disp) + ')';
1218 });
1219
1220 this.draw_legend_elements(el_added, rect_dim);
1221
1222 this.legend_el
1223 .append('text')
1224 .attr('class', 'legendtext')
1225 .attr('x', rect_dim * 1.2)
1226 .attr('y', rect_dim / 2)
1227 .attr('dy', '0.35em')
1228 .text((d, i) => {
1229 return that.model.get('labels')[i];
1230 })
1231 .style('fill', (d, i) => {
1232 return colors[i % len];
1233 });
1234
1235 const max_length = d3.max(this.model.get('labels'), (d: any[]) => {
1236 return d.length;
1237 });
1238
1239 this.legend_el.exit().remove();
1240 return [1, max_length];
1241 }
1242
1243 draw_legend_elements(elements_added, rect_dim) {
1244 const colors = this.model.get('colors'),
1245 stroke = this.model.get('stroke'),
1246 fill = this.model.get('fill');
1247
1248 elements_added
1249 .append('path')
1250 .attr('transform', (d, i) => {
1251 return 'translate( ' + rect_dim / 2 + ', ' + rect_dim / 2 + ')';
1252 })
1253 .attr('d', this.dot.size(64))
1254 .style('fill', fill ? colors[0] : 'none')
1255 .style('stroke', stroke ? stroke : colors[0]);
1256 }
1257
1258 update_legend() {
1259 if (this.legend_el) {
1260 const colors = this.model.get('colors'),
1261 stroke = this.model.get('stroke'),
1262 fill = this.model.get('fill');
1263 this.legend_el
1264 .select('path')
1265 .style('fill', fill ? colors[0] : 'none')
1266 .style('stroke', stroke ? stroke : colors[0]);
1267 this.legend_el.select('text').style('fill', fill ? colors[0] : 'none');
1268 if (this.legend_el) {
1269 this.legend_el
1270 .select('path')
1271 .attr('d', this.dot.type(this.model.get('marker')));
1272 }
1273 }
1274 }
1275
1276 relayout() {
1277 this.set_ranges();
1278 this.update_position();
1279 }
1280
1281 compute_view_padding() {
1282 //This function computes the padding along the x and y directions.
1283 //The value is in pixels.
1284 const xPadding = Math.sqrt(this.model.get('default_size')) / 2 + 1.0;
1285
1286 if (xPadding !== this.xPadding || xPadding !== this.yPadding) {
1287 this.xPadding = xPadding;
1288 this.yPadding = xPadding;
1289 this.trigger('mark_padding_updated');
1290 }
1291 }
1292
1293 draw(animate?) {}
1294 clear_style(style_dict, indices?, elements?) {}
1295 set_default_style(indices, elements?) {}
1296 set_style_on_elements(style, indices, elements?) {}
1297
1298 transitions: any[];
1299 x_scale: Scale;
1300 y_scale: Scale;
1301 pixel_x: Float64Array;
1302 pixel_y: Float64Array;
1303 trottled_selector_changed: any;
1304 invalidated_pixel_position: boolean;
1305 camera: THREE.OrthographicCamera;
1306 scene: THREE.Scene;
1307 instanced_geometry: THREE.InstancedBufferGeometry;
1308 scatter_material: THREE.RawShaderMaterial;
1309 mesh: THREE.Mesh;
1310
1311 markers_number: number;
1312
1313 x: THREE.InstancedBufferAttribute;
1314 x_previous: THREE.InstancedBufferAttribute;
1315
1316 y: THREE.InstancedBufferAttribute;
1317 y_previous: THREE.InstancedBufferAttribute;
1318
1319 color: THREE.InstancedBufferAttribute;
1320
1321 size: THREE.InstancedBufferAttribute;
1322 size_previous: THREE.InstancedBufferAttribute;
1323
1324 opacity: THREE.InstancedBufferAttribute;
1325 opacity_previous: THREE.InstancedBufferAttribute;
1326
1327 rotation: THREE.InstancedBufferAttribute;
1328 rotation_previous: THREE.InstancedBufferAttribute;
1329
1330 selected: THREE.InstancedBufferAttribute;
1331
1332 legend_el: d3.Selection<any, any, any, any>;
1333 dot: any;
1334
1335 model: ScatterGLModel;
1336 }