public void texShared(TextureInfo texInfo)
	{
		if(sharingName == "" || sharingName == texInfo.name || sharingName == "Any")
		{
			texture = texInfo.getTexture();
		}
	}
Exemple #2
0
 public static TextureInfo[] ChopUpAllTextures(TextureInfo[] texInfos)
 {
     for (int i = 0; i < texInfos.Length; i++)
     {
         texInfos[i].chopTexture();
     }
     return texInfos;
 }
	public void  texStopped(TextureInfo texInfo)
	{
		if(texInfo.name == _sharingName)
		{
			
			texture = null;
			
		}else if(sharingName == "Any" && Spout2.activeSenders.Count > 0)
		{
			texture = Spout2.activeSenders[Spout2.activeSenders.Count-1].getTexture();
		}
	}
Exemple #4
0
        static Vector2[] CreateUV(TextureInfo info, float width, float height)
        {
            if (!info.Tile)
                return DefaultUV;

            var tw = info.Width;
            var th = info.Height;

            var u = width / (tw / info.Density);
            var v = height / (th / info.Density);

            return DefaultUV.Select(i => i * new Vector2(u, v)).ToArray();
        }
        public GameObjectAbstract(string spriteFilePath)
        {
            TextureInfo texture_info = new TextureInfo(new Texture2D(spriteFilePath, false) );
            sprite = new SpriteUV() {TextureInfo = texture_info};
            sprite.Quad.S = texture_info.TextureSizef;
            sprite.CenterSprite();
            sprite.Position = new Vector2(100,100);

            velocity =  new Vector2(0,0);
            mass = 10.0f;

            isAlive = false;

            lifeTime = 0;
        }
Exemple #6
0
        public Block(Device device, TextureInfo texture, float width, float height, float depth, bool containsTransparency)
        {
            Material = new TextureMaterial(texture.Texture, containsTransparency);

            var xUV = CreateUV(texture, depth, height);
            var yUV = CreateUV(texture, width, depth);
            var zUV = CreateUV(texture, width, height);

            this.Add(new MeshRenderer
            {
                Mesh = new TexturedCube(device, width, height, depth, zUV, zUV, xUV, xUV, yUV, yUV),
                Material = Material
            });

            this.Add(new AxisAlignedBoxCollider { RadiusWidth = width / 2, RadiusHeight = height / 2, RadiusDepth = depth / 2 });
        }
Exemple #7
0
    public static Texture2D BuildTexture(TextureInfo[] texInfos,
                                              int[] size_mesh,
                                              CardInfo cardInfo)
    {
        //TextureInfo texInfo = texInfos[0];
        int size_x = size_mesh[0];
        int size_z = size_mesh[1];

        // HARD: Using the first textures resolution (for now) assuming all will be same (for now)
        int tileResolution = texInfos[0].resolution;
        int texWidth = size_x * tileResolution;
        int texHeight = size_z * tileResolution;
        Texture2D texture = new Texture2D(texWidth, texHeight);

        for (int y = 0; y < size_z; y++)
        {
            for (int x = 0; x < size_x; x++)
            {
                // Creating the color array, p
                // Color[] p = texInfo.texColors[0];

                Color[] p;
                if (cardInfo != null)
                    p = getCardColors(x, y, size_x, size_z, texInfos, cardInfo);
                else
                    p = getColors(x, y, size_x, size_z, texInfos);

                // Setting the texture's pixels using the color array, p
                texture.SetPixels(x * tileResolution,
                                  y * tileResolution,
                                  tileResolution,
                                  tileResolution,
                                  p);
            }
        }

        texture.filterMode = FilterMode.Point;
        texture.wrapMode = TextureWrapMode.Clamp;
        texture.Apply();

        return texture;
    }
            public override void set(KSPTextureInfo info)
            {
                _main = new TextureInfo();
                _main.texture = info.mainTexture;
                _main.url = info.mainUrl;

                if (info.hasNormalMap)
                {
                    _normalMap = new TextureInfo();
                    _normalMap.texture = info.normalMapTexture;
                    _normalMap.url = info.normalMapUrl;
                    _normalMap.normalMap = true;
                    _hasNormalMap = true;
                }
                else
                {
                    _normalMap = null;
                    _hasNormalMap = false;
                }
            }
Exemple #9
0
        /// <summary>
        /// Binds a texture to the given path and context</summary>
        /// <param name="image">Path to image file containing texture</param>
        /// <param name="contextId">Context ID of texture</param>
        /// <param name="enableflipimage">True to enable flipping the image</param>
        /// <returns>OpenGL name of bound texture or -1 if texture could not be found/loaded</returns>
        public int GetTextureName(string image, object contextId, bool enableflipimage)
        {
            int name = -1;

            lock (this)
            {
                TextureContext context = FindContext(contextId);
                if (context == null)
                {
                    context = new TextureContext(contextId);
                    m_texCollections.Add(context);
                }

                if (!context.NameMap.TryGetValue(image, out name))
                {
                    TextureInfo texData;
                    texData = new TextureInfo();
                    texData.EnableFlipImage = enableflipimage;
                    name = BuildImage(image, texData);

                    // When textures can't be found, let's note that fact so as to avoid
                    //  hundreds or thousands of IO exceptions that are then printed in
                    //  OutputService's window.
                    context.NameMap.Add(image, name);

                    if (name >= 0)
                    {
                        //defensive programming -- http://sf.ship.scea.com/sf/go/artf21789
                        if (!context.TextureDataMap.ContainsKey(name))
                        {
                            context.TextureDataMap.Add(name, texData);
                            context.Names.Add(name);
                        }
                    }
                }
            }

            return name;
        }
Exemple #10
0
    public static Color[][] ChopUpTiles(TextureInfo texInfo)
    {
        Texture2D tex = texInfo.texSheet;
        int tileResolution = texInfo.resolution;

        int numTilesPerRow = tex.width / tileResolution;
        int numRows = tex.height / tileResolution;

        Color[][] tiles = new Color[numTilesPerRow * numRows][];

        for (int y = 0; y < numRows; y++)
        {
            for (int x = 0; x < numTilesPerRow; x++)
            {
                tiles[y * numTilesPerRow + x] = tex.GetPixels(x * tileResolution,
                                                              y * tileResolution,
                                                              tileResolution,
                                                              tileResolution);
            }
        }

        return tiles;
    }
    public PhysicalSpriteUV(TextureInfo textureInfo, PhysicsScene physicsScene, bool circle = false)
        : base(textureInfo)
    {
        // Texture Setup
            Quad.S = TextureInfo.TextureSizef;
            Pivot = new Vector2(TextureInfo.Texture.Width / 2f, TextureInfo.Texture.Height / 2f );

            // Physics Setup (get the indicies we will be using
            PhysicsScene = physicsScene;
            ShapeIndex = PhysicsScene.NumShape;
            BodyIndex = PhysicsScene.NumBody;
            JointIndex = -1;

            // Create shapes (will want to let the programmer pass in things like friction and rotation at some point, AND SPECIFY CIRCLE OR SQUARE SHAPE)
            PhysicsShape shape;
            if(!circle)
            {
                shape = new PhysicsShape(new Vector2(textureInfo.Texture.Width/2, textureInfo.Texture.Height/2));
            }
            else
            {
                shape = new PhysicsShape(textureInfo.Texture.Width/2);
            }

            // Why 100?
            PhysicsBody body = new PhysicsBody(shape, 100);
            body.ShapeIndex = (uint)ShapeIndex;

            PhysicsScene.sceneShapes[ShapeIndex] = shape;
            PhysicsScene.sceneBodies[BodyIndex] = body;
            //PhysicsScene.sceneBodies[BodyIndex].Rotation = 0.1f;
            //PhysicsScene.sceneBodies[BodyIndex].AirFriction = 0.01f;

            PhysicsScene.NumShape++;
            PhysicsScene.NumBody++;
    }
            public override void set(KSPTextureInfo info)
            {
                string[] textureNamesArray = Utils.SplitString(_textureNames);
                string[] normalMapNamesArray = Utils.SplitString(_normalMapNames);

                string dirUrl = info.dirUrl;
                if (_textureDir != string.Empty) dirUrl = _textureDir;

                _mainTextInfo = new List<TextureInfo>();
                for (int i = 0; i < textureNamesArray.Length; ++i)
                {
                    TextureInfo texInfo = new TextureInfo();
                    texInfo.url = dirUrl + "/" + textureNamesArray[i];
                    texInfo.name = System.IO.Path.GetFileNameWithoutExtension(texInfo.url);
                    _mainTextInfo.Add(texInfo);
                }

                _normalTextInfo = new List<TextureInfo>();
                for (int i = 0; i < normalMapNamesArray.Length; ++i)
                {
                    TextureInfo texInfo = new TextureInfo();
                    texInfo.url = dirUrl + "/" + normalMapNamesArray[i];
                    texInfo.name = System.IO.Path.GetFileNameWithoutExtension(texInfo.url);
                    texInfo.normalMap = true;
                    _normalTextInfo.Add(texInfo);
                }

                if (_normalTextInfo.Count > 0) _hasNormalMap = true;
                else _hasNormalMap = false;

                if (_mainTextInfo.Count == 0)
                {
                    valid = false;
                    Utils.LogError("no main textures");
                    return;
                }

                if (_hasNormalMap && _mainTextInfo.Count != _normalTextInfo.Count)
                {
                    Utils.LogError("different numbers of mainTextures ({0}) and normalMaps ({1})", _mainTextInfo.Count, _normalTextInfo.Count);
                    valid = false;
                    return;
                }

                if (Global.Debug2) Utils.Log("valid multiple base texture, textures: {0}", _mainTextInfo.Count);

                valid = true;
            }
Exemple #13
0
        private void SetUsedTextureOrImage(
            Dictionary <TextureInfo, TextureMeta> dict,
            int cbufSlot,
            int handle,
            SamplerType type,
            TextureFormat format,
            bool intCoords,
            bool write,
            bool accurateType,
            bool coherent)
        {
            var dimensions = type.GetDimensions();
            var isIndexed  = type.HasFlag(SamplerType.Indexed);

            var usageFlags = TextureUsageFlags.None;

            if (intCoords)
            {
                usageFlags |= TextureUsageFlags.NeedsScaleValue;

                var canScale = Stage.SupportsRenderScale() && !isIndexed && !write && dimensions == 2;

                if (!canScale)
                {
                    // Resolution scaling cannot be applied to this texture right now.
                    // Flag so that we know to blacklist scaling on related textures when binding them.
                    usageFlags |= TextureUsageFlags.ResScaleUnsupported;
                }
            }

            if (write)
            {
                usageFlags |= TextureUsageFlags.ImageStore;
            }

            if (coherent)
            {
                usageFlags |= TextureUsageFlags.ImageCoherent;
            }

            int arraySize = isIndexed ? SamplerArraySize : 1;

            for (int layer = 0; layer < arraySize; layer++)
            {
                var info = new TextureInfo(cbufSlot, handle + layer * 2, isIndexed, format);
                var meta = new TextureMeta()
                {
                    AccurateType = accurateType,
                    Type         = type,
                    UsageFlags   = usageFlags
                };

                if (dict.TryGetValue(info, out var existingMeta))
                {
                    dict[info] = MergeTextureMeta(meta, existingMeta);
                }
                else
                {
                    dict.Add(info, meta);
                }
            }
        }
Exemple #14
0
 public ByteArrayLoader(byte[] data, Format pixelFormat, int width, int height, int depth)
 {
     info = new TextureInfo(data, pixelFormat, width, height, depth);
 }
Exemple #15
0
 public PakTextureInfo(TextureInfo tex)
 {
     Name        = tex.Name;
     GlobalIndex = tex.GlobalIndex;
     Image       = tex.Image;
 }
Exemple #16
0
 public RawDataLoader(IntPtr data, Format pixelFormat, int width, int height, int depth)
 {
     info = new TextureInfo(data, pixelFormat, width, height, depth);
 }
Exemple #17
0
    static Color[] getCardColors(int x, int y, int size_x, int size_z, TextureInfo[] texInfos, CardInfo cardInfo)
    {
        Color[] p;
        // HARD: Using magic values for now knowing the size of textures
        //      NEED: x, z, size_x, size_z, texInfos, cardInfo
        // ::Texture [0]::
        // Cost:
        if (x == 1 && y == size_z - 2)
        {
            //p = texInfos[0].texColors[Math.Abs(9 - cardInfo.cost)];
            p = texInfos[0].texColors[cardInfo.cost];
        }
        // Points:
        else if (x == size_x - 2 && y == size_z - 2)
        {
            p = texInfos[0].texColors[cardInfo.score];
        }
        // ::Texture [1]::
        // Sides:
        else if (y == 1 && (x > 0 && x < size_x - 1))
        {
            //p = texInfos[1].texColors[Math.Abs(9 - cardInfo.sideID[Math.Abs(5 - (x - 1))])];
            p = texInfos[1].texColors[cardInfo.sideID[x - 1]];
        }
        // ::Solid Colors::
        // outsideColor:
        else if (x == 0 || y == 0 || y == size_z - 1 || x == size_x - 1)
        {
            p = new Color[texInfos[0].texColors[0].Length];
            for (int i = 0; i < texInfos[0].texColors[0].Length; i++)
            {
                //p[i] = new Color(cardInfo.outsideColorRGB[0], cardInfo.outsideColorRGB[1], cardInfo.outsideColorRGB[2], 1);
                p[i] = cardInfo.outsideColor;
            }
        }
        // insideColor:
        else
        {
            p = new Color[texInfos[0].texColors[0].Length];
            for (int i = 0; i < texInfos[0].texColors[0].Length; i++)
            {
                //p[i] = new Color(cardInfo.insideColorRGB[0], cardInfo.insideColorRGB[1], cardInfo.insideColorRGB[2], 1);
                p[i] = cardInfo.insideColor;
            }
        }

        return p;
    }
        private void DrawBatchPerTexture(ref TextureInfo texture, SpriteInfo[] sprites, int offset, int count)
        {
            if (m_customEffect != null)
            {
                var currentTechnique = m_customEffect.Technique;

                int passCount = m_customEffect.GetTechniqueDescription(currentTechnique).Passes;
                for (int i = 0; i < passCount; i++)
                {
                    // Sets the texture on the custom effect if the parameter exist
                    if (m_customEffectTexture != null)
                    {
                        m_customEffect.SetTexture(m_customEffectTexture, texture.Texture);
                    }


                    m_customEffect.Begin();
                    // Apply the current pass
                    m_customEffect.BeginPass(i);

                    // Draw the batch of sprites
                    DrawBatchPerTextureAndPass(ref texture, sprites, offset, count);

                    m_customEffect.EndPass();
                    m_customEffect.End();
                }
            }
            else
            {
                var spriteEffect = MyRender.GetEffect(MyEffects.SpriteBatch) as Effects.MyEffectSpriteBatchShader;

                if (texture.Face.HasValue)
                {
                    spriteEffect.SetCubeTexture(texture.Texture as CubeTexture);

                    switch (texture.Face.Value)
                    {
                    case CubeMapFace.PositiveX:
                        spriteEffect.SetTechnique(Effects.MyEffectSpriteBatchShader.Technique.SpriteBatchCube0);
                        break;

                    case CubeMapFace.NegativeX:
                        spriteEffect.SetTechnique(Effects.MyEffectSpriteBatchShader.Technique.SpriteBatchCube1);
                        break;

                    case CubeMapFace.PositiveY:
                        spriteEffect.SetTechnique(Effects.MyEffectSpriteBatchShader.Technique.SpriteBatchCube2);
                        break;

                    case CubeMapFace.NegativeY:
                        spriteEffect.SetTechnique(Effects.MyEffectSpriteBatchShader.Technique.SpriteBatchCube3);
                        break;

                    case CubeMapFace.PositiveZ:
                        spriteEffect.SetTechnique(Effects.MyEffectSpriteBatchShader.Technique.SpriteBatchCube4);
                        break;

                    case CubeMapFace.NegativeZ:
                        spriteEffect.SetTechnique(Effects.MyEffectSpriteBatchShader.Technique.SpriteBatchCube5);
                        break;
                    }
                }
                else
                {
                    spriteEffect.SetTexture(texture.Texture as Texture);
                    spriteEffect.SetTechnique(Effects.MyEffectSpriteBatchShader.Technique.Sprite);
                }

                spriteEffect.Begin();

                DrawBatchPerTextureAndPass(ref texture, sprites, offset, count);

                spriteEffect.End();
            }
        }
Exemple #19
0
 public Color4ArrayLoader(Color4[] data, int width)
 {
     info = new TextureInfo(data, width);
 }
Exemple #20
0
 /// <summary>
 /// Completes loading
 /// </summary>
 /// <param name="info">The information.</param>
 /// <param name="succ">if set to <c>true</c> [succ].</param>
 public void Complete(TextureInfo info, bool succ)
 {
     TextureInfoLoader.Complete(Guid, info, succ);
 }
        private static Material ConvertMaterialAndTextures(Ai.Material aiMaterial, ModelPackConverterOptions options, string baseDirectoryPath, TextureDictionary textureDictionary)
        {
            // Convert all textures
            TextureInfo diffuseTexture = null;

            if (aiMaterial.HasTextureDiffuse)
            {
                diffuseTexture = ConvertTexture(aiMaterial.TextureDiffuse, baseDirectoryPath);
            }

            TextureInfo lightmapTexture = null;

            if (aiMaterial.HasTextureLightMap)
            {
                lightmapTexture = ConvertTexture(aiMaterial.TextureLightMap, baseDirectoryPath);
            }

            TextureInfo displacementTexture = null;

            if (aiMaterial.HasTextureDisplacement)
            {
                displacementTexture = ConvertTexture(aiMaterial.TextureDisplacement, baseDirectoryPath);
            }

            TextureInfo opacityTexture = null;

            if (aiMaterial.HasTextureOpacity)
            {
                opacityTexture = ConvertTexture(aiMaterial.TextureOpacity, baseDirectoryPath);
            }

            TextureInfo normalTexture = null;

            if (aiMaterial.HasTextureNormal)
            {
                normalTexture = ConvertTexture(aiMaterial.TextureNormal, baseDirectoryPath);
            }

            TextureInfo heightTexture = null;

            if (aiMaterial.HasTextureHeight)
            {
                heightTexture = ConvertTexture(aiMaterial.TextureHeight, baseDirectoryPath);
            }

            TextureInfo emissiveTexture = null;

            if (aiMaterial.HasTextureEmissive)
            {
                emissiveTexture = ConvertTexture(aiMaterial.TextureEmissive, baseDirectoryPath);
            }

            TextureInfo ambientTexture = null;

            if (aiMaterial.HasTextureAmbient)
            {
                ambientTexture = ConvertTexture(aiMaterial.TextureAmbient, baseDirectoryPath);
            }

            TextureInfo specularTexture = null;

            if (aiMaterial.HasTextureSpecular)
            {
                specularTexture = ConvertTexture(aiMaterial.TextureSpecular, baseDirectoryPath);
            }

            TextureInfo reflectionTexture = null;

            if (aiMaterial.HasTextureReflection)
            {
                reflectionTexture = ConvertTexture(aiMaterial.TextureReflection, baseDirectoryPath);
            }

            // Convert material
            Material material     = null;
            string   materialName = AssimpConverterCommon.UnescapeName(aiMaterial.Name);

            switch (options.MaterialPreset)
            {
            case MaterialPreset.FieldTerrain:
            {
                if (diffuseTexture != null)
                {
                    textureDictionary.Add(diffuseTexture.Texture);
                    material = MaterialFactory.CreateFieldTerrainMaterial(materialName, diffuseTexture.Name, HasAlpha(diffuseTexture.PixelFormat));
                }
            }
            break;

            case MaterialPreset.FieldTerrainCastShadow:
            {
                if (diffuseTexture != null)
                {
                    textureDictionary.Add(diffuseTexture.Texture);
                    material = MaterialFactory.CreateFieldTerrainCastShadowMaterial(materialName, diffuseTexture.Name, HasAlpha(diffuseTexture.PixelFormat));
                }
            }
            break;

            case MaterialPreset.CharacterSkinP5:
            case MaterialPreset.CharacterSkinFB:
            {
                if (diffuseTexture != null)
                {
                    textureDictionary.Add(diffuseTexture.Texture);
                    string shadowTextureName = diffuseTexture.Name;

                    if (ambientTexture != null)
                    {
                        textureDictionary.Add(ambientTexture.Texture);
                        shadowTextureName = ambientTexture.Name;
                    }

                    // TODO: transparency
                    var hasTransparency = HasAlpha(diffuseTexture.PixelFormat);

                    if (options.MaterialPreset == MaterialPreset.CharacterSkinP5)
                    {
                        material = MaterialFactory.CreateCharacterSkinP5Material(materialName, diffuseTexture.Name, shadowTextureName,
                                                                                 hasTransparency);
                    }
                    else
                    {
                        material = MaterialFactory.CreateCharacterSkinFBMaterial(materialName, diffuseTexture.Name, shadowTextureName,
                                                                                 hasTransparency);
                    }
                }
            }
            break;

            case MaterialPreset.PersonaSkinP5:
            {
                if (diffuseTexture != null)
                {
                    textureDictionary.Add(diffuseTexture.Texture);
                    string shadowTextureName   = diffuseTexture.Name;
                    string specularTextureName = diffuseTexture.Name;

                    if (ambientTexture != null)
                    {
                        textureDictionary.Add(ambientTexture.Texture);
                        shadowTextureName = ambientTexture.Name;
                    }

                    if (specularTexture != null)
                    {
                        textureDictionary.Add(specularTexture.Texture);
                        specularTextureName = specularTexture.Name;
                    }

                    material = MaterialFactory.CreatePersonaSkinP5Material(materialName, diffuseTexture.Name, specularTextureName, shadowTextureName);
                }
            }
            break;

            case MaterialPreset.CharacterClothP4D:
            {
                if (diffuseTexture != null)
                {
                    textureDictionary.Add(diffuseTexture.Texture);
                    material = MaterialFactory.CreateCharacterClothP4DMaterial(materialName, diffuseTexture.Name,
                                                                               HasAlpha(diffuseTexture.PixelFormat));
                }
            }
            break;

            case MaterialPreset.CharacterSkinP3DP5D:
            {
                if (diffuseTexture != null)
                {
                    textureDictionary.Add(diffuseTexture.Texture);
                    material = MaterialFactory.CreateCharacterSkinP3DP5DMaterial(materialName, diffuseTexture.Name,
                                                                                 HasAlpha(diffuseTexture.PixelFormat));
                }
            }
            break;
            }

            // Create dummy material if none was created
            if (material == null)
            {
                material = new Material(materialName);
            }

            return(material);
        }
Exemple #22
0
        internal void Run(DEMDataSet dataSet, bool trackIn3D = true, bool generateTIN = false, int outputSrid = Reprojection.SRID_PROJECTED_LAMBERT_93)
        {
            try
            {
                string _gpxFile    = Path.Combine("SampleData", "BikeRide.gpx");
                bool   withTexture = true;
                float  Z_FACTOR    = 4f;
                float  Z_TRANSLATE_GPX_TRACK_METERS = 5;
                float  trailWidthMeters             = 5f;
                int    skipGpxPointsEvery           = 1;

                ImageryProvider provider = ImageryProvider.MapBoxSatellite; // new TileDebugProvider(null, maxDegreeOfParallelism: 1);//  ImageryProvider.MapBoxSatellite;

                string outputDir = Path.GetFullPath(".");

                //=======================
                /// Line strip from GPX
                ///
                // Get GPX points
                var segments = GpxImport.ReadGPX_Segments(_gpxFile);
                var points   = segments.SelectMany(seg => seg);
                var bbox     = points.GetBoundingBox().Scale(1.3, 1.3);
                // DEBUG
                // Test case : ASTER GDEMv3 : 5.5 43.5 Z=315
                // 303     307     308
                // 309    *315*    317
                // 314     321     324
                //points = GenerateDebugTrailPointsGenerateDebugTrailPoints(5.003, 5.006, 43.995, 43.997, 0.0001, 0.001);
                //points = GenerateDebugTrailPointsGenerateDebugTrailPoints(5.4990, 5.501, 43.4990, 43.501, 0.0001, 0.001);
                //points = GenerateDebugTrailPointsGenerateDebugTrailPoints(5.49, 5.51, 43.49, 43.51, 0.0005, 0.001);
                //bbox = points.GetBoundingBox().Scale(1.3,1.3);
                IEnumerable <GeoPoint> gpxPointsElevated = _elevationService.GetPointsElevation(points, dataSet);


                //
                //=======================

                //=======================
                /// Height map (get dem elevation for bbox)
                ///
                HeightMap hMap = _elevationService.GetHeightMap(ref bbox, dataSet);

//                var refPoint = new GeoPoint(43.5, 5.5);
//                hMap = hMap.BakeCoordinates();
//                var hMapRefPoint = hMap.Coordinates.OrderBy(c => c.DistanceSquaredTo(refPoint)).First();
//                var gpxRefPoint = gpxPointsElevated.OrderBy(c => c.DistanceSquaredTo(refPoint)).First();
//                hMapRefPoint.Elevation += 60;
//                gpxRefPoint.Elevation += 60;

                hMap = hMap.ReprojectTo(4326, outputSrid)
                       //.CenterOnOrigin()
                       .ZScale(Z_FACTOR)
                       .BakeCoordinates();
                //
                //=======================

                //=======================
                // Textures
                //
                PBRTexture pbrTexture = null;
                if (withTexture)
                {
                    Console.WriteLine("Download image tiles...");
                    TileRange tiles    = _imageryService.DownloadTiles(bbox, provider, 8);
                    string    fileName = Path.Combine(outputDir, "Texture.jpg");

                    Console.WriteLine("Construct texture...");
                    TextureInfo texInfo = _imageryService.ConstructTextureWithGpxTrack(tiles, bbox, fileName, TextureImageFormat.image_jpeg, gpxPointsElevated, false);

                    //
                    //=======================

                    //=======================
                    // Normal map
                    Console.WriteLine("Height map...");
                    //float Z_FACTOR = 0.00002f;

                    //hMap = hMap.CenterOnOrigin().ZScale(Z_FACTOR);
                    var normalMap = _imageryService.GenerateNormalMap(hMap, outputDir);

                    pbrTexture = PBRTexture.Create(texInfo, normalMap);

                    //hMap = hMap.CenterOnOrigin(Z_FACTOR);
                    //
                    //=======================
                }


                //=======================
                // MESH 3D terrain
                Console.WriteLine("Height map...");

                Console.WriteLine("GenerateTriangleMesh...");
                //hMap = _elevationService.GetHeightMap(bbox, _dataSet);
                ModelRoot model = null;
                if (generateTIN)
                {
                    model = TINGeneration.GenerateTIN(hMap, 10d, _sharpGltfService, pbrTexture, outputSrid);
                }
                else
                {
                    //hMap = hMap.CenterOnOrigin().ZScale(Z_FACTOR);
                    // generate mesh with texture
                    model = _sharpGltfService.CreateTerrainMesh(hMap, pbrTexture);
                }

                if (trackIn3D)
                {
                    // take 1 point evert nth
                    gpxPointsElevated = gpxPointsElevated.Where((x, i) => (i + 1) % skipGpxPointsEvery == 0);
                    gpxPointsElevated = gpxPointsElevated.ZTranslate(Z_TRANSLATE_GPX_TRACK_METERS)
                                        .ReprojectTo(4326, outputSrid)
                                        //.CenterOnOrigin()
                                        //.CenterOnOrigin(hMap.BoundingBox)
                                        .ZScale(Z_FACTOR);


                    model = _sharpGltfService.AddLine(model, gpxPointsElevated, new Vector4(0, 1, 0, 0.5f), trailWidthMeters);
                }

                // model export
                Console.WriteLine("GenerateModel...");
                model.SaveGLB(Path.Combine(Directory.GetCurrentDirectory(), $"{GetType().Name} dst{dataSet.Name} TIN{generateTIN} Srid{outputSrid}.glb"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }
        }
Exemple #23
0
 public void Complete(Guid id, TextureInfo info, bool succeeded)
 {
 }
Exemple #24
0
 public Color4ArrayLoader(Color4[] data, int width, int height, int depth)
 {
     info = new TextureInfo(data, width, height, depth);
 }
Exemple #25
0
        private (ModelRoot Model, double widthMeters, double heightMeters, double averageElevation, BoundingBox projectedBbox) GenerateSampleModel(BoundingBox bbox, DEMDataSet dataset, bool withTexture = true)
        {
            try
            {
                int    TEXTURE_TILES = 8; // 4: med, 8: high
                string outputDir     = Directory.GetCurrentDirectory();

                //_rasterService.GenerateDirectoryMetadata(dataset, false);

                ImageryProvider provider = ImageryProvider.MapBoxSatellite;// new TileDebugProvider(new GeoPoint(43.5,5.5));


                _logger.LogInformation($"Getting height map data...");

                var heightMap = _elevationService.GetHeightMap(ref bbox, dataset);

                var wgs84bbox = bbox;
                ModelGenerationTransform transform = new ModelGenerationTransform(bbox, 3857, true, 1.5f, true);

                _logger.LogInformation($"Processing height map data ({heightMap.Count} coordinates)...");
                heightMap = transform.TransformHeightMap(heightMap);


                //=======================
                // Textures
                //
                PBRTexture pbrTexture = null;
                if (withTexture)
                {
                    Console.WriteLine("Download image tiles...");
                    TileRange tiles    = _imageryService.DownloadTiles(bbox, provider, TEXTURE_TILES);
                    string    fileName = Path.Combine(outputDir, "Texture.jpg");

                    Console.WriteLine("Construct texture...");
                    TextureInfo texInfo = _imageryService.ConstructTexture(tiles, bbox, fileName, TextureImageFormat.image_jpeg);

                    //
                    //=======================

                    //=======================
                    // Normal map
                    Console.WriteLine("Height map...");
                    //float Z_FACTOR = 0.00002f;

                    //hMap = hMap.CenterOnOrigin().ZScale(Z_FACTOR);
                    //var normalMap = _imageryService.GenerateNormalMap(heightMap, outputDir);

                    pbrTexture = PBRTexture.Create(texInfo, null);

                    //hMap = hMap.CenterOnOrigin(Z_FACTOR);
                    //
                    //=======================
                }
                // Triangulate height map
                // and add base and sides
                _logger.LogInformation($"Triangulating height map and generating 3D mesh...");

                var model = _sharpGltfService.CreateTerrainMesh(heightMap, pbrTexture);

                var width  = new GeoPoint(wgs84bbox.Center[1], bbox.Center[0] - bbox.Width / 2f).DistanceTo(new GeoPoint(wgs84bbox.Center[1], bbox.Center[0] + bbox.Width / 2f));
                var height = new GeoPoint(bbox.Center[1] - bbox.Height / 2f, wgs84bbox.Center[0]).DistanceTo(new GeoPoint(bbox.Center[1] + bbox.Height, wgs84bbox.Center[0]));

                return(model, width, height, wgs84bbox.Center[2], heightMap.BoundingBox);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(null, 0, 0, 0, null);
            }
        }
 public CharacterAnimationResolver(TextureInfo textureInfo, int[] animateLeftColumns, int[] animateRightColumns)
 {
     this.animateLeftColumns  = animateLeftColumns;
     this.animateRightColumns = animateRightColumns;
     this.textureInfo         = textureInfo;
 }
 public Material(Color color, TextureInfo texture)
 {
     DiffuseName     = texture.RelativeName;
     DiffuseColor    = color;
     _DiffuseTexture = texture;
 }
Exemple #28
0
 internal SpriteInfo(TextureInfo p, Sprite s)
 {
     parent = p;
     sprite = s;
 }
        Image GetImage(TestClient client, UUID id)
        {
            byte[] assetData = new byte[0];

            AutoResetEvent fetchDone = new AutoResetEvent(false);
            client.Assets.RequestImage(id, delegate(TextureRequestState state, OpenMetaverse.Assets.AssetTexture asset)
            {
                if ((state == TextureRequestState.Finished) && (asset != null))
                {
                    fetchDone.Set();
                    assetData = asset.AssetData;
                }
            });
            if (!fetchDone.WaitOne(30000, false))
                return null;

            ManagedImage managedImage = null;

            OpenJPEG.DecodeToImage(assetData, out managedImage);

            if (managedImage == null)
                return null;

            bool hasAlpha = false;
            ulong rSum = 0;
            ulong gSum = 0;
            ulong bSum = 0;
            ulong aSum = 0;
            uint numPix = (uint)managedImage.Red.Length;
            var red = managedImage.Red;
            var green = managedImage.Green;
            var blue = managedImage.Blue;

            if ((managedImage.Channels & ManagedImage.ImageChannels.Alpha) != 0)
            {

                var alpha = managedImage.Alpha;
                for (uint i = 0; i < numPix; i++)
                    aSum += alpha[i];

                managedImage.ConvertChannels(managedImage.Channels & ~ManagedImage.ImageChannels.Alpha);
                hasAlpha = true;
            }
            for (uint i = 0; i < numPix; i++)
            {
                rSum += red[i];
                gSum += green[i];
                bSum += blue[i];
            }
            rSum /= numPix;
            gSum /= numPix;
            bSum /= numPix;
            aSum /= numPix;

            Color4 meanColor = new Color4((byte)rSum, (byte)gSum, (byte)bSum, hasAlpha ? (byte)aSum : (byte)255);

            TextureInfo ti = new TextureInfo();
            ti.Id = id;
            ti.MeanColor = meanColor;
            mKnownTextures[id] = ti;

            Bitmap imgData = LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA()));

            return (Image)imgData;
        }
Exemple #30
0
    static IEnumerator Loading(Bitmap baseimage)
    {
        TextureInfo ti = null;
        FileInfo    fi = new FileInfo(baseimage.path);

        if (fi.Exists)
        {
            FileStream fs       = fi.OpenRead();
            var        filesize = fs.Length;
            byte[]     content  = new byte[filesize];

            var async = fs.BeginRead(content, 0, (int)filesize, null, null);
            while (!async.IsCompleted)
            {
                yield return(null);
            }

            TextureFormat format = TextureFormat.DXT1;

            var extname = uEmuera.Utils.GetSuffix(baseimage.path).ToLower();
            if (extname == "png")
            {
                format = TextureFormat.DXT5;
            }

            if (extname == "webp")
            {
                var tex = Texture2DExt.CreateTexture2DFromWebP(content, false, false,
                                                               out Error err);
                if (err != Error.Success)
                {
                    Debug.LogWarning($"{baseimage.path} {err.ToString()}");
                    yield break;
                }
                ti = new TextureInfo(baseimage.filename, tex);
                texture_dict.Add(baseimage.filename, ti);

                baseimage.size.Width  = tex.width;
                baseimage.size.Height = tex.height;
            }
            else
            {
                var tex = new Texture2D(4, 4, format, false);
                if (tex.LoadImage(content))
                {
                    ti = new TextureInfo(baseimage.filename, tex);
                    texture_dict.Add(baseimage.filename, ti);

                    baseimage.size.Width  = tex.width;
                    baseimage.size.Height = tex.height;
                }
            }
        }
        List <CallbackInfo> list = null;

        if (loading_set.TryGetValue(baseimage.filename, out list))
        {
            var          count = list.Count;
            CallbackInfo item  = null;
            for (int i = 0; i < count; ++i)
            {
                item = list[i];
                item.DoCallback(GetSpriteInfo(ti, item.src));
            }
            list.Clear();
            loading_set.Remove(baseimage.filename);
        }
    }
 public void RefreshMe()
 {
     if (sb == null)
     {
         return;
     }
     listTex    = new List <TextureInfo>();
     listChunks = new List <ChunkInfo>();
     listBox1.Items.Clear();
     rtb1.Text = "Searching for Textures...";
     Application.DoEvents();
     foreach (Tools.Entry e in sb.lines)
     {
         if (e.type == 0x82)
         {
             foreach (Tools.Field f in e.fields)
             {
                 if (f.fieldname == "bundles" && f.type == 1)
                 {
                     FindTextures((List <Tools.Entry>)f.data);
                 }
             }
         }
     }
     rtb1.AppendText("done.\nLoading cat file...");
     Application.DoEvents();
     if (cat == null)
     {
         OpenFileDialog d = new OpenFileDialog();
         d.Filter = "*.cat|*.cat";
         if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             cat = new CATFile(d.FileName);
         }
         else
         {
             rtb1.AppendText("aborted.");
             return;
         }
     }
     rtb1.AppendText("done.\nSearching cat for SHA1s...");
     pb1.Maximum = listTex.Count + listChunks.Count;
     pb1.Value   = 0;
     for (int i = 0; i < listTex.Count; i++)
     {
         pb1.Value++;
         if ((i & 10) == 0)
         {
             Application.DoEvents();
         }
         TextureInfo t   = listTex[i];
         List <uint> res = cat.FindBySHA1(t.sha1);
         if (res.Count == 8)
         {
             t.catline  = res;
             listTex[i] = t;
         }
     }
     for (int i = 0; i < listChunks.Count; i++)
     {
         pb1.Value++;
         if ((i & 10) == 0)
         {
             Application.DoEvents();
         }
         ChunkInfo   c   = listChunks[i];
         List <uint> res = cat.FindBySHA1(c.sha1);
         if (res.Count == 8)
         {
             c.catline     = res;
             listChunks[i] = c;
         }
     }
     rtb1.AppendText("done.\nLinking Textures and Chunks...");
     pb1.Value = 0;
     Application.DoEvents();
     LinkTexAndChunks();
     rtb1.AppendText("done.\nFinished!");
     Application.DoEvents();
     foreach (TextureInfo t in listTex)
     {
         listBox1.Items.Add(t.fullpath);
     }
 }
Exemple #32
0
 static SpriteInfo GetSpriteInfo(TextureInfo textinfo, ASprite src)
 {
     return(textinfo.GetSprite(src));
 }
Exemple #33
0
 static Color[] getColors(int x, int y, int size_x, int size_z, TextureInfo[] texInfos)
 {
     Color[] p;
     if (x == 0 && y == 0)
         p = texInfos[0].texColors[0];
     else if (x == 3 && y == 2)
         p = texInfos[0].texColors[21];
     else
         p = texInfos[0].texColors[11];
     return p;
 }
        public IntRect Get(Texture texture, IntRect subrect)
        {
            var info = new TextureInfo(texture, subrect);

            IntRect res;
            if (textureLocations.TryGetValue(info, out res))
                return res;

            IntRect r;

            try
            {
                r = freeRects.First(rect => rect.Width >= subrect.Width && rect.Height >= subrect.Height);
            }
            catch
            {
                throw new Exception("SpriteBatch size is too small");
            }

            freeRects.Remove(r);

            res = new IntRect(r.Left, r.Top, subrect.Width, subrect.Height);
            textureLocations.Add(info, res);

            var rightSector = new IntRect(r.Left + subrect.Width, r.Top, r.Width - subrect.Width, subrect.Height);
            var bottomSector = new IntRect(r.Left, r.Top + subrect.Height, r.Width, r.Height - subrect.Height);

            if (rightSector.Width != 0 && rightSector.Height != 0)
                freeRects.Add(rightSector);

            if (bottomSector.Width != 0 && bottomSector.Height != 0)
                freeRects.Add(bottomSector);

            freeRects.Sort((i, j) => i.Height - j.Height);

            var spr = new Sprite(texture, subrect) { Position = new Vector2f(res.Left, res.Top) };

            renderTexture.Draw(spr, new RenderStates(BlendMode.None));
            renderTexture.Display();

            return res;
        }
Exemple #35
0
        async Task LoadFIX()
        {
            textures     = new TextureInfo[0];
            loadingState = "Loading fixed memory";
            await WaitIfNecessary();

            files_array[Mem.Fix].GotoHeader();
            Reader reader = files_array[Mem.Fix].reader;

            reader.ReadUInt32();             // Offset of languages
            byte num_lvlNames = reader.ReadByte();

            reader.ReadByte();
            reader.ReadByte();
            reader.ReadByte();
            ReadLevelNames(reader, Pointer.Current(reader), num_lvlNames);
            if (Settings.s.platform == Settings.Platform.PC)
            {
                reader.ReadChars(0x1E);
                reader.ReadChars(0x1E);                 // two zero entries
            }
            string firstMapName            = new string(reader.ReadChars(0x1E));
            byte   num_languages_subtitles = reader.ReadByte();
            byte   num_languages_voice     = reader.ReadByte();

            reader.ReadByte();
            reader.ReadByte();
            print(Pointer.Current(reader));
            Pointer off_languages_subtitles = Pointer.Read(reader);
            Pointer off_languages_voice     = Pointer.Read(reader);

            Pointer.DoAt(ref reader, off_languages_subtitles, () => {
                ReadLanguages(reader, off_languages_subtitles, num_languages_subtitles);
            });
            Pointer.DoAt(ref reader, off_languages_voice, () => {
                ReadLanguages(reader, off_languages_voice, num_languages_voice);
            });

            int sz_entryActions = 0xC0;

            reader.ReadBytes(sz_entryActions);             // 3DOS_EntryActions
            reader.ReadUInt16();
            ushort num_matrices = reader.ReadUInt16();

            for (int i = 0; i < 4; i++)
            {
                reader.ReadBytes(0x101);
            }
            loadingState = "Loading input structure";
            await WaitIfNecessary();

            inputStruct = InputStructure.Read(reader, Pointer.Current(reader));
            foreach (EntryAction ea in inputStruct.entryActions)
            {
                print(ea.ToString());
            }
            reader.ReadUInt32();
            reader.ReadUInt32();
            reader.ReadUInt32();
            ushort num_unk2 = reader.ReadUInt16();

            reader.ReadUInt16();
            Pointer off_unk2         = Pointer.Read(reader);
            Pointer off_entryActions = Pointer.Read(reader);

            Pointer[] unkMatrices = new Pointer[2];
            for (int i = 0; i < 2; i++)
            {
                unkMatrices[i] = Pointer.Read(reader);
            }
            fonts = FromOffsetOrRead <FontStructure>(reader, Pointer.Current(reader), inline: true);

            Pointer off_matrices           = Pointer.Read(reader);
            Pointer off_specialEntryAction = Pointer.Read(reader);
            Pointer off_identityMatrix     = Pointer.Read(reader);
            Pointer off_unk = Pointer.Read(reader);

            reader.ReadUInt32();
            reader.ReadUInt32();
            reader.ReadBytes(0xc8);
            reader.ReadUInt16();
            reader.ReadUInt16();
            reader.ReadByte();
            reader.ReadByte();
            reader.ReadByte();
            reader.ReadByte();
            Pointer.Read(reader);
            Pointer off_haloTexture = Pointer.Read(reader);
            Pointer off_material1   = Pointer.Read(reader);
            Pointer off_material2   = Pointer.Read(reader);

            for (int i = 0; i < 10; i++)
            {
                reader.ReadBytes(0xcc);
            }
        }
Exemple #36
0
 internal Mem( Context context, IntPtr memID )
 {
     Context = context;
     MemID = memID;
     TxInfo = new TextureInfo(this);
 }
Exemple #37
0
		private void ReadGndFile() {
			string Root = textBox2.Text;
			using( FileStream s = File.OpenRead( textBox1.Text ) ) {
				using( BinaryReader bin = new BinaryReader( s, Encoding.GetEncoding( "ISO-8859-1" ) ) ) {
					bin.BaseStream.Position += 6;

					mHeader = new HeaderInfo();
					mHeader.Width = bin.ReadUInt32();
					mHeader.Height = bin.ReadUInt32();
					mHeader.Ratio = bin.ReadUInt32();
					mHeader.TextureCount = bin.ReadUInt32();
					mHeader.TextureSize = bin.ReadUInt32();

					mTextures = new TextureInfo[ mHeader.TextureCount ];
					for( int i = 0; i < mTextures.Length; i++ ) {
						mTextures[ i ] = new TextureInfo();
						mTextures[ i ].TexPath = ReadWord( bin, 40 ).ToLower();
						mTextures[ i ].Unknown = ReadWord( bin, 40 ).ToCharArray();

						mTextures[ i ].TextureBmp = Bitmap.FromFile( Root + @"\" + mTextures[ i ].TexPath ) as Bitmap;
					}

					mLightmapCount = (uint)bin.ReadInt32();

					mGrid = new GridInfo();
					mGrid.X = bin.ReadUInt32();
					mGrid.Y = bin.ReadUInt32();
					mGrid.Cells = bin.ReadUInt32();

					mLightmaps = new LitghmapInfo[ mLightmapCount ];
					for( int i = 0; i < mLightmaps.Length; i++ ) {
						mLightmaps[ i ] = new LitghmapInfo();
						mLightmaps[ i ].brightness = bin.ReadChars( 64 );
						mLightmaps[ i ].colorrbg = bin.ReadChars( 192 );
					}


					mTileCount = (uint)bin.ReadInt32();
					mTiles = new TileInfo[ mTileCount ];
					for( int i = 0; i < mTiles.Length; i++ ) {
						mTiles[ i ] = new TileInfo();
						mTiles[ i ].VectorWidth = ReadVector4( bin );
						mTiles[ i ].VectorHeight = ReadVector4( bin );
						mTiles[ i ].TextureIndex = bin.ReadUInt16();
						mTiles[ i ].Lightmap = bin.ReadUInt16();
						mTiles[ i ].color = bin.ReadChars( 4 );
					}

					mCubeCount = mHeader.Width * mHeader.Height;
					mCubes = new CubeInfo[ mCubeCount ];
					for( int i = 0; i < mCubes.Length; i++ ) {
						mCubes[ i ] = new CubeInfo();
						mCubes[ i ].Height = ReadVector4( bin );
						mCubes[ i ].tile_up = bin.ReadInt32();
						mCubes[ i ].tile_side = bin.ReadInt32();
						mCubes[ i ].tile_aside = bin.ReadInt32();
					}

				}

			}

		}
 public bool TryGetTextureInfo(UUID textureID, out TextureInfo info)
 {
     info = new TextureInfo();
     return false;
 }
	public void senderStopped(TextureInfo texInfo)
	{
		//Debug.Log ("Editor : senderStopped :"+texInfo.name);
		updateOptions();
	}
 /// <summary>
 /// Creates a texture level from a bitmap
 /// </summary>
 private static void CreateTextureImageLevelFromBitmap( int target, int level, BitmapData bmpData, TextureInfo info, bool generateMipMaps )
 {
     int expectedStride = bmpData.Width * ( Image.GetPixelFormatSize( bmpData.PixelFormat ) / 8 );
     if ( bmpData.Stride < expectedStride )
     {
         throw new ArgumentException( string.Format( "Bitmap had unexpectedly low stride {0} - expected at least {1}", bmpData.Stride, expectedStride ), "bmp" );
     }
     if ( bmpData.Stride != expectedStride )
     {
         GraphicsLog.Warning( "Bitmap had unexpected stride {0} - copying to scratch memory", expectedStride );
         CreateTextureImageLevelFromUnpackedBitmap( target, level, info, expectedStride, bmpData, generateMipMaps );
     }
     else if ( generateMipMaps )
     {
         Glu.gluBuild2DMipmaps( target, info.GlInternalFormat, bmpData.Width, bmpData.Height, info.GlFormat, info.GlType, bmpData.Scan0 );
     }
     else
     {
         Gl.glTexImage2D( target, level, info.GlInternalFormat, bmpData.Width, bmpData.Height, 0, info.GlFormat, info.GlType, bmpData.Scan0 );
     }
 }
Exemple #41
0
 public Block(Device device, float width, float height, float depth, TextureInfo texture, bool containsTransparency = false)
     : this(device, texture, width, height, depth, containsTransparency)
 {
 }
Exemple #42
0
 private bool IsTileInTexture(TextureInfo texture, Point tile)
 {
     //TODO
     return true;
 }
        async Task LoadPS2()
        {
            await WaitIfNecessary();

            textures = new TextureInfo[0];

            loadingState = "Loading fixed memory";
            await WaitIfNecessary();

            files_array[Mem.Fix].GotoHeader();
            Reader  reader       = files_array[Mem.Fix].reader;
            Pointer off_base_fix = Pointer.Current(reader);

            loadingState = "Loading input struct";
            await WaitIfNecessary();

            for (int i = 0; i < Settings.s.numEntryActions; i++)
            {
                Pointer.Read(reader);                 // 3DOS_EntryActions
            }

            inputStruct = InputStructure.Read(reader, Pointer.Current(reader));
            foreach (EntryAction ea in inputStruct.entryActions)
            {
                print(ea.ToString());
            }
            localization = FromOffsetOrRead <LocalizationStructure>(reader, Pointer.Current(reader), inline: true);

            /*
             * Pointer off_inputStructure = Pointer.Read(reader);
             * Pointer.DoAt(ref reader, off_inputStructure, () => {
             * inputStruct = InputStructure.Read(reader, off_inputStructure);
             *      foreach (EntryAction ea in inputStruct.entryActions) {
             *              print(ea.ToString());
             *      }
             * });*/


            /*uint base_language = reader.ReadUInt32(); //Pointer off_language = Pointer.Read(reader);
             * reader.ReadUInt32();
             * uint num_text_language = reader.ReadUInt32();
             * reader.ReadUInt16();
             * reader.ReadUInt16();
             * reader.ReadUInt32(); // base
             * Pointer off_text_general = Pointer.Read(reader);
             * Pointer.DoAt(ref reader, off_text_general, () => {
             * fontStruct = FontStructure.Read(reader, off_text_general);
             * });
             * Pointer off_inputStructure = Pointer.Read(reader);
             * Pointer.DoAt(ref reader, off_inputStructure, () => {
             * inputStruct = InputStructure.Read(reader, off_inputStructure);
             *      foreach (EntryAction ea in inputStruct.entryActions) {
             *              print(ea.ToString());
             *      }
             * });
             *
             * await WaitIfNecessary();
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * Pointer.Read(reader);
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * reader.ReadUInt32();
             * Pointer.Read(reader);
             * Pointer off_levelNames = Pointer.Read(reader);
             * Pointer off_languages = Pointer.Read(reader);
             * uint num_levelNames = reader.ReadUInt32();
             * uint num_languages = reader.ReadUInt32();
             * reader.ReadUInt32(); // same as num_levelNames
             * Pointer.DoAt(ref reader, off_levelNames, () => {
             * lvlNames = new string[num_levelNames];
             * for (uint i = 0; i < num_levelNames; i++) {
             * lvlNames[i] = reader.ReadString(0x1E);
             * }
             * });
             * Pointer.DoAt(ref reader, off_languages, () => {
             * ReadLanguages(reader, off_languages, num_languages);
             * });
             * if (languages != null && fontStruct != null) {
             * for (int i = 0; i < num_languages; i++) {
             * loadingState = "Loading text files: " + (i+1) + "/" + num_languages;
             * string langFilePath = gameDataBinFolder + "TEXTS/" + languages[i].ToUpper() + ".LNG";
             * await PrepareFile(langFilePath));
             * files_array[2] = new DCDAT(languages[i], langFilePath, 2);
             * ((DCDAT)files_array[2]).SetHeaderOffset(base_language);
             * files_array[2].GotoHeader();
             * fontStruct.ReadLanguageTableDreamcast(files_array[2].reader, i, (ushort)num_text_language);
             * files_array[2].Dispose();
             * }
             * }
             *
             * loadingState = "Loading fixed textures";
             * await WaitIfNecessary();
             * Pointer off_events_fix = Pointer.Read(reader);
             * uint num_events_fix = reader.ReadUInt32();
             * uint num_textures_fix = reader.ReadUInt32();
             * Pointer off_textures_fix = Pointer.Read(reader);
             * Pointer.DoAt(ref reader, off_textures_fix, () => {
             * Array.Resize(ref textures, (int)num_textures_fix);
             * for (uint i = 0; i < num_textures_fix; i++) {
             * Pointer off_texture = Pointer.Read(reader);
             * textures[i] = null;
             * Pointer.DoAt(ref reader, off_texture, () => {
             * textures[i] = TextureInfo.Read(reader, off_texture);
             * });
             * }
             * TEX tex = new TEX(tplPaths[0]);
             * for (uint i = 0; i < num_textures_fix; i++) {
             * if (textures[i] != null && tex.Count > i) {
             * textures[i].Texture = tex.textures[i];
             * }
             * }
             * });*/
            loadingState = "Loading level memory";
            await WaitIfNecessary();

            files_array[Mem.Lvl].GotoHeader();
            reader = files_array[Mem.Lvl].reader;
            string build = reader.ReadString(0x20);

            reader.ReadUInt32();
            reader.ReadUInt32();             // 0xc
            reader.ReadUInt32();             // 0
            Pointer.Read(reader);
            Pointer.Read(reader);

            // Globals
            globals.off_actualWorld  = Pointer.Read(reader);
            globals.off_dynamicWorld = Pointer.Read(reader);
            globals.off_fatherSector = Pointer.Read(reader);
            globals.num_always       = reader.ReadUInt32();
            globals.spawnablePersos  = LinkedList <Perso> .ReadHeader(reader, Pointer.Current(reader), LinkedList.Type.Double);

            //globals.spawnablePersos.FillPointers(reader, globals.spawnablePersos.off_tail, globals.spawnablePersos.offset);
            Pointer.Read(reader);                                 // format: (0x4 number, number * 0x4: null)
            globals.off_always_reusableSO = Pointer.Read(reader); // There are (num_always) empty SuperObjects starting with this one.
            Pointer.Read(reader);
            Pointer.Read(reader);
            Pointer.Read(reader);
            Pointer.Read(reader);
            Pointer.Read(reader);

            LinkedList <Perso> cameras = LinkedList <Perso> .ReadHeader(reader, Pointer.Current(reader), LinkedList.Type.Double);

            families = LinkedList <Family> .ReadHeader(reader, Pointer.Current(reader), type : LinkedList.Type.Double);

            LinkedList <Perso> mainChars = LinkedList <Perso> .ReadHeader(reader, Pointer.Current(reader), LinkedList.Type.Double);

            Pointer.Read(reader);                      // Rayman
            reader.ReadUInt32();
            globals.off_camera = Pointer.Read(reader); // Camera
            Pointer.Read(reader);
            Pointer.Read(reader);
            Pointer.Read(reader);

            uint numMeshes             = (uint)files_array[Mem.Lvl].extraData["numMeshes"];
            uint numMaterials          = (uint)files_array[Mem.Lvl].extraData["numMaterials"];
            uint numTextures           = (uint)files_array[Mem.Lvl].extraData["numTextures"];
            uint numLightmappedObjects = (uint)files_array[Mem.Lvl].extraData["numLightmappedObjects"];

            //print("numTextures " + numTextures + " - " + txds[0].Count + " - " + numMeshes + " - " + ato.numAtomics + " - " + numLightmappedObjects);


            textures = new TextureInfo[numTextures];
            Pointer[] off_meshes = new Pointer[numMeshes];
            off_materials = new Pointer[numMaterials];
            for (int i = 0; i < numMeshes; i++)
            {
                off_meshes[i] = Pointer.Read(reader);
            }
            for (int i = 0; i < numMaterials; i++)
            {
                off_materials[i] = Pointer.Read(reader);
            }
            for (int i = 0; i < numTextures; i++)
            {
                Pointer off_textureInfo = Pointer.Read(reader);
                int     texture_index   = reader.ReadInt32();
                Pointer.DoAt(ref reader, off_textureInfo, () => {
                    textures[i]         = TextureInfo.Read(reader, off_textureInfo);
                    textures[i].Texture = txds[0].Lookup(texture_index.ToString("D3"));
                    //textures[i].Texture = txds[0].textures[txds[0].Count - 1 - texture_index];
                });
            }
            Pointer.Read(reader);
            reader.ReadUInt32();
            reader.ReadUInt32();
            Pointer.Read(reader);
            uint num_unk = reader.ReadUInt32();

            for (int i = 0; i < num_unk; i++)
            {
                Pointer.Read(reader);
            }
            uint num_unk2 = reader.ReadUInt32();

            for (int i = 0; i < num_unk2; i++)
            {
                Pointer.Read(reader);
            }
            Pointer.Read(reader);
            reader.ReadSingle();             // a bounding volume most likely
            reader.ReadSingle();
            reader.ReadSingle();
            reader.ReadSingle();
            reader.ReadSingle();
            reader.ReadSingle();
            Pointer.Read(reader);
            reader.ReadUInt32();             // 2?
            uint    num_poTable = reader.ReadUInt32();
            Pointer off_poTable = Pointer.Read(reader);

            reader.ReadUInt32();             // 1. 10x 0
            reader.ReadUInt32();             // 2
            reader.ReadUInt32();             // 3
            reader.ReadUInt32();             // 4
            reader.ReadUInt32();             // 5
            reader.ReadUInt32();             // 6
            reader.ReadUInt32();             // 7
            reader.ReadUInt32();             // 8
            reader.ReadUInt32();             // 9
            reader.ReadUInt32();             // 10
            uint num_lightCookies = reader.ReadUInt32();

            lightCookieColors = new Color[num_lightCookies];
            for (int i = 0; i < num_lightCookies; i++)
            {
                reader.ReadUInt32();
                reader.ReadUInt32();
                reader.ReadUInt32();
                reader.ReadUInt32();
                byte b = reader.ReadByte();
                byte g = reader.ReadByte();
                byte r = reader.ReadByte();
                reader.ReadByte();
                lightCookieColors[i] = new Color(r / 255f, g / 255f, b / 255f, 1f);
                reader.ReadUInt32();
                reader.ReadInt32();
                reader.ReadUInt32();
            }
            for (int i = 0; i < num_lightCookies; i++)
            {
                reader.ReadByte();
            }
            reader.Align(0x4);
            Pointer off_lightCookieMaterial = Pointer.Read(reader);

            lightCookieMaterial = VisualMaterial.FromOffsetOrRead(off_lightCookieMaterial, reader);
            off_lightmapUV      = new Pointer[numLightmappedObjects];
            for (int i = 0; i < numLightmappedObjects; i++)
            {
                reader.ReadUInt32();
                reader.ReadUInt32();
                reader.ReadUInt32();
                off_lightmapUV[i] = Pointer.Read(reader);
            }



            for (int i = 0; i < numMaterials; i++)
            {
                VisualMaterial.FromOffsetOrRead(off_materials[i], reader);
            }
            for (int i = 0; i < numMeshes; i++)
            {
                Pointer.DoAt(ref reader, off_meshes[i], () => {
                    GeometricObject mesh = GeometricObject.Read(reader, off_meshes[i]);
                    meshObjects.Add(mesh);
                    //print("Mesh " + i + ": " + mesh.num_vertices + " - " + mesh.subblock_types[0] + " - " + mesh.num_subblocks);
                });
            }

            loadingState = "Loading families";
            await WaitIfNecessary();

            ReadFamilies(reader);
            //print("Families: " + families.Count);
            loadingState = "Loading superobject hierarchy";
            await WaitIfNecessary();

            ReadSuperObjects(reader);
            loadingState = "Loading always structure";
            await WaitIfNecessary();

            ReadAlways(reader);
            loadingState = "Filling in cross-references";
            await WaitIfNecessary();

            ReadCrossReferences(reader);
            await WaitIfNecessary();
        }
                public TextureInfo cloneTexture()
                {
                    TextureInfo info = new TextureInfo();
                    info.url = url;
                    info.normalMap = normalMap;
                    info.texture = texture;
                    info.name = name;

                    return info;
                }
Exemple #45
0
        /// <summary>
        /// Processes a <see cref="BrushSide"/> into a state where it can be output into a file that map editors can read.
        /// </summary>
        /// <param name="brushSide">The <see cref="BrushSide"/> to process.</param>
        /// <param name="worldPosition">The position of the parent <see cref="Entity"/> in the world. This is important for calculating UVs on solids.</param>
        /// <param name="sideIndex">The index of this side reference in the parent <see cref="Brush"/>. Important for Call of Duty series maps, since
        /// the first six <see cref="BrushSide"/>s in a <see cref="Brush"/> don't contain <see cref="Plane"/> references.</param>
        /// <returns>The processed <see cref="MAPBrushSode"/> object, to be added to a <see cref="Brush"/> object.</returns>
        private MAPBrushSide ProcessBrushSide(BrushSide brushSide, Vector3 worldPosition, int sideIndex)
        {
            if (brushSide.IsBevel)
            {
                return(null);
            }
            MAPBrushSide mapBrushSide;
            // The things we'll need to define a .MAP brush side
            string      texture;
            string      material = "wld_lightmap";
            TextureInfo texInfo;

            Vector3[] threePoints;
            Plane     plane;
            int       flags = 0;

            // If we have a face reference here, let's use it!
            if (brushSide.FaceIndex >= 0)
            {
                Face face = _bsp.faces[brushSide.FaceIndex];
                // In Nightfire, faces with "256" flag set should be ignored
                if ((face.Type & (1 << 8)) != 0)
                {
                    return(null);
                }
                texture     = (_master.settings.replace512WithNull && (face.Type & (1 << 9)) != 0) ? "**nulltexture**" : _bsp.textures[face.TextureIndex].Name;
                threePoints = GetPointsForFace(face, brushSide);
                if (face.PlaneIndex >= 0 && face.PlaneIndex < _bsp.planes.Count)
                {
                    plane = _bsp.planes[face.PlaneIndex];
                }
                else if (brushSide.PlaneIndex >= 0 && brushSide.PlaneIndex < _bsp.planes.Count)
                {
                    plane = _bsp.planes[brushSide.PlaneIndex];
                }
                else
                {
                    plane = new Plane(0, 0, 0, 0);
                }
                if (_bsp.texInfo != null)
                {
                    texInfo = _bsp.texInfo[face.TextureInfoIndex];
                }
                else
                {
                    Vector3[] newAxes = TextureInfo.TextureAxisFromPlane(plane);
                    texInfo = new TextureInfo(newAxes[0], newAxes[1], Vector2.Zero, Vector2.One, flags, -1, 0);
                }
                flags = _master.settings.noFaceFlags ? 0 : face.Type;
                if (face.MaterialIndex >= 0)
                {
                    material = _bsp.materials[face.MaterialIndex].Name;
                }
            }
            else
            {
                // TODO: This is awful. Let's rework the enum to have internal ways to check engine forks.
                if (_bsp.version == MapType.CoD || _bsp.version == MapType.CoD2 || _bsp.version == MapType.CoD4)
                {
                    switch (sideIndex)
                    {
                    case 0: {                             // XMin
                        plane = new Plane(-1, 0, 0, -brushSide.Distance);
                        break;
                    }

                    case 1: {                             // XMax
                        plane = new Plane(1, 0, 0, brushSide.Distance);
                        break;
                    }

                    case 2: {                             // YMin
                        plane = new Plane(0, -1, 0, -brushSide.Distance);
                        break;
                    }

                    case 3: {                             // YMax
                        plane = new Plane(0, 1, 0, brushSide.Distance);
                        break;
                    }

                    case 4: {                             // ZMin
                        plane = new Plane(0, 0, -1, -brushSide.Distance);
                        break;
                    }

                    case 5: {                             // ZMax
                        plane = new Plane(0, 0, 1, brushSide.Distance);
                        break;
                    }

                    default: {
                        plane = _bsp.planes[brushSide.PlaneIndex];
                        break;
                    }
                    }
                }
                else
                {
                    plane = _bsp.planes[brushSide.PlaneIndex];
                }
                threePoints = plane.GenerateThreePoints();
                if (brushSide.TextureIndex >= 0)
                {
                    // TODO: This is awful. Let's rework the enum to have internal ways to check engine forks.
                    if (_bsp.version == MapType.Source17 ||
                        _bsp.version == MapType.Source18 ||
                        _bsp.version == MapType.Source19 ||
                        _bsp.version == MapType.Source20 ||
                        _bsp.version == MapType.Source21 ||
                        _bsp.version == MapType.Source22 ||
                        _bsp.version == MapType.Source23 ||
                        _bsp.version == MapType.Source27 ||
                        _bsp.version == MapType.Vindictus ||
                        _bsp.version == MapType.DMoMaM ||
                        _bsp.version == MapType.L4D2 ||
                        _bsp.version == MapType.TacticalInterventionEncrypted ||
                        _bsp.version == MapType.Titanfall)
                    {
                        texInfo = _bsp.texInfo[brushSide.TextureIndex];
                        TextureData currentTexData;
                        // I've only found one case where this is bad: c2a3a in HL Source. Don't know why.
                        if (texInfo.TextureIndex >= 0)
                        {
                            currentTexData = _bsp.texDatas[texInfo.TextureIndex];
                            texture        = _bsp.textures.GetTextureAtOffset((uint)_bsp.texTable[currentTexData.TextureStringOffsetIndex]);
                        }
                        else
                        {
                            texture = "**skiptexture**";
                        }
                    }
                    else
                    {
                        Texture textureDef = _bsp.textures[brushSide.TextureIndex];
                        texture = textureDef.Name;
                        texInfo = textureDef.TextureInfo;
                    }
                }
                else
                {
                    Vector3[] newAxes = TextureInfo.TextureAxisFromPlane(plane);
                    texInfo = new TextureInfo(newAxes[0], newAxes[1], Vector2.Zero, Vector2.One, flags, -1, 0);
                    texture = "**cliptexture**";
                }
            }

            TextureInfo outputTexInfo;

            if (texInfo.Data != null && texInfo.Data.Length > 0)
            {
                outputTexInfo = texInfo.BSP2MAPTexInfo(worldPosition);
            }
            else
            {
                Vector3[] newAxes = TextureInfo.TextureAxisFromPlane(plane);
                outputTexInfo = new TextureInfo(newAxes[0], newAxes[1], Vector2.Zero, Vector2.One, 0, -1, 0);
            }

            mapBrushSide = new MAPBrushSide()
            {
                vertices    = threePoints,
                plane       = plane,
                texture     = texture,
                textureInfo = outputTexInfo,
                material    = material,
                lgtScale    = 16,
                lgtRot      = 0
            };

            return(mapBrushSide);
        }
Exemple #46
0
 public StreamLoader(Stream stream, bool autoClose)
 {
     info           = new TextureInfo(stream);
     this.autoClose = autoClose;
 }
Exemple #47
0
        /// <summary>
        /// テクスチャを連結する
        /// </summary>
        /// <param name="texture"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <remarks>
        /// 他のテクスチャを (x,y) の位置に連結する
        /// 連結後の Textures のサイズは、被覆部分を考慮しての最大矩形。
        /// 
        /// rateをかける前のwidth,heightから計算するので
        /// rate == 1と考えて座標を指定してください。
        /// 
        /// Addしたあとは再計算のために必ずUpdate()を呼び出すこと。
        /// </remarks>
        /// <example>
        /// 例)
        /// 	横50×縦30のTexturesに、横100×縦200のTexturesを
        /// 	(0,20)の位置の連結した場合、連結後のTexturesは、
        /// 	横100×縦220のサイズ。
        /// ITexture は、Texture , Textures の元となるクラスなので、
        /// 通常のTexture でも Textures でも連結できることを意味する。
        /// 
        /// x,yは負を指定しても良いが、その場合はwidth,heightには反映されない。
        /// </example>
        public void Add(ITexture texture, int x, int y)
        {
            TextureInfo info = new TextureInfo();

            info.Texture = texture;
            info.PosX = x;
            info.PosY = y;
            info.Width = texture.Width;
            info.Height = texture.Height;

            infos.Add(info);

            /* 連結後のtextureサイズを計算しなくては.. */
            float w = x + texture.Width;
            float h = y + texture.Height;

            //		width  = max(width,w);
            //		height = max(height,h);
            if (width < w) width = w;
            if (height < h) height = h;
        }
Exemple #48
0
        internal static Dictionary <string, int> AddMaterials(this Gltf gltf, IList <Material> materials, List <byte> buffer, List <BufferView> bufferViews)
        {
            var materialDict = new Dictionary <string, int>();
            var newMaterials = new List <glTFLoader.Schema.Material>();

            var textureDict = new Dictionary <string, int>(); // the name of the texture image, the id of the texture
            var textures    = new List <glTFLoader.Schema.Texture>();

            var images   = new List <glTFLoader.Schema.Image>();
            var samplers = new List <glTFLoader.Schema.Sampler>();

            var matId     = 0;
            var texId     = 0;
            var imageId   = 0;
            var samplerId = 0;

            foreach (var material in materials)
            {
                if (materialDict.ContainsKey(material.Name))
                {
                    continue;
                }

                var m = new glTFLoader.Schema.Material();
                newMaterials.Add(m);

                m.PbrMetallicRoughness = new MaterialPbrMetallicRoughness();
                m.PbrMetallicRoughness.BaseColorFactor = material.Color.ToArray();
                m.PbrMetallicRoughness.MetallicFactor  = 1.0f;
                m.DoubleSided = material.DoubleSided;
                m.Name        = material.Name;

                if (material.Unlit)
                {
                    m.Extensions = new Dictionary <string, object> {
                        { "KHR_materials_unlit", new Dictionary <string, object> {
                          } }
                    };
                }
                else
                {
                    m.Extensions = new Dictionary <string, object> {
                        { "KHR_materials_pbrSpecularGlossiness", new Dictionary <string, object> {
                              { "diffuseFactor", new[] { material.Color.Red, material.Color.Green, material.Color.Blue, material.Color.Alpha } },
                              { "specularFactor", new[] { material.SpecularFactor, material.SpecularFactor, material.SpecularFactor } },
                              { "glossinessFactor", material.GlossinessFactor }
                          } }
                    };
                }

                if (material.Texture != null)
                {
                    // Add the texture
                    var ti = new TextureInfo();
                    m.PbrMetallicRoughness.BaseColorTexture = ti;
                    ti.Index    = texId;
                    ti.TexCoord = 0;
                    ((Dictionary <string, object>)m.Extensions["KHR_materials_pbrSpecularGlossiness"])["diffuseTexture"] = ti;

                    if (textureDict.ContainsKey(material.Texture))
                    {
                        ti.Index = textureDict[material.Texture];
                    }
                    else
                    {
                        var tex = new Texture();
                        textures.Add(tex);

                        var image = new glTFLoader.Schema.Image();

                        using (var ms = new MemoryStream())
                        {
                            // Flip the texture image vertically
                            // to align with OpenGL convention.
                            // 0,1  1,1
                            // 0,0  1,0
                            using (var texImage = SixLabors.ImageSharp.Image.Load(material.Texture))
                            {
                                texImage.Mutate(x => x.Flip(FlipMode.Vertical));
                                texImage.Save(ms, new SixLabors.ImageSharp.Formats.Png.PngEncoder());
                            }
                            var imageData = ms.ToArray();
                            image.BufferView = AddBufferView(bufferViews, 0, buffer.Count, imageData.Length, null, null);
                            buffer.AddRange(imageData);
                        }

                        while (buffer.Count % 4 != 0)
                        {
                            // Console.WriteLine("Padding...");
                            buffer.Add(0);
                        }

                        image.MimeType = glTFLoader.Schema.Image.MimeTypeEnum.image_png;
                        tex.Source     = imageId;
                        images.Add(image);

                        var sampler = new Sampler();
                        sampler.MagFilter = Sampler.MagFilterEnum.LINEAR;
                        sampler.MinFilter = Sampler.MinFilterEnum.LINEAR;
                        sampler.WrapS     = Sampler.WrapSEnum.REPEAT;
                        sampler.WrapT     = Sampler.WrapTEnum.REPEAT;
                        tex.Sampler       = samplerId;
                        samplers.Add(sampler);

                        textureDict.Add(material.Texture, texId);

                        texId++;
                        imageId++;
                        samplerId++;
                    }
                }

                if (material.Color.Alpha < 1.0)
                {
                    m.AlphaMode = glTFLoader.Schema.Material.AlphaModeEnum.BLEND;
                }
                else
                {
                    m.AlphaMode = glTFLoader.Schema.Material.AlphaModeEnum.OPAQUE;
                }

                materialDict.Add(m.Name, matId);
                matId++;
            }

            if (materials.Count > 0)
            {
                gltf.Materials = newMaterials.ToArray();
            }
            if (textures.Count > 0)
            {
                gltf.Textures = textures.ToArray();
            }
            if (images.Count > 0)
            {
                gltf.Images = images.ToArray();
            }
            if (samplers.Count > 0)
            {
                gltf.Samplers = samplers.ToArray();
            }

            return(materialDict);
        }
Exemple #49
0
    static List <TextureInfo> GetAllDataList(string uiPicRootDir, string prefabRoot)
    {
        EditorUtility.ClearProgressBar();

        if (string.IsNullOrEmpty(prefabRoot))
        {
            return(null);
        }

        if (string.IsNullOrEmpty(uiPicRootDir))
        {
            return(null);
        }

        //获取所有纹理的uuid
        var pngs = Directory.GetFiles(uiPicRootDir, "*.meta", SearchOption.AllDirectories)
                   .Select(p => "Assets/" + p.Replace('\\', '/').Substring(Application.dataPath.Length + 1))
                   .Where(p => p.EndsWith(".png.meta")).ToList();

        var imgUuid2path = new Dictionary <string, string>();

        List <TextureInfo> list = new List <TextureInfo>();

        var uuidReg = new Regex(@"guid: ([a-f0-9]{32})");

        for (var i = 0; i < pngs.Count; ++i)
        {
            var png = pngs[i];

            var matcher = uuidReg.Match(File.ReadAllText(png));
            var uuid    = matcher.Groups[1].Value;
            if (imgUuid2path.ContainsKey(uuid))
            {
                Debug.LogError("uuid dup" + uuid + " \n" + png + "\n" + imgUuid2path[uuid]);
            }
            else
            {
                string _path = png.Substring(0, png.Length - 5).Replace("Assets/App/Pro/GameRes/UI/Module/", "");
                imgUuid2path.Add(uuid, _path);

                if (!_path.Contains("config") && !_path.Contains("common") && !_path.Contains("timeline"))
                {
                    string fileName = Path.GetFileNameWithoutExtension(_path);

                    var t = list.Find(l => l.imgName == fileName);
                    if (t == null)
                    {
                        t = new TextureInfo {
                            imgName = fileName
                        };
                        list.Add(t);
                    }

                    TextureInfo.imageInfo img = new TextureInfo.imageInfo {
                        UUID = uuid
                    };

                    t.imgList.Add(img);
                }
            }
            if (EditorUtility.DisplayCancelableProgressBar("扫描图片中", Path.GetFileNameWithoutExtension(png),
                                                           (float)i / pngs.Count))
            {
                EditorUtility.ClearProgressBar();
                return(null);
            }
        }


        EditorUtility.ClearProgressBar();

        var prefabs = Directory.GetFiles(prefabRoot, "*.prefab", SearchOption.AllDirectories).ToList();

        for (var i = 0; i < prefabs.Count; i++)
        {
            var prefab = prefabs[i];

            if (EditorUtility.DisplayCancelableProgressBar("获取引用关系", Path.GetFileNameWithoutExtension(prefab),
                                                           (float)i / prefabs.Count))
            {
                EditorUtility.ClearProgressBar();
                return(null);
            }

            var uuids = getUUIDsInFile(prefab);

            var fullPath = prefab;

            prefab = prefab.Replace('\\', '/').Substring(prefabRoot.Length + 1);

            var moduleName = prefab.Remove(prefab.IndexOf(Path.AltDirectorySeparatorChar));
            moduleName = moduleName.ToLower();

            foreach (var uuid in uuids)
            {
                //是图片
                if (imgUuid2path.ContainsKey(uuid))
                {
                    var imgPath = imgUuid2path[uuid];
                    if (!imgPath.Contains("config") && !imgPath.Contains("common") && !imgPath.Contains("timeline"))
                    {
                        var fileName = Path.GetFileNameWithoutExtension(imgPath);

                        var tex = list.Find(l => l.imgName.Equals(fileName));

                        if (tex == null)
                        {
                            Debug.LogError("Error");
                        }

                        var uuid1 = uuid;
                        var img   = tex.imgList.Find(im => im.UUID == uuid1);
                        if (img == null)
                        {
                            img = new TextureInfo.imageInfo {
                                UUID = uuid1
                            };
                        }

                        if (!img.prefab.Contains(fullPath))
                        {
                            img.prefab.Add(fullPath);
                        }
                    }
                }
            }
        }

        EditorUtility.ClearProgressBar();

        return(list);
    }
Exemple #50
0
        /// <summary>
        /// Generates a VisualTopo file 3D model
        /// </summary>
        /// <remarks>LT* (Lambert Carto) projections are not supported and could produce imprecise results (shifted by +10meters)</remarks>
        /// <param name="vtopoFile">VisualTopo .TRO file</param>
        /// <param name="imageryProvider">Imagery provider for terrain texture. Set to null for untextured model</param>
        /// <param name="bboxMarginMeters">Terrain margin (meters) around VisualTopo model</param>
        public void Run_3DModelGeneration(string vtopoFile, ImageryProvider imageryProvider, float bboxMarginMeters = 1000, bool generateTopoOnlyModel = false, float zFactor = 1f)
        {
            try
            {
                //=======================
                // Generation params
                //
                int    outputSRID      = 3857;                         // Output SRID
                float  lineWidth       = 1.0F;                         // Topo lines width (meters)
                var    dataset         = DEMDataSet.AW3D30;            // DEM dataset for terrain and elevation
                int    TEXTURE_TILES   = 8;                            // Texture quality (number of tiles for bigger side) 4: med, 8: high, 12: ultra
                string outputDir       = Directory.GetCurrentDirectory();
                bool   GENERATE_LINE3D = false;

                //=======================
                // Open and parse file
                //
                // model will have available properties
                // => Graph (nodes/arcs)
                // => BoundingBox
                // => Topology3D -> list of point-to-point lines
                // => SRID of model file
                StopwatchLog    timeLog = StopwatchLog.StartNew(_logger);
                VisualTopoModel model   = _visualTopoService.LoadFile(vtopoFile, Encoding.GetEncoding("ISO-8859-1")
                                                                      , decimalDegrees: true
                                                                      , ignoreRadialBeams: true
                                                                      , zFactor);
                timeLog.LogTime($"Loading {vtopoFile} model file");

                // for debug,
                //var b = GetBranches(model); // graph list of all nodes
                //var lowestPoint = model.Sets.Min(s => s.Data.Min(d => d.GlobalGeoPoint?.Elevation ?? 0));

                BoundingBox bbox = model.BoundingBox                                                                                  // relative coords
                                   .Translate(model.EntryPoint.Longitude, model.EntryPoint.Latitude, model.EntryPoint.Elevation ?? 0) // absolute coords
                                   .Pad(bboxMarginMeters)                                                                             // margin around model
                                   .ReprojectTo(model.SRID, dataset.SRID);                                                            // DEM coords
                                                                                                                                      // Get height map
                                                                                                                                      // Note that ref Bbox means that the bbox will be adjusted to match DEM data
                var heightMap        = _elevationService.GetHeightMap(ref bbox, dataset, downloadMissingFiles: true);
                var bboxTerrainSpace = bbox.ReprojectTo(dataset.SRID, outputSRID);                                                    // terrain coords
                timeLog.LogTime("Terrain height map");

                //=======================
                // Get entry elevation (need to reproject to DEM coordinate system first)
                // and sections entry elevations
                //
                _visualTopoService.ComputeFullCavityElevations(model, dataset, zFactor); // will add TerrainElevationAbove and entry elevations
                _visualTopoService.Create3DTriangulation(model);
                timeLog.LogTime("Cavity points elevation");

                // Model origin
                GeoPoint axisOriginWorldSpace = model.EntryPoint.ReprojectTo(model.SRID, outputSRID)
                                                .CenterOnOrigin(bboxTerrainSpace);
                Vector3 axisOriginModelSpace = model.EntryPoint.AsVector3();

                //=======================
                // Local transform function from model coordinates (relative to entry, in meters)
                // and global coordinates absolute in final 3D model space
                //
                IEnumerable <GeoPoint> TransformLine(IEnumerable <GeoPoint> line)
                {
                    var newLine = line.Translate(model.EntryPoint)             // Translate to entry (=> global topo coord space)
                                  .ReprojectTo(model.SRID, outputSRID)         // Reproject to terrain coord space
                                  .CenterOnOrigin(bboxTerrainSpace)            // Center on terrain space origin
                                  .CenterOnOrigin(axisOriginWorldSpace);

                    return(newLine);
                };


                //=======================
                // 3D model
                //
                var gltfModel = _gltfService.CreateNewModel();

                // Add X/Y/Z axis on entry point
                var axis = _meshService.CreateAxis();
                _gltfService.AddMesh(gltfModel, "Axis", axis, doubleSided: false);

                int i = 0;

                var triangulation = model.TriangulationFull3D.Clone()
                                    .Translate(axisOriginModelSpace)             // already zScaled if zFactor > 1
                                    .ReprojectTo(model.SRID, outputSRID)
                                    .CenterOnOrigin(bboxTerrainSpace)
                                    .CenterOnOrigin(axisOriginWorldSpace.AsVector3());
                gltfModel = _gltfService.AddMesh(gltfModel, "Cavite3D", model.TriangulationFull3D, VectorsExtensions.CreateColor(0, 255, 0), doubleSided: false);

                if (GENERATE_LINE3D)
                {
                    foreach (var line in model.Topology3D) // model.Topology3D is the graph of topo paths
                    {
                        // Add line to model
                        gltfModel = _gltfService.AddLine(gltfModel
                                                         , string.Concat("GPX", i++)    // name of 3D node
                                                         , TransformLine(line)          // call transform function
                                                         , color: VectorsExtensions.CreateColor(255, 0, 0, 128)
                                                         , lineWidth);
                    }
                }
                timeLog.LogTime("Topo 3D model");


                //axis = _meshService.CreateAxis(10,100);
                //_gltfService.AddMesh(gltfModel, "Axis", axis, doubleSided: false);

                if (generateTopoOnlyModel)
                {
                    // Uncomment this to save 3D model for topo only (without terrain)
                    gltfModel.SaveGLB(string.Concat(Path.GetFileNameWithoutExtension(vtopoFile) + $"Z{zFactor}_TopoOnly.glb"));
                }

                // Reproject and center height map coordinates
                heightMap = heightMap.ReprojectTo(dataset.SRID, outputSRID)
                            .CenterOnOrigin(bboxTerrainSpace)
                            .ZScale(zFactor)
                            .CenterOnOrigin(axisOriginWorldSpace);
                //.BakeCoordinates();
                timeLog.LogTime("Height map transform");

                //=======================
                // Textures
                //
                PBRTexture pbrTexture = null;
                if (imageryProvider != null)
                {
                    TileRange tiles    = _imageryService.DownloadTiles(bbox, imageryProvider, TEXTURE_TILES);
                    string    fileName = Path.Combine(outputDir, "Texture.jpg");
                    timeLog.LogTime("Imagery download");

                    Console.WriteLine("Construct texture...");
                    //TextureInfo texInfo = _imageryService.ConstructTexture(tiles, bbox, fileName, TextureImageFormat.image_jpeg);
                    var         topoTexture = model.Topology3D.SelectMany(l => l).Translate(model.EntryPoint).ReprojectTo(model.SRID, 4326);
                    TextureInfo texInfo     = _imageryService.ConstructTextureWithGpxTrack(tiles, bbox, fileName, TextureImageFormat.image_jpeg
                                                                                           , topoTexture, false);

                    pbrTexture = PBRTexture.Create(texInfo, null);
                    timeLog.LogTime("Texture creation");
                }
                //
                //=======================

                // Triangulate height map
                _logger.LogInformation($"Triangulating height map and generating 3D mesh...");

                gltfModel = _gltfService.AddTerrainMesh(gltfModel, heightMap, pbrTexture);
                gltfModel.SaveGLB(string.Concat(Path.GetFileNameWithoutExtension(vtopoFile) + $"Z{zFactor}.glb"));
                timeLog.LogTime("3D model");
            }
            catch (Exception ex)
            {
                _logger.LogError("Error :" + ex.Message);
            }
        }
        /// <summary>
        /// Checks if a pixel format is valid
        /// </summary>
        /// <param name="format">Format to check</param>
        /// <param name="info">Texture formatting information is output into this parameter</param>
        /// <returns>Returns either format, if it was directly supported by OpenGL, or a reasonable alternative</returns>
        private static PixelFormat CheckPixelFormat( PixelFormat format, out TextureInfo info )
        {
            //	Handle direct mappings to GL texture image formats
            switch ( format )
            {
                case PixelFormat.Alpha					:	break;
                case PixelFormat.Canonical				:	break;
                case PixelFormat.DontCare				:	break;
                case PixelFormat.Extended				:	break;
                case PixelFormat.Format16bppArgb1555	:	break;
                case PixelFormat.Format16bppGrayScale	:	break;
                case PixelFormat.Format16bppRgb555 		:	break;
                case PixelFormat.Format16bppRgb565 		:	break;
                case PixelFormat.Format1bppIndexed 		:	break;
                case PixelFormat.Format24bppRgb			:
                {
                    info = new TextureInfo( Gl.GL_RGB, Gl.GL_BGR_EXT, Gl.GL_UNSIGNED_BYTE, TextureFormat.R8G8B8 );
                    return format;
                }
                case PixelFormat.Format32bppArgb		:
                {
                    info = new TextureInfo( Gl.GL_RGBA, Gl.GL_BGRA, Gl.GL_UNSIGNED_BYTE, TextureFormat.A8R8G8B8 );
                    return format;
                }
                case PixelFormat.Format32bppPArgb		:	break;
                case PixelFormat.Format32bppRgb			:
                {

                //	info = new TextureInfo( Gl.GL_ABGR_EXT, Gl.GL_BGRA, Gl.GL_UNSIGNED_BYTE, TextureFormat.A8R8G8B8 );
                //	return format;
                    //	glFormat			= Gl.GL_ABGR_EXT;
                //	glFormat = Gl.GL_RGBA;	//	NOTE: AP: ABGR extension not supported on dev machine! SHIT!
                //	glInternalFormat	= Gl.GL_RGBA;
                //	glType				= Gl.GL_UNSIGNED_BYTE;
                    //	return format;
                    info = new TextureInfo( Gl.GL_RGB, Gl.GL_BGRA, Gl.GL_UNSIGNED_BYTE, TextureFormat.A8R8G8B8 );
                    return PixelFormat.Format32bppArgb;
                }
                case PixelFormat.Format48bppRgb			:	break;
                case PixelFormat.Format4bppIndexed		:	break;
                case PixelFormat.Format64bppArgb		:	break;
                case PixelFormat.Format64bppPArgb		:	break;
                case PixelFormat.Format8bppIndexed		:	break;
                case PixelFormat.Gdi					:	break;
                case PixelFormat.Indexed				:	break;
                case PixelFormat.Max					:	break;
                case PixelFormat.PAlpha					:	break;
            }

            info = new TextureInfo( Gl.GL_RGB, Gl.GL_BGR_EXT, Gl.GL_UNSIGNED_BYTE, TextureFormat.R8G8B8 );
            return PixelFormat.Format24bppRgb;
        }
Exemple #52
0
        public List <TextureInfo> GetConfiguredTexutres()
        {
            var result = new List <TextureInfo>();

            foreach (var prop in properties.OfType <TextureShaderProperty>())
            {
                if (prop.referenceName != null)
                {
                    var textureInfo = new TextureInfo
                    {
                        name      = prop.referenceName,
                        textureId = prop.value.texture != null?prop.value.texture.GetInstanceID() : 0,
                                        modifiable = prop.modifiable
                    };
                    result.Add(textureInfo);
                }
            }

            foreach (var prop in properties.OfType <Texture2DArrayShaderProperty>())
            {
                if (prop.referenceName != null)
                {
                    var textureInfo = new TextureInfo
                    {
                        name      = prop.referenceName,
                        textureId = prop.value.textureArray != null?prop.value.textureArray.GetInstanceID() : 0,
                                        modifiable = prop.modifiable
                    };
                    result.Add(textureInfo);
                }
            }

            foreach (var prop in properties.OfType <Texture3DShaderProperty>())
            {
                if (prop.referenceName != null)
                {
                    var textureInfo = new TextureInfo
                    {
                        name      = prop.referenceName,
                        textureId = prop.value.texture != null?prop.value.texture.GetInstanceID() : 0,
                                        modifiable = prop.modifiable
                    };
                    result.Add(textureInfo);
                }
            }

            foreach (var prop in properties.OfType <CubemapShaderProperty>())
            {
                if (prop.referenceName != null)
                {
                    var textureInfo = new TextureInfo
                    {
                        name      = prop.referenceName,
                        textureId = prop.value.cubemap != null?prop.value.cubemap.GetInstanceID() : 0,
                                        modifiable = prop.modifiable
                    };
                    result.Add(textureInfo);
                }
            }
            return(result);
        }
        /// <summary>
        /// Creates a texture image level from an unpacked bitmap (stride is not equal to expected stride)
        /// </summary>
        private static unsafe void CreateTextureImageLevelFromUnpackedBitmap( int target, int level, TextureInfo info, int expectedStride, BitmapData bmpData, bool generateMipMaps )
        {
            byte[] tempImage = new byte[ expectedStride * bmpData.Height ];

            fixed ( byte* dstBytes = tempImage )
            {
                byte* dstPixel = dstBytes;
                byte* srcBytes = ( byte* )bmpData.Scan0.ToPointer( );
                for ( int y = 0; y < bmpData.Height; ++y )
                {
                    byte* srcPixel = srcBytes;
                    for ( int x = 0; x < expectedStride; ++x )
                    {
                        *( dstPixel++ ) = *( srcPixel++ );
                    }

                    srcBytes += bmpData.Stride;
                }
                if ( generateMipMaps )
                {
                    Glu.gluBuild2DMipmaps( target, info.GlInternalFormat, bmpData.Width, bmpData.Height, info.GlFormat, info.GlType, new IntPtr( dstBytes ) );
                }
                else
                {
                    Gl.glTexImage2D( target, level, info.GlInternalFormat, bmpData.Width, bmpData.Height, 0, info.GlFormat, info.GlType, new IntPtr( dstBytes ) );
                }
            }
        }
        /// <summary>
        /// Exports a texture
        /// </summary>
        /// <param name="info"></param>
        /// <param name="platforms"></param>
        /// <returns></returns>
        public bool Export(TextureInfo info, List <Platform> platforms)
        {
            if (info == null)
            {
                return(false);
            }

            string filename = info.Filename;
            string ext      = System.IO.Path.GetExtension(filename).ToLower();

            foreach (Platform platform in platforms)
            {
                // Determine the destination file
                string destFile = platform.OutputDirectory + "/" + filename;
                if (!System.IO.Path.IsPathRooted(destFile))
                {
                    destFile = GUIProject.CurrentProject.ProjectDirectory + "/" + destFile;
                }

                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(destFile));

                string sourceFile = GUIProject.CurrentProject.ProjectDirectory + "/" + filename;
                if (System.IO.File.Exists(sourceFile))
                {
                    bool doRawCopy = true;

                    if (platform.SquarifyTextures)
                    {
                        Bitmap bitmap = new Bitmap(sourceFile);
                        if (bitmap.Width != 0 && bitmap.Height != 0)
                        {
                            int w = bitmap.Width;
                            int h = bitmap.Height;
                            if (w != h || (w & (w - 1)) != 0 || (h & (h - 1)) != 0)
                            {
                                int larger = w > h ? w : h;
                                if ((larger & (larger - 1)) != 0)
                                {
                                    larger--;
                                    larger |= larger >> 1;
                                    larger |= larger >> 2;
                                    larger |= larger >> 4;
                                    larger |= larger >> 8;
                                    larger |= larger >> 16;
                                    larger++;
                                }

                                Bitmap newBitmap = new Bitmap(bitmap, new Size(larger, larger));
                                newBitmap.Save(destFile, bitmap.RawFormat);

                                newBitmap.Dispose();
                                bitmap.Dispose();

                                doRawCopy = false;
                            }
                        }
                    }

                    if (doRawCopy)
                    {
                        System.IO.File.Copy(sourceFile, destFile, true);
                    }

                    FileAttributes attr = System.IO.File.GetAttributes(destFile);

                    // Remove the ReadOnly flag
                    attr &= ~FileAttributes.ReadOnly;
                    System.IO.File.SetAttributes(destFile, attr);
                }
            }

            return(true);
        }
Exemple #55
0
        private void RefreshTexture(TextureInfo texture)
        {
            Ogmo.GraphicsDevice.SetRenderTarget(texture.Texture);
            Ogmo.GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.Transparent);

            Texture2D tiles = Ogmo.EditorDraw.TilesetTextures[TileLayer.Tileset];
            Ogmo.EditorDraw.SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.Opaque);

            int offsetX = texture.Position.X / TileLayer.Definition.Grid.Width;
            int offsetY = texture.Position.Y / TileLayer.Definition.Grid.Height;
            int tilesWidth = texture.Texture.Width / TileLayer.Definition.Grid.Width;
            int tilesHeight = texture.Texture.Height / TileLayer.Definition.Grid.Height;

            for (int i = 0; i < tilesWidth; i++)
            {
                for (int j = 0; j < tilesHeight; j++)
                {
                    if (TileLayer.Tiles[i + offsetX, j + offsetY] != -1)
                        Ogmo.EditorDraw.SpriteBatch.Draw(
                            tiles,
                            new Microsoft.Xna.Framework.Vector2(i * TileLayer.Definition.Grid.Width, j * TileLayer.Definition.Grid.Height),
                            TileLayer.Tileset.GetXNARectFromID(TileLayer.Tiles[i + offsetX, j + offsetY]),
                            Microsoft.Xna.Framework.Color.White);
                }
            }
            Ogmo.EditorDraw.SpriteBatch.End();

            Ogmo.GraphicsDevice.SetRenderTarget(null);
        }
 public RotateAnimationResolver(TextureInfo textureInfo)
 {
     this.textureInfo = textureInfo;
 }
        /// <summary>
        /// Loads & stores a texture using a color key for transparent pixels.
        /// </summary>
        /// <param name="fileName">File name of the texture to load (relative to the Current Working Directory).</param>
        /// <param name="colorkey">Transparent color (use Color.FromArgb() function )</param>
        /// <returns>The id for the loaded texture, -1 on failure.</returns>
        public int LoadTexture( string fileName, Color colorkey )
        {
            // Verify the filename
            if( string.IsNullOrWhiteSpace( fileName ) )
                return -1;

            // Check if this file has already been loaded (with any color key)
            for( int i = 0; i < m_Textures.Count; i++ )
            {
                TextureInfo info = m_Textures[ i ];

                // Compare filenames, ignoring case
                if( info.fileName.Equals( fileName, StringComparison.OrdinalIgnoreCase ) )
                {
                    info.refCount++;		// increase the reference count
                    m_Textures[ i ] = info;	// store the new value back into the list
                    return i;				// return the index of the existing texture
                }
            }

            // Create the new TextureInfo to use
            TextureInfo tex = new TextureInfo();

            // Copy the filename of the loaded texture.
            tex.fileName = fileName;

            // Attempt to load the texture from file
            try
            {
                tex.texture = TextureLoader.FromFile( m_Device, fileName, 0, 0, 1, Usage.None, Format.Unknown, Pool.Managed, Filter.None, Filter.None, colorkey.ToArgb( ) );
            }
            catch( Exception )
            {
                MessageBox.Show( "Failed to load texture: " + fileName, "ManagedTextureManager::Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
                return -1;
            }

            // AddRef.
            tex.refCount = 1;

            // Get Width & Height of the texture.
            SurfaceDescription d3dSurfDesc = tex.texture.GetSurfaceLevel( 0 ).Description;
            tex.width = d3dSurfDesc.Width;
            tex.height = d3dSurfDesc.Height;

            // Look for an open spot
            int id = -1;
            for( int i = 0; i < m_Textures.Count; i++ )
            {
                if( m_Textures[ i ].refCount == 0 )
                {
                    id = i;
                    break;
                }
            }

            // if we didn't find an open spot, load it into a new one
            if( id == -1 )
            {
                m_Textures.Add( tex );
                id = m_Textures.Count - 1;
            }
            else
            {
                // Make sure the old texture has been disposed
                if( m_Textures[ id ].texture != null )
                    m_Textures[ id ].texture.Dispose( );

                // Overwrite with the new texture
                m_Textures[ id ] = tex;
            }

            // Check if the surface size matches the original image's size
            ImageInformation img = TextureLoader.ImageInformationFromFile( fileName );
            if( tex.width != img.Width || tex.height != img.Height )
            {
                MessageBox.Show( "Image (" + fileName + ") is stretched from "
                                    + img.Width.ToString() + "x"+ img.Height.ToString() + " to "
                                    + tex.width.ToString() + "x" + tex.height.ToString(),
                                    "ManagedTextureManager::Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning );

            }

            // Return the id of the texture.
            return id;
        }
        private void FindTextures(List <Tools.Entry> bundle)
        {
            foreach (Tools.Entry e in bundle)
            {
                if (e.type == 0x82)
                {
                    bool        foundc = false;
                    bool        foundr = false;
                    string      path   = "";
                    Tools.Field chunks = new Tools.Field();
                    Tools.Field res    = new Tools.Field();
                    #region findfields
                    foreach (Tools.Field f in e.fields)
                    {
                        if (f.fieldname == "path")
                        {
                            path = (string)f.data;
                        }
                        else if (f.fieldname == "res")
                        {
                            foundr = true;
                            res    = f;
                            if (foundc)
                            {
                                break;
                            }
                        }
                        else if (f.fieldname == "chunks")
                        {
                            foundc = true;
                            chunks = f;
                            if (foundr)
                            {
                                break;
                            }
                        }
                    }
                    #endregion
                    path += "/";
                    if (foundr && foundc) //contains textures at all
                    {
                        #region gettextures
                        List <Tools.Entry> reslist = (List <Tools.Entry>)res.data;
                        foreach (Tools.Entry e2 in reslist)
                        {
                            if (e2.type == 0x82)
                            {
                                bool foundt = false;
                                foreach (Tools.Field f2 in e2.fields)
                                {
                                    if (f2.fieldname == "resType")
                                    {
                                        if (Tools.GetResType(BitConverter.ToUInt32((byte[])f2.data, 0)) == ".itexture")
                                        {
                                            foundt = true;
                                            break;
                                        }
                                    }
                                }
                                if (foundt) //is a texture
                                {
                                    TextureInfo t = new TextureInfo();
                                    foreach (Tools.Field f2 in e2.fields)
                                    {
                                        switch (f2.fieldname)
                                        {
                                        case "name":
                                            t.path     = (string)f2.data;
                                            t.fullpath = path + t.path;
                                            break;

                                        case "sha1":
                                            t.sha1 = (byte[])f2.data;
                                            break;
                                        }
                                    }
                                    listTex.Add(t);
                                }
                            }
                        }
                        #endregion

                        #region getchunks
                        List <Tools.Entry> chunklist = (List <Tools.Entry>)chunks.data;
                        foreach (Tools.Entry e2 in chunklist)
                        {
                            if (e2.type == 0x82)
                            {
                                ChunkInfo c = new ChunkInfo();
                                foreach (Tools.Field f2 in e2.fields)
                                {
                                    switch (f2.fieldname)
                                    {
                                    case "id":
                                        c.id = (byte[])f2.data;
                                        break;

                                    case "sha1":
                                        c.sha1 = (byte[])f2.data;
                                        break;
                                    }
                                }
                                listChunks.Add(c);
                            }
                        }
                        #endregion
                    }
                }
            }
        }
        public override string Execute(string[] args, UUID fromAgentID)
        {
            // load known texture table
            OSD knownTexturesOsd = null;
            if (File.Exists(mKnownTexturesCacheFile))
            {
                knownTexturesOsd = OSDParser.DeserializeJson(
                    File.ReadAllText(mKnownTexturesCacheFile));

                if (knownTexturesOsd is OSDArray)
                {
                    foreach (OSD osd in (OSDArray)knownTexturesOsd)
                    {
                        TextureInfo ti = new TextureInfo(osd);
                        mKnownTextures[ti.Id] = ti;
                    }
                }
                knownTexturesOsd = null;
            }

            string fileName = "sim.pov";

            if (args.Length > 0)
                fileName = args[args.Length - 1];
            if (!fileName.EndsWith(".pov"))
                fileName += ".pov";

            Logger.Log("dpovray: fileName:" + fileName, Helpers.LogLevel.Debug);

            ulong regionHandle = Client.Network.CurrentSim.Handle;

            bool success = ProcessScene(regionHandle, fileName);

            // load known textures again in case another bot wrote some while we were busy
            // load known texture table
            if (File.Exists(mKnownTexturesCacheFile))
            {
                knownTexturesOsd = OSDParser.DeserializeJson(
                    File.ReadAllText(mKnownTexturesCacheFile));

                if (knownTexturesOsd is OSDArray)
                {
                    foreach (OSD osd in (OSDArray)knownTexturesOsd)
                    {
                        TextureInfo ti = new TextureInfo(osd);
                        mKnownTextures[ti.Id] = ti;
                    }
                }
            }
            // now save our known textuer cache
            OSDArray knownTexturesArr = new OSDArray();
            foreach (KeyValuePair<UUID, TextureInfo> kvp in mKnownTextures)
            {
                if (kvp.Value != null)
                    knownTexturesArr.Add(kvp.Value.GetOsd());
            }
            File.WriteAllText(mKnownTexturesCacheFile, OSDParser.SerializeJsonString(knownTexturesArr));

            if (success)
                return "exported sim to file: " + fileName;

            return "error exporting sim to file: " + fileName;
        }
        public static void OnGUI(HLOD hlod, bool isFirst)
        {
            if (isFirst)
            {
                inputTexturePropertyNames  = null;
                outputTexturePropertyNames = null;
            }

            EditorGUI.indentLevel += 1;
            dynamic batcherOptions = hlod.BatcherOptions;

            if (batcherOptions.PackTextureSize == null)
            {
                batcherOptions.PackTextureSize = 1024;
            }
            if (batcherOptions.LimitTextureSize == null)
            {
                batcherOptions.LimitTextureSize = 128;
            }
            if (batcherOptions.MaterialGUID == null)
            {
                batcherOptions.MaterialGUID = "";
            }
            if (batcherOptions.TextureInfoList == null)
            {
                batcherOptions.TextureInfoList = new List <TextureInfo>();
                batcherOptions.TextureInfoList.Add(new TextureInfo()
                {
                    InputName  = "_MainTex",
                    OutputName = "_MainTex",
                    Type       = PackingType.White
                });
            }

            if (batcherOptions.EnableTintColor == null)
            {
                batcherOptions.EnableTintColor = false;
            }
            if (batcherOptions.TintColorName == null)
            {
                batcherOptions.TintColorName = "";
            }

            batcherOptions.PackTextureSize  = EditorGUILayout.IntPopup("Pack texture size", batcherOptions.PackTextureSize, Styles.PackTextureSizeNames, Styles.PackTextureSizes);
            batcherOptions.LimitTextureSize = EditorGUILayout.IntPopup("Limit texture size", batcherOptions.LimitTextureSize, Styles.LimitTextureSizeNames, Styles.LimitTextureSizes);

            Material mat = null;

            string matGUID = batcherOptions.MaterialGUID;
            string path    = "";

            if (string.IsNullOrEmpty(matGUID) == false)
            {
                path = AssetDatabase.GUIDToAssetPath(matGUID);
                mat  = AssetDatabase.LoadAssetAtPath <Material>(path);
            }
            mat = EditorGUILayout.ObjectField("Material", mat, typeof(Material), false) as Material;
            if (mat == null)
            {
                mat = new Material(Shader.Find("Standard"));
            }

            path    = AssetDatabase.GetAssetPath(mat);
            matGUID = AssetDatabase.AssetPathToGUID(path);


            if (matGUID != batcherOptions.MaterialGUID)
            {
                batcherOptions.MaterialGUID = matGUID;
                outputTexturePropertyNames  = mat.GetTexturePropertyNames();
            }
            if (inputTexturePropertyNames == null)
            {
                inputTexturePropertyNames = GetAllMaterialTextureProperties(hlod.gameObject);
            }
            if (outputTexturePropertyNames == null)
            {
                outputTexturePropertyNames = mat.GetTexturePropertyNames();
            }

            //apply tint color
            batcherOptions.EnableTintColor =
                EditorGUILayout.Toggle("Enable tint color", batcherOptions.EnableTintColor);
            if (batcherOptions.EnableTintColor == true)
            {
                EditorGUI.indentLevel += 1;

                var           shader             = mat.shader;
                List <string> colorPropertyNames = new List <string>();
                int           propertyCount      = ShaderUtil.GetPropertyCount(shader);
                for (int i = 0; i < propertyCount; ++i)
                {
                    string name = ShaderUtil.GetPropertyName(shader, i);
                    if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.Color)
                    {
                        colorPropertyNames.Add(name);
                    }
                }

                int index = colorPropertyNames.IndexOf(batcherOptions.TintColorName);
                index = EditorGUILayout.Popup("Tint color property", index, colorPropertyNames.ToArray());
                if (index >= 0)
                {
                    batcherOptions.TintColorName = colorPropertyNames[index];
                }
                else
                {
                    batcherOptions.TintColorName = "";
                }

                EditorGUI.indentLevel -= 1;
            }

            //ext textures
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Textures");
            EditorGUI.indentLevel += 1;
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel(" ");
            //EditorGUILayout.LabelField();
            EditorGUILayout.SelectableLabel("Input");
            EditorGUILayout.SelectableLabel("Output");
            EditorGUILayout.SelectableLabel("Type");
            EditorGUILayout.EndHorizontal();

            for (int i = 0; i < batcherOptions.TextureInfoList.Count; ++i)
            {
                TextureInfo info = batcherOptions.TextureInfoList[i];
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.PrefixLabel(" ");

                info.InputName  = StringPopup(info.InputName, inputTexturePropertyNames);
                info.OutputName = StringPopup(info.OutputName, outputTexturePropertyNames);
                info.Type       = (PackingType)EditorGUILayout.EnumPopup(info.Type);

                if (i == 0)
                {
                    GUI.enabled = false;
                }
                if (GUILayout.Button("x") == true)
                {
                    batcherOptions.TextureInfoList.RemoveAt(i);
                    i -= 1;
                }
                if (i == 0)
                {
                    GUI.enabled = true;
                }
                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel(" ");
            if (GUILayout.Button("Add new texture property") == true)
            {
                batcherOptions.TextureInfoList.Add(new TextureInfo());
            }

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel(" ");
            if (GUILayout.Button("Update texture properties"))
            {
                //TODO: Need update automatically
                inputTexturePropertyNames  = null;
                outputTexturePropertyNames = null;
            }
            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel -= 1;
            EditorGUI.indentLevel -= 1;
        }