Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using Microsoft.Xna.Framework;
- using Microsoft.Xna.Framework.Graphics;
- namespace XXX
- {
- public sealed class Cylinder : MeshPrimitiveBase
- {
- public Cylinder(GraphicsDevice graphicsDevice, Color color)
- : this(graphicsDevice, 1, 1, 32, color)
- {
- }
- public Cylinder(GraphicsDevice graphicsDevice, float height, float diameter, int tessellation, Color color)
- : this(graphicsDevice, height, diameter, diameter, tessellation, color)
- {
- }
- public Cylinder(GraphicsDevice graphicsDevice, float height, float diameterTop, float diameterBottom, int tessellation, Color color)
- : base(graphicsDevice, PrimitiveType.TriangleList)
- {
- Guard.GreaterThan(height, 0, nameof(height));
- Guard.GreaterThan(diameterTop, 0, nameof(diameterTop));
- Guard.GreaterThan(diameterBottom, 0, nameof(diameterBottom));
- Guard.GreaterThan(tessellation, 2, nameof(tessellation));
- CreateMesh(height, diameterTop, diameterBottom, tessellation, color);
- }
- private void CreateMesh(float height, float diameterTop, float diameterBottom, int tessellation, Color color)
- {
- height /= 2;
- var radius1 = diameterTop / 2;
- var radius2 = diameterBottom / 2;
- for (var i = 0; i < tessellation; i++)
- {
- Vector3 normal = GetCircleVector(i, tessellation);
- AddVertex(new VertexPositionColorNormalTexture((normal * radius1) + (Vector3.UnitY * height), color, normal, Vector2.Zero));
- AddVertex(new VertexPositionColorNormalTexture((normal * radius2) - (Vector3.UnitY * height), color, normal, Vector2.Zero));
- AddIndex((i * 2));
- AddIndex(((i * 2) + 1));
- AddIndex(((i * 2) + 2) % (tessellation * 2));
- AddIndex(((i * 2) + 1));
- AddIndex(((i * 2) + 3) % (tessellation * 2));
- AddIndex(((i * 2) + 2) % (tessellation * 2));
- }
- CreateCap(tessellation, height, radius1, color, Vector3.UnitY);
- CreateCap(tessellation, height, radius2, color, -Vector3.UnitY);
- PrepareBuffers();
- }
- private void CreateCap(int tessellation, float height, float radius, Color color, Vector3 normal)
- {
- for (var i = 0; i < tessellation - 2; i++)
- {
- if (normal.Y > 0)
- {
- AddIndex(VerticesCount);
- AddIndex(VerticesCount + ((i + 1) % tessellation));
- AddIndex(VerticesCount + ((i + 2) % tessellation));
- }
- else
- {
- AddIndex(VerticesCount);
- AddIndex(VerticesCount + ((i + 2) % tessellation));
- AddIndex(VerticesCount + ((i + 1) % tessellation));
- }
- }
- for (var i = 0; i < tessellation; i++)
- {
- var position = (GetCircleVector(i, tessellation) * radius) + (normal * height);
- AddVertex(new VertexPositionColorNormalTexture(position, color, normal, Vector2.Zero));
- }
- }
- private static Vector3 GetCircleVector(int i, int tessellation)
- {
- var angle = i * MathHelper.TwoPi / tessellation;
- var dx = (float)Math.Cos(angle);
- var dz = (float)Math.Sin(angle);
- return new Vector3(dx, 0, dz);
- }
- }
- }
Add Comment
Please, Sign In to add comment