Beispiel #1
0
 public CloudInCell(IParticleStorage<Particle> particles, IGrid2D grid, IMesh mesh, bool parallel)
 {
     this.particles = particles;
     this.grid = grid;
     this.mesh = mesh;
     this.parallel = parallel;
 }
        public void Smooth(IMesh mesh, int limit)
        {
            var smoothedMesh = (Mesh)mesh;

            var mesher = new GenericMesher(config);
            var predicates = config.Predicates();

            // The smoother should respect the mesh segment splitting behavior.
            this.options.SegmentSplitting = smoothedMesh.behavior.NoBisect;

            // Take a few smoothing rounds (Lloyd's algorithm).
            for (int i = 0; i < limit; i++)
            {
                Step(smoothedMesh, factory, predicates);

                // Actually, we only want to rebuild, if the mesh is no longer
                // Delaunay. Flipping edges could be the right choice instead 
                // of re-triangulating...
                smoothedMesh = (Mesh)mesher.Triangulate(Rebuild(smoothedMesh), options);

                factory.Reset();
            }

            smoothedMesh.CopyTo((Mesh)mesh);
        }
Beispiel #3
0
        public CPlayer(IGameObjectManager pObjMan, IEngineCore pEngineCore)
            : base(pObjMan, pEngineCore)
        {
            _fVelocity = 0f;
            uiShotPause = 15;

            ObjType = EGameObjectType.GotPlayer;

            _stPos = new TPoint2(Res.GameVpWidth / 2f, Res.GameVpHeight / 2f);
            _fSize = 150f;
            _fColScale = 0.6f;

            dimPl = new TPoint3(_fSize, _fSize, _fSize);

            IResourceManager pResMan;
            IEngineSubSystem pSubSys;

            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_INPUT, out pSubSys);
            pInput = (IInput)pSubSys;

            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_RESOURCE_MANAGER, out pSubSys);
            pResMan = (IResourceManager)pSubSys;

            IEngineBaseObject pBaseObj;
            pResMan.GetResourceByName(Res.MeshShip, out pBaseObj);
            pMesh = (IMesh)pBaseObj;
            pResMan.GetResourceByName(Res.TexShip, out pBaseObj);
            pTex = (ITexture)pBaseObj;
            pResMan.GetResourceByName(Res.TexSpark, out pBaseObj);
            pTexSpark = (ITexture)pBaseObj;
        }
Beispiel #4
0
        public bool Collides(
            Ray testRay, 
            IEnumerable<IMesh> meshes, 
            out Vector3 position, 
            out IMesh hitMesh, 
            bool furthest = false)
        {
            var distance = furthest ? 0f : 10000f;
            var closestPosition = Vector3.Zero;
            IMesh closestMesh = null;

            foreach (var mesh in meshes)
            {
                if (mesh.MeshVertexPositions == null)
                {
                    continue;
                }

                for (var a = 0; a < mesh.MeshIndicies.Length; a += 3)
                {
                    var vertexA = mesh.MeshVertexPositions[mesh.MeshIndicies[a]];
                    var vertexB = mesh.MeshVertexPositions[mesh.MeshIndicies[a + 1]];
                    var vertexC = mesh.MeshVertexPositions[mesh.MeshIndicies[a + 2]];

                    float tempDistance;
                    var point = this.m_Collision.CollidesWithTriangle(
                        testRay,
                        vertexA,
                        vertexB,
                        vertexC,
                        out tempDistance,
                        false);
                    if (point != null)
                    {
                        if (!furthest)
                        {
                            if (tempDistance < distance && tempDistance > 0)
                            {
                                distance = tempDistance;
                                closestPosition = point.Value;
                                closestMesh = mesh;
                            }
                        }
                        else
                        {
                            if (tempDistance > distance && tempDistance > 0)
                            {
                                distance = tempDistance;
                                closestPosition = point.Value;
                                closestMesh = mesh;
                            }
                        }
                    }
                }
            }

            position = closestPosition;
            hitMesh = closestMesh;
            return closestPosition != Vector3.Zero;
        }
Beispiel #5
0
 /// <summary>
 /// Combine this mesh with another.
 /// </summary>
 /// <param name="anotherMesh">Another mesh.</param>
 /// <seealso cref="ConstructiveSolidGeometry.Union"/>
 public virtual void Combine(IMesh anotherMesh)
 {
     BspNode<SplittableTriangle> a = this.ToBspTree();
     BspNode<SplittableTriangle> b = anotherMesh.ToBspTree();
     a.Unite(b);
     this.SetBsp(a);
 }
Beispiel #6
0
        public void Test()
        {
            u = 100000;
            particles = new ParticleArrayStorage<Particle>(1000000);
            boundaryConditions = new BoundaryConditions
            {
                Top = new BoundaryCondition { Value = x => 0, Type = BoundaryConditionType.Neumann },
                Bottom = new BoundaryCondition { Value = x => 0, Type = BoundaryConditionType.Neumann },
                Left = new BoundaryCondition { Value = x => 0, Type = BoundaryConditionType.Dirichlet },
                Right = new BoundaryCondition { Value = x => u, Type = BoundaryConditionType.Dirichlet }
            };

            grid = new Grid2D();
            grid.InitializeGrid(5, 5, 0, 4, 0, 4);
            mesh = new Mesh2D();
            mesh.InitializeMesh(grid.N * grid.M);
            interpolator = new CloudInCellCurrentLinkage(particles, grid, mesh, false);
            poissonSolver = new Poisson2DFdmSolver(grid, boundaryConditions);
            poissonSolver.FdmMatrix = poissonSolver.BuildMatrix();
            var particle = new Particle(4, 1, 0, 0, 0, 0, 1);
            var particleId = particles.Add(particle);
            particles.Set(Field.PrevX, particleId, 2);
            particles.Set(Field.PrevY, particleId, 1);

            var cell = grid.FindCell(particles.Get(Field.X, particleId), particles.Get(Field.Y, particleId));
            particles.SetParticleCell(particleId, cell);

            interpolator.InterpolateDensity();
        }
 public void Load(IMesh mesh, string filePath)
 {
   using (var streamReader = new StreamReader(filePath))
   {
     Load(streamReader, mesh);
   }
 }
 public void Write(IMesh mesh, string filename)
 {
     if (mesh.Vertices.Count > 0)
     {
         format.Write(mesh, filename);
     }
 }
Beispiel #9
0
        public unsafe bool SetTextureVertices(IMesh maxMesh, MyMesh myMesh)
        {
            bool countChanged = false;

            if (maxMesh.NumTVerts != myMesh.NumTextureCoordinates)
            {
                maxMesh.SetNumTVerts(myMesh.NumTextureCoordinates, false);
                countChanged = true;
            }

            IntPtr p3h = maxMesh.GetTVertPtr(0).NativePointer;
            float* p3 = (float*)p3h.ToPointer();

            int elementsPerVertex = myMesh.TextureCoordinates.Count / myMesh.NumTextureCoordinates;
            switch (elementsPerVertex)
            {
                case 2:
                    for (int i = 0; i < myMesh.NumTextureCoordinates; i++)
                    {
                        p3[(i * 3) + 0] = myMesh.TextureCoordinates[(i * 2) + 0];
                        p3[(i * 3) + 1] = myMesh.TextureCoordinates[(i * 2) + 1];
                        p3[(i * 3) + 2] = 0.0f;
                    };
                    break;
                case 3:
                    Marshal.Copy(myMesh.TextureCoordinates.ToArray(), 0, p3h, myMesh.NumTextureCoordinates * 3);
                    break;
                default:
                    throw new NotImplementedException(("Unable to handle texture coordinates with " + elementsPerVertex + " elements."));
            }

            return countChanged;
        }
Beispiel #10
0
		//private Texture cubeTex;

		#region Constructors and Destructors

		public Base3DEditorContent(ToeGraphicsContext graphicsContext, IStreamConverterFactory streamConverterFactory)
		{
			this.graphicsContext = graphicsContext;
			this.streamConverterFactory = streamConverterFactory;
			var cubeBytes = Properties.Resources.xyzcube;
			if (cubeBytes != null)
			{
				IScene scene = (new AseReader(streamConverterFactory)).Load(new MemoryStream(cubeBytes), null);
				foreach (var node in scene.Nodes)
				{
					if (node.Mesh != null)
					{
						this.cube = node.Mesh;
					}
				}
				//this.cubeTex = new Toe.Marmalade.IwGx.Texture ();
				//cubeTex.Image = new Toe.Marmalade.IwGx.Image (Toe.Editors.Properties.Resources.xyzcube1);
				this.cube.Submeshes.First().Material = new SceneMaterial
					{
						Effect =
							new SceneEffect
								{
									CullMode = CullMode.Front,
									Diffuse = new ImageColorSource { Image = new EmbeddedImage(Properties.Resources.xyzcube1) { } }
								}
					};
			}
		}
        public void Prepare(PICProject project)
        {
            w = project.Relaxation;
            backscattering = project.Backscattering;
            alfa = project.BackscatteringAlfa;
            beta = project.BackscatteringBeta;
            step = project.Step;
            u = project.Voltage;

            particles = new ParticleArrayStorage<Particle>(project.ParticlesCount);
            boundaryConditions = new BoundaryConditions
            {
                Top = new BoundaryCondition { Value = x => 0, Type = BoundaryConditionType.Neumann },
                Bottom = new BoundaryCondition { Value = x => 0, Type = BoundaryConditionType.Neumann },
                Left = new BoundaryCondition { Value = x => 0, Type = BoundaryConditionType.Dirichlet },
                Right = new BoundaryCondition { Value = x => u, Type = BoundaryConditionType.Dirichlet }
            };

            emitter = new Emitter2D(0, project.EmitterBottom, 0, project.EmitterTop, project.ParticlesCount, 0, 0, -0.5 * Constants.ChildLangmuirCurrent(project.Length, u), step);
            mover = new Leapfrog();
            grid = new Grid2D();
            grid.InitializeGrid(project.GridN, project.GridM, 0, project.Length, 0, project.Height);
            mesh = new Mesh2D();
            mesh.InitializeMesh(grid.N * grid.M);
            interpolator = new CloudInCellCurrentLinkage(particles, grid, mesh, false);
            poissonSolver = new Poisson2DFdmSolver(grid, boundaryConditions);
            poissonSolver.FdmMatrix = poissonSolver.BuildMatrix();
            h = step * Constants.LightVelocity;
            Monitor = new PICMonitor(grid, mesh, particles, this);
            density = new double[grid.N * grid.M];
            Trajectories = new List<Tuple<int, double, double>>(particles.Count * 1000);
        }
        public void Write(IMesh mesh, string filename)
        {
            var writer = new TriangleWriter();

            writer.WritePoly((Mesh)mesh, Path.ChangeExtension(filename, ".poly"));
            writer.WriteElements((Mesh)mesh, Path.ChangeExtension(filename, ".ele"));
        }
Beispiel #13
0
 public void Load(IMesh mesh, string filePath)
 {
   var dxfLoad = DxfDocument.Load(filePath);
   var vertices = new List<IVertex>();
   var faces = new List<IFace>();
   var verticesIndexMap = new Dictionary<IVertex, int>();
   int currentVertexIndex = 0;
   foreach (var face3D in dxfLoad.Faces3d)
   {
     var v1 = face3D.FirstVertex;
     var v2 = face3D.SecondVertex;
     var v3 = face3D.ThirdVertex;
     var v4 = face3D.FourthVertex;
     currentVertexIndex = CreateTriangleFace(v1, v2, v3, verticesIndexMap, currentVertexIndex, vertices, faces);
     currentVertexIndex = CreateTriangleFace(v3, v4, v1, verticesIndexMap, currentVertexIndex, vertices, faces);
   }
   foreach (var vertex in vertices)
   {
     mesh.AddVertex(vertex);
   }
   foreach (var face in faces)
   {
     mesh.AddFace(face);
   }
 }
Beispiel #14
0
        public static VNormal[] ComputeNormals(IMesh mesh)
        {
            var vnorms = new VNormal[mesh.NumVerts];
            var fnorms = new Vector3[mesh.NumFaces];

            for (var index = 0; index < mesh.NumVerts; index++)
            {
                vnorms[index] = new VNormal();
            }

            for (var index = 0; index < mesh.NumFaces; index++)
            {
                var face = mesh.Faces[index];
                Vector3 v0 = mesh.Verts[(int)face.V[0]].ToVector3();
                Vector3 v1 = mesh.Verts[(int)face.V[1]].ToVector3();
                Vector3 v2 = mesh.Verts[(int)face.V[2]].ToVector3();

                fnorms[index] = Vector3.Cross((v1 - v0), (v2 - v1));

                for (var j = 0; j < 3; j++)
                {
                    vnorms[(int)face.V[j]].AddNormal(fnorms[index], face.SmGroup);
                }

                fnorms[index].Normalize();
            }

            for (var index = 0; index < mesh.NumVerts; index++)
            {
                vnorms[index].Normalize();
            }

            return vnorms;
        }
Beispiel #15
0
 public void DestroyMesh(ref IMesh _OutMesh)
 {
     if (m_MeshInstanceContainer.ContainsKey(_OutMesh.m_InstanceID)) {
         m_MeshInstanceContainer[_OutMesh.m_InstanceID].Release();
         m_MeshInstanceContainer.Remove(_OutMesh.m_InstanceID);
         _OutMesh = null;
     }
 }
Beispiel #16
0
 /// <summary>
 /// Subtracts another mesh from this one.
 /// </summary>
 /// <param name="anotherMesh">Another mesh.</param>
 /// <seealso cref="ConstructiveSolidGeometry.Subtract"/>
 public virtual void Subtract(IMesh anotherMesh)
 {
     BspNode<SplittableTriangle> a = this.ToBspTree();
     BspNode<SplittableTriangle> b = anotherMesh.ToBspTree();
     a.Invert();
     a.Unite(b);
     a.Invert();
     this.SetBsp(a);
 }
Beispiel #17
0
    public static Vector3[] vertexPositions(IMesh mesh){

      Vector3[] positions = new Vector3[mesh.VerticesCount];
      int i = 0;
      foreach(IVertex v in mesh.Vertices) {
        positions [i] = v.Position;
        i++;
      }
      return positions;
    }
Beispiel #18
0
 public PICMonitor(IGrid2D grid, IMesh mesh, IParticleStorage<Particle> particles, IPICSolver solver)
 {
     this.grid = grid;
     this.particles = particles;
     this.mesh = mesh;
     this.solver = solver;
     GridX = grid.X;
     GridY = grid.Y;
     Status = PICStatus.Created;
 }
Beispiel #19
0
 // copy
 public Mesh_VoxelChunk(IMesh _CopyMesh) : base(_CopyMesh)
 {
     Mesh_VoxelChunk _copyVoxelChunk = _CopyMesh as Mesh_VoxelChunk;
     if (_copyVoxelChunk.HasChunk)
     {
         m_ChunkMap = new Dictionary<string, Chunk>(_copyVoxelChunk.ChunkMap);
     }
     if (_copyVoxelChunk.HasModel)
     {
         m_ModelMap = new Dictionary<string, Chunk>(_copyVoxelChunk.ModelMap);
     }
 }
Beispiel #20
0
    public static uint[] faceIndices(IMesh mesh){

      uint[] faces = new uint[mesh.FacesCount * 3];
      int i = 0;
      foreach (IFace f in mesh.Faces) {
        foreach (int indx in f.VertexIndices) {
          faces [i] = (uint)indx;
          i++;
        }
      }
      return faces;
    }
Beispiel #21
0
        public bool SetPositionVertices(IMesh maxMesh, MyMesh myMesh)
        {
            bool countChanged = false;

            if (maxMesh.NumVerts != myMesh.NumVertices)
            {
                maxMesh.SetNumVerts(myMesh.NumVertices, false, false);
                countChanged = true;
            }

            IPoint3 p3 = maxMesh.GetVertPtr(0);
            Marshal.Copy(myMesh.Vertices.ToArray(), 0, p3.NativePointer, myMesh.NumVertices * 3);

            return countChanged;
        }
Beispiel #22
0
        public BiologicalEquation(IMesh mesh)
        {
            this.mesh = mesh;

            k = 17;
            Kb = 0.0005;
            Km = 0.0005;
            r = 0.2;
            mmu = 1.5;
            nnu = 0;
            zet = 0;
            c1 = 0;
            c2 = 0;
            dt = 0.0416667;
            // TODO: Take from args.
        }
Beispiel #23
0
 /// <summary>
 /// Intersects this mesh with another.
 /// </summary>
 /// <param name="anotherMesh">Another mesh.</param>
 /// <seealso cref="ConstructiveSolidGeometry.Intersection"/>
 public virtual void Intersect(IMesh anotherMesh)
 {
     BspNode<SplittableTriangle> a = this.ToBspTree();
     BspNode<SplittableTriangle> b = anotherMesh.ToBspTree();
     a.Invert();				// Cut geometry that is not common for the meshes.
     b.CutTreeOut(a);		//
     b.Invert();				//
     a.CutTreeOut(b);		//
     // Clean up remains.
     b.CutTreeOut(a);
     // Combine geometry.
     a.AddElements(b.AllElements);
     // Invert everything.
     a.Invert();
     this.SetBsp(a);
 }
Beispiel #24
0
		public MaterialPreview(
			MaterialEditor editor,
			ToeGraphicsContext graphicsContext,
			IComponentContext context,
			IEditorOptions<Base3DEditorOptions> options,
			Base3DEditorContent content,
			IStreamConverterFactory streamConverterFactory)
			: base(context, options, content)
		{
			this.editor = editor;
			this.graphicsContext = graphicsContext;
			this.Camera.Ortho = false;
			this.Camera.ZNear = 16.0f;
			this.Camera.ZFar = 2048.0f;
			base.RenderScene += this.RenderMaterialScene;
			this.box = BoxBuilder.BuildSoftEdgedBox(250, streamConverterFactory);
		}
Beispiel #25
0
        internal Mesh(IMesh m)
        {            
            faces = new Face[m.NumFaces];
            for (int i = 0; i < m.NumFaces; ++i)
                faces[i] = new Face(m.Faces[i]);

            verts = new Point3[m.NumVerts];
            for (int i = 0; i < m.NumVerts; ++i)
                verts[i] = new Point3(m.Verts[i]);

            tfaces = new Face[m.NumFaces];
            for (int i = 0; i < m.NumFaces; ++i)
                tfaces[i] = new Face(m.Faces[i]);

            tverts = new Point3[m.NumTVerts];
            for (int i = 0; i < m.NumTVerts; ++i)
                tverts[i] = new Point3(m.TVerts[i]);

            fnormals = new Point3[m.NumFaces];
            vnormals = new Point3[m.NumVerts];

            for (int i = 0; i < m.NumVerts; ++i)
                vnormals[i] = Point3.Origin;
            
            // Compute vertex normals ignoring smoothing groups
            // Each vertex normal is the average of the face normals.
            for (int i = 0; i < m.NumFaces; ++i)
            {
                uint a = faces[i].a;
                uint b = faces[i].b;
                uint c = faces[i].c;
                Point3 va = verts[a];
                Point3 vb = verts[b];
                Point3 vc = verts[c];
                Point3 fnorm = (vb - va) ^ (vc - vb);
                vnormals[a] += fnorm;
                vnormals[b] += fnorm;
                vnormals[c] += fnorm;
                fnormals[i] = fnorm.Normalized;
            }

            // Last step is to normalize the vector normals.
            for (int i = 0; i < m.NumVerts; ++i)
                vnormals[i].Normalize();
        }
Beispiel #26
0
        public unsafe bool SetFaces(IMesh maxMesh, MyMesh myMesh)
        {
            bool countChanged = false;

            TriangulateFaces(myMesh);

            if (maxMesh.NumFaces != myMesh.TriangulatedFaces.Length)
            {
                maxMesh.SetNumFaces(myMesh.TriangulatedFaces.Length, false, false);
                maxMesh.SetNumTVFaces(myMesh.TriangulatedFaces.Length, false, 0);
                countChanged = true;
            }

            /* Get the default flags value */

            IFace referenceFace = gi.Face.Create();
            referenceFace.SetEdgeVisFlags(EdgeVisibility.Vis, EdgeVisibility.Vis, EdgeVisibility.Vis);
            Face referenceMaxFace = *(Face*)referenceFace.NativePointer.ToPointer();
            UInt32 referenceFlags = referenceMaxFace.flags;

            /* Create the faces that define the surface of the mesh */

            Face* faces = (Face*)maxMesh.Faces[0].NativePointer.ToPointer();
            TVFace* tvfaces = (TVFace*)maxMesh.TvFace[0].NativePointer.ToPointer();

            for (int i = 0; i < myMesh.TriangulatedFaces.Length; i++)
            {
                MyFace myFace = myMesh.TriangulatedFaces[i];

                faces[i].v.v1 = (UInt32)myFace.PositionVertex1;
                faces[i].v.v2 = (UInt32)myFace.PositionVertex2;
                faces[i].v.v3 = (UInt32)myFace.PositionVertex3;
                faces[i].flags = (UInt32)((ushort)myFace.MaterialId << 16) | (ushort)referenceFlags;

                tvfaces[i].t1 = (UInt32)myFace.TextureVertex1;
                tvfaces[i].t2 = (UInt32)myFace.TextureVertex2;
                tvfaces[i].t3 = (UInt32)myFace.TextureVertex3;

            };

            return countChanged;
        }
Beispiel #27
0
    // copy
    public IMesh(IMesh _CopyMesh) {
        m_SourceStr = _CopyMesh.m_SourceStr;
        m_Name = _CopyMesh.m_Name;
        m_nSize = _CopyMesh.m_nSize;
        m_InstanceID = _CopyMesh.m_InstanceID;

        if (null != _CopyMesh.m_Vertices)
        {
            m_Vertices = new int[_CopyMesh.m_Vertices.Length];
            System.Array.Copy(_CopyMesh.m_Vertices, m_Vertices, _CopyMesh.m_Vertices.Length);
        }

        // optional field
        if (_CopyMesh.m_PartMask != null)
        {
            m_nPartCount = _CopyMesh.m_nPartCount;
            m_PartMask = new int[_CopyMesh.m_PartMask.Length];
            System.Array.Copy(_CopyMesh.m_PartMask, m_PartMask, _CopyMesh.m_PartMask.Length);
        }
    }
Beispiel #28
0
        public CBackGround(IGameObjectManager pObjMan, IEngineCore pEngineCore)
            : base(pObjMan, pEngineCore)
        {
            RenderLayer = -1;

            IResourceManager pResMan;
            IEngineSubSystem pSubSys;
            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_RESOURCE_MANAGER, out pSubSys);
            pResMan = (IResourceManager)pSubSys;

            IEngineBaseObject pBaseObj;
            pResMan.GetResourceByName(Res.MeshPlanet, out pBaseObj);
            _pMeshPlanet = (IMesh)pBaseObj;
            pResMan.GetResourceByName(Res.TexStars, out pBaseObj);
            _pTexSpace = (ITexture)pBaseObj;
            pResMan.GetResourceByName(Res.TexPlanet, out pBaseObj);
            _pTexEarth = (ITexture)pBaseObj;
            pResMan.GetResourceByName(Res.TexClouds, out pBaseObj);
            _pTexClouds = (ITexture)pBaseObj;
        }
Beispiel #29
0
        void Init(IntPtr pParam)
        {
            IEngineSubSystem pSubSys;

            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_CORE_RENDERER, out pSubSys);
            pCoreRenderer = (ICoreRenderer)pSubSys;

            E_CORE_RENDERER_TYPE type;
            pCoreRenderer.GetRendererType(out type);
            if (type != E_CORE_RENDERER_TYPE.CRT_OPENGL_LEGACY)
                pEngineCore.WriteToLogEx("This example will work only with Legacy OpenGL renderer!", E_LOG_TYPE.LT_FATAL, "", 0);

            IResourceManager pResMan;
            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_RESOURCE_MANAGER, out pSubSys);
            pResMan = (IResourceManager)pSubSys;

            IEngineBaseObject pBaseObj = null;

            pResMan.Load(ResPath + "meshes\\torus.dmd", out pBaseObj, (int)E_MESH_MODEL_LOAD_FLAGS.MMLF_FORCE_MODEL_TO_MESH);
            pMesh = (IMesh)pBaseObj;
            pResMan.Load(ResPath + "textures\\stone.tga", out pBaseObj, (int)E_TEXTURE_LOAD_FLAGS.TEXTURE_LOAD_DEFAULT_3D);
            pTex = (ITexture)pBaseObj;
        }
Beispiel #30
0
        public CAsteroid(IGameObjectManager pObjMan, IEngineCore pEngineCore, TPoint2 stPos, float fSize)
            : base(pObjMan, pEngineCore)
        {
            ObjType = EGameObjectType.GotAsteroid;

            _uiCounter = (uint)Rand.Next(500);
            RenderLayer = 2;
            _fSize = fSize;
            _fColScale = 0.8f;
            _stPos = stPos;
            _fAngle = Rand.Next(360);

            IResourceManager pResMan;
            IEngineSubSystem pSubSys;
            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_RESOURCE_MANAGER, out pSubSys);
            pResMan = (IResourceManager)pSubSys;

            IEngineBaseObject pBaseObj;
            pResMan.GetResourceByName(Res.MeshAsteroid, out pBaseObj);
            _pMesh = (IMesh)pBaseObj;
            pResMan.GetResourceByName(Res.TexAsteroid, out pBaseObj);
            _pTex = (ITexture)pBaseObj;
        }
Beispiel #31
0
 public bool AppendMesh(IMesh appendMesh, int appendGID = -1)
 {
     int[] mapV;
     return(AppendMesh(appendMesh, out mapV, appendGID));
 }
 public override void Execute(IMesh mesh)
 {
     mesh.RotateZ(angle);
     Log($"Rotation Z by {angle.ToString("0.00", CultureInfo.InvariantCulture)} done");
 }
Beispiel #33
0
    //public void GenHighway() {
    public IEnumerator GenHighwayCoroutine()
    {
        WorldManager.GenHighwayState = true;
        Dictionary <Vector2, float> densityLookup = new Dictionary <Vector2, float>();

        // cluster nearby points with DBScan
        List <Vector2> features = new List <Vector2>();// = new MyFeatureDataSource().GetFeatureData();

        for (int i = 0; i < patchDensityCenters.Count; i++)
        {
            (Vector2, float)cd = ((Vector2, float))patchDensityCenters[i];
            features.Add(cd.Item1);
            densityLookup[cd.Item1] = cd.Item2;
        }

        var result = RunOfflineDbscan(features);

        // Build highway graph
        var points = new List <Vertex>();

        foreach (int i in result.Clusters.Keys)
        {
            points.Add(new Vertex(result.Clusters[i][0].Feature.x, result.Clusters[i][0].Feature.y));
        }

        // Generate a default mesher
        var mesher = new GenericMesher(new Dwyer());

        // Generate mesh (Delaunay Triangulation)
        mesh = mesher.Triangulate(points);

        // Init edge/vertex lists for mutation
        foreach (Vertex v in mesh.Vertices)
        {
            vertices.Add(v);
        }
        foreach (Edge e in mesh.Edges)
        {
            edges.Add(e);

            // build neighbor map
            Vertex v0 = (Vertex)vertices[e.P0];
            Vertex v1 = (Vertex)vertices[e.P1];
            if (!neighbors.ContainsKey(v0))
            {
                neighbors[v0] = new List <Vertex>();
            }
            neighbors[v0].Add(v1);
        }

        // Remove unecessary edges on cost basis
        foreach (Edge e in mesh.Edges)
        {
            Vertex v0 = (Vertex)vertices[e.P0];
            Vertex v1 = (Vertex)vertices[e.P1];
            (Vector2, Vector2)tup1 = (Util.VertexToVector2(v0), Util.VertexToVector2(v1));
            (Vector2, Vector2)tup2 = (Util.VertexToVector2(v1), Util.VertexToVector2(v0));

            if (!InPatchBounds(regionIdx, tup1.Item1, tup1.Item2))
            {
                RemoveEdge(e);
                continue;
            }

            if (!WorldManager.edgeState.ContainsKey(tup1)) //needs removal check
            {
                if (ShouldRemoveEdge(e, densityLookup))
                {
                    // remove edge for first time
                    WorldManager.edgeState[tup1] = false;
                    WorldManager.edgeState[tup2] = false;
                    RemoveEdge(e);
                }
                else
                {
                    // keep edge, register with edgeState
                    WorldManager.edgeState[tup1] = true;
                    WorldManager.edgeState[tup2] = true;
                }
            }
            else // remove if removed before
            {
                if (!WorldManager.edgeState[tup1])
                {
                    RemoveEdge(e);
                }
            }
        }

        // Generate final highway segments for each edge
        // Uses A* search to pathfind
        int hwCount = 0;

        foreach (Edge e in edges)
        {
            hwCount++;
            (Vector2Int, Vector2Int)eVec = (Util.VertexToVector2Int((Vertex)vertices[e.P0]), Util.VertexToVector2Int((Vertex)vertices[e.P1]));
            Vertex v0 = (Vertex)vertices[e.P0];
            Vertex v1 = (Vertex)vertices[e.P1];

            // Skip pathfinding for edges that have been generated/built already
            if (WorldBuilder.builtHighways.ContainsKey((Util.VertexToVector2(v0), Util.VertexToVector2(v0))) &&
                WorldBuilder.builtHighways[(Util.VertexToVector2(v0), Util.VertexToVector2(v0))])
            {
                //Debug.Log("Aborting pathfind since already built!");
                continue;
            }

            // A* pathfind from v0 to v1
            ArrayList segments = pathfinding.FindPath(Util.VertexToVector2(v0), Util.VertexToVector2(v1));

            // Removal of redundant paths
            int firstIdx = -1, secondIdx = -1;
            List <(Vector2, (Vector2Int, Vector2Int))> vertListFirst = null, vertListSecond = null;
            // traverse from beginning
            for (int i = 0; i < segments.Count - 1; i++)
            {
                Vector2 v = (Vector2)segments[i];

                if (WorldBuilder.DoesChunkContainHighway(v))
                {
                    firstIdx      = i;
                    vertListFirst = WorldBuilder.GetHighwayVertList(v);
                    break;
                }
            }
            // traverse from end
            if (firstIdx >= 0)
            {
                for (int i = segments.Count - 1; i > 0; i--)
                {
                    Vector2 v = (Vector2)segments[i];
                    if (WorldBuilder.DoesChunkContainHighway(v))
                    {
                        secondIdx      = i;
                        vertListSecond = WorldBuilder.GetHighwayVertList(v);
                        break;
                    }
                }
            }

            // segment join logic
            if (vertListFirst != null && vertListSecond != null && firstIdx >= 0 && secondIdx >= 0)
            {
                // Direct connection with existing path
                bool done = false;
                // *--|____/*
                foreach ((Vector2, (Vector2Int, Vector2Int))tup in vertListFirst)
                {
                    if (eVec.Item2 == tup.Item2.Item2 || eVec.Item2 == tup.Item2.Item1)
                    {
                        segments.RemoveRange(firstIdx, segments.Count - firstIdx);
                        segments.Insert(firstIdx, tup.Item1);
                        done = true;
                        break;
                    }
                }
                if (!done)
                {
                    // *\____|--*
                    foreach ((Vector2, (Vector2Int, Vector2Int))tup in vertListSecond)
                    {
                        if (eVec.Item1 == tup.Item2.Item2 || eVec.Item1 == tup.Item2.Item1)
                        {
                            segments.RemoveRange(0, secondIdx);

                            segments.Insert(0, tup.Item1);
                            done = true;
                            break;
                        }
                    }
                }

                if (!done)
                {
                    // No direct connection cases (needs paths from start and end)
                    (bool, (Vector2Int, Vector2Int))sameEdgeRes = DoListsContainSameEdge(vertListFirst, vertListSecond);
                    if (sameEdgeRes.Item1)
                    {
                        Vector2 con1 = FindVecWithEdge(sameEdgeRes.Item2, vertListFirst), con2 = FindVecWithEdge(sameEdgeRes.Item2, vertListSecond);
                        if (con1 == con2) // same vert
                                          // *--|-----* pass through path
                        {
                            segments.RemoveAt(firstIdx);
                            segments.Insert(firstIdx, con1);
                        }
                        else // diff vert
                             // *--|__|--* join at existing path
                             //Debug.Log(firstIdx + " " + secondIdx);
                        {
                            segments.RemoveRange(firstIdx, secondIdx - firstIdx + 1);
                            segments.Insert(firstIdx, con2);
                            segments.Insert(firstIdx, WorldBuilder.SignalVector);
                            segments.Insert(firstIdx, con1);
                        }
                    }
                    else// not matched so edges different!
                    {
                        Vector2 con1 = vertListFirst[0].Item1, con2 = vertListSecond[0].Item1;
                        //neighbor or not
                        if (DoListsContainNeighbors(vertListFirst, vertListSecond))
                        {
                            // *--\./---*
                            segments.RemoveRange(firstIdx, secondIdx - firstIdx + 1);
                            segments.Insert(firstIdx, con2);
                            segments.Insert(firstIdx, WorldBuilder.SignalVector);
                            segments.Insert(firstIdx, con1);
                        }
                        else
                        {
                            // *--|--|--* pass through paths
                            segments.RemoveAt(secondIdx);
                            segments.RemoveAt(firstIdx);
                            segments.Insert(firstIdx, con1);
                            segments.Insert(secondIdx, con2);
                        }
                    }
                }
            }

            foreach (Vector2 v in segments)
            {
                WorldBuilder.AddHighwayVertToChunkHash(v, eVec);
            }

            if (segments != null)
            {
                highways.Add(segments);
            }

            if (hwCount % Settings.hwPathfindingIncrement == 0)
            {
                yield return(null);
            }
        }
        WorldManager.GenHighwayState = false;
    }
Beispiel #34
0
        public static GeometryBase GetGeometryFromElement(IMesh mesh, int eKey)
        {
            GeometryBase geom = null;

            if (mesh.ContainsElementKey(eKey))
            {
                IElement e = mesh.GetElementWithKey(eKey);

                if (e.TopologicDimension == 1)
                {
                    Point3d p1 = mesh.GetVertexWithKey(e.Vertices[0]).RhinoPoint;
                    Point3d p2 = mesh.GetVertexWithKey(e.Vertices[1]).RhinoPoint;
                    geom = new LineCurve(p1, p2);
                }
                if (e.TopologicDimension == 2)
                {
                    Surface   f;
                    Point3d[] pts = new Point3d[e.VerticesCount];
                    for (int i = 0; i < e.VerticesCount; i++)
                    {
                        pts[i] = mesh.GetVertexWithKey(e.Vertices[i]).RhinoPoint;
                    }

                    if (pts.Length == 4)
                    {
                        f = NurbsSurface.CreateFromCorners(pts[0], pts[1], pts[2], pts[3]);
                    }
                    else if (pts.Length == 3)
                    {
                        f = NurbsSurface.CreateFromCorners(pts[0], pts[1], pts[2]);
                    }
                    else
                    {
                        f = Brep.CreateEdgeSurface(new PolylineCurve[] { new PolylineCurve(pts), new PolylineCurve(new Point3d[] { pts[pts.Length - 1], pts[0] }) }).Surfaces[0];
                    }
                    geom = f.ToBrep();
                }
                else if (e.TopologicDimension == 3)
                {
                    Brep[] faces = new Brep[e.HalfFacetsCount];

                    for (int i = 1; i <= e.HalfFacetsCount; i++)
                    {
                        int[] hf;
                        e.GetHalfFacetWithPrincipalNodesOnly(i, out hf);

                        Point3d[] pts = new Point3d[hf.Length];

                        for (int j = 0; j < hf.Length; j++)
                        {
                            pts[j] = mesh.GetVertexWithKey(hf[j]).RhinoPoint;
                        }

                        if (pts.Length == 4)
                        {
                            faces[i - 1] = Brep.CreateFromCornerPoints(pts[0], pts[1], pts[2], pts[3], RhinoDoc.ActiveDoc.ModelAbsoluteTolerance);
                        }
                        else
                        {
                            faces[i - 1] = Brep.CreateFromCornerPoints(pts[0], pts[1], pts[2], RhinoDoc.ActiveDoc.ModelAbsoluteTolerance);
                        }
                    }

                    geom = Brep.JoinBreps(faces, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance)[0];
                }
            }

            return(geom);
        }
 public string GetLoadedPath(IMesh mesh)
 {
     return(MeshFactory.GetLoadedPath(mesh));
 }
 /// <summary>
 /// add the loaded chunk mesh data to this level
 /// </summary>
 /// <param name="chunkLocation"></param>
 public abstract void setChunkMesh(Coordinate chunkLocation, IMesh chunkMesh);
Beispiel #37
0
 public void Smooth(IMesh mesh)
 {
     Smooth(mesh, 10);
 }
Beispiel #38
0
 public void FillMesh(IMesh mesh, IBrush brush)
 {
     base.innerRefT.FillMesh(mesh, brush);
 }
Beispiel #39
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            IMesh mesh = new IMesh();

            DA.GetData(0, ref mesh);

            GH_Structure <GH_String> sibHalfFacets = new GH_Structure <GH_String>();
            GH_Structure <GH_String> elements      = new GH_Structure <GH_String>();
            GH_Structure <GH_Number> eKeys         = new GH_Structure <GH_Number>();
            IElement e;
            Int64    sibData;
            GH_Path  path;
            GH_Path  oPath = new GH_Path(0);

            foreach (int eK in mesh.ElementsKeys)
            {
                path = new GH_Path(eK);
                e    = mesh.GetElementWithKey(eK);

                elements.Append(new GH_String(e.ToString()), oPath);
                eKeys.Append(new GH_Number(eK), oPath);

                for (int i = 1; i <= e.HalfFacetsCount; i++)
                {
                    GH_String msg = new GH_String("");
                    sibData = e.GetSiblingHalfFacet(i);

                    if (sibData != 0)
                    {
                        if (e.TopologicDimension == 2)
                        {
                            msg = new GH_String("Face Element ID: " + e.GetSiblingElementID(i) + " :: Half-Edge ID: " + e.GetSiblingHalfFacetID(i));
                        }
                        if (e.TopologicDimension == 3)
                        {
                            msg = new GH_String("Solid Element ID: " + e.GetSiblingElementID(i) + " :: Half-Face ID: " + e.GetSiblingHalfFacetID(i));
                        }
                    }
                    else
                    {
                        if (e.TopologicDimension == 2)
                        {
                            msg = new GH_String("Naked Half-Edge");
                        }
                        if (e.TopologicDimension == 3)
                        {
                            msg = new GH_String("Naked Half-Face");
                        }
                    }

                    sibHalfFacets.Append(msg, path);
                }
            }

            //Vertex to half-edge
            GH_Structure <GH_String> vertexToHalfFacet = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>  vertices          = new GH_Structure <GH_Point>();
            GH_Structure <GH_Number> vKeys             = new GH_Structure <GH_Number>();

            foreach (ITopologicVertex v in mesh.Vertices)
            {
                GH_String msg = new GH_String("Empty");
                if (v.V2HF > 0)
                {
                    msg.Value = v.SiblingHalfFacetDataToString();
                }

                vertexToHalfFacet.Append(msg, oPath);
                vertices.Append(new GH_Point(v.RhinoPoint), oPath);
                vKeys.Append(new GH_Number(v.Key), oPath);
            }


            DA.SetDataTree(0, vertices);
            DA.SetDataTree(1, vKeys);
            DA.SetDataTree(2, elements);
            DA.SetDataTree(3, eKeys);
            DA.SetDataTree(4, sibHalfFacets);
            DA.SetDataTree(5, vertexToHalfFacet);
        }
 public void AddMesh(IMesh mesh)
 {
     map.Add(mesh.Guid, mesh);
 }
Beispiel #41
0
        public static Mesh TryGetRhinoMesh(IMesh iM, bool trianglesOnly = false)
        {
            Mesh rM = new Mesh();

            Dictionary <int, int> maps = new Dictionary <int, int>();
            int idx = 0;

            foreach (ITopologicVertex v in iM.Vertices)
            {
                rM.Vertices.Add(v.RhinoPoint);
                maps.Add(v.Key, idx);
                idx++;
            }

            int vKey = iM.FindNextVertexKey();

            int[] hf;
            foreach (IElement e in iM.Elements)
            {
                if (e.TopologicDimension == 1)
                {
                    rM.Faces.AddFace(new MeshFace(maps[e.Vertices[0]], maps[e.Vertices[1]], maps[e.Vertices[0]]));
                }
                else if (e.TopologicDimension == 2)
                {
                    if (e.VerticesCount == 3)
                    {
                        rM.Faces.AddFace(new MeshFace(maps[e.Vertices[0]], maps[e.Vertices[1]], maps[e.Vertices[2]]));
                    }
                    else if (e.VerticesCount == 4)
                    {
                        if (trianglesOnly)
                        {
                            rM.Faces.AddFace(new MeshFace(maps[e.Vertices[0]], maps[e.Vertices[1]], maps[e.Vertices[3]]));
                            rM.Faces.AddFace(new MeshFace(maps[e.Vertices[3]], maps[e.Vertices[1]], maps[e.Vertices[2]]));
                        }
                        else
                        {
                            rM.Faces.AddFace(new MeshFace(maps[e.Vertices[0]], maps[e.Vertices[1]], maps[e.Vertices[2]], maps[e.Vertices[3]]));
                        }
                    }
                    else
                    {
                        IPoint3D pos = ISubdividor.ComputeAveragePosition(e.Vertices, iM);
                        rM.Vertices.Add(new Point3d(pos.X, pos.Y, pos.Z));
                        maps.Add(vKey, idx);
                        for (int i = 1; i <= e.HalfFacetsCount; i++)
                        {
                            e.GetHalfFacet(i, out hf);
                            rM.Faces.AddFace(new MeshFace(maps[hf[0]], maps[hf[1]], maps[vKey]));
                        }
                        vKey++;
                        idx++;
                    }
                }
                else if (e.TopologicDimension == 3)
                {
                    if (!iM.IsMultidimensionalMesh)
                    {
                        for (int i = 1; i <= e.HalfFacetsCount; i++)
                        {
                            if (e.IsNakedSiblingHalfFacet(i))
                            {
                                e.GetHalfFacet(i, out hf);
                                if (hf.Length == 3)
                                {
                                    rM.Faces.AddFace(new MeshFace(maps[hf[0]], maps[hf[1]], maps[hf[2]]));
                                }
                                else
                                {
                                    rM.Faces.AddFace(new MeshFace(maps[hf[0]], maps[hf[1]], maps[hf[2]], maps[hf[3]]));
                                }
                            }
                        }
                    }
                    else
                    {
                        if (e.IsBoundaryElement())
                        {
                            for (int i = 1; i <= e.HalfFacetsCount; i++)
                            {
                                e.GetHalfFacet(i, out hf);
                                if (hf.Length == 3)
                                {
                                    rM.Faces.AddFace(new MeshFace(maps[hf[0]], maps[hf[1]], maps[hf[2]]));
                                }
                                else
                                {
                                    rM.Faces.AddFace(new MeshFace(maps[hf[0]], maps[hf[1]], maps[hf[2]], maps[hf[3]]));
                                }
                            }
                        }
                    }
                }
            }

            rM.UnifyNormals();
            return(rM);
        }
Beispiel #42
0
 public void ReleaseMesh(IMesh imesh)
 {
 }
Beispiel #43
0
 public void Write(IMesh mesh, Stream stream)
 {
     throw new NotImplementedException();
 }
Beispiel #44
0
 public WoWMeshManager(IMeshManager meshManager)
 {
     this.meshManager = meshManager;
     chunkMesh        = meshManager.CreateMesh(ChunkMesh.Create());
 }
 public override void Execute(IMesh mesh)
 {
     mesh.Scale(factor);
     Log($"Scaling by {factor.ToString("0.00", CultureInfo.InvariantCulture)} done");
 }
Beispiel #46
0
        int CreateGlobalVertex(IMesh mesh, int face, int facePart, List <GlobalVertex> vertices, bool hasUV, bool hasUV2, VNormal[] vnorms, List <GlobalVertex>[] verticesAlreadyExported, IISkinContextData skinContextData)
        {
            var faceObject  = mesh.Faces[face];
            var vertexIndex = (int)faceObject.V[facePart];

            var vertex = new GlobalVertex
            {
                BaseIndex = vertexIndex,
                Position  = mesh.Verts[vertexIndex],
                Normal    = vnorms[vertexIndex].GetNormal(verticesAlreadyExported != null ? 1 : faceObject.SmGroup)
            };

            if (hasUV)
            {
                var tvertexIndex = (int)mesh.TvFace[face].T[facePart];
                vertex.UV = Loader.Global.Point2.Create(mesh.TVerts[tvertexIndex].X, mesh.TVerts[tvertexIndex].Y);
            }

            if (hasUV2)
            {
                var tvertexIndex = (int)mesh.MapFaces(2)[face].T[facePart];
                vertex.UV2 = Loader.Global.Point2.Create(mesh.MapVerts(2)[tvertexIndex].X, mesh.MapVerts(2)[tvertexIndex].Y);
            }

            if (skinContextData != null)
            {
                float weight0 = 0;
                float weight1 = 0;
                float weight2 = 0;
                int   bone0   = bonesCount;
                int   bone1   = bonesCount;
                int   bone2   = bonesCount;
                int   bone3   = bonesCount;
                int   nbBones = skinContextData.GetNumAssignedBones(vertexIndex);

                if (nbBones > 0)
                {
                    bone0   = skinContextData.GetAssignedBone(vertexIndex, 0);
                    weight0 = skinContextData.GetBoneWeight(vertexIndex, 0);
                }

                if (nbBones > 1)
                {
                    bone1   = skinContextData.GetAssignedBone(vertexIndex, 1);
                    weight1 = skinContextData.GetBoneWeight(vertexIndex, 1);
                }

                if (nbBones > 2)
                {
                    bone2   = skinContextData.GetAssignedBone(vertexIndex, 2);
                    weight2 = skinContextData.GetBoneWeight(vertexIndex, 2);
                }

                if (nbBones > 3)
                {
                    bone3 = skinContextData.GetAssignedBone(vertexIndex, 3);
                }

                if (nbBones == 0)
                {
                    weight0 = 1.0f;
                    bone0   = bonesCount;
                }

                if (nbBones > 4)
                {
                    RaiseError("Too many bones influences per vertex: " + nbBones + ". Babylon.js only support 4 bones influences per vertex.", 2);
                }

                vertex.Weights      = Loader.Global.Point4.Create(weight0, weight1, weight2, 1.0 - weight0 - weight1 - weight2);
                vertex.BonesIndices = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
            }

            if (verticesAlreadyExported != null)
            {
                if (verticesAlreadyExported[vertexIndex] != null)
                {
                    var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);

                    if (index > -1)
                    {
                        return(verticesAlreadyExported[vertexIndex][index].CurrentIndex);
                    }
                }
                else
                {
                    verticesAlreadyExported[vertexIndex] = new List <GlobalVertex>();
                }

                vertex.CurrentIndex = vertices.Count;
                verticesAlreadyExported[vertexIndex].Add(vertex);
            }

            vertices.Add(vertex);

            return(vertices.Count - 1);
        }
Beispiel #47
0
 /// <summary>
 /// Create an translation modifer
 /// </summary>
 /// <param name="mesh">original mesh</param>
 /// <param name="offset">translation offset</param>
 public Translate(IMesh mesh, Vec3 offset) : base(mesh)
 {
     this.Offset = offset;
 }
Beispiel #48
0
        public void GetMesh(ODEPhysRepData repData)
        {
            PhysicsActor actor = repData.actor;

            PrimitiveBaseShape pbs = repData.pbs;

            repData.mesh   = null;
            repData.hasOBB = false;

            if (!needsMeshing(repData))
            {
                repData.meshState = MeshState.noNeed;
                return;
            }

            if (repData.meshState == MeshState.MeshFailed)
            {
                return;
            }

            if (pbs.SculptEntry)
            {
                if (repData.meshState == MeshState.AssetFailed)
                {
                    if (pbs.SculptTexture == repData.assetID)
                    {
                        return;
                    }
                }
            }

            repData.meshState = MeshState.noNeed;

            IMesh   mesh      = null;
            Vector3 size      = repData.size;
            byte    shapetype = repData.shapetype;

            bool convex;
            int  clod = (int)LevelOfDetail.High;

            if (shapetype == 0)
            {
                convex = false;
            }
            else
            {
                convex = true;
                if (pbs.SculptType != (byte)SculptType.Mesh)
                {
                    clod = (int)LevelOfDetail.Low;
                }
            }

            mesh = m_mesher.CreateMesh(actor.Name, pbs, size, clod, true, convex, true);

            if (mesh == null)
            {
                if (pbs.SculptEntry)
                {
                    if (pbs.SculptTexture == UUID.Zero)
                    {
                        return;
                    }

                    repData.assetID = pbs.SculptTexture;

                    if (pbs.SculptData == null || pbs.SculptData.Length == 0)
                    {
                        repData.meshState = MeshState.needAsset;
                        return;
                    }
                }
            }

            repData.mesh           = mesh;
            repData.pbs.SculptData = Utils.EmptyBytes;

            if (mesh == null)
            {
                if (pbs.SculptEntry)
                {
                    repData.meshState = MeshState.AssetFailed;
                }
                else
                {
                    repData.meshState = MeshState.MeshFailed;
                }

                return;
            }

            repData.meshState = MeshState.AssetOK;

            return;
        }
 /// <summary>
 /// TODO: wtf is zis??
 /// </summary>
 /// <param name="mesh"></param>
 /// <returns></returns>
 public BoundingBox GetBoundingBox(IMesh mesh)
 {
     return(MeshFactory.GetBoundingBox(mesh));
 }
Beispiel #50
0
 public MeshDebugView(IMesh g)
 {
     Interface = g;
 }
Beispiel #51
0
        // see if we need a mesh and if so if we have a cached one
        // called with a new repData
        public void CheckMesh(ODEPhysRepData repData)
        {
            PhysicsActor       actor = repData.actor;
            PrimitiveBaseShape pbs   = repData.pbs;

            if (!needsMeshing(repData))
            {
                repData.meshState = MeshState.noNeed;
                repData.hasOBB    = false;
                return;
            }

            IMesh mesh = null;

            Vector3 size = repData.size;

            int  clod = (int)LevelOfDetail.High;
            bool convex;
            byte shapetype = repData.shapetype;

            if (shapetype == 0)
            {
                convex = false;
            }
            else
            {
                convex = true;
                // sculpts pseudo convex
                if (pbs.SculptEntry && pbs.SculptType != (byte)SculptType.Mesh)
                {
                    clod = (int)LevelOfDetail.Low;
                }
            }

            mesh = m_mesher.GetMesh(actor.Name, pbs, size, clod, true, convex);

            if (mesh == null)
            {
                if (pbs.SculptEntry)
                {
                    if (pbs.SculptTexture != null && pbs.SculptTexture != UUID.Zero)
                    {
                        repData.assetID   = pbs.SculptTexture;
                        repData.meshState = MeshState.needAsset;
                    }
                    else
                    {
                        repData.meshState = MeshState.MeshFailed;
                    }

                    return;
                }
                else
                {
                    repData.meshState = MeshState.needMesh;
                    mesh = m_mesher.CreateMesh(actor.Name, pbs, size, clod, true, convex, true);
                    if (mesh == null)
                    {
                        repData.meshState = MeshState.MeshFailed;
                        return;
                    }
                }
            }

            repData.meshState = MeshState.AssetOK;
            repData.mesh      = mesh;
            repData.OBB       = mesh.GetOBB();
            repData.OBBOffset = mesh.GetCentroid();
            repData.hasOBB    = true;

            if (pbs.SculptEntry)
            {
                repData.assetID = pbs.SculptTexture;
            }

            pbs.SculptData = Utils.EmptyBytes;
            return;
        }
Beispiel #52
0
        protected override void LoadContent()
        {
            base.LoadContent();

            // vertex declaration
            VertexElement[] vertexElements = new VertexElement[]
            {
                // vertex position
                new VertexElement(0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0),
                // texture coordinates
                new VertexElement(0, 12, VertexElementFormat.Vector2, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0),
            };
            VertexDeclaration vdecl = new VertexDeclaration(game.Graphics.Device, vertexElements);

            // vertices
            VertexPositionTexture[] verts = new VertexPositionTexture[7];
            verts[0] = new VertexPositionTexture(new Vector3(-0.5f, 0, 1), new Vector2(1, 1));
            verts[1] = new VertexPositionTexture(new Vector3(0, 0, 1), new Vector2(1, 0.5f));
            verts[2] = new VertexPositionTexture(new Vector3(0.5f, 0, 1), new Vector2(1, 0));
            verts[3] = new VertexPositionTexture(new Vector3(0.5f, 0, 0), new Vector2(0, 0));
            verts[4] = new VertexPositionTexture(new Vector3(0.1f, 0.5f, 0), new Vector2(0, 0.4f));
            verts[5] = new VertexPositionTexture(new Vector3(-0.1f, 0.5f, 0), new Vector2(0, 0.6f));
            verts[6] = new VertexPositionTexture(new Vector3(-0.5f, 0, 0), new Vector2(0, 1));
            // vertexBuffer
            VertexBuffer vertexBuffer = new VertexBuffer(game.Graphics.Device,
                                                         VertexPositionTexture.SizeInBytes * verts.Length,
                                                         BufferUsage.WriteOnly | BufferUsage.None);

            vertexBuffer.SetData(verts);

            // indices
            short[] indices = new short[15];
            indices[0]  = 0;
            indices[1]  = 6;
            indices[2]  = 1;
            indices[3]  = 1;
            indices[4]  = 3;
            indices[5]  = 2;
            indices[6]  = 6;
            indices[7]  = 5;
            indices[8]  = 1;
            indices[9]  = 5;
            indices[10] = 4;
            indices[11] = 1;
            indices[12] = 4;
            indices[13] = 3;
            indices[14] = 1;
            // indexBuffer
            IndexBuffer ib = new IndexBuffer(
                game.Graphics.Device,
                sizeof(short) * indices.Length,
                BufferUsage.None,
                IndexElementSize.SixteenBits
                );

            ib.SetData(indices);

            IMaterial[] materials = new IMaterial[1];
            materials[0] = Material.Create(game, "AfterBurner", InstancingType.None);

            IMesh[] meshes = new IMesh[1];
            meshes[0] = new VbIbAdapterMesh(game, vertexBuffer, ib, vdecl, 5, 7, "AfterBurner");

            Model = new Engine.Graphics.Models.Model(game, meshes, materials, "AfterBurner");

            maxSize = LocalScale;

            rotation = LocalRotation;
        }
Beispiel #53
0
 public void Dispose()
 {
     meshManager.DisposeMesh(chunkMesh);
     chunkMesh = null !;
 }
Beispiel #54
0
 public MeshRenderData(IMesh mesh)
 {
     Mesh = mesh;
 }
Beispiel #55
0
        void Init(IntPtr pParam)
        {
            IEngineSubSystem pSubSys;

            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_CORE_RENDERER, out pSubSys);
            pCoreRenderer = (ICoreRenderer)pSubSys;

            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_RENDER, out pSubSys);
            IRender pRender = (IRender)pSubSys;

            pRender.GetRender3D(out pRender3D);
            TColor4 c = TColor4.ColorGray();

            pRender.SetClearColor(ref c);

            IResourceManager pResMan;

            pEngineCore.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_RESOURCE_MANAGER, out pSubSys);
            pResMan = (IResourceManager)pSubSys;

            IEngineBaseObject pBaseObj;

            const uint load_3d_flag = (uint)(E_TEXTURE_LOAD_FLAGS.TLF_FILTERING_ANISOTROPIC |
                                             E_TEXTURE_LOAD_FLAGS.TLF_ANISOTROPY_4X | E_TEXTURE_LOAD_FLAGS.TLF_GENERATE_MIPMAPS);

            pResMan.Load(RESOURCE_PATH + "fonts\\Times_New_Roman_18_Bold.dft", out pBaseObj,
                         (uint)E_BITMAP_FONT_LOAD_FLAGS.BFLF_GENERATE_MIPMAPS);
            pFont = (IBitmapFont)pBaseObj;
            pResMan.Load(RESOURCE_PATH + "textures\\grass.jpg", out pBaseObj, load_3d_flag |
                         (uint)E_TEXTURE_LOAD_FLAGS.TLF_COORDS_REPEAT /* cause we will tile this texture */);
            pTexGrass = (ITexture)pBaseObj;

            pResMan.Load(RESOURCE_PATH + "sprites\\cartoon_owl.png", out pBaseObj, load_3d_flag | (uint)E_TEXTURE_LOAD_FLAGS.TLF_COORDS_CLAMP);
            pTexOwl = (ITexture)pBaseObj;
            pTexOwl.SetFrameSize(48, 128);

            pResMan.Load(RESOURCE_PATH + "meshes\\trees\\tree_1.png", out pBaseObj, load_3d_flag | (uint)E_TEXTURE_LOAD_FLAGS.TLF_COORDS_CLAMP);
            pTexTree1 = (ITexture)pBaseObj;
            pResMan.Load(RESOURCE_PATH + "meshes\\trees\\tree_1.dmd", out pBaseObj, (uint)E_MESH_MODEL_LOAD_FLAGS.MMLF_FORCE_MODEL_TO_MESH);
            pMeshTree1 = (IMesh)pBaseObj;

            pResMan.Load(RESOURCE_PATH + "meshes\\trees\\tree_2.png", out pBaseObj, load_3d_flag | (uint)E_TEXTURE_LOAD_FLAGS.TLF_COORDS_CLAMP);
            pTexTree2 = (ITexture)pBaseObj;
            pResMan.Load(RESOURCE_PATH + "meshes\\trees\\tree_2.dmd", out pBaseObj, (uint)E_MESH_MODEL_LOAD_FLAGS.MMLF_FORCE_MODEL_TO_MESH);
            pMeshTree2 = (IMesh)pBaseObj;

            pResMan.Load(RESOURCE_PATH + "meshes\\trees\\tree_3.png", out pBaseObj, load_3d_flag | (uint)E_TEXTURE_LOAD_FLAGS.TLF_COORDS_CLAMP);
            pTexTree3 = (ITexture)pBaseObj;
            pResMan.Load(RESOURCE_PATH + "meshes\\trees\\tree_3.dmd", out pBaseObj, (uint)E_MESH_MODEL_LOAD_FLAGS.MMLF_FORCE_MODEL_TO_MESH);
            pMeshTree3 = (IMesh)pBaseObj;

            pResMan.Load(RESOURCE_PATH + "meshes\\zard\\zard_diff.dds", out pBaseObj, load_3d_flag | (uint)E_TEXTURE_LOAD_FLAGS.TLF_COORDS_CLAMP);
            pTexZard = (ITexture)pBaseObj;
            pResMan.Load(RESOURCE_PATH + "meshes\\zard\\zard_walk.dmd", out pBaseObj, 0);
            pModelZard = (IModel)pBaseObj;

            // add some fog to the scene
            pRender3D.SetFogColor(ref c);
            pRender3D.SetLinearFogBounds(1.5f, 4f);
            pRender3D.ToggleFog(true);

            PlaneDataPtr = Unmanaged.New <float>(c_afPlane.Length);
            PlaneDataPtr.Copy(c_afPlane);

            desc = new TDrawDataDesc
                   (
                PlaneDataPtr,
                12 * sizeof(float),
                24 * sizeof(float),
                false
                   );
        }
Beispiel #56
0
        public IOWriteResult Write(TextWriter writer, List <WriteMesh> vMeshes, WriteOptions options)
        {
            if (options.groupNamePrefix != null)
            {
                GroupNamePrefix = options.groupNamePrefix;
            }

            if (options.GroupNameF != null)
            {
                GroupNameF = options.GroupNameF;
            }

            int nAccumCountV  = 1;                  // OBJ indices always start at 1
            int nAccumCountUV = 1;

            // collect materials
            string sMaterialLib   = "";
            int    nHaveMaterials = 0;

            if (options.bWriteMaterials && options.MaterialFilePath.Length > 0)
            {
                List <GenericMaterial> vMaterials = MeshIOUtil.FindUniqueMaterialList(vMeshes);
                IOWriteResult          ok         = write_materials(vMaterials, options);
                if (ok.code == IOCode.Ok)
                {
                    sMaterialLib   = Path.GetFileName(options.MaterialFilePath);
                    nHaveMaterials = vMeshes.Count;
                }
            }


            if (options.AsciiHeaderFunc != null)
            {
                writer.WriteLine(options.AsciiHeaderFunc());
            }

            if (sMaterialLib != "")
            {
                writer.WriteLine("mtllib {0}", sMaterialLib);
            }

            for (int mi = 0; mi < vMeshes.Count; ++mi)
            {
                IMesh mesh = vMeshes[mi].Mesh;

                if (options.ProgressFunc != null)
                {
                    options.ProgressFunc(mi, vMeshes.Count);
                }

                bool bVtxColors = options.bPerVertexColors && mesh.HasVertexColors;
                bool bNormals   = options.bPerVertexNormals && mesh.HasVertexNormals;

                // use separate UV set if we have it, otherwise write per-vertex UVs if we have those
                bool bVtxUVs = options.bPerVertexUVs && mesh.HasVertexUVs;
                if (vMeshes[mi].UVs != null)
                {
                    bVtxUVs = false;
                }

                int[] mapV = new int[mesh.MaxVertexID];

                // write vertices for this mesh
                foreach (int vi in mesh.VertexIndices())
                {
                    mapV[vi] = nAccumCountV++;
                    Vector3d v = mesh.GetVertex(vi);
                    if (bVtxColors)
                    {
                        Vector3d c = mesh.GetVertexColor(vi);
                        writer.WriteLine("v {0} {1} {2} {3:F8} {4:F8} {5:F8}", v[0], v[1], v[2], c[0], c[1], c[2]);
                    }
                    else
                    {
                        writer.WriteLine("v {0} {1} {2}", v[0], v[1], v[2]);
                    }

                    if (bNormals)
                    {
                        Vector3d n = mesh.GetVertexNormal(vi);
                        writer.WriteLine("vn {0:F10} {1:F10} {2:F10}", n[0], n[1], n[2]);
                    }

                    if (bVtxUVs)
                    {
                        Vector2f uv = mesh.GetVertexUV(vi);
                        writer.WriteLine("vt {0:F10} {1:F10}", uv.x, uv.y);
                    }
                }

                // write independent UVs for this mesh, if we have them
                IIndexMap   mapUV = (bVtxUVs) ? new IdentityIndexMap() : null;
                DenseUVMesh uvSet = null;
                if (vMeshes[mi].UVs != null)
                {
                    uvSet = vMeshes[mi].UVs;
                    int nUV     = uvSet.UVs.Length;
                    var fullMap = new IndexMap(false, nUV);                       // [TODO] do we really need a map here? is just integer shift, no?
                    for (int ui = 0; ui < nUV; ++ui)
                    {
                        writer.WriteLine("vt {0:F8} {1:F8}", uvSet.UVs[ui].x, uvSet.UVs[ui].y);
                        fullMap[ui] = nAccumCountUV++;
                    }
                    mapUV = fullMap;
                }

                // check if we need to write usemtl lines for this mesh
                bool bWriteMaterials = nHaveMaterials > 0 &&
                                       vMeshes[mi].TriToMaterialMap != null &&
                                       vMeshes[mi].Materials != null;

                // various ways we can write triangles to minimize state changes...
                // [TODO] support writing materials when mesh has groups!!
                if (options.bWriteGroups && mesh.HasTriangleGroups)
                {
                    write_triangles_bygroup(writer, mesh, mapV, uvSet, mapUV, bNormals);
                }
                else
                {
                    write_triangles_flat(writer, vMeshes[mi], mapV, uvSet, mapUV, bNormals, bWriteMaterials);
                }

                if (options.ProgressFunc != null)
                {
                    options.ProgressFunc(mi + 1, vMeshes.Count);
                }
            }


            return(new IOWriteResult(IOCode.Ok, ""));
        }
Beispiel #57
0
        protected override void LoadContent()
        {
            base.LoadContent();

            IMesh[] meshes = new IMesh[1];

            // vertex declaration
            VertexElement[] vertexElements = new VertexElement[]
            {
                // vertex data
                // vertex position
                new VertexElement(0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0),
                // texture coordinates
                new VertexElement(0, 12, VertexElementFormat.Vector2, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 1),

                // instance data
                // instance transform matrix 3x4
                new VertexElement(1, 0, VertexElementFormat.Single, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0)
            };
            VertexDeclaration vdecl = new VertexDeclaration(Game.Graphics.Device, vertexElements);

            // vertices
            VertexPositionTexture[] verts = new VertexPositionTexture[4];
            verts[0] = new VertexPositionTexture(new Vector3(-8f, 0, -4), new Vector2(0, 0));
            verts[1] = new VertexPositionTexture(new Vector3(-8f, 0, 0), new Vector2(0, 1));
            verts[2] = new VertexPositionTexture(new Vector3(8f, 0, -4), new Vector2(1, 0));
            verts[3] = new VertexPositionTexture(new Vector3(8f, 0, 0), new Vector2(1, 1));
            // vertexBuffer
            VertexBuffer vertexBuffer = new VertexBuffer(Game.Graphics.Device,
                                                         VertexPositionTexture.SizeInBytes * verts.Length,
                                                         BufferUsage.WriteOnly | BufferUsage.None);

            vertexBuffer.SetData <VertexPositionTexture>(verts);

            // instances
            instanceVertices = new InstanceVertex[instanceCount];
            for (int i = 0; i < instanceCount; ++i)
            {
                instanceVertices[i] = new InstanceVertex(i);
            }
            // instanceBuffer
            instanceBuffer = new VertexBuffer(Game.Graphics.Device,
                                              typeof(InstanceVertex),
                                              instanceCount,
                                              BufferUsage.WriteOnly);
            instanceBuffer.SetData <InstanceVertex>(instanceVertices);

            // indices
            short[] indices = new short[6];
            indices[0] = 0;
            indices[1] = 2;
            indices[2] = 3;
            indices[3] = 3;
            indices[4] = 1;
            indices[5] = 0;

            // ib
            IndexBuffer ib = new IndexBuffer(
                Game.Graphics.Device,
                sizeof(short) * indices.Length,
                BufferUsage.None,
                IndexElementSize.SixteenBits
                );

            ib.SetData <short>(indices);

            meshes[0] = new VbIbAdapterMesh(Game, vertexBuffer, instanceBuffer, ib, vdecl, 2, 4, instanceCount, "UltraPhaserProjectile");

            IMaterial[] materials = new IMaterial[1];
            materials[0] = Material.Create(Game, "PhaserTex", InstancingType.Constants);

            projectileInstances = new DynamicInstancingModel(Game, meshes, materials, "Phaser");
            foreach (EffectParameter parameter in projectileInstances.Materials[0].Effect.Parameters)
            {
                if (parameter.Semantic == "INSTANCE_DATA")
                {
                    instanceParameter = parameter;
                }
            }
        }
Beispiel #58
0
 /// <summary>
 /// Retrieves a single random vertex from the mesh using the
 /// weighted collection of equal distribution along the shape
 /// ignoring high levels of detail.
 /// </summary>
 /// <param name="mesh">The mesh to retrieve the vertices from.</param>
 /// <param name="rand">The randomizer for deterministic behaviour.</param>
 /// <returns>A single verted randomly chosen from the mesh.</returns>
 /// <exception cref="ArgumentNullException">If the specified mesh or randomizer
 /// does not exist.</exception>
 public static Vector3 GetRandomVertex(this IMesh mesh, Random rand)
 => GetRandomVertices(mesh, 1, rand)[0];
 /// <summary>
 /// Method for getting a random vertex of a mesh.
 /// </summary>
 /// <param name="mesh">The mesh of which the random vertices will be taken.</param>
 /// <param name="random">The (threadsafe) random generator.</param>
 /// <returns>The random vertex.</returns>
 private static Vector3 GetRandomVertex(IMesh mesh, Random random)
 => GetRandomVertices(mesh, random, 1)[0];
 /// <summary>
 /// Method for getting a certain number of random vertices from a mesh.
 /// </summary>
 /// <param name="mesh">The mesh of which the random vertices will be taken.</param>
 /// <param name="random">The (threadsafe) random generator.</param>
 /// <param name="numberOfVertices">The number of random vertices.</param>
 /// <returns>An array containing the random vertices.</returns>
 private static Vector3[] GetRandomVertices(IMesh mesh, Random random, int numberOfVertices)
 {
     return(mesh.GetRandomVertices(numberOfVertices, random));
 }