CARLA
Loading...
Searching...
No Matches
Episode.cpp
Go to the documentation of this file.
1// Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma
2// de Barcelona (UAB).
3//
4// This work is licensed under the terms of the MIT license.
5// For a copy, see <https://opensource.org/licenses/MIT>.
6
8
9#include "carla/Logging.h"
14
15#include <exception>
16
17class FPoseSnapShot;
18
19namespace carla {
20namespace client {
21namespace detail {
22
23using namespace std::chrono_literals;
24
25 static auto &CastData(const sensor::SensorData &data) {
26 using target_t = const sensor::data::RawEpisodeState;
27 return static_cast<target_t &>(data);
28 }
29
30 template <typename RangeT>
31 static auto GetActorsById_Impl(Client &client, CachedActorList &actors, const RangeT &actor_ids) {
32 auto missing_ids = actors.GetMissingIds(actor_ids);
33 if (!missing_ids.empty()) {
34 actors.InsertRange(client.GetActorsById(missing_ids));
35 }
36 return actors.GetActorsById(actor_ids);
37 }
38
39 Episode::Episode(Client &client, std::weak_ptr<Simulator> simulator)
40 : Episode(client, client.GetEpisodeInfo(), simulator) {}
41
42 Episode::Episode(Client &client, const rpc::EpisodeInfo &info, std::weak_ptr<Simulator> simulator)
43 : _client(client),
44 _state(std::make_shared<EpisodeState>(info.id)),
45 _token(info.token),
46 _simulator(simulator),
47 _handled_episode_id(std::make_shared<std::atomic<uint64_t>>(info.id)) {}
48
50 try {
52 } catch (const std::exception &e) {
53 log_error("exception trying to disconnect from episode:", e.what());
54 }
55 }
56
58 std::weak_ptr<Episode> weak = shared_from_this();
59 _client.SubscribeToStream(_token, [weak](auto buffer) {
60 auto self = weak.lock();
61 if (self != nullptr) {
62
63 auto data = sensor::Deserializer::Deserialize(std::move(buffer));
64 auto next = std::make_shared<const EpisodeState>(CastData(*data));
65 auto prev = self->GetState();
66
67 // TODO: Update how the map change is detected
68 bool HasMapChanged = next->HasMapChanged();
69 bool UpdateLights = next->IsLightUpdatePending();
70
71 /// Check for pending exceptions (Mainly TM server closed)
72 if(self->_pending_exceptions) {
73
74 /// Mark pending exception false
75 self->_pending_exceptions = false;
76
77 /// Create exception for the error message
78 auto exception(self->_pending_exceptions_msg);
79 // Notify waiting threads that exception occurred
80 self->_snapshot.SetException(std::runtime_error(exception));
81 }
82 /// Sensor case: inconsistent data
83 else {
84 bool episode_changed = (next->GetEpisodeId() != prev->GetEpisodeId());
85
86 if (episode_changed) {
87 // Drop the previous episode's WalkerNavigation BEFORE the new
88 // episode id becomes visible (the compare_exchange below is what
89 // unblocks load_world): it caches that map's navmesh (.bin) and
90 // its server-side-navigation probe, so any query through it --
91 // e.g. get_random_location_from_navigation -- would keep
92 // answering with the previous map's data after a load_world.
93 // OnEpisodeStarted() used to do this but is no longer called on
94 // episode change (see OnEpisodeChanged below).
95 self->_walker_navigation.reset();
96 // Same ordering rule for the map cache: load_world returns as
97 // soon as the new episode id is published below, and the first
98 // world.get_map() must already see the cache as stale.
99 self->_should_update_map = true;
100 }
101
102 do {
103 if (prev->GetFrame() >= next->GetFrame() && !episode_changed) {
104 self->_on_tick_callbacks.Call(next);
105 return;
106 }
107 } while (!self->_state.compare_exchange(&prev, next));
108
109 if(UpdateLights || HasMapChanged) {
110 // The LightManager queries the server here; a time-out or a dying Simulator must not terminate the process.
111 try {
112 self->_on_light_update_callbacks.Call(next);
113 } catch (const std::exception &e) {
114 log_error("failed to update the lights for the new snapshot:", e.what());
115 }
116 }
117
118 if(HasMapChanged) {
119 self->_should_update_map = true;
120 }
121
122 /// Episode change
123 if(episode_changed) {
124 self->OnEpisodeChanged(next->GetEpisodeId());
125 }
126
127 // Notify waiting threads and do the callbacks.
128 self->_snapshot.SetValue(next);
129
130 // Call user callbacks.
131 self->_on_tick_callbacks.Call(next);
132 }
133 }
134 });
135 }
136
137 std::optional<rpc::Actor> Episode::GetActorById(ActorId id) {
138 auto actor = _actors.GetActorById(id);
139 if (!actor.has_value()) {
140 auto actor_list = _client.GetActorsById({id});
141 if (!actor_list.empty()) {
142 actor = std::move(actor_list.front());
143 _actors.Insert(*actor);
144 }
145 }
146 return actor;
147 }
148
149 std::vector<rpc::Actor> Episode::GetActorsById(const std::vector<ActorId> &actor_ids) {
150 return GetActorsById_Impl(_client, _actors, actor_ids);
151 }
152
153 std::vector<rpc::Actor> Episode::GetActors() {
154 return GetActorsById_Impl(_client, _actors, GetState()->GetActorIds());
155 }
156
163
164 void Episode::OnEpisodeChanged(uint64_t episode_id) {
165 // Hand the reset to the process-wide TM thread: resetting here can destroy clients and deadlock.
167 [handled = _handled_episode_id, episode_id]() { handled->store(episode_id); });
168 }
169
172 _should_update_map = false;
173 return true;
174 }
175 return false;
176 }
177
178 std::shared_ptr<WalkerNavigation> Episode::CreateNavigationIfMissing() {
179 std::shared_ptr<WalkerNavigation> nav;
180 do {
181 nav = _walker_navigation.load();
182 if (nav == nullptr) {
183 // Queried once per episode: _walker_navigation is reset on episode
184 // change (see Listen), so a load_world onto/off a server-side-nav
185 // map re-detects.
186 auto new_nav = std::make_shared<WalkerNavigation>(
188 _walker_navigation.compare_exchange(&nav, new_nav);
189 }
190 } while (nav == nullptr);
191 return nav;
192 }
193
194} // namespace detail
195} // namespace client
196} // namespace carla
Keeps a list of actor descriptions to avoid requesting each time the descriptions to the server.
void InsertRange(RangeT range)
Inserts a range containing actors.
void Insert(rpc::Actor actor)
Inserts an actor into the list.
std::optional< rpc::Actor > GetActorById(ActorId id) const
Retrieve the actor matching id, or empty optional if actor is not cached.
std::vector< rpc::Actor > GetActorsById(const RangeT &range) const
Retrieve the actors matching the ids in range.
std::vector< ActorId > GetMissingIds(const RangeT &range) const
Return the actor ids present in range that haven't been added to this list.
Provides communication with the rpc and streaming servers of a CARLA simulator.
std::vector< rpc::Actor > GetActorsById(const std::vector< ActorId > &ids)
bool IsNavigationServerSide() const
True when the server hosts the pedestrian navigation (a World-Partitioned navmesh exists in the curre...
void UnSubscribeFromStream(const streaming::Token &token)
void SubscribeToStream(const streaming::Token &token, std::function< void(Buffer)> callback)
Represents the state of all the actors of an episode at a given frame.
AtomicSharedPtr< const EpisodeState > _state
Definition Episode.h:121
std::weak_ptr< Simulator > _simulator
Definition Episode.h:143
CallbackList< WorldSnapshot > _on_tick_callbacks
Definition Episode.h:127
std::shared_ptr< WalkerNavigation > CreateNavigationIfMissing()
Definition Episode.cpp:178
std::vector< rpc::Actor > GetActorsById(const std::vector< ActorId > &actor_ids)
Definition Episode.cpp:149
std::shared_ptr< std::atomic< uint64_t > > _handled_episode_id
Shared with the TM reset thread, which may outlive this Episode.
Definition Episode.h:146
std::shared_ptr< const EpisodeState > GetState() const
Definition Episode.h:56
std::optional< rpc::Actor > GetActorById(ActorId id)
Definition Episode.cpp:137
void OnEpisodeChanged(uint64_t episode_id)
Definition Episode.cpp:164
const streaming::Token _token
Definition Episode.h:137
AtomicSharedPtr< WalkerNavigation > _walker_navigation
Definition Episode.h:135
std::vector< rpc::Actor > GetActors()
Definition Episode.cpp:153
Episode(Client &client, std::weak_ptr< Simulator > simulator)
Definition Episode.cpp:39
static SharedPtr< SensorData > Deserialize(Buffer &&buffer)
Base class for all the objects containing data generated by a sensor.
Definition SensorData.h:22
State of the episode at a given frame.
static void RequestReset(uint64_t episode_id, std::function< void()> on_done)
Non-blocking: reset all TMs once per episode on the reset thread, then call on_done.
static auto GetActorsById_Impl(Client &client, CachedActorList &actors, const RangeT &actor_ids)
Definition Episode.cpp:31
static auto & CastData(const sensor::SensorData &data)
Definition Episode.cpp:25
This file contains definitions of common data structures used in traffic manager.