-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathmod.rs
1354 lines (1259 loc) · 47.1 KB
/
mod.rs
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#[cfg(feature = "gltf-loader")]
pub(crate) mod load_gltf;
use std::{cmp, fs, io, iter, ops};
use std::borrow::Cow;
use std::collections::hash_map::{Entry, HashMap};
use std::io::Read;
use std::path::{Path, PathBuf};
use cgmath::{Vector3};
use gfx;
use gfx::format::I8Norm;
use gfx::traits::{Factory as Factory_, FactoryExt};
use hub;
use image;
use itertools::Either;
use mint;
use obj;
use animation;
use audio;
use camera::{Camera, Projection, ZRange};
use color::{BLACK, Color};
use geometry::Geometry;
use hub::{Hub, HubPtr, LightData, SubLight, SubNode};
use light::{Ambient, Directional, Hemisphere, Point, ShadowMap};
use material::{self, Material};
use mesh::{DynamicMesh, Mesh};
use object::{self, Group, Object};
use render::{basic_pipe,
BackendFactory, BackendResources, BasicPipelineState, DisplacementContribution,
DynamicData, GpuData, Instance, InstanceCacheKey, PipelineCreationError, ShadowFormat, Source, Vertex,
DEFAULT_VERTEX, VECS_PER_BONE, ZEROED_DISPLACEMENT_CONTRIBUTION,
};
use scene::{Background, Scene};
use sprite::Sprite;
use skeleton::{Bone, Skeleton};
use template::{
InstancedGeometry,
LightTemplate,
SubLightTemplate,
Template,
NodeTemplateData,
};
use text::{Font, Text, TextData};
use texture::{CubeMap, CubeMapPath, FilterMethod, Sampler, Texture, WrapMode};
const TANGENT_X: [I8Norm; 4] = [I8Norm(1), I8Norm(0), I8Norm(0), I8Norm(1)];
const NORMAL_Z: [I8Norm; 4] = [I8Norm(0), I8Norm(0), I8Norm(1), I8Norm(0)];
const QUAD: [Vertex; 4] = [
Vertex {
pos: [-1.0, -1.0, 0.0, 1.0],
uv: [0.0, 0.0],
.. DEFAULT_VERTEX
},
Vertex {
pos: [1.0, -1.0, 0.0, 1.0],
uv: [1.0, 0.0],
.. DEFAULT_VERTEX
},
Vertex {
pos: [-1.0, 1.0, 0.0, 1.0],
uv: [0.0, 1.0],
.. DEFAULT_VERTEX
},
Vertex {
pos: [1.0, 1.0, 0.0, 1.0],
uv: [1.0, 1.0],
.. DEFAULT_VERTEX
},
];
/// Mapping writer.
pub type MapVertices<'a> = gfx::mapping::Writer<'a, BackendResources, Vertex>;
/// `Factory` is used to instantiate game objects.
pub struct Factory {
pub(crate) backend: BackendFactory,
hub: HubPtr,
quad_buf: gfx::handle::Buffer<BackendResources, Vertex>,
texture_cache: HashMap<PathBuf, Texture<[f32; 4]>>,
default_sampler: gfx::handle::Sampler<BackendResources>,
}
fn f2i(x: f32) -> I8Norm {
I8Norm(cmp::min(cmp::max((x * 127.0) as isize, -128), 127) as i8)
}
impl Factory {
fn create_instance_buffer(&mut self) -> gfx::handle::Buffer<BackendResources, Instance> {
// TODO: Better error handling
self.backend
.create_buffer(
1,
gfx::buffer::Role::Vertex,
gfx::memory::Usage::Dynamic,
gfx::memory::Bind::TRANSFER_DST,
)
.unwrap()
}
fn create_gpu_data(&mut self, geometry: Geometry) -> GpuData {
let vertices = Self::mesh_vertices(&geometry);
let (vbuf, mut slice) = if geometry.faces.is_empty() {
self.backend.create_vertex_buffer_with_slice(&vertices, ())
} else {
let faces: &[u32] = gfx::memory::cast_slice(&geometry.faces);
self.backend
.create_vertex_buffer_with_slice(&vertices, faces)
};
slice.instances = Some((1, 0));
let num_shapes = geometry.shapes.len();
let mut displacement_contributions = Vec::with_capacity(num_shapes);
let instances = self.create_instance_buffer();
let displacements = if num_shapes != 0 {
let num_vertices = geometry.base.vertices.len();
let mut contents = vec![[0.0; 4]; num_shapes * 3 * num_vertices];
for (content_chunk, shape) in contents.chunks_mut(3 * num_vertices).zip(&geometry.shapes) {
let mut contribution = DisplacementContribution::ZERO;
if !shape.vertices.is_empty() {
contribution.position = 1.0;
for (out, v) in content_chunk[0 * num_vertices .. 1 * num_vertices].iter_mut().zip(&shape.vertices) {
*out = [v.x, v.y, v.z, 1.0];
}
}
if !shape.normals.is_empty() {
contribution.normal = 1.0;
for (out, v) in content_chunk[1 * num_vertices .. 2 * num_vertices].iter_mut().zip(&shape.normals) {
*out = [v.x, v.y, v.z, 0.0];
}
}
if !shape.tangents.is_empty() {
contribution.tangent = 1.0;
for (out, &v) in content_chunk[2 * num_vertices .. 3 * num_vertices].iter_mut().zip(&shape.tangents) {
*out = v.into();
}
}
displacement_contributions.push(contribution);
}
let texture_and_view = self.backend
.create_texture_immutable::<[f32; 4]>(
gfx::texture::Kind::D2(
num_vertices as _,
3 * num_shapes as gfx::texture::Size,
gfx::texture::AaMode::Single,
),
gfx::texture::Mipmap::Provided,
&[gfx::memory::cast_slice(&contents)],
)
.unwrap();
Some(texture_and_view)
} else {
None
};
GpuData {
slice,
vertices: vbuf,
instances,
displacements,
pending: None,
instance_cache_key: None,
displacement_contributions,
}
}
pub(crate) fn new(mut backend: BackendFactory) -> Self {
let quad_buf = backend.create_vertex_buffer(&QUAD);
let default_sampler = backend.create_sampler_linear();
Factory {
backend: backend,
hub: Hub::new(),
quad_buf,
texture_cache: HashMap::new(),
default_sampler: default_sampler,
}
}
/// Create new empty [`Scene`](struct.Scene.html).
pub fn scene(&mut self) -> Scene {
let hub = self.hub.clone();
let background = Background::Color(BLACK);
Scene {
hub,
first_child: None,
background,
}
}
/// Creates an instance of all the objects described in the template.
///
/// Returns a [`Group`] that is the root object for all objects created from the template, as
/// well as a list of all animation clips instantiated from the template.
///
/// See the module documentation for [`template`] for more information on the template
/// system.
///
/// # Examples
///
/// Create an empty template and then instantiate it, effectively the most verbose way to
/// call [`Factory::group`]:
///
/// ```no_run
/// use three::template::Template;
///
/// # let mut window = three::Window::new("Three-rs");
/// let template = Template::new();
/// let (group, animations) = window.factory.instantiate_template(&template);
/// ```
///
/// [`Group`]: ./struct.Group.html
/// [`template`]: ./template/index.html
/// [`Factory::group`]: #method.group
pub fn instantiate_template(&mut self, template: &Template) -> (Group, Vec<animation::Clip>) {
// Create group to act as the root node of the instantiated hierarchy.
let root = self.group();
// Create collections for different types of objects that will need to be re-used later.
// Since all nodes in the template are kept in a flat list, we must first instantiate all
// the objects, then we can later hook up any places where one object wants to reference
// another object.
let mut nodes = HashMap::with_capacity(template.nodes.len());
let mut groups = HashMap::new();
let mut bones = HashMap::new();
let mut skinned_meshes = Vec::new();
// For each of the nodes, instantiate the correct type of object, add that object to the
// collection for its type, then set the local transform for the node and add it to the
// list of all nodes.
for (index, node) in template.nodes.iter().enumerate() {
let base = match node.data {
NodeTemplateData::Mesh(mesh_index) => {
let mesh_template = &template.meshes[mesh_index];
let material = template.materials[mesh_template.material].clone();
let mesh = self.create_instanced_mesh(&mesh_template.geometry, material);
mesh.upcast()
}
NodeTemplateData::SkinnedMesh { mesh, skeleton } => {
let mesh_template = &template.meshes[mesh];
let material = template.materials[mesh_template.material].clone();
let mesh = self.create_instanced_mesh(&mesh_template.geometry, material);
skinned_meshes.push((mesh.clone(), skeleton));
mesh.upcast()
}
NodeTemplateData::Group(_) => {
let group = self.group();
groups.insert(index, group.clone());
group.upcast()
}
NodeTemplateData::Camera(camera_index) => {
let projection = template.cameras[camera_index].clone();
let camera = self.camera(projection);
camera.upcast()
}
NodeTemplateData::Bone(bone_index, inverse_bind_matrix) => {
let bone = self.bone(bone_index, inverse_bind_matrix);
bones.insert(index, bone.clone());
bone.upcast()
}
NodeTemplateData::Light(light_template) => {
let LightTemplate {
color,
intensity,
sub_light,
} = template.lights[light_template];
match sub_light {
SubLightTemplate::Ambient =>
self.ambient_light(color, intensity).upcast(),
SubLightTemplate::Directional =>
self.directional_light(color, intensity).upcast(),
SubLightTemplate::Hemisphere { ground } =>
self.hemisphere_light(color, ground, intensity).upcast(),
SubLightTemplate::Point =>
self.point_light(color, intensity).upcast(),
}
}
// NOTE: We defer the creation of skeleton nodes until all other nodes
// have been created, because we need all of the skeleton's bones to have been
// instantiated before we can instantiate the skeleton. Skeletons are
// instantiated immediately following all other nodes, so they will still be
// created before anything tries to reference one (e.g. skinned meshes,
// animations, etc.).
NodeTemplateData::Skeleton(..) => { continue; }
};
// Set the node's transform.
base.set_transform(node.translation, node.rotation, node.scale);
// Add the node to the list of nodes.
nodes.insert(index, base);
}
// Instantiate skeleton nodes once all other nodes have been instantiated.
let mut skeletons = HashMap::new();
for (index, node) in template.nodes.iter().enumerate() {
if let NodeTemplateData::Skeleton(ref bone_indices) = node.data {
let bones = bone_indices
.iter()
.map(|index| bones[index].clone())
.collect();
let skeleton = self.skeleton(bones);
skeleton.set_transform(node.translation, node.rotation, node.scale);
nodes.insert(index, skeleton.upcast());
skeletons.insert(index, skeleton);
}
}
// Once skeletons have been instantiated, setup each skinned mesh with its skeleton.
for (mut mesh, skeleton_index) in skinned_meshes {
mesh.set_skeleton(skeletons[&skeleton_index].clone());
}
// Instantiate all animation clips in the template.
let animations = template
.animations
.iter()
.map(|animation| {
let tracks = animation
.tracks
.iter()
.map(|&(ref track, target)| (track.clone(), nodes[&target].upcast()))
.collect();
animation::Clip {
name: template.name.clone(),
tracks,
}
})
.collect();
// Add each of the root nodes to the root group.
for root_index in &template.roots {
root.add(&nodes[root_index]);
}
// Add children to their parents.
for (&index, group) in &groups {
// Retrieve the list of children from the template node.
let node = &template.nodes[index];
let children = match node.data {
NodeTemplateData::Group(ref children) => children,
_ => panic!(
"Node with index {} does not correspond to a `Group` node: {:?}",
index,
node,
),
};
for child_index in children {
let child = &nodes[child_index];
group.add(child);
}
}
(root, animations)
}
/// Create a new [`Bone`], one component of a [`Skeleton`].
///
/// [`Bone`]: ../skeleton/struct.Bone.html
/// [`Skeleton`]: ../skeleton/struct.Skeleton.html
pub fn bone(
&mut self,
index: usize,
inverse_bind_matrix: mint::ColumnMatrix4<f32>,
) -> Bone {
let data = SubNode::Bone { index, inverse_bind_matrix };
let object = self.hub.lock().unwrap().spawn(data);
Bone { object }
}
/// Create a new [`Skeleton`] from a set of [`Bone`] instances.
///
/// * `bones` is the array of bones that form the skeleton.
/// * `inverses` is an optional array of inverse bind matrices for each bone.
/// [`Skeleton`]: ../skeleton/struct.Skeleton.html
/// [`Bone`]: ../skeleton/struct.Bone.html
pub fn skeleton(
&mut self,
bones: Vec<Bone>,
) -> Skeleton {
let gpu_buffer = self.backend
.create_buffer(
bones.len() * VECS_PER_BONE,
gfx::buffer::Role::Constant,
gfx::memory::Usage::Dynamic,
gfx::memory::Bind::SHADER_RESOURCE,
)
.expect("create GPU target buffer");
let gpu_buffer_view = self.backend
.view_buffer_as_shader_resource(&gpu_buffer)
.expect("create shader resource view for GPU target buffer");
let data = hub::SkeletonData { bones, gpu_buffer, gpu_buffer_view };
let object = self.hub.lock().unwrap().spawn_skeleton(data);
Skeleton { object }
}
/// Create a new camera using the provided projection.
///
/// This allows you to create a camera from a predefined projection, which is useful if you
/// e.g. load projection data from a file and don't necessarily know ahead of time what type
/// of projection the camera uses. If you're manually creating a camera, you should use
/// [`perspective_camera`] or [`orthographic_camera`].
pub fn camera<P: Into<Projection>>(&mut self, projection: P) -> Camera {
Camera::new(
&mut *self.hub.lock().unwrap(),
projection.into(),
)
}
/// Create new [Orthographic] Camera.
/// It's used to render 2D.
///
/// [Orthographic]: https://en.wikipedia.org/wiki/Orthographic_projection
pub fn orthographic_camera<P: Into<mint::Point2<f32>>>(
&mut self,
center: P,
extent_y: f32,
range: ops::Range<f32>,
) -> Camera {
Camera::new(
&mut *self.hub.lock().unwrap(),
Projection::orthographic(center, extent_y, range),
)
}
/// Create new [Perspective] Camera.
///
/// It's used to render 3D.
///
/// # Examples
///
/// Creating a finite perspective camera.
///
/// ```rust,no_run
/// # #![allow(unreachable_code, unused_variables)]
/// # let mut factory: three::Factory = unimplemented!();
/// let camera = factory.perspective_camera(60.0, 0.1 .. 1.0);
/// ```
///
/// Creating an infinite perspective camera.
///
/// ```rust,no_run
/// # #![allow(unreachable_code, unused_variables)]
/// # let mut factory: three::Factory = unimplemented!();
/// let camera = factory.perspective_camera(60.0, 0.1 ..);
/// ```
///
/// [Perspective]: https://en.wikipedia.org/wiki/Perspective_(graphical)
pub fn perspective_camera<R: Into<ZRange>>(
&mut self,
fov_y: f32,
range: R,
) -> Camera {
Camera::new(
&mut *self.hub.lock().unwrap(),
Projection::perspective(fov_y, range),
)
}
/// Create empty [`Group`](struct.Group.html).
pub fn group(&mut self) -> object::Group {
object::Group::new(&mut *self.hub.lock().unwrap())
}
fn mesh_vertices(geometry: &Geometry) -> Vec<Vertex> {
let position_iter = geometry.base.vertices.iter();
let normal_iter = if geometry.base.normals.is_empty() {
Either::Left(iter::repeat(NORMAL_Z))
} else {
Either::Right(
geometry.base.normals
.iter()
.map(|n| [f2i(n.x), f2i(n.y), f2i(n.z), I8Norm(0)]),
)
};
let uv_iter = if geometry.tex_coords.is_empty() {
Either::Left(iter::repeat([0.0, 0.0]))
} else {
Either::Right(geometry.tex_coords.iter().map(|uv| [uv.x, uv.y]))
};
let tangent_iter = if geometry.base.tangents.is_empty() {
// TODO: Generate tangents if texture coordinates are provided.
// (Use mikktspace algorithm or otherwise.)
Either::Left(iter::repeat(TANGENT_X))
} else {
Either::Right(
geometry.base.tangents
.iter()
.map(|t| [f2i(t.x), f2i(t.y), f2i(t.z), f2i(t.w)]),
)
};
let joint_indices_iter = if geometry.joints.indices.is_empty() {
Either::Left(iter::repeat([0, 0, 0, 0]))
} else {
Either::Right(geometry.joints.indices.iter().cloned())
};
let joint_weights_iter = if geometry.joints.weights.is_empty() {
Either::Left(iter::repeat([1.0, 1.0, 1.0, 1.0]))
} else {
Either::Right(geometry.joints.weights.iter().cloned())
};
izip!(
position_iter,
normal_iter,
tangent_iter,
uv_iter,
joint_indices_iter,
joint_weights_iter,
)
.map(|(pos, normal, tangent, uv, joint_indices, joint_weights)| {
Vertex {
pos: [pos.x, pos.y, pos.z, 1.0],
normal,
uv,
tangent,
joint_indices,
joint_weights,
}
})
.collect()
}
/// Uploads geometry data to the GPU so that it can be reused for instanced rendering.
///
/// See the module documentation in [`template`] for information on mesh instancing and
/// its benefits.
///
/// # Examples
///
/// ```no_run
/// use three::Geometry;
///
/// # let mut window = three::Window::new("Three-rs");
/// // Create geometry for a triangle.
/// let vertices = vec![
/// [-0.5, -0.5, -0.5].into(),
/// [0.5, -0.5, -0.5].into(),
/// [0.0, 0.5, -0.5].into(),
/// ];
/// let geometry = Geometry::with_vertices(vertices);
///
/// // Upload the triangle data to the GPU.
/// let upload_geometry = window.factory.upload_geometry(geometry);
///
/// // Create multiple meshes with the same GPU data and material.
/// let material = three::material::Basic {
/// color: 0xFFFF00,
/// map: None,
/// };
/// let first = window.factory.create_instanced_mesh(&upload_geometry, material.clone());
/// let second = window.factory.create_instanced_mesh(&upload_geometry, material.clone());
/// let third = window.factory.create_instanced_mesh(&upload_geometry, material.clone());
/// ```
///
/// [`template`]: ./template/index.html#mesh-instancing
pub fn upload_geometry(
&mut self,
geometry: Geometry,
) -> InstancedGeometry {
let gpu_data = self.create_gpu_data(geometry);
InstancedGeometry { gpu_data }
}
/// Create new `Mesh` with desired `Geometry` and `Material`.
pub fn mesh<M: Into<Material>>(
&mut self,
geometry: Geometry,
material: M,
) -> Mesh {
let gpu_data = self.create_gpu_data(geometry);
Mesh {
object: self.hub.lock().unwrap().spawn_visual(
material.into(),
gpu_data,
None,
),
}
}
/// Creates a [`Mesh`] using geometry that has already been loaded to the GPU.
///
/// See the module documentation in [`template`] for information on mesh instancing and
/// its benefits.
///
/// # Examples
///
/// ```no_run
/// use three::Geometry;
///
/// # let mut window = three::Window::new("Three-rs");
/// // Create geometry for a triangle.
/// let vertices = vec![
/// [-0.5, -0.5, -0.5].into(),
/// [0.5, -0.5, -0.5].into(),
/// [0.0, 0.5, -0.5].into(),
/// ];
/// let geometry = Geometry::with_vertices(vertices);
///
/// // Upload the triangle data to the GPU.
/// let upload_geometry = window.factory.upload_geometry(geometry);
///
/// // Create multiple meshes with the same GPU data and material.
/// let material = three::material::Basic {
/// color: 0xFFFF00,
/// map: None,
/// };
/// let first = window.factory.create_instanced_mesh(&upload_geometry, material.clone());
/// let second = window.factory.create_instanced_mesh(&upload_geometry, material.clone());
/// let third = window.factory.create_instanced_mesh(&upload_geometry, material.clone());
/// ```
///
/// [`Mesh`]: ./struct.Mesh.html
/// [`template`]: ./template/index.html#mesh-instancing
pub fn create_instanced_mesh<M: Into<Material>>(
&mut self,
geometry: &InstancedGeometry,
material: M,
) -> Mesh {
// Create a clone of the geometry for this mesh.
let mut gpu_data = geometry.gpu_data.clone();
let material = material.into();
// Setup the GPU data for instanced rendering.
gpu_data.instance_cache_key = Some(InstanceCacheKey {
geometry: gpu_data.vertices.clone(),
material: material.clone(),
});
Mesh {
object: self.hub.lock().unwrap().spawn_visual(
material,
gpu_data,
None,
),
}
}
/// Create a new `DynamicMesh` with desired `Geometry` and `Material`.
pub fn mesh_dynamic<M: Into<Material>>(
&mut self,
geometry: Geometry,
material: M,
) -> DynamicMesh {
let slice = {
let data: &[u32] = gfx::memory::cast_slice(&geometry.faces);
gfx::Slice {
start: 0,
end: data.len() as u32,
base_vertex: 0,
instances: Some((1, 0)),
buffer: self.backend.create_index_buffer(data),
}
};
let (num_vertices, vertices, upload_buf) = {
let data = Self::mesh_vertices(&geometry);
let dest_buf = self.backend
.create_buffer_immutable(&data, gfx::buffer::Role::Vertex, gfx::memory::Bind::TRANSFER_DST)
.unwrap();
let upload_buf = self.backend.create_upload_buffer(data.len()).unwrap();
// TODO: Workaround for not having a 'write-to-slice' capability.
// Reason: The renderer copies the entire staging buffer upon updates.
{
self.backend
.write_mapping(&upload_buf)
.unwrap()
.copy_from_slice(&data);
}
(data.len(), dest_buf, upload_buf)
};
let instances = self.create_instance_buffer();
DynamicMesh {
object: self.hub.lock().unwrap().spawn_visual(
material.into(),
GpuData {
slice,
vertices,
instances,
displacements: None,
pending: None,
instance_cache_key: None,
displacement_contributions: ZEROED_DISPLACEMENT_CONTRIBUTION.to_vec(),
},
None,
),
geometry,
dynamic: DynamicData {
num_vertices,
buffer: upload_buf,
},
}
}
/// Create a `Mesh` sharing the geometry with another one.
/// Rendering a sequence of meshes with the same geometry is faster.
/// The material is duplicated from the template.
pub fn mesh_instance(
&mut self,
template: &Mesh,
) -> Mesh {
let instances = self.create_instance_buffer();
let mut hub = self.hub.lock().unwrap();
let (material, gpu_data) = match hub[template].sub_node {
SubNode::Visual(ref mat, ref gpu, _) => {
(mat.clone(), GpuData {
instances,
instance_cache_key: Some(InstanceCacheKey {
material: mat.clone(),
geometry: gpu.vertices.clone(),
}),
..gpu.clone()
})
}
_ => unreachable!(),
};
Mesh {
object: hub.spawn_visual(material, gpu_data, None),
}
}
/// Create a `Mesh` sharing the geometry with another one but with a different material.
/// Rendering a sequence of meshes with the same geometry is faster.
pub fn mesh_instance_with_material<M: Into<Material>>(
&mut self,
template: &Mesh,
material: M,
) -> Mesh {
let instances = self.create_instance_buffer();
let material = material.into();
let mut hub = self.hub.lock().unwrap();
let gpu_data = match hub[template].sub_node {
SubNode::Visual(_, ref gpu, _) => GpuData {
instances,
instance_cache_key: Some(InstanceCacheKey {
material: material.clone(),
geometry: gpu.vertices.clone(),
}),
..gpu.clone()
},
_ => unreachable!(),
};
Mesh {
object: hub.spawn_visual(material, gpu_data, None),
}
}
/// Create new sprite from `Material`.
pub fn sprite(
&mut self,
material: material::Sprite,
) -> Sprite {
let instances = self.create_instance_buffer();
let mut slice = gfx::Slice::new_match_vertex_buffer(&self.quad_buf);
slice.instances = Some((1, 0));
let material = Material::from(material);
Sprite::new(self.hub.lock().unwrap().spawn_visual(
material,
GpuData {
slice,
vertices: self.quad_buf.clone(),
instances,
displacements: None,
pending: None,
instance_cache_key: None,
displacement_contributions: ZEROED_DISPLACEMENT_CONTRIBUTION.to_vec(),
},
None,
))
}
/// Create a `Sprite` sharing the material with another one.
/// Rendering a sequence of instanced sprites is much faster.
pub fn sprite_instance(
&mut self,
template: &Sprite,
) -> Sprite {
let instances = self.create_instance_buffer();
let mut hub = self.hub.lock().unwrap();
let (material, gpu_data) = match hub[template].sub_node {
SubNode::Visual(ref mat, ref gpu, _) => {
(mat.clone(), GpuData {
instances,
instance_cache_key: Some(InstanceCacheKey {
material: mat.clone(),
geometry: self.quad_buf.clone(),
}),
..gpu.clone()
})
}
_ => unreachable!(),
};
Sprite::new(hub.spawn_visual(material, gpu_data, None))
}
/// Create new `AmbientLight`.
pub fn ambient_light(
&mut self,
color: Color,
intensity: f32,
) -> Ambient {
Ambient::new(self.hub.lock().unwrap().spawn_light(LightData {
color,
intensity,
sub_light: SubLight::Ambient,
shadow: None,
}))
}
/// Create new `DirectionalLight`.
pub fn directional_light(
&mut self,
color: Color,
intensity: f32,
) -> Directional {
Directional::new(self.hub.lock().unwrap().spawn_light(LightData {
color,
intensity,
sub_light: SubLight::Directional,
shadow: None,
}))
}
/// Create new `HemisphereLight`.
pub fn hemisphere_light(
&mut self,
sky_color: Color,
ground_color: Color,
intensity: f32,
) -> Hemisphere {
Hemisphere::new(self.hub.lock().unwrap().spawn_light(LightData {
color: sky_color,
intensity,
sub_light: SubLight::Hemisphere {
ground: ground_color,
},
shadow: None,
}))
}
/// Create new `PointLight`.
pub fn point_light(
&mut self,
color: Color,
intensity: f32,
) -> Point {
Point::new(self.hub.lock().unwrap().spawn_light(LightData {
color,
intensity,
sub_light: SubLight::Point,
shadow: None,
}))
}
/// Create a `Sampler` with default properties.
///
/// The default sampler has `Clamp` as its horizontal and vertical
/// wrapping mode and `Scale` as its filtering method.
pub fn default_sampler(&self) -> Sampler {
Sampler(self.default_sampler.clone())
}
/// Create new `Sampler`.
pub fn sampler(
&mut self,
filter_method: FilterMethod,
horizontal_wrap_mode: WrapMode,
vertical_wrap_mode: WrapMode,
) -> Sampler {
use gfx::texture::Lod;
let info = gfx::texture::SamplerInfo {
filter: filter_method,
wrap_mode: (horizontal_wrap_mode, vertical_wrap_mode, WrapMode::Clamp),
lod_bias: Lod::from(0.0),
lod_range: (Lod::from(-8000.0), Lod::from(8000.0)),
comparison: None,
border: gfx::texture::PackedColor(0),
};
let inner = self.backend.create_sampler(info);
Sampler(inner)
}
/// Create new `ShadowMap`.
pub fn shadow_map(
&mut self,
width: u16,
height: u16,
) -> ShadowMap {
let (_, resource, target) = self.backend
.create_depth_stencil::<ShadowFormat>(width, height)
.unwrap();
ShadowMap { resource, target }
}
/// Create a basic mesh pipeline using a custom shader.
pub fn basic_pipeline<P: AsRef<Path>>(
&mut self,
dir: P,
name: &str,
primitive: gfx::Primitive,
rasterizer: gfx::state::Rasterizer,
color_mask: gfx::state::ColorMask,
blend_state: gfx::state::Blend,
depth_state: gfx::state::Depth,
stencil_state: gfx::state::Stencil,
) -> Result<BasicPipelineState, PipelineCreationError> {
use gfx::traits::FactoryExt;
let vs = Source::user(&dir, name, "vs")?;
let ps = Source::user(&dir, name, "ps")?;
let shaders = self.backend
.create_shader_set(vs.0.as_bytes(), ps.0.as_bytes())?;
let init = basic_pipe::Init {
out_color: ("Target0", color_mask, blend_state),
out_depth: (depth_state, stencil_state),
..basic_pipe::new()
};
let pso = self.backend
.create_pipeline_state(&shaders, primitive, rasterizer, init)?;
Ok(pso)
}
/// Create new UI (on-screen) text. See [`Text`](struct.Text.html) for default settings.
pub fn ui_text<S: Into<String>>(
&mut self,
font: &Font,
text: S,
) -> Text {
let sub = SubNode::UiText(TextData::new(font, text));
let object = self.hub.lock().unwrap().spawn(sub);
Text::with_object(object)
}
/// Create new audio source.
pub fn audio_source(&mut self) -> audio::Source {
let sub = SubNode::Audio(audio::AudioData::new());
let object = self.hub.lock().unwrap().spawn(sub);
audio::Source::with_object(object)
}
/// Map vertices for updating their data.
pub fn map_vertices<'a>(
&'a mut self,
mesh: &'a mut DynamicMesh,
) -> MapVertices<'a> {
self.hub.lock().unwrap().update_mesh(mesh);
self.backend.write_mapping(&mesh.dynamic.buffer).unwrap()
}
/// Interpolate between the shapes of a `DynamicMesh`.
pub fn mix(
&mut self,
mesh: &DynamicMesh,
shapes: &[(usize, f32)],
) {
self.hub.lock().unwrap().update_mesh(mesh);
let mut mapping = self.backend.write_mapping(&mesh.dynamic.buffer).unwrap();
let n = mesh.geometry.base.vertices.len();
for i in 0 .. n {
let (mut pos, ksum) = shapes.iter().fold(
(Vector3::new(0.0, 0.0, 0.0), 0.0),
|(pos, ksum), &(idx, k)| {
let p: [f32; 3] = mesh.geometry.shapes[idx].vertices[i].into();
(pos + k * Vector3::from(p), ksum + k)
},
);
if ksum != 1.0 {
let p: [f32; 3] = mesh.geometry.base.vertices[i].into();
pos += (1.0 - ksum) * Vector3::from(p);
}
mapping[i] = Vertex {
pos: [pos.x, pos.y, pos.z, 1.0],
.. mapping[i]
};
}
}
/// Load TrueTypeFont (.ttf) from file.
/// #### Panics
/// Panics if I/O operations with file fails (e.g. file not found or corrupted)
pub fn load_font<P: AsRef<Path>>(
&mut self,
file_path: P,