public AssetLandmark(AssetBase a) : base(a.ID, a.Name, a.TypeAsset, a.CreatorID) { Data = a.Data; Description = a.Description; InternData(); }
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> /// </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> 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 && // not actually a texture texture.Type != (sbyte)AssetType.Unknown && // .. but valid texture.Type != (sbyte)AssetType.Simstate) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; response = MainServer.BlankResponse; return true; } response = WriteTextureData (httpRequest, httpResponse, texture, format); return true; } else { string textureUrl = REDIRECT_URL + textureID; MainConsole.Instance.Debug ("[AssetCAPS]: Redirecting texture request to " + textureUrl); httpResponse.RedirectLocation = textureUrl; response = MainServer.BlankResponse; return true; } } // 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; texture.Dispose (); return true; } if (format == DefaultFormat) { try { response = WriteTextureData (httpRequest, httpResponse, texture, format); } catch { response = MainServer.BlankResponse; } texture.Dispose (); return true; } AssetBase newTexture = new AssetBase (texture.ID + "-" + format, texture.Name, AssetType.Texture, texture.CreatorID) { Data = ConvertTextureData (texture, format) }; if (newTexture.Data.Length == 0) // unable to convert { response = MainServer.BlankResponse; texture.Dispose (); newTexture.Dispose (); return false; // !!! Caller try another codec, please! } newTexture.Flags = AssetFlags.Collectable | AssetFlags.Temporary; newTexture.ID = m_assetService.Store (newTexture); try { response = WriteTextureData (httpRequest, httpResponse, newTexture, format); } catch { response = MainServer.BlankResponse; } newTexture.Dispose (); texture.Dispose (); return true; } // nothing found... replace with the 'missing_texture" texture // try the cache first texture = m_assetService.GetCached (Constants.MISSING_TEXTURE_ID); if (texture == null) texture = m_assetService.Get (Constants.MISSING_TEXTURE_ID); // not in local cache... if (texture != null) { if (format == DefaultFormat) { MainConsole.Instance.Debug ("[AssetCAPS]: Texture " + textureID + " replaced with default 'missing' texture"); response = WriteTextureData (httpRequest, httpResponse, texture, format); texture.Dispose (); return true; } } // texture not found and we have no 'missing texture'?? // ... or if all else fails... MainConsole.Instance.Warn ("[AssetCAPS]: Texture " + textureID + " not found (no default)"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; response = MainServer.BlankResponse; return true; } // found the texture in 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; } // the best result... //MainConsole.Instance.DebugFormat("[GETTEXTURE]: texture was in the cache"); response = WriteTextureData (httpRequest, httpResponse, texture, format); return true; }
/// <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 (assetData != null) { try { detailTexture[i] = (Bitmap) J2kImage.FromBytes(assetData); } catch (Exception ex) { MainConsole.Instance.Warn("Failed to decode terrain texture " + textureIDs[i] + ": " + 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; }
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); }
public void AbuseTextureUploaded(UUID agentID, UUID assetID, byte[] data) { //MainConsole.Instance.InfoFormat("[AssetCAPS]: Received baked texture {0}", assetID.ToString()); AssetBase asset = new AssetBase(assetID, "Abuse Texture", AssetType.Texture, agentID) { Data = data }; asset.ID = m_Scene.AssetService.Store(asset); MainConsole.Instance.DebugFormat("[AbuseCAPS]: texture new id {0}", assetID.ToString()); }
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, 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); // clear out... these are all redundant? //terraindata = null; //mapdata = null; //overlay = null; //terrain = null; }
public void BakedTextureUploaded (byte [] data, out UUID newAssetID) { //MainConsole.Instance.InfoFormat("[AssetCAPS]: Received baked texture {0}", assetID); 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); }
public virtual UUID Store(AssetBase asset) { if (asset == null) return UUID.Zero; object remoteValue = DoRemoteByURL("AssetServerURI", asset); if (remoteValue != null || m_doRemoteOnly) { if (remoteValue == null) return UUID.Zero; asset.ID = (UUID) remoteValue; } else RedisSetAsset(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; }
/// <summary> /// Create a new asset data structure. /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="assetType"></param> /// <param name="data"></param> /// <param name="creatorID"></param> /// <returns></returns> private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID) { AssetBase asset = new AssetBase(UUID.Random(), name, (AssetType) assetType, UUID.Parse(creatorID)) {Description = description, Data = data ?? new byte[1]}; return asset; }
public UUID Store(AssetBase asset) { StoreAsset(asset); return asset.ID; }
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; }
public virtual UUID SaveAsAsset(List<ISceneEntity> objectGroups, out AssetBase asset) { Vector3 GroupMiddle = Vector3.Zero; string AssetXML = "<groups>"; if (objectGroups.Count == 1) { m_scene.WhiteCoreEventManager.FireGenericEventHandler("DeleteToInventory", objectGroups[0]); AssetXML = objectGroups[0].ToXml2(); } else { foreach (ISceneEntity objectGroup in objectGroups) { Vector3 inventoryStoredPosition = new Vector3 (((objectGroup.AbsolutePosition.X > m_scene.RegionInfo.RegionSizeX) ? m_scene.RegionInfo.RegionSizeX - 1 : objectGroup.AbsolutePosition.X) , (objectGroup.AbsolutePosition.Y > m_scene.RegionInfo.RegionSizeY) ? m_scene.RegionInfo.RegionSizeY - 1 : objectGroup.AbsolutePosition.Y, objectGroup.AbsolutePosition.Z); GroupMiddle += inventoryStoredPosition; Vector3 originalPosition = objectGroup.AbsolutePosition; objectGroup.AbsolutePosition = inventoryStoredPosition; m_scene.WhiteCoreEventManager.FireGenericEventHandler("DeleteToInventory", objectGroup); AssetXML += objectGroup.ToXml2(); objectGroup.AbsolutePosition = originalPosition; } GroupMiddle.X /= objectGroups.Count; GroupMiddle.Y /= objectGroups.Count; GroupMiddle.Z /= objectGroups.Count; AssetXML += "<middle>"; AssetXML += "<mid>" + GroupMiddle.ToRawString() + "</mid>"; AssetXML += "</middle>"; AssetXML += "</groups>"; } asset = CreateAsset( objectGroups[0].Name, objectGroups[0].RootChild.Description, (sbyte) AssetType.Object, Utils.StringToBytes(AssetXML), objectGroups[0].OwnerID.ToString()); asset.ID = m_scene.AssetService.Store(asset); AssetXML = null; return asset.ID; }
/// <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; }
public byte[] RenderMaterialsPostCap(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { MainConsole.Instance.Debug ("[Materials]: POST cap handler"); OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml (request); OSDMap resp = new OSDMap (); OSDMap materialsFromViewer = null; OSDArray respArr = new OSDArray (); if (req.ContainsKey ("Zipped")) { OSD osd; byte[] inBytes = req ["Zipped"].AsBinary (); try { osd = ZDecompressBytesToOsd (inBytes); if (osd != null) { if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries { foreach (OSD elem in (OSDArray)osd) { try { UUID id = new UUID (elem.AsBinary (), 0); AssetBase materialAsset = null; if (m_knownMaterials.ContainsKey (id)) { MainConsole.Instance.Info ("[Materials]: request for known material ID: " + id); OSDMap matMap = new OSDMap (); matMap ["ID"] = elem.AsBinary (); matMap ["Material"] = m_knownMaterials [id]; respArr.Add (matMap); } else if ((materialAsset = m_scene.AssetService.Get (id.ToString ())) != null) { MainConsole.Instance.Info ("[Materials]: request for stored material ID: " + id); OSDMap matMap = new OSDMap (); matMap ["ID"] = elem.AsBinary (); matMap ["Material"] = OSDParser.DeserializeJson (Encoding.UTF8.GetString (materialAsset.Data)); respArr.Add (matMap); } else MainConsole.Instance.Info ("[Materials]: request for UNKNOWN material ID: " + id); } catch (Exception) { // report something here? continue; } } } else if (osd is OSDMap) // request to assign a material { materialsFromViewer = osd as OSDMap; if (materialsFromViewer.ContainsKey ("FullMaterialsPerFace")) { OSD matsOsd = materialsFromViewer ["FullMaterialsPerFace"]; if (matsOsd is OSDArray) { OSDArray matsArr = matsOsd as OSDArray; try { foreach (OSDMap matsMap in matsArr) { // MainConsole.Instance.Debug("[Materials]: processing matsMap: " + OSDParser.SerializeJsonString(matsMap)); uint matLocalID = 0; try { matLocalID = matsMap ["ID"].AsUInteger (); } catch (Exception e) { MainConsole.Instance.Warn ("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message); } // MainConsole.Instance.Debug("[Materials]: matLocalId: " + matLocalID); OSDMap mat = null; if (matsMap.ContainsKey ("Material")) { try { mat = matsMap ["Material"] as OSDMap; } catch (Exception e) { MainConsole.Instance.Warn ("[MaterialsDemoModule]: cannot decode \"Material\" from matsMap: " + e.Message); continue; } } if (mat == null) continue; // MainConsole.Instance.Debug("[Materials]: mat: " + OSDParser.SerializeJsonString(mat)); UUID id = HashOsd (mat); m_knownMaterials [id] = mat; var sop = m_scene.GetSceneObjectPart (matLocalID); if (sop == null) MainConsole.Instance.Debug ("[Materials]: null SOP for localId: " + matLocalID); else { //var te = sop.Shape.Textures; var te = new Primitive.TextureEntry (sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); if (te == null) { MainConsole.Instance.Debug ("[Materials]: null TextureEntry for localId: " + matLocalID); } else { int face = -1; if (matsMap.ContainsKey ("Face")) { face = matsMap ["Face"].AsInteger (); if (te.FaceTextures == null) // && face == 0) { if (te.DefaultTexture == null) MainConsole.Instance.Debug ("[Materials]: te.DefaultTexture is null"); else { //## FixMe ## // comparison always results in 'False' if (te.DefaultTexture.MaterialID == null) // MainConsole.Instance.Debug("[MaterialsDemoModule]: te.DefaultTexture.MaterialID is null"); // else // { te.DefaultTexture.MaterialID = id; // } } } else { if (te.FaceTextures.Length >= face - 1) { if (te.FaceTextures [face] == null) te.DefaultTexture.MaterialID = id; else te.FaceTextures [face].MaterialID = id; } } } else { if (te.DefaultTexture != null) te.DefaultTexture.MaterialID = id; } MainConsole.Instance.Debug ("[Materials]: setting material ID for face " + face + " to " + id); //we cant use sop.UpdateTextureEntry(te); because it filters so do it manually if (sop.ParentEntity != null) { sop.Shape.TextureEntry = te.GetBytes (); sop.TriggerScriptChangedEvent (Changed.TEXTURE); sop.ParentEntity.HasGroupChanged = true; sop.ScheduleUpdate (PrimUpdateFlags.FullUpdate); AssetBase asset = new AssetBase (id, "RenderMaterial", AssetType.Texture, sop.OwnerID) { Data = Encoding.UTF8.GetBytes ( OSDParser.SerializeJsonString (mat)) }; m_scene.AssetService.Store (asset); StoreMaterialsForPart (sop); } } } } } catch (Exception e) { MainConsole.Instance.Warn ("[Materials]: exception processing received material: " + e); } } } } } } catch (Exception e) { MainConsole.Instance.Warn ("[Materials]: exception decoding zipped CAP payload: " + e); //return ""; } MainConsole.Instance.Debug ("[Materials]: knownMaterials.Count: " + m_knownMaterials.Count); } resp ["Zipped"] = ZCompressOSD (respArr, false); string response = OSDParser.SerializeLLSDXmlString (resp); //MainConsole.Instance.Debug("[Materials]: cap request: " + request); MainConsole.Instance.Debug ("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString (req ["Zipped"].AsBinary ())); MainConsole.Instance.Debug ("[Materials]: cap response: " + response); return OSDParser.SerializeLLSDBinary (resp); }
/// <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="everyoneMask"></param> /// <param name="groupMask"></param> /// <param name="nextOwnerMask"></param> public UUID UploadCompleteHandler (string assetName, string assetDescription, UUID assetID, UUID inventoryItem, UUID parentFolder, byte [] data, string inventoryType, string assetType, uint everyoneMask, uint groupMask, uint nextOwnerMask) { 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, FolderType.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, FolderType.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 = everyoneMask, GroupPermissions = groupMask, NextPermissions = nextOwnerMask }; //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 (); // not currently used int material = inner_instance_list["material"].AsInteger(); // not currently used 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 = everyoneMask; prim.NextOwnerMask = nextOwnerMask; prim.GroupMask = groupMask; 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 != null) { // unlikely not to have anything but itis possible 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 = everyoneMask, NextPermissions = nextOwnerMask, GroupPermissions = groupMask, CreationDate = Util.UnixTimeSinceEpoch () }; m_inventoryService.AddItem (item); return assetID; }
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; } } MainConsole.Instance.Warn ("[AssetCAPS]: Malformed Range header: " + range); response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; return MainServer.BlankResponse; } // 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; }
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) { if (MainConsole.Instance != null) MainConsole.Instance.Debug( "[LocalAssetDatabase]: Asset already exists in the db, overwriting - " + asset.ID); Delete(asset.ID, true); InsertAsset(asset, asset.ID); } else { if (MainConsole.Instance != null) MainConsole.Instance.Debug( "[LocalAssetDatabase]: Asset already exists in the db, fixing ID... - " + asset.ID); InsertAsset(asset, UUID.Random()); } } else { InsertAsset(asset, asset.ID); } } catch (Exception e) { if (MainConsole.Instance != null) MainConsole.Instance.ErrorFormat( "[LocalAssetDatabase]: Failure creating asset {0} with name \"{1}\". Error: {2}", asset.ID, asset.Name, e); } return true; }
byte [] ConvertTextureData (AssetBase texture, string format) { MainConsole.Instance.DebugFormat ("[AssetCAPS]: 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 try { 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 ("[AssetCAPS]: No such codec {0}", format); } catch { MainConsole.Instance.ErrorFormat ("[AssetCAPS]: Unable to retrieve codec {0}", format); } myEncoderParameters.Dispose (); } catch (Exception e) { MainConsole.Instance.WarnFormat ("[AssetCAPS]: 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 (); imgstream.Close (); } return data; }
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); } } }
public bool RedisSetAsset(AssetBase asset) { bool duplicate = RedisEnsureConnection((conn) => conn.Exists(DATA_PREFIX + asset.HashCode)); MemoryStream memStream = new MemoryStream(); byte[] data = asset.Data; string hash = asset.HashCode; asset.Data = new byte[0]; ProtoBuf.Serializer.Serialize<AssetBase>(memStream, asset); asset.Data = data; try { //Deduplication... if (duplicate) { if (MainConsole.Instance != null) MainConsole.Instance.Debug("[REDIS ASSET SERVICE]: Found duplicate asset " + asset.IDString + " for " + asset.IDString); //Only set id --> asset, and not the hashcode --> data to de-duplicate RedisEnsureConnection((conn) => conn.Set(asset.IDString, memStream.ToArray())); return true; } RedisEnsureConnection((conn) => { conn.Pipeline((c) => { c.Set(asset.IDString, memStream.ToArray()); c.Set(DATA_PREFIX + hash, data); }); return true; }); return true; } catch { return false; } finally { memStream.Close(); } }
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); }
private static AssetBase LoadAssetFromDataRead(IDataRecord dr) { AssetBase asset = new AssetBase(dr["id"].ToString()) { Name = dr["name"].ToString(), Description = dr["description"].ToString() }; string Flags = dr["asset_flags"].ToString(); if (Flags != "") asset.Flags = (AssetFlags) int.Parse(Flags); string type = dr["assetType"].ToString(); asset.TypeAsset = (AssetType) int.Parse(type); UUID creator; if (UUID.TryParse(dr["creatorID"].ToString(), out creator)) asset.CreatorID = creator; try { object d = dr["data"]; if ((d != null) && (d.ToString() != "")) { asset.Data = (Byte[]) d; asset.MetaOnly = false; } else { asset.MetaOnly = true; asset.Data = new byte[0]; } } catch (Exception ex) { asset.MetaOnly = true; asset.Data = new byte[0]; if (MainConsole.Instance != null) MainConsole.Instance.Error("[LocalAssetDatabase]: Failed to cast data for " + asset.ID + ", " + ex); } if (dr["local"].ToString().Equals("1") || dr["local"].ToString().Equals("true", StringComparison.InvariantCultureIgnoreCase)) asset.Flags |= AssetFlags.Local; string temp = dr["temporary"].ToString(); if (temp != "") { bool tempbool = false; int tempint = 0; if (bool.TryParse(temp, out tempbool)) { if (tempbool) asset.Flags |= AssetFlags.Temporary; } else if (int.TryParse(temp, out tempint)) { if (tempint == 1) asset.Flags |= AssetFlags.Temporary; } } return asset; }
public bool FileSetAsset(AssetBase asset) { FileStream assetStream = null; try { string hash = asset.HashCode; bool duplicate = File.Exists(GetDataPathForID(hash)); byte[] data = asset.Data; asset.Data = new byte[0]; lock (_lock) { assetStream = File.OpenWrite(GetPathForID(asset.IDString)); asset.HashCode = hash; ProtoBuf.Serializer.Serialize<AssetBase>(assetStream, asset); assetStream.SetLength(assetStream.Position); assetStream.Close(); asset.Data = data; //Deduplication... if (duplicate) { //Only set id --> asset, and not the hashcode --> data to deduplicate return true; } File.WriteAllBytes(GetDataPathForID(hash), data); } return true; } catch { return false; } finally { //if (assetStream != null) // assetStream.Close(); } }
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; }
private void InsertAsset(AssetBase asset, UUID assetID) { int now = (int) Utils.DateTimeToUnixTime(DateTime.UtcNow); Dictionary<string, object> row = new Dictionary<string, object>(11); row["id"] = assetID; row["name"] = asset.Name; row["description"] = asset.Description; row["assetType"] = (sbyte) asset.TypeAsset; row["local"] = (asset.Flags & AssetFlags.Local) == AssetFlags.Local; row["temporary"] = (asset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary; row["create_time"] = now; row["access_time"] = now; row["asset_flags"] = (int) asset.Flags; row["creatorID"] = asset.CreatorID; row["data"] = asset.Data; m_Gd.Insert("assets", row); }
AssetBase LoadAssetBase (OSDMap map) { AssetBase asset = new AssetBase (); asset.FromOSD (map); return asset; }
/// <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++; } }
/// <summary> /// Load an asset /// </summary> /// <param name="assetPath"> </param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private 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); 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 if (!m_assetService.GetExists(asset.ID.ToString())) m_assetService.Store(asset); return true; } MainConsole.Instance.ErrorFormat( "[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; }
/// <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); } }