Skip to main content

rpfm_lib/files/trade_routes/
mod.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! Trade routes file format support (`campaign_maps/<map>/trade_routes.ptd`).
12//!
13//! These files contain the precomputed trade network of a campaign map: the spline curves trade routes
14//! follow, and the routes between regions and between ports. The game copies them into the trade manager of
15//! the campaign startpos.
16//!
17//! # File Format
18//!
19//! All values are little endian:
20//!
21//! - Signature `\x89PTD\r\n\x1a\n`, `u32` version (1 in Attila).
22//! - `u32` region count, then each region key as `u32` length + bytes.
23//! - `u32` spline count, then per spline: 4 flag bytes, `u32` segment count, and per segment the start point
24//!   (`u16`, `u16`), the first control point as an `i16` offset from the start, the second control point as an
25//!   `i16` offset from the end, and the end point (`u16`, `u16`). Points are in raw map units; offsets are at
26//!   100 times the raw scale.
27//! - Region routes, then port routes: `u32` count, then per route `u32` from, `u32` to, `u32` edge count and
28//!   the edges. `from`/`to` index the region table. A pair can appear more than once (alternative paths).
29//! - A trailing `u32` (checksum?).
30
31use getset::*;
32use serde_derive::{Deserialize, Serialize};
33
34use crate::binary::{ReadBytes, WriteBytes};
35use crate::error::{Result, RLibError};
36use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
37use crate::utils::check_size_mismatch;
38
39pub use crate::files::detection::trade_routes::EXTENSION;
40
41/// Signature of trade routes files.
42pub const SIGNATURE: &[u8; 8] = b"\x89PTD\r\n\x1a\n";
43
44/// Version of trade routes files supported.
45const SUPPORTED_VERSION: u32 = 1;
46
47#[cfg(test)] mod trade_routes_test;
48
49//---------------------------------------------------------------------------//
50//                              Enum & Structs
51//---------------------------------------------------------------------------//
52
53/// Decoded trade routes (`.ptd`) file.
54#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
55#[getset(get = "pub", get_mut = "pub", set = "pub")]
56pub struct TradeRoutes {
57
58    /// File version.
59    version: u32,
60
61    /// Region keys. Routes refer to regions by their index in this list.
62    regions: Vec<String>,
63
64    /// Spline curves the routes are made of.
65    splines: Vec<TradeSpline>,
66
67    /// Routes between regions. A region pair may have several alternatives.
68    region_routes: Vec<TradeRoute>,
69
70    /// Routes between ports.
71    port_routes: Vec<TradeRoute>,
72
73    /// Trailing value of the file (checksum?).
74    trailer: u32,
75}
76
77/// A spline of the trade network: a chain of cubic Bezier segments.
78#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
79#[getset(get = "pub", get_mut = "pub", set = "pub")]
80pub struct TradeSpline {
81
82    /// Flags. Meaning unknown; the game copies them into the startpos spline record.
83    flags: [bool; 4],
84
85    /// Bezier segments, in order.
86    segments: Vec<TradeSplineSegment>,
87}
88
89/// A cubic Bezier segment, in raw map units.
90#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
91#[getset(get = "pub", get_mut = "pub", set = "pub")]
92pub struct TradeSplineSegment {
93
94    /// Start point.
95    start: (u16, u16),
96
97    /// First control point, as an offset from the start point (at 100x the raw scale).
98    start_control: (i16, i16),
99
100    /// Second control point, as an offset from the end point (at 100x the raw scale).
101    end_control: (i16, i16),
102
103    /// End point.
104    end: (u16, u16),
105}
106
107/// A route between two regions or ports: the spline edges to follow, in order.
108#[derive(Default, PartialEq, Eq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
109#[getset(get = "pub", get_mut = "pub", set = "pub")]
110pub struct TradeRoute {
111
112    /// Index of the origin in the region table.
113    from: u32,
114
115    /// Index of the destination in the region table.
116    to: u32,
117
118    /// Edges to follow.
119    edges: Vec<TradeRouteEdge>,
120}
121
122/// A spline traversal in a route: `spline index * 2 + direction`, where an odd value means the spline is
123/// traversed from end to start.
124#[derive(Default, PartialEq, Eq, Hash, Clone, Copy, Debug, Serialize, Deserialize)]
125pub struct TradeRouteEdge(u32);
126
127//---------------------------------------------------------------------------//
128//                              Implementations
129//---------------------------------------------------------------------------//
130
131impl Decodeable for TradeRoutes {
132
133    fn decode<R: ReadBytes>(data: &mut R, _extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
134        let signature = data.read_slice(SIGNATURE.len(), false)?;
135        if signature != SIGNATURE {
136            return Err(RLibError::DecodingPTDUnsupportedSignature(signature));
137        }
138
139        let version = data.read_u32()?;
140        if version != SUPPORTED_VERSION {
141            return Err(RLibError::DecodingPTDUnsupportedVersion(version));
142        }
143
144        let region_count = data.read_u32()?;
145        let regions = (0..region_count).map(|_| data.read_sized_string_u8_u32()).collect::<Result<Vec<_>>>()?;
146
147        let spline_count = data.read_u32()?;
148        let splines = (0..spline_count).map(|_| TradeSpline::decode(data)).collect::<Result<Vec<_>>>()?;
149
150        let region_routes = TradeRoute::decode_list(data)?;
151        let port_routes = TradeRoute::decode_list(data)?;
152        let trailer = data.read_u32()?;
153
154        check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
155
156        Ok(Self {
157            version,
158            regions,
159            splines,
160            region_routes,
161            port_routes,
162            trailer,
163        })
164    }
165}
166
167impl Encodeable for TradeRoutes {
168
169    fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
170        buffer.write_all(SIGNATURE)?;
171        buffer.write_u32(self.version)?;
172
173        buffer.write_u32(self.regions.len() as u32)?;
174        for region in &self.regions {
175            buffer.write_sized_string_u8_u32(region)?;
176        }
177
178        buffer.write_u32(self.splines.len() as u32)?;
179        for spline in &self.splines {
180            spline.encode(buffer)?;
181        }
182
183        TradeRoute::encode_list(&self.region_routes, buffer)?;
184        TradeRoute::encode_list(&self.port_routes, buffer)?;
185        buffer.write_u32(self.trailer)?;
186        Ok(())
187    }
188}
189
190impl TradeSpline {
191
192    fn decode<R: ReadBytes>(data: &mut R) -> Result<Self> {
193        let mut flags = [false; 4];
194        for flag in &mut flags {
195            *flag = data.read_bool()?;
196        }
197
198        let segment_count = data.read_u32()?;
199        let segments = (0..segment_count).map(|_| TradeSplineSegment::decode(data)).collect::<Result<Vec<_>>>()?;
200        Ok(Self { flags, segments })
201    }
202
203    fn encode<W: WriteBytes>(&self, buffer: &mut W) -> Result<()> {
204        for flag in self.flags {
205            buffer.write_bool(flag)?;
206        }
207
208        buffer.write_u32(self.segments.len() as u32)?;
209        for segment in &self.segments {
210            segment.encode(buffer)?;
211        }
212        Ok(())
213    }
214}
215
216impl TradeSplineSegment {
217
218    fn decode<R: ReadBytes>(data: &mut R) -> Result<Self> {
219        Ok(Self {
220            start: (data.read_u16()?, data.read_u16()?),
221            start_control: (data.read_i16()?, data.read_i16()?),
222            end_control: (data.read_i16()?, data.read_i16()?),
223            end: (data.read_u16()?, data.read_u16()?),
224        })
225    }
226
227    fn encode<W: WriteBytes>(&self, buffer: &mut W) -> Result<()> {
228        buffer.write_u16(self.start.0)?;
229        buffer.write_u16(self.start.1)?;
230        buffer.write_i16(self.start_control.0)?;
231        buffer.write_i16(self.start_control.1)?;
232        buffer.write_i16(self.end_control.0)?;
233        buffer.write_i16(self.end_control.1)?;
234        buffer.write_u16(self.end.0)?;
235        buffer.write_u16(self.end.1)
236    }
237}
238
239impl TradeRoute {
240
241    /// Creates a route.
242    pub fn new(from: u32, to: u32, edges: Vec<TradeRouteEdge>) -> Self {
243        Self { from, to, edges }
244    }
245
246    /// Decodes a `u32` count followed by that many routes.
247    fn decode_list<R: ReadBytes>(data: &mut R) -> Result<Vec<Self>> {
248        let count = data.read_u32()?;
249        (0..count).map(|_| {
250            let from = data.read_u32()?;
251            let to = data.read_u32()?;
252            let edge_count = data.read_u32()?;
253            let edges = (0..edge_count).map(|_| data.read_u32().map(TradeRouteEdge)).collect::<Result<Vec<_>>>()?;
254            Ok(Self { from, to, edges })
255        }).collect()
256    }
257
258    /// Encodes a `u32` count followed by the routes.
259    fn encode_list<W: WriteBytes>(routes: &[Self], buffer: &mut W) -> Result<()> {
260        buffer.write_u32(routes.len() as u32)?;
261        for route in routes {
262            buffer.write_u32(route.from)?;
263            buffer.write_u32(route.to)?;
264            buffer.write_u32(route.edges.len() as u32)?;
265            for edge in &route.edges {
266                buffer.write_u32(edge.0)?;
267            }
268        }
269        Ok(())
270    }
271}
272
273impl TradeRouteEdge {
274
275    /// Creates an edge from its stored value.
276    pub fn new(value: u32) -> Self {
277        Self(value)
278    }
279
280    /// Returns the stored value.
281    pub fn value(&self) -> u32 {
282        self.0
283    }
284
285    /// Returns the index of the spline this edge traverses.
286    pub fn spline(&self) -> usize {
287        (self.0 / 2) as usize
288    }
289
290    /// Returns `true` if the spline is traversed from end to start.
291    pub fn is_reversed(&self) -> bool {
292        self.0 % 2 == 1
293    }
294}