Exemplo n.º 1
0
        public void TestUsingDefaultRPackages()
        {
            // This test was designed to look at a symptom observed alongside the issue https://github.com/rdotnet/rdotnet/issues/127
            SetUpTest();
            var engine = this.Engine;
            var se     = engine.Evaluate("set.seed");

            if (NativeUtility.GetPlatform() == PlatformID.Win32NT)
            {
                Assert.True(engine.Evaluate("Sys.which('R.dll')").AsCharacter()[0].Length > 0);
                Assert.True(engine.Evaluate("Sys.which('RBLAS.dll')").AsCharacter()[0].Length > 0);
            }

            string[] expected   = { "base", "methods", "utils", "grDevices", "graphics", "stats" };
            var      loadedDlls = engine.Evaluate("getLoadedDLLs()").AsList();

            string[] dllnames = loadedDlls.Select(x => x.AsCharacter().ToArray()[0]).ToArray();

            IEnumerable <string> query = from x in expected.Intersect(dllnames)
                                         select x;

            Assert.Equal(expected, query.ToArray());

            se = engine.Evaluate("set.seed(0)");
            se = engine.Evaluate("blah <- rnorm(4)");
        }
Exemplo n.º 2
0
        //[WriteOnly]
        //public NativeQueue<float4>.ParallelWriter dstGridPositions;
        //[WriteOnly]
        //public NativeList<uint> dstCubes;

        public void Execute()
        {
            var id = 0;

            for (var i = 0; i < this.srcCubeGrids.Length; i++)
            {
                var g   = this.srcCubeGrids[i];
                var ggg = new CubeNearGridsNativeArray
                {
                    current         = NativeUtility.PtrToNativeArray(g.current, 32 * 32),
                    current_right   = NativeUtility.PtrToNativeArray(g.current_right, 32 * 32),
                    back            = NativeUtility.PtrToNativeArray(g.back, 32 * 32),
                    back_right      = NativeUtility.PtrToNativeArray(g.back_right, 32 * 32),
                    under           = NativeUtility.PtrToNativeArray(g.under, 32 * 32),
                    under_right     = NativeUtility.PtrToNativeArray(g.under_right, 32 * 32),
                    backUnder       = NativeUtility.PtrToNativeArray(g.backUnder, 32 * 32),
                    backUnder_right = NativeUtility.PtrToNativeArray(g.backUnder_right, 32 * 32)
                };
                var isCubeAdded = ggg.SampleAllCubes(id, this.dstCubes);
                if (isCubeAdded)
                {
                    this.dstGridPositions.Add(new float4(id * 32, -0 * 32, -0 * 32, 0));
                    id++;
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="MultiCatchmentCompositeObjectiveEvaluator" /> class.
        /// </summary>
        /// <param name="objDefn"> The objective definition. </param>
        private RCompositeObjectiveEvaluator(RexpObjectiveDefinition objDefn)
        {
            objectiveDefinition = objDefn;
            string pathToRDynLib = objDefn.DirectoryForRLibrary;
            string rhome         = Environment.GetEnvironmentVariable("R_HOME");

            if (!Directory.Exists(pathToRDynLib))
            {
                REngine.SetEnvironmentVariables();
            }
            else
            {
                if (string.IsNullOrEmpty(rhome))
                {
                    var plat = NativeUtility.GetPlatform();
                    switch (plat)
                    {
                    case PlatformID.Win32NT:
                        if (string.IsNullOrEmpty(rhome))
                        {
                            rhome = Path.Combine(pathToRDynLib, @"..\..");     // Assume R more recent than 2.12 : binaries under bin\x64 for instance; folder containing 'bin' is R_HOME
                            Log.WarnFormat("R_HOME environment variable not set. Setting R_HOME = {0}", rhome);
                        }
                        break;

                    case PlatformID.Unix:
                        Log.Debug("R init: detected Unix platform");
                        if (String.IsNullOrEmpty(rhome))
                        {
                            throw new Exception("R_HOME environment variable is not set");
                        }
                        break;

                    default:
                        throw new NotSupportedException(string.Format("Platform not supported: {0}", plat));
                    }
                }
                Log.Debug("R init: R_HOME = " + rhome);
                REngine.SetEnvironmentVariables(pathToRDynLib, rhome);
            }

            Log.Debug("R init: creating R engine");
            rEngine = REngine.GetInstance(dll: null, initialize: false, parameter: null, device: null);
            Log.Debug("R init: initialising R engine");
            StartupParameter rStartParams = new StartupParameter
            {
                Quiet         = true,
                SaveAction    = StartupSaveAction.NoSave,
                Slave         = false,
                Interactive   = true,
                Verbose       = false,
                LoadInitFile  = true,
                LoadSiteFile  = true,
                RestoreAction = StartupRestoreAction.NoRestore,
                NoRenviron    = false
            };

            rEngine.Initialize(rStartParams);
            Log.Debug("Created rEngine: " + rEngine.ToString());
        }
 private void OnMapEditorModeExit()
 {
     _mapEditorCamera.Exit();
     _mapEditorMenu.IsVisible        = false;
     Game.Player.CanControlCharacter = true;
     NativeUtility.UserFriendlyPrint("Exited Map Editor");
 }
        private void ChangeRotationAxis()
        {
            var totalRotationAxisEntries = Enum.GetValues(typeof(TransformationAxis)).Length;

            _rotationAxis = (TransformationAxis)(((int)_rotationAxis + 1) % totalRotationAxisEntries);
            NativeUtility.UserFriendlyPrint($"Rotation Axis: {_rotationAxis}");
        }
        private void ChangeTransformationMode()
        {
            var totalTransformationModeEntries = Enum.GetValues(typeof(TransformationMode)).Length;

            _transformationMode = (TransformationMode)(((int)_transformationMode + 1) % totalTransformationModeEntries);
            NativeUtility.UserFriendlyPrint($"Transformation Mode: {_transformationMode}");
        }
Exemplo n.º 7
0
        public IntPtr GetBufferForWriting(Vector2I size)
        {
            unsafe
            {
                if (this.size != size)
                {
                    Clear();

                    this.size = size;

                    if (size != Vector2I.Zero)
                    {
                        //create buffer
                        buffer = NativeUtility.Alloc(NativeUtility.MemoryAllocationType.SoundAndVideo, size.X * size.Y * 4);
                        byte *pBuffer = (byte *)buffer;
                        int   z       = 0;
                        for (int n = 0; n < size.X * size.Y; n++)
                        {
                            pBuffer[z + 0] = 0;
                            pBuffer[z + 1] = 0;
                            pBuffer[z + 2] = 0;
                            pBuffer[z + 3] = 255;
                            z += 4;
                        }
                    }
                }

                needUpdateTexture = true;
                return(buffer);
            }
        }
Exemplo n.º 8
0
        public void TestLoadWindows()
        {
            // Test, if possible, loading 32 bits R.dll from a 64 bits process.
            // I do not really like tests to be platform-dependent, but this is pragmatically unavoidable.
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                return;
            }
            string rDllPath = "";

            try
            {
                rDllPath = new NativeUtility().FindRPathFromRegistry();
            }
            catch (ApplicationException) // registry keys not found - bail out
            {
                return;
            }
            if (Environment.Is64BitProcess)
            {
                if (!rDllPath.Contains("x64")) // Odd, but not what we are testing here.
                {
                    return;
                }
                rDllPath = rDllPath.Replace("x64", "i386");
                var rDllFullFilePath = Path.Combine(rDllPath, NativeUtility.GetRLibraryFileName());
                if (!File.Exists(rDllFullFilePath))
                {
                    return;
                }
                Assert.Throws <ArgumentException>(() => { var lib = new MockLoadLib(rDllFullFilePath); });
            }
        }
Exemplo n.º 9
0
        public static void SetEnvironmentVariables()
        {
            var rhome       = Environment.GetEnvironmentVariable("R_HOME");
            var currentPath = Environment.GetEnvironmentVariable("PATH");

            switch (NativeUtility.GetPlatform())
            {
            case PlatformID.Win32NT:
                Environment.SetEnvironmentVariable("PATH", FindRPathFromRegistry() + Path.PathSeparator + currentPath);
                break;

            case PlatformID.MacOSX:
                if (string.IsNullOrEmpty(rhome))
                {
                    Environment.SetEnvironmentVariable("R_HOME", "/Library/Frameworks/R.framework/Resources");
                }
                Environment.SetEnvironmentVariable("PATH", "/Library/Frameworks/R.framework/Libraries" + Path.PathSeparator + currentPath);
                break;

            case PlatformID.Unix:
                if (string.IsNullOrEmpty(rhome))
                {
                    Environment.SetEnvironmentVariable("R_HOME", "/usr/lib/R");
                }
                // TODO: cater for cases where user has build R from source and installed to e.g. /usr/local/lib
                Environment.SetEnvironmentVariable("PATH", "/usr/lib" + Path.PathSeparator + currentPath);
                break;
            }
        }
        private MapObject SpawnObject(string modelName, Vector3 position, Vector3 rotation)
        {
            Entity entity;

            if (modelName.StartsWith("0x"))
            {
                if (int.TryParse(modelName.Substring(2), NumberStyles.HexNumber, new NumberFormatInfo(), out var modelHash))
                {
                    entity = NativeUtility.CreateObject(modelHash, position);
                }
                else
                {
                    NativeUtility.UserFriendlyPrint($"Failed to spawn \"{modelName}\"");
                    return(null);
                }
            }
            else
            {
                entity = NativeUtility.CreateObject(modelName, position);
            }
            NativeUtility.SetEntityRotation(entity, rotation);
            var spawnedObject = new MapObject(modelName, position, rotation, entity);

            if (entity == null)
            {
                NativeUtility.UserFriendlyPrint($"Failed to spawn \"{modelName}\"");
                return(null);
            }
            _spawnedObjects.Add(spawnedObject);
            _selectedMapObject = spawnedObject;
            NativeUtility.UserFriendlyPrint($"Created \"{modelName}\"");
            return(spawnedObject);
        }
Exemplo n.º 11
0
 /// <summary>
 /// if the parameter is null or empty string, return the default names of the R shared library file depending on the platform
 /// </summary>
 /// <param name="dll">The name of the library provided, possibly null or empty</param>
 /// <returns>A candidate for the file name of the R shared library</returns>
 protected static string ProcessRDllFileName(string dll)
 {
     if (!string.IsNullOrEmpty(dll))
     {
         return(dll);
     }
     return(NativeUtility.GetRLibraryFileName());
 }
Exemplo n.º 12
0
        public void TestFindRBinPath()
        {
            string rLibPath = NativeUtility.FindRPath();
            var    files    = Directory.GetFiles(rLibPath);
            var    fnmatch  = files.Where(fn => fn.ToLower() == Path.Combine(rLibPath.ToLower(), NativeUtility.GetRLibraryFileName().ToLower()));

            Assert.AreEqual(1, fnmatch.Count());
        }
        /// <summary>
        /// The size in pixels.
        /// </summary>
        /// <returns></returns>
        public Vector2 GetMenuItemAbsoluteSize()
        {
            var displayText = _getDisplayText();

            return(new Vector2(
                       NativeUtility.GetTextScale(displayText, _fontSizeInPixels).X *_fontSizeInPixels,
                       _fontSizeInPixels
                       ));
        }
Exemplo n.º 14
0
 public MapEditorScript()
 {
     Tick    += OnTick;
     KeyDown += _mapEditor.OnKeyDown;
     KeyUp   += _mapEditor.OnKeyUp;
     DllImportsUtility.AllocConsole();
     Console.WriteLine(LoadedText);
     NativeUtility.UserFriendlyPrint(LoadedText);
 }
Exemplo n.º 15
0
        private void HandleWindowResize(HtmlEvent args)
        {
            if (_ribbon.GetField <bool>("initStarted"))
            {
                return;
            }

            NativeUtility.RibbonScaleHeader((HtmlElement)Browser.Document.GetById("RibbonTopBarsElt"), false);
        }
Exemplo n.º 16
0
        private bool OnNcHitTest(ref Message m, bool contentControl)
        {
            int x = NativeUtility.LOWORD(m.LParam);
            int y = NativeUtility.HIWORD(m.LParam);

            var    clientLocation = PointToClient(new Point(x, y));
            var    gripBounds     = new GripBounds(contentControl ? Content.ClientRectangle : ClientRectangle);
            IntPtr transparent    = new IntPtr(Constants.HTTRANSPARENT);

            if (_resizableTop)
            {
                if (_resizableLeft && gripBounds.TopLeft.Contains(clientLocation))
                {
                    m.Result = contentControl ? transparent : (IntPtr)Constants.HTTOPLEFT;
                    return(true);
                }
                if (!_resizableLeft && gripBounds.TopRight.Contains(clientLocation))
                {
                    m.Result = contentControl ? transparent : (IntPtr)Constants.HTTOPRIGHT;
                    return(true);
                }
                if (gripBounds.Top.Contains(clientLocation))
                {
                    m.Result = contentControl ? transparent : (IntPtr)Constants.HTTOP;
                    return(true);
                }
            }
            else
            {
                if (_resizableLeft && gripBounds.BottomLeft.Contains(clientLocation))
                {
                    m.Result = contentControl ? transparent : (IntPtr)Constants.HTBOTTOMLEFT;
                    return(true);
                }
                if (!_resizableLeft && gripBounds.BottomRight.Contains(clientLocation))
                {
                    m.Result = contentControl ? transparent : (IntPtr)Constants.HTBOTTOMRIGHT;
                    return(true);
                }
                if (gripBounds.Bottom.Contains(clientLocation))
                {
                    m.Result = contentControl ? transparent : (IntPtr)Constants.HTBOTTOM;
                    return(true);
                }
            }
            if (_resizableLeft && gripBounds.Left.Contains(clientLocation))
            {
                m.Result = contentControl ? transparent : (IntPtr)Constants.HTLEFT;
                return(true);
            }
            if (!_resizableLeft && gripBounds.Right.Contains(clientLocation))
            {
                m.Result = contentControl ? transparent : (IntPtr)Constants.HTRIGHT;
                return(true);
            }
            return(false);
        }
Exemplo n.º 17
0
        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
            if ((Visible && PopupAnimation == PopupAnimations.None) || (!Visible && CloseAnimation == PopupAnimations.None))
            {
                return;
            }
            AnimationFlags  flags  = Visible ? AnimationFlags.Roll : AnimationFlags.Hide;
            PopupAnimations _flags = Visible ? PopupAnimation : CloseAnimation;

            if (_flags == PopupAnimations.SystemDefault)
            {
                if (SystemInformation.IsMenuAnimationEnabled)
                {
                    if (SystemInformation.IsMenuFadeEnabled)
                    {
                        _flags = PopupAnimations.Blend;
                    }
                    else
                    {
                        _flags = PopupAnimations.Slide | (Visible ? PopupAnimations.TopToBottom : PopupAnimations.BottomToTop);
                    }
                }
                else
                {
                    _flags = PopupAnimations.None;
                }
            }
            if ((_flags & (PopupAnimations.Blend | PopupAnimations.Center | PopupAnimations.Roll | PopupAnimations.Slide)) == PopupAnimations.None)
            {
                return;
            }
            if (_resizableTop)            // popup is “inverted”, so the animation must be
            {
                if ((_flags & PopupAnimations.BottomToTop) != PopupAnimations.None)
                {
                    _flags = (_flags & ~PopupAnimations.BottomToTop) | PopupAnimations.TopToBottom;
                }
                else if ((_flags & PopupAnimations.TopToBottom) != PopupAnimations.None)
                {
                    _flags = (_flags & ~PopupAnimations.TopToBottom) | PopupAnimations.BottomToTop;
                }
            }
            if (_resizableLeft)            // popup is “inverted”, so the animation must be
            {
                if ((_flags & PopupAnimations.RightToLeft) != PopupAnimations.None)
                {
                    _flags = (_flags & ~PopupAnimations.RightToLeft) | PopupAnimations.LeftToRight;
                }
                else if ((_flags & PopupAnimations.LeftToRight) != PopupAnimations.None)
                {
                    _flags = (_flags & ~PopupAnimations.LeftToRight) | PopupAnimations.RightToLeft;
                }
            }
            flags |= (AnimationFlags.Mask & (AnimationFlags)(int)_flags);
            NativeUtility.AnimateWindow(this, AnimationDuration, flags);
        }
 public override void Draw()
 {
     NativeUtility.DrawText(
         Message,
         FontSizeInPixels,
         Color,
         NormalizedScreenPosition,
         IsCentered
         );
 }
Exemplo n.º 19
0
        public void TestFindRHomePath()
        {
            string rHomePath = NativeUtility.FindRHome();
            var    files     = Directory.GetDirectories(rHomePath);
            var    fnmatch   = files.Where(fn => Path.GetFileName(fn) == "library");

            Assert.AreEqual(1, fnmatch.Count());
            fnmatch = Directory.GetDirectories(fnmatch.First()).Where(fn => Path.GetFileName(fn) == "base");
            Assert.AreEqual(1, fnmatch.Count());
        }
Exemplo n.º 20
0
        public void Enter()
        {
            var playerPed      = Game.Player.Character;
            var cameraPosition = NativeUtility.GetEntityPosition(playerPed);
            var cameraRotation = NativeUtility.GetEntityRotation(playerPed);

            _camera          = World.CreateCamera(cameraPosition, cameraRotation, 75.0f);
            _camera.IsActive = true;
            NativeUtility.EnterScriptedCamera();
        }
        unsafe byte[] ConvertVertices(StandardVertex.StaticOneTexCoord[] vertices)
        {
            var result = new byte[vertices.Length * sizeof(StandardVertex.StaticOneTexCoord)];

            fixed(byte *pResult = result)
            fixed(StandardVertex.StaticOneTexCoord * pVertices = vertices)
            NativeUtility.CopyMemory(pResult, pVertices, result.Length);

            return(result);
        }
Exemplo n.º 22
0
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            var x = new COMBOBOXINFO();

            x.cbSize = (uint)Marshal.SizeOf(typeof(COMBOBOXINFO));
            var b = User32.GetComboBoxInfo(Handle, ref x);

            _listBoxDefaultWndProc = NativeUtility.SetWindowProc(x.hwndList, _listBoxWndProc);
        }
Exemplo n.º 23
0
 internal static void SetEnvironmentVariables()
 {
     NativeUtility.SetEnvironmentVariables();
     // TOCHECK: was the following deliberate?
     //switch (Environment.OSVersion.Platform)
     //{
     //   case PlatformID.Win32NT:
     //      Environment.SetEnvironmentVariable("PATH", FindRPathFromRegistry());
     //      break;
     //}
 }
        private void RotateLastSpawnedObject(Vector3 deltaRotation)
        {
            if (_selectedMapObject == null)
            {
                return;
            }
            var newRotation = _selectedMapObject.Rotation + deltaRotation;

            NativeUtility.SetEntityRotation(_selectedMapObject.Entity, newRotation);
            _selectedMapObject.Rotation = newRotation;
        }
        private void TranslateLastSpawnedObject(Vector3 deltaTranslation)
        {
            if (_selectedMapObject == null)
            {
                return;
            }
            var newPosition = _selectedMapObject.Position + deltaTranslation;

            NativeUtility.SetEntityPosition(_selectedMapObject.Entity, newPosition);
            _selectedMapObject.Position = newPosition;
        }
Exemplo n.º 26
0
        private void RibbonStartInit(HtmlEvent args)
        {
            if (!NativeUtility.RibbonReadyForInit())
            {
                return;
            }

            if (!CUIUtility.IsNullOrUndefined(args))
            {
                _ribbon.SetField <bool>("initialTabSelectedByUser", true);
            }

            Utility.CancelEventUtility(args, false, true);
            if (_ribbon.GetField <bool>("initStarted"))
            {
                return;
            }
            _ribbon.SetField <bool>("initStarted", true);

            // Get the name of the tab that was just selected
            Anchor   tab          = (Anchor)args.CurrentTargetElement;
            ListItem parent       = (ListItem)tab.ParentNode;
            string   initialTabId = parent.Id.Substring(0, parent.Id.IndexOf("-title"));

            string firstTabId = "";

            if (!string.IsNullOrEmpty(initialTabId))
            {
                firstTabId = _ribbon.GetField <string>("initialTabId");
                _ribbon.SetField <string>("initialTabId", initialTabId);
            }

            _ribbon.SetField <bool>("buildMinimized", false);

            if (!string.IsNullOrEmpty(initialTabId))
            {
                NativeUtility.RibbonOnStartInit(_ribbon);

                ListItem oldTab = (ListItem)Browser.Document.GetById(firstTabId + "-title");
                if (!CUIUtility.IsNullOrUndefined(oldTab))
                {
                    oldTab.ClassName = "ms-cui-tt";
                }

                ListItem newTab = (ListItem)Browser.Document.GetById(initialTabId + "-title");
                if (!CUIUtility.IsNullOrUndefined(newTab))
                {
                    newTab.ClassName = "ms-cui-tt ms-cui-tt-s";
                }
            }

            RibbonInitFunc1();
        }
Exemplo n.º 27
0
        public void Clear()
        {
            DestroyTexture();

            if (buffer != IntPtr.Zero)
            {
                NativeUtility.Free(buffer);
                buffer = IntPtr.Zero;
            }

            size = Vector2I.Zero;
        }
        private void SaveMap()
        {
            const string mapFilePath     = "scripts/MapEditor/maps/test.map";
            var          serializableMap = new SerializableMap
            {
                MapName    = $"{Game.Player.Name}'s Map",
                AuthorName = Game.Player.Name,
                MapObjects = _spawnedObjects.Select(mapObject => new SerializableMapObject(mapObject)),
            };

            _mapPersistenceManager.SaveMap(mapFilePath, serializableMap);
            NativeUtility.UserFriendlyPrint($"Map saved to {mapFilePath}");
        }
Exemplo n.º 29
0
        public static void SetupPath()
        {
            // as of 2013-10, there is a helper that should work for all platforms:
            NativeUtility.SetEnvironmentVariables();
            // The following sample code is left as a fallback option if you have unforeseen issues,
            // but you should report issues on the R.NET discussion list.
//            var oldPath = System.Environment.GetEnvironmentVariable("PATH");
//            var rPath = System.Environment.Is64BitProcess ? @"C:\Program Files\R\R-3.0.2\bin\x64" : @"C:\Program Files\R\R-3.0.2\bin\i386";
//            if (Directory.Exists(rPath) == false)
//                throw new DirectoryNotFoundException(string.Format("Could not found the specified path to the directory containing R.dll: {0}", rPath));
//            var newPath = string.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath);
//            System.Environment.SetEnvironmentVariable("PATH", newPath);
        }
Exemplo n.º 30
0
    private static void DeepLinkHandler(IntPtr deepLinkDataPairArray, int deepLinkDataPairCount)
    {
        if (deepLinkDataPairArray == IntPtr.Zero)
        {
            return;
        }

        Dictionary <string, string> deepLinkData =
            NativeUtility.MarshalStringStringDictionary(deepLinkDataPairArray, deepLinkDataPairCount);

        lock (deferredDeeplinkEvents) {
            deferredDeeplinkEvents.Push(deepLinkData);
        }
    }