Animate 3D graphic

View on GitHubSample viewer app

An AGSOrbitGeoElementCameraController follows a graphic while the graphic's position and rotation are animated.

Animate 3D graphic sample

Use case

Visualize movement through a 3D landscape.

How to use the sample

Tap the bottom buttons to adjust settings for the animation:

  • Mission: change the flight path, speed, and view progress
  • Play/Pause: toggle the animation
  • Stats: view the attributes of the animation
  • Camera: change the camera distance, heading, pitch, and other camera properties.

How it works

  1. Create an AGSGraphicsOverlay object and add it to the scene view.
  2. Create an AGSModelSceneSymbol object.
  3. Create an AGSGraphic object configured with a point and the model scene symbol.
  4. Add heading, pitch, and roll attributes to the graphic.
  5. Create an AGSSimpleRenderer object and set its expression properties.
  6. Add graphic and a renderer to the graphics overlay.
  7. Create an AGSOrbitGeoElementCameraController which is set to target the graphic.
  8. Assign the camera controller to the AGSSceneView.
  9. Update the graphic's location, heading, pitch, and roll.

Relevant API

  • AGSCamera
  • AGSGlobeCameraController
  • AGSGraphic
  • AGSGraphicsOverlay
  • AGSModelSceneSymbol
  • AGSOrbitGeoElementCameraController
  • AGSRenderer
  • AGSScene
  • AGSSceneView
  • AGSSurfacePlacement

Offline data

This sample uses the following data which are all included and downloaded on-demand:

Tags

animation, camera, heading, pitch, roll, rotation, visualize

Sample Code

Animate3DGraphicViewController.swiftAnimate3DGraphicViewController.swiftCameraSettingsViewController.swiftMissionSettingsViewController.swiftPlaneStatsViewController.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//
// Copyright 2017 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
//
//   http://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 UIKit
import ArcGIS

class Animate3DGraphicViewController: UIViewController {
    @IBOutlet private var sceneView: AGSSceneView!
    @IBOutlet private var mapView: AGSMapView!
    @IBOutlet private var playBBI: UIBarButtonItem!

    private var missionFileNames = ["GrandCanyon.csv", "Hawaii.csv", "Pyrenees.csv", "Snowdon.csv"]
    private var selectedMissionIndex = 0
    private var sceneGraphicsOverlay = AGSGraphicsOverlay()
    private var mapGraphicsOverlay = AGSGraphicsOverlay()
    private var frames: [Frame] = []
    private var planeModelGraphic: AGSGraphic?
    private var triangleGraphic: AGSGraphic?
    private var routeGraphic: AGSGraphic?
    private var currentFrameIndex = 0
    private var animationTimer: Timer?
    private var animationSpeed = 50
    private var orbitGeoElementCameraController: AGSOrbitGeoElementCameraController?
    private weak var planeStatsViewController: PlaneStatsViewController?
    private weak var missionSettingsViewController: MissionSettingsViewController?

    private var isAnimating = false {
        didSet {
            playBBI?.title = isAnimating ? "Pause" : "Play"
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the source code button item to the right of navigation bar
        (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["Animate3DGraphicViewController", "MissionSettingsViewController", "CameraSettingsViewController", "PlaneStatsViewController", "OptionsTableViewController"]

        // map
        let map = AGSMap(basemapStyle: .arcGISStreets)
        mapView.map = map
        mapView.interactionOptions.isEnabled = false

        mapView.layer.borderColor = UIColor.white.cgColor
        mapView.layer.borderWidth = 2

        // hide attribution text for map view
        mapView.isAttributionTextVisible = false

        // Initalize scene with imagery basemap style.
        let scene = AGSScene(basemapStyle: .arcGISImagery)

        // assign scene to scene view
        sceneView.scene = scene

        /// The url of the Terrain 3D ArcGIS REST Service.
        let worldElevationServiceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
        // elevation source
        let elevationSource = AGSArcGISTiledElevationSource(url: worldElevationServiceURL)

        // surface
        let surface = AGSSurface()
        surface.elevationSources.append(elevationSource)
        scene.baseSurface = surface

        // graphics overlay for scene view
        sceneGraphicsOverlay.sceneProperties?.surfacePlacement = .absolute
        sceneView.graphicsOverlays.add(sceneGraphicsOverlay)

        // renderer for scene graphics overlay
        let renderer = AGSSimpleRenderer()

        // expressions
        renderer.sceneProperties?.headingExpression = "[HEADING]"
        renderer.sceneProperties?.pitchExpression = "[PITCH]"
        renderer.sceneProperties?.rollExpression = "[ROLL]"

        // set renderer on the overlay
        sceneGraphicsOverlay.renderer = renderer

        // graphics overlay for map view
        mapView.graphicsOverlays.add(mapGraphicsOverlay)

        // renderer for map graphics overlay
        let renderer2D = AGSSimpleRenderer()
        renderer2D.rotationExpression = "[ANGLE]"
        mapGraphicsOverlay.renderer = renderer2D

        // route graphic
        let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: .blue, width: 1)
        let routeGraphic = AGSGraphic(geometry: nil, symbol: lineSymbol, attributes: nil)
        self.routeGraphic = routeGraphic
        mapGraphicsOverlay.graphics.add(routeGraphic)

        addPlane2D()

        // add the plane model
        addPlane3D()

        // setup camera to follow the plane
        setupCamera()

        // select the first mission by default
        changeMissionAction()
    }

    private func addPlane2D() {
        let triangleSymbol = AGSSimpleMarkerSymbol(style: .triangle, color: .red, size: 10)
        let triangleGraphic = AGSGraphic(geometry: nil, symbol: triangleSymbol, attributes: nil)
        self.triangleGraphic = triangleGraphic
        mapGraphicsOverlay.graphics.add(triangleGraphic)
    }

    private func addPlane3D() {
        // model symbol
        let planeModelSymbol = AGSModelSceneSymbol(name: "Bristol", extension: "dae", scale: 20)
        planeModelSymbol.anchorPosition = .center

        // arbitrary geometry for time being, the geometry will update with animation
        let point = AGSPoint(x: 0, y: 0, z: 0, spatialReference: .wgs84())

        // create graphic for the model
        let planeModelGraphic = AGSGraphic()
        self.planeModelGraphic = planeModelGraphic
        planeModelGraphic.geometry = point
        planeModelGraphic.symbol = planeModelSymbol

        // add graphic to the graphics overlay
        sceneGraphicsOverlay.graphics.add(planeModelGraphic)
    }

    private func setupCamera() {
        guard let planeModelGraphic = planeModelGraphic else {
            return
        }

        // AGSOrbitGeoElementCameraController to follow plane graphic
        // initialize object specifying the target geo element and distance to keep from it
        let orbitGeoElementCameraController = AGSOrbitGeoElementCameraController(targetGeoElement: planeModelGraphic, distance: 1000)
        self.orbitGeoElementCameraController = orbitGeoElementCameraController

        // set camera to align its heading with the model
        orbitGeoElementCameraController.isAutoHeadingEnabled = true

        // will keep the camera still while the model pitches or rolls
        orbitGeoElementCameraController.isAutoPitchEnabled = false
        orbitGeoElementCameraController.isAutoRollEnabled = false

        // min and max distance values between the model and the camera
        orbitGeoElementCameraController.minCameraDistance = 500
        orbitGeoElementCameraController.maxCameraDistance = 8000

        // set the camera controller on scene view
        sceneView.cameraController = orbitGeoElementCameraController
    }

    private func loadMissionData(_ name: String) {
        // get the path of the specified file in the bundle
        if let path = Bundle.main.path(forResource: name, ofType: nil) {
            // get content of the file
            if let content = try? String(contentsOfFile: path) {
                // split content into array of lines separated by new line character
                // each line is one frame
                let lines = content.components(separatedBy: CharacterSet.newlines)

                // create a frame object for each line
                frames = lines.map { (line) -> Frame in
                    let details = line.components(separatedBy: ",")
                    precondition(details.count == 6)

                    let position = AGSPoint(x: Double(details[0])!,
                                            y: Double(details[1])!,
                                            z: Double(details[2])!,
                                            spatialReference: .wgs84())

                    // load position, heading, pitch and roll for each frame
                    return Frame(position: position,
                                 heading: Measurement(value: Double(details[3])!, unit: UnitAngle.degrees),
                                 pitch: Measurement(value: Double(details[4])!, unit: UnitAngle.degrees),
                                 roll: Measurement(value: Double(details[5])!, unit: UnitAngle.degrees))
                }
            }
        } else {
            print("Mission file not found")
        }
    }

    private func startAnimation() {
        // invalidate timer to stop previous ongoing animation
        self.animationTimer?.invalidate()

        // duration or interval
        let duration = 1 / Double(animationSpeed)

        // new timer
        let animationTimer = Timer(timeInterval: duration, repeats: true) { [weak self] _ in
            self?.animate()
        }
        self.animationTimer = animationTimer
        RunLoop.main.add(animationTimer, forMode: .common)
    }

    private func animate() {
        // validations
        guard !frames.isEmpty,
            let planeModelGraphic = planeModelGraphic,
            let triangleGraphic = triangleGraphic else {
            return
        }

        // if animation is complete
        if currentFrameIndex >= frames.count {
            // invalidate timer
            animationTimer?.invalidate()

            // update state
            isAnimating = false

            // reset index
            currentFrameIndex = 0

            return
        }

        // else get the frame
        let frame = frames[currentFrameIndex]

        // update the properties on the model
        planeModelGraphic.geometry = frame.position
        planeModelGraphic.attributes["HEADING"] = frame.heading.value
        planeModelGraphic.attributes["PITCH"] = frame.pitch.value
        planeModelGraphic.attributes["ROLL"] = frame.roll.value

        // 2D plane
        triangleGraphic.geometry = frame.position

        // set viewpoint for map view
        let viewpoint = AGSViewpoint(center: frame.position, scale: 100000, rotation: 360 + frame.heading.value)
        mapView.setViewpoint(viewpoint)

        // update progress
        missionSettingsViewController?.progress = Float(currentFrameIndex) / Float(frames.count)

        // update stats
        planeStatsViewController?.frame = frame

        // increment current frame index
        currentFrameIndex += 1
    }

    // MARK: - Actions

    @IBAction func changeMissionAction() {
        // invalidate timer
        animationTimer?.invalidate()

        // set play button
        isAnimating = false

        // new mission name
        let missionFileName = missionFileNames[selectedMissionIndex]
        loadMissionData(missionFileName)

        // create a polyline from position in each frame to be used as path
        let points = frames.map { (frame) -> AGSPoint in
            return frame.position
        }

        let polylineBuilder = AGSPolylineBuilder(points: points)
        routeGraphic?.geometry = polylineBuilder.toGeometry()

        // set current frame to zero
        currentFrameIndex = 0

        // animate to first frame
        animate()
    }

    @IBAction func playAction(sender: UIBarButtonItem) {
        if isAnimating {
            animationTimer?.invalidate()
        } else {
            startAnimation()
        }

        isAnimating.toggle()
    }

    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // dismiss any shown view controllers
        dismiss(animated: false)

        if let controller = segue.destination as? CameraSettingsViewController {
            controller.orbitGeoElementCameraController = orbitGeoElementCameraController

            // pop over settings
            controller.presentationController?.delegate = self

            // preferred content size
            if traitCollection.horizontalSizeClass == .regular,
                traitCollection.verticalSizeClass == .regular {
                controller.preferredContentSize = CGSize(width: 300, height: 380)
            } else {
                controller.preferredContentSize = CGSize(width: 300, height: 250)
            }
        } else if let planeStatsViewController = segue.destination as? PlaneStatsViewController {
            self.planeStatsViewController = planeStatsViewController
            let frame = frames[currentFrameIndex]
            // Update stats.
            planeStatsViewController.frame = frame
            // pop over settings
            planeStatsViewController.presentationController?.delegate = self
        } else if let navController = segue.destination as? UINavigationController,
            let controller = navController.viewControllers.first as? MissionSettingsViewController {
            self.missionSettingsViewController = controller
            // initial values
            controller.missionFileNames = missionFileNames
            controller.selectedMissionIndex = selectedMissionIndex
            controller.animationSpeed = animationSpeed
            controller.progress = Float(currentFrameIndex) / Float(frames.count)

            // pop over settings
            navController.presentationController?.delegate = self
            controller.preferredContentSize = CGSize(width: 300, height: 200)
            controller.delegate = self
        }
    }
}

extension Animate3DGraphicViewController: MissionSettingsViewControllerDelegate {
    func missionSettingsViewController(_ missionSettingsViewController: MissionSettingsViewController, didSelectMissionAtIndex index: Int) {
        selectedMissionIndex = index
        changeMissionAction()
    }

    func missionSettingsViewController(_ missionSettingsViewController: MissionSettingsViewController, didChangeSpeed speed: Int) {
        animationSpeed = speed

        if isAnimating {
            animationTimer?.invalidate()
            startAnimation()
        }
    }
}

extension Animate3DGraphicViewController: UIAdaptivePresentationControllerDelegate {
    func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        // for popover or non modal presentation
        return .none
    }
}

struct Frame {
    let position: AGSPoint
    let heading: Measurement<UnitAngle>
    let pitch: Measurement<UnitAngle>
    let roll: Measurement<UnitAngle>

    init(position: AGSPoint, heading: Measurement<UnitAngle>, pitch: Measurement<UnitAngle>, roll: Measurement<UnitAngle>) {
        self.position = position
        self.heading = heading
        self.pitch = pitch
        self.roll = roll
    }

    var altitude: Measurement<UnitLength> {
        return Measurement(value: position.z, unit: UnitLength.meters)
    }
}

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