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
use crate::*;

/// Categorizes the declaration of animation information.
#[derive(Clone, Debug, Default)]
pub struct Animation {
    /// A text string containing the unique identifier of the element.
    pub id: Option<String>,
    /// The text string name of this element.
    pub name: Option<String>,
    /// Asset management information about this element.
    pub asset: Option<Box<Asset>>,
    /// Allows the formation of a hierarchy of related animations.
    pub children: Vec<Animation>,
    /// The data repository that provides values according to the semantics of an
    /// [`Input`] element that refers to it.
    pub source: Vec<Source>,
    /// Describes the interpolation sampling function for the animation.
    pub sampler: Vec<Sampler>,
    /// Describes an output channel for the animation.
    pub channel: Vec<Channel>,
    /// Provides arbitrary additional information about this element.
    pub extra: Vec<Extra>,
}

impl XNode for Animation {
    const NAME: &'static str = "animation";
    fn parse(element: &Element) -> Result<Self> {
        debug_assert_eq!(element.name(), Self::NAME);
        let mut it = element.children().peekable();
        let res = Animation {
            id: element.attr("id").map(Into::into),
            name: element.attr("name").map(Into::into),
            asset: Asset::parse_opt_box(&mut it)?,
            children: Animation::parse_list(&mut it)?,
            source: Source::parse_list(&mut it)?,
            sampler: Sampler::parse_list(&mut it)?,
            channel: Channel::parse_list(&mut it)?,
            extra: Extra::parse_many(it)?,
        };
        if res.children.is_empty() && res.sampler.is_empty() {
            return Err("animation: no sampler/channel or children".into());
        }
        if res.sampler.is_empty() != res.channel.is_empty() {
            return Err("animation: sampler and channel must be used together".into());
        }
        Ok(res)
    }
}

impl XNodeWrite for Animation {
    fn write_to<W: Write>(&self, w: &mut XWriter<W>) -> Result<()> {
        let mut e = Self::elem();
        e.opt_attr("id", &self.id);
        e.opt_attr("name", &self.name);
        let e = e.start(w)?;
        self.asset.write_to(w)?;
        self.children.write_to(w)?;
        self.source.write_to(w)?;
        self.sampler.write_to(w)?;
        self.channel.write_to(w)?;
        self.extra.write_to(w)?;
        e.end(w)
    }
}

impl CollectLocalMaps for Animation {
    fn collect_local_maps<'a>(&'a self, maps: &mut LocalMaps<'a>) {
        maps.insert(self);
        self.children.collect_local_maps(maps);
        self.source.collect_local_maps(maps);
        self.sampler.collect_local_maps(maps);
    }
}

impl Animation {
    fn on_children<'a, E>(
        &'a self,
        f: &mut impl FnMut(&'a Self) -> Result<(), E>,
    ) -> Result<(), E> {
        f(self)?;
        for child in &self.children {
            child.on_children(f)?
        }
        Ok(())
    }
}

impl Traversable for Animation {
    fn traverse<'a, E>(
        doc: &'a Document,
        mut f: impl FnMut(&'a Animation) -> Result<(), E>,
    ) -> Result<(), E> {
        doc.iter()
            .try_for_each(|e: &Animation| e.on_children(&mut f))
    }
}

/// Defines a section of a set of animation curves to be used together as an animation clip.
#[derive(Clone, Debug)]
pub struct AnimationClip {
    /// A text string containing the unique identifier of the element.
    pub id: Option<String>,
    /// The text string name of this element.
    pub name: Option<String>,
    /// The time in seconds of the beginning of the clip. This time is the same as that used in the
    /// key-frame data and is used to determine which set of key frames will be included in the
    /// clip. The start time does not specify when the clip will be played. If the time falls between
    /// two key frames of a referenced animation, an interpolated value should be used.
    pub start: f32,
    /// The time in seconds of the end of the clip. This is used in the same way as the start time.
    /// If `end` is not specified, the value is taken to be the end time of the longest animation.
    pub end: Option<f32>,
    /// Asset management information about this element.
    pub asset: Option<Box<Asset>>,
    /// Instantiates an [`Animation`] object.
    pub instance_animation: Vec<Instance<Animation>>,
    /// Provides arbitrary additional information about this element.
    pub extra: Vec<Extra>,
}

impl AnimationClip {
    /// Create a new `AnimationClip` from the given list of instances.
    pub fn new(instance_animation: Vec<Instance<Animation>>) -> Self {
        assert!(!instance_animation.is_empty());
        Self {
            id: Default::default(),
            name: Default::default(),
            start: Default::default(),
            end: Default::default(),
            asset: Default::default(),
            instance_animation,
            extra: Default::default(),
        }
    }
}

impl XNode for AnimationClip {
    const NAME: &'static str = "animation_clip";
    fn parse(element: &Element) -> Result<Self> {
        debug_assert_eq!(element.name(), Self::NAME);
        let mut it = element.children().peekable();
        Ok(AnimationClip {
            id: element.attr("id").map(Into::into),
            name: element.attr("name").map(Into::into),
            start: parse_attr(element.attr("start"))?.unwrap_or(0.),
            end: parse_attr(element.attr("end"))?,
            asset: Asset::parse_opt_box(&mut it)?,
            instance_animation: Instance::parse_list_n::<1>(&mut it)?,
            extra: Extra::parse_many(it)?,
        })
    }
}

impl XNodeWrite for AnimationClip {
    fn write_to<W: Write>(&self, w: &mut XWriter<W>) -> Result<()> {
        let mut e = Self::elem();
        e.opt_attr("id", &self.id);
        e.opt_attr("name", &self.name);
        e.print_attr("start", &self.start);
        e.opt_print_attr("end", &self.end);
        let e = e.start(w)?;
        self.asset.write_to(w)?;
        self.instance_animation.write_to(w)?;
        self.extra.write_to(w)?;
        e.end(w)
    }
}

/// Declares an output channel of an animation.
#[derive(Clone, Debug)]
pub struct Channel {
    /// The location of the animation sampler using a URL expression.
    pub source: UrlRef<Sampler>,
    /// The location of the element bound to the output of the sampler.
    pub target: Address,
}

impl Channel {
    /// Construct a new `Channel` from a source and target.
    pub fn new(source: Url, target: String) -> Self {
        Self {
            source: Ref::new(source),
            target: Address(target),
        }
    }
}

impl XNode for Channel {
    const NAME: &'static str = "channel";
    fn parse(element: &Element) -> Result<Self> {
        debug_assert_eq!(element.name(), Self::NAME);
        let target = element.attr("target").ok_or("expecting target attr")?;
        Ok(Channel {
            source: parse_attr(element.attr("source"))?.ok_or("missing source attr")?,
            target: Address(target.into()),
        })
    }
}

impl XNodeWrite for Channel {
    fn write_to<W: Write>(&self, w: &mut XWriter<W>) -> Result<()> {
        let mut e = Self::elem();
        e.print_attr("source", &self.source);
        e.print_attr("target", &self.target);
        e.end(w)
    }
}

/// Declares an interpolation sampling function for an animation.
#[derive(Clone, Debug)]
pub struct Sampler {
    /// A text string containing the unique identifier of the element.
    pub id: Option<String>,
    /// Assigns semantics to each [`Source`]. See the COLLADA spec for details.
    pub inputs: Vec<Input>,
    /// The index into `inputs` for the [`Semantic::Interpolation`] input (which must exist).
    pub interpolation: usize,
}

impl Sampler {
    /// Construct a new `Sampler` from a list of inputs.
    /// One of the inputs must have [`Semantic::Interpolation`].
    pub fn new(inputs: Vec<Input>) -> Self {
        Self {
            id: None,
            interpolation: inputs
                .iter()
                .position(|i| i.semantic == Semantic::Interpolation)
                .expect("sampler: missing INTERPOLATION input"),
            inputs,
        }
    }
}

impl XNode for Sampler {
    const NAME: &'static str = "sampler";
    fn parse(element: &Element) -> Result<Self> {
        debug_assert_eq!(element.name(), Self::NAME);
        let mut it = element.children().peekable();
        let inputs = Input::parse_list(&mut it)?;
        let res = Sampler {
            id: element.attr("id").map(Into::into),
            interpolation: inputs
                .iter()
                .position(|i| i.semantic == Semantic::Interpolation)
                .ok_or("sampler: missing INTERPOLATION input")?,
            inputs,
        };
        finish(res, it)
    }
}

impl XNodeWrite for Sampler {
    fn write_to<W: Write>(&self, w: &mut XWriter<W>) -> Result<()> {
        let mut e = Self::elem();
        e.opt_attr("id", &self.id);
        let e = e.start(w)?;
        self.inputs.write_to(w)?;
        e.end(w)
    }
}

impl CollectLocalMaps for Sampler {
    fn collect_local_maps<'a>(&'a self, maps: &mut LocalMaps<'a>) {
        maps.insert(self)
    }
}

impl Traversable for Sampler {
    fn traverse<'a, E>(
        doc: &'a Document,
        mut f: impl FnMut(&'a Self) -> Result<(), E>,
    ) -> Result<(), E>
    where
        Self: 'a,
    {
        doc.iter()
            .try_for_each(|lib: &Animation| lib.sampler.iter().try_for_each(&mut f))
    }
}

impl Sampler {
    /// The input with [`Semantic::Interpolation`].
    pub fn interpolation_input(&self) -> &Input {
        &self.inputs[self.interpolation]
    }
}