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
//! TST Simulation

use futures::future::FutureExt;
use geo::{Area, Centroid};

use crate::definitions::agent as definitions_agent;
use crate::definitions::tst as definitions_tst;
use crate::definitions::tst::SpeedCompute;
use crate::execution::tst as execution_tst;
use crate::execution::tst::AgentExecutorTrait;
use crate::{Error, Result};

mod utils;

//  ____  _                 _       _   _             ____                 _ _
// / ___|(_)_ __ ___  _   _| | __ _| |_(_) ___  _ __ |  _ \ ___  ___ _   _| | |_
// \___ \| | '_ ` _ \| | | | |/ _` | __| |/ _ \| '_ \| |_) / _ \/ __| | | | | __|
//  ___) | | | | | | | |_| | | (_| | |_| | (_) | | | |  _ |  __/\__ \ |_| | | |_
// |____/|_|_| |_| |_|\__,_|_|\__,_|\__|_|\___/|_| |_|_| \_\___||___/\__,_|_|\__|

/// Result of the simulation, with the estimated cost and final states.
#[derive(Default, Clone)]
pub struct SimulationResult
{
  estimated_cost: f32,
  final_states: crate::states::States,
}

impl SimulationResult
{
  /// Return the estimated cost
  pub fn get_estimated_cost(&self) -> f32
  {
    self.estimated_cost
  }
}

//  ____  _                 _       _   _             _____                     _   _
// / ___|(_)_ __ ___  _   _| | __ _| |_(_) ___  _ __ | ____|_  _____  ___ _   _| |_(_) ___  _ __
// \___ \| | '_ ` _ \| | | | |/ _` | __| |/ _ \| '_ \|  _| \ \/ / _ \/ __| | | | __| |/ _ \| '_ \
//  ___) | | | | | | | |_| | | (_| | |_| | (_) | | | | |___ >  <  __/ (__| |_| | |_| | (_) | | | |
// |____/|_|_| |_| |_|\__,_|_|\__,_|\__|_|\___/|_| |_|_____/_/\_\___|\___|\__,_|\__|_|\___/|_| |_|

/// Simulate the execution of a task, to compute the feasibility and the associated cost.
pub async fn simulate_execution(
  initial_states: crate::states::States,
  capabilities: definitions_agent::capabilities::Capabilities,
  tst_node: definitions_tst::Node,
) -> Result<SimulationResult>
{
  let agent = Agent {
    capabilities: capabilities,
    ..Default::default()
  };
  agent.simulation_result.lock().unwrap().final_states = initial_states;
  let executor =
    execution_tst::DefaultAgentExecutor::<MoveToExecutor, SearchAreaExecutor>::from_agent(&agent);
  let r = executor.execute(tst_node);
  let res = r.await;
  if let Err(e) = res
  {
    Err(e.into())
  }
  else
  {
    Ok(agent.simulation_result.lock().unwrap().clone())
  }
}

// Simulation executor

// Structures

#[derive(Clone, Default)]
struct Agent
{
  capabilities: definitions_agent::capabilities::Capabilities,
  simulation_result: std::sync::Arc<std::sync::Mutex<SimulationResult>>,
}

impl execution_tst::Agent for Agent {}

struct MoveToExecutor
{
  agent: Agent,
}

impl execution_tst::CreatableFromAgent<Agent, MoveToExecutor> for MoveToExecutor
{
  fn from_agent(agent: &Agent) -> MoveToExecutor
  {
    MoveToExecutor {
      agent: agent.clone(),
    }
  }
}

impl execution_tst::Executor<definitions_tst::MoveTo> for MoveToExecutor
{
  fn execute<'a, 'b>(
    &'a self,
    _executors: &'b impl execution_tst::Executors,
    t: definitions_tst::MoveTo,
  ) -> execution_tst::ExecutionResult<'b>
  {
    let simulation_result = self.agent.simulation_result.clone();
    let capabilities = self.agent.capabilities.clone();
    async move {
      let mut simulation_result = simulation_result.lock().unwrap();
      let current_position = simulation_result.final_states.get_position()?;

      let move_to_capability = capabilities
        .get_move()
        .map_err(|e| crate::Error::ExecutionFailed(e.to_string()))?;
      let vel = t
        .params
        .speed
        .compute_velocity(move_to_capability.get_max_velocity());
      // TODO use velocity in the cost
      simulation_result.estimated_cost += utils::distance(
        current_position.x,
        t.params.waypoint.longitude,
        current_position.y,
        t.params.waypoint.latitude,
      );

      simulation_result
        .final_states
        .update_state(crate::states::Position {
          x: t.params.waypoint.longitude,
          y: t.params.waypoint.latitude,
        })?;
      Ok::<(), Error>(())
    }
    .boxed()
  }
}

struct SearchAreaExecutor
{
  agent: Agent,
}

impl execution_tst::CreatableFromAgent<Agent, SearchAreaExecutor> for SearchAreaExecutor
{
  fn from_agent(agent: &Agent) -> SearchAreaExecutor
  {
    SearchAreaExecutor {
      agent: agent.clone(),
    }
  }
}

impl execution_tst::Executor<definitions_tst::SearchArea> for SearchAreaExecutor
{
  fn execute<'a, 'b>(
    &'a self,
    _executors: &'b impl execution_tst::Executors,
    t: definitions_tst::SearchArea,
  ) -> execution_tst::ExecutionResult<'b>
  {
    let simulation_result = self.agent.simulation_result.clone();
    async move {
      let mut simulation_result = simulation_result.lock().unwrap();
      let current_position = simulation_result.final_states.get_position()?;

      // Compute surface of polygon and center
      let mut polygon_points = Vec::<(f32, f32)>::new();

      for pt in t.params.area
      {
        polygon_points.push((pt.longitude, pt.latitude));
      }

      polygon_points.push(polygon_points[0]);

      let polygon = geo::Polygon::new(geo::LineString::from(polygon_points), vec![]);

      // TODO use velocity in the cost
      let center = polygon.centroid().unwrap();
      simulation_result.estimated_cost += utils::distance(
        current_position.x,
        center.x(),
        current_position.y,
        center.y(),
      );
      simulation_result.estimated_cost += polygon.unsigned_area();

      simulation_result
        .final_states
        .update_state(crate::states::Position {
          x: center.x(),
          y: center.y(),
        })?;
      Ok::<(), Error>(())
    }
    .boxed()
  }
}