Show realistic light and shadows

View on GitHub

Show realistic lighting and shadows for a given time of day.

Image of show realistic light and shadows

Use case

You can use realistic lighting to evaluate the shadow impact of buildings and utility infrastructure on the surrounding community. This could be useful for civil engineers and urban planners, or for events management assessing the impact of building shadows during an outdoor event.

How to use the sample

Select one of the three lighting options to show that lighting effect on the SceneView. Select a time of day from the slider (based on a 24hr clock) to show the lighting for that time of day in the SceneView.

How it works

  1. Create a Scene and display it in a SceneView.
  2. Create a Calendar to define the time of day.
  3. Set the sun time to the scene view using the sunDate(_:) modifier.
  4. Set the sun lighting of the scene view to off, light, or lightAndShadows using the sunLighting(_:) modifier.

Relevant API

  • Scene
  • SceneView
  • SceneView.SunLighting

Tags

3D, lighting, realism, realistic, rendering, shadows, sun, time

Sample Code

ShowRealisticLightAndShadowsView.swift
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// Copyright 2023 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import ArcGIS
import SwiftUI

struct ShowRealisticLightAndShadowsView: View {
    /// The view model for this sample.
    @StateObject private var model = Model()

    /// The date second value controlled by the slider.
    @State private var dateSecond: Float = Model.dateSecondsNoon

    /// The formatted text of the date controlled by the slider.
    @State private var dateTimeText: String = DateFormatter.localizedString(
        from: .startOfDay.advanced(by: TimeInterval(Model.dateSecondsNoon)),
        dateStyle: .medium,
        timeStyle: .short
    )

    /// The sun lighting mode of the scene view.
    @State private var lightingMode: SceneView.SunLighting = .lightAndShadows

    /// The sun date that gets passed into the scene view.
    @State private var sunDate = Date.startOfDay.advanced(by: TimeInterval(Model.dateSecondsNoon))

    var body: some View {
        VStack {
            SceneView(scene: model.scene)
                .atmosphereEffect(.realistic)
                .sunLighting(lightingMode)
                .sunDate(sunDate)

            Slider(value: $dateSecond, in: Model.dateSecondValueRange) {
                Text("Time of day")
            } minimumValueLabel: {
                Text("AM")
            } maximumValueLabel: {
                Text("PM")
            }
            .frame(maxWidth: 540)
            .onChange(of: dateSecond, perform: sliderValueChanged(toValue:))
            .padding(.horizontal)
        }
        .overlay(alignment: .top) {
            dateTimeOverlay
        }
        .toolbar {
            ToolbarItem(placement: .bottomBar) {
                Picker("Lighting Mode", selection: $lightingMode) {
                    ForEach(SceneView.SunLighting.allCases, id: \.self) { mode in
                        Text(mode.label)
                    }
                }
            }
        }
    }

    /// An overlay showing the date time adjusted by the slider.
    var dateTimeOverlay: some View {
        Text(dateTimeText)
            .frame(maxWidth: .infinity)
            .padding(.vertical, 6)
            .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal)
    }

    /// Handles slider value changed event and set the scene view's sun date.
    /// - Parameter value: The slider's value.
    private func sliderValueChanged(toValue value: Float) {
        // A DateComponents struct to encapsulate the second value from the slider.
        let dateComponents = DateComponents(second: Int(value))
        sunDate = Calendar.current.date(byAdding: dateComponents, to: .startOfDay)!
        dateTimeText = DateFormatter.localizedString(from: sunDate, dateStyle: .medium, timeStyle: .short)
    }
}

extension ShowRealisticLightAndShadowsView {
    /// The model used to store the geo model and other expensive objects
    /// used in this view.
    class Model: ObservableObject {
        /// A scene with buildings.
        let scene: ArcGIS.Scene = {
            // Creates a scene layer from buildings REST service.
            let buildingsURL = URL(string: "https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/DevA_BuildingShells/SceneServer")!
            let buildingsLayer = ArcGISSceneLayer(url: buildingsURL)
            // Creates an elevation source from Terrain3D REST service.
            let elevationServiceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
            let elevationSource = ArcGISTiledElevationSource(url: elevationServiceURL)
            let surface = Surface()
            surface.addElevationSource(elevationSource)
            let scene = Scene(basemapStyle: .arcGISTopographic)
            scene.baseSurface = surface
            scene.addOperationalLayer(buildingsLayer)
            scene.initialViewpoint = Viewpoint(
                latitude: .zero,
                longitude: .zero,
                scale: .nan,
                camera: Camera(latitude: 45.54605, longitude: -122.69033, altitude: 500, heading: 162.58544, pitch: 72.0, roll: 0)
            )
            return scene
        }()

        /// The range of possible date second values.
        /// The range is 0 to 86,340 seconds ((60 seconds * 60 minutes * 24 hours)  - 60 seconds),
        /// which means 12 am to 11:59 pm.
        static var dateSecondValueRange: ClosedRange<Float> { 0...86340 }

        /// The number of seconds to represent 12 pm (60 seconds * 60 minutes * 12 hours).
        static let dateSecondsNoon: Float = 43200
    }
}

private extension SceneView.SunLighting {
    /// A human-readable label of the sun lighting mode.
    var label: String {
        switch self {
        case .lightAndShadows:
            return "Light and Shadows"
        case .light:
            return "Light Only"
        case .off:
            return "No Light"
        @unknown default:
            return "Unknown"
        }
    }
}

private extension Date {
    static let startOfDay = Calendar.current.startOfDay(for: .now)
}

#Preview {
    NavigationStack {
        ShowRealisticLightAndShadowsView()
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.