예제 #1
0
        public override void LeaveObject(ObjectNode objectNode)
        {
            base.LeaveObject(objectNode);

            if(objectNode.ShouldWrite)
                Emit(string.Format("print '</{0}>';" + Environment.NewLine, objectNode.ObjectClass.Name));
        }
 public DynamicObjectMemberNode(ObjectNode parent, DynamicObject item, int maxDepth, DataContextDriver dcDriver) : base(parent, item, maxDepth, dcDriver)
 {
     base.Name = "DynamicObject";
     base.Summary = item.ToString();
     if (base.Summary.Length > 150)
     {
         base.Summary = base.Summary.Substring(0, 150) + "...";
     }
     IEnumerable<string> dynamicMemberNames = item.GetDynamicMemberNames();
     if (dynamicMemberNames.Any<string>() && (base.CyclicReference == null))
     {
         if (!(!base.IsAtNestingLimit() || (base.Parent is ListNode)))
         {
             base.GraphTruncated = true;
         }
         else
         {
             foreach (string str in dynamicMemberNames)
             {
                 object propValue = this.GetPropValue(item, str);
                 base.Members.Add(new MemberData(str, null, ObjectNode.Create(this, propValue, false, maxDepth, dcDriver)));
             }
         }
     }
 }
 public DataRecordMemberNode(ObjectNode parent, Type[] types, IDataRecord r, int maxDepth, DataContextDriver dcDriver) : base(parent, r, maxDepth, dcDriver)
 {
     if (base.IsAtNestingLimit())
     {
         base.GraphTruncated = true;
     }
     else
     {
         for (int i = 0; i < r.FieldCount; i++)
         {
             object item = r.GetValue(i);
             Type type = null;
             if (types != null)
             {
                 type = types[i];
             }
             else if (item != null)
             {
                 type = item.GetType();
             }
             if (!(item is IDataRecord))
             {
             }
             base.Members.Add(new MemberData(r.GetName(i), type, ObjectNode.Create(this, item, maxDepth, base.DCDriver)));
         }
         if ((base.Members.Count > 50) && (base.NestingDepth > 1))
         {
             base.InitiallyHidden = true;
         }
     }
 }
예제 #4
0
 public HeaderItem(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSymbol, ISymbolNode endSymbol)
 {
     Id = id;
     Node = node;
     StartSymbol = startSymbol;
     EndSymbol = endSymbol;
 }
 public CustomMemberProviderNode(ObjectNode parent, object item, int maxDepth, DataContextDriver dcDriver, bool useDataContextDriver) : base(parent, item, maxDepth, dcDriver)
 {
     base.Name = item.GetType().FormatTypeName();
     if (base.IsAtNestingLimit())
     {
         base.GraphTruncated = true;
     }
     else
     {
         IEnumerable<string> names;
         IEnumerable<Type> types;
         IEnumerable<object> values;
         if (useDataContextDriver)
         {
             ICustomMemberProvider customDisplayMemberProvider = dcDriver.GetCustomDisplayMemberProvider(item);
             names = customDisplayMemberProvider.GetNames();
             types = customDisplayMemberProvider.GetTypes();
             values = customDisplayMemberProvider.GetValues();
         }
         else
         {
             Type type2 = item.GetType().GetInterfaces().First<Type>(t => t.FullName == typeof(ICustomMemberProvider).FullName);
             MethodInfo method = type2.GetMethod("GetNames");
             MethodInfo info2 = type2.GetMethod("GetTypes");
             MethodInfo info3 = type2.GetMethod("GetValues");
             names = (IEnumerable<string>) method.Invoke(item, null);
             types = (IEnumerable<Type>) info2.Invoke(item, null);
             values = (IEnumerable<object>) info3.Invoke(item, null);
         }
         IEnumerator<Type> enumerator = types.GetEnumerator();
         enumerator.MoveNext();
         IEnumerator<object> enumerator2 = values.GetEnumerator();
         enumerator2.MoveNext();
         foreach (string str in names)
         {
             object current;
             try
             {
                 current = enumerator2.Current;
             }
             catch (Exception innerException)
             {
                 if ((innerException is TargetInvocationException) && (innerException.InnerException != null))
                 {
                     innerException = innerException.InnerException;
                 }
                 current = innerException;
             }
             base.Members.Add(new MemberData(str, enumerator.Current, ObjectNode.Create(this, current, maxDepth, dcDriver)));
             enumerator.MoveNext();
             enumerator2.MoveNext();
         }
         if ((base.Members.Count > 50) && (base.NestingDepth > 1))
         {
             base.InitiallyHidden = true;
         }
     }
 }
예제 #6
0
        public override void EnterObject(ObjectNode objectNode)
        {
            base.EnterObject(objectNode);

            if(++objectCount % 100 == 0)
                Emit(string.Format("print '#{0}';" + Environment.NewLine, objectCount));

            if(objectNode.ShouldWrite)
                Emit(string.Format("print '<{0}>';" + Environment.NewLine, objectNode.ObjectClass.Name));
        }
 /// <summary>
 /// Loads the asset for the specified path and filename. Used for loading player and mob prefabs.
 /// </summary>
 /// <returns>The asset.</returns>
 /// <param name="node">The ObjectNode of the player/mob.</param>
 /// <param name="path">Path.</param>
 /// <param name="fileName">File name.</param>
 public override object LoadAsset(ObjectNode node, string path, string fileName)
 {
     string prefabName = path + fileName;
     if (prefabName.Contains(".prefab"))
     {
         prefabName = prefabName.Remove(prefabName.Length - 7);
         prefabName = prefabName.Remove(0, 17);
         return Resources.Load(prefabName);
     } else {
         return Resources.Load (prefabName);
     }
 }
예제 #8
0
        public void LoadObjectNode()
        {
            RtfTree tree = new RtfTree();
            tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf");

            RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode;

            ObjectNode objNode = new ObjectNode(node);

            Assert.That(objNode.ObjectType, Is.EqualTo("objemb"));
            Assert.That(objNode.ObjectClass, Is.EqualTo("Excel.Sheet.8"));
        }
예제 #9
0
 public MultiDimArrayNode(ObjectNode parent, Array array, string name) : base(parent, array, 0, null)
 {
     if (name == null)
     {
         this.Name = array.GetType().GetElementType().FormatTypeName() + "[,]";
     }
     else
     {
         this.Name = name;
     }
     this.ElementType = array.GetType().GetElementType();
     this.Data = array;
 }
예제 #10
0
 public SimpleNode(ObjectNode parent, string text, string tip, SimpleNodeKind nodeKind) : base(parent, text, 0, null)
 {
     if (text == null)
     {
         this.NodeKind = SimpleNodeKind.Metadata;
         this.Text = "null";
     }
     else
     {
         this.Text = text;
         this.NodeKind = nodeKind;
     }
     this.ToolTip = tip;
 }
예제 #11
0
파일: Scalar.cs 프로젝트: virmitio/clrplus
        public Scalar(ObjectNode context, IEnumerable<Token> singleExpression)
        {
            var item = singleExpression.ToList();

            // trim off whitespace
            while (item.Count > 0 && item[0].IsWhitespaceOrComment) {
                item.RemoveAt(0);
            }
            while (item.Count > 0 && item[item.Count - 1].IsWhitespaceOrComment) {
                item.RemoveAt(item.Count - 1);
            }

            // may have to expand out certian types of tokens here.
            _content = item.Aggregate("", (current, each) => current + each.Data);
            Context = context;
        }
예제 #12
0
        public Scalar(ObjectNode context, IEnumerable<Token> singleExpression, string sourceFile) {
            var item = singleExpression.ToList();

            // trim off whitespace 
            while (item.Count > 0 && item[0].IsWhitespaceOrComment) {
                item.RemoveAt(0);
            }
            _sourceLocations = new[] { new SourceLocation(item.FirstOrDefault(), sourceFile) };

            while (item.Count > 0 && item[item.Count - 1].IsWhitespaceOrComment) {
                item.RemoveAt(item.Count - 1);
            }

            // may have to expand out certian types of tokens here.
            _content = item.Aggregate("", (current, each) => current + each.Data);
            Context = context;
        }
예제 #13
0
        public void ObjectBinData()
        {
            RtfTree tree = new RtfTree();
            tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf");

            RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode;

            ObjectNode objNode = new ObjectNode(node);

            BinaryWriter bw = new BinaryWriter(new FileStream("..\\..\\testdocs\\objbindata-result.dat", FileMode.Create));
            foreach (byte b in objNode.GetByteData())
                bw.Write(b);
            bw.Close();

            FileStream fs1 = new FileStream("..\\..\\testdocs\\objbindata-result.dat", FileMode.Open);
            FileStream fs2 = new FileStream("..\\..\\testdocs\\objbindata.dat", FileMode.Open);

            Assert.That(fs1, Is.EqualTo(fs2));
        }
예제 #14
0
 public DataRowNode(ObjectNode parent, DataRow item, int maxDepth, DataContextDriver dcDriver) : base(parent, item, maxDepth, dcDriver)
 {
     base.Name = "DataRow";
     if (base.IsAtNestingLimit())
     {
         base.GraphTruncated = true;
     }
     else
     {
         foreach (DataColumn column in item.Table.Columns)
         {
             object obj2 = item[column];
             base.Members.Add(new MemberData(column.ColumnName, column.DataType, ObjectNode.Create(this, obj2, maxDepth, dcDriver)));
         }
         if ((base.Members.Count > 50) && (base.NestingDepth > 1))
         {
             base.InitiallyHidden = true;
         }
     }
 }
예제 #15
0
 protected abstract void DumpObjectNode(NameMangler mangler, ObjectNode node, ObjectData objectData);
예제 #16
0
        /// <summary>
        /// Collects the child methods of a Node.
        /// </summary>
        private bool CollectMethods(Node node, bool testErrors, List <TestMethod> methods)
        {
            if (node == null || node.NodeClass != NodeClass.Method)
            {
                return(true);
            }

            MethodNode method = node as MethodNode;

            IList <INode> parents = Session.NodeCache.Find(
                node.NodeId,
                ReferenceTypeIds.HasComponent,
                true,
                true);

            for (int ii = 0; ii < parents.Count; ii++)
            {
                ObjectNode parent = parents[ii] as ObjectNode;

                if (parent != null && method != null)
                {
                    if (!testErrors && parent.BrowseName.Name != "MethodTest")
                    {
                        continue;
                    }

                    bool found = false;

                    for (int jj = 0; jj < methods.Count; jj++)
                    {
                        if (Object.ReferenceEquals(method, methods[jj].Method))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (found)
                    {
                        continue;
                    }

                    TestMethod test = new TestMethod();

                    test.Parent          = parent;
                    test.Method          = method;
                    test.InputArguments  = new Argument[0];
                    test.OutputArguments = new Argument[0];
                    test.Inputs          = new List <object>();

                    methods.Add(test);

                    if (methods.Count % 25 == 0)
                    {
                        Log("Found for {0} Methods to Call", methods.Count);
                    }

                    IList <INode> properties = Session.NodeCache.Find(
                        method.NodeId,
                        ReferenceTypeIds.HasProperty,
                        false,
                        true);

                    for (int jj = 0; jj < properties.Count; jj++)
                    {
                        VariableNode property = properties[jj] as VariableNode;

                        if (property != null)
                        {
                            if (property.BrowseName == BrowseNames.InputArguments)
                            {
                                if (property.Value.Value == null)
                                {
                                    DataValue value = Session.ReadValue(property.NodeId);
                                    property.Value = value.WrappedValue;
                                }

                                test.InputArguments = (Argument[])ExtensionObject.ToArray(property.Value.Value as Array, typeof(Argument));

                                if (test.InputArguments == null)
                                {
                                    Log(
                                        "Could not read input arguments for method '{0}'. NodeId = {1}, Method = {2}",
                                        test.Parent,
                                        test.Parent.NodeId,
                                        test.Method);

                                    return(false);
                                }

                                continue;
                            }

                            if (property.BrowseName == BrowseNames.OutputArguments)
                            {
                                if (property.Value.Value == null)
                                {
                                    DataValue value = Session.ReadValue(property.NodeId);
                                    property.Value = value.WrappedValue;
                                }

                                test.OutputArguments = (Argument[])ExtensionObject.ToArray(property.Value.Value as Array, typeof(Argument));

                                if (test.OutputArguments == null)
                                {
                                    Log(
                                        "Could not read output arguments for method '{0}'. NodeId = {1}, Method = {2}",
                                        test.Parent,
                                        test.Parent.NodeId,
                                        test.Method);

                                    return(false);
                                }

                                continue;
                            }
                        }
                    }
                }
            }

            return(true);
        }
예제 #17
0
 string GetValueFromVariable(ObjectNode variable)
 {
     return(variable == null ? string.Empty : variable.Value.ReturnValue.ToString());
 }
예제 #18
0
 public void Setup()
 {
     _parent = new ObjectNode(_context, null,
                              new SimpleValue(new object(), typeof(object).ToCachedType()), null, null);
 }
예제 #19
0
        /// <see cref="BaseTreeCtrl.EnableMenuItems" />
        protected override void EnableMenuItems(TreeNode clickedNode)
        {
            BrowseOptionsMI.Enabled   = true;
            ShowReferencesMI.Enabled  = true;
            SelectMI.Visible          = m_allowPick;
            SelectSeparatorMI.Visible = m_allowPick;

            if (clickedNode != null)
            {
                // do nothing if an error is detected.
                if (m_browser.Session.KeepAliveStopped)
                {
                    return;
                }

                SelectMI.Enabled         = true;
                SelectItemMI.Enabled     = true;
                SelectChildrenMI.Enabled = clickedNode.Nodes.Count > 0;
                BrowseRefreshMI.Enabled  = true;

                ReferenceDescription reference = clickedNode.Tag as ReferenceDescription;

                if (reference != null)
                {
                    BrowseMI.Enabled         = (reference.NodeId != null && !reference.NodeId.IsAbsolute);
                    ViewAttributesMI.Enabled = true;

                    NodeId nodeId = ExpandedNodeId.ToNodeId(reference.NodeId, m_browser.Session.NamespaceUris);

                    INode node = m_browser.Session.ReadNode(nodeId);

                    byte accessLevel   = 0;
                    byte eventNotifier = 0;
                    bool executable    = false;

                    VariableNode variableNode = node as VariableNode;

                    if (variableNode != null)
                    {
                        accessLevel = variableNode.UserAccessLevel;
                    }

                    ObjectNode objectNode = node as ObjectNode;

                    if (objectNode != null)
                    {
                        eventNotifier = objectNode.EventNotifier;
                    }

                    ViewNode viewNode = node as ViewNode;

                    if (viewNode != null)
                    {
                        eventNotifier = viewNode.EventNotifier;
                    }

                    MethodNode methodNode = node as MethodNode;

                    if (methodNode != null)
                    {
                        executable = methodNode.UserExecutable;
                    }

                    ReadMI.Visible          = false;
                    HistoryReadMI.Visible   = false;
                    WriteMI.Visible         = false;
                    HistoryUpdateMI.Visible = false;
                    EncodingsMI.Visible     = false;
                    SubscribeMI.Visible     = false;
                    CallMI.Visible          = false;

                    if (accessLevel != 0)
                    {
                        ReadMI.Visible          = true;
                        HistoryReadMI.Visible   = true;
                        WriteMI.Visible         = true;
                        HistoryUpdateMI.Visible = true;
                        EncodingsMI.Visible     = true;
                        SubscribeMI.Visible     = m_SessionTreeCtrl != null;

                        if ((accessLevel & (byte)AccessLevels.CurrentRead) != 0)
                        {
                            ReadMI.Enabled         = true;
                            EncodingsMI.Enabled    = true;
                            SubscribeMI.Enabled    = true;
                            SubscribeNewMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.CurrentWrite) != 0)
                        {
                            WriteMI.Enabled     = true;
                            EncodingsMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.HistoryRead) != 0)
                        {
                            HistoryReadMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.HistoryWrite) != 0)
                        {
                            HistoryUpdateMI.Enabled = true;
                        }
                    }

                    if (eventNotifier != 0)
                    {
                        HistoryReadMI.Visible   = true;
                        HistoryUpdateMI.Visible = true;
                        SubscribeMI.Visible     = true;

                        if ((eventNotifier & (byte)EventNotifiers.HistoryRead) != 0)
                        {
                            HistoryReadMI.Enabled = true;
                        }

                        if ((eventNotifier & (byte)EventNotifiers.HistoryWrite) != 0)
                        {
                            HistoryUpdateMI.Enabled = true;
                        }

                        SubscribeMI.Enabled    = (eventNotifier & (byte)EventNotifiers.SubscribeToEvents) != 0;
                        SubscribeNewMI.Enabled = SubscribeMI.Enabled;
                    }

                    if (methodNode != null)
                    {
                        CallMI.Visible = true;
                        CallMI.Enabled = executable;
                    }

                    if (variableNode != null && EncodingsMI.Enabled)
                    {
                        ReferenceDescriptionCollection encodings = m_browser.Session.ReadAvailableEncodings(variableNode.NodeId);

                        if (encodings.Count == 0)
                        {
                            EncodingsMI.Visible = false;
                        }
                    }

                    if (SubscribeMI.Enabled)
                    {
                        while (SubscribeMI.DropDown.Items.Count > 1)
                        {
                            SubscribeMI.DropDown.Items.RemoveAt(SubscribeMI.DropDown.Items.Count - 1);
                        }

                        foreach (Subscription subscription in m_browser.Session.Subscriptions)
                        {
                            if (subscription.Created)
                            {
                                ToolStripItem item = SubscribeMI.DropDown.Items.Add(subscription.DisplayName);
                                item.Click += new EventHandler(Subscription_Click);
                                item.Tag    = subscription;
                            }
                        }
                    }
                }
            }
        }
 protected bool RightKind(ObjectNode node)
 {
     return((kind == StaticGeometryKind.BigOrLittleNode ||
             (node.PerceptionRadius == 0) == (kind == StaticGeometryKind.LittleNode)) &&
            (node.Entity == null || node.Entity.Mesh.Skeleton == null));
 }
 private void TreeViewBeforeSelect(object sender, TreeViewCancelEventArgs e)
 {
     LoggingService.InfoFormatted("新选中节点:{0}", new object[] { e.Node.Text });
     if (this.lastNode != e.Node)
     {
         if (((this.lastNode != null) && (PropertyView.Instance != null)) && (PropertyView.Instance.PropertyEditPanel != null))
         {
             LoggingService.Info("检查数据是否已经修改...");
             PropertyView.Instance.PropertyEditPanel.PostEditor();
             if ((this.lastNode != null) && PropertyView.Instance.IsDirty)
             {
                 if (MessageHelper.ShowYesNoInfo("数据已修改,是否保存?") == DialogResult.Yes)
                 {
                     try
                     {
                         PropertyView.Instance.Save();
                         this.lastNode.PropertyChanged();
                     }
                     catch (Exception exception)
                     {
                         LoggingService.ErrorFormatted("保存数据出错:{0}\r\n", new object[] { exception.Message, exception.StackTrace });
                         MessageHelper.ShowError("保存数据出错", exception);
                         e.Cancel = true;
                     }
                 }
                 else
                 {
                     PropertyView.Instance.CancelEdit();
                 }
             }
         }
         ObjectNode node = e.Node as ObjectNode;
         if (node != null)
         {
             this.lastNode = node;
             if (LoggingService.IsInfoEnabled)
             {
                 LoggingService.Info("will select object node...");
             }
             node.Select();
         }
     }
 }
        public void Indexer_should_return_null_if_key_is_not_found()
        {
            var node = new ObjectNode(new ISettingsNode[] {});

            node["key"].Should().BeNull();
        }
예제 #23
0
 public Collection(ObjectNode context, IEnumerable <IValue> values)
 {
     Context = context;
     AddRange(values);
 }
예제 #24
0
 public Collection(ObjectNode context)
 {
     Context = context;
 }
        public override IntPtr OnEntryPoint(MethodEntrypointPtr methodEntrypoint, IntPtr callerArgs)
        {
            lock (this)
            {
                if (_corInfoImpl == null)
                {
                    InitJitCodeManager(RuntimeAugments.RhGetOSModuleForMrt());

                    // TODO: Recycle jit interface object and TypeSystemContext
                    _context = TypeSystemContextFactory.Create();

                    Compilation compilation = new Compilation(_context);
                    _nodeFactory = compilation.NodeFactory;

                    JitConfigProvider configProvider = new JitConfigProvider(new CorJitFlag[] { CorJitFlag.CORJIT_FLAG_DEBUG_CODE }, Array.Empty <KeyValuePair <string, string> >());

                    _corInfoImpl = new CorInfoImpl(compilation, configProvider);
                }

                MethodDesc methodToCompile = methodEntrypoint.MethodIdentifier.ToMethodDesc(_context);

                JitMethodCodeNode codeNode = new JitMethodCodeNode(methodToCompile);
                _corInfoImpl.CompileMethod(codeNode);

                ObjectNode.ObjectData codeData = codeNode.GetData(null, false);

                List <ObjectNode> nodesToEmit = new List <ObjectNode>();
                Dictionary <DependencyNodeCore <NodeFactory>, object> relocTargets = new Dictionary <DependencyNodeCore <NodeFactory>, object>();
                int totalAllocSizeNeeded  = 0;
                int nonObjectRelocTargets = 0;

                nodesToEmit.Add(codeNode);
                UpdateBytesUsed(codeNode.GetData(_nodeFactory), ref totalAllocSizeNeeded);

                int offsetOfEHData = totalAllocSizeNeeded;

                if (codeNode.EHInfo != null)
                {
                    Debug.Assert(codeNode.EHInfo.Alignment == 1); // Assert needed as otherwise offsetOfEHData will be wrong

                    UpdateBytesUsed(codeNode.EHInfo, ref totalAllocSizeNeeded);
                    ComputeDependencySizeAndRelocData(codeNode.EHInfo, relocTargets, nodesToEmit, ref totalAllocSizeNeeded, ref nonObjectRelocTargets);
                }

                for (int i = 0; i < nodesToEmit.Count; i++)
                {
                    ObjectNode objNode = nodesToEmit[i];
                    ComputeDependencySizeAndRelocData(objNode.GetData(_nodeFactory, true), relocTargets, nodesToEmit, ref totalAllocSizeNeeded, ref nonObjectRelocTargets);
                }

                if (nonObjectRelocTargets != 0)
                {
                    totalAllocSizeNeeded = totalAllocSizeNeeded.AlignUp(IntPtr.Size);
                }

                int relocTargetOffsetStart = totalAllocSizeNeeded;

                DependencyNodeCore <NodeFactory>[] relocTargetsArray = new DependencyNodeCore <NodeFactory> [nonObjectRelocTargets];
                {
                    int iRelocTarget = 0;
                    foreach (var relocTarget in relocTargets)
                    {
                        if (!(relocTarget.Key is ObjectNode))
                        {
                            relocTargetsArray[iRelocTarget] = relocTarget.Key;
                            totalAllocSizeNeeded           += IntPtr.Size;
                            iRelocTarget++;
                        }
                    }
                    Debug.Assert(iRelocTarget == nonObjectRelocTargets);
                }

                GenericDictionaryCell[] genDictCells = new GenericDictionaryCell[relocTargetsArray.Length];
                for (int iRelocTarget = 0; iRelocTarget < relocTargetsArray.Length; iRelocTarget++)
                {
                    DependencyNodeCore <NodeFactory> relocTarget = relocTargetsArray[iRelocTarget];
                    GenericDictionaryCell            newCell     = null;

                    if (relocTarget is ExternObjectSymbolNode)
                    {
                        var externObjectSymbolNode = (ExternObjectSymbolNode)relocTarget;
                        var newMethodCell          = externObjectSymbolNode.GetDictionaryCell();
                        newCell = newMethodCell;
                    }

                    if (newCell == null)
                    {
                        Environment.FailFast("Unknown reloc target type");
                    }
                    genDictCells[iRelocTarget] = newCell;
                }

                IntPtr[] relocTargetsAsIntPtr = null;

                TypeLoaderEnvironment.Instance.RunUnderTypeLoaderLock(
                    () =>
                {
                    TypeBuilderApi.ResolveMultipleCells(genDictCells, out relocTargetsAsIntPtr);
                });

                // Layout of allocated memory...
                // ObjectNodes (aligned as appropriate)
                IntPtr pCodeManager;
                IntPtr jittedCode    = AllocJittedCode(checked ((uint)totalAllocSizeNeeded), 8 /* TODO, alignment calculation */, out pCodeManager);
                int    currentOffset = 0;

                foreach (var node in nodesToEmit)
                {
                    ObjectNode.ObjectData objectData = node.GetData(_nodeFactory);
                    EmitAndRelocData(objectData, jittedCode, relocTargetOffsetStart, ref currentOffset, relocTargetsArray, relocTargetsAsIntPtr);

                    // EHInfo doesn't get its own node, but it does get emitted into the stream.
                    if ((node == codeNode) && (codeNode.EHInfo != null))
                    {
                        Debug.Assert(offsetOfEHData == currentOffset);
                        EmitAndRelocData(codeNode.EHInfo, jittedCode, relocTargetOffsetStart, ref currentOffset, relocTargetsArray, relocTargetsAsIntPtr);
                    }
                }

                foreach (IntPtr ptr in relocTargetsAsIntPtr)
                {
                    currentOffset = currentOffset.AlignUp(IntPtr.Size);
                    Marshal.WriteIntPtr(jittedCode, currentOffset, ptr);
                    currentOffset += IntPtr.Size;
                }

                SetEHInfoPtr(pCodeManager, jittedCode, jittedCode + offsetOfEHData);

                IntPtr mainRuntimeFunction = IntPtr.Zero;

                for (int i = 0; i < codeNode.FrameInfos.Length; i++)
                {
                    FrameInfo frame           = codeNode.FrameInfos[i];
                    byte[]    frameData       = frame.BlobData;
                    byte[]    gcInfoData      = Array.Empty <byte>();
                    byte[]    gcInfoDataDeref = frameData;

                    if (i == 0)
                    {
                        // For main function, add the gc info to the data
                        gcInfoDataDeref = gcInfoData = codeNode.GCInfo;
                    }

                    IntPtr publishedFunction = PublishRuntimeFunction(pCodeManager,
                                                                      jittedCode,
                                                                      mainRuntimeFunction,
                                                                      checked ((uint)frame.StartOffset),
                                                                      checked ((uint)frame.EndOffset),
                                                                      frameData,
                                                                      checked ((uint)frameData.Length),
                                                                      gcInfoDataDeref,
                                                                      checked ((uint)gcInfoData.Length));

                    if (i == 0)
                    {
                        mainRuntimeFunction = publishedFunction;
                    }
                }

                if (mainRuntimeFunction != IntPtr.Zero)
                {
                    UpdateRuntimeFunctionTable(pCodeManager);
                }

                methodEntrypoint.MethodCode = jittedCode;

                return(jittedCode);
            }
        }
        private void GenerateMemberAssignment(CodeMemberMethod initComponentMethod, MemberNode member, CodeExpression targetExpression, CodeExpression valueExpression, CodeDomObjectNode targetObjectNode)
        {
            CodeStatement cs = null;

            //if (member.Member.IsUnknown)
            //{
            //    throw new Exception("Unknown member " + member.Member.Name);
            //}
            if (member.Member == XamlLanguage.Items)
            {
                ObjectNode parentObjectNode = member.ParentObjectNode;
                XamlType   parentType       = null;
                if (parentObjectNode.IsGetObject)
                {
                    parentType = parentObjectNode.ParentMemberNode.Member.Type;
                }
                else
                {
                    parentType = parentObjectNode.Type;
                }
                if (parentType.IsDictionary)
                {
                    if (!typeof(IDictionary).IsAssignableFrom(parentType.UnderlyingType))
                    {
                        throw new NotImplementedException("Support non-IDictionary adds");
                    }
                    CodeExpression keyExpression;
                    if (targetObjectNode.XKeyNode != null)
                    {
                        keyExpression = new CodeSnippetExpression("\"" + ((ValueNode)targetObjectNode.XKeyNode.ItemNodes[0]).Value + "\"");
                    }
                    else
                    {
                        if (targetObjectNode.DictionaryKeyProperty == null)
                        {
                            throw new NotSupportedException("No key on dictionary entry");
                        }
                        throw new NotImplementedException();
                    }
                    cs = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IDictionary), targetExpression), "Add", keyExpression, valueExpression));
                }
                else
                {
                    if (!typeof(IList).IsAssignableFrom(parentType.UnderlyingType))
                    {
                        throw new NotImplementedException("Support non-IList adds");
                    }
                    //TODO: calling Add directly is how I'll leave it for now...
                    //cs = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IList), targetExpression), "Add", valueExpression));
                    cs = new CodeExpressionStatement(new CodeMethodInvokeExpression(targetExpression, "Add", valueExpression));
                }
            }
            else if (member.Member.IsEvent)
            {
                throw new NotImplementedException();
            }
            else
            {
                if (member.Member.IsAttachable)
                {
                    cs = new CodeExpressionStatement(new CodeMethodInvokeExpression(
                                                         new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(member.Member.DeclaringType.UnderlyingType.Name),
                                                                                           "Set" + member.Member.Name), targetExpression, valueExpression));
                }
                else //normal property
                {
                    cs = new CodeAssignStatement(
                        new CodePropertyReferenceExpression(targetExpression, member.Member.Name), valueExpression);
                }
            }
            initComponentMethod.Statements.Add(cs);
        }
예제 #27
0
 public Iterator(ObjectNode context, IValue chainedSource)
     : this(context, chainedSource.SourceLocations.ToArray())
 {
     Add(chainedSource);
 }
예제 #28
0
 public Iterator(ObjectNode context, params SourceLocation[] sourceLocation)
 {
     _sourceLocations = sourceLocation;
     Context          = context;
 }
예제 #29
0
파일: XMLRenderer.cs 프로젝트: wrmsr/xdc
 public override void LeaveObject(ObjectNode objectNode)
 {
     xw.WriteEndElement();
 }
        public void Indexer_should_return_null_if_children_is_null()
        {
            var node = new ObjectNode(null as ISettingsNode[]);

            node["key"].Should().BeNull();
        }
예제 #31
0
        public void ResultNode()
        {
            RtfTree tree = new RtfTree();
            tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf");

            RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode;

            ObjectNode objNode = new ObjectNode(node);

            RtfTreeNode resNode = objNode.ResultNode;

            Assert.That(resNode, Is.SameAs(tree.MainGroup.SelectSingleGroup("object").SelectSingleChildGroup("result")));

            RtfTreeNode pictNode = resNode.SelectSingleNode("pict").ParentNode;
            ImageNode imgNode = new ImageNode(pictNode);

            Assert.That(imgNode.Height, Is.EqualTo(2247));
            Assert.That(imgNode.Width, Is.EqualTo(9320));

            Assert.That(imgNode.DesiredHeight, Is.EqualTo(1274));
            Assert.That(imgNode.DesiredWidth, Is.EqualTo(5284));

            Assert.That(imgNode.ScaleX, Is.EqualTo(100));
            Assert.That(imgNode.ScaleY, Is.EqualTo(100));

            Assert.That(imgNode.ImageFormat, Is.EqualTo(ImageFormat.Emf));
        }
        public async Task <ActionResult> GetChildren(string jstreeNode)
        {
            string[] publishedNodes = await GetListofPublishedNodeIDsforServer();

            // This delimiter is used to allow the storing of the OPC UA parent node ID together with the OPC UA child node ID in jstree data structures and provide it as parameter to
            // Ajax calls.
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            ReferenceDescriptionCollection references;

            Byte[] continuationPoint;
            var    jsonTree = new List <object>();

            bool retry = true;

            while (true)
            {
                try
                {
                    Session session = await OpcSessionHelper.Instance.GetSessionAsync(Session.SessionID, (string)Session["EndpointUrl"]);

                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    session.Browse(
                        null,
                        null,
                        node,
                        0u,
                        BrowseDirection.Forward,
                        ReferenceTypeIds.HierarchicalReferences,
                        true,
                        0,
                        out continuationPoint,
                        out references);

                    Trace.TraceInformation("Browse {0} ms", stopwatch.ElapsedMilliseconds);

                    if (references != null)
                    {
                        var idList = new List <string>();
                        foreach (var nodeReference in references)
                        {
                            bool idFound = false;
                            foreach (var id in idList)
                            {
                                if (id == nodeReference.NodeId.ToString())
                                {
                                    idFound = true;
                                }
                            }
                            if (idFound == true)
                            {
                                continue;
                            }

                            ReferenceDescriptionCollection childReferences = null;
                            Byte[] childContinuationPoint;

                            session.Browse(
                                null,
                                null,
                                ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris),
                                0u,
                                BrowseDirection.Forward,
                                ReferenceTypeIds.HierarchicalReferences,
                                true,
                                0,
                                out childContinuationPoint,
                                out childReferences);

                            INode currentNode = null;
                            try
                            {
                                currentNode = session.ReadNode(ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris));
                            }
                            catch (Exception)
                            {
                                // skip this node
                                continue;
                            }

                            byte currentNodeAccessLevel   = 0;
                            byte currentNodeEventNotifier = 0;
                            bool currentNodeExecutable    = false;

                            VariableNode variableNode = currentNode as VariableNode;
                            if (variableNode != null)
                            {
                                currentNodeAccessLevel = variableNode.UserAccessLevel;
                                if (!PermsChecker.HasPermission(Permission.ControlOpcServer))
                                {
                                    currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                                }
                            }

                            ObjectNode objectNode = currentNode as ObjectNode;
                            if (objectNode != null)
                            {
                                currentNodeEventNotifier = objectNode.EventNotifier;
                            }

                            ViewNode viewNode = currentNode as ViewNode;
                            if (viewNode != null)
                            {
                                currentNodeEventNotifier = viewNode.EventNotifier;
                            }

                            MethodNode methodNode = currentNode as MethodNode;
                            if (methodNode != null && PermsChecker.HasPermission(Permission.ControlOpcServer))
                            {
                                currentNodeExecutable = methodNode.UserExecutable;
                            }

                            var published = false;
                            foreach (var nodeId in publishedNodes)
                            {
                                if (nodeId == nodeReference.NodeId.ToString())
                                {
                                    published = true;
                                }
                            }

                            jsonTree.Add(new
                            {
                                id            = ("__" + node + delimiter[0] + nodeReference.NodeId.ToString()),
                                text          = nodeReference.DisplayName.ToString(),
                                nodeClass     = nodeReference.NodeClass.ToString(),
                                accessLevel   = currentNodeAccessLevel.ToString(),
                                eventNotifier = currentNodeEventNotifier.ToString(),
                                executable    = currentNodeExecutable.ToString(),
                                children      = (childReferences.Count == 0) ? false : true,
                                publishedNode = published
                            });
                            idList.Add(nodeReference.NodeId.ToString());
                        }

                        // If there are no children, then this is a call to read the properties of the node itself.
                        if (jsonTree.Count == 0)
                        {
                            INode currentNode = session.ReadNode(new NodeId(node));

                            byte currentNodeAccessLevel   = 0;
                            byte currentNodeEventNotifier = 0;
                            bool currentNodeExecutable    = false;

                            VariableNode variableNode = currentNode as VariableNode;

                            if (variableNode != null)
                            {
                                currentNodeAccessLevel = variableNode.UserAccessLevel;
                                if (!PermsChecker.HasPermission(Permission.ControlOpcServer))
                                {
                                    currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                                }
                            }

                            ObjectNode objectNode = currentNode as ObjectNode;

                            if (objectNode != null)
                            {
                                currentNodeEventNotifier = objectNode.EventNotifier;
                            }

                            ViewNode viewNode = currentNode as ViewNode;

                            if (viewNode != null)
                            {
                                currentNodeEventNotifier = viewNode.EventNotifier;
                            }

                            MethodNode methodNode = currentNode as MethodNode;

                            if (methodNode != null && PermsChecker.HasPermission(Permission.ControlOpcServer))
                            {
                                currentNodeExecutable = methodNode.UserExecutable;
                            }

                            jsonTree.Add(new
                            {
                                id            = jstreeNode,
                                text          = currentNode.DisplayName.ToString(),
                                nodeClass     = currentNode.NodeClass.ToString(),
                                accessLevel   = currentNodeAccessLevel.ToString(),
                                eventNotifier = currentNodeEventNotifier.ToString(),
                                executable    = currentNodeExecutable.ToString(),
                                children      = false
                            });
                        }
                    }

                    stopwatch.Stop();
                    Trace.TraceInformation("GetChildren took {0} ms", stopwatch.ElapsedMilliseconds);

                    return(Json(jsonTree, JsonRequestBehavior.AllowGet));
                }
                catch (Exception exception)
                {
                    OpcSessionHelper.Instance.Disconnect(Session.SessionID);
                    if (!retry)
                    {
                        return(Content(CreateOpcExceptionActionString(exception)));
                    }
                    retry = false;
                }
            }
        }
예제 #33
0
 public MultiDimArrayNode(ObjectNode parent, Array array) : this(parent, array, null)
 {
 }
예제 #34
0
 public HeaderItem(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSymbol)
 {
     Id          = id;
     Node        = node;
     StartSymbol = startSymbol;
 }
예제 #35
0
 public void Add(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSymbol)
 {
     _items.Add(new HeaderItem(id, node, startSymbol));
 }
예제 #36
0
 public string Format(ObjectNode node)
 {
     node.Accept(this);
     return(Regex.Replace(new XElement("div", node.Accept(this)).ToString(), @"[\u0080-\uFFFF]", (MatchEvaluator)(m => ("&#" + ((int)m.Value[0]).ToString() + ";"))));
 }
예제 #37
0
 public Instruction(ObjectNode context, string instructionText, params SourceLocation[] sourceLocations) {
     InstructionText = instructionText;
     Context = context;
     _sourceLocations = sourceLocations;
 }
예제 #38
0
        public Tree GetChildren(string node)
        {
            ReferenceDescriptionCollection references;

            Byte[] continuationPoint;
            Tree   browserTree = new Tree();

            try
            {
                session.Browse(
                    null,
                    null,
                    node,
                    0u,
                    BrowseDirection.Forward,
                    ReferenceTypeIds.HierarchicalReferences,
                    true,
                    0,
                    out continuationPoint,
                    out references);

                if (references != null)
                {
                    foreach (var nodeReference in references)
                    {
                        ReferenceDescriptionCollection childReferences = null;
                        Byte[] childContinuationPoint;

                        session.Browse(
                            null,
                            null,
                            ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris),
                            0u,
                            BrowseDirection.Forward,
                            ReferenceTypeIds.HierarchicalReferences,
                            true,
                            0,
                            out childContinuationPoint,
                            out childReferences);

                        INode currentNode = null;
                        try
                        {
                            currentNode = session.ReadNode(ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris));
                        }
                        catch (Exception)
                        {
                            // skip this node
                            continue;
                        }

                        byte currentNodeAccessLevel   = 0;
                        byte currentNodeEventNotifier = 0;
                        bool currentNodeExecutable    = false;

                        VariableNode variableNode = currentNode as VariableNode;
                        if (variableNode != null)
                        {
                            currentNodeAccessLevel = variableNode.UserAccessLevel;
                            currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                        }

                        ObjectNode objectNode = currentNode as ObjectNode;
                        if (objectNode != null)
                        {
                            currentNodeEventNotifier = objectNode.EventNotifier;
                        }

                        ViewNode viewNode = currentNode as ViewNode;
                        if (viewNode != null)
                        {
                            currentNodeEventNotifier = viewNode.EventNotifier;
                        }

                        MethodNode methodNode = currentNode as MethodNode;
                        if (methodNode != null)
                        {
                            currentNodeExecutable = methodNode.UserExecutable;
                        }

                        browserTree.currentView.Add(new ListNode()
                        {
                            id            = nodeReference.NodeId.ToString(),
                            NodeName      = nodeReference.DisplayName.Text.ToString(),
                            nodeClass     = nodeReference.NodeClass.ToString(),
                            accessLevel   = currentNodeAccessLevel.ToString(),
                            eventNotifier = currentNodeEventNotifier.ToString(),
                            executable    = currentNodeExecutable.ToString(),
                            children      = (references?.Count != 0),
                            ImageUrl      = (nodeReference.NodeClass.ToString() == "Variable") ? "folderOpen.jpg" : "folder.jpg"
                        });
                        if (browserTree.currentView[0].ImageUrl == null)
                        {
                            browserTree.currentView[0].ImageUrl = "";
                        }
                    }
                    if (browserTree.currentView.Count == 0)
                    {
                        INode currentNode = session.ReadNode(new NodeId(node));

                        byte currentNodeAccessLevel   = 0;
                        byte currentNodeEventNotifier = 0;
                        bool currentNodeExecutable    = false;

                        VariableNode variableNode = currentNode as VariableNode;

                        if (variableNode != null)
                        {
                            currentNodeAccessLevel = variableNode.UserAccessLevel;
                            currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                        }

                        ObjectNode objectNode = currentNode as ObjectNode;

                        if (objectNode != null)
                        {
                            currentNodeEventNotifier = objectNode.EventNotifier;
                        }

                        ViewNode viewNode = currentNode as ViewNode;

                        if (viewNode != null)
                        {
                            currentNodeEventNotifier = viewNode.EventNotifier;
                        }

                        MethodNode methodNode = currentNode as MethodNode;

                        if (methodNode != null)
                        {
                            currentNodeExecutable = methodNode.UserExecutable;
                        }

                        browserTree.currentView.Add(new ListNode()
                        {
                            id            = node,
                            NodeName      = currentNode.DisplayName.Text.ToString(),
                            nodeClass     = currentNode.NodeClass.ToString(),
                            accessLevel   = currentNodeAccessLevel.ToString(),
                            eventNotifier = currentNodeEventNotifier.ToString(),
                            executable    = currentNodeExecutable.ToString(),
                            children      = false,
                            ImageUrl      = null
                        });
                    }
                }
                return(browserTree);
            }
            catch
            {
                Disconnect(session);
                return(null);
            }
        }
예제 #39
0
 public ClrMemberNode(ObjectNode parent, object item, int maxDepth, DataContextDriver dcDriver) : base(parent, item, maxDepth, dcDriver)
 {
     base.Name = item.GetType().FormatTypeName();
     Type type = item.GetType();
     if (!((base.CyclicReference != null) || base.IsAtNestingLimit()))
     {
         base.InitiallyHidden = ((((item is MemberInfo) || (item is RuntimeMethodHandle)) || ((item is CultureInfo) || (item is ProcessModule))) || (((item is Uri) || (item is Version)) || ((type.Namespace == "Microsoft.SqlServer.Types") || (type.FullName == "System.Data.EntityKey")))) || ((type.Namespace != null) && (type.Namespace.StartsWith("System.Reflection", StringComparison.Ordinal) || type.Namespace.StartsWith("System.IO", StringComparison.Ordinal)));
     }
     if (item is Type)
     {
         base.Name = "typeof(" + ((Type) item).Name + ")";
     }
     if (!base.Name.StartsWith("{", StringComparison.Ordinal))
     {
         if ((item is MethodBase) && (((MethodBase) item).DeclaringType != null))
         {
             MethodBase base2 = (MethodBase) item;
             string[] strArray = new string[] { base2.DeclaringType.FormatTypeName(), ".", base2.Name, " (", string.Join(", ", (from p in base2.GetParameters() select p.ParameterType.FormatTypeName() + " " + p.Name).ToArray<string>()), ")" };
             base.Summary = string.Concat(strArray);
         }
         else
         {
             try
             {
                 base.Summary = item.ToString();
             }
             catch
             {
             }
         }
     }
     if (base.Summary.Length > 150)
     {
         base.Summary = base.Summary.Substring(0, 150) + "...";
     }
     FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
     PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
     if (((fields.Length != 0) || (properties.Length != 0)) && (base.CyclicReference == null))
     {
         if (!((!base.IsAtNestingLimit() || Util.IsMetaGraphNode(item)) || (base.Parent is ListNode)))
         {
             base.GraphTruncated = true;
         }
         else
         {
             object obj2;
             bool isAnonType = base.IsAnonType;
             Func<object> getter = null;
             foreach (FieldInfo fi in fields)
             {
                 if (isAnonType || (((fi.GetCustomAttributes(typeof(AssociationAttribute), true).Length == 0) && !fi.FieldType.FullName.StartsWith("System.Data.Objects.DataClasses.EntityReference")) && !IsUnloadedEntityAssociation(item, fi)))
                 {
                     if (getter == null)
                     {
                         getter = () => fi.GetValue(item);
                     }
                     obj2 = this.GetValue(fi, getter, isAnonType);
                     base.Members.Add(new MemberData(fi.Name, fi.FieldType, ObjectNode.Create(this, obj2, item is Exception, maxDepth, dcDriver)));
                 }
             }
             foreach (PropertyInfo pi in properties)
             {
                 if ((pi.GetIndexParameters().Length == 0) && (isAnonType || ((((pi.GetCustomAttributes(typeof(AssociationAttribute), true).Length == 0) && !pi.PropertyType.FullName.StartsWith("System.Data.Objects.DataClasses.EntityReference")) && ((pi.PropertyType.FullName != "System.Data.EntityKey") && (pi.PropertyType.FullName != "System.Data.EntityState"))) && !IsUnloadedEntityAssociation(item, pi))))
                 {
                     bool exceptionThrown = false;
                     obj2 = this.GetValue(pi, () => this.GetPropValue(pi, item, out exceptionThrown), isAnonType);
                     bool flag2 = exceptionThrown && ((item is Exception) || ((parent != null) && (parent.ObjectValue is Exception)));
                     base.Members.Add(new MemberData(pi.Name, pi.PropertyType, ObjectNode.Create(this, obj2, item is Exception, flag2 ? 1 : maxDepth, dcDriver)));
                 }
             }
             if ((base.Members.Count > 50) && (base.NestingDepth > 1))
             {
                 base.InitiallyHidden = true;
             }
         }
     }
 }
예제 #40
0
 private GUIObjectNodeHelper(ObjectNode objectNode, InterfaceableContainerPropertyDrawer.SerializedContainer serializedContainer)
 {
     _objectNode          = objectNode;
     _serializedContainer = serializedContainer;
     _displayFoldout      = _objectNode.Children.Any();
 }
예제 #41
0
 void IObjectDumper.DumpObjectNode(NameMangler mangler, ObjectNode node, ObjectData objectData) => DumpObjectNode(mangler, node, objectData);
예제 #42
0
 public virtual bool TryTransform([NotNull] ObjectNode objectNode, out ISettingsNode transformedNode)
 {
     transformedNode = null;
     return(false);
 }
예제 #43
0
        private String GetCodeForObjectNode(ObjectNode node, NodeFactory factory)
        {
            // virtual slots
            var nodeData = node.GetData(factory, false);

            CppGenerationBuffer nodeCode = new CppGenerationBuffer();

            /* Create list of byte data. Used to divide contents between reloc and byte data
             * First val - isReloc
             * Second val - size of byte data if first value of tuple is false
             */

            List <NodeDataSection> nodeDataSections = new List <NodeDataSection>();

            byte[]       actualData = new byte[nodeData.Data.Length];
            Relocation[] relocs     = nodeData.Relocs;

            int nextRelocOffset = -1;
            int nextRelocIndex  = -1;
            int lastByteIndex   = 0;

            if (relocs.Length > 0)
            {
                nextRelocOffset = relocs[0].Offset;
                nextRelocIndex  = 0;
            }

            int i      = 0;
            int offset = 0;
            CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer();

            if (node is ISymbolDefinitionNode)
            {
                offset        = (node as ISymbolDefinitionNode).Offset;
                i             = offset;
                lastByteIndex = offset;
            }
            while (i < nodeData.Data.Length)
            {
                if (i == nextRelocOffset)
                {
                    Relocation reloc = relocs[nextRelocIndex];

                    int size = _compilation.TypeSystemContext.Target.PointerSize;
                    // Make sure we've gotten the correct size for the reloc
                    System.Diagnostics.Debug.Assert(reloc.RelocType == (size == 8 ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW));

                    // Update nextRelocIndex/Offset
                    if (++nextRelocIndex < relocs.Length)
                    {
                        nextRelocOffset = relocs[nextRelocIndex].Offset;
                    }
                    nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.Relocation, size));
                    i            += size;
                    lastByteIndex = i;
                }
                else
                {
                    i++;
                    if (i + 1 == nextRelocOffset || i + 1 == nodeData.Data.Length)
                    {
                        nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.ByteData, (i + 1) - lastByteIndex));
                    }
                }
            }
            string pointerType = node is EETypeNode ? "MethodTable * " : "void* ";

            nodeCode.Append(pointerType);
            if (node is EETypeNode)
            {
                nodeCode.Append(GetCppMethodDeclarationName((node as EETypeNode).Type, "__getMethodTable"));
            }
            else
            {
                string mangledName = ((ISymbolNode)node).GetMangledName(factory.NameMangler);

                // Rename generic composition and optional fields nodes to avoid name clash with types
                bool shouldReplaceNamespaceQualifier = node is GenericCompositionNode || node is EETypeOptionalFieldsNode;
                nodeCode.Append(shouldReplaceNamespaceQualifier ? mangledName.Replace("::", "_") : mangledName);
            }
            nodeCode.Append("()");
            nodeCode.AppendLine();
            nodeCode.Append("{");
            nodeCode.Indent();
            nodeCode.AppendLine();
            nodeCode.Append("static struct {");

            nodeCode.AppendLine();
            nodeCode.Append(GetCodeForNodeStruct(nodeDataSections, node));

            nodeCode.AppendLine();
            nodeCode.Append("} mt = {");
            nodeCode.Append(GetCodeForNodeData(nodeDataSections, relocs, nodeData.Data, node, offset, factory));

            nodeCode.Append("};");
            nodeCode.AppendLine();
            nodeCode.Append("return ( ");
            nodeCode.Append(pointerType);
            nodeCode.Append(")&mt;");
            nodeCode.Exdent();
            nodeCode.AppendLine();
            nodeCode.Append("}");
            nodeCode.AppendLine();
            return(nodeCode.ToString());
        }
예제 #44
0
 public ObjectIterator(ObjectNode context, params SourceLocation[] sourceLocation) : base(context, sourceLocation)
 {
 }
예제 #45
0
파일: EdgeAnalyzer.cs 프로젝트: sys27/Edge
        private void CheckCtor(SyntaxTree tree, Type objType, ObjectNode objNode)
        {
            ConstructorInfo   ctor;
            List <IValueNode> args = null;

            if (objNode.ConstructorArguments != null)
            {
                args = objNode.ConstructorArguments.ToList();
            }

            if (objNode.ConstructorArguments == null || args.Count == 0)
            {
                ctor = objType.GetConstructor(Type.EmptyTypes);
                if (ctor != null)
                {
                    return;
                }
            }
            else
            {
                var types = new Type[args.Count];

                var strType    = typeof(string);
                var doubleType = typeof(double);

                for (int i = 0; i < types.Length; i++)
                {
                    var t = args[0];

                    var refType = t as ReferenceNode;
                    if (refType != null)
                    {
                        types[i] = CheckType(refType.Type);
                    }
                    else if (t is StringNode)
                    {
                        types[i] = strType;
                    }
                    else if (t is NumberNode)
                    {
                        types[i] = doubleType;
                    }
                    else if (t is EnumNode)
                    {
                        types[i] = CheckType(((EnumNode)t).Type);
                    }
                    else
                    {
                        // todo: error message
                        throw new EdgeParserException();
                    }
                }

                ctor = objType.GetConstructor(types);
                if (ctor != null)
                {
                    return;
                }

                // ctor type inference
                // todo: refactor!!!
                var avaliableCtors = objType.GetConstructors()
                                     .Select(t => t.GetParameters())
                                     .Where(t => t.Length == types.Length)
                                     .ToArray();
                var uriType = typeof(Uri);

                for (int i = 0; i < avaliableCtors.Length && ctor == null; i++)
                {
                    var currentCtor = avaliableCtors[i];

                    for (int j = 0; j < currentCtor.Length && ctor == null; j++)
                    {
                        if (currentCtor[j].ParameterType == uriType && types[j] == strType)
                        {
                            types[j] = uriType;

                            // id
                            var    urlStrType = char.ToLowerInvariant(uriType.Name[0]) + uriType.Name.Substring(1);
                            string id         = null;
                            for (int k = 1; k < int.MaxValue; k++)
                            {
                                id = urlStrType + k;
                                if (!tree.Objects.Any(obj => obj.Id == id))
                                {
                                    break;
                                }
                            }
                            if (id == null)
                            {
                                // todo: message
                                throw new EdgeAnalyzerException();
                            }

                            tree.AddObject(new ObjectNode(uriType.Name, id, new[] { args[j] }));
                            args[j] = new ReferenceNode(id, uriType.Name);

                            ctor = objType.GetConstructor(types);
                        }
                    }
                }

                // todo: fix
                if (ctor != null)
                {
                    objNode.ConstructorArguments = args;

                    return;
                }
            }

            // todo: error message
            throw new EdgeAnalyzerException();
        }
예제 #46
0
 public void EmitDebugVarInfo(ObjectNode node)
 {
     // No interest if it's not a debug node.
     var nodeWithDebugInfo = node as INodeWithDebugInfo;
     if (nodeWithDebugInfo != null)
     {
         DebugVarInfo[] vars = nodeWithDebugInfo.DebugVarInfos;
         if (vars != null)
         {
             foreach (var v in vars)
             {
                 EmitDebugVar(v);
             }
         }
     }
 }
예제 #47
0
파일: XMLRenderer.cs 프로젝트: wrmsr/xdc
        public override void EnterObject(ObjectNode objectNode)
        {
            xw.WriteStartElement(objectNode.ObjectClass.Name);

            xw.WriteAttributeString("Name", objectNode.Name);
        }
예제 #48
0
        public void BuildCFIMap(NodeFactory factory, ObjectNode node)
        {
            _offsetToCfis.Clear();
            _offsetToCfiStart.Clear();
            _offsetToCfiEnd.Clear();
            _frameOpened = false;

            INodeWithCodeInfo nodeWithCodeInfo = node as INodeWithCodeInfo;
            if (nodeWithCodeInfo == null)
            {
                return;
            }

            FrameInfo[] frameInfos = nodeWithCodeInfo.FrameInfos;
            if (frameInfos == null)
            {
                return;
            }

            ObjectNode.ObjectData ehInfo = nodeWithCodeInfo.EHInfo;

            int i = 0;
            foreach (var frameInfo in frameInfos)
            {
                int start = frameInfo.StartOffset;
                int end = frameInfo.EndOffset;
                int len = frameInfo.BlobData.Length;
                byte[] blob = frameInfo.BlobData;

                if (_targetPlatform.OperatingSystem == TargetOS.Windows)
                {
                    string blobSymbolName = "_unwind" + (i++).ToStringInvariant() + _currentNodeName;

                    ObjectNodeSection section = ObjectNodeSection.XDataSection;
                    if (node.ShouldShareNodeAcrossModules(factory) && factory.Target.OperatingSystem == TargetOS.Windows)
                    {
                        section = section.GetSharedSection(blobSymbolName);
                        CreateCustomSection(section);
                    }
                    SwitchSection(_nativeObjectWriter, section.Name);
                    
                    EmitAlignment(4);
                    EmitSymbolDef(blobSymbolName);

                    if (ehInfo != null)
                    {
                        blob[blob.Length - 1] |= 0x04; // Flag to indicate that EHClauses follows
                    }

                    EmitBlob(blob);

                    if (ehInfo != null)
                    {
                        Debug.Assert(ehInfo.Alignment == 1);
                        Debug.Assert(ehInfo.DefinedSymbols.Length == 0);
                        EmitBlobWithRelocs(ehInfo.Data, ehInfo.Relocs);
                        ehInfo = null;
                    }

                    // TODO: Currently we get linker errors if we emit frame info for shared types.
                    //       This needs follow-up investigation.
                    if (!node.ShouldShareNodeAcrossModules(factory))
                    {
                        // For window, just emit the frame blob (UNWIND_INFO) as a whole.
                        EmitWinFrameInfo(start, end, len, blobSymbolName);
                    }

                    EnsureCurrentSection();
                }
                else
                {
                    // For Unix, we build CFI blob map for each offset.
                    Debug.Assert(len % CfiCodeSize == 0);

                    // Record start/end of frames which shouldn't be overlapped.
                    _offsetToCfiStart.Add(start);
                    _offsetToCfiEnd.Add(end);
                    for (int j = 0; j < len; j += CfiCodeSize)
                    {
                        // The first byte of CFI_CODE is offset from the range the frame covers.
                        // Compute code offset from the root method.
                        int codeOffset = blob[j] + start;
                        List<byte[]> cfis;
                        if (!_offsetToCfis.TryGetValue(codeOffset, out cfis))
                        {
                            cfis = new List<byte[]>();
                            _offsetToCfis.Add(codeOffset, cfis);
                        }
                        byte[] cfi = new byte[CfiCodeSize];
                        Array.Copy(blob, j, cfi, 0, CfiCodeSize);
                        cfis.Add(cfi);
                    }
                }
            }
        }
예제 #49
0
 public override void LeaveObject(ObjectNode objectNode)
 {
     writeQueue.Enqueue(objectNode);
     Emit("print '-';" + Environment.NewLine);
 }
예제 #50
0
 public static Segment3D CalculateSegmentBetweenNodes(ObjectNode firstNode, ObjectNode secondNode)
 {
     return(new Segment3D(firstNode.ObjectSurfaceData.BasePosition, secondNode.ObjectSurfaceData.BasePosition));
 }
예제 #51
0
        private String GetCodeForObjectNode(ObjectNode node, NodeFactory factory)
        {
            // virtual slots
            var nodeData = node.GetData(factory, false);

            CppGenerationBuffer nodeCode = new CppGenerationBuffer();

            /* Create list of byte data. Used to divide contents between reloc and byte data
          * First val - isReloc
          * Second val - size of byte data if first value of tuple is false
          */

            List<NodeDataSection> nodeDataSections = new List<NodeDataSection>();
            byte[] actualData = new byte[nodeData.Data.Length];
            Relocation[] relocs = nodeData.Relocs;

            int nextRelocOffset = -1;
            int nextRelocIndex = -1;
            int lastByteIndex = 0;

            if (relocs.Length > 0)
            {
                nextRelocOffset = relocs[0].Offset;
                nextRelocIndex = 0;
            }

            int i = 0;
            int offset = 0;
            CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer();

            if (node is ISymbolNode)
            {
                offset = (node as ISymbolNode).Offset;
                i = offset;
                lastByteIndex = offset;
            }
            while (i < nodeData.Data.Length)
            {
                if (i == nextRelocOffset)
                {
                    Relocation reloc = relocs[nextRelocIndex];

                    int size = _compilation.TypeSystemContext.Target.PointerSize;
                    // Make sure we've gotten the correct size for the reloc
                    System.Diagnostics.Debug.Assert(reloc.RelocType == (size == 8 ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW));

                    // Update nextRelocIndex/Offset
                    if (++nextRelocIndex < relocs.Length)
                    {
                        nextRelocOffset = relocs[nextRelocIndex].Offset;
                    }
                    nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.Relocation, size));
                    i += size;
                    lastByteIndex = i;
                }
                else
                {
                    i++;
                    if (i + 1 == nextRelocOffset || i + 1 == nodeData.Data.Length)
                    {
                        nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.ByteData, (i + 1) - lastByteIndex));
                    }
                }
            }
            string pointerType = node is EETypeNode ? "MethodTable * " : "void* ";
            nodeCode.Append(pointerType);
            if (node is EETypeNode)
            {
                nodeCode.Append(GetCppMethodDeclarationName((node as EETypeNode).Type, "__getMethodTable"));
            }
            else
            {
                string mangledName = ((ISymbolNode)node).GetMangledName();

                // Rename generic composition and optional fields nodes to avoid name clash with types
                bool shouldReplaceNamespaceQualifier = node is GenericCompositionNode || node is EETypeOptionalFieldsNode;
                nodeCode.Append(shouldReplaceNamespaceQualifier ? mangledName.Replace("::", "_") : mangledName);
            }
            nodeCode.Append("()");
            nodeCode.AppendLine();
            nodeCode.Append("{");
            nodeCode.Indent();
            nodeCode.AppendLine();
            nodeCode.Append("static struct {");

            nodeCode.AppendLine();
            nodeCode.Append(GetCodeForNodeStruct(nodeDataSections, node));

            nodeCode.AppendLine();
            nodeCode.Append("} mt = {");
            nodeCode.Append(GetCodeForNodeData(nodeDataSections, relocs, nodeData.Data, node, offset, factory));

            nodeCode.Append("};");
            nodeCode.AppendLine();
            nodeCode.Append("return ( ");
            nodeCode.Append(pointerType);
            nodeCode.Append(")&mt;");
            nodeCode.Exdent();
            nodeCode.AppendLine();
            nodeCode.Append("}");
            nodeCode.AppendLine();
            return nodeCode.ToString();
        }
예제 #52
0
        public List <ObjectPlacementData> Calculate(Quaternion rotationToApplyForStrokeAlignment)
        {
            if (!ValidateCalculationRequirements())
            {
                return(new List <ObjectPlacementData>());
            }

            _objectNodeNetwork.Clear();
            _rotationToApplyForStrokeAlignment = rotationToApplyForStrokeAlignment;
            CreateSurfaceColliderProjector();
            _elementToNewPrefabRotation.Clear();
            _allowObjectIntersection = ObjectPlacementSettings.Get().ObjectIntersectionSettings.AllowIntersectionForDecorPaintBrushModeDrag;

            int currentObjectIndex           = 0;
            var objectPlacementDataInstances = new List <ObjectPlacementData>(_workingBrush.MaxNumberOfObjects);

            while (currentObjectIndex < _workingBrush.MaxNumberOfObjects)
            {
                DecorPaintObjectPlacementBrushElement brushElement = _brushElementSpawnChanceTable.PickEntity(UnityEngine.Random.Range(0.0f, 1.0f));
                int brushElementIndex = _allValidBrushElements.FindIndex(item => item == brushElement);
                ++currentObjectIndex;

                // No object nodes were created yet?
                if (_objectNodeNetwork.NumberOfNodes == 0)
                {
                    // Create the first node at a random position inside the brush circle
                    Vector3             randomPositionInsideCircle = _workingBrushCircle.GetRandomPointInside();
                    ObjectSurfaceData   objectSurfaceData          = CalculateObjectSurfaceData(randomPositionInsideCircle);
                    MatrixObjectBoxPair matrixObjectBoxPair        = CalculateMatrixObjectBoxPair(brushElementIndex, objectSurfaceData);

                    // We need to know if the normal of the surface on which the object resides lies within the desired slope range
                    bool passesSlopeTest = DoesObjectSurfacePassSlopeTest(objectSurfaceData, brushElement);

                    // Note: Even if the slope test is not passed, we will still create an object node. The reason for this is that
                    //       we want to have some kind of continuity in the algorithm. Imagine that the brush circle is large and is
                    //       divided by a large terrain mountain which sits in the middle. If the object generation starts on one side
                    //       of the mountain, the algorithm might never get a chance to go over the other side if the slope condition
                    //       is not satisifed. We want to spread objects as much as possible so even though this object will not be
                    //       placed in the scene, we will still add it to the node network.
                    _objectNodeNetwork.AddNodeToEnd(matrixObjectBoxPair.ObjectBox, objectSurfaceData);
                    if (passesSlopeTest && DoesBoxPassObjectIntersectionTest(matrixObjectBoxPair.ObjectBox, brushElement.Prefab.UnityPrefab, matrixObjectBoxPair.ObjectMatrix))
                    {
                        objectPlacementDataInstances.Add(new ObjectPlacementData(matrixObjectBoxPair.ObjectMatrix, brushElement.Prefab, brushElement.MustEmbedInSurface));
                    }
                }
                else
                {
                    // Are there any node segments available?
                    if (_objectNodeNetwork.NumberOfSegments != 0)
                    {
                        // The first step is to generate a random node index and store references to that node and its immediate neighbour
                        _objectNodeNetwork.RemoveAllNodesWhichGenerateConcavities(_workingBrushCircle.Plane);
                        int        randomNodeIndex = _objectNodeNetwork.GetRandomNodeIndex();
                        ObjectNode firstNode       = _objectNodeNetwork.GetNodeByIndex(randomNodeIndex);
                        ObjectNode secondNode      = _objectNodeNetwork.GetNodeByIndex(randomNodeIndex + 1);

                        // Calculate the plane of the segment which unites the 2 nodes. We will also store the
                        // actual segment and the middle point on the segment. We will use this middle point to
                        // generate the initial object position.
                        Segment3D   nodeSegment     = ObjectNodeNetwork.CalculateSegmentBetweenNodes(firstNode, secondNode);
                        Vector3     segmentMidPoint = nodeSegment.GetPoint(0.5f);
                        Plane       segmentPlane    = ObjectNodeNetwork.CalculateSegmentPlaneNormal(firstNode, secondNode);
                        OrientedBox firstNodeBox    = firstNode.ObjectBox;
                        OrientedBox secondNodeBox   = secondNode.ObjectBox;

                        // Calculate the furthest point in front of the plane using the corner points of the
                        // 2 nodes. The idea is to move the new object as much as possible from the bulk of
                        // objects that have already been generated.
                        Vector3        furthestPointFromPlane;
                        List <Vector3> nodeCornerPoints = firstNodeBox.GetCornerPoints();
                        nodeCornerPoints.AddRange(secondNodeBox.GetCornerPoints());
                        if (!segmentPlane.GetFurthestPointInFront(nodeCornerPoints, out furthestPointFromPlane))
                        {
                            continue;
                        }

                        // Use the calculated furthest point from plane and the the existing plane normal to calculate the
                        // pivot plane. The new object will reside at some distance away from this plane.
                        Plane pivotPlane = new Plane(segmentPlane.normal, furthestPointFromPlane);

                        // Calculate the new object transform data. We will use the segment's mid point to generate the
                        // initial object position.
                        ObjectSurfaceData   objectSurfaceData   = CalculateObjectSurfaceData(segmentMidPoint);
                        MatrixObjectBoxPair matrixObjectBoxPair = CalculateMatrixObjectBoxPair(brushElementIndex, objectSurfaceData);
                        OrientedBox         objectBox           = matrixObjectBoxPair.ObjectBox;

                        // Identify the objects's furthest point behind the plane
                        Vector3        objectBoxPivotPoint;
                        List <Vector3> objectBoxCornerPoints = objectBox.GetCornerPoints();
                        if (!pivotPlane.GetFurthestPointBehind(objectBoxCornerPoints, out objectBoxPivotPoint))
                        {
                            continue;
                        }

                        // Use the furthest point to move the object in front of the plane and take the distance between objects into account
                        Vector3 fromPivotPointToCenter = objectBox.Center - objectBoxPivotPoint;
                        Vector3 projectedPivotPoint    = pivotPlane.ProjectPoint(objectBoxPivotPoint);
                        objectBox.Center = projectedPivotPoint + fromPivotPointToCenter + pivotPlane.normal * _workingBrush.DistanceBetweenObjects;

                        // Generate the object surface data
                        objectSurfaceData = CalculateObjectSurfaceData(objectBox.Center);
                        bool passesSlopeTest = DoesObjectSurfacePassSlopeTest(objectSurfaceData, brushElement);

                        // Now we need to adjust the orientation and center of the box. If the calculated center
                        // lies outside the brush circle, we will ignore this node.
                        AdjustObjectBoxRotationOnSurface(objectBox, objectSurfaceData, brushElement);
                        AdjustObjectBoxCenterToSitOnSurface(objectBox, objectSurfaceData, brushElement);
                        if (!_workingBrushCircle.ContainsPoint(_workingBrushCircle.Plane.ProjectPoint(objectBox.Center)))
                        {
                            continue;
                        }

                        // Recalculate the object matrix using the new box data
                        TransformMatrix objectMatrix = matrixObjectBoxPair.ObjectMatrix;
                        objectMatrix.Rotation    = objectBox.Rotation;
                        objectMatrix.Translation = ObjectPositionCalculator.CalculateObjectHierarchyPosition(brushElement.Prefab, objectBox.Center, objectMatrix.Scale, objectBox.Rotation);

                        // We have been modifying the matrix and box data independently so we will ensure that the box uses the latest data
                        OrientedBox finalBox = new OrientedBox(objectBox);
                        finalBox.SetTransformMatrix(objectMatrix);

                        // If the slope test passed, we will calculate an object placement data instance. Otherwise, we will just insert a new node.
                        if (passesSlopeTest && DoesBoxPassObjectIntersectionTest(finalBox, brushElement.Prefab.UnityPrefab, objectMatrix))
                        {
                            objectPlacementDataInstances.Add(new ObjectPlacementData(objectMatrix, brushElement.Prefab, brushElement.MustEmbedInSurface));
                        }
                        _objectNodeNetwork.InsertAfterNode(objectBox, objectSurfaceData, randomNodeIndex);
                    }
                    else
                    {
                        // When there are no segments available it means we have only one node. We will use this node to generate
                        // a new one at some distance away from it. First we will store some data that we will need during the entire
                        // procedure.
                        ObjectNode  pivotNode = _objectNodeNetwork.GetFirstNode();
                        Vector3     pivotNodeSurfaceTangent = pivotNode.ObjectSurfaceData.GetSurfaceTangentVector();
                        OrientedBox pivotNodeObjectBox      = pivotNode.ObjectBox;

                        // We will place the new node at some distance away from the first node's face which points
                        // along the calculated tangent vector. We will call this the pivot face.
                        BoxFace pivotBoxFace   = pivotNodeObjectBox.GetBoxFaceMostAlignedWithNormal(pivotNodeSurfaceTangent);
                        Plane   pivotFacePlane = pivotNodeObjectBox.GetBoxFacePlane(pivotBoxFace);

                        // Generate the data for the new node in the same position as the first node.
                        // Note: Although the same position is used, the rotation and scale will differ and they will
                        //       be established by 'CalculateMatrixObjectBoxPair'.
                        MatrixObjectBoxPair matrixObjectBoxPair = CalculateMatrixObjectBoxPair(brushElementIndex, pivotNode.ObjectSurfaceData);
                        OrientedBox         objectBox           = matrixObjectBoxPair.ObjectBox;

                        // At this point we have to start moving the generated object box to its new positino along the
                        // tangent vector. We will do this by calculating the furthest box point which lies behind the
                        // pivot plane and then move the box so that this point resides on that plane. We will call this
                        // the pivot point.
                        // Note: We will perform a safety check to see if this point could not be calculated and use the
                        //       closest point in front if necessary. However, this check should not be necessary. Because
                        //       we are placing te object box in the center of the previous box, we can be usre that there
                        //       will always be a point which lies behind the pivot plane.
                        Vector3        objectBoxPivotPoint;
                        List <Vector3> objectBoxCornerPoints = objectBox.GetCornerPoints();
                        if (!pivotFacePlane.GetFurthestPointBehind(objectBoxCornerPoints, out objectBoxPivotPoint) &&
                            !pivotFacePlane.GetClosestPointInFront(objectBoxCornerPoints, out objectBoxPivotPoint))
                        {
                            continue;
                        }

                        // Project the pivot point onto the pivot plane. We will also store a vector which goes from the
                        // original pivot point to the box center. This will allow us to maintain the relationship between
                        // the projected pivot point and the box center so that the center can be adjusted accordingly.
                        Vector3 fromPivotPointToCenter = objectBox.Center - objectBoxPivotPoint;
                        Vector3 projectedPivotPoint    = pivotFacePlane.ProjectPoint(objectBoxPivotPoint);

                        // Adjust the center using the projected pivot point and also take the distance between objects into account
                        objectBox.Center = projectedPivotPoint + fromPivotPointToCenter + pivotNodeSurfaceTangent * _workingBrush.DistanceBetweenObjects;

                        // Generate the object surface data at the current box position.
                        // Note: This is the step which can actually cause objects to intersect a little bit. The surface data is
                        //       calculated by projecting along the brush circle plane normal. If we are placing objects on a terrain
                        //       and the center of the circle lies somewhere at the base of the terrain where the normal points straight
                        //       up, but the center of the box resides somewhere on a clif, the new center might move the box closer
                        //       or even further away from the pivot node. This however, should not be a problem especially if the distance
                        //       between objects is not 0.
                        ObjectSurfaceData objectSurfaceData = CalculateObjectSurfaceData(objectBox.Center);
                        bool passesSlopeTest = DoesObjectSurfacePassSlopeTest(objectSurfaceData, brushElement);

                        // Now we need to adjust the orientation and center of the box. If the calculated center
                        // lies outside the brush circle, we will ignore this node.
                        AdjustObjectBoxRotationOnSurface(objectBox, objectSurfaceData, brushElement);
                        AdjustObjectBoxCenterToSitOnSurface(objectBox, objectSurfaceData, brushElement);
                        if (!_workingBrushCircle.ContainsPoint(_workingBrushCircle.Plane.ProjectPoint(objectBox.Center)))
                        {
                            continue;
                        }

                        // Recalculate the object matrix using the new box data
                        TransformMatrix objectMatrix = matrixObjectBoxPair.ObjectMatrix;
                        objectMatrix.Rotation    = objectBox.Rotation;
                        objectMatrix.Translation = ObjectPositionCalculator.CalculateObjectHierarchyPosition(brushElement.Prefab, objectBox.Center, objectMatrix.Scale, objectBox.Rotation);

                        // We have been modifying the matrix and box data independently so we will ensure that the box uses the latest data
                        OrientedBox finalBox = new OrientedBox(objectBox);
                        finalBox.SetTransformMatrix(objectMatrix);

                        // If the slope test passed, we will calculate an object placement data instance. Otherwise, we will just insert a new node.
                        if (passesSlopeTest && DoesBoxPassObjectIntersectionTest(finalBox, brushElement.Prefab.UnityPrefab, objectMatrix))
                        {
                            objectPlacementDataInstances.Add(new ObjectPlacementData(objectMatrix, brushElement.Prefab, brushElement.MustEmbedInSurface));
                        }
                        _objectNodeNetwork.InsertAfterNode(objectBox, objectSurfaceData, 0);
                    }
                }
            }

            // Adjust the prefab rotations for the next time the function is called
            if (_elementToNewPrefabRotation.Count != 0)
            {
                foreach (var prefabRotationPair in _elementToNewPrefabRotation)
                {
                    DecorPaintObjectPlacementBrushElement brushElement = prefabRotationPair.Key;
                    if (_elementToCurrentPrefabRotation.ContainsKey(brushElement))
                    {
                        _elementToCurrentPrefabRotation[brushElement] = prefabRotationPair.Value;
                    }
                }
            }

            return(objectPlacementDataInstances);
        }
        /// <summary>
        /// Creates an Object node in the address space.
        /// </summary>
        public NodeId CreateObject(
            NodeId           parentId,
            NodeId           referenceTypeId,
            NodeId           nodeId,
            QualifiedName    browseName,
            ObjectAttributes attributes,
            ExpandedNodeId   typeDefinitionId)
        {
            try
            {
                m_lock.Enter();

                // validate browse name.
                if (QualifiedName.IsNull(browseName))
                {
                    throw ServiceResultException.Create(StatusCodes.BadBrowseNameInvalid, "BrowsName must not be empty.");
                }

                // check for null node id.
                if (NodeId.IsNull(nodeId))
                {
                    nodeId = CreateUniqueNodeId();
                }

                // check if node id exists.
                if (m_nodes.Exists(nodeId))
                {
                    throw ServiceResultException.Create(StatusCodes.BadNodeIdExists, "NodeId '{0}' already exists.", nodeId);
                }

                // find parent.
                ILocalNode parent = null;

                if (!NodeId.IsNull(parentId))
                {
                    parent = GetManagerHandle(parentId) as ILocalNode;

                    if (parent == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadParentNodeIdInvalid, "Parent node '{0}' does not exist.", parentId);
                    }

                    // validate reference.
                    ValidateReference(parent, referenceTypeId, false, NodeClass.Object);
                }

                // find type definition.
                if (NodeId.IsNull(typeDefinitionId))
                {
                    typeDefinitionId = ObjectTypes.BaseObjectType;
                }

                IObjectType objectType = GetManagerHandle(typeDefinitionId) as IObjectType;

                if (objectType == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadTypeDefinitionInvalid, "Type definition '{0}' does not exist or is not an ObjectType.", typeDefinitionId);
                }                               

                // verify instance declarations.
                ILocalNode instanceDeclaration = FindInstanceDeclaration(parent, browseName);

                if (instanceDeclaration != null)
                {
                    if (instanceDeclaration.NodeClass != NodeClass.Object)
                    {                        
                        throw ServiceResultException.Create(
                            StatusCodes.BadNodeClassInvalid, 
                            "The type model requires that node with a browse name of {0} have a NodeClass of {1}.", 
                            browseName,
                            instanceDeclaration.NodeClass);
                    }

                    if (!m_server.TypeTree.IsTypeOf(typeDefinitionId, instanceDeclaration.TypeDefinitionId))
                    {
                        throw ServiceResultException.Create(
                            StatusCodes.BadNodeClassInvalid, 
                            "The type model requires that node have a type definition of {0}.", 
                            instanceDeclaration.TypeDefinitionId);
                    }
                }

                // get the variable.
                IObject objectd = instanceDeclaration as IObject;

                // create node.
                ObjectNode node = new ObjectNode();

                // set defaults from type definition.
                node.NodeId        = nodeId;
                node.NodeClass     = NodeClass.Object;
                node.BrowseName    = browseName;
                node.DisplayName   = browseName.Name;
                node.Description   = null;
                node.WriteMask     = 0;
                node.UserWriteMask = 0;
                node.EventNotifier = EventNotifiers.None;

                // set defaults from instance declaration.
                if (objectd != null)
                {
                    node.DisplayName   = objectd.DisplayName;
                    node.Description   = objectd.Description;
                    node.WriteMask     = (uint)objectd.WriteMask;
                    node.UserWriteMask = (uint)objectd.UserWriteMask;
                    node.EventNotifier = objectd.EventNotifier;
                }            
                      
                // update with attributes provided.
                UpdateAttributes(node, attributes);

                // EventNotifier    
                if (attributes != null && (attributes.SpecifiedAttributes & (uint)NodeAttributesMask.EventNotifier) != 0)
                {
                    node.EventNotifier = attributes.EventNotifier;
                }

                // add references with parent.
                if (parent != null)
                {
                    AddReference(parent, referenceTypeId, false, node, true);                
                }
                
                // add type definition.
                AddReference(node, ReferenceTypeIds.HasTypeDefinition, false, objectType, false);     

                // add to address space.
                AddNode(node);
                                
                // apply modelling rules.
                NodeFactory factory = new NodeFactory(m_nodes);

                IList<ILocalNode> nodesToAdd = factory.ApplyModellingRules(node, objectType.NodeId, ref m_lastId, 1);
                
                // add the nodes.
                foreach (Node nodeToAdd in nodesToAdd)
                {               
                    AddNode(nodeToAdd);
                }
                
                // find the top level parent that must be used to apply the modelling rules.
                if (instanceDeclaration != null)
                {
                    ILocalNode toplevelParent = FindTopLevelModelParent(parent);
                    
                    // add modelling rule.
                    AddReference(node, ReferenceTypeIds.HasModelParent, false, parent, true);     
                                    
                    // update the hierarchy.
                    nodesToAdd = factory.ApplyModellingRules(toplevelParent, (NodeId)toplevelParent.TypeDefinitionId, ref m_lastId, 1);
                    
                    // add the nodes.
                    foreach (Node nodeToAdd in nodesToAdd)
                    {               
                        AddNode(nodeToAdd);
                    }
                }

                // return the new node id.
                return node.NodeId;
            }
            finally
            {
                m_lock.Exit();
            } 
        }        
        // Lock the node dictionary, and rebuild the static
        // geometry for objects of this kind
        protected void Rebuild(SceneManager mgr, Dictionary <long, WorldEntity> nodeDictionary)
        {
            log.DebugFormat("Entering StaticGeometryHelper.Rebuild for geometry '{0}'", name);
            long tickStart = TimeTool.CurrentTime;

            try {
                nodesAddedSinceLastRebuild   = 0;
                nodesRemovedSinceLastRebuild = 0;
                force = false;
                Monitor.Enter(mgr);
                if (objectGeometry != null)
                {
                    objectGeometry.Reset();
                }
                else
                {
                    objectGeometry = new StaticGeometry(mgr, name);
                }
                // Dictionary mapping Material into a list of
                // ObjectNodes in which some submesh uses the material
                Dictionary <Material, MaterialAndNodeCounts> materialsUsedMap = new Dictionary <Material, MaterialAndNodeCounts>();
                lock (nodeDictionary) {
                    foreach (WorldEntity entity in nodeDictionary.Values)
                    {
                        if (entity is ObjectNode)
                        {
                            ObjectNode node = (ObjectNode)entity;
                            // For now, we only consider "props" that have an associated SceneNode
                            // and are direct descendants of the root scene node, and are of the right
                            // kind, i.e., don't have a perception radius if this static geometry is for
                            // little nodes, and vice versa.
//                             log.DebugFormat("StaticGeometry.Rebuild: Examining node {0}, oid {1}, type {2}, sceneNode {3}, InStaticGeometry {4}, top-level {5}",
//                                 node.Name, node.Oid, node.ObjectType, node.SceneNode, node.InStaticGeometry, node.SceneNode.Parent == mgr.RootSceneNode);
                            if (node.ObjectType == ObjectNodeType.Prop &&
                                (node.InStaticGeometry || (node.SceneNode != null && node.SceneNode.Parent == mgr.RootSceneNode)) &&
                                RightKind(node))
                            {
                                foreach (Material m in node.Entity.SubEntityMaterials)
                                {
                                    MaterialAndNodeCounts nodesUsingMaterial;
                                    if (!materialsUsedMap.TryGetValue(m, out nodesUsingMaterial))
                                    {
                                        nodesUsingMaterial  = new MaterialAndNodeCounts();
                                        materialsUsedMap[m] = nodesUsingMaterial;
                                    }
                                    nodesUsingMaterial.materialUseCount++;
                                    int subMeshUseCount;
                                    Dictionary <ObjectNode, int> submeshUseCounts = nodesUsingMaterial.submeshUseCounts;
                                    if (!submeshUseCounts.TryGetValue(node, out subMeshUseCount))
                                    {
                                        submeshUseCounts[node] = 1;
                                    }
                                    else
                                    {
                                        submeshUseCounts[node] = subMeshUseCount + 1;
                                    }
                                }
                            }
                        }
                    }
                }

                // Now we have a count of uses of each material, and
                // for each node, the number of subentities that use the
                // material.  Now we need to calculate the number of
                // instance of sharings for each object node
                Dictionary <ObjectNode, bool> candidateNodes = new Dictionary <ObjectNode, bool>();
                foreach (MaterialAndNodeCounts counts in materialsUsedMap.Values)
                {
                    if (counts.materialUseCount > 1)
                    {
                        foreach (KeyValuePair <ObjectNode, int> pair in counts.submeshUseCounts)
                        {
                            candidateNodes[pair.Key] = true;
                        }
                    }
                }
                Dictionary <ObjectNode, int> staticNodes = new Dictionary <ObjectNode, int>();
                foreach (KeyValuePair <ObjectNode, bool> pair in candidateNodes)
                {
                    ObjectNode candidate = pair.Key;
                    bool       useIt     = pair.Value;
                    if (useIt)
                    {
                        staticNodes[candidate] = 0;
                    }
                }
                if (staticNodes.Count == 0)
                {
                    log.InfoFormat("StaticGeometryHelper.Rebuild: Didn't build static geometry {0} because object count was zero", name);
                }
                else
                {
                    log.InfoFormat("StaticGeometryHelper.Rebuild: {0} ObjectNodes", staticNodes.Count);
                    foreach (ObjectNode staticNode in staticNodes.Keys)
                    {
                        SceneNode sc = staticNode.SceneNode;
                        if (!staticNode.InStaticGeometry)
                        {
                            sc.RemoveFromParent();
                            staticNode.InStaticGeometry = true;
                        }
                        log.DebugFormat("StaticGeometryHelper.Rebuild: Add node {0} with name {1} to static geometry",
                                        staticNode.Oid, staticNode.Name);
                        objectGeometry.AddSceneNode(sc);
                    }
                }
                if (lastStaticNodes != null)
                {
                    foreach (ObjectNode node in lastStaticNodes.Keys)
                    {
                        if (!staticNodes.ContainsKey(node))
                        {
                            // Only 1 instance of the mesh, so make sure that if in a former build it was in
                            // static geometry, that we add it back to the scene graph.
                            if (node.InStaticGeometry)
                            {
                                SceneNode sn = node.SceneNode;
                                if (sn != null)
                                {
                                    mgr.RootSceneNode.AddChild(sn);
                                }
                                node.InStaticGeometry = false;
                            }
                        }
                    }
                }
                if (staticNodes.Count > 0)
                {
                    objectGeometry.Build();
                }
                lastStaticNodes   = staticNodes;
                timeOfLastRebuild = TimeTool.CurrentTime;
            }
            finally {
                Monitor.Exit(mgr);
            }
            log.InfoFormat("StaticGeometryHelper.Rebuild: Rebuild of geometry '{0}' took {1} ms",
                           name, TimeTool.CurrentTime - tickStart);
        }
예제 #55
0
        public void ObjectHexData()
        {
            RtfTree tree = new RtfTree();
            tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf");

            RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode;

            ObjectNode objNode = new ObjectNode(node);

            StreamReader sr = null;

            sr = new StreamReader("..\\..\\testdocs\\objhexdata.txt");
            string hexdata = sr.ReadToEnd();
            sr.Close();

            Assert.That(objNode.HexData, Is.EqualTo(hexdata));
        }
예제 #56
0
        public static bool TryGetInstallationState(ObjectNode parent, out ILibraryInstallationState installationState, string defaultProvider = null)
        {
            installationState = null;

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

            var state = new LibraryInstallationStateOnDisk();

            SortedNodeList <Node> children = GetChildren(parent);

            foreach (MemberNode child in children.OfType <MemberNode>())
            {
                switch (child.UnquotedNameText)
                {
                case ManifestConstants.Provider:
                    state.ProviderId = child.UnquotedValueText;
                    break;

                case ManifestConstants.Library:
                    state.LibraryId = child.UnquotedValueText;
                    break;

                case ManifestConstants.Destination:
                    state.DestinationPath = child.UnquotedValueText;
                    break;

                case ManifestConstants.Files:
                    state.Files = (child.Value as ArrayNode)?.Elements.Select(e => e.UnquotedValueText).ToList();
                    break;
                }
            }

            children = GetChildren(parent.Parent?.FindType <ObjectNode>());
            IEnumerable <MemberNode> rootMembers = children?.OfType <MemberNode>();

            // Check for defaultProvider
            if (string.IsNullOrEmpty(state.ProviderId))
            {
                if (rootMembers != null)
                {
                    foreach (MemberNode child in rootMembers)
                    {
                        if (child.UnquotedNameText == "defaultProvider")
                        {
                            state.ProviderId = child.UnquotedValueText;
                        }
                    }
                }
            }

            // Check for defaultDestination
            if (string.IsNullOrEmpty(state.DestinationPath))
            {
                if (rootMembers != null)
                {
                    foreach (MemberNode child in rootMembers)
                    {
                        if (child.UnquotedNameText == ManifestConstants.DefaultDestination)
                        {
                            state.DestinationPath = child.UnquotedValueText;
                        }
                    }
                }
            }

            var converter = new LibraryStateToFileConverter(defaultProvider, defaultDestination: null);

            installationState = converter.ConvertToLibraryInstallationState(state);

            return(!string.IsNullOrEmpty(installationState.ProviderId));
        }
예제 #57
0
        public void BuildDebugLocInfoMap(ObjectNode node)
        {
            if (!HasModuleDebugInfo())
            {
                return;
            }

            _offsetToDebugLoc.Clear();
            INodeWithDebugInfo debugNode = node as INodeWithDebugInfo;
            if (debugNode != null)
            {
                DebugLocInfo[] locs = debugNode.DebugLocInfos;
                if (locs != null)
                {
                    foreach (var loc in locs)
                    {
                        _offsetToDebugLoc.Add(loc.NativeOffset, loc);
                    }
                }
            }
        }
예제 #58
0
        public Node ReadNode(NodeId nodeId)
        {
            // build list of attributes.
            SortedDictionary<uint,DataValue> attributes = new SortedDictionary<uint,DataValue>();
            
            attributes.Add(Attributes.NodeId, null);
            attributes.Add(Attributes.NodeClass, null);
            attributes.Add(Attributes.BrowseName, null);
            attributes.Add(Attributes.DisplayName, null);
            attributes.Add(Attributes.Description, null);
            attributes.Add(Attributes.WriteMask, null);
            attributes.Add(Attributes.UserWriteMask, null);
            attributes.Add(Attributes.DataType, null);
            attributes.Add(Attributes.ValueRank, null);
            attributes.Add(Attributes.ArrayDimensions, null);
            attributes.Add(Attributes.AccessLevel, null);
            attributes.Add(Attributes.UserAccessLevel, null);
            attributes.Add(Attributes.Historizing, null);
            attributes.Add(Attributes.MinimumSamplingInterval, null);
            attributes.Add(Attributes.EventNotifier, null);
            attributes.Add(Attributes.Executable, null);
            attributes.Add(Attributes.UserExecutable, null);
            attributes.Add(Attributes.IsAbstract, null);
            attributes.Add(Attributes.InverseName, null);
            attributes.Add(Attributes.Symmetric, null);
            attributes.Add(Attributes.ContainsNoLoops, null);

            // build list of values to read.
            ReadValueIdCollection itemsToRead = new ReadValueIdCollection();

            foreach (uint attributeId in attributes.Keys)
            {
                ReadValueId itemToRead = new ReadValueId();

                itemToRead.NodeId      = nodeId;
                itemToRead.AttributeId = attributeId;
                
                itemsToRead.Add(itemToRead);
            }

            // read from server.
            DataValueCollection values = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = Read(
                null,
                0,
                TimestampsToReturn.Neither,
                itemsToRead,
                out values, 
                out diagnosticInfos);
            
            ClientBase.ValidateResponse(values, itemsToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, itemsToRead);

            // process results.
            int? nodeClass = null;

            for (int ii = 0; ii < itemsToRead.Count; ii++)
            {
                uint attributeId = itemsToRead[ii].AttributeId;
                
                // the node probably does not exist if the node class is not found.
                if (attributeId == Attributes.NodeClass)
                {
                    if (!DataValue.IsGood(values[ii]))
                    {
                        throw ServiceResultException.Create(values[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                    }       
     
                    // check for valid node class.
                    nodeClass  = values[ii].Value as int?;

                    if (nodeClass == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not have a valid value for NodeClass: {0}.", values[ii].Value);
                    }
                }
                else
                {
                    if (!DataValue.IsGood(values[ii]))
                    {
                        // check for unsupported attributes.
                        if (values[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                        {
                            continue;
                        }

                        // all supported attributes must be readable.
                        if (attributeId != Attributes.Value)
                        {
                            throw ServiceResultException.Create(values[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                        }
                    }      
                }

                attributes[attributeId] = values[ii];
            }

            Node node = null;
            DataValue value = null;

            switch ((NodeClass)nodeClass.Value)
            {
                default:
                {
                    throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not have a valid value for NodeClass: {0}.", nodeClass.Value);
                }

                case NodeClass.Object:
                {
                    ObjectNode objectNode = new ObjectNode();

                    value = attributes[Attributes.EventNotifier];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Object does not support the EventNotifier attribute.");
                    }

                    objectNode.EventNotifier = (byte)attributes[Attributes.EventNotifier].GetValue(typeof(byte));
                    node = objectNode;
                    break;
                }

                case NodeClass.ObjectType:
                {
                    ObjectTypeNode objectTypeNode = new ObjectTypeNode();

                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ObjectType does not support the IsAbstract attribute.");
                    }

                    objectTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));
                    node = objectTypeNode;
                    break;
                }

                case NodeClass.Variable:
                {
                    VariableNode variableNode = new VariableNode();
                    
                    // DataType Attribute
                    value = attributes[Attributes.DataType];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the DataType attribute.");
                    }

                    variableNode.DataType = (NodeId)attributes[Attributes.DataType].GetValue(typeof(NodeId));     

                    // ValueRank Attribute
                    value = attributes[Attributes.ValueRank];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the ValueRank attribute.");
                    }

                    variableNode.ValueRank = (int)attributes[Attributes.ValueRank].GetValue(typeof(int));                                      
                    
                    // ArrayDimensions Attribute
                    value = attributes[Attributes.ArrayDimensions];

                    if (value != null)
                    {
                        if (value.Value == null)
                        {
                            variableNode.ArrayDimensions = new uint[0];
                        }
                        else
                        {
                            variableNode.ArrayDimensions = (uint[])value.GetValue(typeof(uint[]));
                        }
                    }
                    
                    // AccessLevel Attribute
                    value = attributes[Attributes.AccessLevel];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the AccessLevel attribute.");
                    }

                    variableNode.AccessLevel = (byte)attributes[Attributes.AccessLevel].GetValue(typeof(byte));     
                    
                    // UserAccessLevel Attribute
                    value = attributes[Attributes.UserAccessLevel];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the UserAccessLevel attribute.");
                    }

                    variableNode.UserAccessLevel = (byte)attributes[Attributes.UserAccessLevel].GetValue(typeof(byte));     
                    
                    // Historizing Attribute
                    value = attributes[Attributes.Historizing];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the Historizing attribute.");
                    }

                    variableNode.Historizing = (bool)attributes[Attributes.Historizing].GetValue(typeof(bool));    
                    
                    // MinimumSamplingInterval Attribute
                    value = attributes[Attributes.MinimumSamplingInterval];

                    if (value != null)
                    {
                        variableNode.MinimumSamplingInterval = Convert.ToDouble(attributes[Attributes.MinimumSamplingInterval].Value);
                    }

                    node = variableNode;
                    break;
                }
                    
                case NodeClass.VariableType:
                {
                    VariableTypeNode variableTypeNode = new VariableTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the IsAbstract attribute.");
                    }

                    variableTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));
                    
                    // DataType Attribute
                    value = attributes[Attributes.DataType];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the DataType attribute.");
                    }

                    variableTypeNode.DataType = (NodeId)attributes[Attributes.DataType].GetValue(typeof(NodeId));     

                    // ValueRank Attribute
                    value = attributes[Attributes.ValueRank];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the ValueRank attribute.");
                    }

                    variableTypeNode.ValueRank = (int)attributes[Attributes.ValueRank].GetValue(typeof(int));                                      
                    
                    // ArrayDimensions Attribute
                    value = attributes[Attributes.ArrayDimensions];

                    if (value != null && value.Value != null)
                    {
                        variableTypeNode.ArrayDimensions = (uint[])attributes[Attributes.ArrayDimensions].GetValue(typeof(uint[]));
                    }
                    
                    node = variableTypeNode;
                    break;
                }
                    
                case NodeClass.Method:
                {
                    MethodNode methodNode = new MethodNode();

                    // Executable Attribute
                    value = attributes[Attributes.Executable];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Method does not support the Executable attribute.");
                    }

                    methodNode.Executable = (bool)attributes[Attributes.Executable].GetValue(typeof(bool));
                    
                    // UserExecutable Attribute
                    value = attributes[Attributes.UserExecutable];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Method does not support the UserExecutable attribute.");
                    }

                    methodNode.UserExecutable = (bool)attributes[Attributes.UserExecutable].GetValue(typeof(bool));

                    node = methodNode;
                    break;
                }
                    
                case NodeClass.DataType:
                {
                    DataTypeNode dataTypeNode = new DataTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "DataType does not support the IsAbstract attribute.");
                    }

                    dataTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    node = dataTypeNode;
                    break;
                }
                    
                case NodeClass.ReferenceType:
                {
                    ReferenceTypeNode referenceTypeNode = new ReferenceTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ReferenceType does not support the IsAbstract attribute.");
                    }

                    referenceTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    // Symmetric Attribute
                    value = attributes[Attributes.Symmetric];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ReferenceType does not support the Symmetric attribute.");
                    }

                    referenceTypeNode.Symmetric = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    // InverseName Attribute
                    value = attributes[Attributes.InverseName];

                    if (value != null && value.Value != null)
                    {
                        referenceTypeNode.InverseName = (LocalizedText)attributes[Attributes.InverseName].GetValue(typeof(LocalizedText));
                    }
                    
                    node = referenceTypeNode;
                    break;
                }
                    
                case NodeClass.View:
                {
                    ViewNode viewNode = new ViewNode();

                    // EventNotifier Attribute
                    value = attributes[Attributes.EventNotifier];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "View does not support the EventNotifier attribute.");
                    }

                    viewNode.EventNotifier = (byte)attributes[Attributes.EventNotifier].GetValue(typeof(byte));
                    
                    // ContainsNoLoops Attribute
                    value = attributes[Attributes.ContainsNoLoops];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "View does not support the ContainsNoLoops attribute.");
                    }

                    viewNode.ContainsNoLoops = (bool)attributes[Attributes.ContainsNoLoops].GetValue(typeof(bool));

                    node = viewNode;
                    break;
                }                    
            }
                
            // NodeId Attribute
            value = attributes[Attributes.NodeId];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the NodeId attribute.");
            }

            node.NodeId = (NodeId)attributes[Attributes.NodeId].GetValue(typeof(NodeId));
            node.NodeClass = (NodeClass)nodeClass.Value;

            // BrowseName Attribute
            value = attributes[Attributes.BrowseName];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the BrowseName attribute.");
            }

            node.BrowseName = (QualifiedName)attributes[Attributes.BrowseName].GetValue(typeof(QualifiedName));

            // DisplayName Attribute
            value = attributes[Attributes.DisplayName];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the DisplayName attribute.");
            }

            node.DisplayName = (LocalizedText)attributes[Attributes.DisplayName].GetValue(typeof(LocalizedText));
    
            // Description Attribute
            value = attributes[Attributes.Description];

            if (value != null && value.Value != null)
            {
                node.Description = (LocalizedText)attributes[Attributes.Description].GetValue(typeof(LocalizedText));
            }

            // WriteMask Attribute
            value = attributes[Attributes.WriteMask];

            if (value != null)
            {
                node.WriteMask = (uint)attributes[Attributes.WriteMask].GetValue(typeof(uint));
            }

            // UserWriteMask Attribute
            value = attributes[Attributes.UserWriteMask];

            if (value != null)
            {
                node.WriteMask = (uint)attributes[Attributes.UserWriteMask].GetValue(typeof(uint));
            }
                
            return node;
        }
예제 #59
0
        public void BuildSymbolDefinitionMap(ObjectNode node, ISymbolNode[] definedSymbols)
        {
            _offsetToDefName.Clear();
            foreach (ISymbolNode n in definedSymbols)
            {
                if (!_offsetToDefName.ContainsKey(n.Offset))
                {
                    _offsetToDefName[n.Offset] = new List<string>();
                }

                string symbolToEmit = GetSymbolToEmitForTargetPlatform(n.MangledName);
                _offsetToDefName[n.Offset].Add(symbolToEmit);

                string alternateName = _nodeFactory.GetSymbolAlternateName(n);
                if (alternateName != null)
                {
                    symbolToEmit = GetSymbolToEmitForTargetPlatform(alternateName);
                    _offsetToDefName[n.Offset].Add(symbolToEmit);
                }
            }

            var symbolNode = node as ISymbolNode;
            if (symbolNode != null)
            {
                _currentNodeName = GetSymbolToEmitForTargetPlatform(symbolNode.MangledName);
                Debug.Assert(_offsetToDefName[symbolNode.Offset].Contains(_currentNodeName));
            }
            else
            {
                _currentNodeName = null;
            }
        }
예제 #60
0
 public void AddSubNode(ObjectNode objectNode)
 {
     SubNodes.Add(objectNode);
 }