@cesium/engine
Version:
CesiumJS is a JavaScript library for creating 3D globes and 2D maps in a web browser without a plugin.
1,530 lines (1,353 loc) • 96.9 kB
JavaScript
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartesian4 from "../Core/Cartesian4.js";
import Cartographic from "../Core/Cartographic.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import HeadingPitchRoll from "../Core/HeadingPitchRoll.js";
import IntersectionTests from "../Core/IntersectionTests.js";
import KeyboardEventModifier from "../Core/KeyboardEventModifier.js";
import CesiumMath from "../Core/Math.js";
import Matrix3 from "../Core/Matrix3.js";
import Matrix4 from "../Core/Matrix4.js";
import OrthographicFrustum from "../Core/OrthographicFrustum.js";
import Plane from "../Core/Plane.js";
import Quaternion from "../Core/Quaternion.js";
import Ray from "../Core/Ray.js";
import VerticalExaggeration from "../Core/VerticalExaggeration.js";
import Transforms from "../Core/Transforms.js";
import CameraEventAggregator from "./CameraEventAggregator.js";
import CameraEventType from "./CameraEventType.js";
import MapMode2D from "./MapMode2D.js";
import SceneMode from "./SceneMode.js";
import SceneTransforms from "./SceneTransforms.js";
import TweenCollection from "./TweenCollection.js";
/**
* Modifies the camera position and orientation based on mouse input to a canvas.
* @alias ScreenSpaceCameraController
* @constructor
*
* @param {Scene} scene The scene.
*/
function ScreenSpaceCameraController(scene) {
//>>includeStart('debug', pragmas.debug);
if (!defined(scene)) {
throw new DeveloperError("scene is required.");
}
//>>includeEnd('debug');
/**
* If true, inputs are allowed conditionally with the flags enableTranslate, enableZoom,
* enableRotate, enableTilt, and enableLook. If false, all inputs are disabled.
*
* NOTE: This setting is for temporary use cases, such as camera flights and
* drag-selection of regions (see Picking demo). It is typically set to false at the
* start of such events, and set true on completion. To keep inputs disabled
* past the end of camera flights, you must use the other booleans (enableTranslate,
* enableZoom, enableRotate, enableTilt, and enableLook).
* @type {boolean}
* @default true
*/
this.enableInputs = true;
/**
* If true, allows the user to pan around the map. If false, the camera stays locked at the current position.
* This flag only applies in 2D and Columbus view modes.
* @type {boolean}
* @default true
*/
this.enableTranslate = true;
/**
* If true, allows the user to zoom in and out. If false, the camera is locked to the current distance from the ellipsoid.
* @type {boolean}
* @default true
*/
this.enableZoom = true;
/**
* If true, allows the user to rotate the world which translates the user's position.
* This flag only applies in 2D and 3D.
* @type {boolean}
* @default true
*/
this.enableRotate = true;
/**
* If true, allows the user to tilt the camera. If false, the camera is locked to the current heading.
* This flag only applies in 3D and Columbus view.
* @type {boolean}
* @default true
*/
this.enableTilt = true;
/**
* If true, allows the user to use free-look. If false, the camera view direction can only be changed through translating
* or rotating. This flag only applies in 3D and Columbus view modes.
* @type {boolean}
* @default true
*/
this.enableLook = true;
/**
* A parameter in the range <code>[0, 1)</code> used to determine how long
* the camera will continue to spin because of inertia.
* With value of zero, the camera will have no inertia.
* @type {number}
* @default 0.9
*/
this.inertiaSpin = 0.9;
/**
* A parameter in the range <code>[0, 1)</code> used to determine how long
* the camera will continue to translate because of inertia.
* With value of zero, the camera will have no inertia.
* @type {number}
* @default 0.9
*/
this.inertiaTranslate = 0.9;
/**
* A parameter in the range <code>[0, 1)</code> used to determine how long
* the camera will continue to zoom because of inertia.
* With value of zero, the camera will have no inertia.
* @type {number}
* @default 0.8
*/
this.inertiaZoom = 0.8;
/**
* A parameter in the range <code>[0, 1)</code> used to limit the range
* of various user inputs to a percentage of the window width/height per animation frame.
* This helps keep the camera under control in low-frame-rate situations.
* @type {number}
* @default 0.1
*/
this.maximumMovementRatio = 0.1;
/**
* Sets the duration, in seconds, of the bounce back animations in 2D and Columbus view.
* @type {number}
* @default 3.0
*/
this.bounceAnimationTime = 3.0;
/**
* The minimum magnitude, in meters, of the camera position when zooming. Defaults to 1.0.
* @type {number}
* @default 1.0
*/
this.minimumZoomDistance = 1.0;
/**
* The maximum magnitude, in meters, of the camera position when zooming. Defaults to positive infinity.
* @type {number}
* @default {@link Number.POSITIVE_INFINITY}
*/
this.maximumZoomDistance = Number.POSITIVE_INFINITY;
/**
* A multiplier for the speed at which the camera will zoom.
* @type {Number}
* @default 5.0
*/
this.zoomFactor = 5.0;
/**
* The input that allows the user to pan around the map. This only applies in 2D and Columbus view modes.
* <p>
* The type can be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
* and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
* or an array of any of the preceding.
* </p>
* @type {CameraEventType|Array|undefined}
* @default {@link CameraEventType.LEFT_DRAG}
*/
this.translateEventTypes = CameraEventType.LEFT_DRAG;
/**
* The input that allows the user to zoom in/out.
* <p>
* The type can be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
* and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
* or an array of any of the preceding.
* </p>
* @type {CameraEventType|Array|undefined}
* @default [{@link CameraEventType.RIGHT_DRAG}, {@link CameraEventType.WHEEL}, {@link CameraEventType.PINCH}]
*/
this.zoomEventTypes = [
CameraEventType.RIGHT_DRAG,
CameraEventType.WHEEL,
CameraEventType.PINCH,
];
/**
* The input that allows the user to rotate around the globe or another object. This only applies in 3D and Columbus view modes.
* <p>
* The type can be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
* and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
* or an array of any of the preceding.
* </p>
* @type {CameraEventType|Array|undefined}
* @default {@link CameraEventType.LEFT_DRAG}
*/
this.rotateEventTypes = CameraEventType.LEFT_DRAG;
/**
* The input that allows the user to tilt in 3D and Columbus view or twist in 2D.
* <p>
* The type can be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
* and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
* or an array of any of the preceding.
* </p>
* @type {CameraEventType|Array|undefined}
* @default [{@link CameraEventType.MIDDLE_DRAG}, {@link CameraEventType.PINCH}, {
* eventType : {@link CameraEventType.LEFT_DRAG},
* modifier : {@link KeyboardEventModifier.CTRL}
* }, {
* eventType : {@link CameraEventType.RIGHT_DRAG},
* modifier : {@link KeyboardEventModifier.CTRL}
* }]
*/
this.tiltEventTypes = [
CameraEventType.MIDDLE_DRAG,
CameraEventType.PINCH,
{
eventType: CameraEventType.LEFT_DRAG,
modifier: KeyboardEventModifier.CTRL,
},
{
eventType: CameraEventType.RIGHT_DRAG,
modifier: KeyboardEventModifier.CTRL,
},
];
/**
* The input that allows the user to change the direction the camera is viewing. This only applies in 3D and Columbus view modes.
* <p>
* The type can be a {@link CameraEventType}, <code>undefined</code>, an object with <code>eventType</code>
* and <code>modifier</code> properties with types <code>CameraEventType</code> and {@link KeyboardEventModifier},
* or an array of any of the preceding.
* </p>
* @type {CameraEventType|Array|undefined}
* @default { eventType : {@link CameraEventType.LEFT_DRAG}, modifier : {@link KeyboardEventModifier.SHIFT} }
*/
this.lookEventTypes = {
eventType: CameraEventType.LEFT_DRAG,
modifier: KeyboardEventModifier.SHIFT,
};
const ellipsoid = scene.ellipsoid ?? Ellipsoid.default;
/**
* The minimum height the camera must be before picking the terrain or scene content instead of the ellipsoid. Defaults to scene.ellipsoid.minimumRadius * 0.025 when another ellipsoid than WGS84 is used.
* @type {number}
* @default 150000.0 or scene.ellipsoid.minimumRadius * 0.025
*/
this.minimumPickingTerrainHeight = Ellipsoid.WGS84.equals(ellipsoid)
? 150000.0
: ellipsoid.minimumRadius * 0.025;
this._minimumPickingTerrainHeight = this.minimumPickingTerrainHeight;
/**
* The minimum distance the camera must be before testing for collision with terrain when zoom with inertia. Default to scene.ellipsoid.minimumRadius * 0.00063 when another ellipsoid than WGS84 is used.
* @type {number}
* @default 4000.0 or scene.ellipsoid.minimumRadius * 0.00063
*/
this.minimumPickingTerrainDistanceWithInertia = Ellipsoid.WGS84.equals(
ellipsoid,
)
? 4000.0
: ellipsoid.minimumRadius * 0.00063;
/**
* The minimum height the camera must be before testing for collision with terrain. Default to scene.ellipsoid.minimumRadius * 0.0025 when another ellipsoid than WGS84 is used.
* @type {number}
* @default 15000.0 or scene.ellipsoid.minimumRadius * 0.0025.
*/
this.minimumCollisionTerrainHeight = Ellipsoid.WGS84.equals(ellipsoid)
? 15000.0
: ellipsoid.minimumRadius * 0.0025;
this._minimumCollisionTerrainHeight = this.minimumCollisionTerrainHeight;
/**
* The minimum height the camera must be before switching from rotating a track ball to
* free look when clicks originate on the sky or in space. Defaults to ellipsoid.minimumRadius * 1.175 when another ellipsoid than WGS84 is used.
* @type {number}
* @default 7500000.0 or scene.ellipsoid.minimumRadius * 1.175
*/
this.minimumTrackBallHeight = Ellipsoid.WGS84.equals(ellipsoid)
? 7500000.0
: ellipsoid.minimumRadius * 1.175;
this._minimumTrackBallHeight = this.minimumTrackBallHeight;
/**
* When disabled, the values of <code>maximumZoomDistance</code> and <code>minimumZoomDistance</code> are ignored.
* Also used in conjunction with {@link Cesium3DTileset#enableCollision} to prevent the camera from moving through or below a 3D Tileset surface.
* This may also affect clamping behavior when using {@link HeightReference.CLAMP_TO_GROUND} on 3D Tiles.
* @type {boolean}
* @default true
*/
this.enableCollisionDetection = true;
/**
* The angle, relative to the ellipsoid normal, restricting the maximum amount that the user can tilt the camera. If <code>undefined</code>, the angle of the camera tilt is unrestricted.
* @type {number|undefined}
* @default undefined
*
* @example
* // Prevent the camera from tilting below the ellipsoid surface
* viewer.scene.screenSpaceCameraController.maximumTiltAngle = Math.PI / 2.0;
*/
this.maximumTiltAngle = undefined;
this._scene = scene;
this._globe = undefined;
this._ellipsoid = ellipsoid;
this._lastGlobeHeight = 0.0;
this._aggregator = new CameraEventAggregator(scene.canvas);
this._lastInertiaSpinMovement = undefined;
this._lastInertiaZoomMovement = undefined;
this._lastInertiaTranslateMovement = undefined;
this._lastInertiaTiltMovement = undefined;
// Zoom disables tilt, spin, and translate inertia
// Tilt disables spin and translate inertia
this._inertiaDisablers = {
_lastInertiaZoomMovement: [
"_lastInertiaSpinMovement",
"_lastInertiaTranslateMovement",
"_lastInertiaTiltMovement",
],
_lastInertiaTiltMovement: [
"_lastInertiaSpinMovement",
"_lastInertiaTranslateMovement",
],
};
this._tweens = new TweenCollection();
this._tween = undefined;
this._horizontalRotationAxis = undefined;
this._tiltCenterMousePosition = new Cartesian2(-1.0, -1.0);
this._tiltCenter = new Cartesian3();
this._rotateMousePosition = new Cartesian2(-1.0, -1.0);
this._rotateStartPosition = new Cartesian3();
this._strafeStartPosition = new Cartesian3();
this._strafeMousePosition = new Cartesian2();
this._strafeEndMousePosition = new Cartesian2();
this._zoomMouseStart = new Cartesian2(-1.0, -1.0);
this._zoomWorldPosition = new Cartesian3();
this._useZoomWorldPosition = false;
this._panLastMousePosition = new Cartesian2();
this._panLastWorldPosition = new Cartesian3();
this._tiltCVOffMap = false;
this._looking = false;
this._rotating = false;
this._strafing = false;
this._zoomingOnVector = false;
this._zoomingUnderground = false;
this._rotatingZoom = false;
this._adjustedHeightForTerrain = false;
this._cameraUnderground = false;
const projection = scene.mapProjection;
this._maxCoord = projection.project(
new Cartographic(Math.PI, CesiumMath.PI_OVER_TWO),
);
// Constants, Make any of these public?
this._rotateFactor = undefined;
this._rotateRateRangeAdjustment = undefined;
this._maximumRotateRate = 1.77;
this._minimumRotateRate = 1.0 / 5000.0;
this._minimumZoomRate = 20.0;
this._maximumZoomRate = 5906376272000.0; // distance from the Sun to Pluto in meters.
this._minimumUndergroundPickDistance = 2000.0;
this._maximumUndergroundPickDistance = 10000.0;
}
function decay(time, coefficient) {
if (time < 0) {
return 0.0;
}
const tau = (1.0 - coefficient) * 25.0;
return Math.exp(-tau * time);
}
function sameMousePosition(movement) {
return Cartesian2.equalsEpsilon(
movement.startPosition,
movement.endPosition,
CesiumMath.EPSILON14,
);
}
// If the time between mouse down and mouse up is not between
// these thresholds, the camera will not move with inertia.
// This value is probably dependent on the browser and/or the
// hardware. Should be investigated further.
const inertiaMaxClickTimeThreshold = 0.4;
function maintainInertia(
aggregator,
type,
modifier,
decayCoef,
action,
object,
lastMovementName,
) {
let movementState = object[lastMovementName];
if (!defined(movementState)) {
movementState = object[lastMovementName] = {
startPosition: new Cartesian2(),
endPosition: new Cartesian2(),
motion: new Cartesian2(),
inertiaEnabled: true,
};
}
const ts = aggregator.getButtonPressTime(type, modifier);
const tr = aggregator.getButtonReleaseTime(type, modifier);
const threshold = ts && tr && (tr.getTime() - ts.getTime()) / 1000.0;
const now = new Date();
const fromNow = tr && (now.getTime() - tr.getTime()) / 1000.0;
if (ts && tr && threshold < inertiaMaxClickTimeThreshold) {
const d = decay(fromNow, decayCoef);
const lastMovement = aggregator.getLastMovement(type, modifier);
if (
!defined(lastMovement) ||
sameMousePosition(lastMovement) ||
!movementState.inertiaEnabled
) {
return;
}
movementState.motion.x =
(lastMovement.endPosition.x - lastMovement.startPosition.x) * 0.5;
movementState.motion.y =
(lastMovement.endPosition.y - lastMovement.startPosition.y) * 0.5;
movementState.startPosition = Cartesian2.clone(
lastMovement.startPosition,
movementState.startPosition,
);
movementState.endPosition = Cartesian2.multiplyByScalar(
movementState.motion,
d,
movementState.endPosition,
);
movementState.endPosition = Cartesian2.add(
movementState.startPosition,
movementState.endPosition,
movementState.endPosition,
);
// If value from the decreasing exponential function is close to zero,
// the end coordinates may be NaN.
if (
isNaN(movementState.endPosition.x) ||
isNaN(movementState.endPosition.y) ||
Cartesian2.distance(
movementState.startPosition,
movementState.endPosition,
) < 0.5
) {
return;
}
if (!aggregator.isButtonDown(type, modifier)) {
const startPosition = aggregator.getStartMousePosition(type, modifier);
action(object, startPosition, movementState);
}
}
}
function activateInertia(controller, inertiaStateName) {
if (defined(inertiaStateName)) {
// Re-enable inertia if it was disabled
let movementState = controller[inertiaStateName];
if (defined(movementState)) {
movementState.inertiaEnabled = true;
}
// Disable inertia on other movements
const inertiasToDisable = controller._inertiaDisablers[inertiaStateName];
if (defined(inertiasToDisable)) {
const length = inertiasToDisable.length;
for (let i = 0; i < length; ++i) {
movementState = controller[inertiasToDisable[i]];
if (defined(movementState)) {
movementState.inertiaEnabled = false;
}
}
}
}
}
const scratchEventTypeArray = [];
function reactToInput(
controller,
enabled,
eventTypes,
action,
inertiaConstant,
inertiaStateName,
) {
if (!defined(eventTypes)) {
return;
}
const aggregator = controller._aggregator;
if (!Array.isArray(eventTypes)) {
scratchEventTypeArray[0] = eventTypes;
eventTypes = scratchEventTypeArray;
}
const length = eventTypes.length;
for (let i = 0; i < length; ++i) {
const eventType = eventTypes[i];
const type = defined(eventType.eventType) ? eventType.eventType : eventType;
const modifier = eventType.modifier;
const movement =
aggregator.isMoving(type, modifier) &&
aggregator.getMovement(type, modifier);
const startPosition = aggregator.getStartMousePosition(type, modifier);
if (controller.enableInputs && enabled) {
if (movement) {
action(controller, startPosition, movement);
activateInertia(controller, inertiaStateName);
} else if (inertiaConstant < 1.0) {
maintainInertia(
aggregator,
type,
modifier,
inertiaConstant,
action,
controller,
inertiaStateName,
);
}
}
}
}
const scratchZoomPickRay = new Ray();
const scratchPickCartesian = new Cartesian3();
const scratchZoomOffset = new Cartesian2();
const scratchZoomDirection = new Cartesian3();
const scratchCenterPixel = new Cartesian2();
const scratchCenterPosition = new Cartesian3();
const scratchPositionNormal = new Cartesian3();
const scratchPickNormal = new Cartesian3();
const scratchZoomAxis = new Cartesian3();
const scratchCameraPositionNormal = new Cartesian3();
// Scratch variables used in zooming algorithm
const scratchTargetNormal = new Cartesian3();
const scratchCameraPosition = new Cartesian3();
const scratchCameraUpNormal = new Cartesian3();
const scratchCameraRightNormal = new Cartesian3();
const scratchForwardNormal = new Cartesian3();
const scratchPositionToTarget = new Cartesian3();
const scratchPositionToTargetNormal = new Cartesian3();
const scratchPan = new Cartesian3();
const scratchCenterMovement = new Cartesian3();
const scratchCenter = new Cartesian3();
const scratchCartesian = new Cartesian3();
const scratchCartesianTwo = new Cartesian3();
const scratchCartesianThree = new Cartesian3();
const scratchZoomViewOptions = {
orientation: new HeadingPitchRoll(),
};
function handleZoom(
object,
startPosition,
movement,
zoomFactor,
distanceMeasure,
unitPositionDotDirection,
) {
let percentage = 1.0;
if (defined(unitPositionDotDirection)) {
percentage = CesiumMath.clamp(
Math.abs(unitPositionDotDirection),
0.25,
1.0,
);
}
const diff = movement.endPosition.y - movement.startPosition.y;
// distanceMeasure should be the height above the ellipsoid.
// When approaching the surface, the zoomRate slows and stops minimumZoomDistance above it.
const approachingSurface = diff > 0;
const minHeight = approachingSurface
? object.minimumZoomDistance * percentage
: 0;
const maxHeight = object.maximumZoomDistance;
const minDistance = distanceMeasure - minHeight;
let zoomRate = zoomFactor * minDistance;
zoomRate = CesiumMath.clamp(
zoomRate,
object._minimumZoomRate,
object._maximumZoomRate,
);
let rangeWindowRatio = diff / object._scene.canvas.clientHeight;
rangeWindowRatio = Math.min(rangeWindowRatio, object.maximumMovementRatio);
let distance = zoomRate * rangeWindowRatio;
if (
object.enableCollisionDetection ||
object.minimumZoomDistance === 0.0 ||
!defined(object._globe) // look-at mode
) {
if (distance > 0.0 && Math.abs(distanceMeasure - minHeight) < 1.0) {
return;
}
if (distance < 0.0 && Math.abs(distanceMeasure - maxHeight) < 1.0) {
return;
}
if (distanceMeasure - distance < minHeight) {
distance = distanceMeasure - minHeight - 1.0;
} else if (distanceMeasure - distance > maxHeight) {
distance = distanceMeasure - maxHeight;
}
}
const scene = object._scene;
const camera = scene.camera;
const mode = scene.mode;
const orientation = scratchZoomViewOptions.orientation;
orientation.heading = camera.heading;
orientation.pitch = camera.pitch;
orientation.roll = camera.roll;
const sameStartPosition =
movement.inertiaEnabled ??
Cartesian2.equals(startPosition, object._zoomMouseStart);
let zoomingOnVector = object._zoomingOnVector;
let rotatingZoom = object._rotatingZoom;
let pickedPosition;
if (!sameStartPosition) {
object._zoomMouseStart = Cartesian2.clone(
startPosition,
object._zoomMouseStart,
);
// When camera transform is set, such as tracking an entity, object._globe will be undefined, and no position should be picked
if (defined(object._globe) && mode === SceneMode.SCENE2D) {
pickedPosition = camera.getPickRay(
startPosition,
scratchZoomPickRay,
).origin;
pickedPosition = Cartesian3.fromElements(
pickedPosition.y,
pickedPosition.z,
pickedPosition.x,
);
} else if (defined(object._globe)) {
pickedPosition = pickPosition(
object,
startPosition,
scratchPickCartesian,
);
}
if (defined(pickedPosition)) {
object._useZoomWorldPosition = true;
object._zoomWorldPosition = Cartesian3.clone(
pickedPosition,
object._zoomWorldPosition,
);
} else {
object._useZoomWorldPosition = false;
}
zoomingOnVector = object._zoomingOnVector = false;
rotatingZoom = object._rotatingZoom = false;
object._zoomingUnderground = object._cameraUnderground;
}
if (!object._useZoomWorldPosition) {
camera.zoomIn(distance);
return;
}
let zoomOnVector = mode === SceneMode.COLUMBUS_VIEW;
if (camera.positionCartographic.height < 2000000) {
rotatingZoom = true;
}
if (!sameStartPosition || rotatingZoom) {
if (mode === SceneMode.SCENE2D) {
const worldPosition = object._zoomWorldPosition;
const endPosition = camera.position;
if (
!Cartesian3.equals(worldPosition, endPosition) &&
camera.positionCartographic.height < object._maxCoord.x * 2.0
) {
const savedX = camera.position.x;
const direction = Cartesian3.subtract(
worldPosition,
endPosition,
scratchZoomDirection,
);
Cartesian3.normalize(direction, direction);
const d =
(Cartesian3.distance(worldPosition, endPosition) * distance) /
(camera.getMagnitude() * 0.5);
camera.move(direction, d * 0.5);
if (
(camera.position.x < 0.0 && savedX > 0.0) ||
(camera.position.x > 0.0 && savedX < 0.0)
) {
pickedPosition = camera.getPickRay(
startPosition,
scratchZoomPickRay,
).origin;
pickedPosition = Cartesian3.fromElements(
pickedPosition.y,
pickedPosition.z,
pickedPosition.x,
);
object._zoomWorldPosition = Cartesian3.clone(
pickedPosition,
object._zoomWorldPosition,
);
}
}
} else if (mode === SceneMode.SCENE3D) {
const cameraPositionNormal = Cartesian3.normalize(
camera.position,
scratchCameraPositionNormal,
);
if (
object._cameraUnderground ||
object._zoomingUnderground ||
(camera.positionCartographic.height < 3000.0 &&
Math.abs(Cartesian3.dot(camera.direction, cameraPositionNormal)) <
0.6)
) {
zoomOnVector = true;
} else {
const canvas = scene.canvas;
const centerPixel = scratchCenterPixel;
centerPixel.x = canvas.clientWidth / 2;
centerPixel.y = canvas.clientHeight / 2;
const centerPosition = pickPosition(
object,
centerPixel,
scratchCenterPosition,
);
// If centerPosition is not defined, it means the globe does not cover the center position of screen
if (!defined(centerPosition)) {
zoomOnVector = true;
} else if (camera.positionCartographic.height < 1000000) {
// The math in the else block assumes the camera
// points toward the earth surface, so we check it here.
// Theoretically, we should check for 90 degree, but it doesn't behave well when parallel
// to the earth surface
if (Cartesian3.dot(camera.direction, cameraPositionNormal) >= -0.5) {
zoomOnVector = true;
} else {
const cameraPosition = scratchCameraPosition;
Cartesian3.clone(camera.position, cameraPosition);
const target = object._zoomWorldPosition;
let targetNormal = scratchTargetNormal;
targetNormal = Cartesian3.normalize(target, targetNormal);
if (Cartesian3.dot(targetNormal, cameraPositionNormal) < 0.0) {
return;
}
const center = scratchCenter;
const forward = scratchForwardNormal;
Cartesian3.clone(camera.direction, forward);
Cartesian3.add(
cameraPosition,
Cartesian3.multiplyByScalar(forward, 1000, scratchCartesian),
center,
);
const positionToTarget = scratchPositionToTarget;
const positionToTargetNormal = scratchPositionToTargetNormal;
Cartesian3.subtract(target, cameraPosition, positionToTarget);
Cartesian3.normalize(positionToTarget, positionToTargetNormal);
const alphaDot = Cartesian3.dot(
cameraPositionNormal,
positionToTargetNormal,
);
if (alphaDot >= 0.0) {
// We zoomed past the target, and this zoom is not valid anymore.
// This line causes the next zoom movement to pick a new starting point.
object._zoomMouseStart.x = -1;
return;
}
const alpha = Math.acos(-alphaDot);
const cameraDistance = Cartesian3.magnitude(cameraPosition);
const targetDistance = Cartesian3.magnitude(target);
const remainingDistance = cameraDistance - distance;
const positionToTargetDistance =
Cartesian3.magnitude(positionToTarget);
const gamma = Math.asin(
CesiumMath.clamp(
(positionToTargetDistance / targetDistance) * Math.sin(alpha),
-1.0,
1.0,
),
);
const delta = Math.asin(
CesiumMath.clamp(
(remainingDistance / targetDistance) * Math.sin(alpha),
-1.0,
1.0,
),
);
const beta = gamma - delta + alpha;
const up = scratchCameraUpNormal;
Cartesian3.normalize(cameraPosition, up);
let right = scratchCameraRightNormal;
right = Cartesian3.cross(positionToTargetNormal, up, right);
right = Cartesian3.normalize(right, right);
Cartesian3.normalize(
Cartesian3.cross(up, right, scratchCartesian),
forward,
);
// Calculate new position to move to
Cartesian3.multiplyByScalar(
Cartesian3.normalize(center, scratchCartesian),
Cartesian3.magnitude(center) - distance,
center,
);
Cartesian3.normalize(cameraPosition, cameraPosition);
Cartesian3.multiplyByScalar(
cameraPosition,
remainingDistance,
cameraPosition,
);
// Pan
const pMid = scratchPan;
Cartesian3.multiplyByScalar(
Cartesian3.add(
Cartesian3.multiplyByScalar(
up,
Math.cos(beta) - 1,
scratchCartesianTwo,
),
Cartesian3.multiplyByScalar(
forward,
Math.sin(beta),
scratchCartesianThree,
),
scratchCartesian,
),
remainingDistance,
pMid,
);
Cartesian3.add(cameraPosition, pMid, cameraPosition);
Cartesian3.normalize(center, up);
Cartesian3.normalize(
Cartesian3.cross(up, right, scratchCartesian),
forward,
);
const cMid = scratchCenterMovement;
Cartesian3.multiplyByScalar(
Cartesian3.add(
Cartesian3.multiplyByScalar(
up,
Math.cos(beta) - 1,
scratchCartesianTwo,
),
Cartesian3.multiplyByScalar(
forward,
Math.sin(beta),
scratchCartesianThree,
),
scratchCartesian,
),
Cartesian3.magnitude(center),
cMid,
);
Cartesian3.add(center, cMid, center);
// Update camera
// Set new position
Cartesian3.clone(cameraPosition, camera.position);
// Set new direction
Cartesian3.normalize(
Cartesian3.subtract(center, cameraPosition, scratchCartesian),
camera.direction,
);
Cartesian3.clone(camera.direction, camera.direction);
// Set new right & up vectors
Cartesian3.cross(camera.direction, camera.up, camera.right);
Cartesian3.cross(camera.right, camera.direction, camera.up);
camera.setView(scratchZoomViewOptions);
return;
}
} else {
const positionNormal = Cartesian3.normalize(
centerPosition,
scratchPositionNormal,
);
const pickedNormal = Cartesian3.normalize(
object._zoomWorldPosition,
scratchPickNormal,
);
const dotProduct = Cartesian3.dot(pickedNormal, positionNormal);
if (dotProduct > 0.0 && dotProduct < 1.0) {
const angle = CesiumMath.acosClamped(dotProduct);
const axis = Cartesian3.cross(
pickedNormal,
positionNormal,
scratchZoomAxis,
);
const denom =
Math.abs(angle) > CesiumMath.toRadians(20.0)
? camera.positionCartographic.height * 0.75
: camera.positionCartographic.height - distance;
const scalar = distance / denom;
camera.rotate(axis, angle * scalar);
}
}
}
}
object._rotatingZoom = !zoomOnVector;
}
if ((!sameStartPosition && zoomOnVector) || zoomingOnVector) {
let ray;
const zoomMouseStart = SceneTransforms.worldToWindowCoordinates(
scene,
object._zoomWorldPosition,
scratchZoomOffset,
);
if (
mode !== SceneMode.COLUMBUS_VIEW &&
Cartesian2.equals(startPosition, object._zoomMouseStart) &&
defined(zoomMouseStart)
) {
ray = camera.getPickRay(zoomMouseStart, scratchZoomPickRay);
} else {
ray = camera.getPickRay(startPosition, scratchZoomPickRay);
}
const rayDirection = ray.direction;
if (mode === SceneMode.COLUMBUS_VIEW || mode === SceneMode.SCENE2D) {
Cartesian3.fromElements(
rayDirection.y,
rayDirection.z,
rayDirection.x,
rayDirection,
);
}
camera.move(rayDirection, distance);
object._zoomingOnVector = true;
} else {
camera.zoomIn(distance);
}
if (!object._cameraUnderground) {
camera.setView(scratchZoomViewOptions);
}
}
const translate2DStart = new Ray();
const translate2DEnd = new Ray();
const scratchTranslateP0 = new Cartesian3();
function translate2D(controller, startPosition, movement) {
const scene = controller._scene;
const camera = scene.camera;
let start = camera.getPickRay(
movement.startPosition,
translate2DStart,
).origin;
let end = camera.getPickRay(movement.endPosition, translate2DEnd).origin;
start = Cartesian3.fromElements(start.y, start.z, start.x, start);
end = Cartesian3.fromElements(end.y, end.z, end.x, end);
const direction = Cartesian3.subtract(start, end, scratchTranslateP0);
const distance = Cartesian3.magnitude(direction);
if (distance > 0.0) {
Cartesian3.normalize(direction, direction);
camera.move(direction, distance);
}
}
function zoom2D(controller, startPosition, movement) {
if (defined(movement.distance)) {
movement = movement.distance;
}
const scene = controller._scene;
const camera = scene.camera;
handleZoom(
controller,
startPosition,
movement,
controller.zoomFactor,
camera.getMagnitude(),
);
}
const twist2DStart = new Cartesian2();
const twist2DEnd = new Cartesian2();
function twist2D(controller, startPosition, movement) {
if (defined(movement.angleAndHeight)) {
singleAxisTwist2D(controller, startPosition, movement.angleAndHeight);
return;
}
const scene = controller._scene;
const camera = scene.camera;
const canvas = scene.canvas;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
let start = twist2DStart;
start.x = (2.0 / width) * movement.startPosition.x - 1.0;
start.y = (2.0 / height) * (height - movement.startPosition.y) - 1.0;
start = Cartesian2.normalize(start, start);
let end = twist2DEnd;
end.x = (2.0 / width) * movement.endPosition.x - 1.0;
end.y = (2.0 / height) * (height - movement.endPosition.y) - 1.0;
end = Cartesian2.normalize(end, end);
let startTheta = CesiumMath.acosClamped(start.x);
if (start.y < 0) {
startTheta = CesiumMath.TWO_PI - startTheta;
}
let endTheta = CesiumMath.acosClamped(end.x);
if (end.y < 0) {
endTheta = CesiumMath.TWO_PI - endTheta;
}
const theta = endTheta - startTheta;
camera.twistRight(theta);
}
function singleAxisTwist2D(controller, startPosition, movement) {
let rotateRate =
controller._rotateFactor * controller._rotateRateRangeAdjustment;
if (rotateRate > controller._maximumRotateRate) {
rotateRate = controller._maximumRotateRate;
}
if (rotateRate < controller._minimumRotateRate) {
rotateRate = controller._minimumRotateRate;
}
const scene = controller._scene;
const camera = scene.camera;
const canvas = scene.canvas;
let phiWindowRatio =
(movement.endPosition.x - movement.startPosition.x) / canvas.clientWidth;
phiWindowRatio = Math.min(phiWindowRatio, controller.maximumMovementRatio);
const deltaPhi = rotateRate * phiWindowRatio * Math.PI * 4.0;
camera.twistRight(deltaPhi);
}
function update2D(controller) {
const rotatable2D = controller._scene.mapMode2D === MapMode2D.ROTATE;
if (!Matrix4.equals(Matrix4.IDENTITY, controller._scene.camera.transform)) {
reactToInput(
controller,
controller.enableZoom,
controller.zoomEventTypes,
zoom2D,
controller.inertiaZoom,
"_lastInertiaZoomMovement",
);
if (rotatable2D) {
reactToInput(
controller,
controller.enableRotate,
controller.translateEventTypes,
twist2D,
controller.inertiaSpin,
"_lastInertiaSpinMovement",
);
}
} else {
reactToInput(
controller,
controller.enableTranslate,
controller.translateEventTypes,
translate2D,
controller.inertiaTranslate,
"_lastInertiaTranslateMovement",
);
reactToInput(
controller,
controller.enableZoom,
controller.zoomEventTypes,
zoom2D,
controller.inertiaZoom,
"_lastInertiaZoomMovement",
);
if (rotatable2D) {
reactToInput(
controller,
controller.enableRotate,
controller.tiltEventTypes,
twist2D,
controller.inertiaSpin,
"_lastInertiaTiltMovement",
);
}
}
}
const pickGlobeScratchRay = new Ray();
const scratchDepthIntersection = new Cartesian3();
const scratchRayIntersection = new Cartesian3();
function pickPosition(controller, mousePosition, result) {
const scene = controller._scene;
const globe = controller._globe;
const camera = scene.camera;
let depthIntersection;
if (scene.pickPositionSupported) {
depthIntersection = scene.pickPositionWorldCoordinates(
mousePosition,
scratchDepthIntersection,
);
}
if (!defined(globe)) {
return Cartesian3.clone(depthIntersection, result);
}
const cullBackFaces = !controller._cameraUnderground;
const ray = camera.getPickRay(mousePosition, pickGlobeScratchRay);
const rayIntersection = globe.pickWorldCoordinates(
ray,
scene,
cullBackFaces,
scratchRayIntersection,
);
const pickDistance = defined(depthIntersection)
? Cartesian3.distance(depthIntersection, camera.positionWC)
: Number.POSITIVE_INFINITY;
const rayDistance = defined(rayIntersection)
? Cartesian3.distance(rayIntersection, camera.positionWC)
: Number.POSITIVE_INFINITY;
if (pickDistance < rayDistance) {
return Cartesian3.clone(depthIntersection, result);
}
return Cartesian3.clone(rayIntersection, result);
}
const scratchDistanceCartographic = new Cartographic();
function getDistanceFromSurface(controller) {
const ellipsoid = controller._ellipsoid;
const scene = controller._scene;
const camera = scene.camera;
const mode = scene.mode;
let height = 0.0;
if (mode === SceneMode.SCENE3D) {
const cartographic = ellipsoid.cartesianToCartographic(
camera.position,
scratchDistanceCartographic,
);
if (defined(cartographic)) {
height = cartographic.height;
}
} else {
height = camera.position.z;
}
const globeHeight = controller._scene.globeHeight ?? 0.0;
const distanceFromSurface = Math.abs(globeHeight - height);
return distanceFromSurface;
}
const scratchSurfaceNormal = new Cartesian3();
function getZoomDistanceUnderground(controller, ray) {
const origin = ray.origin;
const direction = ray.direction;
const distanceFromSurface = getDistanceFromSurface(controller);
// Weight zoom distance based on how strongly the pick ray is pointing inward.
// Geocentric normal is accurate enough for these purposes
const surfaceNormal = Cartesian3.normalize(origin, scratchSurfaceNormal);
let strength = Math.abs(Cartesian3.dot(surfaceNormal, direction));
strength = Math.max(strength, 0.5) * 2.0;
return distanceFromSurface * strength;
}
function getTiltCenterUnderground(controller, ray, pickedPosition, result) {
let distance = Cartesian3.distance(ray.origin, pickedPosition);
const distanceFromSurface = getDistanceFromSurface(controller);
const maximumDistance = CesiumMath.clamp(
distanceFromSurface * 5.0,
controller._minimumUndergroundPickDistance,
controller._maximumUndergroundPickDistance,
);
if (distance > maximumDistance) {
// Simulate look-at behavior by tilting around a small invisible sphere
distance = Math.min(distance, distanceFromSurface / 5.0);
distance = Math.max(distance, 100.0);
}
return Ray.getPoint(ray, distance, result);
}
function getStrafeStartPositionUnderground(
controller,
ray,
pickedPosition,
result,
) {
let distance;
if (!defined(pickedPosition)) {
distance = getDistanceFromSurface(controller);
} else {
distance = Cartesian3.distance(ray.origin, pickedPosition);
if (distance > controller._maximumUndergroundPickDistance) {
// If the picked position is too far away set the strafe speed based on the
// camera's height from the globe surface
distance = getDistanceFromSurface(controller);
}
}
return Ray.getPoint(ray, distance, result);
}
const scratchInertialDelta = new Cartesian2();
function continueStrafing(controller, movement) {
// Update the end position continually based on the inertial delta
const originalEndPosition = movement.endPosition;
const inertialDelta = Cartesian2.subtract(
movement.endPosition,
movement.startPosition,
scratchInertialDelta,
);
const endPosition = controller._strafeEndMousePosition;
Cartesian2.add(endPosition, inertialDelta, endPosition);
movement.endPosition = endPosition;
strafe(controller, movement, controller._strafeStartPosition);
movement.endPosition = originalEndPosition;
}
const translateCVStartRay = new Ray();
const translateCVEndRay = new Ray();
const translateCVStartPos = new Cartesian3();
const translateCVEndPos = new Cartesian3();
const translateCVDifference = new Cartesian3();
const translateCVOrigin = new Cartesian3();
const translateCVPlane = new Plane(Cartesian3.UNIT_X, 0.0);
const translateCVStartMouse = new Cartesian2();
const translateCVEndMouse = new Cartesian2();
function translateCV(controller, startPosition, movement) {
if (!Cartesian3.equals(startPosition, controller._translateMousePosition)) {
controller._looking = false;
}
if (!Cartesian3.equals(startPosition, controller._strafeMousePosition)) {
controller._strafing = false;
}
if (controller._looking) {
look3D(controller, startPosition, movement);
return;
}
if (controller._strafing) {
continueStrafing(controller, movement);
return;
}
const scene = controller._scene;
const camera = scene.camera;
const cameraUnderground = controller._cameraUnderground;
const startMouse = Cartesian2.clone(
movement.startPosition,
translateCVStartMouse,
);
const endMouse = Cartesian2.clone(movement.endPosition, translateCVEndMouse);
let startRay = camera.getPickRay(startMouse, translateCVStartRay);
const origin = Cartesian3.clone(Cartesian3.ZERO, translateCVOrigin);
const normal = Cartesian3.UNIT_X;
let globePos;
if (camera.position.z < controller._minimumPickingTerrainHeight) {
globePos = pickPosition(controller, startMouse, translateCVStartPos);
if (defined(globePos)) {
origin.x = globePos.x;
}
}
if (
cameraUnderground ||
(origin.x > camera.position.z && defined(globePos))
) {
let pickPosition = globePos;
if (cameraUnderground) {
pickPosition = getStrafeStartPositionUnderground(
controller,
startRay,
globePos,
translateCVStartPos,
);
}
Cartesian2.clone(startPosition, controller._strafeMousePosition);
Cartesian2.clone(startPosition, controller._strafeEndMousePosition);
Cartesian3.clone(pickPosition, controller._strafeStartPosition);
controller._strafing = true;
strafe(controller, movement, controller._strafeStartPosition);
return;
}
const plane = Plane.fromPointNormal(origin, normal, translateCVPlane);
startRay = camera.getPickRay(startMouse, translateCVStartRay);
const startPlanePos = IntersectionTests.rayPlane(
startRay,
plane,
translateCVStartPos,
);
const endRay = camera.getPickRay(endMouse, translateCVEndRay);
const endPlanePos = IntersectionTests.rayPlane(
endRay,
plane,
translateCVEndPos,
);
if (!defined(startPlanePos) || !defined(endPlanePos)) {
controller._looking = true;
look3D(controller, startPosition, movement);
Cartesian2.clone(startPosition, controller._translateMousePosition);
return;
}
const diff = Cartesian3.subtract(
startPlanePos,
endPlanePos,
translateCVDifference,
);
const temp = diff.x;
diff.x = diff.y;
diff.y = diff.z;
diff.z = temp;
const mag = Cartesian3.magnitude(diff);
if (mag > CesiumMath.EPSILON6) {
Cartesian3.normalize(diff, diff);
camera.move(diff, mag);
}
}
const rotateCVWindowPos = new Cartesian2();
const rotateCVWindowRay = new Ray();
const rotateCVCenter = new Cartesian3();
const rotateCVVerticalCenter = new Cartesian3();
const rotateCVTransform = new Matrix4();
const rotateCVVerticalTransform = new Matrix4();
const rotateCVOrigin = new Cartesian3();
const rotateCVPlane = new Plane(Cartesian3.UNIT_X, 0.0);
const rotateCVCartesian3 = new Cartesian3();
const rotateCVCart = new Cartographic();
const rotateCVOldTransform = new Matrix4();
const rotateCVQuaternion = new Quaternion();
const rotateCVMatrix = new Matrix3();
const tilt3DCartesian3 = new Cartesian3();
function rotateCV(controller, startPosition, movement) {
if (defined(movement.angleAndHeight)) {
movement = movement.angleAndHeight;
}
if (!Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) {
controller._tiltCVOffMap = false;
controller._looking = false;
}
if (controller._looking) {
look3D(controller, startPosition, movement);
return;
}
const scene = controller._scene;
const camera = scene.camera;
if (
controller._tiltCVOffMap ||
!controller.onMap() ||
Math.abs(camera.position.z) > controller._minimumPickingTerrainHeight
) {
controller._tiltCVOffMap = true;
rotateCVOnPlane(controller, startPosition, movement);
} else {
rotateCVOnTerrain(controller, startPosition, movement);
}
}
function rotateCVOnPlane(controller, startPosition, movement) {
const scene = controller._scene;
const camera = scene.camera;
const canvas = scene.canvas;
const windowPosition = rotateCVWindowPos;
windowPosition.x = canvas.clientWidth / 2;
windowPosition.y = canvas.clientHeight / 2;
const ray = camera.getPickRay(windowPosition, rotateCVWindowRay);
const normal = Cartesian3.UNIT_X;
const position = ray.origin;
const direction = ray.direction;
let scalar;
const normalDotDirection = Cartesian3.dot(normal, direction);
if (Math.abs(normalDotDirection) > CesiumMath.EPSILON6) {
scalar = -Cartesian3.dot(normal, position) / normalDotDirection;
}
if (!defined(scalar) || scalar <= 0.0) {
controller._looking = true;
look3D(controller, startPosition, movement);
Cartesian2.clone(startPosition, controller._tiltCenterMousePosition);
return;
}
const center = Cartesian3.multiplyByScalar(direction, scalar, rotateCVCenter);
Cartesian3.add(position, center, center);
const projection = scene.mapProjection;
const ellipsoid = projection.ellipsoid;
Cartesian3.fromElements(center.y, center.z, center.x, center);
const cart = projection.unproject(center, rotateCVCart);
ellipsoid.cartographicToCartesian(cart, center);
const transform = Transforms.eastNorthUpToFixedFrame(
center,
ellipsoid,
rotateCVTransform,
);
const oldGlobe = controller._globe;
const oldEllipsoid = controller._ellipsoid;
controller._globe = undefined;
controller._ellipsoid = Ellipsoid.UNIT_SPHERE;
controller._rotateFactor = 1.0;
controller._rotateRateRangeAdjustment = 1.0;
const oldTransform = Matrix4.clone(camera.transform, rotateCVOldTransform);
camera._setTransform(transform);
rotate3D(controller, startPosition, movement, Cartesian3.UNIT_Z);
camera._setTransform(oldTransform);
controller._globe = oldGlobe;
controller._ellipsoid = oldEllipsoid;
const radius = oldEllipsoid.maximumRadius;
controller._rotateFactor = 1.0 / radius;
controller._rotateRateRangeAdjustment = radius;
}
function rotateCVOnTerrain(controller, startPosition, movement) {
const scene = controller._scene;
const camera = scene.camera;
const cameraUnderground = controller._cameraUnderground;
let center;
let ray;
const normal = Cartesian3.UNIT_X;
if (Cartesian2.equals(startPosition, controller._tiltCenterMousePosition)) {
center = Cartesian3.clone(controller._tiltCenter, rotateCVCenter);
} else {
if (camera.position.z < controller._minimumPickingTerrainHeight) {
center = pickPosition(controller, startPosition, rotateCVCenter);
}
if (!defined(center)) {
ray = camera.getPickRay(startPosition, rotateCVWindowRay);
const position = ray.origin;
const direction = ray.direction;
let scalar;
const normalDotDirection = Cartesian3.dot(normal, direction);
if (Math.abs(normalDotDirection) > CesiumMath.EPSILON6) {
scalar = -Cartesian3.dot(normal, position) / normalDotDirection;
}
if (!defined(scalar) || scalar <= 0.0) {
controller._looking = true;
look3D(controller, startPosition, mov