コード例 #1
0
        void MaterialNewObjectCreateShaderGraph(Component_Material material, NewMaterialData data, out Component_FlowGraph graph)
        {
            graph                = material.CreateComponent <Component_FlowGraph>();
            graph.Name           = "Shader graph";
            graph.Specialization = ReferenceUtility.MakeReference(
                MetadataManager.GetTypeOfNetType(typeof(Component_FlowGraphSpecialization_Shader)).Name + "|Instance");

            {
                var node = graph.CreateComponent <Component_FlowGraphNode>();
                node.Name             = "Node " + "Material";    //Name;
                node.Position         = new Vector2I(10, -7);
                node.ControlledObject = ReferenceUtility.MakeThisReference(node, material);
            }

            //configure
            {
                const int step     = 9;
                Vector2I  position = new Vector2I(-20, -data.GetTextureCount() * step / 2);

                //BaseColor
                if (!string.IsNullOrEmpty(data.BaseColorTexture))
                {
                    var node = graph.CreateComponent <Component_FlowGraphNode>();
                    node.Name     = "Node Texture Sample " + "BaseColor";
                    node.Position = position;
                    position.Y   += step;

                    var sample = node.CreateComponent <Component_ShaderTextureSample>();
                    sample.Name    = ComponentUtility.GetNewObjectUniqueName(sample);
                    sample.Texture = new Reference <Component_Image>(null, data.BaseColorTexture);

                    node.ControlledObject = ReferenceUtility.MakeThisReference(node, sample);

                    material.BaseColor = ReferenceUtility.MakeThisReference(material, sample, "RGBA");
                }
                //else if( data.BaseColor.HasValue )
                //	BaseColor = data.BaseColor.Value;

                //Metallic
                if (!string.IsNullOrEmpty(data.MetallicTexture))
                {
                    var node = graph.CreateComponent <Component_FlowGraphNode>();
                    node.Name     = "Node Texture Sample " + "Metallic";
                    node.Position = position;
                    position.Y   += step;

                    var sample = node.CreateComponent <Component_ShaderTextureSample>();
                    sample.Name    = ComponentUtility.GetNewObjectUniqueName(sample);
                    sample.Texture = new Reference <Component_Image>(null, data.MetallicTexture);

                    node.ControlledObject = ReferenceUtility.MakeThisReference(node, sample);

                    material.Metallic = ReferenceUtility.MakeThisReference(material, sample, "R");
                }

                //Roughness
                if (!string.IsNullOrEmpty(data.RoughnessTexture))
                {
                    var node = graph.CreateComponent <Component_FlowGraphNode>();
                    node.Name     = "Node Texture Sample " + "Roughness";
                    node.Position = position;
                    position.Y   += step;

                    var sample = node.CreateComponent <Component_ShaderTextureSample>();
                    sample.Name    = ComponentUtility.GetNewObjectUniqueName(sample);
                    sample.Texture = new Reference <Component_Image>(null, data.RoughnessTexture);

                    node.ControlledObject = ReferenceUtility.MakeThisReference(node, sample);

                    material.Roughness = ReferenceUtility.MakeThisReference(material, sample, "R");
                }

                //Normal
                if (!string.IsNullOrEmpty(data.NormalTexture))
                {
                    var node = graph.CreateComponent <Component_FlowGraphNode>();
                    node.Name     = "Node Texture Sample " + "Normal";
                    node.Position = position;
                    position.Y   += step;

                    var sample = node.CreateComponent <Component_ShaderTextureSample>();
                    sample.Name    = ComponentUtility.GetNewObjectUniqueName(sample);
                    sample.Texture = new Reference <Component_Image>(null, data.NormalTexture);

                    node.ControlledObject = ReferenceUtility.MakeThisReference(node, sample);

                    material.Normal = ReferenceUtility.MakeThisReference(material, sample, "RGBA");
                }

                ////Displacement
                //if( !string.IsNullOrEmpty( data.DisplacementTexture ) )
                //{
                //	var node = graph.CreateComponent<Component_FlowGraphNode>();
                //	node.Name = "Node Texture Sample " + "Displacement";
                //	node.Position = position;
                //	position.Y += step;

                //	var sample = node.CreateComponent<Component_ShaderTextureSample>();
                //	sample.Name = ComponentUtility.GetNewObjectUniqueName( sample );
                //	sample.Texture = new Reference<Component_Image>( null, data.DisplacementTexture );

                //	node.ControlledObject = ReferenceUtility.MakeThisReference( node, sample );

                //	Displacement = ReferenceUtility.MakeThisReference( this, sample, "R" );
                //}

                ////AmbientOcclusion
                //if( !string.IsNullOrEmpty( data.AmbientOcclusionTexture ) )
                //{
                //	var node = graph.CreateComponent<Component_FlowGraphNode>();
                //	node.Name = "Node Texture Sample " + "AmbientOcclusion";
                //	node.Position = position;
                //	position.Y += step;

                //	var sample = node.CreateComponent<Component_ShaderTextureSample>();
                //	sample.Name = ComponentUtility.GetNewObjectUniqueName( sample );
                //	sample.Texture = new Reference<Component_Image>( null, data.AmbientOcclusionTexture );

                //	node.ControlledObject = ReferenceUtility.MakeThisReference( node, sample );

                //	AmbientOcclusion = ReferenceUtility.MakeThisReference( this, sample, "R" );
                //}

                ////Emissive
                //if( !string.IsNullOrEmpty( data.EmissiveTexture ) )
                //{
                //	var node = graph.CreateComponent<Component_FlowGraphNode>();
                //	node.Name = "Node Texture Sample " + "Emissive";
                //	node.Position = position;
                //	position.Y += step;

                //	var sample = node.CreateComponent<Component_ShaderTextureSample>();
                //	sample.Name = ComponentUtility.GetNewObjectUniqueName( sample );
                //	sample.Texture = new Reference<Component_Image>( null, data.EmissiveTexture );

                //	node.ControlledObject = ReferenceUtility.MakeThisReference( node, sample );

                //	Emissive = ReferenceUtility.MakeThisReference( this, sample, "RGBA" );
                //}

                //Opacity
                if (!string.IsNullOrEmpty(data.OpacityTexture))
                {
                    var node = graph.CreateComponent <Component_FlowGraphNode>();
                    node.Name     = "Node Texture Sample " + "Opacity";
                    node.Position = position;
                    position.Y   += step;

                    var sample = node.CreateComponent <Component_ShaderTextureSample>();
                    sample.Name    = ComponentUtility.GetNewObjectUniqueName(sample);
                    sample.Texture = new Reference <Component_Image>(null, data.OpacityTexture);

                    node.ControlledObject = ReferenceUtility.MakeThisReference(node, sample);

                    material.Opacity = ReferenceUtility.MakeThisReference(material, sample, "R");

                    material.BlendMode = Component_Material.BlendModeEnum.Masked;
                }
            }
        }
コード例 #2
0
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            if (s_Contents == null)
            {
                s_Contents = new Contents();
            }

            serializedObject.Update();
            Event e = Event.current;

            if (e != null)
            {
                if (image) //Auto set Image's native size if Image.sprite is not null
                {
                    if (e.type == EventType.DragPerform || e.type == EventType.MouseDown)
                    {
                        autoSetNativeSize = !image.sprite;
                    }

                    if (autoSetNativeSize && image.sprite && image.type == Image.Type.Simple)
                    {
                        autoSetNativeSize = false;
                        RectTransform tf = target as RectTransform;
                        float         x  = image.sprite.rect.width / image.pixelsPerUnit;
                        float         y  = image.sprite.rect.height / image.pixelsPerUnit;
                        tf.anchorMax = tf.anchorMin;
                        tf.sizeDelta = new Vector2(x, y);
                    }
                }

                //Keyboard control move by pixel style like Photoshop's move tool
                if (e.type == EventType.KeyDown && e.control)
                {
                    int nUnit = e.shift ? 10 : 1;
                    switch (e.keyCode)
                    {
                    case KeyCode.UpArrow:
                        Undo.RecordObjects(targets, "UpArrow");
                        MoveTargetAnchoredPosition(Vector2.up * nUnit);
                        e.Use();
                        break;

                    case KeyCode.DownArrow:
                        Undo.RecordObjects(targets, "DownArrow");
                        MoveTargetAnchoredPosition(Vector2.down * nUnit);
                        e.Use();
                        break;

                    case KeyCode.LeftArrow:
                        Undo.RecordObjects(targets, "LeftArrow");
                        MoveTargetAnchoredPosition(Vector2.left * nUnit);
                        e.Use();
                        break;

                    case KeyCode.RightArrow:
                        Undo.RecordObjects(targets, "RightArrow");
                        MoveTargetAnchoredPosition(Vector2.right * nUnit);
                        e.Use();
                        break;
                    }
                }
            }

            const float fButtonWidth = 21;

            if (stylePivotSetup == null)
            {
                stylePivotSetup = new GUIStyle("PreButton")
                {
                    normal     = new GUIStyle("CN Box").normal,
                    active     = new GUIStyle("AppToolbar").normal,
                    overflow   = new RectOffset(),
                    padding    = new RectOffset(0, 0, -1, 0),
                    fixedWidth = 19
                };

                styleMove = new GUIStyle(stylePivotSetup)
                {
                    padding = new RectOffset(0, 0, -2, 0)
                };
            }

            GUILayout.BeginHorizontal();
            {
                GUILayout.BeginVertical();
                {
                    #region Tools
                    GUILayout.BeginHorizontal();
                    {
                        EditorGUIUtility.labelWidth = 64;
                        float newScale = EditorGUILayout.FloatField(s_Contents.scaleContent, scaleAll);
                        if (!Mathf.Approximately(scaleAll, newScale))
                        {
                            scaleAll = newScale;
                            spLocalScale.vector3Value = Vector3.one * scaleAll;
                        }
                    }

                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    {
                        if (GUILayout.Button(s_Contents.anchoredPosition0Content, strButtonLeft, GUILayout.Width(fButtonWidth)))
                        {
                            foreach (Object item in targets)
                            {
                                RectTransform rtf = item as RectTransform;
                                rtf.LocalPositionIdentity();
                            }
                        }

                        if (GUILayout.Button(s_Contents.deltaSize0Content, strButtonMid, GUILayout.Width(fButtonWidth)))
                        {
                            spSizeDelta.vector2Value = Vector2.zero;
                        }

                        if (GUILayout.Button(s_Contents.rotation0Content, strButtonMid, GUILayout.Width(fButtonWidth)))
                        {
                            spLocalRotation.quaternionValue = Quaternion.identity;
                        }

                        if (GUILayout.Button(s_Contents.scale0Content, strButtonRight, GUILayout.Width(fButtonWidth)))
                        {
                            spLocalScale.vector3Value = Vector3.one;
                            scaleAll = spLocalScale.FindPropertyRelative("x").floatValue;
                        }

                        if (GUILayout.Button(s_Contents.roundContent))
                        {
                            Vector2 v2 = spAnchoredPosition.vector2Value;
                            spAnchoredPosition.vector2Value = new Vector2(Mathf.Round(v2.x), Mathf.Round(v2.y));
                            v2 = spSizeDelta.vector2Value;
                            spSizeDelta.vector2Value = new Vector2(Mathf.Round(v2.x), Mathf.Round(v2.y));
                        }
                    }
                    GUILayout.EndHorizontal();
                    #endregion

                    #region Copy Paste
                    GUILayout.BeginHorizontal();
                    Color c = GUI.color;
                    GUI.color = new Color(1f, 1f, 0.5f, 1f);
                    if (GUILayout.Button(s_Contents.copyContent, strButtonLeft, GUILayout.Width(fButtonWidth)))
                    {
                        ComponentUtility.CopyComponent(target as RectTransform);
                    }

                    GUI.color = new Color(1f, 0.5f, 0.5f, 1f);
                    if (GUILayout.Button(s_Contents.pasteContent, strButtonMid, GUILayout.Width(fButtonWidth)))
                    {
                        foreach (Object item in targets)
                        {
                            ComponentUtility.PasteComponentValues(item as RectTransform);
                        }
                    }

                    GUI.color = c;
                    if (GUILayout.Button(s_Contents.fillParentContent, strButtonMid, GUILayout.Width(fButtonWidth)))
                    {
                        Undo.RecordObjects(targets, "F");
                        foreach (Object item in targets)
                        {
                            RectTransform rtf = item as RectTransform;
                            rtf.anchorMax = Vector2.one;
                            rtf.anchorMin = Vector2.zero;
                            rtf.offsetMax = Vector2.zero;
                            rtf.offsetMin = Vector2.zero;
                        }
                    }

                    if (GUILayout.Button(s_Contents.normalSizeDeltaContent, strButtonRight, GUILayout.Width(fButtonWidth)))
                    {
                        Undo.RecordObjects(targets, "N");
                        foreach (Object item in targets)
                        {
                            RectTransform rtf  = item as RectTransform;
                            Rect          rect = rtf.rect;
                            rtf.anchorMax = new Vector2(0.5f, 0.5f);
                            rtf.anchorMin = new Vector2(0.5f, 0.5f);
                            rtf.sizeDelta = rect.size;
                        }
                    }

                    GUILayout.Label(s_Contents.readmeContent);
                    GUILayout.EndHorizontal();
                    #endregion
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical();
                {
                    #region Pivot
                    GUILayout.Label("Pivot", "ProfilerPaneSubLabel"); //┌─┐
                    GUILayout.BeginHorizontal();                      //│┼│
                    {
                        //└─┘
                        if (GUILayout.Button("◤", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0, 1);
                        }

                        if (GUILayout.Button("", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0.5f, 1);
                        }

                        if (GUILayout.Button("◥", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(1, 1);
                        }
                    }

                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    {
                        if (GUILayout.Button("", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0, 0.5f);
                        }

                        if (GUILayout.Button("+", styleMove))
                        {
                            spPivot.vector2Value = new Vector2(0.5f, 0.5f);
                        }

                        if (GUILayout.Button("", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(1, 0.5f);
                        }
                    }

                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    {
                        if (GUILayout.Button("◣", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0, 0);
                        }

                        if (GUILayout.Button("", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(0.5f, 0);
                        }

                        if (GUILayout.Button("◢", stylePivotSetup))
                        {
                            spPivot.vector2Value = new Vector2(1, 0);
                        }
                    }

                    GUILayout.EndHorizontal();
                }
                #endregion

                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();

            TransformInspector.DrawBottomPanel(targets);
            serializedObject.ApplyModifiedProperties();
        }
コード例 #3
0
 public void ReturnsEmptyForNullComponent()
 {
     Assert.Empty(ComponentUtility.GetAllVisibleComponents(null));
 }
コード例 #4
0
        void UpdateSelectedReference()
        {
            //!!!!не только компоненты?

            //!!!!multiselection
            ContentBrowser.Item item = null;
            if (contentBrowser1.SelectedItems.Length != 0)
            {
                item = contentBrowser1.SelectedItems[0];
            }

            string newSelection = null;
            bool   canSet       = false;

            if (item != null)
            {
                //!!!!multiselection?

                item.CalculateReferenceValue(setReferenceModeData.selectedComponents[0], setReferenceModeData.property.TypeUnreferenced, out newSelection, out canSet);

                //make relative file path
                if (kryptonCheckBoxCanMakeRelativeFilePath.Checked && !string.IsNullOrEmpty(newSelection))
                {
                    if (!newSelection.Contains(':'))                       //ignore references
                    {
                        var fromResource       = ComponentUtility.GetOwnedFileNameOfComponent(setReferenceModeData.selectedComponents[0]);
                        var fromResourceFolder = "";
                        if (!string.IsNullOrEmpty(fromResource))
                        {
                            fromResourceFolder = Path.GetDirectoryName(fromResource);
                        }

                        int commonChars = GetEqualPart(new string[] { fromResourceFolder, newSelection });

                        var path = "";

                        //go up (dots)
                        {
                            var c = fromResourceFolder.Substring(commonChars).Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries).Length;
                            for (int n = 0; n < c; n++)
                            {
                                path = Path.Combine(path, "..");
                            }
                        }

                        //go down
                        {
                            var s = newSelection.Substring(commonChars);
                            if (s.Length != 0 && (s[0] == '\\' || s[0] == '/'))
                            {
                                s = s.Substring(1);
                            }

                            //can't use Path.Combine, invalid character exception
                            if (path.Length != 0 && path[path.Length - 1] != '\\' && path[path.Length - 1] != '/')
                            {
                                path += "\\";
                            }
                            path += s;
                            //path = Path.Combine( path, s );
                        }

                        newSelection = "relative:" + path;
                    }
                }
            }

            //update
            selectedReference       = newSelection;
            selectedReferenceCanSet = canSet;
            UpdateSetButtons();
            UpdateTextBox();
            TextBoxSetError(false);
            ////change
            //if( string.Compare( selectedReference, newSelection ) != 0 )
            //{
            //	selectedReference = newSelection;
            //	selectedReferenceCanSet = canSet;
            //	SelectedReferenceChanged();
            //}
        }
コード例 #5
0
ファイル: eTransform.cs プロジェクト: Theadd/SmartCore
        private static void ApplyTransformToColliders(Transform tr)
        {
            foreach (var go in tr.gameObject.GetAllChildrenAndThisDescending())
            {
                if (!go.activeSelf)
                {
                    continue;
                }
                if (go.transform.localRotation != Quaternion.identity)
                {
                    continue;
                }

                var pos = go.transform.localPosition;
                go.transform.localPosition = Vector3.zero;

                var size = go.transform.localScale;
                go.transform.localScale = Vector3.one;

                foreach (var bc in go.GetFirstDepthChildrenComponents <BoxCollider>())
                {
                    if (bc.transform != go.transform && bc.transform.rotation == go.transform.rotation)
                    {
                        bc.center += Vector3.Scale(bc.transform.localPosition, bc.transform.localScale);
                        bc.size    = Vector3.Scale(bc.size, bc.transform.localScale);
                    }

                    bc.size    = Vector3.Scale(bc.size, size);
                    bc.center  = Vector3.Scale(bc.center, size);
                    bc.center += pos;

                    if (bc.transform != go.transform && bc.transform.rotation == go.transform.rotation)
                    {
                        ComponentUtility.CopyComponent(bc);
                        ComponentUtility.PasteComponentAsNew(go);
                        DestroyImmediate(bc);
                    }
                }

                foreach (var cc in go.GetFirstDepthChildrenComponents <CapsuleCollider>())
                {
                    if (cc.transform != go.transform && cc.transform.rotation == go.transform.rotation)
                    {
                        cc.center += Vector3.Scale(cc.transform.localPosition, cc.transform.localScale);
                        var lcs = cc.transform.localScale;
                        cc.height *= lcs[cc.direction];
                        cc.radius *=
                            cc.direction == 0
                                ? Mathf.Max(lcs.y, lcs.z)
                                : cc.direction == 1
                                    ? Mathf.Max(lcs.x, lcs.z)
                                    : Mathf.Max(lcs.x, lcs.y);
                    }

                    cc.center  = Vector3.Scale(cc.center, size);
                    cc.center += pos;
                    cc.height *= size[cc.direction];
                    cc.radius *=
                        cc.direction == 0
                            ? Mathf.Max(size.y, size.z)
                            : cc.direction == 1
                                ? Mathf.Max(size.x, size.z)
                                : Mathf.Max(size.x, size.y);


                    if (cc.transform != go.transform && cc.transform.rotation == go.transform.rotation)
                    {
                        ComponentUtility.CopyComponent(cc);
                        ComponentUtility.PasteComponentAsNew(go);
                        DestroyImmediate(cc);
                    }
                }

                foreach (var sc in go.GetFirstDepthChildrenComponents <SphereCollider>())
                {
                    if (sc.transform != go.transform && sc.transform.rotation == go.transform.rotation)
                    {
                        sc.center += Vector3.Scale(sc.transform.localPosition, sc.transform.localScale);
                        var lcs = sc.transform.localScale;
                        sc.radius *= Mathf.Max(lcs.x, lcs.y, lcs.z);
                    }

                    sc.center  = Vector3.Scale(sc.center, size);
                    sc.center += pos;
                    sc.radius *= Mathf.Max(size.x, size.y, size.z);

                    if (sc.transform != go.transform && sc.transform.rotation == go.transform.rotation)
                    {
                        ComponentUtility.CopyComponent(sc);
                        ComponentUtility.PasteComponentAsNew(go);
                        DestroyImmediate(sc);
                    }
                }
            }
        }
コード例 #6
0
        void HandleEditorDragging(Editor[] editors, int editorIndex, Rect targetRect, float markerY, bool bottomTarget)
        {
            var evt = Event.current;

            switch (evt.type)
            {
            case EventType.DragUpdated:
                if (targetRect.Contains(evt.mousePosition))
                {
                    var draggingMode = DragAndDrop.GetGenericData(k_DraggingModeKey) as DraggingMode ? ;
                    if (!draggingMode.HasValue)
                    {
                        var draggedObjects = DragAndDrop.objectReferences;

                        if (draggedObjects.Length == 0)
                        {
                            draggingMode = DraggingMode.NotApplicable;
                        }
                        else if (draggedObjects.All(o => o is Component && !(o is Transform)))
                        {
                            draggingMode = DraggingMode.Component;
                        }
                        else if (draggedObjects.All(o => o is MonoScript))
                        {
                            draggingMode = DraggingMode.Script;
                        }
                        else
                        {
                            draggingMode = DraggingMode.NotApplicable;
                        }

                        DragAndDrop.SetGenericData(k_DraggingModeKey, draggingMode);
                    }

                    if (draggingMode.Value != DraggingMode.NotApplicable)
                    {
                        if (bottomTarget)
                        {
                            m_TargetAbove = false;
                            m_TargetIndex = m_LastIndex;
                        }
                        else
                        {
                            m_TargetAbove = evt.mousePosition.y < targetRect.y + targetRect.height / 2f;
                            m_TargetIndex = editorIndex;

                            if (m_TargetAbove)
                            {
                                m_TargetIndex++;
                                while (m_TargetIndex < editors.Length && m_InspectorWindow.ShouldCullEditor(editors, m_TargetIndex))
                                {
                                    m_TargetIndex++;
                                }

                                if (m_TargetIndex == editors.Length)
                                {
                                    m_TargetIndex = -1;
                                    return;
                                }
                            }
                        }

                        if (m_TargetAbove && m_InspectorWindow.EditorHasLargeHeader(m_TargetIndex, editors))
                        {
                            m_TargetIndex--;
                            while (m_TargetIndex >= 0 && m_InspectorWindow.ShouldCullEditor(editors, m_TargetIndex))
                            {
                                m_TargetIndex--;
                            }

                            if (m_TargetIndex == -1)
                            {
                                return;
                            }

                            m_TargetAbove = false;
                        }

                        if (draggingMode.Value == DraggingMode.Script)
                        {
                            // Validate dragging scripts
                            // Always allow script dragging, instead fail during DragPerform with a dialog box
                            DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        }
                        else
                        {
                            // Validate dragging components
                            var valid = false;
                            if (editors[m_TargetIndex].targets.All(t => t is Component))
                            {
                                var targetComponents = editors[m_TargetIndex].targets.Cast <Component>().ToArray();
                                var sourceComponents = DragAndDrop.objectReferences.Cast <Component>().ToArray();
                                valid = MoveOrCopyComponents(sourceComponents, targetComponents, EditorUtility.EventHasDragCopyModifierPressed(evt), true);
                            }

                            if (valid)
                            {
                                DragAndDrop.visualMode = EditorUtility.EventHasDragCopyModifierPressed(evt) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Move;
                            }
                            else
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.None;
                                m_TargetIndex          = -1;
                                return;
                            }
                        }

                        evt.Use();
                    }
                }
                else
                {
                    m_TargetIndex = -1;
                }
                break;

            case EventType.DragPerform:
                if (m_TargetIndex != -1)
                {
                    var draggingMode = DragAndDrop.GetGenericData(k_DraggingModeKey) as DraggingMode ? ;
                    if (!draggingMode.HasValue || draggingMode.Value == DraggingMode.NotApplicable)
                    {
                        m_TargetIndex = -1;
                        return;
                    }

                    if (!editors[m_TargetIndex].targets.All(t => t is Component))
                    {
                        return;
                    }

                    var targetComponents = editors[m_TargetIndex].targets.Cast <Component>().ToArray();

                    if (draggingMode.Value == DraggingMode.Script)
                    {
                        var scripts = DragAndDrop.objectReferences.Cast <MonoScript>();

                        // Ensure all script components can be added
                        var valid = true;
                        foreach (var targetComponent in targetComponents)
                        {
                            var gameObject = targetComponent.gameObject;
                            if (scripts.Any(s => !ComponentUtility.WarnCanAddScriptComponent(targetComponent.gameObject, s)))
                            {
                                valid = false;
                                break;
                            }
                        }

                        if (valid)
                        {
                            Undo.IncrementCurrentGroup();
                            var undoGroup = Undo.GetCurrentGroup();

                            // Add script components
                            var index           = 0;
                            var addedComponents = new Component[targetComponents.Length * scripts.Count()];
                            for (int i = 0; i < targetComponents.Length; i++)
                            {
                                var  targetComponent   = targetComponents[i];
                                var  gameObject        = targetComponent.gameObject;
                                bool targetIsTransform = targetComponent is Transform;
                                foreach (var script in scripts)
                                {
                                    addedComponents[index++] = ObjectFactory.AddComponent(gameObject, script.GetClass());
                                }

                                // If the target is a Transform, the AddComponent might have replaced it with a RectTransform.
                                // Handle this possibility by updating the target component.
                                if (targetIsTransform)
                                {
                                    targetComponents[i] = gameObject.transform;
                                }
                            }

                            // Move added components relative to target components
                            if (!ComponentUtility.MoveComponentsRelativeToComponents(addedComponents, targetComponents, m_TargetAbove))
                            {
                                // Revert added components if move operation fails (e.g. user aborts when asked to break prefab instance)
                                Undo.RevertAllDownToGroup(undoGroup);
                            }
                        }
                    }
                    else
                    {
                        // Handle dragging components
                        var sourceComponents = DragAndDrop.objectReferences.Cast <Component>().ToArray();
                        if (sourceComponents.Length == 0 || targetComponents.Length == 0)
                        {
                            return;
                        }

                        MoveOrCopyComponents(sourceComponents, targetComponents, EditorUtility.EventHasDragCopyModifierPressed(evt), false);
                    }

                    m_TargetIndex = -1;
                    DragAndDrop.AcceptDrag();
                    evt.Use();
                    EditorGUIUtility.ExitGUI();
                }
                break;

            case EventType.DragExited:
                m_TargetIndex = -1;
                break;

            case EventType.Repaint:
                if (m_TargetIndex != -1 && targetRect.Contains(evt.mousePosition))
                {
                    var markerRect = new Rect(targetRect.x, markerY, targetRect.width, 3f);
                    if (!m_TargetAbove)
                    {
                        markerRect.y += 2f;
                    }

                    Styles.insertionMarker.Draw(markerRect, false, false, false, false);
                }
                break;
            }
        }
コード例 #7
0
 /// <summary>
 /// { id: "-1", text: "Select a repository" }
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public Select2Option Placeholder(object value)
 {
     Attributes["placeholder"] = ComponentUtility.ToJsonStringWithoutQuotes(value);
     return(this);
 }
        private async Task <ExistingStartMessageContext> ProcessStartMessageAsync(
            MessageChangeEvent change,
            EventEntity eventEntity,
            IComponent rootComponent,
            IComponent component,
            ExistingStartMessageContext existingStartMessageContext)
        {
            _logger.LogInformation("Applying change to component tree.");
            component.Status = change.AffectedComponentStatus;

            // This change may affect a component that we do not display on the status page.
            // Find the deepester ancestor of the component that is directly affected.
            _logger.LogInformation("Determining if change affects visible component tree.");
            var lowestVisibleComponent = rootComponent.GetDeepestVisibleAncestorOfSubComponent(component);

            if (lowestVisibleComponent == null || lowestVisibleComponent.Status == ComponentStatus.Up)
            {
                // The change does not bubble up to a component that we display on the status page.
                // Therefore, we shouldn't post a message about it.
                _logger.LogInformation("Change does not affect visible component tree. Will not post or edit any messages.");
                return(existingStartMessageContext);
            }

            // The change bubbles up to a component that we display on the status page.
            // We must post or update a message about it.
            if (existingStartMessageContext != null)
            {
                // There is an existing message we need to update.
                _logger.LogInformation("Found existing message, will edit it with information from new change.");
                // We must expand the scope of the existing message to include the component affected by this change.
                // In other words, if the message claims V2 Restore is down and V3 Restore is now down as well, we need to update the message to say Restore is down.
                var leastCommonAncestorPath = ComponentUtility.GetLeastCommonAncestorPath(existingStartMessageContext.AffectedComponent, lowestVisibleComponent);
                _logger.LogInformation("Least common ancestor component of existing message and this change is {LeastCommonAncestorPath}.", leastCommonAncestorPath);
                var leastCommonAncestor = rootComponent.GetByPath(leastCommonAncestorPath);
                if (leastCommonAncestor == null)
                {
                    // If the two components don't have a common ancestor, then they must not be a part of the same component tree.
                    // This should not be possible because it is asserted earlier that both these components are subcomponents of the root component.
                    throw new ArgumentException("Least common ancestor component of existing message and this change does not exist!", nameof(change));
                }

                if (leastCommonAncestor.Status == ComponentStatus.Up)
                {
                    // The least common ancestor of the component affected by the change and the component referred to by the existing message is unaffected!
                    // This should not be possible because the ancestor of any visible component should be visible (in other words, changes to visible components should always bubble up).
                    throw new ArgumentException("Least common ancestor of two visible components is unaffected!");
                }

                await _factory.UpdateMessageAsync(eventEntity, existingStartMessageContext.Timestamp, MessageType.Start, leastCommonAncestor);

                return(new ExistingStartMessageContext(existingStartMessageContext.Timestamp, leastCommonAncestor, leastCommonAncestor.Status));
            }
            else
            {
                // There is not an existing message we need to update.
                _logger.LogInformation("No existing message found. Creating new start message for change.");
                await _factory.CreateMessageAsync(eventEntity, change.Timestamp, change.Type, lowestVisibleComponent);

                return(new ExistingStartMessageContext(change.Timestamp, lowestVisibleComponent, lowestVisibleComponent.Status));
            }
        }
コード例 #9
0
ファイル: PixHandler.cs プロジェクト: shenghu/client-registry
        /// <summary>
        /// Handle the PIX merge request
        /// </summary>
        private IMessage HandlePixMerge(NHapi.Model.V231.Message.ADT_A39 request, Hl7MessageReceivedEventArgs evt)
        {
            // Get config
            var config      = this.Context.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService;
            var locale      = this.Context.GetService(typeof(ILocalizationService)) as ILocalizationService;
            var dataService = this.Context.GetService(typeof(IClientRegistryDataService)) as IClientRegistryDataService;

            // Create a details array
            List <IResultDetail> dtls = new List <IResultDetail>();

            // Validate the inbound message
            MessageUtil.Validate((IMessage)request, config, dtls, this.Context);

            IMessage response = null;

            // Control
            if (request == null)
            {
                return(null);
            }

            // Data controller
            //DataUtil dataUtil = new DataUtil() { Context = this.Context };
            AuditUtil auditUtil = new AuditUtil()
            {
                Context = this.Context
            };

            // Construct appropriate audit
            List <AuditData> audit = new List <AuditData>();

            try
            {
                // Create Query Data
                ComponentUtility cu = new ComponentUtility()
                {
                    Context = this.Context
                };
                DeComponentUtility dcu = new DeComponentUtility()
                {
                    Context = this.Context
                };
                var data = cu.CreateComponents(request, dtls);
                if (data == null)
                {
                    throw new InvalidOperationException(locale.GetString("MSGE00A"));
                }

                // Merge
                var result = dataService.Merge(data, request.MSH.ProcessingID.ProcessingID.Value == "P" ? DataPersistenceMode.Production : DataPersistenceMode.Debugging);

                if (result == null || result.VersionId == null)
                {
                    throw new InvalidOperationException(locale.GetString("DTPE001"));
                }

                List <VersionedDomainIdentifier> deletedRecordIds = new List <VersionedDomainIdentifier>(),
                                                 updatedRecordIds = new List <VersionedDomainIdentifier>();

                // Subjects
                var oidData = config.OidRegistrar.GetOid("CR_CID").Oid;
                foreach (Person subj in data.FindAllComponents(SVC.Core.ComponentModel.HealthServiceRecordSiteRoleType.SubjectOf))
                {
                    PersonRegistrationRef replcd = subj.FindComponent(SVC.Core.ComponentModel.HealthServiceRecordSiteRoleType.ReplacementOf) as PersonRegistrationRef;
                    deletedRecordIds.Add(new VersionedDomainIdentifier()
                    {
                        Identifier = replcd.Id.ToString(),
                        Domain     = oidData
                    });
                    updatedRecordIds.Add(new VersionedDomainIdentifier()
                    {
                        Identifier = subj.Id.ToString(),
                        Domain     = oidData
                    });
                }

                // Now audit
                audit.Add(auditUtil.CreateAuditData("ITI-8", ActionType.Delete, OutcomeIndicator.Success, evt, deletedRecordIds));
                audit.Add(auditUtil.CreateAuditData("ITI-8", ActionType.Update, OutcomeIndicator.Success, evt, updatedRecordIds));
                // Now process the result
                response = MessageUtil.CreateNack(request, dtls, this.Context, typeof(NHapi.Model.V231.Message.ACK));
                MessageUtil.UpdateMSH(new NHapi.Base.Util.Terser(response), request, config);
                (response as NHapi.Model.V231.Message.ACK).MSH.MessageType.TriggerEvent.Value = request.MSH.MessageType.TriggerEvent.Value;
                (response as NHapi.Model.V231.Message.ACK).MSH.MessageType.MessageType.Value  = "ACK";
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                if (!dtls.Exists(o => o.Message == e.Message || o.Exception == e))
                {
                    dtls.Add(new ResultDetail(ResultDetailType.Error, e.Message, e));
                }
                response = MessageUtil.CreateNack(request, dtls, this.Context, typeof(NHapi.Model.V231.Message.ACK));
                audit.Add(auditUtil.CreateAuditData("ITI-8", ActionType.Delete, OutcomeIndicator.EpicFail, evt, new List <VersionedDomainIdentifier>()));
            }
            finally
            {
                IAuditorService auditSvc = this.Context.GetService(typeof(IAuditorService)) as IAuditorService;
                if (auditSvc != null)
                {
                    foreach (var aud in audit)
                    {
                        auditSvc.SendAudit(aud);
                    }
                }
            }
            return(response);
        }
コード例 #10
0
ファイル: EditorAPI.cs プロジェクト: dromanov/NeoAxisEngine
        public static DocumentWindow OpenDocumentWindowForObject(DocumentInstance document, object obj)          //, bool canUseAlreadyOpened )
        {
            if (!IsDocumentObjectSupport(obj))
            {
                return(null);
            }

            //another document or no document
            {
                var objectToDocument = GetDocumentByObject(obj);
                if (objectToDocument == null || objectToDocument != document)
                {
                    var component = obj as Component;
                    if (component != null)
                    {
                        var fileName = ComponentUtility.GetOwnedFileNameOfComponent(component);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            var realFileName = VirtualPathUtility.GetRealPathByVirtual(fileName);

                            if (IsDocumentFileSupport(realFileName))
                            {
                                var documentWindow = OpenFileAsDocument(realFileName, true, true) as DocumentWindow;
                                if (documentWindow != null)
                                {
                                    var newDocument = documentWindow.Document;
                                    var newObject   = newDocument.ResultComponent.Components[component.GetPathFromRoot()];
                                    if (newObject != null)
                                    {
                                        return(OpenDocumentWindowForObject(newDocument, newObject));
                                    }
                                }

                                return(null);
                            }
                        }
                    }

                    return(null);
                }
            }

            //check for already opened
            var canUseAlreadyOpened = !EditorForm.ModifierKeys.HasFlag(Keys.Shift);

            if (canUseAlreadyOpened)
            {
                var openedWindow = EditorForm.Instance.WorkspaceController.FindWindowRecursive(document, obj);
                if (openedWindow != null)
                {
                    EditorForm.Instance.WorkspaceController.SelectDockWindow(openedWindow);
                    return(openedWindow);
                }
            }

            //create document window
            var window = CreateWindowImpl(document, obj, false);

            //!!!!
            bool floatingWindow = false;
            bool select         = true;

            EditorForm.Instance.WorkspaceController.AddDockWindow(window, floatingWindow, select);

            return(window);
        }
        public override bool TryParseAffectedComponentPath(Incident incident, GroupCollection groups, out string affectedComponentPath)
        {
            affectedComponentPath = null;

            var checkName = groups[CheckNameGroupName].Value;

            _logger.LogInformation("Check name is {CheckName}.", checkName);

            switch (checkName)
            {
            case "CDN DNS":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.RestoreName, NuGetServiceComponentFactory.V3ProtocolName);
                break;

            case "CDN Global":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.RestoreName, NuGetServiceComponentFactory.V3ProtocolName, NuGetServiceComponentFactory.GlobalRegionName);
                break;

            case "CDN China":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.RestoreName, NuGetServiceComponentFactory.V3ProtocolName, NuGetServiceComponentFactory.ChinaRegionName);
                break;

            case "Gallery DNS":
            case "Gallery Home":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.GalleryName);
                break;

            case "Gallery USNC /":
            case "Gallery USNC /Packages":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.GalleryName, NuGetServiceComponentFactory.UsncInstanceName);
                break;

            case "Gallery USSC /":
            case "Gallery USSC /Packages":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.GalleryName, NuGetServiceComponentFactory.UsscInstanceName);
                break;

            case "Gallery USNC /api/v2/Packages()":
            case "Gallery USNC /api/v2/package/NuGet.GalleryUptime/1.0.0":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.RestoreName, NuGetServiceComponentFactory.V2ProtocolName, NuGetServiceComponentFactory.UsncInstanceName);
                break;

            case "Gallery USSC /api/v2/Packages()":
            case "Gallery USSC /api/v2/package/NuGet.GalleryUptime/1.0.0":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.RestoreName, NuGetServiceComponentFactory.V2ProtocolName, NuGetServiceComponentFactory.UsscInstanceName);
                break;

            case "Search USNC /query":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.SearchName, NuGetServiceComponentFactory.GlobalRegionName, NuGetServiceComponentFactory.UsncInstanceName);
                break;

            case "Search USSC /query":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.SearchName, NuGetServiceComponentFactory.GlobalRegionName, NuGetServiceComponentFactory.UsscInstanceName);
                break;

            case "Search EA /query":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.SearchName, NuGetServiceComponentFactory.ChinaRegionName, NuGetServiceComponentFactory.EaInstanceName);
                break;

            case "Search SEA /query":
                affectedComponentPath = ComponentUtility.GetPath(
                    NuGetServiceComponentFactory.RootName, NuGetServiceComponentFactory.SearchName, NuGetServiceComponentFactory.ChinaRegionName, NuGetServiceComponentFactory.SeaInstanceName);
                break;

            default:
                return(false);
            }

            return(true);
        }
コード例 #12
0
 void CopyPasteComponentData(Component src, Component dest)
 {
     ComponentUtility.CopyComponent(src);
     ComponentUtility.PasteComponentValues(dest);
 }
コード例 #13
0
        public override void Register()
        {
            var types = new List <Metadata.TypeInfo>();

            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Revolute)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Prismatic)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Distance)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Weld)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Fixed)));

            foreach (var type in types)
            {
                var displayName = TypeUtility.GetUserFriendlyNameForInstanceOfType(type.GetNetType());

                var a = new EditorAction();
                a.Name = "Add " + displayName;
                //a.ImageSmall = Properties.Resources.New_16;
                //a.ImageBig = Properties.Resources.New_32;

                a.QatSupport = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenu.MenuTypeEnum.Document;

                Component_PhysicalBody2D GetBody(object obj)
                {
                    if (obj is Component_PhysicalBody2D body)
                    {
                        return(body);
                    }

                    var c = obj as Component;

                    if (c != null)
                    {
                        var body2 = c.GetComponent <Component_PhysicalBody2D>();
                        if (body2 != null)
                        {
                            return(body2);
                        }
                    }

                    return(null);
                }

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length == 2)
                        {
                            var bodyA = GetBody(selectedObjects[0]);
                            var bodyB = GetBody(selectedObjects[1]);

                            if (bodyA != null && bodyB != null)
                            {
                                context.Enabled = true;
                            }
                            //if( selectedObjects[ 0 ] is Component_PhysicalBody2D && selectedObjects[ 1 ] is Component_PhysicalBody2D )
                            //	context.Enabled = true;
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    object[] selectedObjects = context.ObjectsInFocus.Objects;
                    if (selectedObjects.Length == 2)
                    {
                        var bodyA = GetBody(selectedObjects[0]);
                        var bodyB = GetBody(selectedObjects[1]);
                        //var bodyA = (Component_PhysicalBody2D)context.ObjectsInFocus.Objects[ 0 ];
                        //var bodyB = (Component_PhysicalBody2D)context.ObjectsInFocus.Objects[ 1 ];

                        var parent = ComponentUtility.FindNearestCommonParent(new Component[] { bodyA, bodyB });
                        if (parent != null)
                        {
                            var data = new NewObjectWindow.CreationDataClass();

                            data.initDocumentWindow = context.ObjectsInFocus.DocumentWindow;
                            data.initParentObjects  = new List <object>();
                            data.initParentObjects.Add(parent);
                            data.initLockType = type;

                            data.additionActionBeforeEnabled = delegate(NewObjectWindow window)
                            {
                                var constraint = (Component_Constraint2D)data.createdComponentsOnTopLevel[0];

                                constraint.BodyA = ReferenceUtility.MakeReference <Component_PhysicalBody2D>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyA));
                                constraint.BodyB = ReferenceUtility.MakeReference <Component_PhysicalBody2D>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyB));

                                if (constraint is Component_Constraint2D_Distance)
                                {
                                    var pos  = bodyA.Transform.Value.Position;
                                    var posB = bodyB.Transform.Value.Position;

                                    var distance = (posB - pos).Length();

                                    var rot = Quaternion.FromDirectionZAxisUp((posB - pos).GetNormalize());
                                    var scl = new Vector3(distance, distance, distance);

                                    constraint.Transform = new Transform(pos, rot, scl);
                                }
                                else
                                {
                                    var pos = (bodyA.Transform.Value.Position + bodyB.Transform.Value.Position) * 0.5;
                                    constraint.Transform = new Transform(pos, Quaternion.Identity);
                                }
                            };

                            EditorAPI.OpenNewObjectWindow(data);
                        }
                    }
                };

                EditorActions.Register(a);
            }
        }
コード例 #14
0
        void RenderMaterial(Component_Camera camera, string destRealFileName)
        {
            var renderToFile = RenderToFile;
            var scene        = renderToFile.ParentRoot as Component_Scene;

            var textureFileNames = new string[5];

            //ImageUtility.Image2D opacityImage = null;
            Vector2I[,] opacityImageNearestCellTable = null;

            //write textures
            for (int nChannel = 0; nChannel < 5; nChannel++)
            {
                var channel = (MaterialChannel)nChannel;

                Component_Image texture     = null;
                Component_Image textureRead = null;

                try
                {
                    //!!!!все каналы
                    //!!!!какие еще параметры?

                    var prefix = Path.GetFileNameWithoutExtension(destRealFileName) + "_";

                    string fileName = "";
                    switch (nChannel)
                    {
                    case 0: fileName = prefix + "Opacity.png"; break;

                    case 1: fileName = prefix + "BaseColor.png"; break;

                    case 2: fileName = prefix + "Metallic.png"; break;

                    case 3: fileName = prefix + "Roughness.png"; break;

                    case 4: fileName = prefix + "Normal.png"; break;
                    }

                    var fullPath = Path.Combine(Path.GetDirectoryName(destRealFileName), fileName);

                    //create
                    var resolution = renderToFile.Resolution.Value;

                    PixelFormat format = PixelFormat.A8R8G8B8;

                    texture               = ComponentUtility.CreateComponent <Component_Image>(null, true, false);
                    texture.CreateType    = Component_Image.TypeEnum._2D;
                    texture.CreateSize    = resolution;
                    texture.CreateMipmaps = false;
                    texture.CreateFormat  = format;
                    texture.CreateUsage   = Component_Image.Usages.RenderTarget;
                    texture.CreateFSAA    = 0;
                    texture.Enabled       = true;

                    var renderTexture = texture.Result.GetRenderTarget(0, 0);
                    var viewport      = renderTexture.AddViewport(true, true);
                    viewport.AttachedScene = scene;

                    textureRead               = ComponentUtility.CreateComponent <Component_Image>(null, true, false);
                    textureRead.CreateType    = Component_Image.TypeEnum._2D;
                    textureRead.CreateSize    = resolution;
                    textureRead.CreateMipmaps = false;
                    textureRead.CreateFormat  = format;
                    textureRead.CreateUsage   = Component_Image.Usages.ReadBack | Component_Image.Usages.BlitDestination;
                    textureRead.CreateFSAA    = 0;
                    textureRead.Enabled       = true;
                    //!!!!
                    textureRead.Result.PrepareNativeObject();


                    var restorePipeline = scene.RenderingPipeline;

                    var pipeline = ComponentUtility.CreateComponent <Component_RenderingPipeline_Default>(null, true, true);
                    switch (nChannel)
                    {
                    case 0: pipeline.DebugMode = Component_RenderingPipeline_Basic.DebugModeEnum.Normal; break;

                    case 1: pipeline.DebugMode = Component_RenderingPipeline_Basic.DebugModeEnum.BaseColor; break;

                    case 2: pipeline.DebugMode = Component_RenderingPipeline_Basic.DebugModeEnum.Metallic; break;

                    case 3: pipeline.DebugMode = Component_RenderingPipeline_Basic.DebugModeEnum.Roughness; break;

                    case 4: pipeline.DebugMode = Component_RenderingPipeline_Basic.DebugModeEnum.Normal; break;
                    }

                    try
                    {
                        scene.RenderingPipeline = pipeline;
                        scene.GetDisplayDevelopmentDataInThisApplicationOverride += Scene_GetDisplayDevelopmentDataInThisApplicationOverride;

                        var cameraSettings = new Viewport.CameraSettingsClass(viewport, camera);

                        viewport.Update(true, cameraSettings);

                        //clear temp data
                        viewport.RenderingContext.MultiRenderTarget_DestroyAll();
                        viewport.RenderingContext.DynamicTexture_DestroyAll();
                    }
                    finally
                    {
                        scene.RenderingPipeline = restorePipeline;
                        scene.GetDisplayDevelopmentDataInThisApplicationOverride -= Scene_GetDisplayDevelopmentDataInThisApplicationOverride;
                    }

                    texture.Result.GetRealObject(true).BlitTo(viewport.RenderingContext.CurrentViewNumber, textureRead.Result.GetRealObject(true), 0, 0);


                    //!!!!pitch

                    //get data
                    var totalBytes = PixelFormatUtility.GetNumElemBytes(format) * resolution.X * resolution.Y;
                    var data       = new byte[totalBytes];
                    unsafe
                    {
                        fixed(byte *pBytes = data)
                        {
                            var demandedFrame = textureRead.Result.GetRealObject(true).Read((IntPtr)pBytes, 0);

                            while (RenderingSystem.CallBgfxFrame() < demandedFrame)
                            {
                            }
                        }
                    }

                    var image = new ImageUtility.Image2D(format, resolution, data);

                    if (channel == MaterialChannel.Opacity)
                    {
                        //convert pixels
                        for (int y = 0; y < image.Size.Y; y++)
                        {
                            for (int x = 0; x < image.Size.X; x++)
                            {
                                var pixel = image.GetPixel(new Vector2I(x, y));

                                if (pixel.ToVector3F() != Vector3F.Zero)
                                {
                                    pixel = Vector4F.One;
                                }
                                else
                                {
                                    pixel = Vector4F.Zero;
                                }

                                image.SetPixel(new Vector2I(x, y), pixel);
                            }
                        }

                        //opacityImageNearestCellTable
                        if (renderToFile.FillTransparentPixelsByNearPixels)
                        {
                            var boolOpacityImage = new bool[image.Size.X, image.Size.Y];
                            for (int y = 0; y < image.Size.Y; y++)
                            {
                                for (int x = 0; x < image.Size.X; x++)
                                {
                                    var c = image.GetPixelByte(new Vector2I(x, y));
                                    boolOpacityImage[x, y] = c.Red == 0;
                                }
                            }

                            var distanceMap = GetDistanceMap(image);

                            opacityImageNearestCellTable = new Vector2I[image.Size.X, image.Size.Y];
                            for (int y = 0; y < image.Size.Y; y++)
                            {
                                for (int x = 0; x < image.Size.X; x++)
                                {
                                    opacityImageNearestCellTable[x, y] = new Vector2I(x, y);
                                }
                            }

                            var table = opacityImageNearestCellTable;

                            //!!!!slowly

                            Parallel.For(0, image.Size.Y, delegate(int y)                                //for( int y = 0; y < image.Size.Y; y++ )
                            {
                                for (int x = 0; x < image.Size.X; x++)
                                {
                                    var transparent = boolOpacityImage[x, y];
                                    if (transparent)
                                    {
                                        for (int n = 0; n < distanceMap.Length; n++)                                         //foreach( var indexItem in distanceMap )
                                        {
                                            ref var indexItem = ref distanceMap[n];

                                            var takeFrom = new Vector2I(x, y) + indexItem.offset;
                                            if (takeFrom.X >= 0 && takeFrom.X < image.Size.X && takeFrom.Y >= 0 && takeFrom.Y < image.Size.Y)
                                            {
                                                var transparent2 = boolOpacityImage[takeFrom.X, takeFrom.Y];
                                                if (!transparent2)
                                                {
                                                    table[x, y] = takeFrom;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    }
コード例 #15
0
        /// <summary>
        /// 視線制御の設定をコピーします。
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        /// <param name="sourceSkeletonBones"></param>
        internal static void Copy(
            GameObject source,
            GameObject destination,
            Dictionary <HumanBodyBones, Transform> sourceSkeletonBones
            )
        {
            if (!source.GetComponent <VRMFirstPerson>())
            {
                return;
            }

            var sourceLookAtHead = source.GetComponent <VRMLookAtHead>();

            if (!sourceLookAtHead)
            {
                var destinationLookAtHead = destination.GetComponent <VRMLookAtHead>();
                if (destinationLookAtHead)
                {
                    Object.DestroyImmediate(destinationLookAtHead);
                }
                return;
            }

            var sourceBoneApplyer = source.GetComponent <VRMLookAtBoneApplyer>();

            if (sourceBoneApplyer)
            {
                ComponentUtility.CopyComponent(sourceBoneApplyer);
                var destinationBoneApplyer = destination.GetOrAddComponent <VRMLookAtBoneApplyer>();
                ComponentUtility.PasteComponentValues(destinationBoneApplyer);

                if (destinationBoneApplyer.LeftEye.Transform)
                {
                    destinationBoneApplyer.LeftEye.Transform = BoneMapper.FindCorrespondingBone(
                        sourceBone: destinationBoneApplyer.LeftEye.Transform,
                        source: source,
                        destination: destination,
                        sourceSkeletonBones: sourceSkeletonBones
                        );
                }
                if (destinationBoneApplyer.RightEye.Transform)
                {
                    destinationBoneApplyer.RightEye.Transform = BoneMapper.FindCorrespondingBone(
                        sourceBone: destinationBoneApplyer.RightEye.Transform,
                        source: source,
                        destination: destination,
                        sourceSkeletonBones: sourceSkeletonBones
                        );
                }

                var blendShapeApplyer = destination.GetComponent <VRMLookAtBlendShapeApplyer>();
                if (blendShapeApplyer)
                {
                    Object.DestroyImmediate(blendShapeApplyer);
                }
                return;
            }

            var sourceBlendShapeApplyer = source.GetComponent <VRMLookAtBlendShapeApplyer>();

            if (sourceBlendShapeApplyer)
            {
                ComponentUtility.CopyComponent(sourceBlendShapeApplyer);
                var destinationBlendShapeApplyer = destination.GetOrAddComponent <VRMLookAtBlendShapeApplyer>();
                ComponentUtility.PasteComponentValues(destinationBlendShapeApplyer);
            }
        }
コード例 #16
0
ファイル: PixHandler.cs プロジェクト: shenghu/client-registry
        /// <summary>
        /// Handle a PIX admission
        /// </summary>
        private IMessage HandlePixAdmit(NHapi.Model.V231.Message.ADT_A01 request, Hl7MessageReceivedEventArgs evt)
        {
            // Get config
            var config      = this.Context.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService;
            var locale      = this.Context.GetService(typeof(ILocalizationService)) as ILocalizationService;
            var dataService = this.Context.GetService(typeof(IClientRegistryDataService)) as IClientRegistryDataService;
            // Create a details array
            List <IResultDetail> dtls = new List <IResultDetail>();

            // Validate the inbound message
            MessageUtil.Validate((IMessage)request, config, dtls, this.Context);

            IMessage response = null;

            // Control
            if (request == null)
            {
                return(null);
            }

            // Data controller
            AuditUtil auditUtil = new AuditUtil()
            {
                Context = this.Context
            };
            //DataUtil dataUtil = new DataUtil() { Context = this.Context };

            // Construct appropriate audit
            AuditData audit = null;

            try
            {
                // Create Query Data
                ComponentUtility cu = new ComponentUtility()
                {
                    Context = this.Context
                };
                DeComponentUtility dcu = new DeComponentUtility()
                {
                    Context = this.Context
                };
                var data = cu.CreateComponents(request, dtls);
                if (data == null)
                {
                    throw new InvalidOperationException(locale.GetString("MSGE00A"));
                }

                var result = dataService.Register(data, request.MSH.ProcessingID.ProcessingID.Value == "P" ? DataPersistenceMode.Production : DataPersistenceMode.Debugging);
                if (result == null || result.VersionId == null)
                {
                    throw new InvalidOperationException(locale.GetString("DTPE001"));
                }

                dtls.AddRange(result.Details);

                audit = auditUtil.CreateAuditData("ITI-8", result.VersionId.UpdateMode == UpdateModeType.Update ? ActionType.Update : ActionType.Create, OutcomeIndicator.Success, evt, new List <VersionedDomainIdentifier>()
                {
                    result.VersionId
                });

                // Now process the result
                response = MessageUtil.CreateNack(request, dtls, this.Context, typeof(NHapi.Model.V231.Message.ACK));
                MessageUtil.UpdateMSH(new NHapi.Base.Util.Terser(response), request, config);
                (response as NHapi.Model.V231.Message.ACK).MSH.MessageType.TriggerEvent.Value = request.MSH.MessageType.TriggerEvent.Value;
                (response as NHapi.Model.V231.Message.ACK).MSH.MessageType.MessageType.Value  = "ACK";
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                if (!dtls.Exists(o => o.Message == e.Message || o.Exception == e))
                {
                    dtls.Add(new ResultDetail(ResultDetailType.Error, e.Message, e));
                }
                response = MessageUtil.CreateNack(request, dtls, this.Context, typeof(NHapi.Model.V231.Message.ACK));
                audit    = auditUtil.CreateAuditData("ITI-8", ActionType.Create, OutcomeIndicator.EpicFail, evt, new List <VersionedDomainIdentifier>());
            }
            finally
            {
                IAuditorService auditSvc = this.Context.GetService(typeof(IAuditorService)) as IAuditorService;
                if (auditSvc != null)
                {
                    auditSvc.SendAudit(audit);
                }
            }
            return(response);
        }
コード例 #17
0
 public BsDialog Data(object value)
 {
     Attributes["data"] = ComponentUtility.ToJsonString(value);
     SetScript();
     return(this);
 }
コード例 #18
0
ファイル: PixHandler.cs プロジェクト: shenghu/client-registry
        /// <summary>
        /// Handle a PIX query
        /// </summary>
        private IMessage HandlePixQuery(NHapi.Model.V25.Message.QBP_Q21 request, Hl7MessageReceivedEventArgs evt)
        {
            // Get config
            var config      = this.Context.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService;
            var locale      = this.Context.GetService(typeof(ILocalizationService)) as ILocalizationService;
            var dataService = this.Context.GetService(typeof(IClientRegistryDataService)) as IClientRegistryDataService;

            // Create a details array
            List <IResultDetail> dtls = new List <IResultDetail>();

            // Validate the inbound message
            MessageUtil.Validate((IMessage)request, config, dtls, this.Context);

            IMessage response = null;

            // Control
            if (request == null)
            {
                return(null);
            }

            // Construct appropriate audit
            AuditData audit = null;

            // Data controller
            AuditUtil auditUtil = new AuditUtil()
            {
                Context = this.Context
            };

            //DataUtil dataUtil = new DataUtil() { Context = this.Context };

            try
            {
                // Create Query Data
                ComponentUtility cu = new ComponentUtility()
                {
                    Context = this.Context
                };
                DeComponentUtility dcu = new DeComponentUtility()
                {
                    Context = this.Context
                };
                var data = cu.CreateQueryComponents(request, dtls);

                if (data == null)
                {
                    throw new InvalidOperationException(locale.GetString("MSGE00A"));
                }


                RegistryQueryResult result = dataService.Query(data);
                dtls.AddRange(result.Details);

                // Update locations?
                foreach (var dtl in dtls)
                {
                    if (dtl is PatientNotFoundResultDetail)
                    {
                        dtl.Location = "QPD^1^3^1^1";
                    }
                    else if (dtl is UnrecognizedPatientDomainResultDetail)
                    {
                        dtl.Location = "QPD^1^3^1^4";
                    }
                    else if (dtl is UnrecognizedTargetDomainResultDetail)
                    {
                        dtl.Location = "QPD^1^4^";
                    }
                }


                audit = auditUtil.CreateAuditData("ITI-9", ActionType.Execute, OutcomeIndicator.Success, evt, result);

                // Now process the result
                response = dcu.CreateRSP_K23(result, dtls);
                //var r = dcu.CreateRSP_K23(null, null);
                // Copy QPD
                try
                {
                    (response as NHapi.Model.V25.Message.RSP_K23).QPD.MessageQueryName.Identifier.Value = request.QPD.MessageQueryName.Identifier.Value;
                    Terser reqTerser = new Terser(request),
                           rspTerser = new Terser(response);
                    rspTerser.Set("/QPD-1", reqTerser.Get("/QPD-1"));
                    rspTerser.Set("/QPD-2", reqTerser.Get("/QPD-2"));
                    rspTerser.Set("/QPD-3-1", reqTerser.Get("/QPD-3-1"));
                    rspTerser.Set("/QPD-3-4-1", reqTerser.Get("/QPD-3-4-1"));
                    rspTerser.Set("/QPD-3-4-2", reqTerser.Get("/QPD-3-4-2"));
                    rspTerser.Set("/QPD-3-4-3", reqTerser.Get("/QPD-3-4-3"));
                    rspTerser.Set("/QPD-4-1", reqTerser.Get("/QPD-4-1"));
                    rspTerser.Set("/QPD-4-4-1", reqTerser.Get("/QPD-4-4-1"));
                    rspTerser.Set("/QPD-4-4-2", reqTerser.Get("/QPD-4-4-2"));
                    rspTerser.Set("/QPD-4-4-3", reqTerser.Get("/QPD-4-4-3"));
                }
                catch (Exception e)
                {
                    Trace.TraceError(e.ToString());
                }
                //MessageUtil.((response as NHapi.Model.V25.Message.RSP_K23).QPD, request.QPD);

                MessageUtil.UpdateMSH(new NHapi.Base.Util.Terser(response), request, config);
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                if (!dtls.Exists(o => o is UnrecognizedPatientDomainResultDetail || o is UnrecognizedTargetDomainResultDetail || o.Message == e.Message || o.Exception == e))
                {
                    dtls.Add(new ResultDetail(ResultDetailType.Error, e.Message, e));
                }
                response = MessageUtil.CreateNack(request, dtls, this.Context, typeof(RSP_K23));
                Terser errTerser = new Terser(response);
                // HACK: Fix the generic ACK with a real ACK for this message
                errTerser.Set("/MSH-9-2", "K23");
                errTerser.Set("/MSH-9-3", "RSP_K23");
                errTerser.Set("/QAK-2", "AE");
                errTerser.Set("/MSA-1", "AE");
                errTerser.Set("/QAK-1", request.QPD.QueryTag.Value);
                audit = auditUtil.CreateAuditData("ITI-9", ActionType.Execute, OutcomeIndicator.EpicFail, evt, new List <VersionedDomainIdentifier>());
            }
            finally
            {
                IAuditorService auditSvc = this.Context.GetService(typeof(IAuditorService)) as IAuditorService;
                if (auditSvc != null)
                {
                    auditSvc.SendAudit(audit);
                }
            }

            return(response);
        }
コード例 #19
0
 /// <summary>
 /// new[] { new { id = 1, name = "ali1" }, new { id = 2, name = "ali2" }, new { id = 3, name = "ali3" } }
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public Select2Option Data(IEnumerable value)
 {
     Attributes["data"] = ComponentUtility.ToJsonStringWithoutQuotes(value);
     return(this);
 }
コード例 #20
0
 private void Awake()
 {
     ItemSnapArray = GetComponentsInChildren <ItemSnap>();
     _itemSettings = ComponentUtility.FindOnNamedGameObject <ItemSettings>();
 }
コード例 #21
0
        void UpdateContentBrowser(out bool selected)
        {
            selected = false;

            contentBrowser1.Init(documentWindow, null, /*null, */ setReferenceModeData);
            contentBrowser1.UpdateData();

            if (GetInitialReference(out var reference))
            {
                //!!!!
                //convert relative file paths
                //!!!!multiselection?
                if (ReferenceUtility.ConvertRelativePathToResource(reference, setReferenceModeData.selectedComponents[0], out var reference2))
                {
                    reference = reference2;
                    kryptonCheckBoxCanMakeRelativeFilePath.Checked = true;
                }

                bool expand = false;

                //if reference is empty, then select folder of resource
                if (string.IsNullOrEmpty(reference))
                {
                    if (setReferenceModeData.propertyOwners.Length != 0)
                    {
                        //!!!!multiselection
                        var obj = setReferenceModeData.propertyOwners[0];

                        var component = obj as Component;
                        if (component != null)
                        {
                            var path = ComponentUtility.GetOwnedFileNameOfComponent(component);
                            if (!string.IsNullOrEmpty(path))
                            {
                                try
                                {
                                    reference = Path.GetDirectoryName(path);
                                    expand    = true;
                                }
                                catch { }
                            }
                        }
                    }
                }

                try
                {
                    selected = SelectReference(reference, expand);
                }
                catch { }
            }

            //if( setReferenceModeData.propertyOwners.Length != 0 )
            //{
            //	//!!!!multiselection
            //	var obj = setReferenceModeData.propertyOwners[ 0 ];

            //	try
            //	{
            //		var value = setReferenceModeData.property.GetValue( obj, setReferenceModeData.propertyIndexes );
            //		if( value != null )
            //		{
            //			var iReference = value as IReference;
            //			if( iReference != null )
            //			{
            //				var reference = iReference.GetByReference;
            //				if( reference == null )
            //					reference = "";

            //				selected = SelectReference( reference );
            //			}
            //		}
            //	}
            //	catch { }
            //}
        }
コード例 #22
0
        private bool MoveOrCopyComponents(Component[] sourceComponents, Component[] targetComponents, bool copy, bool validateOnly)
        {
            bool result;

            if (copy)
            {
                result = false;
            }
            else if (sourceComponents.Length == 1 && targetComponents.Length == 1)
            {
                result = (!(sourceComponents[0].gameObject != targetComponents[0].gameObject) && ComponentUtility.MoveComponentRelativeToComponent(sourceComponents[0], targetComponents[0], this.m_TargetAbove, validateOnly));
            }
            else
            {
                result = ComponentUtility.MoveComponentsRelativeToComponents(sourceComponents, targetComponents, this.m_TargetAbove, validateOnly);
            }
            return(result);
        }
コード例 #23
0
 private void AssertLeastCommonAncestorPathHelper(IComponent firstComponent, IComponent secondComponent, string expectedLeastCommonAncestor)
 {
     Assert.Equal(expectedLeastCommonAncestor, ComponentUtility.GetLeastCommonAncestorPath(firstComponent, secondComponent));
     Assert.Equal(expectedLeastCommonAncestor, ComponentUtility.GetLeastCommonAncestorPath(firstComponent.Path, secondComponent.Path));
 }
コード例 #24
0
        private void HandleEditorDragging(int editorIndex, Rect targetRect, float markerY, bool bottomTarget, ActiveEditorTracker tracker)
        {
            Event     current = Event.current;
            EventType type    = current.type;

            switch (type)
            {
            case EventType.Repaint:
                if (this.m_TargetIndex != -1 && targetRect.Contains(current.mousePosition))
                {
                    Rect position = new Rect(targetRect.x, markerY, targetRect.width, 3f);
                    if (!this.m_TargetAbove)
                    {
                        position.y += 2f;
                    }
                    EditorDragging.Styles.insertionMarker.Draw(position, false, false, false, false);
                }
                return;

            case EventType.Layout:
IL_26:
                if (type != EventType.DragExited)
                {
                    return;
                }
                this.m_TargetIndex = -1;
                return;

            case EventType.DragUpdated:
                if (targetRect.Contains(current.mousePosition))
                {
                    EditorDragging.DraggingMode?draggingMode = DragAndDrop.GetGenericData("InspectorEditorDraggingMode") as EditorDragging.DraggingMode?;
                    if (!draggingMode.HasValue)
                    {
                        UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences;
                        if (objectReferences.Length == 0)
                        {
                            draggingMode = new EditorDragging.DraggingMode?(EditorDragging.DraggingMode.NotApplicable);
                        }
                        else if (objectReferences.All((UnityEngine.Object o) => o is Component && !(o is Transform)))
                        {
                            draggingMode = new EditorDragging.DraggingMode?(EditorDragging.DraggingMode.Component);
                        }
                        else if (objectReferences.All((UnityEngine.Object o) => o is MonoScript))
                        {
                            draggingMode = new EditorDragging.DraggingMode?(EditorDragging.DraggingMode.Script);
                        }
                        else
                        {
                            draggingMode = new EditorDragging.DraggingMode?(EditorDragging.DraggingMode.NotApplicable);
                        }
                        DragAndDrop.SetGenericData("InspectorEditorDraggingMode", draggingMode);
                    }
                    if (draggingMode.Value != EditorDragging.DraggingMode.NotApplicable)
                    {
                        Editor[]             activeEditors     = tracker.activeEditors;
                        UnityEngine.Object[] objectReferences2 = DragAndDrop.objectReferences;
                        if (bottomTarget)
                        {
                            this.m_TargetAbove = false;
                            this.m_TargetIndex = this.m_LastIndex;
                        }
                        else
                        {
                            this.m_TargetAbove = (current.mousePosition.y < targetRect.y + targetRect.height / 2f);
                            this.m_TargetIndex = editorIndex;
                            if (this.m_TargetAbove)
                            {
                                this.m_TargetIndex++;
                                while (this.m_TargetIndex < activeEditors.Length && this.m_InspectorWindow.ShouldCullEditor(activeEditors, this.m_TargetIndex))
                                {
                                    this.m_TargetIndex++;
                                }
                                if (this.m_TargetIndex == activeEditors.Length)
                                {
                                    this.m_TargetIndex = -1;
                                    return;
                                }
                            }
                        }
                        if (this.m_TargetAbove && this.m_InspectorWindow.EditorHasLargeHeader(this.m_TargetIndex, activeEditors))
                        {
                            this.m_TargetIndex--;
                            while (this.m_TargetIndex >= 0 && this.m_InspectorWindow.ShouldCullEditor(activeEditors, this.m_TargetIndex))
                            {
                                this.m_TargetIndex--;
                            }
                            if (this.m_TargetIndex == -1)
                            {
                                return;
                            }
                            this.m_TargetAbove = false;
                        }
                        if (draggingMode.Value == EditorDragging.DraggingMode.Script)
                        {
                            DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                        }
                        else
                        {
                            bool flag = false;
                            if (activeEditors[this.m_TargetIndex].targets.All((UnityEngine.Object t) => t is Component))
                            {
                                Component[] targetComponents = activeEditors[this.m_TargetIndex].targets.Cast <Component>().ToArray <Component>();
                                Component[] sourceComponents = DragAndDrop.objectReferences.Cast <Component>().ToArray <Component>();
                                flag = this.MoveOrCopyComponents(sourceComponents, targetComponents, EditorUtility.EventHasDragCopyModifierPressed(current), true);
                            }
                            if (!flag)
                            {
                                DragAndDrop.visualMode = DragAndDropVisualMode.None;
                                this.m_TargetIndex     = -1;
                                return;
                            }
                            DragAndDrop.visualMode = ((!EditorUtility.EventHasDragCopyModifierPressed(current)) ? DragAndDropVisualMode.Move : DragAndDropVisualMode.Copy);
                        }
                        current.Use();
                    }
                }
                else
                {
                    this.m_TargetIndex = -1;
                }
                return;

            case EventType.DragPerform:
                if (this.m_TargetIndex != -1)
                {
                    EditorDragging.DraggingMode?draggingMode2 = DragAndDrop.GetGenericData("InspectorEditorDraggingMode") as EditorDragging.DraggingMode?;
                    if (!draggingMode2.HasValue || draggingMode2.Value == EditorDragging.DraggingMode.NotApplicable)
                    {
                        this.m_TargetIndex = -1;
                    }
                    else
                    {
                        Editor[] activeEditors2 = tracker.activeEditors;
                        if (activeEditors2[this.m_TargetIndex].targets.All((UnityEngine.Object t) => t is Component))
                        {
                            Component[] array = activeEditors2[this.m_TargetIndex].targets.Cast <Component>().ToArray <Component>();
                            if (draggingMode2.Value == EditorDragging.DraggingMode.Script)
                            {
                                IEnumerable <MonoScript> enumerable = DragAndDrop.objectReferences.Cast <MonoScript>();
                                bool        flag2  = true;
                                Component[] array2 = array;
                                for (int i = 0; i < array2.Length; i++)
                                {
                                    Component  targetComponent = array2[i];
                                    GameObject gameObject      = targetComponent.gameObject;
                                    if (enumerable.Any((MonoScript s) => !ComponentUtility.WarnCanAddScriptComponent(targetComponent.gameObject, s)))
                                    {
                                        flag2 = false;
                                        break;
                                    }
                                }
                                if (flag2)
                                {
                                    Undo.IncrementCurrentGroup();
                                    int         currentGroup = Undo.GetCurrentGroup();
                                    int         num          = 0;
                                    Component[] array3       = new Component[array.Length * enumerable.Count <MonoScript>()];
                                    Component[] array4       = array;
                                    for (int j = 0; j < array4.Length; j++)
                                    {
                                        Component  component   = array4[j];
                                        GameObject gameObject2 = component.gameObject;
                                        foreach (MonoScript current2 in enumerable)
                                        {
                                            array3[num++] = Undo.AddComponent(gameObject2, current2.GetClass());
                                        }
                                    }
                                    if (!ComponentUtility.MoveComponentsRelativeToComponents(array3, array, this.m_TargetAbove))
                                    {
                                        Undo.RevertAllDownToGroup(currentGroup);
                                    }
                                }
                            }
                            else
                            {
                                Component[] array5 = DragAndDrop.objectReferences.Cast <Component>().ToArray <Component>();
                                if (array5.Length == 0 || array.Length == 0)
                                {
                                    return;
                                }
                                this.MoveOrCopyComponents(array5, array, EditorUtility.EventHasDragCopyModifierPressed(current), false);
                            }
                            this.m_TargetIndex = -1;
                            DragAndDrop.AcceptDrag();
                            current.Use();
                            GUIUtility.ExitGUI();
                        }
                    }
                }
                return;
            }
            goto IL_26;
        }
コード例 #25
0
        void HandleDragPerformEvent(Editor[] editors, Event evt, ref int targetIndex)
        {
            if (targetIndex != -1)
            {
                var draggingMode = DragAndDrop.GetGenericData(k_DraggingModeKey) as DraggingMode ? ;
                if (!draggingMode.HasValue || draggingMode.Value == DraggingMode.NotApplicable)
                {
                    targetIndex = -1;
                    return;
                }

                if (!editors[targetIndex].targets.All(t => t is Component))
                {
                    return;
                }

                var targetComponents = editors[targetIndex].targets.Cast <Component>().ToArray();

                if (draggingMode.Value == DraggingMode.Script)
                {
                    var scripts = DragAndDrop.objectReferences.Cast <MonoScript>();

                    // Ensure all script components can be added
                    var valid = true;
                    foreach (var targetComponent in targetComponents)
                    {
                        var gameObject = targetComponent.gameObject;
                        if (scripts.Any(s => !ComponentUtility.WarnCanAddScriptComponent(gameObject, s)))
                        {
                            valid = false;
                            break;
                        }
                    }

                    if (valid)
                    {
                        Undo.IncrementCurrentGroup();
                        var undoGroup = Undo.GetCurrentGroup();

                        // Add script components
                        var index           = 0;
                        var addedComponents = new Component[targetComponents.Length * scripts.Count()];
                        for (int i = 0; i < targetComponents.Length; i++)
                        {
                            var  targetComponent   = targetComponents[i];
                            var  gameObject        = targetComponent.gameObject;
                            bool targetIsTransform = targetComponent is Transform;
                            foreach (var script in scripts)
                            {
                                addedComponents[index++] = ObjectFactory.AddComponent(gameObject, script.GetClass());
                            }

                            // If the target is a Transform, the AddComponent might have replaced it with a RectTransform.
                            // Handle this possibility by updating the target component.
                            if (targetIsTransform)
                            {
                                targetComponents[i] = gameObject.transform;
                            }
                        }

                        // Move added components relative to target components
                        if (!ComponentUtility.MoveComponentsRelativeToComponents(addedComponents, targetComponents, m_TargetAbove))
                        {
                            // Ensure we have the same selection after calling RevertAllDownToGroup below (MoveComponentsRelativeToComponents can have opened a Prefab in Prefab Mode and changed selection to that root)
                            var wantedSelectedGameObject = Selection.activeGameObject;

                            // Revert added components if move operation fails (e.g. user has been shown the dialog with 'prefab instance restructuring is not posssible' or object is not editable)
                            Undo.RevertAllDownToGroup(undoGroup);

                            if (wantedSelectedGameObject != Selection.activeGameObject)
                            {
                                Selection.activeGameObject = wantedSelectedGameObject;
                            }
                        }
                    }
                }
                else
                {
                    // Handle dragging components
                    var sourceComponents = DragAndDrop.objectReferences.Cast <Component>().ToArray();
                    if (sourceComponents.Length == 0 || targetComponents.Length == 0)
                    {
                        return;
                    }

                    MoveOrCopyComponents(sourceComponents, targetComponents, EditorUtility.EventHasDragCopyModifierPressed(evt), false);
                }

                targetIndex = -1;
                DragAndDrop.AcceptDrag();
                evt.Use();
                EditorGUIUtility.ExitGUI();
            }
        }
コード例 #26
0
        public static MvcHtmlString Select2DropDown <T1, T2>(this HtmlHelper html, string name, T1 value, Dictionary <T1, T2> source, string defaultValue = null, object htmlAttribute = null, Select2Option option = null)
        {
            option = option ?? new Select2Option();
            var id         = html.ViewData.TemplateInfo.GetFullHtmlFieldId(name);
            var selectList = new SelectList(source, "Key", "Value", value);
            var items      = selectList.Cast <SelectListItem>().ToList();
            //if (defaultValue.HasValue())
            //    items.Insert(0, new SelectListItem { Value = null, Text = defaultValue });
            var attributes = ComponentUtility.MergeAttributes(htmlAttribute, new { @class = "form-control", style = "width: 100%" });
            var editor     = html.DropDownList(name, items, defaultValue, attributes);
            var result     =
                editor.ToHtmlString() +
                html.StyleFileSingle(@"<link href=""" + ComponentUtility.GetWebResourceUrl(select2_css) + @""" rel=""stylesheet"" />").ToHtmlString() +
                html.StyleFileSingle(@"<link href=""" + ComponentUtility.GetWebResourceUrl(select2_custom_css) + @""" rel=""stylesheet"" />").ToHtmlString() +
                (option.Attributes["language"] == null ? "" : html.ScriptFileSingle(@"<script src=""" + ComponentUtility.GetWebResourceUrl(string.Format("Savosh.Component.Select2.i18n.{0}.js", option.Attributes["language"].ToString().Trim('\''))) + @"""></script>").ToHtmlString()) +
                html.ScriptFileSingle(@" <script src=""" + ComponentUtility.GetWebResourceUrl(select2_js) + @"""></script>").ToHtmlString() +
                html.Script(@"
            <script>
                $(function(){
                    $(""#" + id + @""").select2(" + option.RenderOptions() + @").change(function () { 
                        $(this).valid();
                    });
                });
            </script>").ToHtmlString();

            return(MvcHtmlString.Create(result));
        }
コード例 #27
0
 public BsUploadSetting UploadExtraData(object keyValueAttributes)
 {
     //var dic = (IDictionary<string, string>)keyValueAttributes;
     Attributes["uploadExtraData"] = ComponentUtility.ToJsonStringWithoutQuotes(keyValueAttributes);
     return(this);
 }
コード例 #28
0
        public static MvcHtmlString Select2DropDownFor <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, SelectList selectList, string defaultValue = null, object htmlAttribute = null, Select2Option option = null)
        {
            option = option ?? new Select2Option();
            var metadata      = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            var id            = html.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName);
            var displayName   = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            var value         = metadata.Model;
            var items         = selectList.Cast <SelectListItem>().ToList();

            if (defaultValue.HasValue())
            {
                items.Insert(0, new SelectListItem {
                    Value = "", Text = defaultValue
                });
            }
            var attributes = ComponentUtility.MergeAttributes(htmlAttribute, new { @class = "form-control", placeholder = displayName, style = "width: 100%" });
            var editor     = html.DropDownListFor(expression, items, attributes);
            var result     =
                editor.ToHtmlString() +
                html.StyleFileSingle(@"<link href=""" + ComponentUtility.GetWebResourceUrl(select2_css) + @""" rel=""stylesheet"" />").ToHtmlString() +
                html.StyleFileSingle(@"<link href=""" + ComponentUtility.GetWebResourceUrl(select2_custom_css) + @""" rel=""stylesheet"" />").ToHtmlString() +
                (option.Attributes["language"] == null ? "" : html.ScriptFileSingle(@"<script src=""" + ComponentUtility.GetWebResourceUrl(string.Format("Savosh.Component.Select2.i18n.{0}.js", option.Attributes["language"].ToString().Trim('\''))) + @"""></script>").ToHtmlString()) +
                html.ScriptFileSingle(@" <script src=""" + ComponentUtility.GetWebResourceUrl(select2_js) + @"""></script>").ToHtmlString() +
                html.Script(@"
            <script>
                $(function(){
                    $(""#" + id + @""").select2(" + option.RenderOptions() + @").change(function () { 
                        $(this).valid();
                    });
                });
            </script>").ToHtmlString();

            return(MvcHtmlString.Create(result));
        }
コード例 #29
0
 public void ReturnsEmptyForNullReadOnlyComponent()
 {
     Assert.Empty(ComponentUtility.GetAllComponents(null));
 }
コード例 #30
0
        void RenderScreenshot(Component_Camera camera, string destRealFileName)
        {
            var renderToFile = RenderToFile;
            var scene        = renderToFile.ParentRoot as Component_Scene;

            Component_Image texture     = null;
            Component_Image textureRead = null;

            try
            {
                //create
                var resolution = renderToFile.Resolution.Value;

                //!!!!impl
                var         hdr    = false;     //HDR.Value;
                PixelFormat format = hdr ? PixelFormat.Float16RGBA : PixelFormat.A8R8G8B8;
                //PixelFormat format = hdr ? PixelFormat.Float32RGBA : PixelFormat.A8R8G8B8;

                texture               = ComponentUtility.CreateComponent <Component_Image>(null, true, false);
                texture.CreateType    = Component_Image.TypeEnum._2D;
                texture.CreateSize    = resolution;
                texture.CreateMipmaps = false;
                texture.CreateFormat  = format;
                texture.CreateUsage   = Component_Image.Usages.RenderTarget;
                texture.CreateFSAA    = 0;
                texture.Enabled       = true;

                var renderTexture = texture.Result.GetRenderTarget(0, 0);
                var viewport      = renderTexture.AddViewport(true, true);
                viewport.AttachedScene = scene;

                textureRead               = ComponentUtility.CreateComponent <Component_Image>(null, true, false);
                textureRead.CreateType    = Component_Image.TypeEnum._2D;
                textureRead.CreateSize    = resolution;
                textureRead.CreateMipmaps = false;
                textureRead.CreateFormat  = format;
                textureRead.CreateUsage   = Component_Image.Usages.ReadBack | Component_Image.Usages.BlitDestination;
                textureRead.CreateFSAA    = 0;
                textureRead.Enabled       = true;
                //!!!!
                textureRead.Result.PrepareNativeObject();

                //render
                //var image2D = new ImageUtility.Image2D( PixelFormat.Float32RGB, new Vector2I( size * 4, size * 3 ) );

                //var position = Transform.Value.Position;

                //for( int face = 0; face < 6; face++ )
                //{

                //Vector3 dir = Vector3.Zero;
                //Vector3 up = Vector3.Zero;

                ////flipped
                //switch( face )
                //{
                //case 0: dir = -Vector3.YAxis; up = Vector3.ZAxis; break;
                //case 1: dir = Vector3.YAxis; up = Vector3.ZAxis; break;
                //case 2: dir = Vector3.ZAxis; up = -Vector3.XAxis; break;
                //case 3: dir = -Vector3.ZAxis; up = Vector3.XAxis; break;
                //case 4: dir = Vector3.XAxis; up = Vector3.ZAxis; break;
                //case 5: dir = -Vector3.XAxis; up = Vector3.ZAxis; break;
                //}

                try
                {
                    scene.GetDisplayDevelopmentDataInThisApplicationOverride += Scene_GetDisplayDevelopmentDataInThisApplicationOverride;

                    var cameraSettings = new Viewport.CameraSettingsClass(viewport, camera);

                    //var cameraSettings = new Viewport.CameraSettingsClass( viewport, 1, 90, NearClipPlane.Value, FarClipPlane.Value, position, dir, up, ProjectionType.Perspective, 1, 1, 1 );

                    viewport.Update(true, cameraSettings);

                    //clear temp data
                    viewport.RenderingContext.MultiRenderTarget_DestroyAll();
                    viewport.RenderingContext.DynamicTexture_DestroyAll();
                }
                finally
                {
                    scene.GetDisplayDevelopmentDataInThisApplicationOverride -= Scene_GetDisplayDevelopmentDataInThisApplicationOverride;
                }

                texture.Result.GetRealObject(true).BlitTo(viewport.RenderingContext.CurrentViewNumber, textureRead.Result.GetRealObject(true), 0, 0);


                //!!!!pitch

                //get data
                var totalBytes = PixelFormatUtility.GetNumElemBytes(format) * resolution.X * resolution.Y;
                var data       = new byte[totalBytes];
                unsafe
                {
                    fixed(byte *pBytes = data)
                    {
                        var demandedFrame = textureRead.Result.GetRealObject(true).Read((IntPtr)pBytes, 0);

                        while (RenderingSystem.CallBgfxFrame() < demandedFrame)
                        {
                        }
                    }
                }

                var image = new ImageUtility.Image2D(format, resolution, data);

                //reset alpha channel
                for (int y = 0; y < image.Size.Y; y++)
                {
                    for (int x = 0; x < image.Size.X; x++)
                    {
                        var pixel = image.GetPixel(new Vector2I(x, y));
                        pixel.W = 1.0f;
                        image.SetPixel(new Vector2I(x, y), pixel);
                    }
                }

                //image.Data
                //image2D.Blit( index * size, faceImage );

                //Vector2I index = Vector2I.Zero;
                //switch( face )
                //{
                //case 0: index = new Vector2I( 2, 1 ); break;
                //case 1: index = new Vector2I( 0, 1 ); break;
                //case 2: index = new Vector2I( 1, 0 ); break;
                //case 3: index = new Vector2I( 1, 2 ); break;
                //case 4: index = new Vector2I( 1, 1 ); break;
                //case 5: index = new Vector2I( 3, 1 ); break;
                //}

                //var faceImage = new ImageUtility.Image2D( format, new Vector2I( size, size ), data );
                //image2D.Blit( index * size, faceImage );
                //}

                if (!Directory.Exists(Path.GetDirectoryName(destRealFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(destRealFileName));
                }

                if (!ImageUtility.Save(destRealFileName, image.Data, image.Size, 1, image.Format, 1, 0, out var error))
                {
                    throw new Exception(error);
                }
            }
            catch (Exception e)
            {
                EditorMessageBox.ShowWarning(e.Message);
                return;
            }
            finally
            {
                texture?.Dispose();
                textureRead?.Dispose();
            }

            ScreenNotifications.Show("Rendering completed successfully.");
        }