feat: 实现供水运营专题大屏BI可视化

- 新增OperationDashboard.vue全屏大屏组件
- 添加6个核心KPI指标卡片: 进水总量/出水总量/产销差率/营收额/平均水质/报警次数
- 实现6个ECharts图表: 供水趋势/水质分布/报警统计/管网空间/设备状态/营收分析
- 创建静态HTML版本operation-dashboard.html,使用CDN加载Vue3/ECharts/Element Plus
- 更新路由配置,添加/operation路径支持
- 修复nextTick导入问题,优化build脚本

🚧 开发者: bot_dev1
📝 任务: #38 [BI] 运营仪表盘 + 供水专题大屏
This commit is contained in:
2026-06-15 09:06:11 +08:00
parent 37bcc78eee
commit 85df71fc28
17426 changed files with 4091508 additions and 47 deletions
@@ -0,0 +1,419 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} BillboardGraphics.ConstructorOptions
*
* Initialization options for the BillboardGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the billboard.
* @property {Property | string | HTMLImageElement | HTMLCanvasElement} [image] A Property specifying the Image, URI, or Canvas to use for the billboard.
* @property {Property | number} [scale=1.0] A numeric Property specifying the scale to apply to the image size.
* @property {Property | Cartesian2} [pixelOffset=Cartesian2.ZERO] A {@link Cartesian2} Property specifying the pixel offset.
* @property {Property | Cartesian3} [eyeOffset=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the eye offset.
* @property {Property | HorizontalOrigin} [horizontalOrigin=HorizontalOrigin.CENTER] A Property specifying the {@link HorizontalOrigin}.
* @property {Property | VerticalOrigin} [verticalOrigin=VerticalOrigin.CENTER] A Property specifying the {@link VerticalOrigin}.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
* @property {Property | Color} [color=Color.WHITE] A Property specifying the tint {@link Color} of the image.
* @property {Property | number} [rotation=0] A numeric Property specifying the rotation about the alignedAxis.
* @property {Property | Cartesian3} [alignedAxis=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the unit vector axis of rotation.
* @property {Property | boolean} [sizeInMeters] A boolean Property specifying whether this billboard's size should be measured in meters.
* @property {Property | number} [width] A numeric Property specifying the width of the billboard in pixels, overriding the native size.
* @property {Property | number} [height] A numeric Property specifying the height of the billboard in pixels, overriding the native size.
* @property {Property | NearFarScalar} [scaleByDistance] A {@link NearFarScalar} Property used to scale the point based on distance from the camera.
* @property {Property | NearFarScalar} [translucencyByDistance] A {@link NearFarScalar} Property used to set translucency based on distance from the camera.
* @property {Property | NearFarScalar} [pixelOffsetScaleByDistance] A {@link NearFarScalar} Property used to set pixelOffset based on distance from the camera.
* @property {Property | BoundingRectangle} [imageSubRegion] A Property specifying a {@link BoundingRectangle} that defines a sub-region of the image to use for the billboard, rather than the entire image, measured in pixels from the bottom-left.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this billboard will be displayed.
* @property {Property | number} [disableDepthTestDistance] A Property specifying the distance from the camera at which to disable the depth test to.
* @property {Property | SplitDirection} [splitDirection] A Property specifying the {@link SplitDirection} of the billboard.
*/
/**
* Describes a two dimensional icon located at the position of the containing {@link Entity}.
* <p>
* <div align='center'>
* <img src='Images/Billboard.png' width='400' height='300' /><br />
* Example billboards
* </div>
* </p>
*
* @alias BillboardGraphics
* @constructor
*
* @param {BillboardGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @demo {@link https://sandcastle.cesium.com/index.html?id=billboards|Cesium Sandcastle Billboard Demo}
*/
function BillboardGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._image = undefined;
this._imageSubscription = undefined;
this._scale = undefined;
this._scaleSubscription = undefined;
this._pixelOffset = undefined;
this._pixelOffsetSubscription = undefined;
this._eyeOffset = undefined;
this._eyeOffsetSubscription = undefined;
this._horizontalOrigin = undefined;
this._horizontalOriginSubscription = undefined;
this._verticalOrigin = undefined;
this._verticalOriginSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._color = undefined;
this._colorSubscription = undefined;
this._rotation = undefined;
this._rotationSubscription = undefined;
this._alignedAxis = undefined;
this._alignedAxisSubscription = undefined;
this._sizeInMeters = undefined;
this._sizeInMetersSubscription = undefined;
this._width = undefined;
this._widthSubscription = undefined;
this._height = undefined;
this._heightSubscription = undefined;
this._scaleByDistance = undefined;
this._scaleByDistanceSubscription = undefined;
this._translucencyByDistance = undefined;
this._translucencyByDistanceSubscription = undefined;
this._pixelOffsetScaleByDistance = undefined;
this._pixelOffsetScaleByDistanceSubscription = undefined;
this._imageSubRegion = undefined;
this._imageSubRegionSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._disableDepthTestDistance = undefined;
this._disableDepthTestDistanceSubscription = undefined;
this._splitDirection = undefined;
this._splitDirectionSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(BillboardGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof BillboardGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the billboard.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the Property specifying the Image, URI, or Canvas to use for the billboard.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
image: createPropertyDescriptor("image"),
/**
* Gets or sets the numeric Property specifying the uniform scale to apply to the image.
* A scale greater than <code>1.0</code> enlarges the billboard while a scale less than <code>1.0</code> shrinks it.
* <p>
* <div align='center'>
* <img src='Images/Billboard.setScale.png' width='400' height='300' /><br/>
* From left to right in the above image, the scales are <code>0.5</code>, <code>1.0</code>, and <code>2.0</code>.
* </div>
* </p>
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
scale: createPropertyDescriptor("scale"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the billboard's pixel offset in screen space
* from the origin of this billboard. This is commonly used to align multiple billboards and labels at
* the same position, e.g., an image and text. The screen space origin is the top, left corner of the
* canvas; <code>x</code> increases from left to right, and <code>y</code> increases from top to bottom.
* <p>
* <div align='center'>
* <table border='0' cellpadding='5'><tr>
* <td align='center'><code>default</code><br/><img src='Images/Billboard.setPixelOffset.default.png' width='250' height='188' /></td>
* <td align='center'><code>b.pixeloffset = new Cartesian2(50, 25);</code><br/><img src='Images/Billboard.setPixelOffset.x50y-25.png' width='250' height='188' /></td>
* </tr></table>
* The billboard's origin is indicated by the yellow point.
* </div>
* </p>
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default Cartesian2.ZERO
*/
pixelOffset: createPropertyDescriptor("pixelOffset"),
/**
* Gets or sets the {@link Cartesian3} Property specifying the billboard's offset in eye coordinates.
* Eye coordinates is a left-handed coordinate system, where <code>x</code> points towards the viewer's
* right, <code>y</code> points up, and <code>z</code> points into the screen.
* <p>
* An eye offset is commonly used to arrange multiple billboards or objects at the same position, e.g., to
* arrange a billboard above its corresponding 3D model.
* </p>
* Below, the billboard is positioned at the center of the Earth but an eye offset makes it always
* appear on top of the Earth regardless of the viewer's or Earth's orientation.
* <p>
* <div align='center'>
* <table border='0' cellpadding='5'><tr>
* <td align='center'><img src='Images/Billboard.setEyeOffset.one.png' width='250' height='188' /></td>
* <td align='center'><img src='Images/Billboard.setEyeOffset.two.png' width='250' height='188' /></td>
* </tr></table>
* <code>b.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);</code>
* </div>
* </p>
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default Cartesian3.ZERO
*/
eyeOffset: createPropertyDescriptor("eyeOffset"),
/**
* Gets or sets the Property specifying the {@link HorizontalOrigin}.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default HorizontalOrigin.CENTER
*/
horizontalOrigin: createPropertyDescriptor("horizontalOrigin"),
/**
* Gets or sets the Property specifying the {@link VerticalOrigin}.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default VerticalOrigin.CENTER
*/
verticalOrigin: createPropertyDescriptor("verticalOrigin"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the Property specifying the {@link Color} that is multiplied with the <code>image</code>.
* This has two common use cases. First, the same white texture may be used by many different billboards,
* each with a different color, to create colored billboards. Second, the color's alpha component can be
* used to make the billboard translucent as shown below. An alpha of <code>0.0</code> makes the billboard
* transparent, and <code>1.0</code> makes the billboard opaque.
* <p>
* <div align='center'>
* <table border='0' cellpadding='5'><tr>
* <td align='center'><code>default</code><br/><img src='Images/Billboard.setColor.Alpha255.png' width='250' height='188' /></td>
* <td align='center'><code>alpha : 0.5</code><br/><img src='Images/Billboard.setColor.Alpha127.png' width='250' height='188' /></td>
* </tr></table>
* </div>
* </p>
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor("color"),
/**
* Gets or sets the numeric Property specifying the rotation of the image
* counter clockwise from the <code>alignedAxis</code>.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default 0
*/
rotation: createPropertyDescriptor("rotation"),
/**
* Gets or sets the {@link Cartesian3} Property specifying the unit vector axis of rotation
* in the fixed frame. When set to Cartesian3.ZERO the rotation is from the top of the screen.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default Cartesian3.ZERO
*/
alignedAxis: createPropertyDescriptor("alignedAxis"),
/**
* Gets or sets the boolean Property specifying if this billboard's size will be measured in meters.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default false
*/
sizeInMeters: createPropertyDescriptor("sizeInMeters"),
/**
* Gets or sets the numeric Property specifying the width of the billboard in pixels.
* When undefined, the native width is used.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
width: createPropertyDescriptor("width"),
/**
* Gets or sets the numeric Property specifying the height of the billboard in pixels.
* When undefined, the native height is used.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
height: createPropertyDescriptor("height"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the scale of the billboard based on the distance from the camera.
* A billboard's scale will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the billboard's scale remains clamped to the nearest bound.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
scaleByDistance: createPropertyDescriptor("scaleByDistance"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the translucency of the billboard based on the distance from the camera.
* A billboard's translucency will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the billboard's translucency remains clamped to the nearest bound.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
translucencyByDistance: createPropertyDescriptor("translucencyByDistance"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the pixel offset of the billboard based on the distance from the camera.
* A billboard's pixel offset will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the billboard's pixel offset remains clamped to the nearest bound.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
pixelOffsetScaleByDistance: createPropertyDescriptor(
"pixelOffsetScaleByDistance",
),
/**
* Gets or sets the Property specifying a {@link BoundingRectangle} that defines a
* sub-region of the <code>image</code> to use for the billboard, rather than the entire image,
* measured in pixels from the bottom-left.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
imageSubRegion: createPropertyDescriptor("imageSubRegion"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this billboard will be displayed.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
* When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
*/
disableDepthTestDistance: createPropertyDescriptor(
"disableDepthTestDistance",
),
/**
* Gets or sets the Property specifying the {@link SplitDirection} of this billboard.
* @memberof BillboardGraphics.prototype
* @type {Property|undefined}
* @default SplitDirection.NONE
*/
splitDirection: createPropertyDescriptor("splitDirection"),
});
/**
* Duplicates this instance.
*
* @param {BillboardGraphics} [result] The object onto which to store the result.
* @returns {BillboardGraphics} The modified result parameter or a new instance if one was not provided.
*/
BillboardGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new BillboardGraphics(this);
}
result.show = this._show;
result.image = this._image;
result.scale = this._scale;
result.pixelOffset = this._pixelOffset;
result.eyeOffset = this._eyeOffset;
result.horizontalOrigin = this._horizontalOrigin;
result.verticalOrigin = this._verticalOrigin;
result.heightReference = this._heightReference;
result.color = this._color;
result.rotation = this._rotation;
result.alignedAxis = this._alignedAxis;
result.sizeInMeters = this._sizeInMeters;
result.width = this._width;
result.height = this._height;
result.scaleByDistance = this._scaleByDistance;
result.translucencyByDistance = this._translucencyByDistance;
result.pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance;
result.imageSubRegion = this._imageSubRegion;
result.distanceDisplayCondition = this._distanceDisplayCondition;
result.disableDepthTestDistance = this._disableDepthTestDistance;
result.splitDirection = this._splitDirection;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {BillboardGraphics} source The object to be merged into this object.
*/
BillboardGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this._show ?? source.show;
this.image = this._image ?? source.image;
this.scale = this._scale ?? source.scale;
this.pixelOffset = this._pixelOffset ?? source.pixelOffset;
this.eyeOffset = this._eyeOffset ?? source.eyeOffset;
this.horizontalOrigin = this._horizontalOrigin ?? source.horizontalOrigin;
this.verticalOrigin = this._verticalOrigin ?? source.verticalOrigin;
this.heightReference = this._heightReference ?? source.heightReference;
this.color = this._color ?? source.color;
this.rotation = this._rotation ?? source.rotation;
this.alignedAxis = this._alignedAxis ?? source.alignedAxis;
this.sizeInMeters = this._sizeInMeters ?? source.sizeInMeters;
this.width = this._width ?? source.width;
this.height = this._height ?? source.height;
this.scaleByDistance = this._scaleByDistance ?? source.scaleByDistance;
this.translucencyByDistance =
this._translucencyByDistance ?? source.translucencyByDistance;
this.pixelOffsetScaleByDistance =
this._pixelOffsetScaleByDistance ?? source.pixelOffsetScaleByDistance;
this.imageSubRegion = this._imageSubRegion ?? source.imageSubRegion;
this.distanceDisplayCondition =
this._distanceDisplayCondition ?? source.distanceDisplayCondition;
this.disableDepthTestDistance =
this._disableDepthTestDistance ?? source.disableDepthTestDistance;
this.splitDirection = this.splitDirection ?? source.splitDirection;
};
export default BillboardGraphics;
@@ -0,0 +1,351 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import BoundingRectangle from "../Core/BoundingRectangle.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import NearFarScalar from "../Core/NearFarScalar.js";
import HeightReference from "../Scene/HeightReference.js";
import HorizontalOrigin from "../Scene/HorizontalOrigin.js";
import VerticalOrigin from "../Scene/VerticalOrigin.js";
import BoundingSphereState from "./BoundingSphereState.js";
import Property from "./Property.js";
import SplitDirection from "../Scene/SplitDirection.js";
const defaultColor = Color.WHITE;
const defaultEyeOffset = Cartesian3.ZERO;
const defaultHeightReference = HeightReference.NONE;
const defaultPixelOffset = Cartesian2.ZERO;
const defaultScale = 1.0;
const defaultRotation = 0.0;
const defaultAlignedAxis = Cartesian3.ZERO;
const defaultHorizontalOrigin = HorizontalOrigin.CENTER;
const defaultVerticalOrigin = VerticalOrigin.CENTER;
const defaultSizeInMeters = false;
const defaultSplitDirection = SplitDirection.NONE;
const positionScratch = new Cartesian3();
const colorScratch = new Color();
const eyeOffsetScratch = new Cartesian3();
const pixelOffsetScratch = new Cartesian2();
const scaleByDistanceScratch = new NearFarScalar();
const translucencyByDistanceScratch = new NearFarScalar();
const pixelOffsetScaleByDistanceScratch = new NearFarScalar();
const boundingRectangleScratch = new BoundingRectangle();
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
function EntityData(entity) {
this.entity = entity;
this.billboard = undefined;
this.textureValue = undefined;
}
/**
* A {@link Visualizer} which maps {@link Entity#billboard} to a {@link Billboard}.
* @alias BillboardVisualizer
* @constructor
*
* @param {EntityCluster} entityCluster The entity cluster to manage the collection of billboards and optionally cluster with other entities.
* @param {EntityCollection} entityCollection The entityCollection to visualize.
*/
function BillboardVisualizer(entityCluster, entityCollection) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entityCluster)) {
throw new DeveloperError("entityCluster is required.");
}
if (!defined(entityCollection)) {
throw new DeveloperError("entityCollection is required.");
}
//>>includeEnd('debug');
entityCollection.collectionChanged.addEventListener(
BillboardVisualizer.prototype._onCollectionChanged,
this,
);
this._cluster = entityCluster;
this._entityCollection = entityCollection;
this._items = new AssociativeArray();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
/**
* Updates the primitives created by this visualizer to match their
* Entity counterpart at the given time.
*
* @param {JulianDate} time The time to update to.
* @returns {boolean} This function always returns true.
*/
BillboardVisualizer.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
//>>includeEnd('debug');
const items = this._items.values;
const cluster = this._cluster;
for (let i = 0, len = items.length; i < len; i++) {
const item = items[i];
const entity = item.entity;
const billboardGraphics = entity._billboard;
let textureValue;
let billboard = item.billboard;
let show =
entity.isShowing &&
entity.isAvailable(time) &&
Property.getValueOrDefault(billboardGraphics._show, time, true);
let position;
if (show) {
position = Property.getValueOrUndefined(
entity._position,
time,
positionScratch,
);
textureValue = Property.getValueOrUndefined(
billboardGraphics._image,
time,
);
show = defined(position) && defined(textureValue);
}
if (!show) {
//don't bother creating or updating anything else
returnPrimitive(item, entity, cluster);
continue;
}
if (!Property.isConstant(entity._position)) {
cluster._clusterDirty = true;
}
if (!defined(billboard)) {
billboard = cluster.getBillboard(entity);
billboard.id = entity;
item.billboard = billboard;
item.textureValue = undefined;
}
billboard.show = show;
billboard.position = position;
billboard.color = Property.getValueOrDefault(
billboardGraphics._color,
time,
defaultColor,
colorScratch,
);
billboard.eyeOffset = Property.getValueOrDefault(
billboardGraphics._eyeOffset,
time,
defaultEyeOffset,
eyeOffsetScratch,
);
billboard.heightReference = Property.getValueOrDefault(
billboardGraphics._heightReference,
time,
defaultHeightReference,
);
billboard.pixelOffset = Property.getValueOrDefault(
billboardGraphics._pixelOffset,
time,
defaultPixelOffset,
pixelOffsetScratch,
);
billboard.scale = Property.getValueOrDefault(
billboardGraphics._scale,
time,
defaultScale,
);
billboard.rotation = Property.getValueOrDefault(
billboardGraphics._rotation,
time,
defaultRotation,
);
billboard.alignedAxis = Property.getValueOrDefault(
billboardGraphics._alignedAxis,
time,
defaultAlignedAxis,
);
billboard.horizontalOrigin = Property.getValueOrDefault(
billboardGraphics._horizontalOrigin,
time,
defaultHorizontalOrigin,
);
billboard.verticalOrigin = Property.getValueOrDefault(
billboardGraphics._verticalOrigin,
time,
defaultVerticalOrigin,
);
billboard.width = Property.getValueOrUndefined(
billboardGraphics._width,
time,
);
billboard.height = Property.getValueOrUndefined(
billboardGraphics._height,
time,
);
billboard.scaleByDistance = Property.getValueOrUndefined(
billboardGraphics._scaleByDistance,
time,
scaleByDistanceScratch,
);
billboard.translucencyByDistance = Property.getValueOrUndefined(
billboardGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch,
);
billboard.pixelOffsetScaleByDistance = Property.getValueOrUndefined(
billboardGraphics._pixelOffsetScaleByDistance,
time,
pixelOffsetScaleByDistanceScratch,
);
billboard.sizeInMeters = Property.getValueOrDefault(
billboardGraphics._sizeInMeters,
time,
defaultSizeInMeters,
);
billboard.distanceDisplayCondition = Property.getValueOrUndefined(
billboardGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch,
);
billboard.disableDepthTestDistance = Property.getValueOrUndefined(
billboardGraphics._disableDepthTestDistance,
time,
);
billboard.splitDirection = Property.getValueOrDefault(
billboardGraphics._splitDirection,
time,
defaultSplitDirection,
);
// Apply .image last, so any necessary property values are available
// in Billboard#_computeImageTextureSize before adding to the atlas.
if (item.textureValue !== textureValue) {
billboard.image = textureValue;
item.textureValue = textureValue;
}
const subRegion = Property.getValueOrUndefined(
billboardGraphics._imageSubRegion,
time,
boundingRectangleScratch,
);
if (defined(subRegion)) {
billboard.setImageSubRegion(billboard.image, subRegion);
}
}
return true;
};
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
BillboardVisualizer.prototype.getBoundingSphere = function (entity, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entity)) {
throw new DeveloperError("entity is required.");
}
if (!defined(result)) {
throw new DeveloperError("result is required.");
}
//>>includeEnd('debug');
const item = this._items.get(entity.id);
if (!defined(item) || !defined(item.billboard)) {
return BoundingSphereState.FAILED;
}
const billboard = item.billboard;
if (billboard.heightReference === HeightReference.NONE) {
result.center = Cartesian3.clone(billboard.position, result.center);
} else {
if (!defined(billboard._clampedPosition)) {
return BoundingSphereState.PENDING;
}
result.center = Cartesian3.clone(billboard._clampedPosition, result.center);
}
result.radius = 0;
return BoundingSphereState.DONE;
};
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
BillboardVisualizer.prototype.isDestroyed = function () {
return false;
};
/**
* Removes and destroys all primitives created by this instance.
*/
BillboardVisualizer.prototype.destroy = function () {
this._entityCollection.collectionChanged.removeEventListener(
BillboardVisualizer.prototype._onCollectionChanged,
this,
);
const entities = this._entityCollection.values;
for (let i = 0; i < entities.length; i++) {
this._cluster.removeBillboard(entities[i]);
}
return destroyObject(this);
};
BillboardVisualizer.prototype._onCollectionChanged = function (
entityCollection,
added,
removed,
changed,
) {
let i;
let entity;
const items = this._items;
const cluster = this._cluster;
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
if (defined(entity._billboard) && defined(entity._position)) {
items.set(entity.id, new EntityData(entity));
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined(entity._billboard) && defined(entity._position)) {
if (!items.contains(entity.id)) {
items.set(entity.id, new EntityData(entity));
}
} else {
returnPrimitive(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
returnPrimitive(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
};
function returnPrimitive(item, entity, cluster) {
if (defined(item)) {
item.billboard = undefined;
cluster.removeBillboard(entity);
}
}
export default BillboardVisualizer;
@@ -0,0 +1,26 @@
/**
* The state of a BoundingSphere computation being performed by a {@link Visualizer}.
* @enum {number}
* @private
*/
const BoundingSphereState = Object.freeze({
/**
* The BoundingSphere has been computed.
* @type BoundingSphereState
* @constant
*/
DONE: 0,
/**
* The BoundingSphere is still being computed.
* @type BoundingSphereState
* @constant
*/
PENDING: 1,
/**
* The BoundingSphere does not exist.
* @type BoundingSphereState
* @constant
*/
FAILED: 2,
});
export default BoundingSphereState;
@@ -0,0 +1,326 @@
import BoxGeometry from "../Core/BoxGeometry.js";
import BoxOutlineGeometry from "../Core/BoxOutlineGeometry.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import GeometryOffsetAttribute from "../Core/GeometryOffsetAttribute.js";
import Iso8601 from "../Core/Iso8601.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import HeightReference from "../Scene/HeightReference.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import heightReferenceOnEntityPropertyChanged from "./heightReferenceOnEntityPropertyChanged.js";
import Property from "./Property.js";
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
const positionScratch = new Cartesian3();
const scratchColor = new Color();
function BoxGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.dimensions = undefined;
this.offsetAttribute = undefined;
}
/**
* A {@link GeometryUpdater} for boxes.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias BoxGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function BoxGeometryUpdater(entity, scene) {
GeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new BoxGeometryOptions(entity),
geometryPropertyName: "box",
observedPropertyNames: ["availability", "position", "orientation", "box"],
});
this._onEntityPropertyChanged(entity, "box", entity.box, undefined);
}
if (defined(Object.create)) {
BoxGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
BoxGeometryUpdater.prototype.constructor = BoxGeometryUpdater;
}
Object.defineProperties(BoxGeometryUpdater.prototype, {
/**
* Gets the terrain offset property
* @type {TerrainOffsetProperty}
* @memberof BoxGeometryUpdater.prototype
* @readonly
* @private
*/
terrainOffsetProperty: {
get: function () {
return this._terrainOffsetProperty;
},
},
});
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
BoxGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const show = new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const distanceDisplayConditionAttribute =
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
);
const attributes = {
show: show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color: undefined,
offset: undefined,
};
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
}
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: BoxGeometry.fromDimensions(this._options),
modelMatrix: entity.computeModelMatrixForHeightReference(
time,
entity.box.heightReference,
this._options.dimensions.z * 0.5,
this._scene.ellipsoid,
),
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
BoxGeometryUpdater.prototype.createOutlineGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
),
offset: undefined,
};
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: BoxOutlineGeometry.fromDimensions(this._options),
modelMatrix: entity.computeModelMatrixForHeightReference(
time,
entity.box.heightReference,
this._options.dimensions.z * 0.5,
this._scene.ellipsoid,
),
attributes: attributes,
});
};
BoxGeometryUpdater.prototype._computeCenter = function (time, result) {
return Property.getValueOrUndefined(this._entity.position, time, result);
};
BoxGeometryUpdater.prototype._isHidden = function (entity, box) {
return (
!defined(box.dimensions) ||
!defined(entity.position) ||
GeometryUpdater.prototype._isHidden.call(this, entity, box)
);
};
BoxGeometryUpdater.prototype._isDynamic = function (entity, box) {
return (
!entity.position.isConstant ||
!Property.isConstant(entity.orientation) ||
!box.dimensions.isConstant ||
!Property.isConstant(box.outlineWidth)
);
};
BoxGeometryUpdater.prototype._setStaticOptions = function (entity, box) {
const heightReference = Property.getValueOrDefault(
box.heightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
const options = this._options;
options.vertexFormat =
this._materialProperty instanceof ColorMaterialProperty
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
options.dimensions = box.dimensions.getValue(
Iso8601.MINIMUM_VALUE,
options.dimensions,
);
options.offsetAttribute =
heightReference !== HeightReference.NONE
? GeometryOffsetAttribute.ALL
: undefined;
};
BoxGeometryUpdater.prototype._onEntityPropertyChanged =
heightReferenceOnEntityPropertyChanged;
BoxGeometryUpdater.DynamicGeometryUpdater = DynamicBoxGeometryUpdater;
/**
* @private
*/
function DynamicBoxGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
}
if (defined(Object.create)) {
DynamicBoxGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DynamicBoxGeometryUpdater.prototype.constructor = DynamicBoxGeometryUpdater;
}
DynamicBoxGeometryUpdater.prototype._isHidden = function (entity, box, time) {
const position = Property.getValueOrUndefined(
entity.position,
time,
positionScratch,
);
const dimensions = this._options.dimensions;
return (
!defined(position) ||
!defined(dimensions) ||
DynamicGeometryUpdater.prototype._isHidden.call(this, entity, box, time)
);
};
DynamicBoxGeometryUpdater.prototype._setOptions = function (entity, box, time) {
const heightReference = Property.getValueOrDefault(
box.heightReference,
time,
HeightReference.NONE,
);
const options = this._options;
options.dimensions = Property.getValueOrUndefined(
box.dimensions,
time,
options.dimensions,
);
options.offsetAttribute =
heightReference !== HeightReference.NONE
? GeometryOffsetAttribute.ALL
: undefined;
};
export default BoxGeometryUpdater;
+208
View File
@@ -0,0 +1,208 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} BoxGraphics.ConstructorOptions
*
* Initialization options for the BoxGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the box.
* @property {Property | Cartesian3} [dimensions] A {@link Cartesian3} Property specifying the length, width, and height of the box.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height from the entity position is relative to.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the box is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the box.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the box is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the box casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this box will be displayed.
*
*/
/**
* Describes a box. The center position and orientation are determined by the containing {@link Entity}.
*
* @alias BoxGraphics
* @constructor
*
* @param {BoxGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @demo {@link https://sandcastle.cesium.com/index.html?id=box|Cesium Sandcastle Box Demo}
*/
function BoxGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._dimensions = undefined;
this._dimensionsSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(BoxGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof BoxGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the box.
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets {@link Cartesian3} Property property specifying the length, width, and height of the box.
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
*/
dimensions: createPropertyDescriptor("dimensions"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the boolean Property specifying whether the box is filled with the provided material.
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the material used to fill the box.
* @memberof BoxGraphics.prototype
* @type {MaterialProperty|undefined}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying whether the box is outlined.
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Get or sets the enum Property specifying whether the box
* casts or receives shadows from light sources.
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this box will be displayed.
* @memberof BoxGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
});
/**
* Duplicates this instance.
*
* @param {BoxGraphics} [result] The object onto which to store the result.
* @returns {BoxGraphics} The modified result parameter or a new instance if one was not provided.
*/
BoxGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new BoxGraphics(this);
}
result.show = this.show;
result.dimensions = this.dimensions;
result.heightReference = this.heightReference;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {BoxGraphics} source The object to be merged into this object.
*/
BoxGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.dimensions = this.dimensions ?? source.dimensions;
this.heightReference = this.heightReference ?? source.heightReference;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
};
export default BoxGraphics;
@@ -0,0 +1,172 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import ReferenceFrame from "../Core/ReferenceFrame.js";
import PositionProperty from "./PositionProperty.js";
/**
* A {@link PositionProperty} whose value is lazily evaluated by a callback function.
*
* @alias CallbackPositionProperty
* @constructor
*
* @param {CallbackPositionProperty.Callback} callback The function to be called when the position property is evaluated.
* @param {boolean} isConstant <code>true</code> when the callback function returns the same value every time, <code>false</code> if the value will change.
* @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
*
* @demo {@link https://sandcastle.cesium.com/index.html?id=callback-position-property|Cesium Sandcastle Callback Position Property Demo}
*/
function CallbackPositionProperty(callback, isConstant, referenceFrame) {
this._callback = undefined;
this._isConstant = undefined;
this._referenceFrame = referenceFrame ?? ReferenceFrame.FIXED;
this._definitionChanged = new Event();
this.setCallback(callback, isConstant);
}
Object.defineProperties(CallbackPositionProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* @memberof CallbackPositionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._isConstant;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof CallbackPositionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the reference frame in which the position is defined.
* @memberof CallbackPositionProperty.prototype
* @type {ReferenceFrame}
* @default ReferenceFrame.FIXED;
*/
referenceFrame: {
get: function () {
return this._referenceFrame;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time in the fixed frame.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
CallbackPositionProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return this.getValueInReferenceFrame(time, ReferenceFrame.FIXED, result);
};
/**
* Sets the callback to be used.
*
* @param {CallbackPositionProperty.Callback} callback The function to be called when the property is evaluated.
* @param {boolean} isConstant <code>true</code> when the callback function returns the same value every time, <code>false</code> if the value will change.
*/
CallbackPositionProperty.prototype.setCallback = function (
callback,
isConstant,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(callback)) {
throw new DeveloperError("callback is required.");
}
if (!defined(isConstant)) {
throw new DeveloperError("isConstant is required.");
}
//>>includeEnd('debug');
const changed =
this._callback !== callback || this._isConstant !== isConstant;
this._callback = callback;
this._isConstant = isConstant;
if (changed) {
this._definitionChanged.raiseEvent(this);
}
};
/**
* Gets the value of the property at the provided time and in the provided reference frame.
*
* @param {JulianDate} time The time for which to retrieve the value.
* @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
CallbackPositionProperty.prototype.getValueInReferenceFrame = function (
time,
referenceFrame,
result,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
if (!defined(referenceFrame)) {
throw new DeveloperError("referenceFrame is required.");
}
//>>includeEnd('debug');
const value = this._callback(time, result);
return PositionProperty.convertToReferenceFrame(
time,
value,
this._referenceFrame,
referenceFrame,
result,
);
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
CallbackPositionProperty.prototype.equals = function (other) {
return (
this === other ||
(other instanceof CallbackPositionProperty &&
this._callback === other._callback &&
this._isConstant === other._isConstant &&
this._referenceFrame === other._referenceFrame)
);
};
/**
* A function that returns the value of the position property.
* @callback CallbackPositionProperty.Callback
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {Cartesian3} [result] The object to store the value into. If omitted, the function must create and return a new instance.
* @returns {Cartesian3 | undefined} The modified result parameter, or a new instance if the result parameter was not supplied or is unsupported.
*/
export default CallbackPositionProperty;
@@ -0,0 +1,117 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
/**
* A {@link Property} whose value is lazily evaluated by a callback function.
*
* @alias CallbackProperty
* @constructor
*
* @param {CallbackProperty.Callback} callback The function to be called when the property is evaluated.
* @param {boolean} isConstant <code>true</code> when the callback function returns the same value every time, <code>false</code> if the value will change.
*/
function CallbackProperty(callback, isConstant) {
this._callback = undefined;
this._isConstant = undefined;
this._definitionChanged = new Event();
this.setCallback(callback, isConstant);
}
Object.defineProperties(CallbackProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* @memberof CallbackProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._isConstant;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setCallback is called.
* @memberof CallbackProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied or is unsupported.
*/
CallbackProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return this._callback(time, result);
};
/**
* Sets the callback to be used.
*
* @param {CallbackProperty.Callback} callback The function to be called when the property is evaluated.
* @param {boolean} isConstant <code>true</code> when the callback function returns the same value every time, <code>false</code> if the value will change.
*/
CallbackProperty.prototype.setCallback = function (callback, isConstant) {
//>>includeStart('debug', pragmas.debug);
if (!defined(callback)) {
throw new DeveloperError("callback is required.");
}
if (!defined(isConstant)) {
throw new DeveloperError("isConstant is required.");
}
//>>includeEnd('debug');
const changed =
this._callback !== callback || this._isConstant !== isConstant;
this._callback = callback;
this._isConstant = isConstant;
if (changed) {
this._definitionChanged.raiseEvent(this);
}
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
CallbackProperty.prototype.equals = function (other) {
return (
this === other ||
(other instanceof CallbackProperty &&
this._callback === other._callback &&
this._isConstant === other._isConstant)
);
};
/**
* A function that returns the value of the property.
* @callback CallbackProperty.Callback
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into. If omitted, the function must create and return a new instance.
* @returns {object} The modified result parameter, or a new instance if the result parameter was not supplied or is unsupported.
*/
export default CallbackProperty;
@@ -0,0 +1,111 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} Cesium3DTilesetGraphics.ConstructorOptions
*
* Initialization options for the Cesium3DTilesetGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the tileset.
* @property {Property | string | Resource} [uri] A string or Resource Property specifying the URI of the tileset.
* @property {Property | number} [maximumScreenSpaceError] A number or Property specifying the maximum screen space error used to drive level of detail refinement.
*/
/**
* A 3D Tiles tileset represented by an {@link Entity}.
* The tileset modelMatrix is determined by the containing Entity position and orientation
* or is left unset if position is undefined.
*
* @alias Cesium3DTilesetGraphics
* @constructor
*
* @param {Cesium3DTilesetGraphics.ConstructorOptions} [options] Object describing initialization options
*/
function Cesium3DTilesetGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._uri = undefined;
this._uriSubscription = undefined;
this._maximumScreenSpaceError = undefined;
this._maximumScreenSpaceErrorSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(Cesium3DTilesetGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof Cesium3DTilesetGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the model.
* @memberof Cesium3DTilesetGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the string Property specifying the URI of the glTF asset.
* @memberof Cesium3DTilesetGraphics.prototype
* @type {Property|undefined}
*/
uri: createPropertyDescriptor("uri"),
/**
* Gets or sets the maximum screen space error used to drive level of detail refinement.
* @memberof Cesium3DTilesetGraphics.prototype
* @type {Property|undefined}
*/
maximumScreenSpaceError: createPropertyDescriptor("maximumScreenSpaceError"),
});
/**
* Duplicates this instance.
*
* @param {Cesium3DTilesetGraphics} [result] The object onto which to store the result.
* @returns {Cesium3DTilesetGraphics} The modified result parameter or a new instance if one was not provided.
*/
Cesium3DTilesetGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new Cesium3DTilesetGraphics(this);
}
result.show = this.show;
result.uri = this.uri;
result.maximumScreenSpaceError = this.maximumScreenSpaceError;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {Cesium3DTilesetGraphics} source The object to be merged into this object.
*/
Cesium3DTilesetGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.uri = this.uri ?? source.uri;
this.maximumScreenSpaceError =
this.maximumScreenSpaceError ?? source.maximumScreenSpaceError;
};
export default Cesium3DTilesetGraphics;
@@ -0,0 +1,261 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import BoundingSphere from "../Core/BoundingSphere.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import Matrix4 from "../Core/Matrix4.js";
import Resource from "../Core/Resource.js";
import Cesium3DTileset from "../Scene/Cesium3DTileset.js";
import BoundingSphereState from "./BoundingSphereState.js";
import Property from "./Property.js";
const modelMatrixScratch = new Matrix4();
/**
* A {@link Visualizer} which maps {@link Entity#tileset} to a {@link Cesium3DTileset}.
* @alias Cesium3DTilesetVisualizer
* @constructor
*
* @param {Scene} scene The scene the primitives will be rendered in.
* @param {EntityCollection} entityCollection The entityCollection to visualize.
*/
function Cesium3DTilesetVisualizer(scene, entityCollection) {
//>>includeStart('debug', pragmas.debug);
if (!defined(scene)) {
throw new DeveloperError("scene is required.");
}
if (!defined(entityCollection)) {
throw new DeveloperError("entityCollection is required.");
}
//>>includeEnd('debug');
entityCollection.collectionChanged.addEventListener(
Cesium3DTilesetVisualizer.prototype._onCollectionChanged,
this,
);
this._scene = scene;
this._primitives = scene.primitives;
this._entityCollection = entityCollection;
this._tilesetHash = {};
this._entitiesToVisualize = new AssociativeArray();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
/**
* Updates models created this visualizer to match their
* Entity counterpart at the given time.
*
* @param {JulianDate} time The time to update to.
* @returns {boolean} This function always returns true.
*/
Cesium3DTilesetVisualizer.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
//>>includeEnd('debug');
const entities = this._entitiesToVisualize.values;
const tilesetHash = this._tilesetHash;
const primitives = this._primitives;
for (let i = 0, len = entities.length; i < len; i++) {
const entity = entities[i];
const tilesetGraphics = entity._tileset;
let resource;
const tilesetData = tilesetHash[entity.id];
const show =
entity.isShowing &&
entity.isAvailable(time) &&
Property.getValueOrDefault(tilesetGraphics._show, time, true);
let modelMatrix;
if (show) {
modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch);
resource = Resource.createIfNeeded(
Property.getValueOrUndefined(tilesetGraphics._uri, time),
);
}
const tileset = defined(tilesetData)
? tilesetData.tilesetPrimitive
: undefined;
if (!show) {
if (defined(tileset)) {
tileset.show = false;
}
continue;
}
if (!defined(tilesetData) || resource.url !== tilesetData.url) {
if (defined(tileset)) {
primitives.removeAndDestroy(tileset);
}
delete tilesetHash[entity.id];
createTileset(resource, tilesetHash, entity, primitives);
}
if (!defined(tileset)) {
continue;
}
tileset.show = true;
if (defined(modelMatrix)) {
tileset.modelMatrix = modelMatrix;
}
tileset.maximumScreenSpaceError = Property.getValueOrDefault(
tilesetGraphics.maximumScreenSpaceError,
time,
tileset.maximumScreenSpaceError,
);
}
return true;
};
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
Cesium3DTilesetVisualizer.prototype.isDestroyed = function () {
return false;
};
/**
* Removes and destroys all primitives created by this instance.
*/
Cesium3DTilesetVisualizer.prototype.destroy = function () {
this._entityCollection.collectionChanged.removeEventListener(
Cesium3DTilesetVisualizer.prototype._onCollectionChanged,
this,
);
const entities = this._entitiesToVisualize.values;
const tilesetHash = this._tilesetHash;
const primitives = this._primitives;
for (let i = entities.length - 1; i > -1; i--) {
removeTileset(this, entities[i], tilesetHash, primitives);
}
return destroyObject(this);
};
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
Cesium3DTilesetVisualizer.prototype.getBoundingSphere = function (
entity,
result,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entity)) {
throw new DeveloperError("entity is required.");
}
if (!defined(result)) {
throw new DeveloperError("result is required.");
}
//>>includeEnd('debug');
const tilesetData = this._tilesetHash[entity.id];
if (!defined(tilesetData) || tilesetData.loadFail) {
return BoundingSphereState.FAILED;
}
const primitive = tilesetData.tilesetPrimitive;
if (!defined(primitive)) {
return BoundingSphereState.PENDING;
}
if (!primitive.show) {
return BoundingSphereState.FAILED;
}
BoundingSphere.clone(primitive.boundingSphere, result);
return BoundingSphereState.DONE;
};
/**
* @private
*/
Cesium3DTilesetVisualizer.prototype._onCollectionChanged = function (
entityCollection,
added,
removed,
changed,
) {
let i;
let entity;
const entities = this._entitiesToVisualize;
const tilesetHash = this._tilesetHash;
const primitives = this._primitives;
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
if (defined(entity._tileset)) {
entities.set(entity.id, entity);
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined(entity._tileset)) {
entities.set(entity.id, entity);
} else {
removeTileset(this, entity, tilesetHash, primitives);
entities.remove(entity.id);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
removeTileset(this, entity, tilesetHash, primitives);
entities.remove(entity.id);
}
};
function removeTileset(visualizer, entity, tilesetHash, primitives) {
const tilesetData = tilesetHash[entity.id];
if (defined(tilesetData)) {
if (defined(tilesetData.tilesetPrimitive)) {
primitives.removeAndDestroy(tilesetData.tilesetPrimitive);
}
delete tilesetHash[entity.id];
}
}
async function createTileset(resource, tilesetHash, entity, primitives) {
tilesetHash[entity.id] = {
url: resource.url,
loadFail: false,
};
try {
const tileset = await Cesium3DTileset.fromUrl(resource);
tileset.id = entity;
primitives.add(tileset);
if (!defined(tilesetHash[entity.id])) {
return;
}
tilesetHash[entity.id].tilesetPrimitive = tileset;
} catch (error) {
console.error(error);
tilesetHash[entity.id].loadFail = true;
}
}
export default Cesium3DTilesetVisualizer;
@@ -0,0 +1,157 @@
import Cartesian2 from "../Core/Cartesian2.js";
import Color from "../Core/Color.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
const defaultEvenColor = Color.WHITE;
const defaultOddColor = Color.BLACK;
const defaultRepeat = new Cartesian2(2.0, 2.0);
/**
* A {@link MaterialProperty} that maps to checkerboard {@link Material} uniforms.
* @alias CheckerboardMaterialProperty
* @constructor
*
* @param {object} [options] Object with the following properties:
* @param {Property|Color} [options.evenColor=Color.WHITE] A Property specifying the first {@link Color}.
* @param {Property|Color} [options.oddColor=Color.BLACK] A Property specifying the second {@link Color}.
* @param {Property|Cartesian2} [options.repeat=new Cartesian2(2.0, 2.0)] A {@link Cartesian2} Property specifying how many times the tiles repeat in each direction.
*/
function CheckerboardMaterialProperty(options) {
options = options ?? Frozen.EMPTY_OBJECT;
this._definitionChanged = new Event();
this._evenColor = undefined;
this._evenColorSubscription = undefined;
this._oddColor = undefined;
this._oddColorSubscription = undefined;
this._repeat = undefined;
this._repeatSubscription = undefined;
this.evenColor = options.evenColor;
this.oddColor = options.oddColor;
this.repeat = options.repeat;
}
Object.defineProperties(CheckerboardMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof CheckerboardMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
Property.isConstant(this._evenColor) && //
Property.isConstant(this._oddColor) && //
Property.isConstant(this._repeat)
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof CheckerboardMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the Property specifying the first {@link Color}.
* @memberof CheckerboardMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
evenColor: createPropertyDescriptor("evenColor"),
/**
* Gets or sets the Property specifying the second {@link Color}.
* @memberof CheckerboardMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
oddColor: createPropertyDescriptor("oddColor"),
/**
* Gets or sets the {@link Cartesian2} Property specifying how many times the tiles repeat in each direction.
* @memberof CheckerboardMaterialProperty.prototype
* @type {Property|undefined}
* @default new Cartesian2(2.0, 2.0)
*/
repeat: createPropertyDescriptor("repeat"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
CheckerboardMaterialProperty.prototype.getType = function (time) {
return "Checkerboard";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
CheckerboardMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.lightColor = Property.getValueOrClonedDefault(
this._evenColor,
time,
defaultEvenColor,
result.lightColor,
);
result.darkColor = Property.getValueOrClonedDefault(
this._oddColor,
time,
defaultOddColor,
result.darkColor,
);
result.repeat = Property.getValueOrDefault(this._repeat, time, defaultRepeat);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
CheckerboardMaterialProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof CheckerboardMaterialProperty && //
Property.equals(this._evenColor, other._evenColor) && //
Property.equals(this._oddColor, other._oddColor) && //
Property.equals(this._repeat, other._repeat))
);
};
export default CheckerboardMaterialProperty;
@@ -0,0 +1,112 @@
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
/**
* A {@link MaterialProperty} that maps to solid color {@link Material} uniforms.
*
* @param {Property|Color} [color=Color.WHITE] The {@link Color} Property to be used.
*
* @alias ColorMaterialProperty
* @constructor
*/
function ColorMaterialProperty(color) {
this._definitionChanged = new Event();
this._color = undefined;
this._colorSubscription = undefined;
this.color = color;
}
Object.defineProperties(ColorMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof ColorMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return Property.isConstant(this._color);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof ColorMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the {@link Color} {@link Property}.
* @memberof ColorMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor("color"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
ColorMaterialProperty.prototype.getType = function (time) {
return "Color";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
ColorMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.color = Property.getValueOrClonedDefault(
this._color,
time,
Color.WHITE,
result.color,
);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
ColorMaterialProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof ColorMaterialProperty && //
Property.equals(this._color, other._color))
);
};
export default ColorMaterialProperty;
@@ -0,0 +1,591 @@
import createGuid from "../Core/createGuid.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import CesiumMath from "../Core/Math.js";
import Entity from "./Entity.js";
import EntityCollection from "./EntityCollection.js";
const entityOptionsScratch = {
id: undefined,
};
const entityIdScratch = new Array(2);
function clean(entity) {
const propertyNames = entity.propertyNames;
const propertyNamesLength = propertyNames.length;
for (let i = 0; i < propertyNamesLength; i++) {
entity[propertyNames[i]] = undefined;
}
entity._name = undefined;
entity._availability = undefined;
}
function subscribeToEntity(that, eventHash, collectionId, entity) {
entityIdScratch[0] = collectionId;
entityIdScratch[1] = entity.id;
eventHash[JSON.stringify(entityIdScratch)] =
entity.definitionChanged.addEventListener(
CompositeEntityCollection.prototype._onDefinitionChanged,
that,
);
}
function unsubscribeFromEntity(that, eventHash, collectionId, entity) {
entityIdScratch[0] = collectionId;
entityIdScratch[1] = entity.id;
const id = JSON.stringify(entityIdScratch);
eventHash[id]();
eventHash[id] = undefined;
}
function recomposite(that) {
that._shouldRecomposite = true;
if (that._suspendCount !== 0) {
return;
}
const collections = that._collections;
const collectionsLength = collections.length;
const collectionsCopy = that._collectionsCopy;
const collectionsCopyLength = collectionsCopy.length;
let i;
let entity;
let entities;
let iEntities;
let collection;
const composite = that._composite;
const newEntities = new EntityCollection(that);
const eventHash = that._eventHash;
let collectionId;
for (i = 0; i < collectionsCopyLength; i++) {
collection = collectionsCopy[i];
collection.collectionChanged.removeEventListener(
CompositeEntityCollection.prototype._onCollectionChanged,
that,
);
entities = collection.values;
collectionId = collection.id;
for (iEntities = entities.length - 1; iEntities > -1; iEntities--) {
entity = entities[iEntities];
unsubscribeFromEntity(that, eventHash, collectionId, entity);
}
}
for (i = collectionsLength - 1; i >= 0; i--) {
collection = collections[i];
collection.collectionChanged.addEventListener(
CompositeEntityCollection.prototype._onCollectionChanged,
that,
);
//Merge all of the existing entities.
entities = collection.values;
collectionId = collection.id;
for (iEntities = entities.length - 1; iEntities > -1; iEntities--) {
entity = entities[iEntities];
subscribeToEntity(that, eventHash, collectionId, entity);
let compositeEntity = newEntities.getById(entity.id);
if (!defined(compositeEntity)) {
compositeEntity = composite.getById(entity.id);
if (!defined(compositeEntity)) {
entityOptionsScratch.id = entity.id;
compositeEntity = new Entity(entityOptionsScratch);
} else {
clean(compositeEntity);
}
newEntities.add(compositeEntity);
}
compositeEntity.merge(entity);
}
}
that._collectionsCopy = collections.slice(0);
composite.suspendEvents();
composite.removeAll();
const newEntitiesArray = newEntities.values;
for (i = 0; i < newEntitiesArray.length; i++) {
composite.add(newEntitiesArray[i]);
}
composite.resumeEvents();
}
/**
* Non-destructively composites multiple {@link EntityCollection} instances into a single collection.
* If a Entity with the same ID exists in multiple collections, it is non-destructively
* merged into a single new entity instance. If an entity has the same property in multiple
* collections, the property of the Entity in the last collection of the list it
* belongs to is used. CompositeEntityCollection can be used almost anywhere that a
* EntityCollection is used.
*
* @alias CompositeEntityCollection
* @constructor
*
* @param {EntityCollection[]} [collections] The initial list of EntityCollection instances to merge.
* @param {DataSource|CompositeEntityCollection} [owner] The data source (or composite entity collection) which created this collection.
*/
function CompositeEntityCollection(collections, owner) {
this._owner = owner;
this._composite = new EntityCollection(this);
this._suspendCount = 0;
this._collections = defined(collections) ? collections.slice() : [];
this._collectionsCopy = [];
this._id = createGuid();
this._eventHash = {};
recomposite(this);
this._shouldRecomposite = false;
}
Object.defineProperties(CompositeEntityCollection.prototype, {
/**
* Gets the event that is fired when entities are added or removed from the collection.
* The generated event is a {@link EntityCollection.collectionChangedEventCallback}.
* @memberof CompositeEntityCollection.prototype
* @readonly
* @type {Event}
*/
collectionChanged: {
get: function () {
return this._composite._collectionChanged;
},
},
/**
* Gets a globally unique identifier for this collection.
* @memberof CompositeEntityCollection.prototype
* @readonly
* @type {string}
*/
id: {
get: function () {
return this._id;
},
},
/**
* Gets the array of Entity instances in the collection.
* This array should not be modified directly.
* @memberof CompositeEntityCollection.prototype
* @readonly
* @type {Entity[]}
*/
values: {
get: function () {
return this._composite.values;
},
},
/**
* Gets the owner of this composite entity collection, ie. the data source or composite entity collection which created it.
* @memberof CompositeEntityCollection.prototype
* @readonly
* @type {DataSource|CompositeEntityCollection}
*/
owner: {
get: function () {
return this._owner;
},
},
});
/**
* Adds a collection to the composite.
*
* @param {EntityCollection} collection the collection to add.
* @param {number} [index] the index to add the collection at. If omitted, the collection will
* added on top of all existing collections.
*
* @exception {DeveloperError} index, if supplied, must be greater than or equal to zero and less than or equal to the number of collections.
*/
CompositeEntityCollection.prototype.addCollection = function (
collection,
index,
) {
const hasIndex = defined(index);
//>>includeStart('debug', pragmas.debug);
if (!defined(collection)) {
throw new DeveloperError("collection is required.");
}
if (hasIndex) {
if (index < 0) {
throw new DeveloperError("index must be greater than or equal to zero.");
} else if (index > this._collections.length) {
throw new DeveloperError(
"index must be less than or equal to the number of collections.",
);
}
}
//>>includeEnd('debug');
if (!hasIndex) {
index = this._collections.length;
this._collections.push(collection);
} else {
this._collections.splice(index, 0, collection);
}
recomposite(this);
};
/**
* Removes a collection from this composite, if present.
*
* @param {EntityCollection} collection The collection to remove.
* @returns {boolean} true if the collection was in the composite and was removed,
* false if the collection was not in the composite.
*/
CompositeEntityCollection.prototype.removeCollection = function (collection) {
const index = this._collections.indexOf(collection);
if (index !== -1) {
this._collections.splice(index, 1);
recomposite(this);
return true;
}
return false;
};
/**
* Removes all collections from this composite.
*/
CompositeEntityCollection.prototype.removeAllCollections = function () {
this._collections.length = 0;
recomposite(this);
};
/**
* Checks to see if the composite contains a given collection.
*
* @param {EntityCollection} collection the collection to check for.
* @returns {boolean} true if the composite contains the collection, false otherwise.
*/
CompositeEntityCollection.prototype.containsCollection = function (collection) {
return this._collections.indexOf(collection) !== -1;
};
/**
* Returns true if the provided entity is in this collection, false otherwise.
*
* @param {Entity} entity The entity.
* @returns {boolean} true if the provided entity is in this collection, false otherwise.
*/
CompositeEntityCollection.prototype.contains = function (entity) {
return this._composite.contains(entity);
};
/**
* Determines the index of a given collection in the composite.
*
* @param {EntityCollection} collection The collection to find the index of.
* @returns {number} The index of the collection in the composite, or -1 if the collection does not exist in the composite.
*/
CompositeEntityCollection.prototype.indexOfCollection = function (collection) {
return this._collections.indexOf(collection);
};
/**
* Gets a collection by index from the composite.
*
* @param {number} index the index to retrieve.
*/
CompositeEntityCollection.prototype.getCollection = function (index) {
//>>includeStart('debug', pragmas.debug);
if (!defined(index)) {
throw new DeveloperError("index is required.", "index");
}
//>>includeEnd('debug');
return this._collections[index];
};
/**
* Gets the number of collections in this composite.
*/
CompositeEntityCollection.prototype.getCollectionsLength = function () {
return this._collections.length;
};
function getCollectionIndex(collections, collection) {
//>>includeStart('debug', pragmas.debug);
if (!defined(collection)) {
throw new DeveloperError("collection is required.");
}
//>>includeEnd('debug');
const index = collections.indexOf(collection);
//>>includeStart('debug', pragmas.debug);
if (index === -1) {
throw new DeveloperError("collection is not in this composite.");
}
//>>includeEnd('debug');
return index;
}
function swapCollections(composite, i, j) {
const arr = composite._collections;
i = CesiumMath.clamp(i, 0, arr.length - 1);
j = CesiumMath.clamp(j, 0, arr.length - 1);
if (i === j) {
return;
}
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
recomposite(composite);
}
/**
* Raises a collection up one position in the composite.
*
* @param {EntityCollection} collection the collection to move.
*
* @exception {DeveloperError} collection is not in this composite.
*/
CompositeEntityCollection.prototype.raiseCollection = function (collection) {
const index = getCollectionIndex(this._collections, collection);
swapCollections(this, index, index + 1);
};
/**
* Lowers a collection down one position in the composite.
*
* @param {EntityCollection} collection the collection to move.
*
* @exception {DeveloperError} collection is not in this composite.
*/
CompositeEntityCollection.prototype.lowerCollection = function (collection) {
const index = getCollectionIndex(this._collections, collection);
swapCollections(this, index, index - 1);
};
/**
* Raises a collection to the top of the composite.
*
* @param {EntityCollection} collection the collection to move.
*
* @exception {DeveloperError} collection is not in this composite.
*/
CompositeEntityCollection.prototype.raiseCollectionToTop = function (
collection,
) {
const index = getCollectionIndex(this._collections, collection);
if (index === this._collections.length - 1) {
return;
}
this._collections.splice(index, 1);
this._collections.push(collection);
recomposite(this);
};
/**
* Lowers a collection to the bottom of the composite.
*
* @param {EntityCollection} collection the collection to move.
*
* @exception {DeveloperError} collection is not in this composite.
*/
CompositeEntityCollection.prototype.lowerCollectionToBottom = function (
collection,
) {
const index = getCollectionIndex(this._collections, collection);
if (index === 0) {
return;
}
this._collections.splice(index, 1);
this._collections.splice(0, 0, collection);
recomposite(this);
};
/**
* Prevents {@link EntityCollection#collectionChanged} events from being raised
* until a corresponding call is made to {@link EntityCollection#resumeEvents}, at which
* point a single event will be raised that covers all suspended operations.
* This allows for many items to be added and removed efficiently.
* While events are suspended, recompositing of the collections will
* also be suspended, as this can be a costly operation.
* This function can be safely called multiple times as long as there
* are corresponding calls to {@link EntityCollection#resumeEvents}.
*/
CompositeEntityCollection.prototype.suspendEvents = function () {
this._suspendCount++;
this._composite.suspendEvents();
};
/**
* Resumes raising {@link EntityCollection#collectionChanged} events immediately
* when an item is added or removed. Any modifications made while while events were suspended
* will be triggered as a single event when this function is called. This function also ensures
* the collection is recomposited if events are also resumed.
* This function is reference counted and can safely be called multiple times as long as there
* are corresponding calls to {@link EntityCollection#resumeEvents}.
*
* @exception {DeveloperError} resumeEvents can not be called before suspendEvents.
*/
CompositeEntityCollection.prototype.resumeEvents = function () {
//>>includeStart('debug', pragmas.debug);
if (this._suspendCount === 0) {
throw new DeveloperError(
"resumeEvents can not be called before suspendEvents.",
);
}
//>>includeEnd('debug');
this._suspendCount--;
// recomposite before triggering events (but only if required for performance) that might depend on a composited collection
if (this._shouldRecomposite && this._suspendCount === 0) {
recomposite(this);
this._shouldRecomposite = false;
}
this._composite.resumeEvents();
};
/**
* Computes the maximum availability of the entities in the collection.
* If the collection contains a mix of infinitely available data and non-infinite data,
* It will return the interval pertaining to the non-infinite data only. If all
* data is infinite, an infinite interval will be returned.
*
* @returns {TimeInterval} The availability of entities in the collection.
*/
CompositeEntityCollection.prototype.computeAvailability = function () {
return this._composite.computeAvailability();
};
/**
* Gets an entity with the specified id.
*
* @param {string} id The id of the entity to retrieve.
* @returns {Entity|undefined} The entity with the provided id or undefined if the id did not exist in the collection.
*/
CompositeEntityCollection.prototype.getById = function (id) {
return this._composite.getById(id);
};
CompositeEntityCollection.prototype._onCollectionChanged = function (
collection,
added,
removed,
) {
const collections = this._collectionsCopy;
const collectionsLength = collections.length;
const composite = this._composite;
composite.suspendEvents();
let i;
let q;
let entity;
let compositeEntity;
const removedLength = removed.length;
const eventHash = this._eventHash;
const collectionId = collection.id;
for (i = 0; i < removedLength; i++) {
const removedEntity = removed[i];
unsubscribeFromEntity(this, eventHash, collectionId, removedEntity);
const removedId = removedEntity.id;
//Check if the removed entity exists in any of the remaining collections
//If so, we clean and remerge it.
for (q = collectionsLength - 1; q >= 0; q--) {
entity = collections[q].getById(removedId);
if (defined(entity)) {
if (!defined(compositeEntity)) {
compositeEntity = composite.getById(removedId);
clean(compositeEntity);
}
compositeEntity.merge(entity);
}
}
//We never retrieved the compositeEntity, which means it no longer
//exists in any of the collections, remove it from the composite.
if (!defined(compositeEntity)) {
composite.removeById(removedId);
}
compositeEntity = undefined;
}
const addedLength = added.length;
for (i = 0; i < addedLength; i++) {
const addedEntity = added[i];
subscribeToEntity(this, eventHash, collectionId, addedEntity);
const addedId = addedEntity.id;
//We know the added entity exists in at least one collection,
//but we need to check all collections and re-merge in order
//to maintain the priority of properties.
for (q = collectionsLength - 1; q >= 0; q--) {
entity = collections[q].getById(addedId);
if (defined(entity)) {
if (!defined(compositeEntity)) {
compositeEntity = composite.getById(addedId);
if (!defined(compositeEntity)) {
entityOptionsScratch.id = addedId;
compositeEntity = new Entity(entityOptionsScratch);
composite.add(compositeEntity);
} else {
clean(compositeEntity);
}
}
compositeEntity.merge(entity);
}
}
compositeEntity = undefined;
}
composite.resumeEvents();
};
CompositeEntityCollection.prototype._onDefinitionChanged = function (
entity,
propertyName,
newValue,
oldValue,
) {
const collections = this._collections;
const composite = this._composite;
const collectionsLength = collections.length;
const id = entity.id;
const compositeEntity = composite.getById(id);
let compositeProperty = compositeEntity[propertyName];
const newProperty = !defined(compositeProperty);
let firstTime = true;
for (let q = collectionsLength - 1; q >= 0; q--) {
const innerEntity = collections[q].getById(entity.id);
if (defined(innerEntity)) {
const property = innerEntity[propertyName];
if (defined(property)) {
if (firstTime) {
firstTime = false;
//We only want to clone if the property is also mergeable.
//This ensures that leaf properties are referenced and not copied,
//which is the entire point of compositing.
if (defined(property.merge) && defined(property.clone)) {
compositeProperty = property.clone(compositeProperty);
} else {
compositeProperty = property;
break;
}
}
compositeProperty.merge(property);
}
}
}
if (
newProperty &&
compositeEntity.propertyNames.indexOf(propertyName) === -1
) {
compositeEntity.addProperty(propertyName);
}
compositeEntity[propertyName] = compositeProperty;
};
export default CompositeEntityCollection;
@@ -0,0 +1,128 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import CompositeProperty from "./CompositeProperty.js";
import Property from "./Property.js";
/**
* A {@link CompositeProperty} which is also a {@link MaterialProperty}.
*
* @alias CompositeMaterialProperty
* @constructor
*/
function CompositeMaterialProperty() {
this._definitionChanged = new Event();
this._composite = new CompositeProperty();
this._composite.definitionChanged.addEventListener(
CompositeMaterialProperty.prototype._raiseDefinitionChanged,
this,
);
}
Object.defineProperties(CompositeMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof CompositeMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._composite.isConstant;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value.
* @memberof CompositeMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the interval collection.
* @memberof CompositeMaterialProperty.prototype
*
* @type {TimeIntervalCollection}
*/
intervals: {
get: function () {
return this._composite._intervals;
},
},
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
CompositeMaterialProperty.prototype.getType = function (time) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required");
}
//>>includeEnd('debug');
const innerProperty =
this._composite._intervals.findDataForIntervalContainingDate(time);
if (defined(innerProperty)) {
return innerProperty.getType(time);
}
return undefined;
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
CompositeMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
const innerProperty =
this._composite._intervals.findDataForIntervalContainingDate(time);
if (defined(innerProperty)) {
return innerProperty.getValue(time, result);
}
return undefined;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
CompositeMaterialProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof CompositeMaterialProperty && //
this._composite.equals(other._composite, Property.equals))
);
};
/**
* @private
*/
CompositeMaterialProperty.prototype._raiseDefinitionChanged = function () {
this._definitionChanged.raiseEvent(this);
};
export default CompositeMaterialProperty;
@@ -0,0 +1,153 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import ReferenceFrame from "../Core/ReferenceFrame.js";
import CompositeProperty from "./CompositeProperty.js";
import Property from "./Property.js";
/**
* A {@link CompositeProperty} which is also a {@link PositionProperty}.
*
* @alias CompositePositionProperty
* @constructor
*
* @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
*/
function CompositePositionProperty(referenceFrame) {
this._referenceFrame = referenceFrame ?? ReferenceFrame.FIXED;
this._definitionChanged = new Event();
this._composite = new CompositeProperty();
this._composite.definitionChanged.addEventListener(
CompositePositionProperty.prototype._raiseDefinitionChanged,
this,
);
}
Object.defineProperties(CompositePositionProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof CompositePositionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._composite.isConstant;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value.
* @memberof CompositePositionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the interval collection.
* @memberof CompositePositionProperty.prototype
*
* @type {TimeIntervalCollection}
*/
intervals: {
get: function () {
return this._composite.intervals;
},
},
/**
* Gets or sets the reference frame which this position presents itself as.
* Each PositionProperty making up this object has it's own reference frame,
* so this property merely exposes a "preferred" reference frame for clients
* to use.
* @memberof CompositePositionProperty.prototype
*
* @type {ReferenceFrame}
*/
referenceFrame: {
get: function () {
return this._referenceFrame;
},
set: function (value) {
this._referenceFrame = value;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time in the fixed frame.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
CompositePositionProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return this.getValueInReferenceFrame(time, ReferenceFrame.FIXED, result);
};
/**
* Gets the value of the property at the provided time and in the provided reference frame.
*
* @param {JulianDate} time The time for which to retrieve the value.
* @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
CompositePositionProperty.prototype.getValueInReferenceFrame = function (
time,
referenceFrame,
result,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
if (!defined(referenceFrame)) {
throw new DeveloperError("referenceFrame is required.");
}
//>>includeEnd('debug');
const innerProperty =
this._composite._intervals.findDataForIntervalContainingDate(time);
if (defined(innerProperty)) {
return innerProperty.getValueInReferenceFrame(time, referenceFrame, result);
}
return undefined;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
CompositePositionProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof CompositePositionProperty && //
this._referenceFrame === other._referenceFrame && //
this._composite.equals(other._composite, Property.equals))
);
};
/**
* @private
*/
CompositePositionProperty.prototype._raiseDefinitionChanged = function () {
this._definitionChanged.raiseEvent(this);
};
export default CompositePositionProperty;
@@ -0,0 +1,154 @@
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import EventHelper from "../Core/EventHelper.js";
import JulianDate from "../Core/JulianDate.js";
import TimeIntervalCollection from "../Core/TimeIntervalCollection.js";
import Property from "./Property.js";
function subscribeAll(property, eventHelper, definitionChanged, intervals) {
function callback() {
definitionChanged.raiseEvent(property);
}
const items = [];
eventHelper.removeAll();
const length = intervals.length;
for (let i = 0; i < length; i++) {
const interval = intervals.get(i);
if (defined(interval.data) && items.indexOf(interval.data) === -1) {
eventHelper.add(interval.data.definitionChanged, callback);
}
}
}
/**
* A {@link Property} which is defined by a {@link TimeIntervalCollection}, where the
* data property of each {@link TimeInterval} is another Property instance which is
* evaluated at the provided time.
*
* @alias CompositeProperty
* @constructor
*
*
* @example
* const constantProperty = ...;
* const sampledProperty = ...;
*
* //Create a composite property from two previously defined properties
* //where the property is valid on August 1st, 2012 and uses a constant
* //property for the first half of the day and a sampled property for the
* //remaining half.
* const composite = new Cesium.CompositeProperty();
* composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
* iso8601 : '2012-08-01T00:00:00.00Z/2012-08-01T12:00:00.00Z',
* data : constantProperty
* }));
* composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
* iso8601 : '2012-08-01T12:00:00.00Z/2012-08-02T00:00:00.00Z',
* isStartIncluded : false,
* isStopIncluded : false,
* data : sampledProperty
* }));
*
* @see CompositeMaterialProperty
* @see CompositePositionProperty
*/
function CompositeProperty() {
this._eventHelper = new EventHelper();
this._definitionChanged = new Event();
this._intervals = new TimeIntervalCollection();
this._intervals.changedEvent.addEventListener(
CompositeProperty.prototype._intervalsChanged,
this,
);
}
Object.defineProperties(CompositeProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof CompositeProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._intervals.isEmpty;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value.
* @memberof CompositeProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the interval collection.
* @memberof CompositeProperty.prototype
*
* @type {TimeIntervalCollection}
*/
intervals: {
get: function () {
return this._intervals;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
CompositeProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
const innerProperty = this._intervals.findDataForIntervalContainingDate(time);
if (defined(innerProperty)) {
return innerProperty.getValue(time, result);
}
return undefined;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
CompositeProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof CompositeProperty && //
this._intervals.equals(other._intervals, Property.equals))
);
};
/**
* @private
*/
CompositeProperty.prototype._intervalsChanged = function () {
subscribeAll(
this,
this._eventHelper,
this._definitionChanged,
this._intervals,
);
this._definitionChanged.raiseEvent(this);
};
export default CompositeProperty;
@@ -0,0 +1,151 @@
import Cartesian3 from "../Core/Cartesian3.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import ReferenceFrame from "../Core/ReferenceFrame.js";
import PositionProperty from "./PositionProperty.js";
/**
* A {@link PositionProperty} whose value does not change in respect to the
* {@link ReferenceFrame} in which is it defined.
*
* @alias ConstantPositionProperty
* @constructor
*
* @param {Cartesian3} [value] The property value.
* @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
*/
function ConstantPositionProperty(value, referenceFrame) {
this._definitionChanged = new Event();
this._value = Cartesian3.clone(value);
this._referenceFrame = referenceFrame ?? ReferenceFrame.FIXED;
}
Object.defineProperties(ConstantPositionProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof ConstantPositionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
!defined(this._value) || this._referenceFrame === ReferenceFrame.FIXED
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof ConstantPositionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the reference frame in which the position is defined.
* @memberof ConstantPositionProperty.prototype
* @type {ReferenceFrame}
* @default ReferenceFrame.FIXED;
*/
referenceFrame: {
get: function () {
return this._referenceFrame;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time in the fixed frame.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
ConstantPositionProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return this.getValueInReferenceFrame(time, ReferenceFrame.FIXED, result);
};
/**
* Sets the value of the property.
*
* @param {Cartesian3} value The property value.
* @param {ReferenceFrame} [referenceFrame=this.referenceFrame] The reference frame in which the position is defined.
*/
ConstantPositionProperty.prototype.setValue = function (value, referenceFrame) {
let definitionChanged = false;
if (!Cartesian3.equals(this._value, value)) {
definitionChanged = true;
this._value = Cartesian3.clone(value);
}
if (defined(referenceFrame) && this._referenceFrame !== referenceFrame) {
definitionChanged = true;
this._referenceFrame = referenceFrame;
}
if (definitionChanged) {
this._definitionChanged.raiseEvent(this);
}
};
/**
* Gets the value of the property at the provided time and in the provided reference frame.
*
* @param {JulianDate} time The time for which to retrieve the value.
* @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3} The modified result parameter or a new instance if the result parameter was not supplied.
*/
ConstantPositionProperty.prototype.getValueInReferenceFrame = function (
time,
referenceFrame,
result,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
if (!defined(referenceFrame)) {
throw new DeveloperError("referenceFrame is required.");
}
//>>includeEnd('debug');
return PositionProperty.convertToReferenceFrame(
time,
this._value,
this._referenceFrame,
referenceFrame,
result,
);
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
ConstantPositionProperty.prototype.equals = function (other) {
return (
this === other ||
(other instanceof ConstantPositionProperty &&
Cartesian3.equals(this._value, other._value) &&
this._referenceFrame === other._referenceFrame)
);
};
export default ConstantPositionProperty;
@@ -0,0 +1,116 @@
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
/**
* A {@link Property} whose value does not change with respect to simulation time.
*
* @alias ConstantProperty
* @constructor
*
* @param {*} [value] The property value.
*
* @see ConstantPositionProperty
*/
function ConstantProperty(value) {
this._value = undefined;
this._hasClone = false;
this._hasEquals = false;
this._definitionChanged = new Event();
this.setValue(value);
}
Object.defineProperties(ConstantProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* This property always returns <code>true</code>.
* @memberof ConstantProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
value: true,
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value.
* @memberof ConstantProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
});
/**
* Gets the value of the property.
*
* @param {JulianDate} [time] The time for which to retrieve the value. This parameter is unused since the value does not change with respect to time.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
ConstantProperty.prototype.getValue = function (time, result) {
return this._hasClone ? this._value.clone(result) : this._value;
};
/**
* Sets the value of the property.
*
* @param {*} value The property value.
*/
ConstantProperty.prototype.setValue = function (value) {
const oldValue = this._value;
if (oldValue !== value) {
const isDefined = defined(value);
const hasClone = isDefined && typeof value.clone === "function";
const hasEquals = isDefined && typeof value.equals === "function";
const changed = !hasEquals || !value.equals(oldValue);
if (changed) {
this._hasClone = hasClone;
this._hasEquals = hasEquals;
this._value = !hasClone ? value : value.clone(this._value);
this._definitionChanged.raiseEvent(this);
}
}
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
ConstantProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof ConstantProperty && //
((!this._hasEquals && this._value === other._value) || //
(this._hasEquals && this._value.equals(other._value))))
);
};
/**
* Gets this property's value.
*
* @returns {*} This property's value.
*/
ConstantProperty.prototype.valueOf = function () {
return this._value;
};
/**
* Creates a string representing this property's value.
*
* @returns {string} A string representing the property's value.
*/
ConstantProperty.prototype.toString = function () {
return String(this._value);
};
export default ConstantProperty;
@@ -0,0 +1,409 @@
import ApproximateTerrainHeights from "../Core/ApproximateTerrainHeights.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import CorridorGeometry from "../Core/CorridorGeometry.js";
import CorridorOutlineGeometry from "../Core/CorridorOutlineGeometry.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import Iso8601 from "../Core/Iso8601.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import Rectangle from "../Core/Rectangle.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import HeightReference from "../Scene/HeightReference.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import GroundGeometryUpdater from "./GroundGeometryUpdater.js";
import Property from "./Property.js";
const scratchColor = new Color();
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
const scratchRectangle = new Rectangle();
function CorridorGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.positions = undefined;
this.width = undefined;
this.cornerType = undefined;
this.height = undefined;
this.extrudedHeight = undefined;
this.granularity = undefined;
this.offsetAttribute = undefined;
}
/**
* A {@link GeometryUpdater} for corridors.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias CorridorGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function CorridorGeometryUpdater(entity, scene) {
GroundGeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new CorridorGeometryOptions(entity),
geometryPropertyName: "corridor",
observedPropertyNames: ["availability", "corridor"],
});
this._onEntityPropertyChanged(entity, "corridor", entity.corridor, undefined);
}
if (defined(Object.create)) {
CorridorGeometryUpdater.prototype = Object.create(
GroundGeometryUpdater.prototype,
);
CorridorGeometryUpdater.prototype.constructor = CorridorGeometryUpdater;
}
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
CorridorGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time),
),
offset: undefined,
color: undefined,
};
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
}
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new CorridorGeometry(this._options),
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
CorridorGeometryUpdater.prototype.createOutlineGeometryInstance = function (
time,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time),
),
offset: undefined,
};
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new CorridorOutlineGeometry(this._options),
attributes: attributes,
});
};
CorridorGeometryUpdater.prototype._computeCenter = function (time, result) {
const positions = Property.getValueOrUndefined(
this._entity.corridor.positions,
time,
);
if (!defined(positions) || positions.length === 0) {
return;
}
return Cartesian3.clone(
positions[Math.floor(positions.length / 2.0)],
result,
);
};
CorridorGeometryUpdater.prototype._isHidden = function (entity, corridor) {
return (
!defined(corridor.positions) ||
!defined(corridor.width) ||
GeometryUpdater.prototype._isHidden.call(this, entity, corridor)
);
};
CorridorGeometryUpdater.prototype._isDynamic = function (entity, corridor) {
return (
!corridor.positions.isConstant || //
!Property.isConstant(corridor.height) || //
!Property.isConstant(corridor.extrudedHeight) || //
!Property.isConstant(corridor.granularity) || //
!Property.isConstant(corridor.width) || //
!Property.isConstant(corridor.outlineWidth) || //
!Property.isConstant(corridor.cornerType) || //
!Property.isConstant(corridor.zIndex) || //
(this._onTerrain &&
!Property.isConstant(this._materialProperty) &&
!(this._materialProperty instanceof ColorMaterialProperty))
);
};
CorridorGeometryUpdater.prototype._setStaticOptions = function (
entity,
corridor,
) {
let heightValue = Property.getValueOrUndefined(
corridor.height,
Iso8601.MINIMUM_VALUE,
);
const heightReferenceValue = Property.getValueOrDefault(
corridor.heightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
let extrudedHeightValue = Property.getValueOrUndefined(
corridor.extrudedHeight,
Iso8601.MINIMUM_VALUE,
);
const extrudedHeightReferenceValue = Property.getValueOrDefault(
corridor.extrudedHeightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
if (defined(extrudedHeightValue) && !defined(heightValue)) {
heightValue = 0;
}
const options = this._options;
options.vertexFormat =
this._materialProperty instanceof ColorMaterialProperty
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
options.positions = corridor.positions.getValue(
Iso8601.MINIMUM_VALUE,
options.positions,
);
options.width = corridor.width.getValue(Iso8601.MINIMUM_VALUE);
options.granularity = Property.getValueOrUndefined(
corridor.granularity,
Iso8601.MINIMUM_VALUE,
);
options.cornerType = Property.getValueOrUndefined(
corridor.cornerType,
Iso8601.MINIMUM_VALUE,
);
options.offsetAttribute =
GroundGeometryUpdater.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue,
);
options.height = GroundGeometryUpdater.getGeometryHeight(
heightValue,
heightReferenceValue,
);
extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue,
);
if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
CorridorGeometry.computeRectangle(options, scratchRectangle),
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
CorridorGeometryUpdater.DynamicGeometryUpdater = DynamicCorridorGeometryUpdater;
/**
* @private
*/
function DynamicCorridorGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
}
if (defined(Object.create)) {
DynamicCorridorGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DynamicCorridorGeometryUpdater.prototype.constructor =
DynamicCorridorGeometryUpdater;
}
DynamicCorridorGeometryUpdater.prototype._isHidden = function (
entity,
corridor,
time,
) {
const options = this._options;
return (
!defined(options.positions) ||
!defined(options.width) ||
DynamicGeometryUpdater.prototype._isHidden.call(
this,
entity,
corridor,
time,
)
);
};
DynamicCorridorGeometryUpdater.prototype._setOptions = function (
entity,
corridor,
time,
) {
const options = this._options;
let heightValue = Property.getValueOrUndefined(corridor.height, time);
const heightReferenceValue = Property.getValueOrDefault(
corridor.heightReference,
time,
HeightReference.NONE,
);
let extrudedHeightValue = Property.getValueOrUndefined(
corridor.extrudedHeight,
time,
);
const extrudedHeightReferenceValue = Property.getValueOrDefault(
corridor.extrudedHeightReference,
time,
HeightReference.NONE,
);
if (defined(extrudedHeightValue) && !defined(heightValue)) {
heightValue = 0;
}
options.positions = Property.getValueOrUndefined(corridor.positions, time);
options.width = Property.getValueOrUndefined(corridor.width, time);
options.granularity = Property.getValueOrUndefined(
corridor.granularity,
time,
);
options.cornerType = Property.getValueOrUndefined(corridor.cornerType, time);
options.offsetAttribute =
GroundGeometryUpdater.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue,
);
options.height = GroundGeometryUpdater.getGeometryHeight(
heightValue,
heightReferenceValue,
);
extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue,
);
if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
CorridorGeometry.computeRectangle(options, scratchRectangle),
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
export default CorridorGeometryUpdater;
@@ -0,0 +1,316 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} CorridorGraphics.ConstructorOptions
*
* Initialization options for the CorridorGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the corridor.
* @property {Property | Cartesian3[]} [positions] A Property specifying the array of {@link Cartesian3} positions that define the centerline of the corridor.
* @property {Property | number} [width] A numeric Property specifying the distance between the edges of the corridor.
* @property {Property | number} [height=0] A numeric Property specifying the altitude of the corridor relative to the ellipsoid surface.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
* @property {Property | number} [extrudedHeight] A numeric Property specifying the altitude of the corridor's extruded face relative to the ellipsoid surface.
* @property {Property | HeightReference} [extrudedHeightReference=HeightReference.NONE] A Property specifying what the extrudedHeight is relative to.
* @property {Property | CornerType} [cornerType=CornerType.ROUNDED] A {@link CornerType} Property specifying the style of the corners.
* @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the distance between each latitude and longitude.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the corridor is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the corridor.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the corridor is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the corridor casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this corridor will be displayed.
* @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this corridor will classify terrain, 3D Tiles, or both when on the ground.
* @property {ConstantProperty | number} [zIndex] A Property specifying the zIndex of the corridor, used for ordering. Only has an effect if height and extrudedHeight are undefined, and if the corridor is static.
*/
/**
* Describes a corridor, which is a shape defined by a centerline and width that
* conforms to the curvature of the globe. It can be placed on the surface or at altitude
* and can optionally be extruded into a volume.
*
* @alias CorridorGraphics
* @constructor
*
* @param {CorridorGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @see Entity
* @demo {@link https://sandcastle.cesium.com/index.html?id=corridor|Cesium Sandcastle Corridor Demo}
*/
function CorridorGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._positions = undefined;
this._positionsSubscription = undefined;
this._width = undefined;
this._widthSubscription = undefined;
this._height = undefined;
this._heightSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._extrudedHeight = undefined;
this._extrudedHeightSubscription = undefined;
this._extrudedHeightReference = undefined;
this._extrudedHeightReferenceSubscription = undefined;
this._cornerType = undefined;
this._cornerTypeSubscription = undefined;
this._granularity = undefined;
this._granularitySubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._classificationType = undefined;
this._classificationTypeSubscription = undefined;
this._zIndex = undefined;
this._zIndexSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(CorridorGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof CorridorGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the corridor.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets a Property specifying the array of {@link Cartesian3} positions that define the centerline of the corridor.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
*/
positions: createPropertyDescriptor("positions"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
*/
width: createPropertyDescriptor("width"),
/**
* Gets or sets the numeric Property specifying the altitude of the corridor.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
height: createPropertyDescriptor("height"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the numeric Property specifying the altitude of the corridor extrusion.
* Setting this property creates a corridor shaped volume starting at height and ending
* at this altitude.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
*/
extrudedHeight: createPropertyDescriptor("extrudedHeight"),
/**
* Gets or sets the Property specifying the extruded {@link HeightReference}.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
extrudedHeightReference: createPropertyDescriptor("extrudedHeightReference"),
/**
* Gets or sets the {@link CornerType} Property specifying how corners are styled.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default CornerType.ROUNDED
*/
cornerType: createPropertyDescriptor("cornerType"),
/**
* Gets or sets the numeric Property specifying the sampling distance between each latitude and longitude point.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default {CesiumMath.RADIANS_PER_DEGREE}
*/
granularity: createPropertyDescriptor("granularity"),
/**
* Gets or sets the boolean Property specifying whether the corridor is filled with the provided material.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the Property specifying the material used to fill the corridor.
* @memberof CorridorGraphics.prototype
* @type {MaterialProperty|undefined}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying whether the corridor is outlined.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Get or sets the enum Property specifying whether the corridor
* casts or receives shadows from light sources.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this corridor will be displayed.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the {@link ClassificationType} Property specifying whether this corridor will classify terrain, 3D Tiles, or both when on the ground.
* @memberof CorridorGraphics.prototype
* @type {Property|undefined}
* @default ClassificationType.BOTH
*/
classificationType: createPropertyDescriptor("classificationType"),
/**
* Gets or sets the zIndex Property specifying the ordering of the corridor. Only has an effect if the coridor is static and neither height or exturdedHeight are specified.
* @memberof CorridorGraphics.prototype
* @type {ConstantProperty|undefined}
* @default 0
*/
zIndex: createPropertyDescriptor("zIndex"),
});
/**
* Duplicates this instance.
*
* @param {CorridorGraphics} [result] The object onto which to store the result.
* @returns {CorridorGraphics} The modified result parameter or a new instance if one was not provided.
*/
CorridorGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new CorridorGraphics(this);
}
result.show = this.show;
result.positions = this.positions;
result.width = this.width;
result.height = this.height;
result.heightReference = this.heightReference;
result.extrudedHeight = this.extrudedHeight;
result.extrudedHeightReference = this.extrudedHeightReference;
result.cornerType = this.cornerType;
result.granularity = this.granularity;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.classificationType = this.classificationType;
result.zIndex = this.zIndex;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {CorridorGraphics} source The object to be merged into this object.
*/
CorridorGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.positions = this.positions ?? source.positions;
this.width = this.width ?? source.width;
this.height = this.height ?? source.height;
this.heightReference = this.heightReference ?? source.heightReference;
this.extrudedHeight = this.extrudedHeight ?? source.extrudedHeight;
this.extrudedHeightReference =
this.extrudedHeightReference ?? source.extrudedHeightReference;
this.cornerType = this.cornerType ?? source.cornerType;
this.granularity = this.granularity ?? source.granularity;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.classificationType =
this.classificationType ?? source.classificationType;
this.zIndex = this.zIndex ?? source.zIndex;
};
export default CorridorGraphics;
@@ -0,0 +1,173 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import DataSource from "./DataSource.js";
import EntityCluster from "./EntityCluster.js";
import EntityCollection from "./EntityCollection.js";
/**
* A {@link DataSource} implementation which can be used to manually manage a group of entities.
*
* @alias CustomDataSource
* @constructor
*
* @param {string} [name] A human-readable name for this instance.
*
* @example
* const dataSource = new Cesium.CustomDataSource('myData');
*
* const entity = dataSource.entities.add({
* position : Cesium.Cartesian3.fromDegrees(1, 2, 0),
* billboard : {
* image : 'image.png'
* }
* });
*
* viewer.dataSources.add(dataSource);
*/
function CustomDataSource(name) {
this._name = name;
this._clock = undefined;
this._changed = new Event();
this._error = new Event();
this._isLoading = false;
this._loading = new Event();
this._entityCollection = new EntityCollection(this);
this._entityCluster = new EntityCluster();
}
Object.defineProperties(CustomDataSource.prototype, {
/**
* Gets or sets a human-readable name for this instance.
* @memberof CustomDataSource.prototype
* @type {string}
*/
name: {
get: function () {
return this._name;
},
set: function (value) {
if (this._name !== value) {
this._name = value;
this._changed.raiseEvent(this);
}
},
},
/**
* Gets or sets the clock for this instance.
* @memberof CustomDataSource.prototype
* @type {DataSourceClock}
*/
clock: {
get: function () {
return this._clock;
},
set: function (value) {
if (this._clock !== value) {
this._clock = value;
this._changed.raiseEvent(this);
}
},
},
/**
* Gets the collection of {@link Entity} instances.
* @memberof CustomDataSource.prototype
* @type {EntityCollection}
*/
entities: {
get: function () {
return this._entityCollection;
},
},
/**
* Gets or sets whether the data source is currently loading data.
* @memberof CustomDataSource.prototype
* @type {boolean}
*/
isLoading: {
get: function () {
return this._isLoading;
},
set: function (value) {
DataSource.setLoading(this, value);
},
},
/**
* Gets an event that will be raised when the underlying data changes.
* @memberof CustomDataSource.prototype
* @type {Event}
*/
changedEvent: {
get: function () {
return this._changed;
},
},
/**
* Gets an event that will be raised if an error is encountered during processing.
* @memberof CustomDataSource.prototype
* @type {Event}
*/
errorEvent: {
get: function () {
return this._error;
},
},
/**
* Gets an event that will be raised when the data source either starts or stops loading.
* @memberof CustomDataSource.prototype
* @type {Event}
*/
loadingEvent: {
get: function () {
return this._loading;
},
},
/**
* Gets whether or not this data source should be displayed.
* @memberof CustomDataSource.prototype
* @type {boolean}
*/
show: {
get: function () {
return this._entityCollection.show;
},
set: function (value) {
this._entityCollection.show = value;
},
},
/**
* Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
*
* @memberof CustomDataSource.prototype
* @type {EntityCluster}
*/
clustering: {
get: function () {
return this._entityCluster;
},
set: function (value) {
//>>includeStart('debug', pragmas.debug);
if (!defined(value)) {
throw new DeveloperError("value must be defined.");
}
//>>includeEnd('debug');
this._entityCluster = value;
},
},
});
/**
* Updates the data source to the provided time. This function is optional and
* is not required to be implemented. It is provided for data sources which
* retrieve data based on the current animation time or scene state.
* If implemented, update will be called by {@link DataSourceDisplay} once a frame.
*
* @param {JulianDate} time The simulation time.
* @returns {boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
*/
CustomDataSource.prototype.update = function (time) {
return true;
};
export default CustomDataSource;
@@ -0,0 +1,375 @@
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import CylinderGeometry from "../Core/CylinderGeometry.js";
import CylinderOutlineGeometry from "../Core/CylinderOutlineGeometry.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import GeometryOffsetAttribute from "../Core/GeometryOffsetAttribute.js";
import Iso8601 from "../Core/Iso8601.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import HeightReference from "../Scene/HeightReference.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import heightReferenceOnEntityPropertyChanged from "./heightReferenceOnEntityPropertyChanged.js";
import Property from "./Property.js";
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
const positionScratch = new Cartesian3();
const scratchColor = new Color();
function CylinderGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.length = undefined;
this.topRadius = undefined;
this.bottomRadius = undefined;
this.slices = undefined;
this.numberOfVerticalLines = undefined;
this.offsetAttribute = undefined;
}
/**
* A {@link GeometryUpdater} for cylinders.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias CylinderGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function CylinderGeometryUpdater(entity, scene) {
GeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new CylinderGeometryOptions(entity),
geometryPropertyName: "cylinder",
observedPropertyNames: [
"availability",
"position",
"orientation",
"cylinder",
],
});
this._onEntityPropertyChanged(entity, "cylinder", entity.cylinder, undefined);
}
if (defined(Object.create)) {
CylinderGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
CylinderGeometryUpdater.prototype.constructor = CylinderGeometryUpdater;
}
Object.defineProperties(CylinderGeometryUpdater.prototype, {
/**
* Gets the terrain offset property
* @type {TerrainOffsetProperty}
* @memberof CylinderGeometryUpdater.prototype
* @readonly
* @private
*/
terrainOffsetProperty: {
get: function () {
return this._terrainOffsetProperty;
},
},
});
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
CylinderGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const show = new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const distanceDisplayConditionAttribute =
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
);
const attributes = {
show: show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color: undefined,
offset: undefined,
};
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
}
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new CylinderGeometry(this._options),
modelMatrix: entity.computeModelMatrixForHeightReference(
time,
entity.cylinder.heightReference,
this._options.length * 0.5,
this._scene.ellipsoid,
),
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
CylinderGeometryUpdater.prototype.createOutlineGeometryInstance = function (
time,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
),
offset: undefined,
};
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new CylinderOutlineGeometry(this._options),
modelMatrix: entity.computeModelMatrixForHeightReference(
time,
entity.cylinder.heightReference,
this._options.length * 0.5,
this._scene.ellipsoid,
),
attributes: attributes,
});
};
CylinderGeometryUpdater.prototype._computeCenter = function (time, result) {
return Property.getValueOrUndefined(this._entity.position, time, result);
};
CylinderGeometryUpdater.prototype._isHidden = function (entity, cylinder) {
return (
!defined(entity.position) ||
!defined(cylinder.length) ||
!defined(cylinder.topRadius) ||
!defined(cylinder.bottomRadius) ||
GeometryUpdater.prototype._isHidden.call(this, entity, cylinder)
);
};
CylinderGeometryUpdater.prototype._isDynamic = function (entity, cylinder) {
return (
!entity.position.isConstant || //
!Property.isConstant(entity.orientation) || //
!cylinder.length.isConstant || //
!cylinder.topRadius.isConstant || //
!cylinder.bottomRadius.isConstant || //
!Property.isConstant(cylinder.slices) || //
!Property.isConstant(cylinder.outlineWidth) || //
!Property.isConstant(cylinder.numberOfVerticalLines)
);
};
CylinderGeometryUpdater.prototype._setStaticOptions = function (
entity,
cylinder,
) {
const heightReference = Property.getValueOrDefault(
cylinder.heightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
const options = this._options;
options.vertexFormat =
this._materialProperty instanceof ColorMaterialProperty
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
options.length = cylinder.length.getValue(Iso8601.MINIMUM_VALUE);
options.topRadius = cylinder.topRadius.getValue(Iso8601.MINIMUM_VALUE);
options.bottomRadius = cylinder.bottomRadius.getValue(Iso8601.MINIMUM_VALUE);
options.slices = Property.getValueOrUndefined(
cylinder.slices,
Iso8601.MINIMUM_VALUE,
);
options.numberOfVerticalLines = Property.getValueOrUndefined(
cylinder.numberOfVerticalLines,
Iso8601.MINIMUM_VALUE,
);
options.offsetAttribute =
heightReference !== HeightReference.NONE
? GeometryOffsetAttribute.ALL
: undefined;
};
CylinderGeometryUpdater.prototype._onEntityPropertyChanged =
heightReferenceOnEntityPropertyChanged;
CylinderGeometryUpdater.DynamicGeometryUpdater = DynamicCylinderGeometryUpdater;
/**
* @private
*/
function DynamicCylinderGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
}
if (defined(Object.create)) {
DynamicCylinderGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DynamicCylinderGeometryUpdater.prototype.constructor =
DynamicCylinderGeometryUpdater;
}
DynamicCylinderGeometryUpdater.prototype._isHidden = function (
entity,
cylinder,
time,
) {
const options = this._options;
const position = Property.getValueOrUndefined(
entity.position,
time,
positionScratch,
);
return (
!defined(position) ||
!defined(options.length) ||
!defined(options.topRadius) || //
!defined(options.bottomRadius) ||
DynamicGeometryUpdater.prototype._isHidden.call(
this,
entity,
cylinder,
time,
)
);
};
DynamicCylinderGeometryUpdater.prototype._setOptions = function (
entity,
cylinder,
time,
) {
const heightReference = Property.getValueOrDefault(
cylinder.heightReference,
time,
HeightReference.NONE,
);
const options = this._options;
options.length = Property.getValueOrUndefined(cylinder.length, time);
options.topRadius = Property.getValueOrUndefined(cylinder.topRadius, time);
options.bottomRadius = Property.getValueOrUndefined(
cylinder.bottomRadius,
time,
);
options.slices = Property.getValueOrUndefined(cylinder.slices, time);
options.numberOfVerticalLines = Property.getValueOrUndefined(
cylinder.numberOfVerticalLines,
time,
);
options.offsetAttribute =
heightReference !== HeightReference.NONE
? GeometryOffsetAttribute.ALL
: undefined;
};
export default CylinderGeometryUpdater;
@@ -0,0 +1,258 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} CylinderGraphics.ConstructorOptions
*
* Initialization options for the CylinderGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the cylinder.
* @property {Property | number} [length] A numeric Property specifying the length of the cylinder.
* @property {Property | number} [topRadius] A numeric Property specifying the radius of the top of the cylinder.
* @property {Property | number} [bottomRadius] A numeric Property specifying the radius of the bottom of the cylinder.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height from the entity position is relative to.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the cylinder is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the cylinder.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the cylinder is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | number} [numberOfVerticalLines=16] A numeric Property specifying the number of vertical lines to draw along the perimeter for the outline.
* @property {Property | number} [slices=128] The number of edges around the perimeter of the cylinder.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the cylinder casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this cylinder will be displayed.
*/
/**
* Describes a cylinder, truncated cone, or cone defined by a length, top radius, and bottom radius.
* The center position and orientation are determined by the containing {@link Entity}.
*
* @alias CylinderGraphics
* @constructor
*
* @param {CylinderGraphics.ConstructorOptions} [options] Object describing initialization options
*/
function CylinderGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._length = undefined;
this._lengthSubscription = undefined;
this._topRadius = undefined;
this._topRadiusSubscription = undefined;
this._bottomRadius = undefined;
this._bottomRadiusSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._numberOfVerticalLines = undefined;
this._numberOfVerticalLinesSubscription = undefined;
this._slices = undefined;
this._slicesSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(CylinderGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof CylinderGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the cylinder.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the numeric Property specifying the length of the cylinder.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
*/
length: createPropertyDescriptor("length"),
/**
* Gets or sets the numeric Property specifying the radius of the top of the cylinder.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
*/
topRadius: createPropertyDescriptor("topRadius"),
/**
* Gets or sets the numeric Property specifying the radius of the bottom of the cylinder.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
*/
bottomRadius: createPropertyDescriptor("bottomRadius"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the boolean Property specifying whether the cylinder is filled with the provided material.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the Property specifying the material used to fill the cylinder.
* @memberof CylinderGraphics.prototype
* @type {MaterialProperty|undefined}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the boolean Property specifying whether the cylinder is outlined.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Gets or sets the Property specifying the number of vertical lines to draw along the perimeter for the outline.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default 16
*/
numberOfVerticalLines: createPropertyDescriptor("numberOfVerticalLines"),
/**
* Gets or sets the Property specifying the number of edges around the perimeter of the cylinder.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default 128
*/
slices: createPropertyDescriptor("slices"),
/**
* Get or sets the enum Property specifying whether the cylinder
* casts or receives shadows from light sources.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this cylinder will be displayed.
* @memberof CylinderGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
});
/**
* Duplicates this instance.
*
* @param {CylinderGraphics} [result] The object onto which to store the result.
* @returns {CylinderGraphics} The modified result parameter or a new instance if one was not provided.
*/
CylinderGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new CylinderGraphics(this);
}
result.show = this.show;
result.length = this.length;
result.topRadius = this.topRadius;
result.bottomRadius = this.bottomRadius;
result.heightReference = this.heightReference;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.numberOfVerticalLines = this.numberOfVerticalLines;
result.slices = this.slices;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {CylinderGraphics} source The object to be merged into this object.
*/
CylinderGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.length = this.length ?? source.length;
this.topRadius = this.topRadius ?? source.topRadius;
this.bottomRadius = this.bottomRadius ?? source.bottomRadius;
this.heightReference = this.heightReference ?? source.heightReference;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.numberOfVerticalLines =
this.numberOfVerticalLines ?? source.numberOfVerticalLines;
this.slices = this.slices ?? source.slices;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
};
export default CylinderGraphics;
File diff suppressed because it is too large Load Diff
+121
View File
@@ -0,0 +1,121 @@
import DeveloperError from "../Core/DeveloperError.js";
/**
* Defines the interface for data sources, which turn arbitrary data into a
* {@link EntityCollection} for generic consumption. This object is an interface
* for documentation purposes and is not intended to be instantiated directly.
* @alias DataSource
* @constructor
*
* @see Entity
* @see DataSourceDisplay
*/
function DataSource() {
DeveloperError.throwInstantiationError();
}
Object.defineProperties(DataSource.prototype, {
/**
* Gets a human-readable name for this instance.
* @memberof DataSource.prototype
* @type {string}
*/
name: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets the preferred clock settings for this data source.
* @memberof DataSource.prototype
* @type {DataSourceClock}
*/
clock: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets the collection of {@link Entity} instances.
* @memberof DataSource.prototype
* @type {EntityCollection}
*/
entities: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets a value indicating if the data source is currently loading data.
* @memberof DataSource.prototype
* @type {boolean}
*/
isLoading: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets an event that will be raised when the underlying data changes.
* @memberof DataSource.prototype
* @type {Event}
*/
changedEvent: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets an event that will be raised if an error is encountered during processing.
* @memberof DataSource.prototype
* @type {Event<function(this, RequestErrorEvent)>}
*/
errorEvent: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets an event that will be raised when the value of isLoading changes.
* @memberof DataSource.prototype
* @type {Event<function(this, boolean)>}
*/
loadingEvent: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets whether or not this data source should be displayed.
* @memberof DataSource.prototype
* @type {boolean}
*/
show: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
*
* @memberof DataSource.prototype
* @type {EntityCluster}
*/
clustering: {
get: DeveloperError.throwInstantiationError,
},
});
/**
* Updates the data source to the provided time. This function is optional and
* is not required to be implemented. It is provided for data sources which
* retrieve data based on the current animation time or scene state.
* If implemented, update will be called by {@link DataSourceDisplay} once a frame.
*
* @param {JulianDate} time The simulation time.
* @returns {boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
*/
DataSource.prototype.update = function (time) {
DeveloperError.throwInstantiationError();
};
/**
* @private
*/
DataSource.setLoading = function (dataSource, isLoading) {
if (dataSource._isLoading !== isLoading) {
if (isLoading) {
dataSource._entityCollection.suspendEvents();
} else {
dataSource._entityCollection.resumeEvents();
}
dataSource._isLoading = isLoading;
dataSource._loading.raiseEvent(dataSource, isLoading);
}
};
export default DataSource;
@@ -0,0 +1,164 @@
import Clock from "../Core/Clock.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createRawPropertyDescriptor from "./createRawPropertyDescriptor.js";
/**
* Represents desired clock settings for a particular {@link DataSource}. These settings may be applied
* to the {@link Clock} when the DataSource is loaded.
*
* @alias DataSourceClock
* @constructor
*/
function DataSourceClock() {
this._definitionChanged = new Event();
this._startTime = undefined;
this._stopTime = undefined;
this._currentTime = undefined;
this._clockRange = undefined;
this._clockStep = undefined;
this._multiplier = undefined;
}
Object.defineProperties(DataSourceClock.prototype, {
/**
* Gets the event that is raised whenever a new property is assigned.
* @memberof DataSourceClock.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the desired start time of the clock.
* See {@link Clock#startTime}.
* @memberof DataSourceClock.prototype
* @type {JulianDate}
*/
startTime: createRawPropertyDescriptor("startTime"),
/**
* Gets or sets the desired stop time of the clock.
* See {@link Clock#stopTime}.
* @memberof DataSourceClock.prototype
* @type {JulianDate}
*/
stopTime: createRawPropertyDescriptor("stopTime"),
/**
* Gets or sets the desired current time when this data source is loaded.
* See {@link Clock#currentTime}.
* @memberof DataSourceClock.prototype
* @type {JulianDate}
*/
currentTime: createRawPropertyDescriptor("currentTime"),
/**
* Gets or sets the desired clock range setting.
* See {@link Clock#clockRange}.
* @memberof DataSourceClock.prototype
* @type {ClockRange}
*/
clockRange: createRawPropertyDescriptor("clockRange"),
/**
* Gets or sets the desired clock step setting.
* See {@link Clock#clockStep}.
* @memberof DataSourceClock.prototype
* @type {ClockStep}
*/
clockStep: createRawPropertyDescriptor("clockStep"),
/**
* Gets or sets the desired clock multiplier.
* See {@link Clock#multiplier}.
* @memberof DataSourceClock.prototype
* @type {number}
*/
multiplier: createRawPropertyDescriptor("multiplier"),
});
/**
* Duplicates a DataSourceClock instance.
*
* @param {DataSourceClock} [result] The object onto which to store the result.
* @returns {DataSourceClock} The modified result parameter or a new instance if one was not provided.
*/
DataSourceClock.prototype.clone = function (result) {
if (!defined(result)) {
result = new DataSourceClock();
}
result.startTime = this.startTime;
result.stopTime = this.stopTime;
result.currentTime = this.currentTime;
result.clockRange = this.clockRange;
result.clockStep = this.clockStep;
result.multiplier = this.multiplier;
return result;
};
/**
* Returns true if this DataSourceClock is equivalent to the other
*
* @param {DataSourceClock} [other] The other DataSourceClock to compare to.
* @returns {boolean} <code>true</code> if the DataSourceClocks are equal; otherwise, <code>false</code>.
*/
DataSourceClock.prototype.equals = function (other) {
return (
this === other ||
(defined(other) &&
JulianDate.equals(this.startTime, other.startTime) &&
JulianDate.equals(this.stopTime, other.stopTime) &&
JulianDate.equals(this.currentTime, other.currentTime) &&
this.clockRange === other.clockRange &&
this.clockStep === other.clockStep &&
this.multiplier === other.multiplier)
);
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {DataSourceClock} source The object to be merged into this object.
*/
DataSourceClock.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.startTime = this.startTime ?? source.startTime;
this.stopTime = this.stopTime ?? source.stopTime;
this.currentTime = this.currentTime ?? source.currentTime;
this.clockRange = this.clockRange ?? source.clockRange;
this.clockStep = this.clockStep ?? source.clockStep;
this.multiplier = this.multiplier ?? source.multiplier;
};
/**
* Gets the value of this clock instance as a {@link Clock} object.
*
* @returns {Clock} The modified result parameter or a new instance if one was not provided.
*/
DataSourceClock.prototype.getValue = function (result) {
if (!defined(result)) {
result = new Clock();
}
result.startTime = this.startTime ?? result.startTime;
result.stopTime = this.stopTime ?? result.stopTime;
result.currentTime = this.currentTime ?? result.currentTime;
result.clockRange = this.clockRange ?? result.clockRange;
result.multiplier = this.multiplier ?? result.multiplier;
result.clockStep = this.clockStep ?? result.clockStep;
return result;
};
export default DataSourceClock;
@@ -0,0 +1,335 @@
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import CesiumMath from "../Core/Math.js";
/**
* A collection of {@link DataSource} instances.
* @alias DataSourceCollection
* @constructor
*/
function DataSourceCollection() {
this._dataSources = [];
this._dataSourceAdded = new Event();
this._dataSourceRemoved = new Event();
this._dataSourceMoved = new Event();
}
Object.defineProperties(DataSourceCollection.prototype, {
/**
* Gets the number of data sources in this collection.
* @memberof DataSourceCollection.prototype
* @type {number}
* @readonly
*/
length: {
get: function () {
return this._dataSources.length;
},
},
/**
* An event that is raised when a data source is added to the collection.
* Event handlers are passed the data source that was added.
* @memberof DataSourceCollection.prototype
* @type {Event}
* @readonly
*/
dataSourceAdded: {
get: function () {
return this._dataSourceAdded;
},
},
/**
* An event that is raised when a data source is removed from the collection.
* Event handlers are passed the data source that was removed.
* @memberof DataSourceCollection.prototype
* @type {Event}
* @readonly
*/
dataSourceRemoved: {
get: function () {
return this._dataSourceRemoved;
},
},
/**
* An event that is raised when a data source changes position in the collection. Event handlers are passed the data source
* that was moved, its new index after the move, and its old index prior to the move.
* @memberof DataSourceCollection.prototype
* @type {Event}
* @readonly
*/
dataSourceMoved: {
get: function () {
return this._dataSourceMoved;
},
},
});
/**
* Adds a data source to the collection.
*
* @param {DataSource|Promise<DataSource>} dataSource A data source or a promise to a data source to add to the collection.
* When passing a promise, the data source will not actually be added
* to the collection until the promise resolves successfully.
* @returns {Promise<DataSource>} A Promise that resolves once the data source has been added to the collection.
*/
DataSourceCollection.prototype.add = function (dataSource) {
//>>includeStart('debug', pragmas.debug);
if (!defined(dataSource)) {
throw new DeveloperError("dataSource is required.");
}
//>>includeEnd('debug');
const that = this;
const dataSources = this._dataSources;
return Promise.resolve(dataSource).then(function (value) {
//Only add the data source if removeAll has not been called
//Since it was added.
if (dataSources === that._dataSources) {
that._dataSources.push(value);
that._dataSourceAdded.raiseEvent(that, value);
}
return value;
});
};
/**
* Removes a data source from this collection, if present.
*
* @param {DataSource} dataSource The data source to remove.
* @param {boolean} [destroy=false] Whether to destroy the data source in addition to removing it.
* @returns {boolean} true if the data source was in the collection and was removed,
* false if the data source was not in the collection.
*/
DataSourceCollection.prototype.remove = function (dataSource, destroy) {
destroy = destroy ?? false;
const index = this._dataSources.indexOf(dataSource);
if (index !== -1) {
this._dataSources.splice(index, 1);
this._dataSourceRemoved.raiseEvent(this, dataSource);
if (destroy && typeof dataSource.destroy === "function") {
dataSource.destroy();
}
return true;
}
return false;
};
/**
* Removes all data sources from this collection.
*
* @param {boolean} [destroy=false] whether to destroy the data sources in addition to removing them.
*/
DataSourceCollection.prototype.removeAll = function (destroy) {
destroy = destroy ?? false;
const dataSources = this._dataSources;
for (let i = 0, len = dataSources.length; i < len; ++i) {
const dataSource = dataSources[i];
this._dataSourceRemoved.raiseEvent(this, dataSource);
if (destroy && typeof dataSource.destroy === "function") {
dataSource.destroy();
}
}
this._dataSources = [];
};
/**
* Checks to see if the collection contains a given data source.
*
* @param {DataSource} dataSource The data source to check for.
* @returns {boolean} true if the collection contains the data source, false otherwise.
*/
DataSourceCollection.prototype.contains = function (dataSource) {
return this.indexOf(dataSource) !== -1;
};
/**
* Determines the index of a given data source in the collection.
*
* @param {DataSource} dataSource The data source to find the index of.
* @returns {number} The index of the data source in the collection, or -1 if the data source does not exist in the collection.
*/
DataSourceCollection.prototype.indexOf = function (dataSource) {
return this._dataSources.indexOf(dataSource);
};
/**
* Gets a data source by index from the collection.
*
* @param {number} index the index to retrieve.
* @returns {DataSource} The data source at the specified index.
*/
DataSourceCollection.prototype.get = function (index) {
//>>includeStart('debug', pragmas.debug);
if (!defined(index)) {
throw new DeveloperError("index is required.");
}
//>>includeEnd('debug');
return this._dataSources[index];
};
/**
* Gets a data source by name from the collection.
*
* @param {string} name The name to retrieve.
* @returns {DataSource[]} A list of all data sources matching the provided name.
*/
DataSourceCollection.prototype.getByName = function (name) {
//>>includeStart('debug', pragmas.debug);
if (!defined(name)) {
throw new DeveloperError("name is required.");
}
//>>includeEnd('debug');
return this._dataSources.filter(function (dataSource) {
return dataSource.name === name;
});
};
function getIndex(dataSources, dataSource) {
//>>includeStart('debug', pragmas.debug);
if (!defined(dataSource)) {
throw new DeveloperError("dataSource is required.");
}
//>>includeEnd('debug');
const index = dataSources.indexOf(dataSource);
//>>includeStart('debug', pragmas.debug);
if (index === -1) {
throw new DeveloperError("dataSource is not in this collection.");
}
//>>includeEnd('debug');
return index;
}
function swapDataSources(collection, i, j) {
const arr = collection._dataSources;
const length = arr.length - 1;
i = CesiumMath.clamp(i, 0, length);
j = CesiumMath.clamp(j, 0, length);
if (i === j) {
return;
}
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
collection.dataSourceMoved.raiseEvent(temp, j, i);
}
/**
* Raises a data source up one position in the collection.
*
* @param {DataSource} dataSource The data source to move.
*
* @exception {DeveloperError} dataSource is not in this collection.
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*/
DataSourceCollection.prototype.raise = function (dataSource) {
const index = getIndex(this._dataSources, dataSource);
swapDataSources(this, index, index + 1);
};
/**
* Lowers a data source down one position in the collection.
*
* @param {DataSource} dataSource The data source to move.
*
* @exception {DeveloperError} dataSource is not in this collection.
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*/
DataSourceCollection.prototype.lower = function (dataSource) {
const index = getIndex(this._dataSources, dataSource);
swapDataSources(this, index, index - 1);
};
/**
* Raises a data source to the top of the collection.
*
* @param {DataSource} dataSource The data source to move.
*
* @exception {DeveloperError} dataSource is not in this collection.
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*/
DataSourceCollection.prototype.raiseToTop = function (dataSource) {
const index = getIndex(this._dataSources, dataSource);
if (index === this._dataSources.length - 1) {
return;
}
this._dataSources.splice(index, 1);
this._dataSources.push(dataSource);
this.dataSourceMoved.raiseEvent(
dataSource,
this._dataSources.length - 1,
index,
);
};
/**
* Lowers a data source to the bottom of the collection.
*
* @param {DataSource} dataSource The data source to move.
*
* @exception {DeveloperError} dataSource is not in this collection.
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*/
DataSourceCollection.prototype.lowerToBottom = function (dataSource) {
const index = getIndex(this._dataSources, dataSource);
if (index === 0) {
return;
}
this._dataSources.splice(index, 1);
this._dataSources.splice(0, 0, dataSource);
this.dataSourceMoved.raiseEvent(dataSource, 0, index);
};
/**
* Returns true if this object was destroyed; otherwise, false.
* If this object was destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
*
* @returns {boolean} true if this object was destroyed; otherwise, false.
*
* @see DataSourceCollection#destroy
*/
DataSourceCollection.prototype.isDestroyed = function () {
return false;
};
/**
* Destroys the resources held by all data sources in this collection. Explicitly destroying this
* object allows for deterministic release of WebGL resources, instead of relying on the garbage
* collector. Once this object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
*
* @example
* dataSourceCollection = dataSourceCollection && dataSourceCollection.destroy();
*
* @see DataSourceCollection#isDestroyed
*/
DataSourceCollection.prototype.destroy = function () {
this.removeAll(true);
return destroyObject(this);
};
export default DataSourceCollection;
@@ -0,0 +1,543 @@
import ApproximateTerrainHeights from "../Core/ApproximateTerrainHeights.js";
import BoundingSphere from "../Core/BoundingSphere.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import EventHelper from "../Core/EventHelper.js";
import GroundPolylinePrimitive from "../Scene/GroundPolylinePrimitive.js";
import GroundPrimitive from "../Scene/GroundPrimitive.js";
import OrderedGroundPrimitiveCollection from "../Scene/OrderedGroundPrimitiveCollection.js";
import PrimitiveCollection from "../Scene/PrimitiveCollection.js";
import BillboardVisualizer from "./BillboardVisualizer.js";
import BoundingSphereState from "./BoundingSphereState.js";
import CustomDataSource from "./CustomDataSource.js";
import GeometryVisualizer from "./GeometryVisualizer.js";
import LabelVisualizer from "./LabelVisualizer.js";
import ModelVisualizer from "./ModelVisualizer.js";
import Cesium3DTilesetVisualizer from "./Cesium3DTilesetVisualizer.js";
import PathVisualizer from "./PathVisualizer.js";
import PointVisualizer from "./PointVisualizer.js";
import PolylineVisualizer from "./PolylineVisualizer.js";
/**
* Visualizes a collection of {@link DataSource} instances.
* @alias DataSourceDisplay
* @constructor
*
* @param {object} options Object with the following properties:
* @param {Scene} options.scene The scene in which to display the data.
* @param {DataSourceCollection} options.dataSourceCollection The data sources to display.
* @param {DataSourceDisplay.VisualizersCallback} [options.visualizersCallback=DataSourceDisplay.defaultVisualizersCallback]
* A function which creates an array of visualizers used for visualization.
* If undefined, all standard visualizers are used.
*/
function DataSourceDisplay(options) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.object("options", options);
Check.typeOf.object("options.scene", options.scene);
Check.typeOf.object(
"options.dataSourceCollection",
options.dataSourceCollection,
);
//>>includeEnd('debug');
GroundPrimitive.initializeTerrainHeights();
GroundPolylinePrimitive.initializeTerrainHeights();
const scene = options.scene;
const dataSourceCollection = options.dataSourceCollection;
this._eventHelper = new EventHelper();
this._eventHelper.add(
dataSourceCollection.dataSourceAdded,
this._onDataSourceAdded,
this,
);
this._eventHelper.add(
dataSourceCollection.dataSourceRemoved,
this._onDataSourceRemoved,
this,
);
this._eventHelper.add(
dataSourceCollection.dataSourceMoved,
this._onDataSourceMoved,
this,
);
this._eventHelper.add(scene.postRender, this._postRender, this);
this._dataSourceCollection = dataSourceCollection;
this._scene = scene;
this._visualizersCallback =
options.visualizersCallback ?? DataSourceDisplay.defaultVisualizersCallback;
let primitivesAdded = false;
const primitives = new PrimitiveCollection();
const groundPrimitives = new PrimitiveCollection();
if (dataSourceCollection.length > 0) {
scene.primitives.add(primitives);
scene.groundPrimitives.add(groundPrimitives);
primitivesAdded = true;
}
this._primitives = primitives;
this._groundPrimitives = groundPrimitives;
for (let i = 0, len = dataSourceCollection.length; i < len; i++) {
this._onDataSourceAdded(dataSourceCollection, dataSourceCollection.get(i));
}
const defaultDataSource = new CustomDataSource();
this._onDataSourceAdded(undefined, defaultDataSource);
this._defaultDataSource = defaultDataSource;
let removeDefaultDataSourceListener;
let removeDataSourceCollectionListener;
if (!primitivesAdded) {
const that = this;
const addPrimitives = function () {
scene.primitives.add(primitives);
scene.groundPrimitives.add(groundPrimitives);
removeDefaultDataSourceListener();
removeDataSourceCollectionListener();
that._removeDefaultDataSourceListener = undefined;
that._removeDataSourceCollectionListener = undefined;
};
removeDefaultDataSourceListener =
defaultDataSource.entities.collectionChanged.addEventListener(
addPrimitives,
);
removeDataSourceCollectionListener =
dataSourceCollection.dataSourceAdded.addEventListener(addPrimitives);
}
this._removeDefaultDataSourceListener = removeDefaultDataSourceListener;
this._removeDataSourceCollectionListener = removeDataSourceCollectionListener;
this._ready = false;
}
const ExtraVisualizers = [];
/**
* Add the provided Visualizer to the default visualizers callback if not already included
* @private
* @param {Visualizer} visualizer Visualizer class to add
*/
DataSourceDisplay.registerVisualizer = function (visualizer) {
if (!ExtraVisualizers.includes(visualizer)) {
ExtraVisualizers.push(visualizer);
}
};
/**
* Remove the provided Visualizer from the default visualizers callback if it's already included
* @private
* @param {Visualizer} visualizer Visualizer class to remove
*/
DataSourceDisplay.unregisterVisualizer = function (visualizer) {
if (ExtraVisualizers.includes(visualizer)) {
const index = ExtraVisualizers.indexOf(visualizer);
ExtraVisualizers.splice(index, 1);
}
};
/**
* Gets or sets the default function which creates an array of visualizers used for visualization.
* By default, this function uses all standard visualizers.
*
* @type {DataSourceDisplay.VisualizersCallback}
*/
DataSourceDisplay.defaultVisualizersCallback = function (
scene,
entityCluster,
dataSource,
) {
const entities = dataSource.entities;
return [
new BillboardVisualizer(entityCluster, entities),
new GeometryVisualizer(
scene,
entities,
dataSource._primitives,
dataSource._groundPrimitives,
),
new LabelVisualizer(entityCluster, entities),
new ModelVisualizer(scene, entities),
new Cesium3DTilesetVisualizer(scene, entities),
new PointVisualizer(entityCluster, entities),
new PathVisualizer(scene, entities),
new PolylineVisualizer(
scene,
entities,
dataSource._primitives,
dataSource._groundPrimitives,
),
...ExtraVisualizers.map(
(VisualizerClass) => new VisualizerClass(scene, entities),
),
];
};
Object.defineProperties(DataSourceDisplay.prototype, {
/**
* Gets the scene associated with this display.
* @memberof DataSourceDisplay.prototype
* @type {Scene}
*/
scene: {
get: function () {
return this._scene;
},
},
/**
* Gets the collection of data sources to display.
* @memberof DataSourceDisplay.prototype
* @type {DataSourceCollection}
*/
dataSources: {
get: function () {
return this._dataSourceCollection;
},
},
/**
* Gets the default data source instance which can be used to
* manually create and visualize entities not tied to
* a specific data source. This instance is always available
* and does not appear in the list dataSources collection.
* @memberof DataSourceDisplay.prototype
* @type {CustomDataSource}
*/
defaultDataSource: {
get: function () {
return this._defaultDataSource;
},
},
/**
* Gets a value indicating whether or not all entities in the data source are ready
* @memberof DataSourceDisplay.prototype
* @type {boolean}
* @readonly
*/
ready: {
get: function () {
return this._ready;
},
},
});
/**
* Returns true if this object was destroyed; otherwise, false.
* <br /><br />
* If this object was destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*
* @see DataSourceDisplay#destroy
*/
DataSourceDisplay.prototype.isDestroyed = function () {
return false;
};
/**
* Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
* release of WebGL resources, instead of relying on the garbage collector to destroy this object.
* <br /><br />
* Once an object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
*
* @example
* dataSourceDisplay = dataSourceDisplay.destroy();
*
* @see DataSourceDisplay#isDestroyed
*/
DataSourceDisplay.prototype.destroy = function () {
this._eventHelper.removeAll();
const dataSourceCollection = this._dataSourceCollection;
for (let i = 0, length = dataSourceCollection.length; i < length; ++i) {
this._onDataSourceRemoved(
this._dataSourceCollection,
dataSourceCollection.get(i),
);
}
this._onDataSourceRemoved(undefined, this._defaultDataSource);
if (defined(this._removeDefaultDataSourceListener)) {
this._removeDefaultDataSourceListener();
this._removeDataSourceCollectionListener();
} else {
this._scene.primitives.remove(this._primitives);
this._scene.groundPrimitives.remove(this._groundPrimitives);
}
return destroyObject(this);
};
/**
* Updates the display to the provided time.
*
* @param {JulianDate} time The simulation time.
* @returns {boolean} True if all data sources are ready to be displayed, false otherwise.
*/
DataSourceDisplay.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
if (!ApproximateTerrainHeights.initialized) {
this._ready = false;
return false;
}
let result = true;
let i;
let x;
let visualizers;
let vLength;
const dataSources = this._dataSourceCollection;
const length = dataSources.length;
for (i = 0; i < length; i++) {
const dataSource = dataSources.get(i);
if (defined(dataSource.update)) {
result = dataSource.update(time) && result;
}
visualizers = dataSource._visualizers;
vLength = visualizers.length;
for (x = 0; x < vLength; x++) {
result = visualizers[x].update(time) && result;
}
}
visualizers = this._defaultDataSource._visualizers;
vLength = visualizers.length;
for (x = 0; x < vLength; x++) {
result = visualizers[x].update(time) && result;
}
// Request a rendering of the scene when the data source
// becomes 'ready' for the first time
if (!this._ready && result) {
this._scene.requestRender();
}
// once the DataSourceDisplay is ready it should stay ready to prevent
// entities from breaking updates when they become "un-ready"
this._ready = this._ready || result;
return result;
};
DataSourceDisplay.prototype._postRender = function () {
// Adds credits for all datasources
const frameState = this._scene.frameState;
const dataSources = this._dataSourceCollection;
const length = dataSources.length;
for (let i = 0; i < length; i++) {
const dataSource = dataSources.get(i);
const credit = dataSource.credit;
if (defined(credit)) {
frameState.creditDisplay.addCreditToNextFrame(credit);
}
// Credits from the resource that the user can't remove
const credits = dataSource._resourceCredits;
if (defined(credits)) {
const creditCount = credits.length;
for (let c = 0; c < creditCount; c++) {
frameState.creditDisplay.addCreditToNextFrame(credits[c]);
}
}
}
};
const getBoundingSphereArrayScratch = [];
const getBoundingSphereBoundingSphereScratch = new BoundingSphere();
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {boolean} allowPartial If true, pending bounding spheres are ignored and an answer will be returned from the currently available data.
* If false, the the function will halt and return pending if any of the bounding spheres are pending.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
DataSourceDisplay.prototype.getBoundingSphere = function (
entity,
allowPartial,
result,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("entity", entity);
Check.typeOf.bool("allowPartial", allowPartial);
Check.defined("result", result);
//>>includeEnd('debug');
if (!this._ready) {
return BoundingSphereState.PENDING;
}
let i;
let length;
let dataSource = this._defaultDataSource;
if (!dataSource.entities.contains(entity)) {
dataSource = undefined;
const dataSources = this._dataSourceCollection;
length = dataSources.length;
for (i = 0; i < length; i++) {
const d = dataSources.get(i);
if (d.entities.contains(entity)) {
dataSource = d;
break;
}
}
}
if (!defined(dataSource)) {
return BoundingSphereState.FAILED;
}
const boundingSpheres = getBoundingSphereArrayScratch;
const tmp = getBoundingSphereBoundingSphereScratch;
let count = 0;
let state = BoundingSphereState.DONE;
const visualizers = dataSource._visualizers;
const visualizersLength = visualizers.length;
for (i = 0; i < visualizersLength; i++) {
const visualizer = visualizers[i];
if (defined(visualizer.getBoundingSphere)) {
state = visualizers[i].getBoundingSphere(entity, tmp);
if (!allowPartial && state === BoundingSphereState.PENDING) {
return BoundingSphereState.PENDING;
} else if (state === BoundingSphereState.DONE) {
boundingSpheres[count] = BoundingSphere.clone(
tmp,
boundingSpheres[count],
);
count++;
}
}
}
if (count === 0) {
return BoundingSphereState.FAILED;
}
boundingSpheres.length = count;
BoundingSphere.fromBoundingSpheres(boundingSpheres, result);
return BoundingSphereState.DONE;
};
DataSourceDisplay.prototype._onDataSourceAdded = function (
dataSourceCollection,
dataSource,
) {
const scene = this._scene;
const displayPrimitives = this._primitives;
const displayGroundPrimitives = this._groundPrimitives;
const primitives = displayPrimitives.add(new PrimitiveCollection());
const groundPrimitives = displayGroundPrimitives.add(
new OrderedGroundPrimitiveCollection(),
);
dataSource._primitives = primitives;
dataSource._groundPrimitives = groundPrimitives;
const entityCluster = dataSource.clustering;
entityCluster._initialize(scene);
primitives.add(entityCluster);
dataSource._visualizers = this._visualizersCallback(
scene,
entityCluster,
dataSource,
);
};
DataSourceDisplay.prototype._onDataSourceRemoved = function (
dataSourceCollection,
dataSource,
) {
const displayPrimitives = this._primitives;
const displayGroundPrimitives = this._groundPrimitives;
const primitives = dataSource._primitives;
const groundPrimitives = dataSource._groundPrimitives;
const entityCluster = dataSource.clustering;
primitives.remove(entityCluster);
const visualizers = dataSource._visualizers;
const length = visualizers.length;
for (let i = 0; i < length; i++) {
visualizers[i].destroy();
}
displayPrimitives.remove(primitives);
displayGroundPrimitives.remove(groundPrimitives);
dataSource._visualizers = undefined;
};
DataSourceDisplay.prototype._onDataSourceMoved = function (
dataSource,
newIndex,
oldIndex,
) {
const displayPrimitives = this._primitives;
const displayGroundPrimitives = this._groundPrimitives;
const primitives = dataSource._primitives;
const groundPrimitives = dataSource._groundPrimitives;
if (newIndex === oldIndex + 1) {
displayPrimitives.raise(primitives);
displayGroundPrimitives.raise(groundPrimitives);
} else if (newIndex === oldIndex - 1) {
displayPrimitives.lower(primitives);
displayGroundPrimitives.lower(groundPrimitives);
} else if (newIndex === 0) {
displayPrimitives.lowerToBottom(primitives);
displayGroundPrimitives.lowerToBottom(groundPrimitives);
displayPrimitives.raise(primitives); // keep defaultDataSource primitives at index 0 since it's not in the collection
displayGroundPrimitives.raise(groundPrimitives);
} else {
displayPrimitives.raiseToTop(primitives);
displayGroundPrimitives.raiseToTop(groundPrimitives);
}
};
/**
* A function which creates an array of visualizers used for visualization.
* @callback DataSourceDisplay.VisualizersCallback
*
* @param {Scene} scene The scene to create visualizers for.
* @param {EntityCluster} entityCluster The entity cluster to create visualizers for.
* @param {DataSource} dataSource The data source to create visualizers for.
* @returns {Visualizer[]} An array of visualizers used for visualization.
*
* @example
* function createVisualizers(scene, entityCluster, dataSource) {
* return [new Cesium.BillboardVisualizer(entityCluster, dataSource.entities)];
* }
*/
export default DataSourceDisplay;
@@ -0,0 +1,56 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import defined from "../Core/defined.js";
import BoundingSphereState from "./BoundingSphereState.js";
/**
* @private
*/
function DynamicGeometryBatch(primitives, orderedGroundPrimitives) {
this._primitives = primitives;
this._orderedGroundPrimitives = orderedGroundPrimitives;
this._dynamicUpdaters = new AssociativeArray();
}
DynamicGeometryBatch.prototype.add = function (time, updater) {
this._dynamicUpdaters.set(
updater.id,
updater.createDynamicUpdater(
this._primitives,
this._orderedGroundPrimitives,
),
);
};
DynamicGeometryBatch.prototype.remove = function (updater) {
const id = updater.id;
const dynamicUpdater = this._dynamicUpdaters.get(id);
if (defined(dynamicUpdater)) {
this._dynamicUpdaters.remove(id);
dynamicUpdater.destroy();
}
};
DynamicGeometryBatch.prototype.update = function (time) {
const geometries = this._dynamicUpdaters.values;
for (let i = 0, len = geometries.length; i < len; i++) {
geometries[i].update(time);
}
return true;
};
DynamicGeometryBatch.prototype.removeAllPrimitives = function () {
const geometries = this._dynamicUpdaters.values;
for (let i = 0, len = geometries.length; i < len; i++) {
geometries[i].destroy();
}
this._dynamicUpdaters.removeAll();
};
DynamicGeometryBatch.prototype.getBoundingSphere = function (updater, result) {
updater = this._dynamicUpdaters.get(updater.id);
if (defined(updater) && defined(updater.getBoundingSphere)) {
return updater.getBoundingSphere(result);
}
return BoundingSphereState.FAILED;
};
export default DynamicGeometryBatch;
@@ -0,0 +1,270 @@
import BoundingSphere from "../Core/BoundingSphere.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import GroundPrimitive from "../Scene/GroundPrimitive.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import Primitive from "../Scene/Primitive.js";
import BoundingSphereState from "./BoundingSphereState.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import MaterialProperty from "./MaterialProperty.js";
import Property from "./Property.js";
/**
* Defines the interface for a dynamic geometry updater. A DynamicGeometryUpdater
* is responsible for handling visualization of a specific type of geometry
* that needs to be recomputed based on simulation time.
* This object is never used directly by client code, but is instead created by
* {@link GeometryUpdater} implementations which contain dynamic geometry.
*
* This type defines an interface and cannot be instantiated directly.
*
* @alias DynamicGeometryUpdater
* @constructor
* @private
* @abstract
*/
function DynamicGeometryUpdater(
geometryUpdater,
primitives,
orderedGroundPrimitives,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("geometryUpdater", geometryUpdater);
Check.defined("primitives", primitives);
Check.defined("orderedGroundPrimitives", orderedGroundPrimitives);
//>>includeEnd('debug');
this._primitives = primitives;
this._orderedGroundPrimitives = orderedGroundPrimitives;
this._primitive = undefined;
this._outlinePrimitive = undefined;
this._geometryUpdater = geometryUpdater;
this._options = geometryUpdater._options;
this._entity = geometryUpdater._entity;
this._material = undefined;
}
DynamicGeometryUpdater.prototype._isHidden = function (entity, geometry, time) {
return (
!entity.isShowing ||
!entity.isAvailable(time) ||
!Property.getValueOrDefault(geometry.show, time, true)
);
};
DynamicGeometryUpdater.prototype._setOptions =
DeveloperError.throwInstantiationError;
/**
* Updates the geometry to the specified time.
* @memberof DynamicGeometryUpdater
* @function
*
* @param {JulianDate} time The current time.
*/
DynamicGeometryUpdater.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
const geometryUpdater = this._geometryUpdater;
const onTerrain = geometryUpdater._onTerrain;
const primitives = this._primitives;
const orderedGroundPrimitives = this._orderedGroundPrimitives;
if (onTerrain) {
orderedGroundPrimitives.remove(this._primitive);
} else {
primitives.removeAndDestroy(this._primitive);
primitives.removeAndDestroy(this._outlinePrimitive);
this._outlinePrimitive = undefined;
}
this._primitive = undefined;
const entity = this._entity;
const geometry = entity[this._geometryUpdater._geometryPropertyName];
this._setOptions(entity, geometry, time);
if (this._isHidden(entity, geometry, time)) {
return;
}
const shadows = this._geometryUpdater.shadowsProperty.getValue(time);
const options = this._options;
if (!defined(geometry.fill) || geometry.fill.getValue(time)) {
const fillMaterialProperty = geometryUpdater.fillMaterialProperty;
const isColorAppearance =
fillMaterialProperty instanceof ColorMaterialProperty;
let appearance;
const closed = geometryUpdater._getIsClosed(options);
if (isColorAppearance) {
appearance = new PerInstanceColorAppearance({
closed: closed,
flat:
onTerrain && !geometryUpdater._supportsMaterialsforEntitiesOnTerrain,
});
} else {
const material = MaterialProperty.getValue(
time,
fillMaterialProperty,
this._material,
);
this._material = material;
appearance = new MaterialAppearance({
material: material,
translucent: material.isTranslucent(),
closed: closed,
});
}
if (onTerrain) {
options.vertexFormat = PerInstanceColorAppearance.VERTEX_FORMAT;
this._primitive = orderedGroundPrimitives.add(
new GroundPrimitive({
geometryInstances:
this._geometryUpdater.createFillGeometryInstance(time),
appearance: appearance,
asynchronous: false,
shadows: shadows,
classificationType:
this._geometryUpdater.classificationTypeProperty.getValue(time),
}),
Property.getValueOrUndefined(this._geometryUpdater.zIndex, time),
);
} else {
options.vertexFormat = appearance.vertexFormat;
const fillInstance =
this._geometryUpdater.createFillGeometryInstance(time);
if (isColorAppearance) {
appearance.translucent = fillInstance.attributes.color.value[3] !== 255;
}
this._primitive = primitives.add(
new Primitive({
geometryInstances: fillInstance,
appearance: appearance,
asynchronous: false,
shadows: shadows,
}),
);
}
}
if (
!onTerrain &&
defined(geometry.outline) &&
geometry.outline.getValue(time)
) {
const outlineInstance =
this._geometryUpdater.createOutlineGeometryInstance(time);
const outlineWidth = Property.getValueOrDefault(
geometry.outlineWidth,
time,
1.0,
);
this._outlinePrimitive = primitives.add(
new Primitive({
geometryInstances: outlineInstance,
appearance: new PerInstanceColorAppearance({
flat: true,
translucent: outlineInstance.attributes.color.value[3] !== 255,
renderState: {
lineWidth: geometryUpdater._scene.clampLineWidth(outlineWidth),
},
}),
asynchronous: false,
shadows: shadows,
}),
);
}
};
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
* @function
*
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
DynamicGeometryUpdater.prototype.getBoundingSphere = function (result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(result)) {
throw new DeveloperError("result is required.");
}
//>>includeEnd('debug');
const entity = this._entity;
const primitive = this._primitive;
const outlinePrimitive = this._outlinePrimitive;
let attributes;
//Outline and Fill geometries have the same bounding sphere, so just use whichever one is defined and ready
if (defined(primitive) && primitive.show && primitive.ready) {
attributes = primitive.getGeometryInstanceAttributes(entity);
if (defined(attributes) && defined(attributes.boundingSphere)) {
BoundingSphere.clone(attributes.boundingSphere, result);
return BoundingSphereState.DONE;
}
}
if (
defined(outlinePrimitive) &&
outlinePrimitive.show &&
outlinePrimitive.ready
) {
attributes = outlinePrimitive.getGeometryInstanceAttributes(entity);
if (defined(attributes) && defined(attributes.boundingSphere)) {
BoundingSphere.clone(attributes.boundingSphere, result);
return BoundingSphereState.DONE;
}
}
if (
(defined(primitive) && !primitive.ready) ||
(defined(outlinePrimitive) && !outlinePrimitive.ready)
) {
return BoundingSphereState.PENDING;
}
return BoundingSphereState.FAILED;
};
/**
* Returns true if this object was destroyed; otherwise, false.
* @memberof DynamicGeometryUpdater
* @function
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
DynamicGeometryUpdater.prototype.isDestroyed = function () {
return false;
};
/**
* Destroys and resources used by the object. Once an object is destroyed, it should not be used.
* @memberof DynamicGeometryUpdater
* @function
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*/
DynamicGeometryUpdater.prototype.destroy = function () {
const primitives = this._primitives;
const orderedGroundPrimitives = this._orderedGroundPrimitives;
if (this._geometryUpdater._onTerrain) {
orderedGroundPrimitives.remove(this._primitive);
} else {
primitives.removeAndDestroy(this._primitive);
}
primitives.removeAndDestroy(this._outlinePrimitive);
destroyObject(this);
};
export default DynamicGeometryUpdater;
@@ -0,0 +1,434 @@
import ApproximateTerrainHeights from "../Core/ApproximateTerrainHeights.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import EllipseGeometry from "../Core/EllipseGeometry.js";
import EllipseOutlineGeometry from "../Core/EllipseOutlineGeometry.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import Iso8601 from "../Core/Iso8601.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import Rectangle from "../Core/Rectangle.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import HeightReference from "../Scene/HeightReference.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import GroundGeometryUpdater from "./GroundGeometryUpdater.js";
import Property from "./Property.js";
const scratchColor = new Color();
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
const scratchRectangle = new Rectangle();
function EllipseGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.center = undefined;
this.semiMajorAxis = undefined;
this.semiMinorAxis = undefined;
this.rotation = undefined;
this.height = undefined;
this.extrudedHeight = undefined;
this.granularity = undefined;
this.stRotation = undefined;
this.numberOfVerticalLines = undefined;
this.offsetAttribute = undefined;
}
/**
* A {@link GeometryUpdater} for ellipses.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias EllipseGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function EllipseGeometryUpdater(entity, scene) {
GroundGeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new EllipseGeometryOptions(entity),
geometryPropertyName: "ellipse",
observedPropertyNames: ["availability", "position", "ellipse"],
});
this._onEntityPropertyChanged(entity, "ellipse", entity.ellipse, undefined);
}
if (defined(Object.create)) {
EllipseGeometryUpdater.prototype = Object.create(
GroundGeometryUpdater.prototype,
);
EllipseGeometryUpdater.prototype.constructor = EllipseGeometryUpdater;
}
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
EllipseGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time),
),
offset: undefined,
color: undefined,
};
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
}
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new EllipseGeometry(this._options),
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
EllipseGeometryUpdater.prototype.createOutlineGeometryInstance = function (
time,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
),
offset: undefined,
};
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new EllipseOutlineGeometry(this._options),
attributes: attributes,
});
};
EllipseGeometryUpdater.prototype._computeCenter = function (time, result) {
return Property.getValueOrUndefined(this._entity.position, time, result);
};
EllipseGeometryUpdater.prototype._isHidden = function (entity, ellipse) {
const position = entity.position;
return (
!defined(position) ||
!defined(ellipse.semiMajorAxis) ||
!defined(ellipse.semiMinorAxis) ||
GeometryUpdater.prototype._isHidden.call(this, entity, ellipse)
);
};
EllipseGeometryUpdater.prototype._isDynamic = function (entity, ellipse) {
return (
!entity.position.isConstant || //
!ellipse.semiMajorAxis.isConstant || //
!ellipse.semiMinorAxis.isConstant || //
!Property.isConstant(ellipse.rotation) || //
!Property.isConstant(ellipse.height) || //
!Property.isConstant(ellipse.extrudedHeight) || //
!Property.isConstant(ellipse.granularity) || //
!Property.isConstant(ellipse.stRotation) || //
!Property.isConstant(ellipse.outlineWidth) || //
!Property.isConstant(ellipse.numberOfVerticalLines) || //
!Property.isConstant(ellipse.zIndex) || //
(this._onTerrain &&
!Property.isConstant(this._materialProperty) &&
!(this._materialProperty instanceof ColorMaterialProperty))
);
};
EllipseGeometryUpdater.prototype._setStaticOptions = function (
entity,
ellipse,
) {
let heightValue = Property.getValueOrUndefined(
ellipse.height,
Iso8601.MINIMUM_VALUE,
);
const heightReferenceValue = Property.getValueOrDefault(
ellipse.heightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
let extrudedHeightValue = Property.getValueOrUndefined(
ellipse.extrudedHeight,
Iso8601.MINIMUM_VALUE,
);
const extrudedHeightReferenceValue = Property.getValueOrDefault(
ellipse.extrudedHeightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
if (defined(extrudedHeightValue) && !defined(heightValue)) {
heightValue = 0;
}
const options = this._options;
options.vertexFormat =
this._materialProperty instanceof ColorMaterialProperty
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
options.center = entity.position.getValue(
Iso8601.MINIMUM_VALUE,
options.center,
);
options.semiMajorAxis = ellipse.semiMajorAxis.getValue(
Iso8601.MINIMUM_VALUE,
options.semiMajorAxis,
);
options.semiMinorAxis = ellipse.semiMinorAxis.getValue(
Iso8601.MINIMUM_VALUE,
options.semiMinorAxis,
);
options.rotation = Property.getValueOrUndefined(
ellipse.rotation,
Iso8601.MINIMUM_VALUE,
);
options.granularity = Property.getValueOrUndefined(
ellipse.granularity,
Iso8601.MINIMUM_VALUE,
);
options.stRotation = Property.getValueOrUndefined(
ellipse.stRotation,
Iso8601.MINIMUM_VALUE,
);
options.numberOfVerticalLines = Property.getValueOrUndefined(
ellipse.numberOfVerticalLines,
Iso8601.MINIMUM_VALUE,
);
options.offsetAttribute =
GroundGeometryUpdater.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue,
);
options.height = GroundGeometryUpdater.getGeometryHeight(
heightValue,
heightReferenceValue,
);
extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue,
);
if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
EllipseGeometry.computeRectangle(options, scratchRectangle),
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
EllipseGeometryUpdater.DynamicGeometryUpdater = DynamicEllipseGeometryUpdater;
/**
* @private
*/
function DynamicEllipseGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
}
if (defined(Object.create)) {
DynamicEllipseGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DynamicEllipseGeometryUpdater.prototype.constructor =
DynamicEllipseGeometryUpdater;
}
DynamicEllipseGeometryUpdater.prototype._isHidden = function (
entity,
ellipse,
time,
) {
const options = this._options;
return (
!defined(options.center) ||
!defined(options.semiMajorAxis) ||
!defined(options.semiMinorAxis) ||
DynamicGeometryUpdater.prototype._isHidden.call(this, entity, ellipse, time)
);
};
DynamicEllipseGeometryUpdater.prototype._setOptions = function (
entity,
ellipse,
time,
) {
const options = this._options;
let heightValue = Property.getValueOrUndefined(ellipse.height, time);
const heightReferenceValue = Property.getValueOrDefault(
ellipse.heightReference,
time,
HeightReference.NONE,
);
let extrudedHeightValue = Property.getValueOrUndefined(
ellipse.extrudedHeight,
time,
);
const extrudedHeightReferenceValue = Property.getValueOrDefault(
ellipse.extrudedHeightReference,
time,
HeightReference.NONE,
);
if (defined(extrudedHeightValue) && !defined(heightValue)) {
heightValue = 0;
}
options.center = Property.getValueOrUndefined(
entity.position,
time,
options.center,
);
options.semiMajorAxis = Property.getValueOrUndefined(
ellipse.semiMajorAxis,
time,
);
options.semiMinorAxis = Property.getValueOrUndefined(
ellipse.semiMinorAxis,
time,
);
options.rotation = Property.getValueOrUndefined(ellipse.rotation, time);
options.granularity = Property.getValueOrUndefined(ellipse.granularity, time);
options.stRotation = Property.getValueOrUndefined(ellipse.stRotation, time);
options.numberOfVerticalLines = Property.getValueOrUndefined(
ellipse.numberOfVerticalLines,
time,
);
options.offsetAttribute =
GroundGeometryUpdater.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue,
);
options.height = GroundGeometryUpdater.getGeometryHeight(
heightValue,
heightReferenceValue,
);
extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue,
);
if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
EllipseGeometry.computeRectangle(options, scratchRectangle),
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
export default EllipseGeometryUpdater;
@@ -0,0 +1,343 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} EllipseGraphics.ConstructorOptions
*
* Initialization options for the EllipseGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the ellipse.
* @property {Property | number} [semiMajorAxis] The numeric Property specifying the semi-major axis.
* @property {Property | number} [semiMinorAxis] The numeric Property specifying the semi-minor axis.
* @property {Property | number} [height=0] A numeric Property specifying the altitude of the ellipse relative to the ellipsoid surface.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
* @property {Property | number} [extrudedHeight] A numeric Property specifying the altitude of the ellipse's extruded face relative to the ellipsoid surface.
* @property {Property | HeightReference} [extrudedHeightReference=HeightReference.NONE] A Property specifying what the extrudedHeight is relative to.
* @property {Property | number} [rotation=0.0] A numeric property specifying the rotation of the ellipse counter-clockwise from north.
* @property {Property | number} [stRotation=0.0] A numeric property specifying the rotation of the ellipse texture counter-clockwise from north.
* @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between points on the ellipse.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the ellipse is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the ellipse.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the ellipse is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | number} [numberOfVerticalLines=16] A numeric Property specifying the number of vertical lines to draw along the perimeter for the outline.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the ellipse casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this ellipse will be displayed.
* @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this ellipse will classify terrain, 3D Tiles, or both when on the ground.
* @property {ConstantProperty | number} [zIndex=0] A property specifying the zIndex of the Ellipse. Used for ordering ground geometry. Only has an effect if the ellipse is constant and neither height or exturdedHeight are specified.
*/
/**
* Describes an ellipse defined by a center point and semi-major and semi-minor axes.
* The ellipse conforms to the curvature of the globe and can be placed on the surface or
* at altitude and can optionally be extruded into a volume.
* The center point is determined by the containing {@link Entity}.
*
* @alias EllipseGraphics
* @constructor
*
* @param {EllipseGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @demo {@link https://sandcastle.cesium.com/index.html?id=circles-and-ellipses|Cesium Sandcastle Circles and Ellipses Demo}
*/
function EllipseGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._semiMajorAxis = undefined;
this._semiMajorAxisSubscription = undefined;
this._semiMinorAxis = undefined;
this._semiMinorAxisSubscription = undefined;
this._height = undefined;
this._heightSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._extrudedHeight = undefined;
this._extrudedHeightSubscription = undefined;
this._extrudedHeightReference = undefined;
this._extrudedHeightReferenceSubscription = undefined;
this._rotation = undefined;
this._rotationSubscription = undefined;
this._stRotation = undefined;
this._stRotationSubscription = undefined;
this._granularity = undefined;
this._granularitySubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._numberOfVerticalLines = undefined;
this._numberOfVerticalLinesSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._classificationType = undefined;
this._classificationTypeSubscription = undefined;
this._zIndex = undefined;
this._zIndexSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(EllipseGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof EllipseGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the ellipse.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the numeric Property specifying the semi-major axis.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
*/
semiMajorAxis: createPropertyDescriptor("semiMajorAxis"),
/**
* Gets or sets the numeric Property specifying the semi-minor axis.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
*/
semiMinorAxis: createPropertyDescriptor("semiMinorAxis"),
/**
* Gets or sets the numeric Property specifying the altitude of the ellipse.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
height: createPropertyDescriptor("height"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the numeric Property specifying the altitude of the ellipse extrusion.
* Setting this property creates volume starting at height and ending at this altitude.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
*/
extrudedHeight: createPropertyDescriptor("extrudedHeight"),
/**
* Gets or sets the Property specifying the extruded {@link HeightReference}.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
extrudedHeightReference: createPropertyDescriptor("extrudedHeightReference"),
/**
* Gets or sets the numeric property specifying the rotation of the ellipse counter-clockwise from north.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default 0
*/
rotation: createPropertyDescriptor("rotation"),
/**
* Gets or sets the numeric property specifying the rotation of the ellipse texture counter-clockwise from north.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default 0
*/
stRotation: createPropertyDescriptor("stRotation"),
/**
* Gets or sets the numeric Property specifying the angular distance between points on the ellipse.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default {CesiumMath.RADIANS_PER_DEGREE}
*/
granularity: createPropertyDescriptor("granularity"),
/**
* Gets or sets the boolean Property specifying whether the ellipse is filled with the provided material.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the Property specifying the material used to fill the ellipse.
* @memberof EllipseGraphics.prototype
* @type {MaterialProperty|undefined}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying whether the ellipse is outlined.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Gets or sets the numeric Property specifying the number of vertical lines to draw along the perimeter for the outline.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default 16
*/
numberOfVerticalLines: createPropertyDescriptor("numberOfVerticalLines"),
/**
* Get or sets the enum Property specifying whether the ellipse
* casts or receives shadows from light sources.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this ellipse will be displayed.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the {@link ClassificationType} Property specifying whether this ellipse will classify terrain, 3D Tiles, or both when on the ground.
* @memberof EllipseGraphics.prototype
* @type {Property|undefined}
* @default ClassificationType.BOTH
*/
classificationType: createPropertyDescriptor("classificationType"),
/**
* Gets or sets the zIndex Property specifying the ellipse ordering. Only has an effect if the ellipse is constant and neither height or extrudedHeight are specified
* @memberof EllipseGraphics.prototype
* @type {ConstantProperty|undefined}
* @default 0
*/
zIndex: createPropertyDescriptor("zIndex"),
});
/**
* Duplicates this instance.
*
* @param {EllipseGraphics} [result] The object onto which to store the result.
* @returns {EllipseGraphics} The modified result parameter or a new instance if one was not provided.
*/
EllipseGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new EllipseGraphics(this);
}
result.show = this.show;
result.semiMajorAxis = this.semiMajorAxis;
result.semiMinorAxis = this.semiMinorAxis;
result.height = this.height;
result.heightReference = this.heightReference;
result.extrudedHeight = this.extrudedHeight;
result.extrudedHeightReference = this.extrudedHeightReference;
result.rotation = this.rotation;
result.stRotation = this.stRotation;
result.granularity = this.granularity;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.numberOfVerticalLines = this.numberOfVerticalLines;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.classificationType = this.classificationType;
result.zIndex = this.zIndex;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {EllipseGraphics} source The object to be merged into this object.
*/
EllipseGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.semiMajorAxis = this.semiMajorAxis ?? source.semiMajorAxis;
this.semiMinorAxis = this.semiMinorAxis ?? source.semiMinorAxis;
this.height = this.height ?? source.height;
this.heightReference = this.heightReference ?? source.heightReference;
this.extrudedHeight = this.extrudedHeight ?? source.extrudedHeight;
this.extrudedHeightReference =
this.extrudedHeightReference ?? source.extrudedHeightReference;
this.rotation = this.rotation ?? source.rotation;
this.stRotation = this.stRotation ?? source.stRotation;
this.granularity = this.granularity ?? source.granularity;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.numberOfVerticalLines =
this.numberOfVerticalLines ?? source.numberOfVerticalLines;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.classificationType =
this.classificationType ?? source.classificationType;
this.zIndex = this.zIndex ?? source.zIndex;
};
export default EllipseGraphics;
@@ -0,0 +1,710 @@
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import EllipsoidGeometry from "../Core/EllipsoidGeometry.js";
import EllipsoidOutlineGeometry from "../Core/EllipsoidOutlineGeometry.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import GeometryOffsetAttribute from "../Core/GeometryOffsetAttribute.js";
import Iso8601 from "../Core/Iso8601.js";
import Matrix4 from "../Core/Matrix4.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import HeightReference from "../Scene/HeightReference.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import Primitive from "../Scene/Primitive.js";
import SceneMode from "../Scene/SceneMode.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import heightReferenceOnEntityPropertyChanged from "./heightReferenceOnEntityPropertyChanged.js";
import MaterialProperty from "./MaterialProperty.js";
import Property from "./Property.js";
const defaultMaterial = new ColorMaterialProperty(Color.WHITE);
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
const radiiScratch = new Cartesian3();
const innerRadiiScratch = new Cartesian3();
const scratchColor = new Color();
const unitSphere = new Cartesian3(1, 1, 1);
function EllipsoidGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.radii = undefined;
this.innerRadii = undefined;
this.minimumClock = undefined;
this.maximumClock = undefined;
this.minimumCone = undefined;
this.maximumCone = undefined;
this.stackPartitions = undefined;
this.slicePartitions = undefined;
this.subdivisions = undefined;
this.offsetAttribute = undefined;
}
/**
* A {@link GeometryUpdater} for ellipsoids.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias EllipsoidGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function EllipsoidGeometryUpdater(entity, scene) {
GeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new EllipsoidGeometryOptions(entity),
geometryPropertyName: "ellipsoid",
observedPropertyNames: [
"availability",
"position",
"orientation",
"ellipsoid",
],
});
this._onEntityPropertyChanged(
entity,
"ellipsoid",
entity.ellipsoid,
undefined,
);
}
if (defined(Object.create)) {
EllipsoidGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
EllipsoidGeometryUpdater.prototype.constructor = EllipsoidGeometryUpdater;
}
Object.defineProperties(EllipsoidGeometryUpdater.prototype, {
/**
* Gets the terrain offset property
* @type {TerrainOffsetProperty}
* @memberof EllipsoidGeometryUpdater.prototype
* @readonly
* @private
*/
terrainOffsetProperty: {
get: function () {
return this._terrainOffsetProperty;
},
},
});
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @param {boolean} [skipModelMatrix=false] Whether to compute a model matrix for the geometry instance
* @param {Matrix4} [modelMatrixResult] Used to store the result of the model matrix calculation
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
EllipsoidGeometryUpdater.prototype.createFillGeometryInstance = function (
time,
skipModelMatrix,
modelMatrixResult,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
let color;
const show = new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const distanceDisplayConditionAttribute =
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
);
const attributes = {
show: show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color: undefined,
offset: undefined,
};
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
color = ColorGeometryInstanceAttribute.fromColor(currentColor);
attributes.color = color;
}
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new EllipsoidGeometry(this._options),
modelMatrix: skipModelMatrix
? undefined
: entity.computeModelMatrixForHeightReference(
time,
entity.ellipsoid.heightReference,
this._options.radii.z * 0.5,
this._scene.ellipsoid,
modelMatrixResult,
),
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @param {boolean} [skipModelMatrix=false] Whether to compute a model matrix for the geometry instance
* @param {Matrix4} [modelMatrixResult] Used to store the result of the model matrix calculation
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
EllipsoidGeometryUpdater.prototype.createOutlineGeometryInstance = function (
time,
skipModelMatrix,
modelMatrixResult,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
),
offset: undefined,
};
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new EllipsoidOutlineGeometry(this._options),
modelMatrix: skipModelMatrix
? undefined
: entity.computeModelMatrixForHeightReference(
time,
entity.ellipsoid.heightReference,
this._options.radii.z * 0.5,
this._scene.ellipsoid,
modelMatrixResult,
),
attributes: attributes,
});
};
EllipsoidGeometryUpdater.prototype._computeCenter = function (time, result) {
return Property.getValueOrUndefined(this._entity.position, time, result);
};
EllipsoidGeometryUpdater.prototype._isHidden = function (entity, ellipsoid) {
return (
!defined(entity.position) ||
!defined(ellipsoid.radii) ||
GeometryUpdater.prototype._isHidden.call(this, entity, ellipsoid)
);
};
EllipsoidGeometryUpdater.prototype._isDynamic = function (entity, ellipsoid) {
return (
!entity.position.isConstant || //
!Property.isConstant(entity.orientation) || //
!ellipsoid.radii.isConstant || //
!Property.isConstant(ellipsoid.innerRadii) || //
!Property.isConstant(ellipsoid.stackPartitions) || //
!Property.isConstant(ellipsoid.slicePartitions) || //
!Property.isConstant(ellipsoid.outlineWidth) || //
!Property.isConstant(ellipsoid.minimumClock) || //
!Property.isConstant(ellipsoid.maximumClock) || //
!Property.isConstant(ellipsoid.minimumCone) || //
!Property.isConstant(ellipsoid.maximumCone) || //
!Property.isConstant(ellipsoid.subdivisions)
);
};
EllipsoidGeometryUpdater.prototype._setStaticOptions = function (
entity,
ellipsoid,
) {
const heightReference = Property.getValueOrDefault(
ellipsoid.heightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
const options = this._options;
options.vertexFormat =
this._materialProperty instanceof ColorMaterialProperty
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
options.radii = ellipsoid.radii.getValue(
Iso8601.MINIMUM_VALUE,
options.radii,
);
options.innerRadii = Property.getValueOrUndefined(
ellipsoid.innerRadii,
options.radii,
);
options.minimumClock = Property.getValueOrUndefined(
ellipsoid.minimumClock,
Iso8601.MINIMUM_VALUE,
);
options.maximumClock = Property.getValueOrUndefined(
ellipsoid.maximumClock,
Iso8601.MINIMUM_VALUE,
);
options.minimumCone = Property.getValueOrUndefined(
ellipsoid.minimumCone,
Iso8601.MINIMUM_VALUE,
);
options.maximumCone = Property.getValueOrUndefined(
ellipsoid.maximumCone,
Iso8601.MINIMUM_VALUE,
);
options.stackPartitions = Property.getValueOrUndefined(
ellipsoid.stackPartitions,
Iso8601.MINIMUM_VALUE,
);
options.slicePartitions = Property.getValueOrUndefined(
ellipsoid.slicePartitions,
Iso8601.MINIMUM_VALUE,
);
options.subdivisions = Property.getValueOrUndefined(
ellipsoid.subdivisions,
Iso8601.MINIMUM_VALUE,
);
options.offsetAttribute =
heightReference !== HeightReference.NONE
? GeometryOffsetAttribute.ALL
: undefined;
};
EllipsoidGeometryUpdater.prototype._onEntityPropertyChanged =
heightReferenceOnEntityPropertyChanged;
EllipsoidGeometryUpdater.DynamicGeometryUpdater =
DynamicEllipsoidGeometryUpdater;
/**
* @private
*/
function DynamicEllipsoidGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
this._scene = geometryUpdater._scene;
this._modelMatrix = new Matrix4();
this._attributes = undefined;
this._outlineAttributes = undefined;
this._lastSceneMode = undefined;
this._lastShow = undefined;
this._lastOutlineShow = undefined;
this._lastOutlineWidth = undefined;
this._lastOutlineColor = undefined;
this._lastOffset = new Cartesian3();
this._material = {};
}
if (defined(Object.create)) {
DynamicEllipsoidGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DynamicEllipsoidGeometryUpdater.prototype.constructor =
DynamicEllipsoidGeometryUpdater;
}
DynamicEllipsoidGeometryUpdater.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
const entity = this._entity;
const ellipsoid = entity.ellipsoid;
if (
!entity.isShowing ||
!entity.isAvailable(time) ||
!Property.getValueOrDefault(ellipsoid.show, time, true)
) {
if (defined(this._primitive)) {
this._primitive.show = false;
}
if (defined(this._outlinePrimitive)) {
this._outlinePrimitive.show = false;
}
return;
}
const radii = Property.getValueOrUndefined(
ellipsoid.radii,
time,
radiiScratch,
);
let modelMatrix = defined(radii)
? entity.computeModelMatrixForHeightReference(
time,
ellipsoid.heightReference,
radii.z * 0.5,
this._scene.ellipsoid,
this._modelMatrix,
)
: undefined;
if (!defined(modelMatrix) || !defined(radii)) {
if (defined(this._primitive)) {
this._primitive.show = false;
}
if (defined(this._outlinePrimitive)) {
this._outlinePrimitive.show = false;
}
return;
}
//Compute attributes and material.
const showFill = Property.getValueOrDefault(ellipsoid.fill, time, true);
const showOutline = Property.getValueOrDefault(
ellipsoid.outline,
time,
false,
);
const outlineColor = Property.getValueOrClonedDefault(
ellipsoid.outlineColor,
time,
Color.BLACK,
scratchColor,
);
const material = MaterialProperty.getValue(
time,
ellipsoid.material ?? defaultMaterial,
this._material,
);
// Check properties that could trigger a primitive rebuild.
const innerRadii = Property.getValueOrUndefined(
ellipsoid.innerRadii,
time,
innerRadiiScratch,
);
const minimumClock = Property.getValueOrUndefined(
ellipsoid.minimumClock,
time,
);
const maximumClock = Property.getValueOrUndefined(
ellipsoid.maximumClock,
time,
);
const minimumCone = Property.getValueOrUndefined(ellipsoid.minimumCone, time);
const maximumCone = Property.getValueOrUndefined(ellipsoid.maximumCone, time);
const stackPartitions = Property.getValueOrUndefined(
ellipsoid.stackPartitions,
time,
);
const slicePartitions = Property.getValueOrUndefined(
ellipsoid.slicePartitions,
time,
);
const subdivisions = Property.getValueOrUndefined(
ellipsoid.subdivisions,
time,
);
const outlineWidth = Property.getValueOrDefault(
ellipsoid.outlineWidth,
time,
1.0,
);
const heightReference = Property.getValueOrDefault(
ellipsoid.heightReference,
time,
HeightReference.NONE,
);
const offsetAttribute =
heightReference !== HeightReference.NONE
? GeometryOffsetAttribute.ALL
: undefined;
//In 3D we use a fast path by modifying Primitive.modelMatrix instead of regenerating the primitive every frame.
//Also check for height reference because this method doesn't work when the height is relative to terrain.
const sceneMode = this._scene.mode;
const in3D =
sceneMode === SceneMode.SCENE3D && heightReference === HeightReference.NONE;
const options = this._options;
const shadows = this._geometryUpdater.shadowsProperty.getValue(time);
const distanceDisplayConditionProperty =
this._geometryUpdater.distanceDisplayConditionProperty;
const distanceDisplayCondition =
distanceDisplayConditionProperty.getValue(time);
const offset = Property.getValueOrDefault(
this._geometryUpdater.terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
);
//We only rebuild the primitive if something other than the radii has changed
//For the radii, we use unit sphere and then deform it with a scale matrix.
const rebuildPrimitives =
!in3D ||
this._lastSceneMode !== sceneMode ||
!defined(this._primitive) || //
options.stackPartitions !== stackPartitions ||
options.slicePartitions !== slicePartitions || //
(defined(innerRadii) &&
!Cartesian3.equals(options.innerRadii !== innerRadii)) ||
options.minimumClock !== minimumClock || //
options.maximumClock !== maximumClock ||
options.minimumCone !== minimumCone || //
options.maximumCone !== maximumCone ||
options.subdivisions !== subdivisions || //
this._lastOutlineWidth !== outlineWidth ||
options.offsetAttribute !== offsetAttribute;
if (rebuildPrimitives) {
const primitives = this._primitives;
primitives.removeAndDestroy(this._primitive);
primitives.removeAndDestroy(this._outlinePrimitive);
this._primitive = undefined;
this._outlinePrimitive = undefined;
this._lastSceneMode = sceneMode;
this._lastOutlineWidth = outlineWidth;
options.stackPartitions = stackPartitions;
options.slicePartitions = slicePartitions;
options.subdivisions = subdivisions;
options.offsetAttribute = offsetAttribute;
options.radii = Cartesian3.clone(in3D ? unitSphere : radii, options.radii);
if (defined(innerRadii)) {
if (in3D) {
options.innerRadii = Cartesian3.fromElements(
innerRadii.x / radii.x,
innerRadii.y / radii.y,
innerRadii.z / radii.z,
options.innerRadii,
);
} else {
options.innerRadii = Cartesian3.clone(innerRadii, options.innerRadii);
}
} else {
options.innerRadii = undefined;
}
options.minimumClock = minimumClock;
options.maximumClock = maximumClock;
options.minimumCone = minimumCone;
options.maximumCone = maximumCone;
const appearance = new MaterialAppearance({
material: material,
translucent: material.isTranslucent(),
closed: true,
});
options.vertexFormat = appearance.vertexFormat;
const fillInstance = this._geometryUpdater.createFillGeometryInstance(
time,
in3D,
this._modelMatrix,
);
this._primitive = primitives.add(
new Primitive({
geometryInstances: fillInstance,
appearance: appearance,
asynchronous: false,
shadows: shadows,
}),
);
const outlineInstance = this._geometryUpdater.createOutlineGeometryInstance(
time,
in3D,
this._modelMatrix,
);
this._outlinePrimitive = primitives.add(
new Primitive({
geometryInstances: outlineInstance,
appearance: new PerInstanceColorAppearance({
flat: true,
translucent: outlineInstance.attributes.color.value[3] !== 255,
renderState: {
lineWidth:
this._geometryUpdater._scene.clampLineWidth(outlineWidth),
},
}),
asynchronous: false,
shadows: shadows,
}),
);
this._lastShow = showFill;
this._lastOutlineShow = showOutline;
this._lastOutlineColor = Color.clone(outlineColor, this._lastOutlineColor);
this._lastDistanceDisplayCondition = distanceDisplayCondition;
this._lastOffset = Cartesian3.clone(offset, this._lastOffset);
} else if (this._primitive.ready) {
//Update attributes only.
const primitive = this._primitive;
const outlinePrimitive = this._outlinePrimitive;
primitive.show = true;
outlinePrimitive.show = true;
primitive.appearance.material = material;
let attributes = this._attributes;
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(entity);
this._attributes = attributes;
}
if (showFill !== this._lastShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
showFill,
attributes.show,
);
this._lastShow = showFill;
}
let outlineAttributes = this._outlineAttributes;
if (!defined(outlineAttributes)) {
outlineAttributes =
outlinePrimitive.getGeometryInstanceAttributes(entity);
this._outlineAttributes = outlineAttributes;
}
if (showOutline !== this._lastOutlineShow) {
outlineAttributes.show = ShowGeometryInstanceAttribute.toValue(
showOutline,
outlineAttributes.show,
);
this._lastOutlineShow = showOutline;
}
if (!Color.equals(outlineColor, this._lastOutlineColor)) {
outlineAttributes.color = ColorGeometryInstanceAttribute.toValue(
outlineColor,
outlineAttributes.color,
);
Color.clone(outlineColor, this._lastOutlineColor);
}
if (
!DistanceDisplayCondition.equals(
distanceDisplayCondition,
this._lastDistanceDisplayCondition,
)
) {
attributes.distanceDisplayCondition =
DistanceDisplayConditionGeometryInstanceAttribute.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition,
);
outlineAttributes.distanceDisplayCondition =
DistanceDisplayConditionGeometryInstanceAttribute.toValue(
distanceDisplayCondition,
outlineAttributes.distanceDisplayCondition,
);
DistanceDisplayCondition.clone(
distanceDisplayCondition,
this._lastDistanceDisplayCondition,
);
}
if (!Cartesian3.equals(offset, this._lastOffset)) {
attributes.offset = OffsetGeometryInstanceAttribute.toValue(
offset,
attributes.offset,
);
outlineAttributes.offset = OffsetGeometryInstanceAttribute.toValue(
offset,
attributes.offset,
);
Cartesian3.clone(offset, this._lastOffset);
}
}
if (in3D) {
//Since we are scaling a unit sphere, we can't let any of the values go to zero.
//Instead we clamp them to a small value. To the naked eye, this produces the same results
//that you get passing EllipsoidGeometry a radii with a zero component.
radii.x = Math.max(radii.x, 0.001);
radii.y = Math.max(radii.y, 0.001);
radii.z = Math.max(radii.z, 0.001);
modelMatrix = Matrix4.multiplyByScale(modelMatrix, radii, modelMatrix);
this._primitive.modelMatrix = modelMatrix;
this._outlinePrimitive.modelMatrix = modelMatrix;
}
};
export default EllipsoidGeometryUpdater;
@@ -0,0 +1,312 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} EllipsoidGraphics.ConstructorOptions
*
* Initialization options for the EllipsoidGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the ellipsoid.
* @property {Property | Cartesian3} [radii] A {@link Cartesian3} Property specifying the radii of the ellipsoid.
* @property {Property | Cartesian3} [innerRadii] A {@link Cartesian3} Property specifying the inner radii of the ellipsoid.
* @property {Property | number} [minimumClock=0.0] A Property specifying the minimum clock angle of the ellipsoid.
* @property {Property | number} [maximumClock=2*PI] A Property specifying the maximum clock angle of the ellipsoid.
* @property {Property | number} [minimumCone=0.0] A Property specifying the minimum cone angle of the ellipsoid.
* @property {Property | number} [maximumCone=PI] A Property specifying the maximum cone angle of the ellipsoid.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height from the entity position is relative to.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the ellipsoid is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the ellipsoid.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the ellipsoid is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | number} [stackPartitions=64] A Property specifying the number of stacks.
* @property {Property | number} [slicePartitions=64] A Property specifying the number of radial slices.
* @property {Property | number} [subdivisions=128] A Property specifying the number of samples per outline ring, determining the granularity of the curvature.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the ellipsoid casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this ellipsoid will be displayed.
*/
/**
* Describe an ellipsoid or sphere. The center position and orientation are determined by the containing {@link Entity}.
*
* @alias EllipsoidGraphics
* @constructor
*
* @param {EllipsoidGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @demo {@link https://sandcastle.cesium.com/index.html?id=spheres-and-ellipsoids|Cesium Sandcastle Spheres and Ellipsoids Demo}
*/
function EllipsoidGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._radii = undefined;
this._radiiSubscription = undefined;
this._innerRadii = undefined;
this._innerRadiiSubscription = undefined;
this._minimumClock = undefined;
this._minimumClockSubscription = undefined;
this._maximumClock = undefined;
this._maximumClockSubscription = undefined;
this._minimumCone = undefined;
this._minimumConeSubscription = undefined;
this._maximumCone = undefined;
this._maximumConeSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._stackPartitions = undefined;
this._stackPartitionsSubscription = undefined;
this._slicePartitions = undefined;
this._slicePartitionsSubscription = undefined;
this._subdivisions = undefined;
this._subdivisionsSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(EllipsoidGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof EllipsoidGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the ellipsoid.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the {@link Cartesian3} {@link Property} specifying the radii of the ellipsoid.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
*/
radii: createPropertyDescriptor("radii"),
/**
* Gets or sets the {@link Cartesian3} {@link Property} specifying the inner radii of the ellipsoid.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default radii
*/
innerRadii: createPropertyDescriptor("innerRadii"),
/**
* Gets or sets the Property specifying the minimum clock angle of the ellipsoid.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
minimumClock: createPropertyDescriptor("minimumClock"),
/**
* Gets or sets the Property specifying the maximum clock angle of the ellipsoid.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default 2*PI
*/
maximumClock: createPropertyDescriptor("maximumClock"),
/**
* Gets or sets the Property specifying the minimum cone angle of the ellipsoid.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
minimumCone: createPropertyDescriptor("minimumCone"),
/**
* Gets or sets the Property specifying the maximum cone angle of the ellipsoid.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default PI
*/
maximumCone: createPropertyDescriptor("maximumCone"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the boolean Property specifying whether the ellipsoid is filled with the provided material.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the Property specifying the material used to fill the ellipsoid.
* @memberof EllipsoidGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying whether the ellipsoid is outlined.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Gets or sets the Property specifying the number of stacks.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default 64
*/
stackPartitions: createPropertyDescriptor("stackPartitions"),
/**
* Gets or sets the Property specifying the number of radial slices per 360 degrees.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default 64
*/
slicePartitions: createPropertyDescriptor("slicePartitions"),
/**
* Gets or sets the Property specifying the number of samples per outline ring, determining the granularity of the curvature.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default 128
*/
subdivisions: createPropertyDescriptor("subdivisions"),
/**
* Get or sets the enum Property specifying whether the ellipsoid
* casts or receives shadows from light sources.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this ellipsoid will be displayed.
* @memberof EllipsoidGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
});
/**
* Duplicates this instance.
*
* @param {EllipsoidGraphics} [result] The object onto which to store the result.
* @returns {EllipsoidGraphics} The modified result parameter or a new instance if one was not provided.
*/
EllipsoidGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new EllipsoidGraphics(this);
}
result.show = this.show;
result.radii = this.radii;
result.innerRadii = this.innerRadii;
result.minimumClock = this.minimumClock;
result.maximumClock = this.maximumClock;
result.minimumCone = this.minimumCone;
result.maximumCone = this.maximumCone;
result.heightReference = this.heightReference;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.stackPartitions = this.stackPartitions;
result.slicePartitions = this.slicePartitions;
result.subdivisions = this.subdivisions;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {EllipsoidGraphics} source The object to be merged into this object.
*/
EllipsoidGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.radii = this.radii ?? source.radii;
this.innerRadii = this.innerRadii ?? source.innerRadii;
this.minimumClock = this.minimumClock ?? source.minimumClock;
this.maximumClock = this.maximumClock ?? source.maximumClock;
this.minimumCone = this.minimumCone ?? source.minimumCone;
this.maximumCone = this.maximumCone ?? source.maximumCone;
this.heightReference = this.heightReference ?? source.heightReference;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.stackPartitions = this.stackPartitions ?? source.stackPartitions;
this.slicePartitions = this.slicePartitions ?? source.slicePartitions;
this.subdivisions = this.subdivisions ?? source.subdivisions;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
};
export default EllipsoidGraphics;
+789
View File
@@ -0,0 +1,789 @@
import Cartesian3 from "../Core/Cartesian3.js";
import Cartographic from "../Core/Cartographic.js";
import Check from "../Core/Check.js";
import createGuid from "../Core/createGuid.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import CesiumMath from "../Core/Math.js";
import Matrix3 from "../Core/Matrix3.js";
import Matrix4 from "../Core/Matrix4.js";
import Quaternion from "../Core/Quaternion.js";
import TrackingReferenceFrame from "../Core/TrackingReferenceFrame.js";
import Transforms from "../Core/Transforms.js";
import GroundPolylinePrimitive from "../Scene/GroundPolylinePrimitive.js";
import GroundPrimitive from "../Scene/GroundPrimitive.js";
import HeightReference, {
isHeightReferenceClamp,
} from "../Scene/HeightReference.js";
import BillboardGraphics from "./BillboardGraphics.js";
import BoxGraphics from "./BoxGraphics.js";
import ConstantPositionProperty from "./ConstantPositionProperty.js";
import CorridorGraphics from "./CorridorGraphics.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import createRawPropertyDescriptor from "./createRawPropertyDescriptor.js";
import CylinderGraphics from "./CylinderGraphics.js";
import EllipseGraphics from "./EllipseGraphics.js";
import EllipsoidGraphics from "./EllipsoidGraphics.js";
import LabelGraphics from "./LabelGraphics.js";
import ModelGraphics from "./ModelGraphics.js";
import Cesium3DTilesetGraphics from "./Cesium3DTilesetGraphics.js";
import PathGraphics from "./PathGraphics.js";
import PlaneGraphics from "./PlaneGraphics.js";
import PointGraphics from "./PointGraphics.js";
import PolygonGraphics from "./PolygonGraphics.js";
import PolylineGraphics from "./PolylineGraphics.js";
import PolylineVolumeGraphics from "./PolylineVolumeGraphics.js";
import Property from "./Property.js";
import PropertyBag from "./PropertyBag.js";
import RectangleGraphics from "./RectangleGraphics.js";
import WallGraphics from "./WallGraphics.js";
const cartoScratch = new Cartographic();
const ExtraPropertyNames = [];
function createConstantPositionProperty(value) {
return new ConstantPositionProperty(value);
}
function createPositionPropertyDescriptor(name) {
return createPropertyDescriptor(
name,
undefined,
createConstantPositionProperty,
);
}
function createPropertyTypeDescriptor(name, Type) {
return createPropertyDescriptor(name, undefined, function (value) {
if (value instanceof Type) {
return value;
}
return new Type(value);
});
}
/**
* @typedef {object} Entity.ConstructorOptions
*
* Initialization options for the Entity constructor
*
* @property {string} [id] A unique identifier for this object. If none is provided, a GUID is generated.
* @property {string} [name] A human readable name to display to users. It does not have to be unique.
* @property {TimeIntervalCollection} [availability] The availability, if any, associated with this object.
* @property {boolean} [show] A boolean value indicating if the entity and its children are displayed.
* @property {TrackingReferenceFrame} [trackingReferenceFrame=TrackingReferenceFrame.AUTODETECT] The reference frame used when this entity is being tracked. <br/> If <code>undefined</code>, reference frame is determined based on entity velocity: near-surface slow moving entities are tracked using the local east-north-up reference frame, whereas fast moving entities such as satellites are tracked using VVLH (Vehicle Velocity, Local Horizontal).
* @property {Property | string} [description] A string Property specifying an HTML description for this entity.
* @property {PositionProperty | Cartesian3 | CallbackPositionProperty} [position] A Property specifying the entity position.
* @property {Property | Quaternion} [orientation=Transforms.eastNorthUpToFixedFrame(position)] A Property specifying the entity orientation in respect to Earth-fixed-Earth-centered (ECEF). If undefined, east-north-up at entity position is used.
* @property {Property | Cartesian3} [viewFrom] A suggested initial offset for viewing this object.
* @property {Entity} [parent] A parent entity to associate with this entity.
* @property {BillboardGraphics | BillboardGraphics.ConstructorOptions} [billboard] A billboard to associate with this entity.
* @property {BoxGraphics | BoxGraphics.ConstructorOptions} [box] A box to associate with this entity.
* @property {CorridorGraphics | CorridorGraphics.ConstructorOptions} [corridor] A corridor to associate with this entity.
* @property {CylinderGraphics | CylinderGraphics.ConstructorOptions} [cylinder] A cylinder to associate with this entity.
* @property {EllipseGraphics | EllipseGraphics.ConstructorOptions} [ellipse] A ellipse to associate with this entity.
* @property {EllipsoidGraphics | EllipsoidGraphics.ConstructorOptions} [ellipsoid] A ellipsoid to associate with this entity.
* @property {LabelGraphics | LabelGraphics.ConstructorOptions} [label] A options.label to associate with this entity.
* @property {ModelGraphics | ModelGraphics.ConstructorOptions} [model] A model to associate with this entity.
* @property {Cesium3DTilesetGraphics | Cesium3DTilesetGraphics.ConstructorOptions} [tileset] A 3D Tiles tileset to associate with this entity.
* @property {PathGraphics | PathGraphics.ConstructorOptions} [path] A path to associate with this entity.
* @property {PlaneGraphics | PlaneGraphics.ConstructorOptions} [plane] A plane to associate with this entity.
* @property {PointGraphics | PointGraphics.ConstructorOptions} [point] A point to associate with this entity.
* @property {PolygonGraphics | PolygonGraphics.ConstructorOptions} [polygon] A polygon to associate with this entity.
* @property {PolylineGraphics | PolylineGraphics.ConstructorOptions} [polyline] A polyline to associate with this entity.
* @property {PropertyBag | Object<string,*>} [properties] Arbitrary properties to associate with this entity.
* @property {PolylineVolumeGraphics | PolylineVolumeGraphics.ConstructorOptions} [polylineVolume] A polylineVolume to associate with this entity.
* @property {RectangleGraphics | RectangleGraphics.ConstructorOptions} [rectangle] A rectangle to associate with this entity.
* @property {WallGraphics | WallGraphics.ConstructorOptions} [wall] A wall to associate with this entity.
*/
/**
* Entity instances aggregate multiple forms of visualization into a single high-level object.
* They can be created manually and added to {@link Viewer#entities} or be produced by
* data sources, such as {@link CzmlDataSource} and {@link GeoJsonDataSource}.
* @alias Entity
* @constructor
*
* @param {Entity.ConstructorOptions} [options] Object describing initialization options
*
* @see {@link https://cesium.com/learn/cesiumjs-learn/cesiumjs-creating-entities/|Creating Entities}
*/
function Entity(options) {
options = options ?? Frozen.EMPTY_OBJECT;
let id = options.id;
if (!defined(id)) {
id = createGuid();
}
this._availability = undefined;
this._id = id;
this._definitionChanged = new Event();
this._name = options.name;
this._show = options.show ?? true;
this._trackingReferenceFrame =
options.trackingReferenceFrame ?? TrackingReferenceFrame.AUTODETECT;
this._parent = undefined;
this._propertyNames = [
"billboard",
"box",
"corridor",
"cylinder",
"description",
"ellipse",
"ellipsoid",
"label",
"model",
"tileset",
"orientation",
"path",
"plane",
"point",
"polygon",
"polyline",
"polylineVolume",
"position",
"properties",
"rectangle",
"viewFrom",
"wall",
...ExtraPropertyNames,
];
this._billboard = undefined;
this._billboardSubscription = undefined;
this._box = undefined;
this._boxSubscription = undefined;
this._corridor = undefined;
this._corridorSubscription = undefined;
this._cylinder = undefined;
this._cylinderSubscription = undefined;
this._description = undefined;
this._descriptionSubscription = undefined;
this._ellipse = undefined;
this._ellipseSubscription = undefined;
this._ellipsoid = undefined;
this._ellipsoidSubscription = undefined;
this._label = undefined;
this._labelSubscription = undefined;
this._model = undefined;
this._modelSubscription = undefined;
this._tileset = undefined;
this._tilesetSubscription = undefined;
this._orientation = undefined;
this._orientationSubscription = undefined;
this._path = undefined;
this._pathSubscription = undefined;
this._plane = undefined;
this._planeSubscription = undefined;
this._point = undefined;
this._pointSubscription = undefined;
this._polygon = undefined;
this._polygonSubscription = undefined;
this._polyline = undefined;
this._polylineSubscription = undefined;
this._polylineVolume = undefined;
this._polylineVolumeSubscription = undefined;
this._position = undefined;
this._positionSubscription = undefined;
this._properties = undefined;
this._propertiesSubscription = undefined;
this._rectangle = undefined;
this._rectangleSubscription = undefined;
this._viewFrom = undefined;
this._viewFromSubscription = undefined;
this._wall = undefined;
this._wallSubscription = undefined;
this._children = [];
/**
* Gets or sets the entity collection that this entity belongs to.
* @type {EntityCollection}
*/
this.entityCollection = undefined;
this.parent = options.parent;
this.merge(options);
}
function updateShow(entity, children, isShowing) {
const length = children.length;
for (let i = 0; i < length; i++) {
const child = children[i];
const childShow = child._show;
const oldValue = !isShowing && childShow;
const newValue = isShowing && childShow;
if (oldValue !== newValue) {
updateShow(child, child._children, isShowing);
}
}
entity._definitionChanged.raiseEvent(
entity,
"isShowing",
isShowing,
!isShowing,
);
}
Object.defineProperties(Entity.prototype, {
/**
* The availability, if any, associated with this object.
* If availability is undefined, it is assumed that this object's
* other properties will return valid data for any provided time.
* If availability exists, the objects other properties will only
* provide valid data if queried within the given interval.
* @memberof Entity.prototype
* @type {TimeIntervalCollection|undefined}
*/
availability: createRawPropertyDescriptor("availability"),
/**
* Gets the unique ID associated with this object.
* @memberof Entity.prototype
* @type {string}
*/
id: {
get: function () {
return this._id;
},
},
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof Entity.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the name of the object. The name is intended for end-user
* consumption and does not need to be unique.
* @memberof Entity.prototype
* @type {string|undefined}
*/
name: createRawPropertyDescriptor("name"),
/**
* Gets or sets whether this entity should be displayed. When set to true,
* the entity is only displayed if the parent entity's show property is also true.
* @memberof Entity.prototype
* @type {boolean}
*/
show: {
get: function () {
return this._show;
},
set: function (value) {
//>>includeStart('debug', pragmas.debug);
if (!defined(value)) {
throw new DeveloperError("value is required.");
}
//>>includeEnd('debug');
if (value === this._show) {
return;
}
const wasShowing = this.isShowing;
this._show = value;
const isShowing = this.isShowing;
if (wasShowing !== isShowing) {
updateShow(this, this._children, isShowing);
}
this._definitionChanged.raiseEvent(this, "show", value, !value);
},
},
/**
* Gets or sets the entity's tracking reference frame.
* @demo {@link https://sandcastle.cesium.com/index.html?id=entity-tracking|Cesium Sandcastle Entity tracking Demo}
*
* @memberof Entity.prototype
* @type {TrackingReferenceFrame}
*/
trackingReferenceFrame: createRawPropertyDescriptor("trackingReferenceFrame"),
/**
* Gets whether this entity is being displayed, taking into account
* the visibility of any ancestor entities.
* @memberof Entity.prototype
* @type {boolean}
*/
isShowing: {
get: function () {
return (
this._show &&
(!defined(this.entityCollection) || this.entityCollection.show) &&
(!defined(this._parent) || this._parent.isShowing)
);
},
},
/**
* Gets or sets the parent object.
* @memberof Entity.prototype
* @type {Entity|undefined}
*/
parent: {
get: function () {
return this._parent;
},
set: function (value) {
const oldValue = this._parent;
if (oldValue === value) {
return;
}
const wasShowing = this.isShowing;
if (defined(oldValue)) {
const index = oldValue._children.indexOf(this);
oldValue._children.splice(index, 1);
}
this._parent = value;
if (defined(value)) {
value._children.push(this);
}
const isShowing = this.isShowing;
if (wasShowing !== isShowing) {
updateShow(this, this._children, isShowing);
}
this._definitionChanged.raiseEvent(this, "parent", value, oldValue);
},
},
/**
* Gets the names of all properties registered on this instance.
* @memberof Entity.prototype
* @type {string[]}
*/
propertyNames: {
get: function () {
return this._propertyNames;
},
},
/**
* Gets or sets the billboard.
* @memberof Entity.prototype
* @type {BillboardGraphics|undefined}
*/
billboard: createPropertyTypeDescriptor("billboard", BillboardGraphics),
/**
* Gets or sets the box.
* @memberof Entity.prototype
* @type {BoxGraphics|undefined}
*/
box: createPropertyTypeDescriptor("box", BoxGraphics),
/**
* Gets or sets the corridor.
* @memberof Entity.prototype
* @type {CorridorGraphics|undefined}
*/
corridor: createPropertyTypeDescriptor("corridor", CorridorGraphics),
/**
* Gets or sets the cylinder.
* @memberof Entity.prototype
* @type {CylinderGraphics|undefined}
*/
cylinder: createPropertyTypeDescriptor("cylinder", CylinderGraphics),
/**
* Gets or sets the description.
* @memberof Entity.prototype
* @type {Property|undefined}
*/
description: createPropertyDescriptor("description"),
/**
* Gets or sets the ellipse.
* @memberof Entity.prototype
* @type {EllipseGraphics|undefined}
*/
ellipse: createPropertyTypeDescriptor("ellipse", EllipseGraphics),
/**
* Gets or sets the ellipsoid.
* @memberof Entity.prototype
* @type {EllipsoidGraphics|undefined}
*/
ellipsoid: createPropertyTypeDescriptor("ellipsoid", EllipsoidGraphics),
/**
* Gets or sets the label.
* @memberof Entity.prototype
* @type {LabelGraphics|undefined}
*/
label: createPropertyTypeDescriptor("label", LabelGraphics),
/**
* Gets or sets the model.
* @memberof Entity.prototype
* @type {ModelGraphics|undefined}
*/
model: createPropertyTypeDescriptor("model", ModelGraphics),
/**
* Gets or sets the tileset.
* @memberof Entity.prototype
* @type {Cesium3DTilesetGraphics|undefined}
*/
tileset: createPropertyTypeDescriptor("tileset", Cesium3DTilesetGraphics),
/**
* Gets or sets the orientation in respect to Earth-fixed-Earth-centered (ECEF).
* Defaults to east-north-up at entity position.
* @memberof Entity.prototype
* @type {Property|undefined}
*/
orientation: createPropertyDescriptor("orientation"),
/**
* Gets or sets the path.
* @memberof Entity.prototype
* @type {PathGraphics|undefined}
*/
path: createPropertyTypeDescriptor("path", PathGraphics),
/**
* Gets or sets the plane.
* @memberof Entity.prototype
* @type {PlaneGraphics|undefined}
*/
plane: createPropertyTypeDescriptor("plane", PlaneGraphics),
/**
* Gets or sets the point graphic.
* @memberof Entity.prototype
* @type {PointGraphics|undefined}
*/
point: createPropertyTypeDescriptor("point", PointGraphics),
/**
* Gets or sets the polygon.
* @memberof Entity.prototype
* @type {PolygonGraphics|undefined}
*/
polygon: createPropertyTypeDescriptor("polygon", PolygonGraphics),
/**
* Gets or sets the polyline.
* @memberof Entity.prototype
* @type {PolylineGraphics|undefined}
*/
polyline: createPropertyTypeDescriptor("polyline", PolylineGraphics),
/**
* Gets or sets the polyline volume.
* @memberof Entity.prototype
* @type {PolylineVolumeGraphics|undefined}
*/
polylineVolume: createPropertyTypeDescriptor(
"polylineVolume",
PolylineVolumeGraphics,
),
/**
* Gets or sets the bag of arbitrary properties associated with this entity.
* @memberof Entity.prototype
* @type {PropertyBag|undefined}
*/
properties: createPropertyTypeDescriptor("properties", PropertyBag),
/**
* Gets or sets the position.
* @memberof Entity.prototype
* @type {PositionProperty|undefined}
*/
position: createPositionPropertyDescriptor("position"),
/**
* Gets or sets the rectangle.
* @memberof Entity.prototype
* @type {RectangleGraphics|undefined}
*/
rectangle: createPropertyTypeDescriptor("rectangle", RectangleGraphics),
/**
* Gets or sets the suggested initial offset when tracking this object.
* The offset is typically defined in the east-north-up reference frame,
* but may be another frame depending on the object's velocity.
* @memberof Entity.prototype
* @type {Property|undefined}
*/
viewFrom: createPropertyDescriptor("viewFrom"),
/**
* Gets or sets the wall.
* @memberof Entity.prototype
* @type {WallGraphics|undefined}
*/
wall: createPropertyTypeDescriptor("wall", WallGraphics),
});
/**
* Add the specified type and construct the properties for it in the Entity class
* @private
* @param {string} propertyName name of the property that controls/accesses this entity type
* @param {{ constructor: function }} Type The Graphics class to associate with this entity type
*/
Entity.registerEntityType = function (propertyName, Type) {
Object.defineProperties(Entity.prototype, {
[propertyName]: createPropertyTypeDescriptor(propertyName, Type),
});
if (!ExtraPropertyNames.includes(propertyName)) {
ExtraPropertyNames.push(propertyName);
}
};
/**
* Given a time, returns true if this object should have data during that time.
*
* @param {JulianDate} time The time to check availability for.
* @returns {boolean} true if the object should have data during the provided time, false otherwise.
*/
Entity.prototype.isAvailable = function (time) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
//>>includeEnd('debug');
const availability = this._availability;
return !defined(availability) || availability.contains(time);
};
/**
* Adds a property to this object. Once a property is added, it can be
* observed with {@link Entity#definitionChanged} and composited
* with {@link CompositeEntityCollection}
*
* @param {string} propertyName The name of the property to add.
*
* @exception {DeveloperError} "propertyName" is a reserved property name.
* @exception {DeveloperError} "propertyName" is already a registered property.
*/
Entity.prototype.addProperty = function (propertyName) {
const propertyNames = this._propertyNames;
//>>includeStart('debug', pragmas.debug);
if (!defined(propertyName)) {
throw new DeveloperError("propertyName is required.");
}
if (propertyNames.indexOf(propertyName) !== -1) {
throw new DeveloperError(
`${propertyName} is already a registered property.`,
);
}
if (propertyName in this) {
throw new DeveloperError(`${propertyName} is a reserved property name.`);
}
//>>includeEnd('debug');
propertyNames.push(propertyName);
Object.defineProperty(
this,
propertyName,
createRawPropertyDescriptor(propertyName, true),
);
};
/**
* Removed a property previously added with addProperty.
*
* @param {string} propertyName The name of the property to remove.
*
* @exception {DeveloperError} "propertyName" is a reserved property name.
* @exception {DeveloperError} "propertyName" is not a registered property.
*/
Entity.prototype.removeProperty = function (propertyName) {
const propertyNames = this._propertyNames;
const index = propertyNames.indexOf(propertyName);
//>>includeStart('debug', pragmas.debug);
if (!defined(propertyName)) {
throw new DeveloperError("propertyName is required.");
}
if (index === -1) {
throw new DeveloperError(`${propertyName} is not a registered property.`);
}
//>>includeEnd('debug');
this._propertyNames.splice(index, 1);
delete this[propertyName];
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {Entity} source The object to be merged into this object.
*/
Entity.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
//Name, show, and availability are not Property objects and are currently handled differently.
//source.show is intentionally ignored because this.show always has a value.
this.name = this.name ?? source.name;
this.availability = this.availability ?? source.availability;
const propertyNames = this._propertyNames;
const sourcePropertyNames = defined(source._propertyNames)
? source._propertyNames
: Object.keys(source);
const propertyNamesLength = sourcePropertyNames.length;
for (let i = 0; i < propertyNamesLength; i++) {
const name = sourcePropertyNames[i];
//While source is required by the API to be an Entity, we internally call this method from the
//constructor with an options object to configure initial custom properties.
//So we need to ignore reserved-non-property.
if (
name === "parent" ||
name === "name" ||
name === "availability" ||
name === "children"
) {
continue;
}
const targetProperty = this[name];
const sourceProperty = source[name];
//Custom properties that are registered on the source entity must also
//get registered on this entity.
if (!defined(targetProperty) && propertyNames.indexOf(name) === -1) {
this.addProperty(name);
}
if (defined(sourceProperty)) {
if (defined(targetProperty)) {
if (defined(targetProperty.merge)) {
targetProperty.merge(sourceProperty);
}
} else if (
defined(sourceProperty.merge) &&
defined(sourceProperty.clone)
) {
this[name] = sourceProperty.clone();
} else {
this[name] = sourceProperty;
}
}
}
};
const matrix3Scratch = new Matrix3();
const positionScratch = new Cartesian3();
const orientationScratch = new Quaternion();
/**
* Computes the model matrix for the entity's transform at specified time. Returns undefined if position is undefined
*
* @param {JulianDate} time The time to retrieve model matrix for.
* @param {Matrix4} [result] The object onto which to store the result.
*
* @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. Result is undefined if position is undefined.
*/
Entity.prototype.computeModelMatrix = function (time, result) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.object("time", time);
//>>includeEnd('debug');
const position = Property.getValueOrUndefined(
this._position,
time,
positionScratch,
);
if (!defined(position)) {
return undefined;
}
const orientation = Property.getValueOrUndefined(
this._orientation,
time,
orientationScratch,
);
if (!defined(orientation)) {
result = Transforms.eastNorthUpToFixedFrame(position, undefined, result);
} else {
result = Matrix4.fromRotationTranslation(
Matrix3.fromQuaternion(orientation, matrix3Scratch),
position,
result,
);
}
return result;
};
/**
* @private
*/
Entity.prototype.computeModelMatrixForHeightReference = function (
time,
heightReferenceProperty,
heightOffset,
ellipsoid,
result,
) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.object("time", time);
//>>includeEnd('debug');
const heightReference = Property.getValueOrDefault(
heightReferenceProperty,
time,
HeightReference.NONE,
);
let position = Property.getValueOrUndefined(
this._position,
time,
positionScratch,
);
if (
heightReference === HeightReference.NONE ||
!defined(position) ||
Cartesian3.equalsEpsilon(position, Cartesian3.ZERO, CesiumMath.EPSILON8)
) {
return this.computeModelMatrix(time, result);
}
const carto = ellipsoid.cartesianToCartographic(position, cartoScratch);
if (isHeightReferenceClamp(heightReference)) {
carto.height = heightOffset;
} else {
carto.height += heightOffset;
}
position = ellipsoid.cartographicToCartesian(carto, position);
const orientation = Property.getValueOrUndefined(
this._orientation,
time,
orientationScratch,
);
if (!defined(orientation)) {
result = Transforms.eastNorthUpToFixedFrame(position, undefined, result);
} else {
result = Matrix4.fromRotationTranslation(
Matrix3.fromQuaternion(orientation, matrix3Scratch),
position,
result,
);
}
return result;
};
/**
* Checks if the given Scene supports materials besides Color on Entities draped on terrain or 3D Tiles.
* If this feature is not supported, Entities with non-color materials but no `height` will
* instead be rendered as if height is 0.
*
* @param {Scene} scene The current scene.
* @returns {boolean} Whether or not the current scene supports materials for entities on terrain.
*/
Entity.supportsMaterialsforEntitiesOnTerrain = function (scene) {
return GroundPrimitive.supportsMaterials(scene);
};
/**
* Checks if the given Scene supports polylines clamped to terrain or 3D Tiles.
* If this feature is not supported, Entities with PolylineGraphics will be rendered with vertices at
* the provided heights and using the `arcType` parameter instead of clamped to the ground.
*
* @param {Scene} scene The current scene.
* @returns {boolean} Whether or not the current scene supports polylines on terrain or 3D TIles.
*/
Entity.supportsPolylinesOnTerrain = function (scene) {
return GroundPolylinePrimitive.isSupported(scene);
};
export default Entity;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,439 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import createGuid from "../Core/createGuid.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import Iso8601 from "../Core/Iso8601.js";
import JulianDate from "../Core/JulianDate.js";
import TimeInterval from "../Core/TimeInterval.js";
import Entity from "./Entity.js";
const entityOptionsScratch = {
id: undefined,
};
function fireChangedEvent(collection) {
if (collection._firing) {
collection._refire = true;
return;
}
if (collection._suspendCount === 0) {
const added = collection._addedEntities;
const removed = collection._removedEntities;
const changed = collection._changedEntities;
if (changed.length !== 0 || added.length !== 0 || removed.length !== 0) {
collection._firing = true;
do {
collection._refire = false;
const addedArray = added.values.slice(0);
const removedArray = removed.values.slice(0);
const changedArray = changed.values.slice(0);
added.removeAll();
removed.removeAll();
changed.removeAll();
collection._collectionChanged.raiseEvent(
collection,
addedArray,
removedArray,
changedArray,
);
} while (collection._refire);
collection._firing = false;
}
}
}
/**
* An observable collection of {@link Entity} instances where each entity has a unique id.
* @alias EntityCollection
* @constructor
*
* @param {DataSource|CompositeEntityCollection} [owner] The data source (or composite entity collection) which created this collection.
*/
function EntityCollection(owner) {
this._owner = owner;
this._entities = new AssociativeArray();
this._addedEntities = new AssociativeArray();
this._removedEntities = new AssociativeArray();
this._changedEntities = new AssociativeArray();
this._suspendCount = 0;
this._collectionChanged = new Event();
this._id = createGuid();
this._show = true;
this._firing = false;
this._refire = false;
}
/**
* Prevents {@link EntityCollection#collectionChanged} events from being raised
* until a corresponding call is made to {@link EntityCollection#resumeEvents}, at which
* point a single event will be raised that covers all suspended operations.
* This allows for many items to be added and removed efficiently.
* This function can be safely called multiple times as long as there
* are corresponding calls to {@link EntityCollection#resumeEvents}.
*/
EntityCollection.prototype.suspendEvents = function () {
this._suspendCount++;
};
/**
* Resumes raising {@link EntityCollection#collectionChanged} events immediately
* when an item is added or removed. Any modifications made while while events were suspended
* will be triggered as a single event when this function is called.
* This function is reference counted and can safely be called multiple times as long as there
* are corresponding calls to {@link EntityCollection#resumeEvents}.
*
* @exception {DeveloperError} resumeEvents can not be called before suspendEvents.
*/
EntityCollection.prototype.resumeEvents = function () {
//>>includeStart('debug', pragmas.debug);
if (this._suspendCount === 0) {
throw new DeveloperError(
"resumeEvents can not be called before suspendEvents.",
);
}
//>>includeEnd('debug');
this._suspendCount--;
fireChangedEvent(this);
};
/**
* The signature of the event generated by {@link EntityCollection#collectionChanged}.
* @callback EntityCollection.CollectionChangedEventCallback
*
* @param {EntityCollection} collection The collection that triggered the event.
* @param {Entity[]} added The array of {@link Entity} instances that have been added to the collection.
* @param {Entity[]} removed The array of {@link Entity} instances that have been removed from the collection.
* @param {Entity[]} changed The array of {@link Entity} instances that have been modified.
*/
Object.defineProperties(EntityCollection.prototype, {
/**
* Gets the event that is fired when entities are added or removed from the collection.
* The generated event is a {@link EntityCollection.CollectionChangedEventCallback}.
* @memberof EntityCollection.prototype
* @readonly
* @type {Event<EntityCollection.CollectionChangedEventCallback>}
*/
collectionChanged: {
get: function () {
return this._collectionChanged;
},
},
/**
* Gets a globally unique identifier for this collection.
* @memberof EntityCollection.prototype
* @readonly
* @type {string}
*/
id: {
get: function () {
return this._id;
},
},
/**
* Gets the array of Entity instances in the collection.
* This array should not be modified directly.
* @memberof EntityCollection.prototype
* @readonly
* @type {Entity[]}
*/
values: {
get: function () {
return this._entities.values;
},
},
/**
* Gets whether or not this entity collection should be
* displayed. When true, each entity is only displayed if
* its own show property is also true.
* @memberof EntityCollection.prototype
* @type {boolean}
*/
show: {
get: function () {
return this._show;
},
set: function (value) {
//>>includeStart('debug', pragmas.debug);
if (!defined(value)) {
throw new DeveloperError("value is required.");
}
//>>includeEnd('debug');
if (value === this._show) {
return;
}
//Since entity.isShowing includes the EntityCollection.show state
//in its calculation, we need to loop over the entities array
//twice, once to get the old showing value and a second time
//to raise the changed event.
this.suspendEvents();
let i;
const oldShows = [];
const entities = this._entities.values;
const entitiesLength = entities.length;
for (i = 0; i < entitiesLength; i++) {
oldShows.push(entities[i].isShowing);
}
this._show = value;
for (i = 0; i < entitiesLength; i++) {
const oldShow = oldShows[i];
const entity = entities[i];
if (oldShow !== entity.isShowing) {
entity.definitionChanged.raiseEvent(
entity,
"isShowing",
entity.isShowing,
oldShow,
);
}
}
this.resumeEvents();
},
},
/**
* Gets the owner of this entity collection, ie. the data source or composite entity collection which created it.
* @memberof EntityCollection.prototype
* @readonly
* @type {DataSource|CompositeEntityCollection}
*/
owner: {
get: function () {
return this._owner;
},
},
});
/**
* Computes the maximum availability of the entities in the collection.
* If the collection contains a mix of infinitely available data and non-infinite data,
* it will return the interval pertaining to the non-infinite data only. If all
* data is infinite, an infinite interval will be returned.
*
* @returns {TimeInterval} The availability of entities in the collection.
*/
EntityCollection.prototype.computeAvailability = function () {
let startTime = Iso8601.MAXIMUM_VALUE;
let stopTime = Iso8601.MINIMUM_VALUE;
const entities = this._entities.values;
for (let i = 0, len = entities.length; i < len; i++) {
const entity = entities[i];
const availability = entity.availability;
if (defined(availability)) {
const start = availability.start;
const stop = availability.stop;
if (
JulianDate.lessThan(start, startTime) &&
!start.equals(Iso8601.MINIMUM_VALUE)
) {
startTime = start;
}
if (
JulianDate.greaterThan(stop, stopTime) &&
!stop.equals(Iso8601.MAXIMUM_VALUE)
) {
stopTime = stop;
}
}
}
if (Iso8601.MAXIMUM_VALUE.equals(startTime)) {
startTime = Iso8601.MINIMUM_VALUE;
}
if (Iso8601.MINIMUM_VALUE.equals(stopTime)) {
stopTime = Iso8601.MAXIMUM_VALUE;
}
return new TimeInterval({
start: startTime,
stop: stopTime,
});
};
/**
* Add an entity to the collection.
*
* @param {Entity | Entity.ConstructorOptions} entity The entity to be added.
* @returns {Entity} The entity that was added.
* @exception {DeveloperError} An entity with <entity.id> already exists in this collection.
*/
EntityCollection.prototype.add = function (entity) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entity)) {
throw new DeveloperError("entity is required.");
}
//>>includeEnd('debug');
if (!(entity instanceof Entity)) {
entity = new Entity(entity);
}
const id = entity.id;
const entities = this._entities;
if (entities.contains(id)) {
throw new DeveloperError(
`An entity with id ${id} already exists in this collection.`,
);
}
entity.entityCollection = this;
entities.set(id, entity);
if (!this._removedEntities.remove(id)) {
this._addedEntities.set(id, entity);
}
entity.definitionChanged.addEventListener(
EntityCollection.prototype._onEntityDefinitionChanged,
this,
);
fireChangedEvent(this);
return entity;
};
/**
* Removes an entity from the collection.
*
* @param {Entity} entity The entity to be removed.
* @returns {boolean} true if the item was removed, false if it did not exist in the collection.
*/
EntityCollection.prototype.remove = function (entity) {
if (!defined(entity)) {
return false;
}
return this.removeById(entity.id);
};
/**
* Returns true if the provided entity is in this collection, false otherwise.
*
* @param {Entity} entity The entity.
* @returns {boolean} true if the provided entity is in this collection, false otherwise.
*/
EntityCollection.prototype.contains = function (entity) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entity)) {
throw new DeveloperError("entity is required");
}
//>>includeEnd('debug');
return this._entities.get(entity.id) === entity;
};
/**
* Removes an entity with the provided id from the collection.
*
* @param {string} id The id of the entity to remove.
* @returns {boolean} true if the item was removed, false if no item with the provided id existed in the collection.
*/
EntityCollection.prototype.removeById = function (id) {
if (!defined(id)) {
return false;
}
const entities = this._entities;
const entity = entities.get(id);
if (!this._entities.remove(id)) {
return false;
}
if (!this._addedEntities.remove(id)) {
this._removedEntities.set(id, entity);
this._changedEntities.remove(id);
}
this._entities.remove(id);
entity.definitionChanged.removeEventListener(
EntityCollection.prototype._onEntityDefinitionChanged,
this,
);
fireChangedEvent(this);
return true;
};
/**
* Removes all Entities from the collection.
*/
EntityCollection.prototype.removeAll = function () {
//The event should only contain items added before events were suspended
//and the contents of the collection.
const entities = this._entities;
const entitiesLength = entities.length;
const array = entities.values;
const addedEntities = this._addedEntities;
const removed = this._removedEntities;
for (let i = 0; i < entitiesLength; i++) {
const existingItem = array[i];
const existingItemId = existingItem.id;
const addedItem = addedEntities.get(existingItemId);
if (!defined(addedItem)) {
existingItem.definitionChanged.removeEventListener(
EntityCollection.prototype._onEntityDefinitionChanged,
this,
);
removed.set(existingItemId, existingItem);
}
}
entities.removeAll();
addedEntities.removeAll();
this._changedEntities.removeAll();
fireChangedEvent(this);
};
/**
* Gets an entity with the specified id.
*
* @param {string} id The id of the entity to retrieve.
* @returns {Entity|undefined} The entity with the provided id or undefined if the id did not exist in the collection.
*/
EntityCollection.prototype.getById = function (id) {
//>>includeStart('debug', pragmas.debug);
if (!defined(id)) {
throw new DeveloperError("id is required.");
}
//>>includeEnd('debug');
return this._entities.get(id);
};
/**
* Gets an entity with the specified id or creates it and adds it to the collection if it does not exist.
*
* @param {string} id The id of the entity to retrieve or create.
* @returns {Entity} The new or existing object.
*/
EntityCollection.prototype.getOrCreateEntity = function (id) {
//>>includeStart('debug', pragmas.debug);
if (!defined(id)) {
throw new DeveloperError("id is required.");
}
//>>includeEnd('debug');
let entity = this._entities.get(id);
if (!defined(entity)) {
entityOptionsScratch.id = id;
entity = new Entity(entityOptionsScratch);
this.add(entity);
}
return entity;
};
EntityCollection.prototype._onEntityDefinitionChanged = function (entity) {
const id = entity.id;
if (!this._addedEntities.contains(id)) {
this._changedEntities.set(id, entity);
}
fireChangedEvent(this);
};
export default EntityCollection;
+476
View File
@@ -0,0 +1,476 @@
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import HeadingPitchRange from "../Core/HeadingPitchRange.js";
import JulianDate from "../Core/JulianDate.js";
import CesiumMath from "../Core/Math.js";
import Matrix3 from "../Core/Matrix3.js";
import Matrix4 from "../Core/Matrix4.js";
import Quaternion from "../Core/Quaternion.js";
import TrackingReferenceFrame from "../Core/TrackingReferenceFrame.js";
import Transforms from "../Core/Transforms.js";
import SceneMode from "../Scene/SceneMode.js";
import VelocityVectorProperty from "./VelocityVectorProperty.js";
const updateTransformMatrix3Scratch1 = new Matrix3();
const updateTransformMatrix3Scratch2 = new Matrix3();
const updateTransformMatrix3Scratch3 = new Matrix3();
const updateTransformMatrix4Scratch = new Matrix4();
const updateTransformCartesian3Scratch1 = new Cartesian3();
const updateTransformCartesian3Scratch2 = new Cartesian3();
const updateTransformCartesian3Scratch3 = new Cartesian3();
const updateTransformCartesian3Scratch4 = new Cartesian3();
const updateTransformCartesian3Scratch5 = new Cartesian3();
const updateTransformCartesian3Scratch6 = new Cartesian3();
const updateTransformOrientationScratch = new Quaternion();
const velocityScratch = new Cartesian3();
const rotationScratch = new Matrix3();
const deltaTime = new JulianDate();
const northUpAxisFactor = 1.25; // times ellipsoid's maximum radius
function updateTransform(
that,
camera,
updateLookAt,
saveCamera,
positionProperty,
velocityProperty,
orientationProperty,
trackingReferenceFrame,
time,
ellipsoid,
) {
const mode = that.scene.mode;
let cartesian = positionProperty.getValue(time, that._lastCartesian);
if (defined(cartesian)) {
let hasBasis = false;
let invertVelocity = false;
let xBasis;
let yBasis;
let zBasis;
if (mode === SceneMode.SCENE3D) {
// The time delta was determined based on how fast satellites move compared to vehicles near the surface.
// Slower moving vehicles will most likely default to east-north-up, while faster ones will be VVLH.
JulianDate.addSeconds(time, 0.001, deltaTime);
let deltaCartesian = positionProperty.getValue(
deltaTime,
updateTransformCartesian3Scratch1,
);
// If no valid position at (time + 0.001), sample at (time - 0.001) and invert the vector
if (!defined(deltaCartesian)) {
JulianDate.addSeconds(time, -0.001, deltaTime);
deltaCartesian = positionProperty.getValue(
deltaTime,
updateTransformCartesian3Scratch1,
);
invertVelocity = true;
}
if (defined(deltaCartesian)) {
let toInertial = Transforms.computeFixedToIcrfMatrix(
time,
updateTransformMatrix3Scratch1,
);
let toInertialDelta = Transforms.computeFixedToIcrfMatrix(
deltaTime,
updateTransformMatrix3Scratch2,
);
let toFixed;
if (!defined(toInertial) || !defined(toInertialDelta)) {
toFixed = Transforms.computeTemeToPseudoFixedMatrix(
time,
updateTransformMatrix3Scratch3,
);
toInertial = Matrix3.transpose(
toFixed,
updateTransformMatrix3Scratch1,
);
toInertialDelta = Transforms.computeTemeToPseudoFixedMatrix(
deltaTime,
updateTransformMatrix3Scratch2,
);
Matrix3.transpose(toInertialDelta, toInertialDelta);
} else {
toFixed = Matrix3.transpose(
toInertial,
updateTransformMatrix3Scratch3,
);
}
const inertialCartesian = Matrix3.multiplyByVector(
toInertial,
cartesian,
updateTransformCartesian3Scratch5,
);
const inertialDeltaCartesian = Matrix3.multiplyByVector(
toInertialDelta,
deltaCartesian,
updateTransformCartesian3Scratch6,
);
Cartesian3.subtract(
inertialCartesian,
inertialDeltaCartesian,
updateTransformCartesian3Scratch4,
);
const inertialVelocity =
Cartesian3.magnitude(updateTransformCartesian3Scratch4) * 1000.0; // meters/sec
const mu = CesiumMath.GRAVITATIONALPARAMETER; // m^3 / sec^2
const semiMajorAxis =
-mu /
(inertialVelocity * inertialVelocity -
(2 * mu) / Cartesian3.magnitude(inertialCartesian));
if (
semiMajorAxis < 0 ||
semiMajorAxis > northUpAxisFactor * ellipsoid.maximumRadius
) {
// North-up viewing from deep space.
// X along the nadir
xBasis = updateTransformCartesian3Scratch2;
Cartesian3.normalize(cartesian, xBasis);
Cartesian3.negate(xBasis, xBasis);
// Z is North
zBasis = Cartesian3.clone(
Cartesian3.UNIT_Z,
updateTransformCartesian3Scratch3,
);
// Y is along the cross of z and x (right handed basis / in the direction of motion)
yBasis = Cartesian3.cross(
zBasis,
xBasis,
updateTransformCartesian3Scratch1,
);
if (Cartesian3.magnitude(yBasis) > CesiumMath.EPSILON7) {
Cartesian3.normalize(xBasis, xBasis);
Cartesian3.normalize(yBasis, yBasis);
zBasis = Cartesian3.cross(
xBasis,
yBasis,
updateTransformCartesian3Scratch3,
);
Cartesian3.normalize(zBasis, zBasis);
hasBasis = true;
}
} else if (
!Cartesian3.equalsEpsilon(
cartesian,
deltaCartesian,
CesiumMath.EPSILON7,
)
) {
// Approximation of VVLH (Vehicle Velocity Local Horizontal) with the Z-axis flipped.
// Z along the position
zBasis = updateTransformCartesian3Scratch2;
Cartesian3.normalize(inertialCartesian, zBasis);
Cartesian3.normalize(inertialDeltaCartesian, inertialDeltaCartesian);
// Y is along the angular momentum vector (e.g. "orbit normal")
yBasis = Cartesian3.cross(
zBasis,
inertialDeltaCartesian,
updateTransformCartesian3Scratch3,
);
if (invertVelocity) {
yBasis = Cartesian3.multiplyByScalar(yBasis, -1, yBasis);
}
if (
!Cartesian3.equalsEpsilon(
yBasis,
Cartesian3.ZERO,
CesiumMath.EPSILON7,
)
) {
// X is along the cross of y and z (right handed basis / in the direction of motion)
xBasis = Cartesian3.cross(
yBasis,
zBasis,
updateTransformCartesian3Scratch1,
);
Matrix3.multiplyByVector(toFixed, xBasis, xBasis);
Matrix3.multiplyByVector(toFixed, yBasis, yBasis);
Matrix3.multiplyByVector(toFixed, zBasis, zBasis);
Cartesian3.normalize(xBasis, xBasis);
Cartesian3.normalize(yBasis, yBasis);
Cartesian3.normalize(zBasis, zBasis);
hasBasis = true;
}
}
}
}
if (defined(that.boundingSphere)) {
cartesian = that.boundingSphere.center;
}
let position;
let direction;
let up;
if (saveCamera) {
position = Cartesian3.clone(
camera.position,
updateTransformCartesian3Scratch4,
);
direction = Cartesian3.clone(
camera.direction,
updateTransformCartesian3Scratch5,
);
up = Cartesian3.clone(camera.up, updateTransformCartesian3Scratch6);
}
const transform = updateTransformMatrix4Scratch;
let orientation;
if (defined(orientationProperty)) {
orientation = orientationProperty.getValue(
time,
updateTransformOrientationScratch,
);
}
const velocity = velocityProperty.getValue(time, velocityScratch);
if (
trackingReferenceFrame === TrackingReferenceFrame.INERTIAL &&
defined(orientation)
) {
Matrix4.fromTranslationQuaternionRotationScale(
cartesian,
orientation,
Cartesian3.ONE,
transform,
);
} else if (
trackingReferenceFrame === TrackingReferenceFrame.VELOCITY &&
defined(velocity)
) {
const rotation = Transforms.rotationMatrixFromPositionVelocity(
cartesian,
velocity,
ellipsoid,
rotationScratch,
);
Matrix4.fromRotationTranslation(rotation, cartesian, transform);
} else if (
trackingReferenceFrame === TrackingReferenceFrame.ENU ||
!hasBasis
) {
Transforms.eastNorthUpToFixedFrame(cartesian, ellipsoid, transform);
} else {
transform[0] = xBasis.x;
transform[1] = xBasis.y;
transform[2] = xBasis.z;
transform[3] = 0.0;
transform[4] = yBasis.x;
transform[5] = yBasis.y;
transform[6] = yBasis.z;
transform[7] = 0.0;
transform[8] = zBasis.x;
transform[9] = zBasis.y;
transform[10] = zBasis.z;
transform[11] = 0.0;
transform[12] = cartesian.x;
transform[13] = cartesian.y;
transform[14] = cartesian.z;
transform[15] = 0.0;
}
camera._setTransform(transform);
if (saveCamera) {
Cartesian3.clone(position, camera.position);
Cartesian3.clone(direction, camera.direction);
Cartesian3.clone(up, camera.up);
Cartesian3.cross(direction, up, camera.right);
}
}
if (updateLookAt) {
const offset =
mode === SceneMode.SCENE2D ||
Cartesian3.equals(that._offset3D, Cartesian3.ZERO)
? undefined
: that._offset3D;
camera.lookAtTransform(camera.transform, offset);
}
}
/**
* A utility object for tracking an entity with the camera.
* @alias EntityView
* @constructor
*
* @param {Entity} entity The entity to track with the camera.
* @param {Scene} scene The scene to use.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid to use for orienting the camera.
*/
function EntityView(entity, scene, ellipsoid) {
//>>includeStart('debug', pragmas.debug);
Check.defined("entity", entity);
Check.defined("scene", scene);
//>>includeEnd('debug');
/**
* The entity to track with the camera.
* @type {Entity}
*/
this.entity = entity;
/**
* The scene in which to track the object.
* @type {Scene}
*/
this.scene = scene;
/**
* The ellipsoid to use for orienting the camera.
* @type {Ellipsoid}
*/
this.ellipsoid = ellipsoid ?? Ellipsoid.default;
/**
* The bounding sphere of the object.
* @type {BoundingSphere}
*/
this.boundingSphere = undefined;
// Shadow copies of the objects so we can detect changes.
this._lastEntity = undefined;
this._mode = undefined;
this._lastCartesian = new Cartesian3();
this._defaultOffset3D = undefined;
this._velocityProperty = new VelocityVectorProperty(entity.position, true);
this._offset3D = new Cartesian3();
}
// STATIC properties defined here, not per-instance.
Object.defineProperties(EntityView, {
/**
* Gets or sets a camera offset that will be used to
* initialize subsequent EntityViews.
* @memberof EntityView
* @type {Cartesian3}
*/
defaultOffset3D: {
get: function () {
return this._defaultOffset3D;
},
set: function (vector) {
this._defaultOffset3D = Cartesian3.clone(vector, new Cartesian3());
},
},
});
// Initialize the static property.
EntityView.defaultOffset3D = new Cartesian3(-14000, 3500, 3500);
const scratchHeadingPitchRange = new HeadingPitchRange();
const scratchCartesian = new Cartesian3();
/**
* Should be called each animation frame to update the camera
* to the latest settings.
* @param {JulianDate} time The current animation time.
* @param {BoundingSphere} [boundingSphere] bounding sphere of the object.
*/
EntityView.prototype.update = function (time, boundingSphere) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
const scene = this.scene;
const ellipsoid = this.ellipsoid;
const sceneMode = scene.mode;
if (sceneMode === SceneMode.MORPHING) {
return;
}
const entity = this.entity;
const trackingReferenceFrame = entity.trackingReferenceFrame;
const positionProperty = entity.position;
if (!defined(positionProperty)) {
return;
}
const velocityProperty = this._velocityProperty;
const orientationProperty = entity.orientation;
const objectChanged = entity !== this._lastEntity;
const sceneModeChanged = sceneMode !== this._mode;
const camera = scene.camera;
let updateLookAt = objectChanged || sceneModeChanged;
let saveCamera = true;
if (objectChanged) {
const viewFromProperty = entity.viewFrom;
const hasViewFrom = defined(viewFromProperty);
if (!hasViewFrom && defined(boundingSphere)) {
// The default HPR is not ideal for high altitude objects so
// we scale the pitch as we get further from the earth for a more
// downward view.
scratchHeadingPitchRange.pitch = -CesiumMath.PI_OVER_FOUR;
scratchHeadingPitchRange.range = 0;
const position = positionProperty.getValue(time, scratchCartesian);
if (defined(position)) {
const factor =
2 -
1 /
Math.max(
1,
Cartesian3.magnitude(position) / ellipsoid.maximumRadius,
);
scratchHeadingPitchRange.pitch *= factor;
}
camera.viewBoundingSphere(boundingSphere, scratchHeadingPitchRange);
this.boundingSphere = boundingSphere;
updateLookAt = false;
saveCamera = false;
} else if (
!hasViewFrom ||
!defined(viewFromProperty.getValue(time, this._offset3D))
) {
Cartesian3.clone(EntityView._defaultOffset3D, this._offset3D);
}
} else if (!sceneModeChanged && this._mode !== SceneMode.SCENE2D) {
Cartesian3.clone(camera.position, this._offset3D);
}
this._lastEntity = entity;
this._mode = sceneMode;
updateTransform(
this,
camera,
updateLookAt,
saveCamera,
positionProperty,
velocityProperty,
orientationProperty,
trackingReferenceFrame,
time,
ellipsoid,
);
};
export default EntityView;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,538 @@
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import Event from "../Core/Event.js";
import Iso8601 from "../Core/Iso8601.js";
import oneTimeWarning from "../Core/oneTimeWarning.js";
import ClassificationType from "../Scene/ClassificationType.js";
import ShadowMode from "../Scene/ShadowMode.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import ConstantProperty from "./ConstantProperty.js";
import Entity from "./Entity.js";
import Property from "./Property.js";
const defaultMaterial = new ColorMaterialProperty(Color.WHITE);
const defaultShow = new ConstantProperty(true);
const defaultFill = new ConstantProperty(true);
const defaultOutline = new ConstantProperty(false);
const defaultOutlineColor = new ConstantProperty(Color.BLACK);
const defaultShadows = new ConstantProperty(ShadowMode.DISABLED);
const defaultDistanceDisplayCondition = new ConstantProperty(
new DistanceDisplayCondition(),
);
const defaultClassificationType = new ConstantProperty(ClassificationType.BOTH);
/**
* An abstract class for updating geometry entities.
* @alias GeometryUpdater
* @constructor
*
* @param {object} options An object with the following properties:
* @param {Entity} options.entity The entity containing the geometry to be visualized.
* @param {Scene} options.scene The scene where visualization is taking place.
* @param {object} options.geometryOptions Options for the geometry
* @param {string} options.geometryPropertyName The geometry property name
* @param {string[]} options.observedPropertyNames The entity properties this geometry cares about
*/
function GeometryUpdater(options) {
//>>includeStart('debug', pragmas.debug);
Check.defined("options.entity", options.entity);
Check.defined("options.scene", options.scene);
Check.defined("options.geometryOptions", options.geometryOptions);
Check.defined("options.geometryPropertyName", options.geometryPropertyName);
Check.defined("options.observedPropertyNames", options.observedPropertyNames);
//>>includeEnd('debug');
const entity = options.entity;
const geometryPropertyName = options.geometryPropertyName;
this._entity = entity;
this._scene = options.scene;
this._fillEnabled = false;
this._isClosed = false;
this._onTerrain = false;
this._dynamic = false;
this._outlineEnabled = false;
this._geometryChanged = new Event();
this._showProperty = undefined;
this._materialProperty = undefined;
this._showOutlineProperty = undefined;
this._outlineColorProperty = undefined;
this._outlineWidth = 1.0;
this._shadowsProperty = undefined;
this._distanceDisplayConditionProperty = undefined;
this._classificationTypeProperty = undefined;
this._options = options.geometryOptions;
this._geometryPropertyName = geometryPropertyName;
this._id = `${geometryPropertyName}-${entity.id}`;
this._observedPropertyNames = options.observedPropertyNames;
this._supportsMaterialsforEntitiesOnTerrain =
Entity.supportsMaterialsforEntitiesOnTerrain(options.scene);
}
Object.defineProperties(GeometryUpdater.prototype, {
/**
* Gets the unique ID associated with this updater
* @memberof GeometryUpdater.prototype
* @type {string}
* @readonly
*/
id: {
get: function () {
return this._id;
},
},
/**
* Gets the entity associated with this geometry.
* @memberof GeometryUpdater.prototype
*
* @type {Entity}
* @readonly
*/
entity: {
get: function () {
return this._entity;
},
},
/**
* Gets a value indicating if the geometry has a fill component.
* @memberof GeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
fillEnabled: {
get: function () {
return this._fillEnabled;
},
},
/**
* Gets a value indicating if fill visibility varies with simulation time.
* @memberof GeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
hasConstantFill: {
get: function () {
return (
!this._fillEnabled ||
(!defined(this._entity.availability) &&
Property.isConstant(this._showProperty) &&
Property.isConstant(this._fillProperty))
);
},
},
/**
* Gets the material property used to fill the geometry.
* @memberof GeometryUpdater.prototype
*
* @type {MaterialProperty}
* @readonly
*/
fillMaterialProperty: {
get: function () {
return this._materialProperty;
},
},
/**
* Gets a value indicating if the geometry has an outline component.
* @memberof GeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
outlineEnabled: {
get: function () {
return this._outlineEnabled;
},
},
/**
* Gets a value indicating if the geometry has an outline component.
* @memberof GeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
hasConstantOutline: {
get: function () {
return (
!this._outlineEnabled ||
(!defined(this._entity.availability) &&
Property.isConstant(this._showProperty) &&
Property.isConstant(this._showOutlineProperty))
);
},
},
/**
* Gets the {@link Color} property for the geometry outline.
* @memberof GeometryUpdater.prototype
*
* @type {Property}
* @readonly
*/
outlineColorProperty: {
get: function () {
return this._outlineColorProperty;
},
},
/**
* Gets the constant with of the geometry outline, in pixels.
* This value is only valid if isDynamic is false.
* @memberof GeometryUpdater.prototype
*
* @type {number}
* @readonly
*/
outlineWidth: {
get: function () {
return this._outlineWidth;
},
},
/**
* Gets the property specifying whether the geometry
* casts or receives shadows from light sources.
* @memberof GeometryUpdater.prototype
*
* @type {Property}
* @readonly
*/
shadowsProperty: {
get: function () {
return this._shadowsProperty;
},
},
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this geometry will be displayed.
* @memberof GeometryUpdater.prototype
*
* @type {Property}
* @readonly
*/
distanceDisplayConditionProperty: {
get: function () {
return this._distanceDisplayConditionProperty;
},
},
/**
* Gets or sets the {@link ClassificationType} Property specifying if this geometry will classify terrain, 3D Tiles, or both when on the ground.
* @memberof GeometryUpdater.prototype
*
* @type {Property}
* @readonly
*/
classificationTypeProperty: {
get: function () {
return this._classificationTypeProperty;
},
},
/**
* Gets a value indicating if the geometry is time-varying.
*
* @memberof GeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
isDynamic: {
get: function () {
return this._dynamic;
},
},
/**
* Gets a value indicating if the geometry is closed.
* This property is only valid for static geometry.
* @memberof GeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
isClosed: {
get: function () {
return this._isClosed;
},
},
/**
* Gets a value indicating if the geometry should be drawn on terrain.
* @memberof EllipseGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
onTerrain: {
get: function () {
return this._onTerrain;
},
},
/**
* Gets an event that is raised whenever the public properties
* of this updater change.
* @memberof GeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
geometryChanged: {
get: function () {
return this._geometryChanged;
},
},
});
/**
* Checks if the geometry is outlined at the provided time.
*
* @param {JulianDate} time The time for which to retrieve visibility.
* @returns {boolean} true if geometry is outlined at the provided time, false otherwise.
*/
GeometryUpdater.prototype.isOutlineVisible = function (time) {
const entity = this._entity;
const visible =
this._outlineEnabled &&
entity.isAvailable(time) &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time);
return visible ?? false;
};
/**
* Checks if the geometry is filled at the provided time.
*
* @param {JulianDate} time The time for which to retrieve visibility.
* @returns {boolean} true if geometry is filled at the provided time, false otherwise.
*/
GeometryUpdater.prototype.isFilled = function (time) {
const entity = this._entity;
const visible =
this._fillEnabled &&
entity.isAvailable(time) &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time);
return visible ?? false;
};
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @function
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
GeometryUpdater.prototype.createFillGeometryInstance =
DeveloperError.throwInstantiationError;
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @function
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
GeometryUpdater.prototype.createOutlineGeometryInstance =
DeveloperError.throwInstantiationError;
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
GeometryUpdater.prototype.isDestroyed = function () {
return false;
};
/**
* Destroys and resources used by the object. Once an object is destroyed, it should not be used.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*/
GeometryUpdater.prototype.destroy = function () {
destroyObject(this);
};
/**
* @param {Entity} entity
* @param {object} geometry
* @private
*/
GeometryUpdater.prototype._isHidden = function (entity, geometry) {
const show = geometry.show;
return (
defined(show) && show.isConstant && !show.getValue(Iso8601.MINIMUM_VALUE)
);
};
/**
* @param {Entity} entity
* @param {object} geometry
* @private
*/
GeometryUpdater.prototype._isOnTerrain = function (entity, geometry) {
return false;
};
/**
* @param {GeometryOptions} options
* @private
*/
GeometryUpdater.prototype._getIsClosed = function (options) {
return true;
};
/**
* @param {Entity} entity
* @param {object} geometry
* @private
*/
GeometryUpdater.prototype._isDynamic = DeveloperError.throwInstantiationError;
/**
* @param {Entity} entity
* @param {object} geometry
* @private
*/
GeometryUpdater.prototype._setStaticOptions =
DeveloperError.throwInstantiationError;
/**
* @param {Entity} entity
* @param {string} propertyName
* @param {*} newValue
* @param {*} oldValue
* @private
*/
GeometryUpdater.prototype._onEntityPropertyChanged = function (
entity,
propertyName,
newValue,
oldValue,
) {
if (this._observedPropertyNames.indexOf(propertyName) === -1) {
return;
}
const geometry = this._entity[this._geometryPropertyName];
if (!defined(geometry)) {
if (this._fillEnabled || this._outlineEnabled) {
this._fillEnabled = false;
this._outlineEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
const fillProperty = geometry.fill;
const fillEnabled =
defined(fillProperty) && fillProperty.isConstant
? fillProperty.getValue(Iso8601.MINIMUM_VALUE)
: true;
const outlineProperty = geometry.outline;
let outlineEnabled = defined(outlineProperty);
if (outlineEnabled && outlineProperty.isConstant) {
outlineEnabled = outlineProperty.getValue(Iso8601.MINIMUM_VALUE);
}
if (!fillEnabled && !outlineEnabled) {
if (this._fillEnabled || this._outlineEnabled) {
this._fillEnabled = false;
this._outlineEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
const show = geometry.show;
if (this._isHidden(entity, geometry)) {
if (this._fillEnabled || this._outlineEnabled) {
this._fillEnabled = false;
this._outlineEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
this._materialProperty = geometry.material ?? defaultMaterial;
this._fillProperty = fillProperty ?? defaultFill;
this._showProperty = show ?? defaultShow;
this._showOutlineProperty = geometry.outline ?? defaultOutline;
this._outlineColorProperty = outlineEnabled
? (geometry.outlineColor ?? defaultOutlineColor)
: undefined;
this._shadowsProperty = geometry.shadows ?? defaultShadows;
this._distanceDisplayConditionProperty =
geometry.distanceDisplayCondition ?? defaultDistanceDisplayCondition;
this._classificationTypeProperty =
geometry.classificationType ?? defaultClassificationType;
this._fillEnabled = fillEnabled;
const onTerrain =
this._isOnTerrain(entity, geometry) &&
(this._supportsMaterialsforEntitiesOnTerrain ||
this._materialProperty instanceof ColorMaterialProperty);
if (outlineEnabled && onTerrain) {
oneTimeWarning(oneTimeWarning.geometryOutlines);
outlineEnabled = false;
}
this._onTerrain = onTerrain;
this._outlineEnabled = outlineEnabled;
if (this._isDynamic(entity, geometry)) {
if (!this._dynamic) {
this._dynamic = true;
this._geometryChanged.raiseEvent(this);
}
} else {
this._setStaticOptions(entity, geometry);
this._isClosed = this._getIsClosed(this._options);
const outlineWidth = geometry.outlineWidth;
this._outlineWidth = defined(outlineWidth)
? outlineWidth.getValue(Iso8601.MINIMUM_VALUE)
: 1.0;
this._dynamic = false;
this._geometryChanged.raiseEvent(this);
}
};
/**
* Creates the dynamic updater to be used when GeometryUpdater#isDynamic is true.
*
* @param {PrimitiveCollection} primitives The primitive collection to use.
* @param {PrimitiveCollection} [groundPrimitives] The primitive collection to use for ground primitives.
*
* @returns {DynamicGeometryUpdater} The dynamic updater used to update the geometry each frame.
*
* @exception {DeveloperError} This instance does not represent dynamic geometry.
* @private
*/
GeometryUpdater.prototype.createDynamicUpdater = function (
primitives,
groundPrimitives,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("primitives", primitives);
Check.defined("groundPrimitives", groundPrimitives);
if (!this._dynamic) {
throw new DeveloperError(
"This instance does not represent dynamic geometry.",
);
}
//>>includeEnd('debug');
return new this.constructor.DynamicGeometryUpdater(
this,
primitives,
groundPrimitives,
);
};
export default GeometryUpdater;
@@ -0,0 +1,114 @@
import destroyObject from "../Core/destroyObject.js";
import Event from "../Core/Event.js";
import EventHelper from "../Core/EventHelper.js";
import BoxGeometryUpdater from "./BoxGeometryUpdater.js";
import CorridorGeometryUpdater from "./CorridorGeometryUpdater.js";
import CylinderGeometryUpdater from "./CylinderGeometryUpdater.js";
import EllipseGeometryUpdater from "./EllipseGeometryUpdater.js";
import EllipsoidGeometryUpdater from "./EllipsoidGeometryUpdater.js";
import PlaneGeometryUpdater from "./PlaneGeometryUpdater.js";
import PolygonGeometryUpdater from "./PolygonGeometryUpdater.js";
import PolylineVolumeGeometryUpdater from "./PolylineVolumeGeometryUpdater.js";
import RectangleGeometryUpdater from "./RectangleGeometryUpdater.js";
import WallGeometryUpdater from "./WallGeometryUpdater.js";
/** @type {GeometryUpdater[]} */
const geometryUpdaters = [
BoxGeometryUpdater,
CylinderGeometryUpdater,
CorridorGeometryUpdater,
EllipseGeometryUpdater,
EllipsoidGeometryUpdater,
PlaneGeometryUpdater,
PolygonGeometryUpdater,
PolylineVolumeGeometryUpdater,
RectangleGeometryUpdater,
WallGeometryUpdater,
];
/**
* Manages a set of "updater" classes for the {@link GeometryVisualizer} for each entity
*
* @private
* @param {Entity} entity
* @param {Scene} scene
*/
function GeometryUpdaterSet(entity, scene) {
this.entity = entity;
this.scene = scene;
const updaters = new Array(geometryUpdaters.length);
const geometryChanged = new Event();
const eventHelper = new EventHelper();
for (let i = 0; i < updaters.length; i++) {
const updater = new geometryUpdaters[i](entity, scene);
eventHelper.add(updater.geometryChanged, (geometry) => {
geometryChanged.raiseEvent(geometry);
});
updaters[i] = updater;
}
this.updaters = updaters;
this.geometryChanged = geometryChanged;
this.eventHelper = eventHelper;
this._removeEntitySubscription = entity.definitionChanged.addEventListener(
GeometryUpdaterSet.prototype._onEntityPropertyChanged,
this,
);
}
GeometryUpdaterSet.prototype._onEntityPropertyChanged = function (
entity,
propertyName,
newValue,
oldValue,
) {
const updaters = this.updaters;
for (let i = 0; i < updaters.length; i++) {
updaters[i]._onEntityPropertyChanged(
entity,
propertyName,
newValue,
oldValue,
);
}
};
GeometryUpdaterSet.prototype.forEach = function (callback) {
const updaters = this.updaters;
for (let i = 0; i < updaters.length; i++) {
callback(updaters[i]);
}
};
GeometryUpdaterSet.prototype.destroy = function () {
this.eventHelper.removeAll();
const updaters = this.updaters;
for (let i = 0; i < updaters.length; i++) {
updaters[i].destroy();
}
this._removeEntitySubscription();
destroyObject(this);
};
/**
* Add the provided updater to the default list of updaters if not already included
* @param {GeometryUpdater} updater
*/
GeometryUpdaterSet.registerUpdater = function (updater) {
if (!geometryUpdaters.includes(updater)) {
geometryUpdaters.push(updater);
}
};
/**
* Remove the provided updater from the default list of updaters if included
* @param {GeometryUpdater} updater
*/
GeometryUpdaterSet.unregisterUpdater = function (updater) {
if (geometryUpdaters.includes(updater)) {
const index = geometryUpdaters.indexOf(updater);
geometryUpdaters.splice(index, 1);
}
};
export default GeometryUpdaterSet;
@@ -0,0 +1,549 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import BoundingSphere from "../Core/BoundingSphere.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import ClassificationType from "../Scene/ClassificationType.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ShadowMode from "../Scene/ShadowMode.js";
import BoundingSphereState from "./BoundingSphereState.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryBatch from "./DynamicGeometryBatch.js";
import Entity from "./Entity.js";
import GeometryUpdaterSet from "./GeometryUpdaterSet.js";
import StaticGeometryColorBatch from "./StaticGeometryColorBatch.js";
import StaticGeometryPerMaterialBatch from "./StaticGeometryPerMaterialBatch.js";
import StaticGroundGeometryColorBatch from "./StaticGroundGeometryColorBatch.js";
import StaticGroundGeometryPerMaterialBatch from "./StaticGroundGeometryPerMaterialBatch.js";
import StaticOutlineGeometryBatch from "./StaticOutlineGeometryBatch.js";
const emptyArray = [];
/**
* A general purpose visualizer for geometry represented by {@link Primitive} instances.
* @alias GeometryVisualizer
* @constructor
*
* @param {Scene} scene The scene the primitives will be rendered in.
* @param {EntityCollection} entityCollection The entityCollection to visualize.
* @param {PrimitiveCollection} [primitives=scene.primitives] A collection to add primitives related to the entities
* @param {PrimitiveCollection} [groundPrimitives=scene.groundPrimitives] A collection to add ground primitives related to the entities
*/
function GeometryVisualizer(
scene,
entityCollection,
primitives,
groundPrimitives,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("scene", scene);
Check.defined("entityCollection", entityCollection);
//>>includeEnd('debug');
primitives = primitives ?? scene.primitives;
groundPrimitives = groundPrimitives ?? scene.groundPrimitives;
this._scene = scene;
this._primitives = primitives;
this._groundPrimitives = groundPrimitives;
this._entityCollection = undefined;
this._addedObjects = new AssociativeArray();
this._removedObjects = new AssociativeArray();
this._changedObjects = new AssociativeArray();
const numberOfShadowModes = ShadowMode.NUMBER_OF_SHADOW_MODES;
this._outlineBatches = new Array(numberOfShadowModes * 2);
this._closedColorBatches = new Array(numberOfShadowModes * 2);
this._closedMaterialBatches = new Array(numberOfShadowModes * 2);
this._openColorBatches = new Array(numberOfShadowModes * 2);
this._openMaterialBatches = new Array(numberOfShadowModes * 2);
const supportsMaterialsforEntitiesOnTerrain =
Entity.supportsMaterialsforEntitiesOnTerrain(scene);
this._supportsMaterialsforEntitiesOnTerrain =
supportsMaterialsforEntitiesOnTerrain;
let i;
for (i = 0; i < numberOfShadowModes; ++i) {
this._outlineBatches[i] = new StaticOutlineGeometryBatch(
primitives,
scene,
i,
false,
);
this._outlineBatches[numberOfShadowModes + i] =
new StaticOutlineGeometryBatch(primitives, scene, i, true);
this._closedColorBatches[i] = new StaticGeometryColorBatch(
primitives,
PerInstanceColorAppearance,
undefined,
true,
i,
true,
);
this._closedColorBatches[numberOfShadowModes + i] =
new StaticGeometryColorBatch(
primitives,
PerInstanceColorAppearance,
undefined,
true,
i,
false,
);
this._closedMaterialBatches[i] = new StaticGeometryPerMaterialBatch(
primitives,
MaterialAppearance,
undefined,
true,
i,
true,
);
this._closedMaterialBatches[numberOfShadowModes + i] =
new StaticGeometryPerMaterialBatch(
primitives,
MaterialAppearance,
undefined,
true,
i,
false,
);
this._openColorBatches[i] = new StaticGeometryColorBatch(
primitives,
PerInstanceColorAppearance,
undefined,
false,
i,
true,
);
this._openColorBatches[numberOfShadowModes + i] =
new StaticGeometryColorBatch(
primitives,
PerInstanceColorAppearance,
undefined,
false,
i,
false,
);
this._openMaterialBatches[i] = new StaticGeometryPerMaterialBatch(
primitives,
MaterialAppearance,
undefined,
false,
i,
true,
);
this._openMaterialBatches[numberOfShadowModes + i] =
new StaticGeometryPerMaterialBatch(
primitives,
MaterialAppearance,
undefined,
false,
i,
false,
);
}
const numberOfClassificationTypes =
ClassificationType.NUMBER_OF_CLASSIFICATION_TYPES;
const groundColorBatches = new Array(numberOfClassificationTypes);
const groundMaterialBatches = [];
if (supportsMaterialsforEntitiesOnTerrain) {
for (i = 0; i < numberOfClassificationTypes; ++i) {
groundMaterialBatches.push(
new StaticGroundGeometryPerMaterialBatch(
groundPrimitives,
i,
MaterialAppearance,
),
);
groundColorBatches[i] = new StaticGroundGeometryColorBatch(
groundPrimitives,
i,
);
}
} else {
for (i = 0; i < numberOfClassificationTypes; ++i) {
groundColorBatches[i] = new StaticGroundGeometryColorBatch(
groundPrimitives,
i,
);
}
}
this._groundColorBatches = groundColorBatches;
this._groundMaterialBatches = groundMaterialBatches;
this._dynamicBatch = new DynamicGeometryBatch(primitives, groundPrimitives);
this._batches = this._outlineBatches.concat(
this._closedColorBatches,
this._closedMaterialBatches,
this._openColorBatches,
this._openMaterialBatches,
this._groundColorBatches,
this._groundMaterialBatches,
this._dynamicBatch,
);
this._subscriptions = new AssociativeArray();
this._updaterSets = new AssociativeArray();
this._entityCollection = entityCollection;
entityCollection.collectionChanged.addEventListener(
GeometryVisualizer.prototype._onCollectionChanged,
this,
);
this._onCollectionChanged(
entityCollection,
entityCollection.values,
emptyArray,
);
}
/**
* Add the provided updater to the default list of updaters if not already included
* @private
* @param {GeometryUpdater} updater
*/
GeometryVisualizer.registerUpdater = function (updater) {
GeometryUpdaterSet.registerUpdater(updater);
};
/**
* Remove the provided updater from the default list of updaters if included
* @private
* @param {GeometryUpdater} updater
*/
GeometryVisualizer.unregisterUpdater = function (updater) {
GeometryUpdaterSet.unregisterUpdater(updater);
};
/**
* Updates all of the primitives created by this visualizer to match their
* Entity counterpart at the given time.
*
* @param {JulianDate} time The time to update to.
* @returns {boolean} True if the visualizer successfully updated to the provided time,
* false if the visualizer is waiting for asynchronous primitives to be created.
*/
GeometryVisualizer.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
const addedObjects = this._addedObjects;
const added = addedObjects.values;
const removedObjects = this._removedObjects;
const removed = removedObjects.values;
const changedObjects = this._changedObjects;
const changed = changedObjects.values;
let i;
let entity;
let id;
let updaterSet;
const that = this;
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
id = entity.id;
updaterSet = this._updaterSets.get(id);
//If in a single update, an entity gets removed and a new instance
//re-added with the same id, the updater no longer tracks the
//correct entity, we need to both remove the old one and
//add the new one, which is done by pushing the entity
//onto the removed/added lists.
if (updaterSet.entity === entity) {
updaterSet.forEach(function (updater) {
that._removeUpdater(updater);
that._insertUpdaterIntoBatch(time, updater);
});
} else {
removed.push(entity);
added.push(entity);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
id = entity.id;
updaterSet = this._updaterSets.get(id);
updaterSet.forEach(this._removeUpdater.bind(this));
updaterSet.destroy();
this._updaterSets.remove(id);
this._subscriptions.get(id)();
this._subscriptions.remove(id);
}
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
id = entity.id;
updaterSet = new GeometryUpdaterSet(entity, this._scene);
this._updaterSets.set(id, updaterSet);
updaterSet.forEach(function (updater) {
that._insertUpdaterIntoBatch(time, updater);
});
this._subscriptions.set(
id,
updaterSet.geometryChanged.addEventListener(
GeometryVisualizer._onGeometryChanged,
this,
),
);
}
addedObjects.removeAll();
removedObjects.removeAll();
changedObjects.removeAll();
let isUpdated = true;
const batches = this._batches;
const length = batches.length;
for (i = 0; i < length; i++) {
isUpdated = batches[i].update(time) && isUpdated;
}
return isUpdated;
};
const getBoundingSphereArrayScratch = [];
const getBoundingSphereBoundingSphereScratch = new BoundingSphere();
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
GeometryVisualizer.prototype.getBoundingSphere = function (entity, result) {
//>>includeStart('debug', pragmas.debug);
Check.defined("entity", entity);
Check.defined("result", result);
//>>includeEnd('debug');
const boundingSpheres = getBoundingSphereArrayScratch;
const tmp = getBoundingSphereBoundingSphereScratch;
let count = 0;
let state = BoundingSphereState.DONE;
const batches = this._batches;
const batchesLength = batches.length;
const id = entity.id;
const updaters = this._updaterSets.get(id).updaters;
for (let j = 0; j < updaters.length; j++) {
const updater = updaters[j];
for (let i = 0; i < batchesLength; i++) {
state = batches[i].getBoundingSphere(updater, tmp);
if (state === BoundingSphereState.PENDING) {
return BoundingSphereState.PENDING;
} else if (state === BoundingSphereState.DONE) {
boundingSpheres[count] = BoundingSphere.clone(
tmp,
boundingSpheres[count],
);
count++;
}
}
}
if (count === 0) {
return BoundingSphereState.FAILED;
}
boundingSpheres.length = count;
BoundingSphere.fromBoundingSpheres(boundingSpheres, result);
return BoundingSphereState.DONE;
};
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
GeometryVisualizer.prototype.isDestroyed = function () {
return false;
};
/**
* Removes and destroys all primitives created by this instance.
*/
GeometryVisualizer.prototype.destroy = function () {
this._entityCollection.collectionChanged.removeEventListener(
GeometryVisualizer.prototype._onCollectionChanged,
this,
);
this._addedObjects.removeAll();
this._removedObjects.removeAll();
let i;
const batches = this._batches;
let length = batches.length;
for (i = 0; i < length; i++) {
batches[i].removeAllPrimitives();
}
const subscriptions = this._subscriptions.values;
length = subscriptions.length;
for (i = 0; i < length; i++) {
subscriptions[i]();
}
this._subscriptions.removeAll();
const updaterSets = this._updaterSets.values;
length = updaterSets.length;
for (i = 0; i < length; i++) {
updaterSets[i].destroy();
}
this._updaterSets.removeAll();
return destroyObject(this);
};
/**
* @private
*/
GeometryVisualizer.prototype._removeUpdater = function (updater) {
//We don't keep track of which batch an updater is in, so just remove it from all of them.
const batches = this._batches;
const length = batches.length;
for (let i = 0; i < length; i++) {
batches[i].remove(updater);
}
};
/**
* @private
*/
GeometryVisualizer.prototype._insertUpdaterIntoBatch = function (
time,
updater,
) {
if (updater.isDynamic) {
this._dynamicBatch.add(time, updater);
return;
}
let shadows;
if (updater.outlineEnabled || updater.fillEnabled) {
shadows = updater.shadowsProperty.getValue(time);
}
const numberOfShadowModes = ShadowMode.NUMBER_OF_SHADOW_MODES;
if (updater.outlineEnabled) {
if (defined(updater.terrainOffsetProperty)) {
this._outlineBatches[numberOfShadowModes + shadows].add(time, updater);
} else {
this._outlineBatches[shadows].add(time, updater);
}
}
if (updater.fillEnabled) {
if (updater.onTerrain) {
const classificationType =
updater.classificationTypeProperty.getValue(time);
if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
this._groundColorBatches[classificationType].add(time, updater);
} else {
// If unsupported, updater will not be on terrain.
this._groundMaterialBatches[classificationType].add(time, updater);
}
} else if (updater.isClosed) {
if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
if (defined(updater.terrainOffsetProperty)) {
this._closedColorBatches[numberOfShadowModes + shadows].add(
time,
updater,
);
} else {
this._closedColorBatches[shadows].add(time, updater);
}
} else if (defined(updater.terrainOffsetProperty)) {
this._closedMaterialBatches[numberOfShadowModes + shadows].add(
time,
updater,
);
} else {
this._closedMaterialBatches[shadows].add(time, updater);
}
} else if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
if (defined(updater.terrainOffsetProperty)) {
this._openColorBatches[numberOfShadowModes + shadows].add(
time,
updater,
);
} else {
this._openColorBatches[shadows].add(time, updater);
}
} else if (defined(updater.terrainOffsetProperty)) {
this._openMaterialBatches[numberOfShadowModes + shadows].add(
time,
updater,
);
} else {
this._openMaterialBatches[shadows].add(time, updater);
}
}
};
/**
* @private
*/
GeometryVisualizer._onGeometryChanged = function (updater) {
const removedObjects = this._removedObjects;
const changedObjects = this._changedObjects;
const entity = updater.entity;
const id = entity.id;
if (!defined(removedObjects.get(id)) && !defined(changedObjects.get(id))) {
changedObjects.set(id, entity);
}
};
/**
* @private
*/
GeometryVisualizer.prototype._onCollectionChanged = function (
entityCollection,
added,
removed,
) {
const addedObjects = this._addedObjects;
const removedObjects = this._removedObjects;
const changedObjects = this._changedObjects;
let i;
let id;
let entity;
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
id = entity.id;
if (!addedObjects.remove(id)) {
removedObjects.set(id, entity);
changedObjects.remove(id);
}
}
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
id = entity.id;
if (removedObjects.remove(id)) {
changedObjects.set(id, entity);
} else {
addedObjects.set(id, entity);
}
}
};
export default GeometryVisualizer;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,204 @@
import Cartesian2 from "../Core/Cartesian2.js";
import Color from "../Core/Color.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
const defaultColor = Color.WHITE;
const defaultCellAlpha = 0.1;
const defaultLineCount = new Cartesian2(8, 8);
const defaultLineOffset = new Cartesian2(0, 0);
const defaultLineThickness = new Cartesian2(1, 1);
/**
* A {@link MaterialProperty} that maps to grid {@link Material} uniforms.
* @alias GridMaterialProperty
*
* @param {object} [options] Object with the following properties:
* @param {Property|Color} [options.color=Color.WHITE] A Property specifying the grid {@link Color}.
* @param {Property|number} [options.cellAlpha=0.1] A numeric Property specifying cell alpha values.
* @param {Property|Cartesian2} [options.lineCount=new Cartesian2(8, 8)] A {@link Cartesian2} Property specifying the number of grid lines along each axis.
* @param {Property|Cartesian2} [options.lineThickness=new Cartesian2(1.0, 1.0)] A {@link Cartesian2} Property specifying the thickness of grid lines along each axis.
* @param {Property|Cartesian2} [options.lineOffset=new Cartesian2(0.0, 0.0)] A {@link Cartesian2} Property specifying starting offset of grid lines along each axis.
*
* @constructor
*/
function GridMaterialProperty(options) {
options = options ?? Frozen.EMPTY_OBJECT;
this._definitionChanged = new Event();
this._color = undefined;
this._colorSubscription = undefined;
this._cellAlpha = undefined;
this._cellAlphaSubscription = undefined;
this._lineCount = undefined;
this._lineCountSubscription = undefined;
this._lineThickness = undefined;
this._lineThicknessSubscription = undefined;
this._lineOffset = undefined;
this._lineOffsetSubscription = undefined;
this.color = options.color;
this.cellAlpha = options.cellAlpha;
this.lineCount = options.lineCount;
this.lineThickness = options.lineThickness;
this.lineOffset = options.lineOffset;
}
Object.defineProperties(GridMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof GridMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
Property.isConstant(this._color) &&
Property.isConstant(this._cellAlpha) &&
Property.isConstant(this._lineCount) &&
Property.isConstant(this._lineThickness) &&
Property.isConstant(this._lineOffset)
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof GridMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the Property specifying the grid {@link Color}.
* @memberof GridMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor("color"),
/**
* Gets or sets the numeric Property specifying cell alpha values.
* @memberof GridMaterialProperty.prototype
* @type {Property|undefined}
* @default 0.1
*/
cellAlpha: createPropertyDescriptor("cellAlpha"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the number of grid lines along each axis.
* @memberof GridMaterialProperty.prototype
* @type {Property|undefined}
* @default new Cartesian2(8.0, 8.0)
*/
lineCount: createPropertyDescriptor("lineCount"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the thickness of grid lines along each axis.
* @memberof GridMaterialProperty.prototype
* @type {Property|undefined}
* @default new Cartesian2(1.0, 1.0)
*/
lineThickness: createPropertyDescriptor("lineThickness"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the starting offset of grid lines along each axis.
* @memberof GridMaterialProperty.prototype
* @type {Property|undefined}
* @default new Cartesian2(0.0, 0.0)
*/
lineOffset: createPropertyDescriptor("lineOffset"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
GridMaterialProperty.prototype.getType = function (time) {
return "Grid";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
GridMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.color = Property.getValueOrClonedDefault(
this._color,
time,
defaultColor,
result.color,
);
result.cellAlpha = Property.getValueOrDefault(
this._cellAlpha,
time,
defaultCellAlpha,
);
result.lineCount = Property.getValueOrClonedDefault(
this._lineCount,
time,
defaultLineCount,
result.lineCount,
);
result.lineThickness = Property.getValueOrClonedDefault(
this._lineThickness,
time,
defaultLineThickness,
result.lineThickness,
);
result.lineOffset = Property.getValueOrClonedDefault(
this._lineOffset,
time,
defaultLineOffset,
result.lineOffset,
);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
GridMaterialProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof GridMaterialProperty && //
Property.equals(this._color, other._color) && //
Property.equals(this._cellAlpha, other._cellAlpha) && //
Property.equals(this._lineCount, other._lineCount) && //
Property.equals(this._lineThickness, other._lineThickness) && //
Property.equals(this._lineOffset, other._lineOffset))
);
};
export default GridMaterialProperty;
@@ -0,0 +1,234 @@
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import GeometryOffsetAttribute from "../Core/GeometryOffsetAttribute.js";
import oneTimeWarning from "../Core/oneTimeWarning.js";
import GroundPrimitive from "../Scene/GroundPrimitive.js";
import HeightReference, {
isHeightReferenceClamp,
} from "../Scene/HeightReference.js";
import CallbackProperty from "./CallbackProperty.js";
import ConstantProperty from "./ConstantProperty.js";
import GeometryUpdater from "./GeometryUpdater.js";
import TerrainOffsetProperty from "./TerrainOffsetProperty.js";
const defaultZIndex = new ConstantProperty(0);
/**
* An abstract class for updating ground geometry entities.
* @constructor
* @alias GroundGeometryUpdater
* @param {object} options An object with the following properties:
* @param {Entity} options.entity The entity containing the geometry to be visualized.
* @param {Scene} options.scene The scene where visualization is taking place.
* @param {object} options.geometryOptions Options for the geometry
* @param {string} options.geometryPropertyName The geometry property name
* @param {string[]} options.observedPropertyNames The entity properties this geometry cares about
*/
function GroundGeometryUpdater(options) {
GeometryUpdater.call(this, options);
this._zIndex = 0;
this._terrainOffsetProperty = undefined;
}
if (defined(Object.create)) {
GroundGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
GroundGeometryUpdater.prototype.constructor = GroundGeometryUpdater;
}
Object.defineProperties(GroundGeometryUpdater.prototype, {
/**
* Gets the zindex
* @type {number}
* @memberof GroundGeometryUpdater.prototype
* @readonly
*/
zIndex: {
get: function () {
return this._zIndex;
},
},
/**
* Gets the terrain offset property
* @type {TerrainOffsetProperty}
* @memberof GroundGeometryUpdater.prototype
* @readonly
* @private
*/
terrainOffsetProperty: {
get: function () {
return this._terrainOffsetProperty;
},
},
});
GroundGeometryUpdater.prototype._isOnTerrain = function (entity, geometry) {
return (
this._fillEnabled &&
!defined(geometry.height) &&
!defined(geometry.extrudedHeight) &&
GroundPrimitive.isSupported(this._scene)
);
};
GroundGeometryUpdater.prototype._getIsClosed = function (options) {
const height = options.height;
const extrudedHeight = options.extrudedHeight;
return height === 0 || (defined(extrudedHeight) && extrudedHeight !== height);
};
GroundGeometryUpdater.prototype._computeCenter =
DeveloperError.throwInstantiationError;
GroundGeometryUpdater.prototype._onEntityPropertyChanged = function (
entity,
propertyName,
newValue,
oldValue,
) {
GeometryUpdater.prototype._onEntityPropertyChanged.call(
this,
entity,
propertyName,
newValue,
oldValue,
);
if (this._observedPropertyNames.indexOf(propertyName) === -1) {
return;
}
const geometry = this._entity[this._geometryPropertyName];
if (!defined(geometry)) {
return;
}
if (
defined(geometry.zIndex) &&
(defined(geometry.height) || defined(geometry.extrudedHeight))
) {
oneTimeWarning(oneTimeWarning.geometryZIndex);
}
this._zIndex = geometry.zIndex ?? defaultZIndex;
if (defined(this._terrainOffsetProperty)) {
this._terrainOffsetProperty.destroy();
this._terrainOffsetProperty = undefined;
}
const heightReferenceProperty = geometry.heightReference;
const extrudedHeightReferenceProperty = geometry.extrudedHeightReference;
if (
defined(heightReferenceProperty) ||
defined(extrudedHeightReferenceProperty)
) {
const centerPosition = new CallbackProperty(
this._computeCenter.bind(this),
!this._dynamic,
);
this._terrainOffsetProperty = new TerrainOffsetProperty(
this._scene,
centerPosition,
heightReferenceProperty,
extrudedHeightReferenceProperty,
);
}
};
/**
* Destroys and resources used by the object. Once an object is destroyed, it should not be used.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*/
GroundGeometryUpdater.prototype.destroy = function () {
if (defined(this._terrainOffsetProperty)) {
this._terrainOffsetProperty.destroy();
this._terrainOffsetProperty = undefined;
}
GeometryUpdater.prototype.destroy.call(this);
};
/**
* @private
*/
GroundGeometryUpdater.getGeometryHeight = function (height, heightReference) {
//>>includeStart('debug', pragmas.debug);
Check.defined("heightReference", heightReference);
//>>includeEnd('debug');
if (!defined(height)) {
if (heightReference !== HeightReference.NONE) {
oneTimeWarning(oneTimeWarning.geometryHeightReference);
}
return;
}
if (!isHeightReferenceClamp(heightReference)) {
return height;
}
return 0.0;
};
/**
* @private
*/
GroundGeometryUpdater.getGeometryExtrudedHeight = function (
extrudedHeight,
extrudedHeightReference,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("extrudedHeightReference", extrudedHeightReference);
//>>includeEnd('debug');
if (!defined(extrudedHeight)) {
if (extrudedHeightReference !== HeightReference.NONE) {
oneTimeWarning(oneTimeWarning.geometryExtrudedHeightReference);
}
return;
}
if (!isHeightReferenceClamp(extrudedHeightReference)) {
return extrudedHeight;
}
return GroundGeometryUpdater.CLAMP_TO_GROUND;
};
/**
* @private
*/
GroundGeometryUpdater.CLAMP_TO_GROUND = "clamp";
/**
* @private
*/
GroundGeometryUpdater.computeGeometryOffsetAttribute = function (
height,
heightReference,
extrudedHeight,
extrudedHeightReference,
) {
if (!defined(height) || !defined(heightReference)) {
heightReference = HeightReference.NONE;
}
if (!defined(extrudedHeight) || !defined(extrudedHeightReference)) {
extrudedHeightReference = HeightReference.NONE;
}
let n = 0;
if (heightReference !== HeightReference.NONE) {
n++;
}
if (extrudedHeightReference === HeightReference.RELATIVE_TO_GROUND) {
n++;
}
if (n === 2) {
return GeometryOffsetAttribute.ALL;
}
if (n === 1) {
return GeometryOffsetAttribute.TOP;
}
return undefined;
};
export default GroundGeometryUpdater;
@@ -0,0 +1,173 @@
import Cartesian2 from "../Core/Cartesian2.js";
import Color from "../Core/Color.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
const defaultRepeat = new Cartesian2(1, 1);
const defaultTransparent = false;
const defaultColor = Color.WHITE;
/**
* A {@link MaterialProperty} that maps to image {@link Material} uniforms.
* @alias ImageMaterialProperty
* @constructor
*
* @param {object} [options] Object with the following properties:
* @param {Property|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [options.image] A Property specifying the Image, URL, Canvas, or Video.
* @param {Property|Cartesian2} [options.repeat=new Cartesian2(1.0, 1.0)] A {@link Cartesian2} Property specifying the number of times the image repeats in each direction.
* @param {Property|Color} [options.color=Color.WHITE] The color applied to the image
* @param {Property|boolean} [options.transparent=false] Set to true when the image has transparency (for example, when a png has transparent sections)
*/
function ImageMaterialProperty(options) {
options = options ?? Frozen.EMPTY_OBJECT;
this._definitionChanged = new Event();
this._image = undefined;
this._imageSubscription = undefined;
this._repeat = undefined;
this._repeatSubscription = undefined;
this._color = undefined;
this._colorSubscription = undefined;
this._transparent = undefined;
this._transparentSubscription = undefined;
this.image = options.image;
this.repeat = options.repeat;
this.color = options.color;
this.transparent = options.transparent;
}
Object.defineProperties(ImageMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof ImageMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
Property.isConstant(this._image) && Property.isConstant(this._repeat)
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof ImageMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the Property specifying Image, URL, Canvas, or Video to use.
* @memberof ImageMaterialProperty.prototype
* @type {Property|undefined}
*/
image: createPropertyDescriptor("image"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the number of times the image repeats in each direction.
* @memberof ImageMaterialProperty.prototype
* @type {Property|undefined}
* @default new Cartesian2(1, 1)
*/
repeat: createPropertyDescriptor("repeat"),
/**
* Gets or sets the Color Property specifying the desired color applied to the image.
* @memberof ImageMaterialProperty.prototype
* @type {Property|undefined}
* @default 1.0
*/
color: createPropertyDescriptor("color"),
/**
* Gets or sets the Boolean Property specifying whether the image has transparency
* @memberof ImageMaterialProperty.prototype
* @type {Property|undefined}
* @default 1.0
*/
transparent: createPropertyDescriptor("transparent"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
ImageMaterialProperty.prototype.getType = function (time) {
return "Image";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
ImageMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.image = Property.getValueOrUndefined(this._image, time);
result.repeat = Property.getValueOrClonedDefault(
this._repeat,
time,
defaultRepeat,
result.repeat,
);
result.color = Property.getValueOrClonedDefault(
this._color,
time,
defaultColor,
result.color,
);
if (Property.getValueOrDefault(this._transparent, time, defaultTransparent)) {
result.color.alpha = Math.min(0.99, result.color.alpha);
}
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
ImageMaterialProperty.prototype.equals = function (other) {
return (
this === other ||
(other instanceof ImageMaterialProperty &&
Property.equals(this._image, other._image) &&
Property.equals(this._repeat, other._repeat) &&
Property.equals(this._color, other._color) &&
Property.equals(this._transparent, other._transparent))
);
};
export default ImageMaterialProperty;
+13
View File
@@ -0,0 +1,13 @@
/**
* Representation of <Camera> from KML
* @alias KmlCamera
* @constructor
*
* @param {Cartesian3} position camera position
* @param {HeadingPitchRoll} headingPitchRoll camera orientation
*/
function KmlCamera(position, headingPitchRoll) {
this.position = position;
this.headingPitchRoll = headingPitchRoll;
}
export default KmlCamera;
File diff suppressed because it is too large Load Diff
+12
View File
@@ -0,0 +1,12 @@
/**
* @alias KmlLookAt
* @constructor
*
* @param {Cartesian3} position camera position
* @param {HeadingPitchRange} headingPitchRange camera orientation
*/
function KmlLookAt(position, headingPitchRange) {
this.position = position;
this.headingPitchRange = headingPitchRange;
}
export default KmlLookAt;
+165
View File
@@ -0,0 +1,165 @@
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
/**
* Describes a KmlTour, which uses KmlTourFlyTo, and KmlTourWait to
* guide the camera to a specified destinations on given time intervals.
*
* @alias KmlTour
* @constructor
*
* @param {string} name name parsed from KML
* @param {string} id id parsed from KML
* @param {Array} playlist array with KmlTourFlyTos and KmlTourWaits
*
* @see KmlTourFlyTo
* @see KmlTourWait
*
* @demo {@link https://sandcastle.cesium.com/?id=kml-tours|KML Tours}
*/
function KmlTour(name, id) {
/**
* Id of kml gx:Tour entry
* @type {string}
*/
this.id = id;
/**
* Tour name
* @type {string}
*/
this.name = name;
/**
* Index of current entry from playlist
* @type {number}
*/
this.playlistIndex = 0;
/**
* Array of playlist entries
* @type {Array}
*/
this.playlist = [];
/**
* Event will be called when tour starts to play,
* before any playlist entry starts to play.
* @type Event
*/
this.tourStart = new Event();
/**
* Event will be called when all playlist entries are
* played, or tour playback being canceled.
*
* If tour playback was terminated, event callback will
* be called with terminated=true parameter.
* @type Event
*/
this.tourEnd = new Event();
/**
* Event will be called when entry from playlist starts to play.
*
* Event callback will be called with curent entry as first parameter.
* @type Event
*/
this.entryStart = new Event();
/**
* Event will be called when entry from playlist ends to play.
*
* Event callback will be called with following parameters:
* 1. entry - entry
* 2. terminated - true if playback was terminated by calling {@link KmlTour#stop}
* @type Event
*/
this.entryEnd = new Event();
this._activeEntries = [];
}
/**
* Add entry to this tour playlist.
*
* @param {KmlTourFlyTo|KmlTourWait} entry an entry to add to the playlist.
*/
KmlTour.prototype.addPlaylistEntry = function (entry) {
this.playlist.push(entry);
};
/**
* Play this tour.
*
* @param {CesiumWidget} widget The widget.
* @param {object} [cameraOptions] these options will be merged with {@link Camera#flyTo}
* options for FlyTo playlist entries.
*/
KmlTour.prototype.play = function (widget, cameraOptions) {
this.tourStart.raiseEvent();
const tour = this;
playEntry.call(this, widget, cameraOptions, function (terminated) {
tour.playlistIndex = 0;
// Stop nonblocking entries
if (!terminated) {
cancelAllEntries(tour._activeEntries);
}
tour.tourEnd.raiseEvent(terminated);
});
};
/**
* Stop curently playing tour.
*/
KmlTour.prototype.stop = function () {
cancelAllEntries(this._activeEntries);
};
// Stop all activeEntries.
function cancelAllEntries(activeEntries) {
for (
let entry = activeEntries.pop();
entry !== undefined;
entry = activeEntries.pop()
) {
entry.stop();
}
}
// Play playlist entry.
// This function is called recursevly with playNext and iterates over all entries from playlist.
function playEntry(widget, cameraOptions, allDone) {
const entry = this.playlist[this.playlistIndex];
if (entry) {
const _playNext = playNext.bind(this, widget, cameraOptions, allDone);
this._activeEntries.push(entry);
this.entryStart.raiseEvent(entry);
if (entry.blocking) {
entry.play(_playNext, widget.scene.camera, cameraOptions);
} else {
const tour = this;
entry.play(function () {
tour.entryEnd.raiseEvent(entry);
const indx = tour._activeEntries.indexOf(entry);
if (indx >= 0) {
tour._activeEntries.splice(indx, 1);
}
});
_playNext(widget, cameraOptions, allDone);
}
} else if (defined(allDone)) {
allDone(false);
}
}
// Increment playlistIndex and call playEntry if terminated isn't true.
function playNext(widget, cameraOptions, allDone, terminated) {
const entry = this.playlist[this.playlistIndex];
this.entryEnd.raiseEvent(entry, terminated);
if (terminated) {
allDone(terminated);
} else {
const indx = this._activeEntries.indexOf(entry);
if (indx >= 0) {
this._activeEntries.splice(indx, 1);
}
this.playlistIndex++;
playEntry.call(this, widget, cameraOptions, allDone);
}
}
export default KmlTour;
+109
View File
@@ -0,0 +1,109 @@
import BoundingSphere from "../Core/BoundingSphere.js";
import combine from "../Core/combine.js";
import defined from "../Core/defined.js";
import EasingFunction from "../Core/EasingFunction.js";
/**
* Transitions the KmlTour to the next destination. This transition is facilitated
* using a specified flyToMode over a given number of seconds.
*
* @alias KmlTourFlyTo
* @constructor
*
* @param {number} duration entry duration
* @param {string} flyToMode KML fly to mode: bounce, smooth, etc
* @param {KmlCamera|KmlLookAt} view KmlCamera or KmlLookAt
*
* @see KmlTour
* @see KmlTourWait
*/
function KmlTourFlyTo(duration, flyToMode, view) {
this.type = "KmlTourFlyTo";
this.blocking = true;
this.activeCamera = null;
this.activeCallback = null;
this.duration = duration;
this.view = view;
this.flyToMode = flyToMode;
}
/**
* Play this playlist entry
*
* @param {KmlTourFlyTo.DoneCallback} done function which will be called when playback ends
* @param {Camera} camera Cesium camera
* @param {object} [cameraOptions] which will be merged with camera flyTo options. See {@link Camera#flyTo}
*/
KmlTourFlyTo.prototype.play = function (done, camera, cameraOptions) {
this.activeCamera = camera;
if (defined(done) && done !== null) {
const self = this;
this.activeCallback = function (terminated) {
delete self.activeCallback;
delete self.activeCamera;
done(defined(terminated) ? false : terminated);
};
}
const options = this.getCameraOptions(cameraOptions);
if (this.view.headingPitchRoll) {
camera.flyTo(options);
} else if (this.view.headingPitchRange) {
const target = new BoundingSphere(this.view.position);
camera.flyToBoundingSphere(target, options);
}
};
/**
* Stop execution of curent entry. Cancel camera flyTo
*/
KmlTourFlyTo.prototype.stop = function () {
if (defined(this.activeCamera)) {
this.activeCamera.cancelFlight();
}
if (defined(this.activeCallback)) {
this.activeCallback(true);
}
};
/**
* Returns options for {@link Camera#flyTo} or {@link Camera#flyToBoundingSphere}
* depends on this.view type.
*
* @param {object} cameraOptions options to merge with generated. See {@link Camera#flyTo}
* @returns {object} {@link Camera#flyTo} or {@link Camera#flyToBoundingSphere} options
*/
KmlTourFlyTo.prototype.getCameraOptions = function (cameraOptions) {
let options = {
duration: this.duration,
};
if (defined(this.activeCallback)) {
options.complete = this.activeCallback;
}
if (this.flyToMode === "smooth") {
options.easingFunction = EasingFunction.LINEAR_NONE;
}
if (this.view.headingPitchRoll) {
options.destination = this.view.position;
options.orientation = this.view.headingPitchRoll;
} else if (this.view.headingPitchRange) {
options.offset = this.view.headingPitchRange;
}
if (defined(cameraOptions)) {
options = combine(options, cameraOptions);
}
return options;
};
/**
* A function that will be executed when the flight completes.
* @callback KmlTourFlyTo.DoneCallback
*
* @param {boolean} terminated true if {@link KmlTourFlyTo#stop} was
* called before entry done playback.
*/
export default KmlTourFlyTo;
+52
View File
@@ -0,0 +1,52 @@
import defined from "../Core/defined.js";
/**
* Pauses the KmlTour for a given number of seconds.
*
* @alias KmlTourWait
* @constructor
*
* @param {number} duration entry duration
*
* @see KmlTour
* @see KmlTourFlyTo
*/
function KmlTourWait(duration) {
this.type = "KmlTourWait";
this.blocking = true;
this.duration = duration;
this.timeout = null;
}
/**
* Play this playlist entry
*
* @param {KmlTourWait.DoneCallback} done function which will be called when playback ends
*/
KmlTourWait.prototype.play = function (done) {
const self = this;
this.activeCallback = done;
this.timeout = setTimeout(function () {
delete self.activeCallback;
done(false);
}, this.duration * 1000);
};
/**
* Stop execution of curent entry, cancel curent timeout
*/
KmlTourWait.prototype.stop = function () {
clearTimeout(this.timeout);
if (defined(this.activeCallback)) {
this.activeCallback(true);
}
};
/**
* A function which will be called when playback ends.
*
* @callback KmlTourWait.DoneCallback
* @param {boolean} terminated true if {@link KmlTourWait#stop} was
* called before entry done playback.
*/
export default KmlTourWait;
@@ -0,0 +1,401 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} LabelGraphics.ConstructorOptions
*
* Initialization options for the LabelGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the label.
* @property {Property | string} [text] A Property specifying the text. Explicit newlines '\n' are supported.
* @property {Property | string} [font='30px sans-serif'] A Property specifying the CSS font.
* @property {Property | LabelStyle} [style=LabelStyle.FILL] A Property specifying the {@link LabelStyle}.
* @property {Property | number} [scale=1.0] A numeric Property specifying the scale to apply to the text.
* @property {Property | boolean} [showBackground=false] A boolean Property specifying the visibility of the background behind the label.
* @property {Property | Color} [backgroundColor=new Color(0.165, 0.165, 0.165, 0.8)] A Property specifying the background {@link Color}.
* @property {Property | Cartesian2} [backgroundPadding=new Cartesian2(7, 5)] A {@link Cartesian2} Property specifying the horizontal and vertical background padding in pixels.
* @property {Property | Cartesian2} [pixelOffset=Cartesian2.ZERO] A {@link Cartesian2} Property specifying the pixel offset.
* @property {Property | Cartesian3} [eyeOffset=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the eye offset.
* @property {Property | HorizontalOrigin} [horizontalOrigin=HorizontalOrigin.CENTER] A Property specifying the {@link HorizontalOrigin}.
* @property {Property | VerticalOrigin} [verticalOrigin=VerticalOrigin.CENTER] A Property specifying the {@link VerticalOrigin}.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
* @property {Property | Color} [fillColor=Color.WHITE] A Property specifying the fill {@link Color}.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the outline {@link Color}.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the outline width.
* @property {Property | NearFarScalar} [translucencyByDistance] A {@link NearFarScalar} Property used to set translucency based on distance from the camera.
* @property {Property | NearFarScalar} [pixelOffsetScaleByDistance] A {@link NearFarScalar} Property used to set pixelOffset based on distance from the camera.
* @property {Property | NearFarScalar} [scaleByDistance] A {@link NearFarScalar} Property used to set scale based on distance from the camera.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this label will be displayed.
* @property {Property | number} [disableDepthTestDistance] A Property specifying the distance from the camera at which to disable the depth test to.
*/
/**
* Describes a two dimensional label located at the position of the containing {@link Entity}.
* <p>
* <div align='center'>
* <img src='Images/Label.png' width='400' height='300' /><br />
* Example labels
* </div>
* </p>
*
* @alias LabelGraphics
* @constructor
*
* @param {LabelGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @demo {@link https://sandcastle.cesium.com/index.html?id=labels|Cesium Sandcastle Labels Demo}
*/
function LabelGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._text = undefined;
this._textSubscription = undefined;
this._font = undefined;
this._fontSubscription = undefined;
this._style = undefined;
this._styleSubscription = undefined;
this._scale = undefined;
this._scaleSubscription = undefined;
this._showBackground = undefined;
this._showBackgroundSubscription = undefined;
this._backgroundColor = undefined;
this._backgroundColorSubscription = undefined;
this._backgroundPadding = undefined;
this._backgroundPaddingSubscription = undefined;
this._pixelOffset = undefined;
this._pixelOffsetSubscription = undefined;
this._eyeOffset = undefined;
this._eyeOffsetSubscription = undefined;
this._horizontalOrigin = undefined;
this._horizontalOriginSubscription = undefined;
this._verticalOrigin = undefined;
this._verticalOriginSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._fillColor = undefined;
this._fillColorSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._translucencyByDistance = undefined;
this._translucencyByDistanceSubscription = undefined;
this._pixelOffsetScaleByDistance = undefined;
this._pixelOffsetScaleByDistanceSubscription = undefined;
this._scaleByDistance = undefined;
this._scaleByDistanceSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._disableDepthTestDistance = undefined;
this._disableDepthTestDistanceSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(LabelGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof LabelGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the label.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the string Property specifying the text of the label.
* Explicit newlines '\n' are supported.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
text: createPropertyDescriptor("text"),
/**
* Gets or sets the string Property specifying the font in CSS syntax.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/font|CSS font on MDN}
*/
font: createPropertyDescriptor("font"),
/**
* Gets or sets the Property specifying the {@link LabelStyle}.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
style: createPropertyDescriptor("style"),
/**
* Gets or sets the numeric Property specifying the uniform scale to apply to the image.
* A scale greater than <code>1.0</code> enlarges the label while a scale less than <code>1.0</code> shrinks it.
* <p>
* <div align='center'>
* <img src='Images/Label.setScale.png' width='400' height='300' /><br/>
* From left to right in the above image, the scales are <code>0.5</code>, <code>1.0</code>,
* and <code>2.0</code>.
* </div>
* </p>
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
scale: createPropertyDescriptor("scale"),
/**
* Gets or sets the boolean Property specifying the visibility of the background behind the label.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
* @default false
*/
showBackground: createPropertyDescriptor("showBackground"),
/**
* Gets or sets the Property specifying the background {@link Color}.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
* @default new Color(0.165, 0.165, 0.165, 0.8)
*/
backgroundColor: createPropertyDescriptor("backgroundColor"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the label's horizontal and vertical
* background padding in pixels.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
* @default new Cartesian2(7, 5)
*/
backgroundPadding: createPropertyDescriptor("backgroundPadding"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the label's pixel offset in screen space
* from the origin of this label. This is commonly used to align multiple labels and labels at
* the same position, e.g., an image and text. The screen space origin is the top, left corner of the
* canvas; <code>x</code> increases from left to right, and <code>y</code> increases from top to bottom.
* <p>
* <div align='center'>
* <table border='0' cellpadding='5'><tr>
* <td align='center'><code>default</code><br/><img src='Images/Label.setPixelOffset.default.png' width='250' height='188' /></td>
* <td align='center'><code>l.pixeloffset = new Cartesian2(25, 75);</code><br/><img src='Images/Label.setPixelOffset.x50y-25.png' width='250' height='188' /></td>
* </tr></table>
* The label's origin is indicated by the yellow point.
* </div>
* </p>
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
* @default Cartesian2.ZERO
*/
pixelOffset: createPropertyDescriptor("pixelOffset"),
/**
* Gets or sets the {@link Cartesian3} Property specifying the label's offset in eye coordinates.
* Eye coordinates is a left-handed coordinate system, where <code>x</code> points towards the viewer's
* right, <code>y</code> points up, and <code>z</code> points into the screen.
* <p>
* An eye offset is commonly used to arrange multiple labels or objects at the same position, e.g., to
* arrange a label above its corresponding 3D model.
* </p>
* Below, the label is positioned at the center of the Earth but an eye offset makes it always
* appear on top of the Earth regardless of the viewer's or Earth's orientation.
* <p>
* <div align='center'>
* <table border='0' cellpadding='5'><tr>
* <td align='center'><img src='Images/Billboard.setEyeOffset.one.png' width='250' height='188' /></td>
* <td align='center'><img src='Images/Billboard.setEyeOffset.two.png' width='250' height='188' /></td>
* </tr></table>
* <code>l.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);</code><br /><br />
* </div>
* </p>
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
* @default Cartesian3.ZERO
*/
eyeOffset: createPropertyDescriptor("eyeOffset"),
/**
* Gets or sets the Property specifying the {@link HorizontalOrigin}.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
horizontalOrigin: createPropertyDescriptor("horizontalOrigin"),
/**
* Gets or sets the Property specifying the {@link VerticalOrigin}.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
verticalOrigin: createPropertyDescriptor("verticalOrigin"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the Property specifying the fill {@link Color}.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
fillColor: createPropertyDescriptor("fillColor"),
/**
* Gets or sets the Property specifying the outline {@link Color}.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the outline width.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the translucency of the label based on the distance from the camera.
* A label's translucency will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the label's translucency remains clamped to the nearest bound.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
translucencyByDistance: createPropertyDescriptor("translucencyByDistance"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the pixel offset of the label based on the distance from the camera.
* A label's pixel offset will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the label's pixel offset remains clamped to the nearest bound.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
pixelOffsetScaleByDistance: createPropertyDescriptor(
"pixelOffsetScaleByDistance",
),
/**
* Gets or sets near and far scaling properties of a Label based on the label's distance from the camera.
* A label's scale will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the label's scale remains clamped to the nearest bound. If undefined,
* scaleByDistance will be disabled.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
scaleByDistance: createPropertyDescriptor("scaleByDistance"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this label will be displayed.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
* When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
* @memberof LabelGraphics.prototype
* @type {Property|undefined}
*/
disableDepthTestDistance: createPropertyDescriptor(
"disableDepthTestDistance",
),
});
/**
* Duplicates this instance.
*
* @param {LabelGraphics} [result] The object onto which to store the result.
* @returns {LabelGraphics} The modified result parameter or a new instance if one was not provided.
*/
LabelGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new LabelGraphics(this);
}
result.show = this.show;
result.text = this.text;
result.font = this.font;
result.style = this.style;
result.scale = this.scale;
result.showBackground = this.showBackground;
result.backgroundColor = this.backgroundColor;
result.backgroundPadding = this.backgroundPadding;
result.pixelOffset = this.pixelOffset;
result.eyeOffset = this.eyeOffset;
result.horizontalOrigin = this.horizontalOrigin;
result.verticalOrigin = this.verticalOrigin;
result.heightReference = this.heightReference;
result.fillColor = this.fillColor;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.translucencyByDistance = this.translucencyByDistance;
result.pixelOffsetScaleByDistance = this.pixelOffsetScaleByDistance;
result.scaleByDistance = this.scaleByDistance;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.disableDepthTestDistance = this.disableDepthTestDistance;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {LabelGraphics} source The object to be merged into this object.
*/
LabelGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.text = this.text ?? source.text;
this.font = this.font ?? source.font;
this.style = this.style ?? source.style;
this.scale = this.scale ?? source.scale;
this.showBackground = this.showBackground ?? source.showBackground;
this.backgroundColor = this.backgroundColor ?? source.backgroundColor;
this.backgroundPadding = this.backgroundPadding ?? source.backgroundPadding;
this.pixelOffset = this.pixelOffset ?? source.pixelOffset;
this.eyeOffset = this.eyeOffset ?? source.eyeOffset;
this.horizontalOrigin = this.horizontalOrigin ?? source.horizontalOrigin;
this.verticalOrigin = this.verticalOrigin ?? source.verticalOrigin;
this.heightReference = this.heightReference ?? source.heightReference;
this.fillColor = this.fillColor ?? source.fillColor;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.translucencyByDistance =
this.translucencyByDistance ?? source.translucencyByDistance;
this.pixelOffsetScaleByDistance =
this.pixelOffsetScaleByDistance ?? source.pixelOffsetScaleByDistance;
this.scaleByDistance = this.scaleByDistance ?? source.scaleByDistance;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.disableDepthTestDistance =
this.disableDepthTestDistance ?? source.disableDepthTestDistance;
};
export default LabelGraphics;
@@ -0,0 +1,359 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import NearFarScalar from "../Core/NearFarScalar.js";
import HeightReference from "../Scene/HeightReference.js";
import HorizontalOrigin from "../Scene/HorizontalOrigin.js";
import LabelStyle from "../Scene/LabelStyle.js";
import VerticalOrigin from "../Scene/VerticalOrigin.js";
import BoundingSphereState from "./BoundingSphereState.js";
import Property from "./Property.js";
const defaultScale = 1.0;
const defaultFont = "30px sans-serif";
const defaultStyle = LabelStyle.FILL;
const defaultFillColor = Color.WHITE;
const defaultOutlineColor = Color.BLACK;
const defaultOutlineWidth = 1.0;
const defaultShowBackground = false;
const defaultBackgroundColor = new Color(0.165, 0.165, 0.165, 0.8);
const defaultBackgroundPadding = new Cartesian2(7, 5);
const defaultPixelOffset = Cartesian2.ZERO;
const defaultEyeOffset = Cartesian3.ZERO;
const defaultHeightReference = HeightReference.NONE;
const defaultHorizontalOrigin = HorizontalOrigin.CENTER;
const defaultVerticalOrigin = VerticalOrigin.CENTER;
const positionScratch = new Cartesian3();
const fillColorScratch = new Color();
const outlineColorScratch = new Color();
const backgroundColorScratch = new Color();
const backgroundPaddingScratch = new Cartesian2();
const eyeOffsetScratch = new Cartesian3();
const pixelOffsetScratch = new Cartesian2();
const translucencyByDistanceScratch = new NearFarScalar();
const pixelOffsetScaleByDistanceScratch = new NearFarScalar();
const scaleByDistanceScratch = new NearFarScalar();
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
function EntityData(entity) {
this.entity = entity;
this.label = undefined;
this.index = undefined;
}
/**
* A {@link Visualizer} which maps the {@link LabelGraphics} instance
* in {@link Entity#label} to a {@link Label}.
* @alias LabelVisualizer
* @constructor
*
* @param {EntityCluster} entityCluster The entity cluster to manage the collection of billboards and optionally cluster with other entities.
* @param {EntityCollection} entityCollection The entityCollection to visualize.
*/
function LabelVisualizer(entityCluster, entityCollection) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entityCluster)) {
throw new DeveloperError("entityCluster is required.");
}
if (!defined(entityCollection)) {
throw new DeveloperError("entityCollection is required.");
}
//>>includeEnd('debug');
entityCollection.collectionChanged.addEventListener(
LabelVisualizer.prototype._onCollectionChanged,
this,
);
this._cluster = entityCluster;
this._entityCollection = entityCollection;
this._items = new AssociativeArray();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
/**
* Updates the primitives created by this visualizer to match their
* Entity counterpart at the given time.
*
* @param {JulianDate} time The time to update to.
* @returns {boolean} This function always returns true.
*/
LabelVisualizer.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
//>>includeEnd('debug');
const items = this._items.values;
const cluster = this._cluster;
for (let i = 0, len = items.length; i < len; i++) {
const item = items[i];
const entity = item.entity;
const labelGraphics = entity._label;
let text;
let label = item.label;
let show =
entity.isShowing &&
entity.isAvailable(time) &&
Property.getValueOrDefault(labelGraphics._show, time, true);
let position;
if (show) {
position = Property.getValueOrUndefined(
entity._position,
time,
positionScratch,
);
text = Property.getValueOrUndefined(labelGraphics._text, time);
show = defined(position) && defined(text);
}
if (!show) {
//don't bother creating or updating anything else
returnPrimitive(item, entity, cluster);
continue;
}
if (!Property.isConstant(entity._position)) {
cluster._clusterDirty = true;
}
let updateClamping = false;
const heightReference = Property.getValueOrDefault(
labelGraphics._heightReference,
time,
defaultHeightReference,
);
if (!defined(label)) {
label = cluster.getLabel(entity);
label.id = entity;
item.label = label;
// If this new label happens to have a position and height reference that match our new values,
// label._updateClamping will not be called automatically. That's a problem because the clamped
// height may be based on different terrain than is now loaded. So we'll manually call
// _updateClamping below.
updateClamping =
Cartesian3.equals(label.position, position) &&
label.heightReference === heightReference;
}
label.show = true;
label.position = position;
label.text = text;
label.scale = Property.getValueOrDefault(
labelGraphics._scale,
time,
defaultScale,
);
label.font = Property.getValueOrDefault(
labelGraphics._font,
time,
defaultFont,
);
label.style = Property.getValueOrDefault(
labelGraphics._style,
time,
defaultStyle,
);
label.fillColor = Property.getValueOrDefault(
labelGraphics._fillColor,
time,
defaultFillColor,
fillColorScratch,
);
label.outlineColor = Property.getValueOrDefault(
labelGraphics._outlineColor,
time,
defaultOutlineColor,
outlineColorScratch,
);
label.outlineWidth = Property.getValueOrDefault(
labelGraphics._outlineWidth,
time,
defaultOutlineWidth,
);
label.showBackground = Property.getValueOrDefault(
labelGraphics._showBackground,
time,
defaultShowBackground,
);
label.backgroundColor = Property.getValueOrDefault(
labelGraphics._backgroundColor,
time,
defaultBackgroundColor,
backgroundColorScratch,
);
label.backgroundPadding = Property.getValueOrDefault(
labelGraphics._backgroundPadding,
time,
defaultBackgroundPadding,
backgroundPaddingScratch,
);
label.pixelOffset = Property.getValueOrDefault(
labelGraphics._pixelOffset,
time,
defaultPixelOffset,
pixelOffsetScratch,
);
label.eyeOffset = Property.getValueOrDefault(
labelGraphics._eyeOffset,
time,
defaultEyeOffset,
eyeOffsetScratch,
);
label.heightReference = heightReference;
label.horizontalOrigin = Property.getValueOrDefault(
labelGraphics._horizontalOrigin,
time,
defaultHorizontalOrigin,
);
label.verticalOrigin = Property.getValueOrDefault(
labelGraphics._verticalOrigin,
time,
defaultVerticalOrigin,
);
label.translucencyByDistance = Property.getValueOrUndefined(
labelGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch,
);
label.pixelOffsetScaleByDistance = Property.getValueOrUndefined(
labelGraphics._pixelOffsetScaleByDistance,
time,
pixelOffsetScaleByDistanceScratch,
);
label.scaleByDistance = Property.getValueOrUndefined(
labelGraphics._scaleByDistance,
time,
scaleByDistanceScratch,
);
label.distanceDisplayCondition = Property.getValueOrUndefined(
labelGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch,
);
label.disableDepthTestDistance = Property.getValueOrUndefined(
labelGraphics._disableDepthTestDistance,
time,
);
if (updateClamping) {
label._updateClamping();
}
}
return true;
};
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
LabelVisualizer.prototype.getBoundingSphere = function (entity, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entity)) {
throw new DeveloperError("entity is required.");
}
if (!defined(result)) {
throw new DeveloperError("result is required.");
}
//>>includeEnd('debug');
const item = this._items.get(entity.id);
if (!defined(item) || !defined(item.label)) {
return BoundingSphereState.FAILED;
}
const label = item.label;
result.center = Cartesian3.clone(
label._clampedPosition ?? label.position,
result.center,
);
result.radius = 0;
return BoundingSphereState.DONE;
};
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
LabelVisualizer.prototype.isDestroyed = function () {
return false;
};
/**
* Removes and destroys all primitives created by this instance.
*/
LabelVisualizer.prototype.destroy = function () {
this._entityCollection.collectionChanged.removeEventListener(
LabelVisualizer.prototype._onCollectionChanged,
this,
);
const entities = this._entityCollection.values;
for (let i = 0; i < entities.length; i++) {
this._cluster.removeLabel(entities[i]);
}
return destroyObject(this);
};
LabelVisualizer.prototype._onCollectionChanged = function (
entityCollection,
added,
removed,
changed,
) {
let i;
let entity;
const items = this._items;
const cluster = this._cluster;
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
if (defined(entity._label) && defined(entity._position)) {
items.set(entity.id, new EntityData(entity));
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined(entity._label) && defined(entity._position)) {
if (!items.contains(entity.id)) {
items.set(entity.id, new EntityData(entity));
}
} else {
returnPrimitive(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
returnPrimitive(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
};
function returnPrimitive(item, entity, cluster) {
if (defined(item)) {
item.label = undefined;
cluster.removeLabel(entity);
}
}
export default LabelVisualizer;
@@ -0,0 +1,111 @@
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import JulianDate from "../Core/JulianDate.js";
import Material from "../Scene/Material.js";
/**
* The interface for all {@link Property} objects that represent {@link Material} uniforms.
* This type defines an interface and cannot be instantiated directly.
*
* @alias MaterialProperty
* @constructor
* @abstract
*
* @see ColorMaterialProperty
* @see CompositeMaterialProperty
* @see GridMaterialProperty
* @see ImageMaterialProperty
* @see PolylineGlowMaterialProperty
* @see PolylineOutlineMaterialProperty
* @see StripeMaterialProperty
*/
function MaterialProperty() {
DeveloperError.throwInstantiationError();
}
Object.defineProperties(MaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof MaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof MaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: DeveloperError.throwInstantiationError,
},
});
/**
* Gets the {@link Material} type at the provided time.
* @function
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
MaterialProperty.prototype.getType = DeveloperError.throwInstantiationError;
/**
* Gets the value of the property at the provided time.
* @function
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
MaterialProperty.prototype.getValue = DeveloperError.throwInstantiationError;
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
* @function
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
MaterialProperty.prototype.equals = DeveloperError.throwInstantiationError;
const timeScratch = new JulianDate();
/**
* @private
*/
MaterialProperty.getValue = function (time, materialProperty, material) {
let type;
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (defined(materialProperty)) {
type = materialProperty.getType(time);
if (defined(type)) {
if (!defined(material) || material.type !== type) {
material = Material.fromType(type);
}
materialProperty.getValue(time, material.uniforms);
return material;
}
}
if (!defined(material) || material.type !== Material.ColorType) {
material = Material.fromType(Material.ColorType);
}
Color.clone(Color.WHITE, material.uniforms.color);
return material;
};
export default MaterialProperty;
@@ -0,0 +1,456 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import NodeTransformationProperty from "./NodeTransformationProperty.js";
import PropertyBag from "./PropertyBag.js";
function createNodeTransformationProperty(value) {
return new NodeTransformationProperty(value);
}
function createNodeTransformationPropertyBag(value) {
return new PropertyBag(value, createNodeTransformationProperty);
}
function createArticulationStagePropertyBag(value) {
return new PropertyBag(value);
}
function createEnvironmentMapPropertyBag(value) {
return new PropertyBag(value);
}
/**
* @typedef {object} ModelGraphics.ConstructorOptions
*
* Initialization options for the ModelGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the model.
* @property {Property | string | Resource} [uri] A string or Resource Property specifying the URI of the glTF asset.
* @property {Property | number} [scale=1.0] A numeric Property specifying a uniform linear scale.
* @property {Property | boolean} [enableVerticalExaggeration=true] A boolean Property specifying if the model is exaggerated along the ellipsoid normal when {@link Scene.verticalExaggeration} is set to a value other than <code>1.0</code>.
* @property {Property | number} [minimumPixelSize=0.0] A numeric Property specifying the approximate minimum pixel size of the model regardless of zoom.
* @property {Property | number} [maximumScale] The maximum scale size of a model. An upper limit for minimumPixelSize.
* @property {Property | boolean} [incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
* @property {Property | boolean} [runAnimations=true] A boolean Property specifying if glTF animations specified in the model should be started.
* @property {Property | boolean} [clampAnimations=true] A boolean Property specifying if glTF animations should hold the last pose for time durations with no keyframes.
* @property {Property | ShadowMode} [shadows=ShadowMode.ENABLED] An enum Property specifying whether the model casts or receives shadows from light sources.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
* @property {Property | Color} [silhouetteColor=Color.RED] A Property specifying the {@link Color} of the silhouette.
* @property {Property | number} [silhouetteSize=0.0] A numeric Property specifying the size of the silhouette in pixels.
* @property {Property | Color} [color=Color.WHITE] A Property specifying the {@link Color} that blends with the model's rendered color.
* @property {Property | ColorBlendMode} [colorBlendMode=ColorBlendMode.HIGHLIGHT] An enum Property specifying how the color blends with the model.
* @property {Property | number} [colorBlendAmount=0.5] A numeric Property specifying the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.
* @property {Property | Cartesian2} [imageBasedLightingFactor=new Cartesian2(1.0, 1.0)] A property specifying the contribution from diffuse and specular image-based lighting.
* @property {PropertyBag | Object<string, *>} [environmentMapOptions] The properties for managing dynamic environment maps on this entity.
* @property {Property | Color} [lightColor] A property specifying the light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this model will be displayed.
* @property {PropertyBag | Object<string, TranslationRotationScale>} [nodeTransformations] An object, where keys are names of nodes, and values are {@link TranslationRotationScale} Properties describing the transformation to apply to that node. The transformation is applied after the node's existing transformation as specified in the glTF, and does not replace the node's existing transformation.
* @property {PropertyBag | Object<string, number>} [articulations] An object, where keys are composed of an articulation name, a single space, and a stage name, and the values are numeric properties.
* @property {Property | ClippingPlaneCollection} [clippingPlanes] A property specifying the {@link ClippingPlaneCollection} used to selectively disable rendering the model.
* @property {Property | CustomShader} [customShader] A property specifying the {@link CustomShader} to apply to this model.
*/
/**
* A 3D model based on {@link https://github.com/KhronosGroup/glTF|glTF}, the runtime asset format for WebGL, OpenGL ES, and OpenGL.
* The position and orientation of the model is determined by the containing {@link Entity}.
* <p>
* Cesium includes support for glTF geometry, materials, animations, and skinning.
* Cameras and lights are not currently supported.
* </p>
*
* @alias ModelGraphics
* @constructor
*
* @param {ModelGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @demo {@link https://sandcastle.cesium.com/index.html?id=3d-models|Cesium Sandcastle 3D Models Demo}
*/
function ModelGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._uri = undefined;
this._uriSubscription = undefined;
this._scale = undefined;
this._scaleSubscription = undefined;
this._hasVerticalExaggeration = undefined;
this._hasVerticalExaggerationSubscription = undefined;
this._enableVerticalExaggeration = undefined;
this._enableVerticalExaggerationSubscription = undefined;
this._minimumPixelSize = undefined;
this._minimumPixelSizeSubscription = undefined;
this._maximumScale = undefined;
this._maximumScaleSubscription = undefined;
this._incrementallyLoadTextures = undefined;
this._incrementallyLoadTexturesSubscription = undefined;
this._runAnimations = undefined;
this._runAnimationsSubscription = undefined;
this._clampAnimations = undefined;
this._clampAnimationsSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._silhouetteColor = undefined;
this._silhouetteColorSubscription = undefined;
this._silhouetteSize = undefined;
this._silhouetteSizeSubscription = undefined;
this._color = undefined;
this._colorSubscription = undefined;
this._colorBlendMode = undefined;
this._colorBlendModeSubscription = undefined;
this._colorBlendAmount = undefined;
this._colorBlendAmountSubscription = undefined;
this._imageBasedLightingFactor = undefined;
this._imageBasedLightingFactorSubscription = undefined;
this._environmentMapOptions = undefined;
this._environmentMapOptionsSubscription = undefined;
this._lightColor = undefined;
this._lightColorSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._nodeTransformations = undefined;
this._nodeTransformationsSubscription = undefined;
this._articulations = undefined;
this._articulationsSubscription = undefined;
this._clippingPlanes = undefined;
this._clippingPlanesSubscription = undefined;
this._customShader = undefined;
this._customShaderSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(ModelGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof ModelGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the model.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the string Property specifying the URI of the glTF asset.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
uri: createPropertyDescriptor("uri"),
/**
* Gets or sets the numeric Property specifying a uniform linear scale
* for this model. Values greater than 1.0 increase the size of the model while
* values less than 1.0 decrease it.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
scale: createPropertyDescriptor("scale"),
/**
* Gets or sets the boolean Property specifying if the model is exaggerated along the ellipsoid normal when {@link Scene.verticalExaggeration} is set to a value other than <code>1.0</code>.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default true
*/
enableVerticalExaggeration: createPropertyDescriptor(
"enableVerticalExaggeration",
),
/**
* Gets or sets the numeric Property specifying the approximate minimum
* pixel size of the model regardless of zoom. This can be used to ensure that
* a model is visible even when the viewer zooms out. When <code>0.0</code>,
* no minimum size is enforced.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
minimumPixelSize: createPropertyDescriptor("minimumPixelSize"),
/**
* Gets or sets the numeric Property specifying the maximum scale
* size of a model. This property is used as an upper limit for
* {@link ModelGraphics#minimumPixelSize}.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
maximumScale: createPropertyDescriptor("maximumScale"),
/**
* Get or sets the boolean Property specifying whether textures
* may continue to stream in after the model is loaded.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
incrementallyLoadTextures: createPropertyDescriptor(
"incrementallyLoadTextures",
),
/**
* Gets or sets the boolean Property specifying if glTF animations should be run.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default true
*/
runAnimations: createPropertyDescriptor("runAnimations"),
/**
* Gets or sets the boolean Property specifying if glTF animations should hold the last pose for time durations with no keyframes.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default true
*/
clampAnimations: createPropertyDescriptor("clampAnimations"),
/**
* Get or sets the enum Property specifying whether the model
* casts or receives shadows from light sources.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.ENABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the Property specifying the {@link Color} of the silhouette.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default Color.RED
*/
silhouetteColor: createPropertyDescriptor("silhouetteColor"),
/**
* Gets or sets the numeric Property specifying the size of the silhouette in pixels.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
silhouetteSize: createPropertyDescriptor("silhouetteSize"),
/**
* Gets or sets the Property specifying the {@link Color} that blends with the model's rendered color.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor("color"),
/**
* Gets or sets the enum Property specifying how the color blends with the model.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default ColorBlendMode.HIGHLIGHT
*/
colorBlendMode: createPropertyDescriptor("colorBlendMode"),
/**
* A numeric Property specifying the color strength when the <code>colorBlendMode</code> is MIX.
* A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with
* any value in-between resulting in a mix of the two.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
* @default 0.5
*/
colorBlendAmount: createPropertyDescriptor("colorBlendAmount"),
/**
* A property specifying the {@link Cartesian2} used to scale the diffuse and specular image-based lighting contribution to the final color.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
imageBasedLightingFactor: createPropertyDescriptor(
"imageBasedLightingFactor",
),
/**
* Gets or sets the {@link DynamicEnvironmentMapManager.ConstructorOptions} to apply to this model. This is represented as an {@link PropertyBag}.
* @memberof ModelGraphics.prototype
* @type {PropertyBag}
*/
environmentMapOptions: createPropertyDescriptor(
"environmentMapOptions",
undefined,
createEnvironmentMapPropertyBag,
),
/**
* A property specifying the {@link Cartesian3} light color when shading the model. When <code>undefined</code> the scene's light color is used instead.
* @memberOf ModelGraphics.prototype
* @type {Property|undefined}
*/
lightColor: createPropertyDescriptor("lightColor"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this model will be displayed.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the set of node transformations to apply to this model. This is represented as an {@link PropertyBag}, where keys are
* names of nodes, and values are {@link TranslationRotationScale} Properties describing the transformation to apply to that node.
* The transformation is applied after the node's existing transformation as specified in the glTF, and does not replace the node's existing transformation.
* @memberof ModelGraphics.prototype
* @type {PropertyBag}
*/
nodeTransformations: createPropertyDescriptor(
"nodeTransformations",
undefined,
createNodeTransformationPropertyBag,
),
/**
* Gets or sets the set of articulation values to apply to this model. This is represented as an {@link PropertyBag}, where keys are
* composed as the name of the articulation, a single space, and the name of the stage.
* @memberof ModelGraphics.prototype
* @type {PropertyBag}
*/
articulations: createPropertyDescriptor(
"articulations",
undefined,
createArticulationStagePropertyBag,
),
/**
* A property specifying the {@link ClippingPlaneCollection} used to selectively disable rendering the model.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
clippingPlanes: createPropertyDescriptor("clippingPlanes"),
/**
* Gets or sets the {@link CustomShader} to apply to this model. When <code>undefined</code>, no custom shader code is used.
* @memberof ModelGraphics.prototype
* @type {Property|undefined}
*/
customShader: createPropertyDescriptor("customShader"),
});
/**
* Duplicates this instance.
*
* @param {ModelGraphics} [result] The object onto which to store the result.
* @returns {ModelGraphics} The modified result parameter or a new instance if one was not provided.
*/
ModelGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new ModelGraphics(this);
}
result.show = this.show;
result.uri = this.uri;
result.scale = this.scale;
result.enableVerticalExaggeration = this.enableVerticalExaggeration;
result.minimumPixelSize = this.minimumPixelSize;
result.maximumScale = this.maximumScale;
result.incrementallyLoadTextures = this.incrementallyLoadTextures;
result.runAnimations = this.runAnimations;
result.clampAnimations = this.clampAnimations;
result.heightReference = this._heightReference;
result.silhouetteColor = this.silhouetteColor;
result.silhouetteSize = this.silhouetteSize;
result.color = this.color;
result.colorBlendMode = this.colorBlendMode;
result.colorBlendAmount = this.colorBlendAmount;
result.imageBasedLightingFactor = this.imageBasedLightingFactor;
result.environmentMapOptions = this.environmentMapOptions;
result.lightColor = this.lightColor;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.nodeTransformations = this.nodeTransformations;
result.articulations = this.articulations;
result.clippingPlanes = this.clippingPlanes;
result.customShader = this.customShader;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {ModelGraphics} source The object to be merged into this object.
*/
ModelGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.uri = this.uri ?? source.uri;
this.scale = this.scale ?? source.scale;
this.enableVerticalExaggeration =
this.enableVerticalExaggeration ?? source.enableVerticalExaggeration;
this.minimumPixelSize = this.minimumPixelSize ?? source.minimumPixelSize;
this.maximumScale = this.maximumScale ?? source.maximumScale;
this.incrementallyLoadTextures =
this.incrementallyLoadTextures ?? source.incrementallyLoadTextures;
this.runAnimations = this.runAnimations ?? source.runAnimations;
this.clampAnimations = this.clampAnimations ?? source.clampAnimations;
this.shadows = this.shadows ?? source.shadows;
this.heightReference = this.heightReference ?? source.heightReference;
this.silhouetteColor = this.silhouetteColor ?? source.silhouetteColor;
this.silhouetteSize = this.silhouetteSize ?? source.silhouetteSize;
this.color = this.color ?? source.color;
this.colorBlendMode = this.colorBlendMode ?? source.colorBlendMode;
this.colorBlendAmount = this.colorBlendAmount ?? source.colorBlendAmount;
this.imageBasedLightingFactor =
this.imageBasedLightingFactor ?? source.imageBasedLightingFactor;
this.environmentMapOptions =
this.environmentMapOptions ?? source.environmentMapOptions;
this.lightColor = this.lightColor ?? source.lightColor;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.clippingPlanes = this.clippingPlanes ?? source.clippingPlanes;
this.customShader = this.customShader ?? source.customShader;
const sourceNodeTransformations = source.nodeTransformations;
if (defined(sourceNodeTransformations)) {
const targetNodeTransformations = this.nodeTransformations;
if (defined(targetNodeTransformations)) {
targetNodeTransformations.merge(sourceNodeTransformations);
} else {
this.nodeTransformations = new PropertyBag(
sourceNodeTransformations,
createNodeTransformationProperty,
);
}
}
const sourceArticulations = source.articulations;
if (defined(sourceArticulations)) {
const targetArticulations = this.articulations;
if (defined(targetArticulations)) {
targetArticulations.merge(sourceArticulations);
} else {
this.articulations = new PropertyBag(sourceArticulations);
}
}
};
export default ModelGraphics;
@@ -0,0 +1,560 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import BoundingSphere from "../Core/BoundingSphere.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.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 Matrix4 from "../Core/Matrix4.js";
import Resource from "../Core/Resource.js";
import ColorBlendMode from "../Scene/ColorBlendMode.js";
import HeightReference, {
isHeightReferenceClamp,
} from "../Scene/HeightReference.js";
import Model from "../Scene/Model/Model.js";
import ModelAnimationLoop from "../Scene/ModelAnimationLoop.js";
import ShadowMode from "../Scene/ShadowMode.js";
import BoundingSphereState from "./BoundingSphereState.js";
import Property from "./Property.js";
import Cartographic from "../Core/Cartographic.js";
const defaultScale = 1.0;
const defaultEnableVerticalExaggeration = true;
const defaultMinimumPixelSize = 0.0;
const defaultIncrementallyLoadTextures = true;
const defaultClampAnimations = true;
const defaultShadows = ShadowMode.ENABLED;
const defaultHeightReference = HeightReference.NONE;
const defaultSilhouetteColor = Color.RED;
const defaultSilhouetteSize = 0.0;
const defaultColor = Color.WHITE;
const defaultColorBlendMode = ColorBlendMode.HIGHLIGHT;
const defaultColorBlendAmount = 0.5;
const defaultImageBasedLightingFactor = new Cartesian2(1.0, 1.0);
const defaultEnvironmentMapOptions = {
maximumPositionEpsilon: Number.POSITIVE_INFINITY,
};
const modelMatrixScratch = new Matrix4();
const nodeMatrixScratch = new Matrix4();
const scratchColor = new Color();
const scratchArray = new Array(4);
const scratchCartesian = new Cartesian3();
/**
* A {@link Visualizer} which maps {@link Entity#model} to a {@link Model}.
* @alias ModelVisualizer
* @constructor
*
* @param {Scene} scene The scene the primitives will be rendered in.
* @param {EntityCollection} entityCollection The entityCollection to visualize.
*/
function ModelVisualizer(scene, entityCollection) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.object("scene", scene);
Check.typeOf.object("entityCollection", entityCollection);
//>>includeEnd('debug');
entityCollection.collectionChanged.addEventListener(
ModelVisualizer.prototype._onCollectionChanged,
this,
);
this._scene = scene;
this._primitives = scene.primitives;
this._entityCollection = entityCollection;
this._modelHash = {};
this._entitiesToVisualize = new AssociativeArray();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
async function createModelPrimitive(
visualizer,
entity,
resource,
incrementallyLoadTextures,
environmentMapOptions,
) {
const primitives = visualizer._primitives;
const modelHash = visualizer._modelHash;
try {
const model = await Model.fromGltfAsync({
url: resource,
incrementallyLoadTextures: incrementallyLoadTextures,
scene: visualizer._scene,
environmentMapOptions: environmentMapOptions,
});
if (visualizer.isDestroyed() || !defined(modelHash[entity.id])) {
return;
}
model.id = entity;
primitives.add(model);
modelHash[entity.id].modelPrimitive = model;
model.errorEvent.addEventListener((error) => {
if (!defined(modelHash[entity.id])) {
return;
}
console.log(error);
// Texture failures when incrementallyLoadTextures
// will not affect the ability to compute the bounding sphere
if (error.name !== "TextureError" && model.incrementallyLoadTextures) {
modelHash[entity.id].loadFailed = true;
}
});
} catch (error) {
if (visualizer.isDestroyed() || !defined(modelHash[entity.id])) {
return;
}
console.log(error);
modelHash[entity.id].loadFailed = true;
}
}
/**
* Updates models created this visualizer to match their
* Entity counterpart at the given time.
*
* @param {JulianDate} time The time to update to.
* @returns {boolean} This function always returns true.
*/
ModelVisualizer.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
//>>includeEnd('debug');
const entities = this._entitiesToVisualize.values;
const modelHash = this._modelHash;
const primitives = this._primitives;
for (let i = 0, len = entities.length; i < len; i++) {
const entity = entities[i];
const modelGraphics = entity._model;
let resource;
let modelData = modelHash[entity.id];
let show =
entity.isShowing &&
entity.isAvailable(time) &&
Property.getValueOrDefault(modelGraphics._show, time, true);
let modelMatrix;
if (show) {
modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch);
resource = Resource.createIfNeeded(
Property.getValueOrUndefined(modelGraphics._uri, time),
);
show = defined(modelMatrix) && defined(resource);
}
if (!show) {
if (defined(modelData) && modelData.modelPrimitive) {
modelData.modelPrimitive.show = false;
}
continue;
}
if (!defined(modelData) || resource.url !== modelData.url) {
if (defined(modelData?.modelPrimitive)) {
primitives.removeAndDestroy(modelData.modelPrimitive);
delete modelHash[entity.id];
}
modelData = {
modelPrimitive: undefined,
url: resource.url,
animationsRunning: false,
nodeTransformationsScratch: {},
articulationsScratch: {},
loadFailed: false,
modelUpdated: false,
environmentMapOptionsScratch: {
...defaultEnvironmentMapOptions,
},
};
modelHash[entity.id] = modelData;
const incrementallyLoadTextures = Property.getValueOrDefault(
modelGraphics._incrementallyLoadTextures,
time,
defaultIncrementallyLoadTextures,
);
const environmentMapOptions = Property.getValueOrDefault(
modelGraphics._environmentMapOptions,
time,
defaultEnvironmentMapOptions,
modelData.environmentMapOptionsScratch,
);
createModelPrimitive(
this,
entity,
resource,
incrementallyLoadTextures,
environmentMapOptions,
);
}
const model = modelData.modelPrimitive;
if (!defined(model)) {
continue;
}
model.show = true;
model.scale = Property.getValueOrDefault(
modelGraphics._scale,
time,
defaultScale,
);
model.enableVerticalExaggeration = Property.getValueOrDefault(
modelGraphics._enableVerticalExaggeration,
time,
defaultEnableVerticalExaggeration,
);
model.minimumPixelSize = Property.getValueOrDefault(
modelGraphics._minimumPixelSize,
time,
defaultMinimumPixelSize,
);
model.maximumScale = Property.getValueOrUndefined(
modelGraphics._maximumScale,
time,
);
model.modelMatrix = Matrix4.clone(modelMatrix, model.modelMatrix);
model.shadows = Property.getValueOrDefault(
modelGraphics._shadows,
time,
defaultShadows,
);
model.heightReference = Property.getValueOrDefault(
modelGraphics._heightReference,
time,
defaultHeightReference,
);
model.distanceDisplayCondition = Property.getValueOrUndefined(
modelGraphics._distanceDisplayCondition,
time,
);
model.silhouetteColor = Property.getValueOrDefault(
modelGraphics._silhouetteColor,
time,
defaultSilhouetteColor,
scratchColor,
);
model.silhouetteSize = Property.getValueOrDefault(
modelGraphics._silhouetteSize,
time,
defaultSilhouetteSize,
);
model.color = Property.getValueOrDefault(
modelGraphics._color,
time,
defaultColor,
scratchColor,
);
model.colorBlendMode = Property.getValueOrDefault(
modelGraphics._colorBlendMode,
time,
defaultColorBlendMode,
);
model.colorBlendAmount = Property.getValueOrDefault(
modelGraphics._colorBlendAmount,
time,
defaultColorBlendAmount,
);
model.clippingPlanes = Property.getValueOrUndefined(
modelGraphics._clippingPlanes,
time,
);
model.clampAnimations = Property.getValueOrDefault(
modelGraphics._clampAnimations,
time,
defaultClampAnimations,
);
model.imageBasedLighting.imageBasedLightingFactor =
Property.getValueOrDefault(
modelGraphics._imageBasedLightingFactor,
time,
defaultImageBasedLightingFactor,
);
let lightColor = Property.getValueOrUndefined(
modelGraphics._lightColor,
time,
);
// Convert from Color to Cartesian3
if (defined(lightColor)) {
Color.pack(lightColor, scratchArray, 0);
lightColor = Cartesian3.unpack(scratchArray, 0, scratchCartesian);
}
model.lightColor = lightColor;
model.customShader = Property.getValueOrUndefined(
modelGraphics._customShader,
time,
);
// It's possible for getBoundingSphere to run before
// model becomes ready and these properties are updated
modelHash[entity.id].modelUpdated = true;
if (model.ready) {
const runAnimations = Property.getValueOrDefault(
modelGraphics._runAnimations,
time,
true,
);
if (modelData.animationsRunning !== runAnimations) {
if (runAnimations) {
model.activeAnimations.addAll({
loop: ModelAnimationLoop.REPEAT,
});
} else {
model.activeAnimations.removeAll();
}
modelData.animationsRunning = runAnimations;
}
// Apply node transformations
const nodeTransformations = Property.getValueOrUndefined(
modelGraphics._nodeTransformations,
time,
modelData.nodeTransformationsScratch,
);
if (defined(nodeTransformations)) {
const nodeNames = Object.keys(nodeTransformations);
for (
let nodeIndex = 0, nodeLength = nodeNames.length;
nodeIndex < nodeLength;
++nodeIndex
) {
const nodeName = nodeNames[nodeIndex];
const nodeTransformation = nodeTransformations[nodeName];
if (!defined(nodeTransformation)) {
continue;
}
const modelNode = model.getNode(nodeName);
if (!defined(modelNode)) {
continue;
}
const transformationMatrix = Matrix4.fromTranslationRotationScale(
nodeTransformation,
nodeMatrixScratch,
);
modelNode.matrix = Matrix4.multiply(
modelNode.originalMatrix,
transformationMatrix,
transformationMatrix,
);
}
}
// Apply articulations
let anyArticulationUpdated = false;
const articulations = Property.getValueOrUndefined(
modelGraphics._articulations,
time,
modelData.articulationsScratch,
);
if (defined(articulations)) {
const articulationStageKeys = Object.keys(articulations);
for (
let s = 0, numKeys = articulationStageKeys.length;
s < numKeys;
++s
) {
const key = articulationStageKeys[s];
const articulationStageValue = articulations[key];
if (!defined(articulationStageValue)) {
continue;
}
anyArticulationUpdated = true;
model.setArticulationStage(key, articulationStageValue);
}
}
if (anyArticulationUpdated) {
model.applyArticulations();
}
}
}
return true;
};
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
ModelVisualizer.prototype.isDestroyed = function () {
return false;
};
/**
* Removes and destroys all primitives created by this instance.
*/
ModelVisualizer.prototype.destroy = function () {
this._entityCollection.collectionChanged.removeEventListener(
ModelVisualizer.prototype._onCollectionChanged,
this,
);
const entities = this._entitiesToVisualize.values;
const modelHash = this._modelHash;
const primitives = this._primitives;
for (let i = entities.length - 1; i > -1; i--) {
removeModel(this, entities[i], modelHash, primitives);
}
return destroyObject(this);
};
const scratchPosition = new Cartesian3();
const scratchCartographic = new Cartographic();
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
ModelVisualizer.prototype.getBoundingSphere = function (entity, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entity)) {
throw new DeveloperError("entity is required.");
}
if (!defined(result)) {
throw new DeveloperError("result is required.");
}
//>>includeEnd('debug');
const modelData = this._modelHash[entity.id];
if (!defined(modelData)) {
return BoundingSphereState.FAILED;
}
if (modelData.loadFailed) {
return BoundingSphereState.FAILED;
}
const model = modelData.modelPrimitive;
if (!defined(model) || !model.show) {
return BoundingSphereState.PENDING;
}
if (!model.ready || !modelData.modelUpdated) {
return BoundingSphereState.PENDING;
}
const scene = this._scene;
const ellipsoid = scene.ellipsoid ?? Ellipsoid.default;
const hasHeightReference = model.heightReference !== HeightReference.NONE;
if (hasHeightReference) {
const modelMatrix = model.modelMatrix;
scratchPosition.x = modelMatrix[12];
scratchPosition.y = modelMatrix[13];
scratchPosition.z = modelMatrix[14];
const cartoPosition = ellipsoid.cartesianToCartographic(
scratchPosition,
scratchCartographic,
);
const height = scene.getHeight(cartoPosition, model.heightReference);
if (defined(height)) {
if (isHeightReferenceClamp(model.heightReference)) {
cartoPosition.height = height;
} else {
cartoPosition.height += height;
}
}
BoundingSphere.clone(model.boundingSphere, result);
result.center = ellipsoid.cartographicToCartesian(cartoPosition);
return BoundingSphereState.DONE;
}
BoundingSphere.clone(model.boundingSphere, result);
return BoundingSphereState.DONE;
};
/**
* @private
*/
ModelVisualizer.prototype._onCollectionChanged = function (
entityCollection,
added,
removed,
changed,
) {
let i;
let entity;
const entities = this._entitiesToVisualize;
const modelHash = this._modelHash;
const primitives = this._primitives;
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
if (defined(entity._model) && defined(entity._position)) {
entities.set(entity.id, entity);
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined(entity._model) && defined(entity._position)) {
clearNodeTransformationsArticulationsScratch(entity, modelHash);
entities.set(entity.id, entity);
} else {
removeModel(this, entity, modelHash, primitives);
entities.remove(entity.id);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
removeModel(this, entity, modelHash, primitives);
entities.remove(entity.id);
}
};
function removeModel(visualizer, entity, modelHash, primitives) {
const modelData = modelHash[entity.id];
if (defined(modelData)) {
primitives.removeAndDestroy(modelData.modelPrimitive);
delete modelHash[entity.id];
}
}
function clearNodeTransformationsArticulationsScratch(entity, modelHash) {
const modelData = modelHash[entity.id];
if (defined(modelData)) {
modelData.nodeTransformationsScratch = {};
modelData.articulationsScratch = {};
}
}
export default ModelVisualizer;
@@ -0,0 +1,150 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import TranslationRotationScale from "../Core/TranslationRotationScale.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
const defaultNodeTransformation = new TranslationRotationScale();
/**
* A {@link Property} that produces {@link TranslationRotationScale} data.
* @alias NodeTransformationProperty
* @constructor
*
* @param {object} [options] Object with the following properties:
* @param {Property|Cartesian3} [options.translation=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the (x, y, z) translation to apply to the node.
* @param {Property|Quaternion} [options.rotation=Quaternion.IDENTITY] A {@link Quaternion} Property specifying the (x, y, z, w) rotation to apply to the node.
* @param {Property|Cartesian3} [options.scale=new Cartesian3(1.0, 1.0, 1.0)] A {@link Cartesian3} Property specifying the (x, y, z) scaling to apply to the node.
*/
function NodeTransformationProperty(options) {
options = options ?? Frozen.EMPTY_OBJECT;
this._definitionChanged = new Event();
this._translation = undefined;
this._translationSubscription = undefined;
this._rotation = undefined;
this._rotationSubscription = undefined;
this._scale = undefined;
this._scaleSubscription = undefined;
this.translation = options.translation;
this.rotation = options.rotation;
this.scale = options.scale;
}
Object.defineProperties(NodeTransformationProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof NodeTransformationProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
Property.isConstant(this._translation) &&
Property.isConstant(this._rotation) &&
Property.isConstant(this._scale)
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof NodeTransformationProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the {@link Cartesian3} Property specifying the (x, y, z) translation to apply to the node.
* @memberof NodeTransformationProperty.prototype
* @type {Property|undefined}
* @default Cartesian3.ZERO
*/
translation: createPropertyDescriptor("translation"),
/**
* Gets or sets the {@link Quaternion} Property specifying the (x, y, z, w) rotation to apply to the node.
* @memberof NodeTransformationProperty.prototype
* @type {Property|undefined}
* @default Quaternion.IDENTITY
*/
rotation: createPropertyDescriptor("rotation"),
/**
* Gets or sets the {@link Cartesian3} Property specifying the (x, y, z) scaling to apply to the node.
* @memberof NodeTransformationProperty.prototype
* @type {Property|undefined}
* @default new Cartesian3(1.0, 1.0, 1.0)
*/
scale: createPropertyDescriptor("scale"),
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {TranslationRotationScale} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {TranslationRotationScale} The modified result parameter or a new instance if the result parameter was not supplied.
*/
NodeTransformationProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = new TranslationRotationScale();
}
result.translation = Property.getValueOrClonedDefault(
this._translation,
time,
defaultNodeTransformation.translation,
result.translation,
);
result.rotation = Property.getValueOrClonedDefault(
this._rotation,
time,
defaultNodeTransformation.rotation,
result.rotation,
);
result.scale = Property.getValueOrClonedDefault(
this._scale,
time,
defaultNodeTransformation.scale,
result.scale,
);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
NodeTransformationProperty.prototype.equals = function (other) {
return (
this === other ||
(other instanceof NodeTransformationProperty &&
Property.equals(this._translation, other._translation) &&
Property.equals(this._rotation, other._rotation) &&
Property.equals(this._scale, other._scale))
);
};
export default NodeTransformationProperty;
+174
View File
@@ -0,0 +1,174 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} PathGraphics.ConstructorOptions
*
* Initialization options for the PathGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the path.
* @property {Property | number} [leadTime] A Property specifying the number of seconds in front the object to show.
* @property {Property | number} [trailTime] A Property specifying the number of seconds behind of the object to show.
* @property {Property | number} [width=1.0] A numeric Property specifying the width in pixels.
* @property {Property | number} [resolution=60] A numeric Property specifying the maximum number of seconds to step when sampling the position.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to draw the path.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this path will be displayed.
* @property {Property | string} [relativeTo] A Property specifying the frame in which to visualize the path. Use another entity's id to visualize the path relative to that entity, or use the string values "FIXED" or "INERTIAL" to visualize the path in those reference frames.
*/
/**
* Describes a polyline defined as the path made by an {@link Entity} as it moves over time.
*
* @alias PathGraphics
* @constructor
*
* @param {PathGraphics.ConstructorOptions} [options] Object describing initialization options
*/
function PathGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._leadTime = undefined;
this._leadTimeSubscription = undefined;
this._trailTime = undefined;
this._trailTimeSubscription = undefined;
this._width = undefined;
this._widthSubscription = undefined;
this._resolution = undefined;
this._resolutionSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._relativeTo = undefined;
this._relativeToSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(PathGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof PathGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the path.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the Property specifying the number of seconds in front of the object to show.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
*/
leadTime: createPropertyDescriptor("leadTime"),
/**
* Gets or sets the Property specifying the number of seconds behind the object to show.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
*/
trailTime: createPropertyDescriptor("trailTime"),
/**
* Gets or sets the numeric Property specifying the width in pixels.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
width: createPropertyDescriptor("width"),
/**
* Gets or sets the Property specifying the maximum number of seconds to step when sampling the position.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
* @default 60
*/
resolution: createPropertyDescriptor("resolution"),
/**
* Gets or sets the Property specifying the material used to draw the path.
* @memberof PathGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this path will be displayed.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the frame in which to visualize the path. Use another entity's id to visualize the path relative to that entity, or use the string values "FIXED" or "INERTIAL" to visualize the path in those reference frames.
* @memberof PathGraphics.prototype
* @type {Property|undefined}
* @experimental This feature is not final and is subject to change without Cesium's standard deprecation policy.
*/
relativeTo: createPropertyDescriptor("relativeTo"),
});
/**
* Duplicates this instance.
*
* @param {PathGraphics} [result] The object onto which to store the result.
* @returns {PathGraphics} The modified result parameter or a new instance if one was not provided.
*/
PathGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new PathGraphics(this);
}
result.show = this.show;
result.leadTime = this.leadTime;
result.trailTime = this.trailTime;
result.width = this.width;
result.resolution = this.resolution;
result.material = this.material;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.relativeTo = this.relativeTo;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {PathGraphics} source The object to be merged into this object.
*/
PathGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.leadTime = this.leadTime ?? source.leadTime;
this.trailTime = this.trailTime ?? source.trailTime;
this.width = this.width ?? source.width;
this.resolution = this.resolution ?? source.resolution;
this.material = this.material ?? source.material;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.relativeTo = this.relativeTo ?? source.relativeTo;
};
export default PathGraphics;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,385 @@
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import Iso8601 from "../Core/Iso8601.js";
import CesiumMath from "../Core/Math.js";
import Matrix3 from "../Core/Matrix3.js";
import Matrix4 from "../Core/Matrix4.js";
import PlaneGeometry from "../Core/PlaneGeometry.js";
import PlaneOutlineGeometry from "../Core/PlaneOutlineGeometry.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import Property from "./Property.js";
const positionScratch = new Cartesian3();
const scratchColor = new Color();
function PlaneGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.plane = undefined;
this.dimensions = undefined;
}
/**
* A {@link GeometryUpdater} for planes.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias PlaneGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function PlaneGeometryUpdater(entity, scene) {
GeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new PlaneGeometryOptions(entity),
geometryPropertyName: "plane",
observedPropertyNames: ["availability", "position", "orientation", "plane"],
});
this._onEntityPropertyChanged(entity, "plane", entity.plane, undefined);
}
if (defined(Object.create)) {
PlaneGeometryUpdater.prototype = Object.create(GeometryUpdater.prototype);
PlaneGeometryUpdater.prototype.constructor = PlaneGeometryUpdater;
}
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
PlaneGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
let attributes;
let color;
const show = new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const distanceDisplayConditionAttribute =
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
);
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
color = ColorGeometryInstanceAttribute.fromColor(currentColor);
attributes = {
show: show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color: color,
};
} else {
attributes = {
show: show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
};
}
const planeGraphics = entity.plane;
const options = this._options;
let modelMatrix = entity.computeModelMatrix(time);
const plane = Property.getValueOrDefault(
planeGraphics.plane,
time,
options.plane,
);
const dimensions = Property.getValueOrUndefined(
planeGraphics.dimensions,
time,
options.dimensions,
);
options.plane = plane;
options.dimensions = dimensions;
modelMatrix = createPrimitiveMatrix(
plane,
dimensions,
modelMatrix,
modelMatrix,
);
return new GeometryInstance({
id: entity,
geometry: new PlaneGeometry(this._options),
modelMatrix: modelMatrix,
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
PlaneGeometryUpdater.prototype.createOutlineGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const planeGraphics = entity.plane;
const options = this._options;
let modelMatrix = entity.computeModelMatrix(time);
const plane = Property.getValueOrDefault(
planeGraphics.plane,
time,
options.plane,
);
const dimensions = Property.getValueOrUndefined(
planeGraphics.dimensions,
time,
options.dimensions,
);
options.plane = plane;
options.dimensions = dimensions;
modelMatrix = createPrimitiveMatrix(
plane,
dimensions,
modelMatrix,
modelMatrix,
);
return new GeometryInstance({
id: entity,
geometry: new PlaneOutlineGeometry(),
modelMatrix: modelMatrix,
attributes: {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
),
},
});
};
PlaneGeometryUpdater.prototype._isHidden = function (entity, plane) {
return (
!defined(plane.plane) ||
!defined(plane.dimensions) ||
!defined(entity.position) ||
GeometryUpdater.prototype._isHidden.call(this, entity, plane)
);
};
PlaneGeometryUpdater.prototype._getIsClosed = function (options) {
return false;
};
PlaneGeometryUpdater.prototype._isDynamic = function (entity, plane) {
return (
!entity.position.isConstant || //
!Property.isConstant(entity.orientation) || //
!plane.plane.isConstant || //
!plane.dimensions.isConstant || //
!Property.isConstant(plane.outlineWidth)
);
};
PlaneGeometryUpdater.prototype._setStaticOptions = function (entity, plane) {
const isColorMaterial =
this._materialProperty instanceof ColorMaterialProperty;
const options = this._options;
options.vertexFormat = isColorMaterial
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
options.plane = plane.plane.getValue(Iso8601.MINIMUM_VALUE, options.plane);
options.dimensions = plane.dimensions.getValue(
Iso8601.MINIMUM_VALUE,
options.dimensions,
);
};
PlaneGeometryUpdater.DynamicGeometryUpdater = DynamicPlaneGeometryUpdater;
/**
* @private
*/
function DynamicPlaneGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
}
if (defined(Object.create)) {
DynamicPlaneGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DynamicPlaneGeometryUpdater.prototype.constructor =
DynamicPlaneGeometryUpdater;
}
DynamicPlaneGeometryUpdater.prototype._isHidden = function (
entity,
plane,
time,
) {
const options = this._options;
const position = Property.getValueOrUndefined(
entity.position,
time,
positionScratch,
);
return (
!defined(position) ||
!defined(options.plane) ||
!defined(options.dimensions) ||
DynamicGeometryUpdater.prototype._isHidden.call(this, entity, plane, time)
);
};
DynamicPlaneGeometryUpdater.prototype._setOptions = function (
entity,
plane,
time,
) {
const options = this._options;
options.plane = Property.getValueOrDefault(plane.plane, time, options.plane);
options.dimensions = Property.getValueOrUndefined(
plane.dimensions,
time,
options.dimensions,
);
};
const scratchAxis = new Cartesian3();
const scratchUp = new Cartesian3();
const scratchTranslation = new Cartesian3();
const scratchScale = new Cartesian3();
const scratchRotation = new Matrix3();
const scratchRotationScale = new Matrix3();
const scratchLocalTransform = new Matrix4();
function createPrimitiveMatrix(plane, dimensions, transform, result) {
const normal = plane.normal;
const distance = plane.distance;
const translation = Cartesian3.multiplyByScalar(
normal,
-distance,
scratchTranslation,
);
let up = Cartesian3.clone(Cartesian3.UNIT_Z, scratchUp);
if (
CesiumMath.equalsEpsilon(
Math.abs(Cartesian3.dot(up, normal)),
1.0,
CesiumMath.EPSILON8,
)
) {
up = Cartesian3.clone(Cartesian3.UNIT_Y, up);
}
const left = Cartesian3.cross(up, normal, scratchAxis);
up = Cartesian3.cross(normal, left, up);
Cartesian3.normalize(left, left);
Cartesian3.normalize(up, up);
const rotationMatrix = scratchRotation;
Matrix3.setColumn(rotationMatrix, 0, left, rotationMatrix);
Matrix3.setColumn(rotationMatrix, 1, up, rotationMatrix);
Matrix3.setColumn(rotationMatrix, 2, normal, rotationMatrix);
const scale = Cartesian3.fromElements(
dimensions.x,
dimensions.y,
1.0,
scratchScale,
);
const rotationScaleMatrix = Matrix3.multiplyByScale(
rotationMatrix,
scale,
scratchRotationScale,
);
const localTransform = Matrix4.fromRotationTranslation(
rotationScaleMatrix,
translation,
scratchLocalTransform,
);
return Matrix4.multiplyTransformation(transform, localTransform, result);
}
/**
* @private
*/
PlaneGeometryUpdater.createPrimitiveMatrix = createPrimitiveMatrix;
export default PlaneGeometryUpdater;
@@ -0,0 +1,208 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} PlaneGraphics.ConstructorOptions
*
* Initialization options for the PlaneGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the plane.
* @property {Property | Plane} [plane] A {@link Plane} Property specifying the normal and distance for the plane.
* @property {Property | Cartesian2} [dimensions] A {@link Cartesian2} Property specifying the width and height of the plane.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the plane is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the plane.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the plane is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the plane casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this plane will be displayed.
*/
/**
* Describes a plane. The center position and orientation are determined by the containing {@link Entity}.
*
* @alias PlaneGraphics
* @constructor
*
* @param {PlaneGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @demo {@link https://sandcastle.cesium.com/index.html?id=plane|Cesium Sandcastle Plane Demo}
*/
function PlaneGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._plane = undefined;
this._planeSubscription = undefined;
this._dimensions = undefined;
this._dimensionsSubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(PlaneGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof PlaneGraphics.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the plane.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the {@link Plane} Property specifying the normal and distance of the plane.
*
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
*/
plane: createPropertyDescriptor("plane"),
/**
* Gets or sets the {@link Cartesian2} Property specifying the width and height of the plane.
*
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
*/
dimensions: createPropertyDescriptor("dimensions"),
/**
* Gets or sets the boolean Property specifying whether the plane is filled with the provided material.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the material used to fill the plane.
* @memberof PlaneGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying whether the plane is outlined.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Get or sets the enum Property specifying whether the plane
* casts or receives shadows from light sources.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this plane will be displayed.
* @memberof PlaneGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
});
/**
* Duplicates this instance.
*
* @param {PlaneGraphics} [result] The object onto which to store the result.
* @returns {PlaneGraphics} The modified result parameter or a new instance if one was not provided.
*/
PlaneGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new PlaneGraphics(this);
}
result.show = this.show;
result.plane = this.plane;
result.dimensions = this.dimensions;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {PlaneGraphics} source The object to be merged into this object.
*/
PlaneGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.plane = this.plane ?? source.plane;
this.dimensions = this.dimensions ?? source.dimensions;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
};
export default PlaneGraphics;
@@ -0,0 +1,223 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} PointGraphics.ConstructorOptions
*
* Initialization options for the PointGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the point.
* @property {Property | number} [pixelSize=1] A numeric Property specifying the size in pixels.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
* @property {Property | Color} [color=Color.WHITE] A Property specifying the {@link Color} of the point.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=0] A numeric Property specifying the the outline width in pixels.
* @property {Property | NearFarScalar} [scaleByDistance] A {@link NearFarScalar} Property used to scale the point based on distance.
* @property {Property | NearFarScalar} [translucencyByDistance] A {@link NearFarScalar} Property used to set translucency based on distance from the camera.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this point will be displayed.
* @property {Property | number} [disableDepthTestDistance] A Property specifying the distance from the camera at which to disable the depth test to.
* @property {Property | SplitDirection} [splitDirection] A Property specifying the {@link SplitDirection} split to apply to this point.
*/
/**
* Describes a graphical point located at the position of the containing {@link Entity}.
*
* @alias PointGraphics
* @constructor
*
* @param {PointGraphics.ConstructorOptions} [options] Object describing initialization options
*/
function PointGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._pixelSize = undefined;
this._pixelSizeSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._color = undefined;
this._colorSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._scaleByDistance = undefined;
this._scaleByDistanceSubscription = undefined;
this._translucencyByDistance = undefined;
this._translucencyByDistanceSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._disableDepthTestDistance = undefined;
this._disableDepthTestDistanceSubscription = undefined;
this._splitDirection = undefined;
this._splitDirectionSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(PointGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof PointGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the point.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the numeric Property specifying the size in pixels.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
* @default 1
*/
pixelSize: createPropertyDescriptor("pixelSize"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the Property specifying the {@link Color} of the point.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor("color"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the the outline width in pixels.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
* @default 0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Gets or sets the {@link NearFarScalar} Property used to scale the point based on distance.
* If undefined, a constant size is used.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
*/
scaleByDistance: createPropertyDescriptor("scaleByDistance"),
/**
* Gets or sets {@link NearFarScalar} Property specifying the translucency of the point based on the distance from the camera.
* A point's translucency will interpolate between the {@link NearFarScalar#nearValue} and
* {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
* of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
* Outside of these ranges the points's translucency remains clamped to the nearest bound.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
*/
translucencyByDistance: createPropertyDescriptor("translucencyByDistance"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this point will be displayed.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain.
* When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
*/
disableDepthTestDistance: createPropertyDescriptor(
"disableDepthTestDistance",
),
/**
* Gets or sets the Property specifying the {@link SplitDirection} of this point.
* @memberof PointGraphics.prototype
* @type {Property|undefined}
* @default SplitDirection.NONE
*/
splitDirection: createPropertyDescriptor("splitDirection"),
});
/**
* Duplicates this instance.
*
* @param {PointGraphics} [result] The object onto which to store the result.
* @returns {PointGraphics} The modified result parameter or a new instance if one was not provided.
*/
PointGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new PointGraphics(this);
}
result.show = this.show;
result.pixelSize = this.pixelSize;
result.heightReference = this.heightReference;
result.color = this.color;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.scaleByDistance = this.scaleByDistance;
result.translucencyByDistance = this._translucencyByDistance;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.disableDepthTestDistance = this.disableDepthTestDistance;
result.splitDirection = this.splitDirection;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {PointGraphics} source The object to be merged into this object.
*/
PointGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.pixelSize = this.pixelSize ?? source.pixelSize;
this.heightReference = this.heightReference ?? source.heightReference;
this.color = this.color ?? source.color;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.scaleByDistance = this.scaleByDistance ?? source.scaleByDistance;
this.translucencyByDistance =
this._translucencyByDistance ?? source.translucencyByDistance;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.disableDepthTestDistance =
this.disableDepthTestDistance ?? source.disableDepthTestDistance;
this.splitDirection = this.splitDirection ?? source.splitDirection;
};
export default PointGraphics;
@@ -0,0 +1,438 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import NearFarScalar from "../Core/NearFarScalar.js";
import createBillboardPointCallback from "../Scene/createBillboardPointCallback.js";
import HeightReference from "../Scene/HeightReference.js";
import BoundingSphereState from "./BoundingSphereState.js";
import Property from "./Property.js";
import SplitDirection from "../Scene/SplitDirection.js";
const defaultColor = Color.WHITE;
const defaultOutlineColor = Color.BLACK;
const defaultOutlineWidth = 0.0;
const defaultPixelSize = 1.0;
const defaultDisableDepthTestDistance = 0.0;
const defaultSplitDirection = SplitDirection.NONE;
const colorScratch = new Color();
const positionScratch = new Cartesian3();
const outlineColorScratch = new Color();
const scaleByDistanceScratch = new NearFarScalar();
const translucencyByDistanceScratch = new NearFarScalar();
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
function EntityData(entity) {
this.entity = entity;
this.pointPrimitive = undefined;
this.billboard = undefined;
this.color = undefined;
this.outlineColor = undefined;
this.pixelSize = undefined;
this.outlineWidth = undefined;
}
/**
* A {@link Visualizer} which maps {@link Entity#point} to a {@link PointPrimitive}.
* @alias PointVisualizer
* @constructor
*
* @param {EntityCluster} entityCluster The entity cluster to manage the collection of billboards and optionally cluster with other entities.
* @param {EntityCollection} entityCollection The entityCollection to visualize.
*/
function PointVisualizer(entityCluster, entityCollection) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entityCluster)) {
throw new DeveloperError("entityCluster is required.");
}
if (!defined(entityCollection)) {
throw new DeveloperError("entityCollection is required.");
}
//>>includeEnd('debug');
entityCollection.collectionChanged.addEventListener(
PointVisualizer.prototype._onCollectionChanged,
this,
);
this._cluster = entityCluster;
this._entityCollection = entityCollection;
this._items = new AssociativeArray();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
/**
* Updates the primitives created by this visualizer to match their
* Entity counterpart at the given time.
*
* @param {JulianDate} time The time to update to.
* @returns {boolean} This function always returns true.
*/
PointVisualizer.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
//>>includeEnd('debug');
const items = this._items.values;
const cluster = this._cluster;
for (let i = 0, len = items.length; i < len; i++) {
const item = items[i];
const entity = item.entity;
const pointGraphics = entity._point;
let pointPrimitive = item.pointPrimitive;
let billboard = item.billboard;
const heightReference = Property.getValueOrDefault(
pointGraphics._heightReference,
time,
HeightReference.NONE,
);
let show =
entity.isShowing &&
entity.isAvailable(time) &&
Property.getValueOrDefault(pointGraphics._show, time, true);
let position;
if (show) {
position = Property.getValueOrUndefined(
entity._position,
time,
positionScratch,
);
show = defined(position);
}
if (!show) {
returnPrimitive(item, entity, cluster);
continue;
}
if (!Property.isConstant(entity._position)) {
cluster._clusterDirty = true;
}
let needsRedraw = false;
let updateClamping = false;
if (heightReference !== HeightReference.NONE && !defined(billboard)) {
if (defined(pointPrimitive)) {
returnPrimitive(item, entity, cluster);
pointPrimitive = undefined;
}
billboard = cluster.getBillboard(entity);
billboard.id = entity;
billboard.image = undefined;
item.billboard = billboard;
needsRedraw = true;
// If this new billboard happens to have a position and height reference that match our new values,
// billboard._updateClamping will not be called automatically. That's a problem because the clamped
// height may be based on different terrain than is now loaded. So we'll manually call
// _updateClamping below.
updateClamping =
Cartesian3.equals(billboard.position, position) &&
billboard.heightReference === heightReference;
} else if (
heightReference === HeightReference.NONE &&
!defined(pointPrimitive)
) {
if (defined(billboard)) {
returnPrimitive(item, entity, cluster);
billboard = undefined;
}
pointPrimitive = cluster.getPoint(entity);
pointPrimitive.id = entity;
item.pointPrimitive = pointPrimitive;
}
if (defined(pointPrimitive)) {
pointPrimitive.show = true;
pointPrimitive.position = position;
pointPrimitive.scaleByDistance = Property.getValueOrUndefined(
pointGraphics._scaleByDistance,
time,
scaleByDistanceScratch,
);
pointPrimitive.translucencyByDistance = Property.getValueOrUndefined(
pointGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch,
);
pointPrimitive.color = Property.getValueOrDefault(
pointGraphics._color,
time,
defaultColor,
colorScratch,
);
pointPrimitive.outlineColor = Property.getValueOrDefault(
pointGraphics._outlineColor,
time,
defaultOutlineColor,
outlineColorScratch,
);
pointPrimitive.outlineWidth = Property.getValueOrDefault(
pointGraphics._outlineWidth,
time,
defaultOutlineWidth,
);
pointPrimitive.pixelSize = Property.getValueOrDefault(
pointGraphics._pixelSize,
time,
defaultPixelSize,
);
pointPrimitive.distanceDisplayCondition = Property.getValueOrUndefined(
pointGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch,
);
pointPrimitive.disableDepthTestDistance = Property.getValueOrDefault(
pointGraphics._disableDepthTestDistance,
time,
defaultDisableDepthTestDistance,
);
pointPrimitive.splitDirection = Property.getValueOrDefault(
pointGraphics._splitDirection,
time,
defaultSplitDirection,
);
} else if (defined(billboard)) {
billboard.show = true;
billboard.position = position;
billboard.scaleByDistance = Property.getValueOrUndefined(
pointGraphics._scaleByDistance,
time,
scaleByDistanceScratch,
);
billboard.translucencyByDistance = Property.getValueOrUndefined(
pointGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch,
);
billboard.distanceDisplayCondition = Property.getValueOrUndefined(
pointGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch,
);
billboard.disableDepthTestDistance = Property.getValueOrDefault(
pointGraphics._disableDepthTestDistance,
time,
defaultDisableDepthTestDistance,
);
billboard.splitDirection = Property.getValueOrDefault(
pointGraphics._splitDirection,
time,
defaultSplitDirection,
);
billboard.heightReference = heightReference;
const newColor = Property.getValueOrDefault(
pointGraphics._color,
time,
defaultColor,
colorScratch,
);
const newOutlineColor = Property.getValueOrDefault(
pointGraphics._outlineColor,
time,
defaultOutlineColor,
outlineColorScratch,
);
const newOutlineWidth = Math.round(
Property.getValueOrDefault(
pointGraphics._outlineWidth,
time,
defaultOutlineWidth,
),
);
let newPixelSize = Math.max(
1,
Math.round(
Property.getValueOrDefault(
pointGraphics._pixelSize,
time,
defaultPixelSize,
),
),
);
if (newOutlineWidth > 0) {
billboard.scale = 1.0;
needsRedraw =
needsRedraw || //
newOutlineWidth !== item.outlineWidth || //
newPixelSize !== item.pixelSize || //
!Color.equals(newColor, item.color) || //
!Color.equals(newOutlineColor, item.outlineColor);
} else {
billboard.scale = newPixelSize / 50.0;
newPixelSize = 50.0;
needsRedraw =
needsRedraw || //
newOutlineWidth !== item.outlineWidth || //
!Color.equals(newColor, item.color) || //
!Color.equals(newOutlineColor, item.outlineColor);
}
if (needsRedraw) {
item.color = Color.clone(newColor, item.color);
item.outlineColor = Color.clone(newOutlineColor, item.outlineColor);
item.pixelSize = newPixelSize;
item.outlineWidth = newOutlineWidth;
const centerAlpha = newColor.alpha;
const cssColor = newColor.toCssColorString();
const cssOutlineColor = newOutlineColor.toCssColorString();
const textureId = JSON.stringify([
cssColor,
newPixelSize,
cssOutlineColor,
newOutlineWidth,
]);
billboard.setImage(
textureId,
createBillboardPointCallback(
centerAlpha,
cssColor,
cssOutlineColor,
newOutlineWidth,
newPixelSize,
),
);
}
if (updateClamping) {
billboard._updateClamping();
}
}
}
return true;
};
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
PointVisualizer.prototype.getBoundingSphere = function (entity, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entity)) {
throw new DeveloperError("entity is required.");
}
if (!defined(result)) {
throw new DeveloperError("result is required.");
}
//>>includeEnd('debug');
const item = this._items.get(entity.id);
if (
!defined(item) ||
!(defined(item.pointPrimitive) || defined(item.billboard))
) {
return BoundingSphereState.FAILED;
}
if (defined(item.pointPrimitive)) {
result.center = Cartesian3.clone(
item.pointPrimitive.position,
result.center,
);
} else {
const billboard = item.billboard;
if (!defined(billboard._clampedPosition)) {
return BoundingSphereState.PENDING;
}
result.center = Cartesian3.clone(billboard._clampedPosition, result.center);
}
result.radius = 0;
return BoundingSphereState.DONE;
};
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
PointVisualizer.prototype.isDestroyed = function () {
return false;
};
/**
* Removes and destroys all primitives created by this instance.
*/
PointVisualizer.prototype.destroy = function () {
this._entityCollection.collectionChanged.removeEventListener(
PointVisualizer.prototype._onCollectionChanged,
this,
);
const entities = this._entityCollection.values;
for (let i = 0; i < entities.length; i++) {
this._cluster.removePoint(entities[i]);
}
return destroyObject(this);
};
PointVisualizer.prototype._onCollectionChanged = function (
entityCollection,
added,
removed,
changed,
) {
let i;
let entity;
const items = this._items;
const cluster = this._cluster;
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
if (defined(entity._point) && defined(entity._position)) {
items.set(entity.id, new EntityData(entity));
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined(entity._point) && defined(entity._position)) {
if (!items.contains(entity.id)) {
items.set(entity.id, new EntityData(entity));
}
} else {
returnPrimitive(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
returnPrimitive(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
};
function returnPrimitive(item, entity, cluster) {
if (defined(item)) {
const pointPrimitive = item.pointPrimitive;
if (defined(pointPrimitive)) {
item.pointPrimitive = undefined;
cluster.removePoint(entity);
return;
}
const billboard = item.billboard;
if (defined(billboard)) {
item.billboard = undefined;
cluster.removeBillboard(entity);
}
}
}
export default PointVisualizer;
@@ -0,0 +1,591 @@
import ApproximateTerrainHeights from "../Core/ApproximateTerrainHeights.js";
import ArcType from "../Core/ArcType.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import CoplanarPolygonGeometry from "../Core/CoplanarPolygonGeometry.js";
import CoplanarPolygonOutlineGeometry from "../Core/CoplanarPolygonOutlineGeometry.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import EllipsoidTangentPlane from "../Core/EllipsoidTangentPlane.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import Iso8601 from "../Core/Iso8601.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import oneTimeWarning from "../Core/oneTimeWarning.js";
import PolygonGeometry from "../Core/PolygonGeometry.js";
import PolygonOutlineGeometry from "../Core/PolygonOutlineGeometry.js";
import Rectangle from "../Core/Rectangle.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import HeightReference from "../Scene/HeightReference.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import GroundGeometryUpdater from "./GroundGeometryUpdater.js";
import Property from "./Property.js";
const heightAndPerPositionHeightWarning =
"Entity polygons cannot have both height and perPositionHeight. height will be ignored";
const heightReferenceAndPerPositionHeightWarning =
"heightReference is not supported for entity polygons with perPositionHeight. heightReference will be ignored";
const scratchColor = new Color();
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
const scratchRectangle = new Rectangle();
const scratch2DPositions = [];
const cart2Scratch = new Cartesian2();
function PolygonGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.polygonHierarchy = undefined;
this.perPositionHeight = undefined;
this.closeTop = undefined;
this.closeBottom = undefined;
this.height = undefined;
this.extrudedHeight = undefined;
this.granularity = undefined;
this.stRotation = undefined;
this.offsetAttribute = undefined;
this.arcType = undefined;
this.textureCoordinates = undefined;
}
/**
* A {@link GeometryUpdater} for polygons.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias PolygonGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function PolygonGeometryUpdater(entity, scene) {
GroundGeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new PolygonGeometryOptions(entity),
geometryPropertyName: "polygon",
observedPropertyNames: ["availability", "polygon"],
});
this._onEntityPropertyChanged(entity, "polygon", entity.polygon, undefined);
}
if (defined(Object.create)) {
PolygonGeometryUpdater.prototype = Object.create(
GroundGeometryUpdater.prototype,
);
PolygonGeometryUpdater.prototype.constructor = PolygonGeometryUpdater;
}
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
PolygonGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const options = this._options;
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time),
),
offset: undefined,
color: undefined,
};
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
}
if (defined(options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
let geometry;
if (options.perPositionHeight && !defined(options.extrudedHeight)) {
geometry = new CoplanarPolygonGeometry(options);
} else {
geometry = new PolygonGeometry(options);
}
return new GeometryInstance({
id: entity,
geometry: geometry,
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
PolygonGeometryUpdater.prototype.createOutlineGeometryInstance = function (
time,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const options = this._options;
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
),
offset: undefined,
};
if (defined(options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
let geometry;
if (options.perPositionHeight && !defined(options.extrudedHeight)) {
geometry = new CoplanarPolygonOutlineGeometry(options);
} else {
geometry = new PolygonOutlineGeometry(options);
}
return new GeometryInstance({
id: entity,
geometry: geometry,
attributes: attributes,
});
};
PolygonGeometryUpdater.prototype._computeCenter = function (time, result) {
const hierarchy = Property.getValueOrUndefined(
this._entity.polygon.hierarchy,
time,
);
if (!defined(hierarchy)) {
return;
}
const positions = hierarchy.positions;
if (positions.length === 0) {
return;
}
const ellipsoid = this._scene.ellipsoid;
const tangentPlane = EllipsoidTangentPlane.fromPoints(positions, ellipsoid);
const positions2D = tangentPlane.projectPointsOntoPlane(
positions,
scratch2DPositions,
);
const length = positions2D.length;
let area = 0;
let j = length - 1;
let centroid2D = new Cartesian2();
for (let i = 0; i < length; j = i++) {
const p1 = positions2D[i];
const p2 = positions2D[j];
const f = p1.x * p2.y - p2.x * p1.y;
let sum = Cartesian2.add(p1, p2, cart2Scratch);
sum = Cartesian2.multiplyByScalar(sum, f, sum);
centroid2D = Cartesian2.add(centroid2D, sum, centroid2D);
area += f;
}
const a = 1.0 / (area * 3.0);
centroid2D = Cartesian2.multiplyByScalar(centroid2D, a, centroid2D);
return tangentPlane.projectPointOntoEllipsoid(centroid2D, result);
};
PolygonGeometryUpdater.prototype._isHidden = function (entity, polygon) {
return (
!defined(polygon.hierarchy) ||
GeometryUpdater.prototype._isHidden.call(this, entity, polygon)
);
};
PolygonGeometryUpdater.prototype._isOnTerrain = function (entity, polygon) {
const onTerrain = GroundGeometryUpdater.prototype._isOnTerrain.call(
this,
entity,
polygon,
);
const perPositionHeightProperty = polygon.perPositionHeight;
const perPositionHeightEnabled =
defined(perPositionHeightProperty) &&
(perPositionHeightProperty.isConstant
? perPositionHeightProperty.getValue(Iso8601.MINIMUM_VALUE)
: true);
return onTerrain && !perPositionHeightEnabled;
};
PolygonGeometryUpdater.prototype._isDynamic = function (entity, polygon) {
return (
!polygon.hierarchy.isConstant || //
!Property.isConstant(polygon.height) || //
!Property.isConstant(polygon.extrudedHeight) || //
!Property.isConstant(polygon.granularity) || //
!Property.isConstant(polygon.stRotation) || //
!Property.isConstant(polygon.textureCoordinates) || //
!Property.isConstant(polygon.outlineWidth) || //
!Property.isConstant(polygon.perPositionHeight) || //
!Property.isConstant(polygon.closeTop) || //
!Property.isConstant(polygon.closeBottom) || //
!Property.isConstant(polygon.zIndex) || //
!Property.isConstant(polygon.arcType) || //
(this._onTerrain &&
!Property.isConstant(this._materialProperty) &&
!(this._materialProperty instanceof ColorMaterialProperty))
);
};
PolygonGeometryUpdater.prototype._setStaticOptions = function (
entity,
polygon,
) {
const isColorMaterial =
this._materialProperty instanceof ColorMaterialProperty;
const options = this._options;
options.vertexFormat = isColorMaterial
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
const hierarchyValue = polygon.hierarchy.getValue(Iso8601.MINIMUM_VALUE);
let heightValue = Property.getValueOrUndefined(
polygon.height,
Iso8601.MINIMUM_VALUE,
);
const heightReferenceValue = Property.getValueOrDefault(
polygon.heightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
let extrudedHeightValue = Property.getValueOrUndefined(
polygon.extrudedHeight,
Iso8601.MINIMUM_VALUE,
);
const extrudedHeightReferenceValue = Property.getValueOrDefault(
polygon.extrudedHeightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
const perPositionHeightValue = Property.getValueOrDefault(
polygon.perPositionHeight,
Iso8601.MINIMUM_VALUE,
false,
);
heightValue = GroundGeometryUpdater.getGeometryHeight(
heightValue,
heightReferenceValue,
);
let offsetAttribute;
if (perPositionHeightValue) {
if (defined(heightValue)) {
heightValue = undefined;
oneTimeWarning(heightAndPerPositionHeightWarning);
}
if (
heightReferenceValue !== HeightReference.NONE &&
perPositionHeightValue
) {
heightValue = undefined;
oneTimeWarning(heightReferenceAndPerPositionHeightWarning);
}
} else {
if (defined(extrudedHeightValue) && !defined(heightValue)) {
heightValue = 0;
}
offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue,
);
}
options.polygonHierarchy = hierarchyValue;
options.granularity = Property.getValueOrUndefined(
polygon.granularity,
Iso8601.MINIMUM_VALUE,
);
options.stRotation = Property.getValueOrUndefined(
polygon.stRotation,
Iso8601.MINIMUM_VALUE,
);
options.perPositionHeight = perPositionHeightValue;
options.closeTop = Property.getValueOrDefault(
polygon.closeTop,
Iso8601.MINIMUM_VALUE,
true,
);
options.closeBottom = Property.getValueOrDefault(
polygon.closeBottom,
Iso8601.MINIMUM_VALUE,
true,
);
options.offsetAttribute = offsetAttribute;
options.height = heightValue;
options.arcType = Property.getValueOrDefault(
polygon.arcType,
Iso8601.MINIMUM_VALUE,
ArcType.GEODESIC,
);
options.textureCoordinates = Property.getValueOrUndefined(
polygon.textureCoordinates,
Iso8601.MINIMUM_VALUE,
);
extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue,
);
if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
const rectangle = PolygonGeometry.computeRectangleFromPositions(
options.polygonHierarchy.positions,
options.ellipsoid,
options.arcType,
scratchRectangle,
);
extrudedHeightValue =
ApproximateTerrainHeights.getMinimumMaximumHeights(
rectangle,
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
PolygonGeometryUpdater.prototype._getIsClosed = function (options) {
const height = options.height;
const extrudedHeight = options.extrudedHeight;
const isExtruded = defined(extrudedHeight) && extrudedHeight !== height;
return (
!options.perPositionHeight &&
((!isExtruded && height === 0) ||
(isExtruded && options.closeTop && options.closeBottom))
);
};
PolygonGeometryUpdater.DynamicGeometryUpdater = DyanmicPolygonGeometryUpdater;
/**
* @private
*/
function DyanmicPolygonGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
}
if (defined(Object.create)) {
DyanmicPolygonGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DyanmicPolygonGeometryUpdater.prototype.constructor =
DyanmicPolygonGeometryUpdater;
}
DyanmicPolygonGeometryUpdater.prototype._isHidden = function (
entity,
polygon,
time,
) {
return (
!defined(this._options.polygonHierarchy) ||
DynamicGeometryUpdater.prototype._isHidden.call(this, entity, polygon, time)
);
};
DyanmicPolygonGeometryUpdater.prototype._setOptions = function (
entity,
polygon,
time,
) {
const options = this._options;
options.polygonHierarchy = Property.getValueOrUndefined(
polygon.hierarchy,
time,
);
let heightValue = Property.getValueOrUndefined(polygon.height, time);
const heightReferenceValue = Property.getValueOrDefault(
polygon.heightReference,
time,
HeightReference.NONE,
);
const extrudedHeightReferenceValue = Property.getValueOrDefault(
polygon.extrudedHeightReference,
time,
HeightReference.NONE,
);
let extrudedHeightValue = Property.getValueOrUndefined(
polygon.extrudedHeight,
time,
);
const perPositionHeightValue = Property.getValueOrUndefined(
polygon.perPositionHeight,
time,
);
heightValue = GroundGeometryUpdater.getGeometryHeight(
heightValue,
extrudedHeightReferenceValue,
);
let offsetAttribute;
if (perPositionHeightValue) {
if (defined(heightValue)) {
heightValue = undefined;
oneTimeWarning(heightAndPerPositionHeightWarning);
}
if (
heightReferenceValue !== HeightReference.NONE &&
perPositionHeightValue
) {
heightValue = undefined;
oneTimeWarning(heightReferenceAndPerPositionHeightWarning);
}
} else {
if (defined(extrudedHeightValue) && !defined(heightValue)) {
heightValue = 0;
}
offsetAttribute = GroundGeometryUpdater.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue,
);
}
options.granularity = Property.getValueOrUndefined(polygon.granularity, time);
options.stRotation = Property.getValueOrUndefined(polygon.stRotation, time);
options.textureCoordinates = Property.getValueOrUndefined(
polygon.textureCoordinates,
time,
);
options.perPositionHeight = Property.getValueOrUndefined(
polygon.perPositionHeight,
time,
);
options.closeTop = Property.getValueOrDefault(polygon.closeTop, time, true);
options.closeBottom = Property.getValueOrDefault(
polygon.closeBottom,
time,
true,
);
options.offsetAttribute = offsetAttribute;
options.height = heightValue;
options.arcType = Property.getValueOrDefault(
polygon.arcType,
time,
ArcType.GEODESIC,
);
extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue,
);
if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
const rectangle = PolygonGeometry.computeRectangleFromPositions(
options.polygonHierarchy.positions,
options.ellipsoid,
options.arcType,
scratchRectangle,
);
extrudedHeightValue =
ApproximateTerrainHeights.getMinimumMaximumHeights(
rectangle,
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
export default PolygonGeometryUpdater;
@@ -0,0 +1,383 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import PolygonHierarchy from "../Core/PolygonHierarchy.js";
import ConstantProperty from "./ConstantProperty.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
function createPolygonHierarchyProperty(value) {
if (Array.isArray(value)) {
// convert array of positions to PolygonHierarchy object
value = new PolygonHierarchy(value);
}
return new ConstantProperty(value);
}
/**
* @typedef {object} PolygonGraphics.ConstructorOptions
*
* Initialization options for the PolygonGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the polygon.
* @property {Property | PolygonHierarchy | Cartesian3[]} [hierarchy] A Property specifying the {@link PolygonHierarchy}.
* @property {Property | number} [height=0] A numeric Property specifying the altitude of the polygon relative to the ellipsoid surface.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
* @property {Property | number} [extrudedHeight] A numeric Property specifying the altitude of the polygon's extruded face relative to the ellipsoid surface.
* @property {Property | HeightReference} [extrudedHeightReference=HeightReference.NONE] A Property specifying what the extrudedHeight is relative to.
* @property {Property | number} [stRotation=0.0] A numeric property specifying the rotation of the polygon texture counter-clockwise from north. Only has an effect if textureCoordinates is not defined.
* @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between each latitude and longitude point.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the polygon is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the polygon.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the polygon is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | boolean} [perPositionHeight=false] A boolean specifying whether or not the height of each position is used.
* @property {boolean | boolean} [closeTop=true] When false, leaves off the top of an extruded polygon open.
* @property {boolean | boolean} [closeBottom=true] When false, leaves off the bottom of an extruded polygon open.
* @property {Property | ArcType} [arcType=ArcType.GEODESIC] The type of line the polygon edges must follow.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the polygon casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this polygon will be displayed.
* @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this polygon will classify terrain, 3D Tiles, or both when on the ground.
* @property {ConstantProperty | number} [zIndex=0] A property specifying the zIndex used for ordering ground geometry. Only has an effect if the polygon is constant and neither height or extrudedHeight are specified.
* @property {Property | PolygonHierarchy} [textureCoordinates] A Property specifying texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives.
*/
/**
* Describes a polygon defined by an hierarchy of linear rings which make up the outer shape and any nested holes.
* The polygon conforms to the curvature of the globe and can be placed on the surface or
* at altitude and can optionally be extruded into a volume.
*
* @alias PolygonGraphics
* @constructor
*
* @param {PolygonGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @see Entity
* @demo {@link https://sandcastle.cesium.com/index.html?id=polygon|Cesium Sandcastle Polygon Demo}
*/
function PolygonGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._hierarchy = undefined;
this._hierarchySubscription = undefined;
this._height = undefined;
this._heightSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._extrudedHeight = undefined;
this._extrudedHeightSubscription = undefined;
this._extrudedHeightReference = undefined;
this._extrudedHeightReferenceSubscription = undefined;
this._stRotation = undefined;
this._stRotationSubscription = undefined;
this._granularity = undefined;
this._granularitySubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._perPositionHeight = undefined;
this._perPositionHeightSubscription = undefined;
this._closeTop = undefined;
this._closeTopSubscription = undefined;
this._closeBottom = undefined;
this._closeBottomSubscription = undefined;
this._arcType = undefined;
this._arcTypeSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._classificationType = undefined;
this._classificationTypeSubscription = undefined;
this._zIndex = undefined;
this._zIndexSubscription = undefined;
this._textureCoordinates = undefined;
this._textureCoordinatesSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(PolygonGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof PolygonGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the polygon.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the Property specifying the {@link PolygonHierarchy}.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
*/
hierarchy: createPropertyDescriptor(
"hierarchy",
undefined,
createPolygonHierarchyProperty,
),
/**
* Gets or sets the numeric Property specifying the constant altitude of the polygon.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
height: createPropertyDescriptor("height"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the numeric Property specifying the altitude of the polygon extrusion.
* If {@link PolygonGraphics#perPositionHeight} is false, the volume starts at {@link PolygonGraphics#height} and ends at this altitude.
* If {@link PolygonGraphics#perPositionHeight} is true, the volume starts at the height of each {@link PolygonGraphics#hierarchy} position and ends at this altitude.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
*/
extrudedHeight: createPropertyDescriptor("extrudedHeight"),
/**
* Gets or sets the Property specifying the extruded {@link HeightReference}.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
extrudedHeightReference: createPropertyDescriptor("extrudedHeightReference"),
/**
* Gets or sets the numeric property specifying the rotation of the polygon texture counter-clockwise from north. Only has an effect if textureCoordinates is not defined.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default 0
*/
stRotation: createPropertyDescriptor("stRotation"),
/**
* Gets or sets the numeric Property specifying the angular distance between points on the polygon.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default {CesiumMath.RADIANS_PER_DEGREE}
*/
granularity: createPropertyDescriptor("granularity"),
/**
* Gets or sets the boolean Property specifying whether the polygon is filled with the provided material.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the Property specifying the material used to fill the polygon.
* @memberof PolygonGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying whether the polygon is outlined.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Gets or sets the boolean specifying whether or not the the height of each position is used.
* If true, the shape will have non-uniform altitude defined by the height of each {@link PolygonGraphics#hierarchy} position.
* If false, the shape will have a constant altitude as specified by {@link PolygonGraphics#height}.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
*/
perPositionHeight: createPropertyDescriptor("perPositionHeight"),
/**
* Gets or sets a boolean specifying whether or not the top of an extruded polygon is included.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
*/
closeTop: createPropertyDescriptor("closeTop"),
/**
* Gets or sets a boolean specifying whether or not the bottom of an extruded polygon is included.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
*/
closeBottom: createPropertyDescriptor("closeBottom"),
/**
* Gets or sets the {@link ArcType} Property specifying the type of lines the polygon edges use.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default ArcType.GEODESIC
*/
arcType: createPropertyDescriptor("arcType"),
/**
* Get or sets the enum Property specifying whether the polygon
* casts or receives shadows from light sources.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this polygon will be displayed.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the {@link ClassificationType} Property specifying whether this polygon will classify terrain, 3D Tiles, or both when on the ground.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
* @default ClassificationType.BOTH
*/
classificationType: createPropertyDescriptor("classificationType"),
/**
* Gets or sets the zIndex Prperty specifying the ordering of ground geometry. Only has an effect if the polygon is constant and neither height or extrudedHeight are specified.
* @memberof PolygonGraphics.prototype
* @type {ConstantProperty|undefined}
* @default 0
*/
zIndex: createPropertyDescriptor("zIndex"),
/**
* A Property specifying texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives.
* @memberof PolygonGraphics.prototype
* @type {Property|undefined}
*/
textureCoordinates: createPropertyDescriptor("textureCoordinates"),
});
/**
* Duplicates this instance.
*
* @param {PolygonGraphics} [result] The object onto which to store the result.
* @returns {PolygonGraphics} The modified result parameter or a new instance if one was not provided.
*/
PolygonGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new PolygonGraphics(this);
}
result.show = this.show;
result.hierarchy = this.hierarchy;
result.height = this.height;
result.heightReference = this.heightReference;
result.extrudedHeight = this.extrudedHeight;
result.extrudedHeightReference = this.extrudedHeightReference;
result.stRotation = this.stRotation;
result.granularity = this.granularity;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.perPositionHeight = this.perPositionHeight;
result.closeTop = this.closeTop;
result.closeBottom = this.closeBottom;
result.arcType = this.arcType;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.classificationType = this.classificationType;
result.zIndex = this.zIndex;
result.textureCoordinates = this.textureCoordinates;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {PolygonGraphics} source The object to be merged into this object.
*/
PolygonGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.hierarchy = this.hierarchy ?? source.hierarchy;
this.height = this.height ?? source.height;
this.heightReference = this.heightReference ?? source.heightReference;
this.extrudedHeight = this.extrudedHeight ?? source.extrudedHeight;
this.extrudedHeightReference =
this.extrudedHeightReference ?? source.extrudedHeightReference;
this.stRotation = this.stRotation ?? source.stRotation;
this.granularity = this.granularity ?? source.granularity;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.perPositionHeight = this.perPositionHeight ?? source.perPositionHeight;
this.closeTop = this.closeTop ?? source.closeTop;
this.closeBottom = this.closeBottom ?? source.closeBottom;
this.arcType = this.arcType ?? source.arcType;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.classificationType =
this.classificationType ?? source.classificationType;
this.zIndex = this.zIndex ?? source.zIndex;
this.textureCoordinates =
this.textureCoordinates ?? source.textureCoordinates;
};
export default PolygonGraphics;
@@ -0,0 +1,110 @@
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
/**
* A {@link MaterialProperty} that maps to PolylineArrow {@link Material} uniforms.
*
* @param {Property|Color} [color=Color.WHITE] The {@link Color} Property to be used.
*
* @alias PolylineArrowMaterialProperty
* @constructor
*/
function PolylineArrowMaterialProperty(color) {
this._definitionChanged = new Event();
this._color = undefined;
this._colorSubscription = undefined;
this.color = color;
}
Object.defineProperties(PolylineArrowMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof PolylineArrowMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return Property.isConstant(this._color);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof PolylineArrowMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the {@link Color} {@link Property}.
* @memberof PolylineArrowMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor("color"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
PolylineArrowMaterialProperty.prototype.getType = function (time) {
return "PolylineArrow";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PolylineArrowMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.color = Property.getValueOrClonedDefault(
this._color,
time,
Color.WHITE,
result.color,
);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
PolylineArrowMaterialProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof PolylineArrowMaterialProperty && //
Property.equals(this._color, other._color))
);
};
export default PolylineArrowMaterialProperty;
@@ -0,0 +1,174 @@
import Color from "../Core/Color.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
const defaultColor = Color.WHITE;
const defaultGapColor = Color.TRANSPARENT;
const defaultDashLength = 16.0;
const defaultDashPattern = 255.0;
/**
* A {@link MaterialProperty} that maps to polyline dash {@link Material} uniforms.
* @alias PolylineDashMaterialProperty
* @constructor
*
* @param {object} [options] Object with the following properties:
* @param {Property|Color} [options.color=Color.WHITE] A Property specifying the {@link Color} of the line.
* @param {Property|Color} [options.gapColor=Color.TRANSPARENT] A Property specifying the {@link Color} of the gaps in the line.
* @param {Property|number} [options.dashLength=16.0] A numeric Property specifying the length of the dash pattern in pixels.
* @param {Property|number} [options.dashPattern=255.0] A numeric Property specifying a 16 bit pattern for the dash
*/
function PolylineDashMaterialProperty(options) {
options = options ?? Frozen.EMPTY_OBJECT;
this._definitionChanged = new Event();
this._color = undefined;
this._colorSubscription = undefined;
this._gapColor = undefined;
this._gapColorSubscription = undefined;
this._dashLength = undefined;
this._dashLengthSubscription = undefined;
this._dashPattern = undefined;
this._dashPatternSubscription = undefined;
this.color = options.color;
this.gapColor = options.gapColor;
this.dashLength = options.dashLength;
this.dashPattern = options.dashPattern;
}
Object.defineProperties(PolylineDashMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof PolylineDashMaterialProperty.prototype
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
Property.isConstant(this._color) &&
Property.isConstant(this._gapColor) &&
Property.isConstant(this._dashLength) &&
Property.isConstant(this._dashPattern)
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof PolylineDashMaterialProperty.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the Property specifying the {@link Color} of the line.
* @memberof PolylineDashMaterialProperty.prototype
* @type {Property|undefined}
*/
color: createPropertyDescriptor("color"),
/**
* Gets or sets the Property specifying the {@link Color} of the gaps in the line.
* @memberof PolylineDashMaterialProperty.prototype
* @type {Property|undefined}
*/
gapColor: createPropertyDescriptor("gapColor"),
/**
* Gets or sets the numeric Property specifying the length of a dash cycle
* @memberof PolylineDashMaterialProperty.prototype
* @type {Property|undefined}
*/
dashLength: createPropertyDescriptor("dashLength"),
/**
* Gets or sets the numeric Property specifying a dash pattern
* @memberof PolylineDashMaterialProperty.prototype
* @type {Property|undefined}
*/
dashPattern: createPropertyDescriptor("dashPattern"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
PolylineDashMaterialProperty.prototype.getType = function (time) {
return "PolylineDash";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PolylineDashMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.color = Property.getValueOrClonedDefault(
this._color,
time,
defaultColor,
result.color,
);
result.gapColor = Property.getValueOrClonedDefault(
this._gapColor,
time,
defaultGapColor,
result.gapColor,
);
result.dashLength = Property.getValueOrDefault(
this._dashLength,
time,
defaultDashLength,
result.dashLength,
);
result.dashPattern = Property.getValueOrDefault(
this._dashPattern,
time,
defaultDashPattern,
result.dashPattern,
);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
PolylineDashMaterialProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof PolylineDashMaterialProperty &&
Property.equals(this._color, other._color) &&
Property.equals(this._gapColor, other._gapColor) &&
Property.equals(this._dashLength, other._dashLength) &&
Property.equals(this._dashPattern, other._dashPattern))
);
};
export default PolylineDashMaterialProperty;
@@ -0,0 +1,878 @@
import ArcType from "../Core/ArcType.js";
import BoundingSphere from "../Core/BoundingSphere.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import Event from "../Core/Event.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import GroundPolylineGeometry from "../Core/GroundPolylineGeometry.js";
import Iso8601 from "../Core/Iso8601.js";
import oneTimeWarning from "../Core/oneTimeWarning.js";
import PolylineGeometry from "../Core/PolylineGeometry.js";
import PolylinePipeline from "../Core/PolylinePipeline.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import Entity from "../DataSources/Entity.js";
import ClassificationType from "../Scene/ClassificationType.js";
import GroundPolylinePrimitive from "../Scene/GroundPolylinePrimitive.js";
import PolylineCollection from "../Scene/PolylineCollection.js";
import PolylineColorAppearance from "../Scene/PolylineColorAppearance.js";
import PolylineMaterialAppearance from "../Scene/PolylineMaterialAppearance.js";
import ShadowMode from "../Scene/ShadowMode.js";
import BoundingSphereState from "./BoundingSphereState.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import ConstantProperty from "./ConstantProperty.js";
import MaterialProperty from "./MaterialProperty.js";
import Property from "./Property.js";
const defaultZIndex = new ConstantProperty(0);
//We use this object to create one polyline collection per-scene.
const polylineCollections = {};
const scratchColor = new Color();
const defaultMaterial = new ColorMaterialProperty(Color.WHITE);
const defaultShow = new ConstantProperty(true);
const defaultShadows = new ConstantProperty(ShadowMode.DISABLED);
const defaultDistanceDisplayCondition = new ConstantProperty(
new DistanceDisplayCondition(),
);
const defaultClassificationType = new ConstantProperty(ClassificationType.BOTH);
function GeometryOptions() {
this.vertexFormat = undefined;
this.positions = undefined;
this.width = undefined;
this.arcType = undefined;
this.granularity = undefined;
}
function GroundGeometryOptions() {
this.positions = undefined;
this.width = undefined;
this.arcType = undefined;
this.granularity = undefined;
}
/**
* A {@link GeometryUpdater} for polylines.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias PolylineGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function PolylineGeometryUpdater(entity, scene) {
//>>includeStart('debug', pragmas.debug);
if (!defined(entity)) {
throw new DeveloperError("entity is required");
}
if (!defined(scene)) {
throw new DeveloperError("scene is required");
}
//>>includeEnd('debug');
this._entity = entity;
this._scene = scene;
this._entitySubscription = entity.definitionChanged.addEventListener(
PolylineGeometryUpdater.prototype._onEntityPropertyChanged,
this,
);
this._fillEnabled = false;
this._dynamic = false;
this._geometryChanged = new Event();
this._showProperty = undefined;
this._materialProperty = undefined;
this._shadowsProperty = undefined;
this._distanceDisplayConditionProperty = undefined;
this._classificationTypeProperty = undefined;
this._depthFailMaterialProperty = undefined;
this._geometryOptions = new GeometryOptions();
this._groundGeometryOptions = new GroundGeometryOptions();
this._id = `polyline-${entity.id}`;
this._clampToGround = false;
this._supportsPolylinesOnTerrain = Entity.supportsPolylinesOnTerrain(scene);
this._zIndex = 0;
this._onEntityPropertyChanged(entity, "polyline", entity.polyline, undefined);
}
Object.defineProperties(PolylineGeometryUpdater.prototype, {
/**
* Gets the unique ID associated with this updater
* @memberof PolylineGeometryUpdater.prototype
* @type {string}
* @readonly
*/
id: {
get: function () {
return this._id;
},
},
/**
* Gets the entity associated with this geometry.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {Entity}
* @readonly
*/
entity: {
get: function () {
return this._entity;
},
},
/**
* Gets a value indicating if the geometry has a fill component.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
fillEnabled: {
get: function () {
return this._fillEnabled;
},
},
/**
* Gets a value indicating if fill visibility varies with simulation time.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
hasConstantFill: {
get: function () {
return (
!this._fillEnabled ||
(!defined(this._entity.availability) &&
Property.isConstant(this._showProperty))
);
},
},
/**
* Gets the material property used to fill the geometry.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {MaterialProperty}
* @readonly
*/
fillMaterialProperty: {
get: function () {
return this._materialProperty;
},
},
/**
* Gets the material property used to fill the geometry when it fails the depth test.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {MaterialProperty}
* @readonly
*/
depthFailMaterialProperty: {
get: function () {
return this._depthFailMaterialProperty;
},
},
/**
* Gets a value indicating if the geometry has an outline component.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
outlineEnabled: {
value: false,
},
/**
* Gets a value indicating if outline visibility varies with simulation time.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
hasConstantOutline: {
value: true,
},
/**
* Gets the {@link Color} property for the geometry outline.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {Property}
* @readonly
*/
outlineColorProperty: {
value: undefined,
},
/**
* Gets the property specifying whether the geometry
* casts or receives shadows from light sources.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {Property}
* @readonly
*/
shadowsProperty: {
get: function () {
return this._shadowsProperty;
},
},
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this geometry will be displayed.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {Property}
* @readonly
*/
distanceDisplayConditionProperty: {
get: function () {
return this._distanceDisplayConditionProperty;
},
},
/**
* Gets or sets the {@link ClassificationType} Property specifying if this geometry will classify terrain, 3D Tiles, or both when on the ground.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {Property}
* @readonly
*/
classificationTypeProperty: {
get: function () {
return this._classificationTypeProperty;
},
},
/**
* Gets a value indicating if the geometry is time-varying.
*
* @memberof PolylineGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
isDynamic: {
get: function () {
return this._dynamic;
},
},
/**
* Gets a value indicating if the geometry is closed.
* This property is only valid for static geometry.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
isClosed: {
value: false,
},
/**
* Gets an event that is raised whenever the public properties
* of this updater change.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
geometryChanged: {
get: function () {
return this._geometryChanged;
},
},
/**
* Gets a value indicating if the path of the line.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {ArcType}
* @readonly
*/
arcType: {
get: function () {
return this._arcType;
},
},
/**
* Gets a value indicating if the geometry is clamped to the ground.
* Returns false if polylines on terrain is not supported.
* @memberof PolylineGeometryUpdater.prototype
*
* @type {boolean}
* @readonly
*/
clampToGround: {
get: function () {
return this._clampToGround && this._supportsPolylinesOnTerrain;
},
},
/**
* Gets the zindex
* @type {number}
* @memberof PolylineGeometryUpdater.prototype
* @readonly
*/
zIndex: {
get: function () {
return this._zIndex;
},
},
});
/**
* Checks if the geometry is outlined at the provided time.
*
* @param {JulianDate} time The time for which to retrieve visibility.
* @returns {boolean} true if geometry is outlined at the provided time, false otherwise.
*/
PolylineGeometryUpdater.prototype.isOutlineVisible = function (time) {
return false;
};
/**
* Checks if the geometry is filled at the provided time.
*
* @param {JulianDate} time The time for which to retrieve visibility.
* @returns {boolean} true if geometry is filled at the provided time, false otherwise.
*/
PolylineGeometryUpdater.prototype.isFilled = function (time) {
const entity = this._entity;
const visible =
this._fillEnabled &&
entity.isAvailable(time) &&
this._showProperty.getValue(time);
return visible ?? false;
};
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
PolylineGeometryUpdater.prototype.createFillGeometryInstance = function (time) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const show = new ShowGeometryInstanceAttribute(
isAvailable && entity.isShowing && this._showProperty.getValue(time),
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const distanceDisplayConditionAttribute =
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
);
const attributes = {
show: show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
};
let currentColor;
if (this._materialProperty instanceof ColorMaterialProperty) {
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
}
if (this.clampToGround) {
return new GeometryInstance({
id: entity,
geometry: new GroundPolylineGeometry(this._groundGeometryOptions),
attributes: attributes,
});
}
if (
defined(this._depthFailMaterialProperty) &&
this._depthFailMaterialProperty instanceof ColorMaterialProperty
) {
if (
defined(this._depthFailMaterialProperty.color) &&
(this._depthFailMaterialProperty.color.isConstant || isAvailable)
) {
currentColor = this._depthFailMaterialProperty.color.getValue(
time,
scratchColor,
);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
attributes.depthFailColor =
ColorGeometryInstanceAttribute.fromColor(currentColor);
}
return new GeometryInstance({
id: entity,
geometry: new PolylineGeometry(this._geometryOptions),
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
PolylineGeometryUpdater.prototype.createOutlineGeometryInstance = function (
time,
) {
//>>includeStart('debug', pragmas.debug);
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
//>>includeEnd('debug');
};
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
PolylineGeometryUpdater.prototype.isDestroyed = function () {
return false;
};
/**
* Destroys and resources used by the object. Once an object is destroyed, it should not be used.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*/
PolylineGeometryUpdater.prototype.destroy = function () {
this._entitySubscription();
destroyObject(this);
};
PolylineGeometryUpdater.prototype._onEntityPropertyChanged = function (
entity,
propertyName,
newValue,
oldValue,
) {
if (!(propertyName === "availability" || propertyName === "polyline")) {
return;
}
const polyline = this._entity.polyline;
if (!defined(polyline)) {
if (this._fillEnabled) {
this._fillEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
const positionsProperty = polyline.positions;
const show = polyline.show;
if (
(defined(show) &&
show.isConstant &&
!show.getValue(Iso8601.MINIMUM_VALUE)) || //
!defined(positionsProperty)
) {
if (this._fillEnabled) {
this._fillEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
const zIndex = polyline.zIndex;
const material = polyline.material ?? defaultMaterial;
const isColorMaterial = material instanceof ColorMaterialProperty;
this._materialProperty = material;
this._depthFailMaterialProperty = polyline.depthFailMaterial;
this._showProperty = show ?? defaultShow;
this._shadowsProperty = polyline.shadows ?? defaultShadows;
this._distanceDisplayConditionProperty =
polyline.distanceDisplayCondition ?? defaultDistanceDisplayCondition;
this._classificationTypeProperty =
polyline.classificationType ?? defaultClassificationType;
this._fillEnabled = true;
this._zIndex = zIndex ?? defaultZIndex;
const width = polyline.width;
const arcType = polyline.arcType;
const clampToGround = polyline.clampToGround;
const granularity = polyline.granularity;
if (
!positionsProperty.isConstant ||
!Property.isConstant(width) ||
!Property.isConstant(arcType) ||
!Property.isConstant(granularity) ||
!Property.isConstant(clampToGround) ||
!Property.isConstant(zIndex)
) {
if (!this._dynamic) {
this._dynamic = true;
this._geometryChanged.raiseEvent(this);
}
} else {
const geometryOptions = this._geometryOptions;
const positions = positionsProperty.getValue(
Iso8601.MINIMUM_VALUE,
geometryOptions.positions,
);
//Because of the way we currently handle reference properties,
//we can't automatically assume the positions are always valid.
if (!defined(positions) || positions.length < 2) {
if (this._fillEnabled) {
this._fillEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
let vertexFormat;
if (
isColorMaterial &&
(!defined(this._depthFailMaterialProperty) ||
this._depthFailMaterialProperty instanceof ColorMaterialProperty)
) {
vertexFormat = PolylineColorAppearance.VERTEX_FORMAT;
} else {
vertexFormat = PolylineMaterialAppearance.VERTEX_FORMAT;
}
geometryOptions.vertexFormat = vertexFormat;
geometryOptions.positions = positions;
geometryOptions.width = defined(width)
? width.getValue(Iso8601.MINIMUM_VALUE)
: undefined;
geometryOptions.arcType = defined(arcType)
? arcType.getValue(Iso8601.MINIMUM_VALUE)
: undefined;
geometryOptions.granularity = defined(granularity)
? granularity.getValue(Iso8601.MINIMUM_VALUE)
: undefined;
const groundGeometryOptions = this._groundGeometryOptions;
groundGeometryOptions.positions = positions;
groundGeometryOptions.width = geometryOptions.width;
groundGeometryOptions.arcType = geometryOptions.arcType;
groundGeometryOptions.granularity = geometryOptions.granularity;
this._clampToGround = defined(clampToGround)
? clampToGround.getValue(Iso8601.MINIMUM_VALUE)
: false;
if (!this._clampToGround && defined(zIndex)) {
oneTimeWarning(
"Entity polylines must have clampToGround: true when using zIndex. zIndex will be ignored.",
);
}
this._dynamic = false;
this._geometryChanged.raiseEvent(this);
}
};
/**
* Creates the dynamic updater to be used when GeometryUpdater#isDynamic is true.
*
* @param {PrimitiveCollection} primitives The primitive collection to use.
* @param {PrimitiveCollection|OrderedGroundPrimitiveCollection} groundPrimitives The primitive collection to use for ordered ground primitives.
* @returns {DynamicGeometryUpdater} The dynamic updater used to update the geometry each frame.
*
* @exception {DeveloperError} This instance does not represent dynamic geometry.
* @private
*/
PolylineGeometryUpdater.prototype.createDynamicUpdater = function (
primitives,
groundPrimitives,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("primitives", primitives);
Check.defined("groundPrimitives", groundPrimitives);
if (!this._dynamic) {
throw new DeveloperError(
"This instance does not represent dynamic geometry.",
);
}
//>>includeEnd('debug');
return new DynamicGeometryUpdater(primitives, groundPrimitives, this);
};
/**
* @private
*/
const generateCartesianArcOptions = {
positions: undefined,
granularity: undefined,
height: undefined,
ellipsoid: undefined,
};
function DynamicGeometryUpdater(primitives, groundPrimitives, geometryUpdater) {
this._line = undefined;
this._primitives = primitives;
this._groundPrimitives = groundPrimitives;
this._groundPolylinePrimitive = undefined;
this._material = undefined;
this._geometryUpdater = geometryUpdater;
this._positions = [];
}
function getLine(dynamicGeometryUpdater) {
if (defined(dynamicGeometryUpdater._line)) {
return dynamicGeometryUpdater._line;
}
const primitives = dynamicGeometryUpdater._primitives;
const polylineCollectionId =
dynamicGeometryUpdater._geometryUpdater._scene.id + primitives._guid;
let polylineCollection = polylineCollections[polylineCollectionId];
if (!defined(polylineCollection) || polylineCollection.isDestroyed()) {
polylineCollection = new PolylineCollection();
polylineCollections[polylineCollectionId] = polylineCollection;
primitives.add(polylineCollection);
} else if (!primitives.contains(polylineCollection)) {
primitives.add(polylineCollection);
}
const line = polylineCollection.add();
line.id = dynamicGeometryUpdater._geometryUpdater._entity;
dynamicGeometryUpdater._line = line;
return line;
}
DynamicGeometryUpdater.prototype.update = function (time) {
const geometryUpdater = this._geometryUpdater;
const entity = geometryUpdater._entity;
const polyline = entity.polyline;
const positionsProperty = polyline.positions;
let positions = Property.getValueOrUndefined(
positionsProperty,
time,
this._positions,
);
// Synchronize with geometryUpdater for GroundPolylinePrimitive
geometryUpdater._clampToGround = Property.getValueOrDefault(
polyline._clampToGround,
time,
false,
);
geometryUpdater._groundGeometryOptions.positions = positions;
geometryUpdater._groundGeometryOptions.width = Property.getValueOrDefault(
polyline._width,
time,
1,
);
geometryUpdater._groundGeometryOptions.arcType = Property.getValueOrDefault(
polyline._arcType,
time,
ArcType.GEODESIC,
);
geometryUpdater._groundGeometryOptions.granularity =
Property.getValueOrDefault(polyline._granularity, time, 9999);
const groundPrimitives = this._groundPrimitives;
if (defined(this._groundPolylinePrimitive)) {
groundPrimitives.remove(this._groundPolylinePrimitive); // destroys by default
this._groundPolylinePrimitive = undefined;
}
if (geometryUpdater.clampToGround) {
if (
!entity.isShowing ||
!entity.isAvailable(time) ||
!Property.getValueOrDefault(polyline._show, time, true)
) {
return;
}
if (!defined(positions) || positions.length < 2) {
return;
}
const fillMaterialProperty = geometryUpdater.fillMaterialProperty;
let appearance;
if (fillMaterialProperty instanceof ColorMaterialProperty) {
appearance = new PolylineColorAppearance();
} else {
const material = MaterialProperty.getValue(
time,
fillMaterialProperty,
this._material,
);
appearance = new PolylineMaterialAppearance({
material: material,
translucent: material.isTranslucent(),
});
this._material = material;
}
this._groundPolylinePrimitive = groundPrimitives.add(
new GroundPolylinePrimitive({
geometryInstances: geometryUpdater.createFillGeometryInstance(time),
appearance: appearance,
classificationType:
geometryUpdater.classificationTypeProperty.getValue(time),
asynchronous: false,
}),
Property.getValueOrUndefined(geometryUpdater.zIndex, time),
);
// Hide the polyline in the collection, if any
if (defined(this._line)) {
this._line.show = false;
}
return;
}
const line = getLine(this);
if (
!entity.isShowing ||
!entity.isAvailable(time) ||
!Property.getValueOrDefault(polyline._show, time, true)
) {
line.show = false;
return;
}
if (!defined(positions) || positions.length < 2) {
line.show = false;
return;
}
let arcType = ArcType.GEODESIC;
arcType = Property.getValueOrDefault(polyline._arcType, time, arcType);
const globe = geometryUpdater._scene.globe;
const ellipsoid = geometryUpdater._scene.ellipsoid;
if (arcType !== ArcType.NONE && defined(globe)) {
generateCartesianArcOptions.ellipsoid = ellipsoid;
generateCartesianArcOptions.positions = positions;
generateCartesianArcOptions.granularity = Property.getValueOrUndefined(
polyline._granularity,
time,
);
generateCartesianArcOptions.height = PolylinePipeline.extractHeights(
positions,
ellipsoid,
);
if (arcType === ArcType.GEODESIC) {
positions = PolylinePipeline.generateCartesianArc(
generateCartesianArcOptions,
);
} else {
positions = PolylinePipeline.generateCartesianRhumbArc(
generateCartesianArcOptions,
);
}
}
line.show = true;
line.positions = positions.slice();
line.material = MaterialProperty.getValue(
time,
geometryUpdater.fillMaterialProperty,
line.material,
);
line.width = Property.getValueOrDefault(polyline._width, time, 1);
line.distanceDisplayCondition = Property.getValueOrUndefined(
polyline._distanceDisplayCondition,
time,
line.distanceDisplayCondition,
);
};
DynamicGeometryUpdater.prototype.getBoundingSphere = function (result) {
//>>includeStart('debug', pragmas.debug);
Check.defined("result", result);
//>>includeEnd('debug');
if (!this._geometryUpdater.clampToGround) {
const line = getLine(this);
if (line.show && line.positions.length > 0) {
BoundingSphere.fromPoints(line.positions, result);
return BoundingSphereState.DONE;
}
} else {
const groundPolylinePrimitive = this._groundPolylinePrimitive;
if (
defined(groundPolylinePrimitive) &&
groundPolylinePrimitive.show &&
groundPolylinePrimitive.ready
) {
const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes(
this._geometryUpdater._entity,
);
if (defined(attributes) && defined(attributes.boundingSphere)) {
BoundingSphere.clone(attributes.boundingSphere, result);
return BoundingSphereState.DONE;
}
}
if (defined(groundPolylinePrimitive) && !groundPolylinePrimitive.ready) {
return BoundingSphereState.PENDING;
}
return BoundingSphereState.DONE;
}
return BoundingSphereState.FAILED;
};
DynamicGeometryUpdater.prototype.isDestroyed = function () {
return false;
};
DynamicGeometryUpdater.prototype.destroy = function () {
const geometryUpdater = this._geometryUpdater;
const polylineCollectionId =
geometryUpdater._scene.id + this._primitives._guid;
const polylineCollection = polylineCollections[polylineCollectionId];
if (defined(polylineCollection)) {
polylineCollection.remove(this._line);
if (polylineCollection.length === 0) {
this._primitives.removeAndDestroy(polylineCollection);
delete polylineCollections[polylineCollectionId];
}
}
if (defined(this._groundPolylinePrimitive)) {
this._groundPrimitives.remove(this._groundPolylinePrimitive);
}
destroyObject(this);
};
export default PolylineGeometryUpdater;
@@ -0,0 +1,152 @@
import Color from "../Core/Color.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
const defaultColor = Color.WHITE;
const defaultGlowPower = 0.25;
const defaultTaperPower = 1.0;
/**
* A {@link MaterialProperty} that maps to polyline glow {@link Material} uniforms.
* @alias PolylineGlowMaterialProperty
* @constructor
*
* @param {object} [options] Object with the following properties:
* @param {Property|Color} [options.color=Color.WHITE] A Property specifying the {@link Color} of the line.
* @param {Property|number} [options.glowPower=0.25] A numeric Property specifying the strength of the glow, as a percentage of the total line width.
* @param {Property|number} [options.taperPower=1.0] A numeric Property specifying the strength of the tapering effect, as a percentage of the total line length. If 1.0 or higher, no taper effect is used.
*/
function PolylineGlowMaterialProperty(options) {
options = options ?? Frozen.EMPTY_OBJECT;
this._definitionChanged = new Event();
this._color = undefined;
this._colorSubscription = undefined;
this._glowPower = undefined;
this._glowPowerSubscription = undefined;
this._taperPower = undefined;
this._taperPowerSubscription = undefined;
this.color = options.color;
this.glowPower = options.glowPower;
this.taperPower = options.taperPower;
}
Object.defineProperties(PolylineGlowMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof PolylineGlowMaterialProperty.prototype
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
Property.isConstant(this._color) && Property.isConstant(this._glow)
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof PolylineGlowMaterialProperty.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the Property specifying the {@link Color} of the line.
* @memberof PolylineGlowMaterialProperty.prototype
* @type {Property|undefined}
*/
color: createPropertyDescriptor("color"),
/**
* Gets or sets the numeric Property specifying the strength of the glow, as a percentage of the total line width (less than 1.0).
* @memberof PolylineGlowMaterialProperty.prototype
* @type {Property|undefined}
*/
glowPower: createPropertyDescriptor("glowPower"),
/**
* Gets or sets the numeric Property specifying the strength of the tapering effect, as a percentage of the total line length. If 1.0 or higher, no taper effect is used.
* @memberof PolylineGlowMaterialProperty.prototype
* @type {Property|undefined}
*/
taperPower: createPropertyDescriptor("taperPower"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
PolylineGlowMaterialProperty.prototype.getType = function (time) {
return "PolylineGlow";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PolylineGlowMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.color = Property.getValueOrClonedDefault(
this._color,
time,
defaultColor,
result.color,
);
result.glowPower = Property.getValueOrDefault(
this._glowPower,
time,
defaultGlowPower,
result.glowPower,
);
result.taperPower = Property.getValueOrDefault(
this._taperPower,
time,
defaultTaperPower,
result.taperPower,
);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
PolylineGlowMaterialProperty.prototype.equals = function (other) {
return (
this === other ||
(other instanceof PolylineGlowMaterialProperty &&
Property.equals(this._color, other._color) &&
Property.equals(this._glowPower, other._glowPower) &&
Property.equals(this._taperPower, other._taperPower))
);
};
export default PolylineGlowMaterialProperty;
@@ -0,0 +1,241 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} PolylineGraphics.ConstructorOptions
*
* Initialization options for the PolylineGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the polyline.
* @property {Property | Cartesian3[]} [positions] A Property specifying the array of {@link Cartesian3} positions that define the line strip.
* @property {Property | number} [width=1.0] A numeric Property specifying the width in pixels.
* @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between each latitude and longitude if arcType is not ArcType.NONE.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to draw the polyline.
* @property {MaterialProperty | Color} [depthFailMaterial] A property specifying the material used to draw the polyline when it is below the terrain.
* @property {Property | ArcType} [arcType=ArcType.GEODESIC] The type of line the polyline segments must follow.
* @property {Property | boolean} [clampToGround=false] A boolean Property specifying whether the Polyline should be clamped to the ground.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the polyline casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this polyline will be displayed.
* @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this polyline will classify terrain, 3D Tiles, or both when on the ground.
* @property {Property | number} [zIndex=0] A Property specifying the zIndex used for ordering ground geometry. Only has an effect if `clampToGround` is true and polylines on terrain is supported.
*/
/**
* Describes a polyline. The first two positions define a line segment,
* and each additional position defines a line segment from the previous position. The segments
* can be linear connected points, great arcs, or clamped to terrain.
*
* @alias PolylineGraphics
* @constructor
*
* @param {PolylineGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @see Entity
* @demo {@link https://sandcastle.cesium.com/index.html?id=polyline|Cesium Sandcastle Polyline Demo}
*/
function PolylineGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._positions = undefined;
this._positionsSubscription = undefined;
this._width = undefined;
this._widthSubscription = undefined;
this._granularity = undefined;
this._granularitySubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._depthFailMaterial = undefined;
this._depthFailMaterialSubscription = undefined;
this._arcType = undefined;
this._arcTypeSubscription = undefined;
this._clampToGround = undefined;
this._clampToGroundSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubscription = undefined;
this._classificationType = undefined;
this._classificationTypeSubscription = undefined;
this._zIndex = undefined;
this._zIndexSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(PolylineGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof PolylineGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the polyline.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the Property specifying the array of {@link Cartesian3}
* positions that define the line strip.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
*/
positions: createPropertyDescriptor("positions"),
/**
* Gets or sets the numeric Property specifying the width in pixels.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
width: createPropertyDescriptor("width"),
/**
* Gets or sets the numeric Property specifying the angular distance between each latitude and longitude if arcType is not ArcType.NONE and clampToGround is false.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
* @default Cesium.Math.RADIANS_PER_DEGREE
*/
granularity: createPropertyDescriptor("granularity"),
/**
* Gets or sets the Property specifying the material used to draw the polyline.
* @memberof PolylineGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying the material used to draw the polyline when it fails the depth test.
* <p>
* Requires the EXT_frag_depth WebGL extension to render properly. If the extension is not supported,
* there may be artifacts.
* </p>
* @memberof PolylineGraphics.prototype
* @type {MaterialProperty}
* @default undefined
*/
depthFailMaterial: createMaterialPropertyDescriptor("depthFailMaterial"),
/**
* Gets or sets the {@link ArcType} Property specifying whether the line segments should be great arcs, rhumb lines or linearly connected.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
* @default ArcType.GEODESIC
*/
arcType: createPropertyDescriptor("arcType"),
/**
* Gets or sets the boolean Property specifying whether the polyline
* should be clamped to the ground.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
* @default false
*/
clampToGround: createPropertyDescriptor("clampToGround"),
/**
* Get or sets the enum Property specifying whether the polyline
* casts or receives shadows from light sources.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this polyline will be displayed.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the {@link ClassificationType} Property specifying whether this polyline will classify terrain, 3D Tiles, or both when on the ground.
* @memberof PolylineGraphics.prototype
* @type {Property|undefined}
* @default ClassificationType.BOTH
*/
classificationType: createPropertyDescriptor("classificationType"),
/**
* Gets or sets the zIndex Property specifying the ordering of the polyline. Only has an effect if `clampToGround` is true and polylines on terrain is supported.
* @memberof PolylineGraphics.prototype
* @type {ConstantProperty|undefined}
* @default 0
*/
zIndex: createPropertyDescriptor("zIndex"),
});
/**
* Duplicates this instance.
*
* @param {PolylineGraphics} [result] The object onto which to store the result.
* @returns {PolylineGraphics} The modified result parameter or a new instance if one was not provided.
*/
PolylineGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new PolylineGraphics(this);
}
result.show = this.show;
result.positions = this.positions;
result.width = this.width;
result.granularity = this.granularity;
result.material = this.material;
result.depthFailMaterial = this.depthFailMaterial;
result.arcType = this.arcType;
result.clampToGround = this.clampToGround;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.classificationType = this.classificationType;
result.zIndex = this.zIndex;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {PolylineGraphics} source The object to be merged into this object.
*/
PolylineGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.positions = this.positions ?? source.positions;
this.width = this.width ?? source.width;
this.granularity = this.granularity ?? source.granularity;
this.material = this.material ?? source.material;
this.depthFailMaterial = this.depthFailMaterial ?? source.depthFailMaterial;
this.arcType = this.arcType ?? source.arcType;
this.clampToGround = this.clampToGround ?? source.clampToGround;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.classificationType =
this.classificationType ?? source.classificationType;
this.zIndex = this.zIndex ?? source.zIndex;
};
export default PolylineGraphics;
@@ -0,0 +1,158 @@
import Color from "../Core/Color.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
const defaultColor = Color.WHITE;
const defaultOutlineColor = Color.BLACK;
const defaultOutlineWidth = 1.0;
/**
* A {@link MaterialProperty} that maps to polyline outline {@link Material} uniforms.
* @alias PolylineOutlineMaterialProperty
* @constructor
*
* @param {object} [options] Object with the following properties:
* @param {Property|Color} [options.color=Color.WHITE] A Property specifying the {@link Color} of the line.
* @param {Property|Color} [options.outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @param {Property|number} [options.outlineWidth=1.0] A numeric Property specifying the width of the outline, in pixels.
*/
function PolylineOutlineMaterialProperty(options) {
options = options ?? Frozen.EMPTY_OBJECT;
this._definitionChanged = new Event();
this._color = undefined;
this._colorSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this.color = options.color;
this.outlineColor = options.outlineColor;
this.outlineWidth = options.outlineWidth;
}
Object.defineProperties(PolylineOutlineMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof PolylineOutlineMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
Property.isConstant(this._color) &&
Property.isConstant(this._outlineColor) &&
Property.isConstant(this._outlineWidth)
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof PolylineOutlineMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the Property specifying the {@link Color} of the line.
* @memberof PolylineOutlineMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
color: createPropertyDescriptor("color"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof PolylineOutlineMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* @memberof PolylineOutlineMaterialProperty.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
PolylineOutlineMaterialProperty.prototype.getType = function (time) {
return "PolylineOutline";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PolylineOutlineMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.color = Property.getValueOrClonedDefault(
this._color,
time,
defaultColor,
result.color,
);
result.outlineColor = Property.getValueOrClonedDefault(
this._outlineColor,
time,
defaultOutlineColor,
result.outlineColor,
);
result.outlineWidth = Property.getValueOrDefault(
this._outlineWidth,
time,
defaultOutlineWidth,
);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
PolylineOutlineMaterialProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof PolylineOutlineMaterialProperty && //
Property.equals(this._color, other._color) && //
Property.equals(this._outlineColor, other._outlineColor) && //
Property.equals(this._outlineWidth, other._outlineWidth))
);
};
export default PolylineOutlineMaterialProperty;
@@ -0,0 +1,409 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import BoundingSphere from "../Core/BoundingSphere.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import ClassificationType from "../Scene/ClassificationType.js";
import PolylineColorAppearance from "../Scene/PolylineColorAppearance.js";
import PolylineMaterialAppearance from "../Scene/PolylineMaterialAppearance.js";
import ShadowMode from "../Scene/ShadowMode.js";
import BoundingSphereState from "./BoundingSphereState.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryBatch from "./DynamicGeometryBatch.js";
import PolylineGeometryUpdater from "./PolylineGeometryUpdater.js";
import StaticGeometryColorBatch from "./StaticGeometryColorBatch.js";
import StaticGeometryPerMaterialBatch from "./StaticGeometryPerMaterialBatch.js";
import StaticGroundPolylinePerMaterialBatch from "./StaticGroundPolylinePerMaterialBatch.js";
const emptyArray = [];
function removeUpdater(that, updater) {
//We don't keep track of which batch an updater is in, so just remove it from all of them.
const batches = that._batches;
const length = batches.length;
for (let i = 0; i < length; i++) {
batches[i].remove(updater);
}
}
function insertUpdaterIntoBatch(that, time, updater) {
if (updater.isDynamic) {
that._dynamicBatch.add(time, updater);
return;
}
if (updater.clampToGround && updater.fillEnabled) {
// Also checks for support
const classificationType =
updater.classificationTypeProperty.getValue(time);
that._groundBatches[classificationType].add(time, updater);
return;
}
let shadows;
if (updater.fillEnabled) {
shadows = updater.shadowsProperty.getValue(time);
}
let multiplier = 0;
if (defined(updater.depthFailMaterialProperty)) {
multiplier =
updater.depthFailMaterialProperty instanceof ColorMaterialProperty
? 1
: 2;
}
let index;
if (defined(shadows)) {
index = shadows + multiplier * ShadowMode.NUMBER_OF_SHADOW_MODES;
}
if (updater.fillEnabled) {
if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
that._colorBatches[index].add(time, updater);
} else {
that._materialBatches[index].add(time, updater);
}
}
}
/**
* A visualizer for polylines represented by {@link Primitive} instances.
* @alias PolylineVisualizer
* @constructor
*
* @param {Scene} scene The scene the primitives will be rendered in.
* @param {EntityCollection} entityCollection The entityCollection to visualize.
* @param {PrimitiveCollection} [primitives=scene.primitives] A collection to add primitives related to the entities
* @param {PrimitiveCollection} [groundPrimitives=scene.groundPrimitives] A collection to add ground primitives related to the entities
*/
function PolylineVisualizer(
scene,
entityCollection,
primitives,
groundPrimitives,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("scene", scene);
Check.defined("entityCollection", entityCollection);
//>>includeEnd('debug');
groundPrimitives = groundPrimitives ?? scene.groundPrimitives;
primitives = primitives ?? scene.primitives;
this._scene = scene;
this._primitives = primitives;
this._entityCollection = undefined;
this._addedObjects = new AssociativeArray();
this._removedObjects = new AssociativeArray();
this._changedObjects = new AssociativeArray();
let i;
const numberOfShadowModes = ShadowMode.NUMBER_OF_SHADOW_MODES;
this._colorBatches = new Array(numberOfShadowModes * 3);
this._materialBatches = new Array(numberOfShadowModes * 3);
for (i = 0; i < numberOfShadowModes; ++i) {
this._colorBatches[i] = new StaticGeometryColorBatch(
primitives,
PolylineColorAppearance,
undefined,
false,
i,
); // no depth fail appearance
this._materialBatches[i] = new StaticGeometryPerMaterialBatch(
primitives,
PolylineMaterialAppearance,
undefined,
false,
i,
);
this._colorBatches[i + numberOfShadowModes] = new StaticGeometryColorBatch(
primitives,
PolylineColorAppearance,
PolylineColorAppearance,
false,
i,
); //depth fail appearance variations
this._materialBatches[i + numberOfShadowModes] =
new StaticGeometryPerMaterialBatch(
primitives,
PolylineMaterialAppearance,
PolylineColorAppearance,
false,
i,
);
this._colorBatches[i + numberOfShadowModes * 2] =
new StaticGeometryColorBatch(
primitives,
PolylineColorAppearance,
PolylineMaterialAppearance,
false,
i,
);
this._materialBatches[i + numberOfShadowModes * 2] =
new StaticGeometryPerMaterialBatch(
primitives,
PolylineMaterialAppearance,
PolylineMaterialAppearance,
false,
i,
);
}
this._dynamicBatch = new DynamicGeometryBatch(primitives, groundPrimitives);
const numberOfClassificationTypes =
ClassificationType.NUMBER_OF_CLASSIFICATION_TYPES;
this._groundBatches = new Array(numberOfClassificationTypes);
for (i = 0; i < numberOfClassificationTypes; ++i) {
this._groundBatches[i] = new StaticGroundPolylinePerMaterialBatch(
groundPrimitives,
i,
);
}
this._batches = this._colorBatches.concat(
this._materialBatches,
this._dynamicBatch,
this._groundBatches,
);
this._subscriptions = new AssociativeArray();
this._updaters = new AssociativeArray();
this._entityCollection = entityCollection;
entityCollection.collectionChanged.addEventListener(
PolylineVisualizer.prototype._onCollectionChanged,
this,
);
this._onCollectionChanged(
entityCollection,
entityCollection.values,
emptyArray,
);
}
/**
* Updates all of the primitives created by this visualizer to match their
* Entity counterpart at the given time.
*
* @param {JulianDate} time The time to update to.
* @returns {boolean} True if the visualizer successfully updated to the provided time,
* false if the visualizer is waiting for asynchronous primitives to be created.
*/
PolylineVisualizer.prototype.update = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
const addedObjects = this._addedObjects;
const added = addedObjects.values;
const removedObjects = this._removedObjects;
const removed = removedObjects.values;
const changedObjects = this._changedObjects;
const changed = changedObjects.values;
let i;
let entity;
let id;
let updater;
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
id = entity.id;
updater = this._updaters.get(id);
//If in a single update, an entity gets removed and a new instance
//re-added with the same id, the updater no longer tracks the
//correct entity, we need to both remove the old one and
//add the new one, which is done by pushing the entity
//onto the removed/added lists.
if (updater.entity === entity) {
removeUpdater(this, updater);
insertUpdaterIntoBatch(this, time, updater);
} else {
removed.push(entity);
added.push(entity);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
id = entity.id;
updater = this._updaters.get(id);
removeUpdater(this, updater);
updater.destroy();
this._updaters.remove(id);
this._subscriptions.get(id)();
this._subscriptions.remove(id);
}
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
id = entity.id;
updater = new PolylineGeometryUpdater(entity, this._scene);
this._updaters.set(id, updater);
insertUpdaterIntoBatch(this, time, updater);
this._subscriptions.set(
id,
updater.geometryChanged.addEventListener(
PolylineVisualizer._onGeometryChanged,
this,
),
);
}
addedObjects.removeAll();
removedObjects.removeAll();
changedObjects.removeAll();
let isUpdated = true;
const batches = this._batches;
const length = batches.length;
for (i = 0; i < length; i++) {
isUpdated = batches[i].update(time) && isUpdated;
}
return isUpdated;
};
const getBoundingSphereArrayScratch = [];
const getBoundingSphereBoundingSphereScratch = new BoundingSphere();
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
PolylineVisualizer.prototype.getBoundingSphere = function (entity, result) {
//>>includeStart('debug', pragmas.debug);
Check.defined("entity", entity);
Check.defined("result", result);
//>>includeEnd('debug');
const boundingSpheres = getBoundingSphereArrayScratch;
const tmp = getBoundingSphereBoundingSphereScratch;
let count = 0;
let state = BoundingSphereState.DONE;
const batches = this._batches;
const batchesLength = batches.length;
const updater = this._updaters.get(entity.id);
for (let i = 0; i < batchesLength; i++) {
state = batches[i].getBoundingSphere(updater, tmp);
if (state === BoundingSphereState.PENDING) {
return BoundingSphereState.PENDING;
} else if (state === BoundingSphereState.DONE) {
boundingSpheres[count] = BoundingSphere.clone(
tmp,
boundingSpheres[count],
);
count++;
}
}
if (count === 0) {
return BoundingSphereState.FAILED;
}
boundingSpheres.length = count;
BoundingSphere.fromBoundingSpheres(boundingSpheres, result);
return BoundingSphereState.DONE;
};
/**
* Returns true if this object was destroyed; otherwise, false.
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
PolylineVisualizer.prototype.isDestroyed = function () {
return false;
};
/**
* Removes and destroys all primitives created by this instance.
*/
PolylineVisualizer.prototype.destroy = function () {
this._entityCollection.collectionChanged.removeEventListener(
PolylineVisualizer.prototype._onCollectionChanged,
this,
);
this._addedObjects.removeAll();
this._removedObjects.removeAll();
let i;
const batches = this._batches;
let length = batches.length;
for (i = 0; i < length; i++) {
batches[i].removeAllPrimitives();
}
const subscriptions = this._subscriptions.values;
length = subscriptions.length;
for (i = 0; i < length; i++) {
subscriptions[i]();
}
this._subscriptions.removeAll();
return destroyObject(this);
};
/**
* @private
*/
PolylineVisualizer._onGeometryChanged = function (updater) {
const removedObjects = this._removedObjects;
const changedObjects = this._changedObjects;
const entity = updater.entity;
const id = entity.id;
if (!defined(removedObjects.get(id)) && !defined(changedObjects.get(id))) {
changedObjects.set(id, entity);
}
};
/**
* @private
*/
PolylineVisualizer.prototype._onCollectionChanged = function (
entityCollection,
added,
removed,
) {
const addedObjects = this._addedObjects;
const removedObjects = this._removedObjects;
const changedObjects = this._changedObjects;
let i;
let id;
let entity;
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
id = entity.id;
if (!addedObjects.remove(id)) {
removedObjects.set(id, entity);
changedObjects.remove(id);
}
}
for (i = added.length - 1; i > -1; i--) {
entity = added[i];
id = entity.id;
if (removedObjects.remove(id)) {
changedObjects.set(id, entity);
} else {
addedObjects.set(id, entity);
}
}
};
export default PolylineVisualizer;
@@ -0,0 +1,306 @@
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import Iso8601 from "../Core/Iso8601.js";
import PolylineVolumeGeometry from "../Core/PolylineVolumeGeometry.js";
import PolylineVolumeOutlineGeometry from "../Core/PolylineVolumeOutlineGeometry.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import Property from "./Property.js";
const scratchColor = new Color();
function PolylineVolumeGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.polylinePositions = undefined;
this.shapePositions = undefined;
this.cornerType = undefined;
this.granularity = undefined;
}
/**
* A {@link GeometryUpdater} for polyline volumes.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias PolylineVolumeGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function PolylineVolumeGeometryUpdater(entity, scene) {
GeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new PolylineVolumeGeometryOptions(entity),
geometryPropertyName: "polylineVolume",
observedPropertyNames: ["availability", "polylineVolume"],
});
this._onEntityPropertyChanged(
entity,
"polylineVolume",
entity.polylineVolume,
undefined,
);
}
if (defined(Object.create)) {
PolylineVolumeGeometryUpdater.prototype = Object.create(
GeometryUpdater.prototype,
);
PolylineVolumeGeometryUpdater.prototype.constructor =
PolylineVolumeGeometryUpdater;
}
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
PolylineVolumeGeometryUpdater.prototype.createFillGeometryInstance = function (
time,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
let attributes;
let color;
const show = new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const distanceDisplayConditionAttribute =
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
);
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
color = ColorGeometryInstanceAttribute.fromColor(currentColor);
attributes = {
show: show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color: color,
};
} else {
attributes = {
show: show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
};
}
return new GeometryInstance({
id: entity,
geometry: new PolylineVolumeGeometry(this._options),
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
PolylineVolumeGeometryUpdater.prototype.createOutlineGeometryInstance =
function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
return new GeometryInstance({
id: entity,
geometry: new PolylineVolumeOutlineGeometry(this._options),
attributes: {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
),
},
});
};
PolylineVolumeGeometryUpdater.prototype._isHidden = function (
entity,
polylineVolume,
) {
return (
!defined(polylineVolume.positions) ||
!defined(polylineVolume.shape) ||
GeometryUpdater.prototype._isHidden.call(this, entity, polylineVolume)
);
};
PolylineVolumeGeometryUpdater.prototype._isDynamic = function (
entity,
polylineVolume,
) {
return (
!polylineVolume.positions.isConstant || //
!polylineVolume.shape.isConstant || //
!Property.isConstant(polylineVolume.granularity) || //
!Property.isConstant(polylineVolume.outlineWidth) || //
!Property.isConstant(polylineVolume.cornerType)
);
};
PolylineVolumeGeometryUpdater.prototype._setStaticOptions = function (
entity,
polylineVolume,
) {
const granularity = polylineVolume.granularity;
const cornerType = polylineVolume.cornerType;
const options = this._options;
const isColorMaterial =
this._materialProperty instanceof ColorMaterialProperty;
options.vertexFormat = isColorMaterial
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
options.polylinePositions = polylineVolume.positions.getValue(
Iso8601.MINIMUM_VALUE,
options.polylinePositions,
);
options.shapePositions = polylineVolume.shape.getValue(
Iso8601.MINIMUM_VALUE,
options.shape,
);
options.granularity = defined(granularity)
? granularity.getValue(Iso8601.MINIMUM_VALUE)
: undefined;
options.cornerType = defined(cornerType)
? cornerType.getValue(Iso8601.MINIMUM_VALUE)
: undefined;
};
PolylineVolumeGeometryUpdater.DynamicGeometryUpdater =
DynamicPolylineVolumeGeometryUpdater;
/**
* @private
*/
function DynamicPolylineVolumeGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
}
if (defined(Object.create)) {
DynamicPolylineVolumeGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DynamicPolylineVolumeGeometryUpdater.prototype.constructor =
DynamicPolylineVolumeGeometryUpdater;
}
DynamicPolylineVolumeGeometryUpdater.prototype._isHidden = function (
entity,
polylineVolume,
time,
) {
const options = this._options;
return (
!defined(options.polylinePositions) ||
!defined(options.shapePositions) ||
DynamicGeometryUpdater.prototype._isHidden.call(
this,
entity,
polylineVolume,
time,
)
);
};
DynamicPolylineVolumeGeometryUpdater.prototype._setOptions = function (
entity,
polylineVolume,
time,
) {
const options = this._options;
options.polylinePositions = Property.getValueOrUndefined(
polylineVolume.positions,
time,
options.polylinePositions,
);
options.shapePositions = Property.getValueOrUndefined(
polylineVolume.shape,
time,
);
options.granularity = Property.getValueOrUndefined(
polylineVolume.granularity,
time,
);
options.cornerType = Property.getValueOrUndefined(
polylineVolume.cornerType,
time,
);
};
export default PolylineVolumeGeometryUpdater;
@@ -0,0 +1,235 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} PolylineVolumeGraphics.ConstructorOptions
*
* Initialization options for the PolylineVolumeGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the volume.
* @property {Property | Cartesian3[]} [positions] A Property specifying the array of {@link Cartesian3} positions which define the line strip.
* @property {Property | Cartesian2[]} [shape] A Property specifying the array of {@link Cartesian2} positions which define the shape to be extruded.
* @property {Property | CornerType} [cornerType=CornerType.ROUNDED] A {@link CornerType} Property specifying the style of the corners.
* @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between each latitude and longitude point.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the volume is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the volume.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the volume is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the volume casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this volume will be displayed.
*/
/**
* Describes a polyline volume defined as a line strip and corresponding two dimensional shape which is extruded along it.
* The resulting volume conforms to the curvature of the globe.
*
* @alias PolylineVolumeGraphics
* @constructor
*
* @param {PolylineVolumeGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @see Entity
* @demo {@link https://sandcastle.cesium.com/index.html?id=polyline-volume|Cesium Sandcastle Polyline Volume Demo}
*/
function PolylineVolumeGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._positions = undefined;
this._positionsSubscription = undefined;
this._shape = undefined;
this._shapeSubscription = undefined;
this._cornerType = undefined;
this._cornerTypeSubscription = undefined;
this._granularity = undefined;
this._granularitySubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distanceDisplayConditionSubsription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(PolylineVolumeGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof PolylineVolumeGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the volume.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the Property specifying the array of {@link Cartesian3} positions which define the line strip.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
*/
positions: createPropertyDescriptor("positions"),
/**
* Gets or sets the Property specifying the array of {@link Cartesian2} positions which define the shape to be extruded.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
*/
shape: createPropertyDescriptor("shape"),
/**
* Gets or sets the {@link CornerType} Property specifying the style of the corners.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
* @default CornerType.ROUNDED
*/
cornerType: createPropertyDescriptor("cornerType"),
/**
* Gets or sets the numeric Property specifying the angular distance between points on the volume.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
* @default {CesiumMath.RADIANS_PER_DEGREE}
*/
granularity: createPropertyDescriptor("granularity"),
/**
* Gets or sets the boolean Property specifying whether the volume is filled with the provided material.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the Property specifying the material used to fill the volume.
* @memberof PolylineVolumeGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying whether the volume is outlined.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Get or sets the enum Property specifying whether the volume
* casts or receives shadows from light sources.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this volume will be displayed.
* @memberof PolylineVolumeGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
});
/**
* Duplicates this instance.
*
* @param {PolylineVolumeGraphics} [result] The object onto which to store the result.
* @returns {PolylineVolumeGraphics} The modified result parameter or a new instance if one was not provided.
*/
PolylineVolumeGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new PolylineVolumeGraphics(this);
}
result.show = this.show;
result.positions = this.positions;
result.shape = this.shape;
result.cornerType = this.cornerType;
result.granularity = this.granularity;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {PolylineVolumeGraphics} source The object to be merged into this object.
*/
PolylineVolumeGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.positions = this.positions ?? source.positions;
this.shape = this.shape ?? source.shape;
this.cornerType = this.cornerType ?? source.cornerType;
this.granularity = this.granularity ?? source.granularity;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
};
export default PolylineVolumeGraphics;
@@ -0,0 +1,131 @@
import Cartesian3 from "../Core/Cartesian3.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Matrix3 from "../Core/Matrix3.js";
import ReferenceFrame from "../Core/ReferenceFrame.js";
import Transforms from "../Core/Transforms.js";
/**
* The interface for all {@link Property} objects that define a world
* location as a {@link Cartesian3} with an associated {@link ReferenceFrame}.
* This type defines an interface and cannot be instantiated directly.
*
* @alias PositionProperty
* @constructor
* @abstract
*
* @see CallbackPositionProperty
* @see CompositePositionProperty
* @see ConstantPositionProperty
* @see SampledPositionProperty
* @see TimeIntervalCollectionPositionProperty
*/
function PositionProperty() {
DeveloperError.throwInstantiationError();
}
Object.defineProperties(PositionProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof PositionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof PositionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets the reference frame that the position is defined in.
* @memberof PositionProperty.prototype
* @type {ReferenceFrame}
*/
referenceFrame: {
get: DeveloperError.throwInstantiationError,
},
});
/**
* Gets the value of the property at the provided time in the fixed frame.
* @function
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PositionProperty.prototype.getValue = DeveloperError.throwInstantiationError;
/**
* Gets the value of the property at the provided time and in the provided reference frame.
* @function
*
* @param {JulianDate} time The time for which to retrieve the value.
* @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PositionProperty.prototype.getValueInReferenceFrame =
DeveloperError.throwInstantiationError;
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
* @function
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
PositionProperty.prototype.equals = DeveloperError.throwInstantiationError;
const scratchMatrix3 = new Matrix3();
/**
* @private
*/
PositionProperty.convertToReferenceFrame = function (
time,
value,
inputFrame,
outputFrame,
result,
) {
if (!defined(value)) {
return value;
}
if (!defined(result)) {
result = new Cartesian3();
}
if (inputFrame === outputFrame) {
return Cartesian3.clone(value, result);
}
const icrfToFixed = Transforms.computeIcrfToCentralBodyFixedMatrix(
time,
scratchMatrix3,
);
if (inputFrame === ReferenceFrame.INERTIAL) {
return Matrix3.multiplyByVector(icrfToFixed, value, result);
}
if (inputFrame === ReferenceFrame.FIXED) {
return Matrix3.multiplyByVector(
Matrix3.transpose(icrfToFixed, scratchMatrix3),
value,
result,
);
}
};
export default PositionProperty;
@@ -0,0 +1,192 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import EventHelper from "../Core/EventHelper.js";
import JulianDate from "../Core/JulianDate.js";
import ReferenceFrame from "../Core/ReferenceFrame.js";
import Property from "./Property.js";
/**
* A {@link Property} whose value is an array whose items are the computed value
* of other PositionProperty instances.
*
* @alias PositionPropertyArray
* @constructor
*
* @param {Property[]} [value] An array of Property instances.
* @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
*/
function PositionPropertyArray(value, referenceFrame) {
this._value = undefined;
this._definitionChanged = new Event();
this._eventHelper = new EventHelper();
this._referenceFrame = referenceFrame ?? ReferenceFrame.FIXED;
this.setValue(value);
}
Object.defineProperties(PositionPropertyArray.prototype, {
/**
* Gets a value indicating if this property is constant. This property
* is considered constant if all property items in the array are constant.
* @memberof PositionPropertyArray.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
const value = this._value;
if (!defined(value)) {
return true;
}
const length = value.length;
for (let i = 0; i < length; i++) {
if (!Property.isConstant(value[i])) {
return false;
}
}
return true;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value or one of the properties in the array also changes.
* @memberof PositionPropertyArray.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the reference frame in which the position is defined.
* @memberof PositionPropertyArray.prototype
* @type {ReferenceFrame}
* @default ReferenceFrame.FIXED;
*/
referenceFrame: {
get: function () {
return this._referenceFrame;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {Cartesian3[]} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3[]} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PositionPropertyArray.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return this.getValueInReferenceFrame(time, ReferenceFrame.FIXED, result);
};
/**
* Gets the value of the property at the provided time and in the provided reference frame.
*
* @param {JulianDate} time The time for which to retrieve the value.
* @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
* @param {Cartesian3[]} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3[]} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PositionPropertyArray.prototype.getValueInReferenceFrame = function (
time,
referenceFrame,
result,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
if (!defined(referenceFrame)) {
throw new DeveloperError("referenceFrame is required.");
}
//>>includeEnd('debug');
const value = this._value;
if (!defined(value)) {
return undefined;
}
const length = value.length;
if (!defined(result)) {
result = new Array(length);
}
let i = 0;
let x = 0;
while (i < length) {
const property = value[i];
const itemValue = property.getValueInReferenceFrame(
time,
referenceFrame,
result[i],
);
if (defined(itemValue)) {
result[x] = itemValue;
x++;
}
i++;
}
result.length = x;
return result;
};
/**
* Sets the value of the property.
*
* @param {Property[]} value An array of Property instances.
*/
PositionPropertyArray.prototype.setValue = function (value) {
const eventHelper = this._eventHelper;
eventHelper.removeAll();
if (defined(value)) {
this._value = value.slice();
const length = value.length;
for (let i = 0; i < length; i++) {
const property = value[i];
if (defined(property)) {
eventHelper.add(
property.definitionChanged,
PositionPropertyArray.prototype._raiseDefinitionChanged,
this,
);
}
}
} else {
this._value = undefined;
}
this._definitionChanged.raiseEvent(this);
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
PositionPropertyArray.prototype.equals = function (other) {
return (
this === other || //
(other instanceof PositionPropertyArray && //
this._referenceFrame === other._referenceFrame && //
Property.arrayEquals(this._value, other._value))
);
};
PositionPropertyArray.prototype._raiseDefinitionChanged = function () {
this._definitionChanged.raiseEvent(this);
};
export default PositionPropertyArray;
+137
View File
@@ -0,0 +1,137 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
/**
* The interface for all properties, which represent a value that can optionally vary over time.
* This type defines an interface and cannot be instantiated directly.
*
* @alias Property
* @constructor
* @abstract
*
* @see CompositeProperty
* @see ConstantProperty
* @see SampledProperty
* @see TimeIntervalCollectionProperty
* @see MaterialProperty
* @see PositionProperty
* @see ReferenceProperty
*/
function Property() {
DeveloperError.throwInstantiationError();
}
Object.defineProperties(Property.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof Property.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: DeveloperError.throwInstantiationError,
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof Property.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: DeveloperError.throwInstantiationError,
},
});
/**
* Gets the value of the property at the provided time.
* @function
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
Property.prototype.getValue = DeveloperError.throwInstantiationError;
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
* @function
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Property.prototype.equals = DeveloperError.throwInstantiationError;
/**
* @private
*/
Property.equals = function (left, right) {
return left === right || (defined(left) && left.equals(right));
};
/**
* @private
*/
Property.arrayEquals = function (left, right) {
if (left === right) {
return true;
}
if (!defined(left) || !defined(right) || left.length !== right.length) {
return false;
}
const length = left.length;
for (let i = 0; i < length; i++) {
if (!Property.equals(left[i], right[i])) {
return false;
}
}
return true;
};
/**
* @private
*/
Property.isConstant = function (property) {
return !defined(property) || property.isConstant;
};
/**
* @private
*/
Property.getValueOrUndefined = function (property, time, result) {
return defined(property) ? property.getValue(time, result) : undefined;
};
/**
* @private
*/
Property.getValueOrDefault = function (property, time, valueDefault, result) {
return defined(property)
? (property.getValue(time, result) ?? valueDefault)
: valueDefault;
};
/**
* @private
*/
Property.getValueOrClonedDefault = function (
property,
time,
valueDefault,
result,
) {
let value;
if (defined(property)) {
value = property.getValue(time, result);
}
if (!defined(value)) {
value = valueDefault.clone(value);
}
return value;
};
export default Property;
@@ -0,0 +1,147 @@
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import EventHelper from "../Core/EventHelper.js";
import JulianDate from "../Core/JulianDate.js";
import Property from "./Property.js";
/**
* A {@link Property} whose value is an array whose items are the computed value
* of other property instances.
*
* @alias PropertyArray
* @constructor
*
* @param {Property[]} [value] An array of Property instances.
*/
function PropertyArray(value) {
this._value = undefined;
this._definitionChanged = new Event();
this._eventHelper = new EventHelper();
this.setValue(value);
}
Object.defineProperties(PropertyArray.prototype, {
/**
* Gets a value indicating if this property is constant. This property
* is considered constant if all property items in the array are constant.
* @memberof PropertyArray.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
const value = this._value;
if (!defined(value)) {
return true;
}
const length = value.length;
for (let i = 0; i < length; i++) {
if (!Property.isConstant(value[i])) {
return false;
}
}
return true;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value or one of the properties in the array also changes.
* @memberof PropertyArray.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object[]} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object[]} The modified result parameter, which is an array of values produced by evaluating each of the contained properties at the given time or a new instance if the result parameter was not supplied.
*/
PropertyArray.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
const value = this._value;
if (!defined(value)) {
return undefined;
}
const length = value.length;
if (!defined(result)) {
result = new Array(length);
}
let i = 0;
let x = 0;
while (i < length) {
const property = this._value[i];
const itemValue = property.getValue(time, result[i]);
if (defined(itemValue)) {
result[x] = itemValue;
x++;
}
i++;
}
result.length = x;
return result;
};
/**
* Sets the value of the property.
*
* @param {Property[]} value An array of Property instances.
*/
PropertyArray.prototype.setValue = function (value) {
const eventHelper = this._eventHelper;
eventHelper.removeAll();
if (defined(value)) {
this._value = value.slice();
const length = value.length;
for (let i = 0; i < length; i++) {
const property = value[i];
if (defined(property)) {
eventHelper.add(
property.definitionChanged,
PropertyArray.prototype._raiseDefinitionChanged,
this,
);
}
}
} else {
this._value = undefined;
}
this._definitionChanged.raiseEvent(this);
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
PropertyArray.prototype.equals = function (other) {
return (
this === other || //
(other instanceof PropertyArray && //
Property.arrayEquals(this._value, other._value))
);
};
PropertyArray.prototype._raiseDefinitionChanged = function () {
this._definitionChanged.raiseEvent(this);
};
export default PropertyArray;
+275
View File
@@ -0,0 +1,275 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import ConstantProperty from "./ConstantProperty.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
/**
* A {@link Property} whose value is a key-value mapping of property names to the computed value of other properties.
*
* @alias PropertyBag
* @implements Record<string, any>
* @constructor
*
* @param {object} [value] An object, containing key-value mapping of property names to properties.
* @param {Function} [createPropertyCallback] A function that will be called when the value of any of the properties in value are not a Property.
*/
function PropertyBag(value, createPropertyCallback) {
this._propertyNames = [];
this._definitionChanged = new Event();
if (defined(value)) {
this.merge(value, createPropertyCallback);
}
}
Object.defineProperties(PropertyBag.prototype, {
/**
* Gets the names of all properties registered on this instance.
* @memberof PropertyBag.prototype
* @type {Array}
*/
propertyNames: {
get: function () {
return this._propertyNames;
},
},
/**
* Gets a value indicating if this property is constant. This property
* is considered constant if all property items in this object are constant.
* @memberof PropertyBag.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
const propertyNames = this._propertyNames;
for (let i = 0, len = propertyNames.length; i < len; i++) {
if (!Property.isConstant(this[propertyNames[i]])) {
return false;
}
}
return true;
},
},
/**
* Gets the event that is raised whenever the set of properties contained in this
* object changes, or one of the properties itself changes.
*
* @memberof PropertyBag.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
});
/**
* Determines if this object has defined a property with the given name.
*
* @param {string} propertyName The name of the property to check for.
*
* @returns {boolean} True if this object has defined a property with the given name, false otherwise.
*/
PropertyBag.prototype.hasProperty = function (propertyName) {
return this._propertyNames.indexOf(propertyName) !== -1;
};
function createConstantProperty(value) {
return new ConstantProperty(value);
}
/**
* Adds a property to this object.
*
* @param {string} propertyName The name of the property to add.
* @param {*} [value] The value of the new property, if provided.
* @param {Function} [createPropertyCallback] A function that will be called when the value of this new property is set to a value that is not a Property.
*
* @exception {DeveloperError} "propertyName" is already a registered property.
*/
PropertyBag.prototype.addProperty = function (
propertyName,
value,
createPropertyCallback,
) {
const propertyNames = this._propertyNames;
//>>includeStart('debug', pragmas.debug);
if (!defined(propertyName)) {
throw new DeveloperError("propertyName is required.");
}
if (propertyNames.indexOf(propertyName) !== -1) {
throw new DeveloperError(
`${propertyName} is already a registered property.`,
);
}
//>>includeEnd('debug');
propertyNames.push(propertyName);
Object.defineProperty(
this,
propertyName,
createPropertyDescriptor(
propertyName,
true,
createPropertyCallback ?? createConstantProperty,
),
);
if (defined(value)) {
this[propertyName] = value;
}
this._definitionChanged.raiseEvent(this);
};
/**
* Removed a property previously added with addProperty.
*
* @param {string} propertyName The name of the property to remove.
*
* @exception {DeveloperError} "propertyName" is not a registered property.
*/
PropertyBag.prototype.removeProperty = function (propertyName) {
const propertyNames = this._propertyNames;
const index = propertyNames.indexOf(propertyName);
//>>includeStart('debug', pragmas.debug);
if (!defined(propertyName)) {
throw new DeveloperError("propertyName is required.");
}
if (index === -1) {
throw new DeveloperError(`${propertyName} is not a registered property.`);
}
//>>includeEnd('debug');
this._propertyNames.splice(index, 1);
delete this[propertyName];
this._definitionChanged.raiseEvent(this);
};
const timeScratch = new JulianDate();
/**
* Gets the value of this property. Each contained property will be evaluated at the given time, and the overall
* result will be an object, mapping property names to those values.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* Note that any properties in result which are not part of this PropertyBag will be left as-is.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
PropertyBag.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
const propertyNames = this._propertyNames;
for (let i = 0, len = propertyNames.length; i < len; i++) {
const propertyName = propertyNames[i];
result[propertyName] = Property.getValueOrUndefined(
this[propertyName],
time,
result[propertyName],
);
}
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {object} source The object to be merged into this object.
* @param {Function} [createPropertyCallback] A function that will be called when the value of any of the properties in value are not a Property.
*/
PropertyBag.prototype.merge = function (source, createPropertyCallback) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
const propertyNames = this._propertyNames;
const sourcePropertyNames = defined(source._propertyNames)
? source._propertyNames
: Object.keys(source);
for (let i = 0, len = sourcePropertyNames.length; i < len; i++) {
const name = sourcePropertyNames[i];
const targetProperty = this[name];
const sourceProperty = source[name];
//Custom properties that are registered on the source must also be added to this.
if (targetProperty === undefined && propertyNames.indexOf(name) === -1) {
this.addProperty(name, undefined, createPropertyCallback);
}
if (sourceProperty !== undefined) {
if (targetProperty !== undefined) {
if (defined(targetProperty) && defined(targetProperty.merge)) {
targetProperty.merge(sourceProperty);
}
} else if (
defined(sourceProperty) &&
defined(sourceProperty.merge) &&
defined(sourceProperty.clone)
) {
this[name] = sourceProperty.clone();
} else {
this[name] = sourceProperty;
}
}
}
};
function propertiesEqual(a, b) {
const aPropertyNames = a._propertyNames;
const bPropertyNames = b._propertyNames;
const len = aPropertyNames.length;
if (len !== bPropertyNames.length) {
return false;
}
for (let aIndex = 0; aIndex < len; ++aIndex) {
const name = aPropertyNames[aIndex];
const bIndex = bPropertyNames.indexOf(name);
if (bIndex === -1) {
return false;
}
if (!Property.equals(a[name], b[name])) {
return false;
}
}
return true;
}
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
PropertyBag.prototype.equals = function (other) {
return (
this === other || //
(other instanceof PropertyBag && //
propertiesEqual(this, other))
);
};
export default PropertyBag;
@@ -0,0 +1,427 @@
import ApproximateTerrainHeights from "../Core/ApproximateTerrainHeights.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartographic from "../Core/Cartographic.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import Iso8601 from "../Core/Iso8601.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import Rectangle from "../Core/Rectangle.js";
import RectangleGeometry from "../Core/RectangleGeometry.js";
import RectangleOutlineGeometry from "../Core/RectangleOutlineGeometry.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import HeightReference from "../Scene/HeightReference.js";
import MaterialAppearance from "../Scene/MaterialAppearance.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import DynamicGeometryUpdater from "./DynamicGeometryUpdater.js";
import GeometryUpdater from "./GeometryUpdater.js";
import GroundGeometryUpdater from "./GroundGeometryUpdater.js";
import Property from "./Property.js";
const scratchColor = new Color();
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
const scratchRectangle = new Rectangle();
const scratchCenterRect = new Rectangle();
const scratchCarto = new Cartographic();
function RectangleGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = undefined;
this.rectangle = undefined;
this.height = undefined;
this.extrudedHeight = undefined;
this.granularity = undefined;
this.stRotation = undefined;
this.rotation = undefined;
this.offsetAttribute = undefined;
}
/**
* A {@link GeometryUpdater} for rectangles.
* Clients do not normally create this class directly, but instead rely on {@link DataSourceDisplay}.
* @alias RectangleGeometryUpdater
* @constructor
*
* @param {Entity} entity The entity containing the geometry to be visualized.
* @param {Scene} scene The scene where visualization is taking place.
*/
function RectangleGeometryUpdater(entity, scene) {
GroundGeometryUpdater.call(this, {
entity: entity,
scene: scene,
geometryOptions: new RectangleGeometryOptions(entity),
geometryPropertyName: "rectangle",
observedPropertyNames: ["availability", "rectangle"],
});
this._onEntityPropertyChanged(
entity,
"rectangle",
entity.rectangle,
undefined,
);
}
if (defined(Object.create)) {
RectangleGeometryUpdater.prototype = Object.create(
GroundGeometryUpdater.prototype,
);
RectangleGeometryUpdater.prototype.constructor = RectangleGeometryUpdater;
}
/**
* Creates the geometry instance which represents the fill of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the filled portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent a filled geometry.
*/
RectangleGeometryUpdater.prototype.createFillGeometryInstance = function (
time,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError(
"This instance does not represent a filled geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._fillProperty.getValue(time),
),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time),
),
offset: undefined,
color: undefined,
};
if (this._materialProperty instanceof ColorMaterialProperty) {
let currentColor;
if (
defined(this._materialProperty.color) &&
(this._materialProperty.color.isConstant || isAvailable)
) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined(currentColor)) {
currentColor = Color.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute.fromColor(currentColor);
}
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new RectangleGeometry(this._options),
attributes: attributes,
});
};
/**
* Creates the geometry instance which represents the outline of the geometry.
*
* @param {JulianDate} time The time to use when retrieving initial attribute values.
* @returns {GeometryInstance} The geometry instance representing the outline portion of the geometry.
*
* @exception {DeveloperError} This instance does not represent an outlined geometry.
*/
RectangleGeometryUpdater.prototype.createOutlineGeometryInstance = function (
time,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError(
"This instance does not represent an outlined geometry.",
);
}
//>>includeEnd('debug');
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property.getValueOrDefault(
this._outlineColorProperty,
time,
Color.BLACK,
scratchColor,
);
const distanceDisplayCondition =
this._distanceDisplayConditionProperty.getValue(time);
const attributes = {
show: new ShowGeometryInstanceAttribute(
isAvailable &&
entity.isShowing &&
this._showProperty.getValue(time) &&
this._showOutlineProperty.getValue(time),
),
color: ColorGeometryInstanceAttribute.fromColor(outlineColor),
distanceDisplayCondition:
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition(
distanceDisplayCondition,
),
offset: undefined,
};
if (defined(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute.fromCartesian3(
Property.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch,
),
);
}
return new GeometryInstance({
id: entity,
geometry: new RectangleOutlineGeometry(this._options),
attributes: attributes,
});
};
RectangleGeometryUpdater.prototype._computeCenter = function (time, result) {
const rect = Property.getValueOrUndefined(
this._entity.rectangle.coordinates,
time,
scratchCenterRect,
);
if (!defined(rect)) {
return;
}
const center = Rectangle.center(rect, scratchCarto);
return Cartographic.toCartesian(center, Ellipsoid.default, result);
};
RectangleGeometryUpdater.prototype._isHidden = function (entity, rectangle) {
return (
!defined(rectangle.coordinates) ||
GeometryUpdater.prototype._isHidden.call(this, entity, rectangle)
);
};
RectangleGeometryUpdater.prototype._isDynamic = function (entity, rectangle) {
return (
!rectangle.coordinates.isConstant || //
!Property.isConstant(rectangle.height) || //
!Property.isConstant(rectangle.extrudedHeight) || //
!Property.isConstant(rectangle.granularity) || //
!Property.isConstant(rectangle.stRotation) || //
!Property.isConstant(rectangle.rotation) || //
!Property.isConstant(rectangle.outlineWidth) || //
!Property.isConstant(rectangle.zIndex) || //
(this._onTerrain &&
!Property.isConstant(this._materialProperty) &&
!(this._materialProperty instanceof ColorMaterialProperty))
);
};
RectangleGeometryUpdater.prototype._setStaticOptions = function (
entity,
rectangle,
) {
const isColorMaterial =
this._materialProperty instanceof ColorMaterialProperty;
let heightValue = Property.getValueOrUndefined(
rectangle.height,
Iso8601.MINIMUM_VALUE,
);
const heightReferenceValue = Property.getValueOrDefault(
rectangle.heightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
let extrudedHeightValue = Property.getValueOrUndefined(
rectangle.extrudedHeight,
Iso8601.MINIMUM_VALUE,
);
const extrudedHeightReferenceValue = Property.getValueOrDefault(
rectangle.extrudedHeightReference,
Iso8601.MINIMUM_VALUE,
HeightReference.NONE,
);
if (defined(extrudedHeightValue) && !defined(heightValue)) {
heightValue = 0;
}
const options = this._options;
options.vertexFormat = isColorMaterial
? PerInstanceColorAppearance.VERTEX_FORMAT
: MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat;
options.rectangle = rectangle.coordinates.getValue(
Iso8601.MINIMUM_VALUE,
options.rectangle,
);
options.granularity = Property.getValueOrUndefined(
rectangle.granularity,
Iso8601.MINIMUM_VALUE,
);
options.stRotation = Property.getValueOrUndefined(
rectangle.stRotation,
Iso8601.MINIMUM_VALUE,
);
options.rotation = Property.getValueOrUndefined(
rectangle.rotation,
Iso8601.MINIMUM_VALUE,
);
options.offsetAttribute =
GroundGeometryUpdater.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue,
);
options.height = GroundGeometryUpdater.getGeometryHeight(
heightValue,
heightReferenceValue,
);
extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue,
);
if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
RectangleGeometry.computeRectangle(options, scratchRectangle),
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
RectangleGeometryUpdater.DynamicGeometryUpdater =
DynamicRectangleGeometryUpdater;
/**
* @private
*/
function DynamicRectangleGeometryUpdater(
geometryUpdater,
primitives,
groundPrimitives,
) {
DynamicGeometryUpdater.call(
this,
geometryUpdater,
primitives,
groundPrimitives,
);
}
if (defined(Object.create)) {
DynamicRectangleGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater.prototype,
);
DynamicRectangleGeometryUpdater.prototype.constructor =
DynamicRectangleGeometryUpdater;
}
DynamicRectangleGeometryUpdater.prototype._isHidden = function (
entity,
rectangle,
time,
) {
return (
!defined(this._options.rectangle) ||
DynamicGeometryUpdater.prototype._isHidden.call(
this,
entity,
rectangle,
time,
)
);
};
DynamicRectangleGeometryUpdater.prototype._setOptions = function (
entity,
rectangle,
time,
) {
const options = this._options;
let heightValue = Property.getValueOrUndefined(rectangle.height, time);
const heightReferenceValue = Property.getValueOrDefault(
rectangle.heightReference,
time,
HeightReference.NONE,
);
let extrudedHeightValue = Property.getValueOrUndefined(
rectangle.extrudedHeight,
time,
);
const extrudedHeightReferenceValue = Property.getValueOrDefault(
rectangle.extrudedHeightReference,
time,
HeightReference.NONE,
);
if (defined(extrudedHeightValue) && !defined(heightValue)) {
heightValue = 0;
}
options.rectangle = Property.getValueOrUndefined(
rectangle.coordinates,
time,
options.rectangle,
);
options.granularity = Property.getValueOrUndefined(
rectangle.granularity,
time,
);
options.stRotation = Property.getValueOrUndefined(rectangle.stRotation, time);
options.rotation = Property.getValueOrUndefined(rectangle.rotation, time);
options.offsetAttribute =
GroundGeometryUpdater.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue,
);
options.height = GroundGeometryUpdater.getGeometryHeight(
heightValue,
heightReferenceValue,
);
extrudedHeightValue = GroundGeometryUpdater.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue,
);
if (extrudedHeightValue === GroundGeometryUpdater.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights.getMinimumMaximumHeights(
RectangleGeometry.computeRectangle(options, scratchRectangle),
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
export default RectangleGeometryUpdater;
@@ -0,0 +1,317 @@
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import createMaterialPropertyDescriptor from "./createMaterialPropertyDescriptor.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
/**
* @typedef {object} RectangleGraphics.ConstructorOptions
*
* Initialization options for the RectangleGraphics constructor
*
* @property {Property | boolean} [show=true] A boolean Property specifying the visibility of the rectangle.
* @property {Property | Rectangle} [coordinates] The Property specifying the {@link Rectangle}.
* @property {Property | number} [height=0] A numeric Property specifying the altitude of the rectangle relative to the ellipsoid surface.
* @property {Property | HeightReference} [heightReference=HeightReference.NONE] A Property specifying what the height is relative to.
* @property {Property | number} [extrudedHeight] A numeric Property specifying the altitude of the rectangle's extruded face relative to the ellipsoid surface.
* @property {Property | HeightReference} [extrudedHeightReference=HeightReference.NONE] A Property specifying what the extrudedHeight is relative to.
* @property {Property | number} [rotation=0.0] A numeric property specifying the rotation of the rectangle clockwise from north.
* @property {Property | number} [stRotation=0.0] A numeric property specifying the rotation of the rectangle texture counter-clockwise from north.
* @property {Property | number} [granularity=Cesium.Math.RADIANS_PER_DEGREE] A numeric Property specifying the angular distance between points on the rectangle.
* @property {Property | boolean} [fill=true] A boolean Property specifying whether the rectangle is filled with the provided material.
* @property {MaterialProperty | Color} [material=Color.WHITE] A Property specifying the material used to fill the rectangle.
* @property {Property | boolean} [outline=false] A boolean Property specifying whether the rectangle is outlined.
* @property {Property | Color} [outlineColor=Color.BLACK] A Property specifying the {@link Color} of the outline.
* @property {Property | number} [outlineWidth=1.0] A numeric Property specifying the width of the outline.
* @property {Property | ShadowMode} [shadows=ShadowMode.DISABLED] An enum Property specifying whether the rectangle casts or receives shadows from light sources.
* @property {Property | DistanceDisplayCondition} [distanceDisplayCondition] A Property specifying at what distance from the camera that this rectangle will be displayed.
* @property {Property | ClassificationType} [classificationType=ClassificationType.BOTH] An enum Property specifying whether this rectangle will classify terrain, 3D Tiles, or both when on the ground.
* @property {Property | number} [zIndex=0] A Property specifying the zIndex used for ordering ground geometry. Only has an effect if the rectangle is constant and neither height or extrudedHeight are specified.
*/
/**
* Describes graphics for a {@link Rectangle}.
* The rectangle conforms to the curvature of the globe and can be placed on the surface or
* at altitude and can optionally be extruded into a volume.
*
* @alias RectangleGraphics
* @constructor
*
* @param {RectangleGraphics.ConstructorOptions} [options] Object describing initialization options
*
* @see Entity
* @demo {@link https://sandcastle.cesium.com/index.html?id=rectangle|Cesium Sandcastle Rectangle Demo}
*/
function RectangleGraphics(options) {
this._definitionChanged = new Event();
this._show = undefined;
this._showSubscription = undefined;
this._coordinates = undefined;
this._coordinatesSubscription = undefined;
this._height = undefined;
this._heightSubscription = undefined;
this._heightReference = undefined;
this._heightReferenceSubscription = undefined;
this._extrudedHeight = undefined;
this._extrudedHeightSubscription = undefined;
this._extrudedHeightReference = undefined;
this._extrudedHeightReferenceSubscription = undefined;
this._rotation = undefined;
this._rotationSubscription = undefined;
this._stRotation = undefined;
this._stRotationSubscription = undefined;
this._granularity = undefined;
this._granularitySubscription = undefined;
this._fill = undefined;
this._fillSubscription = undefined;
this._material = undefined;
this._materialSubscription = undefined;
this._outline = undefined;
this._outlineSubscription = undefined;
this._outlineColor = undefined;
this._outlineColorSubscription = undefined;
this._outlineWidth = undefined;
this._outlineWidthSubscription = undefined;
this._shadows = undefined;
this._shadowsSubscription = undefined;
this._distanceDisplayCondition = undefined;
this._distancedisplayConditionSubscription = undefined;
this._classificationType = undefined;
this._classificationTypeSubscription = undefined;
this._zIndex = undefined;
this._zIndexSubscription = undefined;
this.merge(options ?? Frozen.EMPTY_OBJECT);
}
Object.defineProperties(RectangleGraphics.prototype, {
/**
* Gets the event that is raised whenever a property or sub-property is changed or modified.
* @memberof RectangleGraphics.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the boolean Property specifying the visibility of the rectangle.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default true
*/
show: createPropertyDescriptor("show"),
/**
* Gets or sets the Property specifying the {@link Rectangle}.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
*/
coordinates: createPropertyDescriptor("coordinates"),
/**
* Gets or sets the numeric Property specifying the altitude of the rectangle.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default 0.0
*/
height: createPropertyDescriptor("height"),
/**
* Gets or sets the Property specifying the {@link HeightReference}.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
heightReference: createPropertyDescriptor("heightReference"),
/**
* Gets or sets the numeric Property specifying the altitude of the rectangle extrusion.
* Setting this property creates volume starting at height and ending at this altitude.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
*/
extrudedHeight: createPropertyDescriptor("extrudedHeight"),
/**
* Gets or sets the Property specifying the extruded {@link HeightReference}.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default HeightReference.NONE
*/
extrudedHeightReference: createPropertyDescriptor("extrudedHeightReference"),
/**
* Gets or sets the numeric property specifying the rotation of the rectangle clockwise from north.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default 0
*/
rotation: createPropertyDescriptor("rotation"),
/**
* Gets or sets the numeric property specifying the rotation of the rectangle texture counter-clockwise from north.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default 0
*/
stRotation: createPropertyDescriptor("stRotation"),
/**
* Gets or sets the numeric Property specifying the angular distance between points on the rectangle.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default {CesiumMath.RADIANS_PER_DEGREE}
*/
granularity: createPropertyDescriptor("granularity"),
/**
* Gets or sets the boolean Property specifying whether the rectangle is filled with the provided material.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default true
*/
fill: createPropertyDescriptor("fill"),
/**
* Gets or sets the Property specifying the material used to fill the rectangle.
* @memberof RectangleGraphics.prototype
* @type {MaterialProperty}
* @default Color.WHITE
*/
material: createMaterialPropertyDescriptor("material"),
/**
* Gets or sets the Property specifying whether the rectangle is outlined.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default false
*/
outline: createPropertyDescriptor("outline"),
/**
* Gets or sets the Property specifying the {@link Color} of the outline.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
outlineColor: createPropertyDescriptor("outlineColor"),
/**
* Gets or sets the numeric Property specifying the width of the outline.
* <p>
* Note: This property will be ignored on all major browsers on Windows platforms. For details, see (@link https://github.com/CesiumGS/cesium/issues/40}.
* </p>
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default 1.0
*/
outlineWidth: createPropertyDescriptor("outlineWidth"),
/**
* Get or sets the enum Property specifying whether the rectangle
* casts or receives shadows from light sources.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default ShadowMode.DISABLED
*/
shadows: createPropertyDescriptor("shadows"),
/**
* Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this rectangle will be displayed.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
*/
distanceDisplayCondition: createPropertyDescriptor(
"distanceDisplayCondition",
),
/**
* Gets or sets the {@link ClassificationType} Property specifying whether this rectangle will classify terrain, 3D Tiles, or both when on the ground.
* @memberof RectangleGraphics.prototype
* @type {Property|undefined}
* @default ClassificationType.BOTH
*/
classificationType: createPropertyDescriptor("classificationType"),
/**
* Gets or sets the zIndex Property specifying the ordering of the rectangle. Only has an effect if the rectangle is constant and neither height or extrudedHeight are specified.
* @memberof RectangleGraphics.prototype
* @type {ConstantProperty|undefined}
* @default 0
*/
zIndex: createPropertyDescriptor("zIndex"),
});
/**
* Duplicates this instance.
*
* @param {RectangleGraphics} [result] The object onto which to store the result.
* @returns {RectangleGraphics} The modified result parameter or a new instance if one was not provided.
*/
RectangleGraphics.prototype.clone = function (result) {
if (!defined(result)) {
return new RectangleGraphics(this);
}
result.show = this.show;
result.coordinates = this.coordinates;
result.height = this.height;
result.heightReference = this.heightReference;
result.extrudedHeight = this.extrudedHeight;
result.extrudedHeightReference = this.extrudedHeightReference;
result.rotation = this.rotation;
result.stRotation = this.stRotation;
result.granularity = this.granularity;
result.fill = this.fill;
result.material = this.material;
result.outline = this.outline;
result.outlineColor = this.outlineColor;
result.outlineWidth = this.outlineWidth;
result.shadows = this.shadows;
result.distanceDisplayCondition = this.distanceDisplayCondition;
result.classificationType = this.classificationType;
result.zIndex = this.zIndex;
return result;
};
/**
* Assigns each unassigned property on this object to the value
* of the same property on the provided source object.
*
* @param {RectangleGraphics} source The object to be merged into this object.
*/
RectangleGraphics.prototype.merge = function (source) {
//>>includeStart('debug', pragmas.debug);
if (!defined(source)) {
throw new DeveloperError("source is required.");
}
//>>includeEnd('debug');
this.show = this.show ?? source.show;
this.coordinates = this.coordinates ?? source.coordinates;
this.height = this.height ?? source.height;
this.heightReference = this.heightReference ?? source.heightReference;
this.extrudedHeight = this.extrudedHeight ?? source.extrudedHeight;
this.extrudedHeightReference =
this.extrudedHeightReference ?? source.extrudedHeightReference;
this.rotation = this.rotation ?? source.rotation;
this.stRotation = this.stRotation ?? source.stRotation;
this.granularity = this.granularity ?? source.granularity;
this.fill = this.fill ?? source.fill;
this.material = this.material ?? source.material;
this.outline = this.outline ?? source.outline;
this.outlineColor = this.outlineColor ?? source.outlineColor;
this.outlineWidth = this.outlineWidth ?? source.outlineWidth;
this.shadows = this.shadows ?? source.shadows;
this.distanceDisplayCondition =
this.distanceDisplayCondition ?? source.distanceDisplayCondition;
this.classificationType =
this.classificationType ?? source.classificationType;
this.zIndex = this.zIndex ?? source.zIndex;
};
export default RectangleGraphics;
@@ -0,0 +1,371 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import Property from "./Property.js";
function resolve(that) {
let targetProperty = that._targetProperty;
if (!defined(targetProperty)) {
let targetEntity = that._targetEntity;
if (!defined(targetEntity)) {
targetEntity = that._targetCollection.getById(that._targetId);
if (!defined(targetEntity)) {
// target entity not found
that._targetEntity = that._targetProperty = undefined;
return;
}
// target entity was found. listen for changes to entity definition
targetEntity.definitionChanged.addEventListener(
ReferenceProperty.prototype._onTargetEntityDefinitionChanged,
that,
);
that._targetEntity = targetEntity;
}
// walk the list of property names and resolve properties
const targetPropertyNames = that._targetPropertyNames;
targetProperty = that._targetEntity;
for (
let i = 0, len = targetPropertyNames.length;
i < len && defined(targetProperty);
++i
) {
targetProperty = targetProperty[targetPropertyNames[i]];
}
// target property may or may not be defined, depending on if it was found
that._targetProperty = targetProperty;
}
return targetProperty;
}
/**
* A {@link Property} which transparently links to another property on a provided object.
*
* @alias ReferenceProperty
* @constructor
*
* @param {EntityCollection} targetCollection The entity collection which will be used to resolve the reference.
* @param {string} targetId The id of the entity which is being referenced.
* @param {string[]} targetPropertyNames The names of the property on the target entity which we will use.
*
* @example
* const collection = new Cesium.EntityCollection();
*
* //Create a new entity and assign a billboard scale.
* const object1 = new Cesium.Entity({id:'object1'});
* object1.billboard = new Cesium.BillboardGraphics();
* object1.billboard.scale = new Cesium.ConstantProperty(2.0);
* collection.add(object1);
*
* //Create a second entity and reference the scale from the first one.
* const object2 = new Cesium.Entity({id:'object2'});
* object2.model = new Cesium.ModelGraphics();
* object2.model.scale = new Cesium.ReferenceProperty(collection, 'object1', ['billboard', 'scale']);
* collection.add(object2);
*
* //Create a third object, but use the fromString helper function.
* const object3 = new Cesium.Entity({id:'object3'});
* object3.billboard = new Cesium.BillboardGraphics();
* object3.billboard.scale = Cesium.ReferenceProperty.fromString(collection, 'object1#billboard.scale');
* collection.add(object3);
*
* //You can refer to an entity with a # or . in id and property names by escaping them.
* const object4 = new Cesium.Entity({id:'#object.4'});
* object4.billboard = new Cesium.BillboardGraphics();
* object4.billboard.scale = new Cesium.ConstantProperty(2.0);
* collection.add(object4);
*
* const object5 = new Cesium.Entity({id:'object5'});
* object5.billboard = new Cesium.BillboardGraphics();
* object5.billboard.scale = Cesium.ReferenceProperty.fromString(collection, '\\#object\\.4#billboard.scale');
* collection.add(object5);
*/
function ReferenceProperty(targetCollection, targetId, targetPropertyNames) {
//>>includeStart('debug', pragmas.debug);
if (!defined(targetCollection)) {
throw new DeveloperError("targetCollection is required.");
}
if (!defined(targetId) || targetId === "") {
throw new DeveloperError("targetId is required.");
}
if (!defined(targetPropertyNames) || targetPropertyNames.length === 0) {
throw new DeveloperError("targetPropertyNames is required.");
}
for (let i = 0; i < targetPropertyNames.length; i++) {
const item = targetPropertyNames[i];
if (!defined(item) || item === "") {
throw new DeveloperError("reference contains invalid properties.");
}
}
//>>includeEnd('debug');
this._targetCollection = targetCollection;
this._targetId = targetId;
this._targetPropertyNames = targetPropertyNames;
this._targetProperty = undefined;
this._targetEntity = undefined;
this._definitionChanged = new Event();
targetCollection.collectionChanged.addEventListener(
ReferenceProperty.prototype._onCollectionChanged,
this,
);
}
Object.defineProperties(ReferenceProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* @memberof ReferenceProperty.prototype
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return Property.isConstant(resolve(this));
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever the referenced property's definition is changed.
* @memberof ReferenceProperty.prototype
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the reference frame that the position is defined in.
* This property is only valid if the referenced property is a {@link PositionProperty}.
* @memberof ReferenceProperty.prototype
* @type {ReferenceFrame}
* @readonly
*/
referenceFrame: {
get: function () {
const target = resolve(this);
return defined(target) ? target.referenceFrame : undefined;
},
},
/**
* Gets the id of the entity being referenced.
* @memberof ReferenceProperty.prototype
* @type {string}
* @readonly
*/
targetId: {
get: function () {
return this._targetId;
},
},
/**
* Gets the collection containing the entity being referenced.
* @memberof ReferenceProperty.prototype
* @type {EntityCollection}
* @readonly
*/
targetCollection: {
get: function () {
return this._targetCollection;
},
},
/**
* Gets the array of property names used to retrieve the referenced property.
* @memberof ReferenceProperty.prototype
* @type {}
* @readonly
*/
targetPropertyNames: {
get: function () {
return this._targetPropertyNames;
},
},
/**
* Gets the resolved instance of the underlying referenced property.
* @memberof ReferenceProperty.prototype
* @type {Property|undefined}
* @readonly
*/
resolvedProperty: {
get: function () {
return resolve(this);
},
},
});
/**
* Creates a new instance given the entity collection that will
* be used to resolve it and a string indicating the target entity id and property.
* The format of the string is "objectId#foo.bar", where # separates the id from
* property path and . separates sub-properties. If the reference identifier or
* or any sub-properties contains a # . or \ they must be escaped.
*
* @param {EntityCollection} targetCollection
* @param {string} referenceString
* @returns {ReferenceProperty} A new instance of ReferenceProperty.
*
* @exception {DeveloperError} invalid referenceString.
*/
ReferenceProperty.fromString = function (targetCollection, referenceString) {
//>>includeStart('debug', pragmas.debug);
if (!defined(targetCollection)) {
throw new DeveloperError("targetCollection is required.");
}
if (!defined(referenceString)) {
throw new DeveloperError("referenceString is required.");
}
//>>includeEnd('debug');
let identifier;
const values = [];
let inIdentifier = true;
let isEscaped = false;
let token = "";
for (let i = 0; i < referenceString.length; ++i) {
const c = referenceString.charAt(i);
if (isEscaped) {
token += c;
isEscaped = false;
} else if (c === "\\") {
isEscaped = true;
} else if (inIdentifier && c === "#") {
identifier = token;
inIdentifier = false;
token = "";
} else if (!inIdentifier && c === ".") {
values.push(token);
token = "";
} else {
token += c;
}
}
values.push(token);
return new ReferenceProperty(targetCollection, identifier, values);
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
ReferenceProperty.prototype.getValue = function (time, result) {
const target = resolve(this);
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return defined(target) ? target.getValue(time, result) : undefined;
};
/**
* Gets the value of the property at the provided time and in the provided reference frame.
* This method is only valid if the property being referenced is a {@link PositionProperty}.
*
* @param {JulianDate} time The time for which to retrieve the value.
* @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3} The modified result parameter or a new instance if the result parameter was not supplied.
*/
ReferenceProperty.prototype.getValueInReferenceFrame = function (
time,
referenceFrame,
result,
) {
const target = resolve(this);
return defined(target)
? target.getValueInReferenceFrame(time, referenceFrame, result)
: undefined;
};
/**
* Gets the {@link Material} type at the provided time.
* This method is only valid if the property being referenced is a {@link MaterialProperty}.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
ReferenceProperty.prototype.getType = function (time) {
const target = resolve(this);
return defined(target) ? target.getType(time) : undefined;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
ReferenceProperty.prototype.equals = function (other) {
if (this === other) {
return true;
}
const names = this._targetPropertyNames;
const otherNames = other._targetPropertyNames;
if (
this._targetCollection !== other._targetCollection || //
this._targetId !== other._targetId || //
names.length !== otherNames.length
) {
return false;
}
const length = this._targetPropertyNames.length;
for (let i = 0; i < length; i++) {
if (names[i] !== otherNames[i]) {
return false;
}
}
return true;
};
ReferenceProperty.prototype._onTargetEntityDefinitionChanged = function (
targetEntity,
name,
value,
oldValue,
) {
if (defined(this._targetProperty) && this._targetPropertyNames[0] === name) {
this._targetProperty = undefined;
this._definitionChanged.raiseEvent(this);
}
};
ReferenceProperty.prototype._onCollectionChanged = function (
collection,
added,
removed,
) {
let targetEntity = this._targetEntity;
if (defined(targetEntity) && removed.indexOf(targetEntity) !== -1) {
targetEntity.definitionChanged.removeEventListener(
ReferenceProperty.prototype._onTargetEntityDefinitionChanged,
this,
);
this._targetEntity = this._targetProperty = undefined;
} else if (!defined(targetEntity)) {
targetEntity = resolve(this);
if (defined(targetEntity)) {
this._definitionChanged.raiseEvent(this);
}
}
};
export default ReferenceProperty;
+155
View File
@@ -0,0 +1,155 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import CesiumMath from "../Core/Math.js";
/**
* Represents a {@link Packable} number that always interpolates values
* towards the shortest angle of rotation. This object is never used directly
* but is instead passed to the constructor of {@link SampledProperty}
* in order to represent a two-dimensional angle of rotation.
*
* @interface Rotation
*
*
* @example
* const time1 = Cesium.JulianDate.fromIso8601('2010-05-07T00:00:00');
* const time2 = Cesium.JulianDate.fromIso8601('2010-05-07T00:01:00');
* const time3 = Cesium.JulianDate.fromIso8601('2010-05-07T00:02:00');
*
* const property = new Cesium.SampledProperty(Cesium.Rotation);
* property.addSample(time1, 0);
* property.addSample(time3, Cesium.Math.toRadians(350));
*
* //Getting the value at time2 will equal 355 degrees instead
* //of 175 degrees (which is what you get if you construct
* //a SampledProperty(Number) instead. Note, the actual
* //return value is in radians, not degrees.
* property.getValue(time2);
*
* @see PackableForInterpolation
*/
const Rotation = {
/**
* The number of elements used to pack the object into an array.
* @type {number}
*/
packedLength: 1,
/**
* Stores the provided instance into the provided array.
*
* @param {Rotation} value The value to pack.
* @param {number[]} array The array to pack into.
* @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {number[]} The array that was packed into
*/
pack: function (value, array, startingIndex) {
//>>includeStart('debug', pragmas.debug);
if (!defined(value)) {
throw new DeveloperError("value is required");
}
if (!defined(array)) {
throw new DeveloperError("array is required");
}
//>>includeEnd('debug');
startingIndex = startingIndex ?? 0;
array[startingIndex] = value;
return array;
},
/**
* Retrieves an instance from a packed array.
*
* @param {number[]} array The packed array.
* @param {number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Rotation} [result] The object into which to store the result.
* @returns {Rotation} The modified result parameter or a new Rotation instance if one was not provided.
*/
unpack: function (array, startingIndex, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(array)) {
throw new DeveloperError("array is required");
}
//>>includeEnd('debug');
startingIndex = startingIndex ?? 0;
return array[startingIndex];
},
/**
* Converts a packed array into a form suitable for interpolation.
*
* @param {number[]} packedArray The packed array.
* @param {number} [startingIndex=0] The index of the first element to be converted.
* @param {number} [lastIndex=packedArray.length] The index of the last element to be converted.
* @param {number[]} [result] The object into which to store the result.
*/
convertPackedArrayForInterpolation: function (
packedArray,
startingIndex,
lastIndex,
result,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(packedArray)) {
throw new DeveloperError("packedArray is required");
}
//>>includeEnd('debug');
if (!defined(result)) {
result = [];
}
startingIndex = startingIndex ?? 0;
lastIndex = lastIndex ?? packedArray.length;
let previousValue;
for (let i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
const value = packedArray[startingIndex + i];
if (i === 0 || Math.abs(previousValue - value) < Math.PI) {
result[i] = value;
} else {
result[i] = value - CesiumMath.TWO_PI;
}
previousValue = value;
}
},
/**
* Retrieves an instance from a packed array converted with {@link Rotation.convertPackedArrayForInterpolation}.
*
* @param {number[]} array The array previously packed for interpolation.
* @param {number[]} sourceArray The original packed array.
* @param {number} [firstIndex=0] The firstIndex used to convert the array.
* @param {number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
* @param {Rotation} [result] The object into which to store the result.
* @returns {Rotation} The modified result parameter or a new Rotation instance if one was not provided.
*/
unpackInterpolationResult: function (
array,
sourceArray,
firstIndex,
lastIndex,
result,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(array)) {
throw new DeveloperError("array is required");
}
if (!defined(sourceArray)) {
throw new DeveloperError("sourceArray is required");
}
//>>includeEnd('debug');
result = array[0];
if (result < 0) {
return result + CesiumMath.TWO_PI;
}
return result;
},
};
export default Rotation;
@@ -0,0 +1,330 @@
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import ReferenceFrame from "../Core/ReferenceFrame.js";
import PositionProperty from "./PositionProperty.js";
import Property from "./Property.js";
import SampledProperty from "./SampledProperty.js";
/**
* A {@link SampledProperty} which is also a {@link PositionProperty}.
*
* @alias SampledPositionProperty
* @constructor
*
* @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
* @param {number} [numberOfDerivatives=0] The number of derivatives that accompany each position; i.e. velocity, acceleration, etc...
*/
function SampledPositionProperty(referenceFrame, numberOfDerivatives) {
numberOfDerivatives = numberOfDerivatives ?? 0;
let derivativeTypes;
if (numberOfDerivatives > 0) {
derivativeTypes = new Array(numberOfDerivatives);
for (let i = 0; i < numberOfDerivatives; i++) {
derivativeTypes[i] = Cartesian3;
}
}
this._numberOfDerivatives = numberOfDerivatives;
this._property = new SampledProperty(Cartesian3, derivativeTypes);
this._definitionChanged = new Event();
this._referenceFrame = referenceFrame ?? ReferenceFrame.FIXED;
this._property._definitionChanged.addEventListener(function () {
this._definitionChanged.raiseEvent(this);
}, this);
}
Object.defineProperties(SampledPositionProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof SampledPositionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._property.isConstant;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof SampledPositionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the reference frame in which the position is defined.
* @memberof SampledPositionProperty.prototype
* @type {ReferenceFrame}
* @default ReferenceFrame.FIXED;
*/
referenceFrame: {
get: function () {
return this._referenceFrame;
},
},
/**
* Gets the degree of interpolation to perform when retrieving a value. Call <code>setInterpolationOptions</code> to set this.
* @memberof SampledPositionProperty.prototype
*
* @type {number}
* @default 1
* @readonly
*/
interpolationDegree: {
get: function () {
return this._property.interpolationDegree;
},
},
/**
* Gets the interpolation algorithm to use when retrieving a value. Call <code>setInterpolationOptions</code> to set this.
* @memberof SampledPositionProperty.prototype
*
* @type {InterpolationAlgorithm}
* @default LinearApproximation
* @readonly
*/
interpolationAlgorithm: {
get: function () {
return this._property.interpolationAlgorithm;
},
},
/**
* The number of derivatives contained by this property; i.e. 0 for just position, 1 for velocity, etc.
* @memberof SampledPositionProperty.prototype
*
* @type {number}
* @default 0
*/
numberOfDerivatives: {
get: function () {
return this._numberOfDerivatives;
},
},
/**
* Gets or sets the type of extrapolation to perform when a value
* is requested at a time after any available samples.
* @memberof SampledPositionProperty.prototype
* @type {ExtrapolationType}
* @default ExtrapolationType.NONE
*/
forwardExtrapolationType: {
get: function () {
return this._property.forwardExtrapolationType;
},
set: function (value) {
this._property.forwardExtrapolationType = value;
},
},
/**
* Gets or sets the amount of time to extrapolate forward before
* the property becomes undefined. A value of 0 will extrapolate forever.
* @memberof SampledPositionProperty.prototype
* @type {number}
* @default 0
*/
forwardExtrapolationDuration: {
get: function () {
return this._property.forwardExtrapolationDuration;
},
set: function (value) {
this._property.forwardExtrapolationDuration = value;
},
},
/**
* Gets or sets the type of extrapolation to perform when a value
* is requested at a time before any available samples.
* @memberof SampledPositionProperty.prototype
* @type {ExtrapolationType}
* @default ExtrapolationType.NONE
*/
backwardExtrapolationType: {
get: function () {
return this._property.backwardExtrapolationType;
},
set: function (value) {
this._property.backwardExtrapolationType = value;
},
},
/**
* Gets or sets the amount of time to extrapolate backward
* before the property becomes undefined. A value of 0 will extrapolate forever.
* @memberof SampledPositionProperty.prototype
* @type {number}
* @default 0
*/
backwardExtrapolationDuration: {
get: function () {
return this._property.backwardExtrapolationDuration;
},
set: function (value) {
this._property.backwardExtrapolationDuration = value;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the position at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
SampledPositionProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return this.getValueInReferenceFrame(time, ReferenceFrame.FIXED, result);
};
/**
* Gets the position at the provided time and in the provided reference frame.
*
* @param {JulianDate} time The time for which to retrieve the value.
* @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
SampledPositionProperty.prototype.getValueInReferenceFrame = function (
time,
referenceFrame,
result,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
Check.defined("referenceFrame", referenceFrame);
//>>includeEnd('debug');
result = this._property.getValue(time, result);
if (defined(result)) {
return PositionProperty.convertToReferenceFrame(
time,
result,
this._referenceFrame,
referenceFrame,
result,
);
}
return undefined;
};
/**
* Sets the algorithm and degree to use when interpolating a position.
*
* @param {object} [options] Object with the following properties:
* @param {InterpolationAlgorithm} [options.interpolationAlgorithm] The new interpolation algorithm. If undefined, the existing property will be unchanged.
* @param {number} [options.interpolationDegree] The new interpolation degree. If undefined, the existing property will be unchanged.
*/
SampledPositionProperty.prototype.setInterpolationOptions = function (options) {
this._property.setInterpolationOptions(options);
};
/**
* Adds a new sample.
*
* @param {JulianDate} time The sample time.
* @param {Cartesian3} position The position at the provided time.
* @param {Cartesian3[]} [derivatives] The array of derivative values at the provided time.
*/
SampledPositionProperty.prototype.addSample = function (
time,
position,
derivatives,
) {
const numberOfDerivatives = this._numberOfDerivatives;
//>>includeStart('debug', pragmas.debug);
if (
numberOfDerivatives > 0 &&
(!defined(derivatives) || derivatives.length !== numberOfDerivatives)
) {
throw new DeveloperError(
"derivatives length must be equal to the number of derivatives.",
);
}
//>>includeEnd('debug');
this._property.addSample(time, position, derivatives);
};
/**
* Adds multiple samples via parallel arrays.
*
* @param {JulianDate[]} times An array of JulianDate instances where each index is a sample time.
* @param {Cartesian3[]} positions An array of Cartesian3 position instances, where each value corresponds to the provided time index.
* @param {Array[]} [derivatives] An array where each value is another array containing derivatives for the corresponding time index.
*
* @exception {DeveloperError} All arrays must be the same length.
*/
SampledPositionProperty.prototype.addSamples = function (
times,
positions,
derivatives,
) {
this._property.addSamples(times, positions, derivatives);
};
/**
* Adds samples as a single packed array where each new sample is represented as a date,
* followed by the packed representation of the corresponding value and derivatives.
*
* @param {number[]} packedSamples The array of packed samples.
* @param {JulianDate} [epoch] If any of the dates in packedSamples are numbers, they are considered an offset from this epoch, in seconds.
*/
SampledPositionProperty.prototype.addSamplesPackedArray = function (
packedSamples,
epoch,
) {
this._property.addSamplesPackedArray(packedSamples, epoch);
};
/**
* Removes a sample at the given time, if present.
*
* @param {JulianDate} time The sample time.
* @returns {boolean} <code>true</code> if a sample at time was removed, <code>false</code> otherwise.
*/
SampledPositionProperty.prototype.removeSample = function (time) {
return this._property.removeSample(time);
};
/**
* Removes all samples for the given time interval.
*
* @param {TimeInterval} time The time interval for which to remove all samples.
*/
SampledPositionProperty.prototype.removeSamples = function (timeInterval) {
this._property.removeSamples(timeInterval);
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
SampledPositionProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof SampledPositionProperty &&
Property.equals(this._property, other._property) && //
this._referenceFrame === other._referenceFrame)
);
};
export default SampledPositionProperty;
@@ -0,0 +1,855 @@
import binarySearch from "../Core/binarySearch.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import ExtrapolationType from "../Core/ExtrapolationType.js";
import JulianDate from "../Core/JulianDate.js";
import LinearApproximation from "../Core/LinearApproximation.js";
const PackableNumber = {
packedLength: 1,
pack: function (value, array, startingIndex) {
startingIndex = startingIndex ?? 0;
array[startingIndex] = value;
},
unpack: function (array, startingIndex, result) {
startingIndex = startingIndex ?? 0;
return array[startingIndex];
},
};
//We can't use splice for inserting new elements because function apply can't handle
//a huge number of arguments. See https://code.google.com/p/chromium/issues/detail?id=56588
function arrayInsert(array, startIndex, items) {
let i;
const arrayLength = array.length;
const itemsLength = items.length;
const newLength = arrayLength + itemsLength;
array.length = newLength;
if (arrayLength !== startIndex) {
let q = arrayLength - 1;
for (i = newLength - 1; i >= startIndex; i--) {
array[i] = array[q--];
}
}
for (i = 0; i < itemsLength; i++) {
array[startIndex++] = items[i];
}
}
function convertDate(date, epoch) {
if (date instanceof JulianDate) {
return date;
}
if (typeof date === "string") {
return JulianDate.fromIso8601(date);
}
return JulianDate.addSeconds(epoch, date, new JulianDate());
}
const timesSpliceArgs = [];
const valuesSpliceArgs = [];
function mergeNewSamples(epoch, times, values, newData, packedLength) {
let newDataIndex = 0;
let i;
let prevItem;
let timesInsertionPoint;
let valuesInsertionPoint;
let currentTime;
let nextTime;
while (newDataIndex < newData.length) {
currentTime = convertDate(newData[newDataIndex], epoch);
timesInsertionPoint = binarySearch(times, currentTime, JulianDate.compare);
let timesSpliceArgsCount = 0;
let valuesSpliceArgsCount = 0;
if (timesInsertionPoint < 0) {
//Doesn't exist, insert as many additional values as we can.
timesInsertionPoint = ~timesInsertionPoint;
valuesInsertionPoint = timesInsertionPoint * packedLength;
prevItem = undefined;
nextTime = times[timesInsertionPoint];
while (newDataIndex < newData.length) {
currentTime = convertDate(newData[newDataIndex], epoch);
if (
(defined(prevItem) &&
JulianDate.compare(prevItem, currentTime) >= 0) ||
(defined(nextTime) && JulianDate.compare(currentTime, nextTime) >= 0)
) {
break;
}
timesSpliceArgs[timesSpliceArgsCount++] = currentTime;
newDataIndex = newDataIndex + 1;
for (i = 0; i < packedLength; i++) {
valuesSpliceArgs[valuesSpliceArgsCount++] = newData[newDataIndex];
newDataIndex = newDataIndex + 1;
}
prevItem = currentTime;
}
if (timesSpliceArgsCount > 0) {
valuesSpliceArgs.length = valuesSpliceArgsCount;
arrayInsert(values, valuesInsertionPoint, valuesSpliceArgs);
timesSpliceArgs.length = timesSpliceArgsCount;
arrayInsert(times, timesInsertionPoint, timesSpliceArgs);
}
} else {
//Found an exact match
for (i = 0; i < packedLength; i++) {
newDataIndex++;
values[timesInsertionPoint * packedLength + i] = newData[newDataIndex];
}
newDataIndex++;
}
}
}
/**
* A {@link Property} whose value is interpolated for a given time from the
* provided set of samples and specified interpolation algorithm and degree.
* @alias SampledProperty
* @constructor
*
* @param {number|Packable} type The type of property.
* @param {Packable[]} [derivativeTypes] When supplied, indicates that samples will contain derivative information of the specified types.
*
*
* @example
* //Create a linearly interpolated Cartesian2
* const property = new Cesium.SampledProperty(Cesium.Cartesian2);
*
* //Populate it with data
* property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:00:00.00Z'), new Cesium.Cartesian2(0, 0));
* property.addSample(Cesium.JulianDate.fromIso8601('2012-08-02T00:00:00.00Z'), new Cesium.Cartesian2(4, 7));
*
* //Retrieve an interpolated value
* const result = property.getValue(Cesium.JulianDate.fromIso8601('2012-08-01T12:00:00.00Z'));
*
* @example
* //Create a simple numeric SampledProperty that uses third degree Hermite Polynomial Approximation
* const property = new Cesium.SampledProperty(Number);
* property.setInterpolationOptions({
* interpolationDegree : 3,
* interpolationAlgorithm : Cesium.HermitePolynomialApproximation
* });
*
* //Populate it with data
* property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:00:00.00Z'), 1.0);
* property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:01:00.00Z'), 6.0);
* property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:02:00.00Z'), 12.0);
* property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:03:30.00Z'), 5.0);
* property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:06:30.00Z'), 2.0);
*
* //Samples can be added in any order.
* property.addSample(Cesium.JulianDate.fromIso8601('2012-08-01T00:00:30.00Z'), 6.2);
*
* //Retrieve an interpolated value
* const result = property.getValue(Cesium.JulianDate.fromIso8601('2012-08-01T00:02:34.00Z'));
*
* @see SampledPositionProperty
*/
function SampledProperty(type, derivativeTypes) {
//>>includeStart('debug', pragmas.debug);
Check.defined("type", type);
//>>includeEnd('debug');
let innerType = type;
if (innerType === Number) {
innerType = PackableNumber;
}
let packedLength = innerType.packedLength;
let packedInterpolationLength =
innerType.packedInterpolationLength ?? packedLength;
let inputOrder = 0;
let innerDerivativeTypes;
if (defined(derivativeTypes)) {
const length = derivativeTypes.length;
innerDerivativeTypes = new Array(length);
for (let i = 0; i < length; i++) {
let derivativeType = derivativeTypes[i];
if (derivativeType === Number) {
derivativeType = PackableNumber;
}
const derivativePackedLength = derivativeType.packedLength;
packedLength += derivativePackedLength;
packedInterpolationLength +=
derivativeType.packedInterpolationLength ?? derivativePackedLength;
innerDerivativeTypes[i] = derivativeType;
}
inputOrder = length;
}
this._type = type;
this._innerType = innerType;
this._interpolationDegree = 1;
this._interpolationAlgorithm = LinearApproximation;
this._numberOfPoints = 0;
this._times = [];
this._values = [];
this._xTable = [];
this._yTable = [];
this._packedLength = packedLength;
this._packedInterpolationLength = packedInterpolationLength;
this._updateTableLength = true;
this._interpolationResult = new Array(packedInterpolationLength);
this._definitionChanged = new Event();
this._derivativeTypes = derivativeTypes;
this._innerDerivativeTypes = innerDerivativeTypes;
this._inputOrder = inputOrder;
this._forwardExtrapolationType = ExtrapolationType.NONE;
this._forwardExtrapolationDuration = 0;
this._backwardExtrapolationType = ExtrapolationType.NONE;
this._backwardExtrapolationDuration = 0;
}
Object.defineProperties(SampledProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof SampledProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._values.length === 0;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof SampledProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the type of property.
* @memberof SampledProperty.prototype
* @type {*}
*/
type: {
get: function () {
return this._type;
},
},
/**
* Gets the derivative types used by this property.
* @memberof SampledProperty.prototype
* @type {Packable[]}
*/
derivativeTypes: {
get: function () {
return this._derivativeTypes;
},
},
/**
* Gets the degree of interpolation to perform when retrieving a value.
* @memberof SampledProperty.prototype
* @type {number}
* @default 1
*/
interpolationDegree: {
get: function () {
return this._interpolationDegree;
},
},
/**
* Gets the interpolation algorithm to use when retrieving a value.
* @memberof SampledProperty.prototype
* @type {InterpolationAlgorithm}
* @default LinearApproximation
*/
interpolationAlgorithm: {
get: function () {
return this._interpolationAlgorithm;
},
},
/**
* Gets or sets the type of extrapolation to perform when a value
* is requested at a time after any available samples.
* @memberof SampledProperty.prototype
* @type {ExtrapolationType}
* @default ExtrapolationType.NONE
*/
forwardExtrapolationType: {
get: function () {
return this._forwardExtrapolationType;
},
set: function (value) {
if (this._forwardExtrapolationType !== value) {
this._forwardExtrapolationType = value;
this._definitionChanged.raiseEvent(this);
}
},
},
/**
* Gets or sets the amount of time to extrapolate forward before
* the property becomes undefined. A value of 0 will extrapolate forever.
* @memberof SampledProperty.prototype
* @type {number}
* @default 0
*/
forwardExtrapolationDuration: {
get: function () {
return this._forwardExtrapolationDuration;
},
set: function (value) {
if (this._forwardExtrapolationDuration !== value) {
this._forwardExtrapolationDuration = value;
this._definitionChanged.raiseEvent(this);
}
},
},
/**
* Gets or sets the type of extrapolation to perform when a value
* is requested at a time before any available samples.
* @memberof SampledProperty.prototype
* @type {ExtrapolationType}
* @default ExtrapolationType.NONE
*/
backwardExtrapolationType: {
get: function () {
return this._backwardExtrapolationType;
},
set: function (value) {
if (this._backwardExtrapolationType !== value) {
this._backwardExtrapolationType = value;
this._definitionChanged.raiseEvent(this);
}
},
},
/**
* Gets or sets the amount of time to extrapolate backward
* before the property becomes undefined. A value of 0 will extrapolate forever.
* @memberof SampledProperty.prototype
* @type {number}
* @default 0
*/
backwardExtrapolationDuration: {
get: function () {
return this._backwardExtrapolationDuration;
},
set: function (value) {
if (this._backwardExtrapolationDuration !== value) {
this._backwardExtrapolationDuration = value;
this._definitionChanged.raiseEvent(this);
}
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
SampledProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
const times = this._times;
const timesLength = times.length;
if (timesLength === 0) {
return undefined;
}
let timeout;
const innerType = this._innerType;
const values = this._values;
let index = binarySearch(times, time, JulianDate.compare);
if (index < 0) {
index = ~index;
if (index === 0) {
const startTime = times[index];
timeout = this._backwardExtrapolationDuration;
if (
this._backwardExtrapolationType === ExtrapolationType.NONE ||
(timeout !== 0 &&
JulianDate.secondsDifference(startTime, time) > timeout)
) {
return undefined;
}
if (this._backwardExtrapolationType === ExtrapolationType.HOLD) {
return innerType.unpack(values, 0, result);
}
}
if (index >= timesLength) {
index = timesLength - 1;
const endTime = times[index];
timeout = this._forwardExtrapolationDuration;
if (
this._forwardExtrapolationType === ExtrapolationType.NONE ||
(timeout !== 0 && JulianDate.secondsDifference(time, endTime) > timeout)
) {
return undefined;
}
if (this._forwardExtrapolationType === ExtrapolationType.HOLD) {
index = timesLength - 1;
return innerType.unpack(values, index * innerType.packedLength, result);
}
}
const xTable = this._xTable;
const yTable = this._yTable;
const interpolationAlgorithm = this._interpolationAlgorithm;
const packedInterpolationLength = this._packedInterpolationLength;
const inputOrder = this._inputOrder;
if (this._updateTableLength) {
this._updateTableLength = false;
const numberOfPoints = Math.min(
interpolationAlgorithm.getRequiredDataPoints(
this._interpolationDegree,
inputOrder,
),
timesLength,
);
if (numberOfPoints !== this._numberOfPoints) {
this._numberOfPoints = numberOfPoints;
xTable.length = numberOfPoints;
yTable.length = numberOfPoints * packedInterpolationLength;
}
}
const degree = this._numberOfPoints - 1;
if (degree < 1) {
return undefined;
}
let firstIndex = 0;
let lastIndex = timesLength - 1;
const pointsInCollection = lastIndex - firstIndex + 1;
if (pointsInCollection >= degree + 1) {
let computedFirstIndex = index - ((degree / 2) | 0) - 1;
if (computedFirstIndex < firstIndex) {
computedFirstIndex = firstIndex;
}
let computedLastIndex = computedFirstIndex + degree;
if (computedLastIndex > lastIndex) {
computedLastIndex = lastIndex;
computedFirstIndex = computedLastIndex - degree;
if (computedFirstIndex < firstIndex) {
computedFirstIndex = firstIndex;
}
}
firstIndex = computedFirstIndex;
lastIndex = computedLastIndex;
}
const length = lastIndex - firstIndex + 1;
// Build the tables
for (let i = 0; i < length; ++i) {
xTable[i] = JulianDate.secondsDifference(
times[firstIndex + i],
times[lastIndex],
);
}
if (!defined(innerType.convertPackedArrayForInterpolation)) {
let destinationIndex = 0;
const packedLength = this._packedLength;
let sourceIndex = firstIndex * packedLength;
const stop = (lastIndex + 1) * packedLength;
while (sourceIndex < stop) {
yTable[destinationIndex] = values[sourceIndex];
sourceIndex++;
destinationIndex++;
}
} else {
innerType.convertPackedArrayForInterpolation(
values,
firstIndex,
lastIndex,
yTable,
);
}
// Interpolate!
const x = JulianDate.secondsDifference(time, times[lastIndex]);
let interpolationResult;
if (inputOrder === 0 || !defined(interpolationAlgorithm.interpolate)) {
interpolationResult = interpolationAlgorithm.interpolateOrderZero(
x,
xTable,
yTable,
packedInterpolationLength,
this._interpolationResult,
);
} else {
const yStride = Math.floor(packedInterpolationLength / (inputOrder + 1));
interpolationResult = interpolationAlgorithm.interpolate(
x,
xTable,
yTable,
yStride,
inputOrder,
inputOrder,
this._interpolationResult,
);
}
if (!defined(innerType.unpackInterpolationResult)) {
return innerType.unpack(interpolationResult, 0, result);
}
return innerType.unpackInterpolationResult(
interpolationResult,
values,
firstIndex,
lastIndex,
result,
);
}
return innerType.unpack(values, index * this._packedLength, result);
};
/**
* Sets the algorithm and degree to use when interpolating a value.
*
* @param {object} [options] Object with the following properties:
* @param {InterpolationAlgorithm} [options.interpolationAlgorithm] The new interpolation algorithm. If undefined, the existing property will be unchanged.
* @param {number} [options.interpolationDegree] The new interpolation degree. If undefined, the existing property will be unchanged.
*/
SampledProperty.prototype.setInterpolationOptions = function (options) {
if (!defined(options)) {
return;
}
let valuesChanged = false;
const interpolationAlgorithm = options.interpolationAlgorithm;
const interpolationDegree = options.interpolationDegree;
if (
defined(interpolationAlgorithm) &&
this._interpolationAlgorithm !== interpolationAlgorithm
) {
this._interpolationAlgorithm = interpolationAlgorithm;
valuesChanged = true;
}
if (
defined(interpolationDegree) &&
this._interpolationDegree !== interpolationDegree
) {
this._interpolationDegree = interpolationDegree;
valuesChanged = true;
}
if (valuesChanged) {
this._updateTableLength = true;
this._definitionChanged.raiseEvent(this);
}
};
/**
* Adds a new sample.
*
* @param {JulianDate} time The sample time.
* @param {Packable} value The value at the provided time.
* @param {Packable[]} [derivatives] The array of derivatives at the provided time.
*/
SampledProperty.prototype.addSample = function (time, value, derivatives) {
const innerDerivativeTypes = this._innerDerivativeTypes;
const hasDerivatives = defined(innerDerivativeTypes);
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
Check.defined("value", value);
if (hasDerivatives) {
Check.defined("derivatives", derivatives);
}
//>>includeEnd('debug');
const innerType = this._innerType;
const data = [];
data.push(time);
innerType.pack(value, data, data.length);
if (hasDerivatives) {
const derivativesLength = innerDerivativeTypes.length;
for (let x = 0; x < derivativesLength; x++) {
innerDerivativeTypes[x].pack(derivatives[x], data, data.length);
}
}
mergeNewSamples(
undefined,
this._times,
this._values,
data,
this._packedLength,
);
this._updateTableLength = true;
this._definitionChanged.raiseEvent(this);
};
/**
* Adds an array of samples.
*
* @param {JulianDate[]} times An array of JulianDate instances where each index is a sample time.
* @param {Packable[]} values The array of values, where each value corresponds to the provided times index.
* @param {Array[]} [derivativeValues] An array where each item is the array of derivatives at the equivalent time index.
*
* @exception {DeveloperError} times and values must be the same length.
* @exception {DeveloperError} times and derivativeValues must be the same length.
*/
SampledProperty.prototype.addSamples = function (
times,
values,
derivativeValues,
) {
const innerDerivativeTypes = this._innerDerivativeTypes;
const hasDerivatives = defined(innerDerivativeTypes);
//>>includeStart('debug', pragmas.debug);
Check.defined("times", times);
Check.defined("values", values);
if (times.length !== values.length) {
throw new DeveloperError("times and values must be the same length.");
}
if (
hasDerivatives &&
(!defined(derivativeValues) || derivativeValues.length !== times.length)
) {
throw new DeveloperError(
"times and derivativeValues must be the same length.",
);
}
//>>includeEnd('debug');
const innerType = this._innerType;
const length = times.length;
const data = [];
for (let i = 0; i < length; i++) {
data.push(times[i]);
innerType.pack(values[i], data, data.length);
if (hasDerivatives) {
const derivatives = derivativeValues[i];
const derivativesLength = innerDerivativeTypes.length;
for (let x = 0; x < derivativesLength; x++) {
innerDerivativeTypes[x].pack(derivatives[x], data, data.length);
}
}
}
mergeNewSamples(
undefined,
this._times,
this._values,
data,
this._packedLength,
);
this._updateTableLength = true;
this._definitionChanged.raiseEvent(this);
};
/**
* Retrieves the time of the provided sample associated with the index. A negative index accesses the list of samples in reverse order.
*
* @param {number} index The index of samples list.
* @returns {JulianDate | undefined} The JulianDate time of the sample, or undefined if failed.
*/
SampledProperty.prototype.getSample = function (index) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.number("index", index);
//>>includeEnd('debug');
const times = this._times;
const len = times.length;
if (!defined(len)) {
return undefined;
}
if (index < 0) {
index += len;
}
return times[index];
};
/**
* Adds samples as a single packed array where each new sample is represented as a date,
* followed by the packed representation of the corresponding value and derivatives.
*
* @param {number[]} packedSamples The array of packed samples.
* @param {JulianDate} [epoch] If any of the dates in packedSamples are numbers, they are considered an offset from this epoch, in seconds.
*/
SampledProperty.prototype.addSamplesPackedArray = function (
packedSamples,
epoch,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("packedSamples", packedSamples);
//>>includeEnd('debug');
mergeNewSamples(
epoch,
this._times,
this._values,
packedSamples,
this._packedLength,
);
this._updateTableLength = true;
this._definitionChanged.raiseEvent(this);
};
/**
* Removes a sample at the given time, if present.
*
* @param {JulianDate} time The sample time.
* @returns {boolean} <code>true</code> if a sample at time was removed, <code>false</code> otherwise.
*/
SampledProperty.prototype.removeSample = function (time) {
//>>includeStart('debug', pragmas.debug);
Check.defined("time", time);
//>>includeEnd('debug');
const index = binarySearch(this._times, time, JulianDate.compare);
if (index < 0) {
return false;
}
removeSamples(this, index, 1);
return true;
};
function removeSamples(property, startIndex, numberToRemove) {
const packedLength = property._packedLength;
property._times.splice(startIndex, numberToRemove);
property._values.splice(
startIndex * packedLength,
numberToRemove * packedLength,
);
property._updateTableLength = true;
property._definitionChanged.raiseEvent(property);
}
/**
* Removes all samples for the given time interval.
*
* @param {TimeInterval} time The time interval for which to remove all samples.
*/
SampledProperty.prototype.removeSamples = function (timeInterval) {
//>>includeStart('debug', pragmas.debug);
Check.defined("timeInterval", timeInterval);
//>>includeEnd('debug');
const times = this._times;
let startIndex = binarySearch(times, timeInterval.start, JulianDate.compare);
if (startIndex < 0) {
startIndex = ~startIndex;
} else if (!timeInterval.isStartIncluded) {
++startIndex;
}
let stopIndex = binarySearch(times, timeInterval.stop, JulianDate.compare);
if (stopIndex < 0) {
stopIndex = ~stopIndex;
} else if (timeInterval.isStopIncluded) {
++stopIndex;
}
removeSamples(this, startIndex, stopIndex - startIndex);
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
SampledProperty.prototype.equals = function (other) {
if (this === other) {
return true;
}
if (!defined(other)) {
return false;
}
if (
this._type !== other._type || //
this._interpolationDegree !== other._interpolationDegree || //
this._interpolationAlgorithm !== other._interpolationAlgorithm
) {
return false;
}
const derivativeTypes = this._derivativeTypes;
const hasDerivatives = defined(derivativeTypes);
const otherDerivativeTypes = other._derivativeTypes;
const otherHasDerivatives = defined(otherDerivativeTypes);
if (hasDerivatives !== otherHasDerivatives) {
return false;
}
let i;
let length;
if (hasDerivatives) {
length = derivativeTypes.length;
if (length !== otherDerivativeTypes.length) {
return false;
}
for (i = 0; i < length; i++) {
if (derivativeTypes[i] !== otherDerivativeTypes[i]) {
return false;
}
}
}
const times = this._times;
const otherTimes = other._times;
length = times.length;
if (length !== otherTimes.length) {
return false;
}
for (i = 0; i < length; i++) {
if (!JulianDate.equals(times[i], otherTimes[i])) {
return false;
}
}
const values = this._values;
const otherValues = other._values;
length = values.length;
//Since time lengths are equal, values length and other length are guaranteed to be equal.
for (i = 0; i < length; i++) {
if (values[i] !== otherValues[i]) {
return false;
}
}
return true;
};
//Exposed for testing.
SampledProperty._mergeNewSamples = mergeNewSamples;
export default SampledProperty;
@@ -0,0 +1,103 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import ReferenceFrame from "../Core/ReferenceFrame.js";
import Property from "./Property.js";
/**
* This is a temporary class for scaling position properties to the ellipsoid surface.
* It will go away or be refactored to support data with arbitrary height references.
* @private
*/
function ScaledPositionProperty(value) {
this._definitionChanged = new Event();
this._value = undefined;
this._removeSubscription = undefined;
this.setValue(value);
}
Object.defineProperties(ScaledPositionProperty.prototype, {
isConstant: {
get: function () {
return Property.isConstant(this._value);
},
},
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
referenceFrame: {
get: function () {
return defined(this._value)
? this._value.referenceFrame
: ReferenceFrame.FIXED;
},
},
});
const timeScratch = new JulianDate();
ScaledPositionProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return this.getValueInReferenceFrame(time, ReferenceFrame.FIXED, result);
};
ScaledPositionProperty.prototype.setValue = function (value) {
if (this._value !== value) {
this._value = value;
if (defined(this._removeSubscription)) {
this._removeSubscription();
this._removeSubscription = undefined;
}
if (defined(value)) {
this._removeSubscription = value.definitionChanged.addEventListener(
this._raiseDefinitionChanged,
this,
);
}
this._definitionChanged.raiseEvent(this);
}
};
ScaledPositionProperty.prototype.getValueInReferenceFrame = function (
time,
referenceFrame,
result,
) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
if (!defined(referenceFrame)) {
throw new DeveloperError("referenceFrame is required.");
}
//>>includeEnd('debug');
if (!defined(this._value)) {
return undefined;
}
result = this._value.getValueInReferenceFrame(time, referenceFrame, result);
return defined(result)
? Ellipsoid.default.scaleToGeodeticSurface(result, result)
: undefined;
};
ScaledPositionProperty.prototype.equals = function (other) {
return (
this === other ||
(other instanceof ScaledPositionProperty && this._value === other._value)
);
};
ScaledPositionProperty.prototype._raiseDefinitionChanged = function () {
this._definitionChanged.raiseEvent(this);
};
export default ScaledPositionProperty;
@@ -0,0 +1,575 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import Primitive from "../Scene/Primitive.js";
import BoundingSphereState from "./BoundingSphereState.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import MaterialProperty from "./MaterialProperty.js";
import Property from "./Property.js";
const colorScratch = new Color();
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
const defaultDistanceDisplayCondition = new DistanceDisplayCondition();
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
function Batch(
primitives,
translucent,
appearanceType,
depthFailAppearanceType,
depthFailMaterialProperty,
closed,
shadows,
) {
this.translucent = translucent;
this.appearanceType = appearanceType;
this.depthFailAppearanceType = depthFailAppearanceType;
this.depthFailMaterialProperty = depthFailMaterialProperty;
this.depthFailMaterial = undefined;
this.closed = closed;
this.shadows = shadows;
this.primitives = primitives;
this.createPrimitive = false;
this.waitingOnCreate = false;
this.primitive = undefined;
this.oldPrimitive = undefined;
this.geometry = new AssociativeArray();
this.updaters = new AssociativeArray();
this.updatersWithAttributes = new AssociativeArray();
this.attributes = new AssociativeArray();
this.subscriptions = new AssociativeArray();
this.showsUpdated = new AssociativeArray();
this.itemsToRemove = [];
this.invalidated = false;
let removeMaterialSubscription;
if (defined(depthFailMaterialProperty)) {
removeMaterialSubscription =
depthFailMaterialProperty.definitionChanged.addEventListener(
Batch.prototype.onMaterialChanged,
this,
);
}
this.removeMaterialSubscription = removeMaterialSubscription;
}
Batch.prototype.onMaterialChanged = function () {
this.invalidated = true;
};
Batch.prototype.isMaterial = function (updater) {
const material = this.depthFailMaterialProperty;
const updaterMaterial = updater.depthFailMaterialProperty;
if (updaterMaterial === material) {
return true;
}
if (defined(material)) {
return material.equals(updaterMaterial);
}
return false;
};
Batch.prototype.add = function (updater, instance) {
const id = updater.id;
this.createPrimitive = true;
this.geometry.set(id, instance);
this.updaters.set(id, updater);
if (
!updater.hasConstantFill ||
!updater.fillMaterialProperty.isConstant ||
!Property.isConstant(updater.distanceDisplayConditionProperty) ||
!Property.isConstant(updater.terrainOffsetProperty)
) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(
function (entity, propertyName, newValue, oldValue) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
},
),
);
}
};
Batch.prototype.remove = function (updater) {
const id = updater.id;
this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
if (this.updaters.remove(id)) {
this.updatersWithAttributes.remove(id);
const unsubscribe = this.subscriptions.get(id);
if (defined(unsubscribe)) {
unsubscribe();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
Batch.prototype.update = function (time) {
let isUpdated = true;
let removedCount = 0;
let primitive = this.primitive;
const primitives = this.primitives;
let i;
if (this.createPrimitive) {
const geometries = this.geometry.values;
const geometriesLength = geometries.length;
if (geometriesLength > 0) {
if (defined(primitive)) {
if (!defined(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
let depthFailAppearance;
if (defined(this.depthFailAppearanceType)) {
if (defined(this.depthFailMaterialProperty)) {
this.depthFailMaterial = MaterialProperty.getValue(
time,
this.depthFailMaterialProperty,
this.depthFailMaterial,
);
}
const DepthFailAppearanceType = this.depthFailAppearanceType;
depthFailAppearance = new DepthFailAppearanceType({
material: this.depthFailMaterial,
translucent: this.translucent,
closed: this.closed,
});
}
const AppearanceType = this.appearanceType;
primitive = new Primitive({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
appearance: new AppearanceType({
translucent: this.translucent,
closed: this.closed,
}),
depthFailAppearance: depthFailAppearance,
shadows: this.shadows,
});
primitives.add(primitive);
isUpdated = false;
} else {
if (defined(primitive)) {
primitives.remove(primitive);
primitive = undefined;
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
this.waitingOnCreate = true;
} else if (defined(primitive) && primitive.ready) {
primitive.show = true;
if (defined(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = undefined;
}
if (
defined(this.depthFailAppearanceType) &&
!(this.depthFailMaterialProperty instanceof ColorMaterialProperty)
) {
this.depthFailMaterial = MaterialProperty.getValue(
time,
this.depthFailMaterialProperty,
this.depthFailMaterial,
);
this.primitive.depthFailAppearance.material = this.depthFailMaterial;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length = updatersWithAttributes.length;
const waitingOnCreate = this.waitingOnCreate;
for (i = 0; i < length; i++) {
const updater = updatersWithAttributes[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
if (!updater.fillMaterialProperty.isConstant || waitingOnCreate) {
const colorProperty = updater.fillMaterialProperty.color;
const resultColor = Property.getValueOrDefault(
colorProperty,
time,
Color.WHITE,
colorScratch,
);
if (!Color.equals(attributes._lastColor, resultColor)) {
attributes._lastColor = Color.clone(
resultColor,
attributes._lastColor,
);
attributes.color = ColorGeometryInstanceAttribute.toValue(
resultColor,
attributes.color,
);
if (
(this.translucent && attributes.color[3] === 255) ||
(!this.translucent && attributes.color[3] !== 255)
) {
this.itemsToRemove[removedCount++] = updater;
}
}
}
if (
defined(this.depthFailAppearanceType) &&
updater.depthFailMaterialProperty instanceof ColorMaterialProperty &&
(!updater.depthFailMaterialProperty.isConstant || waitingOnCreate)
) {
const depthFailColorProperty = updater.depthFailMaterialProperty.color;
const depthColor = Property.getValueOrDefault(
depthFailColorProperty,
time,
Color.WHITE,
colorScratch,
);
if (!Color.equals(attributes._lastDepthFailColor, depthColor)) {
attributes._lastDepthFailColor = Color.clone(
depthColor,
attributes._lastDepthFailColor,
);
attributes.depthFailColor = ColorGeometryInstanceAttribute.toValue(
depthColor,
attributes.depthFailColor,
);
}
}
const show =
updater.entity.isShowing &&
(updater.hasConstantFill || updater.isFilled(time));
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
}
const distanceDisplayConditionProperty =
updater.distanceDisplayConditionProperty;
if (!Property.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition,
distanceDisplayConditionScratch,
);
if (
!DistanceDisplayCondition.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
)
) {
attributes._lastDistanceDisplayCondition =
DistanceDisplayCondition.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
);
attributes.distanceDisplayCondition =
DistanceDisplayConditionGeometryInstanceAttribute.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition,
);
}
}
const offsetProperty = updater.terrainOffsetProperty;
if (!Property.isConstant(offsetProperty)) {
const offset = Property.getValueOrDefault(
offsetProperty,
time,
defaultOffset,
offsetScratch,
);
if (!Cartesian3.equals(offset, attributes._lastOffset)) {
attributes._lastOffset = Cartesian3.clone(
offset,
attributes._lastOffset,
);
attributes.offset = OffsetGeometryInstanceAttribute.toValue(
offset,
attributes.offset,
);
}
}
}
this.updateShows(primitive);
this.waitingOnCreate = false;
} else if (defined(primitive) && !primitive.ready) {
isUpdated = false;
}
this.itemsToRemove.length = removedCount;
return isUpdated;
};
Batch.prototype.updateShows = function (primitive) {
const showsUpdated = this.showsUpdated.values;
const length = showsUpdated.length;
for (let i = 0; i < length; i++) {
const updater = showsUpdated[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
const show = updater.entity.isShowing;
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch.prototype.contains = function (updater) {
return this.updaters.contains(updater.id);
};
Batch.prototype.getBoundingSphere = function (updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (
!defined(attributes) ||
!defined(attributes.boundingSphere) || //
(defined(attributes.show) && attributes.show[0] === 0)
) {
return BoundingSphereState.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState.DONE;
};
Batch.prototype.destroy = function () {
const primitive = this.primitive;
const primitives = this.primitives;
if (defined(primitive)) {
primitives.remove(primitive);
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
}
if (defined(this.removeMaterialSubscription)) {
this.removeMaterialSubscription();
}
};
/**
* @private
*/
function StaticGeometryColorBatch(
primitives,
appearanceType,
depthFailAppearanceType,
closed,
shadows,
) {
this._solidItems = [];
this._translucentItems = [];
this._primitives = primitives;
this._appearanceType = appearanceType;
this._depthFailAppearanceType = depthFailAppearanceType;
this._closed = closed;
this._shadows = shadows;
}
StaticGeometryColorBatch.prototype.add = function (time, updater) {
let items;
let translucent;
const instance = updater.createFillGeometryInstance(time);
if (instance.attributes.color.value[3] === 255) {
items = this._solidItems;
translucent = false;
} else {
items = this._translucentItems;
translucent = true;
}
const length = items.length;
for (let i = 0; i < length; i++) {
const item = items[i];
if (item.isMaterial(updater)) {
item.add(updater, instance);
return;
}
}
const batch = new Batch(
this._primitives,
translucent,
this._appearanceType,
this._depthFailAppearanceType,
updater.depthFailMaterialProperty,
this._closed,
this._shadows,
);
batch.add(updater, instance);
items.push(batch);
};
function removeItem(items, updater) {
const length = items.length;
for (let i = length - 1; i >= 0; i--) {
const item = items[i];
if (item.remove(updater)) {
if (item.updaters.length === 0) {
items.splice(i, 1);
item.destroy();
}
return true;
}
}
return false;
}
StaticGeometryColorBatch.prototype.remove = function (updater) {
if (!removeItem(this._solidItems, updater)) {
removeItem(this._translucentItems, updater);
}
};
function moveItems(batch, items, time) {
let itemsMoved = false;
const length = items.length;
for (let i = 0; i < length; ++i) {
const item = items[i];
const itemsToRemove = item.itemsToRemove;
const itemsToMoveLength = itemsToRemove.length;
if (itemsToMoveLength > 0) {
for (i = 0; i < itemsToMoveLength; i++) {
const updater = itemsToRemove[i];
item.remove(updater);
batch.add(time, updater);
itemsMoved = true;
}
}
}
return itemsMoved;
}
function updateItems(batch, items, time, isUpdated) {
let length = items.length;
let i;
for (i = length - 1; i >= 0; i--) {
const item = items[i];
if (item.invalidated) {
items.splice(i, 1);
const updaters = item.updaters.values;
const updatersLength = updaters.length;
for (let h = 0; h < updatersLength; h++) {
batch.add(time, updaters[h]);
}
item.destroy();
}
}
length = items.length;
for (i = 0; i < length; ++i) {
isUpdated = items[i].update(time) && isUpdated;
}
return isUpdated;
}
StaticGeometryColorBatch.prototype.update = function (time) {
//Perform initial update
let isUpdated = updateItems(this, this._solidItems, time, true);
isUpdated =
updateItems(this, this._translucentItems, time, isUpdated) && isUpdated;
//If any items swapped between solid/translucent, we need to
//move them between batches
const solidsMoved = moveItems(this, this._solidItems, time);
const translucentsMoved = moveItems(this, this._translucentItems, time);
//If we moved anything around, we need to re-build the primitive
if (solidsMoved || translucentsMoved) {
isUpdated =
updateItems(this, this._solidItems, time, isUpdated) && isUpdated;
isUpdated =
updateItems(this, this._translucentItems, time, isUpdated) && isUpdated;
}
return isUpdated;
};
function getBoundingSphere(items, updater, result) {
const length = items.length;
for (let i = 0; i < length; i++) {
const item = items[i];
if (item.contains(updater)) {
return item.getBoundingSphere(updater, result);
}
}
return BoundingSphereState.FAILED;
}
StaticGeometryColorBatch.prototype.getBoundingSphere = function (
updater,
result,
) {
const boundingSphere = getBoundingSphere(this._solidItems, updater, result);
if (boundingSphere === BoundingSphereState.FAILED) {
return getBoundingSphere(this._translucentItems, updater, result);
}
return boundingSphere;
};
function removeAllPrimitives(items) {
const length = items.length;
for (let i = 0; i < length; i++) {
items[i].destroy();
}
items.length = 0;
}
StaticGeometryColorBatch.prototype.removeAllPrimitives = function () {
removeAllPrimitives(this._solidItems);
removeAllPrimitives(this._translucentItems);
};
export default StaticGeometryColorBatch;
@@ -0,0 +1,493 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import Primitive from "../Scene/Primitive.js";
import BoundingSphereState from "./BoundingSphereState.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import MaterialProperty from "./MaterialProperty.js";
import Property from "./Property.js";
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
const defaultDistanceDisplayCondition = new DistanceDisplayCondition();
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
function Batch(
primitives,
appearanceType,
materialProperty,
depthFailAppearanceType,
depthFailMaterialProperty,
closed,
shadows,
) {
this.primitives = primitives;
this.appearanceType = appearanceType;
this.materialProperty = materialProperty;
this.depthFailAppearanceType = depthFailAppearanceType;
this.depthFailMaterialProperty = depthFailMaterialProperty;
this.closed = closed;
this.shadows = shadows;
this.updaters = new AssociativeArray();
this.createPrimitive = true;
this.primitive = undefined;
this.oldPrimitive = undefined;
this.geometry = new AssociativeArray();
this.material = undefined;
this.depthFailMaterial = undefined;
this.updatersWithAttributes = new AssociativeArray();
this.attributes = new AssociativeArray();
this.invalidated = false;
this.removeMaterialSubscription =
materialProperty.definitionChanged.addEventListener(
Batch.prototype.onMaterialChanged,
this,
);
this.subscriptions = new AssociativeArray();
this.showsUpdated = new AssociativeArray();
}
Batch.prototype.onMaterialChanged = function () {
this.invalidated = true;
};
Batch.prototype.isMaterial = function (updater) {
const material = this.materialProperty;
const updaterMaterial = updater.fillMaterialProperty;
const depthFailMaterial = this.depthFailMaterialProperty;
const updaterDepthFailMaterial = updater.depthFailMaterialProperty;
if (
updaterMaterial === material &&
updaterDepthFailMaterial === depthFailMaterial
) {
return true;
}
let equals = defined(material) && material.equals(updaterMaterial);
equals =
((!defined(depthFailMaterial) && !defined(updaterDepthFailMaterial)) ||
(defined(depthFailMaterial) &&
depthFailMaterial.equals(updaterDepthFailMaterial))) &&
equals;
return equals;
};
Batch.prototype.add = function (time, updater) {
const id = updater.id;
this.updaters.set(id, updater);
this.geometry.set(id, updater.createFillGeometryInstance(time));
if (
!updater.hasConstantFill ||
!updater.fillMaterialProperty.isConstant ||
!Property.isConstant(updater.distanceDisplayConditionProperty) ||
!Property.isConstant(updater.terrainOffsetProperty)
) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(
function (entity, propertyName, newValue, oldValue) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
},
),
);
}
this.createPrimitive = true;
};
Batch.prototype.remove = function (updater) {
const id = updater.id;
this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
if (this.updaters.remove(id)) {
this.updatersWithAttributes.remove(id);
const unsubscribe = this.subscriptions.get(id);
if (defined(unsubscribe)) {
unsubscribe();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
const colorScratch = new Color();
Batch.prototype.update = function (time) {
let isUpdated = true;
let primitive = this.primitive;
const primitives = this.primitives;
const geometries = this.geometry.values;
let i;
if (this.createPrimitive) {
const geometriesLength = geometries.length;
if (geometriesLength > 0) {
if (defined(primitive)) {
if (!defined(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
this.material = MaterialProperty.getValue(
time,
this.materialProperty,
this.material,
);
let depthFailAppearance;
if (defined(this.depthFailMaterialProperty)) {
this.depthFailMaterial = MaterialProperty.getValue(
time,
this.depthFailMaterialProperty,
this.depthFailMaterial,
);
const DepthFailAppearanceType = this.depthFailAppearanceType;
depthFailAppearance = new DepthFailAppearanceType({
material: this.depthFailMaterial,
translucent: this.depthFailMaterial.isTranslucent(),
closed: this.closed,
});
}
const AppearanceType = this.appearanceType;
primitive = new Primitive({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
appearance: new AppearanceType({
material: this.material,
translucent: this.material.isTranslucent(),
closed: this.closed,
}),
depthFailAppearance: depthFailAppearance,
shadows: this.shadows,
});
primitives.add(primitive);
isUpdated = false;
} else {
if (defined(primitive)) {
primitives.remove(primitive);
primitive = undefined;
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
} else if (defined(primitive) && primitive.ready) {
primitive.show = true;
if (defined(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = undefined;
}
this.material = MaterialProperty.getValue(
time,
this.materialProperty,
this.material,
);
this.primitive.appearance.material = this.material;
if (
defined(this.depthFailAppearanceType) &&
!(this.depthFailMaterialProperty instanceof ColorMaterialProperty)
) {
this.depthFailMaterial = MaterialProperty.getValue(
time,
this.depthFailMaterialProperty,
this.depthFailMaterial,
);
this.primitive.depthFailAppearance.material = this.depthFailMaterial;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length = updatersWithAttributes.length;
for (i = 0; i < length; i++) {
const updater = updatersWithAttributes[i];
const entity = updater.entity;
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
if (
defined(this.depthFailAppearanceType) &&
this.depthFailMaterialProperty instanceof ColorMaterialProperty &&
!updater.depthFailMaterialProperty.isConstant
) {
const depthFailColorProperty = updater.depthFailMaterialProperty.color;
const depthFailColor = Property.getValueOrDefault(
depthFailColorProperty,
time,
Color.WHITE,
colorScratch,
);
if (!Color.equals(attributes._lastDepthFailColor, depthFailColor)) {
attributes._lastDepthFailColor = Color.clone(
depthFailColor,
attributes._lastDepthFailColor,
);
attributes.depthFailColor = ColorGeometryInstanceAttribute.toValue(
depthFailColor,
attributes.depthFailColor,
);
}
}
const show =
entity.isShowing && (updater.hasConstantFill || updater.isFilled(time));
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
}
const distanceDisplayConditionProperty =
updater.distanceDisplayConditionProperty;
if (!Property.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition,
distanceDisplayConditionScratch,
);
if (
!DistanceDisplayCondition.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
)
) {
attributes._lastDistanceDisplayCondition =
DistanceDisplayCondition.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
);
attributes.distanceDisplayCondition =
DistanceDisplayConditionGeometryInstanceAttribute.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition,
);
}
}
const offsetProperty = updater.terrainOffsetProperty;
if (!Property.isConstant(offsetProperty)) {
const offset = Property.getValueOrDefault(
offsetProperty,
time,
defaultOffset,
offsetScratch,
);
if (!Cartesian3.equals(offset, attributes._lastOffset)) {
attributes._lastOffset = Cartesian3.clone(
offset,
attributes._lastOffset,
);
attributes.offset = OffsetGeometryInstanceAttribute.toValue(
offset,
attributes.offset,
);
}
}
}
this.updateShows(primitive);
} else if (defined(primitive) && !primitive.ready) {
isUpdated = false;
}
return isUpdated;
};
Batch.prototype.updateShows = function (primitive) {
const showsUpdated = this.showsUpdated.values;
const length = showsUpdated.length;
for (let i = 0; i < length; i++) {
const updater = showsUpdated[i];
const entity = updater.entity;
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
const show = entity.isShowing;
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch.prototype.contains = function (updater) {
return this.updaters.contains(updater.id);
};
Batch.prototype.getBoundingSphere = function (updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (
!defined(attributes) ||
!defined(attributes.boundingSphere) ||
(defined(attributes.show) && attributes.show[0] === 0)
) {
return BoundingSphereState.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState.DONE;
};
Batch.prototype.destroy = function () {
const primitive = this.primitive;
const primitives = this.primitives;
if (defined(primitive)) {
primitives.remove(primitive);
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
}
this.removeMaterialSubscription();
};
/**
* @private
*/
function StaticGeometryPerMaterialBatch(
primitives,
appearanceType,
depthFailAppearanceType,
closed,
shadows,
) {
this._items = [];
this._primitives = primitives;
this._appearanceType = appearanceType;
this._depthFailAppearanceType = depthFailAppearanceType;
this._closed = closed;
this._shadows = shadows;
}
StaticGeometryPerMaterialBatch.prototype.add = function (time, updater) {
const items = this._items;
const length = items.length;
for (let i = 0; i < length; i++) {
const item = items[i];
if (item.isMaterial(updater)) {
item.add(time, updater);
return;
}
}
const batch = new Batch(
this._primitives,
this._appearanceType,
updater.fillMaterialProperty,
this._depthFailAppearanceType,
updater.depthFailMaterialProperty,
this._closed,
this._shadows,
);
batch.add(time, updater);
items.push(batch);
};
StaticGeometryPerMaterialBatch.prototype.remove = function (updater) {
const items = this._items;
const length = items.length;
for (let i = length - 1; i >= 0; i--) {
const item = items[i];
if (item.remove(updater)) {
if (item.updaters.length === 0) {
items.splice(i, 1);
item.destroy();
}
break;
}
}
};
StaticGeometryPerMaterialBatch.prototype.update = function (time) {
let i;
const items = this._items;
const length = items.length;
for (i = length - 1; i >= 0; i--) {
const item = items[i];
if (item.invalidated) {
items.splice(i, 1);
const updaters = item.updaters.values;
const updatersLength = updaters.length;
for (let h = 0; h < updatersLength; h++) {
this.add(time, updaters[h]);
}
item.destroy();
}
}
let isUpdated = true;
for (i = 0; i < items.length; i++) {
isUpdated = items[i].update(time) && isUpdated;
}
return isUpdated;
};
StaticGeometryPerMaterialBatch.prototype.getBoundingSphere = function (
updater,
result,
) {
const items = this._items;
const length = items.length;
for (let i = 0; i < length; i++) {
const item = items[i];
if (item.contains(updater)) {
return item.getBoundingSphere(updater, result);
}
}
return BoundingSphereState.FAILED;
};
StaticGeometryPerMaterialBatch.prototype.removeAllPrimitives = function () {
const items = this._items;
const length = items.length;
for (let i = 0; i < length; i++) {
items[i].destroy();
}
this._items.length = 0;
};
export default StaticGeometryPerMaterialBatch;
@@ -0,0 +1,394 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import GroundPrimitive from "../Scene/GroundPrimitive.js";
import BoundingSphereState from "./BoundingSphereState.js";
import Property from "./Property.js";
import RectangleCollisionChecker from "../Core/RectangleCollisionChecker.js";
const colorScratch = new Color();
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
const defaultDistanceDisplayCondition = new DistanceDisplayCondition();
function Batch(primitives, classificationType, color, zIndex) {
this.primitives = primitives;
this.zIndex = zIndex;
this.classificationType = classificationType;
this.color = color;
this.createPrimitive = false;
this.waitingOnCreate = false;
this.primitive = undefined;
this.oldPrimitive = undefined;
this.geometry = new AssociativeArray();
this.updaters = new AssociativeArray();
this.updatersWithAttributes = new AssociativeArray();
this.attributes = new AssociativeArray();
this.subscriptions = new AssociativeArray();
this.showsUpdated = new AssociativeArray();
this.itemsToRemove = [];
this.isDirty = false;
this.rectangleCollisionCheck = new RectangleCollisionChecker();
}
Batch.prototype.overlapping = function (rectangle) {
return this.rectangleCollisionCheck.collides(rectangle);
};
Batch.prototype.add = function (updater, instance) {
const id = updater.id;
this.createPrimitive = true;
this.geometry.set(id, instance);
this.updaters.set(id, updater);
this.rectangleCollisionCheck.insert(id, instance.geometry.rectangle);
if (
!updater.hasConstantFill ||
!updater.fillMaterialProperty.isConstant ||
!Property.isConstant(updater.distanceDisplayConditionProperty)
) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(
function (entity, propertyName, newValue, oldValue) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
},
),
);
}
};
Batch.prototype.remove = function (updater) {
const id = updater.id;
const geometryInstance = this.geometry.get(id);
this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
if (this.updaters.remove(id)) {
this.rectangleCollisionCheck.remove(
id,
geometryInstance.geometry.rectangle,
);
this.updatersWithAttributes.remove(id);
const unsubscribe = this.subscriptions.get(id);
if (defined(unsubscribe)) {
unsubscribe();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
Batch.prototype.update = function (time) {
let isUpdated = true;
const removedCount = 0;
let primitive = this.primitive;
const primitives = this.primitives;
let i;
if (this.createPrimitive) {
const geometries = this.geometry.values;
const geometriesLength = geometries.length;
if (geometriesLength > 0) {
if (defined(primitive)) {
if (!defined(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
primitive = new GroundPrimitive({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
classificationType: this.classificationType,
});
primitives.add(primitive, this.zIndex);
isUpdated = false;
} else {
if (defined(primitive)) {
primitives.remove(primitive);
primitive = undefined;
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
this.waitingOnCreate = true;
} else if (defined(primitive) && primitive.ready) {
primitive.show = true;
if (defined(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = undefined;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length = updatersWithAttributes.length;
const waitingOnCreate = this.waitingOnCreate;
for (i = 0; i < length; i++) {
const updater = updatersWithAttributes[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
if (!updater.fillMaterialProperty.isConstant || waitingOnCreate) {
const colorProperty = updater.fillMaterialProperty.color;
const fillColor = Property.getValueOrDefault(
colorProperty,
time,
Color.WHITE,
colorScratch,
);
if (!Color.equals(attributes._lastColor, fillColor)) {
attributes._lastColor = Color.clone(fillColor, attributes._lastColor);
attributes.color = ColorGeometryInstanceAttribute.toValue(
fillColor,
attributes.color,
);
}
}
const show =
updater.entity.isShowing &&
(updater.hasConstantFill || updater.isFilled(time));
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
}
const distanceDisplayConditionProperty =
updater.distanceDisplayConditionProperty;
if (!Property.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition,
distanceDisplayConditionScratch,
);
if (
!DistanceDisplayCondition.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
)
) {
attributes._lastDistanceDisplayCondition =
DistanceDisplayCondition.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
);
attributes.distanceDisplayCondition =
DistanceDisplayConditionGeometryInstanceAttribute.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition,
);
}
}
}
this.updateShows(primitive);
this.waitingOnCreate = false;
} else if (defined(primitive) && !primitive.ready) {
isUpdated = false;
}
this.itemsToRemove.length = removedCount;
return isUpdated;
};
Batch.prototype.updateShows = function (primitive) {
const showsUpdated = this.showsUpdated.values;
const length = showsUpdated.length;
for (let i = 0; i < length; i++) {
const updater = showsUpdated[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
const show = updater.entity.isShowing;
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch.prototype.contains = function (updater) {
return this.updaters.contains(updater.id);
};
Batch.prototype.getBoundingSphere = function (updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState.PENDING;
}
const bs = primitive.getBoundingSphere(updater.entity);
if (!defined(bs)) {
return BoundingSphereState.FAILED;
}
bs.clone(result);
return BoundingSphereState.DONE;
};
Batch.prototype.removeAllPrimitives = function () {
const primitives = this.primitives;
const primitive = this.primitive;
if (defined(primitive)) {
primitives.remove(primitive);
this.primitive = undefined;
this.geometry.removeAll();
this.updaters.removeAll();
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
};
/**
* @private
*/
function StaticGroundGeometryColorBatch(primitives, classificationType) {
this._batches = [];
this._primitives = primitives;
this._classificationType = classificationType;
}
StaticGroundGeometryColorBatch.prototype.add = function (time, updater) {
const instance = updater.createFillGeometryInstance(time);
const batches = this._batches;
const zIndex = Property.getValueOrDefault(updater.zIndex, 0);
let batch;
const length = batches.length;
for (let i = 0; i < length; ++i) {
const item = batches[i];
if (
item.zIndex === zIndex &&
!item.overlapping(instance.geometry.rectangle)
) {
batch = item;
break;
}
}
if (!defined(batch)) {
batch = new Batch(
this._primitives,
this._classificationType,
instance.attributes.color.value,
zIndex,
);
batches.push(batch);
}
batch.add(updater, instance);
return batch;
};
StaticGroundGeometryColorBatch.prototype.remove = function (updater) {
const batches = this._batches;
const count = batches.length;
for (let i = 0; i < count; ++i) {
if (batches[i].remove(updater)) {
return;
}
}
};
StaticGroundGeometryColorBatch.prototype.update = function (time) {
let i;
let updater;
//Perform initial update
let isUpdated = true;
const batches = this._batches;
const batchCount = batches.length;
for (i = 0; i < batchCount; ++i) {
isUpdated = batches[i].update(time) && isUpdated;
}
//If any items swapped between batches we need to move them
for (i = 0; i < batchCount; ++i) {
const oldBatch = batches[i];
const itemsToRemove = oldBatch.itemsToRemove;
const itemsToMoveLength = itemsToRemove.length;
for (let j = 0; j < itemsToMoveLength; j++) {
updater = itemsToRemove[j];
oldBatch.remove(updater);
const newBatch = this.add(time, updater);
oldBatch.isDirty = true;
newBatch.isDirty = true;
}
}
//If we moved anything around, we need to re-build the primitive and remove empty batches
for (i = batchCount - 1; i >= 0; --i) {
const batch = batches[i];
if (batch.isDirty) {
isUpdated = batches[i].update(time) && isUpdated;
batch.isDirty = false;
}
if (batch.geometry.length === 0) {
batches.splice(i, 1);
}
}
return isUpdated;
};
StaticGroundGeometryColorBatch.prototype.getBoundingSphere = function (
updater,
result,
) {
const batches = this._batches;
const batchCount = batches.length;
for (let i = 0; i < batchCount; ++i) {
const batch = batches[i];
if (batch.contains(updater)) {
return batch.getBoundingSphere(updater, result);
}
}
return BoundingSphereState.FAILED;
};
StaticGroundGeometryColorBatch.prototype.removeAllPrimitives = function () {
const batches = this._batches;
const batchCount = batches.length;
for (let i = 0; i < batchCount; ++i) {
batches[i].removeAllPrimitives();
}
};
export default StaticGroundGeometryColorBatch;
@@ -0,0 +1,459 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import defined from "../Core/defined.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import RectangleCollisionChecker from "../Core/RectangleCollisionChecker.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import GroundPrimitive from "../Scene/GroundPrimitive.js";
import ShadowVolumeAppearance from "../Scene/ShadowVolumeAppearance.js";
import BoundingSphereState from "./BoundingSphereState.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import MaterialProperty from "./MaterialProperty.js";
import Property from "./Property.js";
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
const defaultDistanceDisplayCondition = new DistanceDisplayCondition();
// Encapsulates a Primitive and all the entities that it represents.
function Batch(
primitives,
classificationType,
appearanceType,
materialProperty,
usingSphericalTextureCoordinates,
zIndex,
) {
this.primitives = primitives; // scene level primitive collection (each Batch manages its own Primitive from this collection)
this.classificationType = classificationType;
this.appearanceType = appearanceType;
this.materialProperty = materialProperty;
this.updaters = new AssociativeArray(); // GeometryUpdaters that manage the visual representation of the primitive.
this.createPrimitive = true;
this.primitive = undefined; // a GroundPrimitive encapsulating all the entities
this.oldPrimitive = undefined; // a GroundPrimitive that is being replaced by the current primitive, but will still be shown until the current primitive is ready.
this.geometry = new AssociativeArray();
this.material = undefined;
this.updatersWithAttributes = new AssociativeArray();
this.attributes = new AssociativeArray();
this.subscriptions = new AssociativeArray();
this.showsUpdated = new AssociativeArray();
this.usingSphericalTextureCoordinates = usingSphericalTextureCoordinates;
this.zIndex = zIndex;
this.rectangleCollisionCheck = new RectangleCollisionChecker();
}
Batch.prototype.overlapping = function (rectangle) {
return this.rectangleCollisionCheck.collides(rectangle);
};
// Check if the given updater's material is compatible with this batch
Batch.prototype.isMaterial = function (updater) {
const material = this.materialProperty;
const updaterMaterial = updater.fillMaterialProperty;
if (
updaterMaterial === material ||
(updaterMaterial instanceof ColorMaterialProperty &&
material instanceof ColorMaterialProperty)
) {
return true;
}
return defined(material) && material.equals(updaterMaterial);
};
/**
* Adds an updater to the Batch, and signals for a new Primitive to be created on the next update.
* @param {JulianDate} time
* @param {GeometryUpdater} updater
* @param {GeometryInstance} geometryInstance
* @private
*/
Batch.prototype.add = function (time, updater, geometryInstance) {
const id = updater.id;
this.updaters.set(id, updater);
this.geometry.set(id, geometryInstance);
this.rectangleCollisionCheck.insert(id, geometryInstance.geometry.rectangle);
// Updaters with dynamic attributes must be tracked separately, may exit the batch
if (
!updater.hasConstantFill ||
!updater.fillMaterialProperty.isConstant ||
!Property.isConstant(updater.distanceDisplayConditionProperty)
) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
// Listen for show changes. These will be synchronized in updateShows.
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(
function (entity, propertyName, newValue, oldValue) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
},
),
);
}
this.createPrimitive = true;
};
/**
* Remove an updater from the Batch, and potentially signals for a new Primitive to be created
* on the next update.
* @param {GeometryUpdater} updater
* @returns true if the updater was removed, false if it was not found.
* @private
*/
Batch.prototype.remove = function (updater) {
const id = updater.id;
const geometryInstance = this.geometry.get(id);
this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
if (this.updaters.remove(id)) {
this.rectangleCollisionCheck.remove(
id,
geometryInstance.geometry.rectangle,
);
this.updatersWithAttributes.remove(id);
const unsubscribe = this.subscriptions.get(id);
if (defined(unsubscribe)) {
unsubscribe();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
/**
* Update a Batch, creating a new primitive, if necessary, or swapping out an old primitive for a new one that's ready.
* A new primitive is created whenever an updater is added to or removed from a Batch.
* @param {JulianDate} time
* @returns a boolean indicating whether the Batch was updated.
* @private
*/
Batch.prototype.update = function (time) {
let isUpdated = true;
let primitive = this.primitive;
const primitives = this.primitives;
const geometries = this.geometry.values;
let i;
if (this.createPrimitive) {
const geometriesLength = geometries.length;
if (geometriesLength > 0) {
if (defined(primitive)) {
// Keep a handle to the old primitive so it can be removed when the updated version is ready.
if (!defined(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
// For if the new primitive changes again before it is ready.
primitives.remove(primitive);
}
}
this.material = MaterialProperty.getValue(
time,
this.materialProperty,
this.material,
);
const AppearanceType = this.appearanceType;
primitive = new GroundPrimitive({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
appearance: new AppearanceType({
material: this.material,
// translucent and closed properties overridden
}),
classificationType: this.classificationType,
});
primitives.add(primitive, this.zIndex);
isUpdated = false;
} else {
if (defined(primitive)) {
primitives.remove(primitive);
primitive = undefined;
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
} else if (defined(primitive) && primitive.ready) {
primitive.show = true;
if (defined(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = undefined;
}
this.material = MaterialProperty.getValue(
time,
this.materialProperty,
this.material,
);
this.primitive.appearance.material = this.material;
const updatersWithAttributes = this.updatersWithAttributes.values;
const length = updatersWithAttributes.length;
for (i = 0; i < length; i++) {
const updater = updatersWithAttributes[i];
const entity = updater.entity;
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
const show =
entity.isShowing && (updater.hasConstantFill || updater.isFilled(time));
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
}
const distanceDisplayConditionProperty =
updater.distanceDisplayConditionProperty;
if (!Property.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition,
distanceDisplayConditionScratch,
);
if (
!DistanceDisplayCondition.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
)
) {
attributes._lastDistanceDisplayCondition =
DistanceDisplayCondition.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
);
attributes.distanceDisplayCondition =
DistanceDisplayConditionGeometryInstanceAttribute.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition,
);
}
}
}
this.updateShows(primitive);
} else if (defined(primitive) && !primitive.ready) {
isUpdated = false;
}
return isUpdated;
};
Batch.prototype.updateShows = function (primitive) {
const showsUpdated = this.showsUpdated.values;
const length = showsUpdated.length;
for (let i = 0; i < length; i++) {
const updater = showsUpdated[i];
const entity = updater.entity;
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
const show = entity.isShowing;
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch.prototype.contains = function (updater) {
return this.updaters.contains(updater.id);
};
Batch.prototype.getBoundingSphere = function (updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (
!defined(attributes) ||
!defined(attributes.boundingSphere) ||
(defined(attributes.show) && attributes.show[0] === 0)
) {
return BoundingSphereState.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState.DONE;
};
/**
* Removes a Batch's primitive (and oldPrimitive, if it exists).
* @private
*/
Batch.prototype.destroy = function () {
const primitive = this.primitive;
const primitives = this.primitives;
if (defined(primitive)) {
primitives.remove(primitive);
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
}
};
/**
* A container of Batch objects of ground geometry primitives, where a Batch is grouped by material,
* texture coordinate type, and spatial overlap.
* @private
*/
function StaticGroundGeometryPerMaterialBatch(
primitives,
classificationType,
appearanceType,
) {
this._items = []; // array of Batch objects, each containing representing a primitive and a set of updaters that manage the visual representation of the primitive.
this._primitives = primitives; // scene level primitive collection
this._classificationType = classificationType;
this._appearanceType = appearanceType;
}
/**
* Adds an geometry updater to a Batch. Tries to find a preexisting compatible Batch, or else creates a new Batch.
* Used by Visualizer classes to add and update (remove->add) a primitive's Updater set.
*
* @param {JulianDate} time
* @param {GeometryUpdater} updater A GeometryUpdater that manages the visual representation of a primitive.
* @private
*/
StaticGroundGeometryPerMaterialBatch.prototype.add = function (time, updater) {
const items = this._items;
const length = items.length;
const geometryInstance = updater.createFillGeometryInstance(time);
const usingSphericalTextureCoordinates =
ShadowVolumeAppearance.shouldUseSphericalCoordinates(
geometryInstance.geometry.rectangle,
);
const zIndex = Property.getValueOrDefault(updater.zIndex, 0);
// Check if the Entity represented by the updater can be placed in an existing batch. Requirements:
// * compatible material (same material or same color)
// * same type of texture coordinates (spherical vs. planar)
// * conservatively non-overlapping with any entities in the existing batch
for (let i = 0; i < length; ++i) {
const item = items[i];
if (
item.isMaterial(updater) &&
item.usingSphericalTextureCoordinates ===
usingSphericalTextureCoordinates &&
item.zIndex === zIndex &&
!item.overlapping(geometryInstance.geometry.rectangle)
) {
item.add(time, updater, geometryInstance);
return;
}
}
// If a compatible batch wasn't found, create a new batch.
const batch = new Batch(
this._primitives,
this._classificationType,
this._appearanceType,
updater.fillMaterialProperty,
usingSphericalTextureCoordinates,
zIndex,
);
batch.add(time, updater, geometryInstance);
items.push(batch);
};
/**
* Removes an updater from a Batch. Defers potential deletion until the next update.
* @param {GeometryUpdater} updater A GeometryUpdater that manages the visual representation of a primitive.
* @private
*/
StaticGroundGeometryPerMaterialBatch.prototype.remove = function (updater) {
const items = this._items;
const length = items.length;
for (let i = length - 1; i >= 0; i--) {
const item = items[i];
if (item.remove(updater)) {
// If the item is now empty, delete it (deferred until the next update,
// in case a new updater is added to the same item first).
break;
}
}
};
/**
* Updates all the items (Batches) in the collection, and deletes any that are empty.
* @param {JulianDate} time
* @returns a boolean indicating whether any of the items (Batches) were updated.
* @private
*/
StaticGroundGeometryPerMaterialBatch.prototype.update = function (time) {
let i;
const items = this._items;
const length = items.length;
for (i = length - 1; i >= 0; i--) {
const item = items[i];
if (item.updaters.length === 0) {
items.splice(i, 1);
item.destroy();
}
}
let isUpdated = true;
for (i = 0; i < items.length; i++) {
isUpdated = items[i].update(time) && isUpdated;
}
return isUpdated;
};
StaticGroundGeometryPerMaterialBatch.prototype.getBoundingSphere = function (
updater,
result,
) {
const items = this._items;
const length = items.length;
for (let i = 0; i < length; i++) {
const item = items[i];
if (item.contains(updater)) {
return item.getBoundingSphere(updater, result);
}
}
return BoundingSphereState.FAILED;
};
StaticGroundGeometryPerMaterialBatch.prototype.removeAllPrimitives =
function () {
const items = this._items;
const length = items.length;
for (let i = 0; i < length; i++) {
items[i].destroy();
}
this._items.length = 0;
};
export default StaticGroundGeometryPerMaterialBatch;
@@ -0,0 +1,437 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import GroundPolylinePrimitive from "../Scene/GroundPolylinePrimitive.js";
import PolylineColorAppearance from "../Scene/PolylineColorAppearance.js";
import PolylineMaterialAppearance from "../Scene/PolylineMaterialAppearance.js";
import BoundingSphereState from "./BoundingSphereState.js";
import ColorMaterialProperty from "./ColorMaterialProperty.js";
import MaterialProperty from "./MaterialProperty.js";
import Property from "./Property.js";
const scratchColor = new Color();
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
const defaultDistanceDisplayCondition = new DistanceDisplayCondition();
// Encapsulates a Primitive and all the entities that it represents.
function Batch(
orderedGroundPrimitives,
classificationType,
materialProperty,
zIndex,
asynchronous,
) {
let appearanceType;
if (materialProperty instanceof ColorMaterialProperty) {
appearanceType = PolylineColorAppearance;
} else {
appearanceType = PolylineMaterialAppearance;
}
this.orderedGroundPrimitives = orderedGroundPrimitives; // scene level primitive collection
this.classificationType = classificationType;
this.appearanceType = appearanceType;
this.materialProperty = materialProperty;
this.updaters = new AssociativeArray();
this.createPrimitive = true;
this.primitive = undefined; // a GroundPolylinePrimitive encapsulating all the entities
this.oldPrimitive = undefined;
this.geometry = new AssociativeArray();
this.material = undefined;
this.updatersWithAttributes = new AssociativeArray();
this.attributes = new AssociativeArray();
this.invalidated = false;
this.removeMaterialSubscription =
materialProperty.definitionChanged.addEventListener(
Batch.prototype.onMaterialChanged,
this,
);
this.subscriptions = new AssociativeArray();
this.showsUpdated = new AssociativeArray();
this.zIndex = zIndex;
this._asynchronous = asynchronous;
}
Batch.prototype.onMaterialChanged = function () {
this.invalidated = true;
};
// Check if the given updater's material is compatible with this batch
Batch.prototype.isMaterial = function (updater) {
const material = this.materialProperty;
const updaterMaterial = updater.fillMaterialProperty;
if (
updaterMaterial === material ||
(updaterMaterial instanceof ColorMaterialProperty &&
material instanceof ColorMaterialProperty)
) {
return true;
}
return defined(material) && material.equals(updaterMaterial);
};
Batch.prototype.add = function (time, updater, geometryInstance) {
const id = updater.id;
this.updaters.set(id, updater);
this.geometry.set(id, geometryInstance);
// Updaters with dynamic attributes must be tracked separately, may exit the batch
if (
!updater.hasConstantFill ||
!updater.fillMaterialProperty.isConstant ||
!Property.isConstant(updater.distanceDisplayConditionProperty)
) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
// Listen for show changes. These will be synchronized in updateShows.
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(
function (entity, propertyName, newValue, oldValue) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
},
),
);
}
this.createPrimitive = true;
};
Batch.prototype.remove = function (updater) {
const id = updater.id;
this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
if (this.updaters.remove(id)) {
this.updatersWithAttributes.remove(id);
const unsubscribe = this.subscriptions.get(id);
if (defined(unsubscribe)) {
unsubscribe();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
Batch.prototype.update = function (time) {
let isUpdated = true;
let primitive = this.primitive;
const orderedGroundPrimitives = this.orderedGroundPrimitives;
const geometries = this.geometry.values;
let i;
if (this.createPrimitive) {
const geometriesLength = geometries.length;
if (geometriesLength > 0) {
if (defined(primitive)) {
// Keep a handle to the old primitive so it can be removed when the updated version is ready.
if (!defined(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
// For if the new primitive changes again before it is ready.
orderedGroundPrimitives.remove(primitive);
}
}
const AppearanceType = this.appearanceType;
primitive = new GroundPolylinePrimitive({
show: false,
asynchronous: this._asynchronous,
geometryInstances: geometries.slice(),
appearance: new AppearanceType(),
classificationType: this.classificationType,
});
if (this.appearanceType === PolylineMaterialAppearance) {
this.material = MaterialProperty.getValue(
time,
this.materialProperty,
this.material,
);
primitive.appearance.material = this.material;
}
orderedGroundPrimitives.add(primitive, this.zIndex);
isUpdated = false;
} else {
if (defined(primitive)) {
orderedGroundPrimitives.remove(primitive);
primitive = undefined;
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
orderedGroundPrimitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
} else if (defined(primitive) && primitive.ready) {
primitive.show = true;
if (defined(this.oldPrimitive)) {
orderedGroundPrimitives.remove(this.oldPrimitive);
this.oldPrimitive = undefined;
}
if (this.appearanceType === PolylineMaterialAppearance) {
this.material = MaterialProperty.getValue(
time,
this.materialProperty,
this.material,
);
this.primitive.appearance.material = this.material;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length = updatersWithAttributes.length;
for (i = 0; i < length; i++) {
const updater = updatersWithAttributes[i];
const entity = updater.entity;
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
if (!updater.fillMaterialProperty.isConstant) {
const colorProperty = updater.fillMaterialProperty.color;
const resultColor = Property.getValueOrDefault(
colorProperty,
time,
Color.WHITE,
scratchColor,
);
if (!Color.equals(attributes._lastColor, resultColor)) {
attributes._lastColor = Color.clone(
resultColor,
attributes._lastColor,
);
attributes.color = ColorGeometryInstanceAttribute.toValue(
resultColor,
attributes.color,
);
}
}
const show =
entity.isShowing && (updater.hasConstantFill || updater.isFilled(time));
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
}
const distanceDisplayConditionProperty =
updater.distanceDisplayConditionProperty;
if (!Property.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition,
distanceDisplayConditionScratch,
);
if (
!DistanceDisplayCondition.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
)
) {
attributes._lastDistanceDisplayCondition =
DistanceDisplayCondition.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
);
attributes.distanceDisplayCondition =
DistanceDisplayConditionGeometryInstanceAttribute.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition,
);
}
}
}
this.updateShows(primitive);
} else if (defined(primitive) && !primitive.ready) {
isUpdated = false;
}
return isUpdated;
};
Batch.prototype.updateShows = function (primitive) {
const showsUpdated = this.showsUpdated.values;
const length = showsUpdated.length;
for (let i = 0; i < length; i++) {
const updater = showsUpdated[i];
const entity = updater.entity;
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
const show = entity.isShowing;
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch.prototype.contains = function (updater) {
return this.updaters.contains(updater.id);
};
Batch.prototype.getBoundingSphere = function (updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (
!defined(attributes) ||
!defined(attributes.boundingSphere) ||
(defined(attributes.show) && attributes.show[0] === 0)
) {
return BoundingSphereState.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState.DONE;
};
Batch.prototype.destroy = function () {
const primitive = this.primitive;
const orderedGroundPrimitives = this.orderedGroundPrimitives;
if (defined(primitive)) {
orderedGroundPrimitives.remove(primitive);
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
orderedGroundPrimitives.remove(oldPrimitive);
}
this.removeMaterialSubscription();
};
/**
* @private
*/
function StaticGroundPolylinePerMaterialBatch(
orderedGroundPrimitives,
classificationType,
asynchronous,
) {
this._items = [];
this._orderedGroundPrimitives = orderedGroundPrimitives;
this._classificationType = classificationType;
this._asynchronous = asynchronous ?? true;
}
StaticGroundPolylinePerMaterialBatch.prototype.add = function (time, updater) {
const items = this._items;
const length = items.length;
const geometryInstance = updater.createFillGeometryInstance(time);
const zIndex = Property.getValueOrDefault(updater.zIndex, 0);
// Check if the Entity represented by the updater has the same material or a material representable with per-instance color.
for (let i = 0; i < length; ++i) {
const item = items[i];
if (item.isMaterial(updater) && item.zIndex === zIndex) {
item.add(time, updater, geometryInstance);
return;
}
}
// If a compatible batch wasn't found, create a new batch.
const batch = new Batch(
this._orderedGroundPrimitives,
this._classificationType,
updater.fillMaterialProperty,
zIndex,
this._asynchronous,
);
batch.add(time, updater, geometryInstance);
items.push(batch);
};
StaticGroundPolylinePerMaterialBatch.prototype.remove = function (updater) {
const items = this._items;
const length = items.length;
for (let i = length - 1; i >= 0; i--) {
const item = items[i];
if (item.remove(updater)) {
if (item.updaters.length === 0) {
items.splice(i, 1);
item.destroy();
}
break;
}
}
};
StaticGroundPolylinePerMaterialBatch.prototype.update = function (time) {
let i;
const items = this._items;
const length = items.length;
for (i = length - 1; i >= 0; i--) {
const item = items[i];
if (item.invalidated) {
items.splice(i, 1);
const updaters = item.updaters.values;
const updatersLength = updaters.length;
for (let h = 0; h < updatersLength; h++) {
this.add(time, updaters[h]);
}
item.destroy();
}
}
let isUpdated = true;
for (i = 0; i < items.length; i++) {
isUpdated = items[i].update(time) && isUpdated;
}
return isUpdated;
};
StaticGroundPolylinePerMaterialBatch.prototype.getBoundingSphere = function (
updater,
result,
) {
const items = this._items;
const length = items.length;
for (let i = 0; i < length; i++) {
const item = items[i];
if (item.contains(updater)) {
return item.getBoundingSphere(updater, result);
}
}
return BoundingSphereState.FAILED;
};
StaticGroundPolylinePerMaterialBatch.prototype.removeAllPrimitives =
function () {
const items = this._items;
const length = items.length;
for (let i = 0; i < length; i++) {
items[i].destroy();
}
this._items.length = 0;
};
export default StaticGroundPolylinePerMaterialBatch;
@@ -0,0 +1,465 @@
import AssociativeArray from "../Core/AssociativeArray.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Color from "../Core/Color.js";
import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
import defined from "../Core/defined.js";
import DistanceDisplayCondition from "../Core/DistanceDisplayCondition.js";
import DistanceDisplayConditionGeometryInstanceAttribute from "../Core/DistanceDisplayConditionGeometryInstanceAttribute.js";
import OffsetGeometryInstanceAttribute from "../Core/OffsetGeometryInstanceAttribute.js";
import ShowGeometryInstanceAttribute from "../Core/ShowGeometryInstanceAttribute.js";
import PerInstanceColorAppearance from "../Scene/PerInstanceColorAppearance.js";
import Primitive from "../Scene/Primitive.js";
import BoundingSphereState from "./BoundingSphereState.js";
import Property from "./Property.js";
const colorScratch = new Color();
const distanceDisplayConditionScratch = new DistanceDisplayCondition();
const defaultDistanceDisplayCondition = new DistanceDisplayCondition();
const defaultOffset = Cartesian3.ZERO;
const offsetScratch = new Cartesian3();
function Batch(primitives, translucent, width, shadows) {
this.translucent = translucent;
this.width = width;
this.shadows = shadows;
this.primitives = primitives;
this.createPrimitive = false;
this.waitingOnCreate = false;
this.primitive = undefined;
this.oldPrimitive = undefined;
this.geometry = new AssociativeArray();
this.updaters = new AssociativeArray();
this.updatersWithAttributes = new AssociativeArray();
this.attributes = new AssociativeArray();
this.itemsToRemove = [];
this.subscriptions = new AssociativeArray();
this.showsUpdated = new AssociativeArray();
}
Batch.prototype.add = function (updater, instance) {
const id = updater.id;
this.createPrimitive = true;
this.geometry.set(id, instance);
this.updaters.set(id, updater);
if (
!updater.hasConstantOutline ||
!updater.outlineColorProperty.isConstant ||
!Property.isConstant(updater.distanceDisplayConditionProperty) ||
!Property.isConstant(updater.terrainOffsetProperty)
) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(
function (entity, propertyName, newValue, oldValue) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
},
),
);
}
};
Batch.prototype.remove = function (updater) {
const id = updater.id;
this.createPrimitive = this.geometry.remove(id) || this.createPrimitive;
if (this.updaters.remove(id)) {
this.updatersWithAttributes.remove(id);
const unsubscribe = this.subscriptions.get(id);
if (defined(unsubscribe)) {
unsubscribe();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
Batch.prototype.update = function (time) {
let isUpdated = true;
let removedCount = 0;
let primitive = this.primitive;
const primitives = this.primitives;
let i;
if (this.createPrimitive) {
const geometries = this.geometry.values;
const geometriesLength = geometries.length;
if (geometriesLength > 0) {
if (defined(primitive)) {
if (!defined(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
primitive = new Primitive({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
appearance: new PerInstanceColorAppearance({
flat: true,
translucent: this.translucent,
renderState: {
lineWidth: this.width,
},
}),
shadows: this.shadows,
});
primitives.add(primitive);
isUpdated = false;
} else {
if (defined(primitive)) {
primitives.remove(primitive);
primitive = undefined;
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
this.waitingOnCreate = true;
} else if (defined(primitive) && primitive.ready) {
primitive.show = true;
if (defined(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = undefined;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length = updatersWithAttributes.length;
const waitingOnCreate = this.waitingOnCreate;
for (i = 0; i < length; i++) {
const updater = updatersWithAttributes[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
if (!updater.outlineColorProperty.isConstant || waitingOnCreate) {
const outlineColorProperty = updater.outlineColorProperty;
const outlineColor = Property.getValueOrDefault(
outlineColorProperty,
time,
Color.WHITE,
colorScratch,
);
if (!Color.equals(attributes._lastColor, outlineColor)) {
attributes._lastColor = Color.clone(
outlineColor,
attributes._lastColor,
);
attributes.color = ColorGeometryInstanceAttribute.toValue(
outlineColor,
attributes.color,
);
if (
(this.translucent && attributes.color[3] === 255) ||
(!this.translucent && attributes.color[3] !== 255)
) {
this.itemsToRemove[removedCount++] = updater;
}
}
}
const show =
updater.entity.isShowing &&
(updater.hasConstantOutline || updater.isOutlineVisible(time));
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
}
const distanceDisplayConditionProperty =
updater.distanceDisplayConditionProperty;
if (!Property.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition,
distanceDisplayConditionScratch,
);
if (
!DistanceDisplayCondition.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
)
) {
attributes._lastDistanceDisplayCondition =
DistanceDisplayCondition.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition,
);
attributes.distanceDisplayCondition =
DistanceDisplayConditionGeometryInstanceAttribute.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition,
);
}
}
const offsetProperty = updater.terrainOffsetProperty;
if (!Property.isConstant(offsetProperty)) {
const offset = Property.getValueOrDefault(
offsetProperty,
time,
defaultOffset,
offsetScratch,
);
if (!Cartesian3.equals(offset, attributes._lastOffset)) {
attributes._lastOffset = Cartesian3.clone(
offset,
attributes._lastOffset,
);
attributes.offset = OffsetGeometryInstanceAttribute.toValue(
offset,
attributes.offset,
);
}
}
}
this.updateShows(primitive);
this.waitingOnCreate = false;
} else if (defined(primitive) && !primitive.ready) {
isUpdated = false;
}
this.itemsToRemove.length = removedCount;
return isUpdated;
};
Batch.prototype.updateShows = function (primitive) {
const showsUpdated = this.showsUpdated.values;
const length = showsUpdated.length;
for (let i = 0; i < length; i++) {
const updater = showsUpdated[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
const show = updater.entity.isShowing;
const currentShow = attributes.show[0] === 1;
if (show !== currentShow) {
attributes.show = ShowGeometryInstanceAttribute.toValue(
show,
attributes.show,
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch.prototype.contains = function (updater) {
return this.updaters.contains(updater.id);
};
Batch.prototype.getBoundingSphere = function (updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (
!defined(attributes) ||
!defined(attributes.boundingSphere) || //
(defined(attributes.show) && attributes.show[0] === 0)
) {
return BoundingSphereState.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState.DONE;
};
Batch.prototype.removeAllPrimitives = function () {
const primitives = this.primitives;
const primitive = this.primitive;
if (defined(primitive)) {
primitives.remove(primitive);
this.primitive = undefined;
this.geometry.removeAll();
this.updaters.removeAll();
}
const oldPrimitive = this.oldPrimitive;
if (defined(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = undefined;
}
};
/**
* @private
*/
function StaticOutlineGeometryBatch(primitives, scene, shadows) {
this._primitives = primitives;
this._scene = scene;
this._shadows = shadows;
this._solidBatches = new AssociativeArray();
this._translucentBatches = new AssociativeArray();
}
StaticOutlineGeometryBatch.prototype.add = function (time, updater) {
const instance = updater.createOutlineGeometryInstance(time);
const width = this._scene.clampLineWidth(updater.outlineWidth);
let batches;
let batch;
if (instance.attributes.color.value[3] === 255) {
batches = this._solidBatches;
batch = batches.get(width);
if (!defined(batch)) {
batch = new Batch(this._primitives, false, width, this._shadows);
batches.set(width, batch);
}
batch.add(updater, instance);
} else {
batches = this._translucentBatches;
batch = batches.get(width);
if (!defined(batch)) {
batch = new Batch(this._primitives, true, width, this._shadows);
batches.set(width, batch);
}
batch.add(updater, instance);
}
};
StaticOutlineGeometryBatch.prototype.remove = function (updater) {
let i;
const solidBatches = this._solidBatches.values;
const solidBatchesLength = solidBatches.length;
for (i = 0; i < solidBatchesLength; i++) {
if (solidBatches[i].remove(updater)) {
return;
}
}
const translucentBatches = this._translucentBatches.values;
const translucentBatchesLength = translucentBatches.length;
for (i = 0; i < translucentBatchesLength; i++) {
if (translucentBatches[i].remove(updater)) {
return;
}
}
};
StaticOutlineGeometryBatch.prototype.update = function (time) {
let i;
let x;
let updater;
let batch;
const solidBatches = this._solidBatches.values;
const solidBatchesLength = solidBatches.length;
const translucentBatches = this._translucentBatches.values;
const translucentBatchesLength = translucentBatches.length;
let itemsToRemove;
let isUpdated = true;
let needUpdate = false;
do {
needUpdate = false;
for (x = 0; x < solidBatchesLength; x++) {
batch = solidBatches[x];
//Perform initial update
isUpdated = batch.update(time);
//If any items swapped between solid/translucent, we need to
//move them between batches
itemsToRemove = batch.itemsToRemove;
const solidsToMoveLength = itemsToRemove.length;
if (solidsToMoveLength > 0) {
needUpdate = true;
for (i = 0; i < solidsToMoveLength; i++) {
updater = itemsToRemove[i];
batch.remove(updater);
this.add(time, updater);
}
}
}
for (x = 0; x < translucentBatchesLength; x++) {
batch = translucentBatches[x];
//Perform initial update
isUpdated = batch.update(time);
//If any items swapped between solid/translucent, we need to
//move them between batches
itemsToRemove = batch.itemsToRemove;
const translucentToMoveLength = itemsToRemove.length;
if (translucentToMoveLength > 0) {
needUpdate = true;
for (i = 0; i < translucentToMoveLength; i++) {
updater = itemsToRemove[i];
batch.remove(updater);
this.add(time, updater);
}
}
}
} while (needUpdate);
return isUpdated;
};
StaticOutlineGeometryBatch.prototype.getBoundingSphere = function (
updater,
result,
) {
let i;
const solidBatches = this._solidBatches.values;
const solidBatchesLength = solidBatches.length;
for (i = 0; i < solidBatchesLength; i++) {
const solidBatch = solidBatches[i];
if (solidBatch.contains(updater)) {
return solidBatch.getBoundingSphere(updater, result);
}
}
const translucentBatches = this._translucentBatches.values;
const translucentBatchesLength = translucentBatches.length;
for (i = 0; i < translucentBatchesLength; i++) {
const translucentBatch = translucentBatches[i];
if (translucentBatch.contains(updater)) {
return translucentBatch.getBoundingSphere(updater, result);
}
}
return BoundingSphereState.FAILED;
};
StaticOutlineGeometryBatch.prototype.removeAllPrimitives = function () {
let i;
const solidBatches = this._solidBatches.values;
const solidBatchesLength = solidBatches.length;
for (i = 0; i < solidBatchesLength; i++) {
solidBatches[i].removeAllPrimitives();
}
const translucentBatches = this._translucentBatches.values;
const translucentBatchesLength = translucentBatches.length;
for (i = 0; i < translucentBatchesLength; i++) {
translucentBatches[i].removeAllPrimitives();
}
};
export default StaticOutlineGeometryBatch;
@@ -0,0 +1,193 @@
import Color from "../Core/Color.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import createPropertyDescriptor from "./createPropertyDescriptor.js";
import Property from "./Property.js";
import StripeOrientation from "./StripeOrientation.js";
const defaultOrientation = StripeOrientation.HORIZONTAL;
const defaultEvenColor = Color.WHITE;
const defaultOddColor = Color.BLACK;
const defaultOffset = 0;
const defaultRepeat = 1;
/**
* A {@link MaterialProperty} that maps to stripe {@link Material} uniforms.
* @alias StripeMaterialProperty
* @constructor
*
* @param {object} [options] Object with the following properties:
* @param {Property|StripeOrientation} [options.orientation=StripeOrientation.HORIZONTAL] A Property specifying the {@link StripeOrientation}.
* @param {Property|Color} [options.evenColor=Color.WHITE] A Property specifying the first {@link Color}.
* @param {Property|Color} [options.oddColor=Color.BLACK] A Property specifying the second {@link Color}.
* @param {Property|number} [options.offset=0] A numeric Property specifying how far into the pattern to start the material.
* @param {Property|number} [options.repeat=1] A numeric Property specifying how many times the stripes repeat.
*/
function StripeMaterialProperty(options) {
options = options ?? Frozen.EMPTY_OBJECT;
this._definitionChanged = new Event();
this._orientation = undefined;
this._orientationSubscription = undefined;
this._evenColor = undefined;
this._evenColorSubscription = undefined;
this._oddColor = undefined;
this._oddColorSubscription = undefined;
this._offset = undefined;
this._offsetSubscription = undefined;
this._repeat = undefined;
this._repeatSubscription = undefined;
this.orientation = options.orientation;
this.evenColor = options.evenColor;
this.oddColor = options.oddColor;
this.offset = options.offset;
this.repeat = options.repeat;
}
Object.defineProperties(StripeMaterialProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof StripeMaterialProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return (
Property.isConstant(this._orientation) && //
Property.isConstant(this._evenColor) && //
Property.isConstant(this._oddColor) && //
Property.isConstant(this._offset) && //
Property.isConstant(this._repeat)
);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof StripeMaterialProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the Property specifying the {@link StripeOrientation}/
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default StripeOrientation.HORIZONTAL
*/
orientation: createPropertyDescriptor("orientation"),
/**
* Gets or sets the Property specifying the first {@link Color}.
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.WHITE
*/
evenColor: createPropertyDescriptor("evenColor"),
/**
* Gets or sets the Property specifying the second {@link Color}.
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default Color.BLACK
*/
oddColor: createPropertyDescriptor("oddColor"),
/**
* Gets or sets the numeric Property specifying the point into the pattern
* to begin drawing; with 0.0 being the beginning of the even color, 1.0 the beginning
* of the odd color, 2.0 being the even color again, and any multiple or fractional values
* being in between.
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default 0.0
*/
offset: createPropertyDescriptor("offset"),
/**
* Gets or sets the numeric Property specifying how many times the stripes repeat.
* @memberof StripeMaterialProperty.prototype
* @type {Property|undefined}
* @default 1.0
*/
repeat: createPropertyDescriptor("repeat"),
});
/**
* Gets the {@link Material} type at the provided time.
*
* @param {JulianDate} time The time for which to retrieve the type.
* @returns {string} The type of material.
*/
StripeMaterialProperty.prototype.getType = function (time) {
return "Stripe";
};
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
StripeMaterialProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
if (!defined(result)) {
result = {};
}
result.horizontal =
Property.getValueOrDefault(this._orientation, time, defaultOrientation) ===
StripeOrientation.HORIZONTAL;
result.evenColor = Property.getValueOrClonedDefault(
this._evenColor,
time,
defaultEvenColor,
result.evenColor,
);
result.oddColor = Property.getValueOrClonedDefault(
this._oddColor,
time,
defaultOddColor,
result.oddColor,
);
result.offset = Property.getValueOrDefault(this._offset, time, defaultOffset);
result.repeat = Property.getValueOrDefault(this._repeat, time, defaultRepeat);
return result;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
StripeMaterialProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof StripeMaterialProperty && //
Property.equals(this._orientation, other._orientation) && //
Property.equals(this._evenColor, other._evenColor) && //
Property.equals(this._oddColor, other._oddColor) && //
Property.equals(this._offset, other._offset) && //
Property.equals(this._repeat, other._repeat))
);
};
export default StripeMaterialProperty;
@@ -0,0 +1,24 @@
// @ts-check
/**
* Defined the orientation of stripes in {@link StripeMaterialProperty}.
*
* @enum {number}
*/
const StripeOrientation = {
/**
* Horizontal orientation.
* @type {number}
*/
HORIZONTAL: 0,
/**
* Vertical orientation.
* @type {number}
*/
VERTICAL: 1,
};
Object.freeze(StripeOrientation);
export default StripeOrientation;
@@ -0,0 +1,243 @@
import Cartesian3 from "../Core/Cartesian3.js";
import Cartographic from "../Core/Cartographic.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import Event from "../Core/Event.js";
import Iso8601 from "../Core/Iso8601.js";
import JulianDate from "../Core/JulianDate.js";
import CesiumMath from "../Core/Math.js";
import HeightReference, {
isHeightReferenceRelative,
} from "../Scene/HeightReference.js";
import Property from "./Property.js";
const scratchPosition = new Cartesian3();
/**
* @private
*/
function TerrainOffsetProperty(
scene,
positionProperty,
heightReferenceProperty,
extrudedHeightReferenceProperty,
) {
//>>includeStart('debug', pragmas.debug);
Check.defined("scene", scene);
Check.defined("positionProperty", positionProperty);
//>>includeEnd('debug');
this._scene = scene;
this._heightReference = heightReferenceProperty;
this._extrudedHeightReference = extrudedHeightReferenceProperty;
this._positionProperty = positionProperty;
this._position = new Cartesian3();
this._cartographicPosition = new Cartographic();
this._normal = new Cartesian3();
this._definitionChanged = new Event();
this._terrainHeight = 0;
this._removeCallbackFunc = undefined;
this._removeEventListener = undefined;
this._removeModeListener = undefined;
const that = this;
if (defined(scene.globe)) {
this._removeEventListener = scene.terrainProviderChanged.addEventListener(
function () {
that._updateClamping();
},
);
this._removeModeListener = scene.morphComplete.addEventListener(
function () {
that._updateClamping();
},
);
}
if (positionProperty.isConstant) {
const position = positionProperty.getValue(
Iso8601.MINIMUM_VALUE,
scratchPosition,
);
if (
!defined(position) ||
Cartesian3.equals(position, Cartesian3.ZERO) ||
!defined(scene.globe)
) {
return;
}
this._position = Cartesian3.clone(position, this._position);
this._updateClamping();
this._normal = scene.ellipsoid.geodeticSurfaceNormal(
position,
this._normal,
);
}
}
Object.defineProperties(TerrainOffsetProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* @memberof TerrainOffsetProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return false;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* @memberof TerrainOffsetProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
});
/**
* @private
*/
TerrainOffsetProperty.prototype._updateClamping = function () {
if (defined(this._removeCallbackFunc)) {
this._removeCallbackFunc();
}
const scene = this._scene;
const position = this._position;
if (Cartesian3.equals(position, Cartesian3.ZERO)) {
this._terrainHeight = 0;
return;
}
const ellipsoid = scene.ellipsoid;
const cartographicPosition = ellipsoid.cartesianToCartographic(
position,
this._cartographicPosition,
);
const height = scene.getHeight(cartographicPosition, this._heightReference);
if (defined(height)) {
this._terrainHeight = height;
} else {
this._terrainHeight = 0;
}
const updateFunction = (clampedPosition) => {
this._terrainHeight = clampedPosition.height;
this.definitionChanged.raiseEvent();
};
this._removeCallbackFunc = scene.updateHeight(
cartographicPosition,
updateFunction,
this._heightReference,
);
};
const timeScratch = new JulianDate();
/**
* Gets the height relative to the terrain based on the positions.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3} The offset
*/
TerrainOffsetProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
const heightReference = Property.getValueOrDefault(
this._heightReference,
time,
HeightReference.NONE,
);
const extrudedHeightReference = Property.getValueOrDefault(
this._extrudedHeightReference,
time,
HeightReference.NONE,
);
if (
heightReference === HeightReference.NONE &&
!isHeightReferenceRelative(extrudedHeightReference)
) {
this._position = Cartesian3.clone(Cartesian3.ZERO, this._position);
return Cartesian3.clone(Cartesian3.ZERO, result);
}
if (this._positionProperty.isConstant) {
return Cartesian3.multiplyByScalar(
this._normal,
this._terrainHeight,
result,
);
}
const scene = this._scene;
const position = this._positionProperty.getValue(time, scratchPosition);
if (
!defined(position) ||
Cartesian3.equals(position, Cartesian3.ZERO) ||
!defined(scene.globe)
) {
return Cartesian3.clone(Cartesian3.ZERO, result);
}
if (
Cartesian3.equalsEpsilon(this._position, position, CesiumMath.EPSILON10)
) {
return Cartesian3.multiplyByScalar(
this._normal,
this._terrainHeight,
result,
);
}
this._position = Cartesian3.clone(position, this._position);
this._updateClamping();
const normal = scene.ellipsoid.geodeticSurfaceNormal(position, this._normal);
return Cartesian3.multiplyByScalar(normal, this._terrainHeight, result);
};
TerrainOffsetProperty.prototype.isDestroyed = function () {
return false;
};
TerrainOffsetProperty.prototype.destroy = function () {
if (defined(this._removeEventListener)) {
this._removeEventListener();
}
if (defined(this._removeModeListener)) {
this._removeModeListener();
}
if (defined(this._removeCallbackFunc)) {
this._removeCallbackFunc();
}
return destroyObject(this);
};
/**
* A function which creates one or more providers.
* @callback TerrainOffsetProperty.PositionFunction
* @param {JulianDate} time The clock time at which to retrieve the position
* @param {Cartesian3} result The result position
* @returns {Cartesian3} The position at which to do the terrain height check
*/
export default TerrainOffsetProperty;
@@ -0,0 +1,155 @@
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import ReferenceFrame from "../Core/ReferenceFrame.js";
import TimeIntervalCollection from "../Core/TimeIntervalCollection.js";
import PositionProperty from "./PositionProperty.js";
import Property from "./Property.js";
/**
* A {@link TimeIntervalCollectionProperty} which is also a {@link PositionProperty}.
*
* @alias TimeIntervalCollectionPositionProperty
* @constructor
*
* @param {ReferenceFrame} [referenceFrame=ReferenceFrame.FIXED] The reference frame in which the position is defined.
*/
function TimeIntervalCollectionPositionProperty(referenceFrame) {
this._definitionChanged = new Event();
this._intervals = new TimeIntervalCollection();
this._intervals.changedEvent.addEventListener(
TimeIntervalCollectionPositionProperty.prototype._intervalsChanged,
this,
);
this._referenceFrame = referenceFrame ?? ReferenceFrame.FIXED;
}
Object.defineProperties(TimeIntervalCollectionPositionProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof TimeIntervalCollectionPositionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._intervals.isEmpty;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is considered to have changed if a call to getValue would return
* a different result for the same time.
* @memberof TimeIntervalCollectionPositionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the interval collection.
* @memberof TimeIntervalCollectionPositionProperty.prototype
* @type {TimeIntervalCollection}
* @readonly
*/
intervals: {
get: function () {
return this._intervals;
},
},
/**
* Gets the reference frame in which the position is defined.
* @memberof TimeIntervalCollectionPositionProperty.prototype
* @type {ReferenceFrame}
* @readonly
* @default ReferenceFrame.FIXED;
*/
referenceFrame: {
get: function () {
return this._referenceFrame;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time in the fixed frame.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
TimeIntervalCollectionPositionProperty.prototype.getValue = function (
time,
result,
) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
return this.getValueInReferenceFrame(time, ReferenceFrame.FIXED, result);
};
/**
* Gets the value of the property at the provided time and in the provided reference frame.
*
* @param {JulianDate} time The time for which to retrieve the value.
* @param {ReferenceFrame} referenceFrame The desired referenceFrame of the result.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3 | undefined} The modified result parameter or a new instance if the result parameter was not supplied.
*/
TimeIntervalCollectionPositionProperty.prototype.getValueInReferenceFrame =
function (time, referenceFrame, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(time)) {
throw new DeveloperError("time is required.");
}
if (!defined(referenceFrame)) {
throw new DeveloperError("referenceFrame is required.");
}
//>>includeEnd('debug');
const position = this._intervals.findDataForIntervalContainingDate(time);
if (defined(position)) {
return PositionProperty.convertToReferenceFrame(
time,
position,
this._referenceFrame,
referenceFrame,
result,
);
}
return undefined;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
TimeIntervalCollectionPositionProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof TimeIntervalCollectionPositionProperty && //
this._intervals.equals(other._intervals, Property.equals) && //
this._referenceFrame === other._referenceFrame)
);
};
/**
* @private
*/
TimeIntervalCollectionPositionProperty.prototype._intervalsChanged =
function () {
this._definitionChanged.raiseEvent(this);
};
export default TimeIntervalCollectionPositionProperty;
@@ -0,0 +1,136 @@
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import TimeIntervalCollection from "../Core/TimeIntervalCollection.js";
import Property from "./Property.js";
/**
* A {@link Property} which is defined by a {@link TimeIntervalCollection}, where the
* data property of each {@link TimeInterval} represents the value at time.
*
* @alias TimeIntervalCollectionProperty
* @constructor
*
* @example
* //Create a Cartesian2 interval property which contains data on August 1st, 2012
* //and uses a different value every 6 hours.
* const composite = new Cesium.TimeIntervalCollectionProperty();
* composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
* iso8601 : '2012-08-01T00:00:00.00Z/2012-08-01T06:00:00.00Z',
* isStartIncluded : true,
* isStopIncluded : false,
* data : new Cesium.Cartesian2(2.0, 3.4)
* }));
* composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
* iso8601 : '2012-08-01T06:00:00.00Z/2012-08-01T12:00:00.00Z',
* isStartIncluded : true,
* isStopIncluded : false,
* data : new Cesium.Cartesian2(12.0, 2.7)
* }));
* composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
* iso8601 : '2012-08-01T12:00:00.00Z/2012-08-01T18:00:00.00Z',
* isStartIncluded : true,
* isStopIncluded : false,
* data : new Cesium.Cartesian2(5.0, 12.4)
* }));
* composite.intervals.addInterval(Cesium.TimeInterval.fromIso8601({
* iso8601 : '2012-08-01T18:00:00.00Z/2012-08-02T00:00:00.00Z',
* isStartIncluded : true,
* isStopIncluded : true,
* data : new Cesium.Cartesian2(85.0, 4.1)
* }));
*/
function TimeIntervalCollectionProperty() {
this._definitionChanged = new Event();
this._intervals = new TimeIntervalCollection();
this._intervals.changedEvent.addEventListener(
TimeIntervalCollectionProperty.prototype._intervalsChanged,
this,
);
}
Object.defineProperties(TimeIntervalCollectionProperty.prototype, {
/**
* Gets a value indicating if this property is constant. A property is considered
* constant if getValue always returns the same result for the current definition.
* @memberof TimeIntervalCollectionProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return this._intervals.isEmpty;
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* The definition is changed whenever setValue is called with data different
* than the current value.
* @memberof TimeIntervalCollectionProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets the interval collection.
* @memberof TimeIntervalCollectionProperty.prototype
*
* @type {TimeIntervalCollection}
* @readonly
*/
intervals: {
get: function () {
return this._intervals;
},
},
});
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {object} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {object} The modified result parameter or a new instance if the result parameter was not supplied.
*/
TimeIntervalCollectionProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
const value = this._intervals.findDataForIntervalContainingDate(time);
if (defined(value) && typeof value.clone === "function") {
return value.clone(result);
}
return value;
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
TimeIntervalCollectionProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof TimeIntervalCollectionProperty && //
this._intervals.equals(other._intervals, Property.equals))
);
};
/**
* @private
*/
TimeIntervalCollectionProperty.prototype._intervalsChanged = function () {
this._definitionChanged.raiseEvent(this);
};
export default TimeIntervalCollectionProperty;
@@ -0,0 +1,158 @@
import Cartesian3 from "../Core/Cartesian3.js";
import defined from "../Core/defined.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import Matrix3 from "../Core/Matrix3.js";
import Quaternion from "../Core/Quaternion.js";
import Transforms from "../Core/Transforms.js";
import Property from "./Property.js";
import VelocityVectorProperty from "./VelocityVectorProperty.js";
/**
* A {@link Property} which evaluates to a {@link Quaternion} rotation
* based on the velocity of the provided {@link PositionProperty}.
*
* @alias VelocityOrientationProperty
* @constructor
*
* @param {PositionProperty} [position] The position property used to compute the orientation.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid used to determine which way is up.
*
* @example
* //Create an entity with position and orientation.
* const position = new Cesium.SampledProperty();
* position.addSamples(...);
* const entity = viewer.entities.add({
* position : position,
* orientation : new Cesium.VelocityOrientationProperty(position)
* }));
*/
function VelocityOrientationProperty(position, ellipsoid) {
this._velocityVectorProperty = new VelocityVectorProperty(position, true);
this._subscription = undefined;
this._ellipsoid = undefined;
this._definitionChanged = new Event();
this.ellipsoid = ellipsoid ?? Ellipsoid.default;
const that = this;
this._velocityVectorProperty.definitionChanged.addEventListener(function () {
that._definitionChanged.raiseEvent(that);
});
}
Object.defineProperties(VelocityOrientationProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* @memberof VelocityOrientationProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return Property.isConstant(this._velocityVectorProperty);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* @memberof VelocityOrientationProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the position property used to compute orientation.
* @memberof VelocityOrientationProperty.prototype
*
* @type {Property|undefined}
*/
position: {
get: function () {
return this._velocityVectorProperty.position;
},
set: function (value) {
this._velocityVectorProperty.position = value;
},
},
/**
* Gets or sets the ellipsoid used to determine which way is up.
* @memberof VelocityOrientationProperty.prototype
*
* @type {Property|undefined}
*/
ellipsoid: {
get: function () {
return this._ellipsoid;
},
set: function (value) {
const oldValue = this._ellipsoid;
if (oldValue !== value) {
this._ellipsoid = value;
this._definitionChanged.raiseEvent(this);
}
},
},
});
const positionScratch = new Cartesian3();
const velocityScratch = new Cartesian3();
const rotationScratch = new Matrix3();
const timeScratch = new JulianDate();
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {Quaternion} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Quaternion} The modified result parameter or a new instance if the result parameter was not supplied.
*/
VelocityOrientationProperty.prototype.getValue = function (time, result) {
if (!defined(time)) {
time = JulianDate.now(timeScratch);
}
const velocity = this._velocityVectorProperty._getValue(
time,
velocityScratch,
positionScratch,
);
if (!defined(velocity)) {
return undefined;
}
Transforms.rotationMatrixFromPositionVelocity(
positionScratch,
velocity,
this._ellipsoid,
rotationScratch,
);
return Quaternion.fromRotationMatrix(rotationScratch, result);
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
VelocityOrientationProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof VelocityOrientationProperty &&
Property.equals(
this._velocityVectorProperty,
other._velocityVectorProperty,
) &&
(this._ellipsoid === other._ellipsoid ||
this._ellipsoid.equals(other._ellipsoid)))
);
};
export default VelocityOrientationProperty;
@@ -0,0 +1,213 @@
import Cartesian3 from "../Core/Cartesian3.js";
import defined from "../Core/defined.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import Property from "./Property.js";
/**
* A {@link Property} which evaluates to a {@link Cartesian3} vector
* based on the velocity of the provided {@link PositionProperty}.
*
* @alias VelocityVectorProperty
* @constructor
*
* @param {PositionProperty} [position] The position property used to compute the velocity.
* @param {boolean} [normalize=true] Whether to normalize the computed velocity vector.
*
* @example
* //Create an entity with a billboard rotated to match its velocity.
* const position = new Cesium.SampledProperty();
* position.addSamples(...);
* const entity = viewer.entities.add({
* position : position,
* billboard : {
* image : 'image.png',
* alignedAxis : new Cesium.VelocityVectorProperty(position, true) // alignedAxis must be a unit vector
* }
* }));
*/
function VelocityVectorProperty(position, normalize) {
this._position = undefined;
this._subscription = undefined;
this._definitionChanged = new Event();
this._normalize = normalize ?? true;
this.position = position;
}
Object.defineProperties(VelocityVectorProperty.prototype, {
/**
* Gets a value indicating if this property is constant.
* @memberof VelocityVectorProperty.prototype
*
* @type {boolean}
* @readonly
*/
isConstant: {
get: function () {
return Property.isConstant(this._position);
},
},
/**
* Gets the event that is raised whenever the definition of this property changes.
* @memberof VelocityVectorProperty.prototype
*
* @type {Event}
* @readonly
*/
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
/**
* Gets or sets the position property used to compute the velocity vector.
* @memberof VelocityVectorProperty.prototype
*
* @type {Property|undefined}
*/
position: {
get: function () {
return this._position;
},
set: function (value) {
const oldValue = this._position;
if (oldValue !== value) {
if (defined(oldValue)) {
this._subscription();
}
this._position = value;
if (defined(value)) {
this._subscription = value._definitionChanged.addEventListener(
function () {
this._definitionChanged.raiseEvent(this);
},
this,
);
}
this._definitionChanged.raiseEvent(this);
}
},
},
/**
* Gets or sets whether the vector produced by this property
* will be normalized or not.
* @memberof VelocityVectorProperty.prototype
*
* @type {boolean}
*/
normalize: {
get: function () {
return this._normalize;
},
set: function (value) {
if (this._normalize === value) {
return;
}
this._normalize = value;
this._definitionChanged.raiseEvent(this);
},
},
});
const position1Scratch = new Cartesian3();
const position2Scratch = new Cartesian3();
const timeScratch = new JulianDate();
const timeNowScratch = new JulianDate();
const step = 1.0 / 60.0;
/**
* Gets the value of the property at the provided time.
*
* @param {JulianDate} [time=JulianDate.now()] The time for which to retrieve the value. If omitted, the current system time is used.
* @param {Cartesian3} [result] The object to store the value into, if omitted, a new instance is created and returned.
* @returns {Cartesian3} The modified result parameter or a new instance if the result parameter was not supplied.
*/
VelocityVectorProperty.prototype.getValue = function (time, result) {
return this._getValue(time, result);
};
/**
* @private
*/
VelocityVectorProperty.prototype._getValue = function (
time,
velocityResult,
positionResult,
) {
if (!defined(time)) {
time = JulianDate.now(timeNowScratch);
}
if (!defined(velocityResult)) {
velocityResult = new Cartesian3();
}
const property = this._position;
if (Property.isConstant(property)) {
return this._normalize
? undefined
: Cartesian3.clone(Cartesian3.ZERO, velocityResult);
}
let position1 = property.getValue(time, position1Scratch);
let position2 = property.getValue(
JulianDate.addSeconds(time, step, timeScratch),
position2Scratch,
);
//If we don't have a position for now, return undefined.
if (!defined(position1)) {
return undefined;
}
//If we don't have a position for now + step, see if we have a position for now - step.
if (!defined(position2)) {
position2 = position1;
position1 = property.getValue(
JulianDate.addSeconds(time, -step, timeScratch),
position2Scratch,
);
if (!defined(position1)) {
return undefined;
}
}
if (Cartesian3.equals(position1, position2)) {
return this._normalize
? undefined
: Cartesian3.clone(Cartesian3.ZERO, velocityResult);
}
if (defined(positionResult)) {
position1.clone(positionResult);
}
const velocity = Cartesian3.subtract(position2, position1, velocityResult);
if (this._normalize) {
return Cartesian3.normalize(velocity, velocityResult);
}
return Cartesian3.divideByScalar(velocity, step, velocityResult);
};
/**
* Compares this property to the provided property and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {Property} [other] The other property.
* @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
VelocityVectorProperty.prototype.equals = function (other) {
return (
this === other || //
(other instanceof VelocityVectorProperty &&
Property.equals(this._position, other._position))
);
};
export default VelocityVectorProperty;
+61
View File
@@ -0,0 +1,61 @@
import DeveloperError from "../Core/DeveloperError.js";
/**
* Defines the interface for visualizers. Visualizers are plug-ins to
* {@link DataSourceDisplay} that render data associated with
* {@link DataSource} instances.
* This object is an interface for documentation purposes and is not intended
* to be instantiated directly.
* @alias Visualizer
* @constructor
*
* @see BillboardVisualizer
* @see LabelVisualizer
* @see ModelVisualizer
* @see PathVisualizer
* @see PointVisualizer
* @see GeometryVisualizer
*/
function Visualizer() {
DeveloperError.throwInstantiationError();
}
/**
* Updates the visualization to the provided time.
* @function
*
* @param {JulianDate} time The time.
*
* @returns {boolean} True if the display was updated to the provided time,
* false if the visualizer is waiting for an asynchronous operation to
* complete before data can be updated.
*/
Visualizer.prototype.update = DeveloperError.throwInstantiationError;
/**
* Computes a bounding sphere which encloses the visualization produced for the specified entity.
* The bounding sphere is in the fixed frame of the scene's globe.
*
* @param {Entity} entity The entity whose bounding sphere to compute.
* @param {BoundingSphere} result The bounding sphere onto which to store the result.
* @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
* BoundingSphereState.PENDING if the result is still being computed, or
* BoundingSphereState.FAILED if the entity has no visualization in the current scene.
* @private
*/
Visualizer.prototype.getBoundingSphere = DeveloperError.throwInstantiationError;
/**
* Returns true if this object was destroyed; otherwise, false.
* @function
*
* @returns {boolean} True if this object was destroyed; otherwise, false.
*/
Visualizer.prototype.isDestroyed = DeveloperError.throwInstantiationError;
/**
* Removes all visualization and cleans up any resources associated with this instance.
* @function
*/
Visualizer.prototype.destroy = DeveloperError.throwInstantiationError;
export default Visualizer;

Some files were not shown because too many files have changed in this diff Show More