cesium中使用线程的一个方面是进行几何数据计算,通常计算耗时,放到线程中计算也很合理,但是通常几何数据占用相当大的内存,虽然浏览器中主线程与子线程传递数据可以使用如下方式转移内存的所有权
myWorker.postMessage(aMessage, transferList);
参数
aMessage
The object to deliver to the worker; this will be in the data field in the event delivered to the DedicatedWorkerGlobalScope.onmessage (en-US) handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
transferList 可选
一个可选的Transferable对象的数组,用于传递所有权。如果一个对象的所有权被转移,在发送它的上下文中将变为不可用(中止),并且只有在它被发送到的worker中可用。
可转移对象是如ArrayBuffer,MessagePort或ImageBitmap的实例对象。transferList数组中不可传入null。
Returns:Void.
但是针对javascript的对象类型,只支持像ArrayBuffer,MessagePort或ImageBitmap这一类的内置对象,不支持自定义对象,所以在向子线程传递需要计算的数据,以及子线程向主线程传递数据时需要对数据进行打包处理,而cesium中将数据打包为ArrayBuffer格式,子线程解包,计算完成后子线程在打包,主线程解包数据。
按照下面的流程讲解一下具体的处理过程:
scene.primitives.add(new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.PolylineGeometry({
positions: positions,
width: 5.0,
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
colors: colors,
}),
}),
appearance: new Cesium.PolylineColorAppearance(),
asynchronous : true
})
);
上面的这个过程创建一个polyline,因为有参数“asynchronous : true”的存在,所以使用了异步的处理过程,在这个过程中会创建子线程。
首先看一下PolylineGeometry这个类的构造函数:
function PolylineGeometry(options) {
// 默认值
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
// 位置
var positions = options.positions;
// 颜色
var colors = options.colors;
// 宽度
var width = defaultValue(options.width, 1.0);
// 每个顶点是否包含颜色颜色
var colorsPerVertex = defaultValue(options.colorsPerVertex, false);
//>>includeStart('debug', pragmas.debug);
if (!defined(positions) || positions.length < 2) {
throw new DeveloperError("At least two positions are required.");
}
if (typeof width !== "number") {
throw new DeveloperError("width must be a number");
}
// 定义了颜色,但是顶点数量和颜色的数量不相同
if (
defined(colors) &&
((colorsPerVertex && colors.length < positions.length) ||
(!colorsPerVertex && colors.length < positions.length - 1))
) {
throw new DeveloperError("colors has an invalid length.");
}
//>>includeEnd('debug');
// 位置
this._positions = positions;
// 颜色
this._colors = colors;
// 宽度
this._width = width;
// 每个顶点是否包含颜色
this._colorsPerVertex = colorsPerVertex;
// 顶点格式
this._vertexFormat = VertexFormat.clone(
defaultValue(options.vertexFormat, VertexFormat.DEFAULT)
);
// 圆弧的类型
this._arcType = defaultValue(options.arcType, ArcType.GEODESIC);
// 粒度
this._granularity = defaultValue(
options.granularity,
CesiumMath.RADIANS_PER_DEGREE
);
// 椭球
this._ellipsoid = Ellipsoid.clone(
defaultValue(options.ellipsoid, Ellipsoid.WGS84)
);
// 线

本文详细介绍了Cesium中如何利用线程进行几何数据的异步计算,重点讨论了线程间数据传输的限制及处理方式。通过创建和合并几何数据任务处理器,实现数据在主线程与子线程间的高效流转,从而优化3D场景的性能。内容包括PolylineGeometry构造函数、Primitive类的update方法以及TaskProcessor的使用等关键步骤。
最低0.47元/天 解锁文章
291

被折叠的 条评论
为什么被折叠?



