Skip to content

Instantly share code, notes, and snippets.

@afonsolage
Created August 14, 2021 10:01
Show Gist options
  • Save afonsolage/5f4e848f8497a5bf702b686613d93f0a to your computer and use it in GitHub Desktop.
Save afonsolage/5f4e848f8497a5bf702b686613d93f0a to your computer and use it in GitHub Desktop.
use bevy::{prelude::*, render::{mesh::Indices, pipeline::{PipelineDescriptor, PrimitiveTopology, RenderPipeline}, shader::{ShaderStage, ShaderStages}}};
/// This example illustrates how to add a custom attribute to a mesh and use it in a custom shader.
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.run();
}
const VERTEX_SHADER: &str = r#"
#version 450
layout(location = 0) in vec3 Vertex_Position;
layout(set = 0, binding = 0) uniform CameraViewProj {
mat4 ViewProj;
};
layout(set = 1, binding = 0) uniform Transform {
mat4 Model;
};
void main() {
gl_Position = ViewProj * Model * vec4(Vertex_Position, 1.0);
}
"#;
const FRAGMENT_SHADER: &str = r#"
#version 450
layout(location = 0) out vec4 o_Target;
void main() {
o_Target = vec4(0.6, 0.4, 0.2, 1.0);
}
"#;
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut pipelines: ResMut<Assets<PipelineDescriptor>>,
mut shaders: ResMut<Assets<Shader>>,
) {
// Create a new shader pipeline
let pipeline_handle = pipelines.add(PipelineDescriptor::default_config(ShaderStages {
vertex: shaders.add(Shader::from_glsl(ShaderStage::Vertex, VERTEX_SHADER)),
fragment: Some(shaders.add(Shader::from_glsl(ShaderStage::Fragment, FRAGMENT_SHADER))),
}));
let v_arr = vec![
[-0.5, -0.5, -0.5],
[0.5, -0.5, -0.5],
[0.5, 0.5, -0.5],
[-0.5, 0.5, -0.5],
];
let v_f32 = vec![
-0.5, -0.5, -0.5,
0.5, -0.5, -0.5,
0.5, 0.5, -0.5,
-0.5, 0.5, -0.5,
];
let indices = vec![0, 1, 2, 2, 3, 0];
let mut mesh = Mesh::new(PrimitiveTopology::TriangleList);
mesh.set_indices(Some(Indices::U32(indices)));
mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, v_f32); //Change from v_f32 to v_arr to render the plane
// plane
commands.spawn_bundle(MeshBundle {
mesh: meshes.add(mesh),
render_pipelines: RenderPipelines::from_pipelines(vec![RenderPipeline::new(
pipeline_handle,
)]),
..Default::default()
});
// camera
commands.spawn_bundle(PerspectiveCameraBundle {
transform: Transform::from_xyz(3.0, 5.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment