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
use std::fmt::Debug;
use std::result::Result as StdResult;

use amethyst_assets::{Asset, AssetStorage, Error, Loader, PrefabData, PrefabError,
                      ProcessingState, Result, ResultExt, SimpleFormat};
use amethyst_core::cgmath::{InnerSpace, Vector3};
use amethyst_core::specs::prelude::{Entity, Read, ReadExpect, VecStorage, WriteStorage};
use wavefront_obj::obj::{parse, Normal, NormalIndex, ObjSet, Object, Primitive, TVertex,
                         TextureIndex, Vertex, VertexIndex};

use mesh::{Mesh, MeshBuilder, MeshHandle};
use vertex::*;
use Renderer;

/// Mesh data for loading
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MeshData {
    /// Position and color
    PosColor(Vec<PosColor>),

    /// Position and texture coordinates
    PosTex(Vec<PosTex>),

    /// Position, normal and texture coordinates
    PosNormTex(Vec<PosNormTex>),

    /// Position, normal, tangent and texture coordinates
    PosNormTangTex(Vec<PosNormTangTex>),

    /// Create a mesh from a given creator
    #[serde(skip)]
    Creator(Box<MeshCreator>),
}

impl From<Vec<PosColor>> for MeshData {
    fn from(data: Vec<PosColor>) -> Self {
        MeshData::PosColor(data)
    }
}

impl From<Vec<PosTex>> for MeshData {
    fn from(data: Vec<PosTex>) -> Self {
        MeshData::PosTex(data)
    }
}

impl From<Vec<PosNormTex>> for MeshData {
    fn from(data: Vec<PosNormTex>) -> Self {
        MeshData::PosNormTex(data)
    }
}

impl From<Vec<PosNormTangTex>> for MeshData {
    fn from(data: Vec<PosNormTangTex>) -> Self {
        MeshData::PosNormTangTex(data)
    }
}

impl<M> From<M> for MeshData
where
    M: MeshCreator,
{
    fn from(creator: M) -> Self {
        MeshData::Creator(Box::new(creator))
    }
}

impl Asset for Mesh {
    const NAME: &'static str = "renderer::Mesh";
    type Data = MeshData;
    type HandleStorage = VecStorage<MeshHandle>;
}

impl<'a> PrefabData<'a> for MeshData {
    type SystemData = (
        ReadExpect<'a, Loader>,
        WriteStorage<'a, MeshHandle>,
        Read<'a, AssetStorage<Mesh>>,
    );
    type Result = ();

    fn load_prefab(
        &self,
        entity: Entity,
        system_data: &mut Self::SystemData,
        _: &[Entity],
    ) -> StdResult<(), PrefabError> {
        let handle = system_data
            .0
            .load_from_data(self.clone(), (), &system_data.2);
        system_data.1.insert(entity, handle).map(|_| ())
    }
}

/// Allows loading from Wavefront files
/// see: https://en.wikipedia.org/wiki/Wavefront_.obj_file
#[derive(Clone, Deserialize, Serialize)]
pub struct ObjFormat;

impl SimpleFormat<Mesh> for ObjFormat {
    const NAME: &'static str = "WAVEFRONT_OBJ";

    type Options = ();

    fn import(&self, bytes: Vec<u8>, _: ()) -> Result<MeshData> {
        String::from_utf8(bytes)
            .map_err(Into::into)
            .and_then(|string| {
                parse(string)
                    .map_err(|e| Error::from(format!("In line {}: {:?}", e.line_number, e.message)))
                    .chain_err(|| "Failed to parse OBJ")
            })
            .map(|set| from_data(set).into())
    }
}

fn convert(
    object: &Object,
    vi: VertexIndex,
    ti: Option<TextureIndex>,
    ni: Option<NormalIndex>,
) -> PosNormTex {
    PosNormTex {
        position: {
            let vertex: Vertex = object.vertices[vi];
            [vertex.x as f32, vertex.y as f32, vertex.z as f32]
        },
        normal: ni.map(|i| {
            let normal: Normal = object.normals[i];
            Vector3::from([normal.x as f32, normal.y as f32, normal.z as f32])
                .normalize()
                .into()
        }).unwrap_or([0.0, 0.0, 0.0]),
        tex_coord: ti.map(|i| {
            let tvertex: TVertex = object.tex_vertices[i];
            [tvertex.u as f32, tvertex.v as f32]
        }).unwrap_or([0.0, 0.0]),
    }
}

fn convert_primitive(object: &Object, prim: &Primitive) -> Option<[PosNormTex; 3]> {
    match *prim {
        Primitive::Triangle(v1, v2, v3) => Some([
            convert(object, v1.0, v1.1, v1.2),
            convert(object, v2.0, v2.1, v2.2),
            convert(object, v3.0, v3.1, v3.2),
        ]),
        _ => None,
    }
}

fn from_data(obj_set: ObjSet) -> Vec<PosNormTex> {
    // Takes a list of objects that contain geometries that contain shapes that contain
    // vertex/texture/normal indices into the main list of vertices, and converts to a
    // flat vec of `PosNormTex` objects.
    // TODO: Doesn't differentiate between objects in a `*.obj` file, treats
    // them all as a single mesh.
    let vertices = obj_set.objects.iter().flat_map(|object| {
        object.geometry.iter().flat_map(move |geometry| {
            geometry
                .shapes
                .iter()
                .filter_map(move |s| convert_primitive(object, &s.primitive))
        })
    });

    let mut result = Vec::new();
    for vvv in vertices {
        result.push(vvv[0]);
        result.push(vvv[1]);
        result.push(vvv[2]);
    }
    result
}

/// Create mesh
pub fn create_mesh_asset(data: MeshData, renderer: &mut Renderer) -> Result<ProcessingState<Mesh>> {
    let data = match data {
        MeshData::PosColor(ref vertices) => {
            let mb = MeshBuilder::new(vertices);
            renderer.create_mesh(mb)
        }
        MeshData::PosTex(ref vertices) => {
            let mb = MeshBuilder::new(vertices);
            renderer.create_mesh(mb)
        }
        MeshData::PosNormTex(ref vertices) => {
            let mb = MeshBuilder::new(vertices);
            renderer.create_mesh(mb)
        }
        MeshData::PosNormTangTex(ref vertices) => {
            let mb = MeshBuilder::new(vertices);
            renderer.create_mesh(mb)
        }
        MeshData::Creator(creator) => creator.build(renderer),
    };

    data.map(|m| ProcessingState::Loaded(m))
        .chain_err(|| "Failed to build mesh")
}

/// Build Mesh with vertex buffer combination
pub fn build_mesh_with_combo(
    combo: VertexBufferCombination,
    renderer: &mut Renderer,
) -> ::error::Result<Mesh> {
    build_mesh_with_some!(
        MeshBuilder::new(combo.0),
        renderer,
        combo.1,
        combo.2,
        combo.3,
        combo.4
    )
}

/// Trait used by the asset processor to convert any user supplied mesh representation into an
/// actual `Mesh`.
///
/// This allows the user to create their own vertex attributes, and have the amethyst asset and
/// render systems be able to convert it into a `Mesh` that can be used from any applicable
/// pass.
pub trait MeshCreator: Send + Sync + Debug + 'static {
    /// Build a mesh given a `Renderer`
    fn build(self: Box<Self>, renderer: &mut Renderer) -> ::error::Result<Mesh>;

    /// Clone a boxed version of this object
    fn box_clone(&self) -> Box<MeshCreator>;
}

impl Clone for Box<MeshCreator> {
    fn clone(&self) -> Box<MeshCreator> {
        self.box_clone()
    }
}

/// Mesh creator for `VertexBufferCombination`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComboMeshCreator {
    combo: VertexBufferCombination,
}

impl ComboMeshCreator {
    /// Create a new combo mesh creator with the given combo
    pub fn new(combo: VertexBufferCombination) -> Self {
        Self { combo }
    }
}

impl MeshCreator for ComboMeshCreator {
    fn build(self: Box<Self>, renderer: &mut Renderer) -> ::error::Result<Mesh> {
        build_mesh_with_combo(self.combo, renderer)
    }

    fn box_clone(&self) -> Box<MeshCreator> {
        Box::new((*self).clone())
    }
}

impl From<VertexBufferCombination> for ComboMeshCreator {
    fn from(combo: VertexBufferCombination) -> Self {
        Self::new(combo)
    }
}