Compare commits

...

4 Commits

Author SHA1 Message Date
dsehnal
966bc14c67 5.0.0-dev.11 2025-08-31 09:51:54 +02:00
David Sehnal
f752b7e155 MVS: Color map interpolation & canvas backgrounds (#1636)
* MVS: Color map interpolation

* print validation errors to plugin log

* fixes

* background postprocessing

* fix resetCanvasProps

* fix link

* add example
2025-08-31 09:36:50 +02:00
Gianluca Tomasello
255b8b9ac3 Fix renderer transparency check (#1635)
* Fix renderer transparency check

* Fading transparent outlines

* improvements
2025-08-29 17:59:26 +02:00
Victoria Doshchenko
42d969bbeb MVS: example story improvements (#1632)
* add intro scene

* fixes

* add author name
2025-08-26 18:55:34 +02:00
19 changed files with 356 additions and 132 deletions

View File

@@ -24,7 +24,7 @@ Note that since we don't clearly distinguish between a public and private interf
- `representation` node: support custom property `molstar_representation_params`
- Add `backbone` and `line` representation types
- `primitives` node: support custom property `molstar_mesh/label/line_params`
- `canvas` node: support custom property `molstar_postprocessing` with the ability to customize outline, depth of field, bloom, shadow, occlusion (SSAO), and fog
- `canvas` node: support custom property `molstar_postprocessing` with the ability to customize outline, depth of field, bloom, shadow, occlusion (SSAO), fog, and background
- `clip` node support for structure and volume representations
- `grid_slice` representation support for volumes
- Support tethers and background for primitive labels
@@ -44,6 +44,7 @@ Note that since we don't clearly distinguish between a public and private interf
- Support loading trajectory coordinates from separate nodes
- Trigger markdown commands from primitives using `molstar_markdown_commands` custom extensions
- Support `molstar_on_load_markdown_commands` custom state on the `root` node
- Print tree validation errors to plugin log
- Added new color schemes, synchronized with D3.js ('inferno', 'magma', 'turbo', 'rainbow', 'sinebow', 'warm', 'cool', 'cubehelix-default', 'category-10', 'observable-10', 'tableau-10')
- Snapshot Markdown improvements
- Add `MarkdownExtensionManager` (`PluginContext.managers.markdownExtensions`)
@@ -100,6 +101,7 @@ Note that since we don't clearly distinguish between a public and private interf
- Add plugin config item ShowReset (shows/hides "Reset Zoom" button)
- Fix transform params not being normalized when used together with param hash version
- Replace `immer` with `mutative`
- Fix renderer transparency check
## [v4.18.0] - 2025-06-08
- MolViewSpec extension:

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "molstar",
"version": "5.0.0-dev.10",
"version": "5.0.0-dev.11",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "molstar",
"version": "5.0.0-dev.10",
"version": "5.0.0-dev.11",
"license": "MIT",
"dependencies": {
"@types/argparse": "^2.0.17",

View File

@@ -1,6 +1,6 @@
{
"name": "molstar",
"version": "5.0.0-dev.10",
"version": "5.0.0-dev.11",
"description": "A comprehensive macromolecular library.",
"homepage": "https://github.com/molstar/molstar#readme",
"repository": {
@@ -122,7 +122,8 @@
"Lukáš Polák <admin@lukaspolak.cz>",
"Chetan Mishra <chetan.s115@gmail.com>",
"Zach Charlop-Powers <zach.charlop.powers@gmail.com>",
"Kim Juho <juho_kim@outlook.com>"
"Kim Juho <juho_kim@outlook.com>",
"Victoria Doshchenko <doshchenko.victoria@gmail.com>"
],
"license": "MIT",
"devDependencies": {

View File

@@ -111,12 +111,28 @@ A story showcasing MolViewSpec animation capabilities.
const builder = createMVSBuilder();
const _1cbs = structure(builder, '1cbs');
const [poly,] = polymer(_1cbs, { color: Colors['1cbs'] });
const [poly, repr] = polymer(_1cbs, { color: Colors['1cbs'] });
repr.colorFromSource({
ref: 'residue_colors',
schema: 'residue',
category_name: 'atom_site',
field_name: 'label_comp_id',
palette: {
kind: 'categorical',
missing_color: 'white',
colors: {
ALA: 'red',
ILE: 'white',
LYS: 'white',
}
}
});
const surface = poly.representation({
type: 'surface',
surface_type: 'gaussian',
});
}).opacity({ opacity: 0.33 });
_1cbs.component({ selector: 'ligand' })
.transform({
@@ -190,6 +206,20 @@ A story showcasing MolViewSpec animation capabilities.
end: Colors['ligand-docked'],
});
anim.interpolate({
kind: 'color',
target_ref: 'residue_colors',
duration_ms: 2000,
property: ['palette', 'colors'],
start: {
ALA: 'yellow',
},
end: {
ILE: 'blue',
LYS: 'purple',
},
});
return builder;
},
camera: {
@@ -311,10 +341,12 @@ function structure(builder: Root, id: string): MVSStructure {
.modelStructure();
}
function polymer(structure: MVSStructure, options: { color: ColorT }) {
function polymer(structure: MVSStructure, options?: { color?: ColorT }) {
const component = structure.component({ selector: { label_asym_id: 'A' } });
const reprensentation = component.representation({ type: 'cartoon' });
reprensentation.color({ color: options.color });
if (options?.color) {
reprensentation.color({ color: options.color });
}
return [component, reprensentation] as const;
}
@@ -332,6 +364,21 @@ export function buildStory(): MVSData_States {
molstar_postprocessing: {
enable_outline: true,
enable_ssao: true,
background: {
name: 'horizontalGradient',
params: {
topColor: 0x777777,
bottomColor: 0xffffff,
}
},
// Example with background image:
// background: {
// name: 'image',
// params: {
// // URL can also be filename in MVSX archive
// source: { name: 'url', params: 'URL' }
// }
// }
}
}
});

View File

@@ -3,6 +3,7 @@
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Ludovic Autin <autin@scripps.edu>
* @author Victoria Doshchenko <doshchenko.victoria@gmail.com>
*/
import { decodeColor } from '../../../extensions/mvs/helpers/utils';
@@ -84,15 +85,21 @@ const _Audio4 = audioPathBase + '/examples/audio/AudioMOM1_D.mp3';
const q = (expr: string, lang = 'pymol') =>
`!query=${encodeURIComponent(expr)}&lang=${lang}&action=highlight,focus`;
const description_intro = `
# Molecule of the Month: Myoglobin
const desc_intro = `
# Introduction
A story based on the orginal [first Molecule of the Month](https://pdb101.rcsb.org/motm/1) made by David Goodsell in January 2000.
🔊 *This story includes short audio commentaries to guide you through the structures.*
For the best experience, please keep your sound on or use headphones.
`;
const description_p0 = `
# Molecule of the Month: Myoglobin
Basic controls for the audio comments:
[Play](${encodeURIComponent(`!play-audio=${_Audio1}`)})
[Pause](!pause-audio)
[Stop](!stop-audio)
${createAudioControls(_Audio1)}
Myoglobin was the first protein to have its atomic structure determined, revealing how it stores oxygen in muscle cells.
@@ -161,9 +168,7 @@ const charged_residues = q(formatMolScript(query3), 'mol-script');
const description_p1 = `
# Myoglobin and Whales
Basic controls for the audio comments:
[Play](${encodeURIComponent(`!play-audio=${_Audio2}`)})
[Pause](!pause-audio)
[Stop](!stop-audio)
${createAudioControls(_Audio2)}
If you look at John Kendrew's PDB file, you'll notice that the myoglobin he used was taken
from sperm whale muscles. Whales and dolphin have a great need for myoglobin, so that they can
@@ -184,9 +189,7 @@ high concentrations.
const description_p2 = `
# Oxygen Bound to Myoglobin
Basic controls for the audio comments:
[Play](${encodeURIComponent(`!play-audio=${_Audio3}`)})
[Pause](!pause-audio)
[Stop](!stop-audio)
${createAudioControls(_Audio3)}
A later structure of myoglobin, PDB entry [1mbo](https://www.rcsb.org/structure/1mbo),
shows that [oxygen](${q('index 1276+1277')}) binds to
@@ -202,9 +205,7 @@ appear and disappear, allowing oxygen in and out.
const description_p3 = `
# Molecule of the Month: Myoglobin
Basic controls for the audio comments:
[Play](${encodeURIComponent(`!play-audio=${_Audio1}`)})
[Pause](!pause-audio)
[Stop](!stop-audio)
${createAudioControls(_Audio4)}
The atomic structure of myoglobin revealed many of the basic principles
of protein structure and stability. For instance, the structure showed
@@ -235,10 +236,67 @@ PDB entry [2jho](https://www.rcsb.org/structure/2jho) includes myoglobin poisone
`;
const Steps = [
{
header: 'Introduction',
key: 'first-slide',
description: desc_intro,
linger_duration_ms: 0,
state: (): Root => {
const builder = createMVSBuilder();
const _1mbn = build1mbn(builder, '1MBN');
builder.extendRootCustomState({
molstar_on_load_markdown_commands: {
'dispose-audio': _Audio1,
}
});
const anim = builder.animation(
{
custom: {
molstar_trackball: {
name: 'spin',
params: { speed: -0.05 },
}
}
}
);
const prims = _1mbn.struct.primitives({
ref: 'start-story',
label_opacity: 0,
label_background_color: 'grey',
snapshot_key: 'intro'
});
prims.label({
text: 'Start story',
position: [13.5, -4, 7.7],
label_size: 8
});
anim.interpolate({
kind: 'scalar',
target_ref: 'start-story',
duration_ms: 1000,
start_ms: 1,
property: 'label_opacity',
start: 0.0,
end: 1.0,
});
return builder;
},
camera: {
position: [13.5, 21.1, 73.1],
target: [13.5, 21.1, 7.7],
up: [0, 1, 0],
} satisfies MVSNodeParams<'camera'>,
},
{
header: 'Molecule of the Month: Myoglobin',
key: 'intro',
description: description_intro,
description: description_p0,
linger_duration_ms: 45000,
transition_duration_ms: 500,
state: (): Root => {
@@ -247,39 +305,10 @@ const Steps = [
builder.canvas({ custom: { molstar_postprocessing: { enable_outline: false } } });
const _1mbn = structure(builder, '1MBN');
_1mbn.component({ selector: 'ligand' })
.representation({ ref: 'ligand', type: 'ball_and_stick' })
.color({ color: 'orange' });
// FE and O should be spacefill
_1mbn.component({ selector: { auth_seq_id: 155, label_atom_id: 'F' } })
.representation({ type: 'spacefill' })
.color({ color: 'yellow' });
_1mbn.component({ selector: { auth_seq_id: 154 } })
.representation({ type: 'spacefill' })
.color({ color: 'blue' });
_1mbn.component({ selector: { auth_seq_id: 154 } })
.representation({ type: 'spacefill' })
.color({ color: 'blue' });
const chA = _1mbn.component({ selector: { label_asym_id: 'A' } });
chA.representation({ type: 'surface', surface_type: 'gaussian' })
.color({ color: '#ff0303' })
.opacity({ ref: 'surfopa', opacity: 0.0 });
chA.representation({ type: 'line' })
.color({ custom: { molstar_color_theme_name: 'element-symbol' } })
.opacity({ ref: 'lineopa', opacity: 0.0 });
chA.representation({ type: 'cartoon' })
.color({ custom: { molstar_color_theme_name: 'secondary-structure' } });
const _1mbn = build1mbn(builder, '1MBN');
// whale
_1mbn.component({ selector: { label_asym_id: 'A' } })
_1mbn.struct.component({ selector: { label_asym_id: 'A' } })
.representation({ type: 'spacefill', custom: { molstar_representation_params: { ignoreLight: true } } })
.colorFromSource({
schema: 'all_atomic',
@@ -296,29 +325,12 @@ const Steps = [
}
}).opacity({ ref: 'cpkopa1', opacity: 0.0 });
_1mbn.component({ selector: { auth_seq_id: 155 } })
_1mbn.struct.component({ selector: { auth_seq_id: 155 } })
.representation({ type: 'spacefill', custom: { molstar_representation_params: { ignoreLight: true } } })
.color({ custom: GColors2 }).opacity({ ref: 'cpkopa2', opacity: 0.0 });
const prims = _1mbn.primitives({
ref: 'prims',
label_opacity: 1,
label_background_color: 'grey',
custom: {
molstar_markdown_commands: {
// 'apply-snapshot': 'interlude',
'play-audio': _Audio1,
}
}
});
prims.label({
text: 'Start Comments',
position: [13.5, 45.1, 7.7],
label_size: 5
});
addNextButton(builder, 'whale', [13.5, 0, 7.7]);
addNextButton(builder, 'whale', [13.5, -4, 7.7]);
// doesnt work for first slide, but work afterward
builder.extendRootCustomState({
molstar_on_load_markdown_commands: {
'play-audio': _Audio1,
@@ -543,7 +555,7 @@ const Steps = [
start: 0.0,
end: 1.0,
});
addNextButton(builder, 'oxygen', [-18.9, 10, 7.3]);
addNextButton(builder, 'oxygen', [-18.9, -4, 7.3]);
anim.interpolate({
kind: 'scalar',
target_ref: 'next',
@@ -897,7 +909,7 @@ function addNextButton(builder: any, snapshotKey: string, position: [number, num
.label({
ref: 'next_label',
position: position,
text: 'Click me to go next',
text: 'Next Scene →',
label_color: 'white',
label_size: 5
});
@@ -955,4 +967,54 @@ export function buildStory(): MVSData_States {
timestamp: new Date().toISOString(),
}
};
}
function build1mbn(builder: any, pdbId: string) {
const struct = structure(builder, '1MBN');
struct.component({ selector: 'ligand' })
.representation({ ref: 'ligand', type: 'ball_and_stick' })
.color({ color: 'orange' });
// FE and O should be spacefill
struct.component({ selector: { auth_seq_id: 155, label_atom_id: 'FE' } })
.representation({ type: 'spacefill' })
.color({ color: 'yellow' });
struct.component({ selector: { auth_seq_id: 154 } })
.representation({ type: 'spacefill' })
.color({ color: 'blue' });
struct.component({ selector: { auth_seq_id: 154 } })
.representation({ type: 'spacefill' })
.color({ color: 'blue' });
const chA = struct.component({ selector: { label_asym_id: 'A' } });
chA.representation({ type: 'surface', surface_type: 'gaussian' })
.color({ color: '#ff0303' })
.opacity({ ref: 'surfopa', opacity: 0.0 });
chA.representation({ type: 'line' })
.color({ custom: { molstar_color_theme_name: 'element-symbol' } })
.opacity({ ref: 'lineopa', opacity: 0.0 });
chA.representation({ type: 'cartoon' })
.color({ custom: { molstar_color_theme_name: 'secondary-structure' } });
return {
struct,
refs: {
surfaceOpacity: 'surfopa',
lineOpacity: 'lineopa',
}
};
}
function createAudioControls(url: string) {
return `
[ **▶ Play** ](${encodeURIComponent(`!play-audio=${url}`)})
[ **⏸ Pause** ](!pause-audio)
[ **⏹ Stop** ](!stop-audio)
[ **Hide** ](!dispose-audio)
`;
}

View File

@@ -1 +1 @@
Find the MVS extension documentation [here](../../../docs/extensions/mvs/README.md).
Please refer to the standalone documentation [here](https://molstar.org/mol-view-spec-docs/).

View File

@@ -8,6 +8,7 @@
import { Camera } from '../../mol-canvas3d/camera';
import { CameraFogParams, Canvas3DParams, Canvas3DProps, DefaultCanvas3DParams } from '../../mol-canvas3d/canvas3d';
import { TrackballControlsParams } from '../../mol-canvas3d/controls/trackball';
import { BackgroundParams } from '../../mol-canvas3d/passes/background';
import { BloomParams } from '../../mol-canvas3d/passes/bloom';
import { DofParams } from '../../mol-canvas3d/passes/dof';
import { OutlineParams } from '../../mol-canvas3d/passes/outline';
@@ -21,6 +22,7 @@ import { PluginState } from '../../mol-plugin/state';
import { StateObjectSelector } from '../../mol-state';
import { fovAdjustedPosition } from '../../mol-util/camera';
import { ColorNames } from '../../mol-util/color/names';
import { deepClone } from '../../mol-util/object';
import { ParamDefinition } from '../../mol-util/param-definition';
import { decodeColor } from './helpers/utils';
import { MolstarLoadingContext } from './load';
@@ -132,6 +134,11 @@ function optionalParams(enable: boolean | undefined, values: any, params: ParamD
return fallback;
}
function normalizeBackground(variant: any, prev: any): any {
if (!variant) return prev;
return ParamDefinition.normalizeParams(BackgroundParams, { variant }, 'children');
}
/** Create a deep copy of `oldCanvasProps` with values modified according to a canvas node params. */
export function modifyCanvasProps(oldCanvasProps: Canvas3DProps, canvasNode: MolstarNode<'canvas'> | undefined, animationNode: MVSAnimationNode<'animation'> | undefined): Canvas3DProps {
const params = canvasNode?.params;
@@ -157,6 +164,8 @@ export function modifyCanvasProps(oldCanvasProps: Canvas3DProps, canvasNode: Mol
const bloom = molstar_postprocessing?.enable_bloom;
const bloomParams = molstar_postprocessing?.bloom_params;
const background = molstar_postprocessing?.background;
const trackballAnimation = animationNode?.custom?.molstar_trackball;
const trackballAnimationName = trackballAnimation?.name;
const trackballAnimationParams = trackballAnimation?.params ?? {};
@@ -170,6 +179,7 @@ export function modifyCanvasProps(oldCanvasProps: Canvas3DProps, canvasNode: Mol
occlusion: optionalParams(occlusion, occlusionParams, SsaoParams, oldCanvasProps.postprocessing.occlusion),
dof: optionalParams(dof, dofParams, DofParams, oldCanvasProps.postprocessing.dof),
bloom: optionalParams(bloom, bloomParams, BloomParams, oldCanvasProps.postprocessing.bloom),
background: normalizeBackground(background, oldCanvasProps.postprocessing.background),
},
cameraFog: optionalParams(fog, fogParams, CameraFogParams, oldCanvasProps.cameraFog),
renderer: {
@@ -200,13 +210,14 @@ export function resetCanvasProps(plugin: PluginContext) {
...old,
postprocessing: {
...old,
outline: DefaultCanvas3DParams.postprocessing.outline,
shadow: DefaultCanvas3DParams.postprocessing.shadow,
occlusion: DefaultCanvas3DParams.postprocessing.occlusion,
dof: DefaultCanvas3DParams.postprocessing.dof,
bloom: DefaultCanvas3DParams.postprocessing.bloom,
outline: deepClone(DefaultCanvas3DParams.postprocessing.outline),
shadow: deepClone(DefaultCanvas3DParams.postprocessing.shadow),
occlusion: deepClone(DefaultCanvas3DParams.postprocessing.occlusion),
dof: deepClone(DefaultCanvas3DParams.postprocessing.dof),
bloom: deepClone(DefaultCanvas3DParams.postprocessing.bloom),
background: deepClone(DefaultCanvas3DParams.postprocessing.background),
},
cameraFog: DefaultCanvas3DParams.cameraFog,
cameraFog: deepClone(DefaultCanvas3DParams.cameraFog),
trackball: {
...old?.trackball,
animate: { name: 'off', params: {} },

View File

@@ -12,6 +12,7 @@ import { EPSILON, Mat3, Mat4, Quat, Vec3 } from '../../../mol-math/linear-algebr
import { RuntimeContext } from '../../../mol-task';
import { deepEqual } from '../../../mol-util';
import { Color } from '../../../mol-util/color';
import { decodeColor } from '../../../mol-util/color/utils';
import { produce } from '../../../mol-util/produce';
import { makeContinuousPaletteCheckpoints, MVSContinuousPaletteProps, MVSDiscretePaletteProps } from '../components/annotation-color-theme';
import { palettePropsFromMVSPalette } from '../load-helpers';
@@ -88,6 +89,8 @@ const EasingFnMap: Record<MVSAnimationEasing, (t: number) => number> = {
interface InterpolationCacheEntry {
paletteFn?: (value: number) => Color,
startColor?: Color | Record<number | string, Color>,
endColor?: Color | Record<number | string, Color>,
rotation?: { axis: Vec3, angle: number, start: Quat, end: Quat },
}
@@ -203,22 +206,15 @@ function processScalarLike(transition: MVSAnimationNode<'interpolate'>, target:
if (transition.params.kind === 'transform_matrix') return;
if (previous && previous.params.kind === 'transform_matrix') return;
const startBase = transition.params.start ?? getPreviousScalarEnd(previous) ?? select(target, transition.params.property, offset);
const startValue = transition.params.start ?? getPreviousScalarEnd(previous) ?? select(target, transition.params.property, offset);
if (transition.params.kind === 'color' && !cacheEntry.paletteFn) {
cacheEntry.paletteFn = makePaletteFunction(transition, startBase, transition.params.end as ColorT | undefined);
cacheEntry.paletteFn = makePaletteFunction(transition);
}
const paletteFn = cacheEntry.paletteFn!;
const startValue: any = transition.params.kind === 'color'
? Color.toHexStyle(paletteFn(0))
: startBase;
const endValue: any = transition.params.kind === 'color'
? Color.toHexStyle(paletteFn(1))
: transition.params.end;
const endValue: any = transition.params.end;
if (time <= 0) return startValue;
else if (time >= 1 - EPSILON && !transition.params.alternate_direction) return endValue;
else if (time >= 1 - EPSILON && !transition.params.alternate_direction && transition.params.kind !== 'color') return endValue;
let t = clamp(time, 0, 1);
t = applyFrequency(t, transition.params.frequency ?? 1, !!transition.params.alternate_direction);
@@ -233,8 +229,13 @@ function processScalarLike(transition: MVSAnimationNode<'interpolate'>, target:
} else if (transition.params.kind === 'rotation_matrix') {
return interpolateRotation(startValue, endValue, t, transition.params.noise_magnitude ?? 0, cacheEntry);
} else if (transition.params.kind === 'color') {
const color = paletteFn(t);
return Color.toHexStyle(color);
if (cacheEntry.paletteFn) {
const color = cacheEntry.paletteFn(t);
return Color.toHexStyle(color);
}
const baseColors = typeof startValue === 'object' ? select(target, transition.params.property, offset) : undefined;
return interpolateColors(startValue, endValue, t, cacheEntry, baseColors);
}
}
@@ -441,6 +442,76 @@ function interpolateRotation(start: Mat3, end: Mat3 | undefined, t: number, nois
return Mat3.fromMat4(Mat3(), RotationState.temp);
}
function decodeColors(color: ColorT | Record<number | string, ColorT> | undefined, baseColors: Record<number | string, ColorT> | undefined) {
if (color === undefined || color === null) return undefined;
if (typeof color === 'object') {
const ret: Record<number | string, Color> = {};
if (baseColors) {
for (const key of Object.keys(baseColors)) {
const decoded = decodeColor(baseColors[key]);
if (decoded !== undefined) {
ret[key] = decoded;
}
}
}
for (const key of Object.keys(color)) {
const decoded = decodeColor(color[key]);
if (decoded !== undefined) {
ret[key] = decoded;
}
}
return ret;
}
return decodeColor(color);
}
function interpolateColors(start: ColorT | Record<number, ColorT>, end: ColorT | Record<number, ColorT> | undefined, time: number, cacheEntry: InterpolationCacheEntry, baseColors: Record<number, ColorT> | undefined) {
const t = clamp(time, 0, 1);
if (cacheEntry.paletteFn) {
const c = cacheEntry.paletteFn(t);
return Color.toHexStyle(c);
}
if (cacheEntry.startColor === undefined) {
cacheEntry.startColor = decodeColors(start, baseColors);
}
if (cacheEntry.endColor === undefined) {
cacheEntry.endColor = decodeColors(end, undefined);
}
const { startColor, endColor } = cacheEntry;
if (typeof startColor === 'object') {
if (typeof baseColors !== 'object') {
throw new Error('Cannot interpolate from scalar color to color mapping');
}
const ret = { ...baseColors as any, ...startColor as any };
if (typeof endColor === 'object') {
for (const key of Object.keys(endColor)) {
ret[key] = Color.toHexStyle(Color.interpolate(startColor[key], endColor[key], t));
}
} else if (typeof endColor === 'number') {
for (const key of Object.keys(startColor)) {
ret[key] = Color.toHexStyle(Color.interpolate(startColor[key], endColor, t));
}
}
return ret;
}
if (typeof endColor === 'object') {
throw new Error('Cannot interpolate from scalar color to color mapping');
}
if (typeof endColor === 'number' && typeof startColor === 'number') {
return Color.toHexStyle(Color.interpolate(startColor, endColor, t));
}
return start;
}
function select(params: any, path: string | (string | number)[], offset: number) {
if (typeof path === 'string') {
return params?.[path];
@@ -493,12 +564,10 @@ function makeNodeMap(tree: Tree, map: Map<string, (string | number)[]>, currentP
return map;
}
function makePaletteFunction(props: MVSAnimationNode<'interpolate'>, start: ColorT | undefined | null, end: ColorT | undefined | null): ((value: number) => Color) | undefined {
if (props.params.kind !== 'color') return undefined;
function makePaletteFunction(props: MVSAnimationNode<'interpolate'>): ((value: number) => Color) | undefined {
if (props.params.kind !== 'color' || !props.params.palette) return undefined;
const params = props.params.palette
? palettePropsFromMVSPalette(props.params.palette)
: palettePropsFromMVSPalette({ kind: 'continuous', colors: [start ?? 'black', end ?? start ?? 'black'] });
const params = palettePropsFromMVSPalette(props.params.palette);
if (params.name === 'discrete') return makePaletteFunctionDiscrete(params.params);
if (params.name === 'continuous') return makePaletteFunctionContinuous(params.params);
throw new Error(`NotImplementedError: makePaletteFunction for ${(props as any).name}`);

View File

@@ -33,7 +33,7 @@ import { NonCovalentInteractionsExtension } from './load-extensions/non-covalent
import { LoadingActions, LoadingExtension, loadTreeVirtual, UpdateTarget } from './load-generic';
import { AnnotationFromSourceKind, AnnotationFromUriKind, collectAnnotationReferences, collectAnnotationTooltips, collectInlineLabels, collectInlineTooltips, colorThemeForNode, componentFromXProps, componentPropsFromSelector, isPhantomComponent, labelFromXProps, makeNearestReprMap, prettyNameFromSelector, representationProps, structureProps, transformAndInstantiateStructure, transformAndInstantiateVolume, volumeColorThemeForNode, volumeRepresentationProps } from './load-helpers';
import { MVSData, MVSData_States, Snapshot, SnapshotMetadata } from './mvs-data';
import { MVSAnimationNode } from './tree/animation/animation-tree';
import { MVSAnimationNode, MVSAnimationSchema } from './tree/animation/animation-tree';
import { validateTree } from './tree/generic/tree-schema';
import { convertMvsToMolstar, mvsSanityCheck } from './tree/molstar/conversion';
import { MolstarNode, MolstarNodeParams, MolstarSubtree, MolstarTree, MolstarTreeSchema } from './tree/molstar/molstar-tree';
@@ -51,6 +51,7 @@ export interface MVSLoadOptions {
sanityChecks?: boolean,
/** Base for resolving relative URLs/URIs. May itself be a relative URL (relative to the window URL). */
sourceUrl?: string,
doNotReportErrors?: boolean
}
@@ -78,10 +79,13 @@ async function _loadMVS(ctx: RuntimeContext, plugin: PluginContext, data: MVSDat
for (let i = 0; i < multiData.snapshots.length; i++) {
const snapshot = multiData.snapshots[i];
const previousSnapshot = i > 0 ? multiData.snapshots[i - 1] : multiData.snapshots[multiData.snapshots.length - 1];
validateTree(MVSTreeSchema, snapshot.root, 'MVS');
validateTree(MVSTreeSchema, snapshot.root, 'MVS', plugin);
if (snapshot.animation) {
validateTree(MVSAnimationSchema, snapshot.animation, 'Animation', plugin);
}
if (options.sanityChecks) mvsSanityCheck(snapshot.root);
const molstarTree = convertMvsToMolstar(snapshot.root, options.sourceUrl);
validateTree(MolstarTreeSchema, molstarTree, 'Converted Molstar');
validateTree(MolstarTreeSchema, molstarTree, 'Converted Molstar', plugin);
const entry = molstarTreeToEntry(
plugin,
molstarTree,

View File

@@ -4,7 +4,7 @@
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { bool, float, int, list, OptionalField, RequiredField, str, union, nullable, literal, ValueFor } from '../generic/field-schema';
import { bool, float, int, list, OptionalField, RequiredField, str, union, nullable, literal, ValueFor, dict } from '../generic/field-schema';
import { SimpleParamsSchema, UnionParamsSchema } from '../generic/params-schema';
import { NodeFor, ParamsOfKind, SubtreeOfKind, TreeFor, TreeSchema } from '../generic/tree-schema';
import { ColorT, ContinuousPalette, DiscretePalette, Matrix, Vector3 } from '../mvs/param-types';
@@ -75,8 +75,8 @@ const ColorInterpolation = {
..._Common,
..._Frequency,
..._Easing,
start: OptionalField(nullable(ColorT), null, 'Start value. If unset, parent state value is used.'),
end: OptionalField(nullable(ColorT), null, 'End value.'),
start: OptionalField(union(nullable(ColorT), dict(union(int, str), ColorT)), null, 'Start value. If unset, parent state value is used.'),
end: OptionalField(union(nullable(ColorT), dict(union(int, str), ColorT)), null, 'End value.'),
palette: OptionalField(nullable(union(DiscretePalette, ContinuousPalette)), null, 'Palette to sample colors from. Overrides start and end values.'),
};

View File

@@ -4,6 +4,7 @@
* @author Adam Midlik <midlik@gmail.com>
*/
import { PluginContext } from '../../../../mol-plugin/context';
import { onelinerJsonString } from '../../../../mol-util/json';
import { isPlainObject, mapObjectMap } from '../../../../mol-util/object';
import { Field } from './field-schema';
@@ -145,13 +146,15 @@ export function treeValidationIssues(schema: TreeSchema, tree: Tree, options: {
/** Validate a tree against the given schema.
* Do nothing if OK; print validation issues on console and throw an error is the tree does not conform.
* Include `label` in the printed output. */
export function validateTree(schema: TreeSchema, tree: Tree, label: string): void {
export function validateTree(schema: TreeSchema, tree: Tree, label: string, plugin: PluginContext): void {
const issues = treeValidationIssues(schema, tree, { noExtra: true });
if (issues) {
console.warn(`Invalid ${label} tree:\n${treeToString(tree)}`);
console.error(`${label} tree validation issues:`);
plugin.log.error(`${label} tree validation issues:`);
for (const line of issues) {
console.error(' ', line);
plugin.log.error(line);
}
throw new Error('FormatError');
}

View File

@@ -53,7 +53,7 @@ const LinesParams = {
vertices: RequiredField(FloatList, '3*n_vertices length array of floats with vertex position (x1, y1, z1, ...).'),
/** 2*n_lines length array of indices into vertices that form lines (l1_1, l1_2, ...). */
indices: RequiredField(IntList, '2*n_lines length array of indices into vertices that form lines (l1_1, l1_2, ...).'),
/** Assign a number to each triangle to group them. If not specified, each line is considered a separate group (line i = group i). */
/** Assign a number to each line to group them. If not specified, each line is considered a separate group (line i = group i). */
line_groups: OptionalField(nullable(IntList), null, 'Assign a number to each triangle to group them. If not specified, each line is considered a separate group (line i = group i).'),
/** Assign a color to each group. Where not assigned, uses `color`. */
group_colors: OptionalField(dict(int, ColorT), {}, 'Assign a color to each group. Where not assigned, uses `color`.'),

View File

@@ -445,8 +445,9 @@ function areImageTexturePropsEqual(sourceA: ImageProps['source'], sourceB: Image
function getImageTexture(ctx: WebGLContext, assetManager: AssetManager, source: ImageProps['source'], onload?: (errored?: boolean) => void): { texture: Texture, asset: Asset } {
const asset = source.name === 'url'
? Asset.getUrlAsset(assetManager, source.params)
? assetManager.tryFindFilename(source.params) ?? Asset.getUrlAsset(assetManager, source.params)
: source.params!;
if (typeof HTMLImageElement === 'undefined') {
console.error(`Missing "HTMLImageElement" required for background image`);
onload?.(true);

View File

@@ -483,13 +483,13 @@ namespace Renderer {
const alpha = clamp(r.values.alpha.ref.value * r.state.alphaFactor, 0, 1);
const xrayShaded = r.values.dXrayShaded?.ref.value === 'on' || r.values.dXrayShaded?.ref.value === 'inverted';
return (
(alpha < 1 && alpha !== 0) ||
alpha !== 0 && (alpha < 1 ||
r.values.transparencyAverage.ref.value > 0 ||
r.values.dGeometryType.ref.value === 'directVolume' ||
r.values.dPointStyle?.ref.value === 'fuzzy' ||
r.values.dGeometryType.ref.value === 'text' ||
r.values.dGeometryType.ref.value === 'image' ||
xrayShaded
xrayShaded)
);
};

View File

@@ -38,11 +38,11 @@ float getDepthOpaque(const in vec2 coords) {
#endif
}
float getDepthTransparent(const in vec2 coords) {
vec2 getDepthTransparentWithAlpha(const in vec2 coords) {
#ifdef dTransparentOutline
return unpackRGBAToDepthWithAlpha(texture2D(tDepthTransparent, coords)).x;
return unpackRGBAToDepthWithAlpha(texture2D(tDepthTransparent, coords));
#else
return 1.0;
return vec2(1.0, 1.0);
#endif
}
@@ -66,7 +66,7 @@ void main(void) {
float selfViewZOpaque = isBackground(selfDepthOpaque) ? backgroundViewZ : getViewZ(selfDepthOpaque);
float pixelSizeOpaque = getPixelSize(coords, selfDepthOpaque) * uOutlineThreshold;
float selfDepthTransparent = getDepthTransparent(coords);
float selfDepthTransparent = getDepthTransparentWithAlpha(coords).x;
float selfViewZTransparent = isBackground(selfDepthTransparent) ? backgroundViewZ : getViewZ(selfDepthTransparent);
float pixelSizeTransparent = getPixelSize(coords, selfDepthTransparent) * uOutlineThreshold;
@@ -79,12 +79,15 @@ void main(void) {
vec2 sampleCoords = coords + vec2(float(x), float(y)) * invTexSize;
float sampleDepthOpaque = getDepthOpaque(sampleCoords);
float sampleDepthTransparent = getDepthTransparent(sampleCoords);
vec2 sampleDepthTransparentWithAlpha = getDepthTransparentWithAlpha(sampleCoords);
float sampleDepthTransparent = sampleDepthTransparentWithAlpha.x;
float sampleAlphaTransparent = sampleDepthTransparentWithAlpha.y;
float sampleViewZOpaque = isBackground(sampleDepthOpaque) ? backgroundViewZ : getViewZ(sampleDepthOpaque);
if (abs(selfViewZOpaque - sampleViewZOpaque) > pixelSizeOpaque && selfDepthOpaque > sampleDepthOpaque && sampleDepthOpaque <= bestDepth) {
outline = 0.0;
bestDepth = sampleDepthOpaque;
transparentFlag = 0.0;
}
if (sampleDepthTransparent < sampleDepthOpaque) {
@@ -92,7 +95,7 @@ void main(void) {
if (abs(selfViewZTransparent - sampleViewZTransparent) > pixelSizeTransparent && selfDepthTransparent > sampleDepthTransparent && sampleDepthTransparent <= bestDepth) {
outline = 0.0;
bestDepth = sampleDepthTransparent;
transparentFlag = 1.0;
transparentFlag = sampleAlphaTransparent;
}
}
}

View File

@@ -168,15 +168,25 @@ void main(void) {
if (outline == 0.0) {
float viewDist = abs(getViewZ(closestTexel));
float fogFactor = smoothstep(uFogNear, uFogFar, viewDist);
if (!uTransparentBackground) {
color.rgb = mix(uOutlineColor, uFogColor, fogFactor);
} else {
color.a = 1.0 - fogFactor;
color.rgb = mix(uOutlineColor, vec3(0.0), fogFactor);
}
#ifdef dBlendTransparency
if (isTransparentOutline == 1.0 || transparentDepth > closestTexel) {
blendTransparency = false;
if (isTransparentOutline > 0.0) {
float outlineAlpha = clamp(isTransparentOutline * 2.0, 0.0, 1.0);
transparentColor.a = transparentColor.a + outlineAlpha * (1.0 - fogFactor) * (1.0 - transparentColor.a);
transparentColor.rgb = uOutlineColor;
} else {
if (!uTransparentBackground) {
color.rgb = mix(uOutlineColor, uFogColor, fogFactor);
} else {
color.a = 1.0 - fogFactor;
color.rgb = mix(uOutlineColor, vec3(0.0), fogFactor);
}
}
#else
if (!uTransparentBackground) {
color.rgb = mix(uOutlineColor, uFogColor, fogFactor);
} else {
color.a = 1.0 - fogFactor;
color.rgb = mix(uOutlineColor, vec3(0.0), fogFactor);
}
#endif
}

View File

@@ -13,9 +13,11 @@ async function setPartialSnapshot(plugin: PluginContext, entry: Partial<PluginSt
if (entry.data) {
await plugin.runTask(plugin.state.data.setSnapshot(entry.data));
// update the canvas3d trackball with the snapshot
plugin.canvas3d?.setProps({
trackball: entry.canvas3d?.props?.trackball
});
if (entry.canvas3d?.props?.trackball) {
plugin.canvas3d?.setProps({
trackball: entry.canvas3d?.props?.trackball
});
}
}

View File

@@ -83,6 +83,15 @@ class AssetManager {
}
}
tryFindFilename(name: string): Asset | undefined {
const it = this._assets.values();
while (true) {
const { done, value } = it.next();
if (done) break;
if (value.file.name === name) return value.asset;
}
}
set(asset: Asset, file: File, options?: { isStatic?: boolean, tag?: string }) {
this._assets.set(asset.id, { asset, file, refCount: 0, tag: options?.tag, isStatic: options?.isStatic });
}

View File

@@ -5,13 +5,13 @@
*/
export class ErrorContext {
private errors: { [tag: string]: any[] } = Object.create(null);
private errors: { [tag: string]: string[] } = Object.create(null);
get(tag: string): ReadonlyArray<any> {
get(tag: string): ReadonlyArray<string> {
return this.errors[tag] ?? [];
}
add(tag: string, error: any) {
add(tag: string, error: string) {
if (tag in this.errors && Array.isArray(this.errors[tag])) {
this.errors[tag].push(error);
} else {