Exemplo n.º 1
0
 public AssetLandmark(AssetBase a)
     : base(a.ID, a.Name, a.TypeAsset, a.CreatorID)
 {
     Data = a.Data;
     Description = a.Description;
     InternData();
 }
Exemplo n.º 2
0
        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;
        }
 /// <summary>
 ///     Create a new Inventory Item
 /// </summary>
 /// <param name="remoteClient"></param>
 /// <param name="creatorData"></param>
 /// <param name="folderID"></param>
 /// <param name="flags"></param>
 /// <param name="callbackID"></param>
 /// <param name="asset"></param>
 /// <param name="invType"></param>
 /// <param name="everyoneMask"></param>
 /// <param name="nextOwnerMask"></param>
 /// <param name="groupMask"></param>
 /// <param name="creationDate"></param>
 /// <param name="creatorID"></param>
 /// <param name="name"></param>
 /// <param name="baseMask"></param>
 /// <param name="currentMask"></param>
 protected void CreateNewInventoryItem(
     IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID, string name, uint flags,
     uint callbackID, AssetBase asset, sbyte invType,
     uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate)
 {
     InventoryItemBase item = new InventoryItemBase
                                  {
                                      Owner = remoteClient.AgentId,
                                      CreatorId = creatorID,
                                      CreatorData = creatorData,
                                      ID = UUID.Random(),
                                      AssetID = asset.ID,
                                      Description = asset.Description,
                                      Name = name,
                                      Flags = flags,
                                      AssetType = asset.Type == -1 ? -1 : asset.Type,
                                      InvType = invType,
                                      Folder = folderID,
                                      CurrentPermissions = currentMask,
                                      NextPermissions = nextOwnerMask,
                                      EveryOnePermissions = everyoneMask,
                                      GroupPermissions = groupMask,
                                      BasePermissions = baseMask,
                                      CreationDate = creationDate
                                  };
     m_scene.InventoryService.AddItemAsync(item,
                                           (itm) =>
                                               { remoteClient.SendInventoryItemCreateUpdate(itm, callbackID); });
 }
        /// <summary>
        ///     Create a new 'link' to another inventory item
        ///     Used in Viewer 2 for appearance.
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="transActionID"></param>
        /// <param name="folderID"></param>
        /// <param name="callbackID"></param>
        /// <param name="description"></param>
        /// <param name="name"></param>
        /// <param name="invType"></param>
        /// <param name="type"></param>
        /// <param name="olditemID"></param>
        protected void HandleLinkInventoryItem(IClientAPI remoteClient, UUID transActionID, UUID folderID,
                                               uint callbackID, string description, string name,
                                               sbyte invType, sbyte type, UUID olditemID)
        {
            //MainConsole.Instance.DebugFormat("[AGENT INVENTORY]: Received request to create inventory item link {0} in folder {1} pointing to {2}", name, folderID, olditemID);

            if (!m_scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId))
                return;

            IScenePresence presence;
            if (m_scene.TryGetScenePresence(remoteClient.AgentId, out presence))
            {
                if (olditemID == AvatarWearable.DEFAULT_EYES_ITEM ||
                    olditemID == AvatarWearable.DEFAULT_BODY_ITEM ||
                    olditemID == AvatarWearable.DEFAULT_HAIR_ITEM ||
                    olditemID == AvatarWearable.DEFAULT_PANTS_ITEM ||
                    olditemID == AvatarWearable.DEFAULT_SHIRT_ITEM ||
                    olditemID == AvatarWearable.DEFAULT_SKIN_ITEM)
                {
                    return;
                }
                AssetBase asset = new AssetBase {ID = olditemID, Type = type, Name = name, Description = description};

                CreateNewInventoryItem(
                    remoteClient, remoteClient.AgentId.ToString(), "", folderID, name, 0, callbackID, asset, invType,
                    (uint) PermissionMask.All, (uint) PermissionMask.All, (uint) PermissionMask.All,
                    (uint) PermissionMask.All, (uint) PermissionMask.All, Util.UnixTimeSinceEpoch());
            }
            else
            {
                MainConsole.Instance.ErrorFormat(
                    "ScenePresence for agent uuid {0} unexpectedly not found in HandleLinkInventoryItem",
                    remoteClient.AgentId);
            }
        }
        /// <summary>
        ///     Resolve a new piece of asset data against stored metadata
        /// </summary>
        /// <param name="assetPath"></param>
        /// <param name="data"></param>
        protected void ResolveAssetData(string assetPath, byte[] data)
        {
            // Right now we're nastily obtaining the UUID from the filename
            string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);

            if (m_metadata.ContainsKey(filename))
            {
                AssetMetadata metadata = m_metadata[filename];

                if (ArchiveConstants.ASSET_TYPE_TO_EXTENSION.ContainsKey(metadata.AssetType))
                {
                    string extension = ArchiveConstants.ASSET_TYPE_TO_EXTENSION[metadata.AssetType];
                    filename = filename.Remove(filename.Length - extension.Length);
                }

                MainConsole.Instance.DebugFormat("[ARCHIVER]: Importing asset {0}", filename);

                AssetBase asset = new AssetBase(filename, metadata.Name, (AssetType) metadata.AssetType, UUID.Zero)
                                      {Description = metadata.Description, Data = data, MetaOnly = false};
                asset.ID = m_cache.Store(asset);
            }
            else
            {
                MainConsole.Instance.ErrorFormat(
                    "[DEARCHIVER]: Tried to dearchive data with filename {0} without any corresponding metadata",
                    assetPath);
            }
        }
 /// <summary>
 ///     The callback made when we request the asset for an object from the asset service.
 /// </summary>
 protected void AssetReceived(string id, Object sender, AssetBase asset)
 {
     lock (this)
     {
         m_requestedObjectAsset = asset;
         m_waitingForObjectAsset = false;
         Monitor.Pulse(this);
     }
 }
Exemplo n.º 7
0
 public void BakedTextureUploaded(byte[] data, out UUID newAssetID)
 {
     //MainConsole.Instance.InfoFormat("[AssetCAPS]: Received baked texture {0}", assetID.ToString());
     AssetBase asset = new AssetBase(UUID.Random(), "Baked Texture", AssetType.Texture, m_AgentID)
                           {Data = data, Flags = AssetFlags.Deletable | AssetFlags.Temporary};
     newAssetID = asset.ID = m_assetService.Store(asset);
     MainConsole.Instance.DebugFormat("[AssetCAPS]: Baked texture new id {0}", newAssetID.ToString());
 }
Exemplo n.º 8
0
        /// <summary>
        /// </summary>
        /// <param name="httpRequest"></param>
        /// <param name="httpResponse"></param>
        /// <param name="textureID"></param>
        /// <param name="format"></param>
        /// <param name="response"></param>
        /// <returns>False for "caller try another codec"; true otherwise</returns>
        private bool FetchTexture(OSHttpRequest httpRequest, OSHttpResponse httpResponse, UUID textureID, string format,
                                  out byte[] response)
        {
            //MainConsole.Instance.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
            AssetBase texture;

            string fullID = textureID.ToString();
            if (format != DefaultFormat)
                fullID = fullID + "-" + format;

            if (!String.IsNullOrEmpty(REDIRECT_URL))
            {
                // Only try to fetch locally cached textures. Misses are redirected
                texture = m_assetService.GetCached(fullID);

                if (texture != null)
                {
                    if (texture.Type != (sbyte) AssetType.Texture && texture.Type != (sbyte) AssetType.Unknown &&
                        texture.Type != (sbyte) AssetType.Simstate)
                    {
                        httpResponse.StatusCode = (int) System.Net.HttpStatusCode.NotFound;
                        response = MainServer.BlankResponse;
                        return true;
                    }
                    WriteTextureData(httpRequest, httpResponse, texture, format);
                }
                else
                {
                    string textureUrl = REDIRECT_URL + textureID.ToString();
                    MainConsole.Instance.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
                    httpResponse.RedirectLocation = textureUrl;
                    response = MainServer.BlankResponse;
                    return true;
                }
            }
            else // no redirect
            {
                // try the cache
                texture = m_assetService.GetCached(fullID);

                if (texture == null)
                {
                    //MainConsole.Instance.DebugFormat("[GETTEXTURE]: texture was not in the cache");

                    // Fetch locally or remotely. Misses return a 404
                    texture = m_assetService.Get(textureID.ToString());

                    if (texture != null)
                    {
                        if (texture.Type != (sbyte) AssetType.Texture && texture.Type != (sbyte) AssetType.Unknown &&
                            texture.Type != (sbyte) AssetType.Simstate)
                        {
                            httpResponse.StatusCode = (int) System.Net.HttpStatusCode.NotFound;
                            response = MainServer.BlankResponse;
                            return true;
                        }
                        if (format == DefaultFormat)
                        {
                            response = WriteTextureData(httpRequest, httpResponse, texture, format);
                            texture = null;
                            return true;
                        }
                        AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, AssetType.Texture,
                                                             texture.CreatorID)
                                                   {Data = ConvertTextureData(texture, format)};
                        if (newTexture.Data.Length == 0)
                        {
                            response = MainServer.BlankResponse;
                            return false; // !!! Caller try another codec, please!
                        }

                        newTexture.Flags = AssetFlags.Collectable | AssetFlags.Temporary;
                        newTexture.ID = m_assetService.Store(newTexture);
                        response = WriteTextureData(httpRequest, httpResponse, newTexture, format);
                        newTexture = null;
                        return true;
                    }
                }
                else // it was on the cache
                {
                    if (texture.Type != (sbyte) AssetType.Texture && texture.Type != (sbyte) AssetType.Unknown &&
                        texture.Type != (sbyte) AssetType.Simstate)
                    {
                        httpResponse.StatusCode = (int) System.Net.HttpStatusCode.NotFound;
                        response = MainServer.BlankResponse;
                        return true;
                    }
                    //MainConsole.Instance.DebugFormat("[GETTEXTURE]: texture was in the cache");
                    response = WriteTextureData(httpRequest, httpResponse, texture, format);
                    texture = null;
                    return true;
                }
            }

            // not found
            MainConsole.Instance.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
            httpResponse.StatusCode = (int) System.Net.HttpStatusCode.NotFound;
            response = MainServer.BlankResponse;
            return true;
        }
        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);
        }
        /// <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);
            }
        }
Exemplo n.º 11
0
        public AvatarAppearance BakeAppearance(UUID agentID, int cof_version)
        {
            AvatarAppearance appearance = m_avatarService.GetAppearance(agentID);
            List<BakeType> pendingBakes = new List<BakeType>();
            InventoryFolderBase cof = m_inventoryService.GetFolderForType(agentID, InventoryType.Unknown, AssetType.CurrentOutfitFolder);
            if (cof.Version < cof_version)
            {
                int i = 0;
                while (i < 10)
                {
                    cof = m_inventoryService.GetFolderForType(agentID, InventoryType.Unknown, AssetType.CurrentOutfitFolder);
                    System.Threading.Thread.Sleep(100);
                    if (cof.Version >= cof_version)
                        break;
                    i++;
                }
            }
            List<InventoryItemBase> items = m_inventoryService.GetFolderItems(agentID, cof.ID);
            foreach (InventoryItemBase itm in items)
                MainConsole.Instance.Warn("[ServerSideAppearance]: Baking " + itm.Name);

            for (int i = 0; i < Textures.Length; i++)
                Textures[i] = new TextureData();

            WearableData alphaWearable = null;
            List<UUID> currentItemIDs = new List<UUID>();
            foreach (InventoryItemBase itm in items)
            {
                if (itm.AssetType == (int)AssetType.Link)
                {
                    UUID assetID = m_inventoryService.GetItemAssetID(agentID, itm.AssetID);
                    if (appearance.Wearables.Any((w) => w.GetItem(assetID) != UUID.Zero))
                    {
                        currentItemIDs.Add(assetID);
                        //if (m_lastInventoryItemIDs.Contains(assetID))
                        //    continue;
                        WearableData wearable = new WearableData();
                        AssetBase asset = m_assetService.Get(assetID.ToString());
                        if (asset != null && asset.TypeAsset != AssetType.Object)
                        {
                            wearable.Asset = new AssetClothing(assetID, asset.Data);
                            if (wearable.Asset.Decode())
                            {
                                wearable.AssetID = assetID;
                                wearable.AssetType = wearable.Asset.AssetType;
                                wearable.WearableType = wearable.Asset.WearableType;
                                wearable.ItemID = itm.AssetID;
                                if (wearable.WearableType == WearableType.Alpha)
                                {
                                    alphaWearable = wearable;
                                    continue;
                                }
                                AppearanceManager.DecodeWearableParams(wearable, ref Textures);
                            }
                        }
                    }
                    else
                    {
                    }
                }
            }
            /*foreach (UUID id in m_lastInventoryItemIDs)
            {
                if (!currentItemIDs.Contains(id))
                {
                    OpenMetaverse.AppearanceManager.WearableData wearable = new OpenMetaverse.AppearanceManager.WearableData();
                    AssetBase asset = m_assetService.Get(id.ToString());
                    if (asset != null && asset.TypeAsset != AssetType.Object)
                    {
                        wearable.Asset = new AssetClothing(id, asset.Data);
                        if (wearable.Asset.Decode())
                        {
                            foreach (KeyValuePair<AvatarTextureIndex, UUID> entry in wearable.Asset.Textures)
                            {
                                int i = (int)entry.Key;

                                Textures[i].Texture = null;
                                Textures[i].TextureID = UUID.Zero;
                            }
                        }
                    }
                }
            }*/
            //m_lastInventoryItemIDs = currentItemIDs;
            for (int i = 0; i < Textures.Length; i++)
            {
                /*if (Textures[i].TextureID == UUID.Zero)
                    continue;
                if (Textures[i].Texture != null)
                    continue;*/
                AssetBase asset = m_assetService.Get(Textures[i].TextureID.ToString());
                if (asset != null)
                {
                    Textures[i].Texture = new AssetTexture(Textures[i].TextureID, asset.Data);
                    Textures[i].Texture.Decode();
                }
            }

            for (int bakedIndex = 0; bakedIndex < AppearanceManager.BAKED_TEXTURE_COUNT; bakedIndex++)
            {
                AvatarTextureIndex textureIndex = AppearanceManager.BakeTypeToAgentTextureIndex((BakeType)bakedIndex);

                if (Textures[(int)textureIndex].TextureID == UUID.Zero)
                {
                    // If this is the skirt layer and we're not wearing a skirt then skip it
                    if (bakedIndex == (int)BakeType.Skirt && appearance.Wearables[(int)WearableType.Skirt].Count == 0)
                        continue;

                    pendingBakes.Add((BakeType)bakedIndex);
                }
            }

            int start = Environment.TickCount;
            List<UUID> newBakeIDs = new List<UUID>();
            foreach (BakeType bakeType in pendingBakes)
            {
                UUID assetID = UUID.Zero;
                List<AvatarTextureIndex> textureIndices = OpenMetaverse.AppearanceManager.BakeTypeToTextures(bakeType);
                Baker oven = new Baker(bakeType);

                for (int i = 0; i < textureIndices.Count; i++)
                {
                    int textureIndex = (int)textureIndices[i];
                    TextureData texture = Textures[(int)textureIndex];
                    texture.TextureIndex = (AvatarTextureIndex)textureIndex;
                    if (alphaWearable != null)
                    {
                        if (alphaWearable.Asset.Textures.ContainsKey(texture.TextureIndex) &&
                            alphaWearable.Asset.Textures[texture.TextureIndex] != UUID.Parse("5748decc-f629-461c-9a36-a35a221fe21f"))
                        {
                            assetID = alphaWearable.Asset.Textures[texture.TextureIndex];
                            goto bake_complete;
                        }
                    }

                    oven.AddTexture(texture);
                }

                oven.Bake();
                byte[] assetData = oven.BakedTexture.AssetData;
                AssetBase newBakedAsset = new AssetBase(UUID.Random());
                newBakedAsset.Data = assetData;
                newBakedAsset.TypeAsset = AssetType.Texture;
                newBakedAsset.Name = "ServerSideAppearance Texture";
                newBakedAsset.Flags = AssetFlags.Deletable | AssetFlags.Collectable | AssetFlags.Rewritable | AssetFlags.Temporary;
                if (appearance.Texture.FaceTextures[(int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType)].TextureID != UUID.Zero)
                    m_assetService.Delete(appearance.Texture.FaceTextures[(int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType)].TextureID);
                assetID = m_assetService.Store(newBakedAsset);
            bake_complete:
                newBakeIDs.Add(assetID);
                MainConsole.Instance.WarnFormat("[ServerSideAppearance]: Baked {0}", assetID);
                int place = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType);
                appearance.Texture.FaceTextures[place].TextureID = assetID;
            }

            MainConsole.Instance.ErrorFormat("[ServerSideAppearance]: Baking took {0} ms", (Environment.TickCount - start));

            appearance.Serial = cof_version + 1;
            cof = m_inventoryService.GetFolderForType(agentID, InventoryType.Unknown, AssetType.CurrentOutfitFolder);
            if (cof.Version > cof_version)
            {
                //it changed during the baking... kill it with fire!
                return null;
            }
            m_avatarService.SetAppearance(agentID, appearance);
            return appearance;
        }
 ////////////////////////////////////////////////////////////
 // IImprovedAssetCache
 //
 public void Cache(string assetID, AssetBase asset)
 {
     if (asset != null)
         m_Cache.AddOrUpdate(asset.IDString, asset);
 }
        /// <summary>
        /// </summary>
        /// <param name="assetName"></param>
        /// <param name="assetDescription"></param>
        /// <param name="assetID"></param>
        /// <param name="inventoryItem"></param>
        /// <param name="parentFolder"></param>
        /// <param name="data"></param>
        /// <param name="inventoryType"></param>
        /// <param name="assetType"></param>
        /// <param name="everyone_mask"></param>
        /// <param name="group_mask"></param>
        /// <param name="next_owner_mask"></param>
        public UUID UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType, uint everyone_mask, uint group_mask, uint next_owner_mask)
        {
            sbyte assType = 0;
            sbyte inType = 0;

            switch (inventoryType)
            {
                case "sound":
                    inType = 1;
                    assType = 1;
                    break;
                case "animation":
                    inType = 19;
                    assType = 20;
                    break;
                case "snapshot":
                    inType = 15;
                    assType = 0;
                    break;
                case "wearable":
                    inType = 18;
                    switch (assetType)
                    {
                        case "bodypart":
                            assType = 13;
                            break;
                        case "clothing":
                            assType = 5;
                            break;
                    }
                    break;
                case "object":
                    {
                        inType = (sbyte) InventoryType.Object;
                        assType = (sbyte) AssetType.Object;

                        List<Vector3> positions = new List<Vector3>();
                        List<Quaternion> rotations = new List<Quaternion>();
                        OSDMap request = (OSDMap) OSDParser.DeserializeLLSDXml(data);
                        OSDArray instance_list = (OSDArray) request["instance_list"];
                        OSDArray mesh_list = (OSDArray) request["mesh_list"];
                        OSDArray texture_list = (OSDArray) request["texture_list"];
                        SceneObjectGroup grp = null;

                        List<UUID> textures = new List<UUID>();
                        foreach (
                            AssetBase textureAsset in
                                texture_list.Select(t => new AssetBase(UUID.Random(), assetName, AssetType.Texture,
                                                                       m_agentID) { Data = t.AsBinary() }))
                        {
                            textureAsset.ID = m_assetService.Store(textureAsset);
                            textures.Add(textureAsset.ID);
                        }

                        InventoryFolderBase meshFolder = m_inventoryService.GetFolderForType(m_agentID,
                                                                                             InventoryType.Mesh,
                                                                                             AssetType.Mesh);
                        for (int i = 0; i < mesh_list.Count; i++)
                        {
                            PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                            Primitive.TextureEntry textureEntry =
                                new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
                            OSDMap inner_instance_list = (OSDMap) instance_list[i];

                            OSDArray face_list = (OSDArray) inner_instance_list["face_list"];
                            for (uint face = 0; face < face_list.Count; face++)
                            {
                                OSDMap faceMap = (OSDMap) face_list[(int) face];
                                Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
                                if (faceMap.ContainsKey("fullbright"))
                                    f.Fullbright = faceMap["fullbright"].AsBoolean();
                                if (faceMap.ContainsKey("diffuse_color"))
                                    f.RGBA = faceMap["diffuse_color"].AsColor4();

                                int textureNum = faceMap["image"].AsInteger();
                                float imagerot = faceMap["imagerot"].AsInteger();
                                float offsets = (float) faceMap["offsets"].AsReal();
                                float offsett = (float) faceMap["offsett"].AsReal();
                                float scales = (float) faceMap["scales"].AsReal();
                                float scalet = (float) faceMap["scalet"].AsReal();

                                if (imagerot != 0)
                                    f.Rotation = imagerot;
                                if (offsets != 0)
                                    f.OffsetU = offsets;
                                if (offsett != 0)
                                    f.OffsetV = offsett;
                                if (scales != 0)
                                    f.RepeatU = scales;
                                if (scalet != 0)
                                    f.RepeatV = scalet;
                                f.TextureID = textures.Count > textureNum
                                                  ? textures[textureNum]
                                                  : Primitive.TextureEntry.WHITE_TEXTURE;
                                textureEntry.FaceTextures[face] = f;
                            }
                            pbs.TextureEntry = textureEntry.GetBytes();

                            AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, AssetType.Mesh, m_agentID)
                                                      {Data = mesh_list[i].AsBinary()};
                            meshAsset.ID = m_assetService.Store(meshAsset);

                            if (meshFolder == null)
                            {
                                m_inventoryService.CreateUserInventory(m_agentID, false);
                                meshFolder = m_inventoryService.GetFolderForType(m_agentID, InventoryType.Mesh,
                                                                                 AssetType.Mesh);
                            }

                            InventoryItemBase itemBase = new InventoryItemBase(UUID.Random(), m_agentID)
                                                             {
                                                                 AssetType = (sbyte) AssetType.Mesh,
                                                                 AssetID = meshAsset.ID,
                                                                 CreatorId = m_agentID.ToString(),
                                                                 Folder = meshFolder.ID,
                                                                 InvType = (int) InventoryType.Texture,
                                                                 Name = "(Mesh) - " + assetName,
                                                                 CurrentPermissions = (uint) PermissionMask.All,
                                                                 BasePermissions = (uint) PermissionMask.All,
                                                                 EveryOnePermissions = everyone_mask,
                                                                 GroupPermissions = group_mask,
                                                                 NextPermissions = next_owner_mask
                                                             };
                            //Bad... but whatever
                            m_inventoryService.AddItem(itemBase);

                            pbs.SculptEntry = true;
                            pbs.SculptTexture = meshAsset.ID;
                            pbs.SculptType = (byte) SculptType.Mesh;
                            pbs.SculptData = meshAsset.Data;

                            Vector3 position = inner_instance_list["position"].AsVector3();
                            Vector3 scale = inner_instance_list["scale"].AsVector3();
                            Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();

                            int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
                            int material = inner_instance_list["material"].AsInteger();
                            int mesh = inner_instance_list["mesh"].AsInteger();

                            SceneObjectPart prim = new SceneObjectPart(m_agentID, pbs, position, Quaternion.Identity,
                                                                       Vector3.Zero, assetName)
                                                       {Scale = scale, AbsolutePosition = position};

                            rotations.Add(rotation);
                            positions.Add(position);
                            prim.UUID = UUID.Random();
                            prim.CreatorID = m_agentID;
                            prim.OwnerID = m_agentID;
                            prim.GroupID = UUID.Zero;
                            prim.LastOwnerID = m_agentID;
                            prim.CreationDate = Util.UnixTimeSinceEpoch();
                            prim.Name = assetName;
                            prim.Description = "";
                            prim.PhysicsType = (byte) physicsShapeType;

                            prim.BaseMask = (uint) PermissionMask.All;
                            prim.EveryoneMask = everyone_mask;
                            prim.NextOwnerMask = next_owner_mask;
                            prim.GroupMask = group_mask;
                            prim.OwnerMask = (uint) PermissionMask.All;

                            if (grp == null)
                                grp = new SceneObjectGroup(prim, null);
                            else
                                grp.AddChild(prim, i + 1);
                            grp.RootPart.IsAttachment = false;
                        }
                        if (grp.ChildrenList.Count > 1) //Fix first link #
                            grp.RootPart.LinkNum++;

                        Vector3 rootPos = positions[0];
                        grp.SetAbsolutePosition(false, rootPos);
                        for (int i = 0; i < positions.Count; i++)
                        {
                            Vector3 offset = positions[i] - rootPos;
                            grp.ChildrenList[i].SetOffsetPosition(offset);
                        }
                        //grp.Rotation = rotations[0];
                        for (int i = 0; i < rotations.Count; i++)
                        {
                            if (i != 0)
                                grp.ChildrenList[i].SetRotationOffset(false, rotations[i], false);
                        }
                        grp.UpdateGroupRotationR(rotations[0]);
                        data = Encoding.ASCII.GetBytes(grp.ToXml2());
                    }
                    break;
            }
            AssetBase asset = new AssetBase(assetID, assetName, (AssetType)assType, m_agentID) { Data = data };
            asset.ID = m_assetService.Store(asset);
            assetID = asset.ID;

            InventoryItemBase item = new InventoryItemBase
                                         {
                                             Owner = m_agentID,
                                             CreatorId = m_agentID.ToString(),
                                             ID = inventoryItem,
                                             AssetID = asset.ID,
                                             Description = assetDescription,
                                             Name = assetName,
                                             AssetType = assType,
                                             InvType = inType,
                                             Folder = parentFolder,
                                             CurrentPermissions = (uint) PermissionMask.All,
                                             BasePermissions = (uint) PermissionMask.All,
                                             EveryOnePermissions = everyone_mask,
                                             NextPermissions = next_owner_mask,
                                             GroupPermissions = group_mask,
                                             CreationDate = Util.UnixTimeSinceEpoch()
                                         };

            m_inventoryService.AddItem(item);

            return assetID;
        }
        private AssetBase SaveNonBinaryAssets(UUID key, AssetBase asset, Dictionary<UUID, UUID> assetBinaryChangeRecord)
        {
            if (!asset.HasBeenSaved)
            {
                string stringData = Utils.BytesToString(asset.Data);
                MatchCollection mc = Regex.Matches(stringData, sPattern);
                bool didChange = false;
                if (mc.Count >= 1)
                {
                    foreach (Match match in mc)
                    {
                        UUID thematch = new UUID(match.Value);
                        UUID newvalue = thematch;
                        if ((thematch == UUID.Zero) || (thematch == key)) continue;
                        if (assetNonBinaryCollection.ContainsKey(thematch))
                        {
                            AssetBase subasset = assetNonBinaryCollection[thematch];
                            if (!subasset.HasBeenSaved)
                                subasset = SaveNonBinaryAssets(thematch, subasset, assetBinaryChangeRecord);
                            newvalue = subasset.ID;
                        }
                        else if (assetBinaryChangeRecord.ContainsKey(thematch))
                            newvalue = assetBinaryChangeRecord[thematch];

                        if (thematch == newvalue) continue;
                        stringData = stringData.Replace(thematch.ToString(), newvalue.ToString());
                        didChange = true;
                    }
                    if (didChange)
                    {
                        asset.Data = Utils.StringToBytes(stringData);
                        // so it doesn't try to find the old file
                        asset.LastHashCode = asset.HashCode;
                    }
                }
                asset.ID = m_scene.AssetService.Store(asset);
                asset.HasBeenSaved = true;
            }
            if (assetNonBinaryCollection.ContainsKey(key))
                assetNonBinaryCollection[key] = asset;
            return asset;
        }
        /// <summary>
        ///     Load an asset
        /// </summary>
        /// <param name="assetPath"></param>
        /// <param name="data"></param>
        /// <param name="asset"> </param>
        /// <returns>true if asset was successfully loaded, false otherwise</returns>
        private bool LoadAsset(string assetPath, byte[] data, out AssetBase asset)
        {
            string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length);
            int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR);

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

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

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

                if (assetType == AssetType.Unknown)
                    MainConsole.Instance.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type",
                                                    data.Length, uuid);
                asset = new AssetBase(UUID.Parse(uuid), String.Empty, assetType, UUID.Zero) {Data = data};
                return true;
            }
            MainConsole.Instance.ErrorFormat(
                "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}",
                assetPath, extension);
            asset = null;
            return false;
        }
        /// <summary>
        ///     Cache asset.
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="asset">
        ///     The asset that is being cached.
        /// </param>
        public void Cache(string assetID, AssetBase asset)
        {
            if (asset != null)
            {
            //                MainConsole.Instance.DebugFormat("[CENOME ASSET CACHE]: Caching asset {0}", asset.IDString);

                long size = asset.Data != null ? asset.Data.Length : 1;
                m_cache.Set(asset.IDString, asset, size);
                m_cachedCount++;
            }
        }
Exemplo n.º 17
0
        private byte[] ConvertTextureData(AssetBase texture, string format)
        {
            MainConsole.Instance.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format);
            byte[] data = new byte[0];

            MemoryStream imgstream = new MemoryStream();
            Image image = null;

            try
            {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
                image = m_j2kDecoder.DecodeToImage(texture.Data);
                if (image == null)
                    return data;
                // Save to bitmap
                image = new Bitmap(image);

                EncoderParameters myEncoderParameters = new EncoderParameters();
                myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);

                // Save bitmap to stream
                ImageCodecInfo codec = GetEncoderInfo("image/" + format);
                if (codec != null)
                {
                    image.Save(imgstream, codec, myEncoderParameters);
                    // Write the stream to a byte array for output
                    data = imgstream.ToArray();
                }
                else
                    MainConsole.Instance.WarnFormat("[GETTEXTURE]: No such codec {0}", format);
            }
            catch (Exception e)
            {
                MainConsole.Instance.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID,
                                                format, e.Message);
            }
            finally
            {
                // Reclaim memory, these are unmanaged resources
                // If we encountered an exception, one or more of these will be null

                if (image != null)
                    image.Dispose();
                image = null;

                imgstream.Close();
                imgstream = null;
            }

            return data;
        }
Exemplo n.º 18
0
        public virtual UUID Store(AssetBase asset)
        {
            object remoteValue = DoRemoteByURL("AssetServerURI", asset);
            if (remoteValue != null || m_doRemoteOnly)
            {
                if (remoteValue == null)
                    return UUID.Zero;
                asset.ID = (UUID) remoteValue;
            }
            else
                asset.ID = m_database.Store(asset);
            IImprovedAssetCache cache = m_registry.RequestModuleInterface<IImprovedAssetCache>();
            if (doDatabaseCaching && cache != null && asset != null && asset.Data != null && asset.Data.Length != 0)
            {
                cache.Expire(asset.ID.ToString());
                cache.Cache(asset.ID.ToString(), asset);
            }

            return asset != null ? asset.ID : UUID.Zero;
        }
Exemplo n.º 19
0
        private byte[] WriteTextureData(OSHttpRequest request, OSHttpResponse response, AssetBase texture, string format)
        {
            string range = request.Headers.GetOne("Range");
            //MainConsole.Instance.DebugFormat("[GETTEXTURE]: Range {0}", range);
            if (!String.IsNullOrEmpty(range)) // JP2's only
            {
                // Range request
                int start, end;
                if (TryParseRange(range, out start, out end))
                {
                    // Before clamping start make sure we can satisfy it in order to avoid
                    // sending back the last byte instead of an error status
                    if (start >= texture.Data.Length)
                    {
                        response.StatusCode = (int) System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
                        return MainServer.BlankResponse;
                    }
                    else
                    {
                        // Handle the case where portions of the range are missing.
                        if (start == -1)
                            start = 0;
                        if (end == -1)
                            end = int.MaxValue;

                        end = Utils.Clamp(end, 0, texture.Data.Length - 1);
                        start = Utils.Clamp(start, 0, end);
                        int len = end - start + 1;

                        //MainConsole.Instance.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);

                        if (len < texture.Data.Length)
                            response.StatusCode = (int) System.Net.HttpStatusCode.PartialContent;
                        else
                            response.StatusCode = (int) System.Net.HttpStatusCode.OK;

                        response.ContentType = texture.TypeString;
                        response.AddHeader("Content-Range",
                                           String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
                        byte[] array = new byte[len];
                        Array.Copy(texture.Data, start, array, 0, len);
                        return array;
                    }
                }
                else
                {
                    MainConsole.Instance.Warn("[GETTEXTURE]: Malformed Range header: " + range);
                    response.StatusCode = (int) System.Net.HttpStatusCode.BadRequest;
                    return MainServer.BlankResponse;
                }
            }
            else // JP2's or other formats
            {
                // Full content request
                response.StatusCode = (int) System.Net.HttpStatusCode.OK;
                response.ContentType = texture.TypeString;
                if (format == DefaultFormat)
                    response.ContentType = texture.TypeString;
                else
                    response.ContentType = "image/" + format;
                return texture.Data;
            }
        }
        /// <summary>
        ///     Update what the avatar is wearing using an item from their inventory.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="e"></param>
        public void AvatarIsWearing(IClientAPI client, AvatarWearingArgs e)
        {
            IScenePresence sp = m_scene.GetScenePresence(client.AgentId);
            if (sp == null)
            {
                MainConsole.Instance.WarnFormat("[AvatarFactory]: AvatarIsWearing unable to find presence for {0}",
                                                client.AgentId);
                return;
            }

            MainConsole.Instance.DebugFormat("[AvatarFactory]: AvatarIsWearing called for {0}", client.AgentId);

            // operate on a copy of the appearance so we don't have to lock anything
            IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule>();
            AvatarAppearance avatAppearance = new AvatarAppearance(appearance.Appearance, false);

            #region Teen Mode Stuff

            IOpenRegionSettingsModule module = m_scene.RequestModuleInterface<IOpenRegionSettingsModule>();

            bool NeedsRebake = false;
            if (module != null && module.EnableTeenMode)
            {
                foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
                {
                    if (wear.Type == 10 & wear.ItemID == UUID.Zero && module.DefaultUnderpants != UUID.Zero)
                    {
                        NeedsRebake = true;
                        wear.ItemID = module.DefaultUnderpants;
                        InventoryItemBase item = new InventoryItemBase(UUID.Random())
                        {
                            InvType = (int)InventoryType.Wearable,
                            AssetType = (int)AssetType.Clothing,
                            Name = "Default Underpants",
                            Folder =
                                m_scene.InventoryService.GetFolderForType(client.AgentId,
                                                                          InventoryType.
                                                                              Wearable,
                                                                          AssetType.
                                                                              Clothing).ID,
                            Owner = client.AgentId,
                            CurrentPermissions = 0,
                            CreatorId = UUID.Zero.ToString(),
                            AssetID = module.DefaultUnderpants
                        };
                        //Locked
                        client.SendInventoryItemCreateUpdate(item, 0);
                    }
                    else if (wear.Type == 10 & wear.ItemID == UUID.Zero)
                    {
                        NeedsRebake = true;
                        InventoryItemBase item = new InventoryItemBase(UUID.Random())
                        {
                            InvType = (int)InventoryType.Wearable,
                            AssetType = (int)AssetType.Clothing,
                            Name = "Default Underpants",
                            Folder =
                                m_scene.InventoryService.GetFolderForType(client.AgentId,
                                                                          InventoryType.
                                                                              Wearable,
                                                                          AssetType.
                                                                              Clothing).ID,
                            Owner = client.AgentId,
                            CurrentPermissions = 0
                        };
                        //Locked
                        if (m_underPantsUUID == UUID.Zero)
                        {
                            m_underPantsUUID = UUID.Random();
                            AssetBase asset = new AssetBase(m_underPantsUUID, "Default Underpants", AssetType.Clothing,
                                                            UUID.Zero) { Data = Utils.StringToBytes(m_defaultUnderPants) };
                            asset.ID = m_scene.AssetService.Store(asset);
                            m_underPantsUUID = asset.ID;
                        }
                        item.CreatorId = UUID.Zero.ToString();
                        item.AssetID = m_underPantsUUID;
                        m_scene.InventoryService.AddItemAsync(item, null);
                        client.SendInventoryItemCreateUpdate(item, 0);
                        wear.ItemID = item.ID;
                    }
                    if (wear.Type == 11 && wear.ItemID == UUID.Zero && module.DefaultUndershirt != UUID.Zero)
                    {
                        NeedsRebake = true;
                        wear.ItemID = module.DefaultUndershirt;
                        InventoryItemBase item = new InventoryItemBase(UUID.Random())
                        {
                            InvType = (int)InventoryType.Wearable,
                            AssetType = (int)AssetType.Clothing,
                            Name = "Default Undershirt",
                            Folder =
                                m_scene.InventoryService.GetFolderForType(client.AgentId,
                                                                          InventoryType.
                                                                              Wearable,
                                                                          AssetType.
                                                                              Clothing).ID,
                            Owner = client.AgentId,
                            CurrentPermissions = 0,
                            CreatorId = UUID.Zero.ToString(),
                            AssetID = module.DefaultUndershirt
                        };
                        //Locked
                        client.SendInventoryItemCreateUpdate(item, 0);
                    }
                    else if (wear.Type == 11 & wear.ItemID == UUID.Zero)
                    {
                        NeedsRebake = true;
                        InventoryItemBase item = new InventoryItemBase(UUID.Random())
                        {
                            InvType = (int)InventoryType.Wearable,
                            AssetType = (int)AssetType.Clothing,
                            Name = "Default Undershirt",
                            Folder =
                                m_scene.InventoryService.GetFolderForType(client.AgentId,
                                                                          InventoryType.
                                                                              Wearable,
                                                                          AssetType.
                                                                              Clothing).ID,
                            Owner = client.AgentId,
                            CurrentPermissions = 0
                        };
                        //Locked
                        if (m_underShirtUUID == UUID.Zero)
                        {
                            m_underShirtUUID = UUID.Random();
                            AssetBase asset = new AssetBase(m_underShirtUUID, "Default Undershirt", AssetType.Clothing,
                                                            UUID.Zero) { Data = Utils.StringToBytes(m_defaultUnderShirt) };
                            asset.ID = m_scene.AssetService.Store(asset);
                            m_underShirtUUID = asset.ID;
                        }
                        item.CreatorId = UUID.Zero.ToString();
                        item.AssetID = m_underShirtUUID;
                        m_scene.InventoryService.AddItemAsync(item, null);
                        client.SendInventoryItemCreateUpdate(item, 0);
                        wear.ItemID = item.ID;
                    }
                }
            }

            #endregion

            foreach (
                AvatarWearingArgs.Wearable wear in e.NowWearing.Where(wear => wear.Type < AvatarWearable.MAX_WEARABLES))
            {
                avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero);
            }

            avatAppearance.GetAssetsFrom(appearance.Appearance);

            // This could take awhile since it needs to pull inventory
            SetAppearanceAssets(sp.UUID, e.NowWearing, appearance.Appearance, ref avatAppearance);

            // could get fancier with the locks here, but in the spirit of "last write wins"
            // this should work correctly, also, we don't need to send the appearance here
            // since the "iswearing" will trigger a new set of visual param and baked texture changes
            // when those complete, the new appearance will be sent
            appearance.Appearance = avatAppearance;

            //This only occurs if something has been forced on afterwards (teen mode stuff)
            if (NeedsRebake)
            {
                //Tell the client about the new things it is wearing
                sp.ControllingClient.SendWearables(appearance.Appearance.Wearables, appearance.Appearance.Serial);
                //Then forcefully tell it to rebake
                foreach (
                    Primitive.TextureEntryFace face in
                        appearance.Appearance.Texture.FaceTextures.Select(t => (t)).Where(face => face != null))
                {
                    sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID);
                }
            }

            QueueAppearanceSave(sp.UUID);
            //Send the wearables HERE so that the client knows what it is wearing
            //sp.ControllingClient.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial);
            //Do not save or send the appearance! The client loops back and sends a bunch of SetAppearance
            //  (handled above) and that takes care of it
        }
        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);
            }
        }
Exemplo n.º 22
0
            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);
                    }
                }
            }
Exemplo n.º 23
0
 private void RetrievedAsset(string id, Object sender, AssetBase asset)
 {
     TarArchiveWriter writer = (TarArchiveWriter) sender;
     //Add the asset
     WriteAsset(id, asset, writer);
     m_missingAssets.Remove(UUID.Parse(id));
     if (m_missingAssets.Count == 0)
         m_isArchiving = false;
 }
Exemplo n.º 24
0
 private void WriteAsset(string id, AssetBase asset, TarArchiveWriter writer)
 {
     if (asset != null)
         writer.WriteFile("assets/" + asset.ID, OSDParser.SerializeJsonString(asset.ToOSD()));
     else
         MainConsole.Instance.WarnFormat("Could not find asset {0}", id);
 }
Exemplo n.º 25
0
 public void AddAsset(AssetBase asset)
 {
     if (asset != null && asset.Data != null)
     {
         if (asset.Type == (sbyte) AssetType.Texture)
         {
             texturesInCache++;
             // This could have been a pull stat, though there was originally a nebulous idea to measure flow rates
             textureCacheMemoryUsage += asset.Data.Length;
         }
         else
         {
             assetsInCache++;
             assetCacheMemoryUsage += asset.Data.Length;
         }
     }
     else
         assetServiceRequestFailures++;
 }
        public void CreateMapTileAsync(object worthless)
        {
            IMapImageGenerator terrain = m_scene.RequestModuleInterface<IMapImageGenerator>();

            if (terrain == null)
                return;

            byte[] terraindata, mapdata;
            terrain.CreateMapTile(out terraindata, out mapdata);
            if (terraindata != null)
            {
                if (m_scene.RegionInfo.RegionSettings.TerrainMapImageID != UUID.Zero)
                    m_scene.RegionInfo.RegionSettings.TerrainMapImageID =
                        m_scene.AssetService.UpdateContent(m_scene.RegionInfo.RegionSettings.TerrainMapImageID,
                                                           terraindata);
                if (m_scene.RegionInfo.RegionSettings.TerrainMapImageID == UUID.Zero)
                    //Do not optimize away! UpdateContent can fail sometimes!
                {
                    AssetBase Terrainasset = new AssetBase(
                        UUID.Random(),
                        "terrainMapImage_" + m_scene.RegionInfo.RegionID.ToString(),
                        AssetType.Simstate,
                        m_scene.RegionInfo.RegionID)
                                                 {
                                                     Data = terraindata,
                                                     Description = m_scene.RegionInfo.RegionName,
                                                     Flags =
                                                         AssetFlags.Deletable | AssetFlags.Rewritable |
                                                         AssetFlags.Maptile
                                                 };
                    m_scene.RegionInfo.RegionSettings.TerrainMapImageID = m_scene.AssetService.Store(Terrainasset);
                }
            }

            if (mapdata != null)
            {
                if (m_scene.RegionInfo.RegionSettings.TerrainImageID != UUID.Zero)
                    m_scene.RegionInfo.RegionSettings.TerrainImageID =
                        m_scene.AssetService.UpdateContent(m_scene.RegionInfo.RegionSettings.TerrainImageID, mapdata);
                if (m_scene.RegionInfo.RegionSettings.TerrainImageID == UUID.Zero)
                    //Do not optimize away! UpdateContent can fail sometimes!
                {
                    AssetBase Mapasset = new AssetBase(
                        UUID.Random(),
                        "terrainImage_" + m_scene.RegionInfo.RegionID.ToString(),
                        AssetType.Simstate,
                        m_scene.RegionInfo.RegionID)
                                             {
                                                 Data = mapdata,
                                                 Description = m_scene.RegionInfo.RegionName,
                                                 Flags =
                                                     AssetFlags.Deletable | AssetFlags.Rewritable | AssetFlags.Maptile
                                             };
                    m_scene.RegionInfo.RegionSettings.TerrainImageID = m_scene.AssetService.Store(Mapasset);
                }
            }

            byte[] overlay = GenerateOverlay();
            if (overlay != null)
            {
                if (m_scene.RegionInfo.RegionSettings.ParcelMapImageID != UUID.Zero)
                    m_scene.RegionInfo.RegionSettings.ParcelMapImageID =
                        m_scene.AssetService.UpdateContent(m_scene.RegionInfo.RegionSettings.ParcelMapImageID, overlay);
                if (m_scene.RegionInfo.RegionSettings.ParcelMapImageID == UUID.Zero)
                    //Do not optimize away! UpdateContent can fail sometimes!
                {
                    AssetBase Parcelasset = new AssetBase(
                        UUID.Random(),
                        "terrainMapImage_" + m_scene.RegionInfo.RegionID.ToString(),
                        AssetType.Simstate,
                        m_scene.RegionInfo.RegionID)
                                                {
                                                    Data = overlay,
                                                    Description = m_scene.RegionInfo.RegionName,
                                                    Flags =
                                                        AssetFlags.Deletable | AssetFlags.Rewritable |
                                                        AssetFlags.Maptile
                                                };
                    m_scene.RegionInfo.RegionSettings.ParcelMapImageID = m_scene.AssetService.Store(Parcelasset);
                }
            }
            else
                m_scene.RegionInfo.RegionSettings.ParcelMapImageID = UUID.Zero;

            m_scene.RegionInfo.RegionSettings.TerrainMapLastRegenerated = DateTime.Now;

            //Update the grid map
            IGridRegisterModule gridRegModule = m_scene.RequestModuleInterface<IGridRegisterModule>();
            if (gridRegModule != null)
                gridRegModule.UpdateGridRegion(m_scene);
        }
        /// <summary>
        ///     Rez a script into a prim's inventory, either ex nihilo or from an existing avatar inventory
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="transactionID"></param>
        /// <param name="localID"></param>
        /// <param name="itemBase"></param>
        protected void RezScript(IClientAPI remoteClient, InventoryItemBase itemBase, UUID transactionID, uint localID)
        {
            UUID itemID = itemBase.ID;
            UUID copyID = UUID.Random();

            if (itemID != UUID.Zero) // transferred from an avatar inventory to the prim's inventory
            {
                //Might be a library item, use UUID.Zero
                InventoryItemBase item = m_scene.InventoryService.GetItem(UUID.Zero, itemID);

                if (item != null)
                {
                    ISceneChildEntity part = m_scene.GetSceneObjectPart(localID);
                    if (part != null)
                    {
                        if (!m_scene.Permissions.CanEditObjectInventory(part.UUID, remoteClient.AgentId))
                            return;

                        part.ParentEntity.AddInventoryItem(remoteClient, localID, item, copyID);
                        part.Inventory.CreateScriptInstance(copyID, 0, false, 0);

                        //                        MainConsole.Instance.InfoFormat("[PRIMINVENTORY]: " +
                        //                                         "Rezzed script {0} into prim local ID {1} for user {2}",
                        //                                         item.inventoryName, localID, remoteClient.Name);
                        part.GetProperties(remoteClient);
                    }
                    else
                    {
                        MainConsole.Instance.ErrorFormat(
                            "[PRIM INVENTORY]: " +
                            "Could not rez script {0} into prim local ID {1} for user {2}"
                            + " because the prim could not be found in the region!",
                            item.Name, localID, remoteClient.Name);
                    }
                }
                else
                {
                    MainConsole.Instance.ErrorFormat(
                        "[PRIM INVENTORY]: Could not find script inventory item {0} to rez for {1}!",
                        itemID, remoteClient.Name);
                }
            }
            else // script has been rezzed directly into a prim's inventory
            {
                ISceneChildEntity part = m_scene.GetSceneObjectPart(itemBase.Folder);
                if (part == null)
                    return;

                if (!m_scene.Permissions.CanCreateObjectInventory(
                    itemBase.InvType, part.UUID, remoteClient.AgentId))
                    return;

                AssetBase asset = new AssetBase(UUID.Random(), itemBase.Name, (AssetType) itemBase.AssetType,
                                                remoteClient.AgentId)
                                      {
                                          Description = itemBase.Description,
                                          Data = Encoding.ASCII.GetBytes(DefaultLSLScript)
                                      };
                asset.ID = m_scene.AssetService.Store(asset);

                TaskInventoryItem taskItem = new TaskInventoryItem();

                taskItem.ResetIDs(itemBase.Folder);
                taskItem.ParentID = itemBase.Folder;
                taskItem.CreationDate = (uint) itemBase.CreationDate;
                taskItem.Name = itemBase.Name;
                taskItem.Description = itemBase.Description;
                taskItem.Type = itemBase.AssetType;
                taskItem.InvType = itemBase.InvType;
                taskItem.OwnerID = itemBase.Owner;
                taskItem.CreatorID = itemBase.CreatorIdAsUuid;
                taskItem.CreatorData = itemBase.CreatorData;
                taskItem.BasePermissions = itemBase.BasePermissions;
                taskItem.CurrentPermissions = itemBase.CurrentPermissions;
                taskItem.EveryonePermissions = itemBase.EveryOnePermissions;
                taskItem.GroupPermissions = itemBase.GroupPermissions;
                taskItem.NextPermissions = itemBase.NextPermissions;
                taskItem.GroupID = itemBase.GroupID;
                taskItem.GroupPermissions = 0;
                taskItem.Flags = itemBase.Flags;
                taskItem.PermsGranter = UUID.Zero;
                taskItem.PermsMask = 0;
                taskItem.AssetID = asset.ID;
                taskItem.SalePrice = itemBase.SalePrice;
                taskItem.SaleType = itemBase.SaleType;

                part.Inventory.AddInventoryItem(taskItem, false);
                part.GetProperties(remoteClient);

                part.Inventory.CreateScriptInstance(taskItem, 0, false, StateSource.NewRez);
            }
        }
        public void AssetReceived(string id, Object sender, AssetBase asset)
        {
            if (asset != null)
            {
                this.Shape.SculptEntry = true;
                this.Shape.SculptData = asset.Data; //Set the asset data
            }

            bool isMesh = asset == null ? false : (asset.Type == (int) AssetType.Mesh);
            if (isMesh)
                this.Shape.SculptType = (byte) SculptType.Mesh;
            PrimitiveBaseShape shape = Shape.Copy();
            if ((bool) sender && this.PhysActor != null &&
                (asset != null || (this.Shape.SculptData != null && this.Shape.SculptData.Length != 0)))
                //Update physics
            {
                //Get physics to update in a hackish way
                this.PhysActor.Shape = shape;
            }
            this.Shape = shape;
        }
        /// <summary>
        ///     Create a new inventory item.  Called when the client creates a new item directly within their
        ///     inventory (e.g. by selecting a context inventory menu option).
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="transactionID"></param>
        /// <param name="folderID"></param>
        /// <param name="callbackID"></param>
        /// <param name="description"></param>
        /// <param name="name"></param>
        /// <param name="invType"></param>
        /// <param name="assetType"></param>
        /// <param name="wearableType"></param>
        /// <param name="nextOwnerMask"></param>
        /// <param name="creationDate"></param>
        protected void CreateNewInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID,
                                              uint callbackID, string description, string name, sbyte invType,
                                              sbyte assetType,
                                              byte wearableType, uint nextOwnerMask, int creationDate)
        {
            //MainConsole.Instance.DebugFormat("[AGENT INVENTORY]: Received request to create inventory item {0} in folder {1}", name, folderID);

            if (!m_scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId))
                return;

            if (transactionID == UUID.Zero)
            {
                IScenePresence presence;
                if (m_scene.TryGetScenePresence(remoteClient.AgentId, out presence))
                {
                    byte[] data = null;

                    if (invType == (sbyte) InventoryType.Landmark && presence != null)
                    {
                        if (m_scene.Permissions.CanTakeLandmark(remoteClient.AgentId))
                        {
                            data = BuildLandmark(presence);
                        }
                        else
                        {
                            remoteClient.SendAlertMessage("You cannot create a landmark here.");
                        }
                    }
                    if (invType == (sbyte) InventoryType.LSL)
                    {
                        data = Encoding.ASCII.GetBytes(DefaultLSLScript);
                    }
                    if (invType == (sbyte) InventoryType.CallingCard)
                    {
                        return;
                    }
                    if (invType == (sbyte) InventoryType.Notecard)
                    {
                        data = Encoding.ASCII.GetBytes(" ");
                    }
                    if (invType == (sbyte) InventoryType.Gesture)
                    {
                        data = /*Default empty gesture*/ new byte[13]
                                                             {50, 10, 50, 53, 53, 10, 48, 10, 10, 10, 48, 10, 0};
                    }

                    AssetBase asset = new AssetBase(UUID.Random(), name, (AssetType) assetType,
                                                    remoteClient.AgentId) {Data = data, Description = description};
                    asset.ID = m_scene.AssetService.Store(asset);

                    CreateNewInventoryItem(
                        remoteClient, remoteClient.AgentId.ToString(), "", folderID, name, 0, callbackID, asset, invType,
                        (uint) PermissionMask.All, (uint) PermissionMask.All, 0, nextOwnerMask, 0, creationDate);
                }
                else
                {
                    MainConsole.Instance.ErrorFormat(
                        "ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem",
                        remoteClient.AgentId);
                }
            }
            else
            {
                IAgentAssetTransactions agentTransactions = m_scene.RequestModuleInterface<IAgentAssetTransactions>();
                if (agentTransactions != null)
                {
                    agentTransactions.HandleItemCreationFromTransaction(
                        remoteClient, transactionID, folderID, callbackID, description,
                        name, invType, assetType, wearableType, nextOwnerMask);
                }
            }
        }
        /// <summary>
        ///     Update the attachment asset for the new sog details if they have changed.
        /// </summary>
        /// This is essential for preserving attachment attributes such as permission.  Unlike normal scene objects,
        /// these details are not stored on the region.
        /// <param name="remoteClient"></param>
        /// <param name="grp"></param>
        /// <param name="itemID"></param>
        /// <param name="agentID"></param>
        protected UUID UpdateKnownItem(IClientAPI remoteClient, ISceneEntity grp, UUID itemID, UUID agentID)
        {
            if (grp != null)
            {
                if (!grp.HasGroupChanged)
                {
                    //MainConsole.Instance.WarnFormat("[ATTACHMENTS MODULE]: Save request for {0} which is unchanged", grp.UUID);
                    return UUID.Zero;
                }

                //let things like state saves and another async things be performed before we serialize the object
                grp.BackupPreparation();

                MainConsole.Instance.InfoFormat(
                    "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}",
                    grp.UUID, grp.GetAttachmentPoint());

                string sceneObjectXml = SceneEntitySerializer.SceneObjectSerializer.ToOriginalXmlFormat(grp);

                AssetBase asset = new AssetBase(UUID.Random(), grp.Name,
                                                AssetType.Object, remoteClient.AgentId)
                                      {
                                          Description = grp.RootChild.Description,
                                          Data = Utils.StringToBytes(sceneObjectXml)
                                      };
                asset.ID = m_scene.AssetService.Store(asset);

                m_scene.InventoryService.UpdateAssetIDForItem(itemID, asset.ID);

                // this gets called when the agent logs off!
                //remoteClient.SendInventoryItemCreateUpdate(item, 0);

                return asset.ID;
            }
            return UUID.Zero;
        }