Cesium JS API
AppearanceArcGisMapServerImageryProviderArcGISTiledElevationTerrainProviderArcTypeAssociativeArrayAxisAxisAlignedBoundingBoxbarycentricCoordinatesBillboardBillboardCollectionBillboardGraphicsBillboardVisualizerbinarySearchbinarySearchComparatorBingMapsGeocoderServiceBingMapsImageryProviderBingMapsStyleBlendEquationBlendFunctionBlendingStateBlendOptionBoundingRectangleBoundingSphereBoxEmitterBoxGeometryBoxGeometryUpdaterBoxGraphicsBoxOutlineGeometrybuildModuleUrlCallbackPropertyCameraCameraEventAggregatorCameraEventTypeCartesian2Cartesian3Cartesian4CartographicCartographicGeocoderServiceCatmullRomSplineCesium3DTileCesium3DTileColorBlendModeCesium3DTileContentCesium3DTileFeatureCesium3DTilePointFeatureCesium3DTilesetCesium3DTilesetGraphicsCesium3DTilesetVisualizerCesium3DTileStyleCesium3DTilesVoxelProviderCesiumTerrainProviderCesiumWidgetCheckerboardMaterialPropertyCircleEmitterCircleGeometryCircleOutlineGeometryClassificationPrimitiveClassificationTypeClippingPlaneClippingPlaneCollectionClockClockRangeClockStepcloneCloudCollectionCloudTypeColorColorBlendModeColorGeometryInstanceAttributeColorMaterialPropertycombineComponentDatatypeCompositeEntityCollectionCompositeMaterialPropertyCompositePositionPropertyCompositePropertyCompressedTextureBufferConditionsExpressionConeEmitterConstantPositionPropertyConstantPropertyConstantSplineContextOptionsCoplanarPolygonGeometryCoplanarPolygonOutlineGeometryCornerTypeCorridorGeometryCorridorGeometryUpdaterCorridorGraphicsCorridorOutlineGeometrycreateElevationBandMaterialcreateElevationBandMaterialBandcreateElevationBandMaterialEntrycreateGuidcreateOsmBuildingscreateTangentSpaceDebugPrimitivecreateWorldImagerycreateWorldTerrainCreditCreditDisplayCubicRealPolynomialCullFaceCullingVolumeCumulusCloudCustomDataSourceCustomHeightmapTerrainProviderCustomShaderCustomShaderModeCustomShaderTranslucencyModeCylinderGeometryCylinderGeometryUpdaterCylinderGraphicsCylinderOutlineGeometryCzmlDataSourceDataSourceDataSourceClockDataSourceCollectionDataSourceDisplayDebugAppearanceDebugCameraPrimitiveDebugModelMatrixPrimitiveDefaultProxydefaultValuedefinedDepthFunctiondestroyObjectDeveloperErrorDirectionalLightDirectionUpDiscardEmptyTileImagePolicyDiscardMissingTileImagePolicyDistanceDisplayConditionDistanceDisplayConditionGeometryInstanceAttributeEasingFunctionEllipseGeometryEllipseGeometryUpdaterEllipseGraphicsEllipseOutlineGeometryEllipsoidEllipsoidGeodesicEllipsoidGeometryEllipsoidGeometryUpdaterEllipsoidGraphicsEllipsoidOutlineGeometryEllipsoidRhumbLineEllipsoidSurfaceAppearanceEllipsoidTangentPlaneEllipsoidTerrainProviderEntityEntityClusterEntityCollectionEntityViewEventEventHelperexcludesReverseAxisexportKmlexportKmlModelCallbackexportKmlResultKmlexportKmlResultKmzExpressionExtrapolationTypeFeatureDetectionFogformatErrorFrameRateMonitorFrustumGeometryFrustumOutlineGeometryFullscreenGeocoderServiceGeocodeTypeGeographicProjectionGeographicTilingSchemeGeoJsonDataSourceGeometryGeometryAttributeGeometryAttributesGeometryFactoryGeometryInstanceGeometryInstanceAttributeGeometryPipelineGeometryUpdaterGeometryVisualizergetAbsoluteUrigetBaseUrigetExtensionFromUriGetFeatureInfoFormatgetFilenameFromUrigetImagePixelsgetTimestampGlobeGlobeTranslucencyGoogleEarthEnterpriseImageryProviderGoogleEarthEnterpriseMapsProviderGoogleEarthEnterpriseMetadataGoogleEarthEnterpriseTerrainDataGoogleEarthEnterpriseTerrainProviderGpxDataSourceGregorianDateGridImageryProviderGridMaterialPropertyGroundGeometryUpdaterGroundPolylineGeometryGroundPolylinePrimitiveGroundPrimitiveHeadingPitchRangeHeadingPitchRollHeadingPitchRollValuesHeightmapEncodingHeightmapTerrainDataHeightReferenceHermitePolynomialApproximationHermiteSplineHilbertOrderHorizontalOriginI3SDataProviderI3SFeatureI3SFieldI3SGeometryI3SLayerI3SNodeImageBasedLightingImageMaterialPropertyImageryLayerImageryLayerCollectionImageryLayerFeatureInfoImageryProviderImageryTypesincludesReverseAxisIndexDatatypeIntersectIntersections2DIntersectionTestsIntervalIonIonGeocoderServiceIonImageryProviderIonResourceIonWorldImageryStyleisLeapYearIso8601JulianDateKeyboardEventModifierKmlCameraKmlDataSourceKmlFeatureDataKmlLookAtKmlTourKmlTourFlyToKmlTourWaitLabelLabelCollectionLabelGraphicsLabelStyleLabelVisualizerLagrangePolynomialApproximationLeapSecondLightLightingModelLinearApproximationLinearSplineMapboxImageryProviderMapboxStyleImageryProviderMapMode2DMapProjectionMaterialMaterialAppearanceMaterialSupportMaterialPropertyMathMatrix2Matrix3Matrix4mergeSortmergeSortComparatorMetadataClassMetadataClassPropertyMetadataComponentTypeMetadataEnumMetadataEnumValueMetadataSchemaMetadataTypeModelModelAnimationModelAnimationCollectionModelAnimationLoopModelFeatureModelGraphicsModelNodeModelVisualizerMoonMorphWeightSplineNearFarScalarNeverTileDiscardPolicyNodeTransformationPropertyobjectToQueryOccluderOpenCageGeocoderServiceOpenStreetMapImageryProviderOrientedBoundingBoxOrthographicFrustumOrthographicOffCenterFrustumPackableForInterpolationParticleParticleBurstParticleEmitterParticleSystemPathGraphicsPathVisualizerPeliasGeocoderServicePerInstanceColorAppearancePerspectiveFrustumPerspectiveOffCenterFrustumPinBuilderPixelDatatypePixelFormatPlanePlaneGeometryPlaneGeometryUpdaterPlaneGraphicsPlaneOutlineGeometryPointCloudShadingPointGraphicspointInsideTrianglePointPrimitivePointPrimitiveCollectionPointVisualizerPolygonGeometryPolygonGeometryUpdaterPolygonGraphicsPolygonHierarchyPolygonOutlineGeometryPolylinePolylineArrowMaterialPropertyPolylineCollectionPolylineColorAppearancePolylineDashMaterialPropertyPolylineGeometryPolylineGeometryUpdaterPolylineGlowMaterialPropertyPolylineGraphicsPolylineMaterialAppearancePolylineOutlineMaterialPropertyPolylineVisualizerPolylineVolumeGeometryPolylineVolumeGeometryUpdaterPolylineVolumeGraphicsPolylineVolumeOutlineGeometryPositionPropertyPositionPropertyArrayPostProcessStagePostProcessStageCollectionPostProcessStageCompositePostProcessStageLibraryPostProcessStageSampleModePrimitivePrimitiveCollectionPrimitiveTypePropertyPropertyArrayPropertyBagProxyQuadraticRealPolynomialQuantizedMeshTerrainDataQuarticRealPolynomialQuaternionQuaternionSplinequeryToObjectQueueRayreadyPromiseRectangleRectangleGeometryRectangleGeometryUpdaterRectangleGraphicsRectangleOutlineGeometryReferenceFrameReferencePropertyremoveExtensionRequestRequestErrorEventRequestSchedulerRequestStateRequestTypeResourceRuntimeErrorSampledPositionPropertySampledPropertysampleTerrainsampleTerrainMostDetailedSceneSceneModeSceneTransformsScreenSpaceCameraControllerScreenSpaceEventHandlerScreenSpaceEventTypeshaderDefinesshaderMaximumIntersectionsLengthshaderUniformsShadowMapShadowModeShowGeometryInstanceAttributeSimon1994PlanetaryPositionsSimplePolylineGeometrySingleTileImageryProviderSkyAtmosphereSkyBoxSphereEmitterSphereGeometrySphereOutlineGeometrySphericalSplineSplitDirectionStencilFunctionStencilOperationSteppedSplineStripeMaterialPropertyStripeOrientationStyleExpressionsubdivideArraySunSunLightTaskProcessorTerrainDataTerrainProviderTextureMagnificationFilterTextureMinificationFilterTextureUniformTileAvailabilityTileCoordinatesImageryProviderTileDiscardPolicyTileMapServiceImageryProviderTileProviderErrorTilingSchemeTimeDynamicImageryTimeDynamicPointCloudTimeIntervalTimeIntervalCollectionTimeIntervalCollectionPositionPropertyTimeIntervalCollectionPropertyTimeStandardTransformsTranslationRotationScaleTridiagonalSystemSolverTrustedServersUniformSpecifierUniformTypeUrlTemplateImageryProviderVaryingTypeVelocityOrientationPropertyVelocityVectorPropertyVertexFormatVerticalOriginVideoSynchronizerViewportQuadVisibilityVisualizerVoxelPrimitiveVoxelProviderVoxelShapeTypeVRTheWorldTerrainProviderWallGeometryWallGeometryUpdaterWallGraphicsWallOutlineGeometryWebGLConstantsWebGLOptionsWebMapServiceImageryProviderWebMapTileServiceImageryProviderWebMercatorProjectionWebMercatorTilingSchemeWindingOrderwriteTextToCanvasAnimationAnimationViewModelBaseLayerPickerBaseLayerPickerViewModelCesium3DTilesInspectorCesium3DTilesInspectorViewModelCesiumInspectorCesiumInspectorViewModelClockViewModelCommandcreateCommandFullscreenButtonFullscreenButtonViewModelGeocoderGeocoderViewModelHomeButtonHomeButtonViewModelInfoBoxInfoBoxViewModelNavigationHelpButtonNavigationHelpButtonViewModelPerformanceWatchdogPerformanceWatchdogViewModelProjectionPickerProjectionPickerViewModelProviderViewModelSceneModePickerSceneModePickerViewModelSelectionIndicatorSelectionIndicatorViewModelSvgPathBindingHandlerTimelineToggleButtonViewModelViewerviewerCesium3DTilesInspectorMixinviewerCesiumInspectorMixinviewerDragDropMixinviewerPerformanceWatchdogMixinviewerVoxelInspectorMixinVoxelInspectorVoxelInspectorViewModelVRButtonVRButtonViewModel

CustomShader

CustomShader是CesiumJS提供的一个组件,它可以让开发者在三维场景中自定义着色器,以实现更复杂、更灵活的场景效果。

使用CustomShader

使用CustomShader时,需要先创建一个ShaderProgram对象,该对象包含了着色器代码和一些配置参数,例如:

var customShaderProgram = new Cesium.ShaderProgram({
  vertexShaderSource: '...',
  fragmentShaderSource: '...',
  attributeLocations: {
    'a_position': 0,
    'a_normal': 1,
    'a_textureCoordinates': 2
  }
});

上述代码创建了一个ShaderProgram对象,包含了顶点着色器和片元着色器的代码,以及一些用于绑定属性的配置参数。

接下来,需要为场景中的渲染器注册该ShaderProgram:

var customShader = new Cesium.CustomShader();
customShader.shaderProgram = customShaderProgram;
viewer.scene.postProcessStages.add(customShader);

在上述代码中,我们创建了一个CustomShader对象,并将ShaderProgram对象赋值给其shaderProgram属性。然后,我们将CustomShader对象添加到场景的后处理阶段中,以便CustomShader的着色器能够对场景进行渲染。

着色器程序的编写

在CustomShader中编写的着色程序与GLSL语言兼容,有关该语言的更多信息,请参见Khronos Group的官方文档。

以一个简单的着色器程序为例:

// 顶点着色器
attribute vec3 a_position;

void main() {
    gl_Position = czm_modelViewProjection * vec4(a_position, 1.0);
}

// 片元着色器
void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

上述代码定义了一个只输出红色的着色器程序,该程序的核心代码如下:

  • 顶点着色器:声明了一个输入变量a_position,表示顶点位置,然后将其经过矩阵变换后输出到gl_Position变量中,该变量表示顶点屏幕坐标。

  • 片元着色器:声明了一个输出变量gl_FragColor,表示片元颜色,该着色器输出的颜色为红色。

以上着色器程序只是一个简单的示例,实际应用中的着色器程序会更加复杂和灵活。

着色器变量的传递

在着色器程序中,我们需要获取一些变量,例如顶点属性、纹理坐标、时间等。在CesiumJS中,我们通过下述方式将变量传递给着色器:

customShaderProgram.uniforms.someUniform = new Cesium.Color(1.0, 0.0, 0.0, 1.0);

上述代码将一个名为someUniform的变量传递给了着色器程序,该变量的值为{1.0, 0.0, 0.0, 1.0}。

我们也可以在着色器程序中使用内置的uniform变量,例如:

  • czm_viewport:表示视口大小。

  • czm_frameNumber:表示当前帧数。

实例代码

接下来,通过一个简单的例子来演示如何使用CustomShader实现简单的效果:

var viewer = new Cesium.Viewer('cesiumContainer');

var customShaderProgram = new Cesium.ShaderProgram({
  vertexShaderSource: `
    attribute vec3 a_position;

    void main() {
      gl_Position = czm_modelViewProjection * vec4(a_position, 1.0);
    }
  `,
  fragmentShaderSource: `
    uniform vec4 u_color;

    void main() {
      gl_FragColor = u_color;
    }
  `,
  attributeLocations: {
    'a_position': 0
  }
});

var customShader = new Cesium.CustomShader();
customShader.shaderProgram = customShaderProgram;
customShaderProgram.uniforms.u_color = new Cesium.Color(1.0, 0.0, 0.0, 1.0);
viewer.scene.postProcessStages.add(customShader);

viewer.entities.add({
  name: 'cube',
  position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883, 100000.0),
  box: {
    dimensions: new Cesium.Cartesian3(100000.0, 100000.0, 100000.0),
    material: new Cesium.Color(1.0, 0.0, 0.0, 1.0)
  }
});

以上代码创建了一个红色的立方体,并使用CustomShader将其颜色更改为用户指定的颜色。着色器程序的核心代码如下:

// 顶点着色器
attribute vec3 a_position;

void main() {
  gl_Position = czm_modelViewProjection * vec4(a_position, 1.0);
}

// 片元着色器
uniform vec4 u_color;

void main() {
  gl_FragColor = u_color;
}

该着色器程序只将一个uniform变量u_color代表的颜色应用到片元上,因此对于任何对象,只需要将u_color设置为对应的颜色即可。这是一种比较灵活的方式,可以通过更改u_color来随时更改对象的颜色。

总结

本文介绍了CustomShader在CesiumJS中的使用方法和原理,CustomShader使得在CesiumJS中实现更加复杂和灵活的场景效果成为可能,是一种值得使用的组件。如果您还想深入学习CesiumJS的API,请访问CesiumJS官方文档。