Пример #1
0
        void CalculateNormals(NodeContent node)
        {
            MeshContent mesh = node as MeshContent;

            if (mesh != null)
            {
                MeshHelper.CalculateNormals(mesh, true);
            }

            foreach (NodeContent child in node.Children)
            {
                CalculateNormals(child);
            }
        }
Пример #2
0
 private void MergeTransforms(NodeContent input)
 {
     if (input is MeshContent)
     {
         MeshContent mc = (MeshContent)input;
         MeshHelper.TransformScene(mc, mc.Transform);
         mc.Transform = Matrix.Identity;
         MeshHelper.OptimizeForCache(mc);
     }
     foreach (NodeContent c in input.Children)
     {
         MergeTransforms(c);
     }
 }
Пример #3
0
        private MyObjectBuilder_VoxelMap BuildAsteroidEntity()
        {
            var filenamepart = Path.GetFileNameWithoutExtension(Filename);
            var filename     = MainViewModel.CreateUniqueVoxelStorageName(filenamepart + MyVoxelMap.V2FileExtension);

            Position = Position.RoundOff(1.0);
            Forward  = Forward.RoundToAxis();
            Up       = Up.RoundToAxis();

            var entity = new MyObjectBuilder_VoxelMap(Position.ToVector3(), filename)
            {
                EntityId        = SpaceEngineersApi.GenerateEntityId(IDType.ASTEROID),
                PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                StorageName     = Path.GetFileNameWithoutExtension(filename)
            };

            double multiplier;

            if (IsMultipleScale)
            {
                multiplier = MultipleScale;
            }
            else
            {
                multiplier = MaxLengthScale / Math.Max(Math.Max(OriginalModelSize.Height, OriginalModelSize.Width), OriginalModelSize.Depth);
            }

            var transform = MeshHelper.TransformVector(new Vector3D(0, 0, 0), 0, 0, 0);

            SourceFile = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);

            var baseMaterial = SpaceEngineersCore.Resources.GetMaterialList().FirstOrDefault(m => m.IsRare == false) ?? SpaceEngineersCore.Resources.GetMaterialList().FirstOrDefault();

            var voxelMap = MyVoxelBuilder.BuildAsteroidFromModel(true, Filename, OutsideStockMaterial.Value, baseMaterial.Id.SubtypeId, InsideStockMaterial.Value != null, InsideStockMaterial.Value, ModelTraceVoxel.ThinSmoothed, multiplier, transform, MainViewModel.ResetProgress, MainViewModel.IncrementProgress);

            voxelMap.Save(SourceFile);

            MainViewModel.ClearProgress();

            entity.PositionAndOrientation = new MyPositionAndOrientation
            {
                Position = Position.ToVector3D(),
                Forward  = Forward.ToVector3(),
                Up       = Up.ToVector3()
            };

            IsValidModel = voxelMap.BoundingContent.Size.Volume > 0f;

            return(entity);
        }
	MeshHelper LoopSubdivide(MeshHelper mesh)
	{
		MeshHelper newMesh = new MeshHelper ();


		// TODO: implement Loop subdivision of mesh here
		foreach (var vertex in mesh.vertices)
		{
		}
		newMesh.triangles = (int[])mesh.triangles.Clone();
		newMesh.vertices = (Vector3[])mesh.vertices.Clone();

		return newMesh;
	}
Пример #5
0
        void FlattenAllTransforms(NodeContent node)
        {
            // Bake the local transform into the actual geometry.
            MeshHelper.TransformScene(node, node.Transform);

            // Having baked it, we can now set the local
            // coordinate system back to identity.
            node.Transform = Matrix.Identity;

            foreach (NodeContent child in node.Children)
            {
                FlattenAllTransforms(child);
            }
        }
Пример #6
0
        /// <summary>
        /// Generate tangents and binormals for the model data at the given node.  Recursively generates for children.
        /// </summary>
        /// <param name="content">The node to process.</param>
        private void GenerateNTBData(NodeContent content)
        {
            MeshContent mesh = content as MeshContent;

            if (mesh != null)
            {
                MeshHelper.CalculateTangentFrames(mesh, VertexChannelNames.TextureCoordinate(0), VertexChannelNames.Tangent(0), VertexChannelNames.Binormal(0));
            }

            foreach (NodeContent child in content.Children)
            {
                GenerateNTBData(child);
            }
        }
        // Normals
        private void GenerateNormals(NodeContent input, ContentProcessorContext context)
        {
            MeshContent mesh = input as MeshContent;

            if (mesh != null)
            {
                MeshHelper.CalculateNormals(mesh, false);
            }

            foreach (NodeContent child in input.Children)
            {
                GenerateNormals(child, context);
            }
        }
        public void TestMergePositionsMultipleGeometries()
        {
            var mb = MeshBuilder.StartMesh("Test");

            mb.CreatePosition(new Vector3(0f, 0f, 0f));
            mb.CreatePosition(new Vector3(1f, 1f, 1f));
            mb.CreatePosition(new Vector3(2f, 2f, 2f));
            mb.CreatePosition(new Vector3(0f, 0f, 0f));
            mb.CreatePosition(new Vector3(1f, 1f, 1f));
            mb.CreatePosition(new Vector3(2f, 2f, 2f));

            mb.SetMaterial(material1);

            mb.AddTriangleVertex(2);
            mb.AddTriangleVertex(1);
            mb.AddTriangleVertex(0);
            mb.AddTriangleVertex(5);
            mb.AddTriangleVertex(4);
            mb.AddTriangleVertex(3);

            mb.SetMaterial(material2);
            mb.AddTriangleVertex(5);
            mb.AddTriangleVertex(4);
            mb.AddTriangleVertex(3);

            var mesh = mb.FinishMesh();

            Assert.AreEqual(6, mesh.Positions.Count);

            MeshHelper.MergeDuplicatePositions(mesh, 1f);
            Assert.AreEqual(3, mesh.Positions.Count);

            var geom = mesh.Geometry[0];

            Assert.AreEqual(6, geom.Vertices.Positions.Count);
            Assert.AreEqual(6, geom.Vertices.PositionIndices.Count);
            Assert.AreEqual(2, geom.Vertices.PositionIndices[0]);
            Assert.AreEqual(1, geom.Vertices.PositionIndices[1]);
            Assert.AreEqual(0, geom.Vertices.PositionIndices[2]);
            Assert.AreEqual(2, geom.Vertices.PositionIndices[0]);
            Assert.AreEqual(1, geom.Vertices.PositionIndices[1]);
            Assert.AreEqual(0, geom.Vertices.PositionIndices[2]);

            geom = mesh.Geometry[1];
            Assert.AreEqual(3, geom.Vertices.Positions.Count);
            Assert.AreEqual(3, geom.Vertices.PositionIndices.Count);
            Assert.AreEqual(2, geom.Vertices.PositionIndices[0]);
            Assert.AreEqual(1, geom.Vertices.PositionIndices[1]);
            Assert.AreEqual(0, geom.Vertices.PositionIndices[2]);
        }
Пример #9
0
 // Update is called once per frame
 void Update()
 {
     if (Input.GetKeyDown("space"))
     {
         Mesh mesh = GetComponent <MeshFilter>().mesh;
         MeshHelper.Subdivide(mesh, 2);
     }
     if (Input.GetKeyDown("return"))
     {
         sortedListOfTrianglesToBeDeleted  = sortedListOfNeighbouringTriangles;
         sortedListOfNeighbouringTriangles = FindNeighbouringTriangles(GetComponent <MeshFilter>().mesh, sortedListOfTrianglesToBeDeleted);
         DestroyTriangles(GetComponent <MeshFilter>().mesh, sortedListOfTrianglesToBeDeleted);
     }
 }
Пример #10
0
    void Start()
    {
        meshfilter = GetComponent <MeshFilter>();
        mesh       = meshfilter.mesh;
        vertices   = mesh.vertices;
        triangles  = mesh.triangles;

        for (int i = 0; i < timesToSubdivide; i++)
        {
            MeshHelper.Subdivide(mesh, subdivision[subdivisionLevel]);
        }
        meshfilter.mesh = mesh;
        vertices        = mesh.vertices;
    }
Пример #11
0
    void Start()
    {
        Mesh mesh = GetComponent <MeshFilter> ().mesh;

        mesh1           = new MeshHelper();
        mesh1.vertices  = mesh.vertices;
        mesh1.triangles = mesh.triangles;
        mesh2           = LoopSubdivide(mesh1);
        mesh3           = LoopSubdivide(mesh2);
        mesh4           = LoopSubdivide(mesh3);


        mesh.RecalculateNormals();
    }
        private void OnModelImporteDialogWindowYes(ModelImportDialogWindow sender)
        {
            EditorUtility.SetDirty(sender.ModelImportData);
            ModelImportDataHelper.SetModelImporterImportSettings(sender.ModelImporter, sender.ModelImportData);
            _state = SkipImportAfterReimportState;
            AssetDatabase.ImportAsset(sender.ModelImporter.assetPath, ImportAssetOptions.ForceUpdate);
            var prefab = PrefabHelper.CreateOrReplacePrefab(sender.ModelPath);

            if (sender.ModelImportData.GenerateMesh)
            {
                MeshHelper.CopyMesh(prefab);
            }
            GenerateAnimatorIfRequired(sender.ModelImporter, sender.ModelImportData);
        }
Пример #13
0
 //  If there are articulating bones above the skinned mesh or skeleton in the mesh,
 //  those will be flattened. Put them further down in the hierarchy if you care.
 protected virtual void BakeTransformsToTop(NodeContent node)
 {
     while (node != null)
     {
         if (!node.Transform.Equals(Matrix.Identity))
         {
             MeshHelper.TransformScene(node, node.Transform);
             node.Transform = Matrix.Identity;
             //  because I baked this node, I can't animate it!
             node.Animations.Clear();
         }
         node = node.Parent;
     }
 }
Пример #14
0
        public void VoxelConvertToVolmeticOdd()
        {
            SpaceEngineersCore.LoadDefinitions();
            var materials = SpaceEngineersCore.Resources.GetMaterialList();

            var stoneMaterial = materials.FirstOrDefault(m => m.Id.SubtypeId.Contains("Stone"));

            Assert.IsNotNull(stoneMaterial, "Stone material should exist.");

            var modelFile       = @".\TestAssets\Sphere_Gold.3ds";
            var scale           = new ScaleTransform3D(5, 5, 5);
            var rotateTransform = MeshHelper.TransformVector(new System.Windows.Media.Media3D.Vector3D(0, 0, 0), 0, 0, 0);
            var traceType       = SEToolbox.Interop.Asteroids.TraceType.Odd;
            var traceCount      = SEToolbox.Interop.Asteroids.TraceCount.Trace5;
            var traceDirection  = SEToolbox.Interop.Asteroids.TraceDirection.XYZ;

            var asteroidFile = @".\TestOutput\test_sphere_odd.vx2";

            var model  = MeshHelper.Load(modelFile, ignoreErrors: true);
            var meshes = new List <SEToolbox.Interop.Asteroids.MyVoxelRayTracer.MyMeshModel>();

            foreach (var model3D in model.Children)
            {
                var gm       = (GeometryModel3D)model3D;
                var geometry = gm.Geometry as MeshGeometry3D;

                if (geometry != null)
                {
                    meshes.Add(new MyVoxelRayTracer.MyMeshModel(new[] { geometry }, stoneMaterial.Id.SubtypeId, stoneMaterial.Id.SubtypeId));
                }
            }

            var voxelMap = MyVoxelRayTracer.ReadModelAsteroidVolmetic(model, meshes, scale, rotateTransform, traceType, traceCount, traceDirection,
                                                                      ResetProgress, IncrementProgress, null, CompleteProgress);

            voxelMap.Save(asteroidFile);

            Assert.IsTrue(File.Exists(asteroidFile), "Generated file must exist");

            var voxelFileLength = new FileInfo(asteroidFile).Length;

            Assert.AreEqual(2133, voxelFileLength, "File size must match.");
            Assert.AreEqual(new Vector3I(64, 64, 64), voxelMap.Size, "Voxel Bounding size must match.");
            Assert.AreEqual(new Vector3I(25, 25, 25), voxelMap.BoundingContent.SizeInt() + 1, "Voxel Content size must match.");

            var voxCells = voxelMap.SumVoxelCells();

            Assert.AreEqual(2031782, voxCells, "Voxel cells must match.");
        }
Пример #15
0
        public override AnimationsContent Process(NodeContent input, ContentProcessorContext context)
        {
            if (_fixRealBoneRoot)
            {
                MGFixRealBoneRoot(input, context);
            }

            ValidateMesh(input, context, null);

            // Find the skeleton.
            BoneContent skeleton = MeshHelper.FindSkeleton(input);

            if (skeleton == null)
            {
                throw new InvalidContentException("Input skeleton not found.");
            }

            // We don't want to have to worry about different parts of the model being
            // in different local coordinate systems, so let's just bake everything.
            FlattenTransforms(input, skeleton);

            // Read the bind pose and skeleton hierarchy data.
            IList <BoneContent> bones = MeshHelper.FlattenSkeleton(skeleton);

            if (bones.Count > MaxBones)
            {
                throw new InvalidContentException(string.Format("Skeleton has {0} bones, but the maximum supported is {1}.", bones.Count, MaxBones));
            }

            List <Matrix> bindPose          = new List <Matrix>();
            List <Matrix> invBindPose       = new List <Matrix>();
            List <int>    skeletonHierarchy = new List <int>();
            List <string> boneNames         = new List <string>();

            foreach (var bone in bones)
            {
                bindPose.Add(bone.Transform);
                invBindPose.Add(Matrix.Invert(bone.AbsoluteTransform));
                skeletonHierarchy.Add(bones.IndexOf(bone.Parent as BoneContent));
                boneNames.Add(bone.Name);
            }

            // Convert animation data to our runtime format.
            Dictionary <string, ClipContent> clips;

            clips = ProcessAnimations(input, context, skeleton.Animations, bones, GenerateKeyframesFrequency);

            return(new AnimationsContent(bindPose, invBindPose, skeletonHierarchy, boneNames, clips));
        }
Пример #16
0
        /// <summary>
        /// The main Process method converts an intermediate format content pipeline
        /// NodeContent tree to a ModelContent object with embedded animation data.
        /// </summary>
        /// <param name="input">
        /// The input.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        public override ModelContent Process(NodeContent input, ContentProcessorContext context)
        {
            ValidateMesh(input, context, null);

            // Find the skeleton.
            BoneContent skeleton = MeshHelper.FindSkeleton(input);

            if (skeleton == null)
            {
                throw new InvalidContentException("Input skeleton not found.");
            }

            // We don't want to have to worry about different parts of the model being
            // in different local coordinate systems, so let's just bake everything.
            FlattenTransforms(input, skeleton);

            // Read the bind pose and skeleton hierarchy data.
            IList <BoneContent> bones = MeshHelper.FlattenSkeleton(skeleton);

            if (bones.Count > MaxBones)
            {
                throw new InvalidContentException(
                          string.Format("Skeleton has {0} bones, but the maximum supported is {1}.", bones.Count, MaxBones));
            }

            var bindPose          = new List <Matrix>();
            var inverseBindPose   = new List <Matrix>();
            var skeletonHierarchy = new List <int>();

            foreach (BoneContent bone in bones)
            {
                bindPose.Add(bone.Transform);
                inverseBindPose.Add(Matrix.Invert(bone.AbsoluteTransform));
                skeletonHierarchy.Add(bones.IndexOf(bone.Parent as BoneContent));
            }

            // Chain to the base ModelProcessor class so it can convert the model data.
            ModelContent model = base.Process(input, context);

            // Convert animation data to our runtime format.
            Dictionary <string, AnimationClip> animationClips;

            animationClips = ProcessAnimations(skeleton.Animations, bones, context, input.Identity.SourceFilename);

            // Store our custom animation data in the Tag property of the model.
            model.Tag = new SkinningData(animationClips, bindPose, inverseBindPose, skeletonHierarchy);

            return(model);
        }
Пример #17
0
    public void PlaceBuilding(Material material)
    {
        this.material = material;

        if (building == null)
        {
            MeshHelper tmp = new MeshHelper();
            tmp.BuildingMesh(foundation, height);
            building = tmp.CreateMesh(material, "buildings");
        }
        else
        {
            UpdateBuilding();
        }
    }
Пример #18
0
        void MergeTransforms(NodeContent input)
        {
            if (input is MeshContent)
            {
                MeshContent content = (MeshContent)input;
                MeshHelper.TransformScene(content, content.Transform);
                content.Transform = Matrix.Identity;
                MeshHelper.OptimizeForCache(content);
            }

            foreach (NodeContent content in input.Children)
            {
                MergeTransforms(content);
            }
        }
Пример #19
0
        public static TerrainFace Create(GameObject obj, int power)
        {
            var face = obj.AddComponent <TerrainFace>();

            face.MeshFilter = obj.GetComponent <MeshFilter>();

            MeshHelper.Subdivide(face.MeshFilter.sharedMesh, power);

            for (var i = 0; i < face.MeshFilter.sharedMesh.vertices.Length; i++)
            {
                TerrainVertex.Create(i, face);
            }

            return(face);
        }
Пример #20
0
    public MeshInfo(Mesh mesh, bool calculateLoops, bool mirror)
    {
        if (mirror)
        {
            mesh = MirrorMesh(mesh);
        }

        Vector3[] vt  = mesh.vertices;
        Vector2[] uv  = mesh.uv;
        int[]     tri = mesh.triangles;

        // Fill data arrays
        Vertices  = new Vector3[vt.Length];
        UVs       = new Vector2[uv.Length];
        Triangles = new int[tri.Length];
        vt.CopyTo(Vertices, 0);
        uv.CopyTo(UVs, 0);
        tri.CopyTo(Triangles, 0);
        if (calculateLoops)
        {
            // Build Edge Loops
            EdgeLoops = MeshHelper.BuildEdgeLoops(MeshHelper.BuildManifoldEdges(mesh));
            // Fill Outline Data
            EdgeVertices = new Vector3[vt.Length];
            EdgeUV       = new Vector2[uv.Length];

            int minIndex  = int.MaxValue;
            int vertsUsed = 0;
            foreach (EdgeLoop loop in EdgeLoops)
            {
                for (int vi = 0; vi < loop.vertexCount; vi++)
                {
                    EdgeVertices[vertsUsed + vi] = vt[loop.vertexIndex[vi]];
                    EdgeUV[vertsUsed + vi]       = uv[loop.vertexIndex[vi]];
                    minIndex = Mathf.Min(minIndex, loop.vertexIndex[vi]);
                }
                vertsUsed += loop.vertexCount;
            }
            // modify EdgeLoops' indices (we need to address changed indices by omitting non-outlined edges
            foreach (EdgeLoop loop in EdgeLoops)
            {
                loop.ShiftIndices(-minIndex);
            }

            System.Array.Resize <Vector3>(ref EdgeVertices, vertsUsed);
            System.Array.Resize <Vector2>(ref EdgeUV, vertsUsed);
        }
    }
Пример #21
0
        /// <summary>
        /// Recursively processes a node from the input data tree.
        /// </summary>
        private void ProcessNode(NodeContent node)
        {
            // Is this node in fact a mesh?
            MeshContent mesh = node as MeshContent;

            if (mesh != null)
            {
                MeshHelper.OptimizeForCache(mesh);

                // create texture coordinates of 0 if none are present
                var texCoord0 = VertexChannelNames.TextureCoordinate(0);
                foreach (var item in mesh.Geometry)
                {
                    if (!item.Vertices.Channels.Contains(texCoord0))
                    {
                        item.Vertices.Channels.Add <Vector2>(texCoord0, null);
                    }
                }

                // calculate tangent frames for normal mapping
                var hasTangents  = GeometryContainsChannel(mesh.Geometry, VertexChannelNames.Tangent(0));
                var hasBinormals = GeometryContainsChannel(mesh.Geometry, VertexChannelNames.Binormal(0));
                if (!hasTangents || !hasBinormals)
                {
                    var tangentName  = hasTangents ? null : VertexChannelNames.Tangent(0);
                    var binormalName = hasBinormals ? null : VertexChannelNames.Binormal(0);
                    MeshHelper.CalculateTangentFrames(mesh, VertexChannelNames.TextureCoordinate(0), tangentName, binormalName);
                }

                //var outputMesh = new MyreMeshContent();
                //outputMesh.Parent = mesh.Parent;
                //outputMesh.BoundingSphere = BoundingSphere.CreateFromPoints(mesh.Positions);

                // Process all the geometry in the mesh.
                foreach (GeometryContent geometry in mesh.Geometry)
                {
                    ProcessGeometry(geometry, outputModel);
                }

                //outputModel.AddMesh(outputMesh);
            }

            // Recurse over any child nodes.
            foreach (NodeContent child in node.Children)
            {
                ProcessNode(child);
            }
        }
Пример #22
0
        public void RayTestVertexReverse3()
        {
            Point3D intersection;
            int     normal;

            var p1 = new Point3D(20, 10, 12);
            var p2 = new Point3D(15, 15, 11);
            var p3 = new Point3D(10, 10, 10);
            var r1 = new Point3D(p3.X, p3.Y, 0);
            var r2 = new Point3D(p3.X, p3.Y, 20);

            var ret = MeshHelper.RayIntersetTriangleRound(p1, p2, p3, r1, r2, out intersection, out normal);

            Assert.AreEqual(true, ret, "ret must be true.");
            Assert.AreEqual(p3, intersection, "intersection must be match.");
        }
Пример #23
0
        private static void TextureFace(Face face, string name, Matrix4X4?initialRotation = null)
        {
            ImageBuffer textureToUse  = new ImageBuffer(256, 256);
            var         frontGraphics = textureToUse.NewGraphics2D();

            frontGraphics.Clear(Color.White);
            frontGraphics.DrawString(name,
                                     textureToUse.Width / 2,
                                     textureToUse.Height / 2,
                                     60,
                                     justification: Agg.Font.Justification.Center,
                                     baseline: Agg.Font.Baseline.BoundsCenter);
            frontGraphics.Render(new Stroke(new RoundedRect(.5, .5, 254.5, 254.4, 0), 6), Color.DarkGray);
            ImageGlPlugin.GetImageGlPlugin(textureToUse, true);
            MeshHelper.PlaceTextureOnFace(face, textureToUse, MeshHelper.GetMaxFaceProjection(face, textureToUse, initialRotation));
        }
Пример #24
0
        /// <summary>
        /// Recursively adds calculated tangent frames to all meshes.
        /// </summary>
        void CalculateTangentFrames(NodeContent input, ContentProcessorContext context)
        {
            MeshContent inputMesh = input as MeshContent;

            if (inputMesh != null)
            {
                MeshHelper.CalculateTangentFrames(inputMesh,
                                                  VertexChannelNames.TextureCoordinate(0),
                                                  VertexChannelNames.Tangent(0), null);
            }

            foreach (NodeContent childNode in input.Children)
            {
                CalculateTangentFrames(childNode, context);
            }
        }
Пример #25
0
 private void InitializeHiDef(IGraphicsService graphicsService)
 {
     _submesh = MeshHelper.GetBox(graphicsService);
     _effect  = graphicsService.Content.Load <Effect>("DigitalRune/Sky/Skybox");
     _parameterWorldViewProjection = _effect.Parameters["WorldViewProjection"];
     _parameterColor        = _effect.Parameters["Color"];
     _parameterRgbmMaxValue = _effect.Parameters["RgbmMax"];
     _parameterTextureSize  = _effect.Parameters["TextureSize"];
     _textureParameter      = _effect.Parameters["Texture"];
     _passRgbToRgb          = _effect.CurrentTechnique.Passes["RgbToRgb"];
     _passSRgbToRgb         = _effect.CurrentTechnique.Passes["SRgbToRgb"];
     _passRgbmToRgb         = _effect.CurrentTechnique.Passes["RgbmToRgb"];
     _passRgbToSRgb         = _effect.CurrentTechnique.Passes["RgbToSRgb"];
     _passSRgbToSRgb        = _effect.CurrentTechnique.Passes["SRgbToSRgb"];
     _passRgbmToSRgb        = _effect.CurrentTechnique.Passes["RgbmToSRgb"];
 }
Пример #26
0
        /// <summary>
        /// Creates a model of a textured sphere with spherical mapping.
        /// </summary>
        /// <param name="engine">The <see cref="Engine"/> to use for rendering.</param>
        /// <param name="texture">The texture to place on the model; <c>null</c> for no texture.</param>
        /// <param name="radiusBottom">The radius of the cylinder at the lower end (negative Z).</param>
        /// <param name="radiusTop">The radius of the cylinder at the upper end (positive Z).</param>
        /// <param name="length">The length of the cylinder.</param>
        /// <param name="slices">The number of vertical slices to divide the cylinder in.</param>
        /// <param name="stacks">The number of horizontal stacks to divide the cylinder in.</param>
        public static Model Cylinder(Engine engine, ITextureProvider texture, float radiusBottom, float radiusTop, float length, int slices, int stacks)
        {
            #region Sanity checks
            if (engine == null)
            {
                throw new ArgumentNullException(nameof(engine));
            }
            #endregion

            Log.Info("Generate predefined model: Cylinder");
            Mesh mesh = MeshGenerator.Cylinder(engine.Device, radiusBottom, radiusTop, length, slices, stacks);
            MeshHelper.GenerateNormals(engine.Device, ref mesh);

            // ToDo: Calculate bounding box
            return(new Model(mesh, new XMaterial(texture)));
        }
    void Start()
    {
        Mesh mesh = GetComponent <MeshFilter> ().mesh;

        mesh1           = new MeshHelper();
        mesh1.vertices  = mesh.vertices;
        mesh1.triangles = mesh.triangles;

        mesh2 = LoopSubdivide(mesh1);
        print("Mesh2 above ===============-======================= Mesh 3 below");
        mesh3 = LoopSubdivide(mesh2);
        print("Mesh3 above ======================================== Mesh 4 below");
        mesh4 = LoopSubdivide(mesh3);

        mesh.RecalculateNormals();


        print("mesh1.vertices: " + mesh1.vertices);
        print("mesh1.vertices.len: " + mesh1.vertices.Length);

        print("mesh1.triangles: " + mesh1.triangles);
        print("mesh1.tri.len: " + mesh1.triangles.Length);

        print("-----------------------------------------");

        print("mesh2.vertices: " + mesh2.vertices);
        print("mesh2.vertices.len: " + mesh2.vertices.Length);

        print("mesh2.triangles: " + mesh2.triangles);
        print("mesh2.tri.len: " + mesh2.triangles.Length);

        print("-----------------------------------------");

        print("mesh3.vertices: " + mesh3.vertices);
        print("mesh3.vertices.len: " + mesh3.vertices.Length);

        print("mesh3.triangles: " + mesh3.triangles);
        print("mesh3.tri.len: " + mesh3.triangles.Length);

        print("-----------------------------------------");

        print("mesh4.vertices: " + mesh4.vertices);
        print("mesh4.vertices.len: " + mesh4.vertices.Length);

        print("mesh4.triangles: " + mesh4.triangles);
        print("mesh4.tri.len: " + mesh4.triangles.Length);
    }
Пример #28
0
        public override SerializableModel Process(NodeContent xnaInputNode, ContentProcessorContext context)
        {
            //System.Diagnostics.Debugger.Launch();

            this.context = context;

            outputModel      = new SerializableModel();
            outputModel.name = RemoveFileExtension(GetFileName(context));

            ValidateMesh(xnaInputNode, context, null);

            // Find the root.
            BoneContent xnaRootBone = MeshHelper.FindSkeleton(xnaInputNode);

            if (xnaRootBone == null)
            {
                throw new InvalidContentException("Input skeleton not found.");
            }

            // We don't want to have to worry about different parts of the model being
            // in different local coordinate systems, so let's just bake everything.
            FlattenTransforms(xnaInputNode, xnaRootBone);

            // Read the bind pose and skeleton hierarchy data.
            IList <BoneContent> xnaBoneList = MeshHelper.FlattenSkeleton(xnaRootBone);

            if (xnaBoneList.Count > MAX_BONES)
            {
                throw new InvalidContentException(string.Format("Skeleton has {0} bones, but the maximum supported is {1}.", xnaBoneList.Count, MAX_BONES));
            }

            SerializableSkeleton skeleton = new SerializableSkeleton();
            SerializableBone     root     = new SerializableBone();

            root.name = xnaRootBone.Name;
            root.matrixLocalTransform = xnaRootBone.Transform;
            skeleton.rootBone         = root;
            skeleton.AddBone(root);
            outputModel.skeleton = skeleton;

            CreateChildBones(xnaRootBone, root, skeleton);

            ProcessNode(xnaInputNode);
            ProcessAnimations(xnaRootBone.Animations, outputModel);

            return(outputModel);
        }
Пример #29
0
        private void RenderSphere(IGraphicsService graphicsService, PrimitiveJob job, RenderContext context)
        {
            if (DrawWireFrame)
            {
                Pose      cameraPose       = context.CameraNode.PoseWorld;
                Matrix44F cameraProjection = context.CameraNode.Camera.Projection;
                if (Numeric.AreEqual(1.0f, cameraProjection.M33))
                {
                    // Orthographic projection
                    Vector3F position = job.Pose.Position;
                    Vector3F right    = cameraPose.Orientation.GetColumn(0);
                    Vector3F up       = cameraPose.Orientation.GetColumn(1);
                    Vector3F forward  = cameraPose.Orientation.GetColumn(2);
                    Matrix   pose     = new Matrix(right.X, right.Y, right.Z, 0,
                                                   up.X, up.Y, up.Z, 0,
                                                   forward.X, forward.Y, forward.Z, 0,
                                                   position.X, position.Y, position.Z, 1);
                    Effect.World = Matrix.CreateScale(job.Size.Radius) * pose;
                    Effect.CurrentTechnique.Passes[0].Apply();

                    if (_circleLinePrimitive == null)
                    {
                        _circleLinePrimitive = MeshHelper.GetCircleLines(graphicsService);
                    }

                    _circleLinePrimitive.Draw();
                }
                else
                {
                    // Perspective projection
                    Vector3F right = cameraPose.Orientation * Vector3F.Right;
                    RenderSphereOutline(job.Size.Radius, ref job.Pose.Position, ref cameraPose, ref right, ref job.Color);
                }
            }
            else
            {
                Effect.World = Matrix.CreateScale(job.Size.Radius) * job.Pose;
                Effect.CurrentTechnique.Passes[0].Apply();

                if (_icospherePrimitive == null)
                {
                    _icospherePrimitive = MeshHelper.GetIcosphere(graphicsService);
                }

                _icospherePrimitive.Draw();
            }
        }
Пример #30
0
    public void AddNewSphere(List <int> triangle, Vector3 spawnPos)
    {
        var verts     = new List <Vector3>(meshFilter.mesh.vertices);
        var triangles = new List <int>(meshFilter.mesh.triangles);

        var center = LayerHelper.CalcCenterPoint(meshFilter.mesh.vertices);

        verts.Add(spawnPos);

        triangles.Add(triangles[triangle[1]]);
        triangles.Add(triangles[triangle[0]]);
        triangles.Add(verts.Count - 1);
        triangles.Add(triangles[triangle[2]]);
        triangles.Add(triangles[triangle[1]]);
        triangles.Add(verts.Count - 1);
        triangles.Add(triangles[triangle[2]]);
        triangles.Add(triangles[triangle[0]]);
        triangles.Add(verts.Count - 1);

        for (int i = triangles.Count - 1; i >= 0; i--)
        {
            for (int j = 0; j < triangle.Count; j++)
            {
                if (i == triangle[j])
                {
                    triangles.RemoveAt(i);
                }
            }
        }

        meshFilter.mesh.SetVertices(verts);
        meshFilter.mesh.SetTriangles(triangles, 0);
        meshFilter.mesh.RecalculateNormals();
        MeshHelper.TurnOutNormals(meshFilter.mesh);

        meshFilter.GetComponent <MeshCollider>().sharedMesh = meshFilter.mesh;

        var go = Instantiate(spherePrefab, dragSpheresParent);

        go.OnPositionChange       += OnSpherePositionChange;
        go.transform.localPosition = spawnPos;
        sphereToVertex.Add(go, new Dictionary <MeshFilter, int>()
        {
            { meshFilter, meshFilter.mesh.vertices.Length - 1 }
        });
    }
Пример #31
0
    void makeSkin()
    {
        Vector3[] verts = new Vector3[v3a_spinePoints.Length * (i_circlePoints + 1)];
        Vector2[] uvs = new Vector2[verts.Length];

        for(int sp = 0; sp < v3a_spinePoints.Length; sp++)
        //for(int sp = 0; sp < 2; sp++)
        {
            for(int cp = 0; cp <= i_circlePoints; cp++)
            {
                int i = sp * (i_circlePoints + 1) + cp;
                float angle = 360f * Mathf.Deg2Rad / (float)i_circlePoints * cp;
                float radiusModifier = (v3a_spinePoints.Length - sp > i_coneHeight) ? 1 : (float)(v3a_spinePoints.Length - sp - 1) / (float)i_coneHeight;
                radiusModifier = (Mathf.Sin(((float)sp + Time.time * 20 + seed) / (float)i_pointsPerNode * Mathf.PI) + 1f) / 4f + .5f;
                float x = Mathf.Cos(angle) * f_skinRadius * radiusModifier + v3a_spinePoints[sp].x;
                float z = Mathf.Sin(angle) * f_skinRadius * radiusModifier + v3a_spinePoints[sp].z;
                verts[i] = new Vector3(x, v3a_spinePoints[sp].y, z);
                float uvx = (float)cp / (float)i_circlePoints;
                float uvy = (float)sp / (float)v3a_spinePoints.Length * (float)i_pointsPerNode;
                uvs[i] = new Vector2(uvx, uvy);

                //TODO: rotate circle around tangent of point
            }
        }

        MeshHelper mh = new MeshHelper(verts, uvs);

        for(int sp = 0; sp < v3a_spinePoints.Length - 1; sp++)
        {
            for(int cp = 0; cp < i_circlePoints; cp++)
            {
                int i = sp * (i_circlePoints + 1) + cp;
                if(cp < i_circlePoints )
                    mh.addQuad(i, i+i_circlePoints+1, i+2+i_circlePoints, i+1);
                    //mh.addQuad(i, i+1, i+1+i_circlePoints, i+i_circlePoints);
                else
                    mh.addQuad(i, i+i_circlePoints, i+1, i-i_circlePoints + 1);
            }
        }

        m_skin = mh.mesh;

        GetComponent<MeshFilter>().mesh = m_skin;

        Debug.Log(verts.Length);
        Debug.Log(GetComponent<MeshFilter>().mesh.vertexCount);
    }
Пример #32
0
    void updateDSlice()
    {
        m.Clear();

        if(props.bA > props.eA)
        {
            float temp = props.bA;
            props.bA = props.eA;
            props.eA = temp;
        }

        float segmentAngle = 2 * Mathf.PI / resolution;

        List<float> angles = new List<float>();

        angles.Add(props.bA);

        for(int i = 0; i < resolution; i++)
        {
            float currentAngle = i * segmentAngle;
            if(currentAngle != Mathf.Clamp(currentAngle, props.bA, props.eA)) continue;

            angles.Add(currentAngle);
        }

        angles.Add(props.eA);

        int numPoints = angles.Count * 4;

        Vector3[] verts = new Vector3[numPoints];
        Vector2[] uvs = new Vector2[verts.Length];

        int a = 0;
        foreach(float angle in angles)
        {
            verts[a] = angleToPoint(angle, props.ir);
            verts[a+1] = verts[a] + new Vector3(0,props.h,0);
            verts[a+2] = angleToPoint(angle, props.r);
            verts[a+3] = verts[a+2] + new Vector3(0,props.h,0);

            uvs[a] = uvs[a+1] = new Vector2(props.texColumn, 1f - (props.ir/props.r));
            uvs[a+2] = uvs[a+3] = new Vector2(props.texColumn,0.01f);

            a += 4;
        }

        MeshHelper mh = new MeshHelper(verts, uvs);

        for(int i = 0; i < numPoints - 4; i += 4)
        {
            //bottom face
            mh.addQuad(i, i+2, i+6, i+4);
            //top face
            mh.addQuad(i+1, i+5, i+7, i+3);
            //back face
            mh.addQuad(i+2, i+3, i+7, i+6);
            //inner face
            mh.addQuad(i, i+4, i+5, i+1);
        }

        //Side1

        a = 0;
        mh.addQuad(
        new Vector3[] {
            verts[a],
            verts[a+1],
            verts[a+3],
            verts[a+2]
        }, new Vector2[] {
            uvs[a],
            uvs[a+1],
            uvs[a+3],
            uvs[a+2]
        });

        //Side2
        a = numPoints - 4;
        mh.addQuad(
        new Vector3[] {
            verts[a],
            verts[a+2],
            verts[a+3],
            verts[a+1]
        }, new Vector2[] {
            uvs[a],
            uvs[a+2],
            uvs[a+3],
            uvs[a+1]
        });

        GetComponent<MeshFilter>().mesh = mh.mesh;
        if(mouseOverAble)
            GetComponent<MeshCollider>().sharedMesh = mh.mesh;
    }
Пример #33
0
    void updateSlice()
    {
        m.Clear();

        if(props.bA > props.eA)
        {
            float temp = props.bA;
            props.bA = props.eA;
            props.eA = temp;
        }

        float segmentAngle = 2 * Mathf.PI / resolution;

        List<float> angles = new List<float>();

        angles.Add(props.bA);

        for(int i = 0; i < resolution; i++)
        {
            float currentAngle = i * segmentAngle;
            if(currentAngle != Mathf.Clamp(currentAngle, props.bA, props.eA)) continue;

            angles.Add(currentAngle);
        }

        angles.Add(props.eA);

        int numPoints = angles.Count * 2 + 2;

        Vector3[] verts = new Vector3[numPoints];
        verts[0] = Vector3.zero; //Center point

        int a = 2;
        foreach(float angle in angles)
        {
            verts[a] = angleToPoint(angle);
            a += 2;
        }

        for(int i = 0; i < verts.Length - 1; i += 2)
        {
            verts[i+1] = verts[i] + new Vector3(0,props.h,0);
        }

        int[] tris = new int[(verts.Length) * 6];

        int ti = 0;

        for(int i = 2; i < numPoints - 2; i += 2)
        {
            //bottom face
            tris[ti++] = 0;
            tris[ti++] = i;
            tris[ti++] = i + 2;
            //back face 1
            tris[ti++] = i;
            tris[ti++] = i + 1;
            tris[ti++] = i + 2;

        }

        for(int i = 3; i < numPoints - 2; i += 2)
        {

            //top face
            tris[ti++] = i + 2;
            tris[ti++] = i;
            tris[ti++] = 1;
            //back face 2
            tris[ti++] = i + 2;
            tris[ti++] = i + 1;
            tris[ti++] = i;
        }

        Vector2[] uvs = new Vector2[verts.Length];

        uvs[0] = uvs[1] = new Vector2(props.texColumn,.99f);

        for(int i = 2; i < uvs.Length; i++)
            uvs[i] = new Vector2(props.texColumn,0.01f);

        m.vertices = verts;
        m.triangles = tris;
        m.uv = uvs;
        m.uv1 = uvs;
        m.uv2 = uvs;

        MeshHelper mh = new MeshHelper(m);

        Mesh side1 = new Mesh();
        Mesh side2 = new Mesh();

        //side 1
        Vector3[] s1Verts = new Vector3[4];
        s1Verts[0] = verts[0];
        s1Verts[1] = verts[1];
        s1Verts[2] = verts[2];
        s1Verts[3] = verts[3];

        mh.addQuad(0,1,2,3);

        Vector2[] s1uvs = new Vector2[4];
        s1uvs[0] = uvs[0];
        s1uvs[1] = uvs[1];
        s1uvs[2] = uvs[2];
        s1uvs[3] = uvs[3];

        int[] s1tris = new int[6];
        ti = 0;
        s1tris[ti++] = 0;
        s1tris[ti++] = 1;
        s1tris[ti++] = 2;

        s1tris[ti++] = 3;
        s1tris[ti++] = 2;
        s1tris[ti++] = 1;

        side1.vertices = s1Verts;
        side1.triangles = s1tris;
        side1.uv = s1uvs;

        //side 2
        Vector3[] s2Verts = new Vector3[4];
        s2Verts[0] = verts[0];
        s2Verts[1] = verts[1];
        s2Verts[2] = verts[verts.Length - 2];
        s2Verts[3] = verts[verts.Length - 1];

        mh.addQuad(verts.Length - 2, verts.Length - 1, 0, 1);

        Vector2[] s2uvs = new Vector2[4];
        s2uvs[0] = uvs[0];
        s2uvs[1] = uvs[1];
        s2uvs[2] = uvs[uvs.Length - 2];
        s2uvs[3] = uvs[uvs.Length - 1];

        int[] s2tris = new int[6];
        ti = 0;

        s2tris[ti++] = 2;
        s2tris[ti++] = 1;
        s2tris[ti++] = 0;

        s2tris[ti++] = 2;
        s2tris[ti++] = 3;
        s2tris[ti++] = 1;

        side2.vertices = s2Verts;
        side2.triangles = s2tris;
        side2.uv = s2uvs;

        MeshHelper mh2 = new MeshHelper(new Mesh[]{m, side1, side2});

        GetComponent<MeshFilter>().mesh = mh2.mesh;
        if(mouseOverAble)
            GetComponent<MeshCollider>().sharedMesh = mh.mesh;
    }