public static JObject ToJson(this VObject obj, VdfJsonConversionSettings settings = null)
        {
            if (settings == null)
            {
                settings = new VdfJsonConversionSettings();
            }

            JObject resultObj = new JObject();

            foreach (VProperty prop in obj.Properties())
            {
                if (!resultObj.ContainsKey(prop.Key))
                {
                    resultObj.Add(prop.ToJson(settings));
                }
                else if (resultObj[prop.Key] is JValue)
                {
                    HandleValueDuplicateKey(resultObj, prop, settings);
                }
                else
                {
                    HandleObjectDuplicateKey(resultObj, prop, settings);
                }
            }

            return(resultObj);
        }
Example #2
0
        private void ReadVObjectAttributes(VObject vObject, SvgElement svg)
        {
            vObject.Visible  = svg.Display != Display.None;
            vObject.UniqueId = svg.ID;

            foreach (var attr in svg.CustomAttributes)
            {
                if (attr.NamespaceUri == XmlNamespace.AurigmaVectorObjects)
                {
                    switch (attr.LocalName)
                    {
                    case "locked":
                        vObject.Locked = attr.GetValue() == "true";
                        break;

                    case "name":
                        vObject.Name = attr.GetValue();
                        break;

                    case "tag":
                        vObject.Tag = _serializer.Deserialize <object>(attr.GetValue());
                        break;

                    case "permissions":
                        vObject.Permissions = _serializer.Deserialize <Permission>(attr.GetValue());
                        break;
                    }
                }
            }
        }
Example #3
0
        private void WriteVObjectAttributes(SvgElement svg, VObject vObject)
        {
            svg.Display = vObject.Visible ? Display.Inline : Display.None;
            svg.ID      = vObject.UniqueId;

            if (vObject.Locked)
            {
                svg.CustomAttributes.Add(new SvgVoAttribute("locked", vObject.Locked));
            }

            if (!string.IsNullOrEmpty(vObject.Name))
            {
                svg.CustomAttributes.Add(new SvgVoAttribute("name", vObject.Name));
            }

            if (vObject.Tag != null)
            {
                svg.CustomAttributes.Add(new SvgVoAttribute("tag", _serializer.Serialize(vObject.Tag)));
            }

            if (vObject.Permissions != null)
            {
                svg.CustomAttributes.Add(new SvgVoAttribute("permissions", _serializer.Serialize(vObject.Permissions)));
            }
        }
Example #4
0
        public override void ApplyState(VObject obj)
        {
            base.ApplyState(obj);

            var t = (BaseTextVObject)obj;

            t.Text = Txt.Replace("&gt;", ">").Replace("&lt;", "<").Replace("&quot;", "\"").Replace("&amp;", "&");

            // Backward compatibility
            if (F_N == null && FN != null)
            {
                var font = FontService.FindSuitableFont(FN, B, I, S);
                t.Font.FauxBold       = font.FauxBold;
                t.Font.FauxItalic     = font.FauxItalic;
                t.Font.PostScriptName = font.PostScriptName;
                t.Font.Size           = FS;
            }
            else
            {
                t.Font.FauxBold       = F_FB;
                t.Font.FauxItalic     = F_FI;
                t.Font.PostScriptName = F_N;
                t.Font.Size           = F_S;
            }

            t.TextColor = TC;
            t.Underline = U;
            t.SetInternalAlignment(A);
            t.Tracking        = Tr;
            t.Leading         = Ld;
            t.CurrentFileId   = CFI;
            t.IsRichText      = IRT;
            t.VerticalScale   = VS;
            t.HorizontalScale = HS;
        }
Example #5
0
        private VObject ReadObject(VdfReader reader)
        {
            VObject result = new VObject();

            if (!reader.ReadToken())
            {
                throw new VdfException("Incomplete VDF data.");
            }

            while (!(reader.CurrentState == VdfReader.State.Object && reader.Value == VdfStructure.ObjectEnd.ToString()))
            {
                if (reader.CurrentState == VdfReader.State.Comment)
                {
                    result.Add(VValue.CreateComment(reader.Value));
                }
                else
                {
                    result.Add(ReadProperty(reader));
                }

                if (!reader.ReadToken())
                {
                    throw new VdfException("Incomplete VDF data.");
                }
            }

            return(result);
        }
Example #6
0
        public ClientListener(Socket handler, bool isDummy = false)
        {
            maxTryNum             = 3;
            isPrintClose          = false;
            isTryLinking          = false;
            batchNum              = 10;
            receiveQueue          = new ConcurrentQueue <byte[]>();
            waitSendQueue         = new Queue <byte[]>();
            m_headLengthConverter = VUInt32.Instance;
            headBuffer            = new byte[m_headLengthConverter.VTypeLength];
            reserveBuffer         = new byte[RESERVE_SIZE];
            m_baseRpcCallHead     = VUInt16.Instance.Encode(MSGIDType.BASEAPP_CLIENT_RPCALL);
            m_cellRpcCallHead     = VUInt16.Instance.Encode(MSGIDType.BASEAPP_CLIENT_RPC2CELL_VIA_BASE);

            m_isDummy = isDummy;
            if (isDummy)
            {
                return;
            }

            client                   = handler;
            client.NoDelay           = true;  //Negal
            client.SendBufferSize    = 0xfa00;
            client.ReceiveBufferSize = 0xfa00;
            resetWhileConnected();
            startReceive();
            if (netStatusListener != null)
            {
                netStatusListener(LINK_OK);
            }
            timeId = TimerHeap.AddTimer(1000, 3000, closeNotice);                                                                 //连接关闭通知
            sendWaitPack();                                                                                                       //发送由于网络中断的滞留包
        }
Example #7
0
        private void Parse(string path)
        {
            VObject vObject = (VObject)VdfConvert.Deserialize(File.ReadAllText(path).Replace(@"\", @"\\")).Value;

            DepotId     = int.Parse(vObject["DepotID"].ToString());
            ContentRoot = vObject["ContentRoot"].ToString();
            foreach (VProperty child in vObject.Children())
            {
                switch (child.Key)
                {
                case "FileMapping":
                    VObject mapping = (VObject)child.Value;
                    FileMappings.Add(new FileMapping {
                        LocalPath = mapping["LocalPath"].ToString(),
                        DepotPath = mapping["DepotPath"].ToString(),
                        Recursive = int.Parse(mapping["recursive"].ToString())
                    });
                    break;

                case "FileExclusion":
                    FileExclusions.Add(new FileExclusion(child.Value.ToString()));
                    break;

                default:
                    continue;
                }
            }
        }
Example #8
0
        static public VProperty InsertProxyIntoMaterial(dynamic Material, string parameter, List <string[]> proxyParameterArray)
        {
            VObject proxy = new VObject();

            foreach (string[] proxyParameter in proxyParameterArray)
            {
                if (String.IsNullOrEmpty(proxyParameter[0]) || String.IsNullOrEmpty(proxyParameter[1]))
                {
                    continue;
                }
                proxy.Add(proxyParameter[0], new VValue(proxyParameter[1]));
            }
            string proxyKeyName = CaseInsensitiveProxyCheck(Material);

            if (proxyKeyName == null)
            {
                proxyKeyName = "Proxies";
                VObject proxies = new VObject();
                Material.Value[proxyKeyName] = proxies;
            }
            if (Material.Value[proxyKeyName].ContainsKey(parameter))
            {
                Material.Value[proxyKeyName].Add(new VProperty(parameter, proxy));
            }
            else
            {
                Material.Value[proxyKeyName][parameter] = proxy;
            }
            return(Material);
        }
Example #9
0
        public override void ApplyState(VObject obj)
        {
            base.ApplyState(obj);
            var c = (ContentVObject)obj;

            c.MaskColor = MC != null ? new RgbColor(Common.ParseWebColor(MC)) : c.MaskColor;
        }
Example #10
0
        public static string GetSteamIdFromConfig(string userName)
        {
            dynamic steamId = null;

            try
            {
                string steamPath = new IniFile(SAMSettings.FILE_NAME).Read(SAMSettings.STEAM_PATH, SAMSettings.SECTION_STEAM);

                // Attempt to find Steam Id from steam config.
                dynamic config   = VdfConvert.Deserialize(File.ReadAllText(steamPath + "config\\config.vdf"));
                dynamic accounts = config.Value.Software.Valve.Steam.Accounts;

                VObject accountsObj = accounts;
                VToken  value;

                accountsObj.TryGetValue(userName, out value);

                dynamic user   = value;
                VValue  userId = user.SteamID;
                steamId = userId.Value.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(Convert.ToString(steamId));
        }
Example #11
0
 public static string[] GetSteamLibraryPaths()
 {
     string[] libraryPaths = Array.Empty <string>();
     using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))// Doesn't work in 32 bit mode without this
     {
         using (RegistryKey steamKey = hklm?.OpenSubKey(STEAM_PATH_KEY))
         {
             string path = (string)steamKey?.GetValue("InstallPath", string.Empty);
             if (path != null && path.Length > 0)
             {
                 string configPath = Path.Combine(path, STEAM_CONFIG_PATH);
                 if (File.Exists(configPath))
                 {
                     VProperty   v             = VdfConvert.Deserialize(File.ReadAllText(configPath));
                     VToken      ics           = v?.Value;
                     VToken      soft          = ics?["Software"];
                     VToken      valve         = soft?["Valve"];
                     VObject     steamSettings = valve?["Steam"] as VObject;
                     VProperty[] settings      = steamSettings?.Children <VProperty>()?.ToArray();
                     if (settings != null)
                     {
                         libraryPaths = settings.Where(p => p.Key.StartsWith("BaseInstallFolder"))
                                        .Select(p => p.Value.ToString()).ToArray();
                     }
                 }
             }
         }
     }
     return(libraryPaths);
 }
Example #12
0
        public override void ApplyState(VObject obj)
        {
            base.ApplyState(obj);

            var t = (AutoScaledTextVObject)obj;

            t.IsVertical = IV;
        }
Example #13
0
        public void StringWithQuotesInListToStringTest()
        {
            var obj = new VObject(new List <VObject> {
                "hello\\\""
            });

            Assert.AreEqual(obj.ToString(), "[\"hello\\\\\\\"\"]");
        }
 public static VToken GetValue(this VObject vdf, string key)
 {
     if (vdf.TryGetValue(key, out var value))
     {
         return(value.Value);
     }
     return(null);
 }
Example #15
0
        public override void UnExecute(ICanvas canvas)
        {
            Object  b   = Activator.CreateInstance(Type.GetType(this.ClassName));
            VObject obj = (VObject)(b);

            obj.Data = this.Data;
            canvas.Layers[this.LayerIndex].VObjects.Insert(this.VObjectIndex, obj);
        }
Example #16
0
        public void ListToStringTest2()
        {
            var obj = new VObject(new List <VObject> {
                1, "abc", 2
            });

            Assert.AreEqual(obj.ToString(), "[1, \"abc\", 2]");
        }
Example #17
0
 public VObjectAddedCommand(VObject vObject, int vObjectIndex, int layerIndex)
 {
     _vObjectIndex = vObjectIndex;
     _layerIndex   = layerIndex;
     _data         = vObject.Data;
     _className    = vObject.GetType().FullName;
     _vObjectId    = vObject.UniqueId;
 }
        public override void ApplyState(VObject obj)
        {
            base.ApplyState(obj);
            var l = (PolylineVObject)obj;

            l.Width = W;
            l.Color = C;
        }
Example #19
0
        public void ListToStringTest3()
        {
            var obj = new VObject(new List <VObject> {
                "hello", "abc", "world"
            });

            Assert.AreEqual(obj.ToString(), "[\"hello\", \"abc\", \"world\"]");
        }
Example #20
0
        public override void ApplyState(VObject obj)
        {
            base.ApplyState(obj);
            var l = (LineVObject)obj;

            l.Color      = C;
            l.Width      = W;
            l.FixedWidth = FW;
        }
        public override void ApplyState(VObject obj)
        {
            base.ApplyState(obj);

            var t = (BaseRectangleVObject)obj;

            t.TextWrappingMode = TWM;
            t.Opacity          = O;
        }
        public override void ApplyState(VObject obj)
        {
            base.ApplyState(obj);
            var l = (DashedLineVObject)obj;

            l.AltColor     = AC;
            l.DashWidth    = DW;
            l.AltDashWidth = ADW;
        }
        public override void ApplyState(VObject obj)
        {
            base.ApplyState(obj);

            var t = (PlainTextVObject)obj;

            t.BaselineLocation = BL;
            t.ActualAngle      = AA;
            t.IsVertical       = IV;
        }
Example #24
0
        public void Interpreter_FilterTest()
        {
            var interpreter = new Interpreter("“string“起当's", new VObject[0]);
            var result      = new VObject(interpreter.Interpret());
            var expected    = new List <VObject> {
                "s"
            };

            Assert.IsTrue(result.Equals(new VObject(expected)), result.Dump());
        }
Example #25
0
        public void Interpreter_String()
        {
            var interpreter = new Interpreter("“Hello, World!", new VObject[0]);
            var result      = new VObject(interpreter.Interpret());
            var expected    = new List <VObject> {
                new VObject("Hello, World!")
            };

            Assert.IsTrue(result.Equals(new VObject(expected)), result.Dump());
        }
Example #26
0
        static private VProperty CaseInsensitiveParameterCheck(VObject vObject, string stringToCheck)
        {
            IEnumerable <VProperty> match = vObject.Children().Where(x => x.Key.Equals(stringToCheck, StringComparison.OrdinalIgnoreCase));

            if (match.Count() > 0)
            {
                return(match.First());
            }
            return(new VProperty(stringToCheck, null));
        }
Example #27
0
        public void Interpreter_Number()
        {
            var interpreter = new Interpreter("22222", new VObject[0]);
            var result      = new VObject(interpreter.Interpret());
            var expected    = new List <VObject> {
                new VObject(22222)
            };

            Assert.IsTrue(result.Equals(new VObject(expected)), result.Dump());
        }
Example #28
0
        public override object ConstructObject()
        {
            var vobj = new VObject();
            int i    = CurrObj;

            foreach (var k in Inputs.Keys)
            {
                vobj.Add(k, Inputs[k][i]);
            }
            return(vobj);
        }
Example #29
0
 internal void AddVObjectMoved(VObject vObject, int oldIndex, int newIndex, int layerIndex)
 {
     if (this.Enable && !this.Locked)
     {
         VObjectMovedCommand command = new VObjectMovedCommand(vObject, oldIndex, newIndex, layerIndex);
         if (command.NewVObjectIndex != -1 && command.OldVObjectIndex != -1 && command.LayerIndex != -1)
         {
             AddCommand(command);
         }
     }
 }
 public void RemoveVObject(VObject vo)
 {
     foreach (Layer l in _canvasViewer.Canvas.Layers)
     {
         bool deleted = l.VObjects.Remove(vo);
         if (deleted)             // object has been deleted, no reason to continue
         {
             break;
         }
     }
 }
Example #31
0
        public override void Initialize()
        {
            userObject = new VObject();

            Reference.Viewer.ProtocolManager.OnTextureFromWebLoaded -= ProtocolManager_OnTextureFromWebLoaded;
            Reference.Viewer.ProtocolManager.OnTextureFromWebLoaded += ProtocolManager_OnTextureFromWebLoaded;
            Reference.Viewer.TextureManager.OnTextureLoaded -= TextureManager_OnTextureLoaded;
            Reference.Viewer.TextureManager.OnTextureLoaded += TextureManager_OnTextureLoaded;

            trianglePickerMapper = new TrianglePickerMapper(Reference.SceneManager.CollisionManager);

            base.Initialize();
        }
Example #32
0
        public override void Cleanup()
        {
            ProcessObjectQueueDeleteToNode(userObject);
            if (userObject.Node != null)
                Reference.SceneManager.AddToDeletionQueue(userObject.Node);
            userObject = null;

            OnRequest = null;

            lock (entities)
            {
                entities.Clear();
            }
            lock (pipeline)
            {
                pipeline.Clear();
            }
            lock (pipelineUpdate)
            {
                pipelineUpdate.Clear();
            }
            lock (eventQueue)
            {
                eventQueue.Clear();
            }
            base.Cleanup();
        }
Example #33
0
        public void AddObject(OpenMetaverse.Avatar _avatar, ulong _regionHandle)
        {
            // Unsafe if the currentsim in libomv is not initialized yet, nullreferenceexception will be raised
            //ulong regionID = Reference.Viewer.ProtocolManager.AvatarConnection.m_user.Network.CurrentSim.Handle;
            //if (regionID != _regionHandle)
            //    return;

            _avatar.RegionHandle = _regionHandle;
            string key = VUtil.GetEntitiesKeyFromPrim(_avatar);

            VObject newObj = new VObject();
            newObj.Prim = _avatar;
            newObj.Node = null;

            VObject delObj = null;

            lock (pipeline)
            {
                lock (entities)
                {
                    // WARNING: this decision about delObj using entities must be in the
                    // **same lock** as the Enqueue() call below! Otherwise, it is possible that
                    // this thread is interrupted after we decide that delObj is NULL, but during
                    // that interruption ANOTHER OnNewAvatar event fires which inserts an avatar
                    // into the Entities, meaning our information and decision about delObj
                    // is now out-of-date.
                    if (entities.ContainsKey(key))
                    {
                        delObj = entities[key];

                        entities.Remove(key);
                    }

                    entities.Add(key, newObj);
                }

                // Atomic operation. Ensure DELETION->ADDITION
                //lock (pipeline) //<-- moved upwards, see WARNING above
                {
                    if (delObj != null)
                    {
                        pipeline.Enqueue(new Action<VObject>(delObj, Operations.DELETE));
                    }
                    pipeline.Enqueue(new Action<VObject>(newObj, Operations.ADD));
                }
            }
        }
Example #34
0
        /// <summary>
        /// Applies individual face settings
        /// </summary>
        /// <param name="vObj"></param>
        /// <param name="alpha">Is this an alpha texture</param>
        /// <param name="teface">Texture Entry Face</param>
        /// <param name="tex">Texture to apply</param>
        /// <param name="face">Which face this is</param>
        /// <param name="shinyval">The selected shiny value</param>
        /// <param name="coldata">The modified Color settings</param>
        public void ApplyFaceSettings(VObject vObj, bool alpha, Primitive.TextureEntryFace teface, Texture tex, int face, 
            float shinyval, Color4 coldata)
        {
            // Apply texture
            if (tex != null)
            {
                vObj.Mesh.GetMeshBuffer(face).Material.Texture1 = tex;
            }

            // Apply colors/transforms
            if (teface != null)
            {
                ApplyFace(vObj, alpha, face, teface, shinyval, coldata);
            }
        }
Example #35
0
        // Picker
        private void DetectObjectUnderMouse()
        {
            if (Reference.SceneManager != null
                && Reference.Device != null
                && Reference.SceneManager.CollisionManager != null)
            {
                SceneNode irrNodeUnderMouse =
                    Reference.SceneManager.CollisionManager.GetSceneNodeFromScreenCoordinates
                        (Reference.Device.CursorControl.Position,
                        0,
                        false);
                if (irrNodeUnderMouse == null)
                {
                    objectUnderMouse = null;
                }
                else
                {
                    Reference.Viewer.Camera.ResetMouseOffsets();
                    projectedray = Reference.SceneManager.CollisionManager.GetRayFromScreenCoordinates
                         (Reference.Device.CursorControl.Position + Reference.Viewer.CursolOffset,
                         Reference.Viewer.Camera.SNCamera);
                    irrNodeUnderMouse =
                        trianglePickerMapper.GetSceneNodeFromRay(projectedray, 0x0128, true, Reference.Viewer.Camera.SNCamera.Position);

                    bool foundRegionPrimCorrespondingToIrrNodeId = false;
                    VObject vobj = null;
                    if (irrNodeUnderMouse != null
                        && irrNodeUnderMouse.ID != -1)
                    {
                        lock (entities)
                        {
                            foreach (string vobjkey in entities.Keys)
                            {
                                vobj = entities[vobjkey];
                                if (vobj != null
                                    && vobj.Node != null
                                    && vobj.Node.ID == irrNodeUnderMouse.ID)
                                {
                                    objectUnderMouse = vobj;

                                    if (vobj.Prim != null)
                                    {
                                        string firstName = string.Empty;;
                                        string lastName = string.Empty;
                                        if (vobj.Prim.NameValues.Length > 1)
                                        {
                                            firstName = (string)vobj.Prim.NameValues[0].Value;
                                            lastName = (string)vobj.Prim.NameValues[1].Value;
                                        }

                                        StringBuilder sb = new StringBuilder();
                                        sb.Append("{");
                                        sb.Append("\"UUID\":" + "\"" + vobj.Prim.ID.ToString() + "\"");
                                        sb.Append(",");
                                        sb.Append("\"NAME\":");
                                        sb.Append("{");
                                        sb.Append("\"FIRST\":" + "\"" + firstName + "\"");
                                        sb.Append(",");
                                        sb.Append("\"LAST\":" + "\"" + lastName + "\"");
                                        sb.Append("}");
                                        sb.Append("}");
                                        Reference.Viewer.Adapter.CallAvatarPicked(sb.ToString());
                                    }

                                    string text = "AVATAR pick target found!: " + vobj.Prim.ID.ToString() + " " + this.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
                                    Reference.Log.Debug(text);

                                    foundRegionPrimCorrespondingToIrrNodeId = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!foundRegionPrimCorrespondingToIrrNodeId)
                    {
                        objectUnderMouse = null;
                    }
                }
            }
        }
Example #36
0
 public void OnNetworkTextureDownloaded(string tex, VObject vObj, UUID AssetID)
 {
     SceneGraph.OnNetworkTextureDownloaded(tex, vObj, AssetID);
 }
Example #37
0
        private void ProcessObjectQueueAddToNode(VObject _obj)
        {
            // Get irr file uuid.
            if (string.IsNullOrEmpty(Reference.Viewer.ProtocolManager.AvatarConnection.m_user.Network.AssetServerUri))
            {
                _obj.RequestIrrfileUUID = new UUID("70101ee9-888d-5bd6-371f-925c9b668ce3");
            }
            else
            {
                _obj.RequestIrrfileUUID = IrrManager.GetIrrfileUUID(Reference.Viewer.ServerURI, _obj.Prim.ID);
            }
            // Create empty node.
            _obj.Node = Reference.SceneManager.AddEmptySceneNode(ParentNode, (int)_obj.Prim.LocalID);

            _obj.SmoothingReset = true;

            // Set ghost avatar and name plate.
            Reference.Viewer.EffectManager.AddGhostSceneNode(_obj.Node);
            _obj.IsGhost = true;
            if (avatarNameVisible)
            {
                Avatar a = _obj.Prim as Avatar;
                Reference.Viewer.EffectManager.AddNameSceneNode(_obj.Node, a.FirstName, a.LastName, false, (EffectManager.AvatarNameType)Reference.Viewer.AvatarNameType);
                _obj.VoiceNode = Reference.Viewer.EffectManager.AddVoiceEffectSceneNode(_obj.Node);
            }

            AnimatedMesh animMesh = Reference.SceneManager.GetMesh(Util.ApplicationDataDirectory + @"/media/models/avatar_pick_object.x");
            _obj.PickNode = Reference.SceneManager.AddMeshSceneNode(animMesh.GetMesh(0), _obj.Node, _obj.Node.ID);
            _obj.PickNode.SetMaterialFlag(MaterialFlag.Lighting, false);
            _obj.PickNode.SetMaterialType(MaterialType.TransparentAlphaChannel);

            // Create triangle sector of pick object.
            TriangleSelector trisel = Reference.SceneManager.CreateTriangleSelector(animMesh.GetMesh(0), _obj.PickNode);
            _obj.PickNode.TriangleSelector = trisel;
            trianglePickerMapper.AddTriangleSelector(trisel, _obj.PickNode);
            trisel.Drop();

            if (_obj.Prim.ID == Reference.Viewer.ProtocolManager.AvatarConnection.GetSelfUUID)
            {
                userObject = _obj;
                userUUID = Reference.Viewer.ProtocolManager.AvatarConnection.GetSelfUUID;
            }
            ProcessObjectQueueUpdateToNode(_obj);

            Reference.Log.Debug("Added avatar: Name:" + ((Avatar)_obj.Prim).Name + " UUID:" + _obj.RequestIrrfileUUID.ToString());
        }
Example #38
0
        /// <summary>
        /// Bread and butter of the texture system.
        /// This is the start point for the texture-> graphics pipeline
        /// </summary>
        /// <param name="tex"></param>
        /// <param name="vObj"></param>
        /// <param name="AssetID"></param>
        public void applyTexture(TextureExtended tex, VObject vObj, UUID AssetID)
        {
            try
            {
                // works
                if (vObj.Mesh == null)
                    return;

                // Check if we have a  sculptie and its sculpting texture
                // If yes, don't apply the texture
                if (vObj.Prim.Sculpt != null && vObj.Prim.Sculpt.SculptTexture == AssetID)
                {
                    m_log.Debug("[TEXTURE]: Skipping applyTexture for sculpt " + AssetID);
                    return;
                }

                bool alphaimage = IsAlphaImage(tex);

                // MeshPrim
                if (vObj._3DiIrrfileUUID != UUID.Zero && vObj.IrrData != null)
                {
                    for (int iTex = 0; iTex < vObj.IrrData.Materials.Count; iTex++)
                    {
                        if (Path.GetFileNameWithoutExtension(vObj.IrrData.Materials[iTex].Texture1) == AssetID.ToString())
                        {
                            Texture loadedTex = Reference.VideoDriver.GetTexture(AssetID.ToString() + tex.extension);
                            if (vObj.Node.Children.Length > 0)
                            {
                                vObj.Node.Children[0].GetMaterial(iTex).Texture1 = loadedTex;
                            }
                            break;
                        }
                    }

                    if (alphaimage)
                    {
                        vObj.Node.Children[0].SetMaterialType(MaterialType.TransparentAlphaChannel);
                        Reference.SceneManager.RegisterNodeForRendering(vObj.Node.Children[0], SceneNodeRenderPass.Transparent);
                    }

                }
                // Normal prim
                else
                {
                    // Apply the Texture based on the TextureEntry
                    if (vObj.Prim.Textures != null)
                    {
                        Reference.SceneManager.MeshCache.RemoveMesh(vObj.Mesh);

                        // TODO: Apply texture per face (including DefaultTexture if a FaceTexture was not specified)
                        for (int i = 0; i < vObj.Mesh.MeshBufferCount; i++)
                        {
                            float shinyval = 0;
                            // Check if there is a facetexture for this MB
                            Primitive.TextureEntryFace applyTexture = null;
                            if (i <  vObj.Prim.Textures.FaceTextures.Length && vObj.Prim.Textures.FaceTextures[i] != null)
                            {
                                // Apply FaceTexture
                                applyTexture = vObj.Prim.Textures.FaceTextures[i];
                            }
                            else if (vObj.Prim.Textures.DefaultTexture != null)
                            {
                                // Apply DefaultTexture
                                applyTexture = vObj.Prim.Textures.DefaultTexture;
                            }

                            if (applyTexture != null)
                            {
                                Color4 coldata = applyTexture.RGBA;
                                switch (applyTexture.Shiny)
                                {
                                    case Shininess.Low:
                                        shinyval = 0.8f;
                                        coldata.R *= 0.8f;
                                        coldata.B *= 0.8f;
                                        coldata.G *= 0.8f;
                                        break;
                                    case Shininess.Medium:
                                        shinyval = 0.7f;
                                        coldata.R *= 0.6f;
                                        coldata.B *= 0.6f;
                                        coldata.G *= 0.6f;
                                        break;
                                    case Shininess.High:
                                        shinyval = 0.6f;
                                        coldata.R *= 0.3f;
                                        coldata.B *= 0.3f;
                                        coldata.G *= 0.3f;
                                        break;
                                }

                                if (applyTexture.TextureID == AssetID)
                                {
                                    ApplyFaceSettings(vObj, alphaimage, applyTexture, tex, i, shinyval, coldata);
                                }
                                else
                                {
                                    // Apply color settings
                                    ApplyFaceSettings(vObj, alphaimage, applyTexture, null, i, shinyval, coldata);
                                }

                                vObj.Mesh.GetMeshBuffer(i).Material.NormalizeNormals = true;
                                vObj.Mesh.GetMeshBuffer(i).Material.GouraudShading = true;
                                vObj.Mesh.GetMeshBuffer(i).Material.BackfaceCulling = (texDownloadStyle == TextureDownloadStyle.TEX_DOWNLOAD_ASSETSERVER);
                            }
                        }

                        if (vObj.Node is MeshSceneNode)
                        {
                            MeshSceneNode msn = (MeshSceneNode) vObj.Node;

                            msn.SetMesh(vObj.Mesh);
                            /*
                            if (vObj.Prim.Textures != null)
                            {
                                // Check the default texture to ensure that it's not null (why would it be null?)
                                if (vObj.Prim.Textures.DefaultTexture != null)
                                {
                                    Color4 coldata = vObj.Prim.Textures.DefaultTexture.RGBA;
                                    IrrlichtNETCP.Color objColor = new Color(
                                        Util.Clamp<int>((int) (coldata.A*255), 0, 255),
                                        Util.Clamp<int>((int) (coldata.R*255), 0, 255),
                                        Util.Clamp<int>((int) (coldata.G*255), 0, 255),
                                        Util.Clamp<int>((int) (coldata.B*255), 0, 255)
                                        );

                                    // Set material color.
                                    for (int i = 0; i < msn.MaterialCount; i++)
                                    {
                                        msn.GetMaterial(i).AmbientColor = objColor;
                                        msn.GetMaterial(i).DiffuseColor = objColor;
                                        msn.GetMaterial(i).SpecularColor = Color.Black;
                                        msn.GetMaterial(i).EmissiveColor = Color.Black;
                                        msn.GetMaterial(i).Shininess = 0;
                                    }
                                }
                            }
                            */

                            Box3D box = new Box3D(0, 0, 0, 0, 0, 0);
                            for (int i = 0; i < msn.GetMesh().MeshBufferCount; i++)
                            {
                                msn.GetMesh().GetMeshBuffer(i).RecalculateBoundingBox();
                                box.AddInternalBox(msn.GetMesh().GetMeshBuffer(i).BoundingBox);
                            }
                            msn.GetMesh().BoundingBox = box;
                        }
                        else
                        {
                            // Swap out the visible untextured object with a textured one.
                            // SceneNode sn = device.SceneManager.AddMeshSceneNode(vObj.Mesh, ParentNode, -1);
                            // ZAKI: Change TextureManager Parent to actual parent node
                            SceneNode sn = Reference.SceneManager.AddMeshSceneNode(vObj.Mesh, vObj.Node.Parent, -1);
                            sn.Position = vObj.Node.Position;
                            sn.Rotation = vObj.Node.Rotation;
                            sn.Scale = vObj.Node.Scale;
                            sn.DebugDataVisible = DebugSceneType.Off;

                            // If it's translucent, register it for the Transparent phase of rendering
                            if (vObj.Prim.Textures.DefaultTexture != null)
                            {
                                if (vObj.Prim.Textures.DefaultTexture.RGBA.A != 1)
                                {
                                    Reference.SceneManager.RegisterNodeForRendering(sn, SceneNodeRenderPass.Transparent);
                                }
                            }
                            // Add the new triangle selector
                            sn.TriangleSelector = Reference.SceneManager.CreateTriangleSelector(vObj.Mesh, sn);
                            sn.TriangleSelector.Drop();
                            Reference.Viewer.EntityManager.AddTriangleSelector(sn.TriangleSelector, sn);

                            // Delete the old node.
                            SceneNode oldnode = vObj.Node;
                            Reference.Viewer.EntityManager.DeleteNode(oldnode);

                            // Assign new node
                            vObj.Node = sn;

                        }
                    }
                } // prim texture is not null

            }
            catch (AccessViolationException)
            {
                VUtil.LogConsole(this.ToString() + "[ACCESSVIOLATION]", " TextureManager::ApplyTexture");
                m_log.Error("[TEXTURE]: Failed to load texture.");
            }
            catch (NullReferenceException)
            {
                m_log.Error("unable to update texture");
            }
        }
Example #39
0
 public void Start()
 {
     userObject = new VObject();
     userObject.Node = Reference.SceneManager.AddEmptySceneNode(ParentNode, -1);
 }
Example #40
0
        /// <summary>
        /// Animations that are received are stored in a dictionary in the protocol module and associated
        /// with an avatar. They are removed from that dictionary here and applied to the proper avatars
        /// in the scene.
        /// </summary>
        private void AnimationFrame(VObject _obj, bool sitting)
        {
            if (_obj.MeshNode is AnimatedMeshSceneNode)
            {
                string key = GetAnimationKey(_obj.Prim.ID);

                if (sitting && (key != null && key == UtilityAnimation.ANIMATION_KEY_STANDING))
                {
                    SetAnimation(_obj, "sitstart");
                }
                else if ((!sitting) && (key != null && key == UtilityAnimation.ANIMATION_KEY_SITTING))
                {
                    SetAnimation(_obj, "standing");
                }
                else if (!string.IsNullOrEmpty(key))
                {
                    SetAnimation(_obj, key);
                }
            }
        }
Example #41
0
        /// <summary>
        /// Requests an image for an object.
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="requestor"></param>
        public void RequestImage(UUID assetID, VObject requestor)
        {
            
            TextureExtended tex = null;

            lock (memoryTextures)
            {
                
                if (memoryTextures.ContainsKey(assetID))
                {
                    tex = memoryTextures[assetID];
                }
            }

            if (tex != null)
            {
#if DebugTexturePipeline
                m_log.Debug("[3Di Mesh]: Already have texture in memory: " + assetID);
#endif
#if DebugTexturePipeline
                m_log.Debug("RequestImage 1 calling applyTexture");
#endif
                // We already have the texture, jump to applyTexture
                applyTexture(tex, requestor, assetID);

                // Apply the texture to all objects that are already waiting for this texture
                lock (ouststandingRequests)
                {
                    if (ouststandingRequests.ContainsKey(assetID))
                    {
                        m_log.Warn("[TEXTURE]: Applying texture from memory to outstanding requestors.");
                        foreach (VObject vObj in ouststandingRequests[assetID])
                        {
                            applyTexture(tex, vObj, assetID);
                        }
                        ouststandingRequests.Remove(assetID);
                    }
                }

                return;
            }

            // Check to see if we've got the texture on disk

            string texturefolderpath = imagefolder;
            if (File.Exists(System.IO.Path.Combine(texturefolderpath, assetID.ToString() + ".tga")))
            {
                Texture texTnorm = driver.GetTexture(System.IO.Path.Combine(texturefolderpath, assetID.ToString() + ".tga"));
                if (texTnorm != null)
                    tex = new TextureExtended(texTnorm.Raw, ".tga");
                if (tex != null)
                {
#if DebugTexturePipeline
                    m_log.Debug("[3Di Mesh]: Already have texture locally on disk: " + assetID);
#endif
                    lock (memoryTextures)
                    {
                        if (!memoryTextures.ContainsKey(assetID))
                        {
                            // Add it to the texture cache.
                            memoryTextures.Add(assetID, tex);
                        }
                    }

#if DebugTexturePipeline
                    m_log.Debug("RequestImage 2 calling applyTexture");
#endif
                    // apply texture
                    applyTexture(tex, requestor, assetID);

                    // Apply the texture to all objects that are already waiting for this texture
                    lock (ouststandingRequests)
                    {
                        if (ouststandingRequests.ContainsKey(assetID))
                        {
                            m_log.Warn("[TEXTURE]: Applying texture from memory to outstanding requestors.");
                            foreach (VObject vObj in ouststandingRequests[assetID])
                            {
                                applyTexture(tex, vObj, assetID);
                            }
                            ouststandingRequests.Remove(assetID);
                        }
                    }

                    return;
                }

            }

            // Check if we've already got an outstanding request for this texture
            lock (ouststandingRequests)
            {
                if (ouststandingRequests.ContainsKey(assetID))
                {
                    // Add it to the objects to be notified when this texture download is complete.
                    ouststandingRequests[assetID].Add(requestor);
#if YK_ADD_DEFAULT_TEXTURE
                    applyTexture(null, requestor, assetID);
#endif

                    return;
                }
                else 
                {
                    // Create a new outstanding request entry
                    List<VObject> requestors = new List<VObject>();
                    requestors.Add(requestor);
                    ouststandingRequests.Add(assetID,requestors);
                    
                }
            }

#if DebugTexturePipeline
            m_log.Debug("[3Di Mesh]: Requesting from libomv the following texture: " + assetID);
#endif

            if (string.IsNullOrEmpty(m_user.m_user.Network.AssetServerUri))
            {
                this.texDownloadStyle = TextureDownloadStyle.TEX_DOWNLOAD_LIBOMV;
            }

            TextureDownloadRequest req = new TextureDownloadRequest();
            req.uuid = assetID;
            downloadTextureQueue.Enqueue(req); // no need to lock b/c it's a BlockingQueue which needs no synchronization
            m_log.Info("[TEXTURE]: Added to DownloadTextureQueue current count " + downloadTextureQueue.Count);
            /*
            if (this.texDownloadStyle == TextureDownloadStyle.TEX_DOWNLOAD_LIBOMV)
            {
                // Request texture from LibOMV
                m_user.RequestTexture(assetID);
            }
            else
            {
                // request texture directly from assetserver via our own background thread
                TextureDownloadRequest req = new TextureDownloadRequest();
                req.uuid = assetID;
                downloadTextureQueue.Enqueue(req); // no need to lock b/c it's a BlockingQueue which needs no synchronization
            }
            */
        }
Example #42
0
        /// <summary>
        /// Load to scene from Irrlicht file.
        /// </summary>
        /// <param name="_datas">IrrDatas</param>
        /// <param name="_smgr">Scene Manager</param>
        /// <param name="_vObj">VObject</param>
        /// <param name="_Entities">VObject list</param>
        public AnimatedMeshSceneNode IrrFileLoad(IrrParseLib.IrrDatas _datas, SceneManager _smgr, VObject _obj, string _prefix)
        {
            _obj.MeshNode = IrrMeshLoad(_datas, _smgr, _obj.Node, _prefix);

            // Copy base param.
            _obj.BaseParam = _datas.Mesh.Param;

            // Create animation key.
            _datas.CreateAnimationKey(workDirectory);
            foreach (IrrParseLib.KeyframeSet key in _datas.AnimationKey.Keys)
            {
                if (!_obj.FrameSetList.ContainsKey(key.Name))
                    _obj.FrameSetList.Add(key.Name, new IrrParseLib.KeyframeSet(key.Name, key.AnimationSpeed, key.StartFrame, key.EndFrame));
            }

            _obj.MeshNode.Position = new Vector3D(_obj.BaseParam.Position[0], _obj.BaseParam.Position[1], _obj.BaseParam.Position[2]);
            _obj.MeshNode.Rotation = new Vector3D(_obj.BaseParam.Rotation[0], _obj.BaseParam.Rotation[1], _obj.BaseParam.Rotation[2]);
            _obj.MeshNode.Scale = new Vector3D(_obj.BaseParam.Scale[0], _obj.BaseParam.Scale[1], _obj.BaseParam.Scale[2]);

            return _obj.MeshNode;
        }
 private void RequestImage(UUID _assetUUID, VObject _vObject)
 {
     if (_vObject == null)
         avatarConnection.RequestImage(_assetUUID, AssetType.Object, true);
     else
         Reference.Viewer.TextureManager.RequestImage(new UUID(_assetUUID), _vObject);
 }
Example #44
0
        public void RequestObject(VObject _obj)
        {
            Reference.Log.Debug(" Request:" + _obj.RequestIrrfileUUID.ToString());
            _obj.Requesting = true;

            lock (requestingList)
            {
                if (requestingList.ContainsKey(_obj.RequestIrrfileUUID))
                {
                    Reference.Log.Debug(" Already Requested:" + _obj.RequestIrrfileUUID.ToString());

                    requestingList[_obj.RequestIrrfileUUID].Add(_obj);
                    return;
                }
                else
                {
                    List<VObject> requestors = new List<VObject>();
                    requestors.Add(_obj);
                    requestingList.Add(_obj.RequestIrrfileUUID, requestors);
                }
            }

            IrrMeshThread ss = new IrrMeshThread(Reference.Viewer, _obj, workDirectory);
            IrrWorkItem item = new IrrWorkItem("IrrMeshThread.Requesting", new WorkItemCallback(ss.Requesting), null);
            IrrWorkItemQueue(item);
        }
Example #45
0
        private void UpdateObjectToPiplineEnqueue(VObject _obj)
        {
            if (_obj == null)
            {
                return;
            }

            string key = String.Format("{0}:{1}", _obj.Prim.RegionHandle, _obj.Prim.LocalID);
            Pair<string, Action<VObject>> pair;
            Action<VObject> action = new Action<VObject>(_obj, Operations.UPDATE);

            lock (pipelineUpdate)
            {
                if (pipelineUpdate.TryGetValue(key, out pair))
                {
                    pair.Value = action;
                }
                else
                {
                    pipelineUpdate.Enqueue(key, action);
                }
            }
        }
Example #46
0
 void TextureManager_OnTextureLoaded(string texname, string extension, VObject node, UUID AssetID)
 {
     EventQueueParam param = new EventQueueParam(EventQueueType.TextureDownloaded, AssetID.ToString());
     bool found = false;
     foreach (SetTextureParam stp in requestTextureList)
     {
         if (stp.TextureUUID == AssetID.ToString())
         {
             found = true;
             break;
         }
     }
     if (!found)
         return;
     lock (eventQueue)
         eventQueue.Enqueue(param);
 }
Example #47
0
 public void ApplyFace(VObject vObj, bool alpha, int face, Primitive.TextureEntryFace teface, float shinyval, Color4 coldata)
 {
     ModifyMeshBuffer(coldata, shinyval, face, vObj.Mesh, teface, alpha);
 }
Example #48
0
        private void ProcessObjectQueueDeleteToNode(VObject _obj)
        {
            if (_obj.Node == null)
                return;

            if (_obj.Prim != null)
            {
                Reference.Log.Debug("Delete avatar: Name:" + ((Avatar)_obj.Prim).Name + " Pos:" + _obj.Prim.Position.ToString());
            }
            else
            {
                Reference.Log.Debug("Delete avatar: Name: (NULL)");
            }

            if (_obj.IsGhost)
            {
                Reference.Viewer.EffectManager.RemoveGhostNode(_obj.Node);
            }

            // Remove this object from our picker.
            if (_obj.PickNode != null && _obj.PickNode.TriangleSelector != null)
            {
                if (trianglePickerMapper != null)
                {
                    trianglePickerMapper.RemTriangleSelector(_obj.PickNode.TriangleSelector);
                }
                lock (NativeElement.Elements) { if (NativeElement.Elements.ContainsKey(_obj.PickNode.TriangleSelector.Raw)) { NativeElement.Elements.Remove(_obj.PickNode.TriangleSelector.Raw); } }
            }

            _obj.Dispose();
            _obj.VoiceNode = null;
            _obj.MeshNode = null;
            _obj.PickNode = null;

            SceneNode node = null;
            if (userObject.Node != null && userObject.Node.Raw == _obj.Node.Raw)
            {
                node = Reference.SceneManager.AddEmptySceneNode(ParentNode, -1);
            }
            Reference.SceneManager.AddToDeletionQueue(_obj.Node);
            _obj.MeshNode = null;

            if (node != null)
                userObject.Node = node;
        }
        public void RequestImage(string _uuidOrUrl, bool _useCache, VObject _vObject)
        {
            if (_useCache)
            {
                string path = Util.TextureFolder + _uuidOrUrl;
                if (System.IO.File.Exists(path))
                    return;
            }

            if (_uuidOrUrl.StartsWith("http://") || _uuidOrUrl.StartsWith("https://"))
                RequestImageToWebServer(_uuidOrUrl);
            else
            {
                string uuid = System.IO.Path.GetFileNameWithoutExtension(_uuidOrUrl);
                RequestImage(new UUID(uuid), _vObject);
            }
        }
Example #50
0
        private void ProcessObjectQueueUpdateToNode(VObject _obj)
        {
            // Little known fact.  Dead avatar in LibOMV have the word 'dead' in their UUID
            // Skip over this one and move on to the next one if it's dead.
            if (((Avatar)_obj.Prim).ID.ToString().Contains("dead"))
            {
                return;
            }

            if (_obj.Node == null)
            {
                return;
            }

            //If we don't have an avatar representation yet for this avatar or it's a full update
            if (_obj.Requesting == false)
            {
                if ((_obj._3DiIrrfileUUID != _obj.RequestIrrfileUUID) && (_obj.RequestIrrfileUUID != UUID.Zero))
                {
                    if (Reference.Viewer.IrrManager.Contains(_obj.RequestIrrfileUUID) == false)
                    {
                        _obj.requestTexturesDirectlyFromAssetServerWithoutJ2KConversion = true;
                        Reference.Viewer.IrrManager.RequestObject(_obj);
                        Reference.Log.Debug("Request object: UUID:" + _obj.RequestIrrfileUUID.ToString());
                    }
                    else
                    {
                        _obj._3DiIrrfileUUID = _obj.RequestIrrfileUUID;

                        IrrDatas datas = Reference.Viewer.IrrManager.GetObject(_obj._3DiIrrfileUUID, true);
                        if (datas != null)
                        {
                            // Set avatar mesh.
                            lock (entities)
                            {
                                Reference.Viewer.EffectManager.RemoveGhostNode(_obj.Node);
                                _obj.IsGhost = false;

                                AnimatedMeshSceneNode animeNode = Reference.Viewer.IrrManager.IrrFileLoad(datas, Reference.SceneManager, _obj, "tmpmesh_" + _obj.Prim.LocalID.ToString() + "_");
                                if (animeNode != null)
                                {
                                    animeNode.AnimationEnd += animeNode_AnimationEnd;
                                    animeNode.SetTransitionTime(0.1f);

                                    _obj.Mesh = animeNode.AnimatedMesh.GetMesh(0);
                                    SetAnimation(_obj, _obj.Prim.ParentID != 0 ? "sitstart" : "standing");
                                }
                            }
                        }

                        Reference.Log.Debug("Loaded object: UUID:" + _obj.RequestIrrfileUUID.ToString());
                    }
                }
            }

            AnimationFrame(_obj, _obj.Prim.ParentID != 0);

            _obj.TargetPosition = new Vector3D(_obj.Prim.Position.X, _obj.Prim.Position.Z - 0.83f, _obj.Prim.Position.Y);
            _obj.Velocity = new Vector3D(_obj.Prim.Velocity.X, _obj.Prim.Velocity.Z, _obj.Prim.Velocity.Y);

            if (_obj.Prim.ID != userUUID)
            {
                // REVIEW NEEDED: a more general calculation
                //float roll, pitch, yaw;
                //_obj.Prim.Rotation.GetEulerAngles(out roll, out pitch, out yaw);
                //_obj.Node.Rotation = new Vector3D(Utils.ToDegrees(roll), Utils.ToDegrees(pi2 - pitch), Utils.ToDegrees(yaw));
                Vector3 axis;
                float angle;
                _obj.Prim.Rotation.GetAxisAngle(out axis, out angle);
                _obj.Node.Rotation = new Vector3D(0, Utils.ToDegrees((axis.Z > 0 ? 1 : -1) * (pi2 - angle)), 0);
            }

            // If exsit parent prim, set parent.
            uint parentID = _obj.Prim.ParentID;
            if (parentID == 0)
            {
                _obj.ParentPosition = new Vector3();

                if (_obj.IsChildAgent)
                {
                    _obj.IsChildAgent = false;
                    _obj.SmoothingReset = true;
                }
            }
            else
            {
                ulong regionID = Reference.Viewer.ProtocolManager.AvatarConnection.m_user.Network.CurrentSim.Handle;

                if (Reference.Viewer.EntityManager.Entities.ContainsKey(regionID.ToString() + parentID.ToString()))
                {
                    VObject parentObj = Reference.Viewer.EntityManager.Entities[regionID.ToString() + parentID.ToString()];

                    if (parentObj != null)
                    {
                        _obj.ParentPosition = parentObj.Prim.Position;

                        IrrlichtNETCP.Quaternion iquParent = new IrrlichtNETCP.Quaternion
                            (parentObj.Prim.Rotation.X,
                             parentObj.Prim.Rotation.Z,
                             parentObj.Prim.Rotation.Y,
                             parentObj.Prim.Rotation.W);
                        iquParent.makeInverse();
                        IrrlichtNETCP.Quaternion iquAvatar = new IrrlichtNETCP.Quaternion
                            (_obj.Prim.Rotation.X,
                             _obj.Prim.Rotation.Z,
                             _obj.Prim.Rotation.Y,
                             _obj.Prim.Rotation.W);
                        iquAvatar.makeInverse();

                        IrrlichtNETCP.Quaternion finalRotation = iquAvatar * iquParent;
                        _obj.Node.Rotation = finalRotation.Matrix.RotationDegrees;
                        _obj.TargetPosition = parentObj.Node.Position + _obj.TargetPosition * iquParent;
                    }

                    _obj.SmoothingReset = true;
                    _obj.IsChildAgent = true;
                }
                else
                {
                    UpdateObjectToPiplineEnqueue(_obj);
                }
            }
            _obj.SyncToChilds();

            // If avatar's height position is minus, teleport to current sim center.
            if (_obj.Prim.ID == Reference.Viewer.ProtocolManager.AvatarConnection.GetSelfUUID && _obj.Prim.Position.Z < 0)
                Reference.Viewer.ProtocolManager.Teleport(Reference.Viewer.ProtocolManager.GetCurrentSimName(), 128, 128, 128);
        }
Example #51
0
        private void SetAnimation(VObject _obj, string _key)
        {
            _obj.SetNextAnimation(string.Empty, true);

            if (!_obj.FrameSetList.ContainsKey(_key))
                return;

            if (_obj.PickNode != null)
            {
                _obj.PickNode.Position = new Vector3D(0, 0, 0);
                _obj.PickNode.Scale = new Vector3D(1, 1, 1);
            }

            bool loopFlag = true;
            JointUpdateOnRenderMode jointMode = JointUpdateOnRenderMode.Control;
            switch (_key)
            {
                case "sitstart":
                    _obj.SetNextAnimation("sitting", true);
                    if (_obj.PickNode != null)
                    {
                        _obj.PickNode.Position = new Vector3D(-0.35f, 0.1f, 0);
                        _obj.PickNode.Scale = new Vector3D(1, 0.75f, 1);
                    }
                    loopFlag = false;
                    jointMode = JointUpdateOnRenderMode.None;
                    break;

                case UtilityAnimation.ANIMATION_KEY_SPEAK_SITTING:
                    _obj.SetNextAnimation(UtilityAnimation.ANIMATION_KEY_SPEAK_SITTING_END, false);
                    break;
                case UtilityAnimation.ANIMATION_KEY_SPEAK_SITTING_END:
                    _obj.SetNextAnimation(UtilityAnimation.ANIMATION_KEY_SITTING, true);
                    loopFlag = false;
                    break;
                case UtilityAnimation.ANIMATION_KEY_SPEAK_STANDING:
                    _obj.SetNextAnimation(UtilityAnimation.ANIMATION_KEY_SPEAK_STANDING_END, false);
                    break;
                case UtilityAnimation.ANIMATION_KEY_SPEAK_STANDING_END:
                    _obj.SetNextAnimation(UtilityAnimation.ANIMATION_KEY_STANDING, true);
                     loopFlag = false;
                     break;

                default:
                    _obj.CurrentAnimationUUID = new UUID();
                    break;
            }

            if (_key.StartsWith("customize"))
            {
                int animNo = int.Parse(_key.Substring(9));
                _obj.CurrentAnimationUUID = UtilityAnimation.CUSTOM_ANIMATIONS[animNo];
                loopFlag = false;
            }

            int startFrame = _obj.FrameSetList[_key].StartFrame;
            int endFrame = _obj.FrameSetList[_key].EndFrame;
            int animFramesPerSecond = _obj.FrameSetList[_key].AnimationSpeed;

            _obj.AnimationCurrentName = _key;
            _obj.AnimationSpeed = animFramesPerSecond;
            _obj.SetAnimationMode(jointMode);
            _obj.SetAnimation(_key, startFrame, endFrame, loopFlag);
        }
Example #52
0
        /// <summary>
        /// Requests an image for an object.
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="requestor"></param>
        public void RequestImage(UUID assetID, VObject requestor)
        {
            TextureExtended tex = null;

            lock (memoryTextures)
            {

                if (memoryTextures.ContainsKey(assetID))
                {
                    tex = memoryTextures[assetID];
                }
            }

            if (tex != null)
            {
                // We already have the texture, jump to applyTexture
                applyTexture(tex, requestor, assetID);

                // Apply the texture to all objects that are already waiting for this texture
                lock (outstandingRequests)
                {
                    if (outstandingRequests.ContainsKey(assetID))
                    {
                        m_log.Warn("[TEXTURE]: Applying texture from memory to outstanding requestors.");
                        foreach (VObject vObj in outstandingRequests[assetID])
                        {
                            applyTexture(tex, vObj, assetID);
                        }
                        outstandingRequests.Remove(assetID);
                    }
                }

                return;
            }

            // Check to see if we've got the texture on disk

            string texturefolderpath = imagefolder;
            bool alreadyRequesting = false;
            lock (outstandingRequests)
            {
                if (outstandingRequests.ContainsKey(assetID))
                {
                    alreadyRequesting = true;
                }
            }
            if (!alreadyRequesting && File.Exists(System.IO.Path.Combine(texturefolderpath, assetID.ToString() + ".tga")))
            {
                Texture texTnorm = Reference.VideoDriver.GetTexture(System.IO.Path.Combine(texturefolderpath, assetID.ToString() + ".tga"));
                if (texTnorm != null)
                    tex = new TextureExtended(texTnorm.Raw, ".tga");
                if (tex != null)
                {
                    lock (memoryTextures)
                    {
                        if (!memoryTextures.ContainsKey(assetID))
                        {
                            // Add it to the texture cache.
                            memoryTextures.Add(assetID, tex);
                        }
                    }

                    // apply texture
                    applyTexture(tex, requestor, assetID);

                    // Apply the texture to all objects that are already waiting for this texture
                    lock (outstandingRequests)
                    {
                        if (outstandingRequests.ContainsKey(assetID))
                        {
                            m_log.Warn("[TEXTURE]: Applying texture from memory to outstanding requestors.");
                            foreach (VObject vObj in outstandingRequests[assetID])
                            {
                                applyTexture(tex, vObj, assetID);
                            }
                            outstandingRequests.Remove(assetID);
                        }
                    }

                    return;
                }

            }

            // Check if we've already got an outstanding request for this texture
            lock (outstandingRequests)
            {
                if (outstandingRequests.ContainsKey(assetID))
                {
                    // Add it to the objects to be notified when this texture download is complete.
                    outstandingRequests[assetID].Add(requestor);
                    return;
                }
                else
                {
                    // Create a new outstanding request entry
                    List<VObject> requestors = new List<VObject>();
                    requestors.Add(requestor);
                    outstandingRequests.Add(assetID,requestors);

                }
            }

            if (string.IsNullOrEmpty(Reference.Viewer.ProtocolManager.AvatarConnection.m_user.Network.AssetServerUri))
            {
                this.texDownloadStyle = TextureDownloadStyle.TEX_DOWNLOAD_LIBOMV;
            }

            TextureDownloadRequest req = new TextureDownloadRequest();
            req.uuid = assetID;
            downloadTextureQueue.Enqueue(req); // no need to lock b/c it's a BlockingQueue which needs no synchronization
            m_log.Info("[TEXTURE]: Added to DownloadTextureQueue current count " + downloadTextureQueue.Count);
            /*
            if (this.texDownloadStyle == TextureDownloadStyle.TEX_DOWNLOAD_LIBOMV)
            {
                // Request texture from LibOMV
                m_user.RequestTexture(assetID);
            }
            else
            {
                // request texture directly from assetserver via our own background thread
                TextureDownloadRequest req = new TextureDownloadRequest();
                req.uuid = assetID;
                downloadTextureQueue.Enqueue(req); // no need to lock b/c it's a BlockingQueue which needs no synchronization
            }
            */
        }
Example #53
0
        /// <summary>
        /// Bread and butter of the texture system.
        /// This is the start point for the texture-> graphics pipeline
        /// </summary>
        /// <param name="tex"></param>
        /// <param name="vObj"></param>
        /// <param name="AssetID"></param>
        public void applyTexture(TextureExtended tex, VObject vObj, UUID AssetID)
        {
            //return;
            try
            {
                // works
                if (vObj.Mesh == null)
                    return;

                // Check if we have a  sculptie and its sculpting texture
                // If yes, don't apply the texture
                if (vObj.Prim.Sculpt != null && vObj.Prim.Sculpt.SculptTexture == AssetID)
                {
                    m_log.Debug("[TEXTURE]: Skipping applyTexture for sculpt " + AssetID);
                    return;
                }

                bool alphaimage = false;

#if YK_ADD_DEFAULT_TEXTURE
                if (tex == null)
                    tex = defaultTexture;
#endif
                // Check if we've already run this through our image alpha checker
                if (tex.Userdata == null)
                {
                    // Check if this image has an alpha channel in use
                    // All textures are 32 Bit and alpha capable, so we have to scan it for an 
                    // alpha pixel
                    Color[,] imgcolors;

                    //tex.Lock();
                    try
                    {
                        imgcolors = tex.Retrieve();
                        //tex.Unlock();
                        for (int i = 0; i < imgcolors.GetUpperBound(0); i++)
                        {
                            for (int j = 0; j < imgcolors.GetUpperBound(1); j++)
                            {
                                if (imgcolors[i, j].A != 255)
                                {
                                    alphaimage = true;
                                    break;
                                }
                            }
                            if (alphaimage)
                                break;
                        }
                    }
                    catch (OutOfMemoryException)
                    {
                        alphaimage = false;
                    }
                    // Save result
                    tex.Userdata = (object)alphaimage;
                }
                else
                {
                    // Use cached result
                    alphaimage = (bool)tex.Userdata;
                }


//#if NOTYET
                if (vObj._3DiIrrfileUUID != UUID.Zero && vObj.IrrData != null)
                {
#if DebugTexturePipeline
                    m_log.Debug("[3Di Mesh]: 3Di mesh applyTexture for tex " + AssetID + " for irrfile " + vObj._3DiIrrfileUUID);
#endif
                    for (int iTex = 0; iTex < vObj.IrrData.Materials.Count; iTex++)
                    {
#if DebugTexturePipeline
                        m_log.Debug("[3Di Mesh]: This mesh references a texture num " + iTex + ": " + vObj.IrrData.Materials[iTex].Texture1);
#endif
                        if (System.IO.Path.GetFileNameWithoutExtension(vObj.IrrData.Materials[iTex].Texture1) == AssetID.ToString())
                        {
#if DebugTexturePipeline
                            m_log.Debug("[3Di Mesh]: Found the texture reference inside the mesh; loading texture and re-assigning the reference.");
#endif
                            Texture loadedTex = device.VideoDriver.GetTexture(AssetID.ToString() + tex.extension);
                            if (vObj.Node.Children.Length > 0)
                            {
                                vObj.Node.Children[0].GetMaterial(iTex).Texture1 = loadedTex;
                            }
                            else
                            {
#if DebugTexturePipeline
                                m_log.Debug("[3Di Mesh]: Could not assign texture; mesh child not found");
#endif
                            }
                        }
                    }
#if DebugTexturePipeline
                    m_log.Debug("[3Di Mesh]: Finished all materials in this mesh.");
#endif
                    if (alphaimage)
                    {
                        vObj.Node.Children[0].SetMaterialType(MaterialType.TransparentAlphaChannel);
                        device.SceneManager.RegisterNodeForRendering(vObj.Node.Children[0], SceneNodeRenderPass.Transparent);
                    }

                }
                else 
//#endif


                // Apply the Texture based on the TextureEntry
                if(vObj.Prim.Textures != null)
                {
                    device.SceneManager.MeshCache.RemoveMesh(vObj.Mesh);
                    // Check the default texture to ensure that it's not null (why would it be null?)
                    if (vObj.Prim.Textures.DefaultTexture != null)
                    {
                        Color4 coldata = vObj.Prim.Textures.DefaultTexture.RGBA;

                        float shinyval = 0;
                        switch (vObj.Prim.Textures.DefaultTexture.Shiny)
                        {
                            case Shininess.Low:
                                shinyval = 0.8f;
                                coldata.R *= 0.8f;
                                coldata.B *= 0.8f;
                                coldata.G *= 0.8f;
                                break;
                            case Shininess.Medium:
                                shinyval = 0.7f;
                                coldata.R *= 0.6f;
                                coldata.B *= 0.6f;
                                coldata.G *= 0.6f;
                                break;
                            case Shininess.High:
                                shinyval = 0.6f;
                                coldata.R *= 0.3f;
                                coldata.B *= 0.3f;
                                coldata.G *= 0.3f;
                                break;
                        }
                        
                        // The mesh buffers correspond to the faces defined in the textureentry

                        int mbcount = vObj.Mesh.MeshBufferCount;
                        for (int j = 0; j < mbcount; j++)
                        {
                            // Only apply default texture if there isn't one already!
                            // we don't want to overwrite a face specific texture with the default
                            if (vObj.Prim.Textures.DefaultTexture.TextureID == AssetID)
                            {
                                ApplyFaceSettings(vObj, alphaimage, vObj.Prim.Textures.DefaultTexture, tex, j, shinyval, coldata);

                            }
                            else
                            {
                                // Apply color settings
                                ApplyFaceSettings(vObj, alphaimage, vObj.Prim.Textures.DefaultTexture, null, j, shinyval, coldata);
                            }


                            vObj.Mesh.GetMeshBuffer(j).Material.NormalizeNormals = true;
                            vObj.Mesh.GetMeshBuffer(j).Material.GouraudShading = true;
                            vObj.Mesh.GetMeshBuffer(j).Material.BackfaceCulling = (this.texDownloadStyle == TextureDownloadStyle.TEX_DOWNLOAD_ASSETSERVER);
                        }

                    }

                    // default taken care of..   now on to the individual face settings.
                    for (int i = 0; i < vObj.Prim.Textures.FaceTextures.Length; i++)
                    {
                        if (vObj.Prim.Textures.FaceTextures[i] != null)
                        {
                            Primitive.TextureEntryFace teface = vObj.Prim.Textures.FaceTextures[i];

                            if (vObj.Mesh.MeshBufferCount > i)
                            {
                                //if (tex.
                                Color4 coldata = teface.RGBA;
                                float shinyval = 0;
                                switch (teface.Shiny)
                                {
                                    case Shininess.Low:
                                        shinyval = 0.8f;
                                        coldata.R *= 0.8f;
                                        coldata.B *= 0.8f;
                                        coldata.G *= 0.8f;
                                        break;
                                    case Shininess.Medium:
                                        shinyval = 0.7f;
                                        coldata.R *= 0.6f;
                                        coldata.B *= 0.6f;
                                        coldata.G *= 0.6f;
                                        break;
                                    case Shininess.High:
                                        shinyval = 0.6f;
                                        coldata.R *= 0.3f;
                                        coldata.B *= 0.3f;
                                        coldata.G *= 0.3f;
                                        break;
                                }

                                // Apply texture only if this face has it linked
                                if (teface.TextureID == AssetID)
                                {
                                    ApplyFaceSettings(vObj, alphaimage, teface, tex, i, shinyval, coldata);
                                }
                                else
                                {
                                    // Only apply the color settings..
                                    ApplyFaceSettings(vObj, alphaimage, teface, null, i, shinyval, coldata);
                                }
                                vObj.Mesh.GetMeshBuffer(i).Material.NormalizeNormals = true;
                                vObj.Mesh.GetMeshBuffer(i).Material.GouraudShading = true;
                                vObj.Mesh.GetMeshBuffer(i).Material.BackfaceCulling = (this.texDownloadStyle == TextureDownloadStyle.TEX_DOWNLOAD_ASSETSERVER);
                            }
                            else
                            {
                                m_log.Warn("[TEXTUREDEF]: Unable to apply Texture to face because mesh buffer doesn't have definition for face");

                            }
                        }// end check if textureentry face is null
                    } // end loop over textureentry faces array

                    if (vObj.Node is MeshSceneNode)
                    {
                        MeshSceneNode msn = (MeshSceneNode)vObj.Node;
                        
                        msn.SetMesh(vObj.Mesh);
                        if (vObj.Prim.Textures != null)
                        {
                            // Check the default texture to ensure that it's not null (why would it be null?)
                            if (vObj.Prim.Textures.DefaultTexture != null)
                            {
                                Color4 coldata = vObj.Prim.Textures.DefaultTexture.RGBA;
                                IrrlichtNETCP.Color objColor = new Color(
                                    Util.Clamp<int>((int)(coldata.A * 255), 0, 255),
                                    Util.Clamp<int>((int)(coldata.R * 255), 0, 255),
                                    Util.Clamp<int>((int)(coldata.G * 255), 0, 255),
                                    Util.Clamp<int>((int)(coldata.B * 255), 0, 255)
                                    );

                                // Set material color.
                                for (int i = 0; i < msn.MaterialCount; i++)
                                {
#if MATERIAL_DEBUG
                                    lock(NativeElement.Elements) {System.Diagnostics.Debug.WriteLine("Element count before get:" + NativeElement.Elements.Count);}
#endif
                                    msn.GetMaterial(i).AmbientColor = objColor;
#if MATERIAL_DEBUG
                                    lock (NativeElement.Elements) { System.Diagnostics.Debug.WriteLine("Element count after get:" + NativeElement.Elements.Count); }
#endif
                                    msn.GetMaterial(i).DiffuseColor = objColor;
                                    msn.GetMaterial(i).SpecularColor = Color.Black;
                                    msn.GetMaterial(i).EmissiveColor = Color.Black;
                                    msn.GetMaterial(i).Shininess = 0;
                                }
                            }
                        }

#if RECALC_BOUNDINGBOX
                        Box3D box = new Box3D(0, 0, 0, 0, 0, 0);
                        for (int i = 0; i < msn.GetMesh().MeshBufferCount; i++)
                        {
                            msn.GetMesh().GetMeshBuffer(i).RecalculateBoundingBox();
                            box.AddInternalBox(msn.GetMesh().GetMeshBuffer(i).BoundingBox);
                        }
                        msn.GetMesh().BoundingBox = box;
#endif
                    }
                    else
                    {
                        // Swap out the visible untextured object with a textured one.
                        // SceneNode sn = device.SceneManager.AddMeshSceneNode(vObj.Mesh, ParentNode, -1);
                        // ZAKI: Change TextureManager Parent to actual parent node
                        SceneNode sn = device.SceneManager.AddMeshSceneNode(vObj.Mesh, vObj.Node.Parent, -1);
                        sn.Position = vObj.Node.Position;
                        sn.Rotation = vObj.Node.Rotation;
                        sn.Scale = vObj.Node.Scale;
                        sn.DebugDataVisible = DebugSceneType.Off;

                        // If it's translucent, register it for the Transparent phase of rendering
                        if (vObj.Prim.Textures.DefaultTexture.RGBA.A != 1)
                        {
                            device.SceneManager.RegisterNodeForRendering(sn, SceneNodeRenderPass.Transparent);
                        }
                        // Add the new triangle selector
                        sn.TriangleSelector = device.SceneManager.CreateTriangleSelector(vObj.Mesh, sn);
                        sn.TriangleSelector.Drop();
                        Reference.Viewer.EntityManager.AddTriangleSelector(sn.TriangleSelector, sn); 

                        // Delete the old node. 
                        SceneNode oldnode = vObj.Node;
                        Reference.Viewer.EntityManager.DeleteNode(oldnode);

                        // Assign new node
                        vObj.Node = sn;

                    }
                } // prim texture is not null


            }
            catch (AccessViolationException)
            {
                VUtil.LogConsole(this.ToString() + "[ACCESSVIOLATION]", " TextureManager::ApplyTexture");
                m_log.Error("[TEXTURE]: Failed to load texture.");
            }
            catch (NullReferenceException)
            {
                m_log.Error("unable to update texture");
            }
        }