GetSubEntity() public method

Gets the SubEntity at the specified index.
public GetSubEntity ( int index ) : SubEntity
index int
return SubEntity
        /// <summary>
        ///   Add the collision data for an object.  This involves looking 
        ///   for a physics file that matches the mesh file's name, and 
        ///   loading the information from that file to build collision 
        ///   volumes.
        /// </summary>
        /// <param name="objNode">the object for which we are adding the collision data</param>
        private void AddCollisionObject(Entity modelEntity, SceneNode modelSceneNode,
                                        long oid, string physicsName)
        {
            // Create a set of collision shapes for the object
            List<CollisionShape> shapes = new List<CollisionShape>();
            PhysicsData pd = new PhysicsData();
            PhysicsSerializer ps = new PhysicsSerializer();

            try {
                Stream stream = ResourceManager.FindCommonResourceData(physicsName);
                ps.ImportPhysics(pd, stream);
                for (int i=0; i<modelEntity.SubEntityCount; i++) {
                    SubEntity subEntity = modelEntity.GetSubEntity(i);
                    if (subEntity.IsVisible) {
                        string submeshName = subEntity.SubMesh.Name;
                        List<CollisionShape> subEntityShapes = pd.GetCollisionShapes(submeshName);
                        foreach (CollisionShape subShape in subEntityShapes) {
                            // static objects will be transformed here, but movable objects
                            // are transformed on the fly
                            subShape.Transform(modelSceneNode.DerivedScale,
                                               modelSceneNode.DerivedOrientation,
                                               modelSceneNode.DerivedPosition);
                            shapes.Add(subShape);
                            log.InfoFormat("Added collision shape: {0} for {1}",
                                           subShape, submeshName);
                        }
                    }
                }
            } catch (Exception e) {
                // Unable to load physics data -- use a sphere or no collision data?
                log.WarnFormat("Unable to load physics data: {0}", e);
            }
            foreach (CollisionShape shape in shapes)
                collisionManager.AddCollisionShape(shape, oid);
        }
Beispiel #2
0
		public void Apply( Entity entity, float time, float weight,
						  bool software, bool hardware )
		{
			foreach ( KeyValuePair<ushort, VertexAnimationTrack> pair in vertexTrackList )
			{
				int handle = pair.Key;
				VertexAnimationTrack track = pair.Value;

				VertexData swVertexData;
				VertexData hwVertexData;
				VertexData origVertexData;
				bool firstAnim = false;
				if ( handle == 0 )
				{
					// shared vertex data
					firstAnim = !entity.BuffersMarkedForAnimation;
					swVertexData = entity.SoftwareVertexAnimVertexData;
					hwVertexData = entity.HardwareVertexAnimVertexData;
					origVertexData = entity.Mesh.SharedVertexData;
					entity.MarkBuffersUsedForAnimation();
				}
				else
				{
					// sub entity vertex data (-1)
					SubEntity s = entity.GetSubEntity( handle - 1 );
					firstAnim = !s.BuffersMarkedForAnimation;
					swVertexData = s.SoftwareVertexAnimVertexData;
					hwVertexData = s.HardwareVertexAnimVertexData;
					origVertexData = s.SubMesh.vertexData;
					s.MarkBuffersUsedForAnimation();
				}
				// Apply to both hardware and software, if requested
				if ( software )
				{
					Debug.Assert( !EqualityComparer<VertexData>.ReferenceEquals( origVertexData, swVertexData ) );
					if ( firstAnim && track.AnimationType == VertexAnimationType.Pose )
					{
						// First time through for a piece of pose animated vertex data
						// We need to copy the original position values to the temp accumulator
						VertexElement origelem =
							origVertexData.vertexDeclaration.FindElementBySemantic( VertexElementSemantic.Position );
						VertexElement destelem =
							swVertexData.vertexDeclaration.FindElementBySemantic( VertexElementSemantic.Position );
						HardwareVertexBuffer origBuffer =
							origVertexData.vertexBufferBinding.GetBuffer( origelem.Source );
						HardwareVertexBuffer destBuffer =
							swVertexData.vertexBufferBinding.GetBuffer( destelem.Source );
						// 						Debug.Assert(!EqualityComparer<HardwareVertexBuffer>.ReferenceEquals(origBuffer, destBuffer));
						if ( !EqualityComparer<HardwareVertexBuffer>.ReferenceEquals( origBuffer, destBuffer ) )
							destBuffer.CopyData( origBuffer, 0, 0, destBuffer.Size, true );
					}
					track.TargetMode = VertexAnimationTargetMode.Software;
					track.ApplyToVertexData( swVertexData, time, weight, entity.Mesh.PoseList );
				}
				if ( hardware )
				{
					track.TargetMode = VertexAnimationTargetMode.Hardware;
					track.ApplyToVertexData( hwVertexData, time, weight, entity.Mesh.PoseList );
				}
			}
		}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="meshName"></param>
        private void PrepareEntity(string meshName)
        {
            if(objectEntity != null) {
                ClearEntity();
            }

            // load mesh if necessary
            originalMesh = (Mesh)MeshManager.Instance.GetByName(meshName);

            // load mesh with shadow buffer so we can do fast reads
            if(originalMesh == null) {
                originalMesh = (Mesh)MeshManager.Instance.Load(
                    meshName,
                    BufferUsage.StaticWriteOnly,
                    BufferUsage.StaticWriteOnly,
                    true, true, 1);

                if(originalMesh == null) {
                    throw new Exception(string.Format("Can't find mesh named '{0}'.", meshName));
                }
            }

            PrepareClonedMesh();

            // create a new entity based on the cloned mesh
            objectEntity = scene.CreateEntity(ENTITY_NAME, MESH_NAME);

            // setting the material here propogates it down to cloned sub entites, no need to clone them
            objectEntity.MaterialName = material.Name;

            Pass pass = material.GetTechnique(0).GetPass(0);

            // add original sub mesh texture layers after the new cube map recently added
            for(int i = 0; i < clonedMesh.SubMeshCount; i++) {
                SubMesh subMesh = clonedMesh.GetSubMesh(i);
                SubEntity subEntity = objectEntity.GetSubEntity(i);

                // does this mesh have its own material set?
                if(subMesh.IsMaterialInitialized) {
                    string matName = subMesh.MaterialName;
                    Material subMat = MaterialManager.Instance.GetByName(matName);

                    if(subMat != null) {
                        subMat.Load();

                        // Clone the sub entities material
                        Material cloned = subMat.Clone(string.Format("CubeMapTempMaterial#{0}", i));
                        Pass clonedPass = cloned.GetTechnique(0).GetPass(0);

                        // add global texture layers to the existing material of the entity
                        for(int j = 0; j < pass.NumTextureUnitStages; j++) {
                            TextureUnitState orgLayer = pass.GetTextureUnitState(j);
                            TextureUnitState newLayer = clonedPass.CreateTextureUnitState(orgLayer.TextureName);
                            orgLayer.CopyTo(newLayer);
                            newLayer.SetColorOperationEx(currentLbx);
                        }

                        // set the new material for the subentity and cache it
                        subEntity.MaterialName = cloned.Name;
                        clonedMaterials.Add(cloned);
                    }
                }
            }

            // attach the entity to the scene
            objectNode.AttachObject(objectEntity);

            // update noise if currently set to on
            if(noiseOn) {
                UpdateNoise();
            }
        }
		///<summary>
		///  Adds an Entity to the static geometry.
		///  <remarks>
		///    This method takes an existing Entity and adds its details to the list of elements to include when building. Note that the Entity itself is not copied or referenced in this method; an Entity is passed simply so that you can change the materials of attached SubEntity objects if you want. You can add the same Entity instance multiple times with different material settings completely safely, and destroy the Entity before destroying this InstancedGeometry if you like. The Entity passed in is simply Must be called before 'Build'.
		///  </remarks>
		///</summary>
		///<param name="ent"> The Entity to use as a definition (the Mesh and Materials referenced will be recorded for the build call). </param>
		///<param name="position"> The world position at which to add this Entity </param>
		///<param name="orientation"> The world orientation at which to add this Entity </param>
		///<param name="scale"> </param>
		public virtual void AddEntity( Entity ent, Vector3 position, Quaternion orientation, Vector3 scale )
		{
			Mesh msh = ent.Mesh;

			// Validate
			if ( msh.IsLodManual )
			{
				LogManager.Instance.Write(
					"(InstancedGeometry): Manual LOD is not supported. Using only highest LOD level for mesh " + msh.Name );
			}

			//get the skeleton of the entity, if that's not already done
			if ( ent.Mesh.Skeleton != null && mBaseSkeleton == null )
			{
				mBaseSkeleton = ent.Mesh.Skeleton;
				mSkeletonInstance = new SkeletonInstance( mBaseSkeleton );
				mSkeletonInstance.Load();
				mAnimationState = ent.GetAllAnimationStates();
			}

			BoundingBox sharedWorldBounds;
			// queue this entities submeshes and choice of material
			// also build the lists of geometry to be used for the source of lods


			for ( int i = 0; i < ent.SubEntityCount; ++i )
			{
				SubEntity se = ent.GetSubEntity( i );
				var q = new QueuedSubMesh();

				// Get the geometry for this SubMesh
				q.submesh = se.SubMesh;
				q.geometryLodList = DetermineGeometry( q.submesh );
				q.materialName = se.MaterialName;
				q.orientation = orientation;
				q.position = position;
				q.scale = scale;
				q.ID = mObjectCount;
			}

			mObjectCount++;
		}
        /// <summary>
        ///   Return the untransformed collision shapes associated
        ///   with a mesh.  If they are already encached, return them,
        ///   else look for a physics file that matches the mesh
        ///   file's name, and  load the information from that file to
        ///   build the collision shapes.
        /// </summary>
        public List<CollisionShape> FindMeshCollisionShapes(string meshName, Entity entity)
        {
            if (collisionManager == null)
            {
                Axiom.Core.LogManager.Instance.Write("DisplayObject.collisionManager is null!");
                return null;
            }
            List<CollisionShape> shapes;
            if (!WorldEditor.Instance.MeshCollisionShapes.TryGetValue(meshName, out shapes))
            {
                string physicsName = Path.GetFileNameWithoutExtension(meshName) + ".physics";
                // Create a set of collision shapes for the object
                shapes = new List<CollisionShape>();
                PhysicsData pd = new PhysicsData();
                PhysicsSerializer ps = new PhysicsSerializer();

                try
                {
                    Stream stream = ResourceManager.FindCommonResourceData(physicsName);
                    ps.ImportPhysics(pd, stream);
                    for (int i = 0; i < entity.SubEntityCount; i++)
                    {
                        SubEntity subEntity = entity.GetSubEntity(i);
                        if (subEntity.IsVisible)
                        {
                            string submeshName = subEntity.SubMesh.Name;
                            List<CollisionShape> subEntityShapes = pd.GetCollisionShapes(submeshName);
                            foreach (CollisionShape subShape in subEntityShapes)
                            {
                                // Clone the shape, and add to the list of
                                // untransformed shapes
                                shapes.Add(subShape);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    // Unable to load physics data -- use a sphere or no collision data?
                    Axiom.Core.LogManager.Instance.Write("Unable to load physics data: " + e);
                    shapes = new List<CollisionShape>();
                }
                WorldEditor.Instance.MeshCollisionShapes[meshName] = shapes;
            }
            List<CollisionShape> newShapes = new List<CollisionShape>();
            foreach (CollisionShape shape in shapes)
                newShapes.Add(shape.Clone());
            return newShapes;
        }
        /// <summary>
        ///     Adds an Entity to the static geometry.
        /// </summary>
        /// <remarks>
        ///     This method takes an existing Entity and adds its details to the 
        ///     list of	elements to include when building. Note that the Entity
        ///     itself is not copied or referenced in this method; an Entity is 
        ///     passed simply so that you can change the materials of attached 
        ///     SubEntity objects if you want. You can add the same Entity 
        ///     instance multiple times with different material settings 
        ///     completely safely, and destroy the Entity before destroying 
        ///     this StaticGeometry if you like. The Entity passed in is simply 
        ///     used as a definition.
        ///
        ///     Note: Must be called before 'build'.
        /// </remarks>
        /// <param name=ent>The Entity to use as a definition (the Mesh and Materials</param>
        /// <param name=position>The world position at which to add this Entity</param>
        /// <param name=orientation>The world orientation at which to add this Entity</param>
        /// <param name=scale>The scale at which to add this entity</param>
        /// <param name=position>The world position at which to add this Entity</position>
        public void AddEntity(Entity ent, Vector3 position, Quaternion orientation, Vector3 scale)
        {
            Mesh msh = ent.Mesh;
            // Validate
            if (msh.IsLodManual)
                log.WarnFormat("StaticGeometry.AddEntity: Manual LOD is not supported. Using only highest LOD level for mesh {0}", msh.Name);

            // queue this entities submeshes and choice of material
            // also build the lists of geometry to be used for the source of lods
            for (int i = 0; i < ent.SubEntityCount; ++i)
            {
                SubEntity se = ent.GetSubEntity(i);
                QueuedSubMesh q = new QueuedSubMesh();

                // Get the geometry for this SubMesh
                q.submesh = se.SubMesh;
                q.geometryLodList = DetermineGeometry(q.submesh);
                q.materialName = se.MaterialName;
                q.orientation = orientation;
                q.position = position;
                q.scale = scale;
                // Determine the bounds based on the highest LOD
                q.worldBounds = CalculateBounds(q.geometryLodList[0].vertexData, position, orientation, scale);
                queuedSubMeshes.Add(q);
            }
        }
		private void SetupInstancedMaterialToEntity( Entity ent )
		{
			for ( int i = 0; i < ent.SubEntityCount; ++i )
			{
				SubEntity se = ent.GetSubEntity( i );
				string materialName = se.MaterialName;
				se.MaterialName = BuildInstancedMaterial( materialName );
			}
		}
Beispiel #8
0
		private void GenerateShaders( Entity entity )
		{
			for ( int i = 0; i < entity.SubEntityCount; i++ )
			{
				SubEntity curSubEntity = entity.GetSubEntity( i );
				string curMaterialName = curSubEntity.MaterialName;
				bool success;

				//Create the shader based technique of this material.
				success = ShaderGenerator.Instance.CreateShaderBasedTechnique( curMaterialName, MaterialManager.DefaultSchemeName,
				                                                               ShaderGenerator.DefaultSchemeName, false );

				//Setup custmo shader sub render states according to current setup.
				if ( success )
				{
					var curMaterial = (Material)MaterialManager.Instance.GetByName( curMaterialName );
					Pass curPass = curMaterial.GetTechnique( 0 ).GetPass( 0 );

					if ( this.specularEnable )
					{
						curPass.Specular = ColorEx.White;
						curPass.Shininess = 32;
					}
					else
					{
						curPass.Specular = ColorEx.Beige;
						curPass.Shininess = 0;
					}
					// Grab the first pass render state. 
					// NOTE: For more complicated samples iterate over the passes and build each one of them as desired.
					RenderState renderState = ShaderGenerator.Instance.GetRenderState( ShaderGenerator.DefaultSchemeName,
					                                                                   curMaterialName, 0 );

					//Remove all sub render states
					renderState.Reset();

					if ( this.curLightingModel == ShaderSystemLightingModel.PerVertexLighting )
					{
						SubRenderState perPerVertexLightModel = ShaderGenerator.Instance.CreateSubRenderState( FFPLighting.FFPType );
						renderState.AddTemplateSubRenderState( perPerVertexLightModel );
					}
					else if ( this.curLightingModel == ShaderSystemLightingModel.PerVertexLighting )
					{
						SubRenderState perPixelLightModel = ShaderGenerator.Instance.CreateSubRenderState( PerPixelLighting.SGXType );
						renderState.AddTemplateSubRenderState( perPixelLightModel );
					}
					else if ( this.curLightingModel == ShaderSystemLightingModel.NormalMapLightingTangentSpace )
					{
						//Apply normal map only on main entity.
						if ( entity.Name == MainEntityName )
						{
							SubRenderState subRenderState = ShaderGenerator.Instance.CreateSubRenderState( NormalMapLighting.SGXType );
							var normalMapSubRS = subRenderState as NormalMapLighting;

							normalMapSubRS.NormalMapSpace = NormalMapSpace.Tangent;
							normalMapSubRS.NormalMapTextureName = "Panels_Normal_Tangent.png";
							renderState.AddTemplateSubRenderState( normalMapSubRS );
						}
							//It is secondary entity -> use simple per pixel lighting
						else
						{
							SubRenderState perPixelLightModel = ShaderGenerator.Instance.CreateSubRenderState( PerPixelLighting.SGXType );
							renderState.AddTemplateSubRenderState( perPixelLightModel );
						}
					}
					else if ( this.curLightingModel == ShaderSystemLightingModel.NormalMapLightingObjectSpace )
					{
						//Apply normal map only on main entity
						if ( entity.Name == MainEntityName )
						{
							SubRenderState subRenderState = ShaderGenerator.Instance.CreateSubRenderState( NormalMapLighting.SGXType );
							var normalMapSubRS = subRenderState as NormalMapLighting;

							normalMapSubRS.NormalMapSpace = NormalMapSpace.Object;
							normalMapSubRS.NormalMapTextureName = "Panels_Normal_Obj.png";

							renderState.AddTemplateSubRenderState( normalMapSubRS );
						}

							//It is secondary entity -> use simple per pixel lighting.
						else
						{
							SubRenderState perPixelLightModel = ShaderGenerator.Instance.CreateSubRenderState( PerPixelLighting.SGXType );
							renderState.AddTemplateSubRenderState( perPixelLightModel );
						}
					}

					if ( this.reflectionMapEnable )
					{
						SubRenderState subRenderState = ShaderGenerator.Instance.CreateSubRenderState( ReflectionMap.SGXType );
						var reflectMapSubRs = subRenderState as ReflectionMap;

						reflectMapSubRs.ReflectionMapType = TextureType.CubeMap;
						reflectMapSubRs.ReflectionPower = this.reflectionPowerSlider.Value;

						//Setup the textures needed by the reflection effect
						reflectMapSubRs.MaskMapTextureName = "Panels_refmask.png";
						reflectMapSubRs.ReflectionMapTextureName = "cubescene.jpg";

						renderState.AddTemplateSubRenderState( subRenderState );
						this.reflectionMapSubRS = subRenderState;
					}
					else
					{
						this.reflectionMapSubRS = null;
					}
					//Invalidate this material in order to regen its shaders
					ShaderGenerator.Instance.InvalidateMaterial( ShaderGenerator.DefaultSchemeName, curMaterialName );
				}
			}
		}