From 3f751044404fbe3757dbef9933ac176370792d6d Mon Sep 17 00:00:00 2001 From: Kirill Kapytov Date: Mon, 17 Jan 2022 17:31:52 +0300 Subject: [PATCH 1/2] Remake global imports --- packages/lib/rollup.config.js | 6 +- packages/lib/src/ComplexVisual.js | 12 +- packages/lib/src/ComplexVisualEdit.js | 26 +- packages/lib/src/Miew-cli.js | 23 +- packages/lib/src/Miew.js | 319 ++++++++++-------- packages/lib/src/Visual.js | 9 +- packages/lib/src/VolumeVisual.js | 4 +- packages/lib/src/chem/AromaticLoopsMarker.js | 14 +- packages/lib/src/chem/Assembly.js | 10 +- packages/lib/src/chem/Atom.js | 2 +- packages/lib/src/chem/BiologicalUnit.js | 12 +- packages/lib/src/chem/Chain.js | 10 +- packages/lib/src/chem/Complex.js | 4 +- packages/lib/src/chem/Residue.js | 4 +- packages/lib/src/chem/SGroup.js | 10 +- packages/lib/src/chem/Volume.js | 32 +- packages/lib/src/chem/VoxelWorld.js | 18 +- packages/lib/src/gfx/Axes.js | 10 +- packages/lib/src/gfx/CSS2DObject.js | 4 +- packages/lib/src/gfx/CSS2DRenderer.js | 14 +- packages/lib/src/gfx/FrameInfo.js | 4 +- packages/lib/src/gfx/RCGroup.js | 4 +- packages/lib/src/gfx/Representation.js | 12 +- packages/lib/src/gfx/ViewInterpolator.js | 6 +- packages/lib/src/gfx/VolumeBounds.js | 37 +- packages/lib/src/gfx/VolumeFarPlane.js | 18 +- packages/lib/src/gfx/VolumeMesh.js | 92 ++--- packages/lib/src/gfx/capabilities.js | 2 +- packages/lib/src/gfx/colorers/Colorer.js | 6 +- .../gfx/geometries/ChunkedObjectsGeometry.js | 32 +- .../lib/src/gfx/geometries/ContactSurface.js | 8 +- .../lib/src/gfx/geometries/CrossGeometry.js | 18 +- .../gfx/geometries/CylinderBufferGeometry.js | 19 +- .../gfx/geometries/CylinderCollisionGeo.js | 8 +- .../gfx/geometries/ExtrudedObjectsGeometry.js | 22 +- .../Instanced2CCylindersGeometry.js | 70 ++-- .../geometries/InstancedSpheresGeometry.js | 28 +- packages/lib/src/gfx/geometries/IsoSurface.js | 70 ++-- .../gfx/geometries/IsoSurfaceAtomColored.js | 4 +- .../lib/src/gfx/geometries/IsoSurfaceGeo.js | 8 +- .../src/gfx/geometries/IsoSurfaceGeometry.js | 6 +- .../gfx/geometries/IsosurfaceBuildNormals.js | 6 +- .../lib/src/gfx/geometries/LabelsGeometry.js | 6 +- .../lib/src/gfx/geometries/LinesGeometry.js | 12 +- .../gfx/geometries/SSIsosurfaceGeometry.js | 26 +- .../geometries/Simple2CCylindersGeometry.js | 10 +- .../gfx/geometries/SimpleSpheresGeometry.js | 4 +- .../src/gfx/geometries/SphereCollisionGeo.js | 12 +- .../src/gfx/geometries/ThickLinesGeometry.js | 27 +- .../src/gfx/geometries/ThinLinesGeometry.js | 21 +- .../gfx/geometries/TwoColorLinesGeometry.js | 4 +- .../gfx/geometries/VolumeSurfaceGeometry.js | 32 +- packages/lib/src/gfx/gfxutils.js | 169 +++++----- packages/lib/src/gfx/materials.js | 4 +- packages/lib/src/gfx/meshes/InstancedMesh.js | 6 +- packages/lib/src/gfx/meshes/SimpleMesh.js | 6 +- packages/lib/src/gfx/meshes/TextMesh.js | 8 +- packages/lib/src/gfx/meshes/ThickLineMesh.js | 8 +- packages/lib/src/gfx/meshes/TransformGroup.js | 11 +- packages/lib/src/gfx/meshes/ZClippedMesh.js | 14 +- packages/lib/src/gfx/meshes/ZSpriteMesh.js | 8 +- packages/lib/src/gfx/meshes/meshes.js | 6 +- packages/lib/src/gfx/meshutils.js | 28 +- packages/lib/src/gfx/modes/CartoonMode.js | 10 +- packages/lib/src/gfx/modes/Mode.js | 8 +- packages/lib/src/gfx/modes/TextMode.js | 4 +- packages/lib/src/gfx/modes/TubeMode.js | 4 +- .../lib/src/gfx/modes/groups/AromaticGroup.js | 6 +- .../gfx/modes/groups/AromaticTorusGroup.js | 8 +- .../gfx/modes/groups/BondsCylinderGroup.js | 10 +- .../src/gfx/modes/groups/BondsLinesGroup.js | 14 +- .../lib/src/gfx/modes/groups/CartoonHelper.js | 6 +- .../gfx/modes/groups/ResiduesSubseqGroup.js | 4 +- packages/lib/src/gfx/noiseTexture.js | 25 +- packages/lib/src/gfx/objects/LinesObj.js | 10 +- packages/lib/src/gfx/objects/SceneObject.js | 6 +- packages/lib/src/gfx/palettes/Palette.js | 4 +- .../lib/src/gfx/shaders/AOHorBlurMaterial.js | 7 +- packages/lib/src/gfx/shaders/AOMaterial.js | 80 +++-- .../shaders/AOVertBlurWithBlendMaterial.js | 13 +- .../lib/src/gfx/shaders/AnaglyphMaterial.js | 5 +- packages/lib/src/gfx/shaders/FXAAMaterial.js | 9 +- .../lib/src/gfx/shaders/OutlineMaterial.js | 9 +- packages/lib/src/gfx/shaders/UberMaterial.js | 77 +++-- .../lib/src/gfx/shaders/VolumeMaterial.js | 44 ++- packages/lib/src/gfx/vr/WebVRPoC.js | 18 +- packages/lib/src/io/exporters/PDBExporter.js | 4 +- packages/lib/src/io/exporters/PDBResult.js | 16 +- .../src/io/exporters/fbx/FBXInfoExtractor.js | 25 +- packages/lib/src/io/exporters/fbx/FBXModel.js | 4 +- packages/lib/src/io/loaders/XHRLoader.js | 4 +- packages/lib/src/io/parsers/CIFParser.js | 16 +- packages/lib/src/io/parsers/CMLParser.js | 18 +- packages/lib/src/io/parsers/DSN6Parser.js | 4 +- packages/lib/src/io/parsers/GROParser.js | 8 +- packages/lib/src/io/parsers/MMTFParser.js | 18 +- packages/lib/src/io/parsers/MOL2Parser.js | 4 +- packages/lib/src/io/parsers/PDBParser.js | 16 +- packages/lib/src/io/parsers/ParserList.js | 2 +- packages/lib/src/io/parsers/PubChemParser.js | 10 +- packages/lib/src/io/parsers/SDFParser.js | 10 +- packages/lib/src/io/parsers/SDFStream.js | 6 +- packages/lib/src/io/parsers/VolumeModel.js | 38 +-- packages/lib/src/io/parsers/XYZParser.js | 8 +- packages/lib/src/io/parsers/pdb/Remark290.js | 12 +- packages/lib/src/io/parsers/pdb/Remark350.js | 8 +- packages/lib/src/io/parsers/readCIF.js | 6 +- packages/lib/src/options.js | 26 +- packages/lib/src/options.test.js | 8 +- packages/lib/src/settings.js | 26 +- packages/lib/src/ui/ObjectControls.js | 60 ++-- packages/lib/src/ui/Picker.js | 15 +- packages/lib/src/utils.js | 29 +- packages/lib/src/utils.test.js | 16 +- packages/lib/src/utils/Cookies.js | 4 +- packages/lib/src/utils/EventDispatcher.js | 12 +- packages/lib/src/utils/MiewCLIParser.jison | 6 +- packages/lib/src/utils/MiewCLIParser.js | 6 +- packages/lib/src/utils/logger.js | 8 +- 119 files changed, 1156 insertions(+), 1123 deletions(-) diff --git a/packages/lib/rollup.config.js b/packages/lib/rollup.config.js index 06681fb7..aaa73443 100644 --- a/packages/lib/rollup.config.js +++ b/packages/lib/rollup.config.js @@ -34,11 +34,7 @@ const config = { name: 'Miew', file: packageJson.main, banner, - sourcemap: true, - globals: { - three: 'THREE', - lodash: '_' - } + sourcemap: true }, { format: 'es', diff --git a/packages/lib/src/ComplexVisual.js b/packages/lib/src/ComplexVisual.js index 901737d4..49464c35 100644 --- a/packages/lib/src/ComplexVisual.js +++ b/packages/lib/src/ComplexVisual.js @@ -1,5 +1,3 @@ -import _ from 'lodash' -import * as THREE from 'three' import utils from './utils' import logger from './utils/logger' import chem from './chem' @@ -13,6 +11,8 @@ import Representation from './gfx/Representation' import Visual from './Visual' import ComplexVisualEdit from './ComplexVisualEdit' import meshutils from './gfx/meshutils' +import { Group, Mesh } from 'three' +import { isEmpty, merge } from 'lodash' const { selectors } = chem @@ -40,7 +40,7 @@ class ComplexVisual extends Visual { this._reprUsedBits = 0 this._selectionCount = 0 - this._selectionGeometry = new THREE.Group() + this._selectionGeometry = new Group() } getBoundaries() { @@ -198,7 +198,7 @@ class ComplexVisual extends Visual { ) // something was changed - if (!_.isEmpty(diff)) { + if (isEmpty(diff)) { target.needsRebuild = true for (const key in diff) { if (diff.hasOwnProperty(key)) { @@ -279,7 +279,7 @@ class ComplexVisual extends Visual { // Fill in default values const def = settings.now.presets.default[0] - const desc = _.merge( + const desc = merge( { selector: def.selector, mode: def.mode, @@ -859,7 +859,7 @@ class ComplexVisual extends Visual { rep.material.setValues(values) if (needTraverse) { rep.geo.traverse((object) => { - if (object instanceof THREE.Mesh) { + if (object instanceof Mesh) { object.material.setValues(values) if (process !== undefined) { diff --git a/packages/lib/src/ComplexVisualEdit.js b/packages/lib/src/ComplexVisualEdit.js index aa90a79c..9348e7c7 100644 --- a/packages/lib/src/ComplexVisualEdit.js +++ b/packages/lib/src/ComplexVisualEdit.js @@ -1,7 +1,7 @@ -import * as THREE from 'three' import logger from './utils/logger' import gfxutils from './gfx/gfxutils' import './gfx/modes' +import { Group, Matrix4, Object3D, Vector3 } from 'three' function _traverseComponentGroups(root, component, callback) { const { children } = root @@ -36,7 +36,7 @@ class ComplexComponentEditor extends ComplexEditor { this._componentTransforms = [] for (let i = 0; i < complex._components.length; ++i) { const component = complex._components[i] - this._componentTransforms[component._index] = new THREE.Object3D() + this._componentTransforms[component._index] = new Object3D() } this._inProgress = true @@ -75,7 +75,7 @@ class ComplexComponentEditor extends ComplexEditor { getAltObj() { const res = { objects: [], - pivot: new THREE.Vector3(0, 0, 0) + pivot: new Vector3(0, 0, 0) } const visual = this._complexVisual @@ -111,12 +111,12 @@ class ComplexComponentEditor extends ComplexEditor { // add dummy object that stores component transformation res.objects.push(this._componentTransforms[component._index]) - const bbmin = new THREE.Vector3( + const bbmin = new Vector3( Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE ) - const bbmax = new THREE.Vector3( + const bbmax = new Vector3( -Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE @@ -235,11 +235,11 @@ class ComplexFragmentEditor extends ComplexEditor { pivotPos.lerp(atoms[1].position, 0.5) } - this._fragmentGeo = new THREE.Group() + this._fragmentGeo = new Group() visual.add(this._fragmentGeo) this._fragmentGeo.position.copy(pivotPos) - this._fragmentSelectionGeo = new THREE.Group() + this._fragmentSelectionGeo = new Group() selection.add(this._fragmentSelectionGeo) this._fragmentSelectionGeo.position.copy(pivotPos) @@ -252,10 +252,10 @@ class ComplexFragmentEditor extends ComplexEditor { continue } - const vg = new THREE.Group() + const vg = new Group() this._fragmentGeo.add(vg) - const sg = new THREE.Group() + const sg = new Group() this._fragmentSelectionGeo.add(sg) const meshes = g.getSubset(selectionMask, true) @@ -289,7 +289,7 @@ class ComplexFragmentEditor extends ComplexEditor { const p = this._fragmentGeo.position const m = this._fragmentGeo.matrix.clone() - m.multiply(new THREE.Matrix4().makeTranslation(-p.x, -p.y, -p.z)) + m.multiply(new Matrix4().makeTranslation(-p.x, -p.y, -p.z)) this._bakeAtomTransform(m, 1 << selectionBit) @@ -334,7 +334,7 @@ class ComplexFragmentEditor extends ComplexEditor { getAltObj() { const res = { objects: [], - pivot: new THREE.Vector3(0, 0, 0) + pivot: new Vector3(0, 0, 0) } res.objects.push(this._fragmentGeo, this._fragmentSelectionGeo) @@ -344,7 +344,7 @@ class ComplexFragmentEditor extends ComplexEditor { if (boundAtoms[0].bonds.length === 1) { // single external bond allows rotation about bond axis const bond = boundAtoms[0].bonds[0] - res.axis = new THREE.Vector3().subVectors( + res.axis = new Vector3().subVectors( bond._right.position, bond._left.position ) @@ -353,7 +353,7 @@ class ComplexFragmentEditor extends ComplexEditor { } } else if (boundAtoms.length === 2) { // two bound atoms allow rotation only about axis running through their centers - res.axis = new THREE.Vector3().subVectors( + res.axis = new Vector3().subVectors( boundAtoms[1].position, boundAtoms[0].position ) diff --git a/packages/lib/src/Miew-cli.js b/packages/lib/src/Miew-cli.js index 712af183..9cdaf9c7 100644 --- a/packages/lib/src/Miew-cli.js +++ b/packages/lib/src/Miew-cli.js @@ -1,9 +1,9 @@ -import _ from 'lodash' import Miew from './Miew' import { parser as parsercli } from './utils/MiewCLIParser' import clihelp from './utils/MiewCLIHelp' import logger from './utils/logger' import utils from './utils' +import { slice, sortBy, get, keys, isUndefined, set, assign } from 'lodash' const { chem: { selectors }, @@ -176,15 +176,15 @@ class CLIUtils { } help(path) { - if (_.isUndefined(path)) { - return `${this.joinHelpStr(clihelp.$help)}\n${_.slice( - _.sortBy(_.keys(clihelp)), + if (isUndefined(path)) { + return `${this.joinHelpStr(clihelp.$help)}\n${slice( + sortBy(keys(clihelp)), 1 ).join(', ')}\n` } - const helpItem = _.get(clihelp, path) - return _.isUndefined(helpItem) + const helpItem = get(clihelp, path) + return isUndefined(helpItem) ? this.help() : `${this.joinHelpStr(helpItem.$help)}\n` } @@ -239,7 +239,7 @@ class CLIUtils { propagateProp(path, arg) { if (path !== undefined) { let argExc = {} - const adapter = options.adapters[typeof _.get(settings.defaults, path)] + const adapter = options.adapters[typeof get(settings.defaults, path)] if (adapter === undefined) { const pathExc = { message: `${path} is not existed` } throw pathExc @@ -277,10 +277,7 @@ class CLIUtils { adapter(arg) !== arg > 0 ) { argExc = { - message: `${path} must be a "${typeof _.get( - settings.defaults, - path - )}"` + message: `${path} must be a "${typeof get(settings.defaults, path)}"` } throw argExc } @@ -335,7 +332,7 @@ ArgList.prototype.toJSO = function (cliUtils, cmd, arg) { const list = this._values for (let i = 0, n = list.length; i < n; ++i) { - _.set( + set( res, list[i].id, cliUtils.propagateProp( @@ -363,7 +360,7 @@ cliutils.echo = null cliutils.representations = representationsStorage cliutils.utils = utilFunctions -cliutils._ = _ +cliutils.assign = assign cliutils.CreateObjectPair = CreateObjectPair cliutils.keyRemap = keyRemap cliutils.Context = selectors.Context diff --git a/packages/lib/src/Miew.js b/packages/lib/src/Miew.js index 16e705ed..b399b299 100644 --- a/packages/lib/src/Miew.js +++ b/packages/lib/src/Miew.js @@ -1,6 +1,4 @@ /* global PACKAGE_VERSION:false */ -import _ from 'lodash' -import * as THREE from 'three' import { Spinner } from 'spin.js' import Stats from './gfx/Stats' import utils from './utils' @@ -43,6 +41,52 @@ import capabilities from './gfx/capabilities' import WebVRPoC from './gfx/vr/WebVRPoC' import vertexScreenQuadShader from './gfx/shaders/ScreenQuad.vert' import fragmentScreenQuadFromDistTex from './gfx/shaders/ScreenQuadFromDistortionTex.frag' +import { + AmbientLight, + Box3, + DepthTexture, + DirectionalLight, + FloatType, + Fog, + Group, + Line, + LinearFilter, + LineSegments, + Matrix4, + Mesh, + NearestFilter, + PCFShadowMap, + PerspectiveCamera, + RGBAFormat, + Scene, + Sphere, + StereoCamera, + UnsignedShortType, + Vector2, + Vector3, + WebGL1Renderer, + WebGLRenderTarget, + Color, + Euler, + Vector4, + Quaternion, + MathUtils, + NoBlending, + RawShaderMaterial, + OrthographicCamera +} from 'three' +import { + assign, + merge, + isString, + head, + defaults, + isUndefined, + isNumber, + get, + isArray, + isEmpty +} from 'lodash' const { selectors, Atom, Residue, Chain, Molecule } = chem @@ -109,7 +153,7 @@ function chooseFogColor() { */ function Miew(opts) { EventDispatcher.call(this) - this._opts = _.merge( + this._opts = merge( { settingsCookie: 'settings', cookiePath: '/' @@ -124,7 +168,7 @@ function Miew(opts) { this._container = (opts && opts.container) || document.getElementById('miew-container') || - _.head(document.getElementsByClassName('miew-container')) || + head(document.getElementsByClassName('miew-container')) || document.body /** @type {HTMLElement} */ this._containerRoot = this._container @@ -222,9 +266,9 @@ function _setContainerContents(container, element) { * @private */ Miew.prototype._updateShadowCamera = (function () { - const shadowMatrix = new THREE.Matrix4() - const direction = new THREE.Vector3() - const OBB = { center: new THREE.Vector3(), halfSize: new THREE.Vector3() } + const shadowMatrix = new Matrix4() + const direction = new Vector3() + const OBB = { center: new Vector3(), halfSize: new Vector3() } return function () { this._gfx.scene.updateMatrixWorld() @@ -445,10 +489,10 @@ Miew.prototype._initGfx = function () { gfx.renderer2d = new CSS2DRenderer() - gfx.renderer = new THREE.WebGL1Renderer(webGLOptions) + gfx.renderer = new WebGL1Renderer(webGLOptions) gfx.renderer.shadowMap.enabled = settings.now.shadow.on gfx.renderer.shadowMap.autoUpdate = false - gfx.renderer.shadowMap.type = THREE.PCFShadowMap + gfx.renderer.shadowMap.type = PCFShadowMap capabilities.init(gfx.renderer) // z-sprites and ambient occlusion possibility @@ -470,7 +514,7 @@ Miew.prototype._initGfx = function () { gfx.renderer2d.setSize(gfx.width, gfx.height) - gfx.camera = new THREE.PerspectiveCamera( + gfx.camera = new PerspectiveCamera( settings.now.camFov, gfx.width / gfx.height, settings.now.camNear, @@ -483,16 +527,12 @@ Miew.prototype._initGfx = function () { gfx.camera.layers.enable(gfxutils.LAYERS.VOLUME) gfx.camera.layers.enable(gfxutils.LAYERS.VOLUME_BFPLANE) - gfx.stereoCam = new THREE.StereoCamera() + gfx.stereoCam = new StereoCamera() - gfx.scene = new THREE.Scene() + gfx.scene = new Scene() const color = chooseFogColor() - gfx.scene.fog = new THREE.Fog( - color, - settings.now.camNear, - settings.now.camFar - ) + gfx.scene.fog = new Fog(color, settings.now.camNear, settings.now.camFar) gfx.root = new gfxutils.RCGroup() gfx.scene.add(gfx.root) @@ -500,16 +540,16 @@ Miew.prototype._initGfx = function () { gfx.pivot = new gfxutils.RCGroup() gfx.root.add(gfx.pivot) - gfx.selectionScene = new THREE.Scene() - gfx.selectionRoot = new THREE.Group() + gfx.selectionScene = new Scene() + gfx.selectionRoot = new Group() gfx.selectionRoot.matrixAutoUpdate = false gfx.selectionScene.add(gfx.selectionRoot) - gfx.selectionPivot = new THREE.Group() + gfx.selectionPivot = new Group() gfx.selectionPivot.matrixAutoUpdate = false gfx.selectionRoot.add(gfx.selectionPivot) - const light12 = new THREE.DirectionalLight(0xffffff, 0.45) + const light12 = new DirectionalLight(0xffffff, 0.45) light12.position.set(0, 0.414, 1) light12.layers.enable(gfxutils.LAYERS.TRANSPARENT) light12.castShadow = true @@ -525,7 +565,7 @@ Miew.prototype._initGfx = function () { gfx.scene.add(light12) gfx.scene.add(light12.target) - const light3 = new THREE.AmbientLight(0x666666) + const light3 = new AmbientLight(0x666666) light3.layers.enable(gfxutils.LAYERS.TRANSPARENT) gfx.scene.add(light3) @@ -534,36 +574,36 @@ Miew.prototype._initGfx = function () { const deviceWidth = gfx.width * pixelRatio const deviceHeight = gfx.height * pixelRatio - gfx.offscreenBuf = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.NearestFilter, - format: THREE.RGBAFormat, + gfx.offscreenBuf = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: NearestFilter, + format: RGBAFormat, depthBuffer: true }) if (gfx.renderer.getContext().getExtension('WEBGL_depth_texture')) { - gfx.offscreenBuf.depthTexture = new THREE.DepthTexture() - gfx.offscreenBuf.depthTexture.type = THREE.UnsignedShortType + gfx.offscreenBuf.depthTexture = new DepthTexture() + gfx.offscreenBuf.depthTexture.type = UnsignedShortType } - gfx.offscreenBuf2 = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - format: THREE.RGBAFormat, + gfx.offscreenBuf2 = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat, depthBuffer: false }) - gfx.offscreenBuf3 = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - format: THREE.RGBAFormat, + gfx.offscreenBuf3 = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat, depthBuffer: false }) - gfx.offscreenBuf4 = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - format: THREE.RGBAFormat, + gfx.offscreenBuf4 = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat, depthBuffer: false }) @@ -573,27 +613,27 @@ Miew.prototype._initGfx = function () { // use float textures for volume rendering if possible if (gfx.renderer.getContext().getExtension('OES_texture_float')) { - gfx.offscreenBuf5 = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - format: THREE.RGBAFormat, - type: THREE.FloatType, + gfx.offscreenBuf5 = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat, + type: FloatType, depthBuffer: false }) - gfx.offscreenBuf6 = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - format: THREE.RGBAFormat, - type: THREE.FloatType, + gfx.offscreenBuf6 = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat, + type: FloatType, depthBuffer: false }) - gfx.offscreenBuf7 = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - format: THREE.RGBAFormat, - type: THREE.FloatType, + gfx.offscreenBuf7 = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat, + type: FloatType, depthBuffer: true }) @@ -604,17 +644,17 @@ Miew.prototype._initGfx = function () { this.logger.warn("Device doesn't support OES_texture_float extension") } - gfx.stereoBufL = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - format: THREE.RGBAFormat, + gfx.stereoBufL = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat, depthBuffer: false }) - gfx.stereoBufR = new THREE.WebGLRenderTarget(deviceWidth, deviceHeight, { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - format: THREE.RGBAFormat, + gfx.stereoBufR = new WebGLRenderTarget(deviceWidth, deviceHeight, { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat, depthBuffer: false }) @@ -984,18 +1024,13 @@ Miew.prototype._getBSphereRadius = function () { * @param {Vector3} OBB.halfSize - half magnitude of OBB sizes. */ Miew.prototype.getOBB = (function () { - const _bSphereForOneVisual = new THREE.Sphere() - const _bBoxForOneVisual = new THREE.Box3() - const _bBox = new THREE.Box3() + const _bSphereForOneVisual = new Sphere() + const _bBoxForOneVisual = new Box3() + const _bBox = new Box3() - const _invMatrix = new THREE.Matrix4() + const _invMatrix = new Matrix4() - const _points = [ - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3(), - new THREE.Vector3() - ] + const _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3()] return function (matrix, OBB) { _bBox.makeEmpty() @@ -1037,7 +1072,7 @@ Miew.prototype._updateFog = function () { if (settings.now.fog) { if (typeof gfx.scene.fog === 'undefined' || gfx.scene.fog === null) { const color = chooseFogColor() - gfx.scene.fog = new THREE.Fog(color) + gfx.scene.fog = new Fog(color) this._setUberMaterialValues({ fog: settings.now.fog }) } updateFogRange( @@ -1104,7 +1139,7 @@ Miew.prototype._onRender = function () { Miew.prototype._renderFrame = (function () { const _anaglyphMat = new AnaglyphMaterial() - const _size = new THREE.Vector2() + const _size = new Vector2() return function (stereo) { const gfx = this._gfx @@ -1200,9 +1235,9 @@ Miew.prototype._onFogColorChanged = function () { Miew.prototype._setUberMaterialValues = function (values) { this._gfx.root.traverse((obj) => { if ( - (obj instanceof THREE.Mesh || - obj instanceof THREE.LineSegments || - obj instanceof THREE.Line) && + (obj instanceof Mesh || + obj instanceof LineSegments || + obj instanceof Line) && obj.material instanceof UberMaterial ) { obj.material.setValues(values) @@ -1388,13 +1423,13 @@ Miew.prototype._renderScene = (function () { })() Miew.prototype._performDistortion = (function () { - const _scene = new THREE.Scene() - const _camera = new THREE.OrthographicCamera(-1.0, 1.0, 1.0, -1.0, -500, 1000) + const _scene = new Scene() + const _camera = new OrthographicCamera(-1.0, 1.0, 1.0, -1.0, -500, 1000) - const _material = new THREE.RawShaderMaterial({ + const _material = new RawShaderMaterial({ uniforms: { srcTex: { type: 't', value: null }, - aberration: { type: 'fv3', value: new THREE.Vector3(1.0) } + aberration: { type: 'fv3', value: new Vector3(1.0) } }, vertexShader: vertexScreenQuadShader, fragmentShader: fragmentScreenQuadFromDistTex, @@ -1441,11 +1476,11 @@ Miew.prototype._renderOutline = (function () { srcDepthBuffer.width, srcDepthBuffer.height ) - _outlineMaterial.uniforms.color.value = new THREE.Color( + _outlineMaterial.uniforms.color.value = new Color( settings.now.outline.color ) _outlineMaterial.uniforms.threshold.value = settings.now.outline.threshold - _outlineMaterial.uniforms.thickness.value = new THREE.Vector2( + _outlineMaterial.uniforms.thickness.value = new Vector2( settings.now.outline.thickness, settings.now.outline.thickness ) @@ -1457,9 +1492,9 @@ Miew.prototype._renderOutline = (function () { Miew.prototype._renderShadowMap = (function () { const pars = { - minFilter: THREE.NearestFilter, - magFilter: THREE.NearestFilter, - format: THREE.RGBAFormat + minFilter: NearestFilter, + magFilter: NearestFilter, + format: RGBAFormat } return function () { @@ -1475,7 +1510,7 @@ Miew.prototype._renderShadowMap = (function () { const _state = gfx.renderer.state // Set GL state for depth map. - _state.setBlending(THREE.NoBlending) + _state.setBlending(NoBlending) _state.buffers.color.setClear(1, 1, 1, 1) _state.buffers.depth.setTest(true) _state.setScissorTest(false) @@ -1485,7 +1520,7 @@ Miew.prototype._renderShadowMap = (function () { const light = gfx.scene.children[i] if (light.shadow.map == null) { - light.shadow.map = new THREE.WebGLRenderTarget( + light.shadow.map = new WebGLRenderTarget( light.shadow.mapSize.width, light.shadow.mapSize.height, pars @@ -1583,8 +1618,8 @@ Miew.prototype._checkVolumeRenderingSupport = function (renderTarget) { Miew.prototype._renderVolume = (function () { const volumeBFMat = new VolumeMaterial.BackFacePosMaterial() const volumeFFMat = new VolumeMaterial.FrontFacePosMaterial() - const cubeOffsetMat = new THREE.Matrix4().makeTranslation(0.5, 0.5, 0.5) - const world2colorMat = new THREE.Matrix4() + const cubeOffsetMat = new Matrix4().makeTranslation(0.5, 0.5, 0.5) + const world2colorMat = new Matrix4() let volumeRenderingSupported @@ -1727,7 +1762,7 @@ Miew.prototype._performAO = (function () { const _horBlurMaterial = new AOHorBlurMaterial() const _vertBlurMaterial = new AOVertBlurWithBlendMaterial() - const _scale = new THREE.Vector3() + const _scale = new Vector3() return function ( srcColorBuffer, normalBuffer, @@ -1747,7 +1782,7 @@ Miew.prototype._performAO = (function () { return } const gfx = this._gfx - const tanHalfFOV = Math.tan(THREE.MathUtils.DEG2RAD * 0.5 * gfx.camera.fov) + const tanHalfFOV = Math.tan(MathUtils.DEG2RAD * 0.5 * gfx.camera.fov) _aoMaterial.uniforms.diffuseTexture.value = srcColorBuffer.texture _aoMaterial.uniforms.depthTexture.value = srcDepthTexture @@ -1862,7 +1897,7 @@ Miew.prototype.resetView = function () { } Miew.prototype._export = function (format) { - const TheExporter = _.head(io.exporters.find({ format })) + const TheExporter = head(io.exporters.find({ format })) if (!TheExporter) { this.logger.error('Could not find suitable exporter for this source') return Promise.reject( @@ -1894,7 +1929,7 @@ const rePubchem = /^(?:pc|pubchem):\s*([a-z]+)$/i const reUrlScheme = /^([a-z][a-z\d\-+.]*):/i function resolveSourceShortcut(source, opts) { - if (!_.isString(source)) { + if (!isString(source)) { return source } @@ -1961,7 +1996,7 @@ function updateBinaryMode(opts) { // detect by format if (opts.fileType !== undefined) { - const TheParser = _.head(io.parsers.find({ format: opts.fileType })) + const TheParser = head(io.parsers.find({ format: opts.fileType })) if (TheParser) { binary = TheParser.binary || false } else { @@ -1971,7 +2006,7 @@ function updateBinaryMode(opts) { // detect by file extension if (binary === undefined && opts.fileExt !== undefined) { - const TheParser = _.head(io.parsers.find({ ext: opts.fileExt })) + const TheParser = head(io.parsers.find({ ext: opts.fileExt })) if (TheParser) { binary = TheParser.binary || false } @@ -2004,7 +2039,7 @@ function _fetchData(source, opts, job) { source = resolveSourceShortcut(source, opts) // detect a proper loader - const TheLoader = _.head(io.loaders.find({ type: opts.sourceType, source })) + const TheLoader = head(io.loaders.find({ type: opts.sourceType, source })) if (!TheLoader) { throw new Error(LOADER_NOT_FOUND) } @@ -2013,7 +2048,7 @@ function _fetchData(source, opts, job) { const fileName = opts.fileName || TheLoader.extractName(source) if (fileName) { const [name, fileExt] = utils.splitFileName(fileName) - _.defaults(opts, { name, fileExt, fileName }) + defaults(opts, { name, fileExt, fileName }) } // should it be text or binary? @@ -2022,8 +2057,8 @@ function _fetchData(source, opts, job) { // FIXME: All new settings retrieved from server are applied after the loading is complete. However, we need some // flags to alter the loading process itself. Here we apply them in advance. Dirty hack. Kill the server, remove // all hacks and everybody's happy. - let newOptions = _.get(opts, 'preset.expression') - if (!_.isUndefined(newOptions)) { + let newOptions = get(opts, 'preset.expression') + if (!isUndefined(newOptions)) { newOptions = JSON.parse(newOptions) if (newOptions && newOptions.settings) { const keys = ['singleUnit'] @@ -2033,8 +2068,8 @@ function _fetchData(source, opts, job) { ++keyIndex ) { const key = keys[keyIndex] - const value = _.get(newOptions.settings, key) - if (!_.isUndefined(value)) { + const value = get(newOptions.settings, key) + if (!isUndefined(value)) { settings.set(key, value) } } @@ -2084,7 +2119,7 @@ function _parseData(data, opts, job) { job.notify({ type: 'parsing' }) - const TheParser = _.head( + const TheParser = head( io.parsers.find({ format: opts.fileType, ext: opts.fileExt, data }) ) if (!TheParser) { @@ -2127,7 +2162,7 @@ function _parseData(data, opts, job) { * @returns {Promise} name of the visual that was added to the viewer */ Miew.prototype.load = function (source, opts) { - opts = _.merge({}, opts, { + opts = merge({}, opts, { context: this }) @@ -2361,7 +2396,7 @@ Miew.prototype._onLoad = function (dataSource, opts) { `Parsed ${opts.fileName} (${desc.atoms} atoms, ${desc.bonds} bonds, ${desc.residues} residues, ${desc.chains} chains).` ) - if (_.isNumber(this._opts.unit)) { + if (isNumber(this._opts.unit)) { complex.setCurrentUnit(this._opts.unit) } @@ -2440,7 +2475,7 @@ Miew.prototype.resetEd = function () { Miew.prototype.loadEd = function (source) { this.resetEd() - const TheLoader = _.head(io.loaders.find({ source })) + const TheLoader = head(io.loaders.find({ source })) if (!TheLoader) { this.logger.error(LOADER_NOT_FOUND) return Promise.reject(new Error(LOADER_NOT_FOUND)) @@ -2451,7 +2486,7 @@ Miew.prototype.loadEd = function (source) { return loader .load() .then((data) => { - const TheParser = _.head(io.parsers.find({ format: 'ccp4' })) + const TheParser = head(io.parsers.find({ format: 'ccp4' })) if (!TheParser) { throw new Error(PARSER_NOT_FOUND) } @@ -2533,7 +2568,7 @@ Miew.prototype.changeUnit = function (unitIdx, name) { if (unitIdx === undefined) { return currentUnitInfo() } - if (_.isString(unitIdx)) { + if (isString(unitIdx)) { unitIdx = Math.max(parseInt(unitIdx, 10), 0) } if (visual.getComplex().setCurrentUnit(unitIdx)) { @@ -3202,13 +3237,13 @@ Miew.prototype._getAltObj = function () { return { objects: [], - pivot: new THREE.Vector3(0, 0, 0) + pivot: new Vector3(0, 0, 0) } } Miew.prototype.resetPivot = (function () { - const boundingBox = new THREE.Box3() - const center = new THREE.Vector3() + const boundingBox = new Box3() + const center = new Vector3() return function () { boundingBox.makeEmpty() @@ -3223,7 +3258,7 @@ Miew.prototype.resetPivot = (function () { })() Miew.prototype.setPivotResidue = (function () { - const center = new THREE.Vector3() + const center = new Vector3() return function (residue) { const visual = this._getVisualForComplex(residue.getChain().getComplex()) @@ -3253,7 +3288,7 @@ Miew.prototype.setPivotResidue = (function () { })() Miew.prototype.setPivotAtom = (function () { - const center = new THREE.Vector3() + const center = new Vector3() return function (atom) { const visual = this._getVisualForComplex( @@ -3271,7 +3306,7 @@ Miew.prototype.setPivotAtom = (function () { })() Miew.prototype.getSelectionCenter = (function () { - const _centerInVisual = new THREE.Vector3(0.0, 0.0, 0.0) + const _centerInVisual = new Vector3(0.0, 0.0, 0.0) return function (center, includesAtom, selector) { center.set(0.0, 0.0, 0.0) @@ -3299,7 +3334,7 @@ Miew.prototype.getSelectionCenter = (function () { })() Miew.prototype.setPivotSubset = (function () { - const _center = new THREE.Vector3(0.0, 0.0, 0.0) + const _center = new Vector3(0.0, 0.0, 0.0) function _includesInCurSelection(atom, selectionBit) { return atom.mask & (1 << selectionBit) @@ -3336,11 +3371,11 @@ Miew.prototype.screenshot = function (width, height) { const deviceHeight = gfx.renderer.domElement.height function fov2Tan(fov) { - return Math.tan(THREE.MathUtils.degToRad(0.5 * fov)) + return Math.tan(MathUtils.degToRad(0.5 * fov)) } function tan2Fov(tan) { - return THREE.MathUtils.radToDeg(Math.atan(tan)) * 2.0 + return MathUtils.radToDeg(Math.atan(tan)) * 2.0 } function getDataURL() { @@ -3525,7 +3560,7 @@ Miew.prototype.setOptions = function (opts) { if (opts.reps) { this._opts.reps = null } - _.merge(this._opts, opts) + merge(this._opts, opts) if (opts.settings) { this.set(opts.settings) } @@ -3553,7 +3588,7 @@ Miew.prototype.setOptions = function (opts) { const visual = this._getComplexVisual() if (visual) { visual.getComplex().resetCurrentUnit() - if (_.isNumber(opts.unit)) { + if (isNumber(opts.unit)) { visual.getComplex().setCurrentUnit(opts.unit) } this.resetView() @@ -3658,7 +3693,7 @@ Miew.prototype.removeObject = function (index) { Miew.prototype.getURL = function (opts) { return options.toURL( this.getState( - _.defaults(opts, { + defaults(opts, { compact: true, settings: false, view: false @@ -3679,7 +3714,7 @@ Miew.prototype.getURL = function (opts) { Miew.prototype.getScript = function (opts) { return options.toScript( this.getState( - _.defaults(opts, { + defaults(opts, { compact: true, settings: true, view: true @@ -3716,7 +3751,7 @@ Miew.prototype._compareReps = function (complexVisual, compareWithDefaults) { repsDiff[i] = complexVisual .repGet(i) .compare(compare ? currPreset[i] : null) - if (!_.isEmpty(repsDiff[i])) { + if (!isEmpty(repsDiff[i])) { emptyReps = false } } @@ -3737,7 +3772,7 @@ Miew.prototype._compareReps = function (complexVisual, compareWithDefaults) { Miew.prototype.getState = function (opts) { const state = {} - opts = _.defaults(opts, { + opts = defaults(opts, { compact: true, settings: false, view: false @@ -3786,7 +3821,7 @@ Miew.prototype.getState = function (opts) { // settings if (opts.settings) { const diff = this.settings.getDiffs(false) - if (!_.isEmpty(diff)) { + if (!isEmpty(diff)) { state.settings = diff } } @@ -3892,7 +3927,7 @@ Miew.prototype._embedWebXR = function () { Miew.prototype._initOnSettingsChanged = function () { const on = (props, func) => { - props = _.isArray(props) ? props : [props] + props = isArray(props) ? props : [props] props.forEach((prop) => { this.settings.addEventListener(`change:${prop}`, func) }) @@ -4089,7 +4124,7 @@ Miew.prototype.select = function (expression, append) { } let sel = expression - if (_.isString(expression)) { + if (isString(expression)) { sel = selectors.parse(expression).selector } @@ -4118,7 +4153,7 @@ Miew.prototype.view = function (expression) { function encode() { const pos = pivot.position const scale = self._objectControls.getScale() / settings.now.radiusToFit - const euler = new THREE.Euler() + const euler = new Euler() euler.setFromQuaternion(self._objectControls.getOrientation(), eulerOrder) transform = [pos.x, pos.y, pos.z, scale, euler.x, euler.y, euler.z] return VIEW_VERSION + utils.arrayToBase64(transform, Float32Array) @@ -4164,7 +4199,7 @@ Miew.prototype.view = function (expression) { dstView.scale = transform[3] // eslint-disable-line prefer-destructuring dstView.orientation.setFromEuler( - new THREE.Euler(transform[4], transform[5], transform[6], eulerOrder) + new Euler(transform[4], transform[5], transform[6], eulerOrder) ) interpolator.setup(srcView, dstView) @@ -4225,7 +4260,7 @@ Miew.prototype.translate = function (x, y, z) { */ Miew.prototype.rotate = function (x, y, z) { this._objectControls.rotate( - new THREE.Quaternion().setFromEuler(new THREE.Euler(x, y, z, 'XYZ')) + new Quaternion().setFromEuler(new Euler(x, y, z, 'XYZ')) ) this.dispatchEvent({ type: 'transform' }) this._needRender = true @@ -4369,14 +4404,14 @@ Miew.prototype.exportCML = function () { const self = this function extractRotation(m) { - const xAxis = new THREE.Vector3() - const yAxis = new THREE.Vector3() - const zAxis = new THREE.Vector3() + const xAxis = new Vector3() + const yAxis = new Vector3() + const zAxis = new Vector3() m.extractBasis(xAxis, yAxis, zAxis) xAxis.normalize() yAxis.normalize() zAxis.normalize() - const retMat = new THREE.Matrix4() + const retMat = new Matrix4() retMat.identity() retMat.makeBasis(xAxis, yAxis, zAxis) return retMat @@ -4385,8 +4420,8 @@ Miew.prototype.exportCML = function () { function updateCMLData(complex) { const { root } = self._gfx const mat = extractRotation(root.matrixWorld) - const v4 = new THREE.Vector4(0, 0, 0, 0) - const vCenter = new THREE.Vector4(0, 0, 0, 0) + const v4 = new Vector4(0, 0, 0, 0) + const vCenter = new Vector4(0, 0, 0, 0) let xml = null let ap = null @@ -4478,7 +4513,7 @@ Miew.prototype.VERSION = // Uncomment this to get debug trace: // Miew.prototype.debugTracer = new utils.DebugTracer(Miew.prototype); -_.assign( +assign( Miew, /** @lends Miew */ { VERSION: Miew.prototype.VERSION, @@ -4497,24 +4532,20 @@ _.assign( utils, gfx: { Representation - }, + } /** * Third-party libraries packaged together with Miew. * * @property {object} lodash - [Lodash](https://lodash.com/), a modern JavaScript utility library delivering * modularity, performance & extras. - * @property {object} three - [three.js](https://threejs.org/), JavaScript 3D library. + * @property {object} three - [js](https://threejs.org/), JavaScript 3D library. * * @example * var _ = Miew.thirdParty.lodash; - * var opts = _.merge({ ... }, Miew.options.fromURL(window.location.search)); + * var opts = merge({ ... }, Miew.options.fromURL(window.location.search)); * var miew = new Miew(opts); */ - thirdParty: { - lodash: _, - three: THREE - } } ) diff --git a/packages/lib/src/Visual.js b/packages/lib/src/Visual.js index 54dcaa2c..3356cb88 100644 --- a/packages/lib/src/Visual.js +++ b/packages/lib/src/Visual.js @@ -1,12 +1,9 @@ -import * as THREE from 'three' import gfxutils from './gfx/gfxutils' +import { Box3, Sphere, Vector3 } from 'three' const _defaultBoundaries = { - boundingBox: new THREE.Box3( - new THREE.Vector3(-1, -1, -1), - new THREE.Vector3(1, 1, 1) - ), - boundingSphere: new THREE.Sphere(new THREE.Vector3(0, 0, 0), 1) + boundingBox: new Box3(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)), + boundingSphere: new Sphere(new Vector3(0, 0, 0), 1) } class Visual extends gfxutils.RCGroup { diff --git a/packages/lib/src/VolumeVisual.js b/packages/lib/src/VolumeVisual.js index 31082a63..4759cb9d 100644 --- a/packages/lib/src/VolumeVisual.js +++ b/packages/lib/src/VolumeVisual.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' import VolumeMesh from './gfx/VolumeMesh' import VolumeBounds from './gfx/VolumeBounds' import VolumeFarPlane from './gfx/VolumeFarPlane' import Visual from './Visual' import settings from './settings' +import { Sphere } from 'three' class VolumeVisual extends Visual { constructor(name, dataSource) { @@ -25,7 +25,7 @@ class VolumeVisual extends Visual { getBoundaries() { const box = this._dataSource.getBox() - const sphere = new THREE.Sphere() + const sphere = new Sphere() box.getBoundingSphere(sphere) return { diff --git a/packages/lib/src/chem/AromaticLoopsMarker.js b/packages/lib/src/chem/AromaticLoopsMarker.js index 5d27e7ed..ca714b64 100644 --- a/packages/lib/src/chem/AromaticLoopsMarker.js +++ b/packages/lib/src/chem/AromaticLoopsMarker.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' import Bond from './Bond' import Element from './Element' +import { MathUtils, Vector3 } from 'three' const cCrossThresh = 0.1 const cAromaticType = Bond.BondType.AROMATIC @@ -18,9 +18,9 @@ const cAromaticAtoms = [ */ const _coDirVectors = (function () { - const v1Tmp = new THREE.Vector3() - const v2Tmp = new THREE.Vector3() - const cp = new THREE.Vector3() + const v1Tmp = new Vector3() + const v2Tmp = new Vector3() + const cp = new Vector3() return function (v1, v2) { v1Tmp.copy(v1).normalize() v2Tmp.copy(v2).normalize() @@ -47,7 +47,7 @@ function _anotherAtom(bond, currAtom) { function _cosBetween(v1, v2) { const theta = v1.dot(v2) / Math.sqrt(v1.lengthSq() * v2.lengthSq()) - return THREE.MathUtils.clamp(theta, -1, 1) + return MathUtils.clamp(theta, -1, 1) } function _markAromatic(bond) { @@ -62,7 +62,7 @@ class Cycle { update() { const { atoms } = this - const center = new THREE.Vector3() + const center = new Vector3() const nA = atoms.length for (let j = 0; j < nA; ++j) { center.add(atoms[j].position) @@ -215,7 +215,7 @@ class AromaticLoopsMarker { _startCycle(bond) { // start from left to right this._currStart = bond._left - if (this._tryBond(bond, bond._right, new THREE.Vector3())) { + if (this._tryBond(bond, bond._right, new Vector3())) { _insertAscending(this._bondsData[bond._index], this._currIdx) this._cycles[this._currIdx].push(bond._left) } diff --git a/packages/lib/src/chem/Assembly.js b/packages/lib/src/chem/Assembly.js index fcc2b416..edda9924 100644 --- a/packages/lib/src/chem/Assembly.js +++ b/packages/lib/src/chem/Assembly.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' import selectors from './selectors' import BiologicalUnit from './BiologicalUnit' +import { Box3, Sphere, Vector3 } from 'three' /** * Biological assembly. @@ -22,16 +22,16 @@ class Assembly extends BiologicalUnit { const { matrices } = this const oldCenter = this._boundaries.boundingSphere.center const oldRad = this._boundaries.boundingSphere.radius - const boundingBox = (this._boundaries.boundingBox = new THREE.Box3()) + const boundingBox = (this._boundaries.boundingBox = new Box3()) boundingBox.makeEmpty() for (let i = 0, n = matrices.length; i < n; ++i) { boundingBox.expandByPoint(oldCenter.clone().applyMatrix4(matrices[i])) } const newRad = boundingBox.max.distanceTo(boundingBox.min) / 2 + oldRad - const center = new THREE.Vector3() + const center = new Vector3() boundingBox.getCenter(center) - this._boundaries.boundingSphere = new THREE.Sphere().set(center, newRad) + this._boundaries.boundingSphere = new Sphere().set(center, newRad) boundingBox.max.addScalar(oldRad) boundingBox.min.subScalar(oldRad) } @@ -46,7 +46,7 @@ class Assembly extends BiologicalUnit { /** * Add a transformation matrix. - * @param {THREE.Matrix4} matrix - transformation matrix + * @param {Matrix4} matrix - transformation matrix */ addMatrix(matrix) { this.matrices[this.matrices.length] = matrix diff --git a/packages/lib/src/chem/Atom.js b/packages/lib/src/chem/Atom.js index ff3cad5e..47bf1f07 100644 --- a/packages/lib/src/chem/Atom.js +++ b/packages/lib/src/chem/Atom.js @@ -4,7 +4,7 @@ * @param {Residue} residue - (required) Residue containing the atom * @param {string} name - (required) Name, unique in the residue * @param {Element} type - (required) Chemical element reference - * @param {THREE.Vector3} position - Registered coordinates + * @param {Vector3} position - Registered coordinates * * @param {number} role - Role of atom inside monomer: Lead and wing are particularity interesting * @param {boolean} het - Non-standard residue indicator diff --git a/packages/lib/src/chem/BiologicalUnit.js b/packages/lib/src/chem/BiologicalUnit.js index 15fad257..1b6e9449 100644 --- a/packages/lib/src/chem/BiologicalUnit.js +++ b/packages/lib/src/chem/BiologicalUnit.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import selectors from './selectors' +import { Box3, Sphere, Vector3 } from 'three' /** * Basic biological unit class. @@ -12,8 +12,8 @@ class BiologicalUnit { this._complex = complex this._selector = selectors.keyword('All')() this._boundaries = { - boundingBox: new THREE.Box3(), - boundingSphere: new THREE.Sphere() + boundingBox: new Box3(), + boundingSphere: new Sphere() } } @@ -26,10 +26,10 @@ class BiologicalUnit { boundingBox.makeEmpty() if (n === 1) { boundingBox.expandByPoint(atoms[0].position) - const bbc = new THREE.Vector3() + const bbc = new Vector3() boundingBox.getCenter(bbc) const s = 2 * atoms[0].element.radius - boundingBox.setFromCenterAndSize(bbc, new THREE.Vector3(s, s, s)) + boundingBox.setFromCenterAndSize(bbc, new Vector3(s, s, s)) } else { for (let i = 0; i < n; ++i) { if (selector.includesAtom(atoms[i])) { @@ -40,7 +40,7 @@ class BiologicalUnit { // Build bounding sphere let radiusSquared = 0.0 - const center = new THREE.Vector3() + const center = new Vector3() boundingBox.getCenter(center) if (n === 1) { this._boundaries.boundingSphere.set(center, atoms[0].element.radius) diff --git a/packages/lib/src/chem/Chain.js b/packages/lib/src/chem/Chain.js index b014d881..9589e2b5 100644 --- a/packages/lib/src/chem/Chain.js +++ b/packages/lib/src/chem/Chain.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' import Residue from './Residue' import ResidueType from './ResidueType' +import { Vector3 } from 'three' /** * Residues in chain are either amino acid either nucleic acid (and water) @@ -105,9 +105,9 @@ class Chain { // fix very first wing if (residues.length > 1 && residues[1]._wingVector) { const p = residues[1]._wingVector - residues[0]._wingVector = new THREE.Vector3(p.x, p.y, p.z) + residues[0]._wingVector = new Vector3(p.x, p.y, p.z) } else if (residues.length > 0) { - residues[0]._wingVector = new THREE.Vector3(1, 0, 0) + residues[0]._wingVector = new Vector3(1, 0, 0) } } @@ -138,9 +138,7 @@ class Chain { } frameRes[residues[0]._index]._wingVector = - n > 1 - ? frameRes[residues[1]._index]._wingVector - : new THREE.Vector3(1, 0, 0) + n > 1 ? frameRes[residues[1]._index]._wingVector : new Vector3(1, 0, 0) } /** diff --git a/packages/lib/src/chem/Complex.js b/packages/lib/src/chem/Complex.js index 227a96ca..bed881d6 100644 --- a/packages/lib/src/chem/Complex.js +++ b/packages/lib/src/chem/Complex.js @@ -1,4 +1,3 @@ -import * as THREE from 'three' import logger from '../utils/logger' import Atom from './Atom' import Chain from './Chain' @@ -15,6 +14,7 @@ import selectors from './selectors' import VoxelWorld from './VoxelWorld' import SecondaryStructureMap from './SecondaryStructureMap' import StructuralElement from './StructuralElement' +import { Vector3 } from 'three' const VOXEL_SIZE = 5.0 @@ -759,7 +759,7 @@ class Complex { try { this._voxelWorld = new VoxelWorld( this.getDefaultBoundaries().boundingBox, - new THREE.Vector3(VOXEL_SIZE, VOXEL_SIZE, VOXEL_SIZE) + new Vector3(VOXEL_SIZE, VOXEL_SIZE, VOXEL_SIZE) ) this._voxelWorld.addAtoms(this) } catch (e) { diff --git a/packages/lib/src/chem/Residue.js b/packages/lib/src/chem/Residue.js index 74525e81..4b676a58 100644 --- a/packages/lib/src/chem/Residue.js +++ b/packages/lib/src/chem/Residue.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' import Atom from './Atom' import Element from './Element' +import { Vector3 } from 'three' const cNucleicControlNames = ["C3'", 'C3*', 'P', 'H5T', 'H3T'] const cNucleicWing1Names = ['OP1', 'O1P'] @@ -230,7 +230,7 @@ class Residue { const bFirstInChain = prev === null const lp = getAtomPosition(this._leadAtom) - const currLeadPos = new THREE.Vector3(lp.x, lp.y, lp.z) + const currLeadPos = new Vector3(lp.x, lp.y, lp.z) if (chainAsNucleic) { this._detectLeadWing(dst, nextRes, getAtomPosition) return diff --git a/packages/lib/src/chem/SGroup.js b/packages/lib/src/chem/SGroup.js index 5866d95a..f881a025 100644 --- a/packages/lib/src/chem/SGroup.js +++ b/packages/lib/src/chem/SGroup.js @@ -1,11 +1,11 @@ -import * as THREE from 'three' +import { Vector3 } from 'three' /** * Atom measurements. * * @param {string} id - SGroup id * @param {string} name - Name of the group - * @param {THREE.Vector3} position - Registered coordinates + * @param {Vector3} position - Registered coordinates * @param {array} atoms - Atoms group consists of * @param {object} saveNode - XML node from file for saving * @@ -16,7 +16,7 @@ class SGroup { constructor(id, name, position, atoms, saveNode) { this._id = id this._name = name - this._position = position || new THREE.Vector3() + this._position = position || new Vector3() this._atoms = atoms || [] this._charge = 0 // default group charge this._repeat = 1 // how many times group repeated: always > 0 @@ -46,8 +46,8 @@ class SGroup { return // nothing to do if we are not relative } - const bLow = new THREE.Vector3(nLimon, nLimon, nLimon) - const bHight = new THREE.Vector3(-nLimon, -nLimon, -nLimon) + const bLow = new Vector3(nLimon, nLimon, nLimon) + const bHight = new Vector3(-nLimon, -nLimon, -nLimon) for (let j = 0, n = this._atoms.length; j < n; j++) { const aPos = this._atoms[j].position bLow.set( diff --git a/packages/lib/src/chem/Volume.js b/packages/lib/src/chem/Volume.js index 98e34f61..708dd51d 100644 --- a/packages/lib/src/chem/Volume.js +++ b/packages/lib/src/chem/Volume.js @@ -1,5 +1,13 @@ -import * as THREE from 'three' import utils from '../utils' +import { + ClampToEdgeWrapping, + DataTexture, + LinearFilter, + LuminanceFormat, + UnsignedByteType, + UVMapping, + Vector3 +} from 'three' function pow2ceil(v) { let p = 2 @@ -133,9 +141,9 @@ class Volume { } getCellSize() { - const boxSize = new THREE.Vector3() + const boxSize = new Vector3() this._box.getSize(boxSize) - const res = new THREE.Vector3() + const res = new Vector3() res.x = this._dimX > 1 ? boxSize.x / (this._dimX - 1) : 0 res.y = this._dimY > 1 ? boxSize.y / (this._dimY - 1) : 0 res.z = this._dimZ > 1 ? boxSize.z / (this._dimZ - 1) : 0 @@ -161,7 +169,7 @@ class Volume { // gradient axis scaling values and averaging factors, to correctly // calculate the gradient for volumes with irregular cell spacing - const vs = new THREE.Vector3(-0.5 / vl.x, -0.5 / vl.y, -0.5 / vl.z) + const vs = new Vector3(-0.5 / vl.x, -0.5 / vl.y, -0.5 / vl.z) // TODO Check for intended bug in VMD (min is zero) function clamp(val, min, max) { @@ -298,17 +306,17 @@ class Volume { } } - const texture = new THREE.DataTexture( + const texture = new DataTexture( data, width, height, - THREE.LuminanceFormat, - THREE.UnsignedByteType, - THREE.UVMapping, - THREE.ClampToEdgeWrapping, - THREE.ClampToEdgeWrapping, - THREE.LinearFilter, - THREE.LinearFilter + LuminanceFormat, + UnsignedByteType, + UVMapping, + ClampToEdgeWrapping, + ClampToEdgeWrapping, + LinearFilter, + LinearFilter ) texture.needsUpdate = true return texture diff --git a/packages/lib/src/chem/VoxelWorld.js b/packages/lib/src/chem/VoxelWorld.js index 994cad4c..b05bfd0d 100644 --- a/packages/lib/src/chem/VoxelWorld.js +++ b/packages/lib/src/chem/VoxelWorld.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import utils from '../utils' +import { Vector2, Vector3 } from 'three' /** * Calculate min & max radius of a sphere slice between zMin & zMax @@ -68,13 +68,13 @@ function _getCircleSliceRadiusRange(center, radius, yMin, yMax) { class VoxelWorld { constructor(box, vCellSizeHint) { this._box = box.clone() - const size = new THREE.Vector3() + const size = new Vector3() box.getSize(size) this._count = size .clone() .divide(vCellSizeHint) .floor() - .max(new THREE.Vector3(1, 1, 1)) + .max(new Vector3(1, 1, 1)) this._last = this._count.clone().subScalar(1) this._cellSize = size.clone().divide(this._count) this._cellInnerR = @@ -126,9 +126,9 @@ class VoxelWorld { * @param {Vector3} point - a point in 3D * @returns {number} - index of voxel */ - static _zero = new THREE.Vector3(0, 0, 0) + static _zero = new Vector3(0, 0, 0) - static _voxel = new THREE.Vector3() + static _voxel = new Vector3() _findVoxel(point) { const zero = VoxelWorld._zero @@ -163,11 +163,11 @@ class VoxelWorld { * @param {function(number,bool)} process - function to call that takes voxel index and boolean isInside */ - static _xRange = new THREE.Vector2() + static _xRange = new Vector2() - static _yRange = new THREE.Vector2() + static _yRange = new Vector2() - static _zRange = new THREE.Vector2() + static _zRange = new Vector2() _forEachVoxelWithinRadius(center, radius, process) { const xRange = VoxelWorld._xRange @@ -265,7 +265,7 @@ class VoxelWorld { * @param {function(number,bool)} process - function to call that takes voxel index and boolean isInside */ - static _vCenter = new THREE.Vector3() + static _vCenter = new Vector3() _forEachVoxelWithinRadiusSimple(center, radius, process) { const xRange = VoxelWorld._xRange diff --git a/packages/lib/src/gfx/Axes.js b/packages/lib/src/gfx/Axes.js index b0b82aa9..00270e25 100644 --- a/packages/lib/src/gfx/Axes.js +++ b/packages/lib/src/gfx/Axes.js @@ -1,19 +1,19 @@ -import * as THREE from 'three' +import { AxesHelper, PerspectiveCamera, Scene, Vector2 } from 'three' class Axes { constructor(target, targetCamera) { this._target = target this._targetCamera = targetCamera - this._camera = new THREE.PerspectiveCamera( + this._camera = new PerspectiveCamera( targetCamera.fov, targetCamera.aspect, 1, 100 ) - this._object = new THREE.AxesHelper(1) - this._scene = new THREE.Scene() + this._object = new AxesHelper(1) + this._scene = new Scene() this._scene.add(this._object) - this._full = new THREE.Vector2() + this._full = new Vector2() this._update() } diff --git a/packages/lib/src/gfx/CSS2DObject.js b/packages/lib/src/gfx/CSS2DObject.js index 2517ddba..3af5f2a5 100644 --- a/packages/lib/src/gfx/CSS2DObject.js +++ b/packages/lib/src/gfx/CSS2DObject.js @@ -2,9 +2,9 @@ * @author mrdoob / http://mrdoob.com/ */ -import * as THREE from 'three' +import { Object3D } from 'three' -class CSS2DObject extends THREE.Object3D { +class CSS2DObject extends Object3D { constructor(element) { super() const self = this diff --git a/packages/lib/src/gfx/CSS2DRenderer.js b/packages/lib/src/gfx/CSS2DRenderer.js index 94c5b2d0..b7296730 100644 --- a/packages/lib/src/gfx/CSS2DRenderer.js +++ b/packages/lib/src/gfx/CSS2DRenderer.js @@ -2,10 +2,10 @@ * @author mrdoob / http://mrdoob.com/ */ -import * as THREE from 'three' import CSS2DObject from './CSS2DObject' +import { Matrix4, Vector3, Color, MathUtils } from 'three' -const tempColor = new THREE.Color() +const tempColor = new Color() class CSS2DRenderer { constructor() { @@ -14,9 +14,9 @@ class CSS2DRenderer { this._widthHalf = 0 this._heightHalf = 0 - this._vector = new THREE.Vector3() - this._viewMatrix = new THREE.Matrix4() - this._projectionMatrix = new THREE.Matrix4() + this._vector = new Vector3() + this._viewMatrix = new Matrix4() + this._projectionMatrix = new Matrix4() this._domElement = document.createElement('div') this._domElement.style.overflow = 'hidden' @@ -67,7 +67,7 @@ class CSS2DRenderer { object.userData !== undefined && object.userData.offset !== undefined ) { - const localOffset = new THREE.Vector3( + const localOffset = new Vector3( object.userData.offset.x, object.userData.offset.y, 0 @@ -90,7 +90,7 @@ class CSS2DRenderer { element.style.background = colorAsHex(object.userData.background) } } else { - const fogFactor = THREE.MathUtils.smoothstep( + const fogFactor = MathUtils.smoothstep( -this._vector.z, scene.fog.near, scene.fog.far diff --git a/packages/lib/src/gfx/FrameInfo.js b/packages/lib/src/gfx/FrameInfo.js index 1d97331f..0613945e 100644 --- a/packages/lib/src/gfx/FrameInfo.js +++ b/packages/lib/src/gfx/FrameInfo.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import SecondaryStructureColorer from './colorers/SecondaryStructureColorer' +import { Vector3 } from 'three' const cDataOffset = 12 const cFirstMask = 0x0fffff00 @@ -333,7 +333,7 @@ class FrameInfo { * Returns link to atom pos vector, clone it if needed */ - static _vec = new THREE.Vector3() + static _vec = new Vector3() getAtomPos(atomIdx) { const vec = FrameInfo._vec diff --git a/packages/lib/src/gfx/RCGroup.js b/packages/lib/src/gfx/RCGroup.js index d9d6babb..629dc07b 100644 --- a/packages/lib/src/gfx/RCGroup.js +++ b/packages/lib/src/gfx/RCGroup.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' +import { Group } from 'three' -class RCGroup extends THREE.Group { +class RCGroup extends Group { raycast(raycaster, intersects) { if (!this.visible) { return diff --git a/packages/lib/src/gfx/Representation.js b/packages/lib/src/gfx/Representation.js index 05de487c..74bb79d8 100644 --- a/packages/lib/src/gfx/Representation.js +++ b/packages/lib/src/gfx/Representation.js @@ -1,11 +1,11 @@ -import _ from 'lodash' -import * as THREE from 'three' import UberMaterial from './shaders/UberMaterial' import gfxutils from './gfxutils' import meshutils from './meshutils' import settings from '../settings' import materials from './materials' import chem from '../chem' +import { Group } from 'three' +import { isEqual } from 'lodash' const { selectors } = chem @@ -99,7 +99,7 @@ class Representation { if (this.geo && 'getSubset' in this.geo) { const meshes = this.geo.getSubset(mask) if (meshes && meshes.length > 0) { - sg = new THREE.Group() + sg = new Group() sg.matrixAutoUpdate = false sg.matrix = this.geo.matrix @@ -179,7 +179,7 @@ class Representation { // modify mode if (repSettings.mode) { const newMode = repSettings.mode - if (!_.isEqual(this.mode.identify(), newMode)) { + if (!isEqual(this.mode.identify(), newMode)) { diff.mode = newMode this.setMode(mode) } @@ -188,7 +188,7 @@ class Representation { // modify colorer if (repSettings.colorer) { const newColorer = repSettings.colorer - if (!_.isEqual(this.colorer.identify(), newColorer)) { + if (!isEqual(this.colorer.identify(), newColorer)) { diff.colorer = newColorer this.colorer = color } @@ -197,7 +197,7 @@ class Representation { // modify material if (repSettings.material) { const newMaterial = repSettings.material - if (!_.isEqual(this.materialPreset.id, newMaterial)) { + if (!isEqual(this.materialPreset.id, newMaterial)) { diff.material = newMaterial this.setMaterialPreset(materials.get(repSettings.material)) } diff --git a/packages/lib/src/gfx/ViewInterpolator.js b/packages/lib/src/gfx/ViewInterpolator.js index 1dc2c7f7..f6510996 100644 --- a/packages/lib/src/gfx/ViewInterpolator.js +++ b/packages/lib/src/gfx/ViewInterpolator.js @@ -1,11 +1,11 @@ -import * as THREE from 'three' import settings from '../settings' +import { Quaternion, Vector3 } from 'three' class View { constructor() { - this.position = new THREE.Vector3(0, 0, 0) + this.position = new Vector3(0, 0, 0) this.scale = 1 - this.orientation = new THREE.Quaternion(0, 0, 0, 1) + this.orientation = new Quaternion(0, 0, 0, 1) } set(position, scale, orientation) { diff --git a/packages/lib/src/gfx/VolumeBounds.js b/packages/lib/src/gfx/VolumeBounds.js index 0e33aeda..5fcf8474 100644 --- a/packages/lib/src/gfx/VolumeBounds.js +++ b/packages/lib/src/gfx/VolumeBounds.js @@ -1,5 +1,11 @@ -import * as THREE from 'three' import gfxutils from './gfxutils' +import { + BufferAttribute, + BufferGeometry, + LineBasicMaterial, + LineSegments, + Vector3 +} from 'three' function _flattenArray(input) { const n = input.length @@ -26,24 +32,20 @@ class VolumeBounds { const { delta } = volInfo // {x: XY, y : XZ, z: YZ} const { obtuseAngle } = volInfo // 1 - obtuse, 0 - acute - const bSize = new THREE.Vector3() + const bSize = new Vector3() bBox.getSize(bSize) bSize.multiplyScalar(0.5) const offsetVert = this._getBaseVertices(delta, obtuseAngle) - const geometry = new THREE.BufferGeometry() + const geometry = new BufferGeometry() const vertices = [] for (let i = 0; i < 4; i++) { vertices.push(offsetVert[i].clone().multiply(bSize)) vertices.push(offsetVert[(i + 1) % 4].clone().multiply(bSize)) } - const translation = new THREE.Vector3( - 2 * bSize.x * (1 - delta.x - delta.y), - 0, - 0 - ) + const translation = new Vector3(2 * bSize.x * (1 - delta.x - delta.y), 0, 0) for (let i = 0; i < 8; i++) { vertices.push(vertices[i].clone().add(translation)) } @@ -51,19 +53,16 @@ class VolumeBounds { vertices.push(vertices[i * 2].clone()) vertices.push(vertices[i * 2 + 8].clone()) } - const center = new THREE.Vector3() + const center = new Vector3() bBox.getCenter(center) vertices.forEach((vertex) => vertex.add(center)) // pivot shift const flatVertices = _flattenArray(vertices) - geometry.setAttribute( - 'position', - new THREE.BufferAttribute(flatVertices, 3) - ) + geometry.setAttribute('position', new BufferAttribute(flatVertices, 3)) - this._lines = new THREE.LineSegments( + this._lines = new LineSegments( geometry, - new THREE.LineBasicMaterial({ color: 0xffffff }) + new LineBasicMaterial({ color: 0xffffff }) ) this._lines.layers.set(gfxutils.LAYERS.VOLUME) } @@ -81,22 +80,22 @@ class VolumeBounds { } const offsetVert = [ - new THREE.Vector3( + new Vector3( -1 + 2 * (proj('XZ', 1) + proj('XY', 1)), -1 + 2 * proj('YZ', 1), -1 ), - new THREE.Vector3( + new Vector3( -1 + 2 * (proj('XZ', -1) + proj('XY', 1)), -1 + 2 * proj('YZ', -1), 1 ), - new THREE.Vector3( + new Vector3( -1 + 2 * (proj('XZ', -1) + proj('XY', -1)), 1 - 2 * proj('YZ', 1), 1 ), - new THREE.Vector3( + new Vector3( -1 + 2 * (proj('XZ', 1) + proj('XY', -1)), 1 - 2 * proj('YZ', -1), -1 diff --git a/packages/lib/src/gfx/VolumeFarPlane.js b/packages/lib/src/gfx/VolumeFarPlane.js index 3990a7bd..5fec4a59 100644 --- a/packages/lib/src/gfx/VolumeFarPlane.js +++ b/packages/lib/src/gfx/VolumeFarPlane.js @@ -1,7 +1,13 @@ -import * as THREE from 'three' import VolumeMaterial from './shaders/VolumeMaterial' import meshes from './meshes/meshes' import gfxutils from './gfxutils' +import { + BufferAttribute, + BufferGeometry, + MathUtils, + Matrix4, + Vector4 +} from 'three' // Thes geometric far plane is required for correct filling in the BFTexture in case, when far plane cuts the volume // cube. In cut place of cube there is no correct data in BFTexture and volume rendering integral is calculated @@ -16,7 +22,7 @@ class VolumeFarPlane { this._plane = new meshes.Mesh(planeGeo, mat) this._plane.frustumCulled = false this._plane.doubleSided = true - const matWorldToVolume = new THREE.Matrix4() + const matWorldToVolume = new Matrix4() this._plane._onBeforeRender = function ( _renderer, @@ -32,7 +38,7 @@ class VolumeFarPlane { } // count point in world at farplane place - const planeCamPos = new THREE.Vector4(0, 0, -(camera.far - 0.1), 1) + const planeCamPos = new Vector4(0, 0, -(camera.far - 0.1), 1) planeCamPos.applyMatrix4(camera.matrixWorld) // recalc matrices to make plane be placed as farplane in the World relative to camera @@ -53,7 +59,7 @@ class VolumeFarPlane { material.uniforms.aspectRatio.value = camera.aspect material.uniforms.farZ.value = camera.far material.uniforms.tanHalfFOV.value = Math.tan( - THREE.MathUtils.DEG2RAD * 0.5 * camera.fov + MathUtils.DEG2RAD * 0.5 * camera.fov ) material.uniforms.matWorld2Volume.value = matWorldToVolume } @@ -63,7 +69,7 @@ class VolumeFarPlane { } _initPlaneGeo(width, height) { - const planeGeo = new THREE.BufferGeometry() + const planeGeo = new BufferGeometry() width = width || 1 height = height || 1 @@ -83,7 +89,7 @@ class VolumeFarPlane { 0 ]) - planeGeo.setAttribute('position', new THREE.BufferAttribute(vertices, 3)) + planeGeo.setAttribute('position', new BufferAttribute(vertices, 3)) planeGeo.setIndex([0, 2, 1, 2, 3, 1]) return planeGeo diff --git a/packages/lib/src/gfx/VolumeMesh.js b/packages/lib/src/gfx/VolumeMesh.js index d1cc3cab..45d5922e 100644 --- a/packages/lib/src/gfx/VolumeMesh.js +++ b/packages/lib/src/gfx/VolumeMesh.js @@ -1,15 +1,23 @@ -import * as THREE from 'three' import VolumeMaterial from './shaders/VolumeMaterial' import settings from '../settings' - -class VolumeMesh extends THREE.Mesh { +import { + BufferAttribute, + BufferGeometry, + Matrix4, + Mesh, + Plane, + Vector3, + Vector4 +} from 'three' + +class VolumeMesh extends Mesh { volumeInfo = {} // data for noise filter constructor() { - const geo = new THREE.BufferGeometry() + const geo = new BufferGeometry() super(geo) - this.clipPlane = new THREE.Plane() - const size = new THREE.Vector3(0.5, 0.5, 0.5) + this.clipPlane = new Plane() + const size = new Vector3(0.5, 0.5, 0.5) this.size = size this.cullFlag = [ @@ -30,35 +38,35 @@ class VolumeMesh extends THREE.Mesh { ] this.faces = [ - { indices: [], norm: new THREE.Vector3(0, 0, -1) }, - { indices: [], norm: new THREE.Vector3(0, 0, 1) }, - { indices: [], norm: new THREE.Vector3(0, -1, 0) }, - { indices: [], norm: new THREE.Vector3(0, 1, 0) }, - { indices: [], norm: new THREE.Vector3(-1, 0, 0) }, - { indices: [], norm: new THREE.Vector3(1, 0, 0) }, - { indices: [], norm: new THREE.Vector3(0, 0, 0) } + { indices: [], norm: new Vector3(0, 0, -1) }, + { indices: [], norm: new Vector3(0, 0, 1) }, + { indices: [], norm: new Vector3(0, -1, 0) }, + { indices: [], norm: new Vector3(0, 1, 0) }, + { indices: [], norm: new Vector3(-1, 0, 0) }, + { indices: [], norm: new Vector3(1, 0, 0) }, + { indices: [], norm: new Vector3(0, 0, 0) } ] this.vertices = [ - new THREE.Vector3(-size.x, -size.y, -size.z), - new THREE.Vector3(-size.x, size.y, -size.z), - new THREE.Vector3(size.x, -size.y, -size.z), - new THREE.Vector3(size.x, size.y, -size.z), - new THREE.Vector3(-size.x, -size.y, size.z), - new THREE.Vector3(-size.x, size.y, size.z), - new THREE.Vector3(size.x, -size.y, size.z), - new THREE.Vector3(size.x, size.y, size.z), - new THREE.Vector3(0.0, 0.0, 0.0), // Placeholder for section - new THREE.Vector3(0.0, 0.0, 0.0), - new THREE.Vector3(0.0, 0.0, 0.0), - new THREE.Vector3(0.0, 0.0, 0.0), - new THREE.Vector3(0.0, 0.0, 0.0), - new THREE.Vector3(0.0, 0.0, 0.0) + new Vector3(-size.x, -size.y, -size.z), + new Vector3(-size.x, size.y, -size.z), + new Vector3(size.x, -size.y, -size.z), + new Vector3(size.x, size.y, -size.z), + new Vector3(-size.x, -size.y, size.z), + new Vector3(-size.x, size.y, size.z), + new Vector3(size.x, -size.y, size.z), + new Vector3(size.x, size.y, size.z), + new Vector3(0.0, 0.0, 0.0), // Placeholder for section + new Vector3(0.0, 0.0, 0.0), + new Vector3(0.0, 0.0, 0.0), + new Vector3(0.0, 0.0, 0.0), + new Vector3(0.0, 0.0, 0.0), + new Vector3(0.0, 0.0, 0.0) ] geo.setAttribute( 'position', - new THREE.BufferAttribute(new Float32Array(this.vertices.length * 3), 3) + new BufferAttribute(new Float32Array(this.vertices.length * 3), 3) ) this.name = 'VolumeMesh' @@ -95,7 +103,7 @@ class VolumeMesh extends THREE.Mesh { static _edgeIntersections = (function () { const edgeIntersections = [] for (let j = 0; j < 12; ++j) { - edgeIntersections.push(new THREE.Vector3()) + edgeIntersections.push(new Vector3()) } return edgeIntersections })() @@ -120,7 +128,7 @@ class VolumeMesh extends THREE.Mesh { const cornerMark = [0, 0, 0, 0, 0, 0, 0, 0] const edgeMark = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] - const curEdge = new THREE.Vector3() + const curEdge = new Vector3() let curEdgeInter = null function CheckX() { @@ -217,8 +225,8 @@ class VolumeMesh extends THREE.Mesh { this.faces[6] = face - const diff = new THREE.Vector3() - const coplanarPoint = new THREE.Vector3() + const diff = new Vector3() + const coplanarPoint = new Vector3() this.clipPlane.coplanarPoint(coplanarPoint) for (i = 0; i < vert.length; ++i) { this.cullFlag[i] = false @@ -260,7 +268,7 @@ class VolumeMesh extends THREE.Mesh { const vert = this.vertices const angle = [] - const dir = new THREE.Vector3() + const dir = new Vector3() for (i = 1; i < face.indices.length; ++i) { dir.subVectors(vert[face.indices[i]], vert[face.indices[0]]) dir.normalize() @@ -306,9 +314,9 @@ class VolumeMesh extends THREE.Mesh { this._collectVertices(this.faces[4], (vertex) => vertex.x === -size.x) this._collectVertices(this.faces[5], (vertex) => vertex.x === size.x) - const vCenter = new THREE.Vector3() - const vRight = new THREE.Vector3() - const vDir = new THREE.Vector3() + const vCenter = new Vector3() + const vRight = new Vector3() + const vDir = new Vector3() for (faceIdx = 0; faceIdx < this.faces.length; ++faceIdx) { face = this.faces[faceIdx] @@ -362,7 +370,7 @@ class VolumeMesh extends THREE.Mesh { } } - this.geometry.setIndex(new THREE.BufferAttribute(indices, 1)) + this.geometry.setIndex(new BufferAttribute(indices, 1)) } setDataSource(dataSource) { @@ -406,15 +414,15 @@ class VolumeMesh extends THREE.Mesh { static _nearClipPlaneOffset = 0.2 - static _pos = new THREE.Vector3() + static _pos = new Vector3() - static _norm = new THREE.Vector3() + static _norm = new Vector3() - static _norm4D = new THREE.Vector4() + static _norm4D = new Vector4() - static _matrixWorldToLocal = new THREE.Matrix4() + static _matrixWorldToLocal = new Matrix4() - static _clipPlane = new THREE.Plane() + static _clipPlane = new Plane() rebuild(camera) { const nearClipPlaneOffset = VolumeMesh._nearClipPlaneOffset diff --git a/packages/lib/src/gfx/capabilities.js b/packages/lib/src/gfx/capabilities.js index 1f2fc04a..c172823a 100644 --- a/packages/lib/src/gfx/capabilities.js +++ b/packages/lib/src/gfx/capabilities.js @@ -3,7 +3,7 @@ export default { /** * - * @param {THREE.WebGLRenderer} renderer + * @param {WebGLRenderer} renderer */ init(renderer) { this.precision = renderer.capabilities.getMaxPrecision('highp') diff --git a/packages/lib/src/gfx/colorers/Colorer.js b/packages/lib/src/gfx/colorers/Colorer.js index 53a07d26..8f913333 100644 --- a/packages/lib/src/gfx/colorers/Colorer.js +++ b/packages/lib/src/gfx/colorers/Colorer.js @@ -1,7 +1,7 @@ -import _ from 'lodash' import settings from '../../settings' import utils from '../../utils' import palettes from '../palettes' +import { merge, isEmpty } from 'lodash' /** * Create new colorer. @@ -26,7 +26,7 @@ class Colorer { * Colorer options inherited (prototyped) from defaults. * @type {object} */ - this.opts = _.merge( + this.opts = merge( utils.deriveDeep(settings.now.colorers[this.id], true), opts ) @@ -45,7 +45,7 @@ class Colorer { */ identify() { const diff = utils.objectsDiff(this.opts, settings.now.colorers[this.id]) - if (!_.isEmpty(diff)) { + if (!isEmpty(diff)) { return [this.id, diff] } return this.id diff --git a/packages/lib/src/gfx/geometries/ChunkedObjectsGeometry.js b/packages/lib/src/gfx/geometries/ChunkedObjectsGeometry.js index 53d9fa5c..7537e024 100644 --- a/packages/lib/src/gfx/geometries/ChunkedObjectsGeometry.js +++ b/packages/lib/src/gfx/geometries/ChunkedObjectsGeometry.js @@ -1,10 +1,10 @@ -import _ from 'lodash' -import * as THREE from 'three' import utils from '../../utils' +import { BufferAttribute, BufferGeometry, Color, Mesh } from 'three' +import { fill } from 'lodash' const MAX_IDC_16BIT = 65535 const VEC_SIZE = 3 -const tmpColor = new THREE.Color() +const tmpColor = new Color() /** * This class represents geometry which consists of separate chunks. @@ -13,7 +13,7 @@ const tmpColor = new THREE.Color() * @constructor */ -class ChunkedObjectsGeometry extends THREE.BufferGeometry { +class ChunkedObjectsGeometry extends BufferGeometry { constructor(chunkGeo, chunksCount) { super() @@ -58,14 +58,14 @@ class ChunkedObjectsGeometry extends THREE.BufferGeometry { const chunkSize = this._chunkSize for (let i = 0, n = chunkIndices.length; i < n; ++i) { const left = chunkIndices[i] * chunkSize - _.fill(alphaArr, value, left, left + chunkSize) + fill(alphaArr, value, left, left + chunkSize) } this.getAttribute('alphaColor').needsUpdate = true } raycast(raycaster, intersects) { const inters = [] - const mesh = new THREE.Mesh() + const mesh = new Mesh() mesh.geometry = this mesh.raycast(raycaster, inters) const facesPerChunk = this._chunkGeo.index.count / 3 @@ -80,7 +80,7 @@ class ChunkedObjectsGeometry extends THREE.BufferGeometry { getSubset(chunkIndices) { const instanceCount = chunkIndices.length - const geom = new THREE.BufferGeometry() + const geom = new BufferGeometry() this._init.call(geom, this._chunkGeo, instanceCount) const srcPos = this._positions @@ -122,7 +122,7 @@ class ChunkedObjectsGeometry extends THREE.BufferGeometry { this._normals = utils.allocateTyped(Float32Array, pointsCount * VEC_SIZE) this._colors = utils.allocateTyped(Float32Array, pointsCount * VEC_SIZE) const alpha = (this._alpha = utils.allocateTyped(Float32Array, pointsCount)) - _.fill(alpha, 1.0) + fill(alpha, 1.0) for (let i = 0; i < chunksCount; ++i) { const offset = i * chunkIndexSize @@ -133,20 +133,14 @@ class ChunkedObjectsGeometry extends THREE.BufferGeometry { } } - this.setIndex(new THREE.BufferAttribute(this._index, 1)) + this.setIndex(new BufferAttribute(this._index, 1)) this.setAttribute( 'position', - new THREE.BufferAttribute(this._positions, VEC_SIZE) + new BufferAttribute(this._positions, VEC_SIZE) ) - this.setAttribute( - 'normal', - new THREE.BufferAttribute(this._normals, VEC_SIZE) - ) - this.setAttribute( - 'color', - new THREE.BufferAttribute(this._colors, VEC_SIZE) - ) - this.setAttribute('alphaColor', new THREE.BufferAttribute(alpha, 1)) + this.setAttribute('normal', new BufferAttribute(this._normals, VEC_SIZE)) + this.setAttribute('color', new BufferAttribute(this._colors, VEC_SIZE)) + this.setAttribute('alphaColor', new BufferAttribute(alpha, 1)) } } export default ChunkedObjectsGeometry diff --git a/packages/lib/src/gfx/geometries/ContactSurface.js b/packages/lib/src/gfx/geometries/ContactSurface.js index 753e3e61..de16f0b0 100644 --- a/packages/lib/src/gfx/geometries/ContactSurface.js +++ b/packages/lib/src/gfx/geometries/ContactSurface.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import utils from '../../utils' +import { Vector3 } from 'three' /** * Modifed from SpatialHash @@ -204,9 +204,9 @@ function ContactSurface(packedArrays, boundaries, params, _indexList) { let neighbours // Vectors for Torus Projection - const mid = new THREE.Vector3(0.0, 0.0, 0.0) - const n1 = new THREE.Vector3(0.0, 0.0, 0.0) - const n2 = new THREE.Vector3(0.0, 0.0, 0.0) + const mid = new Vector3(0.0, 0.0, 0.0) + const n1 = new Vector3(0.0, 0.0, 0.0) + const n2 = new Vector3(0.0, 0.0, 0.0) let ngTorus diff --git a/packages/lib/src/gfx/geometries/CrossGeometry.js b/packages/lib/src/gfx/geometries/CrossGeometry.js index db564633..db3f5011 100644 --- a/packages/lib/src/gfx/geometries/CrossGeometry.js +++ b/packages/lib/src/gfx/geometries/CrossGeometry.js @@ -1,18 +1,18 @@ -import * as THREE from 'three' import ChunkedLinesGeometry from './ChunkedLinesGeometry' import SphereCollisionGeo from './SphereCollisionGeo' +import { Vector3 } from 'three' const vectors = [ - new THREE.Vector3(1, 0, 0), - new THREE.Vector3(-1, 0, 0), - new THREE.Vector3(0, 1, 0), - new THREE.Vector3(0, -1, 0), - new THREE.Vector3(0, 0, 1), - new THREE.Vector3(0, 0, -1) + new Vector3(1, 0, 0), + new Vector3(-1, 0, 0), + new Vector3(0, 1, 0), + new Vector3(0, -1, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1) ] const vecCount = vectors.length -const tempPos1 = new THREE.Vector3() -const tempPos2 = new THREE.Vector3() +const tempPos1 = new Vector3() +const tempPos2 = new Vector3() class CrossGeometry extends SphereCollisionGeo(ChunkedLinesGeometry) { constructor(chunksCount) { diff --git a/packages/lib/src/gfx/geometries/CylinderBufferGeometry.js b/packages/lib/src/gfx/geometries/CylinderBufferGeometry.js index f8539ac8..f47e6df4 100644 --- a/packages/lib/src/gfx/geometries/CylinderBufferGeometry.js +++ b/packages/lib/src/gfx/geometries/CylinderBufferGeometry.js @@ -1,10 +1,15 @@ -import * as THREE from 'three' import utils from '../../utils' +import { + BufferAttribute, + BufferGeometry, + Uint16BufferAttribute, + Vector3 +} from 'three' const MAX_POINTS_COUNT_16BIT = 65536 const PTS_PER_TRIANGLE = 3 -class CylinderBufferGeometry extends THREE.BufferGeometry { +class CylinderBufferGeometry extends BufferGeometry { constructor( radiusTop, radiusBottom, @@ -41,21 +46,21 @@ class CylinderBufferGeometry extends THREE.BufferGeometry { const heightHalf = height / 2 /* eslint-disable no-magic-numbers */ - const positions = new THREE.BufferAttribute( + const positions = new BufferAttribute( utils.allocateTyped(Float32Array, vertexCount * 3), 3 ) - const normals = new THREE.BufferAttribute( + const normals = new BufferAttribute( utils.allocateTyped(Float32Array, vertexCount * 3), 3 ) - const indices = new THREE.Uint16BufferAttribute( + const indices = new Uint16BufferAttribute( utils.allocateTyped(Uint16Array, facesCount * PTS_PER_TRIANGLE), 1 ) /* eslint-enable no-magic-numbers */ - const uvs = new THREE.BufferAttribute( + const uvs = new BufferAttribute( utils.allocateTyped(Float32Array, vertexCount * 2), 2 ) @@ -96,7 +101,7 @@ class CylinderBufferGeometry extends THREE.BufferGeometry { const vy = v * height - heightHalf const vz = radius * Math.cos(u * thetaLength + thetaStart) - const normal = new THREE.Vector3( + const normal = new Vector3( vx, Math.sqrt(vx * vx + vz * vz) * tanTheta, vz diff --git a/packages/lib/src/gfx/geometries/CylinderCollisionGeo.js b/packages/lib/src/gfx/geometries/CylinderCollisionGeo.js index 23ba8b6a..68c7687c 100644 --- a/packages/lib/src/gfx/geometries/CylinderCollisionGeo.js +++ b/packages/lib/src/gfx/geometries/CylinderCollisionGeo.js @@ -1,15 +1,15 @@ -import * as THREE from 'three' import utils from '../../utils' import gfxutils from '../gfxutils' import ChunkedObjectsGeometry from './ChunkedObjectsGeometry' +import { CylinderBufferGeometry, Matrix3, Vector3 } from 'three' const VEC_SIZE = 3 -const tmpVector = new THREE.Vector3() -const normMtx = new THREE.Matrix3() +const tmpVector = new Vector3() +const normMtx = new Matrix3() class CylinderCollisionGeo extends ChunkedObjectsGeometry { constructor(instanceCount, polyComplexity) { - const cylGeometry = new THREE.CylinderBufferGeometry( + const cylGeometry = new CylinderBufferGeometry( 1, 1, 1.0, diff --git a/packages/lib/src/gfx/geometries/ExtrudedObjectsGeometry.js b/packages/lib/src/gfx/geometries/ExtrudedObjectsGeometry.js index aa2a6dd0..98e75648 100644 --- a/packages/lib/src/gfx/geometries/ExtrudedObjectsGeometry.js +++ b/packages/lib/src/gfx/geometries/ExtrudedObjectsGeometry.js @@ -1,23 +1,23 @@ -import * as THREE from 'three' import utils from '../../utils' import ChunkedObjectsGeometry from './ChunkedObjectsGeometry' +import { BufferAttribute, BufferGeometry, Vector3 } from 'three' const VEC_SIZE = 3 const TRI_SIZE = 3 -const tmpPrev = new THREE.Vector3() -const tmpNext = new THREE.Vector3() -const tmpRes = new THREE.Vector3() -const simpleNormal = new THREE.Vector3(1.0, 0.0, 0.0) -const normalOnCut = new THREE.Vector3() -const nearRingPt = new THREE.Vector3() +const tmpPrev = new Vector3() +const tmpNext = new Vector3() +const tmpRes = new Vector3() +const simpleNormal = new Vector3(1.0, 0.0, 0.0) +const normalOnCut = new Vector3() +const nearRingPt = new Vector3() function _createExtrudedChunkGeometry(shape, ringsCount) { - const geo = new THREE.BufferGeometry() + const geo = new BufferGeometry() const ptsCount = shape.length const totalPts = ptsCount * ringsCount const type = totalPts <= 65536 ? Uint16Array : Uint32Array const facesPerChunk = (ringsCount - 1) * ptsCount * 2 - const indices = new THREE.BufferAttribute( + const indices = new BufferAttribute( utils.allocateTyped(type, facesPerChunk * TRI_SIZE), 1 ) @@ -45,7 +45,7 @@ function _createExtrudedChunkGeometry(shape, ringsCount) { geo.setIndex(indices) const pos = utils.allocateTyped(Float32Array, totalPts * VEC_SIZE) - geo.setAttribute('position', new THREE.BufferAttribute(pos, VEC_SIZE)) + geo.setAttribute('position', new BufferAttribute(pos, VEC_SIZE)) geo._positions = shape @@ -60,7 +60,7 @@ class ExtrudedObjectsGeometry extends ChunkedObjectsGeometry { const tmpShape = (this._tmpShape = []) for (let i = 0; i < shape.length; ++i) { - tmpShape[i] = new THREE.Vector3() + tmpShape[i] = new Vector3() } } diff --git a/packages/lib/src/gfx/geometries/Instanced2CCylindersGeometry.js b/packages/lib/src/gfx/geometries/Instanced2CCylindersGeometry.js index 7cf620d4..88b0ff39 100644 --- a/packages/lib/src/gfx/geometries/Instanced2CCylindersGeometry.js +++ b/packages/lib/src/gfx/geometries/Instanced2CCylindersGeometry.js @@ -1,12 +1,18 @@ -import _ from 'lodash' -import * as THREE from 'three' +import { + Color, + InstancedBufferAttribute, + InstancedBufferGeometry, + Matrix4, + PlaneBufferGeometry +} from 'three' import utils from '../../utils' import gfxutils from '../gfxutils' import Simple2CCylindersGeometry from './Simple2CCylindersGeometry' import CylinderBufferGeometry from './CylinderBufferGeometry' +import { fill } from 'lodash' -const tmpColor = new THREE.Color() -const invMatrix = new THREE.Matrix4() +const tmpColor = new Color() +const invMatrix = new Matrix4() const OFFSET_SIZE = 4 const COLOR_SIZE = 3 @@ -66,12 +72,12 @@ function _assignOpacity(cylinderInfo, color1, color2) { } } } -class Instanced2CCylindersGeometry extends THREE.InstancedBufferGeometry { +class Instanced2CCylindersGeometry extends InstancedBufferGeometry { constructor(instanceCount, polyComplexity, useZSprites, openEnded) { super() this._useZSprites = useZSprites this._cylGeometry = useZSprites - ? new THREE.PlaneBufferGeometry(2, 2, 1, 1) + ? new PlaneBufferGeometry(2, 2, 1, 1) : new CylinderBufferGeometry( 1, 1, @@ -163,7 +169,7 @@ class Instanced2CCylindersGeometry extends THREE.InstancedBufferGeometry { const info = _prepareCylinderInfo(chunkIndices) const cylinderIndices = info.indices const instanceCount = cylinderIndices.length - const geom = new THREE.InstancedBufferGeometry() + const geom = new InstancedBufferGeometry() this._init.call(geom, instanceCount, this._cylGeometry, this._useZSprites) copySubArrays( @@ -238,47 +244,32 @@ class Instanced2CCylindersGeometry extends THREE.InstancedBufferGeometry { Float32Array, instanceCount )) - _.fill(alpha, 1.0) + fill(alpha, 1.0) this.setAttribute( 'matVector1', - new THREE.InstancedBufferAttribute( - this._matVector1, - OFFSET_SIZE, - false, - 1 - ) + new InstancedBufferAttribute(this._matVector1, OFFSET_SIZE, false, 1) ) this.setAttribute( 'matVector2', - new THREE.InstancedBufferAttribute( - this._matVector2, - OFFSET_SIZE, - false, - 1 - ) + new InstancedBufferAttribute(this._matVector2, OFFSET_SIZE, false, 1) ) this.setAttribute( 'matVector3', - new THREE.InstancedBufferAttribute( - this._matVector3, - OFFSET_SIZE, - false, - 1 - ) + new InstancedBufferAttribute(this._matVector3, OFFSET_SIZE, false, 1) ) this.setAttribute( 'color', - new THREE.InstancedBufferAttribute(this._color1, COLOR_SIZE, false, 1) + new InstancedBufferAttribute(this._color1, COLOR_SIZE, false, 1) ) this.setAttribute( 'color2', - new THREE.InstancedBufferAttribute(this._color2, COLOR_SIZE, false, 1) + new InstancedBufferAttribute(this._color2, COLOR_SIZE, false, 1) ) this.setAttribute( 'alphaColor', - new THREE.InstancedBufferAttribute(this._alpha, 1, false, 1) + new InstancedBufferAttribute(this._alpha, 1, false, 1) ) if (useZSprites) { @@ -297,30 +288,15 @@ class Instanced2CCylindersGeometry extends THREE.InstancedBufferGeometry { this.setAttribute( 'invmatVector1', - new THREE.InstancedBufferAttribute( - this._invmatVector1, - OFFSET_SIZE, - false, - 1 - ) + new InstancedBufferAttribute(this._invmatVector1, OFFSET_SIZE, false, 1) ) this.setAttribute( 'invmatVector2', - new THREE.InstancedBufferAttribute( - this._invmatVector2, - OFFSET_SIZE, - false, - 1 - ) + new InstancedBufferAttribute(this._invmatVector2, OFFSET_SIZE, false, 1) ) this.setAttribute( 'invmatVector3', - new THREE.InstancedBufferAttribute( - this._invmatVector3, - OFFSET_SIZE, - false, - 1 - ) + new InstancedBufferAttribute(this._invmatVector3, OFFSET_SIZE, false, 1) ) } } diff --git a/packages/lib/src/gfx/geometries/InstancedSpheresGeometry.js b/packages/lib/src/gfx/geometries/InstancedSpheresGeometry.js index 18ba3558..27d12cad 100644 --- a/packages/lib/src/gfx/geometries/InstancedSpheresGeometry.js +++ b/packages/lib/src/gfx/geometries/InstancedSpheresGeometry.js @@ -1,9 +1,15 @@ -import _ from 'lodash' -import * as THREE from 'three' +import { + Color, + InstancedBufferAttribute, + InstancedBufferGeometry, + PlaneBufferGeometry, + SphereBufferGeometry +} from 'three' import utils from '../../utils' import SphereCollisionGeo from './SphereCollisionGeo' +import { fill } from 'lodash' -const tmpColor = new THREE.Color() +const tmpColor = new Color() const OFFSET_SIZE = 4 const COLOR_SIZE = 3 @@ -22,13 +28,13 @@ function setArrayXYZW(arr, idx, x, y, z, w) { arr[idx + 3] = w } class InstancedSpheresGeometry extends SphereCollisionGeo( - THREE.InstancedBufferGeometry + InstancedBufferGeometry ) { constructor(spheresCount, sphereComplexity, useZSprites) { super(spheresCount) this._sphGeometry = useZSprites - ? new THREE.PlaneBufferGeometry(2, 2, 1, 1) - : new THREE.SphereBufferGeometry( + ? new PlaneBufferGeometry(2, 2, 1, 1) + : new SphereBufferGeometry( 1, sphereComplexity * 2, sphereComplexity, @@ -87,7 +93,7 @@ class InstancedSpheresGeometry extends SphereCollisionGeo( getSubset(chunkIndices) { const instanceCount = chunkIndices.length - const geom = new THREE.InstancedBufferGeometry() + const geom = new InstancedBufferGeometry() this._init.call(geom, instanceCount, this._sphGeometry) copySubArrays(this._offsets, geom._offsets, chunkIndices, OFFSET_SIZE) @@ -109,19 +115,19 @@ class InstancedSpheresGeometry extends SphereCollisionGeo( Float32Array, spheresCount )) - _.fill(alpha, 1.0) + fill(alpha, 1.0) this.setAttribute( 'offset', - new THREE.InstancedBufferAttribute(this._offsets, OFFSET_SIZE, false, 1) + new InstancedBufferAttribute(this._offsets, OFFSET_SIZE, false, 1) ) this.setAttribute( 'color', - new THREE.InstancedBufferAttribute(this._colors, COLOR_SIZE, false, 1) + new InstancedBufferAttribute(this._colors, COLOR_SIZE, false, 1) ) this.setAttribute( 'alphaColor', - new THREE.InstancedBufferAttribute(alpha, 1, false, 1) + new InstancedBufferAttribute(alpha, 1, false, 1) ) } } diff --git a/packages/lib/src/gfx/geometries/IsoSurface.js b/packages/lib/src/gfx/geometries/IsoSurface.js index 8e3eeebe..1284a728 100644 --- a/packages/lib/src/gfx/geometries/IsoSurface.js +++ b/packages/lib/src/gfx/geometries/IsoSurface.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' import IsoSurfaceMarchCube from './IsoSurfaceMarchCube' import utils from '../../utils' +import { BufferAttribute, BufferGeometry, Matrix3, Vector3 } from 'three' const edgeTable = [ 0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, @@ -42,8 +42,8 @@ class GridCell { this.g = new Array(this._arrSize) this.val = new Array(this._arrSize) for (let i = 0; i < this._arrSize; ++i) { - this.p[i] = new THREE.Vector3() - this.g[i] = new THREE.Vector3() + this.p[i] = new Vector3() + this.g[i] = new Vector3() } this.cubeIndex = 0 } @@ -53,18 +53,18 @@ class GridCell { class Triangle { constructor() { this.a = { - p: new THREE.Vector3(), - n: new THREE.Vector3() + p: new Vector3(), + n: new Vector3() } this.b = { - p: new THREE.Vector3(), - n: new THREE.Vector3() + p: new Vector3(), + n: new Vector3() } this.c = { - p: new THREE.Vector3(), - n: new THREE.Vector3() + p: new Vector3(), + n: new Vector3() } } } @@ -72,7 +72,7 @@ class Triangle { function createArray(arrSize) { const arr = new Array(arrSize) for (let i = 0; i < arrSize; ++i) { - arr[i] = new THREE.Vector3() + arr[i] = new Vector3() } return arr @@ -87,12 +87,12 @@ class IsoSurface { this._colors = null this._indices = [] this._volumetricData = null - this._xAxis = new THREE.Vector3() - this._yAxis = new THREE.Vector3() - this._zAxis = new THREE.Vector3() - this._xDir = new THREE.Vector3() - this._yDir = new THREE.Vector3() - this._zDir = new THREE.Vector3() + this._xAxis = new Vector3() + this._yAxis = new Vector3() + this._zAxis = new Vector3() + this._xDir = new Vector3() + this._yDir = new Vector3() + this._zDir = new Vector3() } _prepareAxesAndDirs() { @@ -117,7 +117,7 @@ class IsoSurface { zDir.set(0, 0, 1) // flip normals if coordinate system is in the wrong handedness - const tmp = new THREE.Vector3() + const tmp = new Vector3() tmp.crossVectors(xDir, yDir) if (tmp.dot(zDir) < 0) { xDir.negate() @@ -240,14 +240,14 @@ class IsoSurface { const gcVal = gc.val const gcValSize = gc.val.length const additions = [ - new THREE.Vector3(0, 0, 0), // 0 - new THREE.Vector3(step, 0, 0), // 1 - new THREE.Vector3(step, step, 0), // 2 - new THREE.Vector3(0, step, 0), // 3 - new THREE.Vector3(0, 0, step), // 4 - new THREE.Vector3(step, 0, step), // 5 - new THREE.Vector3(step, step, step), // 6 - new THREE.Vector3(0, step, step) // 7 + new Vector3(0, 0, 0), // 0 + new Vector3(step, 0, 0), // 1 + new Vector3(step, step, 0), // 2 + new Vector3(0, step, 0), // 3 + new Vector3(0, 0, step), // 4 + new Vector3(step, 0, step), // 5 + new Vector3(step, step, step), // 6 + new Vector3(0, step, step) // 7 ] const tmpTriCount = 5 @@ -263,11 +263,7 @@ class IsoSurface { if (appendSimple) { // Special case for axis-aligned grid with positive unit vector normals appendVertex = (function () { - const axis = new THREE.Vector3( - self._xAxis.x, - self._yAxis.y, - self._zAxis.z - ) + const axis = new Vector3(self._xAxis.x, self._yAxis.y, self._zAxis.z) return function (triVertex) { const vertex = triVertex.p.clone() vertex.multiply(axis) @@ -277,7 +273,7 @@ class IsoSurface { })() } else { appendVertex = (function () { - const posMtx = new THREE.Matrix3() + const posMtx = new Matrix3() posMtx.set( self._xAxis.x, self._yAxis.x, @@ -289,7 +285,7 @@ class IsoSurface { self._yAxis.z, self._zAxis.z ) - const normMtx = new THREE.Matrix3() + const normMtx = new Matrix3() normMtx.set( self._xDir.x, self._yDir.x, @@ -654,11 +650,11 @@ class IsoSurface { } toMesh() { - const geo = new THREE.BufferGeometry() - geo.setIndex(new THREE.BufferAttribute(this._indices, 1)) - geo.setAttribute('position', new THREE.BufferAttribute(this._position, 3)) - geo.setAttribute('normal', new THREE.BufferAttribute(this._normals, 3)) - geo.setAttribute('color', new THREE.BufferAttribute(this._colors, 3)) + const geo = new BufferGeometry() + geo.setIndex(new BufferAttribute(this._indices, 1)) + geo.setAttribute('position', new BufferAttribute(this._position, 3)) + geo.setAttribute('normal', new BufferAttribute(this._normals, 3)) + geo.setAttribute('color', new BufferAttribute(this._colors, 3)) geo.computeBoundingSphere() return geo } diff --git a/packages/lib/src/gfx/geometries/IsoSurfaceAtomColored.js b/packages/lib/src/gfx/geometries/IsoSurfaceAtomColored.js index f0b7d121..015230e4 100644 --- a/packages/lib/src/gfx/geometries/IsoSurfaceAtomColored.js +++ b/packages/lib/src/gfx/geometries/IsoSurfaceAtomColored.js @@ -1,4 +1,4 @@ -import * as THREE from 'three' +import { Vector3 } from 'three' /** * Class for colored atom. Need for atom structure clusterization @@ -8,7 +8,7 @@ import * as THREE from 'three' */ class IsoSurfaceAtomColored { constructor(vCenter, radiusAt) { - this.coord = new THREE.Vector3() + this.coord = new Vector3() this.coord.copy(vCenter) this.radius = radiusAt this.colorX = 0.99999 diff --git a/packages/lib/src/gfx/geometries/IsoSurfaceGeo.js b/packages/lib/src/gfx/geometries/IsoSurfaceGeo.js index af3facc9..4f0332f3 100644 --- a/packages/lib/src/gfx/geometries/IsoSurfaceGeo.js +++ b/packages/lib/src/gfx/geometries/IsoSurfaceGeo.js @@ -1,4 +1,4 @@ -import * as THREE from 'three' +import { Vector3 } from 'three' /** * Class for geometry (triangle mesh) representation @@ -24,15 +24,15 @@ class IsoSurfaceGeo { let i for (i = 0; i < maxNumVertices; i++) { - this._vertices[i] = new THREE.Vector3() - this._normals[i] = new THREE.Vector3() + this._vertices[i] = new Vector3() + this._normals[i] = new Vector3() } for (i = 0; i < maxNumTriangles * (1 + 2); i++) { this._indices[i] = -1 } if (needVertexColors) { for (i = 0; i < maxNumVertices; i++) { - this._colors[i] = new THREE.Vector3() + this._colors[i] = new Vector3() } } } diff --git a/packages/lib/src/gfx/geometries/IsoSurfaceGeometry.js b/packages/lib/src/gfx/geometries/IsoSurfaceGeometry.js index 94711940..0087e5de 100644 --- a/packages/lib/src/gfx/geometries/IsoSurfaceGeometry.js +++ b/packages/lib/src/gfx/geometries/IsoSurfaceGeometry.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' +import { BufferGeometry, Color } from 'three' import utils from '../../utils' const POS_RAD_SIZE = 4 const COLOR_SIZE = 3 -const tmpColor = new THREE.Color() +const tmpColor = new Color() /** * This is a base class for isosurface algorithms. @@ -11,7 +11,7 @@ const tmpColor = new THREE.Color() * @param opts - geometry specific options * @constructor */ -class IsoSurfaceGeometry extends THREE.BufferGeometry { +class IsoSurfaceGeometry extends BufferGeometry { constructor(spheresCount, opts) { super() diff --git a/packages/lib/src/gfx/geometries/IsosurfaceBuildNormals.js b/packages/lib/src/gfx/geometries/IsosurfaceBuildNormals.js index 945d1244..08e13f38 100644 --- a/packages/lib/src/gfx/geometries/IsosurfaceBuildNormals.js +++ b/packages/lib/src/gfx/geometries/IsosurfaceBuildNormals.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import utils from '../../utils' +import { Vector3 } from 'three' // suppress some JSHint warnings /* jshint bitwise: false */ @@ -18,8 +18,8 @@ class IsosurfaceBuildNormals { constructor(numAtoms, atoms, vBoxMin, vBoxMax, probeRadius) { this._numAtoms = numAtoms this._atoms = atoms - this._vBoxMin = new THREE.Vector3() - this._vBoxMax = new THREE.Vector3() + this._vBoxMin = new Vector3() + this._vBoxMax = new Vector3() this._vBoxMin.copy(vBoxMin) this._vBoxMax.copy(vBoxMax) this._probeRadius = probeRadius diff --git a/packages/lib/src/gfx/geometries/LabelsGeometry.js b/packages/lib/src/gfx/geometries/LabelsGeometry.js index 13217950..cce832db 100644 --- a/packages/lib/src/gfx/geometries/LabelsGeometry.js +++ b/packages/lib/src/gfx/geometries/LabelsGeometry.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import EventDispatcher from '../../utils/EventDispatcher' +import { Vector3 } from 'three' function createLabel(fieldTxt, className) { const text = document.createElement('div') @@ -24,7 +24,7 @@ function createLabel(fieldTxt, className) { } else { text.appendChild(fieldTxt) } - text.worldPos = new THREE.Vector3() + text.worldPos = new Vector3() return text } class LabelsGeometry extends EventDispatcher { @@ -58,7 +58,7 @@ class LabelsGeometry extends EventDispatcher { break } - const deltaPos = new THREE.Vector3(opts.dx || 0, opts.dy || 0, opts.dz || 0) + const deltaPos = new Vector3(opts.dx || 0, opts.dy || 0, opts.dz || 0) this.userData = { translation: `translate(${xTranslation}%, ${yTranslation}%)`, offset: deltaPos diff --git a/packages/lib/src/gfx/geometries/LinesGeometry.js b/packages/lib/src/gfx/geometries/LinesGeometry.js index 5023e272..0a28aad3 100644 --- a/packages/lib/src/gfx/geometries/LinesGeometry.js +++ b/packages/lib/src/gfx/geometries/LinesGeometry.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import BaseLinesGeometry from './ThickLinesGeometry' +import { Box3, Sphere, Vector3 } from 'three' /** * This class represents geometry which consists lines. This can build bounding volumes @@ -16,14 +16,14 @@ class LinesGeometry extends BaseLinesGeometry { const { boundingBox } = this // Build bounding sphere let radiusSquared = 0.0 - const center = new THREE.Vector3() + const center = new Vector3() if (boundingBox) { boundingBox.getCenter(center) } const positions = this._positions - const sphere = this.boundingSphere || new THREE.Sphere() + const sphere = this.boundingSphere || new Sphere() const size = this._positions.length - const pos = new THREE.Vector3() + const pos = new Vector3() const posSize = this.getPositionSize() for (let i = 0; i < size; i += posSize) { pos.set(positions[i], positions[i + 1], positions[i + 2]) @@ -38,9 +38,9 @@ class LinesGeometry extends BaseLinesGeometry { computeBoundingBox() { const positions = this._positions - const box = new THREE.Box3() + const box = new Box3() const size = this._positions.length - const tmpVec = new THREE.Vector3() + const tmpVec = new Vector3() const posSize = this.getPositionSize() for (let i = 0; i < size; i += posSize) { tmpVec.set(positions[i], positions[i + 1], positions[i + 2]) diff --git a/packages/lib/src/gfx/geometries/SSIsosurfaceGeometry.js b/packages/lib/src/gfx/geometries/SSIsosurfaceGeometry.js index 9a3a1e02..e6a90a0e 100644 --- a/packages/lib/src/gfx/geometries/SSIsosurfaceGeometry.js +++ b/packages/lib/src/gfx/geometries/SSIsosurfaceGeometry.js @@ -1,4 +1,3 @@ -import * as THREE from 'three' import IsoSurfaceGeometry from './IsoSurfaceGeometry' import IsoSurfaceAtomColored from './IsoSurfaceAtomColored' import IsosurfaceBuildNormals from './IsosurfaceBuildNormals' @@ -6,6 +5,7 @@ import IsoSurfaceMarchCube from './IsoSurfaceMarchCube' import IsoSurfaceGeo from './IsoSurfaceGeo' import chem from '../../chem' import utils from '../../utils' +import { BufferAttribute, Vector3 } from 'three' const COLOR_SIZE = 3 const HASH_SIZE = 32768 @@ -67,10 +67,10 @@ class SSIsosurfaceGeometry extends IsoSurfaceGeometry { indices[i] = geoOut._indices[i] } - this.setIndex(new THREE.BufferAttribute(indices, 1)) - this.setAttribute('position', new THREE.BufferAttribute(positions, 3)) - this.setAttribute('normal', new THREE.BufferAttribute(normals, 3)) - this.setAttribute('color', new THREE.BufferAttribute(colors, 3)) + this.setIndex(new BufferAttribute(indices, 1)) + this.setAttribute('position', new BufferAttribute(positions, 3)) + this.setAttribute('normal', new BufferAttribute(normals, 3)) + this.setAttribute('color', new BufferAttribute(colors, 3)) this.computeBoundingBox() this.computeBoundingSphere() @@ -288,13 +288,13 @@ class SSIsosurfaceGeometry extends IsoSurfaceGeometry { const vaEdges = new Array(arrSize) for (let i = 0; i < arrSize; i++) { - vaEdges[i] = new THREE.Vector3() + vaEdges[i] = new Vector3() } const sign = [] for (let i = 0; i < cNumVerts; i++) { sign[i] = 1.0 } - const vCorner = new THREE.Vector3() + const vCorner = new Vector3() let indCell = 0 let indY = 0 for (let y = 0; y < numCells; y++, indY += side2) { @@ -489,8 +489,8 @@ class SSIsosurfaceGeometry extends IsoSurfaceGeometry { calculateGridCorners(corners, side, vBoxMin, vBoxMax, atoms, probeRad) { const side2 = side * side const side3 = side2 * side - const vCorner = new THREE.Vector3() - const vDif = new THREE.Vector3() + const vCorner = new Vector3() + const vDif = new Vector3() /* eslint-disable no-magic-numbers */ const aLot = +1.0e12 /* eslint-enable no-magic-numbers */ @@ -618,7 +618,7 @@ class SSIsosurfaceGeometry extends IsoSurfaceGeometry { const r106 = 1.0e-6 const hashResolution = this.marCubeResoultion << 2 - const v = new THREE.Vector3() + const v = new Vector3() const ix = Math.floor( (hashResolution * (vAdd.x - this.vBoxMin.x)) / (this.vBoxMax.x + oneHynberes - this.vBoxMin.x) @@ -812,8 +812,8 @@ class SSIsosurfaceGeometry extends IsoSurfaceGeometry { this.convertToAtomsColored(packedArrays, atomsColored) // find bbox for spheres scene - const vBoxMin = (this.vBoxMin = new THREE.Vector3()) - const vBoxMax = (this.vBoxMax = new THREE.Vector3()) + const vBoxMin = (this.vBoxMin = new Vector3()) + const vBoxMax = (this.vBoxMax = new Vector3()) this.getBoundingBox(atomsColored, vBoxMin, vBoxMax) const marCubeResoultion = (this.marCubeResoultion = @@ -842,7 +842,7 @@ class SSIsosurfaceGeometry extends IsoSurfaceGeometry { return ok } // copy corners to cells - const vCellStep = new THREE.Vector3() + const vCellStep = new Vector3() vCellStep.x = (vBoxMax.x - vBoxMin.x) / numCells vCellStep.y = (vBoxMax.y - vBoxMin.y) / numCells vCellStep.z = (vBoxMax.z - vBoxMin.z) / numCells diff --git a/packages/lib/src/gfx/geometries/Simple2CCylindersGeometry.js b/packages/lib/src/gfx/geometries/Simple2CCylindersGeometry.js index d676e113..6f53d6fd 100644 --- a/packages/lib/src/gfx/geometries/Simple2CCylindersGeometry.js +++ b/packages/lib/src/gfx/geometries/Simple2CCylindersGeometry.js @@ -1,16 +1,16 @@ -import * as THREE from 'three' import utils from '../../utils' import gfxutils from '../gfxutils' import ChunkedObjectsGeometry from './ChunkedObjectsGeometry' +import { CylinderBufferGeometry, Matrix3, Vector3 } from 'three' const VEC_SIZE = 3 -const centerPos = new THREE.Vector3() -const tmpVector = new THREE.Vector3() -const normMtx = new THREE.Matrix3() +const centerPos = new Vector3() +const tmpVector = new Vector3() +const normMtx = new Matrix3() class Simple2CCylindersGeometry extends ChunkedObjectsGeometry { constructor(instanceCount, polyComplexity) { - const cylGeometry = new THREE.CylinderBufferGeometry( + const cylGeometry = new CylinderBufferGeometry( 1, 1, 1.0, diff --git a/packages/lib/src/gfx/geometries/SimpleSpheresGeometry.js b/packages/lib/src/gfx/geometries/SimpleSpheresGeometry.js index b7797360..cc7e70d6 100644 --- a/packages/lib/src/gfx/geometries/SimpleSpheresGeometry.js +++ b/packages/lib/src/gfx/geometries/SimpleSpheresGeometry.js @@ -1,13 +1,13 @@ -import * as THREE from 'three' import utils from '../../utils' import ChunkedObjectsGeometry from './ChunkedObjectsGeometry' import SphereCollisionGeo from './SphereCollisionGeo' +import { SphereBufferGeometry } from 'three' const VEC_SIZE = 3 class SimpleSpheresGeometry extends SphereCollisionGeo(ChunkedObjectsGeometry) { constructor(spheresCount, sphereComplexity) { - const sphGeometry = new THREE.SphereBufferGeometry( + const sphGeometry = new SphereBufferGeometry( 1, sphereComplexity * 2, sphereComplexity, diff --git a/packages/lib/src/gfx/geometries/SphereCollisionGeo.js b/packages/lib/src/gfx/geometries/SphereCollisionGeo.js index e74e87bd..c738ef85 100644 --- a/packages/lib/src/gfx/geometries/SphereCollisionGeo.js +++ b/packages/lib/src/gfx/geometries/SphereCollisionGeo.js @@ -1,4 +1,4 @@ -import * as THREE from 'three' +import { Box3, Sphere, Vector3 } from 'three' class CollisionSphere { constructor(position, radius) { @@ -6,13 +6,13 @@ class CollisionSphere { this._radius = radius } - static _sphere = new THREE.Sphere() + static _sphere = new Sphere() raycast(raycaster) { const sphere = CollisionSphere._sphere sphere.set(this._position, this._radius) - const p = new THREE.Vector3() + const p = new Vector3() if (raycaster.ray.intersectSphere(sphere, p)) { return { distance: raycaster.ray.origin.distanceTo(p), @@ -51,7 +51,7 @@ const SphereCollisionGeo = (base) => const objects = this._objects let { boundingBox } = this if (boundingBox === null) { - this.boundingBox = boundingBox = new THREE.Box3() + this.boundingBox = boundingBox = new Box3() } boundingBox.makeEmpty() for (let i = 0, n = objects.length; i < n; ++i) { @@ -65,7 +65,7 @@ const SphereCollisionGeo = (base) => const { boundingBox } = this // Build bounding sphere let radiusSquared = 0.0 - const center = new THREE.Vector3() + const center = new Vector3() boundingBox.getCenter(center) for (let i = 0, n = objects.length; i < n; ++i) { const pos = objects[i]._position @@ -75,7 +75,7 @@ const SphereCollisionGeo = (base) => } } if (this.boundingSphere === null) { - this.boundingSphere = new THREE.Sphere() + this.boundingSphere = new Sphere() } this.boundingSphere.set(center, Math.sqrt(radiusSquared)) } diff --git a/packages/lib/src/gfx/geometries/ThickLinesGeometry.js b/packages/lib/src/gfx/geometries/ThickLinesGeometry.js index eeb24f12..ab731cc7 100644 --- a/packages/lib/src/gfx/geometries/ThickLinesGeometry.js +++ b/packages/lib/src/gfx/geometries/ThickLinesGeometry.js @@ -1,14 +1,14 @@ -import _ from 'lodash' -import * as THREE from 'three' import utils from '../../utils' +import { Vector3, Color, BufferGeometry, BufferAttribute } from 'three' +import { fill } from 'lodash' const MAX_IDC_16BIT = 65535 const VERTEX_PER_SEGMENT = 4 const POS_SIZE = 4 const DIR_SIZE = 3 const COL_SIZE = 3 -const tmpColor = new THREE.Color() -const direction = new THREE.Vector3() +const tmpColor = new Color() +const direction = new Vector3() function setArrayXYZ(arr, idx, x, y, z) { arr[idx] = x @@ -38,7 +38,7 @@ function getSubset(arr, startSegmentIdx, segmentsCount, elemSize) { * collision geometry. */ -class ThickLinesGeometry extends THREE.BufferGeometry { +class ThickLinesGeometry extends BufferGeometry { constructor(segmentsCount) { super() this._initVertices(segmentsCount) @@ -93,7 +93,7 @@ class ThickLinesGeometry extends THREE.BufferGeometry { setOpacity(startSegIdx, endSegIdx, value) { const start = startSegIdx * VERTEX_PER_SEGMENT const end = endSegIdx * VERTEX_PER_SEGMENT - _.fill(this.alpha, value, end, start) + fill(this.alpha, value, end, start) this.getAttribute('alphaColor').needsUpdate = true } @@ -148,7 +148,7 @@ class ThickLinesGeometry extends THREE.BufferGeometry { this._colors = utils.allocateTyped(Float32Array, pointsCount * COL_SIZE) this._directions = utils.allocateTyped(Float32Array, pointsCount * DIR_SIZE) const alpha = (this._alpha = utils.allocateTyped(Float32Array, pointsCount)) - _.fill(alpha, 1.0) + fill(alpha, 1.0) const index = this._index let indexOffset = 0 @@ -165,20 +165,17 @@ class ThickLinesGeometry extends THREE.BufferGeometry { index[indexOffset + 4] = pointOffset + 2 index[indexOffset + 5] = pointOffset + 3 } - this.setIndex(new THREE.BufferAttribute(this._index, 1)) + this.setIndex(new BufferAttribute(this._index, 1)) this.setAttribute( 'position', - new THREE.BufferAttribute(this._positions, POS_SIZE) + new BufferAttribute(this._positions, POS_SIZE) ) - this.setAttribute( - 'color', - new THREE.BufferAttribute(this._colors, COL_SIZE) - ) - this.setAttribute('alphaColor', new THREE.BufferAttribute(alpha, 1)) + this.setAttribute('color', new BufferAttribute(this._colors, COL_SIZE)) + this.setAttribute('alphaColor', new BufferAttribute(alpha, 1)) this.setAttribute( 'direction', - new THREE.BufferAttribute(this._directions, DIR_SIZE) + new BufferAttribute(this._directions, DIR_SIZE) ) } } diff --git a/packages/lib/src/gfx/geometries/ThinLinesGeometry.js b/packages/lib/src/gfx/geometries/ThinLinesGeometry.js index b84d18af..aaf06cc7 100644 --- a/packages/lib/src/gfx/geometries/ThinLinesGeometry.js +++ b/packages/lib/src/gfx/geometries/ThinLinesGeometry.js @@ -1,11 +1,11 @@ -import _ from 'lodash' -import * as THREE from 'three' +import { BufferAttribute, BufferGeometry, Color } from 'three' import utils from '../../utils' +import { fill } from 'lodash' const VERTEX_PER_SEGMENT = 2 const POS_SIZE = 3 const COL_SIZE = 3 -const tmpColor = new THREE.Color() +const tmpColor = new Color() function setArrayXYZ(arr, idx, x, y, z) { arr[idx] = x @@ -28,7 +28,7 @@ function getSubset(arr, startSegmentIdx, segmentsCount, elemSize) { * collision geometry. */ -class ThinLinesGeometry extends THREE.BufferGeometry { +class ThinLinesGeometry extends BufferGeometry { constructor(segmentsCount) { super() this._initVertices(segmentsCount) @@ -62,7 +62,7 @@ class ThinLinesGeometry extends THREE.BufferGeometry { setOpacity(startSegIdx, endSegIdx, value) { const start = startSegIdx * VERTEX_PER_SEGMENT const end = endSegIdx * VERTEX_PER_SEGMENT - _.fill(this.alpha, value, end, start) + fill(this.alpha, value, end, start) this.getAttribute('alphaColor').needsUpdate = true } @@ -102,16 +102,13 @@ class ThinLinesGeometry extends THREE.BufferGeometry { this._positions = utils.allocateTyped(Float32Array, pointsCount * POS_SIZE) this._colors = utils.allocateTyped(Float32Array, pointsCount * COL_SIZE) const alpha = (this._alpha = utils.allocateTyped(Float32Array, pointsCount)) - _.fill(alpha, 1.0) + fill(alpha, 1.0) this.setAttribute( 'position', - new THREE.BufferAttribute(this._positions, POS_SIZE) + new BufferAttribute(this._positions, POS_SIZE) ) - this.setAttribute( - 'color', - new THREE.BufferAttribute(this._colors, COL_SIZE) - ) - this.setAttribute('alphaColor', new THREE.BufferAttribute(alpha, 1)) + this.setAttribute('color', new BufferAttribute(this._colors, COL_SIZE)) + this.setAttribute('alphaColor', new BufferAttribute(alpha, 1)) } } diff --git a/packages/lib/src/gfx/geometries/TwoColorLinesGeometry.js b/packages/lib/src/gfx/geometries/TwoColorLinesGeometry.js index fd63f790..dce66166 100644 --- a/packages/lib/src/gfx/geometries/TwoColorLinesGeometry.js +++ b/packages/lib/src/gfx/geometries/TwoColorLinesGeometry.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' import LinesGeometry from './LinesGeometry' import Simple2CCylindersGeometry from './Simple2CCylindersGeometry' +import { Vector3 } from 'three' const COLLISION_RAD = 0.3 -const tmpVector = new THREE.Vector3() +const tmpVector = new Vector3() class TwoColorLinesGeometry extends LinesGeometry { constructor(segmentsCount) { diff --git a/packages/lib/src/gfx/geometries/VolumeSurfaceGeometry.js b/packages/lib/src/gfx/geometries/VolumeSurfaceGeometry.js index 2d5cae5c..163c7e6b 100644 --- a/packages/lib/src/gfx/geometries/VolumeSurfaceGeometry.js +++ b/packages/lib/src/gfx/geometries/VolumeSurfaceGeometry.js @@ -1,7 +1,7 @@ -import * as THREE from 'three' import IsoSurfaceGeometry from './IsoSurfaceGeometry' import IsoSurface from './IsoSurface' import utils from '../../utils' +import { Box3, BufferAttribute, Vector3 } from 'three' /** * This is a base class for volumetric maps based isosurface algorithms. @@ -14,11 +14,11 @@ class VolumeSurfaceGeometry extends IsoSurfaceGeometry { _build() { const params = this._opts this.numVoxels = [128, 128, 128] - this.xAxis = new THREE.Vector3(1.0, 0.0, 0.0) - this.yAxis = new THREE.Vector3(0.0, 1.0, 0.0) - this.zAxis = new THREE.Vector3(0.0, 0.0, 1.0) + this.xAxis = new Vector3(1.0, 0.0, 0.0) + this.yAxis = new Vector3(0.0, 1.0, 0.0) + this.zAxis = new Vector3(0.0, 0.0, 1.0) - this.origin = new THREE.Vector3(0.0, 0.0, 0.0) + this.origin = new Vector3(0.0, 0.0, 0.0) this._visibilitySelector = params.visibilitySelector this._calcSurface(params) @@ -98,21 +98,15 @@ class VolumeSurfaceGeometry extends IsoSurfaceGeometry { surface.atomWeightMap, this._visibilitySelector ) - this.setIndex(new THREE.BufferAttribute(isoSurf._indices, 1)) - this.setAttribute( - 'position', - new THREE.BufferAttribute(isoSurf._position, 3) - ) - this.setAttribute( - 'normal', - new THREE.BufferAttribute(isoSurf._normals, 3) - ) - this.setAttribute('color', new THREE.BufferAttribute(isoSurf._colors, 3)) + this.setIndex(new BufferAttribute(isoSurf._indices, 1)) + this.setAttribute('position', new BufferAttribute(isoSurf._position, 3)) + this.setAttribute('normal', new BufferAttribute(isoSurf._normals, 3)) + this.setAttribute('color', new BufferAttribute(isoSurf._colors, 3)) } else { // geometry should have at least empty position attributes to be processed in wireframe mode by three.js this.setAttribute( 'position', - new THREE.BufferAttribute(utils.allocateTyped(Float32Array, 0), 3) + new BufferAttribute(utils.allocateTyped(Float32Array, 0), 3) ) } } @@ -129,11 +123,9 @@ class VolumeSurfaceGeometry extends IsoSurfaceGeometry { } const boundaries = this._findNumVoxels(packedArrays.posRad, params) - const box = new THREE.Box3( + const box = new Box3( this.origin, - new THREE.Vector3(this.xAxis.x, this.yAxis.y, this.zAxis.z).add( - this.origin - ) + new Vector3(this.xAxis.x, this.yAxis.y, this.zAxis.z).add(this.origin) ) const surface = this._computeSurface(packedArrays, box, boundaries, params) diff --git a/packages/lib/src/gfx/gfxutils.js b/packages/lib/src/gfx/gfxutils.js index d7b6d98a..a8b816ab 100644 --- a/packages/lib/src/gfx/gfxutils.js +++ b/packages/lib/src/gfx/gfxutils.js @@ -1,11 +1,33 @@ /* eslint-disable no-magic-numbers */ -import * as THREE from 'three' + import logger from '../utils/logger' import CSS2DObject from './CSS2DObject' import RCGroup from './RCGroup' import vertexScreenQuadShader from './shaders/ScreenQuad.vert' import fragmentScreenQuadFromTex from './shaders/ScreenQuadFromTex.frag' import fragmentScreenQuadFromTexWithDistortion from './shaders/ScreenQuadFromTexWithDistortion.frag' +import { + BufferAttribute, + InstancedBufferGeometry, + LessEqualDepth, + Line, + LineSegments, + MathUtils, + Matrix4, + Mesh, + MeshBasicMaterial, + Object3D, + OrthographicCamera, + PerspectiveCamera, + PlaneBufferGeometry, + RawShaderMaterial, + Raycaster, + Scene, + StereoCamera, + Vector3, + WebGLRenderer, + Color +} from 'three' const LAYERS = { DEFAULT: 0, @@ -23,25 +45,25 @@ const SELECTION_LAYERS = [ LAYERS.TRANSPARENT ] -THREE.Object3D.prototype.resetTransform = function () { +Object3D.prototype.resetTransform = function () { this.position.set(0, 0, 0) this.quaternion.set(0, 0, 0, 1) this.scale.set(1, 1, 1) } // update world matrix of this object and all its ancestors -THREE.Object3D.prototype.updateMatrixWorldRecursive = function () { +Object3D.prototype.updateMatrixWorldRecursive = function () { if (this.parent != null) { this.parent.updateMatrixWorldRecursive() } this.updateMatrixWorld() } // add object to parent, saving objects' world transform -THREE.Object3D.prototype.addSavingWorldTransform = (function () { - const _worldMatrixInverse = new THREE.Matrix4() +Object3D.prototype.addSavingWorldTransform = (function () { + const _worldMatrixInverse = new Matrix4() return function (object) { - if (object instanceof THREE.Object3D) { + if (object instanceof Object3D) { _worldMatrixInverse.copy(this.matrixWorld).invert() _worldMatrixInverse.multiply(object.matrixWorld) object.matrix.copy(_worldMatrixInverse) @@ -52,28 +74,18 @@ THREE.Object3D.prototype.addSavingWorldTransform = (function () { })() // render a tiny transparent quad in the center of the screen -THREE.WebGLRenderer.prototype.renderDummyQuad = (function () { - const _material = new THREE.MeshBasicMaterial({ +WebGLRenderer.prototype.renderDummyQuad = (function () { + const _material = new MeshBasicMaterial({ transparent: true, opacity: 0.0, depthWrite: false }) - const _scene = new THREE.Scene() - const _quad = new THREE.Mesh( - new THREE.PlaneBufferGeometry(0.01, 0.01), - _material - ) + const _scene = new Scene() + const _quad = new Mesh(new PlaneBufferGeometry(0.01, 0.01), _material) _scene.add(_quad) - const _camera = new THREE.OrthographicCamera( - -0.5, - 0.5, - 0.5, - -0.5, - -10000, - 10000 - ) + const _camera = new OrthographicCamera(-0.5, 0.5, 0.5, -0.5, -10000, 10000) _camera.position.z = 100 return function () { @@ -81,19 +93,12 @@ THREE.WebGLRenderer.prototype.renderDummyQuad = (function () { } })() -THREE.WebGLRenderer.prototype.renderScreenQuad = (function () { - const _scene = new THREE.Scene() - const _quad = new THREE.Mesh(new THREE.PlaneBufferGeometry(1.0, 1.0)) +WebGLRenderer.prototype.renderScreenQuad = (function () { + const _scene = new Scene() + const _quad = new Mesh(new PlaneBufferGeometry(1.0, 1.0)) _scene.add(_quad) - const _camera = new THREE.OrthographicCamera( - -0.5, - 0.5, - 0.5, - -0.5, - -10000, - 10000 - ) + const _camera = new OrthographicCamera(-0.5, 0.5, 0.5, -0.5, -10000, 10000) _camera.position.z = 100 return function (material) { @@ -102,14 +107,14 @@ THREE.WebGLRenderer.prototype.renderScreenQuad = (function () { } })() -THREE.Matrix4.prototype.isIdentity = (function () { - const identity = new THREE.Matrix4() +Matrix4.prototype.isIdentity = (function () { + const identity = new Matrix4() return function () { return identity.equals(this) } })() -THREE.Matrix4.prototype.applyToPointsArray = function (array, stride, w) { +Matrix4.prototype.applyToPointsArray = function (array, stride, w) { if (!array || !stride || stride < 3) { return array } @@ -129,7 +134,7 @@ THREE.Matrix4.prototype.applyToPointsArray = function (array, stride, w) { return array } -class ScreenQuadMaterial extends THREE.RawShaderMaterial { +class ScreenQuadMaterial extends RawShaderMaterial { constructor(params) { if (params.uniforms === undefined) { params.uniforms = {} @@ -143,7 +148,7 @@ class ScreenQuadMaterial extends THREE.RawShaderMaterial { } } -THREE.WebGLRenderer.prototype.renderScreenQuadFromTex = (function () { +WebGLRenderer.prototype.renderScreenQuadFromTex = (function () { const _material = new ScreenQuadMaterial({ uniforms: { opacity: { type: 'f', value: 1.0 } }, fragmentShader: fragmentScreenQuadFromTex, @@ -158,39 +163,37 @@ THREE.WebGLRenderer.prototype.renderScreenQuadFromTex = (function () { } })() -THREE.WebGLRenderer.prototype.renderScreenQuadFromTexWithDistortion = - (function () { - const _material = new ScreenQuadMaterial({ - uniforms: { coef: { type: 'f', value: 1.0 } }, - fragmentShader: fragmentScreenQuadFromTexWithDistortion - }) - - return function (srcTex, coef) { - _material.uniforms.srcTex.value = srcTex - _material.uniforms.coef.value = coef - this.renderScreenQuad(_material) - } - })() +WebGLRenderer.prototype.renderScreenQuadFromTexWithDistortion = (function () { + const _material = new ScreenQuadMaterial({ + uniforms: { coef: { type: 'f', value: 1.0 } }, + fragmentShader: fragmentScreenQuadFromTexWithDistortion + }) + + return function (srcTex, coef) { + _material.uniforms.srcTex.value = srcTex + _material.uniforms.coef.value = coef + this.renderScreenQuad(_material) + } +})() /** * @param {number} angle - Field of view in degrees. */ -THREE.PerspectiveCamera.prototype.setMinimalFov = function (angle) { +PerspectiveCamera.prototype.setMinimalFov = function (angle) { if (this.aspect >= 1.0) { this.fov = angle } else { - this.fov = THREE.MathUtils.radToDeg( - 2 * - Math.atan(Math.tan(THREE.MathUtils.degToRad(angle) * 0.5) / this.aspect) + this.fov = MathUtils.radToDeg( + 2 * Math.atan(Math.tan(MathUtils.degToRad(angle) * 0.5) / this.aspect) ) } } /** - * @param {THREE.PerspectiveCamera} camera - Base camera for this stereo camera. + * @param {PerspectiveCamera} camera - Base camera for this stereo camera. * @param {number} angle - Field of view in degrees. */ -THREE.StereoCamera.prototype.updateHalfSized = function (camera, angle) { +StereoCamera.prototype.updateHalfSized = function (camera, angle) { const originalAspect = camera.aspect const originalFov = camera.fov @@ -209,17 +212,17 @@ THREE.StereoCamera.prototype.updateHalfSized = function (camera, angle) { * @param {number} radius - Radius of bounding sphere in angstroms to fit on screen. * @param {number} angle - Field of view in degrees. */ -THREE.PerspectiveCamera.prototype.setDistanceToFit = function (radius, angle) { - this.position.z = radius / Math.sin(0.5 * THREE.MathUtils.degToRad(angle)) +PerspectiveCamera.prototype.setDistanceToFit = function (radius, angle) { + this.position.z = radius / Math.sin(0.5 * MathUtils.degToRad(angle)) } /** * @param {RCGroup} gfxObj - All objects on scene. - * @param {THREE.PerspectiveCamera} camera - Camera used for rendering. + * @param {PerspectiveCamera} camera - Camera used for rendering. * @param {number} clipPlane - Distance to clip plane. * @param {number} fogFarPlane - Distance to fog far plane. */ -THREE.Raycaster.prototype.intersectVisibleObject = function ( +Raycaster.prototype.intersectVisibleObject = function ( gfxObj, camera, clipPlane, @@ -234,7 +237,7 @@ THREE.Raycaster.prototype.intersectVisibleObject = function ( const nearPlane = Math.min(camera.near, clipPlane) let i let p = intersects[0] - const v = new THREE.Vector3() + const v = new Vector3() for (i = 0; i < intersects.length; ++i) { p = intersects[i] v.copy(p.point) @@ -257,8 +260,8 @@ THREE.Raycaster.prototype.intersectVisibleObject = function ( return p } -THREE.Matrix4.prototype.extractScale = (function () { - const _v = new THREE.Vector3() +Matrix4.prototype.extractScale = (function () { + const _v = new Vector3() return function (scale) { if (scale === undefined) { @@ -284,14 +287,14 @@ THREE.Matrix4.prototype.extractScale = (function () { function _calcCylinderMatrix(posBegin, posEnd, radius) { const posCenter = posBegin.clone().lerp(posEnd, 0.5) - const matScale = new THREE.Matrix4() + const matScale = new Matrix4() matScale.makeScale(radius, posBegin.distanceTo(posEnd), radius) - const matRotHalf = new THREE.Matrix4() + const matRotHalf = new Matrix4() matRotHalf.makeRotationX(Math.PI / 2) - const matRotLook = new THREE.Matrix4() - const vUp = new THREE.Vector3(0, 1, 0) + const matRotLook = new Matrix4() + const vUp = new Vector3(0, 1, 0) matRotLook.lookAt(posCenter, posEnd, vUp) matRotLook.multiply(matRotHalf) @@ -301,10 +304,10 @@ function _calcCylinderMatrix(posBegin, posEnd, radius) { } function _calcChunkMatrix(eye, target, up, rad) { - const matScale = new THREE.Matrix4() + const matScale = new Matrix4() matScale.makeScale(rad.x, rad.y, 0) - const matRotLook = new THREE.Matrix4() + const matRotLook = new Matrix4() matRotLook.lookAt(eye, target, up) matRotLook.multiply(matScale) matRotLook.setPosition(eye) @@ -341,12 +344,7 @@ function _buildDistorionMesh(widthSegments, heightSegements, coef) { return 1.0 / dr } - const geo = new THREE.PlaneBufferGeometry( - 2.0, - 2.0, - widthSegments, - heightSegements - ) + const geo = new PlaneBufferGeometry(2.0, 2.0, widthSegments, heightSegements) const pos = geo.getAttribute('position') for (let i = 0; i < pos.count; ++i) { @@ -359,7 +357,7 @@ function _buildDistorionMesh(widthSegments, heightSegements, coef) { return geo } -THREE.BufferAttribute.prototype.copyAtList = function (attribute, indexList) { +BufferAttribute.prototype.copyAtList = function (attribute, indexList) { console.assert( this.itemSize === attribute.itemSize, 'DEBUG: BufferAttribute.copyAtList buffers have different item size.' @@ -382,7 +380,7 @@ function fillArray(array, value, startIndex, endIndex) { } } -/** @param {THREE.Object3D} object - Parent object. */ +/** @param {Object3D} object - Parent object. */ function removeChildren(object) { const { children } = object for (let i = 0, n = children.length; i < n; ++i) { @@ -396,9 +394,9 @@ function removeChildren(object) { function clearTree(object) { object.traverse((obj) => { if ( - obj instanceof THREE.Mesh || - obj instanceof THREE.LineSegments || - obj instanceof THREE.Line + obj instanceof Mesh || + obj instanceof LineSegments || + obj instanceof Line ) { obj.geometry.dispose() } @@ -440,14 +438,14 @@ function applySelectionMaterial(geo) { node.material = node.material.clone(true) // using z-offset to magically fix selection rendering artifact (on z-sprites) node.material.setValues({ - depthFunc: THREE.LessEqualDepth, + depthFunc: LessEqualDepth, overrideColor: true, fog: false, lights: false, shadowmap: false }) node.material.setUberOptions({ - fixedColor: new THREE.Color(0xffff00), + fixedColor: new Color(0xffff00), zOffset: -1e-6 }) } @@ -455,7 +453,7 @@ function applySelectionMaterial(geo) { } function getMiddlePoint(point1, point2, optionalTarget) { - const result = optionalTarget || new THREE.Vector3() + const result = optionalTarget || new Vector3() result.set(0, 0, 0) result.addScaledVector(point1, 0.5) @@ -466,10 +464,9 @@ function getMiddlePoint(point1, point2, optionalTarget) { // Monkey-patch for "InstancedBufferGeometry.instanceCount becomes undefined after copy()" // https://github.com/mrdoob/three.js/issues/22151 -const _oldInstancedBufferGeometryCopy = - THREE.InstancedBufferGeometry.prototype.copy +const _oldInstancedBufferGeometryCopy = InstancedBufferGeometry.prototype.copy -THREE.InstancedBufferGeometry.prototype.copy = function (source) { +InstancedBufferGeometry.prototype.copy = function (source) { _oldInstancedBufferGeometryCopy.call(this, source) if (this.instanceCount === undefined) { this.instanceCount = Infinity diff --git a/packages/lib/src/gfx/materials.js b/packages/lib/src/gfx/materials.js index 86882d31..9a7bdf6c 100644 --- a/packages/lib/src/gfx/materials.js +++ b/packages/lib/src/gfx/materials.js @@ -1,8 +1,8 @@ -import * as THREE from 'three' +import { Color } from 'three' import EntityList from '../utils/EntityList' function neutralColor(intensity) { - return new THREE.Color(intensity, intensity, intensity) + return new Color(intensity, intensity, intensity) } const materialList = [ diff --git a/packages/lib/src/gfx/meshes/InstancedMesh.js b/packages/lib/src/gfx/meshes/InstancedMesh.js index 4b1be2cf..5416b092 100644 --- a/packages/lib/src/gfx/meshes/InstancedMesh.js +++ b/packages/lib/src/gfx/meshes/InstancedMesh.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' import UberObject from './UberObject' +import { Mesh } from 'three' -const Mesh = UberObject(THREE.Mesh) +const OurMesh = UberObject(Mesh) -class InstancedMesh extends Mesh { +class InstancedMesh extends OurMesh { constructor(...rest) { super(...rest) this.castShadow = true diff --git a/packages/lib/src/gfx/meshes/SimpleMesh.js b/packages/lib/src/gfx/meshes/SimpleMesh.js index f99888fc..007a305d 100644 --- a/packages/lib/src/gfx/meshes/SimpleMesh.js +++ b/packages/lib/src/gfx/meshes/SimpleMesh.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' import UberObject from './UberObject' +import { Mesh } from 'three' -const Mesh = UberObject(THREE.Mesh) +const OurMesh = UberObject(Mesh) -class SimpleMesh extends Mesh { +class SimpleMesh extends OurMesh { constructor(geometry, material) { super(geometry, material) this.castShadow = true diff --git a/packages/lib/src/gfx/meshes/TextMesh.js b/packages/lib/src/gfx/meshes/TextMesh.js index f71b36f0..9fda581a 100644 --- a/packages/lib/src/gfx/meshes/TextMesh.js +++ b/packages/lib/src/gfx/meshes/TextMesh.js @@ -1,9 +1,9 @@ -import _ from 'lodash' -import * as THREE from 'three' import CSS2DObject from '../CSS2DObject' import utils from '../../utils' +import { Group } from 'three' +import { clone } from 'lodash' -class TextMesh extends THREE.Group { +class TextMesh extends Group { constructor(geometry, _material) { super() this.geometry = geometry @@ -29,7 +29,7 @@ class TextMesh extends THREE.Group { } const item = utils.shallowCloneNode(srcItem) const label = new CSS2DObject(item) - label.userData = _.clone(userData) + label.userData = clone(userData) const el = label.getElement() el.style.visibility = 'visible' label.source = srcItem diff --git a/packages/lib/src/gfx/meshes/ThickLineMesh.js b/packages/lib/src/gfx/meshes/ThickLineMesh.js index 5c37f099..b123d668 100644 --- a/packages/lib/src/gfx/meshes/ThickLineMesh.js +++ b/packages/lib/src/gfx/meshes/ThickLineMesh.js @@ -1,10 +1,10 @@ -import * as THREE from 'three' import UberObject from './UberObject' +import { Mesh, Vector2 } from 'three' -const Mesh = UberObject(THREE.Mesh) -const _viewport = new THREE.Vector2() +const OurMesh = UberObject(Mesh) +const _viewport = new Vector2() -class ThickLineMesh extends Mesh { +class ThickLineMesh extends OurMesh { _onBeforeRender(renderer, scene, camera, _geometry, _material, _group) { const { material } = this if (!material.uberOptions) { diff --git a/packages/lib/src/gfx/meshes/TransformGroup.js b/packages/lib/src/gfx/meshes/TransformGroup.js index f275a17e..ff30e27f 100644 --- a/packages/lib/src/gfx/meshes/TransformGroup.js +++ b/packages/lib/src/gfx/meshes/TransformGroup.js @@ -1,10 +1,10 @@ -import * as THREE from 'three' import gfxutils from '../gfxutils' +import { Matrix4, Object3D, Ray } from 'three' -class TransformGroup extends THREE.Object3D { - static _inverseMatrix = new THREE.Matrix4() +class TransformGroup extends Object3D { + static _inverseMatrix = new Matrix4() - static _ray = new THREE.Ray() + static _ray = new Ray() constructor(geometry, geoParams, material, transforms) { super() @@ -13,8 +13,7 @@ class TransformGroup extends THREE.Object3D { const mat = material.createInstance() geoParams.initMaterial(mat) this._material = mat - this._transforms = - transforms.length > 0 ? transforms : [new THREE.Matrix4()] + this._transforms = transforms.length > 0 ? transforms : [new Matrix4()] const meshes = this._createMeshes(geometry) for (let i = 0, n = meshes.length; i < n; ++i) { this.add(meshes[i]) diff --git a/packages/lib/src/gfx/meshes/ZClippedMesh.js b/packages/lib/src/gfx/meshes/ZClippedMesh.js index 4634332b..ec6d7c04 100644 --- a/packages/lib/src/gfx/meshes/ZClippedMesh.js +++ b/packages/lib/src/gfx/meshes/ZClippedMesh.js @@ -1,23 +1,23 @@ -import * as THREE from 'three' import UberObject from './UberObject' +import { Matrix4, Mesh, Vector3 } from 'three' -const Mesh = UberObject(THREE.Mesh) +const OurMesh = UberObject(Mesh) -class ZClippedMesh extends Mesh { +class ZClippedMesh extends OurMesh { constructor(geometry, material) { super(geometry, material) this.castShadow = true this.receiveShadow = true } - static _mvLength = new THREE.Vector3() + static _mvLength = new Vector3() - static _center = new THREE.Vector3() + static _center = new Vector3() - static _modelView = new THREE.Matrix4() + static _modelView = new Matrix4() _onBeforeRender(renderer, scene, camera) { - Mesh.prototype._onBeforeRender.call(this, renderer, scene, camera) + OurMesh.prototype._onBeforeRender.call(this, renderer, scene, camera) const geo = this.geometry const { material } = this diff --git a/packages/lib/src/gfx/meshes/ZSpriteMesh.js b/packages/lib/src/gfx/meshes/ZSpriteMesh.js index 375e803b..c86cef46 100644 --- a/packages/lib/src/gfx/meshes/ZSpriteMesh.js +++ b/packages/lib/src/gfx/meshes/ZSpriteMesh.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' import UberObject from './UberObject' +import { Mesh } from 'three' -const Mesh = UberObject(THREE.Mesh) +const OurMesh = UberObject(Mesh) -class ZSpriteMesh extends Mesh { +class ZSpriteMesh extends OurMesh { constructor(...rest) { super(...rest) this.castShadow = true @@ -11,7 +11,7 @@ class ZSpriteMesh extends Mesh { } _onBeforeRender(renderer, scene, camera, _geometry, _material, _group) { - Mesh.prototype._onBeforeRender.call(this, renderer, scene, camera) + OurMesh.prototype._onBeforeRender.call(this, renderer, scene, camera) const { material } = this if (!material) { return diff --git a/packages/lib/src/gfx/meshes/meshes.js b/packages/lib/src/gfx/meshes/meshes.js index 2599d011..23d1cdf6 100644 --- a/packages/lib/src/gfx/meshes/meshes.js +++ b/packages/lib/src/gfx/meshes/meshes.js @@ -1,4 +1,3 @@ -import * as THREE from 'three' import UberObject from './UberObject' import ZSpriteMesh from './ZSpriteMesh' import ZClippedMesh from './ZClippedMesh' @@ -6,13 +5,14 @@ import TextMesh from './TextMesh' import SimpleMesh from './SimpleMesh' import ThickLineMesh from './ThickLineMesh' import InstancedMesh from './InstancedMesh' +import { Line, LineSegments } from 'three' export default { ZClipped: ZClippedMesh, ZSprite: ZSpriteMesh, Text: TextMesh, - Line: UberObject(THREE.Line), - LineSegments: UberObject(THREE.LineSegments), + Line: UberObject(Line), + LineSegments: UberObject(LineSegments), Mesh: SimpleMesh, ThickLineMesh, Instanced: InstancedMesh diff --git a/packages/lib/src/gfx/meshutils.js b/packages/lib/src/gfx/meshutils.js index e3e0011c..c33710dc 100644 --- a/packages/lib/src/gfx/meshutils.js +++ b/packages/lib/src/gfx/meshutils.js @@ -5,9 +5,17 @@ * functions for traversihg tree and create auxiliary meshes for transparency/shadowmaps... * functions for calculating data connected with meshes */ -import * as THREE from 'three' + import UberMaterial from './shaders/UberMaterial' import gfxutils from './gfxutils' +import { + BufferGeometry, + InstancedBufferAttribute, + InstancedBufferGeometry, + Line, + LineSegments, + Mesh +} from 'three' function _gatherObjects(root, meshTypes) { const meshes = [] @@ -52,7 +60,7 @@ function applyTransformsToMeshes(root, mtc) { return } - const meshTypes = [THREE.Mesh, THREE.LineSegments, THREE.Line] + const meshTypes = [Mesh, LineSegments, Line] traverseMeshes(root, meshTypes, (mesh) => { mesh.applyMatrix4(mtc[0]) for (let j = 1; j < mtcCount; ++j) { @@ -79,7 +87,7 @@ const processTransparentMaterial = (function () { return } - traverseMeshes(root, [THREE.Mesh, THREE.LineSegments], (mesh) => { + traverseMeshes(root, [Mesh, LineSegments], (mesh) => { mesh.material.setValues({ prepassTransparancy: false, fakeOpacity: false @@ -118,7 +126,7 @@ const processColFromPosMaterial = (function () { return } - traverseMeshes(root, [THREE.Mesh, THREE.LineSegments], (mesh) => { + traverseMeshes(root, [Mesh, LineSegments], (mesh) => { const colFromPosMesh = createDerivativeMesh( mesh, matValues, @@ -142,7 +150,7 @@ const createShadowmapMaterial = (function () { if (!(material instanceof UberMaterial)) { return } - traverseMeshes(root, [THREE.Mesh, THREE.LineSegments], (mesh) => { + traverseMeshes(root, [Mesh, LineSegments], (mesh) => { if (!mesh.receiveShadow && mesh.material.shadowmap) { // remove shadow from non-receivers mesh.material.setValues({ shadowmap: false }) @@ -176,7 +184,7 @@ function removeShadowmapMaterial(root, material) { return } - traverseMeshes(root, [THREE.Mesh, THREE.LineSegments], (mesh) => { + traverseMeshes(root, [Mesh, LineSegments], (mesh) => { if (mesh.isShadowmapMesh) { mesh.parent.remove(mesh) } @@ -185,7 +193,7 @@ function removeShadowmapMaterial(root, material) { function forEachMeshInGroup(group, process) { function processObj(object) { - if (object instanceof THREE.Mesh) { + if (object instanceof Mesh) { process(object) } for (let i = 0, l = object.children.length; i < l; i++) { @@ -197,12 +205,12 @@ function forEachMeshInGroup(group, process) { function _countMeshTriangles(mesh) { const geom = mesh.geometry - if (geom instanceof THREE.InstancedBufferGeometry) { + if (geom instanceof InstancedBufferGeometry) { const attribs = geom.attributes for (const property in attribs) { if ( attribs.hasOwnProperty(property) && - attribs[property] instanceof THREE.InstancedBufferAttribute + attribs[property] instanceof InstancedBufferAttribute ) { const currAttr = attribs[property] const indexSize = geom.index ? geom.index.array.length / 3 : 0 @@ -211,7 +219,7 @@ function _countMeshTriangles(mesh) { } return 0 } - if (geom instanceof THREE.BufferGeometry) { + if (geom instanceof BufferGeometry) { return geom.index ? geom.index.array.length / 3 : 0 } return geom.faces ? geom.faces.length : 0 diff --git a/packages/lib/src/gfx/modes/CartoonMode.js b/packages/lib/src/gfx/modes/CartoonMode.js index 73c9f8e5..c8e4f5ac 100644 --- a/packages/lib/src/gfx/modes/CartoonMode.js +++ b/packages/lib/src/gfx/modes/CartoonMode.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import Mode from './Mode' +import { Vector2 } from 'three' class CartoonMode extends Mode { static id = 'CA' @@ -70,15 +70,15 @@ class CartoonMode extends Mode { const tubeRad = this.opts.radius const secHeight = this.opts.depth - this.TUBE_RADIUS = new THREE.Vector2(tubeRad, tubeRad) - this.ARROW_END = new THREE.Vector2(secHeight, tubeRad) + this.TUBE_RADIUS = new Vector2(tubeRad, tubeRad) + this.ARROW_END = new Vector2(secHeight, tubeRad) const secCache = {} const secData = this.opts.ss /* eslint-disable guard-for-in */ for (const prop in secData) { secCache[prop] = { - center: new THREE.Vector2(secHeight, secData[prop].width), - start: new THREE.Vector2(secHeight, secData[prop].arrow) + center: new Vector2(secHeight, secData[prop].width), + start: new Vector2(secHeight, secData[prop].arrow) } } this.secCache = secCache diff --git a/packages/lib/src/gfx/modes/Mode.js b/packages/lib/src/gfx/modes/Mode.js index d8b90227..dbaa76bc 100644 --- a/packages/lib/src/gfx/modes/Mode.js +++ b/packages/lib/src/gfx/modes/Mode.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { merge, isArray, isEmpty } from 'lodash' import makeContextDependent from '../../utils/makeContextDependent' import utils from '../../utils' import gfxutils from '../gfxutils' @@ -27,7 +27,7 @@ class Mode { * Mode options inherited (prototyped) from defaults. * @type {object} */ - this.opts = _.merge( + this.opts = merge( utils.deriveDeep(this.settings.now.modes[this.id], true), opts ) @@ -41,7 +41,7 @@ class Mode { */ identify() { const diff = utils.objectsDiff(this.opts, this.settings.now.modes[this.id]) - if (!_.isEmpty(diff)) { + if (!isEmpty(diff)) { return [this.id, diff] } return this.id @@ -58,7 +58,7 @@ class Mode { for (let i = 0; i < groupCount; ++i) { let currGroup = groupList[i] let renderParams = {} - if (_.isArray(currGroup)) { + if (isArray(currGroup)) { renderParams = currGroup[1].call(this) ;[currGroup] = currGroup } diff --git a/packages/lib/src/gfx/modes/TextMode.js b/packages/lib/src/gfx/modes/TextMode.js index 78bae168..54993266 100644 --- a/packages/lib/src/gfx/modes/TextMode.js +++ b/packages/lib/src/gfx/modes/TextMode.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { merge } from 'lodash' import Mode from './Mode' class TextMode extends Mode { @@ -9,7 +9,7 @@ class TextMode extends Mode { } getLabelOpts() { - return _.merge(this.opts, { + return merge(this.opts, { colors: true, adjustColor: true, transparent: true diff --git a/packages/lib/src/gfx/modes/TubeMode.js b/packages/lib/src/gfx/modes/TubeMode.js index 9c64611b..9e71b733 100644 --- a/packages/lib/src/gfx/modes/TubeMode.js +++ b/packages/lib/src/gfx/modes/TubeMode.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import Mode from './Mode' +import { Vector2 } from 'three' class TubeMode extends Mode { static id = 'TU' @@ -18,7 +18,7 @@ class TubeMode extends Mode { buildGeometry(complex, colorer, mask, material) { const rad = this.opts.radius - this.TUBE_RADIUS = new THREE.Vector2(rad, rad) + this.TUBE_RADIUS = new Vector2(rad, rad) return Mode.prototype.buildGeometry.call( this, diff --git a/packages/lib/src/gfx/modes/groups/AromaticGroup.js b/packages/lib/src/gfx/modes/groups/AromaticGroup.js index 192eaca2..37c72af2 100644 --- a/packages/lib/src/gfx/modes/groups/AromaticGroup.js +++ b/packages/lib/src/gfx/modes/groups/AromaticGroup.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import AtomsGroup from './AtomsGroup' +import { Vector3 } from 'three' function _slerp(omega, v1, v2, t) { const oSin = Math.sin(omega) @@ -13,8 +13,8 @@ class AromaticGroup extends AtomsGroup { _buildInner(radOffset, addChunk) { const chunksToIdx = this._selection.chunks - const prevVector = new THREE.Vector3() - const currVector = new THREE.Vector3() + const prevVector = new Vector3() + const currVector = new Vector3() const segmentsHeight = this._segmentsHeight const leprStep = 1.0 / segmentsHeight const colorer = this._colorer diff --git a/packages/lib/src/gfx/modes/groups/AromaticTorusGroup.js b/packages/lib/src/gfx/modes/groups/AromaticTorusGroup.js index 1be7b9ab..bf83258c 100644 --- a/packages/lib/src/gfx/modes/groups/AromaticTorusGroup.js +++ b/packages/lib/src/gfx/modes/groups/AromaticTorusGroup.js @@ -1,12 +1,12 @@ -import * as THREE from 'three' import gfxutils from '../../gfxutils' import AromaticGroup from './AromaticGroup' +import { Vector2, Vector3 } from 'three' function _createShape(rad, parts) { const pts = [] for (let i = 0; i < parts; ++i) { const a = ((-2 * i) / parts) * Math.PI - pts.push(new THREE.Vector3(Math.cos(a) * rad, Math.sin(a) * rad, 0)) + pts.push(new Vector3(Math.cos(a) * rad, Math.sin(a) * rad, 0)) } return pts } @@ -16,9 +16,9 @@ class AromaticTorusGroup extends AromaticGroup { _build() { const segmentsHeight = this._segmentsHeight const torusRad = this._mode.getAromRadius() - const radiusV = new THREE.Vector2(torusRad, torusRad) + const radiusV = new Vector2(torusRad, torusRad) const radOffset = this._mode.calcStickRadius() + 2 * torusRad - const lookAtVector = new THREE.Vector3() + const lookAtVector = new Vector3() const mtc = [] const geo = this._geo this._buildInner(radOffset, (chunkIdx, color, points, center, upDir) => { diff --git a/packages/lib/src/gfx/modes/groups/BondsCylinderGroup.js b/packages/lib/src/gfx/modes/groups/BondsCylinderGroup.js index 389a741f..817a66fa 100644 --- a/packages/lib/src/gfx/modes/groups/BondsCylinderGroup.js +++ b/packages/lib/src/gfx/modes/groups/BondsCylinderGroup.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import BondsGroup from './BondsGroup' +import { Vector3 } from 'three' class BondsCylinderGroup extends BondsGroup { _build() { @@ -14,8 +14,8 @@ class BondsCylinderGroup extends BondsGroup { const stickRad = mode.calcStickRadius() const emptyOffset = mode.calcSpaceFraction() let normDir - const leftPos = new THREE.Vector3() - const rightPos = new THREE.Vector3() + const leftPos = new Vector3() + const rightPos = new Vector3() let currBondIdx = 0 const chunksToIdx = [] for (let i = 0, n = bondsIdc.length; i < n; ++i) { @@ -71,8 +71,8 @@ class BondsCylinderGroup extends BondsGroup { const stickRad = mode.calcStickRadius() const emptyOffset = mode.calcSpaceFraction() let normDir - const leftPos = new THREE.Vector3() - const rightPos = new THREE.Vector3() + const leftPos = new Vector3() + const rightPos = new Vector3() let currBondIdx = 0 const updateColor = frameData.needsColorUpdate(colorer) for (let i = 0, n = bondsIdc.length; i < n; ++i) { diff --git a/packages/lib/src/gfx/modes/groups/BondsLinesGroup.js b/packages/lib/src/gfx/modes/groups/BondsLinesGroup.js index 88f1c803..8047e54e 100644 --- a/packages/lib/src/gfx/modes/groups/BondsLinesGroup.js +++ b/packages/lib/src/gfx/modes/groups/BondsLinesGroup.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import BondsGroup from './BondsGroup' +import { Vector3 } from 'three' const STEP_SIZE = 0.15 @@ -13,10 +13,10 @@ class BondsLinesGroup extends BondsGroup { const drawMultiple = mode.drawMultiorderBonds() const showAromatic = mode.showAromaticLoops() - const bondDir = new THREE.Vector3() + const bondDir = new Vector3() - const leftPos = new THREE.Vector3() - const rightPos = new THREE.Vector3() + const leftPos = new Vector3() + const rightPos = new Vector3() let currBondIdx = 0 const chunksToIdx = [] for (let i = 0, n = bondsIdc.length; i < n; ++i) { @@ -78,10 +78,10 @@ class BondsLinesGroup extends BondsGroup { const drawMultiple = mode.drawMultiorderBonds() const showAromatic = mode.showAromaticLoops() - const bondDir = new THREE.Vector3() + const bondDir = new Vector3() - const leftPos = new THREE.Vector3() - const rightPos = new THREE.Vector3() + const leftPos = new Vector3() + const rightPos = new Vector3() let currBondIdx = 0 const updateColor = frameData.needsColorUpdate(colorer) for (let i = 0, n = bondsIdc.length; i < n; ++i) { diff --git a/packages/lib/src/gfx/modes/groups/CartoonHelper.js b/packages/lib/src/gfx/modes/groups/CartoonHelper.js index abe38b18..de1ca71b 100644 --- a/packages/lib/src/gfx/modes/groups/CartoonHelper.js +++ b/packages/lib/src/gfx/modes/groups/CartoonHelper.js @@ -1,7 +1,7 @@ -import * as THREE from 'three' import { Smooth } from '../../../vendors/Smooth' import gfxutils from '../../gfxutils' import chem from '../../../chem' +import { Vector2, Vector3 } from 'three' const { ResidueType } = chem @@ -25,7 +25,7 @@ function _buildStructureInterpolator(points, tension) { } const newt = transformT(t) const ans = path(newt) - return new THREE.Vector3(ans[0], ans[1], ans[2]) + return new Vector3(ans[0], ans[1], ans[2]) } } @@ -180,7 +180,7 @@ class CartoonHelper { prepareMatrices(idx, firstRad, secondRad) { const mtcCount = this._segmentsCount const outMtc = new Array(mtcCount) - const currRad = new THREE.Vector2(0, 0) + const currRad = new Vector2(0, 0) const topInterp = this._topInterp const cenInterp = this._centerInterp diff --git a/packages/lib/src/gfx/modes/groups/ResiduesSubseqGroup.js b/packages/lib/src/gfx/modes/groups/ResiduesSubseqGroup.js index 2d0d8eb8..bc23b897 100644 --- a/packages/lib/src/gfx/modes/groups/ResiduesSubseqGroup.js +++ b/packages/lib/src/gfx/modes/groups/ResiduesSubseqGroup.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' import ResiduesGroup from './ResiduesGroup' import CartoonHelper from './CartoonHelper' +import { Vector3 } from 'three' function _createShape(rad, parts) { const pts = [] @@ -9,7 +9,7 @@ function _createShape(rad, parts) { // starts from pi/2 because it's important that points are lied on the angles of arrows (visual issues if not) const a = Math.PI / 2.0 - (2 * Math.PI * i) / parts - pts.push(new THREE.Vector3(Math.cos(a) * rad, Math.sin(a) * rad, 0)) + pts.push(new Vector3(Math.cos(a) * rad, Math.sin(a) * rad, 0)) } return pts } diff --git a/packages/lib/src/gfx/noiseTexture.js b/packages/lib/src/gfx/noiseTexture.js index 0ac8d62c..6a51a94c 100644 --- a/packages/lib/src/gfx/noiseTexture.js +++ b/packages/lib/src/gfx/noiseTexture.js @@ -1,4 +1,11 @@ -import * as THREE from 'three' +import { + DataTexture, + NearestFilter, + RepeatWrapping, + RGBFormat, + UnsignedByteType, + UVMapping +} from 'three' const noiseWidth = 4 const noiseHeight = 4 @@ -7,17 +14,17 @@ const _noiseData = new Uint8Array([ 0, 160, 4, 0, 226, 46, 0, 224, 211, 0, 3, 157, 0, 174, 247, 0, 12, 182, 0, 220, 216, 0, 1, 109, 0, 253, 154, 0 ]) -const _noiseWrapS = THREE.RepeatWrapping -const _noiseWrapT = THREE.RepeatWrapping -const _noiseMinFilter = THREE.NearestFilter -const _noiseMagFilter = THREE.NearestFilter -const _noiseMapping = THREE.UVMapping -const noiseTexture = new THREE.DataTexture( +const _noiseWrapS = RepeatWrapping +const _noiseWrapT = RepeatWrapping +const _noiseMinFilter = NearestFilter +const _noiseMagFilter = NearestFilter +const _noiseMapping = UVMapping +const noiseTexture = new DataTexture( _noiseData, noiseWidth, noiseHeight, - THREE.RGBFormat, - THREE.UnsignedByteType, + RGBFormat, + UnsignedByteType, _noiseMapping, _noiseWrapS, _noiseWrapT, diff --git a/packages/lib/src/gfx/objects/LinesObj.js b/packages/lib/src/gfx/objects/LinesObj.js index 3bd6468d..a1eac133 100644 --- a/packages/lib/src/gfx/objects/LinesObj.js +++ b/packages/lib/src/gfx/objects/LinesObj.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' import SceneObject from './SceneObject' import meshutils from '../meshutils' import UberMaterial from '../shaders/UberMaterial' import meshes from '../meshes/meshes' import settings from '../../settings' +import { BufferAttribute, BufferGeometry, Group, Color } from 'three' class LinesObj extends SceneObject { constructor(params, opts) { @@ -25,7 +25,7 @@ class LinesObj extends SceneObject { } build(complex) { - const geom = new THREE.BufferGeometry() + const geom = new BufferGeometry() this._atom1 = this._getAtomFromName(complex, this._id1) this._atom2 = this._getAtomFromName(complex, this._id2) @@ -33,7 +33,7 @@ class LinesObj extends SceneObject { const p2 = this._atom2.position const vertices = new Float32Array([p1.x, p1.y, p1.z, p2.x, p2.y, p2.z]) - geom.setAttribute('position', new THREE.BufferAttribute(vertices, 3)) + geom.setAttribute('position', new BufferAttribute(vertices, 3)) geom.computeBoundingBox() const material = new UberMaterial() material.setValues({ @@ -46,7 +46,7 @@ class LinesObj extends SceneObject { this._line = new meshes.Line(geom, material) this._line.computeLineDistances() this._line.material.setUberOptions({ - fixedColor: new THREE.Color(this.opts.color), + fixedColor: new Color(this.opts.color), dashedLineSize: this.opts.dashSize, dashedLinePeriod: this.opts.dashSize + this.opts.gapSize }) @@ -56,7 +56,7 @@ class LinesObj extends SceneObject { this._mesh = this._line const transforms = complex.getTransforms() if (transforms.length > 0) { - this._mesh = new THREE.Group() + this._mesh = new Group() this._mesh.add(this._line) meshutils.applyTransformsToMeshes(this._mesh, transforms) } diff --git a/packages/lib/src/gfx/objects/SceneObject.js b/packages/lib/src/gfx/objects/SceneObject.js index 305fbad7..f559657b 100644 --- a/packages/lib/src/gfx/objects/SceneObject.js +++ b/packages/lib/src/gfx/objects/SceneObject.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { isEmpty, merge } from 'lodash' import settings from '../../settings' import utils from '../../utils' import gfxutils from '../gfxutils' @@ -28,7 +28,7 @@ class SceneObject { * @type {object} */ this.params = params - this.opts = _.merge( + this.opts = merge( utils.deriveDeep(settings.now.objects[this.type], true), opts ) @@ -49,7 +49,7 @@ class SceneObject { params: this.params } const diff = utils.objectsDiff(this.opts, settings.now.modes[this.id]) - if (!_.isEmpty(diff)) { + if (!isEmpty(diff)) { result.opts = diff } return result diff --git a/packages/lib/src/gfx/palettes/Palette.js b/packages/lib/src/gfx/palettes/Palette.js index d1de94af..19ca4845 100644 --- a/packages/lib/src/gfx/palettes/Palette.js +++ b/packages/lib/src/gfx/palettes/Palette.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { assign } from 'lodash' function clamp(x, a, b) { return x <= b ? (x < 0 ? 0 : x) : b @@ -72,7 +72,7 @@ class Palette { } } -_.assign(Palette.prototype, { +assign(Palette.prototype, { colors: [0xffffff, 0xff0000, 0x00ff00, 0x0000ff, 0x808080], minRangeColor: 0x000000, diff --git a/packages/lib/src/gfx/shaders/AOHorBlurMaterial.js b/packages/lib/src/gfx/shaders/AOHorBlurMaterial.js index 0f1a8386..14858a6a 100644 --- a/packages/lib/src/gfx/shaders/AOHorBlurMaterial.js +++ b/packages/lib/src/gfx/shaders/AOHorBlurMaterial.js @@ -1,12 +1,13 @@ /* eslint-disable no-magic-numbers */ /* eslint-disable guard-for-in */ -import * as THREE from 'three' + import vertexShader from './ScreenQuad.vert' import fragmentShader from './AOHorBlur.frag' +import { RawShaderMaterial, Vector2 } from 'three' const _kernelOffsets = [-2.0, -1.0, 0.0, 1.0, 2.0] -class AOHorBlurMaterial extends THREE.RawShaderMaterial { +class AOHorBlurMaterial extends RawShaderMaterial { constructor() { super() @@ -16,7 +17,7 @@ class AOHorBlurMaterial extends THREE.RawShaderMaterial { depthTexture: { type: 't', value: null }, srcTexelSize: { type: 'v2', - value: new THREE.Vector2(1.0 / 512.0, 1.0 / 512.0) + value: new Vector2(1.0 / 512.0, 1.0 / 512.0) }, aoMap: { type: 't', value: null }, samplesOffsets: { type: 'fv1', value: _kernelOffsets } diff --git a/packages/lib/src/gfx/shaders/AOMaterial.js b/packages/lib/src/gfx/shaders/AOMaterial.js index 7cbace1d..1a2958ad 100644 --- a/packages/lib/src/gfx/shaders/AOMaterial.js +++ b/packages/lib/src/gfx/shaders/AOMaterial.js @@ -1,47 +1,48 @@ /* eslint-disable no-magic-numbers */ /* eslint-disable guard-for-in */ -import * as THREE from 'three' + import vertexShader from './ScreenQuad.vert' import fragmentShader from './AO.frag' import noise from '../noiseTexture' +import { Matrix4, RawShaderMaterial, Vector2, Vector3 } from 'three' const _samplesKernel = [ // hemisphere samples adopted to sphere - new THREE.Vector3(0.295184, 0.077723, 0.068429), - new THREE.Vector3(-0.271976, -0.365221, 0.838363), - new THREE.Vector3(0.547713, 0.467576, 0.488515), - new THREE.Vector3(0.662808, -0.031733, 0.584758), - new THREE.Vector3(-0.025717, 0.218955, 0.657094), - new THREE.Vector3(-0.310153, -0.365223, 0.370701), - new THREE.Vector3(-0.101407, -0.006313, 0.747665), - new THREE.Vector3(-0.769138, 0.360399, 0.086847), - new THREE.Vector3(-0.271988, -0.27514, 0.905353), - new THREE.Vector3(0.09674, -0.566901, 0.700151), - new THREE.Vector3(0.562872, -0.735136, 0.094647), - new THREE.Vector3(0.379877, 0.359278, 0.190061), - new THREE.Vector3(0.519064, -0.023055, 0.405068), - new THREE.Vector3(-0.301036, 0.114696, 0.088885), - new THREE.Vector3(-0.282922, 0.598305, 0.487214), - new THREE.Vector3(-0.181859, 0.25167, 0.679702), - new THREE.Vector3(-0.191463, -0.635818, 0.512919), - new THREE.Vector3(-0.293655, 0.427423, 0.078921), - new THREE.Vector3(-0.267983, 0.680534, 0.13288), - new THREE.Vector3(0.139611, 0.319637, 0.477439), - new THREE.Vector3(-0.352086, 0.31104, 0.653913), - new THREE.Vector3(0.321032, 0.805279, 0.487345), - new THREE.Vector3(0.073516, 0.820734, 0.414183), - new THREE.Vector3(-0.155324, 0.589983, 0.41146), - new THREE.Vector3(0.335976, 0.170782, 0.527627), - new THREE.Vector3(0.46346, -0.355658, 0.167689), - new THREE.Vector3(0.222654, 0.59655, 0.769406), - new THREE.Vector3(0.922138, -0.04207, 0.147555), - new THREE.Vector3(-0.72705, -0.329192, 0.369826), - new THREE.Vector3(-0.090731, 0.53382, 0.463767), - new THREE.Vector3(-0.323457, -0.876559, 0.238524), - new THREE.Vector3(-0.663277, -0.372384, 0.342856) + new Vector3(0.295184, 0.077723, 0.068429), + new Vector3(-0.271976, -0.365221, 0.838363), + new Vector3(0.547713, 0.467576, 0.488515), + new Vector3(0.662808, -0.031733, 0.584758), + new Vector3(-0.025717, 0.218955, 0.657094), + new Vector3(-0.310153, -0.365223, 0.370701), + new Vector3(-0.101407, -0.006313, 0.747665), + new Vector3(-0.769138, 0.360399, 0.086847), + new Vector3(-0.271988, -0.27514, 0.905353), + new Vector3(0.09674, -0.566901, 0.700151), + new Vector3(0.562872, -0.735136, 0.094647), + new Vector3(0.379877, 0.359278, 0.190061), + new Vector3(0.519064, -0.023055, 0.405068), + new Vector3(-0.301036, 0.114696, 0.088885), + new Vector3(-0.282922, 0.598305, 0.487214), + new Vector3(-0.181859, 0.25167, 0.679702), + new Vector3(-0.191463, -0.635818, 0.512919), + new Vector3(-0.293655, 0.427423, 0.078921), + new Vector3(-0.267983, 0.680534, 0.13288), + new Vector3(0.139611, 0.319637, 0.477439), + new Vector3(-0.352086, 0.31104, 0.653913), + new Vector3(0.321032, 0.805279, 0.487345), + new Vector3(0.073516, 0.820734, 0.414183), + new Vector3(-0.155324, 0.589983, 0.41146), + new Vector3(0.335976, 0.170782, 0.527627), + new Vector3(0.46346, -0.355658, 0.167689), + new Vector3(0.222654, 0.59655, 0.769406), + new Vector3(0.922138, -0.04207, 0.147555), + new Vector3(-0.72705, -0.329192, 0.369826), + new Vector3(-0.090731, 0.53382, 0.463767), + new Vector3(-0.323457, -0.876559, 0.238524), + new Vector3(-0.663277, -0.372384, 0.342856) ] -class AOMaterial extends THREE.RawShaderMaterial { +class AOMaterial extends RawShaderMaterial { constructor() { super() @@ -51,20 +52,17 @@ class AOMaterial extends THREE.RawShaderMaterial { noiseTexture: { type: 't', value: noise.noiseTexture }, noiseTexelSize: { type: 'v2', - value: new THREE.Vector2( - 1.0 / noise.noiseWidth, - 1.0 / noise.noiseHeight - ) + value: new Vector2(1.0 / noise.noiseWidth, 1.0 / noise.noiseHeight) }, diffuseTexture: { type: 't', value: null }, normalTexture: { type: 't', value: null }, depthTexture: { type: 't', value: null }, srcTexelSize: { type: 'v2', - value: new THREE.Vector2(1.0 / 512.0, 1.0 / 512.0) + value: new Vector2(1.0 / 512.0, 1.0 / 512.0) }, - camNearFar: { type: 'v2', value: new THREE.Vector2(1.0, 10.0) }, - projMatrix: { type: 'mat4', value: new THREE.Matrix4() }, + camNearFar: { type: 'v2', value: new Vector2(1.0, 10.0) }, + projMatrix: { type: 'mat4', value: new Matrix4() }, aspectRatio: { type: 'f', value: 0.0 }, tanHalfFOV: { type: 'f', value: 0.0 }, samplesKernel: { type: 'v3v', value: _samplesKernel }, diff --git a/packages/lib/src/gfx/shaders/AOVertBlurWithBlendMaterial.js b/packages/lib/src/gfx/shaders/AOVertBlurWithBlendMaterial.js index 30216437..a0e310ec 100644 --- a/packages/lib/src/gfx/shaders/AOVertBlurWithBlendMaterial.js +++ b/packages/lib/src/gfx/shaders/AOVertBlurWithBlendMaterial.js @@ -1,12 +1,13 @@ /* eslint-disable no-magic-numbers */ /* eslint-disable guard-for-in */ -import * as THREE from 'three' + import vertexShader from './ScreenQuad.vert' import fragmentShader from './AOVertBlurWithBlend.frag' +import { Matrix4, RawShaderMaterial, Vector2, Vector4 } from 'three' const _kernelOffsets = [-2.0, -1.0, 0.0, 1.0, 2.0] -class AOVertBlurWithBlendMaterial extends THREE.RawShaderMaterial { +class AOVertBlurWithBlendMaterial extends RawShaderMaterial { constructor(params) { super(params) @@ -17,15 +18,15 @@ class AOVertBlurWithBlendMaterial extends THREE.RawShaderMaterial { depthTexture: { type: 't', value: null }, srcTexelSize: { type: 'v2', - value: new THREE.Vector2(1.0 / 512.0, 1.0 / 512.0) + value: new Vector2(1.0 / 512.0, 1.0 / 512.0) }, aoMap: { type: 't', value: null }, samplesOffsets: { type: 'fv1', value: _kernelOffsets }, - projMatrix: { type: 'mat4', value: new THREE.Matrix4() }, + projMatrix: { type: 'mat4', value: new Matrix4() }, aspectRatio: { type: 'f', value: 0.0 }, tanHalfFOV: { type: 'f', value: 0.0 }, - fogNearFar: { type: 'v2', value: new THREE.Vector2(100.0, 100.0) }, - fogColor: { type: 'v4', value: new THREE.Vector4(0.0, 0.5, 0.0, 1.0) } + fogNearFar: { type: 'v2', value: new Vector2(100.0, 100.0) }, + fogColor: { type: 'v4', value: new Vector4(0.0, 0.5, 0.0, 1.0) } }, vertexShader, fragmentShader, diff --git a/packages/lib/src/gfx/shaders/AnaglyphMaterial.js b/packages/lib/src/gfx/shaders/AnaglyphMaterial.js index a0f9a654..da6abde1 100644 --- a/packages/lib/src/gfx/shaders/AnaglyphMaterial.js +++ b/packages/lib/src/gfx/shaders/AnaglyphMaterial.js @@ -1,10 +1,11 @@ /* eslint-disable no-magic-numbers */ /* eslint-disable guard-for-in */ -import * as THREE from 'three' + import vertexShader from './ScreenQuad.vert' import fragmentShader from './Anaglyph.frag' +import { RawShaderMaterial } from 'three' -class AnaglyphMaterial extends THREE.RawShaderMaterial { +class AnaglyphMaterial extends RawShaderMaterial { constructor() { super() const settings = { diff --git a/packages/lib/src/gfx/shaders/FXAAMaterial.js b/packages/lib/src/gfx/shaders/FXAAMaterial.js index b9296edd..21d21ec4 100644 --- a/packages/lib/src/gfx/shaders/FXAAMaterial.js +++ b/packages/lib/src/gfx/shaders/FXAAMaterial.js @@ -1,10 +1,11 @@ /* eslint-disable no-magic-numbers */ /* eslint-disable guard-for-in */ -import * as THREE from 'three' + import vertexShader from './ScreenQuad.vert' import fragmentShader from './FXAA.frag' +import { RawShaderMaterial, Vector2, Color } from 'three' -class FXAAMaterial extends THREE.RawShaderMaterial { +class FXAAMaterial extends RawShaderMaterial { constructor(params) { super(params) @@ -14,9 +15,9 @@ class FXAAMaterial extends THREE.RawShaderMaterial { srcTex: { type: 't', value: null }, srcTexelSize: { type: 'v2', - value: new THREE.Vector2(1.0 / 512.0, 1.0 / 512.0) + value: new Vector2(1.0 / 512.0, 1.0 / 512.0) }, - bgColor: { type: 'c', value: new THREE.Color(0xffffff) } + bgColor: { type: 'c', value: new Color(0xffffff) } }, vertexShader, fragmentShader, diff --git a/packages/lib/src/gfx/shaders/OutlineMaterial.js b/packages/lib/src/gfx/shaders/OutlineMaterial.js index 42494c0b..2a35eb0b 100644 --- a/packages/lib/src/gfx/shaders/OutlineMaterial.js +++ b/packages/lib/src/gfx/shaders/OutlineMaterial.js @@ -1,10 +1,11 @@ /* eslint-disable no-magic-numbers */ /* eslint-disable guard-for-in */ -import * as THREE from 'three' + import vertexShader from './ScreenQuad.vert' import fragmentShader from './Outline.frag' +import { RawShaderMaterial, Vector2 } from 'three' -class OutlineMaterial extends THREE.RawShaderMaterial { +class OutlineMaterial extends RawShaderMaterial { constructor(params) { // add depth outline super(params) @@ -13,11 +14,11 @@ class OutlineMaterial extends THREE.RawShaderMaterial { uniforms: { srcTex: { type: 't', value: null }, srcDepthTex: { type: 't', value: null }, - srcTexSize: { type: 'v2', value: new THREE.Vector2(512, 512) }, + srcTexSize: { type: 'v2', value: new Vector2(512, 512) }, color: { type: 'v3', value: null }, threshold: { type: 'f', value: null }, opacity: { type: 'f', value: 1.0 }, - thickness: { type: 'v2', value: new THREE.Vector2(1, 1) } + thickness: { type: 'v2', value: new Vector2(1, 1) } }, vertexShader, fragmentShader, diff --git a/packages/lib/src/gfx/shaders/UberMaterial.js b/packages/lib/src/gfx/shaders/UberMaterial.js index 5e379f29..75b3e4b1 100644 --- a/packages/lib/src/gfx/shaders/UberMaterial.js +++ b/packages/lib/src/gfx/shaders/UberMaterial.js @@ -1,43 +1,53 @@ /* eslint-disable no-magic-numbers */ /* eslint-disable guard-for-in */ -import * as THREE from 'three' + import vertexShader from './Uber.vert' import fragmentShader from './Uber.frag' import capabilities from '../capabilities' import noise from '../noiseTexture' +import { + UniformsLib, + UniformsUtils, + Vector2, + Color, + Matrix4, + RawShaderMaterial, + DoubleSide, + Material +} from 'three' // Length of _samplesKernel is used in Uber.frag // If you want to change length of _samplesKernel, please, remember change it in Uber.frag too. // You can easy find places for replace using word:_samplesKernel const _samplesKernel = [ - new THREE.Vector2(-0.541978, 0.840393), - new THREE.Vector2(0.125533, -0.992089), - new THREE.Vector2(0.374329, 0.927296), - new THREE.Vector2(-0.105475, 0.994422) + new Vector2(-0.541978, 0.840393), + new Vector2(0.125533, -0.992089), + new Vector2(0.374329, 0.927296), + new Vector2(-0.105475, 0.994422) ] -const defaultUniforms = THREE.UniformsUtils.merge([ - THREE.UniformsLib.fog, - THREE.UniformsLib.lights, +const defaultUniforms = UniformsUtils.merge([ + UniformsLib.fog, + UniformsLib.lights, { - // are updated automatically by three.js (see THREE.ShaderLib.common) - diffuse: { value: new THREE.Color(0xeeeeee) }, + // are updated automatically by three.js (see ShaderLib.common) + diffuse: { value: new Color(0xeeeeee) }, opacity: { value: 1.0 }, - specular: { type: 'c', value: new THREE.Color(0x111111) }, + specular: { type: 'c', value: new Color(0x111111) }, shininess: { type: 'f', value: 30 }, - fixedColor: { type: 'c', value: new THREE.Color(0xffffff) }, + fixedColor: { type: 'c', value: new Color(0xffffff) }, zOffset: { type: 'f', value: 0.0 }, zClipValue: { type: 'f', value: 0.0 }, clipPlaneValue: { type: 'f', value: 0.0 }, nearPlaneValue: { type: 'f', value: -0.5 }, - invModelViewMatrix: { type: '4fv', value: new THREE.Matrix4() }, - world2colorMatrix: { type: '4fv', value: new THREE.Matrix4() }, + invModelViewMatrix: { type: '4fv', value: new Matrix4() }, + world2colorMatrix: { type: '4fv', value: new Matrix4() }, dashedLineSize: { type: 'f', value: 0.1 }, dashedLinePeriod: { type: 'f', value: 0.2 }, - projMatrixInv: { type: '4fv', value: new THREE.Matrix4() }, - viewport: { type: 'v2', value: new THREE.Vector2() }, + projMatrixInv: { type: '4fv', value: new Matrix4() }, + viewport: { type: 'v2', value: new Vector2() }, lineWidth: { type: 'f', value: 2.0 }, // default value must be the same as settings fogAlpha: { type: 'f', value: 1.0 }, @@ -73,29 +83,26 @@ const uberOptionNames = [ // properties that convert to uniforms const uberOptions = { - diffuse: new THREE.Color(0xffffff), // used in phong lighting - specular: new THREE.Color(0x111111), // used in phong lighting + diffuse: new Color(0xffffff), // used in phong lighting + specular: new Color(0x111111), // used in phong lighting shininess: 30, // used in phong lighting opacity: 1, // set mesh opacity - fixedColor: new THREE.Color(0xffffff), // color to override (see OVERRIDE_COLOR) + fixedColor: new Color(0xffffff), // color to override (see OVERRIDE_COLOR) zOffset: 0.0, // used fo zsprites (see SPHERE_SPRITE CYLINDER_SPRITE) zClipCoef: 2.0, // use for Surfs clipping (mesh param, isn't used in shader) FIXME move to representation param zClipValue: 0.0, // value to clip Surfs in shader (see ZCLIP) clipPlaneValue: 0.0, // value to clip scene globally (see CLIPPLANE) - world2colorMatrix: new THREE.Matrix4(), + world2colorMatrix: new Matrix4(), dashedLineSize: 0.1, dashedLinePeriod: 0.3, - projMatrixInv: new THREE.Matrix4(), - viewport: new THREE.Vector2(800, 600), + projMatrixInv: new Matrix4(), + viewport: new Vector2(800, 600), lineWidth: 2.0, fogAlpha: 1.0, samplesKernel: _samplesKernel, noiseTex: noise.noiseTexture, - noiseTexelSize: new THREE.Vector2( - 1.0 / noise.noiseWidth, - 1.0 / noise.noiseHeight - ), - srcTexelSize: new THREE.Vector2(1.0 / 800.0, 1.0 / 600.0), + noiseTexelSize: new Vector2(1.0 / noise.noiseWidth, 1.0 / noise.noiseHeight), + srcTexelSize: new Vector2(1.0 / 800.0, 1.0 / 600.0), copy(source) { this.diffuse.copy(source.diffuse) @@ -122,7 +129,7 @@ const uberOptions = { } } -class UberMaterial extends THREE.RawShaderMaterial { +class UberMaterial extends RawShaderMaterial { constructor(params) { super(params) // add fog @@ -174,12 +181,12 @@ class UberMaterial extends THREE.RawShaderMaterial { this.uberOptions = uberOptions // set default values this.setValues({ - uniforms: THREE.UniformsUtils.clone(defaultUniforms), + uniforms: UniformsUtils.clone(defaultUniforms), vertexShader: this.precisionString() + vertexShader, fragmentShader: this.precisionString() + fragmentShader, lights: true, fog: true, - side: THREE.DoubleSide, + side: DoubleSide, ...params }) } @@ -198,7 +205,7 @@ class UberMaterial extends THREE.RawShaderMaterial { this.fragmentShader = source.fragmentShader this.vertexShader = source.vertexShader - this.uniforms = THREE.UniformsUtils.clone(source.uniforms) + this.uniforms = UniformsUtils.clone(source.uniforms) this.defines = { ...source.defines } this.extensions = source.extensions @@ -344,7 +351,7 @@ class UberMaterial extends THREE.RawShaderMaterial { continue } - if (this.uberOptions[key] instanceof THREE.Color) { + if (this.uberOptions[key] instanceof Color) { this.uberOptions[key] = values[key].clone() } else { this.uberOptions[key] = values[key] @@ -354,7 +361,7 @@ class UberMaterial extends THREE.RawShaderMaterial { clone(shallow) { if (!shallow) { - return THREE.Material.prototype.clone.call(this) + return Material.prototype.clone.call(this) } return this.createInstance() } @@ -365,8 +372,8 @@ class UberMaterial extends THREE.RawShaderMaterial { uberOptionNames.forEach((p) => { if (self.uniforms.hasOwnProperty(p)) { if ( - self.uberOptions[p] instanceof THREE.Color || - self.uberOptions[p] instanceof THREE.Matrix4 + self.uberOptions[p] instanceof Color || + self.uberOptions[p] instanceof Matrix4 ) { self.uniforms[p].value = self.uberOptions[p].clone() } else { diff --git a/packages/lib/src/gfx/shaders/VolumeMaterial.js b/packages/lib/src/gfx/shaders/VolumeMaterial.js index b3e0380e..def85d3d 100644 --- a/packages/lib/src/gfx/shaders/VolumeMaterial.js +++ b/packages/lib/src/gfx/shaders/VolumeMaterial.js @@ -1,6 +1,5 @@ /* eslint-disable no-magic-numbers */ /* eslint-disable guard-for-in */ -import * as THREE from 'three' import vertexVolumeFaces from './VolumeFaces.vert' import fragmentVolumeFaces from './VolumeFaces.frag' import vertexVolume from './Volume.vert' @@ -8,18 +7,27 @@ import fragmentVolume from './Volume.frag' import vertexFarPlane from './VolumeFarPlane.vert' import fragmentFarPlane from './VolumeFarPlane.frag' import settings from '../../settings' +import { + BackSide, + FrontSide, + Matrix4, + ShaderMaterial, + UniformsUtils, + Vector2, + Vector3 +} from 'three' -const volumeUniforms = THREE.UniformsUtils.merge([ +const volumeUniforms = UniformsUtils.merge([ { - volumeDim: { type: 'v3', value: new THREE.Vector3(512, 512, 512) }, + volumeDim: { type: 'v3', value: new Vector3(512, 512, 512) }, tileTex: { type: 't', value: null }, - tileTexSize: { type: 'v2', value: new THREE.Vector2(512, 512) }, - tileStride: { type: 'v2', value: new THREE.Vector2(512, 512) }, + tileTexSize: { type: 'v2', value: new Vector2(512, 512) }, + tileStride: { type: 'v2', value: new Vector2(512, 512) }, - boxAngles: { type: 'v3', value: new THREE.Vector3(1, 1, 1) }, - delta: { type: 'v3', value: new THREE.Vector3(0, 0, 0) }, + boxAngles: { type: 'v3', value: new Vector3(1, 1, 1) }, + delta: { type: 'v3', value: new Vector3(0, 0, 0) }, - _isoLevel0: { type: 'v2', value: new THREE.Vector3(0.5, 0.75, 1.0) }, + _isoLevel0: { type: 'v2', value: new Vector3(0.5, 0.75, 1.0) }, _flipV: { type: 'f', value: 0.0 }, _BFLeft: { type: 't', value: null }, _BFRight: { type: 't', value: null }, @@ -31,7 +39,7 @@ const volumeUniforms = THREE.UniformsUtils.merge([ ]) function overrideUniforms(params, defUniforms) { - const uniforms = THREE.UniformsUtils.clone(defUniforms) + const uniforms = UniformsUtils.clone(defUniforms) for (const p in params) { if (uniforms.hasOwnProperty(p)) { uniforms[p].value = params[p] @@ -52,9 +60,9 @@ function facesPosMaterialParams(params, sideType) { } } -class BackFacePosMaterial extends THREE.ShaderMaterial { +class BackFacePosMaterial extends ShaderMaterial { constructor(params) { - const backFaceParams = facesPosMaterialParams(params, THREE.BackSide) + const backFaceParams = facesPosMaterialParams(params, BackSide) super(backFaceParams) } } @@ -67,18 +75,18 @@ class ShaderParams { this.transparent = false this.depthTest = false this.depthWrite = false - this.side = THREE.FrontSide + this.side = FrontSide } } -class BackFacePosMaterialFarPlane extends THREE.ShaderMaterial { +class BackFacePosMaterialFarPlane extends ShaderMaterial { constructor(params) { - const matUniforms = THREE.UniformsUtils.merge([ + const matUniforms = UniformsUtils.merge([ { aspectRatio: { type: 'f', value: 0.0 }, farZ: { type: 'f', value: 0.0 }, tanHalfFOV: { type: 'f', value: 0.0 }, - matWorld2Volume: { type: '4fv', value: new THREE.Matrix4() } + matWorld2Volume: { type: '4fv', value: new Matrix4() } } ]) @@ -92,14 +100,14 @@ class BackFacePosMaterialFarPlane extends THREE.ShaderMaterial { } } -class FrontFacePosMaterial extends THREE.ShaderMaterial { +class FrontFacePosMaterial extends ShaderMaterial { constructor(params) { - const frontFaceParams = facesPosMaterialParams(params, THREE.FrontSide) + const frontFaceParams = facesPosMaterialParams(params, FrontSide) super(frontFaceParams) } } -class VolumeMaterial extends THREE.ShaderMaterial { +class VolumeMaterial extends ShaderMaterial { constructor(params) { const shaderParams = new ShaderParams( params, diff --git a/packages/lib/src/gfx/vr/WebVRPoC.js b/packages/lib/src/gfx/vr/WebVRPoC.js index 2a9729ce..a57c0301 100644 --- a/packages/lib/src/gfx/vr/WebVRPoC.js +++ b/packages/lib/src/gfx/vr/WebVRPoC.js @@ -1,19 +1,25 @@ -import * as THREE from 'three' import createWebVRButton from './createWebVRButton' import gfxutils from '../gfxutils' import logger from '../../utils/logger' import settings from '../../settings' import UberMaterial from '../shaders/UberMaterial' +import { + CylinderGeometry, + Mesh, + Object3D, + PerspectiveCamera, + Color +} from 'three' export default class WebVRPoC { constructor(onToggle) { - this._mainCamera = new THREE.PerspectiveCamera() + this._mainCamera = new PerspectiveCamera() this._button = null this._onToggle = onToggle this._molContainer = new gfxutils.RCGroup() this._user = new gfxutils.RCGroup() - this._scalingPivot = new THREE.Object3D() + this._scalingPivot = new Object3D() this._user.add(this._scalingPivot) this._controller1 = null @@ -207,12 +213,12 @@ export default class WebVRPoC { _createControllerMesh() { // visualize controllers with cylinders - const geometry = new THREE.CylinderGeometry(0.04, 0.04, 0.3) + const geometry = new CylinderGeometry(0.04, 0.04, 0.3) const material = new UberMaterial() material.setValues({ lights: false, overrideColor: true }) - material.setUberOptions({ fixedColor: new THREE.Color(0x4444ff) }) + material.setUberOptions({ fixedColor: new Color(0x4444ff) }) material.updateUniforms() - const cylinder = new THREE.Mesh(geometry, material) + const cylinder = new Mesh(geometry, material) cylinder.rotateX(-Math.PI / 2) return cylinder } diff --git a/packages/lib/src/io/exporters/PDBExporter.js b/packages/lib/src/io/exporters/PDBExporter.js index 3094e2b3..2fc73157 100644 --- a/packages/lib/src/io/exporters/PDBExporter.js +++ b/packages/lib/src/io/exporters/PDBExporter.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { invert } from 'lodash' import Complex from '../../chem/Complex' import Exporter from './Exporter' import PDBResult from './PDBResult' @@ -150,7 +150,7 @@ export default class PDBExporter extends Exporter { const helices = this._source._helices for (let i = 0; i < helices.length; i++) { const helix = helices[i] - const helixClass = _.invert(typeByPDBHelixClass) + const helixClass = invert(typeByPDBHelixClass) result.newString() result.writeString(helix.serial, 10, 8) result.writeString(helix.name, 14, 12) diff --git a/packages/lib/src/io/exporters/PDBResult.js b/packages/lib/src/io/exporters/PDBResult.js index 22464b78..aba18e15 100644 --- a/packages/lib/src/io/exporters/PDBResult.js +++ b/packages/lib/src/io/exporters/PDBResult.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { isBoolean, isUndefined, isNumber, isString } from 'lodash' import { Matrix4 } from 'three' export default class PDBResult { @@ -30,12 +30,12 @@ export default class PDBResult { } else { this._tag = tag } - if (!_.isUndefined(numeration)) { - if (_.isNumber(numeration)) { + if (!isUndefined(numeration)) { + if (isNumber(numeration)) { this._tagStrNum = numeration this._numeration = true this._fixedNumeration = true - } else if (_.isBoolean(numeration)) { + } else if (isBoolean(numeration)) { this._tagStrNum = 0 this._numeration = numeration this._fixedNumeration = false @@ -94,19 +94,19 @@ export default class PDBResult { const curStrLength = curStr ? curStr.length : 0 - if (_.isUndefined(string)) { + if (isUndefined(string)) { return } - if (!_.isNumber(begin)) { + if (!isNumber(begin)) { begin = curStrLength + 1 } - if (!_.isNumber(end)) { + if (!isNumber(end)) { end = curStrLength + string.length } - if (!_.isString(string)) { + if (!isString(string)) { str = string.toString() } else { str = string diff --git a/packages/lib/src/io/exporters/fbx/FBXInfoExtractor.js b/packages/lib/src/io/exporters/fbx/FBXInfoExtractor.js index 0ea5713b..f7d9264d 100644 --- a/packages/lib/src/io/exporters/fbx/FBXInfoExtractor.js +++ b/packages/lib/src/io/exporters/fbx/FBXInfoExtractor.js @@ -1,6 +1,3 @@ -import _ from 'lodash' -import * as THREE from 'three' - import utils from '../../../utils' import gfxutils from '../../../gfx/gfxutils' import logger from '../../../utils/logger' @@ -12,6 +9,8 @@ import InstancedSpheresGeometry from '../../../gfx/geometries/InstancedSpheresGe import Instanced2CCylindersGeometry from '../../../gfx/geometries/Instanced2CCylindersGeometry' import FBX1CGeometry from './FBX1CGeometry' import FBX2CCylinder from './FBX2CCylinder' +import { Layers, Matrix4, Mesh, Color } from 'three' +import { findIndex, isEqual } from 'lodash' export default class FBXInfoExtractor { constructor() { @@ -35,12 +34,12 @@ export default class FBXInfoExtractor { * @param {object} data - complexVisual to get geometry info from */ _extractModelsAndMaterials(data) { - const layersOfInterest = new THREE.Layers() + const layersOfInterest = new Layers() layersOfInterest.set(gfxutils.LAYERS.DEFAULT) layersOfInterest.enable(gfxutils.LAYERS.TRANSPARENT) data.traverse((object) => { if ( - object instanceof THREE.Mesh && + object instanceof Mesh && object.layers.test(layersOfInterest) && this.checkExportAbility(object) ) { @@ -196,9 +195,9 @@ export default class FBXInfoExtractor { model.init(instCount * vertCount, instCount * indsCount) const geo = new FBX1CGeometry() geo.init(mesh.geometry) - const instMatrix = new THREE.Matrix4() - const objMatrix = new THREE.Matrix4() - const sphereColor = new THREE.Color() + const instMatrix = new Matrix4() + const objMatrix = new Matrix4() + const sphereColor = new Color() for (let instanceIndex = 0; instanceIndex < instCount; ++instanceIndex) { // update colors in geometry const colorIdx = instanceIndex * color.itemSize @@ -245,10 +244,10 @@ export default class FBXInfoExtractor { instCount * vertCount + additionalVertsCount, instCount * indsCount ) - const instMatrix = new THREE.Matrix4() - const objMatrix = new THREE.Matrix4() - const colorStart = new THREE.Color() - const colorEnd = new THREE.Color() + const instMatrix = new Matrix4() + const objMatrix = new Matrix4() + const colorStart = new Color() + const colorEnd = new Color() let geo = {} for (let instanceIndex = 0; instanceIndex < instCount; ++instanceIndex) { // update colors in geometry @@ -300,7 +299,7 @@ export default class FBXInfoExtractor { * @returns {number} number of model-material pair */ _checkExistingMaterial(material) { - return _.findIndex(this._materials, (m) => _.isEqual(m, material)) + return findIndex(this._materials, (m) => isEqual(m, material)) } _gatherCylindersColoringInfo(geo) { diff --git a/packages/lib/src/io/exporters/fbx/FBXModel.js b/packages/lib/src/io/exporters/fbx/FBXModel.js index 6adc6389..f7b0321c 100644 --- a/packages/lib/src/io/exporters/fbx/FBXModel.js +++ b/packages/lib/src/io/exporters/fbx/FBXModel.js @@ -1,4 +1,4 @@ -import * as THREE from 'three' +import { Vector4 } from 'three' const FBX_POS_SIZE = 3 const FBX_NORM_SIZE = 3 @@ -17,7 +17,7 @@ function copyFbxPoint4(src, srcIdx, dst, dstIdx, value) { dst[dstIdx + 3] = value } -const vector4 = new THREE.Vector4() +const vector4 = new Vector4() function copyTransformedPoint3(src, srcIdx, dst, dstIdx, opts) { vector4.set(src[srcIdx], src[srcIdx + 1], src[srcIdx + 2], opts.w) vector4.applyMatrix4(opts.matrix) diff --git a/packages/lib/src/io/loaders/XHRLoader.js b/packages/lib/src/io/loaders/XHRLoader.js index 54611f1d..b9e8c2c0 100644 --- a/packages/lib/src/io/loaders/XHRLoader.js +++ b/packages/lib/src/io/loaders/XHRLoader.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { isString } from 'lodash' import Loader from './Loader' // we don't need to detect all kinds of URLs, just the evident ones @@ -49,7 +49,7 @@ export default class XHRLoader extends Loader { } static canProbablyLoad(source) { - return _.isString(source) && urlStartRegexp.test(source) + return isString(source) && urlStartRegexp.test(source) } static extractName(source) { diff --git a/packages/lib/src/io/parsers/CIFParser.js b/packages/lib/src/io/parsers/CIFParser.js index d113829f..e7f4fedd 100644 --- a/packages/lib/src/io/parsers/CIFParser.js +++ b/packages/lib/src/io/parsers/CIFParser.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' -import _ from 'lodash' import Parser from './Parser' import chem from '../../chem' import StructuralElement from '../../chem/StructuralElement' import readCIF from './readCIF' +import { isArray, isString } from 'lodash' +import { Matrix4, Vector3 } from 'three' const { Complex, Element, Helix, Sheet, Strand, Assembly, Molecule } = chem @@ -39,7 +39,7 @@ function arrize(arrayLikeObject) { if ( arrayLikeObject === null || arrayLikeObject === undefined || - _.isArray(arrayLikeObject) + isArray(arrayLikeObject) ) { return arrayLikeObject } @@ -82,7 +82,7 @@ function _getOperations(operList) { const ops = [] for (let i = 0, n = idc.length; i < n; ++i) { - const mtx = new THREE.Matrix4() + const mtx = new Matrix4() const { elements } = mtx for (let row = 0; row < 3; ++row) { @@ -98,7 +98,7 @@ function _getOperations(operList) { } function _extractOperations(assemblyGen, opsDict) { - assemblyGen = _.isString(assemblyGen) ? assemblyGen : `${assemblyGen}` + assemblyGen = isString(assemblyGen) ? assemblyGen : `${assemblyGen}` const l = assemblyGen.replace(/\)\s*\(/g, '!').replace(/[()']/g, '') const groupStr = l.split('!') const gps = [] @@ -128,7 +128,7 @@ function _extractOperations(assemblyGen, opsDict) { let cnt = 0 function traverse(level, mtx) { for (let ii = 0, nn = gps[level].length; ii < nn; ++ii) { - const newMtx = mtx ? mtx.clone() : new THREE.Matrix4() + const newMtx = mtx ? mtx.clone() : new Matrix4() newMtx.multiplyMatrices(gps[level][ii], newMtx) if (level === 0) { matrices[cnt++] = newMtx @@ -150,7 +150,7 @@ class CIFParser extends Parser { } static canProbablyParse(data) { - return _.isString(data) && /^\s*data_/i.test(data) + return isString(data) && /^\s*data_/i.test(data) } parseSync() { @@ -313,7 +313,7 @@ class CIFParser extends Parser { const element = elements[i] || nameToElement(name) const type = Element.getByName(element) const role = Element.Role[name.trim()] - const xyz = new THREE.Vector3(x[i], y[i], z[i]) + const xyz = new Vector3(x[i], y[i], z[i]) const het = group[i] === 'HETATM' || false const serial = serials[i] || i const tempFactor = tempFactors[i] || 0.0 diff --git a/packages/lib/src/io/parsers/CMLParser.js b/packages/lib/src/io/parsers/CMLParser.js index 3f4b0e29..a5d0c429 100644 --- a/packages/lib/src/io/parsers/CMLParser.js +++ b/packages/lib/src/io/parsers/CMLParser.js @@ -1,7 +1,7 @@ -import _ from 'lodash' -import * as THREE from 'three' import Parser from './Parser' import chem from '../../chem' +import { isString } from 'lodash' +import { Vector3 } from 'three' const { Complex, Element, SGroup, Bond } = chem @@ -27,7 +27,7 @@ class CMLParser extends Parser { } static canProbablyParse(data) { - return _.isString(data) && cmlStartRegexp.test(data) + return isString(data) && cmlStartRegexp.test(data) } _rebuidBondIndexes(atoms, bonds) { @@ -53,12 +53,12 @@ class CMLParser extends Parser { const newGroup = new SGroup( molecule.id, molecule.fieldData, - new THREE.Vector3(parseFloat(molecule.x), parseFloat(molecule.y), 0), + new Vector3(parseFloat(molecule.x), parseFloat(molecule.y), 0), molecule.atomRefs, molecule ) if (molecule.placement === 'Relative') { - newGroup._center = new THREE.Vector3(0, 0, 0) + newGroup._center = new Vector3(0, 0, 0) } if (molecule.fieldName === 'MDLBG_FRAGMENT_CHARGE') { newGroup._charge = parseInt(molecule.fieldData, 10) || 0 @@ -123,8 +123,8 @@ class CMLParser extends Parser { let atomMap = {} // sgrpmap cache let mapEntry = null const nLimon = 100000000 - const bLow = new THREE.Vector3(nLimon, nLimon, nLimon) - const bHight = new THREE.Vector3(-nLimon, -nLimon, -nLimon) + const bLow = new Vector3(nLimon, nLimon, nLimon) + const bHight = new Vector3(-nLimon, -nLimon, -nLimon) function cycleFuncInner(e) { mapEntry = atomMap[e] @@ -567,13 +567,13 @@ class CMLParser extends Parser { // _x, _y, _z, mname, mindex, atomNameFull, atomName, chainID, serial, isHet, atlLocInd, atomNameToTypeF let xyz = null if (atom.x3) { - xyz = new THREE.Vector3( + xyz = new Vector3( parseFloat(atom.x3), parseFloat(atom.y3), parseFloat(atom.z3) ) } else if (atom.x2) { - xyz = new THREE.Vector3(parseFloat(atom.x2), parseFloat(atom.y2), 0) + xyz = new Vector3(parseFloat(atom.x2), parseFloat(atom.y2), 0) } let element = Element.ByName[atom.elementType.toUpperCase()] if (!element) { diff --git a/packages/lib/src/io/parsers/DSN6Parser.js b/packages/lib/src/io/parsers/DSN6Parser.js index 603cdd79..41ed4614 100644 --- a/packages/lib/src/io/parsers/DSN6Parser.js +++ b/packages/lib/src/io/parsers/DSN6Parser.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' import Parser from './Parser' import VolumeModel, { valueType } from './VolumeModel' +import { Vector3 } from 'three' // http://www.uoxray.uoregon.edu/tnt/manual/node104.html const DSN6Header = { @@ -102,7 +102,7 @@ class DSN6Model extends VolumeModel { header.extent[0] * header.extent[1] * header.extent[2] ) - const blocks = new THREE.Vector3( + const blocks = new Vector3( header.extent[0] / 8, header.extent[1] / 8, header.extent[2] / 8 diff --git a/packages/lib/src/io/parsers/GROParser.js b/packages/lib/src/io/parsers/GROParser.js index 1951e9d2..670f72ce 100644 --- a/packages/lib/src/io/parsers/GROParser.js +++ b/packages/lib/src/io/parsers/GROParser.js @@ -1,8 +1,8 @@ -import * as THREE from 'three' -import _ from 'lodash' import Parser from './Parser' import chem from '../../chem' import GROReader from './GROReader' +import { isString } from 'lodash' +import { Vector3 } from 'three' const { Complex, Element, Molecule } = chem @@ -52,7 +52,7 @@ class GROParser extends Parser { */ canProbablyParse(data) { return ( - _.isString(this._data) && + isString(this._data) && /^\s*[^\n]*\n\s*\d+ *\n\s*\d+[^\n\d]{3}\s*\w+\s*\d+\s*-?\d/.test(data) ) } @@ -139,7 +139,7 @@ class GROParser extends Parser { ) } /* Lastly, add atom to that residue */ - this._atomPosition = new THREE.Vector3(positionX, positionY, positionZ) + this._atomPosition = new Vector3(positionX, positionY, positionZ) /* Adding default constants to correct atom addition process */ const het = true const altLoc = ' ' diff --git a/packages/lib/src/io/parsers/MMTFParser.js b/packages/lib/src/io/parsers/MMTFParser.js index e7eee9e2..d7815ff2 100644 --- a/packages/lib/src/io/parsers/MMTFParser.js +++ b/packages/lib/src/io/parsers/MMTFParser.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' -import _ from 'lodash' import Parser from './Parser' import chem from '../../chem' import MMTF from '../../vendors/mmtf' import StructuralElement from '../../chem/StructuralElement' +import { isArrayBuffer, isUndefined } from 'lodash' +import { Matrix4, Vector3 } from 'three' const { Complex, @@ -88,7 +88,7 @@ class MMTFParser extends Parser { static canProbablyParse(data) { // check if it's binary MessagePack format containing a map (dictionary) // see https://github.com/msgpack/msgpack/blob/master/spec.md - return _.isArrayBuffer(data) && (getFirstByte(data) | 1) === 0xdf + return isArrayBuffer(data) && (getFirstByte(data) | 1) === 0xdf } _onModel(_modelData) {} @@ -137,7 +137,7 @@ class MMTFParser extends Parser { atomData.groupIndex, // we store residue index here to replace it later with actual reference atomData.atomName, Element.getByName(atomData.element.toUpperCase()), - new THREE.Vector3(atomData.xCoord, atomData.yCoord, atomData.zCoord), + new Vector3(atomData.xCoord, atomData.yCoord, atomData.zCoord), Element.Role[atomData.atomName], false, // hetero atoms will be marked later atomData.atomId, @@ -171,7 +171,7 @@ class MMTFParser extends Parser { _updateSecStructure(complex, residue, groupData) { const helixClasses = [3, -1, 1, -1, 5] - if (!_.isUndefined(groupData) && groupData.secStruct === this._ssType) { + if (!isUndefined(groupData) && groupData.secStruct === this._ssType) { residue._secondary = this._ssStruct if (this._ssStruct) { this._ssStruct.term = residue @@ -179,7 +179,7 @@ class MMTFParser extends Parser { return } - if (!_.isUndefined(groupData)) { + if (!isUndefined(groupData)) { // start new secondary structure const type = secStructToType[groupData.secStruct] this._ssType = groupData.secStruct @@ -374,9 +374,7 @@ class MMTFParser extends Parser { // add unique matrices to assembly a.addMatrix( - new THREE.Matrix4() - .fromArray(baInfo.transformList[0].matrix) - .transpose() + new Matrix4().fromArray(baInfo.transformList[0].matrix).transpose() ) for (j = 1; j < baInfo.transformList.length; ++j) { const transform = baInfo.transformList[j] @@ -390,7 +388,7 @@ class MMTFParser extends Parser { continue } - const m = new THREE.Matrix4().fromArray(transform.matrix).transpose() + const m = new Matrix4().fromArray(transform.matrix).transpose() // check if matrix is already in the list for (k = 0; k < a.matrices.length; ++k) { diff --git a/packages/lib/src/io/parsers/MOL2Parser.js b/packages/lib/src/io/parsers/MOL2Parser.js index 60241da7..e80d3683 100644 --- a/packages/lib/src/io/parsers/MOL2Parser.js +++ b/packages/lib/src/io/parsers/MOL2Parser.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' import Parser from './Parser' import chem from '../../chem' +import { Vector3 } from 'three' const { Complex, Element, Bond, Molecule } = chem @@ -176,7 +176,7 @@ class MOL2Parser extends Parser { const type = Element.getByName(element) const role = Element.Role[atomName] - const xyz = new THREE.Vector3(x, y, z) + const xyz = new Vector3(x, y, z) this._residue.addAtom( atomName, type, diff --git a/packages/lib/src/io/parsers/PDBParser.js b/packages/lib/src/io/parsers/PDBParser.js index 370d9955..7761ea75 100644 --- a/packages/lib/src/io/parsers/PDBParser.js +++ b/packages/lib/src/io/parsers/PDBParser.js @@ -1,10 +1,10 @@ -import * as THREE from 'three' -import _ from 'lodash' +import { isString, isUndefined } from 'lodash' import Parser from './Parser' import chem from '../../chem' import Remark290 from './pdb/Remark290' import Remark350 from './pdb/Remark350' import PDBStream from './PDBStream' +import { Vector3 } from 'three' const { Complex, Element, Helix, Sheet, Strand, Bond, Molecule } = chem @@ -61,7 +61,7 @@ class PDBParser extends Parser { } static canProbablyParse(data) { - return _.isString(data) && pdbStartRegexp.test(data) + return isString(data) && pdbStartRegexp.test(data) } _finalize() { @@ -70,12 +70,12 @@ class PDBParser extends Parser { // keep crystallographic symmetry transformations const remark290 = this._remarks[290] - this._complex.symmetry = _.isUndefined(remark290) ? [] : remark290.matrices + this._complex.symmetry = isUndefined(remark290) ? [] : remark290.matrices // add loaded biological assemblies const remark350 = this._remarks[350] this._complex.units = this._complex.units.concat( - _.isUndefined(remark350) ? [] : remark350.assemblies + isUndefined(remark350) ? [] : remark350.assemblies ) // add loaded macromolecules @@ -207,7 +207,7 @@ class PDBParser extends Parser { this._residue = residue = chain.addResidue(resName, resSeq, iCode) } - const xyz = new THREE.Vector3(x, y, z) + const xyz = new Vector3(x, y, z) residue.addAtom( name, type, @@ -293,7 +293,7 @@ class PDBParser extends Parser { // create remark parser if needed let remark = this._remarks[remarkNum] - if (_.isUndefined(remark)) { + if (isUndefined(remark)) { const RemarkParser = remarkParsers[remarkNum] if (typeof RemarkParser === 'function') { this._remarks[remarkNum] = remark = new RemarkParser(this._complex) @@ -301,7 +301,7 @@ class PDBParser extends Parser { } // delegate parsing - if (!_.isUndefined(remark)) { + if (!isUndefined(remark)) { remark.parse(stream) } } diff --git a/packages/lib/src/io/parsers/ParserList.js b/packages/lib/src/io/parsers/ParserList.js index ebc9eec2..66079d68 100644 --- a/packages/lib/src/io/parsers/ParserList.js +++ b/packages/lib/src/io/parsers/ParserList.js @@ -9,7 +9,7 @@ class ParserList extends EntityList { * Create a list of parsers. * The parsers are indexed by supported data formats and file extensions (`.formats` and * `.extensions` properties of a Parser subclass). - * The parsers can be retrieved later by matching against specs (see {@link ParsrerList#find}). + * The parsers can be retrieved later by matching against specs (see {@link ParserList#find}). * * @param {!Array=} someParsers A list of {@link Parser} subclasses to * automatically register at creation time. diff --git a/packages/lib/src/io/parsers/PubChemParser.js b/packages/lib/src/io/parsers/PubChemParser.js index d21086ff..b35d2240 100644 --- a/packages/lib/src/io/parsers/PubChemParser.js +++ b/packages/lib/src/io/parsers/PubChemParser.js @@ -1,7 +1,7 @@ -import * as THREE from 'three' -import _ from 'lodash' +import { fromPairs, isString, zip } from 'lodash' import Parser from './Parser' import chem from '../../chem' +import { Vector3 } from 'three' const { Complex, Element } = chem @@ -12,7 +12,7 @@ class PubChemParser extends Parser { } static canProbablyParse(data) { - return _.isString(data) && data[0] === '{' + return isString(data) && data[0] === '{' } parseSync() { @@ -40,7 +40,7 @@ class PubChemParser extends Parser { if (!elements || aids.length !== elements.length) { throw new Error('Unable to parse atom elements') } - elements = _.fromPairs(_.zip(aids, elements)) + elements = fromPairs(zip(aids, elements)) const atoms = {} const coords = complexData.coords && complexData.coords[0] @@ -59,7 +59,7 @@ class PubChemParser extends Parser { for (let i = 0, n = aids.length; i < n; ++i) { const aid = aids[i] const element = Element.ByAtomicNumber[elements[aid]] - const xyz = new THREE.Vector3(xs[i], ys[i], zs[i] || 0.0) + const xyz = new Vector3(xs[i], ys[i], zs[i] || 0.0) atoms[aid] = residue.addAtom( element.name, element, diff --git a/packages/lib/src/io/parsers/SDFParser.js b/packages/lib/src/io/parsers/SDFParser.js index 209317ab..8ed41ef3 100644 --- a/packages/lib/src/io/parsers/SDFParser.js +++ b/packages/lib/src/io/parsers/SDFParser.js @@ -1,9 +1,9 @@ -import * as THREE from 'three' -import _ from 'lodash' import Parser from './Parser' import chem from '../../chem' import SDFStream from './SDFStream' import Assembly from '../../chem/Assembly' +import { Matrix4, Vector3 } from 'three' +import { isString } from 'lodash' const { Complex, Element, Bond, Molecule } = chem @@ -93,7 +93,7 @@ export default class SDFParser extends Parser { } canProbablyParse(data) { - return _.isString(data) && sdfAndMolRegexp.test(data) + return isString(data) && sdfAndMolRegexp.test(data) } _parseHeader(stream) { @@ -125,7 +125,7 @@ export default class SDFParser extends Parser { const y = parseFloat(curStr.substr(10, 10)) const z = parseFloat(curStr.substr(20, 10)) const charge = chargeMap[parseInt(curStr.substr(36, 3), 10)] - const xyz = new THREE.Vector3(x, y, z) + const xyz = new Vector3(x, y, z) let name = curStr.substr(31, 3).trim().toUpperCase() const type = Element.getByName(name) if (!this._atomsIndexes[name]) { @@ -245,7 +245,7 @@ export default class SDFParser extends Parser { for (let i = 0; i < chains.length; i++) { const assembly = new Assembly(this._complex) - const matrix = new THREE.Matrix4() + const matrix = new Matrix4() assembly.addMatrix(matrix) assembly.addChain(chains[i]._name) this._assemblies.push(assembly) diff --git a/packages/lib/src/io/parsers/SDFStream.js b/packages/lib/src/io/parsers/SDFStream.js index 52d15659..f9215e1a 100644 --- a/packages/lib/src/io/parsers/SDFStream.js +++ b/packages/lib/src/io/parsers/SDFStream.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { isUndefined } from 'lodash' export default class SDFStream { constructor(data) { @@ -33,7 +33,7 @@ export default class SDFStream { findNextDataItem() { let curStr = this.getNextString() let res = false - while (!_.isUndefined(curStr) && curStr.trim() !== '$$$$') { + while (!isUndefined(curStr) && curStr.trim() !== '$$$$') { if (curStr.match(/>\s+<(.*)>/)) { res = true break @@ -46,7 +46,7 @@ export default class SDFStream { findNextCompoundStart() { let curStr = this.getCurrentString() - while (!_.isUndefined(curStr) && curStr.trim() !== '$$$$') { + while (!isUndefined(curStr) && curStr.trim() !== '$$$$') { curStr = this.getNextString() } this.setStart(++this._currentStringIndx) diff --git a/packages/lib/src/io/parsers/VolumeModel.js b/packages/lib/src/io/parsers/VolumeModel.js index 9189a6a5..3ce7a332 100644 --- a/packages/lib/src/io/parsers/VolumeModel.js +++ b/packages/lib/src/io/parsers/VolumeModel.js @@ -1,6 +1,6 @@ -import * as THREE from 'three' -import _ from 'lodash' import Volume from '../../chem/Volume' +import { Box3, Vector3 } from 'three' +import { isArrayBuffer, isTypedArray, pick } from 'lodash' export const valueType = { singular: 0, @@ -12,29 +12,29 @@ export const valueType = { class VolumeModel { _xyz2crs = [] - _origin = new THREE.Vector3(0, 0, 0) + _origin = new Vector3(0, 0, 0) constructor() { this._header = {} - this._boxSize = new THREE.Vector3() - this._boxStart = new THREE.Vector3() + this._boxSize = new Vector3() + this._boxStart = new Vector3() this._header.delta = {} this._header.extent = [] this._header.nstart = [] this._header.grid = [] this._header.crs2xyz = [] - this._header.cellDims = new THREE.Vector3() + this._header.cellDims = new Vector3() this._header.angles = [] - this._header.origin = new THREE.Vector3(0, 0, 0) + this._header.origin = new Vector3(0, 0, 0) this._header.dmin = 0 this._header.dmean = 0 this._header.dmax = 0 } _typedCheck() { - if (_.isTypedArray(this._buff)) { + if (isTypedArray(this._buff)) { this._buff = this._buff.buffer - } else if (!_.isArrayBuffer(this._buff)) { + } else if (!isArrayBuffer(this._buff)) { throw new TypeError('Expected ArrayBuffer or TypedArray') } } @@ -109,13 +109,13 @@ class VolumeModel { (Math.cos(alpha) - Math.cos(beta) * Math.cos(gamma)) / Math.sin(gamma) const z3 = Math.sqrt(1.0 - z1 * z1 - z2 * z2) - const xaxis = new THREE.Vector3(xScale, 0, 0) - const yaxis = new THREE.Vector3( + const xaxis = new Vector3(xScale, 0, 0) + const yaxis = new Vector3( Math.cos(gamma) * yScale, Math.sin(gamma) * yScale, 0 ) - const zaxis = new THREE.Vector3(z1 * zScale, z2 * zScale, z3 * zScale) + const zaxis = new Vector3(z1 * zScale, z2 * zScale, z3 * zScale) return [xaxis, yaxis, zaxis] } @@ -129,13 +129,7 @@ class VolumeModel { } _getVolumeInfo() { - const volInfo = _.pick(this._header, [ - 'dmean', - 'dmin', - 'dmax', - 'sd', - 'delta' - ]) + const volInfo = pick(this._header, ['dmean', 'dmin', 'dmax', 'sd', 'delta']) volInfo.obtuseAngle = this._header.angles.map((angle) => Number(angle >= Math.PI / 2) ) @@ -158,12 +152,12 @@ class VolumeModel { shiftY += Math.abs(zaxis.y) } - this._boxStart = new THREE.Vector3( + this._boxStart = new Vector3( this._origin.x - shiftX, this._origin.y - shiftY, this._origin.z ) - this._boxSize = new THREE.Vector3( + this._boxSize = new Vector3( Math.abs(xaxis.x) + Math.abs(yaxis.x) + Math.abs(zaxis.x), Math.abs(yaxis.y) + Math.abs(zaxis.y), Math.abs(zaxis.z) @@ -176,7 +170,7 @@ class VolumeModel { } _getXYZbox() { - return new THREE.Box3( + return new Box3( this._boxStart.clone(), this._boxStart.clone().add(this._boxSize) ) diff --git a/packages/lib/src/io/parsers/XYZParser.js b/packages/lib/src/io/parsers/XYZParser.js index b985a0b0..ee619909 100644 --- a/packages/lib/src/io/parsers/XYZParser.js +++ b/packages/lib/src/io/parsers/XYZParser.js @@ -1,7 +1,7 @@ -import * as THREE from 'three' -import _ from 'lodash' +import { isString } from 'lodash' import Parser from './Parser' import chem from '../../chem' +import { Vector3 } from 'three' const { Complex, Element, Molecule } = chem @@ -17,7 +17,7 @@ class XYZParser extends Parser { } static canProbablyParse(data) { - return _.isString(data) && /^\s*\d+ *\n[^\n]*\n\s*\w{1,3}\s+-?\d/.test(data) + return isString(data) && /^\s*\d+ *\n[^\n]*\n\s*\w{1,3}\s+-?\d/.test(data) } _parseToAtomsInf(source) { @@ -64,7 +64,7 @@ class XYZParser extends Parser { const serial = i + 1 const name = words[0] - const xyz = new THREE.Vector3( + const xyz = new Vector3( parseFloat(words[1]), parseFloat(words[2]), parseFloat(words[3]) diff --git a/packages/lib/src/io/parsers/pdb/Remark290.js b/packages/lib/src/io/parsers/pdb/Remark290.js index 57bd5faa..4d9c4201 100644 --- a/packages/lib/src/io/parsers/pdb/Remark290.js +++ b/packages/lib/src/io/parsers/pdb/Remark290.js @@ -1,17 +1,17 @@ -import * as THREE from 'three' - /** * Parser helper for PDB tag "REMARK 290". * * @exports Remark290 * @constructor */ +import { Matrix4 } from 'three' + class Remark290 { constructor() { - /** @type {THREE.Matrix4[]} */ + /** @type {Matrix4[]} */ this.matrices = [] - /** @type {?THREE.Matrix4} */ + /** @type {?Matrix4} */ this._matrix = null /** @type {number} */ this._matrixIndex = -1 @@ -23,7 +23,7 @@ class Remark290 { */ parse(stream) { - /** @type {?THREE.Matrix4} */ + /** @type {?Matrix4} */ let matrix = this._matrix if (stream.readString(12, 18) === ' SMTRY') { @@ -33,7 +33,7 @@ class Remark290 { if (this._matrix === null || matrixIndex !== this._matrixIndex) { // TODO: assert(matrixIndex === this.matrices.length + 1); this._matrixIndex = matrixIndex - this._matrix = matrix = new THREE.Matrix4() + this._matrix = matrix = new Matrix4() this.matrices[this.matrices.length] = matrix } diff --git a/packages/lib/src/io/parsers/pdb/Remark350.js b/packages/lib/src/io/parsers/pdb/Remark350.js index 9c514785..27b0dff1 100644 --- a/packages/lib/src/io/parsers/pdb/Remark350.js +++ b/packages/lib/src/io/parsers/pdb/Remark350.js @@ -1,5 +1,5 @@ -import * as THREE from 'three' import chem from '../../../chem' +import { Matrix4 } from 'three' const { Assembly } = chem @@ -18,7 +18,7 @@ class Remark350 { /** @type {?Assembly} */ this._assembly = null - /** @type {?THREE.Matrix4} */ + /** @type {?Matrix4} */ this._matrix = null /** @type {number} */ this._matrixIndex = -1 @@ -32,7 +32,7 @@ class Remark350 { parse(stream) { /** @type {?Assembly} */ let assembly = this._assembly - /** @type {?THREE.Matrix4} */ + /** @type {?Matrix4} */ let matrix = this._matrix if (assembly && stream.readString(12, 18) === ' BIOMT') { @@ -42,7 +42,7 @@ class Remark350 { if (this._matrix === null || matrixIndex !== this._matrixIndex) { // TODO: assert(matrixIndex === assembly.matrices.length + 1); this._matrixIndex = matrixIndex - this._matrix = matrix = new THREE.Matrix4() + this._matrix = matrix = new Matrix4() assembly.addMatrix(matrix) } diff --git a/packages/lib/src/io/parsers/readCIF.js b/packages/lib/src/io/parsers/readCIF.js index 1670cde3..546749dd 100644 --- a/packages/lib/src/io/parsers/readCIF.js +++ b/packages/lib/src/io/parsers/readCIF.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { set } from 'lodash' import ParsingError from './ParsingError' // Implemented and being tested against: https://www.iucr.org/resources/cif/spec/version1.1/cifsyntax @@ -240,7 +240,7 @@ export default function readCIF(source) { break } value = _parseValue() - _.set(block, key, value) + set(block, key, value) state = 1 // block continue } else if (state === 3) { @@ -267,7 +267,7 @@ export default function readCIF(source) { for (let keyIndex = 0; keyIndex < keysCount; ++keyIndex) { value = [] values[keyIndex] = value - _.set(block, keys[keyIndex], value) + set(block, keys[keyIndex], value) } state = 4 continue // parse again in a different state diff --git a/packages/lib/src/options.js b/packages/lib/src/options.js index c8f31b21..f0dafab1 100644 --- a/packages/lib/src/options.js +++ b/packages/lib/src/options.js @@ -1,7 +1,7 @@ -import _ from 'lodash' import settings from './settings' import utils from './utils' import logger from './utils/logger' +import { isString, set, get, isArray, isEmpty } from 'lodash' let repIndex = 0 @@ -9,7 +9,7 @@ function asBoolean(value) { return !( !value || value === '0' || - (_.isString(value) && value.toLowerCase() === 'false') + (isString(value) && value.toLowerCase() === 'false') ) } @@ -135,9 +135,9 @@ function extractArgs(input, defaultsDict, params) { const pair = arg.split(cL2Ass, 2) const key = decodeURIComponent(pair[0]) const value = decodeURIComponent(pair[1]) - const adapter = adapters[typeof _.get(defaults, key)] + const adapter = adapters[typeof get(defaults, key)] if (adapter) { - _.set(opts, key, adapter(value)) + set(opts, key, adapter(value)) } else { logger.warn(`Unknown argument "${key}" for option "${input}"`) } @@ -254,7 +254,7 @@ function _fromArray(entries) { const /** string? */ value = entry[1] if (actions.hasOwnProperty(key)) { let /** function|string? */ action = actions[key] - while (_.isString(action)) { + while (isString(action)) { key = action action = actions[key] } @@ -263,9 +263,9 @@ function _fromArray(entries) { if (result !== undefined) opts[key] = result } } else { - const adapter = adapters[typeof _.get(settings.defaults, key)] + const adapter = adapters[typeof get(settings.defaults, key)] if (adapter) { - _.set(opts, `settings.${key}`, adapter(value)) + set(opts, `settings.${key}`, adapter(value)) } else { logger.warn(`Unknown option "${key}"`) } @@ -293,7 +293,7 @@ function _processOptsForURL(opts) { } function _processArgsForURL(args) { - if (!_.isArray(args)) { + if (!isArray(args)) { return args } if (args.length < 2) { @@ -307,7 +307,7 @@ function _processObjForURL(objOpts) { return undefined } let res = objOpts.type - if (_.isArray(objOpts.params) && objOpts.params.length > 0) { + if (isArray(objOpts.params) && objOpts.params.length > 0) { res += `,${objOpts.params.join(',')}` } if (objOpts.opts) { @@ -332,7 +332,7 @@ function toURL(opts) { return } for (let i = 0, n = repList.length; i < n; ++i) { - if (_.isEmpty(repList[i])) { + if (isEmpty(repList[i])) { continue } checkAndAdd('r', i) @@ -391,7 +391,7 @@ function _processOptsForScript(opts) { } function _processArgsForScript(args) { - if (!_.isArray(args)) { + if (!isArray(args)) { return args } if (args.length < 2) { @@ -405,7 +405,7 @@ function _processObjForScript(objOpts) { return undefined } let res = objOpts.type - if (_.isArray(objOpts.params) && objOpts.params.length > 0) { + if (isArray(objOpts.params) && objOpts.params.length > 0) { res += ` ${objOpts.params.map(utils.enquoteString).join(' ')}` } if (objOpts.opts) { @@ -422,7 +422,7 @@ function _processRepsForScript(rep, index) { repString[strIdx++] = prefix + value } } - if (_.isEmpty(rep)) { + if (isEmpty(rep)) { return null } localAdd('', index) diff --git a/packages/lib/src/options.test.js b/packages/lib/src/options.test.js index c03158cc..c4e01f6e 100644 --- a/packages/lib/src/options.test.js +++ b/packages/lib/src/options.test.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { isArray, isEqual } from 'lodash' import chai, { expect } from 'chai' import dirtyChai from 'dirty-chai' import options from './options' @@ -292,7 +292,7 @@ describe('options', () => { describe('.toScript()', () => { function equalCommands(original, generated) { - if (!_.isArray(original) || original.length !== generated.length + 2) { + if (!isArray(original) || original.length !== generated.length + 2) { return false } if ( @@ -386,7 +386,7 @@ describe('options', () => { if ( key !== 'preset' && key !== 'reps' && - (!another.hasOwnProperty(key) || !_.isEqual(one[key], another[key])) + (!another.hasOwnProperty(key) || !isEqual(one[key], another[key])) ) { return false } @@ -424,7 +424,7 @@ describe('options', () => { if ( ((origReps === undefined || origReps[i] === undefined) && Object.keys(genReps[i]).length > 0) || - !_.isEqual(origReps[i], genReps[i]) + !isEqual(origReps[i], genReps[i]) ) { return false } diff --git a/packages/lib/src/settings.js b/packages/lib/src/settings.js index bd975027..a4ecde54 100644 --- a/packages/lib/src/settings.js +++ b/packages/lib/src/settings.js @@ -1,6 +1,6 @@ -import _ from 'lodash' import utils from './utils' import EventDispatcher from './utils/EventDispatcher' +import { isEmpty, isString, get, set, merge, cloneDeep, filter } from 'lodash' const VERSION = 0 @@ -936,35 +936,35 @@ utils.deriveClass(Settings, EventDispatcher, { defaults, set(path, value) { - if (_.isString(path)) { - const oldValue = _.get(this.now, path) + if (isString(path)) { + const oldValue = get(this.now, path) if (oldValue !== value) { - _.set(this.now, path, value) + set(this.now, path, value) this._notifyChange(path, value) } } else { const diff = utils.objectsDiff(path, this.now) - if (!_.isEmpty(diff)) { - _.merge(this.now, diff) + if (!isEmpty(diff)) { + merge(this.now, diff) this._notifyChanges(diff) } } }, get(path, defaultValue) { - return _.get(this.now, path, defaultValue) + return get(this.now, path, defaultValue) }, reset() { const diff = utils.objectsDiff(defaults, this.now) - this.now = _.cloneDeep(defaults) + this.now = cloneDeep(defaults) this.old = null this._notifyChanges(diff) this._changed = {} }, checkpoint() { - this.old = _.cloneDeep(this.now) + this.old = cloneDeep(this.now) this._changed = {} }, @@ -984,9 +984,9 @@ utils.deriveClass(Settings, EventDispatcher, { return [] } const { old, now } = this - const keys = _.filter( + const keys = filter( Object.keys(this._changed), - (key) => _.get(old, key) !== _.get(now, key) + (key) => get(old, key) !== get(now, key) ) return keys }, @@ -1010,8 +1010,8 @@ utils.deriveClass(Settings, EventDispatcher, { }, setPluginOpts(plugin, opts) { - defaults.plugins[plugin] = _.cloneDeep(opts) - this.now.plugins[plugin] = _.cloneDeep(opts) + defaults.plugins[plugin] = cloneDeep(opts) + this.now.plugins[plugin] = cloneDeep(opts) } }) diff --git a/packages/lib/src/ui/ObjectControls.js b/packages/lib/src/ui/ObjectControls.js index d2a19ef0..633c2f86 100644 --- a/packages/lib/src/ui/ObjectControls.js +++ b/packages/lib/src/ui/ObjectControls.js @@ -1,7 +1,7 @@ -import * as THREE from 'three' import Timer from '../Timer' import settings from '../settings' import EventDispatcher from '../utils/EventDispatcher' +import { Matrix4, Quaternion, Vector2, Vector3 } from 'three' const VK_LEFT = 37 const VK_UP = 38 @@ -19,8 +19,8 @@ const STATE = { // pausing for this amount of time before releasing mouse button prevents inertial rotation (seconds) const FULL_STOP_THRESHOLD = 0.1 -const quaternion = new THREE.Quaternion() -const matrix4 = new THREE.Matrix4() +const quaternion = new Quaternion() +const matrix4 = new Matrix4() // pivot -- local offset of the rotation pivot point function ObjectHandler(objects, camera, pivot, options) { @@ -28,21 +28,21 @@ function ObjectHandler(objects, camera, pivot, options) { ;[this.object] = objects this.camera = camera this.pivot = pivot - this.axis = new THREE.Vector3(0, 0, 1) + this.axis = new Vector3(0, 0, 1) this.options = options this.lastRotation = { - axis: new THREE.Vector3(), + axis: new Vector3(), angle: 0.0 } } ObjectHandler.prototype._rotate = (function () { - const p = new THREE.Vector3() - const q = new THREE.Quaternion() - const s = new THREE.Vector3() + const p = new Vector3() + const q = new Quaternion() + const s = new Vector3() - const m = new THREE.Matrix4() + const m = new Matrix4() return function (quat) { const zeroPivot = @@ -85,7 +85,7 @@ ObjectHandler.prototype.setObjects = function (objects) { ObjectHandler.prototype.rotate = (function () { const rot = { - axis: new THREE.Vector3(), + axis: new Vector3(), angle: 0.0 } @@ -102,8 +102,8 @@ ObjectHandler.prototype.rotate = (function () { })() ObjectHandler.prototype.translate = (function () { - const dir = new THREE.Vector3() - const pivot = new THREE.Vector3() + const dir = new Vector3() + const pivot = new Vector3() return function (delta) { // reverse-project viewport movement to view coords (compensate for screen aspect ratio) @@ -135,7 +135,7 @@ ObjectHandler.prototype.translate = (function () { })() ObjectHandler.prototype.update = (function () { - const axis = new THREE.Vector3() + const axis = new Vector3() return function (timeSinceLastUpdate, timeSinceMove) { if (settings.now.autoRotation !== 0.0) { @@ -188,17 +188,17 @@ ObjectHandler.prototype.stop = function () { // calculate (axis, angle) pair from mouse/touch movement ObjectHandler.prototype.mouse2rotation = (function () { - const center = new THREE.Vector3() + const center = new Vector3() - const eye = new THREE.Vector3() - const eyeDirection = new THREE.Vector3() + const eye = new Vector3() + const eyeDirection = new Vector3() - const cameraUpDirection = new THREE.Vector3() - const cameraSidewaysDirection = new THREE.Vector3() + const cameraUpDirection = new Vector3() + const cameraSidewaysDirection = new Vector3() - const moveDirection = new THREE.Vector3() + const moveDirection = new Vector3() - const mouseDelta = new THREE.Vector2() + const mouseDelta = new Vector2() return function (rot, mousePrev, mouseCur, aboutAxis) { if (aboutAxis) { @@ -213,9 +213,9 @@ ObjectHandler.prototype.mouse2rotation = (function () { this.object.localToWorld(pivot); pivot.project(this.camera); - var v1 = new THREE.Vector3(mousePrev.x, mousePrev.y, this.camera.position.z); + var v1 = new Vector3(mousePrev.x, mousePrev.y, this.camera.position.z); v1.sub(pivot); - var v2 = new THREE.Vector3(mouseCur.x, mouseCur.y, this.camera.position.z); + var v2 = new Vector3(mouseCur.x, mouseCur.y, this.camera.position.z); v2.sub(pivot); v1.sub(res.axis.clone().multiplyScalar(v1.dot(res.axis))); @@ -297,19 +297,19 @@ function ObjectControls(object, objectPivot, camera, domElement, getAltObj) { this._state = STATE.NONE - this._mousePrevPos = new THREE.Vector2() - this._mouseCurPos = new THREE.Vector2() + this._mousePrevPos = new Vector2() + this._mouseCurPos = new Vector2() this._mainObj = new ObjectHandler( [this.object], this.camera, - new THREE.Vector3(0, 0, 0), + new Vector3(0, 0, 0), this.options ) this._altObj = new ObjectHandler( [this.object], this.camera, - new THREE.Vector3(0, 0, 0), + new Vector3(0, 0, 0), this.options ) this._affectedObj = this._mainObj @@ -546,7 +546,7 @@ ObjectControls.prototype.stop = function () { // rotate object based on latest mouse/touch movement ObjectControls.prototype.rotateByMouse = (function () { - const quat = new THREE.Quaternion() + const quat = new Quaternion() return function (aboutZAxis) { this._affectedObj.rotate( @@ -577,7 +577,7 @@ ObjectControls.prototype.setOrientation = function (quat) { // translate object based on latest mouse/touch movement ObjectControls.prototype.translate = (function () { - const delta = new THREE.Vector2() + const delta = new Vector2() return function () { delta.subVectors(this._mouseCurPos, this._mousePrevPos) this._affectedObj.translate(delta) @@ -605,7 +605,7 @@ ObjectControls.prototype.scale = function (factor) { } ObjectControls.prototype.update = (function () { - const shift = new THREE.Vector2() + const shift = new Vector2() return function () { const curTime = this._clock.getElapsedTime() @@ -903,7 +903,7 @@ ObjectControls.prototype.dispose = function () { } ObjectControls.prototype.translatePivotByMouse = (function () { - const delta = new THREE.Vector2() + const delta = new Vector2() return function () { delta.subVectors(this._mouseCurPos, this._mousePrevPos) this.translatePivotInWorld( diff --git a/packages/lib/src/ui/Picker.js b/packages/lib/src/ui/Picker.js index bf1837e9..9a6b7c05 100644 --- a/packages/lib/src/ui/Picker.js +++ b/packages/lib/src/ui/Picker.js @@ -1,7 +1,7 @@ -import * as THREE from 'three' import settings from '../settings' import Timer from '../Timer' import EventDispatcher from '../utils/EventDispatcher' +import { Raycaster, Vector2 } from 'three' function Picker(gfxObj, camera, domElement) { EventDispatcher.call(this) @@ -16,10 +16,10 @@ function Picker(gfxObj, camera, domElement) { width: 0, height: 0 } - this._lastMousePos = new THREE.Vector2(0, 0) + this._lastMousePos = new Vector2(0, 0) this._mouseTotalDist = 0.0 this._lastClickBeginTime = -1000.0 - this._lastClickPos = new THREE.Vector2(0, 0) + this._lastClickPos = new Vector2(0, 0) this._clickBeginTime = 0.0 this._clock = new Timer() @@ -111,7 +111,7 @@ Picker.prototype.pickObject = function (screenPos) { } const { gfxObj } = this - const rayCaster = new THREE.Raycaster() + const rayCaster = new Raycaster() rayCaster.ray.origin.setFromMatrixPosition(this.camera.matrixWorld) rayCaster.ray.direction .set(screenPos.x, screenPos.y, 0.5) @@ -155,7 +155,7 @@ Picker.prototype.pickObject = function (screenPos) { } Picker.prototype.getMouseInViewport = function (pageX, pageY) { - return new THREE.Vector2( + return new Vector2( ((pageX - this.screen.left) / this.screen.width) * 2 - 1, (-(pageY - this.screen.top) / this.screen.height) * 2 + 1 ) @@ -193,10 +193,7 @@ Picker.prototype.mouseup = function (event) { const timeSinceLastClickBegin = curTime - this._lastClickBeginTime if (timeSinceLastClickBegin < 0.7) { - const clickDist = new THREE.Vector2().subVectors( - curPos, - this._lastClickPos - ) + const clickDist = new Vector2().subVectors(curPos, this._lastClickPos) if (clickDist.length() < 0.01) { // it's a double click this.dispatchEvent({ type: 'dblclick', obj: this.picked }) diff --git a/packages/lib/src/utils.js b/packages/lib/src/utils.js index a077987c..f2d06f80 100644 --- a/packages/lib/src/utils.js +++ b/packages/lib/src/utils.js @@ -1,5 +1,12 @@ -import _ from 'lodash' import logger from './utils/logger' +import { + assign, + isPlainObject, + forIn, + isEqual, + isEmpty, + isString +} from 'lodash' const browserType = { DEFAULT: 0, @@ -160,13 +167,13 @@ function createElement(tag, attrs, content) { * @returns {function} Original class. */ function deriveClass(cls, base, members, statics) { - cls.prototype = _.assign( + cls.prototype = assign( Object.create(base.prototype), { constructor: cls }, members ) if (statics) { - _.assign(cls, statics) + assign(cls, statics) } return cls } @@ -326,7 +333,7 @@ function compareOptionsWithDefaults(opts, defOpts) { } function isAlmostPlainObject(o) { - if (_.isPlainObject(o)) { + if (isPlainObject(o)) { return true } const proto = o && Object.getPrototypeOf(o) @@ -340,20 +347,20 @@ function isAlmostPlainObject(o) { /** * Build an object that contains properties (and subproperties) of `src` different from those * in `dst`. Objects are parsed recursively, other values (including arrays) are compared for - * equality using `_.isEqual()`. + * equality using `isEqual()`. * @param {!object} src - a new object to compare, may contain changed or new properties * @param {!object} dst - an old reference object */ function objectsDiff(src, dst) { const diff = {} - _.forIn(src, (srcValue, key) => { + forIn(src, (srcValue, key) => { const dstValue = dst[key] if (isAlmostPlainObject(srcValue) && isAlmostPlainObject(dstValue)) { const deepDiff = objectsDiff(srcValue, dstValue) - if (!_.isEmpty(deepDiff)) { + if (!isEmpty(deepDiff)) { diff[key] = deepDiff } - } else if (!_.isEqual(srcValue, dstValue)) { + } else if (!isEqual(srcValue, dstValue)) { diff[key] = srcValue } }) @@ -362,7 +369,7 @@ function objectsDiff(src, dst) { function forInRecursive(object, callback) { function iterateThrough(obj, prefix) { - _.forIn(obj, (value, key) => { + forIn(obj, (value, key) => { const newPref = prefix + (prefix.length > 0 ? '.' : '') if (value instanceof Object) { iterateThrough(value, newPref + key) @@ -375,14 +382,14 @@ function forInRecursive(object, callback) { } function enquoteString(value) { - if (_.isString(value)) { + if (isString(value)) { return `"${value.replace(/"/g, '\\"')}"` } return value } function unquoteString(value) { - if (!_.isString(value)) { + if (!isString(value)) { return value } if (value[0] === '"' && value[value.length - 1] === '"') { diff --git a/packages/lib/src/utils.test.js b/packages/lib/src/utils.test.js index dae9040e..e1be0742 100644 --- a/packages/lib/src/utils.test.js +++ b/packages/lib/src/utils.test.js @@ -1,6 +1,6 @@ import chai, { expect } from 'chai' import dirtyChai from 'dirty-chai' -import _ from 'lodash' +import { clone } from 'lodash' import utils from './utils' chai.use(dirtyChai) @@ -156,7 +156,7 @@ describe('utils.objectsDiff()', () => { date: new Date(1522576800) } - ref.deep = { inside: _.clone(ref) } + ref.deep = { inside: clone(ref) } const expectSame = (o) => { expect(objectsDiff(o, ref)).to.deep.equal(o) @@ -168,9 +168,9 @@ describe('utils.objectsDiff()', () => { it('ignores the same value', () => { expectEmpty({ num: ref.num }) - expectEmpty({ obj: _.clone(ref.obj) }) - expectEmpty({ array: _.clone(ref.array) }) - expectEmpty({ date: _.clone(ref.date) }) + expectEmpty({ obj: clone(ref.obj) }) + expectEmpty({ array: clone(ref.array) }) + expectEmpty({ date: clone(ref.date) }) }) it('detects a changed value', () => { @@ -189,9 +189,9 @@ describe('utils.objectsDiff()', () => { it('deeply ignores the same value', () => { expectEmpty({ deep: { inside: { num: ref.num } } }) - expectEmpty({ deep: { inside: { obj: _.clone(ref.obj) } } }) - expectEmpty({ deep: { inside: { array: _.clone(ref.array) } } }) - expectEmpty({ deep: { inside: { date: _.clone(ref.date) } } }) + expectEmpty({ deep: { inside: { obj: clone(ref.obj) } } }) + expectEmpty({ deep: { inside: { array: clone(ref.array) } } }) + expectEmpty({ deep: { inside: { date: clone(ref.date) } } }) }) it('deeply detects a changed value', () => { diff --git a/packages/lib/src/utils/Cookies.js b/packages/lib/src/utils/Cookies.js index 21e4345d..a01ca7d2 100644 --- a/packages/lib/src/utils/Cookies.js +++ b/packages/lib/src/utils/Cookies.js @@ -1,4 +1,4 @@ -import _ from 'lodash' +import { merge } from 'lodash' import makeContextDependent from './makeContextDependent' const MAX_COOKIE_LEN = 4000 @@ -22,7 +22,7 @@ function _chunkString(string, chunkLen) { */ function Cookies(context, opts) { this.context = context - this._opts = _.merge( + this._opts = merge( { path: '/' }, diff --git a/packages/lib/src/utils/EventDispatcher.js b/packages/lib/src/utils/EventDispatcher.js index 4c51a98b..ea2ad60e 100644 --- a/packages/lib/src/utils/EventDispatcher.js +++ b/packages/lib/src/utils/EventDispatcher.js @@ -2,7 +2,7 @@ * This class introduces the simplest event system. */ -import _ from 'lodash' +import { remove, find, forEach, omitBy } from 'lodash' function isUndefOrEqual(param, value) { return !param || param === value @@ -42,7 +42,7 @@ EventDispatcher.prototype.addEventListener = function ( return par[0] === params[0] && par[1] === params[1] } - if (_.find(handlers, _checkPar) === undefined) { + if (find(handlers, _checkPar) === undefined) { handlers.push(params) } } @@ -63,8 +63,8 @@ EventDispatcher.prototype.removeEventListener = function ( context ) { const self = this - _.forEach(self._handlers, (handler, ev) => { - _.remove( + forEach(self._handlers, (handler, ev) => { + remove( handler, (values) => isUndefOrEqual(type, ev) && @@ -73,7 +73,7 @@ EventDispatcher.prototype.removeEventListener = function ( ) }) - this._handlers = _.omitBy(self._handlers, (handler) => handler.length === 0) + this._handlers = omitBy(self._handlers, (handler) => handler.length === 0) } /** @@ -84,7 +84,7 @@ EventDispatcher.prototype.removeEventListener = function ( EventDispatcher.prototype.dispatchEvent = function (event) { const self = this - _.forEach(this._handlers[event.type], (callback) => { + forEach(this._handlers[event.type], (callback) => { const context = callback[1] || self callback[0].apply(context, [event]) }) diff --git a/packages/lib/src/utils/MiewCLIParser.jison b/packages/lib/src/utils/MiewCLIParser.jison index ee8e489c..20f2ab15 100644 --- a/packages/lib/src/utils/MiewCLIParser.jison +++ b/packages/lib/src/utils/MiewCLIParser.jison @@ -250,9 +250,9 @@ RepresentationReference Description : Descriptor -> $1 - | Descriptor Descriptor -> yy._.assign($1, $2) - | Descriptor Descriptor Descriptor -> yy._.assign($1, $2, $3) - | Descriptor Descriptor Descriptor Descriptor -> yy._.assign($1, $2, $3, $4) + | Descriptor Descriptor -> yy.assign($1, $2) + | Descriptor Descriptor Descriptor -> yy.assign($1, $2, $3) + | Descriptor Descriptor Descriptor Descriptor -> yy.assign($1, $2, $3, $4) ; Descriptor diff --git a/packages/lib/src/utils/MiewCLIParser.js b/packages/lib/src/utils/MiewCLIParser.js index 211c82e3..43dae211 100644 --- a/packages/lib/src/utils/MiewCLIParser.js +++ b/packages/lib/src/utils/MiewCLIParser.js @@ -810,13 +810,13 @@ var parser = (function () { this.$ = $$[$0] break case 78: - this.$ = yy._.assign($$[$0 - 1], $$[$0]) + this.$ = yy.assign($$[$0 - 1], $$[$0]) break case 79: - this.$ = yy._.assign($$[$0 - 2], $$[$0 - 1], $$[$0]) + this.$ = yy.assign($$[$0 - 2], $$[$0 - 1], $$[$0]) break case 80: - this.$ = yy._.assign($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0]) + this.$ = yy.assign($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0]) break case 81: case 82: diff --git a/packages/lib/src/utils/logger.js b/packages/lib/src/utils/logger.js index 7cc04b5a..87c06683 100644 --- a/packages/lib/src/utils/logger.js +++ b/packages/lib/src/utils/logger.js @@ -4,7 +4,7 @@ * Allows users to log messages for five different levels, * enable console output and catch signal on each message. */ -import _ from 'lodash' +import { findKey, isNumber } from 'lodash' import EventDispatcher from './EventDispatcher' const priorities = { @@ -43,7 +43,7 @@ Logger.prototype.instantiate = function () { } function verify(number) { - if (!_.isNumber(number)) { + if (!isNumber(number)) { throw new Error('Wrong log level specified!') } return number @@ -55,7 +55,7 @@ function verify(number) { */ Object.defineProperty(Logger.prototype, 'level', { get() { - return _.findKey(priorities, (value) => value === this._priority) + return findKey(priorities, (value) => value === this._priority) }, set(level) { this._priority = verify(priorities[level]) @@ -131,7 +131,7 @@ Logger.prototype._message = function (priority, message) { if (priority < this._priority) { return } - const level = _.findKey(priorities, (value) => value === priority) + const level = findKey(priorities, (value) => value === priority) message = String(message) if (this.console) { const output = `miew:${level}: ${message}` From adbcc4e3789565a76acdd6ed08f8a166dd638acb Mon Sep 17 00:00:00 2001 From: Kirill Kapytov Date: Mon, 17 Jan 2022 18:27:13 +0300 Subject: [PATCH 2/2] Repair app --- packages/lib/src/ComplexVisual.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/lib/src/ComplexVisual.js b/packages/lib/src/ComplexVisual.js index 49464c35..921b6a6a 100644 --- a/packages/lib/src/ComplexVisual.js +++ b/packages/lib/src/ComplexVisual.js @@ -11,8 +11,8 @@ import Representation from './gfx/Representation' import Visual from './Visual' import ComplexVisualEdit from './ComplexVisualEdit' import meshutils from './gfx/meshutils' -import { Group, Mesh } from 'three' import { isEmpty, merge } from 'lodash' +import { Group, Mesh } from 'three' const { selectors } = chem @@ -198,7 +198,7 @@ class ComplexVisual extends Visual { ) // something was changed - if (isEmpty(diff)) { + if (!isEmpty(diff)) { target.needsRebuild = true for (const key in diff) { if (diff.hasOwnProperty(key)) {