Inheritance: QMonoBehaviour
コード例 #1
0
ファイル: AssetBaseTest.cs プロジェクト: ChrisD/opensim
 private void CheckContainsReferences(AssetType assetType, bool expected)
 {
     AssetBase asset = new AssetBase();
     asset.Type = (sbyte)assetType;
     bool actual = asset.ContainsReferences;
     Assert.AreEqual(expected, actual, "Expected "+assetType+".ContainsReferences to be "+expected+" but was "+actual+".");
 }
コード例 #2
0
 public bool StoreAsset(AssetBase asset)
 {
     try
     {
         if (asset.Name.Length > 64)
             asset.Name = asset.Name.Substring(0, 64);
         if (asset.Description.Length > 128)
             asset.Description = asset.Description.Substring(0, 128);
         if (ExistsAsset(asset.ID))
         {
             AssetBase oldAsset = GetAsset(asset.ID);
             if (oldAsset == null || (oldAsset.Flags & AssetFlags.Rewritable) == AssetFlags.Rewritable)
             {
                 MainConsole.Instance.Debug("[LocalAssetDatabase]: Asset already exists in the db, overwriting - " + asset.ID);
                 Delete(asset.ID, true);
                 InsertAsset(asset, asset.ID);
             }
             else
             {
                 MainConsole.Instance.Warn("[LocalAssetDatabase]: Asset already exists in the db, fixing ID... - " + asset.ID);
                 InsertAsset(asset, UUID.Random());
             }
         }
         else
         {
             InsertAsset(asset, asset.ID);
         }
     }
     catch (Exception e)
     {
         MainConsole.Instance.ErrorFormat("[LocalAssetDatabase]: Failure creating asset {0} with name \"{1}\". Error: {2}",
                           asset.ID, asset.Name, e);
     }
     return true;
 }
コード例 #3
0
        public LLUUID AddToInventory(LLUUID folderID, AssetBase asset)
        {
            if (this.InventoryFolders.ContainsKey(folderID))
            {
                LLUUID NewItemID = LLUUID.Random();

                InventoryItem Item = new InventoryItem();
                Item.FolderID = folderID;
                Item.OwnerID = AgentID;
                Item.AssetID = asset.FullID;
                Item.ItemID = NewItemID;
                Item.Type = asset.Type;
                Item.Name = asset.Name;
                Item.Description = asset.Description;
                Item.InvType = asset.InvType;
                this.InventoryItems.Add(Item.ItemID, Item);
                InventoryFolder Folder = InventoryFolders[Item.FolderID];
                Folder.Items.Add(Item);
                return (Item.ItemID);
            }
            else
            {
                return (null);
            }
        }
コード例 #4
0
        protected static void LoadAsset(AssetBase info, string path)
        {
//            bool image =
//               (info.Type == (sbyte)AssetType.Texture ||
//                info.Type == (sbyte)AssetType.TextureTGA ||
//                info.Type == (sbyte)AssetType.ImageJPEG ||
//                info.Type == (sbyte)AssetType.ImageTGA);

            FileInfo fInfo = new FileInfo(path);
            long numBytes = fInfo.Length;
            if (fInfo.Exists)
            {
                FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                byte[] idata = new byte[numBytes];
                BinaryReader br = new BinaryReader(fStream);
                idata = br.ReadBytes((int)numBytes);
                br.Close();
                fStream.Close();
                info.Data = idata;
                //info.loaded=true;
            }
            else
            {
                m_log.ErrorFormat("[ASSETS]: file: [{0}] not found !", path);
            }
        }
コード例 #5
0
 public void AddUpload(LLUUID transactionID, AssetBase asset)
 {
     AssetTransaction upload = new AssetTransaction();
     lock (this.transactions)
     {
         upload.Asset = asset;
         upload.TransactionID = transactionID;
         this.transactions.Add(transactionID, upload);
     }
     if (upload.Asset.Data.Length > 2)
     {
         //is complete
         upload.UploadComplete = true;
         AssetUploadCompletePacket response = new AssetUploadCompletePacket();
         response.AssetBlock.Type = asset.Type;
         response.AssetBlock.Success = true;
         response.AssetBlock.UUID = transactionID.Combine(this.ourClient.SecureSessionID);
         this.ourClient.OutPacket(response);
         m_assetCache.AddAsset(asset);
     }
     else
     {
         upload.UploadComplete = false;
         upload.XferID = Util.GetNextXferID();
         RequestXferPacket xfer = new RequestXferPacket();
         xfer.XferID.ID = upload.XferID;
         xfer.XferID.VFileType = upload.Asset.Type;
         xfer.XferID.VFileID = transactionID.Combine(this.ourClient.SecureSessionID);
         xfer.XferID.FilePath = 0;
         xfer.XferID.Filename = new byte[0];
         this.ourClient.OutPacket(xfer);
     }
 }
コード例 #6
0
ファイル: Graphics.cs プロジェクト: KSLcom/Aurora-Sim
        public UUID SaveBitmap(Bitmap data, bool lossless, bool temporary)
        {
            AssetBase asset = new AssetBase(UUID.Random(), "MRMDynamicImage", AssetType.Texture,
                                            m_scene.RegionInfo.RegionID)
                                  {
                                      Data = OpenJPEG.EncodeFromImage(data, lossless),
                                      Description = "MRM Image",
                                      Flags = (temporary) ? AssetFlags.Temporary : 0
                                  };
            asset.ID = m_scene.AssetService.Store(asset);

            return asset.ID;
        }
コード例 #7
0
ファイル: AssetComposite.cs プロジェクト: cg123/xenko
        /// <summary>
        /// Adds the given <see cref="AssetBase"/> to the <see cref="Asset.BaseParts"/> collection of this asset.
        /// </summary>
        /// <remarks>If the <see cref="Asset.BaseParts"/> collection already contains the argument. this method does nothing.</remarks>
        /// <param name="newBasePart">The base to add to the <see cref="Asset.BaseParts"/> collection.</param>
        public void AddBasePart(AssetBase newBasePart)
        {
            if (newBasePart == null) throw new ArgumentNullException(nameof(newBasePart));

            if (BaseParts == null)
            {
                BaseParts = new List<AssetBase>();
            }

            if (BaseParts.All(x => x.Id != newBasePart.Id))
            {
                BaseParts.Add(newBasePart);
            }
        }
コード例 #8
0
        protected static AssetBase CreateAsset(string assetIdStr, string name, string path, sbyte type)
        {
            AssetBase asset = new AssetBase(new UUID(assetIdStr), name, type, LIBRARY_OWNER_ID.ToString());

            if (!String.IsNullOrEmpty(path))
            {
                //m_log.InfoFormat("[ASSETS]: Loading: [{0}][{1}]", name, path);

                LoadAsset(asset, path);
            }
            else
            {
                m_log.InfoFormat("[ASSETS]: Instantiated: [{0}]", name);
            }

            return asset;
        }
コード例 #9
0
ファイル: FileAssetClient.cs プロジェクト: ChrisD/opensim
        public override void StoreAsset(AssetBase asset)
        {
            byte[] idBytes = asset.FullID.Guid.ToByteArray();

            string cdir = m_dir + Path.DirectorySeparatorChar + idBytes[0]
                                + Path.DirectorySeparatorChar + idBytes[1];

            if (!Directory.Exists(m_dir + Path.DirectorySeparatorChar + idBytes[0]))
                Directory.CreateDirectory(m_dir + Path.DirectorySeparatorChar + idBytes[0]);

            if (!Directory.Exists(cdir))
                Directory.CreateDirectory(cdir);

            FileStream x = new FileStream(cdir + Path.DirectorySeparatorChar + asset.FullID + ".xml", FileMode.Create);
            m_xs.Serialize(x, asset);

            x.Flush();
            x.Close();
        }
コード例 #10
0
        protected static AssetBase CreateAsset(string assetIdStr, string name, string path, bool isImage)
        {
            AssetBase asset = new AssetBase(
                new UUID(assetIdStr),
                name
                );

            if (!String.IsNullOrEmpty(path))
            {
                //m_log.InfoFormat("[ASSETS]: Loading: [{0}][{1}]", name, path);

                LoadAsset(asset, isImage, path);
            }
            else
            {
                m_log.InfoFormat("[ASSETS]: Instantiated: [{0}]", name);
            }

            return asset;
        }
コード例 #11
0
        private bool ProcessMergeAssetItem(AssetItem assetItem, HashSet<Guid> beingProcessed)
        {
            if (beingProcessed.Contains(assetItem.Id))
            {
                log.Error(package, assetItem.Asset.Base, AssetMessageCode.AssetNotFound, assetItem.Asset.Base);
                return false;
            }
            beingProcessed.Add(assetItem.Id);

            AssetItem existingAssetBase = null;
            List<AssetBase> existingBaseParts = null;

            // Process asset base
            if (assetItem.Asset.Base != null)
            {
                if (!ProcessMergeAssetBase(assetItem.Asset.Base, beingProcessed, out existingAssetBase))
                {
                    return false;
                }
            }

            // Process asset base parts
            if (assetItem.Asset.BaseParts != null && assetItem.Asset.BaseParts.Count > 0)
            {
                existingBaseParts = new List<AssetBase>();

                foreach (var basePart in assetItem.Asset.BaseParts)
                {
                    AssetItem existingAssetBasePart;
                    if (!ProcessMergeAssetBase(basePart, beingProcessed, out existingAssetBasePart))
                    {
                        return false;
                    }

                    // Replicate the group with the list of ids
                    var newBasePart =new AssetBase(existingAssetBasePart.Location, (Asset)AssetCloner.Clone(existingAssetBasePart.Asset));
                     
                    existingBaseParts.Add(newBasePart);
                }
            }

            // For simple merge (base, newAsset, newBase) => newObject
            // For multi-part prefabs merge (base, newAsset, newBase) + baseParts + newBaseParts => newObject
            if (!MergeAsset(assetItem, existingAssetBase, existingBaseParts))
            {
                return false;
            }

            assetsProcessed.Add(assetItem.Id, assetItem);
            assetsToProcess.Remove(assetItem.Id);

            return true;
        }
コード例 #12
0
 public virtual string Store(AssetBase asset)
 {
     return(Store(asset, false));
 }
コード例 #13
0
ファイル: Backup.cs プロジェクト: TagsRocks/Aurora-Sim
            public void LoadModuleFromArchive(byte[] data, string filePath, TarArchiveReader.TarEntryType type,
                                              IScene scene)
            {
                if (filePath.StartsWith("parcels/"))
                {
                    if (!m_merge)
                    {
                        //Only use if we are not merging
                        LandData parcel     = new LandData();
                        OSD      parcelData = OSDParser.DeserializeLLSDBinary(data);
                        parcel.FromOSD((OSDMap)parcelData);
                        m_parcels.Add(parcel);
                    }
                }
                #region New Style Terrain Loading

                else if (filePath.StartsWith("newstyleterrain/"))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule>();
                    terrainModule.TerrainMap = ReadTerrain(data, scene);
                }
                else if (filePath.StartsWith("newstylerevertterrain/"))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule>();
                    terrainModule.TerrainRevertMap = ReadTerrain(data, scene);
                }
                else if (filePath.StartsWith("newstylewater/"))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule>();
                    terrainModule.TerrainWaterMap = ReadTerrain(data, scene);
                }
                else if (filePath.StartsWith("newstylerevertwater/"))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule>();
                    terrainModule.TerrainWaterRevertMap = ReadTerrain(data, scene);
                }
                #endregion
                #region Old Style Terrain Loading

                else if (filePath.StartsWith("terrain/"))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule>();

                    MemoryStream ms = new MemoryStream(data);
                    terrainModule.LoadFromStream(filePath, ms, 0, 0);
                    ms.Close();
                }
                else if (filePath.StartsWith("revertterrain/"))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule>();

                    MemoryStream ms = new MemoryStream(data);
                    terrainModule.LoadRevertMapFromStream(filePath, ms, 0, 0);
                    ms.Close();
                }
                else if (filePath.StartsWith("water/"))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule>();

                    MemoryStream ms = new MemoryStream(data);
                    terrainModule.LoadWaterFromStream(filePath, ms, 0, 0);
                    ms.Close();
                }
                else if (filePath.StartsWith("revertwater/"))
                {
                    ITerrainModule terrainModule = scene.RequestModuleInterface <ITerrainModule>();

                    MemoryStream ms = new MemoryStream(data);
                    terrainModule.LoadWaterRevertMapFromStream(filePath, ms, 0, 0);
                    ms.Close();
                }
                #endregion

                else if (filePath.StartsWith("entities/"))
                {
                    MemoryStream ms          = new MemoryStream(data);
                    ISceneEntity sceneObject = SceneEntitySerializer.SceneObjectSerializer.FromXml2Format(ref ms, scene);
                    ms.Close();
                    ms   = null;
                    data = null;
                    m_groups.Add(sceneObject);
                }
                else if (filePath.StartsWith("assets/"))
                {
                    if (m_loadAssets)
                    {
                        AssetBase asset = new AssetBase();
                        asset.Unpack(OSDParser.DeserializeJson(Encoding.UTF8.GetString(data)));
                        scene.AssetService.Store(asset);
                    }
                }
            }
コード例 #14
0
        /// <summary>
        ///     Builds a composited terrain texture given the region texture
        ///     and heightmap settings
        /// </summary>
        /// <param name="heightmap">Terrain heightmap</param>
        /// <param name="textureIDs"></param>
        /// <param name="startHeights"></param>
        /// <param name="heightRanges"></param>
        /// <param name="regionPosition"></param>
        /// <param name="assetService"></param>
        /// <param name="textureTerrain"></param>
        /// <returns>A composited 256x256 RGB texture ready for rendering</returns>
        /// <remarks>
        ///     Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
        /// </remarks>
        public static Bitmap Splat(ITerrainChannel heightmap, UUID[] textureIDs, float[] startHeights,
                                   float[] heightRanges, Vector3d regionPosition, IAssetService assetService,
                                   bool textureTerrain)
        {
            Debug.Assert(textureIDs.Length == 4);
            Debug.Assert(startHeights.Length == 4);
            Debug.Assert(heightRanges.Length == 4);

            Bitmap[] detailTexture = new Bitmap[4];

            if (textureTerrain)
            {
                // Swap empty terrain textureIDs with default IDs
                for (int i = 0; i < textureIDs.Length; i++)
                {
                    if (textureIDs[i] == UUID.Zero)
                    {
                        textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
                    }
                }

                #region Texture Fetching

                if (assetService != null)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        UUID      cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]);
                        AssetBase asset   = assetService.Get(cacheID.ToString());
                        if ((asset != null) && (asset.Data != null) && (asset.Data.Length != 0))
                        {
                            try
                            {
                                using (MemoryStream stream = new MemoryStream(asset.Data))
                                    detailTexture[i] = (Bitmap)Image.FromStream(stream);
                            }
                            catch (Exception ex)
                            {
                                MainConsole.Instance.Warn("Failed to decode cached terrain texture " + cacheID +
                                                          " (textureID: " + textureIDs[i] + "): " + ex.Message);
                            }
                        }

                        if (detailTexture[i] == null)
                        {
                            // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
                            byte[] assetData = assetService.GetData(textureIDs[i].ToString());
                            if (asset != null)
                            {
                                try
                                {
                                    detailTexture[i] = (Bitmap)J2kImage.FromBytes(assetData);
                                }
                                catch (Exception ex)
                                {
                                    MainConsole.Instance.Warn("Failed to decode terrain texture " + asset.ID + ": " +
                                                              ex.Message);
                                }
                            }

                            if (detailTexture[i] != null)
                            {
                                Bitmap bitmap = detailTexture[i];

                                // Make sure this texture is the correct size, otherwise resize
                                if (bitmap.Width != 256 || bitmap.Height != 256)
                                {
                                    bitmap = ImageUtils.ResizeImage(bitmap, 256, 256);
                                }

                                // Save the decoded and resized texture to the cache
                                byte[] data;
                                using (MemoryStream stream = new MemoryStream())
                                {
                                    bitmap.Save(stream, ImageFormat.Png);
                                    data = stream.ToArray();
                                }

                                // Cache a PNG copy of this terrain texture
                                AssetBase newAsset = new AssetBase
                                {
                                    Data        = data,
                                    Description = "PNG",
                                    Flags       =
                                        AssetFlags.Collectable | AssetFlags.Temporary |
                                        AssetFlags.Local,
                                    ID         = cacheID,
                                    Name       = String.Empty,
                                    TypeString = "image/png"
                                };
                                newAsset.ID = assetService.Store(newAsset);
                            }
                        }
                    }
                }

                #endregion Texture Fetching
            }

            // Fill in any missing textures with a solid color
            for (int i = 0; i < 4; i++)
            {
                if (detailTexture[i] == null)
                {
                    // Create a solid color texture for this layer
                    detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
                    using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
                    {
                        using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
                            gfx.FillRectangle(brush, 0, 0, 256, 256);
                    }
                }
                else if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256)
                {
                    detailTexture[i] = ResizeBitmap(detailTexture[i], 256, 256);
                }
            }

            #region Layer Map

            float   diff     = (float)heightmap.Height / (float)Constants.RegionSize;
            float[] layermap = new float[Constants.RegionSize * Constants.RegionSize];

            for (float y = 0; y < heightmap.Height; y += diff)
            {
                for (float x = 0; x < heightmap.Height; x += diff)
                {
                    float newX   = x / diff;
                    float newY   = y / diff;
                    float height = heightmap[(int)newX, (int)newY];

                    float pctX = newX / 255f;
                    float pctY = newY / 255f;

                    // Use bilinear interpolation between the four corners of start height and
                    // height range to select the current values at this position
                    float startHeight = ImageUtils.Bilinear(
                        startHeights[0],
                        startHeights[2],
                        startHeights[1],
                        startHeights[3],
                        pctX, pctY);
                    startHeight = Utils.Clamp(startHeight, 0f, 255f);

                    float heightRange = ImageUtils.Bilinear(
                        heightRanges[0],
                        heightRanges[2],
                        heightRanges[1],
                        heightRanges[3],
                        pctX, pctY);
                    heightRange = Utils.Clamp(heightRange, 0f, 255f);

                    // Generate two frequencies of perlin noise based on our global position
                    // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
                    Vector3 vec = new Vector3
                                  (
                        ((float)regionPosition.X + newX) * 0.20319f,
                        ((float)regionPosition.Y + newY) * 0.20319f,
                        height * 0.25f
                                  );

                    float lowFreq  = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f;
                    float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f;
                    float noise    = (lowFreq + highFreq) * 2f;

                    // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
                    float layer = ((height + noise - startHeight) / heightRange) * 4f;
                    if (Single.IsNaN(layer))
                    {
                        layer = 0f;
                    }
                    layermap[(int)(newY * Constants.RegionSize + newX)] = Utils.Clamp(layer, 0f, 3f);
                }
            }

            #endregion Layer Map

            #region Texture Compositing

            Bitmap     output     = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
            BitmapData outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly,
                                                    PixelFormat.Format24bppRgb);

            unsafe
            {
                // Get handles to all of the texture data arrays
                BitmapData[] datas = new[]
                {
                    detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256),
                                              ImageLockMode.ReadOnly,
                                              detailTexture[0].PixelFormat),
                    detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256),
                                              ImageLockMode.ReadOnly,
                                              detailTexture[1].PixelFormat),
                    detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256),
                                              ImageLockMode.ReadOnly,
                                              detailTexture[2].PixelFormat),
                    detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256),
                                              ImageLockMode.ReadOnly,
                                              detailTexture[3].PixelFormat)
                };

                int[] comps = new[]
                {
                    (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
                    (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
                    (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
                    (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
                };

                for (int y = 0; y < Constants.RegionSize; y++)
                {
                    for (int x = 0; x < Constants.RegionSize; x++)
                    {
                        float layer = layermap[y * Constants.RegionSize + x];

                        // Select two textures
                        int l0 = (int)Math.Floor(layer);
                        int l1 = Math.Min(l0 + 1, 3);

                        byte *ptrA = (byte *)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0];
                        byte *ptrB = (byte *)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1];
                        byte *ptrO = (byte *)outputData.Scan0 + y * outputData.Stride + x * 3;

                        float aB = *(ptrA + 0);
                        float aG = *(ptrA + 1);
                        float aR = *(ptrA + 2);

                        float bB = *(ptrB + 0);
                        float bG = *(ptrB + 1);
                        float bR = *(ptrB + 2);

                        float layerDiff = layer - l0;

                        // Interpolate between the two selected textures
                        *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB));
                        *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG));
                        *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR));
                    }
                }

                for (int i = 0; i < 4; i++)
                {
                    detailTexture[i].UnlockBits(datas[i]);
                    detailTexture[i].Dispose();
                }
            }

            layermap = null;
            output.UnlockBits(outputData);

            // We generated the texture upside down, so flip it
            output.RotateFlip(RotateFlipType.RotateNoneFlipY);

            #endregion Texture Compositing

            return(output);
        }
コード例 #15
0
        public string Store(AssetBase asset)
        {
            //m_log.DebugFormat("[ASSET SERVICE]: Store asset {0} {1}", asset.Name, asset.ID);
            m_Database.StoreAsset(asset);

            return asset.ID;
        }
コード例 #16
0
        ///
        /// UpdateInventoryItemAsset
        ///
        public override bool UpdateInventoryItemAsset(UUID ownerID, InventoryItemBase item, AssetBase asset)
        {
            if (base.UpdateInventoryItemAsset(ownerID, item, asset))
            {
                PostInventoryAsset(item, 0);
                return(true);
            }

            return(false);
        }
コード例 #17
0
        public void Import(string conn, string table, int start, int count, bool force, FSStoreDelegate store)
        {
            MySqlConnection importConn;

            try
            {
                importConn = new MySqlConnection(conn);

                importConn.Open();
            }
            catch (MySqlException e)
            {
                m_log.ErrorFormat("[FSASSETS]: Can't connect to database: {0}",
                                  e.Message.ToString());

                return;
            }

            int imported = 0;

            MySqlCommand cmd = importConn.CreateCommand();

            string limit = String.Empty;

            if (count != -1)
            {
                limit = String.Format(" limit {0},{1}", start, count);
            }

            cmd.CommandText = String.Format("select * from {0}{1}", table, limit);

            MainConsole.Instance.Output("Querying database");
            IDataReader reader = cmd.ExecuteReader();

            MainConsole.Instance.Output("Reading data");

            while (reader.Read())
            {
                if ((imported % 100) == 0)
                {
                    MainConsole.Instance.Output(String.Format("{0} assets imported so far", imported));
                }

                AssetBase     asset = new AssetBase();
                AssetMetadata meta  = new AssetMetadata();

                meta.ID     = reader["id"].ToString();
                meta.FullID = new UUID(meta.ID);

                meta.Name         = reader["name"].ToString();
                meta.Description  = reader["description"].ToString();
                meta.Type         = (sbyte)Convert.ToInt32(reader["assetType"]);
                meta.ContentType  = SLUtil.SLAssetTypeToContentType(meta.Type);
                meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"]));

                asset.Metadata = meta;
                asset.Data     = (byte[])reader["data"];

                store(asset, force);

                imported++;
            }

            reader.Close();
            cmd.Dispose();
            importConn.Close();

            MainConsole.Instance.Output(String.Format("Import done, {0} assets imported", imported));
        }
コード例 #18
0
        private void Awake()
        {
            if (loaded)
            {
                Destroy(gameObject);
            }

            if (loadedPrefabs == null)
            {
                string path = KSPUtil.ApplicationRootPath + "GameData/SurfaceExperimentPackage/Resources";

                AssetBundle prefabs = AssetBundle.LoadFromFile(path + "/sep_prefab");

                if (prefabs != null)
                {
                    loadedPrefabs = prefabs.LoadAllAssets <GameObject>();
                }
            }

            if (loadedPrefabs != null)
            {
                if (!TMPLoaded)
                {
                    processTMPPrefabs();
                }

                if (UISkinManager.defaultSkin != null && !UILoaded)
                {
                    if (sliderFrontForeground == null || sliderBackBackground == null || sliderBackForeground == null)
                    {
                        ExperimentsResultDialog scienceDialogPrefab = UnityEngine.Object.Instantiate <GameObject>(AssetBase.GetPrefab("ScienceResultsDialog")).GetComponent <ExperimentsResultDialog>();

                        if (scienceDialogPrefab != null)
                        {
                            Slider[] sliders = scienceDialogPrefab.GetComponentsInChildren <Slider>();;

                            Slider backSlider  = sliders[0];
                            Slider frontSlider = sliders[1];

                            sliderBackBackground = processSliderSprites(backSlider, true, ref sliderBackBackColor);
                            sliderBackForeground = processSliderSprites(backSlider, false, ref sliderBackForeColor);

                            sliderFrontForeground = processSliderSprites(frontSlider, false, ref sliderFrontForeColor);
                        }
                    }

                    processUIPrefabs();
                }
            }

            if (TMPLoaded && UILoaded)
            {
                loaded = true;
            }

            Destroy(gameObject);
        }
コード例 #19
0
        /// <summary>
        ///     Load an asset
        /// </summary>
        /// <param name="assetPath"> </param>
        /// <param name="data"></param>
        /// <returns>true if asset was successfully loaded, false otherwise</returns>
        bool LoadAsset(string assetPath, byte [] data)
        {
            //IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>();
            // Right now we're nastily obtaining the UUID from the filename
            string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);

            int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR, StringComparison.Ordinal);

            if (i == -1)
            {
                MainConsole.Instance.ErrorFormat(
                    "[Inventory Archiver]: Could not find extension information in asset path {0} since it's missing the separator {1}.  Skipping",
                    assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR);

                return(false);
            }

            string extension = filename.Substring(i);
            string uuid      = filename.Remove(filename.Length - extension.Length);
            UUID   assetID   = UUID.Parse(uuid);

            if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension))
            {
                AssetType assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE [extension];

                if (assetType == AssetType.Unknown)
                {
                    MainConsole.Instance.WarnFormat(
                        "[Inventory Archiver]: Importing {0} byte asset {1} with unknown type", data.Length,
                        uuid);
                }
                else if (assetType == AssetType.Object)
                {
                    string       xmlData     = Utils.BytesToString(data);
                    ISceneEntity sceneObject = SceneEntitySerializer.SceneObjectSerializer.FromOriginalXmlFormat(
                        xmlData, m_registry);
                    if (sceneObject != null)
                    {
                        if (m_creatorIdForAssetId.ContainsKey(assetID))
                        {
                            foreach (
                                ISceneChildEntity sop in
                                from sop in sceneObject.ChildrenEntities()
                                where string.IsNullOrEmpty(sop.CreatorData)
                                select sop)
                            {
                                sop.CreatorID = m_creatorIdForAssetId [assetID];
                            }
                        }

                        foreach (ISceneChildEntity sop in sceneObject.ChildrenEntities())
                        {
                            //Fix ownerIDs and perms
                            sop.Inventory.ApplyGodPermissions((uint)PermissionMask.All);
                            sceneObject.ApplyPermissions((uint)PermissionMask.All);
                            foreach (TaskInventoryItem item in sop.Inventory.GetInventoryItems())
                            {
                                item.OwnerID = m_userInfo.PrincipalID;
                            }
                            sop.OwnerID = m_userInfo.PrincipalID;
                        }

                        data =
                            Utils.StringToBytes(
                                SceneEntitySerializer.SceneObjectSerializer.ToOriginalXmlFormat(sceneObject));
                    }
                }
                //MainConsole.Instance.DebugFormat("[Inventory Archiver]: Importing asset {0}, type {1}", uuid, assetType);

                AssetBase asset = new AssetBase(assetID, "From IAR", assetType, m_overridecreator)
                {
                    Data  = data,
                    Flags = AssetFlags.Normal
                };

                if (m_assetData != null && ReplaceAssets)
                {
                    m_assetData.Delete(asset.ID, true);
                }

                // check if this asset already exists in the database
                try {
                    if (!m_assetService.GetExists(asset.ID.ToString()))
                    {
                        m_assetService.Store(asset);
                    }
                } catch {
                    MainConsole.Instance.Error(
                        "[Inventory Archiver]: Error checking if asset exists. Possibly 'Path too long' for file based asset storage");
                }
                asset.Dispose();
                return(true);
            }
            MainConsole.Instance.ErrorFormat(
                "[Inventory Archiver]: Tried to dearchive data with path {0} with an unknown type extension {1}",
                assetPath, extension);

            return(false);
        }
コード例 #20
0
        private Color4 GetFaceColor(Primitive.TextureEntryFace face)
        {
            Color4 color;

            if (face.TextureID == UUID.Zero)
            {
                return(face.RGBA);
            }

            if (!m_colors.TryGetValue(face.TextureID, out color))
            {
                bool fetched = false;

                // Attempt to fetch the texture metadata
                UUID      metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
                AssetBase metadata   = m_scene.AssetService.GetCached(metadataID.ToString());
                if (metadata != null)
                {
                    OSDMap map = null;
                    try
                    {
                        map = OSDParser.Deserialize(metadata.Data) as OSDMap;
                    }
                    catch
                    {
                    }

                    if (map != null)
                    {
                        color = map["X-JPEG2000-RGBA"].AsColor4();
                        if (!(color.R == 0.5f && color.G == 0.5f && color.B == 0.5f && color.A == 1.0f))
                        {
                            //If we failed, don't save it
                            fetched = true;
                        }
                    }
                    map      = null;
                    metadata = null;
                }

                if (!fetched)
                {
                    // Fetch the texture, decode and get the average color,
                    // then save it to a temporary metadata asset
                    AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
                    if (textureAsset != null)
                    {
                        int width, height;
                        color = GetAverageColor(textureAsset.ID, textureAsset.Data, m_scene, out width, out height);
                        if (!(color.R == 0.5f && color.G == 0.5f && color.B == 0.5f && color.A == 1.0f))
                        //If we failed, don't save it
                        {
                            OSDMap data = new OSDMap {
                                { "X-JPEG2000-RGBA", OSD.FromColor4(color) }
                            };
                            metadata = new AssetBase
                            {
                                Data        = Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
                                Description = "Avg Color-JPEG2000 texture " + face.TextureID.ToString(),
                                Flags       = AssetFlags.Collectable | AssetFlags.Temperary | AssetFlags.Local,
                                ID          = metadataID,
                                Name        = String.Empty,
                                TypeAsset   = AssetType.Simstate
                                              // Make something up to get around OpenSim's myopic treatment of assets
                            };
                            metadata.ID = m_scene.AssetService.Store(metadata);
                        }
                        textureAsset = null;
                    }
                    else
                    {
                        color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
                    }
                }

                m_colors[face.TextureID] = color;
            }

            return(color * face.RGBA);
        }
コード例 #21
0
        private void CreatePrim(WarpRenderer renderer, ISceneChildEntity prim)
        {
            try
            {
                const float MIN_SIZE = 2f;

                if ((PCode)prim.Shape.PCode != PCode.Prim)
                {
                    return;
                }
                if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
                {
                    return;
                }

                Primitive   omvPrim    = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
                FacetedMesh renderMesh = null;

                // Are we dealing with a sculptie or mesh?
                if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
                {
                    // Try fetchinng the asset
                    AssetBase sculptAsset = m_scene.AssetService.Get(omvPrim.Sculpt.SculptTexture.ToString());
                    if (sculptAsset != null)
                    {
                        // Is it a mesh?
                        if (omvPrim.Sculpt.Type == SculptType.Mesh)
                        {
                            AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset.Data);
                            FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
                        }
                        else // It's sculptie
                        {
                            IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder>();
                            Image       sculpt     = imgDecoder.DecodeToImage(sculptAsset.Data);
                            if (sculpt != null)
                            {
                                renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
                                                                                    DetailLevel.Medium);
                                sculpt.Dispose();
                            }
                        }
                    }
                }
                else // Prim
                {
                    renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
                }

                if (renderMesh == null)
                {
                    return;
                }

                warp_Vector     primPos = ConvertVector(prim.GetWorldPosition());
                warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);

                warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);

                if (prim.ParentID != 0)
                {
                    ISceneEntity group = m_scene.GetGroupByPrim(prim.LocalId);
                    if (group != null)
                    {
                        m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootChild.RotationOffset)));
                    }
                }

                warp_Vector primScale = ConvertVector(prim.Scale);

                string primID = prim.UUID.ToString();

                // Create the prim faces
                for (int i = 0; i < renderMesh.Faces.Count; i++)
                {
                    Face   face     = renderMesh.Faces[i];
                    string meshName = primID + "-Face-" + i.ToString();

                    warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);

                    foreach (Vertex v in face.Vertices)
                    {
                        warp_Vector pos  = ConvertVector(v.Position);
                        warp_Vector norm = ConvertVector(v.Normal);

                        if (prim.Shape.SculptTexture == UUID.Zero)
                        {
                            norm = norm.reverse();
                        }
                        warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);

                        faceObj.addVertex(vert);
                    }

                    for (int j = 0; j < face.Indices.Count;)
                    {
                        faceObj.addTriangle(
                            face.Indices[j++],
                            face.Indices[j++],
                            face.Indices[j++]);
                    }

                    Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
                    string materialName;
                    Color4 faceColor = GetFaceColor(teFace);

                    if (m_texturePrims && prim.Scale.LengthSquared() > 48 * 48)
                    {
                        materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
                    }
                    else
                    {
                        materialName = GetOrCreateMaterial(renderer, faceColor);
                    }

                    faceObj.transform(m);
                    faceObj.setPos(primPos);
                    faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);

                    renderer.Scene.addObject(meshName, faceObj);

                    renderer.SetObjectMaterial(meshName, materialName);
                }
                renderMesh.Faces.Clear();
                renderMesh = null;
            }
            catch (Exception ex)
            {
                MainConsole.Instance.Warn("[Warp3D]: Exception creating prim, " + ex);
            }
        }
コード例 #22
0
 public void PostAnAsset(AssetBase asset)
 {
     PostAsset(asset);
 }
コード例 #23
0
ファイル: LLLoginService.cs プロジェクト: chazzmac/Aurora-Sim
 private void CreateMetaDataMap(AssetBase data, OSDMap map)
 {
     map["ContentType"] = OSD.FromString(data.TypeString);
     map["CreationDate"] = OSD.FromDate(data.CreationDate);
     map["CreatorID"] = OSD.FromUUID(data.CreatorID);
     map["Description"] = OSD.FromString(data.Description);
     map["ID"] = OSD.FromUUID(data.ID);
     map["Name"] = OSD.FromString(data.Name);
     map["Type"] = OSD.FromInteger(data.Type);
 }
コード例 #24
0
ファイル: FlotsamAssetCache.cs プロジェクト: p07r0457/opensim
        /// <summary>
        /// Try to get an asset from the file cache.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private AssetBase GetFromFileCache(string id)
        {
            AssetBase asset = null;

            string filename = GetFileName(id);

            if (File.Exists(filename))
            {
                FileStream stream = null;
                try
                {
                    stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
                    BinaryFormatter bformatter = new BinaryFormatter();

                    asset = (AssetBase)bformatter.Deserialize(stream);

                    m_DiskHits++;
                }
                catch (System.Runtime.Serialization.SerializationException e)
                {
                    m_log.ErrorFormat(
                        "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}.  Exception {2} {3}",
                        filename, id, e.Message, e.StackTrace);

                    // If there was a problem deserializing the asset, the asset may
                    // either be corrupted OR was serialized under an old format
                    // {different version of AssetBase} -- we should attempt to
                    // delete it and re-cache
                    File.Delete(filename);
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat(
                        "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}.  Exception {2} {3}",
                        filename, id, e.Message, e.StackTrace);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }
            }

#if WAIT_ON_INPROGRESS_REQUESTS
            // Check if we're already downloading this asset.  If so, try to wait for it to
            // download.
            if (m_WaitOnInprogressTimeout > 0)
            {
                m_RequestsForInprogress++;

                ManualResetEvent waitEvent;
                if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
                {
                    waitEvent.WaitOne(m_WaitOnInprogressTimeout);
                    return(Get(id));
                }
            }
#else
            // Track how often we have the problem that an asset is requested while
            // it is still being downloaded by a previous request.
            if (m_CurrentlyWriting.Contains(filename))
            {
                m_RequestsForInprogress++;
            }
#endif
            return(asset);
        }
コード例 #25
0
        private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers)
        {
            if (m_useCache)
                m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10));

            if (m_cache != null)
            {
                string assetID = "j2kCache_" + AssetId.ToString();

                AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, AssetType.Notecard,
                                                           UUID.Zero)
                                                 {Flags = AssetFlags.Local | AssetFlags.Temporary};

                #region Serialize Layer Data

                StringBuilder stringResult = new StringBuilder();
                string strEnd = "\n";
                for (int i = 0; i < Layers.Length; i++)
                {
                    if (i == Layers.Length - 1)
                        strEnd = String.Empty;

                    stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End,
                                              Layers[i].End - Layers[i].Start, strEnd);
                }

                layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());

                #endregion Serialize Layer Data

                m_cache.Cache(assetID, layerDecodeAsset);
            }
        }
コード例 #26
0
            /// <summary>
            ///   Called once new texture data has been received for this updater.
            /// </summary>
            public void DataReceived(byte[] data, IScene scene)
            {
                ISceneChildEntity part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    string msg =
                        String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                    IChatModule chatModule = scene.RequestModuleInterface <IChatModule>();
                    if (chatModule != null)
                    {
                        chatModule.SimChat(msg, ChatTypeEnum.Say, 0,
                                           part.ParentEntity.AbsolutePosition, part.Name, part.UUID, false, scene);
                    }
                    return;
                }

                byte[]    assetData = null;
                AssetBase oldAsset  = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
                    if (defaultFace != null)
                    {
                        oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());

                        if (oldAsset != null)
                        {
                            assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha, scene);
                        }
                    }
                }

                if (assetData == null)
                {
                    assetData = new byte[data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                AssetBase asset = null;

                if (LastAssetID != UUID.Zero)
                {
                    asset             = scene.AssetService.Get(LastAssetID.ToString());
                    asset.Description = String.Format("URL image : {0}", Url);
                    asset.Data        = assetData;
                    if ((asset.Flags & AssetFlags.Local) == AssetFlags.Local)
                    {
                        asset.Flags = asset.Flags & ~AssetFlags.Local;
                    }
                    if (((asset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary) != ((Disp & DISP_TEMP) != 0))
                    {
                        if ((Disp & DISP_TEMP) != 0)
                        {
                            asset.Flags |= AssetFlags.Temporary;
                        }
                        else
                        {
                            asset.Flags = asset.Flags & ~AssetFlags.Temporary;
                        }
                    }
                    asset.ID = scene.AssetService.Store(asset);
                }
                else
                {
                    // Create a new asset for user
                    asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000),
                                          AssetType.Texture,
                                          scene.RegionInfo.RegionID)
                    {
                        Data = assetData, Description = String.Format("URL image : {0}", Url)
                    };
                    if ((Disp & DISP_TEMP) != 0)
                    {
                        asset.Flags = AssetFlags.Temporary;
                    }
                    asset.ID = scene.AssetService.Store(asset);
                }

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface <IJ2KDecoder>();

                if (cacheLayerDecode != null)
                {
                    cacheLayerDecode.Decode(asset.ID, asset.Data);
                    cacheLayerDecode = null;
                    LastAssetID      = asset.ID;
                }

                UUID oldID = UUID.Zero;

                lock (part)
                {
                    // mostly keep the values from before
                    Primitive.TextureEntry tmptex = part.Shape.Textures;

                    // remove the old asset from the cache
                    oldID = tmptex.DefaultTexture.TextureID;

                    if (Face == ALL_SIDES)
                    {
                        tmptex.DefaultTexture.TextureID = asset.ID;
                    }
                    else
                    {
                        try
                        {
                            Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
                            texface.TextureID         = asset.ID;
                            tmptex.FaceTextures[Face] = texface;
                        }
                        catch (Exception)
                        {
                            tmptex.DefaultTexture.TextureID = asset.ID;
                        }
                    }

                    // I'm pretty sure we always want to force this to true
                    // I'm pretty sure noone whats to set fullbright true if it wasn't true before.
                    // tmptex.DefaultTexture.Fullbright = true;

                    part.UpdateTexture(tmptex, true);
                }

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }
                    if (oldAsset != null)
                    {
                        if ((oldAsset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary)
                        {
                            scene.AssetService.Delete(oldID);
                        }
                    }
                }
            }
コード例 #27
0
ファイル: AssetsRequest.cs プロジェクト: KSLcom/Aurora-Sim
        /// <summary>
        ///     Called back by the asset cache when it has the asset
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="sender"></param>
        /// <param name="asset"></param>
        public void AssetRequestCallback(string assetID, object sender, AssetBase asset)
        {
            try
            {
                lock (this)
                {
                    //MainConsole.Instance.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id);

                    m_requestCallbackTimer.Stop();

                    if (m_requestState == RequestState.Aborted)
                    {
                        MainConsole.Instance.WarnFormat(
                            "[ARCHIVER]: Received information about asset {0} after archive save abortion.  Ignoring.",
                            assetID);

                        return;
                    }

                    if (asset != null)
                    {
            //                        MainConsole.Instance.DebugFormat("[ARCHIVER]: Writing asset {0}", id);
                        m_foundAssetUuids.Add(asset.ID);
                        m_assetsArchiver.WriteAsset(asset);
                    }
                    else
                    {
            //                        MainConsole.Instance.DebugFormat("[ARCHIVER]: Recording asset {0} as not found", id);
                        m_notFoundAssetUuids.Add(new UUID(assetID));
                    }

                    if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count == m_repliesRequired)
                    {
                        m_requestState = RequestState.Completed;

                        MainConsole.Instance.InfoFormat(
                            "[ARCHIVER]: Successfully added {0} assets ({1} assets notified missing)",
                            m_foundAssetUuids.Count, m_notFoundAssetUuids.Count);

                        // We want to stop using the asset cache thread asap
                        // as we now need to do the work of producing the rest of the archive
                        Util.FireAndForget(PerformAssetsRequestCallback);
                    }
                    else
                        m_requestCallbackTimer.Start();
                }
            }
            catch (Exception e)
            {
                MainConsole.Instance.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e);
            }
        }
コード例 #28
0
        private void UpdateFileCache(string key, AssetBase asset)
        {
            string filename = GetFileName(key);

            try
            {
                // If the file is already cached, don't cache it, just touch it so access time is updated
                if (File.Exists(filename))
                {
                    // We don't really want to know about sharing
                    // violations here. If the file is locked, then
                    // the other thread has updated the time for us.
                    try
                    {
                        m_CurrentlyWritingRwLock.AcquireReaderLock(-1);
                        try
                        {
                            if (!m_CurrentlyWriting.Contains(filename))
                            {
                                File.SetLastAccessTime(filename, DateTime.Now);
                            }
                        }
                        finally
                        {
                            m_CurrentlyWritingRwLock.ReleaseReaderLock();
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                    // Once we start writing, make sure we flag that we're writing
                    // that object to the cache so that we don't try to write the
                    // same file multiple times.
                    m_CurrentlyWritingRwLock.AcquireReaderLock(-1);
                    try
                    {
                        if (m_CurrentlyWriting.Contains(filename))
                        {
                            return;
                        }
                        LockCookie lc = m_CurrentlyWritingRwLock.UpgradeToWriterLock(-1);
                        try
                        {
                            /* recheck since we were in a reader lock before */
                            if (m_CurrentlyWriting.Contains(filename))
                            {
                                return;
                            }
                            m_CurrentlyWriting.Add(filename);
                        }
                        finally
                        {
                            m_CurrentlyWritingRwLock.DowngradeFromWriterLock(ref lc);
                        }
                    }
                    finally
                    {
                        m_CurrentlyWritingRwLock.ReleaseReaderLock();
                    }

                    Util.FireAndForget(
                        delegate { WriteFileCache(filename, asset); });
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}.  Exception {1} {2}",
                    asset.ID, e.Message, e.StackTrace);
            }
        }
コード例 #29
0
        protected void ConstructDefaultIarBytesForTestLoad()
        {
//            log4net.Config.XmlConfigurator.Configure();

            InventoryArchiverModule archiverModule = new InventoryArchiverModule();
            Scene scene = new SceneHelpers().SetupScene();

            SceneHelpers.SetupSceneModules(scene, archiverModule);

            UserAccountHelpers.CreateUserWithInventory(scene, m_uaLL1, "hampshire");

            MemoryStream archiveWriteStream = new MemoryStream();

            // Create scene object asset
            UUID             ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
            SceneObjectGroup object1 = SceneHelpers.CreateSceneObject(1, ownerId, "Ray Gun Object", 0x50);

            UUID      asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
            AssetBase asset1   = AssetHelpers.CreateAsset(asset1Id, object1);

            scene.AssetService.Store(asset1);

            // Create scene object item
            InventoryItemBase item1 = new InventoryItemBase();

            item1.Name      = m_item1Name;
            item1.ID        = UUID.Parse("00000000-0000-0000-0000-000000000020");
            item1.AssetID   = asset1.FullID;
            item1.GroupID   = UUID.Random();
            item1.CreatorId = m_uaLL1.PrincipalID.ToString();
            item1.Owner     = m_uaLL1.PrincipalID;
            item1.Folder    = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID;
            scene.AddInventoryItem(item1);

            // Create coalesced objects asset
            SceneObjectGroup cobj1 = SceneHelpers.CreateSceneObject(1, m_uaLL1.PrincipalID, "Object1", 0x120);

            cobj1.AbsolutePosition = new Vector3(15, 30, 45);

            SceneObjectGroup cobj2 = SceneHelpers.CreateSceneObject(1, m_uaLL1.PrincipalID, "Object2", 0x140);

            cobj2.AbsolutePosition = new Vector3(25, 50, 75);

            CoalescedSceneObjects coa = new CoalescedSceneObjects(m_uaLL1.PrincipalID, cobj1, cobj2);

            AssetBase coaAsset = AssetHelpers.CreateAsset(0x160, coa);

            scene.AssetService.Store(coaAsset);

            // Create coalesced objects inventory item
            InventoryItemBase coaItem = new InventoryItemBase();

            coaItem.Name      = m_coaItemName;
            coaItem.ID        = UUID.Parse("00000000-0000-0000-0000-000000000180");
            coaItem.AssetID   = coaAsset.FullID;
            coaItem.GroupID   = UUID.Random();
            coaItem.CreatorId = m_uaLL1.PrincipalID.ToString();
            coaItem.Owner     = m_uaLL1.PrincipalID;
            coaItem.Folder    = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID;
            scene.AddInventoryItem(coaItem);

            archiverModule.ArchiveInventory(
                Guid.NewGuid(), m_uaLL1.FirstName, m_uaLL1.LastName, "/*", "hampshire", archiveWriteStream);

            m_iarStreamBytes = archiveWriteStream.ToArray();
        }
コード例 #30
0
        private string Store(AssetBase asset, bool force)
        {
            int    tickCount = Environment.TickCount;
            string hash      = GetSHA256Hash(asset.Data);

            if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
            {
                string assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
                m_log.WarnFormat(
                    "[FSASSETS]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
                    asset.Name, asset.ID, asset.Name.Length, assetName.Length);
                asset.Name = assetName;
            }

            if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
            {
                string assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
                m_log.WarnFormat(
                    "[FSASSETS]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
                    asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
                asset.Description = assetDescription;
            }

            if (!AssetExists(hash))
            {
                string tempFile  = Path.Combine(Path.Combine(m_SpoolDirectory, "spool"), hash + ".asset");
                string finalFile = Path.Combine(m_SpoolDirectory, hash + ".asset");

                if (!File.Exists(finalFile))
                {
                    // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
                    // Fix bad assets before storing on this server
                    if (asset.Type == (int)AssetType.Object && asset.Data != null)
                    {
                        string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
                        asset.Data = Utils.StringToBytes(xml);
                    }

                    FileStream fs = File.Create(tempFile);

                    fs.Write(asset.Data, 0, asset.Data.Length);

                    fs.Close();

                    File.Move(tempFile, finalFile);
                }
            }

            if (asset.ID == string.Empty)
            {
                if (asset.FullID == UUID.Zero)
                {
                    asset.FullID = UUID.Random();
                }
                asset.ID = asset.FullID.ToString();
            }
            else if (asset.FullID == UUID.Zero)
            {
                UUID uuid = UUID.Zero;
                if (UUID.TryParse(asset.ID, out uuid))
                {
                    asset.FullID = uuid;
                }
                else
                {
                    asset.FullID = UUID.Random();
                }
            }

            if (!m_DataConnector.Store(asset.Metadata, hash))
            {
                if (asset.Metadata.Type == -2)
                {
                    return(asset.ID);
                }

                return(UUID.Zero.ToString());
            }
            else
            {
                return(asset.ID);
            }
        }
コード例 #31
0
        ////////////////////////////////////////////////////////////
        // IImprovedAssetCache
        //

        private void UpdateMemoryCache(string key, AssetBase asset)
        {
            m_MemoryCache.AddOrUpdate(GetAssetID(key), asset, m_MemoryExpiration);
        }
コード例 #32
0
            public override void VisitArrayItem(Array array, ArrayDescriptor descriptor, int index, object item, ITypeDescriptor itemDescriptor)
            {
                base.VisitArrayItem(array, descriptor, index, item, itemDescriptor);
                var assetReference    = item as AssetReference;
                var assetBase         = item as AssetBase;
                var attachedReference = AttachedReferenceManager.GetAttachedReference(item);

                if (assetReference != null)
                {
                    AddLink(item,
                            (guid, location) =>
                    {
                        var newValue = AssetReference.New(descriptor.ElementType, guid ?? assetReference.Id, location);
                        array.SetValue(newValue, index);
                        return(newValue);
                    });
                }
                else if (assetBase != null)
                {
                    AddLink(item,
                            (guid, location) =>
                    {
                        var newValue = new AssetBase(location, assetBase.Asset);
                        array.SetValue(newValue, index);
                        return(newValue);
                    });
                }
                else if (attachedReference != null)
                {
                    AddLink(attachedReference,
                            (guid, location) =>
                    {
                        object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateProxyObject(descriptor.ElementType, guid.Value, location) : null;
                        if (newValue != null)
                        {
                            IdentifiableHelper.SetId(newValue, IdentifiableHelper.GetId(item));
                        }
                        array.SetValue(newValue, index);
                        return(newValue);
                    });
                }
                else if (item is UFile)
                {
                    AddLink(item,
                            (guid, location) =>
                    {
                        var newValue = new UFile(location);
                        array.SetValue(newValue, index);
                        return(newValue);
                    });
                }
                else if (item is UDirectory)
                {
                    AddLink(item,
                            (guid, location) =>
                    {
                        var newValue = new UFile(location);
                        array.SetValue(newValue, index);
                        return(newValue);
                    });
                }
            }
コード例 #33
0
        /// <summary>
        /// Writes a file to the file cache, creating any nessesary
        /// tier directories along the way
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="asset"></param>
        private void WriteFileCache(string filename, AssetBase asset)
        {
            Stream stream = null;

            // Make sure the target cache directory exists
            string directory = Path.GetDirectoryName(filename);

            // Write file first to a temp name, so that it doesn't look
            // like it's already cached while it's still writing.
            string tempname = Path.Combine(directory, Path.GetRandomFileName());

            try
            {
                try
                {
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    stream = File.Open(tempname, FileMode.Create);
                    BinaryFormatter bformatter = new BinaryFormatter();
                    bformatter.Serialize(stream, asset);
                }
                catch (IOException e)
                {
                    m_log.WarnFormat(
                        "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}.  Exception {4} {5}.",
                        asset.ID, tempname, filename, directory, e.Message, e.StackTrace);

                    return;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }

                try
                {
                    // Now that it's written, rename it so that it can be found.
                    //
                    //                File.Copy(tempname, filename, true);
                    //                File.Delete(tempname);
                    //
                    // For a brief period, this was done as a separate copy and then temporary file delete operation to
                    // avoid an IOException caused by move if some competing thread had already written the file.
                    // However, this causes exceptions on Windows when other threads attempt to read a file
                    // which is still being copied.  So instead, go back to moving the file and swallow any IOException.
                    //
                    // This situation occurs fairly rarely anyway.  We assume in this that moves are atomic on the
                    // filesystem.
                    File.Move(tempname, filename);

                    if (m_LogLevel >= 2)
                    {
                        m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
                    }
                }
                catch (IOException)
                {
                    // If we see an IOException here it's likely that some other competing thread has written the
                    // cache file first, so ignore.  Other IOException errors (e.g. filesystem full) should be
                    // signally by the earlier temporary file writing code.
                }
            }
            finally
            {
                // Even if the write fails with an exception, we need to make sure
                // that we release the lock on that file, otherwise it'll never get
                // cached
                m_CurrentlyWritingRwLock.AcquireWriterLock(-1);
                try
                {
                    m_CurrentlyWriting.Remove(filename);
                }
                finally
                {
                    m_CurrentlyWritingRwLock.ReleaseWriterLock();
                }
            }
        }
コード例 #34
0
        private void RunRequests()
        {
            while (true)
            {
                byte[] idata = null;
                bool found = false;
                AssetStorage foundAsset = null;
                ARequest req = this._assetRequests.Dequeue();
                IObjectSet result = db.Query(new AssetUUIDQuery(req.AssetID));
                if (result.Count > 0)
                {
                    foundAsset = (AssetStorage)result.Next();
                    found = true;
                }

                AssetBase asset = new AssetBase();
                if (found)
                {
                    asset.FullID = foundAsset.UUID;
                    asset.Type = foundAsset.Type;
                    asset.InvType = foundAsset.Type;
                    asset.Name = foundAsset.Name;
                    idata = foundAsset.Data;
                }
                else
                {
                    asset.FullID = LLUUID.Zero;
                }
                asset.Data = idata;
                _receiver.AssetReceived(asset, req.IsTexture);
            }
        }
コード例 #35
0
        public string Store(AssetBase asset)
        {
            //m_log.DebugFormat("[ASSET SERVICE]: Store asset {0} {1}", asset.Name, asset.ID);
            m_Database.StoreAsset (asset);
            IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache> ();
            if (cache != null && asset != null)
            {
                cache.Expire (asset.ID);
                cache.Cache (asset);
            }

            return asset.ID;
        }
コード例 #36
0
 private AssetBase LoadAssetBase(OSDMap map)
 {
     AssetBase asset = new AssetBase();
     asset.FromOSD(map);
     return asset;
 }
コード例 #37
0
            public override void VisitCollectionItem(IEnumerable collection, CollectionDescriptor descriptor, int index, object item, ITypeDescriptor itemDescriptor)
            {
                base.VisitCollectionItem(collection, descriptor, index, item, itemDescriptor);
                var assetReference    = item as AssetReference;
                var assetBase         = item as AssetBase;
                var attachedReference = AttachedReferenceManager.GetAttachedReference(item);

                // We cannot set links if we do not have indexer accessor
                if (!descriptor.HasIndexerAccessors)
                {
                    return;
                }

                if (assetReference != null)
                {
                    AddLink(assetReference, (guid, location) =>
                    {
                        var link = AssetReference.New(descriptor.ElementType, guid ?? assetReference.Id, location);
                        descriptor.SetValue(collection, index, link);
                        return(link);
                    });
                }
                else if (assetBase != null)
                {
                    AddLink(assetBase, (guid, location) =>
                    {
                        var link = new AssetBase(location, assetBase.Asset);
                        descriptor.SetValue(collection, index, link);
                        return(link);
                    });
                }
                else if (attachedReference != null)
                {
                    AddLink(attachedReference, (guid, location) =>
                    {
                        var link = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateProxyObject(descriptor.ElementType, guid.Value, location) : null;
                        if (link != null)
                        {
                            IdentifiableHelper.SetId(link, IdentifiableHelper.GetId(item));
                        }
                        descriptor.SetValue(collection, index, link);
                        return(link);
                    });
                }
                else if (item is UFile)
                {
                    AddLink(item, (guid, location) =>
                    {
                        var link = new UFile(location);
                        descriptor.SetValue(collection, index, link);
                        return(link);
                    });
                }
                else if (item is UDirectory)
                {
                    AddLink(item, (guid, location) =>
                    {
                        var link = new UDirectory(location);
                        descriptor.SetValue(collection, index, link);
                        return(link);
                    });
                }
            }
コード例 #38
0
        private AssetBase Get(string id, out string sha)
        {
            string hash = string.Empty;

            int           startTime = System.Environment.TickCount;
            AssetMetadata metadata;

            lock (m_readLock)
            {
                metadata = m_DataConnector.Get(id, out hash);
            }

            sha = hash;

            if (metadata == null)
            {
                AssetBase asset = null;
                if (m_FallbackService != null)
                {
                    asset = m_FallbackService.Get(id);
                    if (asset != null)
                    {
                        asset.Metadata.ContentType =
                            SLUtil.SLAssetTypeToContentType((int)asset.Type);
                        sha = GetSHA256Hash(asset.Data);
                        m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
                        Store(asset);
                    }
                }
                if (asset == null && m_showStats)
                {
                    // m_log.InfoFormat("[FSASSETS]: Asset {0} not found", id);
                    m_missingAssets++;
                }
                return(asset);
            }
            AssetBase newAsset = new AssetBase();

            newAsset.Metadata = metadata;
            try
            {
                newAsset.Data = GetFsData(hash);
                if (newAsset.Data.Length == 0)
                {
                    AssetBase asset = null;
                    if (m_FallbackService != null)
                    {
                        asset = m_FallbackService.Get(id);
                        if (asset != null)
                        {
                            asset.Metadata.ContentType =
                                SLUtil.SLAssetTypeToContentType((int)asset.Type);
                            sha = GetSHA256Hash(asset.Data);
                            m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
                            Store(asset);
                        }
                    }
                    if (asset == null)
                    {
                        if (m_showStats)
                        {
                            m_missingAssetsFS++;
                        }
                        // m_log.InfoFormat("[FSASSETS]: Asset {0}, hash {1} not found in FS", id, hash);
                    }
                    else
                    {
                        // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
                        // Fix bad assets before sending them elsewhere
                        if (asset.Type == (int)AssetType.Object && asset.Data != null)
                        {
                            string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
                            asset.Data = Utils.StringToBytes(xml);
                        }
                        return(asset);
                    }
                }

                if (m_showStats)
                {
                    lock (m_statsLock)
                    {
                        m_readTicks += Environment.TickCount - startTime;
                        m_readCount++;
                    }
                }

                // Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
                // Fix bad assets before sending them elsewhere
                if (newAsset.Type == (int)AssetType.Object && newAsset.Data != null)
                {
                    string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(newAsset.Data));
                    newAsset.Data = Utils.StringToBytes(xml);
                }

                return(newAsset);
            }
            catch (Exception exception)
            {
                m_log.Error(exception.ToString());
                return(null);
            }
        }
コード例 #39
0
        private void SetUpAssetDatabase()
        {
            try
            {

                Console.WriteLine("setting up Asset database");

                AssetBase Image = new AssetBase();
                Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000001");
                Image.Name = "Bricks";
                this.LoadAsset(Image, true, "bricks.jp2");
                AssetStorage store = new AssetStorage();
                store.Data = Image.Data;
                store.Name = Image.Name;
                store.UUID = Image.FullID;
                db.Set(store);
                db.Commit();

                Image = new AssetBase();
                Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000002");
                Image.Name = "Plywood";
                this.LoadAsset(Image, true, "plywood.jp2");
                store = new AssetStorage();
                store.Data = Image.Data;
                store.Name = Image.Name;
                store.UUID = Image.FullID;
                db.Set(store);
                db.Commit();

                Image = new AssetBase();
                Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000003");
                Image.Name = "Rocks";
                this.LoadAsset(Image, true, "rocks.jp2");
                store = new AssetStorage();
                store.Data = Image.Data;
                store.Name = Image.Name;
                store.UUID = Image.FullID;
                db.Set(store);
                db.Commit();

                Image = new AssetBase();
                Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000004");
                Image.Name = "Granite";
                this.LoadAsset(Image, true, "granite.jp2");
                store = new AssetStorage();
                store.Data = Image.Data;
                store.Name = Image.Name;
                store.UUID = Image.FullID;
                db.Set(store);
                db.Commit();

                Image = new AssetBase();
                Image.FullID = new LLUUID("00000000-0000-0000-9999-000000000005");
                Image.Name = "Hardwood";
                this.LoadAsset(Image, true, "hardwood.jp2");
                store = new AssetStorage();
                store.Data = Image.Data;
                store.Name = Image.Name;
                store.UUID = Image.FullID;
                db.Set(store);
                db.Commit();

                Image = new AssetBase();
                Image.FullID = new LLUUID("00000000-0000-0000-5005-000000000005");
                Image.Name = "Prim Base Texture";
                this.LoadAsset(Image, true, "plywood.jp2");
                store = new AssetStorage();
                store.Data = Image.Data;
                store.Name = Image.Name;
                store.UUID = Image.FullID;
                db.Set(store);
                db.Commit();

                Image = new AssetBase();
                Image.FullID = new LLUUID("66c41e39-38f9-f75a-024e-585989bfab73");
                Image.Name = "Shape";
                this.LoadAsset(Image, false, "base_shape.dat");
                store = new AssetStorage();
                store.Data = Image.Data;
                store.Name = Image.Name;
                store.UUID = Image.FullID;
                db.Set(store);
                db.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #40
0
            public override void VisitDictionaryKeyValue(object dictionaryObj, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
            {
                base.VisitDictionaryKeyValue(dictionaryObj, descriptor, key, keyDescriptor, value, valueDescriptor);
                var assetReference    = value as AssetReference;
                var assetBase         = value as AssetBase;
                var attachedReference = AttachedReferenceManager.GetAttachedReference(value);

                if (assetReference != null)
                {
                    AddLink(assetReference,
                            (guid, location) =>
                    {
                        var newValue = AssetReference.New(descriptor.ValueType, guid ?? assetReference.Id, location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (assetBase != null)
                {
                    AddLink(assetBase,
                            (guid, location) =>
                    {
                        var newValue = new AssetBase(location, assetBase.Asset);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (attachedReference != null)
                {
                    AddLink(attachedReference,
                            (guid, location) =>
                    {
                        object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateProxyObject(descriptor.ValueType, guid.Value, location) : null;
                        if (newValue != null)
                        {
                            IdentifiableHelper.SetId(newValue, IdentifiableHelper.GetId(value));
                        }
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (value is UFile)
                {
                    AddLink(value,
                            (guid, location) =>
                    {
                        var newValue = new UFile(location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (value is UDirectory)
                {
                    AddLink(value,
                            (guid, location) =>
                    {
                        var newValue = new UDirectory(location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
            }
コード例 #41
0
        protected AssetBase CreateAsset(string assetIdStr, string name, string path, AssetType type)
        {
            AssetBase asset = new AssetBase(new UUID(assetIdStr), name, type, m_service.LibraryOwner);

            if (!String.IsNullOrEmpty(path))
            {
                //MainConsole.Instance.InfoFormat("[ASSETS]: Loading: [{0}][{1}]", name, path);

                LoadAsset(asset, path);
            }
            else
            {
                MainConsole.Instance.InfoFormat("[ASSETS]: Instantiated: [{0}]", name);
            }

            return asset;
        }
コード例 #42
0
            public override void VisitObjectMember(object container, ObjectDescriptor containerDescriptor, IMemberDescriptor member, object value)
            {
                base.VisitObjectMember(container, containerDescriptor, member, value);
                var assetReference    = value as AssetReference;
                var assetBase         = value as AssetBase;
                var attachedReference = AttachedReferenceManager.GetAttachedReference(value);

                if (assetReference != null)
                {
                    AddLink(assetReference,
                            (guid, location) =>
                    {
                        var newValue = AssetReference.New(member.Type, guid ?? assetReference.Id, location);
                        member.Set(container, newValue);
                        return(newValue);
                    });
                }
                else if (assetBase != null)
                {
                    AddLink(assetBase,
                            (guid, location) =>
                    {
                        var newValue = new AssetBase(location, assetBase.Asset);
                        member.Set(container, newValue);
                        return(newValue);
                    });
                }
                else if (attachedReference != null)
                {
                    AddLink(attachedReference,
                            (guid, location) =>
                    {
                        object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateProxyObject(member.Type, guid.Value, location) : null;
                        if (newValue != null)
                        {
                            IdentifiableHelper.SetId(newValue, IdentifiableHelper.GetId(value));
                        }
                        member.Set(container, newValue);
                        return(newValue);
                    });
                }
                else if (value is UFile)
                {
                    AddLink(value,
                            (guid, location) =>
                    {
                        var newValue = new UFile(location);
                        member.Set(container, newValue);
                        return(newValue);
                    });
                }
                else if (value is UDirectory)
                {
                    AddLink(value,
                            (guid, location) =>
                    {
                        var newValue = new UDirectory(location);
                        member.Set(container, newValue);
                        return(newValue);
                    });
                }
            }
コード例 #43
0
        private bool ProcessMergeAssetBase(AssetBase assetBase, HashSet<Guid> beingProcessed, out AssetItem existingAsset)
        {
            var baseId = assetBase.Id;

            // Make sure that the base asset exist
            existingAsset = session.FindAsset(baseId);
            if (existingAsset == null)
            {
                log.Warning(package, assetBase, AssetMessageCode.AssetNotFound, assetBase);
                return false;
            }

            // If the base asset hasn't been processed, continue on next asset
            if (!assetsProcessed.ContainsKey(baseId))
            {
                // If asset is in the same package, we can process it right away
                if (existingAsset.Package == package)
                {
                    if (!ProcessMergeAssetItem(existingAsset, beingProcessed))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
コード例 #44
0
 /// <summary>
 /// Archive the assets given to this archiver to the given archive.
 /// </summary>
 /// <param name="archive"></param>
 public void WriteAsset(AssetBase asset)
 {
     //WriteMetadata(archive);
     WriteData(asset);
 }
コード例 #45
0
            /// <summary>
            ///     Called once new texture data has been received for this updater.
            /// </summary>
            public void DataReceived(byte[] data, IScene scene)
            {
                ISceneChildEntity part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    string msg =
                        String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                    IChatModule chatModule = scene.RequestModuleInterface<IChatModule>();
                    if (chatModule != null)
                        chatModule.SimChat(msg, ChatTypeEnum.Say, 0,
                                           part.ParentEntity.AbsolutePosition, part.Name, part.UUID, false, scene);
                    return;
                }

                byte[] assetData = null;
                AssetBase oldAsset = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
                    if (defaultFace != null)
                    {
                        oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());

                        if (oldAsset != null)
                            assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha, scene);
                    }
                }

                if (assetData == null)
                {
                    assetData = new byte[data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                AssetBase asset = null;

                if (LastAssetID != UUID.Zero)
                {
                    asset = scene.AssetService.Get(LastAssetID.ToString());
                    asset.Description = String.Format("URL image : {0}", Url);
                    asset.Data = assetData;
                    if ((asset.Flags & AssetFlags.Local) == AssetFlags.Local)
                    {
                        asset.Flags = asset.Flags & ~AssetFlags.Local;
                    }
                    if (((asset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary) != ((Disp & DISP_TEMP) != 0))
                    {
                        if ((Disp & DISP_TEMP) != 0) asset.Flags |= AssetFlags.Temporary;
                        else asset.Flags = asset.Flags & ~AssetFlags.Temporary;
                    }
                    asset.ID = scene.AssetService.Store(asset);
                }
                else
                {
                    // Create a new asset for user
                    asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000),
                                          AssetType.Texture,
                                          scene.RegionInfo.RegionID)
                                {Data = assetData, Description = String.Format("URL image : {0}", Url)};
                    if ((Disp & DISP_TEMP) != 0) asset.Flags = AssetFlags.Temporary;
                    asset.ID = scene.AssetService.Store(asset);
                }

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
                if (cacheLayerDecode != null)
                {
                    cacheLayerDecode.Decode(asset.ID, asset.Data);
                    cacheLayerDecode = null;
                    LastAssetID = asset.ID;
                }

                UUID oldID = UUID.Zero;

                lock (part)
                {
                    // mostly keep the values from before
                    Primitive.TextureEntry tmptex = part.Shape.Textures;

                    // remove the old asset from the cache
                    oldID = tmptex.DefaultTexture.TextureID;

                    if (Face == ALL_SIDES)
                    {
                        tmptex.DefaultTexture.TextureID = asset.ID;
                    }
                    else
                    {
                        try
                        {
                            Primitive.TextureEntryFace texface = tmptex.CreateFace((uint) Face);
                            texface.TextureID = asset.ID;
                            tmptex.FaceTextures[Face] = texface;
                        }
                        catch (Exception)
                        {
                            tmptex.DefaultTexture.TextureID = asset.ID;
                        }
                    }

                    // I'm pretty sure we always want to force this to true
                    // I'm pretty sure noone whats to set fullbright true if it wasn't true before.
                    // tmptex.DefaultTexture.Fullbright = true;

                    part.UpdateTexture(tmptex, true);
                }

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null) oldAsset = scene.AssetService.Get(oldID.ToString());
                    if (oldAsset != null)
                    {
                        if ((oldAsset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary)
                        {
                            scene.AssetService.Delete(oldID);
                        }
                    }
                }
            }
コード例 #46
0
        public void TestLoadIarPathWithEscapedChars()
        {
            TestHelpers.InMethod();
            //            log4net.Config.XmlConfigurator.Configure();

            string itemName = "You & you are a mean/man/";
            string humanEscapedItemName = @"You & you are a mean\/man\/";
            string userPassword = "******";

            InventoryArchiverModule archiverModule = new InventoryArchiverModule();

            Scene scene = new SceneHelpers().SetupScene();
            SceneHelpers.SetupSceneModules(scene, archiverModule);

            // Create user
            string userFirstName = "Jock";
            string userLastName = "Stirrup";
            UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
            UserAccountHelpers.CreateUserWithInventory(scene, userFirstName, userLastName, userId, "meowfood");

            // Create asset
            SceneObjectGroup object1;
            SceneObjectPart part1;
            {
                string partName = "part name";
                UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
                PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
                Vector3 groupPosition = new Vector3(10, 20, 30);
                Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
                Vector3 offsetPosition = new Vector3(5, 10, 15);

                part1
                    = new SceneObjectPart(
                        ownerId, shape, groupPosition, rotationOffset, offsetPosition);
                part1.Name = partName;

                object1 = new SceneObjectGroup(part1);
                scene.AddNewSceneObject(object1, false);
            }

            UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
            AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
            scene.AssetService.Store(asset1);

            // Create item
            UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
            InventoryItemBase item1 = new InventoryItemBase();
            item1.Name = itemName;
            item1.AssetID = asset1.FullID;
            item1.ID = item1Id;
            InventoryFolderBase objsFolder
                = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, "Objects")[0];
            item1.Folder = objsFolder.ID;
            scene.AddInventoryItem(item1);

            MemoryStream archiveWriteStream = new MemoryStream();
            archiverModule.OnInventoryArchiveSaved += SaveCompleted;

            mre.Reset();
            archiverModule.ArchiveInventory(
                Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream);
            mre.WaitOne(60000, false);

            // LOAD ITEM
            MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());

            archiverModule.DearchiveInventory(userFirstName, userLastName, "Scripts", userPassword, archiveReadStream);

            InventoryItemBase foundItem1
                = InventoryArchiveUtils.FindItemByPath(
                    scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName);

            Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
            //            Assert.That(
            //                foundItem1.CreatorId, Is.EqualTo(userUuid),
            //                "Loaded item non-uuid creator doesn't match that of the loading user");
            Assert.That(
                foundItem1.Name, Is.EqualTo(itemName),
                "Loaded item name doesn't match saved name");
        }
コード例 #47
0
ファイル: LLLoginService.cs プロジェクト: chazzmac/Aurora-Sim
 private AssetBase LoadAssetBase(OSDMap map)
 {
     AssetBase asset = new AssetBase();
     asset.Data = map["AssetData"].AsBinary();
     asset.TypeString = map["ContentType"].AsString();
     asset.CreationDate = map["CreationDate"].AsDate();
     asset.CreatorID = map["CreatorID"].AsUUID();
     asset.Description = map["Description"].AsString();
     asset.ID = map["ID"].AsUUID();
     asset.Name = map["Name"].AsString();
     asset.Type = map["Type"].AsInteger();
     return asset;
 }
コード例 #48
0
ファイル: HGAssetMapper.cs プロジェクト: wgahnagl/opensim
        public bool PostAsset(string url, AssetBase asset, bool verbose = true)
        {
            if (asset == null)
            {
                m_log.Warn("[HG ASSET MAPPER]: Tried to post asset to remote server, but asset not in local cache.");
                return(false);
            }

            if (string.IsNullOrEmpty(url))
            {
                return(false);
            }

            if (!url.EndsWith("/") && !url.EndsWith("="))
            {
                url = url + "/";
            }

            // See long comment in AssetCache.AddAsset
            if (asset.Temporary || asset.Local)
            {
                return(true);
            }

            // We need to copy the asset into a new asset, because
            // we need to set its ID to be URL+UUID, so that the
            // HGAssetService dispatches it to the remote grid.
            // It's not pretty, but the best that can be done while
            // not having a global naming infrastructure
            AssetBase asset1 = new AssetBase(asset.FullID, asset.Name, asset.Type, asset.Metadata.CreatorID);

            Copy(asset, asset1);
            asset1.ID = url + asset.ID;

            AdjustIdentifiers(asset1.Metadata);
            if (asset1.Metadata.Type == (sbyte)AssetType.Object)
            {
                asset1.Data = AdjustIdentifiers(asset.Data);
            }
            else
            {
                asset1.Data = asset.Data;
            }

            string id = m_scene.AssetService.Store(asset1);

            if (String.IsNullOrEmpty(id))
            {
                if (verbose)
                {
                    m_log.DebugFormat("[HG ASSET MAPPER]: Asset server {0} did not accept {1}", url, asset.ID);
                }
                return(false);
            }

            if (verbose)
            {
                m_log.DebugFormat("[HG ASSET MAPPER]: Posted copy of asset {0} from local asset server to {1}", asset1.ID, url);
            }
            return(true);
        }
コード例 #49
0
        public void SculptTextureCallback(UUID textureID, AssetBase texture)
        {
            if (m_shape.SculptEntry)
            {
                // commented out for sculpt map caching test - null could mean a cached sculpt map has been found
                //if (texture != null)
                {
                    if (texture != null)
                        m_shape.SculptData = texture.Data;

                    if (PhysActor != null)
                    {
                        // Tricks physics engine into thinking we've changed the part shape.
                        PrimitiveBaseShape m_newshape = m_shape.Copy();
                        PhysActor.Shape = m_newshape;
                        m_shape = m_newshape;

                        m_parentGroup.Scene.SceneGraph.PhysicsScene.AddPhysicsActorTaint(PhysActor);
                    }
                }
            }
        }
コード例 #50
0
ファイル: HGAssetMapper.cs プロジェクト: wgahnagl/opensim
        public void Post(UUID assetID, UUID ownerID, string userAssetURL)
        {
            AssetBase asset = m_scene.AssetService.Get(assetID.ToString());

            if (asset == null)
            {
                m_log.DebugFormat("[HG ASSET MAPPER POST]: Something wrong with asset {0}, it could not be found", assetID);
                return;
            }
            m_log.DebugFormat("[HG ASSET MAPPER  POST]: Starting to send asset {0} to asset server {1}", assetID, userAssetURL);

            // Find all the embedded assets
            HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, string.Empty);

            uuidGatherer.AddForInspection(asset.FullID);
            uuidGatherer.GatherAll(true);

            // Check which assets already exist in the destination server

            string url = userAssetURL;

            if (!url.EndsWith("/") && !url.EndsWith("="))
            {
                url = url + "/";
            }

            string[] remoteAssetIDs = new string[uuidGatherer.GatheredUuids.Count];
            int      i = 0;

            foreach (UUID id in uuidGatherer.GatheredUuids.Keys)
            {
                remoteAssetIDs[i++] = url + id.ToString();
            }

            bool[] exist;
            try
            {
                exist = m_scene.AssetService.AssetsExist(remoteAssetIDs);
            }
            catch
            {
                m_log.DebugFormat("[HG ASSET MAPPER POST]: Problems sending asset {0} to asset server {1}", assetID, userAssetURL);
                return;
            }

            var existSet = new HashSet <string>();

            i = 0;
            foreach (UUID id in uuidGatherer.GatheredUuids.Keys)
            {
                if (exist[i])
                {
                    existSet.Add(id.ToString());
                }
                ++i;
            }

            // Send only those assets which don't already exist in the destination server

            bool success  = true;
            var  notFound = new List <string>();
            var  posted   = new List <string>();

            foreach (UUID uuid in uuidGatherer.GatheredUuids.Keys)
            {
                string idstr = uuid.ToString();
                if (existSet.Contains(idstr))
                {
                    continue;
                }

                asset = m_scene.AssetService.Get(idstr);
                if (asset == null)
                {
                    notFound.Add(idstr);
                    continue;
                }

                try
                {
                    bool b = PostAsset(userAssetURL, asset, false);
                    if (b)
                    {
                        posted.Add(idstr);
                    }
                    success &= b;
                }
                catch (Exception e)
                {
                    m_log.Error(
                        string.Format(
                            "[HG ASSET MAPPER POST]: Failed to post asset {0} (type {1}, length {2}) referenced from {3} to {4} with exception  ",
                            asset.ID, asset.Type, asset.Data.Length, assetID, userAssetURL),
                        e);

                    // For debugging purposes for now we will continue to throw the exception up the stack as was already happening.  However, after
                    // debugging we may want to simply report the failure if we can tell this is due to a failure
                    // with a particular asset and not a destination network failure where all asset posts will fail (and
                    // generate large amounts of log spam).
                    throw;
                }
            }
            StringBuilder sb = null;

            if (notFound.Count > 0)
            {
                if (sb == null)
                {
                    sb = new StringBuilder(512);
                }
                i = notFound.Count;
                sb.Append("[HG ASSET MAPPER POST]: did not find embedded UUIDs as assets:\n\t");
                for (int j = 0; j < notFound.Count; ++j)
                {
                    sb.Append(notFound[j]);
                    if (i < j)
                    {
                        sb.Append(',');
                    }
                }
                m_log.Debug(sb.ToString());
                sb.Clear();
            }
            if (existSet.Count > 0)
            {
                if (sb == null)
                {
                    sb = new StringBuilder(512);
                }
                i = existSet.Count;
                sb.Append("[HG ASSET MAPPER POST]: embedded assets already at destination server:\n\t");
                foreach (UUID id in existSet)
                {
                    sb.Append(id);
                    if (--i > 0)
                    {
                        sb.Append(',');
                    }
                }
                m_log.Debug(sb.ToString());
                sb.Clear();
            }
            if (posted.Count > 0)
            {
                if (sb == null)
                {
                    sb = new StringBuilder(512);
                }
                i = posted.Count;
                sb.Append("[HG ASSET MAPPER POST]: Posted assets:\n\t");
                for (int j = 0; j < posted.Count; ++j)
                {
                    sb.Append(posted[j]);
                    if (i < j)
                    {
                        sb.Append(',');
                    }
                }
                m_log.Debug(sb.ToString());
            }

            if (!success)
            {
                m_log.DebugFormat("[HG ASSET MAPPER POST]: Problems sending asset {0} to asset server {1}", assetID, userAssetURL);
            }
            else
            {
                m_log.DebugFormat("[HG ASSET MAPPER POST]: Successfully sent asset {0} to asset server {1}", assetID, userAssetURL);
            }
        }
コード例 #51
0
 private void CheckContainsReferences(AssetType assetType, bool expected)
 {
     AssetBase asset = new AssetBase(UUID.Zero, String.Empty, (sbyte)assetType, UUID.Zero.ToString());
     bool actual = asset.ContainsReferences;
     Assert.AreEqual(expected, actual, "Expected "+assetType+".ContainsReferences to be "+expected+" but was "+actual+".");
 }
コード例 #52
0
ファイル: BuySellModule.cs プロジェクト: osCore2/osCore2
        public bool BuyObject(IClientAPI remoteClient, UUID categoryID, uint localID, byte saleType, int salePrice)
        {
            SceneObjectPart rootpart = m_scene.GetSceneObjectPart(localID);

            if (rootpart == null)
            {
                return(false);
            }

            SceneObjectGroup group = rootpart.ParentGroup;

            if (group == null || group.IsDeleted || group.inTransit)
            {
                return(false);
            }

            // make sure we are not buying a child part
            rootpart = group.RootPart;

            switch (saleType)
            {
            case 1: // Sell as original (in-place sale)
                uint effectivePerms = group.EffectiveOwnerPerms;

                if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
                {
                    if (m_dialogModule != null)
                    {
                        m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
                    }
                    return(false);
                }

                group.SetOwner(remoteClient.AgentId, remoteClient.ActiveGroupId);

                if (m_scene.Permissions.PropagatePermissions())
                {
                    foreach (SceneObjectPart child in group.Parts)
                    {
                        child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
                        child.TriggerScriptChangedEvent(Changed.OWNER);
                        child.ApplyNextOwnerPermissions();
                    }
                    group.InvalidateDeepEffectivePerms();
                }

                rootpart.ObjectSaleType = 0;
                rootpart.SalePrice      = 10;
                rootpart.ClickAction    = Convert.ToByte(0);

                group.HasGroupChanged = true;
                rootpart.SendPropertiesToClient(remoteClient);
                rootpart.TriggerScriptChangedEvent(Changed.OWNER);
                group.ResumeScripts();
                rootpart.ScheduleFullUpdate();

                break;

            case 2: // Sell a copy
                uint perms = group.EffectiveOwnerPerms;

                if ((perms & (uint)PermissionMask.Transfer) == 0)
                {
                    if (m_dialogModule != null)
                    {
                        m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
                    }
                    return(false);
                }

                if ((perms & (uint)PermissionMask.Copy) == 0)
                {
                    if (m_dialogModule != null)
                    {
                        m_dialogModule.SendAlertToUser(remoteClient, "This sale has been blocked by the permissions system");
                    }
                    return(false);
                }

                string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);

                string name = rootpart.Name;
                string desc = rootpart.Description;

                AssetBase asset = m_scene.CreateAsset(
                    name, desc,
                    (sbyte)AssetType.Object,
                    Utils.StringToBytes(sceneObjectXml),
                    rootpart.CreatorID);
                m_scene.AssetService.Store(asset);

                InventoryItemBase item = new InventoryItemBase();
                item.CreatorId   = rootpart.CreatorID.ToString();
                item.CreatorData = rootpart.CreatorData;

                item.ID          = UUID.Random();
                item.Owner       = remoteClient.AgentId;
                item.AssetID     = asset.FullID;
                item.Description = desc;
                item.Name        = name;
                item.AssetType   = asset.Type;
                item.InvType     = (int)InventoryType.Object;
                item.Folder      = categoryID;

                perms = group.CurrentAndFoldedNextPermissions();
                // apply parts inventory next perms
                PermissionsUtil.ApplyNoModFoldedPermissions(perms, ref perms);
                // change to next owner perms
                perms &= rootpart.NextOwnerMask;
                // update folded
                perms = PermissionsUtil.FixAndFoldPermissions(perms);

                item.BasePermissions     = perms;
                item.CurrentPermissions  = perms;
                item.NextPermissions     = rootpart.NextOwnerMask & perms;
                item.EveryOnePermissions = rootpart.EveryoneMask & perms;
                item.GroupPermissions    = rootpart.GroupMask & perms;

                item.Flags       |= (uint)InventoryItemFlags.ObjectSlamPerm;
                item.CreationDate = Util.UnixTimeSinceEpoch();

                if (m_scene.AddInventoryItem(item))
                {
                    remoteClient.SendInventoryItemCreateUpdate(item, 0);
                }
                else
                {
                    if (m_dialogModule != null)
                    {
                        m_dialogModule.SendAlertToUser(remoteClient, "Cannot buy now. Your inventory is unavailable");
                    }
                    return(false);
                }
                break;

            case 3: // Sell contents
                List <UUID> invList = rootpart.Inventory.GetInventoryList();

                bool okToSell = true;

                foreach (UUID invID in invList)
                {
                    TaskInventoryItem item1 = rootpart.Inventory.GetInventoryItem(invID);
                    if ((item1.CurrentPermissions &
                         (uint)PermissionMask.Transfer) == 0)
                    {
                        okToSell = false;
                        break;
                    }
                }

                if (!okToSell)
                {
                    if (m_dialogModule != null)
                    {
                        m_dialogModule.SendAlertToUser(
                            remoteClient, "This item's inventory doesn't appear to be for sale");
                    }
                    return(false);
                }

                if (invList.Count > 0)
                {
                    m_scene.MoveTaskInventoryItems(remoteClient.AgentId, rootpart.Name, rootpart, invList);
                }
                break;
            }

            return(true);
        }
コード例 #53
0
ファイル: AssetsRequest.cs プロジェクト: KSLcom/Aurora-Sim
        protected void PreAssetRequestCallback(string fetchedAssetID, object assetType, AssetBase fetchedAsset)
        {
            // Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer
            if (fetchedAsset != null && fetchedAsset.Type == (sbyte) AssetType.Unknown)
            {
                AssetType type = (AssetType) assetType;
                MainConsole.Instance.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}",
                                                fetchedAsset.ID, type);
                fetchedAsset.Type = (sbyte) type;
            }

            AssetRequestCallback(fetchedAssetID, this, fetchedAsset);
        }
コード例 #54
0
ファイル: Backup.cs プロジェクト: x8ball/Aurora-Sim
 private void RetrievedAsset(string id, Object sender, AssetBase asset)
 {
     m_missingAssets.Remove(UUID.Parse(id));
     TarArchiveWriter writer = (TarArchiveWriter)sender;
     if (writer == null)
     {
         if (m_missingAssets.Count == 0)
             m_isArchiving = false;
         return;
     }
     //Add the asset
     WriteAsset(asset, writer);
     if (m_missingAssets.Count == 0)
         m_isArchiving = false;
 }
コード例 #55
0
 public void SendTexture(AssetBase TextureAsset)
 {
 }
コード例 #56
0
        protected void AssetReceived(string id, Object sender, AssetBase asset)
        {
            SceneObjectPart sop = (SceneObjectPart)sender;

            if (sop != null)
            {
                if (asset != null)
                    sop.SculptTextureCallback(asset.FullID, asset);
            }
        }
コード例 #57
0
ファイル: Backup.cs プロジェクト: x8ball/Aurora-Sim
 private void WriteAsset(AssetBase asset, TarArchiveWriter writer)
 {
     writer.WriteFile("assets", asset.Data);
 }
コード例 #58
0
        public AssetMetadata GetMetadata(string id)
        {
            AssetBase asset = Get(id);

            return(asset.Metadata);
        }
コード例 #59
0
 ////////////////////////////////////////////////////////////
 // IImprovedAssetCache
 //
 public void Cache(string assetID, AssetBase asset)
 {
     if (asset != null)
         m_Cache.AddOrUpdate(asset.IDString, asset);
 }
コード例 #60
0
        public byte[] GetData(string id)
        {
            AssetBase asset = Get(id);

            return(asset.Data);
        }