Beispiel #1
0
        private static RgbaImage TextureDefinitionToImage(TextureDefinition definition)
        {
            RgbaImage newImage = new RgbaImage(definition.Dimension)
            {
                Namespace = definition.Namespace,
                Offset    = definition.Offset
            };

            foreach (TextureDefinitionPatch patch in definition.Patches)
            {
                if (TryGetOrReadImage(patch.Name, patch.Namespace, out RgbaImage image))
                {
                    Vec2I position = patch.Origin;
                    if (patch.UseOffsets)
                    {
                        position += image.Offset;
                    }

                    // TODO: Handle the other fields on the patch (ex: flipping, rotation).

                    newImage.DrawOntoThis(image, position);
                }
                else
                {
                    throw new Exception($"Cannot find image patch {patch.Name} in texture definition {definition.Name}");
                }
            }

            return(newImage);
        }
Beispiel #2
0
    public void InitializeFromMTD(MTD mtd, string virtualPath)
    {
        VirtualPath = virtualPath;
        ShaderPath  = mtd.ShaderPath;
        Textures    = new List <TextureDefinition>();
        foreach (var tex in mtd.Textures)
        {
            var def = new TextureDefinition();
            def.Name            = tex.Type;
            def.UVNumber        = tex.UVNumber;
            def.ShaderDataIndex = tex.ShaderDataIndex;
            if (tex.Extended)
            {
                def.TexturePath = tex.Path;
            }

            // Calculate the uv set index
            int uvoffset = 1;
            for (int j = 1; j < tex.UVNumber; j++)
            {
                if (!mtd.Textures.Any(t => (t.UVNumber == j)))
                {
                    uvoffset++;
                }
            }
            def.UVIndex = tex.UVNumber - uvoffset;

            if (tex.Type.ToUpper() == "G_LIGHTMAP" || tex.Type.ToUpper() == "G_DOLTEXTURE1" || tex.Type.ToUpper() == "G_GITEXTURE")
            {
                LightmapUVIndex = def.UVIndex;
            }

            Textures.Add(def);
        }
    }
Beispiel #3
0
        /// <summary>
        /// Create a new local texture definition, and return a pointer to it.
        /// </summary>
        /// <param name="name">name of the local texture</param>
        /// <returns>pointer to a texture definition</returns>
        public virtual TextureDefinition CreateTextureDefinition(string name)
        {
            var t = new TextureDefinition();

            t.Name = name;
            this.textureDefinitions.Add(t);
            return(t);
        }
Beispiel #4
0
 public static string TexNameGenerate(TextureDefinition textureDefinition)
 {
     if (textureDefinition == null)
     {
         return("None");
     }
     else
     {
         string texName = SeparatorClean(textureDefinition.FilenameOrUrl);
         return("[" + textureDefinition.Source.ToString() + "]-[" + texName.Replace(Path.DirectorySeparatorChar.ToString(), "]-[") + "]");
     }
 }
Beispiel #5
0
        public override void update(GameObject gameObject, SpriteRender spriteRender, GameTime gameTime, float depth)
        {
            string gameObjectStateString = GameObjectStateProvider.GetStateString(gameObject);


            TextureDefinition textureDefinition = TextureDefinitionFactory.Get(gameObjectStateString);

            // gameObject.state as first param
            Sprite sprite = gameObject.AnimationContainer.getCurrentSprite(TextureDefinitionFactory.Get(gameObjectStateString), gameTime);

            sprite.Depth = depth;
            spriteRender.Draw(sprite, gameObject.position, gameObject.Color);
        }
Beispiel #6
0
        public override void update(GameObject gameObject, SpriteRender spriteRender, GameTime gameTime, float depth)
        {
            int originY = Sprite.TILE_TEXTURE_HEIGHT * 2 + 48;

            string gameObjectStateString = GameObjectStateProvider.GetStateString(gameObject);

            TextureDefinition textureDefinition = TextureDefinitionFactory.Get(gameObjectStateString);

            Sprite sprite = gameObject.AnimationContainer.getCurrentSprite(TextureDefinitionFactory.Get(gameObjectStateString), gameTime);

            sprite.Depth = depth;
            spriteRender.Draw(sprite, gameObject.position, new Vector2(0, originY));
        }
Beispiel #7
0
        public override void update(GameObject gameObject, SpriteRender spriteRender, GameTime gameTime, float depth)
        {
            string gameObjectStateString = GameObjectStateProvider.GetStateString(gameObject);

            TextureDefinition textureDefinition = TextureDefinitionFactory.Get(gameObjectStateString);

            // gameObject.state as first param
            Sprite sprite = gameObject.AnimationContainer.getCurrentSprite(TextureDefinitionFactory.Get(gameObjectStateString), gameTime);

            sprite.Depth = 0.6f;

            //based on arrow facing rotate the sprite
            sprite.Size = new Vector2(0.3f, 0.3f);
            spriteRender.Draw(sprite, gameObject.position);
        }
Beispiel #8
0
        public Sprite getCurrentSprite(TextureDefinition textureDefinition, GameTime gameTime)
        {
            float gameTotalSeconds = (float)gameTime.TotalGameTime.TotalSeconds;

            float spritesPerSecond = textureDefinition.GetSriteTotal();
            float second           = 1;

            float refreshRate = second / spritesPerSecond;
            float totalSecondsPerRefreshRate = gameTotalSeconds / refreshRate;

            int animationIndex = (int)Math.Round(totalSecondsPerRefreshRate) % 10;


            // CowboyStandingPistol.spriteList[1]
            string sprite = textureDefinition.GetSpriteIndex(animationIndex);



            return(SpriteSheetContainer(textureDefinition.GetContentFile()).GetSpriteByName(textureDefinition.GetSpriteIndex(animationIndex)));
        }
Beispiel #9
0
        private static void ParseAndAddDefinitions(PNames pnames, TextureX textureX, List <TextureDefinition> definitions)
        {
            if (pnames == null || textureX == null)
            {
                return;
            }

            foreach (TextureXImage image in textureX)
            {
                TextureDefinition definition = new TextureDefinition(image.Name, image.Dimension, ResourceNamespace.Textures);

                foreach (TextureXPatch patch in image.Patches)
                {
                    UpperString            name     = pnames[patch.PatchIndex];
                    TextureDefinitionPatch defPatch = new TextureDefinitionPatch(name, patch.Offset, ResourceNamespace.Textures);
                    definition.Patches.Add(defPatch);
                }

                definitions.Add(definition);
            }
        }
Beispiel #10
0
        public override void update(GameObject gameObject, SpriteRender spriteRender, GameTime gameTime, float depth)
        {
            string gameObjectStateString = GameObjectStateProvider.GetStateString(gameObject);

            TextureDefinition textureDefinition = TextureDefinitionFactory.Get(gameObjectStateString);

            gameObject.Color = gameObject.Damaged ? Color.Red : Color.White;

            // gameObject.state as first param
            Sprite sprite = gameObject.AnimationContainer.getCurrentSprite(TextureDefinitionFactory.Get(gameObjectStateString), gameTime);

            sprite.Depth = depth;

            gameObject.Color = Color.White;
            if (gameObject.GameObjectStateContainer.GetPrevious() is StateWaving)
            {
                gameObject.Color = Color.Red;
            }

            spriteRender.Draw(sprite, gameObject.position, gameObject.Color);
        }
        protected override void Render(GraphicsContext graphicsContext, ref ParticleBuffer.Iterator iterator, TextureDefinition texture, ParticleBlendMode blendMode)
        {
            if (!this.IsSpriteBatchAlreadyRunning)
            {
                graphicsContext.SpriteBatch.Begin(SpriteSortMode.Deferred, blendMode.ToBlendState(), SamplerState.PointClamp, null, null, null);
            }

            float inverseTextureWidth = 1f / texture.Width;
            Vector2 origin = new Vector2(texture.Width, texture.Height) / 2f;

            Particle particle = iterator.First;
            do
            {
                float scale = particle.Scale * inverseTextureWidth;          // Color * alpha is slow....
                graphicsContext.SpriteBatch.Draw(texture, particle.Position, new Color(particle.Color) * particle.Opacity, particle.Rotation, origin, particle.Scale);
            } while (iterator.MoveNext(ref particle));

            if (!this.IsSpriteBatchAlreadyRunning)
            {
                graphicsContext.SpriteBatch.End();
            }
        }
Beispiel #12
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(TextureDefinition obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Beispiel #13
0
    private static void Start(CSharpBoxClass cSharpBox)
    {
        cSharpBox.ClearLogs();

        MainConstruct mainConstruct = cSharpBox.MainConstruct as MainConstruct;

        string outPutFolderPath = Get.ProfilePaths.ProfileRootDir().Append(mainConstruct.GetBlueprintName()).ToString() + string.Format("-{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
        string texFolderPath    = Path.Combine(outPutFolderPath, "Textures");

        Directory.CreateDirectory(outPutFolderPath);
        Directory.CreateDirectory(texFolderPath);

        //TextureDefinition getTexDef(MaterialDefinition I) => Configured.i.Textures.Find(I.ColorTextureReference.Reference.Guid);
        IEnumerable <TextureDefinition> textureDefinitionList = Configured.i.Materials.Components
                                                                .Select(I => Configured.i.Textures.Find(I.ColorTextureReference.Reference.Guid))
                                                                .Where(I => I != null)
                                                                .Distinct();

        StringBuilder sb = new StringBuilder();

        foreach (TextureDefinition textureDefinition in textureDefinitionList)
        {
            ModSource modSource = textureDefinition.Source;

            if (modSource != ModSource.File && modSource != ModSource.Resources)
            {
                continue;
            }

            byte[] encodeResult = null;

            try
            {
                encodeResult = ForcedEncodeToJPG(textureDefinition.Texture.GetTexture());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                continue;
            }

            if (encodeResult != null)
            {
                string texName = TexNameGenerate(textureDefinition);

                File.WriteAllBytes(Path.Combine(texFolderPath, texName + ".jpg"), encodeResult);

                cSharpBox.Log("newmtl " + texName);
                cSharpBox.Log("map_Kd " + Path.Combine("Textures", texName + ".jpg"));
                cSharpBox.Log(string.Empty);

                sb.Append("newmtl " + texName + "\n");
                sb.Append("map_Kd " + Path.Combine("Textures", texName + ".jpg") + "\n");
                sb.Append("\n");
            }
        }

        using (StreamWriter sw = new StreamWriter(Path.Combine(outPutFolderPath, "Test.mtl")))
        {
            sw.Write(sb.ToString());
        }



        List <AllConstruct> allConstructList = new List <AllConstruct>();

        mainConstruct.AllBasicsRestricted.GetAllConstructsBelowUsAndIncludingUs(allConstructList);

        foreach (AllConstruct allConstruct in allConstructList)
        {
            if (!(allConstruct.Chunks is ConstructableMeshMerger))
            {
                continue;
            }

            Dictionary <MaterialDefinition, List <Mesh> > meshListDictionary = new Dictionary <MaterialDefinition, List <Mesh> >();

            foreach (ICarriedObjectReference iCOR in allConstruct.CarriedObjects.Objects)
            {
                MeshRenderer meshRenderer = iCOR.ObjectItself.GetComponent <MeshRenderer>();
                MeshFilter   meshFilter   = iCOR.ObjectItself.GetComponent <MeshFilter>();

                if (meshRenderer == null || meshFilter == null)
                {
                    continue;
                }

                KeyValuePair <Guid, MaterialDefinition> item = Configured.i.Materials.DictionaryOfComponents.FirstOrDefault(d => d.Value.Material == meshRenderer.sharedMaterial);

                if (item.Equals(default(KeyValuePair <Guid, MaterialDefinition>)))
                {
                    continue;
                }

                if (!meshListDictionary.ContainsKey(item.Value))
                {
                    meshListDictionary.Add(item.Value, new List <Mesh>());
                }

                Mesh newMesh = UnityEngine.Object.Instantiate(meshFilter.sharedMesh);
                IEnumerable <Vector3> newVertexList = newMesh.vertices.Select(d => meshFilter.transform.localToWorldMatrix.MultiplyPoint(d));
                newVertexList = newVertexList.Select(d => allConstruct.myTransform.worldToLocalMatrix.MultiplyPoint(d));
                newMesh.SetVertices(newVertexList.ToList());

                meshListDictionary[item.Value].Add(newMesh);
            }

            ConstructableMeshMerger meshMerger = allConstruct.Chunks as ConstructableMeshMerger;
            cSharpBox.Log("AllBlockVertex Count : " + meshMerger.VertexCount);

            foreach (KeyValuePair <int, List <ChunkMesh> > chunkMeshListDictionary in meshMerger.D)
            {
                bool found;
                MaterialDefinition materialDefinition = Configured.i.Materials.FindUsingTheRuntimeId(chunkMeshListDictionary.Key, out found);

                bool flag_0 = chunkMeshListDictionary.Value.Count == 0;
                bool flag_1 = chunkMeshListDictionary.Value.All(d => d.VertCount == 0);

                if (!found || flag_0 || flag_1)
                {
                    continue;
                }

                if (!meshListDictionary.ContainsKey(materialDefinition))
                {
                    meshListDictionary.Add(materialDefinition, new List <Mesh>());
                }

                meshListDictionary[materialDefinition].AddRange(chunkMeshListDictionary.Value.Select(d => d.GetMesh()));
            }



            int  subConstructIndex = allConstruct.PersistentSubConstructIndex;
            bool isSubConstruct    = subConstructIndex != -1;

            Vector3    localPosition = Vector3.zero;
            Quaternion localRotation = Quaternion.identity;

            if (isSubConstruct)
            {
                MainConstruct mc = allConstruct.Main;
                localPosition = mc.SafeGlobalToLocal(allConstruct.SafePosition);
                localRotation = mc.SafeGlobalRotationToLocalRotation(allConstruct.SafeRotation);
            }

            List <Mesh> meshList = new List <Mesh>();

            foreach (KeyValuePair <MaterialDefinition, List <Mesh> > meshListDictionaryData in meshListDictionary)
            {
                List <Vector3> vertices        = new List <Vector3>();
                List <Vector3> normals         = new List <Vector3>();
                List <Vector2> uv              = new List <Vector2>();
                List <int>     triangles       = new List <int>();
                int            loadVertexCount = 0;

                foreach (Mesh mesh in meshListDictionaryData.Value)
                {
                    vertices.AddRange(mesh.vertices);
                    normals.AddRange(mesh.normals);
                    uv.AddRange(mesh.uv);
                    triangles.AddRange(mesh.triangles.Select(d => d + loadVertexCount));
                    loadVertexCount += mesh.vertexCount;
                }

                if (isSubConstruct)
                {
                    vertices = vertices.Select(I => localRotation * I + localPosition).ToList();
                }

                TextureDefinition textureDefinition = Configured.i.Textures.Find(meshListDictionaryData.Key.ColorTextureReference.Reference.Guid);

                Mesh newMesh = new Mesh
                {
                    indexFormat = UnityEngine.Rendering.IndexFormat.UInt32,
                    name        = TexNameGenerate(textureDefinition)
                };

                newMesh.SetVertices(vertices);
                newMesh.SetNormals(normals);
                newMesh.SetUVs(0, uv);
                newMesh.SetTriangles(triangles, 0);

                FlipHorizontal(newMesh);
                meshList.Add(newMesh);

                cSharpBox.Log("vertexCount : " + newMesh.vertices.Length);
            }



            string fileName = $"Test ({OutputCount++})";

            if (subConstructIndex == -1)
            {
                fileName = "MainConstruct";
            }
            else
            {
                fileName = $"SubConstruct_{subConstructIndex}";
            }

            MeshToFile(meshList, Path.Combine(outPutFolderPath, fileName + ".obj"));
        }
    }
		/// <summary>
		/// Create a new local texture definition, and return a pointer to it.
		/// </summary>
		/// <param name="name">name of the local texture</param>
		/// <returns>pointer to a texture definition</returns>
		public virtual TextureDefinition CreateTextureDefinition( string name )
		{
			var t = new TextureDefinition();
			t.Name = name;
			this.textureDefinitions.Add( t );
			return t;
		}
Beispiel #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="localName"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        /// <param name="aa"></param>
        /// <param name="aaHint"></param>
        /// <param name="srgb"></param>
        /// <param name="textureAllreadyAssigned"></param>
        /// <param name="instance"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        public Texture GetPooledTexture( string name, string localName, int width, int height, PixelFormat format, int aa,
            string aaHint, bool srgb, List<Texture> textureAllreadyAssigned,
            CompositorInstance instance, CompositionTechnique.TextureScope scope)
        {
            if ( scope == CompositionTechnique.TextureScope.Global )
            {
                throw new AxiomException( "Global scope texture can not be pooled." );
            }

            var def = new TextureDefinition( width, height, format, aa, aaHint, srgb );
            if ( scope == CompositionTechnique.TextureScope.Chain )
            {
                var pair = new Pair<string>( instance.Compositor.Name, localName );
                SortedList<TextureDefinition, Texture> defMap = null;
                if ( this.chainTexturesByRef.TryGetValue( pair, out defMap ) )
                {
                    Texture tex;
                    if ( defMap.TryGetValue( def, out tex ) )
                    {
                        return tex;
                    }
                }
                // ok, we need to create a new one
                if ( defMap == null )
                {
                    defMap = new SortedList<TextureDefinition, Texture>( new TextureDefLess() );
                }

                var newTex = TextureManager.Instance.CreateManual( name, ResourceGroupManager.InternalResourceGroupName,
                                                                   TextureType.TwoD, width, height, 0, format,
                                                                   TextureUsage.RenderTarget, null, srgb, aa, aaHint );

                defMap.Add( def, newTex );

                if ( this.chainTexturesByRef.ContainsKey( pair ) )
                {
                    this.chainTexturesByRef[ pair ] = defMap;
                }
                else
                {
                    this.chainTexturesByRef.Add( pair, defMap );
                }

                return newTex;
            } //end if scope

            List<Texture> i = null;
            if ( !this.texturesByDef.TryGetValue( def, out i ) )
            {
                i = new List<Texture>();
                this.texturesByDef.Add( def, i );
            }

            var previous = instance.Chain.GetPreviousInstance( instance );
            var next = instance.Chain.GetNextInstance( instance );

            Texture ret = null;
            // iterate over the existing textures and check if we can re-use
            foreach ( var tex in i )
            {
                // check not already used
                if ( !textureAllreadyAssigned.Contains( tex ) )
                {
                    var allowReuse = true;
                    // ok, we didn't use this one already
                    // however, there is an edge case where if we re-use a texture
                    // which has an 'input previous' pass, and it is chained from another
                    // compositor, we can end up trying to use the same texture for both
                    // so, never allow a texture with an input previous pass to be
                    // shared with its immediate predecessor in the chain
                    if ( IsInputPreviousTarget( instance, localName ) )
                    {
                        // Check whether this is also an input to the output target of previous
                        // can't use CompositorInstance._previousInstance, only set up
                        // during compile
                        if ( previous != null && IsInputToOutputTarget( previous, tex ) )
                        {
                            allowReuse = false;
                        }
                    }
                    // now check the other way around since we don't know what order they're bound in
                    if ( IsInputToOutputTarget( instance, localName ) )
                    {
                        if ( next != null && IsInputPreviousTarget( next, tex ) )
                        {
                            allowReuse = false;
                        }
                    }
                    if ( allowReuse )
                    {
                        ret = tex;
                        break;
                    }
                }
            }

            if ( ret == null )
            {
                // ok, we need to create a new one
                ret = TextureManager.Instance.CreateManual( name, ResourceGroupManager.InternalResourceGroupName, TextureType.TwoD,
                                                            width, height, 0, format, TextureUsage.RenderTarget, null, srgb, aa,
                                                            aaHint );
                i.Add( ret );
                this.texturesByDef[ def ] = i;
            }

            // record that we used this one in the requester's list
            textureAllreadyAssigned.Add( ret );

            return ret;
        }
 protected abstract void Render(GraphicsContext graphicsContext, ref ParticleBuffer.Iterator iterator, TextureDefinition texture, ParticleBlendMode blendMode);
Beispiel #17
0
 private bool LoadTextureDefinition(TextureDefinition texture)
 {
     Logger.Warning("RobotLoader::LoadTextureDefinition::Ignoring texture: {0}.", texture.name);
     return(true);
 }
Beispiel #18
0
 public Sprite GetSpriteBasedOnTextureDefinitionAndIndex(TextureDefinition textureDefinition, int spriteIndex)
 {
     return(SpriteSheetContainer(textureDefinition.GetContentFile()).GetSpriteByName(textureDefinition.GetSpriteIndex(spriteIndex)));
 }