前言
cesium目前只能够加载`gltf`或者`glb`(二进制的gltf)格式模型,
其他常见的如obj和fbx格式的模型需要通过工具[fbx2gltf](https://www.npmjs.com/package/fbx2gltf)或者[obj2gltf](https://www.npmjs.com/package/obj2gltf)进行转换。
加载方式
cesium提供了两种方式来加载模型分别是entity和primitive。
entity开箱即用,primitive使用稍微要麻烦一点但是性能方面比entity好很多
如果是大场景的模型比较多的情况下还是推荐使用primitive的方式加载模型
entity方式加载
const gltfModel = window.viewer.entities.add({
orientation: Cesium.Transforms.headingPitchRollQuaternion(
new Cesium.Cartesian3.fromDegrees(lat,lng),
new Cesium.HeadingPitchRoll(
Cesium.Math.toRadians(rotate), //顺时针旋转的角度值
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(0)
)
)
position: Cesium.Cartesian3.fromDegrees(lat,lng)
model: {
uri: url,
scale: 1,
maximumScale: 20000,
incrementallyLoadTextures: true,
runAnimations: true,
clampAnimations: true,
eyeOffset: new Cesium.Cartesian3(0, 0, -10000),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
shadows: Cesium.ShadowMode.ENABLED,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
},
})
primitive方式加载
function useAddModelByPrimitive(
url: string,
position: number[],
option = {
scale: 1,
name: '模型',
rotationz: 0,
} as any
) {
const origin = Cesium.Cartesian3.fromDegrees(position[0], position[1], position[2])
const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin)
let modelPrimitive = null
modelPrimitive = window.viewer.scene.primitives.add(
Cesium.Model.fromGltf({
url: url,
modelMatrix: modelMatrix,
show: true, // default
scale: option.scale || 1,
// minimumPixelSize : 128, // never smaller than 128 pixels
maximumScale: 20000, // never larger than 20000 * model size (overrides minimumPixelSize)
allowPicking: true,
heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
scene: window.viewer.scene,
})
)
modelPrimitive.name = option.name
modelPrimitive.type = 'model'
if (option.rotationz) {
const mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(option.rotationz))
const rotationz = Cesium.Matrix4.fromRotationTranslation(mz)
Cesium.Matrix4.multiply(modelMatrix, rotationz, modelMatrix)
modelPrimitive.modelMatrix = modelMatrix
}
modelPrimitive.readyPromise.then(function (model: any) {
model.activeAnimations.addAll({
speedup: 1,
loop: Cesium.ModelAnimationLoop.REPEAT,
})
})
return modelPrimitive
}